Skip to content

The headless browser for AI agents and web scraping

perf: avoid idle polling and reuse unchanged rendering work (#1)

ice Zeusabf247ba3bb7
diff --git a/crates/obscura-browser/Cargo.toml b/crates/obscura-browser/Cargo.toml
index e2869e4c..20d48286 100644
--- a/crates/obscura-browser/Cargo.toml
+++ b/crates/obscura-browser/Cargo.toml
@@ -23,3 +23,6 @@ anyhow = { workspace = true }
serde_json = { workspace = true }
base64 = { workspace = true }
image = { version = "0.25", default-features = false, features = ["jpeg", "png"], optional = true }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["test-util"] }
diff --git a/crates/obscura-browser/src/idle_deadline.rs b/crates/obscura-browser/src/idle_deadline.rs
new file mode 100644
index 00000000..46d16704
--- /dev/null
+++ b/crates/obscura-browser/src/idle_deadline.rs
@@ -0,0 +1,329 @@
+//! Preserve runtime polling while avoiding a coalesced final idle-deadline wake.
+
+use std::future::Future;
+use tokio::time::Instant;
+
+pub(crate) async fn wait_for_activity(
+ deadline: Instant,
+ final_check: bool,
+ activity: impl Future,
+) {
+ #[cfg(target_os = "macos")]
+ if final_check {
+ let mut activity = std::pin::pin!(activity);
+ let mut wake = None;
+ let mut attempted = false;
+ let activity_or_deadline = std::future::poll_fn(|cx| {
+ // Keep the existing runtime poll first, even if both wakes are
+ // ready. Never replace page work with a timer-only completion.
+ if activity.as_mut().poll(cx).is_ready() {
+ return std::task::Poll::Ready(());
+ }
+ if !attempted {
+ attempted = true;
+ wake = macos::PreciseWake::new(deadline.into_std());
+ }
+ if wake.as_mut().is_some_and(|wake| wake.poll(cx)) {
+ std::task::Poll::Ready(())
+ } else {
+ std::task::Poll::Pending
+ }
+ });
+ // Retain the original timeout if timer creation fails, the platform
+ // delays dispatch, or Tokio's test clock advances independently.
+ let _ = tokio::time::timeout_at(deadline, activity_or_deadline).await;
+ return;
+ }
+ let _ = final_check;
+ let _ = tokio::time::timeout_at(deadline, activity).await;
+}
+
+#[cfg(target_os = "macos")]
+mod macos {
+ use std::ffi::c_void;
+ use std::future::Future;
+ use std::panic::{catch_unwind, AssertUnwindSafe};
+ use std::pin::Pin;
+ use std::ptr::NonNull;
+ use std::task::{Context, Poll};
+ use std::time::Instant;
+ use tokio::sync::oneshot;
+
+ // C function APIs avoid Objective-C blocks and any extra runtime crate.
+ // These signatures and lifetime rules follow dispatch/source.h and
+ // dispatch/object.h. Only the address of the opaque type symbol is used.
+ #[link(name = "System")]
+ unsafe extern "C" {
+ static _dispatch_source_type_timer: u8;
+ fn dispatch_get_global_queue(identifier: isize, flags: usize) -> *mut c_void;
+ fn dispatch_source_create(kind: *const c_void, handle: usize, mask: usize,
+ queue: *mut c_void) -> *mut c_void;
+ fn dispatch_set_context(object: *mut c_void, context: *mut c_void);
+ fn dispatch_source_set_event_handler_f(source: *mut c_void, handler: extern "C" fn(*mut c_void));
+ fn dispatch_source_set_cancel_handler_f(source: *mut c_void, handler: extern "C" fn(*mut c_void));
+ fn dispatch_source_set_timer(source: *mut c_void, start: u64, interval: u64, leeway: u64);
+ fn dispatch_time(when: u64, delta: i64) -> u64;
+ fn dispatch_resume(object: *mut c_void);
+ fn dispatch_source_cancel(source: *mut c_void);
+ fn dispatch_release(object: *mut c_void);
+ }
+
+ const TIMER_STRICT: usize = 1;
+ const TIME_NOW: u64 = 0;
+ const TIME_FOREVER: u64 = u64::MAX;
+
+ struct Callback {
+ source: NonNull<c_void>,
+ deadline: Instant,
+ sender: Option<oneshot::Sender<()>>,
+ }
+
+ #[cfg(test)]
+ static LIVE_CALLBACKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+ #[cfg(test)]
+ static EARLY_WAKES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+
+ #[cfg(test)]
+ impl Drop for Callback {
+ fn drop(&mut self) {
+ LIVE_CALLBACKS.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
+ }
+ }
+
+ fn arm(source: NonNull<c_void>, deadline: Instant) {
+ let nanos = deadline.saturating_duration_since(Instant::now()).as_nanos()
+ .min(i64::MAX as u128) as i64;
+ // SAFETY: the caller owns a live source or runs its event handler.
+ // This is a one-shot uptime timer; no periodic wake remains armed.
+ unsafe {
+ dispatch_source_set_timer(source.as_ptr(), dispatch_time(TIME_NOW, nanos), TIME_FOREVER, 0);
+ }
+ }
+
+ extern "C" fn fired(context: *mut c_void) {
+ // SAFETY: dispatch serializes this source's callbacks. The Box remains
+ // owned by dispatch until cancelled() runs after this handler returns.
+ let callback = unsafe { &mut *context.cast::<Callback>() };
+ if Instant::now() < callback.deadline {
+ #[cfg(test)]
+ EARLY_WAKES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ arm(callback.source, callback.deadline);
+ return;
+ }
+ // A Rust waker must not unwind through a C callback boundary. The
+ // original Tokio timeout remains available if notification fails.
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ if let Some(sender) = callback.sender.take() {
+ let _ = sender.send(());
+ }
+ }));
+ // SAFETY: the source retains its handler until this callback returns;
+ // cancellation is asynchronous and does not join the page/V8 thread.
+ unsafe { dispatch_source_cancel(callback.source.as_ptr()); }
+ }
+
+ extern "C" fn cancelled(context: *mut c_void) {
+ // SAFETY: this runs once, after the final event handler has returned.
+ // It is the sole owner that reconstructs and frees the callback Box.
+ let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
+ drop(Box::from_raw(context.cast::<Callback>()));
+ }));
+ }
+
+ pub(super) struct PreciseWake {
+ source: NonNull<c_void>,
+ receiver: Option<oneshot::Receiver<()>>,
+ }
+
+ impl PreciseWake {
+ pub(super) fn new(deadline: Instant) -> Option<Self> {
+ if deadline <= Instant::now() {
+ return None;
+ }
+ // Strict timers can override coalescing intended to save power.
+ // Use one only for a parked final readiness check, never for all
+ // polling slices, and never create a dedicated waiting thread.
+ // SAFETY: the source is inactive until context and both handlers
+ // are installed. The returned owned reference belongs to Self.
+ let source = unsafe {
+ NonNull::new(dispatch_source_create(
+ (&raw const _dispatch_source_type_timer).cast(), 0, TIMER_STRICT,
+ dispatch_get_global_queue(0, 0),
+ ))?
+ };
+ let (sender, receiver) = oneshot::channel();
+ let callback = Box::new(Callback { source, deadline, sender: Some(sender) });
+ #[cfg(test)]
+ LIVE_CALLBACKS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ unsafe {
+ dispatch_set_context(source.as_ptr(), Box::into_raw(callback).cast());
+ dispatch_source_set_event_handler_f(source.as_ptr(), fired);
+ dispatch_source_set_cancel_handler_f(source.as_ptr(), cancelled);
+ arm(source, deadline);
+ dispatch_resume(source.as_ptr());
+ }
+ Some(Self { source, receiver: Some(receiver) })
+ }
+
+ pub(super) fn poll(&mut self, cx: &mut Context<'_>) -> bool {
+ let Some(receiver) = &mut self.receiver else { return false; };
+ if let Poll::Ready(result) = Pin::new(receiver).poll(cx) {
+ self.receiver = None;
+ return result.is_ok();
+ }
+ false
+ }
+ }
+
+ impl Drop for PreciseWake {
+ fn drop(&mut self) {
+ // Unregister the waiter before asynchronous cancellation can drop
+ // the sender. Cancelled page work must not receive a stray wake.
+ drop(self.receiver.take());
+ // SAFETY: Self owns the create reference; callbacks are retained
+ // by dispatch until cancellation completes and free their context.
+ unsafe {
+ dispatch_source_cancel(self.source.as_ptr());
+ dispatch_release(self.source.as_ptr());
+ }
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
+ use std::task::{Wake, Waker};
+ use std::time::Duration;
+
+ async fn drained() {
+ tokio::time::timeout(Duration::from_secs(2), async {
+ while LIVE_CALLBACKS.load(Ordering::SeqCst) != 0 {
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ }
+ }).await.expect("cancelled timer context must be released");
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn precise_idle_timer_reaches_deadline_without_early_readiness() {
+ let deadline = Instant::now() + Duration::from_millis(20);
+ let mut wake = PreciseWake::new(deadline).unwrap();
+ tokio::time::timeout(Duration::from_secs(2), std::future::poll_fn(|cx| {
+ if wake.poll(cx) { Poll::Ready(()) } else { Poll::Pending }
+ })).await.expect("dispatch timer must notify independently of the fallback");
+ assert!(Instant::now() >= deadline);
+ drop(wake);
+ drained().await;
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn precise_idle_timer_rechecks_and_rearms_an_early_event() {
+ let mut wake = PreciseWake::new(Instant::now() + Duration::from_secs(5)).unwrap();
+ // Exercise the real C handler with an intentionally early event.
+ unsafe { dispatch_source_set_timer(wake.source.as_ptr(), TIME_NOW, TIME_FOREVER, 0); }
+ tokio::time::timeout(Duration::from_secs(2), async {
+ while EARLY_WAKES.load(Ordering::SeqCst) == 0 {
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ }
+ }).await.expect("early event must reach the deadline recheck");
+ assert!(!wake.poll(&mut Context::from_waker(Waker::noop())));
+ drop(wake);
+ drained().await;
+ }
+
+ struct CountWakes(AtomicUsize);
+ impl Wake for CountWakes {
+ fn wake(self: Arc<Self>) { self.0.fetch_add(1, Ordering::SeqCst); }
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn precise_idle_timer_cancellation_releases_context_without_stray_wakes() {
+ let count = Arc::new(CountWakes(AtomicUsize::new(0)));
+ let waker = Waker::from(Arc::clone(&count));
+ for _ in 0..32 {
+ let mut wake = PreciseWake::new(Instant::now() + Duration::from_secs(5)).unwrap();
+ assert!(!wake.poll(&mut Context::from_waker(&waker)));
+ drop(wake);
+ }
+ drained().await;
+ assert_eq!(count.0.load(Ordering::SeqCst), 0);
+ }
+
+ struct PanickingWake(AtomicUsize);
+ impl Wake for PanickingWake {
+ fn wake(self: Arc<Self>) {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ panic!("deliberately panicking test waker");
+ }
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn precise_idle_timer_contains_waker_panics_at_the_c_boundary() {
+ let count = Arc::new(PanickingWake(AtomicUsize::new(0)));
+ let waker = Waker::from(Arc::clone(&count));
+ let mut wake = PreciseWake::new(Instant::now() + Duration::from_millis(20)).unwrap();
+ assert!(!wake.poll(&mut Context::from_waker(&waker)));
+ drained().await;
+ assert_eq!(count.0.load(Ordering::SeqCst), 1);
+ drop(wake);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn precise_idle_activity_is_polled_before_creating_a_timer() {
+ let mut polled = false;
+ super::super::wait_for_activity(tokio::time::Instant::now() + Duration::from_secs(5), true,
+ std::future::poll_fn(|_| { polled = true; Poll::Ready(()) })).await;
+ assert!(polled);
+ assert_eq!(LIVE_CALLBACKS.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn precise_idle_wake_keeps_the_tokio_deadline_fallback() {
+ tokio::time::pause();
+ let started = tokio::time::Instant::now();
+ let mut wait = Box::pin(super::super::wait_for_activity(
+ started + Duration::from_millis(25), true, std::future::pending::<()>()));
+ let mut cx = Context::from_waker(Waker::noop());
+ assert!(wait.as_mut().poll(&mut cx).is_pending());
+ tokio::time::advance(Duration::from_millis(24)).await;
+ assert!(wait.as_mut().poll(&mut cx).is_pending());
+ tokio::time::advance(Duration::from_millis(2)).await;
+ assert!(wait.as_mut().poll(&mut cx).is_ready());
+ drop(wait);
+ tokio::time::resume();
+ drained().await;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn idle_intermediate_check_keeps_the_existing_timeout() {
+ tokio::time::pause();
+ let started = Instant::now();
+ let mut wait = Box::pin(wait_for_activity(started + Duration::from_millis(50), false,
+ std::future::pending::<()>()));
+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
+ assert!(wait.as_mut().poll(&mut cx).is_pending());
+ tokio::time::advance(Duration::from_millis(49)).await;
+ assert!(wait.as_mut().poll(&mut cx).is_pending());
+ tokio::time::advance(Duration::from_millis(2)).await;
+ assert!(wait.as_mut().poll(&mut cx).is_ready());
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn idle_deadline_wait_preserves_ready_activity_and_cancellation() {
+ let mut polled = false;
+ wait_for_activity(Instant::now(), true,
+ std::future::poll_fn(|_| { polled = true; std::task::Poll::Ready(()) })).await;
+ assert!(polled, "an expired deadline must still poll page activity first");
+ let (sender, mut receiver) = tokio::sync::oneshot::channel::<()>();
+ wait_for_activity(Instant::now(), true, &mut receiver).await;
+ sender.send(()).expect("cancelling the wait must not consume unrelated work");
+ receiver.await.unwrap();
+ }
+}
diff --git a/crates/obscura-browser/src/lib.rs b/crates/obscura-browser/src/lib.rs
index 03c8083e..f504bff9 100644
--- a/crates/obscura-browser/src/lib.rs
+++ b/crates/obscura-browser/src/lib.rs
@@ -1,5 +1,6 @@
pub mod context;
mod fork_virtual_url;
+mod idle_deadline;
pub mod lifecycle;
pub mod page;
#[cfg(feature = "render")]
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 15a14933..e7ff3571 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -3618,61 +3618,77 @@ impl Page {
_ => 0,
};
- // Same hazard as the post-script settle: a synchronous poll can pin
- // the thread past the 5s network-idle deadline, so arm a watchdog
- // that terminates the isolate ~500ms past it.
- let netidle_wd = self
- .js
- .as_mut()
- .map(|js| js.arm_watchdog(std::time::Duration::from_millis(5500)));
- let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
- let mut idle_since: Option<tokio::time::Instant> = None;
+ self.wait_for_network_idle(threshold).await;
+ }
- loop {
- let active = self.http_client.active_requests();
- let now = tokio::time::Instant::now();
+ Ok(())
+ }
- if active <= threshold {
- if idle_since.is_none() {
- idle_since = Some(now);
- }
- if now.duration_since(idle_since.unwrap())
- >= tokio::time::Duration::from_millis(500)
- {
- break;
- }
- } else {
- idle_since = None;
- }
+ async fn wait_for_network_idle(&mut self, threshold: u32) {
+ // Same hazard as the post-script settle: a synchronous poll can pin
+ // the thread past the 5s network-idle deadline, so arm a watchdog
+ // that terminates the isolate ~500ms past it.
+ let netidle_wd = self
+ .js
+ .as_mut()
+ .map(|js| js.arm_watchdog(std::time::Duration::from_millis(5500)));
+ let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
+ let mut idle_since: Option<tokio::time::Instant> = None;
- if now >= deadline {
- tracing::debug!(
- "Network idle timeout reached with {} active requests",
- active
- );
+ loop {
+ let active = self.http_client.active_requests();
+ let now = tokio::time::Instant::now();
+
+ if active <= threshold {
+ if idle_since.is_none() {
+ idle_since = Some(now);
+ }
+ if now.duration_since(idle_since.unwrap())
+ >= tokio::time::Duration::from_millis(500)
+ {
break;
}
+ } else {
+ idle_since = None;
+ }
- if let Some(js) = &mut self.js {
- let _ = tokio::time::timeout(
- tokio::time::Duration::from_millis(50),
- js.run_event_loop(),
- )
- .await;
- } else {
- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
- }
+ if now >= deadline {
+ tracing::debug!(
+ "Network idle timeout reached with {} active requests",
+ active
+ );
+ break;
}
- if let Some(token) = netidle_wd {
- if let Some(js) = self.js.as_mut() {
- js.disarm_watchdog(token);
- }
+ // An idle runtime can stay parked. Wake at the existing quiet
+ // window or hard deadline instead of adding a final full slice.
+ let readiness_deadline = idle_since
+ .map_or(deadline, |since| since + tokio::time::Duration::from_millis(500))
+ .min(deadline);
+ if let Some(js) = &mut self.js {
+ let next_check = readiness_deadline.min(now + tokio::time::Duration::from_millis(50));
+ crate::idle_deadline::wait_for_activity(
+ next_check,
+ next_check == readiness_deadline,
+ js.wait_for_event_loop_activity(),
+ )
+ .await;
+ } else {
+ let next_check = readiness_deadline.min(now + tokio::time::Duration::from_millis(100));
+ crate::idle_deadline::wait_for_activity(
+ next_check,
+ next_check == readiness_deadline,
+ std::future::pending::<()>(),
+ ).await;
}
- self.lifecycle = LifecycleState::NetworkIdle;
}
- Ok(())
+ if let Some(token) = netidle_wd {
+ if let Some(js) = self.js.as_mut() {
+ js.disarm_watchdog(token);
+ }
+ }
+ self.lifecycle = LifecycleState::NetworkIdle;
}
/// Builds the child frames of the document that just loaded.
@@ -4971,6 +4987,169 @@ mod tests {
use base64::Engine as _;
use obscura_dom::parse_html;
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_quiet_deadline_does_not_gain_an_extra_polling_slice() {
+ use std::future::Future as _;
+
+ // No JavaScript runtime is needed to test the lifecycle deadline.
+ // This also keeps unrelated V8 maintenance wakes out of the clock test.
+ let context = std::sync::Arc::new(crate::BrowserContext::new("idle-deadline".into()));
+ let mut page = super::Page::new("idle-deadline".into(), context);
+ assert!(page.js.is_none());
+ tokio::time::pause();
+ let started = tokio::time::Instant::now();
+ let mut wait = Box::pin(page.wait_for_network_idle(0));
+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
+ assert!(wait.as_mut().poll(&mut cx).is_pending());
+
+ // Model a delayed executor poll just before the existing quiet window
+ // ends. The next wake belongs to that window, not a fresh full slice.
+ tokio::time::advance(std::time::Duration::from_millis(490)).await;
+ assert!(wait.as_mut().poll(&mut cx).is_pending(),
+ "network idle must not complete before the quiet window");
+ tokio::time::advance(std::time::Duration::from_millis(11)).await;
+ assert!(wait.as_mut().poll(&mut cx).is_ready(),
+ "quiet-window expiry must not wait for another polling slice");
+ drop(wait);
+ assert_eq!(started.elapsed(), std::time::Duration::from_millis(501));
+ assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::NetworkIdle);
+ }
+
+ fn network_idle_test_page() -> super::Page {
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ "network-idle-regression".into(), None, false, None, None, true,
+ ));
+ let mut page = super::Page::new("network-idle-regression".into(), context);
+ page.url = Some(url::Url::parse("http://example.test/").unwrap());
+ page.dom = Some(parse_html("<html><body></body></html>"));
+ page.init_js();
+ page
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_preserves_quiet_window_and_page_tasks() {
+ let mut page = network_idle_test_page();
+ page.js.as_mut().unwrap().execute_script("network-idle-interval", r#"
+ globalThis.__idleTicks = 0;
+ globalThis.__idleObserved = false;
+ new MutationObserver(() => { __idleObserved = true; })
+ .observe(document.body, { attributes: true });
+ const id = setInterval(() => {
+ if (++__idleTicks === 3) {
+ clearInterval(id);
+ Promise.resolve().then(() => document.body.setAttribute('data-ready', 'yes'));
+ }
+ }, 20);
+ "#).unwrap();
+ let started = tokio::time::Instant::now();
+ tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(0))
+ .await.expect("quiet page must finish within its normal window");
+ assert!(started.elapsed() >= std::time::Duration::from_millis(500));
+ assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::NetworkIdle);
+ assert_eq!(page.js.as_mut().unwrap().evaluate("[__idleTicks, __idleObserved]").unwrap(),
+ serde_json::json!([3, true]));
+ }
+
+ async fn network_idle_held_request(
+ client: std::sync::Arc<obscura_net::ObscuraHttpClient>,
+ ) -> (tokio::sync::oneshot::Sender<()>, tokio::task::JoinHandle<()>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
+ let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = Vec::new();
+ let mut bytes = [0u8; 1024];
+ while !request.windows(4).any(|part| part == b"\r\n\r\n") {
+ let read = socket.read(&mut bytes).await.unwrap();
+ assert!(read > 0 && request.len() < 16384);
+ request.extend_from_slice(&bytes[..read]);
+ }
+ ready_tx.send(()).unwrap();
+ let _ = release_rx.await;
+ let _ = socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok").await;
+ });
+ let fetch = tokio::spawn(async move {
+ assert_eq!(client.fetch(&url).await.unwrap().status, 200);
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(2), ready_rx)
+ .await.expect("request reached fixture").unwrap();
+ (release_tx, fetch)
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_two_allows_two_active_requests() {
+ let mut page = network_idle_test_page();
+ let (release_a, fetch_a) = network_idle_held_request(page.http_client.clone()).await;
+ let (release_b, fetch_b) = network_idle_held_request(page.http_client.clone()).await;
+ assert_eq!(page.http_client.active_requests(), 2);
+ let started = tokio::time::Instant::now();
+ tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(2))
+ .await.expect("two active requests must not force the five-second deadline");
+ assert!(started.elapsed() >= std::time::Duration::from_millis(500));
+ assert_eq!(page.http_client.active_requests(), 2, "threshold two must allow both held requests");
+ release_a.send(()).unwrap();
+ release_b.send(()).unwrap();
+ fetch_a.await.unwrap();
+ fetch_b.await.unwrap();
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_zero_starts_quiet_window_after_request_completion() {
+ let mut page = network_idle_test_page();
+ let (release, fetch) = network_idle_held_request(page.http_client.clone()).await;
+ let completed = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let recorded = completed.clone();
+ let release_task = tokio::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(180)).await;
+ release.send(()).unwrap();
+ fetch.await.unwrap();
+ *recorded.lock().unwrap() = Some(tokio::time::Instant::now());
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(0))
+ .await.expect("completed request must permit network idle");
+ release_task.await.unwrap();
+ assert!(completed.lock().unwrap().unwrap().elapsed() >= std::time::Duration::from_millis(490),
+ "an active request must prevent an earlier quiet-window start");
+ assert_eq!(page.http_client.active_requests(), 0);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_restarts_quiet_window_when_request_begins() {
+ let mut page = network_idle_test_page();
+ let client = page.http_client.clone();
+ let completed = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let recorded = completed.clone();
+ let request_task = tokio::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(150)).await;
+ let (release, fetch) = network_idle_held_request(client).await;
+ tokio::time::sleep(std::time::Duration::from_millis(150)).await;
+ release.send(()).unwrap();
+ fetch.await.unwrap();
+ *recorded.lock().unwrap() = Some(tokio::time::Instant::now());
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(0))
+ .await.expect("a completed late request must permit network idle");
+ request_task.await.unwrap();
+ assert!(completed.lock().unwrap().unwrap().elapsed() >= std::time::Duration::from_millis(490),
+ "new traffic must reset the original quiet window");
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_keeps_five_second_deadline_for_stuck_request() {
+ let mut page = network_idle_test_page();
+ let (release, fetch) = network_idle_held_request(page.http_client.clone()).await;
+ let started = tokio::time::Instant::now();
+ tokio::time::timeout(std::time::Duration::from_secs(7), page.wait_for_network_idle(0))
+ .await.expect("network-idle deadline must still finish");
+ assert!(started.elapsed() >= std::time::Duration::from_secs(5));
+ assert_eq!(page.http_client.active_requests(), 1);
+ release.send(()).unwrap();
+ fetch.await.unwrap();
+ assert_eq!(page.js.as_mut().unwrap().evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
+ }
fn install_linked_stylesheet(
runtime: &mut obscura_js::runtime::ObscuraJsRuntime,
index: usize,
@@ -8981,10 +9160,22 @@ mod tests {
while std::time::Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
- let index = served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let served = served.clone();
std::thread::spawn(move || {
- let mut request = [0u8; 2048];
- let _ = stream.read(&mut request);
+ // Accepted sockets can inherit the listener's nonblocking
+ // mode. Consume the complete request before responding or
+ // signalling A's readiness, including fragmented headers.
+ stream.set_nonblocking(false).unwrap();
+ stream.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
+ let mut request = Vec::new();
+ let mut chunk = [0u8; 2048];
+ while !request.windows(4).any(|part| part == b"\r\n\r\n") {
+ let size = stream.read(&mut chunk).unwrap();
+ assert_ne!(size, 0, "request closed before its headers completed");
+ request.extend_from_slice(&chunk[..size]);
+ assert!(request.len() <= 16_384, "fixture request headers too large");
+ }
+ let index = served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let width = if index == 0 {
std::thread::sleep(std::time::Duration::from_millis(1_500));
20
diff --git a/crates/obscura-cdp/Cargo.toml b/crates/obscura-cdp/Cargo.toml
index a4817230..af646734 100644
--- a/crates/obscura-cdp/Cargo.toml
+++ b/crates/obscura-cdp/Cargo.toml
@@ -41,5 +41,6 @@ png = { version = "0.18", optional = true }
libc = "0.2"
[dev-dependencies]
+tokio = { workspace = true, features = ["test-util"] }
tokio-tungstenite = { workspace = true }
futures-util = "0.3"
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index 8603184d..0ef7d4ab 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -2875,6 +2875,176 @@ mod tests {
assert!(parse_cdp_headers(&json!({"url": "https://example.com"})).is_none());
}
+ async fn assert_navigation_intercept_reply_without_timer(method: &str) {
+ use super::{process_with_interception, CdpMessage, ServerMessage, MAX_DEFERRED_MESSAGES};
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use obscura_js::ops::{InterceptedRequest, InterceptResolution};
+
+ tokio::task::LocalSet::new().run_until(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let (requested_tx, requested_rx) = tokio::sync::oneshot::channel();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();
+ let fixture = tokio::task::spawn_local(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut request = Vec::new();
+ let mut buffer = [0u8; 1024];
+ while !request.windows(4).any(|part| part == b"\r\n\r\n") {
+ let count = stream.read(&mut buffer).await.unwrap();
+ assert!(count > 0);
+ request.extend_from_slice(&buffer[..count]);
+ }
+ requested_tx.send(()).unwrap();
+ release_rx.await.unwrap();
+ let body = b"<!doctype html><title>Finished</title><h1>Finished</h1>";
+ let head = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
+ stream.write_all(head.as_bytes()).await.unwrap();
+ stream.write_all(body).await.unwrap();
+ });
+
+ let context = obscura_browser::context::BrowserContext::with_storage_and_network(
+ "interception-test".into(), None, false, None, None, true,
+ );
+ let mut ctx = crate::dispatch::CdpContext::new_with_shared_context(std::sync::Arc::new(context));
+ let page_id = ctx.create_page();
+ let session_id = format!("{page_id}-session");
+ ctx.sessions.insert(session_id.clone(), page_id.clone());
+ let (server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (intercept_tx, intercept_rx) = tokio::sync::mpsc::unbounded_channel();
+ ctx.intercept_tx = Some(intercept_tx.clone());
+ let command = json!({"id": 1, "method": "Page.navigate", "sessionId": session_id,
+ "params": {"url": format!("http://{address}/"), "waitUntil": "load"}}).to_string();
+ let navigation_reply = reply_tx.clone();
+ let navigation = tokio::task::spawn_local(async move {
+ let mut intercept_rx = Some(intercept_rx);
+ let mut paused = HashMap::new();
+ let mut deferred = std::collections::VecDeque::new();
+ process_with_interception(&command, &mut ctx, &navigation_reply,
+ &mut server_rx, &mut intercept_rx, &mut paused, &mut deferred, true).await;
+ (ctx, paused, deferred)
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(5), requested_rx)
+ .await.expect("navigation must reach the held response").unwrap();
+
+ // The real socket is already connected and its response is gated.
+ // Only the channel handshake below runs with a paused clock. An
+ // unconditional timer auto-advances it, independent of host load.
+ tokio::time::pause();
+ let started = tokio::time::Instant::now();
+ let (resolution_tx, resolution_rx) = tokio::sync::oneshot::channel();
+ intercept_tx.send(InterceptedRequest {
+ page_id: page_id.clone(),
+ request_id: "pending-test".into(), url: format!("http://{address}/pending"),
+ method: "GET".into(), headers: HashMap::new(), resource_type: "Fetch".into(),
+ resolver: resolution_tx,
+ }).unwrap();
+ loop {
+ let value: serde_json::Value = serde_json::from_str(
+ &tokio::time::timeout(std::time::Duration::from_secs(1), reply_rx.recv())
+ .await.expect("paused notification").unwrap()).unwrap();
+ assert_ne!(value["id"], 1, "navigation must wait for its response");
+ if value["method"] == "Fetch.requestPaused" {
+ assert_eq!(value["params"]["requestId"], "pending-test");
+ break;
+ }
+ }
+ let send = |value: serde_json::Value| {
+ server_tx.send(ServerMessage::Cdp(CdpMessage {
+ text: value.to_string(), reply_tx: reply_tx.clone(),
+ })).unwrap();
+ };
+ let foreign_count = if method == "failRequest" { MAX_DEFERRED_MESSAGES + 1 } else { 1 };
+ for index in 0..foreign_count {
+ send(json!({"id": 100 + index, "method": "Runtime.evaluate",
+ "sessionId": session_id, "params": {"expression": "globalThis.foreignRan=true"}}));
+ }
+ let mut params = json!({"requestId": "pending-test"});
+ match method {
+ "continueRequest" => {
+ params["url"] = json!("https://example.com/rewritten");
+ params["method"] = json!("POST");
+ params["headers"] = json!([{"name": "X-Check", "value": "kept"}]);
+ params["postData"] = json!("payload");
+ }
+ "fulfillRequest" => {
+ params["responseCode"] = json!(201);
+ params["responseHeaders"] = json!([{"name": "X-Check", "value": "kept"}]);
+ params["body"] = json!("aGVsbG8=");
+ }
+ "failRequest" => params["errorReason"] = json!("Aborted"),
+ _ => unreachable!(),
+ }
+ send(json!({"id": 10, "method": format!("Fetch.{method}"),
+ "sessionId": session_id, "params": params}));
+ let mut overflow_responses = 0;
+ loop {
+ let value: serde_json::Value = serde_json::from_str(
+ &tokio::time::timeout(std::time::Duration::from_secs(1), reply_rx.recv())
+ .await.expect("Fetch resolution reply").unwrap()).unwrap();
+ assert_ne!(value["id"], 1, "must not acknowledge unfinished navigation");
+ if value["id"] == 10 {
+ assert!(value.get("error").is_none(), "{value}");
+ break;
+ }
+ if value.get("id").is_some() {
+ assert_eq!(value["id"], 100 + MAX_DEFERRED_MESSAGES);
+ assert_eq!(value["error"]["code"], -32000);
+ overflow_responses += 1;
+ }
+ }
+ let elapsed = started.elapsed();
+ match (method, resolution_rx.await.unwrap()) {
+ ("continueRequest", InterceptResolution::Continue { url, method, headers, body }) => {
+ assert_eq!(url.as_deref(), Some("https://example.com/rewritten"));
+ assert_eq!(method.as_deref(), Some("POST"));
+ assert_eq!(headers.unwrap().get("X-Check").map(String::as_str), Some("kept"));
+ assert_eq!(body.as_deref(), Some("payload"));
+ }
+ ("fulfillRequest", InterceptResolution::Fulfill { status, headers, body, body_base64 }) => {
+ assert_eq!(status, 201);
+ assert_eq!(headers.get("X-Check").map(String::as_str), Some("kept"));
+ assert_eq!(body, "hello");
+ assert_eq!(body_base64, "aGVsbG8=");
+ }
+ ("failRequest", InterceptResolution::Fail { reason }) => assert_eq!(reason, "Aborted"),
+ _ => panic!("resolution kind changed"),
+ }
+ tokio::time::resume();
+ release_tx.send(()).unwrap();
+ let (ctx, paused, deferred) = tokio::time::timeout(std::time::Duration::from_secs(5), navigation)
+ .await.expect("navigation completion").unwrap();
+ fixture.await.unwrap();
+ assert_eq!(ctx.pages.len(), 1);
+ assert_eq!(ctx.pages[0].url_string(), format!("http://{address}/"));
+ assert!(paused.is_empty());
+ assert_eq!(deferred.len(), foreign_count.min(MAX_DEFERRED_MESSAGES));
+ assert_eq!(overflow_responses, usize::from(foreign_count > MAX_DEFERRED_MESSAGES));
+ let replies: Vec<serde_json::Value> = std::iter::from_fn(|| reply_rx.try_recv().ok())
+ .map(|text| serde_json::from_str(&text).unwrap()).collect();
+ assert_eq!(replies.iter().filter(|reply| reply["id"] == 1).count(), 1);
+ let navigation_reply = replies.iter().find(|reply| reply["id"] == 1).unwrap();
+ assert!(navigation_reply.get("error").is_none(), "{navigation_reply}");
+ assert!(!replies.iter().any(|reply| reply["id"] == 10), "no duplicate resolution reply");
+ assert_eq!(elapsed, std::time::Duration::ZERO, "ready replies must not wait for a timer");
+ }).await;
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn navigation_intercept_continue_has_no_timer_delay() {
+ assert_navigation_intercept_reply_without_timer("continueRequest").await;
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn navigation_intercept_fulfill_has_no_timer_delay() {
+ assert_navigation_intercept_reply_without_timer("fulfillRequest").await;
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn navigation_intercept_fail_keeps_deferral_bounded_without_delay() {
+ assert_navigation_intercept_reply_without_timer("failRequest").await;
+ }
+
#[test]
fn fetch_resolution_is_handled_once_by_the_outer_processor() {
let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rs
index f88ac3c8..7c4e0f86 100644
--- a/crates/obscura-dom/src/selector.rs
+++ b/crates/obscura-dom/src/selector.rs
@@ -745,7 +745,7 @@ impl DomTree {
context.scope_element = Some(DomElement::new(self, root).opaque());
}
- for desc_id in self.descendants(root) {
+ for desc_id in self.descendants_iter(root) {
let is_element = self.with_node(desc_id, |n| n.is_element()).unwrap_or(false);
if is_element {
let element = DomElement::new(self, desc_id);
@@ -791,7 +791,7 @@ impl DomTree {
}
let mut results = Vec::new();
- for desc_id in self.descendants(root) {
+ for desc_id in self.descendants_iter(root) {
let is_element = self.with_node(desc_id, |n| n.is_element()).unwrap_or(false);
if is_element {
let element = DomElement::new(self, desc_id);
@@ -1278,6 +1278,26 @@ mod tests {
use super::{DomElement, SelectorKey};
+ #[test]
+ fn streaming_selectors_keep_scope_order_and_see_reparented_matches() {
+ let tree = parse_html("<!doctype html><i id='duplicate'></i><main id='root'><section id='duplicate' class='hit early'><b class='hit'></b></section>text<!--gap--><span class='hit late'></span></main><aside class='hit'></aside>");
+ let root = tree.get_element_by_id("root").unwrap();
+ let hits = tree.query_selector_all_from(root, ".hit").unwrap();
+ assert_eq!(hits.len(), 3);
+ assert_eq!(tree.query_selector_from(root, ".late, .early").unwrap(), Some(hits[0]));
+ assert_eq!(tree.query_selector_from(root, "#duplicate").unwrap(), Some(hits[0]));
+ assert_eq!(tree.query_selector_all_from(root, ":scope > .hit").unwrap(), vec![hits[0], hits[2]]);
+ assert_eq!(tree.query_selector_from(root, ":scope").unwrap(), None);
+ assert_eq!(tree.query_selector_from(root, "aside").unwrap(), None);
+ tree.append_child(root, hits[0]);
+ assert_eq!(tree.query_selector_from(root, ".hit").unwrap(), Some(hits[2]));
+ assert_eq!(tree.query_selector_all_from(root, ".hit").unwrap(), vec![hits[2], hits[0], hits[1]]);
+ tree.remove(hits[2]);
+ assert_eq!(tree.query_selector_from(root, ".hit").unwrap(), Some(hits[0]));
+ assert!(tree.query_selector_from(root, "[").is_err());
+ }
+
+
#[test]
fn borrowed_selector_traversal_preserves_links_and_shadow_boundaries() {
let payload = "x".repeat(4096);
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index f2110eee..46ec0431 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -1240,6 +1240,37 @@ impl DomTree {
Some(self.children(root))
}
+ /// Internal preorder traversal for synchronous reads such as selectors.
+ /// Unlike `descendants`, this does not allocate a snapshot of the subtree
+ /// before the first result. Only deferred siblings on the current ancestor
+ /// path are retained, and no RefCell borrow survives an iterator step.
+ pub(crate) fn descendants_iter(&self, node_id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
+ let mut next = self.with_node(node_id, |node| node.first_child).flatten();
+ let mut siblings = Vec::new();
+ let mut remaining = self.node_slot_count();
+ std::iter::from_fn(move || {
+ let current = next.take()?;
+ if remaining == 0 {
+ eprintln!("obscura: descendants iterator cap hit at node {} - tree has a cycle", node_id.index());
+ siblings.clear();
+ return None;
+ }
+ remaining -= 1;
+ let (child, sibling) = self
+ .with_node(current, |node| (node.first_child, node.next_sibling))
+ .unwrap_or_default();
+ if let Some(child) = child {
+ if let Some(sibling) = sibling {
+ siblings.push(sibling);
+ }
+ next = Some(child);
+ } else {
+ next = sibling.or_else(|| siblings.pop());
+ }
+ Some(current)
+ })
+ }
+
pub fn descendants(&self, node_id: NodeId) -> Vec<NodeId> {
let inner = self.inner.borrow();
let mut result = Vec::new();
@@ -1915,6 +1946,41 @@ mod tests {
assert!(!sheet.origin_clean);
}
+ #[test]
+ fn streaming_descendants_match_snapshots_and_keep_shadow_roots_separate() {
+ let tree = crate::parse_html("<!doctype html><main id='root'>text<!--gap--><div><i></i><b></b></div><p></p></main><aside id='host'></aside>");
+ let host = tree.get_element_by_id("host").unwrap();
+ let shadow = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();
+ let child = element(&tree, "span");
+ tree.append_child(shadow, child);
+ let mut roots = tree.descendants(tree.document());
+ roots.extend([tree.document(), shadow, child]);
+ for root in roots {
+ assert_eq!(tree.descendants_iter(root).collect::<Vec<_>>(), tree.descendants(root));
+ }
+ assert!(!tree.descendants_iter(tree.document()).any(|node| node == child));
+ assert_eq!(tree.descendants_iter(shadow).collect::<Vec<_>>(), vec![child]);
+ tree.detach(child);
+ assert_eq!(tree.descendants_iter(shadow).count(), 0);
+ assert_eq!(tree.descendants_iter(child).count(), 0);
+ }
+
+ #[test]
+ fn streaming_descendants_bound_broken_child_and_sibling_cycles() {
+ for sibling_cycle in [false, true] {
+ let tree = DomTree::new();
+ let child = element(&tree, "div");
+ tree.append_child(tree.document(), child);
+ tree.with_node_mut(child, |node| {
+ if sibling_cycle { node.next_sibling = Some(child); }
+ else { node.first_child = Some(child); }
+ });
+ let mut walk = tree.descendants_iter(tree.document());
+ assert_eq!(walk.by_ref().count(), tree.node_slot_count());
+ assert_eq!(walk.next(), None);
+ }
+ }
+
fn element(tree: &DomTree, local: &str) -> NodeId {
tree.new_node(NodeData::Element {
name: QualName::new(None, ns!(html), LocalName::from(local)),
@@ -2076,6 +2142,51 @@ mod tests {
);
}
+ #[test]
+ fn slot_assignment_tracks_renames_reordering_and_non_slottable_nodes() {
+ let tree = DomTree::new();
+ let host = element(&tree, "x-card");
+ tree.append_child(tree.document(), host);
+ let light = element(&tree, "span");
+ let text = tree.new_node(NodeData::Text { contents: "text ".repeat(32_768) });
+ let comment = tree.new_node(NodeData::Comment { contents: "comment".into() });
+ for child in [light, text, comment] {
+ tree.append_child(host, child);
+ assert_eq!(tree.assigned_slot(child), None);
+ }
+ let root = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();
+ let first = element(&tree, "slot");
+ let second = element(&tree, "slot");
+ let foreign = tree.new_node(NodeData::Element {
+ name: QualName::new(None, ns!(svg), LocalName::from("slot")),
+ attrs: vec![], template_contents: None,
+ mathml_annotation_xml_integration_point: false,
+ });
+ for child in [foreign, first, second] { tree.append_child(root, child); }
+ assert!(!tree.is_html_slot_element(foreign));
+ assert_eq!(tree.assigned_nodes(foreign), None);
+ assert_eq!(tree.assigned_nodes(first), Some(vec![light, text]));
+ assert_eq!(tree.assigned_slot(comment), None);
+ assert_eq!(tree.assigned_slot(text), Some(first));
+
+ tree.with_node_mut(first, |node| node.set_attribute("name", "Title".into()));
+ tree.with_node_mut(light, |node| node.set_attribute("slot", "title".into()));
+ assert_eq!(tree.assigned_slot(light), None);
+ assert_eq!(tree.assigned_slot(text), Some(second));
+ tree.with_node_mut(first, |node| node.set_attribute("name", "title".into()));
+ assert_eq!(tree.assigned_nodes(first), Some(vec![light]));
+ tree.with_node_mut(second, |node| node.set_attribute("name", "title".into()));
+ tree.insert_before(first, second);
+ assert_eq!(tree.assigned_slot(light), Some(second));
+ assert_eq!(tree.assigned_nodes(first), Some(vec![]));
+ assert_eq!(tree.assigned_slot(text), None);
+ tree.remove(second);
+ assert_eq!(tree.assigned_slot(light), Some(first));
+ tree.append_child(tree.document(), light);
+ assert_eq!(tree.assigned_slot(light), None);
+ assert_eq!(tree.assigned_nodes(first), Some(vec![]));
+ }
+
#[test]
fn document_id_lookup_never_exposes_a_shadow_descendant() {
let tree = DomTree::new();
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 674a7182..f6fec4bc 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -22,6 +22,11 @@ const __obscuraCore = globalThis.Deno.core;
'__obscura_objects', '__obscura_oid', '__obscura_ua',
'__obscura_platform', '__obscura_ua_platform', '__obscura_ua_platform_version',
'__obscura_stealth', '__obscura_markTrusted', '__obscura_core_handoff',
+ // Created by later evaluation, input and emulation paths. Register them
+ // before the snapshot hide list is captured, just like the other internals.
+ '__obscura_await_rejected', '__obscura_click_target',
+ '__obscura_screen_emulated', '__obscura_screen_w', '__obscura_screen_h',
+ '__obscura_viewport_w', '__obscura_viewport_h',
'__obscura_frameId', '__obscura_parentFrameId', '__obscura_frameWindows',
'__obscura_frameObjects', '__obscura_frameElements', '__obscura_deliverMessage',
'__obscura_liveFrameIds', '__obscura_forgetFrame',
@@ -7480,8 +7485,10 @@ globalThis.__obscura_set_screen_override = function(w, h, emulated) {
_applyScreenSize(w, h, !!emulated);
return;
}
- delete globalThis.__obscura_screen_w;
- delete globalThis.__obscura_screen_h;
+ // Keep the snapshot's writable, hidden slots when clearing an override.
+ // Deleting them makes page initialization recreate read-only properties.
+ globalThis.__obscura_screen_w = undefined;
+ globalThis.__obscura_screen_h = undefined;
const fallback = _fp('screen');
_applyScreenSize(fallback[0], fallback[1], !!emulated);
};
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 767ce274..9ac5b184 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -6465,24 +6465,20 @@ fn op_waapi_control(state: &OpState, id: f64, #[string] action: &str, value: f64
changed
}
-// Not tied to `render`: the JS layer resolves every relative URL through here, in all build
-// variants.
+// Rendering and JS URL reflection share one document-generation cache. Geometry
+// and image getters must not run a whole-document selector on every read.
+#[cfg(feature = "render")]
pub(crate) fn document_base_url(state: &ObscuraState) -> Option<String> {
- let document_url = url::Url::parse(&state.url).ok()?;
- let base_href = state.dom.as_ref().and_then(|dom| {
- dom.query_selector("base[href]")
- .ok()
- .flatten()
- .and_then(|id| {
- dom.get_node(id)
- .and_then(|node| node.get_attribute("href").map(str::to_string))
- })
- });
+ base_values_memoized(state).0
+}
+
+fn resolve_document_base_url(document_url: &str, base_href: Option<&str>) -> Option<String> {
+ let document_url = url::Url::parse(document_url).ok()?;
match base_href {
// https://html.spec.whatwg.org/multipage/semantics.html#set-the-frozen-base-url
// A data: or javascript: base falls back to the document URL. Accepting it would instead
// make every later relative resolution fail.
- Some(href) => match document_url.join(&href) {
+ Some(href) => match document_url.join(href) {
Ok(base) if base.scheme() != "data" && base.scheme() != "javascript" => {
Some(base.to_string())
}
@@ -6529,8 +6525,10 @@ fn base_values_memoized(state: &ObscuraState) -> (Option<String>, Option<String>
return (cached.resolved.clone(), cached.raw_href.clone());
}
}
- let resolved = document_base_url(state);
+ // Resolve both forms from the same first <base href>. Keep the existing
+ // conservative mutation key so reordering/removal and URL changes are seen.
let raw_href = document_base_href(state);
+ let resolved = resolve_document_base_url(&state.url, raw_href.as_deref());
*state.base_url_cache.borrow_mut() = Some(BaseUrlCache {
activity_generation: state.activity_generation,
document_generation: state.document_generation,
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 678ea566..5edf00e7 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -3353,6 +3353,39 @@ impl ObscuraJsRuntime {
self.finish_heap_checked(result)
}
+ /// Poll page work, then park until the runtime's timer/I/O waker fires.
+ /// Unlike run-to-idle, an already idle runtime does not complete the first
+ /// poll. Lifecycle callers can wait for their quiet-window deadline without
+ /// busy-polling, and can recheck network state after each subsequent wake.
+ /// The caller owns the timeout and synchronous-execution watchdog.
+ #[doc(hidden)]
+ pub async fn wait_for_event_loop_activity(&mut self) -> Result<(), String> {
+ self.begin_javascript_task();
+ self.runtime().v8_isolate().perform_microtask_checkpoint();
+ let mut waiting_for_wake = false;
+ let result = std::future::poll_fn(|cx| {
+ let tick = self
+ .runtime()
+ .poll_event_loop(cx, deno_core::PollEventLoopOptions::default());
+ match tick {
+ std::task::Poll::Ready(Err(error)) => {
+ std::task::Poll::Ready(Err(format!("Event loop error: {error}")))
+ }
+ _ if waiting_for_wake => std::task::Poll::Ready(Ok(())),
+ _ => {
+ // poll_event_loop registers this waker even at true idle.
+ // Do not self-wake: real work or the caller's deadline
+ // will schedule the next poll.
+ waiting_for_wake = true;
+ std::task::Poll::Pending
+ }
+ }
+ })
+ .await;
+ self.runtime().v8_isolate().perform_microtask_checkpoint();
+ self.finish_heap_checked(result)
+ }
+
/// Whether the serialized dynamic-script queue is still fetching or
/// evaluating a script. The queue stays private to the bootstrap closure;
/// Rust reads it through a hidden status function so page declarations
@@ -3909,6 +3942,7 @@ impl ObscuraJsRuntime {
}
pub fn take_dom(&self) -> Option<DomTree> {
let mut state = self.state.borrow_mut();
+ state.base_url_cache.get_mut().take();
#[cfg(feature = "render")]
{
state.prepared_render = None;
@@ -3967,6 +4001,11 @@ impl ObscuraJsRuntime {
pub fn with_dom<R>(&self, f: impl FnOnce(&DomTree) -> R) -> Option<R> {
let state = self.state.borrow();
+ // Native callers can mutate this interior-mutable tree without a JS
+ // activity notification. Do not retain a base value across that access.
+ // No-render builds retain their existing JS-only cache behavior.
+ #[cfg(feature = "render")]
+ state.base_url_cache.borrow_mut().take();
state.dom.as_ref().map(f)
}
@@ -4009,6 +4048,8 @@ impl ObscuraJsRuntime {
pub fn dom_ref(&self) -> Option<std::cell::Ref<'_, Option<DomTree>>> {
let r = self.state.borrow();
if r.dom.is_some() {
+ #[cfg(feature = "render")]
+ r.base_url_cache.borrow_mut().take();
Some(std::cell::Ref::map(r, |s| &s.dom))
} else {
None
@@ -4505,6 +4546,57 @@ mod tests {
rt
}
+ #[test]
+ fn screen_override_clear_before_page_init_preserves_mutable_hidden_slots() {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_screen_size_override(None, false);
+ rt.set_dom(parse_html("<p>Screen override lifecycle</p>"));
+ rt.set_url("http://example.com/test");
+ rt.run_page_init();
+ for (width, height) in [(1280, 800), (700, 500)] {
+ rt.set_screen_size_override(Some((width as f64, height as f64)), true);
+ assert_eq!(rt.evaluate("[screen.width, screen.height, screen.availWidth, screen.availHeight]").unwrap(),
+ serde_json::json!([width, height, width, height]));
+ assert_eq!(rt.evaluate(r#"(() => {
+ const names = ['__obscura_screen_w', '__obscura_screen_h'];
+ return names.every(name => {
+ const descriptor = Object.getOwnPropertyDescriptor(window, name);
+ return descriptor.writable && descriptor.configurable && !descriptor.enumerable
+ && !Reflect.ownKeys(window).includes(name);
+ });
+ })()"#).unwrap(), serde_json::json!(true));
+ rt.set_screen_size_override(None, false);
+ assert_eq!(rt.evaluate("[__obscura_screen_w, __obscura_screen_h].every(value => value === undefined)").unwrap(),
+ serde_json::json!(true));
+ }
+ }
+
+ #[test]
+ fn late_runtime_internal_names_use_the_existing_reflection_registry() {
+ let mut rt = setup_runtime("<button id='target'>Click</button>");
+ rt.set_viewport(900.0, 700.0);
+ rt.set_screen_size_override(Some((1280.0, 800.0)), true);
+ assert_eq!(rt.evaluate(r#"(() => {
+ document.getElementById('target').click();
+ globalThis.__obscura_await_rejected = false;
+ globalThis.__obscura_page_owned = 42;
+ const names = ['__obscura_await_rejected', '__obscura_click_target',
+ '__obscura_screen_emulated', '__obscura_screen_w', '__obscura_screen_h',
+ '__obscura_viewport_w', '__obscura_viewport_h'];
+ const surfaces = [Object.keys(window), Object.getOwnPropertyNames(window),
+ Reflect.ownKeys(window), Object.keys(Object.getOwnPropertyDescriptors(window))];
+ const ordinary = { __obscura_screen_w: 1 };
+ return [surfaces.every(keys => names.every(name => !keys.includes(name))),
+ surfaces.every(keys => keys.includes('__obscura_page_owned')),
+ Object.keys(ordinary).includes('__obscura_screen_w'),
+ innerWidth, innerHeight, screen.width, screen.height];
+ })()"#).unwrap(), serde_json::json!([true, true, true, 900, 700, 1280, 800]));
+ rt.set_screen_size_override(None, false);
+ rt.set_screen_size_override(Some((1400.0, 900.0)), true);
+ assert_eq!(rt.evaluate("[Reflect.ownKeys(window).includes('__obscura_screen_w'), screen.width]").unwrap(),
+ serde_json::json!([false, 1400]));
+ }
+
#[test]
fn page_script_cannot_reach_deno_core_or_bootstrap_handoff() {
let mut rt = setup_runtime("<html><body><p id='value'>safe</p></body></html>");
@@ -8062,6 +8154,87 @@ mod tests {
);
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_activity_wait_parks_an_idle_runtime() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.run_event_loop().await.unwrap();
+ let mut wait = std::pin::pin!(rt.wait_for_event_loop_activity());
+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
+ assert!(
+ wait.as_mut().poll(&mut cx).is_pending(),
+ "an idle runtime must park instead of completing synchronously",
+ );
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_activity_wait_drives_timer_microtasks_and_observers() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.execute_script("network-idle-tasks", r#"
+ globalThis.__idleEvents = [];
+ new MutationObserver(() => __idleEvents.push('observer'))
+ .observe(document.body, { attributes: true });
+ setTimeout(() => {
+ __idleEvents.push('timer');
+ Promise.resolve().then(() => {
+ __idleEvents.push('microtask');
+ document.body.setAttribute('data-ready', 'yes');
+ });
+ }, 15);
+ "#).unwrap();
+ // No periodic sleep drives the runtime here. If it loses the timer's
+ // waker, the generous safety deadline fails instead of pumping it.
+ tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ loop {
+ rt.wait_for_event_loop_activity().await.unwrap();
+ if rt.evaluate("__idleEvents.includes('observer')").unwrap()
+ == serde_json::json!(true)
+ {
+ break;
+ }
+ }
+ }).await.expect("timer and observer must wake the parked runtime");
+ assert_eq!(rt.evaluate("__idleEvents").unwrap(),
+ serde_json::json!(["timer", "microtask", "observer"]));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_activity_wait_drives_network_completion() {
+ let (mut rt, accepted) = delayed_fetch_runtime(std::time::Duration::from_millis(30));
+ rt.execute_script("network-idle-fetch", r#"
+ fetch('/value').then(r => r.text()).then(value => {
+ document.body.setAttribute('data-response', value);
+ });
+ "#).unwrap();
+ tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ loop {
+ rt.wait_for_event_loop_activity().await.unwrap();
+ if rt.evaluate("document.body.getAttribute('data-response')").unwrap()
+ == serde_json::json!("hydrated")
+ {
+ break;
+ }
+ }
+ }).await.expect("network response must wake the parked runtime");
+ accepted.try_recv().expect("real HTTP request was received");
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn network_idle_activity_wait_cancellation_preserves_timer() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.execute_script("network-idle-cancel", r#"
+ globalThis.__afterCancel = false;
+ setTimeout(() => { __afterCancel = true; }, 15);
+ "#).unwrap();
+ {
+ let mut wait = std::pin::pin!(rt.wait_for_event_loop_activity());
+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
+ assert!(wait.as_mut().poll(&mut cx).is_pending());
+ }
+ tokio::time::timeout(std::time::Duration::from_secs(2), rt.run_event_loop())
+ .await.expect("timer survives cancellation").unwrap();
+ assert_eq!(rt.evaluate("__afterCancel").unwrap(), serde_json::json!(true));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn idle_event_loop_flushes_resolved_promise_continuations() {
let mut rt = setup_runtime("<html><body><div id='state'>pending</div></body></html>");
@@ -18186,6 +18359,87 @@ mod tests {
);
}
+ #[cfg(not(feature = "render"))]
+ #[test]
+ fn native_dom_reads_keep_base_cache_without_rendering() {
+ let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
+ assert_eq!(rt.evaluate("document.baseURI").unwrap().as_str(), Some("http://example.com/app/"));
+ assert!(rt.state.borrow().base_url_cache.borrow().is_some());
+ rt.with_dom(|dom| dom.document());
+ assert!(rt.state.borrow().base_url_cache.borrow().is_some());
+ drop(rt.dom_ref());
+ assert!(rt.state.borrow().base_url_cache.borrow().is_some());
+ assert_eq!(rt.evaluate("document.baseURI").unwrap().as_str(), Some("http://example.com/app/"));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn render_base_cache_tracks_dom_url_and_document_replacement() {
+ let mut rt = setup_runtime_at_deep_url(
+ r#"<html><head><base id="a" href="/a/"><base id="b" href="/b/"></head>
+ <body><img id="image" src="picture.svg"><p>geometry</p></body></html>"#,
+ );
+ let check = |rt: &mut ObscuraJsRuntime, expected: &str| {
+ let base = {
+ let mut state = rt.state.borrow_mut();
+ ensure_prepared_render(&mut state).unwrap().base_url().unwrap().to_string()
+ };
+ assert_eq!(base, expected);
+ let image = rt.evaluate("document.getElementById('image').currentSrc").unwrap();
+ assert_eq!(image.as_str().unwrap(), url::Url::parse(expected).unwrap().join("picture.svg").unwrap().as_str());
+ assert_eq!(rt.evaluate("document.baseURI").unwrap().as_str().unwrap(), expected);
+ };
+ check(&mut rt, "http://example.com/a/");
+ // Warm both geometry and image metadata, then change which base wins.
+ check(&mut rt, "http://example.com/a/");
+ for (script, expected) in [
+ ("document.head.insertBefore(document.getElementById('b'),document.getElementById('a'))", "http://example.com/b/"),
+ ("document.getElementById('b').removeAttribute('href')", "http://example.com/a/"),
+ ("document.getElementById('a').setAttribute('href','assets/')", "http://example.com/deep/assets/"),
+ ("document.getElementById('a').remove()", "http://example.com/deep/page"),
+ ("document.getElementById('b').setAttribute('href','javascript:bad')", "http://example.com/deep/page"),
+ ("document.getElementById('b').setAttribute('href','https://cdn.example.net/v2/')", "https://cdn.example.net/v2/"),
+ ] {
+ rt.evaluate(script).unwrap();
+ check(&mut rt, expected);
+ }
+ // The embedder updates the native document URL separately from JS history.
+ rt.evaluate("document.getElementById('b').setAttribute('href','assets/')").unwrap();
+ rt.set_url("http://example.com/other/page");
+ rt.run_page_init();
+ check(&mut rt, "http://example.com/other/assets/");
+ rt.set_dom(parse_html("<html><head><base href='/replacement/'></head><body></body></html>"));
+ let mut state = rt.state.borrow_mut();
+ assert_eq!(ensure_prepared_render(&mut state).unwrap().base_url(), Some("http://example.com/replacement/"));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn render_base_cache_sees_native_dom_access_and_removal() {
+ let rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
+ let base = |rt: &ObscuraJsRuntime| {
+ let mut state = rt.state.borrow_mut();
+ ensure_prepared_render(&mut state).unwrap().base_url().unwrap().to_string()
+ };
+ assert_eq!(base(&rt), "http://example.com/app/");
+ rt.with_dom(|dom| {
+ let node = dom.query_selector("base").unwrap().unwrap();
+ dom.with_node_mut(node, |node| node.set_attribute("href", "/native/".into()));
+ });
+ assert_eq!(base(&rt), "http://example.com/native/");
+ {
+ let dom = rt.dom_ref().unwrap();
+ let dom = dom.as_ref().unwrap();
+ let node = dom.query_selector("base").unwrap().unwrap();
+ dom.remove(node);
+ }
+ assert_eq!(base(&rt), "http://example.com/deep/page");
+ rt.set_dom(parse_html(BASE_HREF_PAGE));
+ assert_eq!(base(&rt), "http://example.com/app/");
+ rt.take_dom();
+ assert_eq!(crate::ops::document_base_url(&rt.state.borrow()).as_deref(), Some("http://example.com/deep/page"));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn base_href_governs_fetch_and_xhr_targets() {
let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
@@ -20731,6 +20985,37 @@ mod tests {
assert_eq!(request_thread.join().unwrap(), "/scoped.js");
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn guarded_classic_script_preserves_completion_microtasks_and_errors() {
+ let mut rt = ObscuraJsRuntime::new();
+ let padding = format!("/*{}*/", "x".repeat(10_000));
+ let source = format!(
+ "globalThis.__guardedCount = (globalThis.__guardedCount || 0) + 1; \
+ Promise.resolve().then(() => {{ globalThis.__guardedMicrotasks = \
+ (globalThis.__guardedMicrotasks || 0) + 1; }}); {padding}",
+ );
+ for _ in 0..3 {
+ rt.execute_script_guarded("guarded-fast-script", &source).unwrap();
+ }
+ assert_eq!(rt.evaluate("[__guardedCount, __guardedMicrotasks]").unwrap(),
+ serde_json::json!([3, 3]));
+ let error = rt.execute_script_guarded(
+ "guarded-throw",
+ &format!("throw new Error('guarded-script-error'); {padding}"),
+ ).unwrap_err();
+ assert!(error.contains("guarded-script-error"), "{error}");
+ assert_eq!(rt.evaluate("__guardedCount + 1").unwrap().as_f64(), Some(4.0));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn zero_script_timeout_preserves_classic_execution() {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.execute_script_with_timeout(
+ "zero-timeout", "globalThis.__zeroTimeoutRan = true;", std::time::Duration::ZERO,
+ ).unwrap();
+ assert_eq!(rt.evaluate("__zeroTimeoutRan").unwrap(), serde_json::json!(true));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn timed_out_classic_script_leaves_runtime_reusable() {
let mut rt = ObscuraJsRuntime::new();
diff --git a/crates/obscura-render/Cargo.toml b/crates/obscura-render/Cargo.toml
index db0f600b..d152b7db 100644
--- a/crates/obscura-render/Cargo.toml
+++ b/crates/obscura-render/Cargo.toml
@@ -22,7 +22,7 @@ ab_glyph = { workspace = true, optional = true }
# Real inline text layout: HarfBuzz-class shaping (rustybuzz) + UAX#14 line
# breaking, the same algorithms browsers use. Built with only our embedded
# fonts (no system-font scan) so layout stays deterministic across hosts.
-cosmic-text = { version = "=0.14.2", default-features = false, features = ["std", "swash"], optional = true }
+cosmic-text = { version = "=0.14.2", default-features = false, features = ["std", "swash", "shape-run-cache"], optional = true }
# Keep this exactly aligned with cosmic-text 0.14's raster backend. Cosmic
# and the renderer consume the same canonical variation coordinates for
# shaping and rasterization.
diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rs
index b5ba402b..56e3a4cd 100644
--- a/crates/obscura-render/src/css.rs
+++ b/crates/obscura-render/src/css.rs
@@ -616,17 +616,11 @@ fn invalidation_compounds(selector: &str) -> (Vec<(String, InvalidationReaches)>
} else if compounds.is_empty() {
malformed = true;
}
- let mut descendants_to_right = false;
- for (_, reaches) in compounds.iter_mut().rev() {
- if reaches.contains(InvalidationReaches::DESCENDANTS) {
- descendants_to_right = true;
- } else if descendants_to_right && reaches.contains(InvalidationReaches::SIBLINGS) {
- // `.foo ~ .bar .child`: a change to `.foo` can affect descendants
- // of following siblings. A flat Siblings reach is insufficient
- // unless phase 2 also carries the remaining descendant path.
- *reaches = reaches.union(InvalidationReaches::CONSERVATIVE);
- }
- }
+ // The renderer expands SIBLINGS into entire following-sibling subtrees.
+ // An ordinary chain such as `.foo ~ .bar .child` therefore remains within
+ // that scope: later combinators move only down or to later siblings.
+ // Nested selector-list composition still uses its separate conservative
+ // fallback when a flat reach cannot describe the outer continuation.
(compounds, malformed)
}
@@ -3461,6 +3455,7 @@ impl Stylesheet {
None,
animation_sample,
animation_timeline,
+ false,
)
}
@@ -3528,6 +3523,7 @@ impl Stylesheet {
Some(evaluator),
animation_sample,
animation_timeline,
+ false,
)
}
@@ -3552,6 +3548,7 @@ impl Stylesheet {
evaluator: Option<&mut ContainerQueryEvaluator<'_>>,
animation_sample: crate::AnimationSample,
animation_timeline: &mut crate::AnimationTimelineState,
+ ancestor_display_none: bool,
) -> Option<HashMap<String, String>> {
self.apply_internal(
tree,
@@ -3568,6 +3565,7 @@ impl Stylesheet {
evaluator,
animation_sample,
animation_timeline,
+ ancestor_display_none,
)
}
@@ -3587,6 +3585,7 @@ impl Stylesheet {
mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,
animation_sample: crate::AnimationSample,
animation_timeline: &mut crate::AnimationTimelineState,
+ ancestor_display_none: bool,
) -> Option<HashMap<String, String>> {
let shadow_host_declarations = shadow_host_sheet
.map(|sheet| {
@@ -4023,35 +4022,24 @@ impl Stylesheet {
if !self.keyframes.is_empty() && (style.animation_name.is_some() || important_has_animation)
{
let mut animation_style = style.clone();
+ // The winning display declaration participates in animation
+ // eligibility, including !important and shadow-scope declarations.
for &(_, _, i) in &important_matched {
let rule = &self.rules[i];
- if !rule.important_flags.has_animation {
- continue;
- }
let expanded = substitute_declarations(
- &rule.important_decls,
- props,
- rule.important_flags.has_var,
+ &rule.important_decls, props, rule.important_flags.has_var,
);
crate::style::apply_animation_declarations(&mut animation_style, &expanded);
}
- if inline_important_flags.has_animation {
- let expanded = substitute_declarations(
- &inline_important,
- props,
- inline_important_flags.has_var,
- );
- crate::style::apply_animation_declarations(&mut animation_style, &expanded);
- }
- if shadow_important_flags.has_animation {
- let expanded = substitute_declarations(
- &shadow_scope_declarations.important,
- props,
- shadow_important_flags.has_var,
- );
- crate::style::apply_animation_declarations(&mut animation_style, &expanded);
- }
- if let Some(name) = animation_style.animation_name.as_deref() {
+ let expanded = substitute_declarations(&inline_important, props, inline_important_flags.has_var);
+ crate::style::apply_animation_declarations(&mut animation_style, &expanded);
+ let expanded = substitute_declarations(
+ &shadow_scope_declarations.important, props, shadow_important_flags.has_var,
+ );
+ crate::style::apply_animation_declarations(&mut animation_style, &expanded);
+ if ancestor_display_none || animation_style.display == crate::Display::None {
+ animation_timeline.suppress_css_animation(nid, animation_sample);
+ } else if let Some(name) = animation_style.animation_name.as_deref() {
if let Some(keyframes) = self.keyframes.get(name) {
style.animation_has_render_effect = !keyframes.tracks.is_empty();
style.animation_effect_impact = keyframes
@@ -7645,7 +7633,7 @@ mod tests {
trigger,
InvalidationReaches::SIBLINGS,
));
- assert!(dependencies_reach(
+ assert!(!dependencies_reach(
trigger,
InvalidationReaches::CONSERVATIVE,
));
@@ -7711,7 +7699,10 @@ mod tests {
assert!(!entries[2].text_side_effect);
assert!(entries[3].structural_side_effect);
assert!(entries[3].text_side_effect);
- assert!(entries[4].unrepresentable_outer_path);
+ assert!(entries[4]
+ .anchor_reaches
+ .contains(InvalidationReaches::SIBLINGS));
+ assert!(!entries[4].unrepresentable_outer_path);
let tree = obscura_dom::parse_html(
"<section id=host class=host></section><section id=other class=other></section>",
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index a2b54c2f..90245e84 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -391,7 +391,7 @@ pub enum RetainedAttributeMutationKind {
/// frameworks routinely toggle attributes such as `autocomplete`, `part`,
/// and `itemprop`; forcing a document cascade for an unreferenced attribute is
/// both unnecessary and particularly costly during hydration. Known HTML
-/// resource/global attributes remain an explicit full fallback.
+/// document-global attributes remain an explicit full fallback.
pub fn retained_attribute_mutation_kind(
tree: &DomTree,
node: NodeId,
@@ -450,24 +450,21 @@ pub fn retained_attribute_mutation_kind(
return Full;
}
- // Resource selection changes require the embedding runtime to rebuild its
- // decoded-resource/intrinsic-size inputs, not merely recompute CSS.
- if (local == "img"
+ // Image selection and intrinsic sizes are refreshed before every retained
+ // layout. Re-cascade the image's native box and selector dependents, while
+ // retaining unrelated styles. Geometry reuse needs a separate proof that
+ // neither selector dependencies nor intrinsic dimensions can change it.
+ if local == "img" && image_source_attribute(&name) {
+ return Subtree;
+ }
+
+ // Other resource changes can replace an embedded document or affect
+ // resources beyond the mutated element's native box.
+ if (local == "source"
&& matches!(
name.as_str(),
- "crossorigin"
- | "decoding"
- | "fetchpriority"
- | "referrerpolicy"
- | "sizes"
- | "src"
- | "srcset"
+ "height" | "media" | "sizes" | "src" | "srcset" | "type" | "width"
))
- || (local == "source"
- && matches!(
- name.as_str(),
- "height" | "media" | "sizes" | "src" | "srcset" | "type" | "width"
- ))
|| (matches!(local.as_str(), "audio" | "video" | "track")
&& matches!(
name.as_str(),
@@ -576,9 +573,9 @@ impl From<TreeStyleMutation> for RetainedStyleMutation {
}
}
-/// Style maps moved out of a previous layout. Moving, rather than cloning,
-/// keeps incremental restyle from retaining a second heap-heavy LayoutStyle
-/// graph beside the final used styles.
+/// Style maps moved out of a completed layout. Retained restyle consumes
+/// these post-layout values; moving ownership avoids cloning their heap-heavy
+/// payloads when a final layout or query-disabled seed is replaced.
pub(crate) struct RetainedStyleMaps {
pub styles: HashMap<NodeId, crate::LayoutStyle>,
pub custom_properties: HashMap<NodeId, std::rc::Rc<HashMap<String, String>>>,
@@ -2597,22 +2594,23 @@ fn cascade_node_style(
inherited_cell_padding: Option<f32>,
inherited_color_scheme_dark: bool,
fresh_styles: Option<&HashSet<NodeId>>,
+ ancestor_display_none: bool,
) -> Option<(
std::rc::Rc<HashMap<String, String>>,
Option<f32>,
bool,
bool,
)> {
- let Some(node) = tree.borrow_node(id) else {
- return None;
- };
- let is_element = node.is_element();
+ // Text/comment payloads never participate in the cascade, and retained
+ // element styles need only the table-scoped presentational hint below.
+ // Borrow the full node only when its element style must be recomputed.
+ let is_element = tree.with_node(id, |node| node.is_element())?;
// The custom-property map in force for this node's subtree: the parent's,
// unless this element declares its own `--x` (then a richer map).
let mut this_props = parent_props.clone();
let mut descendant_cell_padding = inherited_cell_padding;
let mut descendant_color_scheme_dark = inherited_color_scheme_dark;
- let reuse_style = node.is_element()
+ let reuse_style = is_element
&& fresh_styles.is_some_and(|fresh| !fresh.contains(&id))
&& styles.contains_key(&id)
&& custom_properties.contains_key(&id);
@@ -2622,16 +2620,17 @@ fn cascade_node_style(
.cloned()
.unwrap_or_else(|| parent_props.clone());
descendant_color_scheme_dark = styles.get(&id).is_some_and(|style| style.color_scheme_dark);
- if node
- .as_element()
- .is_some_and(|elem| elem.local.as_ref() == "table")
- {
- descendant_cell_padding = node
- .get_attribute("cellpadding")
- .and_then(|value| value.trim().parse::<f32>().ok())
- .filter(|value| value.is_finite() && *value >= 0.0);
- }
- } else if let Some(elem) = node.as_element() {
+ tree.with_node(id, |node| {
+ if node.as_element().is_some_and(|elem| elem.local.as_ref() == "table") {
+ descendant_cell_padding = node
+ .get_attribute("cellpadding")
+ .and_then(|value| value.trim().parse::<f32>().ok())
+ .filter(|value| value.is_finite() && *value >= 0.0);
+ }
+ });
+ } else if is_element {
+ let node = tree.borrow_node(id)?;
+ let elem = node.as_element()?;
if elem.local.as_ref() == "table" {
// `cellpadding` is a table-scoped presentational hint applied to
// its cells, below author CSS. Entering any nested table resets
@@ -2774,53 +2773,23 @@ fn cascade_node_style(
}
assigned_slot = tree.assigned_slot(slot);
}
- let effective_props = if shadow_host_sheet.is_some() || !slotted_scopes.is_empty() {
- sheet.apply_with_shadow_scopes_at_animation_time(
- shadow_host_sheet.map(|sheet| &**sheet),
- &slotted_scopes,
- tree,
- matcher,
- id,
- node_id,
- &classes,
- elem.local.as_ref(),
- &mut style,
- parent_props,
- node.get_attribute("style"),
- container_evaluator.as_deref_mut(),
- animation_sample,
- animation_timeline,
- )
- } else if let Some(evaluator) = container_evaluator.as_deref_mut() {
- sheet.apply_with_container_queries_at_animation_time(
- tree,
- matcher,
- id,
- node_id,
- &classes,
- elem.local.as_ref(),
- &mut style,
- parent_props,
- node.get_attribute("style"),
- evaluator,
- animation_sample,
- animation_timeline,
- )
- } else {
- sheet.apply_at_animation_time(
- tree,
- matcher,
- id,
- node_id,
- &classes,
- elem.local.as_ref(),
- &mut style,
- parent_props,
- node.get_attribute("style"),
- animation_sample,
- animation_timeline,
- )
- };
+ let effective_props = sheet.apply_with_shadow_scopes_at_animation_time(
+ shadow_host_sheet.map(|sheet| &**sheet),
+ &slotted_scopes,
+ tree,
+ matcher,
+ id,
+ node_id,
+ &classes,
+ elem.local.as_ref(),
+ &mut style,
+ parent_props,
+ node.get_attribute("style"),
+ container_evaluator.as_deref_mut(),
+ animation_sample,
+ animation_timeline,
+ ancestor_display_none,
+ );
if let Some(m) = effective_props {
this_props = std::rc::Rc::new(m);
}
@@ -2913,6 +2882,7 @@ fn cascade_walk(
props: std::rc::Rc<HashMap<String, String>>,
cell_padding: Option<f32>,
color_scheme_dark: bool,
+ display_none: bool,
matcher_base: MatcherBase,
use_container_evaluator: bool,
}
@@ -2930,6 +2900,7 @@ fn cascade_walk(
props: parent_props.clone(),
cell_padding: inherited_cell_padding,
color_scheme_dark: inherited_color_scheme_dark,
+ display_none: false,
matcher_base: MatcherBase::Incremental,
use_container_evaluator: true,
})];
@@ -2994,11 +2965,14 @@ fn cascade_walk(
visit.cell_padding,
visit.color_scheme_dark,
fresh_styles,
+ visit.display_none,
)
else {
continue;
};
+ let descendant_display_none = visit.display_none || styles.get(&visit.id)
+ .is_some_and(|style| style.display == crate::Display::None);
if is_element {
current_matcher.push_ancestor(tree, visit.id);
work.push(Work::PopAncestor);
@@ -3015,6 +2989,7 @@ fn cascade_walk(
props: this_props.clone(),
cell_padding: None,
color_scheme_dark: descendant_color_scheme_dark,
+ display_none: descendant_display_none,
matcher_base: MatcherBase::FreshEmpty,
use_container_evaluator: false,
}));
@@ -3033,6 +3008,7 @@ fn cascade_walk(
props: this_props.clone(),
cell_padding: descendant_cell_padding,
color_scheme_dark: descendant_color_scheme_dark,
+ display_none: descendant_display_none,
matcher_base: MatcherBase::FreshFromAncestors,
use_container_evaluator: true,
}));
@@ -3052,6 +3028,7 @@ fn cascade_walk(
props: this_props.clone(),
cell_padding: descendant_cell_padding,
color_scheme_dark: descendant_color_scheme_dark,
+ display_none: descendant_display_none,
matcher_base: MatcherBase::Incremental,
use_container_evaluator: visit.use_container_evaluator,
}));
@@ -3163,9 +3140,9 @@ fn resolve_css_counters(tree: &DomTree, styles: &mut HashMap<NodeId, crate::Layo
styles: &mut HashMap<NodeId, crate::LayoutStyle>,
counters: &mut CssCounterState,
) -> Vec<String> {
- let Some(node) = tree.borrow_node(id) else {
+ if tree.with_node(id, |_| ()).is_none() {
return Vec::new();
- };
+ }
if styles
.get(&id)
.is_some_and(|style| style.display == crate::Display::None)
@@ -3215,7 +3192,6 @@ fn resolve_css_counters(tree: &DomTree, styles: &mut HashMap<NodeId, crate::Layo
// Non-element nodes cannot create counter scopes, but walking through
// them keeps this robust to document fragments and template wrappers.
- let _ = node;
created
}
@@ -3341,7 +3317,7 @@ fn add_container_query_reset_scopes(
selected_ancestor: bool,
dirty: &mut HashSet<NodeId>,
) {
- let is_element = tree.borrow_node(id).is_some_and(|node| node.is_element());
+ let is_element = tree.with_node(id, |node| node.is_element()).unwrap_or(false);
let can_query_here = inside_active_container || active_containers.contains(&id);
let selected_here = !selected_ancestor
&& can_query_here
@@ -3359,12 +3335,12 @@ fn add_container_query_reset_scopes(
// Stop as soon as an already-recorded context node is reached. An
// earlier selected sibling necessarily inserted the rest of this same
// ancestor chain, so each ancestor is visited at most once.
- let mut ancestor = tree.borrow_node(id).and_then(|node| node.parent);
+ let mut ancestor = tree.with_node(id, |node| node.parent).flatten();
while let Some(parent) = ancestor {
if !dirty.insert(parent) {
break;
}
- ancestor = tree.borrow_node(parent).and_then(|node| node.parent);
+ ancestor = tree.with_node(parent, |node| node.parent).flatten();
}
}
if is_element {
@@ -4048,6 +4024,15 @@ fn retained_style_plan(
}
continue;
};
+ // Rendering observes the final tree at the flush boundary. A queued
+ // attribute write on a now-detached wrapper cannot affect that tree.
+ // Its removal/reparent mutations still invalidate the old parent,
+ // relational anchors, siblings, and any children moved into the page.
+ // In particular, do not let a transient inline-style write force a
+ // document-wide :has([style]) fallback after the wrapper is gone.
+ if !tree.is_connected(mutation.node) {
+ continue;
+ }
let name = mutation.name.to_ascii_lowercase();
match retained_attribute_mutation_kind(tree, mutation.node, &name) {
RetainedAttributeMutationKind::Full => return RetainedStylePlan::Full,
@@ -4150,23 +4135,7 @@ pub(crate) fn can_retain_layout_for_metadata(
if nodes.iter().any(|node| tree.shadow_root(*node).is_some()) {
return false;
}
- let sources = nodes
- .into_iter()
- .filter_map(|id| {
- let node = tree.borrow_node(id)?;
- let element = node.as_element()?;
- (element.local.as_ref() == "style"
- && node.get_attribute("media").is_none_or(|media| {
- media.trim().is_empty()
- || crate::css::media_query_applies_for_viewport_and_type(
- media,
- viewport,
- crate::CssMediaType::Screen,
- )
- }))
- .then(|| tree.text_content(id))
- })
- .collect::<Vec<_>>();
+ let sources = document_stylesheet_sources(tree, viewport, crate::CssMediaType::Screen);
let (sheet, cache_hit) =
cache.get_or_parse(tree, &sources, viewport, crate::CssMediaType::Screen);
cache_hit
@@ -4179,6 +4148,56 @@ pub(crate) fn can_retain_layout_for_metadata(
)
}
+fn image_source_attribute(name: &str) -> bool {
+ matches!(name, "src" | "srcset" | "sizes" | "crossorigin"
+ | "decoding" | "fetchpriority" | "referrerpolicy")
+}
+
+/// Identify image-source changes that cannot alter the cascade. The painter
+/// must separately prove that each image's intrinsic size cannot affect layout.
+pub(crate) fn image_source_updates_without_style_damage(
+ tree: &DomTree,
+ viewport: (f32, f32),
+ cache: &mut crate::css::StylesheetCache,
+ mutations: &[RetainedStyleMutation],
+) -> Option<Vec<NodeId>> {
+ let mut images = Vec::new();
+ let mut names = Vec::new();
+ for mutation in mutations {
+ let RetainedStyleMutation::Attribute(attribute) = mutation else {
+ return None;
+ };
+ let name = attribute.name.to_ascii_lowercase();
+ let metadata = (name.starts_with("data-") || name == "tabindex")
+ && retained_attribute_mutation_kind(tree, attribute.node, &name)
+ == RetainedAttributeMutationKind::Selector;
+ if !metadata {
+ if !image_source_attribute(&name)
+ || !tree.get_node(attribute.node).is_some_and(|node| {
+ node.as_element().is_some_and(|element| element.local.as_ref() == "img")
+ })
+ {
+ return None;
+ }
+ images.push(attribute.node);
+ }
+ names.push(name);
+ }
+ if images.is_empty()
+ || tree.descendants(tree.document()).iter().any(|node| tree.shadow_root(*node).is_some())
+ {
+ return None;
+ }
+ let sources = document_stylesheet_sources(tree, viewport, crate::CssMediaType::Screen);
+ let (sheet, cache_hit) = cache.get_or_parse(tree, &sources, viewport, crate::CssMediaType::Screen);
+ if !cache_hit || names.iter().any(|name| !sheet.invalidation_map().attribute_dependencies(name).is_empty()) {
+ return None;
+ }
+ images.sort_unstable_by_key(|node| node.index());
+ images.dedup();
+ Some(images)
+}
+
pub(crate) fn layout_dom_with_web_fonts(
tree: &DomTree,
viewport: (f32, f32),
@@ -4504,12 +4523,13 @@ pub fn computed_style_without_layout(
let mut pointer_events = false;
let shadow_sheets = HashMap::new();
let mut timeline = crate::AnimationTimelineState::default();
+ let mut ancestor_display_none = false;
for &node in &path {
let (next_props, next_padding, next_dark, element) = cascade_node_style(
tree, node, &sheet, &sheet, &shadow_sheets, &mut matcher,
&mut styles, &mut custom_properties, &props, &mut None, quirks,
viewport, crate::AnimationSample::default(), &mut timeline,
- cell_padding, dark, None,
+ cell_padding, dark, None, ancestor_display_none,
)?;
props = next_props;
cell_padding = next_padding;
@@ -4517,6 +4537,7 @@ pub fn computed_style_without_layout(
if !element { continue; }
matcher.push_ancestor(tree, node);
let style = styles.get_mut(&node)?;
+ ancestor_display_none |= style.display == crate::Display::None;
// Display inheritance and live effects retain the complete normalization
// path. A query cannot become active without a query container on this
// ancestor path, including named normal/style containers.
@@ -4607,6 +4628,45 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
media_type: crate::CssMediaType,
animation_sample: crate::AnimationSample,
animation_timeline: &mut crate::AnimationTimelineState,
+) -> (DomLayout, ContainerLayoutTelemetry) {
+ layout_dom_with_web_fonts_pass_limit_and_query_seed(
+ tree, viewport, intrinsic, fonts, pass_limit, stylesheet_cache, retained,
+ mutations, media_type, animation_sample, animation_timeline, None,
+ )
+}
+
+pub(crate) fn layout_dom_with_query_seed(
+ tree: &DomTree,
+ viewport: (f32, f32),
+ intrinsic: &ReplacedIntrinsicMap,
+ fonts: &[crate::inline::WebFont],
+ stylesheet_cache: &mut crate::css::StylesheetCache,
+ retained: Option<RetainedStyleMaps>,
+ mutations: &[RetainedStyleMutation],
+ media_type: crate::CssMediaType,
+ animation_sample: crate::AnimationSample,
+ animation_timeline: &mut crate::AnimationTimelineState,
+ query_seed: &mut Option<RetainedStyleMaps>,
+) -> DomLayout {
+ layout_dom_with_web_fonts_pass_limit_and_query_seed(
+ tree, viewport, intrinsic, fonts, None, Some(stylesheet_cache), retained,
+ mutations, media_type, animation_sample, animation_timeline, Some(query_seed),
+ ).0
+}
+
+fn layout_dom_with_web_fonts_pass_limit_and_query_seed(
+ tree: &DomTree,
+ viewport: (f32, f32),
+ intrinsic: &ReplacedIntrinsicMap,
+ fonts: &[crate::inline::WebFont],
+ pass_limit: Option<usize>,
+ stylesheet_cache: Option<&mut crate::css::StylesheetCache>,
+ retained: Option<RetainedStyleMaps>,
+ mutations: &[RetainedStyleMutation],
+ media_type: crate::CssMediaType,
+ animation_sample: crate::AnimationSample,
+ animation_timeline: &mut crate::AnimationTimelineState,
+ mut query_seed: Option<&mut Option<RetainedStyleMaps>>,
) -> (DomLayout, ContainerLayoutTelemetry) {
let timing = std::env::var("OBSCURA_RENDER_TIMING").is_ok();
@@ -4628,6 +4688,12 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
let shadow_sheets = collect_shadow_stylesheets(tree, viewport, media_type);
let t_parse = t0.elapsed();
+ // Only the owning PreparedRender can supply an initial-pass cache. Its
+ // ordered stylesheet/media/viewport key and ordinary damage planner still
+ // govern reuse. Query-enabled final styles never enter this cache.
+ let initial_styles = query_seed.as_deref_mut().and_then(Option::take);
+ let retained_is_query_seed = initial_styles.is_some();
+ let retained = initial_styles.or(retained);
let retained_requested = retained
.as_ref()
.map_or(0, |retained| retained.styles.len());
@@ -4667,7 +4733,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
mut dirty,
has_animation_damage,
} => {
- if !active_containers.is_empty() && sheet.has_container_queries() {
+ if !retained_is_query_seed && !active_containers.is_empty() && sheet.has_container_queries() {
let mut matcher = tree.matcher();
add_container_query_reset_scopes(
tree,
@@ -4712,6 +4778,10 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
.as_ref()
.map_or(0, |(retained, _)| retained.styles.len() - retained_fresh);
let retained_fallback = usize::from(retained_requested != 0 && retained.is_none());
+ // Query passes are speculative. Only the chosen layout may commit CSS
+ // animation start/stop history; provisional display:none must not restart
+ // an animation that is visible in the final container-query cascade.
+ let animation_before = sheet.has_container_queries().then(|| animation_timeline.clone());
let (mut laid, _, mut query, mut cascade_time) = layout_dom_once(
tree,
viewport,
@@ -4805,7 +4875,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
},
);
}
- let mut previous_candidate: Option<(DomLayout, crate::css::ContainerDecisionSignature)> = None;
+ let mut previous_candidate: Option<(DomLayout, crate::css::ContainerDecisionSignature, crate::AnimationTimelineState)> = None;
let mut seen_signatures = Vec::new();
let mut passes = 1;
let mut termination = ContainerLayoutTermination::PassCapFallback;
@@ -4823,13 +4893,13 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
element_depths.insert(tree.document(), 0usize);
let mut max_dom_depth = 1usize;
for id in rendered_descendants(tree, tree.document()) {
- let Some(node) = tree.borrow_node(id) else {
+ let Some(is_element) = tree.with_node(id, |node| node.is_element()) else {
continue;
};
let parent_depth = rendered_parent(tree, id)
.and_then(|parent| element_depths.get(&parent).copied())
.unwrap_or(0);
- let depth = parent_depth + usize::from(node.is_element());
+ let depth = parent_depth + usize::from(is_element);
element_depths.insert(id, depth);
max_dom_depth = max_dom_depth.max(depth);
}
@@ -4839,6 +4909,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
});
let mut needs_fallback = false;
for pass in 2..=max_passes {
+ *animation_timeline = animation_before.as_ref().expect("query timeline").clone();
let (next, signature, pass_query, pass_cascade) = layout_dom_once(
tree,
viewport,
@@ -4857,11 +4928,26 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
query.ancestor_steps += pass_query.ancestor_steps;
cascade_time += pass_cascade;
let next_snapshot = container_snapshot(tree, &next);
+ // The first query-enabled pass replaces the initial layout. Move its
+ // query-disabled style maps into the owning preparation instead of
+ // cloning a second graph. RetainedStyleMaps expects the same post-layout
+ // provenance as the existing final-style reuse path; pre-layout cascade
+ // values can change seed geometry and require another convergence pass.
+ // This caps entries, not author-controlled heap payload bytes. Dormant
+ // queries, shadow scopes and larger documents keep the existing path.
+ if pass == 2 && shadow_sheets.is_empty() && laid.styles.len() <= 8192 {
+ if let Some(query_seed) = query_seed.as_deref_mut() {
+ *query_seed = Some(RetainedStyleMaps {
+ styles: std::mem::take(&mut laid.styles),
+ custom_properties: std::mem::take(&mut laid.custom_properties),
+ });
+ }
+ }
let signature = signature.expect("container pass must produce a signature");
if let Some(reason) = container_iteration_termination(
next_snapshot == snapshot,
&signature,
- previous_candidate.as_ref().map(|(_, signature)| signature),
+ previous_candidate.as_ref().map(|(_, signature, _)| signature),
) {
termination = reason;
// Equal adjacent signatures prove that the *previous* candidate's
@@ -4869,10 +4955,11 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
// snapshot. Returning `next` here would be off by one and could
// expose styles evaluated against geometry it no longer has.
laid = if reason == ContainerLayoutTermination::SignatureStable {
- previous_candidate
+ let (layout, _, timeline) = previous_candidate
.take()
- .expect("stable signature requires a previous candidate")
- .0
+ .expect("stable signature requires a previous candidate");
+ *animation_timeline = timeline;
+ layout
} else {
next
};
@@ -4884,7 +4971,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
break;
}
seen_signatures.push(signature.clone());
- previous_candidate = Some((next, signature));
+ previous_candidate = Some((next, signature, animation_timeline.clone()));
snapshot = next_snapshot;
if pass == max_passes {
needs_fallback = true;
@@ -4896,6 +4983,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
// we return a layout whose conditional declarations contradict the
// geometry used to choose them. Disable the unstable conditional
// rules for this render and expose the downgrade in telemetry.
+ *animation_timeline = animation_before.as_ref().expect("query timeline").clone();
let (fallback, _, fallback_query, fallback_cascade) = layout_dom_once(
tree,
viewport,
@@ -4985,9 +5073,9 @@ fn layout_dom_once(
// combinators (".mw-body .firstHeading") fast-reject via the filter
// instead of falling back to the always-true "can't reject" case.
let quirks_mode = !tree.descendants(tree.document()).into_iter().any(|id| {
- tree.borrow_node(id).map_or(false, |node| {
+ tree.with_node(id, |node| {
matches!(node.data, obscura_dom::tree::NodeData::Doctype { .. })
- })
+ }).unwrap_or(false)
});
cascade_walk(
tree,
@@ -5021,12 +5109,12 @@ fn layout_dom_once(
let descendants = tree.descendants(tree.document());
let needs_emoji_font = descendants.iter().any(|id| {
- tree.borrow_node(*id).is_some_and(|node| match &node.data {
+ tree.with_node(*id, |node| match &node.data {
obscura_dom::tree::NodeData::Text { contents } => {
crate::inline::text_may_need_emoji_font(contents)
}
_ => false,
- })
+ }).unwrap_or(false)
}) || styles.values().any(|style| {
style
.before_content
@@ -5051,7 +5139,7 @@ fn layout_dom_once(
// element descendant (the <html> root).
let root = descendants
.into_iter()
- .find(|id| tree.borrow_node(*id).map(|n| n.is_element()).unwrap_or(false));
+ .find(|id| tree.with_node(*id, |node| node.is_element()).unwrap_or(false));
let mut rects = HashMap::new();
let mut grid_overflow = HashMap::new();
@@ -9627,6 +9715,8 @@ pub(crate) fn rendered_children(tree: &DomTree, id: NodeId) -> Vec<NodeId> {
return assigned_or_fallback;
}
+ // Box-tree traversal needs only this predicate, not an owned copy of the
+ // node's text and attributes.
let Some(is_closed_html_details) = tree.with_node(id, |node| {
node.as_element().is_some_and(|name| {
name.ns.as_ref() == "http://www.w3.org/1999/xhtml"
@@ -9828,8 +9918,7 @@ fn build_any(
styles: &HashMap<NodeId, crate::LayoutStyle>,
) -> Vec<taffy::NodeId> {
let is_text = tree
- .borrow_node(id)
- .map(|n| matches!(n.data, obscura_dom::tree::NodeData::Text { .. }))
+ .with_node(id, |node| matches!(node.data, obscura_dom::tree::NodeData::Text { .. }))
.unwrap_or(false);
if is_text {
return build_text_words(tree, id, taffy_tree, styles, words, engine, ifc_items);
@@ -10076,15 +10165,12 @@ fn is_flattenable_inline(
id: NodeId,
styles: &HashMap<NodeId, crate::LayoutStyle>,
) -> bool {
- let Some(node) = tree.borrow_node(id) else {
- return false;
- };
- let Some(element) = node.as_element() else {
- return false;
- };
// BR is boxless-looking but semantically contributes a mandatory break.
// Flattening it as an empty wrapper deletes the break entirely.
- if element.local.as_ref() == "br" {
+ let element_can_flatten = tree.with_node(id, |node| {
+ node.as_element().is_some_and(|element| element.local.as_ref() != "br")
+ }).unwrap_or(false);
+ if !element_can_flatten {
return false;
}
let Some(style) = styles.get(&id) else {
@@ -12645,8 +12731,18 @@ fn build(
ifc_items: &mut IfcRegistry,
styles: &HashMap<NodeId, crate::LayoutStyle>,
) -> Option<taffy::NodeId> {
- let node = tree.borrow_node(id)?;
- let _name = node.as_element()?;
+ // Only the name and native-control flags survive this read. Avoid
+ // copying every attribute (including inline data URLs) for each box.
+ let (_name, has_controls, has_embed_source, is_open) = tree.with_node(id, |node| {
+ let name = node.as_element()?;
+ Some((
+ name.clone(),
+ node.get_attribute("controls").is_some(),
+ name.local.as_ref() != "embed"
+ || node.get_attribute("src").is_some_and(|value| !value.trim().is_empty()),
+ node.get_attribute("open").is_some(),
+ ))
+ })??;
let style = styles.get(&id)?;
if style.display == crate::Display::None {
return None;
@@ -12825,11 +12921,8 @@ fn build(
if let Some((width, height)) = crate::inline::default_replaced_intrinsic_size(
_name.local.as_ref(),
style.font_size.unwrap_or(16.0),
- node.get_attribute("controls").is_some(),
- _name.local.as_ref() != "embed"
- || node
- .get_attribute("src")
- .is_some_and(|value| !value.trim().is_empty()),
+ has_controls,
+ has_embed_source,
) {
let context = engine.register_replaced(width, height, style);
let leaf = taffy_tree
@@ -12973,7 +13066,7 @@ fn build(
// boxes, and layout-only builds where `try_build` always declines).
let is_closed_html_details = _name.ns.as_ref() == "http://www.w3.org/1999/xhtml"
&& _name.local.as_ref() == "details"
- && node.get_attribute("open").is_none();
+ && !is_open;
if !is_closed_html_details && !ifc_items.float_aware_blocks.contains(&id) {
if let Some(item) = engine.try_build(tree, id, styles) {
if style.display == crate::Display::Block && style.width == crate::Dimension::Auto {
@@ -13065,7 +13158,7 @@ fn build(
// the inter-element space belongs to the inline formatting context.
if !has_inline_ish_content {
dom_children.retain(|&cid| {
- tree.borrow_node(cid).map_or(false, |node| node.is_element())
+ tree.with_node(cid, |node| node.is_element()).unwrap_or(false)
|| !tree.text_content(cid).trim().is_empty()
});
}
@@ -15281,6 +15374,28 @@ mod tests {
);
}
+ #[test]
+ fn rendered_details_traversal_tracks_open_and_summary_order() {
+ let tree = parse_html("<details id=d>before<summary id=first>first</summary><p id=body>body</p><summary id=second>second</summary></details>");
+ let details = tree.get_element_by_id("d").unwrap();
+ let first = tree.get_element_by_id("first").unwrap();
+ let second = tree.get_element_by_id("second").unwrap();
+ let body = tree.get_element_by_id("body").unwrap();
+ assert_eq!(rendered_children(&tree, details), vec![first]);
+ assert!(!rendered_descendants(&tree, details).contains(&body));
+ tree.with_node_mut(details, |node| node.set_attribute("open", "".into()));
+ assert_eq!(rendered_children(&tree, details), tree.children(details));
+ assert!(rendered_descendants(&tree, details).contains(&body));
+ assert_eq!(rendered_parent(&tree, body), Some(details));
+ tree.with_node_mut(details, |node| node.remove_attribute_ns("", "open"));
+ tree.insert_before(first, second);
+ assert_eq!(rendered_children(&tree, details), vec![second]);
+ tree.remove(second);
+ assert_eq!(rendered_children(&tree, details), vec![first]);
+ tree.remove(first);
+ assert!(rendered_children(&tree, details).is_empty());
+ }
+
#[test]
fn native_shadow_tree_and_slotted_light_child_generate_layout_boxes() {
let tree = parse_html(
@@ -17659,6 +17774,98 @@ mod tests {
}
}
+ #[test]
+ fn retained_image_source_preflight_checks_linked_css_and_mixed_mutations() {
+ for css in ["", "img[src] { width: 70px }", "body:has(img[src]) { color: red }",
+ "aside::before { content: attr(data-state) }"]
+ {
+ let tree = parse_html("<link id=sheet rel=stylesheet href=/style.css><img id=image><aside id=peer></aside>");
+ let owner = tree.get_element_by_id("sheet").unwrap();
+ let image = tree.get_element_by_id("image").unwrap();
+ let peer = tree.get_element_by_id("peer").unwrap();
+ tree.replace_external_stylesheet(owner, css.into(), false);
+ let viewport = (500.0, 300.0);
+ let mut cache = crate::css::StylesheetCache::default();
+ let _ = layout_dom_with_web_fonts_and_stylesheet_cache(
+ &tree, viewport, &HashMap::new(), &[], &mut cache,
+ );
+ let changes = [
+ AttributeStyleMutation { node: image, name: "src".into(), old_value: None, new_value: Some("a.svg".into()) }.into(),
+ AttributeStyleMutation { node: peer, name: "data-state".into(), old_value: None, new_value: Some("ready".into()) }.into(),
+ ];
+ let misses = cache.miss_count();
+ assert_eq!(image_source_updates_without_style_damage(&tree, viewport, &mut cache, &changes),
+ css.is_empty().then_some(vec![image]), "{css}");
+ assert_eq!(cache.miss_count(), misses, "the preflight must use the full stylesheet key");
+ for name in ["style", "hidden", "width", "class"] {
+ let mut mixed = changes.to_vec();
+ mixed.push(AttributeStyleMutation { node: image, name: name.into(), old_value: None, new_value: Some("20".into()) }.into());
+ assert!(image_source_updates_without_style_damage(&tree, viewport, &mut cache, &mixed).is_none());
+ }
+ let mut resource = changes.to_vec();
+ resource.push(RetainedStyleMutation::Resource);
+ assert!(image_source_updates_without_style_damage(&tree, viewport, &mut cache, &resource).is_none());
+ }
+ }
+
+ #[test]
+ fn metadata_checks_share_cache_with_linked_stylesheets() {
+ let tree = parse_html("<style>#target { width: 80px }</style><link id=sheet rel=stylesheet href=/style.css><p id=target>text</p>");
+ let owner = tree.get_element_by_id("sheet").unwrap();
+ let target = tree.get_element_by_id("target").unwrap();
+ tree.replace_external_stylesheet(owner, "[data-state] { width: 160px }".into(), false);
+ let viewport = (500.0, 300.0);
+ let mut cache = crate::css::StylesheetCache::default();
+ let _ = layout_dom_with_web_fonts_and_stylesheet_cache(
+ &tree, viewport, &HashMap::new(), &[], &mut cache,
+ );
+ let misses = cache.miss_count();
+ for name in ["data-sfc-inited", "tabindex", "data-state"] {
+ let mutation = RetainedStyleMutation::Attribute(AttributeStyleMutation {
+ node: target, name: name.into(), old_value: None, new_value: Some("2".into()),
+ });
+ assert_eq!(can_retain_layout_for_metadata(&tree, viewport, &mut cache, &[mutation]),
+ name != "data-state", "linked CSS dependency: {name}");
+ assert_eq!(cache.miss_count(), misses, "metadata probe replaced the full stylesheet cache");
+ }
+ }
+
+ #[test]
+ fn retained_preflights_share_cssom_rules_with_full_layout() {
+ let tree = parse_html("<style id=sheet>#target { width: 80px }</style><p id=target>text</p><img id=image>");
+ let owner = tree.get_element_by_id("sheet").unwrap();
+ let target = tree.get_element_by_id("target").unwrap();
+ let image = tree.get_element_by_id("image").unwrap();
+ let viewport = (500.0, 300.0);
+ let mut cache = crate::css::StylesheetCache::default();
+ for (css, dependent) in [
+ ("p { width: 80px }", false),
+ ("[data-state] { width: 160px } img[src] { width: 70px }", true),
+ ("p { width: 90px }", false),
+ ] {
+ assert!(tree.update_cssom_stylesheet(owner, 0, 0, vec![css.into()], true));
+ let _ = layout_dom_with_web_fonts_and_stylesheet_cache(
+ &tree, viewport, &HashMap::new(), &[], &mut cache,
+ );
+ let misses = cache.miss_count();
+ let metadata = AttributeStyleMutation {
+ node: target, name: "data-state".into(), old_value: None,
+ new_value: Some("ready".into()),
+ };
+ assert_eq!(can_retain_layout_for_metadata(
+ &tree, viewport, &mut cache, &[metadata.into()],
+ ), !dependent, "CSSOM metadata dependency: {css}");
+ let source = AttributeStyleMutation {
+ node: image, name: "src".into(), old_value: None,
+ new_value: Some("new.png".into()),
+ };
+ assert_eq!(image_source_updates_without_style_damage(
+ &tree, viewport, &mut cache, &[source.into()],
+ ), (!dependent).then_some(vec![image]), "CSSOM image dependency: {css}");
+ assert_eq!(cache.miss_count(), misses, "preflight must retain the complete CSSOM cache key");
+ }
+ }
+
#[test]
fn retained_nested_universal_container_reset_is_bounded_and_matches_full() {
let mut queried = String::new();
@@ -17976,7 +18183,7 @@ mod tests {
target: "subject",
attribute: "data-state",
new_value: "on",
- expectation: ConservativeFallback,
+ expectation: Incremental,
},
RetainedDifferentialCase {
name: "relative selector ancestor traversal",
@@ -18048,6 +18255,22 @@ mod tests {
target: "image",
attribute: "src",
new_value: "replacement.png",
+ expectation: Incremental,
+ },
+ RetainedDifferentialCase {
+ name: "image source selector reaches sibling",
+ css: "#image[src='replacement.png']+aside{width:131px;height:37px}",
+ target: "image",
+ attribute: "src",
+ new_value: "replacement.png",
+ expectation: Incremental,
+ },
+ RetainedDifferentialCase {
+ name: "image source relational selector retains full fallback",
+ css: "body:has(img[src='replacement.png']){color:#123456}",
+ target: "image",
+ attribute: "src",
+ new_value: "replacement.png",
expectation: ConservativeFallback,
},
RetainedDifferentialCase {
@@ -18423,7 +18646,7 @@ mod tests {
#[test]
fn retained_relational_styles_match_forced_full_direction_matrix() {
- use RetainedDifferentialExpectation::{ConservativeFallback, Incremental};
+ use RetainedDifferentialExpectation::Incremental;
// Descendant/child traversal and selector-list pseudos all invalidate
// the keyed anchor without cascading an unrelated sibling branch.
@@ -18701,9 +18924,8 @@ mod tests {
Incremental,
);
- // A sibling-then-descendant path outside the anchor is deliberately
- // left on the correctness-first full path until dependency chains can
- // encode the continuation explicitly.
+ // Following-sibling subtree invalidation includes the descendant
+ // continuation outside a relational anchor.
let tree = parse_html(
r#"<style>.host:has(.signal)~.panel .leaf{width:151px}</style><main><section id=host class=host><i id=signal class=signal></i></section><div class=panel><b class=leaf></b></div></main>"#,
);
@@ -18720,7 +18942,7 @@ mod tests {
);
tree.append_child(host, signal);
finish_retained_tree_case(
- "has unrepresentable outer mixed traversal",
+ "has outer sibling descendant traversal",
&tree,
&mut cache,
initial,
@@ -18729,10 +18951,68 @@ mod tests {
old_parent: None,
new_parent: host,
},
- ConservativeFallback,
+ Incremental,
);
}
+ #[test]
+ fn retained_relational_sibling_descendants_keep_unrelated_branch_clean() {
+ for operation in ["insert", "remove", "reparent"] {
+ let clean = "<i class=clean></i>".repeat(1_000);
+ let tree = parse_html(&format!(
+ r#"<style>
+ .clean{{display:block;height:1px}}
+ .leaf{{display:block;width:30px;height:10px}}
+ #host:has(>.signal) ~ .panel > .leaf{{width:90px;color:#123456}}
+ #host:has(>.signal) ~ .panel > .leaf::before{{content:'active'}}
+ </style><aside>{clean}</aside><main><span id=host><b id=signal class=signal></b></span><span class=panel><b id=leaf class=leaf>Text</b></span><span id=destination></span></main>"#,
+ ));
+ let host = tree.get_element_by_id("host").unwrap();
+ let signal = tree.get_element_by_id("signal").unwrap();
+ let leaf = tree.get_element_by_id("leaf").unwrap();
+ let destination = tree.get_element_by_id("destination").unwrap();
+ if operation == "insert" {
+ tree.remove_child(signal);
+ }
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut initial = layout_dom_with_web_fonts_and_stylesheet_cache(
+ &tree, (360.0, 260.0), &HashMap::new(), &[], &mut cache,
+ );
+ assert_eq!(initial.rects[&leaf].width, if operation == "insert" { 30.0 } else { 90.0 });
+ let mutation = match operation {
+ "insert" => {
+ tree.append_child(host, signal);
+ TreeStyleMutation::Insert { node: signal, old_parent: None, new_parent: host }
+ }
+ "remove" => {
+ tree.remove_child(signal);
+ TreeStyleMutation::Remove { node: signal, old_parent: host }
+ }
+ _ => {
+ tree.append_child(destination, signal);
+ TreeStyleMutation::Insert { node: signal, old_parent: Some(host), new_parent: destination }
+ }
+ };
+ let retained = RetainedStyleMaps {
+ styles: std::mem::take(&mut initial.styles),
+ custom_properties: std::mem::take(&mut initial.custom_properties),
+ };
+ let (incremental, telemetry) = layout_dom_with_web_fonts_pass_limit(
+ &tree, (360.0, 260.0), &HashMap::new(), &[], None,
+ Some(&mut cache), Some(retained), &[mutation.into()],
+ );
+ let full = layout_dom(&tree, (360.0, 260.0));
+ assert_computed_styles_match(operation, &incremental, &full);
+ assert_eq!(incremental.rects, full.rects, "{operation}");
+ assert_eq!(incremental.text_runs, full.text_runs, "{operation}");
+ assert_eq!(incremental.inline_fragments, full.inline_fragments, "{operation}");
+ assert_eq!(incremental.custom_properties, full.custom_properties, "{operation}");
+ assert_eq!(incremental.rects[&leaf].width, if operation == "insert" { 90.0 } else { 30.0 });
+ assert_eq!(telemetry.retained_fallback, 0, "{operation}: {telemetry:?}");
+ assert!(telemetry.retained_reused >= 1_000, "{operation}: {telemetry:?}");
+ }
+ }
+
#[test]
fn retained_mixed_outer_has_dependencies_match_forced_full() {
use RetainedDifferentialExpectation::Incremental;
@@ -18842,6 +19122,67 @@ mod tests {
);
}
+ #[test]
+ fn retained_removed_wrapper_attributes_preserve_connected_selector_effects() {
+ for reinsert in [false, true] {
+ let tree = parse_html(
+ r#"<style>
+ #answer{color:#123456}#wrapper{color:#654321}
+ #after{width:30px;height:10px}
+ #answer:has([style]) + #after{width:90px}
+ .clean{height:12px}
+ </style><main><section id=answer><span id=wrapper style="opacity:1"><b id=child>Text</b></span></section><aside id=after></aside><footer class=clean>Clean</footer></main>"#,
+ );
+ let answer = tree.get_element_by_id("answer").unwrap();
+ let wrapper = tree.get_element_by_id("wrapper").unwrap();
+ let child = tree.get_element_by_id("child").unwrap();
+ let after = tree.get_element_by_id("after").unwrap();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut initial = layout_dom_with_web_fonts_and_stylesheet_cache(
+ &tree, (360.0, 260.0), &HashMap::new(), &[], &mut cache,
+ );
+ assert_eq!(initial.rects[&after].width, 90.0);
+ tree.with_node_mut(wrapper, |node| node.set_attribute("style", "opacity:0.5".into()));
+ tree.insert_before(wrapper, child);
+ tree.remove_child(wrapper);
+ let mut mutations = vec![
+ // The runtime does not retain serialized inline style values.
+ AttributeStyleMutation {
+ node: wrapper, name: "style".into(), old_value: None, new_value: None,
+ }.into(),
+ TreeStyleMutation::Insert {
+ node: child, old_parent: Some(wrapper), new_parent: answer,
+ }.into(),
+ TreeStyleMutation::Remove { node: wrapper, old_parent: answer }.into(),
+ ];
+ if reinsert {
+ tree.append_child(answer, wrapper);
+ mutations.push(TreeStyleMutation::Insert {
+ node: wrapper, old_parent: None, new_parent: answer,
+ }.into());
+ }
+ let retained = RetainedStyleMaps {
+ styles: std::mem::take(&mut initial.styles),
+ custom_properties: std::mem::take(&mut initial.custom_properties),
+ };
+ let (incremental, telemetry) = layout_dom_with_web_fonts_pass_limit(
+ &tree, (360.0, 260.0), &HashMap::new(), &[], None,
+ Some(&mut cache), Some(retained), &mutations,
+ );
+ let full = layout_dom(&tree, (360.0, 260.0));
+ assert_computed_styles_match("attribute then unwrap", &incremental, &full);
+ assert_eq!(incremental.rects, full.rects);
+ assert_eq!(incremental.text_runs, full.text_runs);
+ assert_eq!(incremental.custom_properties, full.custom_properties);
+ assert_eq!(incremental.rects[&after].width, if reinsert { 90.0 } else { 30.0 });
+ if !reinsert {
+ assert_eq!(telemetry.retained_fallback, 0, "{telemetry:?}");
+ assert!(telemetry.retained_reused > 0, "{telemetry:?}");
+ assert!(!incremental.styles.contains_key(&wrapper));
+ }
+ }
+ }
+
#[test]
fn retained_batched_insertions_restore_old_structural_boundaries() {
use RetainedDifferentialExpectation::Incremental;
diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rs
index b98054f7..d72bef51 100644
--- a/crates/obscura-render/src/lib.rs
+++ b/crates/obscura-render/src/lib.rs
@@ -2057,8 +2057,9 @@ pub struct WaapiAnimation {
/// Page-owned CSS animation instance history retained across layout rebuilds.
/// Node ids are document-scoped, so navigation must replace this value.
-#[derive(Debug, Default)]
+#[derive(Debug, Clone, Default)]
pub struct AnimationTimelineState {
+ display_suppressed: std::collections::HashSet<obscura_dom::tree::NodeId>,
instances: std::collections::HashMap<obscura_dom::tree::NodeId, AnimationInstance>,
start_candidates: std::collections::HashMap<obscura_dom::tree::NodeId, f32>,
subtree_start_candidates: std::collections::HashMap<obscura_dom::tree::NodeId, f32>,
@@ -2108,6 +2109,7 @@ impl AnimationTimelineState {
) {
for node in nodes {
self.instances.remove(node);
+ self.display_suppressed.remove(node);
self.start_candidates.remove(node);
self.subtree_start_candidates.remove(node);
self.waapi.retain(|_, animation| animation.node != *node);
@@ -2248,6 +2250,7 @@ impl AnimationTimelineState {
return sample.time;
}
let document_time_ms = sample.time.milliseconds;
+ let was_suppressed = self.display_suppressed.remove(&node);
let transition_time_ms = self.start_candidates.remove(&node);
let retained = self
.instances
@@ -2256,7 +2259,11 @@ impl AnimationTimelineState {
let instance = match retained {
Some(instance) => instance,
None => {
- let candidate = transition_time_ms.unwrap_or(0.0);
+ let candidate = transition_time_ms.unwrap_or(if was_suppressed {
+ document_time_ms
+ } else {
+ 0.0
+ });
let paused = play_state == AnimationPlayState::Paused;
self.instances.insert(
node,
@@ -2291,6 +2298,16 @@ impl AnimationTimelineState {
pub(crate) fn clear_animation(&mut self, node: obscura_dom::tree::NodeId, sample: AnimationSample) {
if sample.mode == AnimationSampleMode::DocumentTime {
self.instances.remove(&node);
+ self.display_suppressed.remove(&node);
+ }
+ }
+
+ /// CSS animations terminate below display:none. Remember the suppression
+ /// so revealing an ancestor starts a new instance at the next style flush.
+ pub(crate) fn suppress_css_animation(&mut self, node: obscura_dom::tree::NodeId, sample: AnimationSample) {
+ if sample.mode == AnimationSampleMode::DocumentTime {
+ self.instances.remove(&node);
+ self.display_suppressed.insert(node);
}
}
@@ -2298,6 +2315,7 @@ impl AnimationTimelineState {
&mut self,
mut keep: impl FnMut(obscura_dom::tree::NodeId) -> bool,
) {
+ self.display_suppressed.retain(|node| keep(*node));
self.instances.retain(|node, _| keep(*node));
self.start_candidates.retain(|node, _| keep(*node));
self.subtree_start_candidates.retain(|node, _| keep(*node));
@@ -2536,9 +2554,19 @@ pub(crate) fn to_taffy_style(style: &LayoutStyle) -> Style {
width: dimension(style.max_width),
height: dimension(style.max_height),
};
- if let Some(ar) = style.aspect_ratio {
- if ar.is_finite() && ar > 0.0 {
- s.aspect_ratio = Some(ar);
+ // Two definite replaced axes size independently of the preferred ratio.
+ // Keep the decoded ratio in LayoutStyle for object fitting, but do not let
+ // Taffy transfer min/max constraints to the other authored axis. Percentage
+ // and calc axes must retain their ratio until their basis is resolved.
+ let definite_replaced_axes = style.has_replaced_sizing
+ && matches!(style.width, Dimension::Px(_))
+ && matches!(style.height, Dimension::Px(_))
+ && style.size_expressions[..2].iter().all(Option::is_none);
+ if !definite_replaced_axes {
+ if let Some(ar) = style.aspect_ratio {
+ if ar.is_finite() && ar > 0.0 {
+ s.aspect_ratio = Some(ar);
+ }
}
}
if style.ignores_used_box_sizes() {
diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rs
index 3014aa98..4f1c2169 100644
--- a/crates/obscura-render/src/paint.rs
+++ b/crates/obscura-render/src/paint.rs
@@ -23,7 +23,7 @@ static FONT_OBLIQUE_BYTES: &[u8] = include_bytes!("../assets/liberation-sans-obl
static FONT_BOLD_OBLIQUE_BYTES: &[u8] = include_bytes!("../assets/liberation-sans-boldoblique.ttf");
use crate::dom::{
- RetainedStyleMaps, layout_dom_with_web_fonts_and_retained_styles_with_animation_state,
+ RetainedStyleMaps, layout_dom_with_query_seed,
layout_dom_with_web_fonts_and_stylesheet_cache_for_media_with_animation_state,
};
@@ -77,10 +77,27 @@ impl RenderResourceLoader for HttpResourceLoader {
}
enum CachedResource {
- Bytes(Arc<[u8]>),
+ Bytes {
+ bytes: Arc<[u8]>,
+ intrinsic: std::sync::OnceLock<Option<crate::ReplacedIntrinsic>>,
+ static_raster: std::sync::OnceLock<bool>,
+ },
Missing(std::time::Instant),
}
+impl CachedResource {
+ fn image_intrinsic(&self) -> Option<crate::ReplacedIntrinsic> {
+ match self {
+ Self::Bytes { bytes, intrinsic, .. } => {
+ // Metadata belongs to these immutable bytes. Replacement and
+ // FIFO eviction discard it with the existing bounded entry.
+ *intrinsic.get_or_init(|| image_intrinsic_metadata(bytes))
+ }
+ Self::Missing(_) => None,
+ }
+ }
+}
+
/// Fetch credentials/CORS identity for an HTML image request. No-CORS uses
/// the ordinary URL cache key so CSS images can share the same response;
/// CORS variants use private keys and can never contaminate one another.
@@ -130,6 +147,16 @@ struct RememberedContentImageIntrinsic {
intrinsic: crate::ReplacedIntrinsic,
}
+const RASTER_PAINT_CACHE_BYTES: usize = 8 * 1024 * 1024;
+const RASTER_PAINT_CACHE_ENTRIES: usize = 64;
+const RASTER_PAINT_CACHE_ENTRY_BYTES: usize = 2 * 1024 * 1024;
+
+struct CachedRasterPaint {
+ resource_key: String,
+ bytes: Arc<[u8]>,
+ raster: Arc<Pixmap>,
+}
+
/// Page-scoped raw resource bytes shared by layout preparation and repeated
/// paints. Entries are FIFO-bounded by both count and retained byte size.
/// Successful bytes use `Arc` so consumers never clone an image/font body.
@@ -137,6 +164,8 @@ pub struct RenderResourceCache {
entries: HashMap<String, CachedResource>,
order: VecDeque<String>,
retained_bytes: usize,
+ raster_paints: VecDeque<CachedRasterPaint>,
+ raster_paint_bytes: usize,
max_entries: usize,
max_bytes: usize,
content_image_intrinsics: HashMap<obscura_dom::tree::NodeId, RememberedContentImageIntrinsic>,
@@ -182,6 +211,8 @@ impl RenderResourceCache {
entries: HashMap::new(),
order: VecDeque::new(),
retained_bytes: 0,
+ raster_paints: VecDeque::new(),
+ raster_paint_bytes: 0,
max_entries,
max_bytes,
content_image_intrinsics: HashMap::new(),
@@ -255,7 +286,7 @@ impl RenderResourceCache {
pub fn has_live_outcome(&self, url: &str) -> bool {
match self.entries.get(&network_resource_url(url)) {
- Some(CachedResource::Bytes(_)) => true,
+ Some(CachedResource::Bytes { .. }) => true,
Some(CachedResource::Missing(at)) => at.elapsed() < MISSING_RESOURCE_RETRY_AFTER,
None => false,
}
@@ -267,7 +298,7 @@ impl RenderResourceCache {
pub fn has_cached_bytes(&self, url: &str) -> bool {
matches!(
self.entries.get(&network_resource_url(url)),
- Some(CachedResource::Bytes(_))
+ Some(CachedResource::Bytes { .. })
)
}
@@ -355,8 +386,8 @@ impl RenderResourceCache {
);
}
match self.entries.get(&network_resource_url(&resolved_url)) {
- Some(CachedResource::Bytes(bytes)) => Some(
- image_metadata_from_bytes(bytes)
+ Some(entry @ CachedResource::Bytes { .. }) => Some(
+ entry.image_intrinsic().and_then(crate::ReplacedIntrinsic::natural_size)
.map(|(width, height)| (resolved_url, width, height)),
),
Some(CachedResource::Missing(at)) if at.elapsed() < MISSING_RESOURCE_RETRY_AFTER => {
@@ -378,8 +409,8 @@ impl RenderResourceCache {
}
let key = image_resource_key(&resolved_url, profile);
match self.entries.get(&key) {
- Some(CachedResource::Bytes(bytes)) => Some(
- image_metadata_from_bytes(bytes)
+ Some(entry @ CachedResource::Bytes { .. }) => Some(
+ entry.image_intrinsic().and_then(crate::ReplacedIntrinsic::natural_size)
.map(|(width, height)| (resolved_url, width, height)),
),
Some(CachedResource::Missing(at)) if at.elapsed() < MISSING_RESOURCE_RETRY_AFTER => {
@@ -404,8 +435,8 @@ impl RenderResourceCache {
let (src, density) = resolve_img_url(tree, id, viewport)?;
let resolved_url = resolve_resource_url(&src, base_url).unwrap_or(src);
let profile = image_request_profile(tree, id);
- let dimensions = fetch_profiled_image_bytes(&resolved_url, None, self, profile)
- .and_then(|bytes| image_metadata_from_bytes(&bytes))
+ let dimensions = self.profiled_image_intrinsic(&resolved_url, profile)
+ .and_then(crate::ReplacedIntrinsic::natural_size)
.map(|(width, height)| (width / density, height / density));
Some((resolved_url, density, dimensions))
}
@@ -468,11 +499,35 @@ impl RenderResourceCache {
}
}
+ fn profiled_image_intrinsic(
+ &mut self,
+ resolved_url: &str,
+ profile: ImageRequestProfile,
+ ) -> Option<crate::ReplacedIntrinsic> {
+ if resolved_url.starts_with("data:") {
+ let bytes = fetch_bytes(resolved_url, None, self)?;
+ return image_intrinsic_metadata(&bytes);
+ }
+ // Preserve the loader's URL-resolution gate for unresolved paths and
+ // unsupported schemes; memoization must not create new requests.
+ let resolved_url = resolve_resource_url(resolved_url, None)?;
+ let key = image_resource_key(&resolved_url, profile);
+ if let Some(entry @ CachedResource::Bytes { .. }) = self.entries.get(&key) {
+ return entry.image_intrinsic();
+ }
+ let bytes = self.get_or_load_image(&resolved_url, profile)?;
+ match self.entries.get(&key) {
+ Some(entry @ CachedResource::Bytes { .. }) => entry.image_intrinsic(),
+ // Disabled/over-budget caches still inspect the fetched response.
+ _ => image_intrinsic_metadata(&bytes),
+ }
+ }
+
fn get_or_load(&mut self, url: &str, is_font: bool) -> Option<Arc<[u8]>> {
let url = network_resource_url(url);
if let Some(entry) = self.entries.get(&url) {
match entry {
- CachedResource::Bytes(bytes) => return Some(Arc::clone(bytes)),
+ CachedResource::Bytes { bytes, .. } => return Some(Arc::clone(bytes)),
CachedResource::Missing(at) if at.elapsed() < MISSING_RESOURCE_RETRY_AFTER => {
return None;
}
@@ -502,7 +557,7 @@ impl RenderResourceCache {
let key = image_resource_key(url, profile);
if let Some(entry) = self.entries.get(&key) {
match entry {
- CachedResource::Bytes(bytes) => return Some(Arc::clone(bytes)),
+ CachedResource::Bytes { bytes, .. } => return Some(Arc::clone(bytes)),
CachedResource::Missing(at) if at.elapsed() < MISSING_RESOURCE_RETRY_AFTER => {
return None;
}
@@ -546,7 +601,11 @@ impl RenderResourceCache {
}
self.retained_bytes = self.retained_bytes.saturating_add(bytes.len());
self.order.push_back(url.clone());
- self.entries.insert(url, CachedResource::Bytes(bytes));
+ self.entries.insert(url, CachedResource::Bytes {
+ bytes,
+ intrinsic: std::sync::OnceLock::new(),
+ static_raster: std::sync::OnceLock::new(),
+ });
}
fn insert_missing(&mut self, url: String) {
@@ -572,9 +631,66 @@ impl RenderResourceCache {
}
fn remove_entry(&mut self, url: &str) {
- if let Some(CachedResource::Bytes(bytes)) = self.entries.remove(url) {
+ if let Some(CachedResource::Bytes { bytes, .. }) = self.entries.remove(url) {
self.retained_bytes = self.retained_bytes.saturating_sub(bytes.len());
}
+ self.raster_paints.retain(|entry| {
+ if entry.resource_key == url {
+ self.raster_paint_bytes -= entry.raster.data().len();
+ false
+ } else {
+ true
+ }
+ });
+ }
+
+ fn raster_paint(
+ &mut self,
+ resource_key: &str,
+ bytes: Arc<[u8]>,
+ width: u32,
+ height: u32,
+ ) -> Option<Arc<Pixmap>> {
+ if let Some(index) = self.raster_paints.iter().position(|entry| {
+ entry.resource_key == resource_key && Arc::ptr_eq(&entry.bytes, &bytes)
+ && entry.raster.width() == width && entry.raster.height() == height
+ }) {
+ let entry = self.raster_paints.remove(index)?;
+ let raster = Arc::clone(&entry.raster);
+ self.raster_paints.push_back(entry);
+ return Some(raster);
+ }
+ let raster = Arc::new(raster_to_pixmap(&bytes, width, height)?);
+ let size = raster.data().len();
+ // Cache only bytes still owned by this page's normal resource cache.
+ // This excludes disabled/over-budget caches and ephemeral data URLs.
+ if size > RASTER_PAINT_CACHE_ENTRY_BYTES {
+ return Some(raster);
+ }
+ // Inspect animation eligibility only when painting, once per immutable
+ // resource. Different raster sizes and cache eviction reuse the result;
+ // resource replacement drops it along with the original bytes.
+ let cacheable = match self.entries.get(resource_key) {
+ Some(CachedResource::Bytes { bytes: current, static_raster, .. })
+ if Arc::ptr_eq(current, &bytes) => {
+ *static_raster.get_or_init(|| static_raster_cacheable(&bytes))
+ }
+ _ => false,
+ };
+ if !cacheable {
+ return Some(raster);
+ }
+ while self.raster_paints.len() >= RASTER_PAINT_CACHE_ENTRIES
+ || self.raster_paint_bytes.saturating_add(size) > RASTER_PAINT_CACHE_BYTES
+ {
+ let oldest = self.raster_paints.pop_front()?;
+ self.raster_paint_bytes -= oldest.raster.data().len();
+ }
+ self.raster_paint_bytes += size;
+ self.raster_paints.push_back(CachedRasterPaint {
+ resource_key: resource_key.to_owned(), bytes, raster: Arc::clone(&raster),
+ });
+ Some(raster)
}
/// Seed a prior stable `content:url(...)` selection into the ordinary
@@ -912,6 +1028,9 @@ pub struct PreparedRender {
selected_images: HashMap<obscura_dom::tree::NodeId, SelectedImage>,
svg_fonts: Arc<usvg::fontdb::Database>,
layout: crate::DomLayout,
+ // Owned by the same document preparation as the final layout; replaced on
+ // every rebuild and dropped with it on navigation or full invalidation.
+ query_seed: Option<RetainedStyleMaps>,
}
impl PreparedRender {
@@ -1967,64 +2086,77 @@ impl PreparedRender {
profile: ImageRequestProfile,
) -> bool {
self.selected_images.iter().any(|(id, selected)| {
- if selected.resolved_url != url || selected.profile != profile {
- return false;
- }
- if !tree.get_node(*id).is_some_and(|node| {
- node.as_element()
- .is_some_and(|name| name.local.as_ref() == "img")
- }) {
- return true;
- }
- let Some(style) = self.layout.styles.get(id) else {
- return true;
- };
- // CSS replaced content has its own selected intrinsic metadata;
- // do not mistake an <img> owner for an ordinary fixed source
- // image merely because both selections share the element id.
- if style.content_image.is_some() {
- return true;
- }
- let fixed_box = matches!(style.width, crate::Dimension::Px(_))
- && matches!(style.height, crate::Dimension::Px(_))
- && matches!(
- style.min_width,
- crate::Dimension::Auto | crate::Dimension::Px(_)
- )
- && matches!(
- style.min_height,
- crate::Dimension::Auto | crate::Dimension::Px(_)
- )
- && matches!(
- style.max_width,
- crate::Dimension::Auto | crate::Dimension::Px(_)
- )
- && matches!(
- style.max_height,
- crate::Dimension::Auto | crate::Dimension::Px(_)
- )
- && !style.width_fit_content
- && style.size_expressions.iter().all(Option::is_none);
- if !fixed_box {
+ selected.resolved_url == url && selected.profile == profile
+ && self.image_intrinsics_affect_geometry(tree, *id)
+ })
+ }
+
+ fn image_is_display_suppressed(&self, tree: &DomTree, id: obscura_dom::tree::NodeId) -> bool {
+ let mut ancestor = Some(id);
+ while let Some(node) = ancestor {
+ if self.layout.styles.get(&node).is_some_and(|style| style.display == crate::Display::None) {
return true;
}
+ ancestor = crate::dom::rendered_parent(tree, node);
+ }
+ false
+ }
- let mut parent = crate::dom::rendered_parent(tree, *id);
- while let Some(parent_id) = parent {
- let Some(parent_style) = self.layout.styles.get(&parent_id) else {
- parent = crate::dom::rendered_parent(tree, parent_id);
- continue;
- };
- if parent_style.display_contents {
- parent = crate::dom::rendered_parent(tree, parent_id);
- continue;
- }
- return parent_style.display == crate::Display::Grid
- || (parent_style.display == crate::Display::Flex
- && !parent_style.internal_flex_container);
+ fn image_intrinsics_affect_geometry(&self, tree: &DomTree, id: obscura_dom::tree::NodeId) -> bool {
+ if !tree.get_node(id).is_some_and(|node| {
+ node.as_element()
+ .is_some_and(|name| name.local.as_ref() == "img")
+ }) {
+ return true;
+ }
+ let Some(style) = self.layout.styles.get(&id) else {
+ return true;
+ };
+ // CSS replaced content has its own selected intrinsic metadata;
+ // do not mistake an <img> owner for an ordinary fixed source
+ // image merely because both selections share the element id.
+ if style.content_image.is_some() {
+ return true;
+ }
+ let fixed_box = matches!(style.width, crate::Dimension::Px(_))
+ && matches!(style.height, crate::Dimension::Px(_))
+ && matches!(
+ style.min_width,
+ crate::Dimension::Auto | crate::Dimension::Px(_)
+ )
+ && matches!(
+ style.min_height,
+ crate::Dimension::Auto | crate::Dimension::Px(_)
+ )
+ && matches!(
+ style.max_width,
+ crate::Dimension::Auto | crate::Dimension::Px(_)
+ )
+ && matches!(
+ style.max_height,
+ crate::Dimension::Auto | crate::Dimension::Px(_)
+ )
+ && !style.width_fit_content
+ && style.size_expressions.iter().all(Option::is_none);
+ if !fixed_box {
+ return true;
+ }
+
+ let mut parent = crate::dom::rendered_parent(tree, id);
+ while let Some(parent_id) = parent {
+ let Some(parent_style) = self.layout.styles.get(&parent_id) else {
+ parent = crate::dom::rendered_parent(tree, parent_id);
+ continue;
+ };
+ if parent_style.display_contents {
+ parent = crate::dom::rendered_parent(tree, parent_id);
+ continue;
}
- false
- })
+ return parent_style.display == crate::Display::Grid
+ || (parent_style.display == crate::Display::Flex
+ && !parent_style.internal_flex_container);
+ }
+ false
}
}
@@ -2531,6 +2663,7 @@ pub fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_for_media_with_animat
dynamic_fonts,
stylesheet_cache,
None,
+ None,
media_type,
animation_sample,
animation_timeline,
@@ -2673,19 +2806,104 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(
{
return Some(previous);
}
+ if previous.viewport == viewport
+ && previous.base_url.as_deref() == base_url
+ && !previous.has_dynamic_fonts
+ && dynamic_fonts.is_empty()
+ {
+ if let Some(images) = crate::dom::image_source_updates_without_style_damage(
+ tree, viewport, stylesheet_cache, mutations,
+ ) {
+ let updates = images.into_iter().map(|id| {
+ // A display-suppressed image has no box or intrinsic layout
+ // contribution. Refresh its resource metadata now; revealing
+ // the subtree still goes through normal style/layout damage.
+ let display_suppressed = previous.image_is_display_suppressed(tree, id);
+ if previous.layout.styles.get(&id)?.content_image.is_some() {
+ return None;
+ }
+ let old_intrinsic = previous.layout.styles.get(&id)?.replaced_intrinsic?;
+ let (url, density) = resolve_img_url(tree, id, viewport)?;
+ let resolved_url = resolve_resource_url(&url, base_url).unwrap_or(url);
+ let profile = image_request_profile(tree, id);
+ let mut intrinsic = resources.profiled_image_intrinsic(&resolved_url, profile)?;
+ intrinsic.width = intrinsic.width.map(|width| width / density);
+ intrinsic.height = intrinsic.height.map(|height| height / density);
+ // Identical density-adjusted metadata leaves every intrinsic
+ // contribution unchanged, including percentage, flex and grid
+ // sizing. The selected resource and its pixels still refresh.
+ // Changed metadata keeps the conservative geometry check.
+ if intrinsic != old_intrinsic
+ && previous.image_intrinsics_affect_geometry(tree, id)
+ && !display_suppressed
+ {
+ return None;
+ }
+ // The eligibility check above excludes changed intrinsic-dependent
+ // boxes: hidden images contribute no geometry, and two fixed
+ // image axes are sized independently of the natural ratio.
+ // Partial SVG metadata still needs the normal layout path to
+ // resolve ratio-only available widths.
+ let complete_intrinsics = [old_intrinsic, intrinsic].iter().all(|metadata| {
+ metadata.width.is_some_and(|width| width.is_finite() && width > 0.0)
+ && metadata.height.is_some_and(|height| height.is_finite() && height > 0.0)
+ });
+ if intrinsic.natural_size().is_none()
+ || (intrinsic.ratio != old_intrinsic.ratio && !complete_intrinsics)
+ {
+ return None;
+ }
+ Some((id, SelectedImage { resolved_url, density, profile }, intrinsic))
+ }).collect::<Option<Vec<_>>>();
+ if let Some(updates) = updates {
+ if !sample_changed || (forward_document_sample
+ && previous.advance_inactive_animation_sample_time(animation_sample.time))
+ {
+ for (id, selected, intrinsic) in updates {
+ let style = previous.layout.styles.get_mut(&id)?;
+ style.intrinsic_size = intrinsic.natural_size();
+ style.replaced_intrinsic = Some(intrinsic);
+ // Preserve an authored ratio; the decoded ratio still
+ // follows the selected source for replaced-object paint.
+ if style.aspect_ratio_is_intrinsic && !style.aspect_ratio_is_mapped {
+ style.aspect_ratio = intrinsic.ratio;
+ }
+ previous.selected_images.insert(id, selected);
+ }
+ return Some(previous);
+ }
+ }
+ }
+ }
+ // A query-disabled seed can contain a different animation owner than the
+ // converged layout. Always resample its named CSS animations, including
+ // provisionally hidden ones, against the current document timeline.
+ let query_seed = previous.query_seed.take();
+ let seed_animation_mutations = query_seed.as_ref().map(|seed| {
+ seed.styles.iter().filter_map(|(node, style)| {
+ style.animation_name.is_some().then_some(crate::dom::RetainedStyleMutation::Animation { node: *node })
+ }).chain(seed.styles.iter().filter_map(|(node, style)| {
+ // Cancellation removes the current timeline record. The cached
+ // sample still needs clearing even after its owner disappears.
+ style.waapi_sample_state.is_some().then_some(crate::dom::RetainedStyleMutation::WaapiAnimation { node: *node })
+ })).chain(animation_timeline.waapi_nodes().into_iter().map(|node| {
+ crate::dom::RetainedStyleMutation::WaapiAnimation { node }
+ })).collect::<Vec<_>>()
+ }).unwrap_or_default();
let sampled_animation_mutations = sample_changed
.then(|| {
retained_animation_restyle_mutations(tree, &previous.layout.styles, animation_timeline)
})
.unwrap_or_default();
let animation_mutations;
- let mutations = if sampled_animation_mutations.is_empty() {
+ let mutations = if sampled_animation_mutations.is_empty() && seed_animation_mutations.is_empty() {
mutations
} else {
animation_mutations = mutations
.iter()
.cloned()
.chain(sampled_animation_mutations)
+ .chain(seed_animation_mutations)
.collect::<Vec<_>>();
animation_mutations.as_slice()
};
@@ -2702,6 +2920,7 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(
dynamic_fonts,
stylesheet_cache,
Some((retained, mutations)),
+ query_seed,
crate::CssMediaType::Screen,
animation_sample,
animation_timeline,
@@ -2746,6 +2965,7 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(
dynamic_fonts: &[DynamicFontFace],
stylesheet_cache: &mut crate::css::StylesheetCache,
retained: Option<(RetainedStyleMaps, &[crate::dom::RetainedStyleMutation])>,
+ mut query_seed: Option<RetainedStyleMaps>,
media_type: crate::CssMediaType,
animation_sample: crate::AnimationSample,
animation_timeline: &mut crate::AnimationTimelineState,
@@ -2789,31 +3009,13 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(
} else {
svg_font_database()
};
- let mut laid = match retained {
- Some((retained, mutations)) => {
- layout_dom_with_web_fonts_and_retained_styles_with_animation_state(
- tree,
- viewport,
- &intrinsic,
- &fonts,
- stylesheet_cache,
- retained,
- mutations,
- animation_sample,
- animation_timeline,
- )
- }
- None => layout_dom_with_web_fonts_and_stylesheet_cache_for_media_with_animation_state(
- tree,
- viewport,
- &intrinsic,
- &fonts,
- stylesheet_cache,
- media_type,
- animation_sample,
- animation_timeline,
- ),
- };
+ let (retained, mutations) = retained.map_or((None, &[][..]), |(styles, mutations)| {
+ (Some(styles), mutations)
+ });
+ let mut laid = layout_dom_with_query_seed(
+ tree, viewport, &intrinsic, &fonts, stylesheet_cache, retained, mutations,
+ media_type, animation_sample, animation_timeline, &mut query_seed,
+ );
// `content:url(...)` is computed by the author cascade, whereas ordinary
// HTML image sources are available before layout. Pay for a second layout
// only on the uncommon pages that actually use a CSS image as replaced
@@ -2833,6 +3035,10 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(
{
resources.content_image_layout_retries += 1;
}
+ // The retry has different image intrinsics. Drop the initial-pass
+ // cache together with the provisional layout; the next prepare may
+ // populate it again from a complete cascade.
+ query_seed = None;
laid = layout_dom_with_web_fonts_and_stylesheet_cache_for_media_with_animation_state(
tree,
viewport,
@@ -2876,6 +3082,7 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(
selected_images,
svg_fonts,
layout: laid,
+ query_seed,
})
}
@@ -7331,14 +7538,10 @@ fn collect_web_fonts(
let mut rules = Vec::new();
for nid in crate::dom::rendered_descendants(tree, tree.document()) {
- let Some(node) = tree.get_node(nid) else {
- continue;
- };
- if node
- .as_element()
- .map(|element| element.local.as_ref() != "style")
- .unwrap_or(true)
- {
+ // Inspect tags without copying unrelated script/text payloads.
+ if !tree.with_node(nid, |node| {
+ node.as_element().is_some_and(|element| element.local.as_ref() == "style")
+ }).unwrap_or(false) {
continue;
}
let css = tree.text_content(nid);
@@ -7391,26 +7594,22 @@ fn collect_web_fonts(
// the matching @font-face descriptors needed for CSS family/weight lookup.
let mut preloads = Vec::new();
for nid in crate::dom::rendered_descendants(tree, tree.document()) {
- let Some(node) = tree.get_node(nid) else {
- continue;
- };
- if node
- .as_element()
- .map(|element| element.local.as_ref() != "link")
- .unwrap_or(true)
- {
- continue;
- }
- let rel = node.get_attribute("rel").unwrap_or("");
- let as_value = node.get_attribute("as").unwrap_or("");
- if rel
- .split_ascii_whitespace()
- .any(|token| token.eq_ignore_ascii_case("preload"))
- && as_value.eq_ignore_ascii_case("font")
- {
- if let Some(href) = node.get_attribute("href") {
- preloads.push(href.to_string());
+ let preload = tree.with_node(nid, |node| {
+ if node.as_element()?.local.as_ref() != "link" {
+ return None;
}
+ let rel = node.get_attribute("rel").unwrap_or("");
+ let as_value = node.get_attribute("as").unwrap_or("");
+ if rel.split_ascii_whitespace().any(|token| token.eq_ignore_ascii_case("preload"))
+ && as_value.eq_ignore_ascii_case("font")
+ {
+ node.get_attribute("href").map(str::to_owned)
+ } else {
+ None
+ }
+ }).flatten();
+ if let Some(href) = preload {
+ preloads.push(href);
}
}
for src in preloads.iter().take(16) {
@@ -7860,6 +8059,17 @@ fn bounded_raster_size(w: u32, h: u32) -> (u32, u32) {
(rw, rh)
}
+// Formats that cannot animate, plus PNG only after its decoder explicitly
+// excludes APNG. Unknown formats, GIF and WebP retain the existing path.
+fn static_raster_cacheable(bytes: &[u8]) -> bool {
+ match image::guess_format(bytes) {
+ Ok(image::ImageFormat::Jpeg | image::ImageFormat::Bmp | image::ImageFormat::Ico) => true,
+ Ok(image::ImageFormat::Png) => image::codecs::png::PngDecoder::new(std::io::Cursor::new(bytes))
+ .ok().and_then(|decoder| decoder.is_apng().ok()) == Some(false),
+ _ => false,
+ }
+}
+
/// Decode raster image bytes (GIF/JPEG/PNG/WebP) to a premultiplied-alpha pixmap
/// resized to `w`x`h`.
fn raster_to_pixmap(bytes: &[u8], w: u32, h: u32) -> Option<Pixmap> {
@@ -9452,33 +9662,32 @@ fn collect_image_intrinsics(
HashMap<obscura_dom::tree::NodeId, crate::ReplacedIntrinsic>,
HashMap<obscura_dom::tree::NodeId, SelectedImage>,
) {
+ enum Source {
+ Image,
+ VideoPoster(String),
+ }
let mut out = std::collections::HashMap::new();
let mut selected = HashMap::new();
for nid in crate::dom::rendered_descendants(tree, tree.document()) {
- let Some(node) = tree.get_node(nid) else {
- continue;
- };
- let Some(element) = node.as_element() else {
- continue;
- };
- let (url, density) = match element.local.as_ref() {
- "img" => {
+ let source = tree.with_node(nid, |node| {
+ match node.as_element()?.local.as_ref() {
+ "img" => Some(Source::Image),
+ "video" => node.get_attribute("poster").map(str::trim)
+ .filter(|poster| !poster.is_empty())
+ .map(|poster| Source::VideoPoster(poster.to_owned())),
+ _ => None,
+ }
+ }).flatten();
+ // Release the scoped borrow before responsive selection reads the tree.
+ let (url, density) = match source {
+ Some(Source::Image) => {
let Some(candidate) = resolve_img_url(tree, nid, viewport) else {
continue;
};
candidate
}
- "video" => {
- let Some(poster) = node.get_attribute("poster") else {
- continue;
- };
- let poster = poster.trim();
- if poster.is_empty() {
- continue;
- }
- (poster.to_string(), 1.0)
- }
- _ => continue,
+ Some(Source::VideoPoster(poster)) => (poster, 1.0),
+ None => continue,
};
let resolved_url = resolve_resource_url(&url, base_url).unwrap_or(url);
let profile = image_request_profile(tree, nid);
@@ -9490,10 +9699,7 @@ fn collect_image_intrinsics(
profile,
},
);
- let Some(bytes) = fetch_profiled_image_bytes(&resolved_url, None, cache, profile) else {
- continue;
- };
- if let Some(mut intrinsic) = image_intrinsic_metadata(&bytes) {
+ if let Some(mut intrinsic) = cache.profiled_image_intrinsic(&resolved_url, profile) {
// A 2x (or w-descriptor) candidate's raw pixels are density times
// its CSS size. A ratio is dimensionless and remains unchanged.
intrinsic.width = intrinsic.width.map(|width| width / density);
@@ -9521,13 +9727,9 @@ fn collect_content_image_intrinsics(
let mut changed = false;
let mut active = HashSet::new();
for (&nid, style) in styles {
- let Some(node) = tree.get_node(nid) else {
- continue;
- };
- if node
- .as_element()
- .map_or(true, |name| name.local.as_ref() != "img")
- {
+ if !tree.with_node(nid, |node| {
+ node.as_element().is_some_and(|name| name.local.as_ref() == "img")
+ }).unwrap_or(false) {
continue;
}
let Some(url) = style.content_image.as_deref() else {
@@ -9985,9 +10187,20 @@ fn paint_image(
if !rect_intersects_paint_surface(visible_rect, pixmap, 1.0) {
return false;
}
- let bytes = match profile {
- Some(profile) => fetch_profiled_image_bytes(src, base_url, cache, profile),
- None => fetch_bytes(src, base_url, cache),
+ // Resolve once for both the byte lookup and the raster-cache identity.
+ // Data URLs retain their existing uncached decoding path.
+ let resolved = if src.starts_with("data:") {
+ None
+ } else {
+ resolve_resource_url(src, base_url)
+ };
+ let bytes = if src.starts_with("data:") {
+ fetch_bytes(src, base_url, cache)
+ } else {
+ resolved.as_deref().and_then(|url| match profile {
+ Some(profile) => cache.get_or_load_image(url, profile),
+ None => cache.get_or_load(url, false),
+ })
};
let Some(bytes) = bytes else {
return false;
@@ -10020,9 +10233,18 @@ fn paint_image(
// result up on draw when the destination is larger.
let (rw, rh) = bounded_raster_size(dw, dh);
let content = if svg {
- render_svg(&bytes, rw, rh)
+ render_svg(&bytes, rw, rh).map(Arc::new)
+ } else if !src.starts_with("data:") {
+ let key = resolved.map(|url| match profile {
+ Some(profile) => image_resource_key(&url, profile),
+ None => network_resource_url(&url),
+ });
+ match key {
+ Some(key) => cache.raster_paint(&key, bytes, rw, rh),
+ None => raster_to_pixmap(&bytes, rw, rh).map(Arc::new),
+ }
} else {
- raster_to_pixmap(&bytes, rw, rh)
+ raster_to_pixmap(&bytes, rw, rh).map(Arc::new)
};
let Some(content) = content else { return false };
@@ -10090,7 +10312,7 @@ fn paint_image(
pixmap.draw_pixmap(
dest.x as i32,
dest.y as i32,
- content.as_ref(),
+ content.as_ref().as_ref(),
&tiny_skia::PixmapPaint::default(),
base,
clip.as_ref(),
@@ -10103,7 +10325,7 @@ fn paint_image(
let scaled = base
.pre_translate(dest.x as i32 as f32, dest.y as i32 as f32)
.pre_scale(dw as f32 / rw as f32, dh as f32 / rh as f32);
- pixmap.draw_pixmap(0, 0, content.as_ref(), &paint, scaled, clip.as_ref());
+ pixmap.draw_pixmap(0, 0, content.as_ref().as_ref(), &paint, scaled, clip.as_ref());
}
true
}
@@ -10633,11 +10855,11 @@ fn has_inline_svg_text(tree: &DomTree) -> bool {
crate::dom::rendered_descendants(tree, tree.document())
.into_iter()
.any(|nid| {
- tree.get_node(nid).is_some_and(|node| {
+ tree.with_node(nid, |node| {
node.as_element().is_some_and(|name| {
matches!(name.local.as_ref(), "text" | "tspan" | "textPath")
})
- })
+ }).unwrap_or(false)
})
}
@@ -11946,6 +12168,110 @@ mod tests {
);
}
+ #[test]
+ fn image_intrinsic_cache_tracks_replacements_failures_and_request_profiles() {
+ let url = "https://assets.test/swap.svg";
+ let profile = ImageRequestProfile::NoCorsInclude;
+ let svg = |width, height| format!(
+ "<svg xmlns='http://www.w3.org/2000/svg' width='{width}' height='{height}'/>"
+ ).into_bytes();
+ let mut cache = RenderResourceCache::with_loader(|_url: &str| {
+ panic!("seeded metadata must not issue a request")
+ });
+ cache.seed_image(url.into(), profile, svg(20, 10));
+ cache.seed_image(url.into(), ImageRequestProfile::CorsInclude, svg(80, 40));
+ for _ in 0..2 {
+ assert_eq!(cache.profiled_image_intrinsic(url, profile).unwrap().natural_size(), Some((20.0, 10.0)));
+ assert_eq!(cache.cached_image_metadata(url, None), Some(Some((url.into(), 20.0, 10.0))));
+ assert_eq!(cache.profiled_image_intrinsic(url, ImageRequestProfile::CorsInclude).unwrap().natural_size(), Some((80.0, 40.0)));
+ }
+ cache.seed_image(url.into(), profile, svg(40, 30));
+ assert_eq!(cache.profiled_image_intrinsic(url, profile).unwrap().natural_size(), Some((40.0, 30.0)));
+ cache.seed_image(url.into(), profile, b"not an image".to_vec());
+ assert_eq!(cache.profiled_image_intrinsic(url, profile), None);
+ assert_eq!(cache.cached_image_metadata(url, None), Some(None));
+ cache.seed_image(url.into(), profile, svg(12, 8));
+ assert_eq!(cache.profiled_image_intrinsic(url, profile).unwrap().natural_size(), Some((12.0, 8.0)));
+ cache.seed_image_missing(url.into(), profile);
+ assert_eq!(cache.profiled_image_intrinsic(url, profile), None);
+ assert_eq!(cache.cached_image_metadata(url, None), Some(None));
+ assert_eq!(cache.profiled_image_intrinsic(url, ImageRequestProfile::CorsInclude).unwrap().natural_size(), Some((80.0, 40.0)));
+ }
+
+ #[test]
+ fn image_intrinsic_cache_eviction_does_not_retain_previous_dimensions() {
+ let mut cache = RenderResourceCache::with_loader_and_limits(|_url: &str| {
+ panic!("all resources are seeded")
+ }, 1, 1024);
+ let first = "https://assets.test/first.svg";
+ let second = "https://assets.test/second.svg";
+ let profile = ImageRequestProfile::NoCorsInclude;
+ cache.seed_image(first.into(), profile, b"<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10'/>".to_vec());
+ assert_eq!(cache.profiled_image_intrinsic(first, profile).unwrap().natural_size(), Some((20.0, 10.0)));
+ cache.seed_image(second.into(), profile, b"<svg xmlns='http://www.w3.org/2000/svg' width='30' height='15'/>".to_vec());
+ assert_eq!(cache.cached_image_metadata(first, None), None);
+ assert_eq!(cache.retained_entry_count(), 1);
+ cache.seed_image(first.into(), profile, b"<svg xmlns='http://www.w3.org/2000/svg' width='60' height='40'/>".to_vec());
+ assert_eq!(cache.profiled_image_intrinsic(first, profile).unwrap().natural_size(), Some((60.0, 40.0)));
+ assert_eq!(cache.cached_image_metadata(second, None), None);
+ assert_eq!(cache.retained_entry_count(), 1);
+ }
+
+ #[test]
+ fn image_intrinsic_metadata_without_retention_uses_each_loader_result() {
+ for (max_entries, max_bytes) in [(0, 1024), (1, 1)] {
+ let mut loads = 0;
+ let mut cache = RenderResourceCache::with_loader_and_limits(move |_url: &str| {
+ loads += 1;
+ Some(format!("<svg xmlns='http://www.w3.org/2000/svg' width='{}' height='10'/>", loads * 20).into_bytes())
+ }, max_entries, max_bytes);
+ let url = "https://assets.test/uncached.svg";
+ for expected in [20.0, 40.0] {
+ assert_eq!(cache.profiled_image_intrinsic(url, ImageRequestProfile::NoCorsInclude).unwrap().natural_size(), Some((expected, 10.0)));
+ assert_eq!(cache.cached_image_metadata(url, None), None);
+ assert_eq!(cache.retained_entry_count(), 0);
+ }
+ }
+ }
+
+ #[test]
+ fn image_intrinsic_cache_preserves_partial_svg_metadata_and_data_sources() {
+ let mut cache = RenderResourceCache::with_loader(|_url: &str| {
+ panic!("metadata probes must not fetch")
+ });
+ let profile = ImageRequestProfile::NoCorsInclude;
+ let url = "https://assets.test/ratio.svg";
+ cache.seed_image(url.into(), profile, b"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'/>".to_vec());
+ let expected = crate::ReplacedIntrinsic { width: None, height: None, ratio: Some(1.0) };
+ for _ in 0..2 {
+ assert_eq!(cache.profiled_image_intrinsic(url, profile), Some(expected));
+ assert_eq!(cache.cached_image_metadata(url, None), Some(Some((url.into(), 150.0, 150.0))));
+ }
+ let data = "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='12'/%3E";
+ assert_eq!(cache.profiled_image_intrinsic(data, profile).unwrap().natural_size(), Some((24.0, 12.0)));
+ assert_eq!(cache.retained_entry_count(), 1);
+ cache.set_sync_loading_enabled(false);
+ assert_eq!(cache.profiled_image_intrinsic("https://assets.test/unknown.svg", profile), None);
+ assert_eq!(cache.cached_image_metadata("https://assets.test/unknown.svg", None), None);
+ let misses = cache.take_sync_misses();
+ assert_eq!(misses, vec![("https://assets.test/unknown.svg".into(), Some(profile), false)]);
+ }
+
+ #[test]
+ fn image_intrinsic_lookup_preserves_url_resolution() {
+ let mut cache = RenderResourceCache::with_loader(|_url: &str| {
+ panic!("metadata must preserve the existing URL-resolution gate")
+ });
+ let profile = ImageRequestProfile::NoCorsInclude;
+ for src in ["relative.svg", "file:///tmp/image.svg", "about:blank"] {
+ assert_eq!(cache.profiled_image_intrinsic(src, profile), None);
+ }
+ assert!(cache.take_sync_misses().is_empty());
+ cache.seed_image("https://assets.test/image.svg".into(), profile,
+ b"<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10'/>".to_vec());
+ assert_eq!(cache.profiled_image_intrinsic("//assets.test/image.svg", profile).unwrap().natural_size(), Some((20.0, 10.0)));
+ }
+
#[test]
fn svg_image_metadata_keeps_view_box_as_ratio_only() {
let ratio_only = svg_image_intrinsic_metadata(
@@ -12101,6 +12427,7 @@ mod tests {
#flex { display:flex }
#contents { display:contents }
#item { display:inline-flex; background-color:green; opacity:.4 }
+ #suppressed { display:none }
#float { float:left; display:inline; position:relative; z-index:3 }
#inherit { display:inherit }
#animated { animation:fade 1s infinite }
@@ -12109,6 +12436,7 @@ mod tests {
@container (min-width:1px) { #query { color:green } }
</style><body>
<div id=flex><div id=contents><span id=item>label</span></div></div>
+ <section id=suppressed><span id=suppressed-child>hidden ancestor</span></section>
<span id=float>floating</span><div id=inherit>inherited</div>
<input id=hidden type=" HIDDEN "><div id=animated>animated</div>
<div id=container><span id=query>query</span></div>
@@ -12123,7 +12451,7 @@ mod tests {
for active in ["yes", "no"] {
tree.with_node_mut(body, |node| node.set_attribute("data-active", active.into()));
let full = prepare_dom(&tree, viewport, None, &mut resources).unwrap();
- for name in ["flex", "contents", "item", "float"] {
+ for name in ["flex", "contents", "item", "float", "suppressed", "suppressed-child"] {
let id = tree.get_element_by_id(name).unwrap();
let fast = crate::dom::computed_style_without_layout(
&tree, id, viewport, crate::CssMediaType::Screen, &cache, "color",
@@ -12480,6 +12808,815 @@ mod tests {
);
}
+ #[test]
+ fn authored_image_axes_override_intrinsic_ratio_and_constraints() {
+ for display in ["block", "flex", "grid"] {
+ for (sizing, expected) in [
+ ("width:20px;height:10px", (20.0, 10.0)),
+ ("width:20%;height:10%", (20.0, 10.0)),
+ ("width:20px;height:10px;min-width:30px", (30.0, 10.0)),
+ ("width:20px;height:10px;min-height:20px", (20.0, 20.0)),
+ ("width:20px;height:10px;max-width:10px", (10.0, 10.0)),
+ ("width:20px;height:10px;max-height:5px", (20.0, 5.0)),
+ ("width:20px;height:10px;border:2px solid black;padding:3px", (30.0, 20.0)),
+ ("width:20px;height:10px;border:2px solid black;padding:3px;box-sizing:border-box", (20.0, 10.0)),
+ ("width:20px;height:auto", (20.0, 15.0)),
+ ("width:20px;height:auto;max-height:10px", (20.0, 10.0)),
+ ] {
+ let tree = parse_html(&format!(r#"<style>
+ html,body{{margin:0}}main{{display:{display};align-items:start;width:100px;height:100px}}
+ img{{display:block;flex:none;{sizing}}}
+ </style><main><img id=image src=https://assets.test/image.svg></main>"#));
+ let image = tree.get_element_by_id("image").unwrap();
+ let mut resources = RenderResourceCache::with_loader(|_: &str| {
+ Some(br#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"/>"#.to_vec())
+ });
+ let prepared = prepare_dom(&tree, (150.0, 150.0), None, &mut resources).unwrap();
+ let rect = prepared.layout.rects[&image];
+ assert_eq!((rect.width, rect.height), expected, "{display} {sizing}");
+ }
+ }
+ }
+
+ #[test]
+ fn retained_image_source_changes_preserve_equal_intrinsics_and_refresh_pixels() {
+ let make_resources = || {
+ let mut resources = RenderResourceCache::with_loader(|_url: &str| {
+ panic!("all image resources must be seeded")
+ });
+ for (url, profile, width, height, color) in [
+ ("https://assets.test/a.svg", ImageRequestProfile::NoCorsInclude, 20, 10, "red"),
+ ("https://assets.test/equal.svg", ImageRequestProfile::NoCorsInclude, 20, 10, "lime"),
+ ("https://assets.test/b.svg", ImageRequestProfile::NoCorsInclude, 40, 30, "lime"),
+ ("https://assets.test/c.svg", ImageRequestProfile::NoCorsInclude, 40, 20, "blue"),
+ ("https://assets.test/a.svg", ImageRequestProfile::CorsSameOrigin, 40, 30, "blue"),
+ ] {
+ resources.seed_image(url.into(), profile, format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"><rect width="100%" height="100%" fill="{color}"/></svg>"#,
+ ).into_bytes());
+ }
+ resources
+ };
+ for (name, initial, value, url, density, profile, dimensions) in [
+ ("src", "", Some("https://assets.test/equal.svg"), Some("https://assets.test/equal.svg"),
+ 1.0, ImageRequestProfile::NoCorsInclude, Some((20.0, 10.0))),
+ ("src", "", Some("https://assets.test/b.svg"), Some("https://assets.test/b.svg"),
+ 1.0, ImageRequestProfile::NoCorsInclude, Some((40.0, 30.0))),
+ ("src", "", Some("https://assets.test/c.svg"), Some("https://assets.test/c.svg"),
+ 1.0, ImageRequestProfile::NoCorsInclude, Some((40.0, 20.0))),
+ ("srcset", "", Some("https://assets.test/c.svg 2x"), Some("https://assets.test/c.svg"),
+ 2.0, ImageRequestProfile::NoCorsInclude, Some((20.0, 10.0))),
+ ("src", "", None, None, 1.0, ImageRequestProfile::NoCorsInclude, None),
+ ("srcset", "", Some("https://assets.test/b.svg 2x"), Some("https://assets.test/b.svg"),
+ 2.0, ImageRequestProfile::NoCorsInclude, Some((20.0, 15.0))),
+ ("srcset", "srcset='https://assets.test/b.svg 2x'", None, Some("https://assets.test/a.svg"),
+ 1.0, ImageRequestProfile::NoCorsInclude, Some((20.0, 10.0))),
+ ("sizes", "srcset='https://assets.test/a.svg 20w, https://assets.test/b.svg 40w' sizes='20px'",
+ Some("40px"), Some("https://assets.test/b.svg"), 1.0,
+ ImageRequestProfile::NoCorsInclude, Some((40.0, 30.0))),
+ ("crossorigin", "", Some("anonymous"), Some("https://assets.test/a.svg"),
+ 1.0, ImageRequestProfile::CorsSameOrigin, Some((40.0, 30.0))),
+ ("crossorigin", "crossorigin='anonymous'", None, Some("https://assets.test/a.svg"),
+ 1.0, ImageRequestProfile::NoCorsInclude, Some((20.0, 10.0))),
+ ] {
+ // Include flow, flex and grid parents: intrinsic contributions must
+ // be recomputed even when most computed styles can be reused.
+ for (display, sizing, selector_css) in [
+ ("block", "", ""),
+ ("flex", "", ""),
+ ("grid", "", ""),
+ ("inline-block", "", ""),
+ ("block", "width:50%;height:auto", ""),
+ ("block", "width:auto;height:50%", ""),
+ ("flex", "width:50%;height:100%;min-width:0", ""),
+ ("grid", "width:100%;height:100%", ""),
+ ("block", "width:20px;height:10px", ""),
+ ("flex", "width:20px;height:10px", ""),
+ ("grid", "width:20px;height:10px", ""),
+ ("block", "width:20px;height:10px;min-width:30px", ""),
+ ("block", "width:20px;height:10px;min-height:20px", ""),
+ ("block", "width:20px;height:10px;max-width:10px", ""),
+ ("block", "width:20px;height:10px;max-height:5px", ""),
+ ("block", "width:20px;height:10px;aspect-ratio:3", ""),
+ ("block", "width:20px;height:10px;padding:3px;border:2px solid black;object-fit:cover", ""),
+ ("block", "width:20px;height:10px", "img[src='https://assets.test/b.svg']+aside{width:19px}"),
+ ("none", "", ""),
+ ("none", "width:100%;height:100%", ""),
+ ("block", "display:none", ""),
+ ("none", "", "img[src='https://assets.test/c.svg']+aside{width:19px}"),
+ ] {
+ let tree = parse_html(&format!(
+ r#"<html><head><style>
+ html,body{{margin:0}}main{{display:{display};width:100px}}
+ img{{display:block;flex:none;{sizing}}}aside{{width:7px;height:9px;background:black}}
+ {selector_css}
+ </style></head><body><main>
+ <img id="image" src="https://assets.test/a.svg" {initial}><aside></aside>
+ </main><div style="height:12px;background:yellow"></div></body></html>"#,
+ ));
+ let image = tree.get_element_by_id("image").unwrap();
+ let viewport = (120.0, 100.0);
+ let mut resources = make_resources();
+ let mut cache = crate::css::StylesheetCache::default();
+ let previous = prepare_dom_with_dynamic_fonts_and_stylesheet_cache(
+ &tree, viewport, None, &mut resources, &[], &mut cache,
+ ).unwrap();
+ let old_value = tree.get_node(image).unwrap().get_attribute(name).map(str::to_owned);
+ tree.with_node_mut(image, |node| match value {
+ Some(value) => node.set_attribute(name, value.into()),
+ None => node.remove_attribute_ns("", name),
+ });
+ let mut retained = prepare_dom_with_retained_attribute_styles(
+ &tree, viewport, None, &mut resources, &[], &mut cache, previous,
+ &[crate::dom::AttributeStyleMutation {
+ node: image, name: name.into(), old_value,
+ new_value: value.map(str::to_owned),
+ }],
+ ).unwrap();
+ let mut oracle_resources = make_resources();
+ let mut oracle = prepare_dom(&tree, viewport, None, &mut oracle_resources).unwrap();
+ assert_eq!(retained.selected_images, oracle.selected_images, "{name} {display}");
+ assert_eq!(retained.selected_image(image).map(|s| (s.resolved_url.as_str(), s.density, s.profile)),
+ url.map(|url| (url, density, profile)), "{name} {display}");
+ if display == "block" {
+ if let Some(dimensions) = dimensions.filter(|_| sizing.is_empty()) {
+ let rect = retained.layout.rects[&image];
+ assert_eq!((rect.width, rect.height), dimensions, "{name}");
+ }
+ }
+ assert_eq!(retained.layout.rects, oracle.layout.rects, "{name} {display}");
+ assert_eq!(retained.content_size, oracle.content_size, "{name} {display}");
+ for (node, style) in &oracle.layout.styles {
+ assert_eq!(format!("{:?}", retained.layout.styles[node]), format!("{style:?}"),
+ "{name} {display} {node:?}");
+ }
+ let pixels = paint_prepared(&tree, &mut retained, &mut resources, (0.0, 0.0)).unwrap();
+ let expected = paint_prepared(&tree, &mut oracle, &mut oracle_resources, (0.0, 0.0)).unwrap();
+ assert_eq!(pixels.data(), expected.data(), "{name} {display}");
+ }
+ }
+ }
+
+ #[test]
+ fn retained_hidden_image_ratio_and_style_are_current_when_revealed() {
+ for own in [false, true] {
+ for display in ["block", "flex", "grid"] {
+ for height in [20, 30, 40] {
+ for (sizing, attributes) in [
+ ("", ""),
+ ("aspect-ratio:3", ""),
+ ("width:100%;height:100%", ""),
+ ("width:20px;height:10px", ""),
+ ("width:auto;height:auto", "width=80 height=40"),
+ ] {
+ let tree = parse_html(&format!(r#"<style>
+ html,body{{margin:0}}main{{display:{display};width:120px;height:70px}}
+ .off{{display:none}}img{{display:block;{sizing}}}aside{{width:7px;height:9px}}
+ </style><main id=parent class='{}'><img id=image class='{}'
+ src='https://assets.test/a.svg' {attributes}><aside></aside></main>"#,
+ if own { "" } else { "off" }, if own { "off" } else { "" }));
+ let image = tree.get_element_by_id("image").unwrap();
+ let hidden = if own { image } else { tree.get_element_by_id("parent").unwrap() };
+ let make_resources = || {
+ let mut resources = RenderResourceCache::with_loader(|_: &str| panic!("unseeded image"));
+ for (name, width, height, color) in [("a", 20, 10, "red"), ("b", 40, height, "blue")] {
+ resources.seed(format!("https://assets.test/{name}.svg"), format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"><rect width="100%" height="100%" fill="{color}"/></svg>"#,
+ ).into_bytes());
+ }
+ resources
+ };
+ let mut resources = make_resources();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut previous = prepare_dom_with_dynamic_fonts_and_stylesheet_cache(
+ &tree, (150.0, 100.0), None, &mut resources, &[], &mut cache,
+ ).unwrap();
+ for (node, name, before, after) in [
+ (image, "src", "https://assets.test/a.svg", "https://assets.test/b.svg"),
+ (hidden, "class", "off", ""),
+ ] {
+ tree.with_node_mut(node, |node| node.set_attribute(name, after.into()));
+ previous = prepare_dom_with_retained_attribute_styles(
+ &tree, (150.0, 100.0), None, &mut resources, &[], &mut cache, previous,
+ &[crate::dom::AttributeStyleMutation {
+ node, name: name.into(), old_value: Some(before.into()), new_value: Some(after.into()),
+ }],
+ ).unwrap();
+ let mut oracle_resources = make_resources();
+ let mut oracle = prepare_dom(&tree, (150.0, 100.0), None, &mut oracle_resources).unwrap();
+ assert_eq!(previous.selected_images, oracle.selected_images, "{own} {display} {height} {sizing} {attributes} {name}");
+ assert_eq!(previous.layout.rects, oracle.layout.rects, "{own} {display} {height} {sizing} {attributes} {name}");
+ for (node, style) in &oracle.layout.styles {
+ assert_eq!(format!("{:?}", previous.layout.styles[node]), format!("{style:?}"),
+ "{own} {display} {height} {sizing} {attributes} {name} {node:?}");
+ }
+ let actual = paint_prepared(&tree, &mut previous, &mut resources, (0.0, 0.0)).unwrap();
+ let expected = paint_prepared(&tree, &mut oracle, &mut oracle_resources, (0.0, 0.0)).unwrap();
+ assert_eq!(actual.data(), expected.data(), "{own} {display} {height} {sizing} {attributes} {name}");
+ }
+ assert_eq!(previous.layout.styles[&image].intrinsic_size, Some((40.0, height as f32)));
+ if sizing.is_empty() {
+ assert_eq!(previous.layout.rects[&image].width, 40.0);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn css_display_none_suppresses_and_restarts_own_and_descendant_animations() {
+ for (own, important) in [(false, false), (true, false), (false, true), (true, true)] {
+ let tree = parse_html(&format!(r#"<style>
+ @keyframes grow {{ from {{ width:20px }} to {{ width:100px }} }}
+ #target {{ width:20px;height:10px;animation:grow 1000ms linear infinite }}
+ .off {{ display:none{} }}
+ .on {{ display:block{} }}
+ </style><div id=ancestor class='{}'><div id=target class='{}'></div></div>"#,
+ if important { " !important" } else { "" },
+ if important { " !important" } else { "" },
+ if own { "" } else { "off" }, if own { "off" } else { "" },
+ ));
+ let target = tree.get_element_by_id("target").unwrap();
+ let owner = if own { target } else { tree.get_element_by_id("ancestor").unwrap() };
+ let mut resources = RenderResourceCache::default();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut timeline = crate::AnimationTimelineState::default();
+ for (sample, class, expected_width, active) in [
+ (250.0, None, 20.0, false),
+ (500.0, Some("on"), 20.0, true),
+ (750.0, None, 40.0, true),
+ (800.0, Some("off"), 20.0, false),
+ (900.0, Some("on"), 20.0, true),
+ (1150.0, None, 40.0, true),
+ ] {
+ if let Some(class) = class {
+ tree.with_node_mut(owner, |node| node.set_attribute("class", class.into()));
+ timeline.note_start_candidate(owner, sample);
+ }
+ let prepared = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, (200.0, 100.0), None, &mut resources, &[], &mut cache,
+ crate::AnimationSample::document(sample), &mut timeline,
+ ).unwrap();
+ let style = &prepared.layout.styles[&target];
+ assert_eq!(style.width, crate::Dimension::Px(expected_width),
+ "own={own} important={important} sample={sample}");
+ assert_eq!(style.animation_has_render_effect, active);
+ assert_eq!(prepared.has_active_declarative_css_animations(), active);
+ timeline.clear_start_candidates();
+ }
+ }
+ }
+
+ #[test]
+ fn css_animation_visibility_and_contents_are_not_display_none() {
+ for parent in ["visibility:hidden", "display:contents"] {
+ let tree = parse_html(&format!(r#"<style>
+ @keyframes grow {{ from {{ width:20px }} to {{ width:100px }} }}
+ #target {{ width:20px;height:10px;animation:grow 1000ms linear infinite }}
+ </style><div style='{parent}'><div id=target></div></div>"#));
+ let target = tree.get_element_by_id("target").unwrap();
+ let mut resources = RenderResourceCache::default();
+ let prepared = prepare_dom_at_animation_time(
+ &tree, (200.0, 100.0), None, &mut resources,
+ crate::AnimationSampleTime { milliseconds: 250.0 },
+ ).unwrap();
+ assert_eq!(prepared.layout.styles[&target].width, crate::Dimension::Px(40.0), "{parent}");
+ assert!(prepared.has_active_declarative_css_animations());
+ }
+ }
+
+ fn assert_query_seed_render_matches(
+ tree: &DomTree,
+ actual: &mut PreparedRender,
+ expected: &mut PreparedRender,
+ resources: &mut RenderResourceCache,
+ oracle_resources: &mut RenderResourceCache,
+ context: &str,
+ ) {
+ assert_eq!(actual.layout.rects, expected.layout.rects, "{context}");
+ assert_eq!(actual.layout.inline_fragments, expected.layout.inline_fragments, "{context}");
+ assert_eq!(actual.layout.transforms, expected.layout.transforms, "{context}");
+ assert_eq!(actual.layout.clip_rects, expected.layout.clip_rects, "{context}");
+ assert_eq!(actual.content_size, expected.content_size, "{context}");
+ for (node, style) in &actual.layout.styles {
+ let reference = &expected.layout.styles[node];
+ assert_eq!(style.color, reference.color, "{context} node={node:?}");
+ assert_eq!(style.opacity, reference.opacity, "{context} node={node:?}");
+ assert_eq!(style.font_size, reference.font_size, "{context} node={node:?}");
+ assert_eq!(style.width, reference.width, "{context} node={node:?}");
+ assert_eq!(style.display, reference.display, "{context} node={node:?}");
+ }
+ let pixels = paint_prepared(tree, actual, resources, (0.0, 0.0)).unwrap();
+ let reference = paint_prepared(tree, expected, oracle_resources, (0.0, 0.0)).unwrap();
+ assert_eq!(pixels.data(), reference.data(), "{context}");
+ }
+
+ // Compare retained preparations with fresh layout using independent resource
+ // caches and animation histories, including geometry and painted pixels.
+ struct QuerySeedCase {
+ resources: RenderResourceCache,
+ oracle_resources: RenderResourceCache,
+ cache: crate::css::StylesheetCache,
+ oracle_cache: crate::css::StylesheetCache,
+ timeline: crate::AnimationTimelineState,
+ oracle_timeline: crate::AnimationTimelineState,
+ previous: Option<PreparedRender>,
+ }
+
+ impl QuerySeedCase {
+ fn new(resources: RenderResourceCache, oracle_resources: RenderResourceCache) -> Self {
+ Self { resources, oracle_resources, cache: Default::default(),
+ oracle_cache: Default::default(), timeline: Default::default(),
+ oracle_timeline: Default::default(), previous: None }
+ }
+
+ fn flush(&mut self, tree: &DomTree, mutations: &[crate::dom::RetainedStyleMutation], sample: f32) {
+ let mut current = if let Some(previous) = self.previous.take() {
+ prepare_dom_with_retained_styles_with_animation_state(
+ tree, (360.0, 260.0), None, &mut self.resources, &[], &mut self.cache,
+ previous, mutations, crate::AnimationSample::document(sample), &mut self.timeline,
+ ).unwrap()
+ } else {
+ prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ tree, (360.0, 260.0), None, &mut self.resources, &[], &mut self.cache,
+ crate::AnimationSample::document(sample), &mut self.timeline,
+ ).unwrap()
+ };
+ let mut oracle = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ tree, (360.0, 260.0), None, &mut self.oracle_resources, &[], &mut self.oracle_cache,
+ crate::AnimationSample::document(sample), &mut self.oracle_timeline,
+ ).unwrap();
+ assert_eq!(current.selected_images, oracle.selected_images);
+ assert_query_seed_render_matches(tree, &mut current, &mut oracle,
+ &mut self.resources, &mut self.oracle_resources, &format!("sample={sample}"));
+ self.timeline.clear_start_candidates();
+ self.oracle_timeline.clear_start_candidates();
+ self.previous = Some(current);
+ }
+
+ fn set_attribute(&mut self, tree: &DomTree, node: obscura_dom::tree::NodeId, name: &str, value: &str, sample: f32) {
+ let old_value = tree.get_node(node).unwrap().get_attribute(name).map(str::to_owned);
+ tree.with_node_mut(node, |node| node.set_attribute(name, value.into()));
+ self.flush(tree, &[crate::dom::AttributeStyleMutation {
+ node, name: name.into(), old_value, new_value: Some(value.into()),
+ }.into()], sample);
+ }
+ }
+
+ #[test]
+ fn query_seed_bounds_large_documents_without_changing_layout() {
+ for count in [32, 8200] {
+ let tree = parse_html(&format!(r#"<style>
+ #container {{container-type:inline-size;width:200px}}
+ .item {{width:20px;height:0}}
+ @container (min-width:100px) {{.item {{width:100px}}}}
+ #marker {{height:12px;background:green}}
+ </style><div id=container>{}<div id=marker></div></div>"#,
+ "<div class=item></div>".repeat(count)));
+ let mut case = QuerySeedCase::new(Default::default(), Default::default());
+ case.flush(&tree, &[], 0.0);
+ assert_eq!(case.previous.as_ref().unwrap().query_seed.is_some(), count < 8192);
+ let marker = tree.get_element_by_id("marker").unwrap();
+ case.set_attribute(&tree, marker, "style", "height:20px;background:blue", 1.0);
+ assert_eq!(case.previous.as_ref().unwrap().query_seed.is_some(), count < 8192);
+ }
+ }
+
+ #[test]
+ fn query_seed_prunes_removed_subtrees_and_reparents_inherited_values() {
+ let tree = parse_html(r#"<style>
+ .container {container-type:inline-size}
+ #left {width:200px;--size:20px;color:red}
+ #right {width:70px;--size:40px;color:blue}
+ #item {width:var(--size);height:20px;background:currentColor}
+ @container (min-width:100px) {#item, #kept {width:100px}}
+ </style><div id=left class=container><div id=item><span id=leaf>text</span></div></div>
+ <div id=right class=container><div id=kept></div></div>"#);
+ let left = tree.get_element_by_id("left").unwrap();
+ let right = tree.get_element_by_id("right").unwrap();
+ let item = tree.get_element_by_id("item").unwrap();
+ let leaf = tree.get_element_by_id("leaf").unwrap();
+ let kept = tree.get_element_by_id("kept").unwrap();
+ let mut case = QuerySeedCase::new(Default::default(), Default::default());
+ case.flush(&tree, &[], 0.0);
+ assert!(case.previous.as_ref().unwrap().query_seed.is_some());
+ tree.append_child(right, item);
+ case.flush(&tree, &[crate::dom::TreeStyleMutation::Insert {
+ node:item, old_parent:Some(left), new_parent:right,
+ }.into()], 1.0);
+ assert_eq!(case.previous.as_ref().unwrap().layout.styles[&item].width, crate::Dimension::Px(40.0));
+ tree.remove_child(item);
+ case.flush(&tree, &[crate::dom::TreeStyleMutation::Remove {node:item, old_parent:right}.into()], 2.0);
+ let seed = case.previous.as_ref().unwrap().query_seed.as_ref().unwrap();
+ assert!(!seed.styles.contains_key(&item));
+ assert!(!seed.styles.contains_key(&leaf));
+ tree.append_child(left, item);
+ case.flush(&tree, &[crate::dom::TreeStyleMutation::Insert {
+ node:item, old_parent:None, new_parent:left,
+ }.into()], 3.0);
+ let current = case.previous.as_ref().unwrap();
+ assert_eq!(current.layout.styles[&item].width, crate::Dimension::Px(100.0));
+ assert_eq!(current.query_seed.as_ref().unwrap().styles[&item].width, crate::Dimension::Px(20.0));
+
+ // With the last matching subject removed, upstream skips the query
+ // passes entirely. No retained seed is needed on that path.
+ tree.remove_child(kept);
+ tree.remove_child(item);
+ case.flush(&tree, &[
+ crate::dom::TreeStyleMutation::Remove {node:kept, old_parent:right}.into(),
+ crate::dom::TreeStyleMutation::Remove {node:item, old_parent:left}.into(),
+ ], 4.0);
+ assert!(case.previous.as_ref().unwrap().query_seed.is_none());
+ tree.append_child(right, item);
+ case.flush(&tree, &[crate::dom::TreeStyleMutation::Insert {
+ node:item, old_parent:None, new_parent:right,
+ }.into()], 5.0);
+ let current = case.previous.as_ref().unwrap();
+ assert_eq!(current.layout.styles[&item].width, crate::Dimension::Px(40.0));
+ assert_eq!(current.query_seed.as_ref().unwrap().styles[&item].width, crate::Dimension::Px(40.0));
+ }
+
+ #[test]
+ fn query_seed_refreshes_images_and_discards_seed_after_content_retry() {
+ let make_resources = || RenderResourceCache::with_loader(|url: &str| {
+ let (width, height, color) = match url {
+ "https://assets.test/a.svg" => (20, 10, "red"),
+ "https://assets.test/b.svg" => (40, 30, "blue"),
+ _ => panic!("unexpected resource: {url}"),
+ };
+ Some(format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"><rect width="100%" height="100%" fill="{color}"/></svg>"#).into_bytes())
+ });
+ let tree = parse_html(r#"<style>
+ #container {container-type:inline-size;width:200px}
+ img {display:block} #fixed {width:20px;height:10px}
+ @container (min-width:100px) {#marker {height:10px;background:green}}
+ </style><div id=container><img id=natural src='https://assets.test/a.svg'>
+ <img id=fixed src='https://assets.test/a.svg'><img id=content src='https://assets.test/a.svg'>
+ <div id=marker></div></div>"#);
+ let natural = tree.get_element_by_id("natural").unwrap();
+ let fixed = tree.get_element_by_id("fixed").unwrap();
+ let content = tree.get_element_by_id("content").unwrap();
+ let marker = tree.get_element_by_id("marker").unwrap();
+ let mut case = QuerySeedCase::new(make_resources(), make_resources());
+ case.flush(&tree, &[], 0.0);
+ assert!(case.previous.as_ref().unwrap().query_seed.is_some());
+ case.set_attribute(&tree, natural, "src", "https://assets.test/b.svg", 1.0);
+ let rect = case.previous.as_ref().unwrap().layout.rects[&natural];
+ assert_eq!((rect.width, rect.height), (40.0, 30.0));
+ case.set_attribute(&tree, fixed, "src", "https://assets.test/b.svg", 2.0);
+ let rect = case.previous.as_ref().unwrap().layout.rects[&fixed];
+ assert_eq!((rect.width, rect.height), (20.0, 10.0));
+ for (sample, value, size) in [
+ (3.0, "content:url('https://assets.test/b.svg')", (40.0, 30.0)),
+ (5.0, "content:url('https://assets.test/a.svg')", (20.0, 10.0)),
+ (7.0, "", (20.0, 10.0)),
+ ] {
+ let retries = case.resources.content_image_layout_retries;
+ case.set_attribute(&tree, content, "style", value, sample);
+ let current = case.previous.as_ref().unwrap();
+ let rect = current.layout.rects[&content];
+ assert_eq!((rect.width, rect.height), size);
+ assert!(case.resources.content_image_layout_retries > retries);
+ assert!(current.query_seed.is_none());
+ case.set_attribute(&tree, marker, "style", &format!("height:{}px", sample + 10.0), sample + 1.0);
+ assert!(case.previous.as_ref().unwrap().query_seed.is_some());
+ }
+ }
+
+ #[test]
+ fn query_seed_clears_cancelled_waapi_samples_after_unrelated_damage() {
+ let tree = parse_html(r#"<style>
+ #container {container-type:inline-size;width:200px}
+ #target {opacity:1;width:20px;height:20px;background:green}
+ @container (min-width:100px) {#target {width:100px}}
+ </style><div id=container><div id=target></div><div id=damage></div></div>"#);
+ let target = tree.get_element_by_id("target").unwrap();
+ let damage = tree.get_element_by_id("damage").unwrap();
+ let mut case = QuerySeedCase::new(Default::default(), Default::default());
+ for timeline in [&mut case.timeline, &mut case.oracle_timeline] {
+ timeline.register_waapi(crate::WaapiAnimation {
+ id:1, node:target,
+ keyframes:vec![
+ crate::WaapiKeyframe {offset:0.0, opacity:Some(0.25), transform:None},
+ crate::WaapiKeyframe {offset:1.0, opacity:Some(0.75), transform:None},
+ ],
+ timing:crate::AnimationTiming {duration_ms:1000.0, ..Default::default()},
+ easing:None, linear_easing:None, start_time_ms:0.0, hold_time_ms:None,
+ play_state:crate::WaapiPlayState::Running,
+ });
+ }
+ case.flush(&tree, &[], 500.0);
+ let current = case.previous.as_ref().unwrap();
+ assert_eq!(current.layout.styles[&target].opacity, Some(0.5));
+ assert!(current.query_seed.as_ref().unwrap().styles[&target].waapi_sample_state.is_some());
+ case.timeline.cancel_waapi(1);
+ case.oracle_timeline.cancel_waapi(1);
+ case.set_attribute(&tree, damage, "style", "height:10px", 600.0);
+ let current = case.previous.as_ref().unwrap();
+ assert_eq!(current.layout.styles[&target].opacity, Some(1.0));
+ assert!(current.query_seed.as_ref().unwrap().styles[&target].waapi_sample_state.is_none());
+ }
+
+ #[test]
+ fn query_seed_falls_back_for_changing_shadow_stylesheets() {
+ let tree = parse_html(r#"<style>
+ #container {container-type:inline-size;width:200px}
+ @container (min-width:100px) {#marker {height:10px;background:green}}
+ </style><div id=container><div id=marker></div><x-card id=host></x-card></div>
+ <div id=source><style id=shadow-sheet>span {display:block;width:20px;height:10px;background:red}</style>
+ <span id=shadow-item></span></div>"#);
+ let host = tree.get_element_by_id("host").unwrap();
+ let source = tree.get_element_by_id("source").unwrap();
+ let sheet = tree.get_element_by_id("shadow-sheet").unwrap();
+ let item = tree.get_element_by_id("shadow-item").unwrap();
+ let text = tree.children(sheet)[0];
+ let root = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();
+ for child in tree.children(source) { tree.append_child(root, child); }
+ tree.remove(source);
+ let mut case = QuerySeedCase::new(Default::default(), Default::default());
+ case.flush(&tree, &[], 0.0);
+ assert!(case.previous.as_ref().unwrap().query_seed.is_none());
+ assert_eq!(case.previous.as_ref().unwrap().layout.rects[&item].width, 20.0);
+ tree.with_node_mut(text, |node| {
+ if let obscura_dom::tree::NodeData::Text {contents} = &mut node.data {
+ *contents = "span {display:block;width:47px;height:20px;background:blue}".into();
+ }
+ });
+ case.flush(&tree, &[crate::dom::TreeStyleMutation::Text {node:text, parent:Some(sheet)}.into()], 1.0);
+ assert!(case.previous.as_ref().unwrap().query_seed.is_none());
+ assert_eq!(case.previous.as_ref().unwrap().layout.rects[&item].width, 47.0);
+ }
+
+
+ #[test]
+ fn query_seed_preserves_conditional_inheritance_and_geometry_after_mutation() {
+ let tree = parse_html(r#"<!doctype html><style>
+ #container { container-type:inline-size;width:250px;--size:20px }
+ #container.narrow { width:80px;--size:30px }
+ .item { width:var(--size);height:15px;background:green }
+ .item.changed { height:35px }
+ .nested { container-type:inline-size;width:70%; }
+ @container (min-width:100px) {
+ .item { width:100px;color:red;font-size:20px }
+ .nested { width:60%;--size:40px }
+ }
+ @container (max-width:100px) { .leaf { padding:3px;color:blue } }
+ </style><div id=container><div id=item class=item><span>text</span></div>
+ <section class=nested><div class='item leaf'>nested</div></section></div>"#);
+ let container = tree.get_element_by_id("container").unwrap();
+ let item = tree.get_element_by_id("item").unwrap();
+ let mut resources = RenderResourceCache::default();
+ let mut oracle_resources = RenderResourceCache::default();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut oracle_cache = crate::css::StylesheetCache::default();
+ let mut timeline = crate::AnimationTimelineState::default();
+ let mut oracle_timeline = crate::AnimationTimelineState::default();
+ let mut current = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, (360.0, 260.0), None, &mut resources, &[], &mut cache,
+ crate::AnimationSample::document(0.0), &mut timeline,
+ ).unwrap();
+ assert_eq!(current.layout.styles[&item].width, crate::Dimension::Px(100.0));
+ assert_eq!(current.query_seed.as_ref().unwrap().styles[&item].width, crate::Dimension::Px(20.0));
+ for (index, (node, name, value, viewport)) in [
+ (item, "class", "item changed", (360.0, 260.0)),
+ (container, "class", "narrow", (360.0, 260.0)),
+ (container, "style", "--size:45px", (360.0, 260.0)),
+ (container, "class", "", (360.0, 260.0)),
+ (item, "style", "font-size:50%;width:50%", (360.0, 260.0)),
+ (container, "style", "width:60%;--size:25px", (180.0, 260.0)),
+ (item, "class", "item", (360.0, 260.0)),
+ ].into_iter().enumerate() {
+ let old_value = tree.get_node(node).unwrap().get_attribute(name).map(str::to_owned);
+ tree.with_node_mut(node, |node| node.set_attribute(name, value.into()));
+ current = prepare_dom_with_retained_styles_with_animation_state(
+ &tree, viewport, None, &mut resources, &[], &mut cache, current,
+ &[crate::dom::AttributeStyleMutation { node, name:name.into(), old_value,
+ new_value:Some(value.into()) }.into()],
+ crate::AnimationSample::document(index as f32 + 1.0), &mut timeline,
+ ).unwrap();
+ let mut oracle = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, viewport, None, &mut oracle_resources, &[], &mut oracle_cache,
+ crate::AnimationSample::document(index as f32 + 1.0), &mut oracle_timeline,
+ ).unwrap();
+ assert!(current.query_seed.is_some());
+ assert_query_seed_render_matches(&tree, &mut current, &mut oracle,
+ &mut resources, &mut oracle_resources, &format!("mutation {index}"));
+ }
+ }
+
+ #[test]
+ fn query_seed_resamples_provisional_animation_owners_and_rewinds() {
+ for seed_hidden in [false, true] {
+ let tree = parse_html(&format!(r#"<!doctype html><style>
+ @keyframes grow {{ from {{width:20px}} to {{width:100px}} }}
+ #container {{container-type:inline-size;width:200px}}
+ #target {{display:{};height:10px;animation:grow 1000ms linear infinite}}
+ @container (min-width:100px) {{#target {{display:{}}}}}
+ </style><div id=container><div id=target></div><i id=damage></i></div>"#,
+ if seed_hidden { "none" } else { "block" },
+ if seed_hidden { "block" } else { "none" }));
+ let target = tree.get_element_by_id("target").unwrap();
+ let damage = tree.get_element_by_id("damage").unwrap();
+ let mut resources = RenderResourceCache::default();
+ let mut oracle_resources = RenderResourceCache::default();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut oracle_cache = crate::css::StylesheetCache::default();
+ let mut timeline = crate::AnimationTimelineState::default();
+ let mut oracle_timeline = crate::AnimationTimelineState::default();
+ timeline.note_start_candidate(target, 0.0);
+ oracle_timeline.note_start_candidate(target, 0.0);
+ let mut previous = None;
+ for sample in [0.0, 250.0, 500.0, 500.0, 100.0, 750.0] {
+ let old_value = tree.get_node(damage).unwrap().get_attribute("style").map(str::to_owned);
+ let value = format!("height:{}px", sample / 50.0 + 1.0);
+ tree.with_node_mut(damage, |node| node.set_attribute("style", value.clone()));
+ let mut current = if let Some(previous) = previous {
+ prepare_dom_with_retained_styles_with_animation_state(
+ &tree, (300.0, 180.0), None, &mut resources, &[], &mut cache, previous,
+ &[crate::dom::AttributeStyleMutation {node:damage, name:"style".into(),
+ old_value, new_value:Some(value)}.into()],
+ crate::AnimationSample::document(sample), &mut timeline,
+ ).unwrap()
+ } else {
+ prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, (300.0, 180.0), None, &mut resources, &[], &mut cache,
+ crate::AnimationSample::document(sample), &mut timeline,
+ ).unwrap()
+ };
+ let mut oracle = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, (300.0, 180.0), None, &mut oracle_resources, &[], &mut oracle_cache,
+ crate::AnimationSample::document(sample), &mut oracle_timeline,
+ ).unwrap();
+ assert_query_seed_render_matches(&tree, &mut current, &mut oracle,
+ &mut resources, &mut oracle_resources, &format!("hidden={seed_hidden} sample={sample}"));
+ timeline.clear_start_candidates();
+ oracle_timeline.clear_start_candidates();
+ previous = Some(current);
+ }
+ }
+ }
+
+ #[test]
+ fn query_seed_is_discarded_when_stylesheet_key_changes() {
+ let tree = parse_html(r#"<!doctype html><style id=sheet>
+ #container {container-type:inline-size;width:200px}
+ #item {height:10px;width:20px}
+ @container (min-width:100px) {#item {width:100px}}
+ </style><div id=container><div id=item></div></div>"#);
+ let sheet = tree.get_element_by_id("sheet").unwrap();
+ let item = tree.get_element_by_id("item").unwrap();
+ let text = tree.children(sheet)[0];
+ let mut resources = RenderResourceCache::default();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut timeline = crate::AnimationTimelineState::default();
+ let previous = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, (300.0, 100.0), None, &mut resources, &[], &mut cache,
+ crate::AnimationSample::document(0.0), &mut timeline,
+ ).unwrap();
+ assert!(previous.query_seed.is_some());
+ tree.with_node_mut(text, |node| {
+ if let obscura_dom::tree::NodeData::Text { contents } = &mut node.data {
+ *contents = "#item {width:47px;height:10px}".into();
+ }
+ });
+ let current = prepare_dom_with_retained_styles_with_animation_state(
+ &tree, (300.0, 100.0), None, &mut resources, &[], &mut cache, previous,
+ &[crate::dom::TreeStyleMutation::Text {node:text,parent:Some(sheet)}.into()],
+ crate::AnimationSample::document(0.0), &mut timeline,
+ ).unwrap();
+ assert!(current.query_seed.is_none());
+ assert_eq!(current.layout.styles[&item].width, crate::Dimension::Px(47.0));
+ }
+
+ #[test]
+ fn container_query_seed_visibility_does_not_restart_final_css_animation() {
+ let tree = parse_html(r#"<style>
+ @keyframes grow { from { width:20px } to { width:100px } }
+ #container { container-type:inline-size;width:200px }
+ #target { display:none;width:20px;height:10px;animation:grow 1000ms linear infinite }
+ @container (min-width:100px) { #target { display:block } }
+ </style><div id=container><div id=target></div></div>"#);
+ let target = tree.get_element_by_id("target").unwrap();
+ let mut resources = RenderResourceCache::default();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut timeline = crate::AnimationTimelineState::default();
+ timeline.note_start_candidate(target, 0.0);
+ for (sample, expected) in [(0.0, 20.0), (250.0, 40.0), (500.0, 60.0)] {
+ let prepared = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, (300.0, 150.0), None, &mut resources, &[], &mut cache,
+ crate::AnimationSample::document(sample), &mut timeline,
+ ).unwrap();
+ assert_eq!(prepared.layout.styles[&target].display, crate::Display::Block);
+ assert_eq!(prepared.layout.styles[&target].width, crate::Dimension::Px(expected));
+ assert!(prepared.has_active_declarative_css_animations());
+ timeline.clear_start_candidates();
+ }
+ }
+
+ #[test]
+ fn css_animation_display_eligibility_uses_winning_important_declaration() {
+ for (inline, expected, active) in [("display:none", 40.0, true), ("display:none!important", 20.0, false)] {
+ let tree = parse_html(&format!(r#"<style>
+ @keyframes grow {{ from {{ width:20px }} to {{ width:100px }} }}
+ #target {{ display:block!important;width:20px;height:10px;animation:grow 1s linear infinite }}
+ </style><div id=target style='{inline}'></div>"#));
+ let target = tree.get_element_by_id("target").unwrap();
+ let mut resources = RenderResourceCache::default();
+ let prepared = prepare_dom_at_animation_time(
+ &tree, (200.0, 100.0), None, &mut resources,
+ crate::AnimationSampleTime { milliseconds: 250.0 },
+ ).unwrap();
+ assert_eq!(prepared.layout.styles[&target].width, crate::Dimension::Px(expected));
+ assert_eq!(prepared.has_active_declarative_css_animations(), active);
+ }
+ }
+
+ #[test]
+ fn css_display_none_suppresses_shadow_and_slotted_animations() {
+ for hide_host in [false, true] {
+ let tree = parse_html(&format!(r#"<style>
+ @keyframes grow {{ from {{ width:20px }} to {{ width:100px }} }}
+ #light {{ width:20px;height:10px;animation:grow 1s linear infinite }}
+ </style><x-card id=host style='display:{}'><span id=light></span></x-card>
+ <div id=source><style>
+ @keyframes grow {{ from {{ width:20px }} to {{ width:100px }} }}
+ #shadow {{ width:20px;height:10px;animation:grow 1s linear infinite }}
+ </style><div style='display:{}'><div id=shadow></div><slot></slot></div></div>"#,
+ if hide_host { "none" } else { "block" },
+ if hide_host { "block" } else { "none" },
+ ));
+ let host = tree.get_element_by_id("host").unwrap();
+ let source = tree.get_element_by_id("source").unwrap();
+ let targets = [tree.get_element_by_id("light").unwrap(), tree.get_element_by_id("shadow").unwrap()];
+ let root = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();
+ for child in tree.children(source) { tree.append_child(root, child); }
+ tree.remove(source);
+ let mut resources = RenderResourceCache::default();
+ let prepared = prepare_dom_at_animation_time(
+ &tree, (200.0, 100.0), None, &mut resources,
+ crate::AnimationSampleTime { milliseconds: 250.0 },
+ ).unwrap();
+ for target in targets {
+ assert_eq!(prepared.layout.styles[&target].width, crate::Dimension::Px(20.0));
+ assert!(!prepared.layout.styles[&target].animation_has_render_effect);
+ }
+ assert!(!prepared.has_active_declarative_css_animations());
+ }
+ }
+
+ #[test]
+ fn retained_fixed_image_source_changes_do_not_freeze_css_animations() {
+ for (before, after) in [(0.0, 500.0), (500.0, 0.0)] {
+ let tree = parse_html(r#"<style>
+ @keyframes grow { from { width:20px } to { width:80px } }
+ #animated { height:10px; background:blue; animation:grow 1s linear both }
+ img { display:block; width:20px; height:10px }
+ </style><div id=animated></div><img id=image src=https://assets.test/a.svg>"#);
+ let image = tree.get_element_by_id("image").unwrap();
+ let animated = tree.get_element_by_id("animated").unwrap();
+ let viewport = (120.0, 80.0);
+ let make_resources = || RenderResourceCache::with_loader(|_url: &str| {
+ Some(br#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"/>"#.to_vec())
+ });
+ let mut resources = make_resources();
+ let mut oracle_resources = make_resources();
+ let mut cache = crate::css::StylesheetCache::default();
+ let mut oracle_cache = crate::css::StylesheetCache::default();
+ let mut timeline = crate::AnimationTimelineState::default();
+ let mut oracle_timeline = crate::AnimationTimelineState::default();
+ timeline.note_start_candidate(animated, 0.0);
+ oracle_timeline.note_start_candidate(animated, 0.0);
+ let previous = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, viewport, None, &mut resources, &[], &mut cache,
+ crate::AnimationSample::document(before), &mut timeline,
+ ).unwrap();
+ let before_rect = previous.layout.rects[&animated];
+ let _ = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, viewport, None, &mut oracle_resources, &[], &mut oracle_cache,
+ crate::AnimationSample::document(before), &mut oracle_timeline,
+ ).unwrap();
+ tree.with_node_mut(image, |node| node.set_attribute("src", "https://assets.test/b.svg".into()));
+ let mut retained = prepare_dom_with_retained_styles_with_animation_state(
+ &tree, viewport, None, &mut resources, &[], &mut cache, previous,
+ &[crate::dom::AttributeStyleMutation { node: image, name: "src".into(),
+ old_value: Some("https://assets.test/a.svg".into()),
+ new_value: Some("https://assets.test/b.svg".into()) }.into()],
+ crate::AnimationSample::document(after), &mut timeline,
+ ).unwrap();
+ let mut oracle = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(
+ &tree, viewport, None, &mut oracle_resources, &[], &mut oracle_cache,
+ crate::AnimationSample::document(after), &mut oracle_timeline,
+ ).unwrap();
+ assert_ne!(retained.layout.rects[&animated], before_rect, "the animation must advance or rewind");
+ assert_eq!(retained.layout.rects, oracle.layout.rects);
+ assert_eq!(retained.animation_sample, crate::AnimationSample::document(after));
+ let pixels = paint_prepared(&tree, &mut retained, &mut resources, (0.0, 0.0)).unwrap();
+ let expected = paint_prepared(&tree, &mut oracle, &mut oracle_resources, (0.0, 0.0)).unwrap();
+ assert_eq!(pixels.data(), expected.data());
+ }
+ }
+
#[test]
fn image_accept_advertises_exactly_decodable_mime_types() {
assert!(!IMAGE_ACCEPT.contains('*'));
@@ -12583,6 +13720,175 @@ mod tests {
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
+ fn raster_cache_fixture() -> Arc<[u8]> {
+ let source = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
+ 2, 3, image::Rgba([20, 40, 60, 127]),
+ ));
+ let mut encoded = std::io::Cursor::new(Vec::new());
+ source.write_to(&mut encoded, image::ImageFormat::Png).unwrap();
+ Arc::from(encoded.into_inner())
+ }
+
+ #[test]
+ fn cached_raster_relative_urls_preserve_request_profiles_and_pixels() {
+ let url = "https://example.test/images/image.png";
+ let base = "https://example.test/pages/index.html";
+ let rect = crate::Rect { x: 0.0, y: 0.0, width: 12.0, height: 18.0 };
+ for profile in [None, Some(ImageRequestProfile::NoCorsInclude),
+ Some(ImageRequestProfile::CorsSameOrigin), Some(ImageRequestProfile::CorsInclude)] {
+ let mut cache = RenderResourceCache::default();
+ let bytes = raster_cache_fixture();
+ match profile {
+ Some(profile) => cache.seed_image_shared(url.to_owned(), profile, bytes),
+ None => cache.seed_shared(url.to_owned(), bytes),
+ }
+ let draw = |src, cache: &mut RenderResourceCache| {
+ let mut surface = Pixmap::new(12, 18).unwrap();
+ assert!(paint_image(src, Some(base), &rect, &rect, crate::ObjectFit::Fill,
+ crate::ObjectPosition::default(), &mut surface, cache, profile, None,
+ crate::ResolvedBorderRadii::default(), None));
+ surface
+ };
+ let relative = draw("../images/image.png", &mut cache);
+ let absolute = draw(url, &mut cache);
+ assert_eq!(relative.data(), absolute.data());
+ assert_eq!(cache.raster_paints.len(), 1);
+ assert_eq!(relative.pixel(0, 0).unwrap().alpha(), 127);
+ }
+ }
+
+ #[test]
+ fn raster_eligibility_is_lazy_and_invalidated_with_resource_bytes() {
+ let mut cache = RenderResourceCache::default();
+ let url = "https://example.test/lazy.png";
+ let bytes = raster_cache_fixture();
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ let eligibility = |cache: &RenderResourceCache| match cache.entries.get(url).unwrap() {
+ CachedResource::Bytes { static_raster, .. } => static_raster.get().copied(),
+ CachedResource::Missing(_) => None,
+ };
+ assert_eq!(eligibility(&cache), None);
+ // Layout/metadata preparation must not initialize paint eligibility.
+ cache.entries.get(url).unwrap().image_intrinsic();
+ assert_eq!(eligibility(&cache), None);
+ cache.raster_paint(url, Arc::clone(&bytes), 12, 18).unwrap();
+ assert_eq!(eligibility(&cache), Some(true));
+ cache.raster_paint(url, Arc::clone(&bytes), 6, 9).unwrap();
+ assert_eq!(eligibility(&cache), Some(true));
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ assert_eq!(eligibility(&cache), None);
+ assert!(cache.raster_paints.is_empty());
+ cache.seed_missing(url.to_owned());
+ assert_eq!(eligibility(&cache), None);
+ }
+
+ #[test]
+ fn raster_paint_cache_reuses_exact_pixels_and_separates_dimensions_and_profiles() {
+ let mut cache = RenderResourceCache::default();
+ let bytes = raster_cache_fixture();
+ let url = "https://example.test/image.png";
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ let first = cache.raster_paint(url, Arc::clone(&bytes), 12, 18).unwrap();
+ let second = cache.raster_paint(url, Arc::clone(&bytes), 12, 18).unwrap();
+ assert!(Arc::ptr_eq(&first, &second));
+ assert_eq!(first.data(), raster_to_pixmap(&bytes, 12, 18).unwrap().data());
+ let resized = cache.raster_paint(url, Arc::clone(&bytes), 6, 9).unwrap();
+ assert!(!Arc::ptr_eq(&first, &resized));
+ let cors_key = image_resource_key(url, ImageRequestProfile::CorsInclude);
+ cache.seed_image_shared(url.to_owned(), ImageRequestProfile::CorsInclude, Arc::clone(&bytes));
+ let cors = cache.raster_paint(&cors_key, bytes, 12, 18).unwrap();
+ assert!(!Arc::ptr_eq(&first, &cors));
+ assert_eq!(first.data(), cors.data());
+ }
+
+ #[test]
+ fn raster_paint_cache_drops_replaced_failed_and_evicted_resources() {
+ let mut cache = RenderResourceCache::with_loader_and_limits(HttpResourceLoader, 1, 4096);
+ let bytes = raster_cache_fixture();
+ let url = "https://example.test/a.png";
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ cache.raster_paint(url, Arc::clone(&bytes), 12, 18).unwrap();
+ assert!(cache.raster_paint_bytes > 0);
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ assert_eq!(cache.raster_paint_bytes, 0);
+ cache.raster_paint(url, Arc::clone(&bytes), 12, 18).unwrap();
+ cache.seed_missing(url.to_owned());
+ assert!(cache.raster_paints.is_empty());
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ cache.raster_paint(url, Arc::clone(&bytes), 12, 18).unwrap();
+ cache.seed_shared("https://example.test/b.png".to_owned(), bytes);
+ assert!(cache.raster_paints.is_empty());
+ assert_eq!(cache.raster_paint_bytes, 0);
+ }
+
+ #[test]
+ fn cached_raster_paint_preserves_cover_clipping_and_transparency() {
+ let mut cache = RenderResourceCache::default();
+ let url = "https://example.test/image.png";
+ cache.seed_shared(url.to_owned(), raster_cache_fixture());
+ let rect = crate::Rect { x: 5.0, y: 5.0, width: 20.0, height: 20.0 };
+ let clip = crate::Rect { x: 10.0, y: 10.0, width: 10.0, height: 10.0 };
+ let draw = |cache: &mut RenderResourceCache| {
+ let mut surface = Pixmap::new(40, 40).unwrap();
+ assert!(paint_image(url, None, &rect, &clip, crate::ObjectFit::Cover,
+ crate::ObjectPosition::default(), &mut surface, cache,
+ Some(ImageRequestProfile::NoCorsInclude), None,
+ crate::ResolvedBorderRadii::default(), None));
+ surface
+ };
+ let cold = draw(&mut cache);
+ assert_eq!(cache.raster_paints.len(), 1);
+ let warm = draw(&mut cache);
+ assert_eq!(cold.data(), warm.data());
+ assert_eq!(warm.pixel(7, 7).unwrap().alpha(), 0);
+ assert_eq!(warm.pixel(15, 15).unwrap().alpha(), 127);
+ }
+
+ #[test]
+ fn raster_paint_cache_excludes_animation_and_unretained_bytes() {
+ use base64::Engine;
+ // A two-frame, 2x3 RGBA APNG with distinct pixel values in each frame.
+ let animated: Arc<[u8]> = Arc::from(base64::engine::general_purpose::STANDARD.decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAYAAAC56t6BAAAACGFjVEwAAAACAAAAAPONk3AAAAAaZmNUTAAAAAAAAAACAAAAAwAAAAAAAAAAAAEAHgAASoAMRAAAABFJREFUeJxjENGwqQdhBgwGAEpDBcvYVzBtAAAAGmZjVEwAAAABAAAAAgAAAAMAAAAAAAAAAAABAB4AANHz5pAAAAAVZmRBVAAAAAJ4nGOw0bCpB2EGDAYAWFMGu+aEKGIAAAAASUVORK5CYII="
+ ).unwrap());
+ assert!(image::codecs::png::PngDecoder::new(std::io::Cursor::new(&*animated))
+ .unwrap().is_apng().unwrap());
+ let mut cache = RenderResourceCache::default();
+ let url = "https://example.test/animated.png";
+ cache.seed_shared(url.to_owned(), Arc::clone(&animated));
+ assert!(cache.raster_paint(url, animated, 2, 3).is_some());
+ assert!(cache.raster_paints.is_empty());
+ let static_bytes = raster_cache_fixture();
+ assert!(cache.raster_paint("https://example.test/unretained.png", static_bytes, 2, 3).is_some());
+ assert!(cache.raster_paints.is_empty());
+ }
+
+ #[test]
+ fn raster_paint_cache_enforces_payload_entry_and_count_bounds() {
+ let mut cache = RenderResourceCache::default();
+ let bytes = raster_cache_fixture();
+ let url = "https://example.test/image.png";
+ cache.seed_shared(url.to_owned(), Arc::clone(&bytes));
+ for width in 1..=80 {
+ cache.raster_paint(url, Arc::clone(&bytes), width, 1).unwrap();
+ assert!(cache.raster_paints.len() <= RASTER_PAINT_CACHE_ENTRIES);
+ }
+ for width in 500..510 {
+ cache.raster_paint(url, Arc::clone(&bytes), width, 800).unwrap();
+ assert!(cache.raster_paint_bytes <= RASTER_PAINT_CACHE_BYTES);
+ assert_eq!(cache.raster_paint_bytes,
+ cache.raster_paints.iter().map(|entry| entry.raster.data().len()).sum::<usize>());
+ }
+ let before = cache.raster_paint_bytes;
+ cache.raster_paint(url, Arc::clone(&bytes), 1024, 1024).unwrap();
+ assert_eq!(cache.raster_paint_bytes, before);
+ assert!(!static_raster_cacheable(b"GIF89a"));
+ assert!(!static_raster_cacheable(b"<svg/>"));
+ assert!(!static_raster_cacheable(b"not an image"));
+ cache.remove(url);
+ assert_eq!(cache.raster_paint_bytes, 0);
+ }
+
#[test]
fn enabled_bmp_and_ico_formats_have_metadata_and_full_raster_decode() {
use std::io::Cursor;
@@ -16131,6 +17437,96 @@ mod tests {
);
}
+
+ #[test]
+ fn metadata_discovery_refreshes_preloads_shadow_fonts_and_svg_text() {
+ let tree = parse_html(r#"<style id=faces>
+ @font-face{font-family:First;src:url(first.ttf)}
+ @font-face{font-family:Second;src:url(second.ttf);font-weight:700;font-style:italic}
+ </style><link id=preload rel="alternate PrElOaD" as="FoNt" href="second.ttf">
+ <x-card id=host><style>@font-face{font-family:Ignored;src:url(ignored.ttf)}</style>
+ <svg><text>Unslotted</text></svg></x-card>
+ <div id=source><style>@font-face{font-family:Shadow;src:url(shadow.ttf)}</style>
+ <svg id=visible><text>Visible</text></svg></div>"#);
+ let host = tree.get_element_by_id("host").unwrap();
+ let source = tree.get_element_by_id("source").unwrap();
+ let visible = tree.get_element_by_id("visible").unwrap();
+ let faces = tree.get_element_by_id("faces").unwrap();
+ let preload = tree.get_element_by_id("preload").unwrap();
+ let shadow = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();
+ for child in tree.children(source) { tree.append_child(shadow, child); }
+ tree.remove(source);
+ let loads = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let observed = loads.clone();
+ let mut resources = RenderResourceCache::with_loader(move |url: &str| {
+ observed.lock().unwrap().push(url.to_owned());
+ Some(SERIF_FONT_BYTES.to_vec())
+ });
+ let fonts = collect_web_fonts(&tree, Some("https://example.test/page"), &mut resources, &[]);
+ assert_eq!(fonts.iter().map(|f| f.family.as_deref().unwrap()).collect::<Vec<_>>(),
+ vec!["Second", "First", "Shadow"]);
+ assert_eq!(fonts[0].weight, Some((700, 700)));
+ assert_eq!(fonts[0].italic, Some(true));
+ assert!(has_inline_svg_text(&tree));
+ let css_text = tree.children(faces)[0];
+ tree.with_node_mut(css_text, |node| {
+ if let obscura_dom::tree::NodeData::Text { contents } = &mut node.data {
+ *contents = "@font-face{font-family:Changed;src:url(first.ttf);font-weight:600}@font-face{font-family:Second;src:url(second.ttf)}".into();
+ }
+ });
+ tree.with_node_mut(preload, |node| node.set_attribute("href", "first.ttf".into()));
+ tree.remove(visible);
+ let fonts = collect_web_fonts(&tree, Some("https://example.test/page"), &mut resources, &[]);
+ assert_eq!(fonts.iter().map(|f| f.family.as_deref().unwrap()).collect::<Vec<_>>(),
+ vec!["Changed", "Second", "Shadow"]);
+ assert_eq!(fonts[0].weight, Some((600, 600)));
+ assert!(!has_inline_svg_text(&tree), "unslotted SVG text must remain excluded");
+ assert_eq!(*loads.lock().unwrap(), vec![
+ "https://example.test/second.ttf", "https://example.test/first.ttf",
+ "https://example.test/shadow.ttf"], "warm resources must not reload or discover unslotted fonts");
+ }
+
+ #[test]
+ fn metadata_discovery_refreshes_responsive_images_posters_and_profiles() {
+ let tree = parse_html(r#"<picture>
+ <source media="(min-width:500px)" srcset="large.svg 2x">
+ <img id=hero src="small.svg" crossorigin="anonymous">
+ </picture><video id=video poster=" poster.svg "></video>
+ <video poster=" "></video><div data-src="ignored.svg">ordinary text</div>"#);
+ let hero = tree.get_element_by_id("hero").unwrap();
+ let video = tree.get_element_by_id("video").unwrap();
+ let mut resources = RenderResourceCache::with_loader(|_: &str| {
+ panic!("seeded metadata must not open a resource request")
+ });
+ for (url, profile, width, height) in [
+ ("large.svg", ImageRequestProfile::CorsSameOrigin, 80, 40),
+ ("small.svg", ImageRequestProfile::CorsSameOrigin, 10, 5),
+ ("poster.svg", ImageRequestProfile::NoCorsInclude, 30, 20),
+ ("large.svg", ImageRequestProfile::CorsInclude, 100, 60),
+ ] {
+ resources.seed_image(format!("https://example.test/{url}"), profile,
+ format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"/>"#).into_bytes());
+ }
+ let (intrinsic, selected) = collect_image_intrinsics(&tree, (800.0, 600.0),
+ Some("https://example.test/page"), &mut resources);
+ assert_eq!(selected.len(), 2);
+ assert_eq!(selected[&hero].resolved_url, "https://example.test/large.svg");
+ assert_eq!(selected[&hero].density, 2.0);
+ assert_eq!(intrinsic[&hero].natural_size(), Some((40.0, 20.0)));
+ assert_eq!(intrinsic[&video].natural_size(), Some((30.0, 20.0)));
+ tree.with_node_mut(video, |node| node.set_attribute("poster", " ".into()));
+ let (intrinsic, selected) = collect_image_intrinsics(&tree, (320.0, 600.0),
+ Some("https://example.test/page"), &mut resources);
+ assert_eq!(selected.len(), 1);
+ assert_eq!(selected[&hero].resolved_url, "https://example.test/small.svg");
+ assert_eq!(intrinsic[&hero].natural_size(), Some((10.0, 5.0)));
+ tree.with_node_mut(hero, |node| node.set_attribute("crossorigin", "use-credentials".into()));
+ let (intrinsic, selected) = collect_image_intrinsics(&tree, (800.0, 600.0),
+ Some("https://example.test/page"), &mut resources);
+ assert_eq!(selected[&hero].profile, ImageRequestProfile::CorsInclude);
+ assert_eq!(intrinsic[&hero].natural_size(), Some((50.0, 30.0)));
+ }
+
#[test]
fn font_face_parser_selects_ascii_subset_and_preserves_functional_src() {
let css = r#"
diff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rs
index f4273d2c..9cef7cc8 100644
--- a/crates/obscura-render/src/style.rs
+++ b/crates/obscura-render/src/style.rs
@@ -424,7 +424,9 @@ pub(crate) fn apply_animation_declarations(style: &mut LayoutStyle, css: &str) {
continue;
};
let name = name.trim().to_ascii_lowercase();
- if name == "animation" || name.starts_with("animation-") {
+ // display:none determines whether a CSS animation can exist, even
+ // when an important declaration overrides the normal display value.
+ if name == "display" || name == "animation" || name.starts_with("animation-") {
apply_value(style, &name, value.trim());
}
}
diff --git a/render-repros/checks.json b/render-repros/checks.json
index b279c529..8fd7327c 100644
--- a/render-repros/checks.json
+++ b/render-repros/checks.json
@@ -1,4 +1,9 @@
{
+ "retained-cssom-raster": [
+ {"name": "CSSOM width and fill survive metadata update", "color": "#246840", "x": 16, "y": 16, "width": 128, "height": 32},
+ {"name": "updated image and animation callback complete", "color": "#246840", "x": 16, "y": 220, "width": 32, "height": 16},
+ {"name": "four raster images preserve authored height", "color": "#d03020", "y": 80, "height": 40, "count": 4}
+ ],
"sparse-grid-scroll": [
{"name": "last contents-wrapped cell reaches scrollport bottom", "color": "#087f5b", "x": 20, "y": 90, "width": 200, "height": 30},
{"name": "empty tracks retain a full scroll viewport", "color": "#7048e8", "x": 260, "y": 20, "width": 200, "height": 100},
diff --git a/render-repros/retained-cssom-raster.html b/render-repros/retained-cssom-raster.html
new file mode 100644
index 00000000..8e6c0ccb
--- /dev/null
+++ b/render-repros/retained-cssom-raster.html
@@ -0,0 +1,35 @@
+<!doctype html><meta charset="utf-8"><title>Retained rendering after CSSOM and image updates</title>
+<style>
+body { margin:0; background:#fff }
+#marker { position:absolute; left:16px; top:16px; width:32px; height:32px; background:#d03020 }
+.tile { position:absolute; top:80px; width:80px; height:40px; background:#eee }
+img { display:block; width:80px; height:40px }
+#clip { position:absolute; left:16px; top:160px; width:56px; height:28px; overflow:hidden; border-radius:8px; background:#eee }
+#clip img { width:112px; height:56px }
+#done { position:absolute; left:16px; top:220px; width:32px; height:16px; background:#d03020 }
+</style>
+<div id="marker"></div>
+<div class="tile" style="left:16px"><img id="image0" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGO4YKDwH4QZoIAJxiBeAAAOAwRFe7UuagAAAABJRU5ErkJggg=="></div>
+<div class="tile" style="left:112px"><img id="image1" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGO4YKDwH4QZoIAJxiBeAAAOAwRFe7UuagAAAABJRU5ErkJggg=="></div>
+<div class="tile" style="left:208px"><img id="image2" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGO4YKDwH4QZoIAJxiBeAAAOAwRFe7UuagAAAABJRU5ErkJggg=="></div>
+<div class="tile" style="left:304px"><img id="image3" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGO4YKDwH4QZoIAJxiBeAAAOAwRFe7UuagAAAABJRU5ErkJggg=="></div>
+<div class="tile" style="left:400px"><img id="image4" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGO4YKDwH4QZoIAJxiBeAAAOAwRFe7UuagAAAABJRU5ErkJggg=="></div>
+<div id="clip"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGO4YKDwH4QZoIAJxiBeAAAOAwRFe7UuagAAAABJRU5ErkJggg=="></div><div id="done"></div>
+<script>
+addEventListener('load', () => {
+ document.getElementById('marker').getBoundingClientRect();
+ const sheet=document.styleSheets[0];
+ sheet.insertRule('#marker { width:128px; background:#246840 }',sheet.cssRules.length);
+ document.getElementById('marker').setAttribute('data-unreferenced','ready');
+ const changed=document.getElementById('image4');
+ changed.onload=() => {
+ requestAnimationFrame(() => {
+ const marker=document.getElementById('marker');
+ const valid=marker.getBoundingClientRect().width===128 && changed.naturalWidth===4;
+ document.getElementById('done').style.background=valid?'#246840':'#d03020';
+ document.documentElement.setAttribute('data-complete',String(valid));
+ });
+ };
+ changed.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGNQCLjwH4QZoIAJxiBeAAAbQwSFDmsp4QAAAABJRU5ErkJggg==";
+});
+</script>
\ No newline at end of file
diff --git a/vendor/cosmic-text/src/attrs.rs b/vendor/cosmic-text/src/attrs.rs
index 3b0ea465..119a4843 100644
--- a/vendor/cosmic-text/src/attrs.rs
+++ b/vendor/cosmic-text/src/attrs.rs
@@ -334,6 +334,11 @@ impl FontVariations {
pub fn iter(&self) -> impl Iterator<Item = &FontVariation> {
self.variations.iter()
}
+
+ #[cfg(feature = "shape-run-cache")]
+ pub(crate) fn allocated_bytes(&self) -> usize {
+ self.variations.capacity() * core::mem::size_of::<FontVariation>()
+ }
}
/// A wrapper for letter spacing to get around that f32 doesn't implement Eq and Hash
diff --git a/vendor/cosmic-text/src/font/system.rs b/vendor/cosmic-text/src/font/system.rs
index d3a91d94..f62bb278 100644
--- a/vendor/cosmic-text/src/font/system.rs
+++ b/vendor/cosmic-text/src/font/system.rs
@@ -240,6 +240,12 @@ impl FontSystem {
/// Get a mutable reference to the database.
pub fn db_mut(&mut self) -> &mut fontdb::Database {
self.font_matches_cache.clear();
+ // New faces or changed generic families can change fallback selection
+ // without changing the run's text or attributes.
+ #[cfg(feature = "shape-run-cache")]
+ {
+ self.shape_run_cache = crate::ShapeRunCache::default();
+ }
&mut self.db
}
diff --git a/vendor/cosmic-text/src/shape.rs b/vendor/cosmic-text/src/shape.rs
index 0799edab..a19623ed 100644
--- a/vendor/cosmic-text/src/shape.rs
+++ b/vendor/cosmic-text/src/shape.rs
@@ -2,6 +2,7 @@
#![allow(clippy::too_many_arguments)]
+use alloc::sync::Arc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::cmp::{max, min};
@@ -82,6 +83,8 @@ pub struct ShapeBuffer {
/// Buffer for holding unicode text.
rustybuzz_buffer: Option<rustybuzz::UnicodeBuffer>,
+ shape_plans: Vec<CachedShapePlan>,
+
/// Temporary buffers for scripts.
scripts: Vec<Script>,
@@ -99,6 +102,53 @@ pub struct ShapeBuffer {
glyph_sets: Vec<Vec<LayoutGlyph>>,
}
+const SHAPE_PLAN_CACHE_LIMIT: usize = 32;
+const SHAPE_PLAN_FEATURE_LIMIT: usize = 16;
+
+struct CachedShapePlan {
+ font: Arc<Font>,
+ direction: rustybuzz::Direction,
+ script: rustybuzz::Script,
+ language: Option<rustybuzz::Language>,
+ features: Vec<rustybuzz::Feature>,
+ plan: rustybuzz::ShapePlan,
+}
+
+impl ShapeBuffer {
+ fn cached_shape_plan(
+ &mut self,
+ font: &Arc<Font>,
+ direction: rustybuzz::Direction,
+ script: rustybuzz::Script,
+ language: Option<rustybuzz::Language>,
+ features: &[rustybuzz::Feature],
+ ) -> &rustybuzz::ShapePlan {
+ if let Some(index) = self.shape_plans.iter().position(|cached| {
+ Arc::ptr_eq(&cached.font, font)
+ && cached.direction == direction
+ && cached.script == script
+ && cached.language == language
+ && cached.features == features
+ }) {
+ return &self.shape_plans[index].plan;
+ }
+ let plan = rustybuzz::ShapePlan::new(
+ font.rustybuzz(), direction, Some(script), language.as_ref(), features,
+ );
+ // Font IDs can be reused after a database change. Retaining the exact
+ // immutable Font prevents a cached plan from matching a different face.
+ // Bound both retained plans and their feature lists for arbitrary text.
+ if self.shape_plans.len() == SHAPE_PLAN_CACHE_LIMIT {
+ self.shape_plans.remove(0);
+ }
+ self.shape_plans.push(CachedShapePlan {
+ font: Arc::clone(font), direction, script, language,
+ features: features.to_vec(), plan,
+ });
+ &self.shape_plans.last().expect("inserted shape plan").plan
+ }
+}
+
impl fmt::Debug for ShapeBuffer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("ShapeBuffer { .. }")
@@ -130,7 +180,7 @@ fn cluster_allows_letter_spacing(line: &str, cluster_start: usize) -> bool {
fn shape_fallback(
scratch: &mut ShapeBuffer,
glyphs: &mut Vec<ShapeGlyph>,
- font: &Font,
+ font: &Arc<Font>,
line: &str,
attrs_list: &AttrsList,
start_run: usize,
@@ -229,14 +279,22 @@ fn shape_fallback(
));
}
- let shape_plan = rustybuzz::ShapePlan::new(
- face,
- buffer.direction(),
- Some(buffer.script()),
- buffer.language().as_ref(),
- &rb_font_features,
- );
- let glyph_buffer = rustybuzz::shape_with_plan(face, &shape_plan, buffer);
+ // Plans depend on face coordinates as well as segment properties. Cache
+ // only the Font's immutable default face; per-span variable coordinates
+ // keep their existing plan construction and shaping behavior.
+ let uncached_plan;
+ let shape_plan = if varied_face.is_none() && rb_font_features.len() <= SHAPE_PLAN_FEATURE_LIMIT {
+ scratch.cached_shape_plan(
+ font, buffer.direction(), buffer.script(), buffer.language(), &rb_font_features,
+ )
+ } else {
+ uncached_plan = rustybuzz::ShapePlan::new(
+ face, buffer.direction(), Some(buffer.script()),
+ buffer.language().as_ref(), &rb_font_features,
+ );
+ &uncached_plan
+ };
+ let glyph_buffer = rustybuzz::shape_with_plan(face, shape_plan, buffer);
let glyph_infos = glyph_buffer.glyph_infos();
let glyph_positions = glyph_buffer.glyph_positions();
@@ -497,6 +555,13 @@ fn shape_run_cached(
) {
use crate::{AttrsOwned, ShapeRunKey};
+ // ShapeRunKey is public and has no direction field. Only memoize LTR
+ // shaping so existing key construction stays source-compatible and RTL
+ // runs cannot collide with a previously cached LTR run.
+ if span_rtl || end_run - start_run > crate::shape_run_cache::MAX_RUN_BYTES {
+ shape_run(glyphs, font_system, line, attrs_list, start_run, end_run, span_rtl);
+ return;
+ }
let run_range = start_run..end_run;
let mut key = ShapeRunKey {
text: line[run_range.clone()].to_string(),
@@ -511,10 +576,18 @@ fn shape_run_cached(
let start = max(attrs_range.start, start_run).saturating_sub(start_run);
let end = min(attrs_range.end, end_run).saturating_sub(start_run);
if end > start {
+ if key.attrs_spans.len() == crate::shape_run_cache::MAX_RUN_SPANS {
+ shape_run(glyphs, font_system, line, attrs_list, start_run, end_run, span_rtl);
+ return;
+ }
let range = start..end;
key.attrs_spans.push((range, attrs.clone()));
}
}
+ if !key.is_cacheable() {
+ shape_run(glyphs, font_system, line, attrs_list, start_run, end_run, span_rtl);
+ return;
+ }
if let Some(cache_glyphs) = font_system.shape_run_cache.get(&key) {
for mut glyph in cache_glyphs.iter().cloned() {
// Adjust glyph start and end to match run position
@@ -2179,6 +2252,213 @@ impl ShapeLine {
}
}
+#[cfg(all(test, feature = "std", feature = "shape-run-cache"))]
+mod shape_run_cache_tests {
+ use super::*;
+ use crate::{fontdb, Attrs, Family, FeatureTag, FontFeatures, FontVariations, VariationTag};
+
+ fn system() -> FontSystem {
+ let mut db = fontdb::Database::new();
+ db.load_font_data(include_bytes!("../fonts/NotoSans-Regular.ttf").to_vec());
+ db.load_font_data(include_bytes!("../fonts/NotoSansHebrew.ttf").to_vec());
+ db.set_sans_serif_family("Noto Sans");
+ FontSystem::new_with_locale_and_db("en-US".into(), db)
+ }
+
+ fn run(system: &mut FontSystem, line: &str, attrs: &AttrsList, start: usize, rtl: bool, cached: bool) -> String {
+ let mut glyphs = Vec::new();
+ if cached {
+ shape_run_cached(&mut glyphs, system, line, attrs, start, line.len(), rtl);
+ } else {
+ shape_run(&mut glyphs, system, line, attrs, start, line.len(), rtl);
+ }
+ format!("{glyphs:?}")
+ }
+
+ #[test]
+ fn shape_run_cache_matches_fresh_attributes_directions_and_rebased_offsets() {
+ let mut system = system();
+ system.db_mut().load_font_data(include_bytes!("../fonts/NotoSansArabic.ttf").to_vec());
+ for text in ["office AV e\u{301}", "שָׁלוֹם עולם", "خالصة كلمة", "a\tb"] {
+ for index in 0..10 {
+ let mut attrs = Attrs::new().family(Family::Name("Noto Sans"));
+ match index {
+ 1 => attrs = attrs.letter_spacing(0.125),
+ 2 => attrs = attrs.metadata(23),
+ 3 => attrs = attrs.color(Color::rgb(23, 45, 67)),
+ 4 => attrs = attrs.metrics(Metrics::new(19.0, 25.0)),
+ 5 => {
+ let mut features = FontFeatures::new();
+ features.disable(FeatureTag::STANDARD_LIGATURES);
+ attrs = attrs.font_features(features);
+ }
+ 6 => {
+ let mut variations = FontVariations::new();
+ variations.set(VariationTag::new(b"wght"), 635.0);
+ attrs.font_variations = variations;
+ }
+ 7 => attrs = attrs.family(Family::Name("Noto Sans Hebrew")),
+ 8 => attrs.font_id_opt = system.db().faces().next().map(|face| face.id),
+ 9 => attrs.font_optical_size_opt = Some(crate::VariationValue(22.0)),
+ _ => {}
+ }
+ for prefix in ["", "prefix "] {
+ let line = format!("{prefix}{text}");
+ let mut list = AttrsList::new(&attrs);
+ let start = prefix.len();
+ let first_end = start + text.chars().next().unwrap().len_utf8();
+ list.add_span(start..first_end, &attrs.clone().metadata(97).color(Color::rgb(3, 5, 7)));
+ for rtl in [false, true, false] {
+ let expected = run(&mut system, &line, &list, start, rtl, false);
+ for _ in 0..2 {
+ assert_eq!(run(&mut system, &line, &list, start, rtl, true), expected,
+ "text={text:?} case={index} prefix={prefix:?} rtl={rtl}");
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn shape_run_cache_invalidates_when_the_font_database_changes() {
+ let mut system = system();
+ let attrs = AttrsList::new(&Attrs::new().family(Family::Name("Noto Sans Arabic")));
+ let text = "خالصة كلمة";
+ // Deliberately exercise an LTR span so this checks invalidation rather
+ // than the RTL bypass. Newly loaded glyphs must replace old fallbacks.
+ let first = run(&mut system, text, &attrs, 0, false, true);
+ system.db_mut().load_font_data(include_bytes!("../fonts/NotoSansArabic.ttf").to_vec());
+ let fresh = run(&mut system, text, &attrs, 0, false, false);
+ assert_ne!(first, fresh);
+ assert_eq!(run(&mut system, text, &attrs, 0, false, true), fresh);
+
+ let attrs = AttrsList::new(&Attrs::new().family(Family::SansSerif));
+ let text = " ";
+ let before = run(&mut system, text, &attrs, 0, false, true);
+ system.db_mut().set_sans_serif_family("Noto Sans Hebrew");
+ let after = run(&mut system, text, &attrs, 0, false, false);
+ assert_ne!(before, after);
+ assert_eq!(run(&mut system, text, &attrs, 0, false, true), after);
+ }
+
+ #[test]
+ fn shape_run_cache_preserves_oversized_run_and_span_output() {
+ let mut system = system();
+ let text = "office AV ".repeat(140);
+ let list = AttrsList::new(&Attrs::new());
+ assert_eq!(run(&mut system, &text, &list, 0, false, true), run(&mut system, &text, &list, 0, false, false));
+ let text = "abcdefghijklmnopqrstuvwxyz";
+ let mut list = AttrsList::new(&Attrs::new());
+ for index in 0..text.len() {
+ list.add_span(index..index + 1, &Attrs::new().metadata(index + 1));
+ }
+ assert_eq!(run(&mut system, text, &list, 0, false, true), run(&mut system, text, &list, 0, false, false));
+ }
+}
+
+#[cfg(all(test, feature = "std"))]
+mod shape_plan_cache_tests {
+ use super::*;
+ use crate::{fontdb, Attrs, FeatureTag, FontFeatures};
+
+ fn font(bytes: &[u8]) -> Arc<Font> {
+ let mut db = fontdb::Database::new();
+ db.load_font_data(bytes.to_vec());
+ let id = db.faces().next().unwrap().id;
+ Arc::new(Font::new(&db, id).unwrap())
+ }
+
+ fn buffer(text: &str, direction: rustybuzz::Direction, language: &str) -> rustybuzz::UnicodeBuffer {
+ let mut buffer = rustybuzz::UnicodeBuffer::new();
+ buffer.push_str(text);
+ buffer.set_direction(direction);
+ buffer.set_language(language.parse().unwrap());
+ buffer.guess_segment_properties();
+ buffer
+ }
+
+ #[test]
+ fn shape_plan_cache_matches_fresh_glyphs_for_all_key_properties() {
+ let mut scratch = ShapeBuffer::default();
+ let cases: [(&[u8], &str); 3] = [
+ (include_bytes!("../fonts/NotoSans-Regular.ttf"), "office ffi e\u{301} AV"),
+ (include_bytes!("../fonts/NotoSansArabic.ttf"), "خالصة كلمة"),
+ (include_bytes!("../fonts/NotoSansHebrew.ttf"), "שָׁלוֹם עולם"),
+ ];
+ for (bytes, text) in cases {
+ let font = font(bytes);
+ for direction in [rustybuzz::Direction::LeftToRight, rustybuzz::Direction::RightToLeft] {
+ for language in ["en", "ar", "he"] {
+ for features in [
+ Vec::new(),
+ vec!["liga=0".parse().unwrap()],
+ vec!["kern=0".parse().unwrap(), "liga=1".parse().unwrap()],
+ ] {
+ let properties = buffer(text, direction, language);
+ let fresh = rustybuzz::ShapePlan::new(
+ font.rustybuzz(), direction, Some(properties.script()),
+ properties.language().as_ref(), &features,
+ );
+ let expected = rustybuzz::shape_with_plan(font.rustybuzz(), &fresh, properties);
+ let expected = format!("{:?}|{:?}", expected.glyph_infos(), expected.glyph_positions());
+ let mut first_plan = None;
+ for _ in 0..2 {
+ let properties = buffer(text, direction, language);
+ let cached = scratch.cached_shape_plan(
+ &font, direction, properties.script(), properties.language(), &features,
+ );
+ let identity = cached as *const rustybuzz::ShapePlan;
+ if let Some(first) = first_plan { assert_eq!(first, identity); }
+ first_plan = Some(identity);
+ let actual = rustybuzz::shape_with_plan(font.rustybuzz(), cached, properties);
+ assert_eq!(expected, format!("{:?}|{:?}", actual.glyph_infos(), actual.glyph_positions()));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn shape_plan_cache_bounds_entries_and_distinguishes_reused_font_ids() {
+ let first = font(include_bytes!("../fonts/NotoSans-Regular.ttf"));
+ let second = font(include_bytes!("../fonts/NotoSansArabic.ttf"));
+ assert_eq!(first.id(), second.id(), "separate databases reuse the first font ID");
+ let mut scratch = ShapeBuffer::default();
+ let direction = rustybuzz::Direction::LeftToRight;
+ let script = rustybuzz::script::LATIN;
+ scratch.cached_shape_plan(&first, direction, script, None, &[]);
+ scratch.cached_shape_plan(&second, direction, script, None, &[]);
+ assert_eq!(scratch.shape_plans.len(), 2);
+ scratch.cached_shape_plan(&first, direction, rustybuzz::script::ARABIC, None, &[]);
+ assert_eq!(scratch.shape_plans.len(), 3, "script is part of the key for the same font");
+ for index in 0..SHAPE_PLAN_CACHE_LIMIT + 5 {
+ scratch.cached_shape_plan(&first, direction, script,
+ Some(format!("en-x-{index}").parse().unwrap()), &[]);
+ assert!(scratch.shape_plans.len() <= SHAPE_PLAN_CACHE_LIMIT);
+ }
+ assert_eq!(scratch.shape_plans.len(), SHAPE_PLAN_CACHE_LIMIT);
+ assert!(!scratch.shape_plans.iter().any(|entry| entry.language.is_none()));
+ assert_eq!(Arc::strong_count(&second), 1, "eviction releases old font ownership");
+ }
+
+ #[test]
+ fn shape_plan_cache_skips_oversized_feature_lists() {
+ let font = font(include_bytes!("../fonts/NotoSans-Regular.ttf"));
+ let mut features = FontFeatures::new();
+ for index in 0..SHAPE_PLAN_FEATURE_LIMIT + 1 {
+ features.set(FeatureTag::KERNING, (index % 2) as u32);
+ }
+ let attrs = Attrs::new().font_features(features);
+ let mut scratch = ShapeBuffer::default();
+ let mut glyphs = Vec::new();
+ shape_fallback(&mut scratch, &mut glyphs, &font, "AV", &AttrsList::new(&attrs), 0, 2, false);
+ assert!(!glyphs.is_empty());
+ assert!(scratch.shape_plans.is_empty());
+ }
+}
+
#[cfg(all(test, feature = "std"))]
mod letter_spacing_tests {
use super::*;
diff --git a/vendor/cosmic-text/src/shape_run_cache.rs b/vendor/cosmic-text/src/shape_run_cache.rs
index 2e1ffc7f..1dc5ab01 100644
--- a/vendor/cosmic-text/src/shape_run_cache.rs
+++ b/vendor/cosmic-text/src/shape_run_cache.rs
@@ -2,7 +2,13 @@
use alloc::{string::String, vec::Vec};
use core::ops::Range;
-use crate::{AttrsOwned, HashMap, ShapeGlyph};
+use crate::{AttrsOwned, FamilyOwned, HashMap, ShapeGlyph};
+
+const MAX_ENTRIES: usize = 512;
+const MAX_RETAINED_BYTES: usize = 2 * 1024 * 1024;
+const MAX_ENTRY_BYTES: usize = 64 * 1024;
+pub(crate) const MAX_RUN_BYTES: usize = 1024;
+pub(crate) const MAX_RUN_SPANS: usize = 16;
/// Key for caching shape runs.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
@@ -12,17 +18,42 @@ pub struct ShapeRunKey {
pub attrs_spans: Vec<(Range<usize>, AttrsOwned)>,
}
+impl ShapeRunKey {
+ fn retained_bytes(&self) -> usize {
+ fn attrs_bytes(attrs: &AttrsOwned) -> usize {
+ let family_bytes = match &attrs.family_owned {
+ FamilyOwned::Name(name) => name.len(),
+ _ => 0,
+ };
+ family_bytes
+ + attrs.font_features.features.capacity() * core::mem::size_of::<crate::Feature>()
+ + attrs.font_variations.allocated_bytes()
+ }
+ core::mem::size_of::<Self>() + self.text.capacity()
+ + self.attrs_spans.capacity() * core::mem::size_of::<(Range<usize>, AttrsOwned)>()
+ + attrs_bytes(&self.default_attrs)
+ + self.attrs_spans.iter().map(|(_, attrs)| attrs_bytes(attrs)).sum::<usize>()
+ }
+
+ pub(crate) fn is_cacheable(&self) -> bool {
+ self.text.len() <= MAX_RUN_BYTES
+ && self.attrs_spans.len() <= MAX_RUN_SPANS
+ && self.retained_bytes() <= MAX_ENTRY_BYTES
+ }
+}
+
/// A helper structure for caching shape runs.
#[derive(Clone, Default)]
pub struct ShapeRunCache {
age: u64,
- cache: HashMap<ShapeRunKey, (u64, Vec<ShapeGlyph>)>,
+ cache: HashMap<ShapeRunKey, (u64, Vec<ShapeGlyph>, usize)>,
+ retained_bytes: usize,
}
impl ShapeRunCache {
/// Get cache item, updating age if found
pub fn get(&mut self, key: &ShapeRunKey) -> Option<&Vec<ShapeGlyph>> {
- self.cache.get_mut(key).map(|(age, glyphs)| {
+ self.cache.get_mut(key).map(|(age, glyphs, _)| {
*age = self.age;
&*glyphs
})
@@ -30,13 +61,35 @@ impl ShapeRunCache {
/// Insert cache item with current age
pub fn insert(&mut self, key: ShapeRunKey, glyphs: Vec<ShapeGlyph>) {
- self.cache.insert(key, (self.age, glyphs));
+ let bytes = key.retained_bytes()
+ + core::mem::size_of::<(u64, Vec<ShapeGlyph>, usize)>()
+ + glyphs.capacity() * core::mem::size_of::<ShapeGlyph>();
+ if !key.is_cacheable() || bytes > MAX_ENTRY_BYTES {
+ return;
+ }
+ if let Some((_, _, previous_bytes)) = self.cache.remove(&key) {
+ self.retained_bytes -= previous_bytes;
+ }
+ // This is disposable memoization. Clearing at either bound avoids an
+ // eviction scan or a second copy of every key. Hash-table overhead is
+ // separately bounded by MAX_ENTRIES; payload accounting uses capacity.
+ if self.cache.len() >= MAX_ENTRIES || self.retained_bytes + bytes > MAX_RETAINED_BYTES {
+ self.cache.clear();
+ self.retained_bytes = 0;
+ }
+ self.retained_bytes += bytes;
+ self.cache.insert(key, (self.age, glyphs, bytes));
}
/// Remove anything in the cache with an age older than `keep_ages`
pub fn trim(&mut self, keep_ages: u64) {
- self.cache
- .retain(|_key, (age, _glyphs)| *age + keep_ages >= self.age);
+ self.cache.retain(|_key, (age, _glyphs, bytes)| {
+ let retain = age.saturating_add(keep_ages) >= self.age;
+ if !retain {
+ self.retained_bytes -= *bytes;
+ }
+ retain
+ });
// Increase age
self.age += 1;
}
@@ -47,3 +100,63 @@ impl core::fmt::Debug for ShapeRunCache {
f.debug_tuple("ShapeRunCache").finish()
}
}
+
+#[cfg(all(test, feature = "std"))]
+mod tests {
+ use super::*;
+ use crate::Attrs;
+
+ fn key(index: usize) -> ShapeRunKey {
+ ShapeRunKey {
+ text: format!("word{index}"),
+ default_attrs: AttrsOwned::new(&Attrs::new()),
+ attrs_spans: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn shape_run_cache_bounds_entries_payload_and_replacement_accounting() {
+ let mut cache = ShapeRunCache::default();
+ for index in 0..MAX_ENTRIES + 4 {
+ cache.insert(key(index), Vec::new());
+ assert!(cache.cache.len() <= MAX_ENTRIES);
+ assert!(cache.retained_bytes <= MAX_RETAINED_BYTES);
+ }
+ assert!(cache.get(&key(0)).is_none());
+ let bytes = cache.retained_bytes;
+ cache.insert(key(MAX_ENTRIES + 3), Vec::new());
+ assert_eq!(cache.retained_bytes, bytes);
+ cache = ShapeRunCache::default();
+ let mut evictions = 0;
+ for index in 0..300 {
+ let previous = cache.cache.len();
+ cache.insert(key(index), Vec::with_capacity(200));
+ evictions += usize::from(cache.cache.len() < previous);
+ assert!(cache.retained_bytes <= MAX_RETAINED_BYTES);
+ assert_eq!(cache.retained_bytes, cache.cache.values().map(|(_, _, bytes)| bytes).sum());
+ }
+ assert!(evictions > 0, "the payload bound must evict before the entry bound");
+ cache.trim(0);
+ cache.trim(0);
+ assert!(cache.cache.is_empty());
+ assert_eq!(cache.retained_bytes, 0);
+ }
+
+ #[test]
+ fn shape_run_cache_rejects_oversized_keys_and_allocations() {
+ let mut cache = ShapeRunCache::default();
+ let mut long = key(0);
+ long.text = "x".repeat(MAX_RUN_BYTES + 1);
+ cache.insert(long, Vec::new());
+ cache.insert(key(1), Vec::with_capacity(MAX_ENTRY_BYTES));
+ let mut spans = key(2);
+ spans.attrs_spans = (0..MAX_RUN_SPANS + 1)
+ .map(|index| (index..index + 1, AttrsOwned::new(&Attrs::new()))).collect();
+ cache.insert(spans, Vec::new());
+ let mut allocation = key(3);
+ allocation.default_attrs.font_features.features.reserve(MAX_ENTRY_BYTES);
+ cache.insert(allocation, Vec::new());
+ assert!(cache.cache.is_empty());
+ assert_eq!(cache.retained_bytes, 0);
+ }
+}
diff --git a/vendor/taffy/src/compute/leaf.rs b/vendor/taffy/src/compute/leaf.rs
index 4f1d979c..ae3c8a50 100644
--- a/vendor/taffy/src/compute/leaf.rs
+++ b/vendor/taffy/src/compute/leaf.rs
@@ -42,10 +42,16 @@ where
(node_size, node_min_size, node_max_size, None)
}
SizingMode::InherentSize => {
- let aspect_ratio = style.aspect_ratio();
- let style_size = style
- .size()
- .maybe_resolve(parent_size, &resolve_calc_value)
+ let resolved_size = style.size().maybe_resolve(parent_size, &resolve_calc_value);
+ // A preferred ratio only supplies an automatic axis. Once both
+ // authored axes resolve, including percentages with definite
+ // bases, it must not raise the used height or transfer constraints.
+ let aspect_ratio = if resolved_size.width.is_some() && resolved_size.height.is_some() {
+ None
+ } else {
+ style.aspect_ratio()
+ };
+ let style_size = resolved_size
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let style_min_size = style