Truly independent web browser
LibWeb: Mark display list chunks and report changes between dumps
Aliaksandr Kalenik20b6cf17088e
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 9aeaeabeed0..eb5bf0360d7 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -1926,11 +1926,24 @@ Utf16String Internals::dump_display_list(Bindings::DisplayListDumpOptions const&.text = options.text,.fonts = options.fonts,.record_ids = options.record_ids,+ .chunks = options.chunks,.raw_node_indices = options.raw_node_indices,.jsonl = options.format == Bindings::DisplayListDumpFormat::Jsonl,});}+Utf16String Internals::dump_display_list_changes(Bindings::DisplayListDumpOptions const& options)+{+ auto& document = window().associated_document();+ auto jsonl = document.dump_display_list({ .raw_node_indices = options.raw_node_indices, .jsonl = true }).to_utf8();+ Optional<StringView> previous_jsonl;+ if (m_display_list_dump_for_changes.has_value() && m_display_list_dump_for_changes->document_id == document.unique_id())+ previous_jsonl = m_display_list_dump_for_changes->jsonl;+ auto changes = Painting::display_list_dump_changes(previous_jsonl, jsonl);+ m_display_list_dump_for_changes = DisplayListDumpForChanges { document.unique_id(), move(jsonl) };+ return changes;+}+Utf16String Internals::dump_accessibility_tree(){return window().associated_document().dump_accessibility_tree_as_json();diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 3dbab12ddce..272d47b7006 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -229,6 +229,7 @@ public:bool has_animation_frame_callbacks();Utf16String dump_display_list(Bindings::DisplayListDumpOptions const&);+ Utf16String dump_display_list_changes(Bindings::DisplayListDumpOptions const&);Utf16String dump_accessibility_tree();String accessibility_character_offsets(GC::Ref<DOM::Node>);String dump_accessibility_node_data(GC::Ref<DOM::Node>);@@ -394,6 +395,12 @@ private:GC::Root<JS::Cell> m_actions_executor;bool m_actions_running { false };Optional<Utf16String> m_pending_action_test_result;++ struct DisplayListDumpForChanges {+ UniqueNodeID document_id;+ String jsonl;+ };+ Optional<DisplayListDumpForChanges> m_display_list_dump_for_changes;Vector<GC::Ref<InternalGamepad>> m_gamepads;Optional<HTML::DevToolsObjectTable> m_devtools_object_table;HTML::DevToolsLoggedObjects m_devtools_logged_objects;diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex b4072ab0ef3..446239aecf2 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -250,6 +250,8 @@ interface Internals {readonly attribute boolean hasAnimationFrameCallbacks;DOMString dumpDisplayList(optional DisplayListDumpOptions options = {});+ // What changed in the display list since the previous call for the document, which the first call only summarizes.+ DOMString dumpDisplayListChanges(optional DisplayListDumpOptions options = {});DOMString dumpAccessibilityTree();// The per-character offsets that the accessibility tree reports for a text node, as space-separated "x,y" pairs.DOMString accessibilityCharacterOffsets(Node node);@@ -549,6 +551,7 @@ dictionary DisplayListDumpOptions {boolean text = true;boolean fonts = false;boolean recordIds = false;+ boolean chunks = false;boolean rawNodeIndices = false;DisplayListDumpFormat format = "text";};diff --git a/Libraries/LibWeb/Painting/DisplayListDumpOptions.h b/Libraries/LibWeb/Painting/DisplayListDumpOptions.hindex 3def38f02ce..763e766cae0 100644--- a/Libraries/LibWeb/Painting/DisplayListDumpOptions.h+++ b/Libraries/LibWeb/Painting/DisplayListDumpOptions.h@@ -13,6 +13,7 @@ struct DisplayListDumpOptions {bool text { true };bool fonts { false };bool record_ids { false };+ bool chunks { false };bool raw_node_indices { false };bool jsonl { false };};diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex 6a3795ca2b7..df505177d55 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -266,6 +266,7 @@ Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document.text = options.text,.fonts = options.fonts,.record_ids = options.record_ids,+ .chunks = options.chunks,.raw_node_indices = options.raw_node_indices,.jsonl = options.jsonl,};@@ -273,6 +274,20 @@ Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Documentreturn move(context.dump);}+Utf16String display_list_dump_changes(Optional<StringView> previous_jsonl, StringView jsonl)+{+ Utf16String changes;+ Layout::RustFFI::painting_dump_changes(+ previous_jsonl.has_value() ? reinterpret_cast<u8 const*>(previous_jsonl->characters_without_null_termination()) : nullptr,+ previous_jsonl.has_value() ? previous_jsonl->length() : 0,+ previous_jsonl.has_value(),+ reinterpret_cast<u8 const*>(jsonl.characters_without_null_termination()),+ jsonl.length(),+ &changes,+ [](void* context, u8 const* bytes, size_t byte_count) { *static_cast<Utf16String*>(context) = Utf16String::from_utf8_without_validation(StringView { bytes, byte_count }); });+ return changes;+}+static void append_bytes_to_string_builder(void* context, u8 const* bytes, size_t byte_count){static_cast<StringBuilder*>(context)->append(StringView { bytes, byte_count });diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.h b/Libraries/LibWeb/Painting/PaintingRustBridge.hindex 40978c7e6c1..09a9b1d7931 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.h+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.h@@ -74,6 +74,7 @@ WEB_API void publish_rust_display_list_recording(Layout::BegunRead const&, DOM::WEB_API void take_recording_trace_if_pending(Layout::BegunRead const&, DOM::Document&);// Dumps the display list the document recorded last.WEB_API Utf16String serialize_painting_dump(Layout::BegunRead const&, DOM::Document const&, DisplayListDumpOptions const&);+WEB_API Utf16String display_list_dump_changes(Optional<StringView> previous_jsonl, StringView jsonl);WEB_API Layout::RustFFI::FfiVectorImageKey vector_image_key_to_ffi(VectorImageKey const&);// Has the compositor rasterize `paint` into `target` as `request` asks, which must be a shareable BGRA8888 bitmap withdiff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rsindex e1461cc74c2..3297a78cc6c 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs@@ -7,6 +7,7 @@use super::builder::{HEADER_SIZE, RecordedDisplayList, for_each_command, inline_clips_of, inline_transform_of, read_command,};+use super::chunks::ChunkId;use super::commands::*;use super::dump_format::{DumpNames, DumpValue, dumped_record_field, json_corner_radii, json_fields, json_float, json_float_point,@@ -52,6 +53,8 @@ pub struct FfiDisplayListDumpOptions {pub fonts: bool,/// Numbers every record, nested ones too, in tape order, and names the records of each layer by those numbers.pub record_ids: bool,+ /// Marks where each chunk of the tape starts, with its id, its record count and its size.+ pub chunks: bool,/// Names visual context nodes by their indices in the tree rather than by the order the dump first prints them in.pub raw_node_indices: bool,/// Writes one JSON object per line instead of text, with everything the other options add.@@ -223,6 +226,7 @@ pub unsafe extern "C" fn painting_dump(text: true,fonts: true,record_ids: true,+ chunks: true,..options}} else {@@ -339,6 +343,12 @@ pub unsafe extern "C" fn painting_dump(prints_glyph_run_texts: options.text,}),font_descriptions,+ chunk_starts: if options.chunks {+ ChunkStart::of_tape(&display_list)+ } else {+ HashMap::new()+ },+ current_chunk: None,};match layer_plan {Some(layer_plan) => records.dump_top_level_commands_with_their_layers(&display_list, &layer_plan),@@ -347,6 +357,34 @@ pub unsafe extern "C" fn painting_dump(callbacks.append_text(&main_thread, &output);}+/// Hands `append_text` what changed from the JSON Lines dump `previous`, if there is one, to the JSON Lines dump+/// `current` of the display list of the same document.+///+/// # Safety+///+/// `previous` must point to `previous_length` readable bytes where `has_previous` is set, and `current` to+/// `current_length`; `append_text` copies the report synchronously.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn painting_dump_changes(+ previous: *const u8,+ previous_length: usize,+ has_previous: bool,+ current: *const u8,+ current_length: usize,+ context: *mut c_void,+ append_text: extern "C" fn(context: *mut c_void, bytes: *const u8, byte_count: usize),+) {+ // SAFETY: Guaranteed by the caller.+ let previous = has_previous.then(|| unsafe { ak::slice_from_raw_parts(previous, previous_length) });+ // SAFETY: Guaranteed by the caller.+ let current = unsafe { ak::slice_from_raw_parts(current, current_length) };+ let report = super::dump_changes::display_list_dump_changes(+ previous.map(|previous| String::from_utf8_lossy(previous)).as_deref(),+ &String::from_utf8_lossy(current),+ );+ append_text(context, report.as_ptr(), report.len());+}+fn push_indent(output: &mut String, indent: usize) {output.extend(std::iter::repeat_n(' ', indent * 2));}@@ -794,6 +832,44 @@ struct RecordDump<'a> {record_notes: Option<RecordNotesInDumpOrder>,// The descriptions of the fonts the glyph runs draw with, by their ids, where the dump prints them.font_descriptions: Option<HashMap<u64, String>>,+ // The chunks of the tape by the index of their first run, where the dump marks them.+ chunk_starts: HashMap<usize, ChunkStart>,+ current_chunk: Option<String>,+}++/// Where a chunk of the tape starts, with what it holds.+struct ChunkStart {+ name: String,+ id: ChunkId,+ record_count: usize,+ byte_count: u32,+}++impl ChunkStart {+ fn of_tape(display_list: &DisplayListStorage) -> HashMap<usize, Self> {+ let (bytes, command_runs, chunks) = (display_list.bytes(), display_list.command_runs(), display_list.chunks());+ (0..chunks.len())+ .map(|chunk_index| {+ let runs = &command_runs[chunks.runs_of(chunk_index)];+ let mut record_count = 0;+ for run in runs {+ for_each_command_including_nested(+ &bytes[run.offset as usize..(run.offset + run.size) as usize],+ &mut |_, _, _| record_count += 1,+ );+ }+ (+ chunks.runs_of(chunk_index).start,+ Self {+ name: format!("k{}", chunk_index + 1),+ id: chunks.id(chunk_index),+ record_count,+ byte_count: runs.iter().map(|run| run.size).sum(),+ },+ )+ })+ .collect()+ }}/// Where a record sits: how deep in other records, in which of them and as what, and in which layer.@@ -829,9 +905,40 @@ fn nested_records_role_name(role: NestedRecordsRole) -> &'static str {}impl RecordDump<'_> {+ fn mark_chunk_starting_at(&mut self, run_index: usize) {+ let Some(chunk) = self.chunk_starts.get(&run_index) else {+ return;+ };+ if self.jsonl {+ push_json_line(+ self.output,+ serde_json::json!({+ "type": "chunk",+ "name": chunk.name,+ "id": format!("{:016x}{:016x}", chunk.id.0[0], chunk.id.0[1]),+ "first_record": self.record_count + 1,+ "records": chunk.record_count,+ "bytes": chunk.byte_count,+ }),+ );+ } else {+ writeln!(+ self.output,+ "Chunk {} id={:012x} records={} bytes={}",+ chunk.name,+ chunk.id.0[0] >> 16,+ chunk.record_count,+ chunk.byte_count+ )+ .unwrap();+ }+ self.current_chunk = Some(chunk.name.clone());+ }+fn dump_commands(&mut self, display_list: &DisplayListStorage) {let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());- for run in command_runs {+ for (run_index, run) in command_runs.iter().enumerate() {+ self.mark_chunk_starting_at(run_index);let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];self.dump_command_bytes(run_bytes, run.context, RecordPlace::TOP_LEVEL);}@@ -840,7 +947,8 @@ impl RecordDump<'_> {// Each top-level command starts with the layer it draws into. The records nested in it draw into the same layer.fn dump_top_level_commands_with_their_layers(&mut self, display_list: &DisplayListStorage, layer_plan: &LayerPlan) {let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());- for run in command_runs {+ for (run_index, run) in command_runs.iter().enumerate() {+ self.mark_chunk_starting_at(run_index);let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];for_each_command(run_bytes, |_, offset_in_run, payload| {let layer = layer_plan.layer_of_record(run.offset + offset_in_run as u32);@@ -1012,6 +1120,9 @@ impl RecordDump<'_> {if let Some(layer) = place.layer {record.insert("layer".into(), json!(format!("L{layer}")));}+ if let Some(chunk) = &self.current_chunk {+ record.insert("chunk".into(), json!(chunk));+ }record.insert("context".into(), json_context(self.names, context));let fields = command_fields(header.command_type, payload);record.insert("fields".into(), json_fields(&fields, self.names));diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump_changes.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump_changes.rsnew file mode 100644index 00000000000..bb3fd09f945--- /dev/null+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump_changes.rs@@ -0,0 +1,273 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What changed between two JSON Lines dumps of the display list of one document. Each dump builds the visual context+//! tree anew and names nodes and chunks by what the tape holds, so nodes are matched by their owner and role, records+//! by their owner, phase and command, and neither by an index.++use serde_json::{Map, Value};+use std::collections::{HashMap, HashSet};+use std::fmt::Write;++struct DumpedEntry {+ // The owner and role of a node, or the owner, phase and command of a record, with how many came before it.+ key: String,+ // What is compared, with the indices and the names that depend on them left out.+ content: String,+ // What the report prints of it.+ line: String,+}++#[derive(Default)]+struct ParsedDump {+ nodes: Vec<DumpedEntry>,+ records: Vec<DumpedEntry>,+ chunk_ids: Vec<String>,+}++// A node or resource name, such as s12, c3 or font2, as a placeholder, since names count up in print order.+fn without_numbered_names(text: &str) -> String {+ let mut result = String::with_capacity(text.len());+ let characters: Vec<char> = text.chars().collect();+ let mut index = 0;+ while index < characters.len() {+ let character = characters[index];+ let starts_word = index == 0 || !characters[index - 1].is_ascii_alphanumeric();+ if starts_word && character.is_ascii_alphabetic() {+ let word_end = (index..characters.len())+ .find(|&end| !characters[end].is_ascii_alphanumeric() && characters[end] != '_')+ .unwrap_or(characters.len());+ let word: String = characters[index..word_end].iter().collect();+ let letters_end = word.find(|c: char| c.is_ascii_digit()).unwrap_or(word.len());+ let (letters, digits) = word.split_at(letters_end);+ if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) {+ result.push_str(letters);+ result.push('#');+ } else {+ result.push_str(&word);+ }+ index = word_end;+ continue;+ }+ result.push(character);+ index += 1;+ }+ result+}++// The raw indices and ids of the names in a value, which differ from one dump to the next.+fn without_raw_indices(value: &Value) -> Value {+ match value {+ Value::Object(object) => Value::Object(+ object+ .iter()+ .filter(|(key, _)| key.as_str() != "raw")+ .map(|(key, value)| (key.clone(), without_raw_indices(value)))+ .collect::<Map<_, _>>(),+ ),+ Value::Array(values) => Value::Array(values.iter().map(without_raw_indices).collect()),+ value => value.clone(),+ }+}++fn string_of(object: &Map<String, Value>, key: &str) -> String {+ object.get(key).and_then(Value::as_str).unwrap_or_default().to_string()+}++fn node_role(description: &str) -> &str {+ let end = description.find(['=', ' ', '(', '[']).unwrap_or(description.len());+ &description[..end]+}++fn parse_dump(jsonl: &str) -> ParsedDump {+ let mut dump = ParsedDump::default();+ let mut key_counts: HashMap<String, usize> = HashMap::new();+ let mut numbered_key = |key: String| {+ let count = key_counts.entry(key.clone()).or_default();+ *count += 1;+ format!("{key}|{count}")+ };+ for line in jsonl.lines() {+ let Ok(Value::Object(object)) = serde_json::from_str::<Value>(line) else {+ continue;+ };+ match object.get("type").and_then(Value::as_str) {+ Some("node") => {+ let (kind, owner, description) = (+ string_of(&object, "kind"),+ string_of(&object, "owner"),+ string_of(&object, "description"),+ );+ let mut line = format!("[{}] {description}", string_of(&object, "name"));+ if !owner.is_empty() {+ write!(line, " ({owner})").unwrap();+ }+ dump.nodes.push(DumpedEntry {+ key: numbered_key(format!("node|{kind}|{owner}|{}", node_role(&description))),+ content: without_numbered_names(&description),+ line,+ });+ }+ Some("record") => {+ let (op, owner, phase) = (+ string_of(&object, "op"),+ string_of(&object, "owner"),+ string_of(&object, "phase"),+ );+ let compared: Map<String, Value> = ["context", "fields", "inline_clips", "inline_transform", "text"]+ .into_iter()+ .filter_map(|key| Some((key.to_string(), without_raw_indices(object.get(key)?))))+ .collect();+ let fields = object.get("fields").map(without_raw_indices).unwrap_or_default();+ let mut line = format!("{op} {fields}");+ if let Some(text) = object.get("text").and_then(Value::as_str) {+ write!(line, " text={text:?}").unwrap();+ }+ write!(line, " owner={owner} phase={phase}").unwrap();+ dump.records.push(DumpedEntry {+ key: numbered_key(format!("record|{op}|{owner}|{phase}")),+ content: without_numbered_names(&Value::Object(compared).to_string()),+ line,+ });+ }+ Some("chunk") => dump.chunk_ids.push(string_of(&object, "id")),+ _ => {}+ }+ }+ dump+}++fn report_entries(report: &mut String, label: &str, previous: &[DumpedEntry], current: &[DumpedEntry]) {+ let previous_by_key: HashMap<&str, &DumpedEntry> =+ previous.iter().map(|entry| (entry.key.as_str(), entry)).collect();+ let current_keys: HashSet<&str> = current.iter().map(|entry| entry.key.as_str()).collect();+ let mut lines = Vec::new();+ let (mut added, mut changed, mut unchanged) = (0, 0, 0);+ for entry in current {+ match previous_by_key.get(entry.key.as_str()) {+ None => {+ added += 1;+ lines.push(format!(" + {}", entry.line));+ }+ Some(previous_entry) if previous_entry.content != entry.content => {+ changed += 1;+ lines.push(format!(" ~ {}\n was {}", entry.line, previous_entry.line));+ }+ Some(_) => unchanged += 1,+ }+ }+ let mut removed = 0;+ for entry in previous {+ if !current_keys.contains(entry.key.as_str()) {+ removed += 1;+ lines.push(format!(" - {}", entry.line));+ }+ }+ writeln!(+ report,+ "{label}: {added} added, {removed} removed, {changed} changed, {unchanged} unchanged"+ )+ .unwrap();+ for line in lines {+ writeln!(report, "{line}").unwrap();+ }+}++/// What changed from the dump `previous` to the dump `current`, both JSON Lines dumps of the display list of one+/// document, or a summary of `current` where there is no previous one.+pub(crate) fn display_list_dump_changes(previous: Option<&str>, current: &str) -> String {+ let current = parse_dump(current);+ let mut report = String::new();+ let Some(previous) = previous.map(parse_dump) else {+ writeln!(+ report,+ "No previous dump of this document. This one, of {} nodes, {} records and {} chunks, is what the next one is compared with.",+ current.nodes.len(),+ current.records.len(),+ current.chunk_ids.len()+ )+ .unwrap();+ return report;+ };+ report_entries(&mut report, "Nodes", &previous.nodes, ¤t.nodes);+ report_entries(&mut report, "Records", &previous.records, ¤t.records);+ let previous_chunk_ids: HashSet<&String> = previous.chunk_ids.iter().collect();+ let kept_chunk_count = current+ .chunk_ids+ .iter()+ .filter(|id| previous_chunk_ids.contains(id))+ .count();+ writeln!(+ report,+ "Chunks: {kept_chunk_count} of {} kept their id",+ current.chunk_ids.len()+ )+ .unwrap();+ report+}++#[cfg(test)]+mod tests {+ use super::*;++ const BEFORE: &str = concat!(+ r#"{"type":"node","kind":"spatial","name":"s0","raw":0,"depth":0,"description":"transform=[1,0,0,1,0,0] origin=(0,0)","owner":"Viewport<#document>"}"#,+ "\n",+ r#"{"type":"node","kind":"spatial","name":"s1","raw":4,"depth":1,"description":"transform=[1,0,0,1,5,0] origin=(0,0)","owner":"BlockContainer<DIV>#moved"}"#,+ "\n",+ r#"{"type":"chunk","name":"k1","id":"aa"}"#,+ "\n",+ r#"{"type":"record","id":1,"op":"FillRect","context":{"spatial":{"name":"s1","raw":4}},"fields":{"rect":[0,0,10,10]},"owner":"BlockContainer<DIV>#moved","phase":"background"}"#,+ "\n",+ r#"{"type":"record","id":2,"op":"FillRect","context":{"spatial":{"name":"s0","raw":0}},"fields":{"rect":[0,0,5,5]},"owner":"BlockContainer<DIV>#gone","phase":"background"}"#,+ "\n",+ );++ const AFTER: &str = concat!(+ r#"{"type":"node","kind":"spatial","name":"s0","raw":0,"depth":0,"description":"transform=[1,0,0,1,0,0] origin=(0,0)","owner":"Viewport<#document>"}"#,+ "\n",+ r#"{"type":"node","kind":"spatial","name":"s1","raw":2,"depth":1,"description":"transform=[1,0,0,1,9,0] origin=(0,0)","owner":"BlockContainer<DIV>#moved"}"#,+ "\n",+ r#"{"type":"chunk","name":"k1","id":"bb"}"#,+ "\n",+ r#"{"type":"record","id":1,"op":"FillRect","context":{"spatial":{"name":"s1","raw":2}},"fields":{"rect":[0,0,10,10]},"owner":"BlockContainer<DIV>#moved","phase":"background"}"#,+ "\n",+ r#"{"type":"record","id":2,"op":"DrawGlyphRun","context":{"spatial":{"name":"s0","raw":0}},"fields":{"glyphs":2},"text":"hi","owner":"BlockContainer<DIV>#new","phase":"foreground"}"#,+ "\n",+ );++ #[test]+ fn nodes_and_records_are_matched_by_owner_not_by_index() {+ assert_eq!(+ display_list_dump_changes(Some(BEFORE), AFTER),+ concat!(+ "Nodes: 0 added, 0 removed, 1 changed, 1 unchanged\n",+ " ~ [s1] transform=[1,0,0,1,9,0] origin=(0,0) (BlockContainer<DIV>#moved)\n",+ " was [s1] transform=[1,0,0,1,5,0] origin=(0,0) (BlockContainer<DIV>#moved)\n",+ "Records: 1 added, 1 removed, 0 changed, 1 unchanged\n",+ " + DrawGlyphRun {\"glyphs\":2} text=\"hi\" owner=BlockContainer<DIV>#new phase=foreground\n",+ " - FillRect {\"rect\":[0,0,5,5]} owner=BlockContainer<DIV>#gone phase=background\n",+ "Chunks: 0 of 1 kept their id\n",+ )+ );+ }++ #[test]+ fn a_first_dump_is_summarized() {+ assert_eq!(+ display_list_dump_changes(None, BEFORE),+ "No previous dump of this document. This one, of 2 nodes, 2 records and 1 chunks, is what the next one is compared with.\n"+ );+ }++ #[test]+ fn numbered_names_are_compared_without_their_numbers() {+ assert_eq!(+ without_numbered_names("sticky scroller=s12 parent_sticky=s3 in c40 font2 x1y"),+ "sticky scroller=s# parent_sticky=s# in c# font# x1y"+ );+ }+}diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/mod.rs b/Libraries/LibWeb/Rust/src/painting/display_list/mod.rsindex cb8c870cf89..3fc0a081b1d 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/mod.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/mod.rs@@ -7,6 +7,7 @@//! The recorder that produces display lists, on top of the display list code the compositor shares.pub mod dump;+pub mod dump_changes;pub mod dump_format;pub mod recorder;diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 67d1d233bf4..09f15a35a23 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -1250,7 +1250,7 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString requestif (request == "dump-display-list") {if (auto doc = page->page().local_traversable()->active_document()) {- auto display_list_dump = doc->dump_display_list({ .owners = true, .text = true, .fonts = true, .record_ids = true, .jsonl = argument == "jsonl" });+ auto display_list_dump = doc->dump_display_list({ .owners = true, .text = true, .fonts = true, .record_ids = true, .chunks = true, .jsonl = argument == "jsonl" });dbgln("{}", display_list_dump.to_utf8());}return;diff --git a/Tests/LibWeb/Text/expected/display_list/chunks-and-changes-since-the-previous-dump.txt b/Tests/LibWeb/Text/expected/display_list/chunks-and-changes-since-the-previous-dump.txtnew file mode 100644index 00000000000..2a778e9bc43--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/chunks-and-changes-since-the-previous-dump.txt@@ -0,0 +1,19 @@+Chunk k1 id=<hash> records=3 bytes=120+No previous dump of this document. This one, of 4 nodes, 3 records and 1 chunks, is what the next one is compared with.++Nodes: 0 added, 0 removed, 1 changed, 3 unchanged+ ~ [s2] transform=[1,0,0,1,20,0] origin=(33,38) bounds=[8,28 50x20] (BlockContainer<DIV>#moved)+ was [s2] transform=[1,0,0,1,10,0] origin=(33,58) bounds=[8,48 50x20] (BlockContainer<DIV>#moved)+Records: 1 added, 1 removed, 2 changed, 0 unchanged+ ~ FillRect {"rect":[8,8,50,20],"color":"#ffff00ff"} owner=BlockContainer<DIV>#recolored phase=background+ was FillRect {"rect":[8,8,50,20],"color":"#008000ff"} owner=BlockContainer<DIV>#recolored phase=background+ + FillRect {"rect":[8,61,50,20],"color":"#000000ff"} owner=BlockContainer<DIV>#added phase=background+ ~ FillRect {"rect":[8,28,50,20],"color":"#ff0000ff"} owner=BlockContainer<DIV>#moved phase=background+ was FillRect {"rect":[8,48,50,20],"color":"#ff0000ff"} owner=BlockContainer<DIV>#moved phase=background+ - FillRect {"rect":[8,28,50,20],"color":"#0000ffff"} owner=BlockContainer<DIV>#removed phase=background+Chunks: 0 of 1 kept their id++Nodes: 0 added, 0 removed, 0 changed, 4 unchanged+Records: 0 added, 0 removed, 0 changed, 3 unchanged+Chunks: 1 of 1 kept their id+diff --git a/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt b/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txtindex 8fe9b004f9b..9565475a404 100644--- a/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt+++ b/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt@@ -1,4 +1,4 @@-types: {"header":1,"node":5,"layer":2,"record":6}+types: {"header":1,"node":5,"layer":2,"chunk":1,"record":6}header: ladybird-display-list-dump version 1 viewport [0,0,800,600] print-order 6 recordsrecord ids count up from 1: true{"type":"node","kind":"spatial","name":"s0","raw":0,"depth":0,"description":"transform=[1,0,0,1,0,0] origin=(0,0)","owner":"Viewport<#document>"}@@ -8,8 +8,8 @@ record ids count up from 1: true{"type":"node","kind":"effect","name":"e1","raw":1,"depth":1,"parent":"e0","space":"s1","description":"mask=[400,20 50x50] kind=alpha origin=css-mask-layers","owner":"BlockContainer<DIV>#masked"}{"type":"layer","name":"L0","kind":"base","rect":[0,0,800,600],"records":[[2,6]]}{"type":"layer","name":"L1","kind":"canvas","rect":[17,17,206,126],"records":[[1,1]],"shown_by_the_window_server":"clip=[0,0 800x600]"}-{"type":"record","id":2,"op":"FillRect","depth":0,"layer":"L0","context":{"spatial":{"name":"s2","raw":2},"effect":{"name":"e0","raw":0}},"fields":{"rect":[300,20,50,50],"color":"#008000ff"},"owner":"BlockContainer<DIV>#transformed","phase":"background"}-{"type":"record","id":3,"op":"DeclareMaskContent","depth":0,"layer":"L0","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[400,20,50,50],"effect":{"name":"e1","raw":1}},"owner":"BlockContainer<DIV>#masked","phase":"preamble"}-{"type":"record","id":4,"op":"PaintLinearGradient","depth":1,"parent":3,"role":"mask-content","layer":"L0","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"gradient_rect":[400,20,50,50],"gradient_angle":180,"color_stops":[{"color":"#000000ff","position":0},{"color":"#00000000","position":1}],"repeat_length":1,"interpolation_method":{"rectangular_color_space":"Srgb"}},"inline_clips":[{"kind":"Rect","rect":[400,20,50,50]}],"owner":"BlockContainer<DIV>#masked","phase":"preamble"}-{"type":"record","id":5,"op":"FillRect","depth":0,"layer":"L0","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[400,20,50,50],"color":"#0000ffff"},"owner":"BlockContainer<DIV>#masked","phase":"background"}+{"type":"record","id":2,"op":"FillRect","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s2","raw":2},"effect":{"name":"e0","raw":0}},"fields":{"rect":[300,20,50,50],"color":"#008000ff"},"owner":"BlockContainer<DIV>#transformed","phase":"background"}+{"type":"record","id":3,"op":"DeclareMaskContent","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[400,20,50,50],"effect":{"name":"e1","raw":1}},"owner":"BlockContainer<DIV>#masked","phase":"preamble"}+{"type":"record","id":4,"op":"PaintLinearGradient","depth":1,"parent":3,"role":"mask-content","layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"gradient_rect":[400,20,50,50],"gradient_angle":180,"color_stops":[{"color":"#000000ff","position":0},{"color":"#00000000","position":1}],"repeat_length":1,"interpolation_method":{"rectangular_color_space":"Srgb"}},"inline_clips":[{"kind":"Rect","rect":[400,20,50,50]}],"owner":"BlockContainer<DIV>#masked","phase":"preamble"}+{"type":"record","id":5,"op":"FillRect","depth":0,"layer":"L0","chunk":"k1","context":{"spatial":{"name":"s1","raw":1},"effect":{"name":"e1","raw":1}},"fields":{"rect":[400,20,50,50],"color":"#0000ffff"},"owner":"BlockContainer<DIV>#masked","phase":"background"}{"id":6,"text":"some text","has_font":true,"owner":"BlockContainer<P>","phase":"foreground"}diff --git a/Tests/LibWeb/Text/input/display_list/chunks-and-changes-since-the-previous-dump.html b/Tests/LibWeb/Text/input/display_list/chunks-and-changes-since-the-previous-dump.htmlnew file mode 100644index 00000000000..7f9f5d62bc5--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/chunks-and-changes-since-the-previous-dump.html@@ -0,0 +1,27 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ div { width: 50px; height: 20px; }+</style>+<div id="recolored" style="background: green"></div>+<div id="removed" style="background: blue"></div>+<div id="moved" style="background: red; transform: translateX(10px)"></div>+<script>+ test(() => {+ const output = [];+ const chunkLines = internals.dumpDisplayList({ chunks: true }).split("\n").filter(line => line.startsWith("Chunk "));+ output.push(...chunkLines.map(line => line.replace(/id=[0-9a-f]+/, "id=<hash>")));+ output.push(internals.dumpDisplayListChanges());+ document.getElementById("recolored").style.background = "yellow";+ document.getElementById("removed").remove();+ const added = document.createElement("div");+ added.id = "added";+ added.style.background = "black";+ document.body.appendChild(added);+ document.getElementById("moved").style.transform = "translateX(20px)";+ output.push(internals.dumpDisplayListChanges());+ output.push(internals.dumpDisplayListChanges());+ for (const line of output)+ println(line);+ });+</script>