Skip to content

Truly independent web browser

LibWeb: Keep compiled style sheets for a while after their removal

Andreas Kling4e0617959f23
diff --git a/Libraries/LibWeb/CSS/StyleComputer.h b/Libraries/LibWeb/CSS/StyleComputer.h
index c88bdc4aed1..64cec83f73f 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.h
+++ b/Libraries/LibWeb/CSS/StyleComputer.h
@@ -217,6 +217,9 @@ public:
void set_style_engine_sheet_id_for(StyleSheetState&, SheetID);
[[nodiscard]] HashMap<SharedCompiledStyleSheetKey, RefPtr<SharedCompiledStyleSheet>>& shared_compiled_style_sheets() { return m_shared_compiled_style_sheets; }
+ [[nodiscard]] Vector<SharedCompiledStyleSheetKey>& detached_shared_compiled_style_sheets() { return m_detached_shared_compiled_style_sheets; }
+ // How many shared compiled sheets a document keeps after no tree scope holds them.
+ static constexpr size_t max_detached_shared_compiled_style_sheets = 8;
// The reverse of a node's style node identity. StyleEngine plans in identities; turning a
// plan back into nodes needs this, and it is maintained at exactly the two points the
@@ -300,6 +303,8 @@ private:
Vector<NonAuthorStyleSheet> m_non_author_style_sheets;
HashMap<RefPtr<StyleSheetState const>, SheetID> m_constructed_sheet_ids;
HashMap<SharedCompiledStyleSheetKey, RefPtr<SharedCompiledStyleSheet>> m_shared_compiled_style_sheets;
+ // The shared compiled sheets that no tree scope holds any longer, least recently detached first.
+ Vector<SharedCompiledStyleSheetKey> m_detached_shared_compiled_style_sheets;
HashMap<u64, WeakPtr<StyleSheetState const>> m_style_engine_sheet_sources;
};
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
index 6ede30a6b33..66c8994065f 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
@@ -2404,6 +2404,8 @@ static RefPtr<SharedCompiledStyleSheet> shared_compiled_style_sheet_for(StyleShe
// Keep a separate program when another occurrence already occupies this scope.
if ((*existing)->is_attached_to(tree_scope) && sheet.native_rules().has_anonymous_layer())
return nullptr;
+ if (!(*existing)->has_attachments())
+ style_computer.detached_shared_compiled_style_sheets().remove_first_matching([&](auto const& detached) { return detached == key; });
return *existing;
}
auto contents = StyleSheetState::create(sheet.native_rules().clone_shared_contents(), &document, RustMediaList {}, {});
@@ -2421,6 +2423,18 @@ static RefPtr<SharedCompiledStyleSheet> shared_compiled_style_sheet_for(StyleShe
return shared_compiled_style_sheet;
}
+static void release_shared_compiled_style_sheet(SharedCompiledStyleSheetKey const& key, StyleComputer& style_computer)
+{
+ auto& shared_compiled_style_sheets = style_computer.shared_compiled_style_sheets();
+ auto sheet_id = shared_compiled_style_sheets.get(key).value()->sheet_id();
+ auto& style_engine = style_computer.style_engine();
+ StyleEngineFFI::style_engine_begin_sheet_rules_replacement(style_engine.host(), sheet_id.value());
+ style_engine.finish_sheet_rules_replacement(sheet_id);
+ shared_compiled_style_sheets.remove(key);
+ if (shared_compiled_style_sheets.is_empty())
+ shared_compiled_style_sheets.clear();
+}
+
static void detach_shared_compiled_style_sheet(SharedCompiledStyleSheet& sheet, u64 occurrence, TreeScopeID tree_scope, StyleComputer& style_computer)
{
auto& style_engine = style_computer.style_engine();
@@ -2429,12 +2443,13 @@ static void detach_shared_compiled_style_sheet(SharedCompiledStyleSheet& sheet,
if (sheet.has_attachments())
return;
- StyleEngineFFI::style_engine_begin_sheet_rules_replacement(style_engine.host(), sheet.sheet_id().value());
- style_engine.finish_sheet_rules_replacement(sheet.sheet_id());
- auto& shared_compiled_style_sheets = style_computer.shared_compiled_style_sheets();
- shared_compiled_style_sheets.remove(sheet.key());
- if (shared_compiled_style_sheets.is_empty())
- shared_compiled_style_sheets.clear();
+ // Pages commonly insert a sheet they removed a moment ago (or a framework re-creates one with the same text).
+ // Keeping the compiled sheet for a while lets that arrival attach it again instead of compiling every rule anew,
+ // and since it holds the parsed contents, the parse cache answers the arriving text without parsing it again.
+ auto& detached = style_computer.detached_shared_compiled_style_sheets();
+ detached.append(sheet.key());
+ if (detached.size() > StyleComputer::max_detached_shared_compiled_style_sheets)
+ release_shared_compiled_style_sheet(detached.take_first(), style_computer);
}
bool stop_sharing_compiled_style_sheet(StyleSheetState& sheet)
diff --git a/Tests/LibWeb/TestSharedCompiledStyleSheet.cpp b/Tests/LibWeb/TestSharedCompiledStyleSheet.cpp
index 76337fd4698..549b3116700 100644
--- a/Tests/LibWeb/TestSharedCompiledStyleSheet.cpp
+++ b/Tests/LibWeb/TestSharedCompiledStyleSheet.cpp
@@ -41,14 +41,22 @@ static GC::Ref<Web::DOM::Element> append_style(Web::DOM::Document& document, Utf
return style;
}
-TEST_CASE(unique_style_text_is_not_retained_in_the_shared_sheet_cache)
+// Detaches enough other sheets that every sheet detached before them is released.
+static void push_out_detached_sheets(Web::DOM::Document& document)
+{
+ for (size_t index = 0; index < Web::CSS::StyleComputer::max_detached_shared_compiled_style_sheets; ++index)
+ append_style(document, Utf16String::formatted("/* filler {} */", index))->remove();
+}
+
+TEST_CASE(unique_style_text_is_retained_only_up_to_the_detached_sheet_limit)
{
auto document = create_document();
for (size_t index = 0; index < 128; ++index) {
auto style = append_style(document, Utf16String::formatted("/* {} */", index));
style->remove();
}
- EXPECT(document->style_computer().shared_compiled_style_sheets().is_empty());
+ EXPECT_EQ(document->style_computer().shared_compiled_style_sheets().size(), Web::CSS::StyleComputer::max_detached_shared_compiled_style_sheets);
+ EXPECT_EQ(document->style_computer().detached_shared_compiled_style_sheets().size(), Web::CSS::StyleComputer::max_detached_shared_compiled_style_sheets);
}
TEST_CASE(shared_sheet_contents_are_released_after_the_last_detachment)
@@ -65,13 +73,20 @@ TEST_CASE(shared_sheet_contents_are_released_after_the_last_detachment)
second->remove();
EXPECT_EQ(cache.size(), 1u);
EXPECT(contents);
+ auto sheet_id = cache.begin()->value->sheet_id();
third->remove();
- EXPECT(cache.is_empty());
- EXPECT(!contents);
+ // The detached sheet is kept, so the same text arriving again attaches it instead of compiling it anew.
+ EXPECT_EQ(cache.size(), 1u);
+ EXPECT(contents);
auto replacement = append_style(document, "div { color: red; }"_utf16);
EXPECT_EQ(cache.size(), 1u);
+ EXPECT(contents);
+ EXPECT_EQ(document->style_scope().style_sheets().last()->style_engine_sheet_id(), sheet_id);
+ EXPECT(document->style_computer().detached_shared_compiled_style_sheets().is_empty());
replacement->remove();
- EXPECT(cache.is_empty());
+ EXPECT(contents);
+ push_out_detached_sheets(document);
+ EXPECT(!contents);
}
TEST_CASE(shared_sheet_contents_are_released_after_copy_on_write)
@@ -82,9 +97,12 @@ TEST_CASE(shared_sheet_contents_are_released_after_copy_on_write)
EXPECT_EQ(cache.size(), 1u);
auto contents = cache.begin()->value->contents().make_weak_ptr();
MUST(document->style_scope().style_sheets().last()->insert_rule("span { color: red; }"_utf16, 0));
- EXPECT(cache.is_empty());
- EXPECT(!contents);
+ // The edited sheet no longer shares, and the shared sheet of the original text is kept like any detached one.
+ EXPECT(!document->style_scope().style_sheets().last()->shared_compiled_style_sheet());
+ EXPECT_EQ(document->style_computer().detached_shared_compiled_style_sheets().size(), 1u);
second->remove();
+ push_out_detached_sheets(document);
+ EXPECT(!contents);
}
TEST_CASE(first_instance_uses_shared_compiled_contents)
@@ -110,8 +128,9 @@ TEST_CASE(first_instance_uses_shared_compiled_contents)
EXPECT(contents);
EXPECT_EQ(second_sheet.shared_compiled_style_sheet(), shared);
second->remove();
+ EXPECT(contents);
+ push_out_detached_sheets(document);
EXPECT(!contents);
- EXPECT(document->style_computer().shared_compiled_style_sheets().is_empty());
}
TEST_CASE(occurrences_share_across_media_and_disabled_changes)
@@ -125,6 +144,7 @@ TEST_CASE(occurrences_share_across_media_and_disabled_changes)
EXPECT(shared);
EXPECT_EQ(second_sheet.shared_compiled_style_sheet(), shared);
auto sheet_id = first_sheet.style_engine_sheet_id();
+ auto contents = shared->contents().make_weak_ptr();
first_sheet.set_disabled(true);
second_sheet.set_media("print"_utf16);
EXPECT_EQ(first_sheet.shared_compiled_style_sheet(), shared);
@@ -141,7 +161,9 @@ TEST_CASE(occurrences_share_across_media_and_disabled_changes)
first->remove();
EXPECT_EQ(document->style_computer().shared_compiled_style_sheets().size(), 1u);
second->remove();
- EXPECT(document->style_computer().shared_compiled_style_sheets().is_empty());
+ EXPECT(contents);
+ push_out_detached_sheets(document);
+ EXPECT(!contents);
}
TEST_CASE(anonymous_layers_keep_distinct_identities_in_the_same_scope)
@@ -154,7 +176,9 @@ TEST_CASE(anonymous_layers_keep_distinct_identities_in_the_same_scope)
EXPECT(first_sheet.shared_compiled_style_sheet());
EXPECT(!second_sheet.shared_compiled_style_sheet());
EXPECT_NE(first_sheet.style_engine_sheet_id(), second_sheet.style_engine_sheet_id());
+ auto contents = first_sheet.shared_compiled_style_sheet()->contents().make_weak_ptr();
first->remove();
second->remove();
- EXPECT(document->style_computer().shared_compiled_style_sheets().is_empty());
+ push_out_detached_sheets(document);
+ EXPECT(!contents);
}
diff --git a/Tests/LibWeb/Text/expected/css/style-element-reinserted-after-removal.txt b/Tests/LibWeb/Text/expected/css/style-element-reinserted-after-removal.txt
new file mode 100644
index 00000000000..33c58e80de5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-element-reinserted-after-removal.txt
@@ -0,0 +1,8 @@
+inserted: color=rgb(1, 2, 3) background=rgba(0, 0, 0, 0)
+removed: color=rgb(0, 0, 0) background=rgba(0, 0, 0, 0)
+resized: color=rgb(0, 0, 0) background=rgba(0, 0, 0, 0)
+reinserted: color=rgb(1, 2, 3) background=rgb(4, 5, 6)
+after other sheets: color=rgb(0, 0, 0) background=rgba(0, 0, 0, 0)
+reinserted after other sheets: color=rgb(1, 2, 3) background=rgb(4, 5, 6)
+shadow: color=rgb(1, 2, 3) background=rgb(4, 5, 6)
+document after shadow: color=rgb(0, 0, 0) background=rgba(0, 0, 0, 0)
diff --git a/Tests/LibWeb/Text/input/css/style-element-reinserted-after-removal.html b/Tests/LibWeb/Text/input/css/style-element-reinserted-after-removal.html
new file mode 100644
index 00000000000..dcb87100b8c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-element-reinserted-after-removal.html
@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const frame = document.createElement("iframe");
+ frame.style.width = "200px";
+ frame.srcdoc = "<!DOCTYPE html><body><span class='target'>target</span>";
+ const loaded = new Promise(resolve => frame.onload = resolve);
+ document.body.append(frame);
+ await loaded;
+
+ const frameDocument = frame.contentDocument;
+ const target = frameDocument.querySelector(".target");
+ const css = ".target { color: rgb(1, 2, 3); } @media (min-width: 300px) { .target { background-color: rgb(4, 5, 6); } }";
+ const insert = text => {
+ const style = frameDocument.createElement("style");
+ style.textContent = text;
+ frameDocument.head.append(style);
+ return style;
+ };
+ const report = label => {
+ const computed = frame.contentWindow.getComputedStyle(target);
+ println(`${label}: color=${computed.color} background=${computed.backgroundColor}`);
+ };
+
+ let style = insert(css);
+ report("inserted");
+ style.remove();
+ report("removed");
+
+ // The viewport changes while no element holds the sheet.
+ frame.style.width = "400px";
+ frameDocument.body.offsetWidth;
+ report("resized");
+ style = insert(css);
+ report("reinserted");
+ style.remove();
+
+ // Enough other sheets come and go that the first one's compiled form is released.
+ for (let i = 0; i < 12; ++i)
+ insert(`.target { color: rgb(${i}, 0, 0); }`).remove();
+ report("after other sheets");
+ style = insert(css);
+ report("reinserted after other sheets");
+ style.remove();
+
+ // A sheet removed from the document is reused in a shadow tree.
+ const host = frameDocument.createElement("div");
+ frameDocument.body.append(host);
+ const shadow = host.attachShadow({ mode: "open" });
+ shadow.innerHTML = `<style>${css}</style><span class="target">shadow</span>`;
+ const shadowComputed = frame.contentWindow.getComputedStyle(shadow.querySelector(".target"));
+ println(`shadow: color=${shadowComputed.color} background=${shadowComputed.backgroundColor}`);
+ report("document after shadow");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js b/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js
index 5b1f5370493..9436234d5d8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js
+++ b/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js
@@ -28,7 +28,10 @@ function createStyleUpdateFixture(elementCount, scenario, seed, measure = false)
if (!Number.isInteger(elementCount) || elementCount < 100 || !["connected", "detached"].includes(scenario))
throw new Error("Invalid fixture configuration");
const style = document.createElement("style");
+ // Each fixture's sheet text is distinct, so that its construction compiles the sheet rather than reusing
+ // the compiled sheet an earlier fixture left behind.
style.textContent = `
+ /* ${scenario} ${seed} */
.fixture { color: rgb(10, 20, 30) }
.fixture.theme { color: rgb(40, 50, 60) }
.fixture .item { display: block; opacity: 1; margin: 0; padding: 0; border: 0 solid black }