Skip to content

Truly independent web browser

LibWeb: Free the style engine's scratch when a document stops styling

Andreas Kling92f07becccd2
diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp b/Libraries/LibWeb/CSS/StyleEngineBridge.cpp
index a3d8c271713..9b4c3046a91 100644
--- a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.cpp
@@ -25,6 +25,7 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Page/RenderingStats.h>
+#include <LibWeb/Platform/Timer.h>
#include <LibWeb/StyleValueRustFFI.h>
namespace Web::CSS {
@@ -45,6 +46,42 @@ StyleEngine::~StyleEngine() = default;
void StyleEngine::visit_edges(GC::Cell::Visitor& visitor)
{
visitor.visit(m_style_computer);
+ visitor.visit(m_scratch_trim_timer);
+}
+
+void StyleEngine::note_style_update_for_scratch_trim()
+{
+ // NB: An update only notes its time, so that a document styling every frame does not move the timer each frame.
+ // The timer, once it fires, waits again for what is left of the delay after the last update.
+ m_last_style_update_time = MonotonicTime::now();
+ if (!m_style_computer)
+ return;
+ if (!m_scratch_trim_timer) {
+ m_scratch_trim_timer = Platform::Timer::create_single_shot(GC::Heap::the(), scratch_trim_delay, GC::create_function(GC::Heap::the(), GC::captures(*m_style_computer), [](StyleComputer& style_computer) {
+ // NB: The timer captures the style computer, so it fires for none that is gone, but a destroyed document
+ // has nothing left to trim.
+ if (!style_computer.document().has_been_destroyed())
+ style_computer.style_engine().trim_scratch();
+ }));
+ }
+ if (!m_scratch_trim_timer->is_active())
+ m_scratch_trim_timer->start(scratch_trim_delay);
+}
+
+void StyleEngine::trim_scratch()
+{
+ auto since_last_update = MonotonicTime::now() - m_last_style_update_time;
+ if (since_last_update < scratch_trim_delay) {
+ m_scratch_trim_timer->start(scratch_trim_delay - since_last_update);
+ return;
+ }
+ // NB: An update that still flies is a document that is still styling.
+ if (StyleEngineFFI::style_engine_style_update_flies(host())) {
+ m_scratch_trim_timer->start(scratch_trim_delay);
+ return;
+ }
+ Layout::ForcedReadScope read { *m_render_document };
+ StyleEngineFFI::style_engine_trim_scratch(host(), read);
}
// More nodes than this waiting to arrive at once are found along the marks instead.
@@ -711,6 +748,7 @@ StyleEngine::StyleUpdateTimings StyleEngine::run_style_update(Layout::BegunRead
if (m_style_computer)
publish_font_faces(m_style_computer->document().font_computer());
StyleEngineFFI::style_engine_run_style_update(m_render_document->host(), &read, root.value(), lent.inputs);
+ note_style_update_for_scratch_trim();
return style_update_timings(submission_started_at, bridge_started_at);
}
@@ -721,6 +759,7 @@ StyleEngine::StyleUpdateTimings StyleEngine::drain_flown_style_update(Layout::Be
submit_recorded_input();
auto bridge_started_at = MonotonicTime::now();
StyleEngineFFI::style_engine_drain_flown_style_update(m_render_document->host(), &read);
+ note_style_update_for_scratch_trim();
// The transaction's reactions were read inside the style record view epoch its seal opened.
if (m_style_computer)
m_style_computer->end_style_record_view_epoch();
diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.h b/Libraries/LibWeb/CSS/StyleEngineBridge.h
index 40b280eca9a..1bd9a7507c8 100644
--- a/Libraries/LibWeb/CSS/StyleEngineBridge.h
+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.h
@@ -403,6 +403,11 @@ public:
// Takes the style update that flew in, waiting for it to land, to drain its reactions against the inputs it
// was sealed with. What was written beside it waits for end_flown_style_drain(): it is the next transaction's.
StyleUpdateTimings drain_flown_style_update(Layout::BegunRead const& read);
+
+ // How long the document goes without a style update before the engine gives back what its passes keep for the
+ // next one. Each update starts the wait over, so a document that styles every frame, as an animation does, keeps it.
+ static constexpr auto scratch_trim_delay = AK::Duration::from_seconds(1);
+ void trim_scratch();
void end_flown_style_drain();
// Takes in the fonts passes resolved against a table older than the document's. Those of a transaction that flew wait
// for the end of its drain, as what was written beside it does; a drain's own later passes publish the newer table
@@ -450,6 +455,7 @@ private:
void gather_computation_inputs(LentComputationInputs&);
void submit_recorded_input();
+ void note_style_update_for_scratch_trim();
void publish_attribute_value_texts_if_requirements_moved(Layout::BegunRead const& read);
Optional<StyleSheetResourceContexts> m_style_sheet_resource_contexts;
@@ -460,6 +466,8 @@ private:
NonnullRefPtr<Layout::RenderDocument> m_render_document;
u64 m_published_font_environment_generation { 0 };
GC::Ptr<StyleComputer> m_style_computer;
+ GC::Ptr<Platform::Timer> m_scratch_trim_timer;
+ MonotonicTime m_last_style_update_time { MonotonicTime::now() };
// The language the host interned last, which most elements arriving after one share: its tag, its atom, and the
// atom generation the atom was interned in.
Utf16String m_last_language_text;
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
index bdc043bae22..c3bea75ef9c 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
@@ -1520,6 +1520,13 @@ pub unsafe extern "C" fn style_engine_memory_report(
MemoryOwner::COUNT
}
+/// Lets go of what the style passes of `host`'s document work in and keep for the next one, for a document that has not
+/// styled in a while.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_trim_scratch(host: &DocumentHost, read: &crate::render_state::BegunRead) {
+ with_engine(read, host, StyleEngine::trim_scratch);
+}
+
/// A record of the allocations reports have counted, for [`style_engine_memory_beyond`].
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_memory_sizer_create() -> *mut c_void {
diff --git a/Libraries/LibWeb/Rust/src/css/style/memory_report.rs b/Libraries/LibWeb/Rust/src/css/style/memory_report.rs
index 5a1fc3cc77b..b3ab2216840 100644
--- a/Libraries/LibWeb/Rust/src/css/style/memory_report.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/memory_report.rs
@@ -112,6 +112,13 @@ impl MemoryReport {
}
impl super::StyleEngine {
+ /// Lets go of what the engine's passes work in and keep for the next one, for a document that stopped styling.
+ pub(crate) fn trim_scratch(&mut self) {
+ if let Some(live) = self.retained.live_style.as_mut() {
+ live.trim_scratch();
+ }
+ }
+
/// What the engine holds on the heap, by owner, with the layout arena's style columns.
pub(crate) fn memory_report(&self, arena: &crate::layout::LayoutNodeArena) -> MemoryReport {
self.memory_report_into(MemoryReport::default(), arena)
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
index 0a51b028e2e..54684f71fac 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
@@ -1988,6 +1988,14 @@ impl GroupCache {
self
}
+ /// Lets go of the room the cache holds beyond its entries, which it keeps for the next pass: a few elements restyled
+ /// later, as on hover, still find their payloads.
+ pub(in crate::css::style) fn trim(&mut self) {
+ self.entries.shrink_to_fit();
+ self.key_values.shrink_to_fit();
+ self.key_inputs.shrink_to_fit();
+ }
+
/// How many lookups the hit counts cover before they start over.
const COUNT_PERIOD: u32 = 4096;
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
index 28157fb203c..475c1ce738d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
@@ -453,6 +453,26 @@ impl MatchedDeclarationsInputs {
}
impl Live {
+ /// Lets go of what the passes and invalidations work in and keep for the next one, for a document that stopped
+ /// styling: the next pass makes it again.
+ pub(in super::super) fn trim_scratch(&mut self) {
+ for memo in self.scratch.memos.made() {
+ *memo.lock().expect("no pass holds a memo while the scratch is trimmed") = FollowScratch::default();
+ }
+ // NB: The memos measure where siblings stand again.
+ self.scratch.memos_dom_order_version = None;
+ for cache in self.scratch.groups.made() {
+ cache
+ .lock()
+ .expect("no pass holds a cache while the scratch is trimmed")
+ .trim();
+ }
+ self.scratch.invalidate = InvalidateScratch::default();
+ self.scratch.install = Default::default();
+ self.scratch.replaced = Default::default();
+ self.scratch.kept = Vec::new();
+ }
+
/// The matched declarations cache the passes keep for the next.
#[cfg(test)]
pub(super) fn matched_declarations(&self) -> &super::matched_declarations::MatchedDeclarationsCache {
@@ -4591,6 +4611,30 @@ mod tests {
const SIBLINGS: u32 = 1000;
+ #[test]
+ fn a_pass_after_the_scratch_is_trimmed_styles_as_a_cold_pass_does() {
+ use super::super::test_support::*;
+ let (mut engine, nodes) = document_with_children(4);
+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);
+ add_rules(
+ &mut engine,
+ sheet,
+ ".item { width: 1px; } .item + .item { color: rgb(0, 128, 0); } .item ~ :last-child { height: 2px; }",
+ );
+ add_class(&mut engine, nodes[1], "item");
+ start_live_on(&mut engine, nodes[0], 2);
+ for node in [nodes[2], nodes[3]] {
+ engine.trim_scratch();
+ add_class(&mut engine, node, "item");
+ run_style_update(&mut engine, nodes[0]);
+ assert_live_matches_cold(&mut engine, nodes[0]);
+ }
+ engine.trim_scratch();
+ remove_class(&mut engine, nodes[2], "item");
+ run_style_update(&mut engine, nodes[0]);
+ assert_live_matches_cold(&mut engine, nodes[0]);
+ }
+
#[test]
fn compound_memo_forgets_answers_when_the_stamp_wraps() {
let mut memo = CompoundMemo::default();