Truly independent web browser
LibWeb: Skip the first contentful paint walk with nothing contentful
Andreas Klingd8c9aa15e74e
diff --git a/Libraries/LibWeb/PaintTiming/PaintTiming.cpp b/Libraries/LibWeb/PaintTiming/PaintTiming.cppindex 198a21151b3..8be5e46b3ad 100644--- a/Libraries/LibWeb/PaintTiming/PaintTiming.cpp+++ b/Libraries/LibWeb/PaintTiming/PaintTiming.cpp@@ -126,6 +126,7 @@ static bool svg_has_rendered_descendants(Layout::Node const& svg_box)// NB: This answers the question for the box of an element, or for a text node's box, which stands for the element// the text node is a child of. Generated content has boxes of its own, so a pseudo-element's content is found// the same way as an element's.+// NB: A box this can answer yes for must also make layout_rows_may_be_contentful() answer yes.static bool is_contentful(Layout::Node const& node){// An element target is contentful when one or more of the following apply:@@ -347,6 +348,11 @@ static PaintedContent find_painted_content(PaintableChecker const& checker, Painif (!viewport)return result;+ // OPTIMIZATION: This runs every frame until first contentful paint is reported, which a document with nothing that+ // can be contentful never does, so its boxes are not walked.+ if (result.has_non_default_content && !Layout::RustFFI::layout_rows_may_be_contentful(viewport->document_host(), &checker.read()))+ return result;+viewport->for_each_in_inclusive_subtree([&](Layout::Node const& node) {if (auto const* node_with_style = as_if<Layout::NodeWithStyle>(node); node_with_style && node_with_style->opacity() <= 0)return TraversalDecision::SkipChildrenAndContinue;diff --git a/Libraries/LibWeb/Rust/src/layout/row_reads.rs b/Libraries/LibWeb/Rust/src/layout/row_reads.rsindex 596ee94f285..e6561d30891 100644--- a/Libraries/LibWeb/Rust/src/layout/row_reads.rs+++ b/Libraries/LibWeb/Rust/src/layout/row_reads.rs@@ -175,6 +175,40 @@ impl RowSnapshot {self.node(id).is_some().then_some(id)}+ /// Whether a row is of a kind that may make an element contentful without an image observer: text that is not all+ /// white space, or a box that holds replaced content. A text row that does not carry its text yet counts.+ pub(crate) fn any_row_may_be_contentful(&self) -> bool {+ self.paintable.live_nodes().any(|(id, node)| match node.kind {+ kind if node_facts::kind_is_text(kind) => self.text_row_may_be_non_empty(id),+ NodeKind::ImageBox+ | NodeKind::SVGImageBox+ | NodeKind::CanvasBox+ | NodeKind::VideoBox+ | NodeKind::SVGSVGBox+ | NodeKind::TextInputBox => true,+ _ => false,+ })+ }++ fn text_row_may_be_non_empty(&self, id: NodeSlotId) -> bool {+ if self+ .text_awaiting_render+ .binary_search_by_key(&id.index, |row| row.index)+ .is_ok()+ {+ return true;+ }+ self.paintable+ .text(id)+ .and_then(|text| text.rendered.as_deref())+ .is_none_or(|rendered| {+ rendered+ .text+ .iter()+ .any(|unit| !matches!(unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20))+ })+ }+/// What the shell factory needs to make the layout node of the row in slot `id`, or none for a row that is gone or/// has no layout node.pub(crate) fn shell_facts(&self, id: NodeSlotId) -> Option<ShellFacts> {diff --git a/Libraries/LibWeb/Rust/src/layout/shell_reads.rs b/Libraries/LibWeb/Rust/src/layout/shell_reads.rsindex 0c253e99132..90daa9fe060 100644--- a/Libraries/LibWeb/Rust/src/layout/shell_reads.rs+++ b/Libraries/LibWeb/Rust/src/layout/shell_reads.rs@@ -161,6 +161,17 @@ pub extern "C" fn layout_row_bound_shell(host: &DocumentHost, read: &BegunRead,bound_shell(host, read, |identities| identities.bound_row(style_node))}+/// Whether a row of `host`'s document may make an element contentful, as paint timing defines it: by holding text that+/// is not all white space or replaced content, or by observing an image its style holds. It errs towards yes, as the+/// rows do not say whether an image is available, and it makes no layout node. It follows `is_contentful()` of+/// PaintTiming.cpp.+#[unsafe(no_mangle)]+pub extern "C" fn layout_rows_may_be_contentful(host: &DocumentHost, read: &BegunRead) -> bool {+ // NB: The rows come first, as bringing them up to date may give a row its image observers.+ let rows = rows(host, read);+ !host.host_tables().image_observer_sets.borrow().is_empty() || rows.any_row_may_be_contentful()+}+/// The content size of the committed box of the row the element with `style_node` is bound to, or none where the/// element has no row or its row no committed box. It makes no layout node, so a host callback a layout round makes/// on the render owner may ask it.diff --git a/Libraries/LibWeb/Rust/src/painting/published_frame.rs b/Libraries/LibWeb/Rust/src/painting/published_frame.rsindex 3f2f52fbce1..69fbf7781e6 100644--- a/Libraries/LibWeb/Rust/src/painting/published_frame.rs+++ b/Libraries/LibWeb/Rust/src/painting/published_frame.rs@@ -82,6 +82,14 @@ impl PublishedRows {.filter(|node| node.generation != 0 && node.generation == id.generation())}+ /// The nodes the slots hold, with the slot of each.+ pub(crate) fn live_nodes(&self) -> impl Iterator<Item = (NodeSlotId, &PaintNode)> {+ (0..self.nodes.slot_capacity()).filter_map(|index| {+ let node = self.nodes.get(index).filter(|node| node.generation != 0)?;+ Some((NodeSlotId::new(index as u32, node.generation), node))+ })+ }+pub(crate) fn paintable_data(&self, id: NodeSlotId) -> &PaintableData {assert!(!id.is_invalid(), "invalid paintable arena slot ID");let data = selfdiff --git a/Tests/LibWeb/Text/expected/PaintTiming/first-contentful-paint-after-frames-without-content.txt b/Tests/LibWeb/Text/expected/PaintTiming/first-contentful-paint-after-frames-without-content.txtnew file mode 100644index 00000000000..57e78141ca6--- /dev/null+++ b/Tests/LibWeb/Text/expected/PaintTiming/first-contentful-paint-after-frames-without-content.txt@@ -0,0 +1,12 @@+text: reported once contentful+generated text: reported once contentful+image: reported once contentful+background image: reported once contentful+border image: reported once contentful+canvas: reported once contentful+svg: reported once contentful+video poster: reported once contentful+input value: reported once contentful+text in a kept white space box: reported once contentful+background image on a kept box: reported once contentful+border image on a kept box: reported once contentfuldiff --git a/Tests/LibWeb/Text/input/PaintTiming/first-contentful-paint-after-frames-without-content.html b/Tests/LibWeb/Text/input/PaintTiming/first-contentful-paint-after-frames-without-content.htmlnew file mode 100644index 00000000000..1f2751b1304--- /dev/null+++ b/Tests/LibWeb/Text/input/PaintTiming/first-contentful-paint-after-frames-without-content.html@@ -0,0 +1,88 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ const image = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";++ const contentfulThings = {+ "text": document => {+ document.body.append("text");+ },+ "generated text": document => {+ const style = document.createElement("style");+ style.textContent = "body::before { content: 'text'; }";+ document.head.append(style);+ },+ "image": document => {+ document.body.innerHTML = `<img src="${image}" width="10" height="10">`;+ },+ "background image": document => {+ document.body.innerHTML = `<div style="width: 10px; height: 10px; background-image: url(${image})"></div>`;+ },+ "border image": document => {+ document.body.innerHTML = `<div style="width: 10px; height: 10px; border: 10px solid; border-image-source: url(${image})"></div>`;+ },+ "canvas": document => {+ document.body.innerHTML = `<canvas width="10" height="10"></canvas>`;+ document.querySelector("canvas").getContext("2d");+ },+ "svg": document => {+ document.body.innerHTML = `<svg width="10" height="10"><rect width="10" height="10"></rect></svg>`;+ },+ "video poster": document => {+ document.body.innerHTML = `<video width="10" height="10" poster="${image}"></video>`;+ },+ "input value": document => {+ document.body.innerHTML = `<input value="text">`;+ },+ "text in a kept white space box": document => {+ document.querySelector("#white-space").firstChild.data = "text";+ },+ "background image on a kept box": document => {+ document.querySelector("#box").style.backgroundImage = `url(${image})`;+ },+ "border image on a kept box": document => {+ const box = document.querySelector("#box");+ box.style.border = "10px solid";+ box.style.borderImageSource = `url(${image})`;+ },+ };++ function nextPaintEntry(window, name) {+ return new Promise(resolve => {+ const observer = new window.PerformanceObserver(list => {+ if (!list.getEntries().some(entry => entry.name === name))+ return;+ observer.disconnect();+ resolve();+ });+ observer.observe({ type: "paint", buffered: true });+ });+ }++ function nextAnimationFrame(window) {+ return new Promise(resolve => window.requestAnimationFrame(resolve));+ }++ asyncTest(async done => {+ for (const [name, addContentfulThing] of Object.entries(contentfulThings)) {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ const frameWindow = iframe.contentWindow;+ const frameDocument = iframe.contentDocument;++ // A background paints, so first paint is reported, while nothing is contentful for a few frames. White space+ // that has a box of its own is not contentful either.+ frameDocument.body.innerHTML = `<div id="box" style="width: 10px; height: 10px; background-color: green"></div><span id="white-space" style="white-space: pre"> </span>`;+ await nextPaintEntry(frameWindow, "first-paint");+ await nextAnimationFrame(frameWindow);+ await nextAnimationFrame(frameWindow);+ const reportedEarly = frameWindow.performance.getEntriesByName("first-contentful-paint").length !== 0;++ addContentfulThing(frameDocument);+ await nextPaintEntry(frameWindow, "first-contentful-paint");+ println(`${name}: ${reportedEarly ? "reported too early" : "reported once contentful"}`);+ iframe.remove();+ }+ done();+ });+</script>