Skip to content

Truly independent web browser

LibWeb: Add a JSON Lines form of the display list dump

Aliaksandr Kalenik2be6f721d9ea
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 5b873c256e0..6106771cb61 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -11761,7 +11761,7 @@ Utf16String Document::dump_display_list(Painting::DisplayListDumpOptions const&
if (paint_state().has_visual_context_tree(read))
schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::FreshTree);
- HTML::PaintConfig config { .records_whole_document = true, .notes_record_origins = options.owners || options.text };
+ HTML::PaintConfig config { .records_whole_document = true, .notes_record_origins = options.owners || options.text || options.jsonl };
if (!record_display_list(read, config, Painting::PaintCommandCacheMode::ReadOnly))
return "No display list"_utf16;
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 8aaddc4881b..9aeaeabeed0 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -1927,6 +1927,7 @@ Utf16String Internals::dump_display_list(Bindings::DisplayListDumpOptions const&
.fonts = options.fonts,
.record_ids = options.record_ids,
.raw_node_indices = options.raw_node_indices,
+ .jsonl = options.format == Bindings::DisplayListDumpFormat::Jsonl,
});
}
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index 147aa92030a..b4072ab0ef3 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -534,6 +534,7 @@ interface Internals {
enum InternalsNavigatorCompatibilityMode { "chrome", "gecko", "webkit" };
enum SpellingMenuItem { "none", "guess", "ignore", "learn" };
+enum DisplayListDumpFormat { "text", "jsonl" };
enum ScrollGesturePhase { "none", "ongoing", "momentum", "ended" };
enum MouseEventThroughUIProcessType { "mousedown", "mouseup", "mousemove", "mouseleave" };
@@ -549,6 +550,7 @@ dictionary DisplayListDumpOptions {
boolean fonts = false;
boolean recordIds = false;
boolean rawNodeIndices = false;
+ DisplayListDumpFormat format = "text";
};
dictionary LayoutTraceOptions {
diff --git a/Libraries/LibWeb/Painting/DisplayListDumpOptions.h b/Libraries/LibWeb/Painting/DisplayListDumpOptions.h
index b9d116317b3..3def38f02ce 100644
--- a/Libraries/LibWeb/Painting/DisplayListDumpOptions.h
+++ b/Libraries/LibWeb/Painting/DisplayListDumpOptions.h
@@ -14,6 +14,7 @@ struct DisplayListDumpOptions {
bool fonts { false };
bool record_ids { false };
bool raw_node_indices { false };
+ bool jsonl { false };
};
}
diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp
index 3d5231a1c42..6a3795ca2b7 100644
--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp
+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp
@@ -267,6 +267,7 @@ Utf16String serialize_painting_dump(Layout::BegunRead const& read, DOM::Document
.fonts = options.fonts,
.record_ids = options.record_ids,
.raw_node_indices = options.raw_node_indices,
+ .jsonl = options.jsonl,
};
Layout::RustFFI::painting_dump(document_host(document), &read, viewport_row_slot(read, document), device_viewport_rect, ffi_options, callbacks);
return move(context.dump);
diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs
index 4f485eba6ca..e1461cc74c2 100644
--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs
+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs
@@ -4,10 +4,13 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use super::builder::{HEADER_SIZE, RecordedDisplayList, for_each_command, inline_transform_of, read_command};
+use super::builder::{
+ HEADER_SIZE, RecordedDisplayList, for_each_command, inline_clips_of, inline_transform_of, read_command,
+};
use super::commands::*;
use super::dump_format::{
- DumpNames, DumpValue, dumped_record_field, path_description, push_clip_radii, push_fields, push_value,
+ DumpNames, DumpValue, dumped_record_field, json_corner_radii, json_fields, json_float, json_float_point,
+ json_float_rect, json_int_rect, json_name, path_description, push_clip_radii, push_fields, push_value,
};
use super::effect_clip_plan::EffectClipPlan;
use super::layers::{LayerPlan, LayerPlanInputs, build_layer_plan};
@@ -25,7 +28,7 @@ use crate::painting::paint_read::PaintRead;
use crate::painting::vector_image_records::display_list_holding_vector_image_records;
use crate::painting::visual_context::VisualContextTree;
use crate::painting::visual_context::VisualContextTreeDump;
-use crate::painting::visual_context::dump::SlotKind;
+use crate::painting::visual_context::dump::{DumpedNode, SlotKind, tree_section_text};
use crate::stage::MainThread;
use libcompositing_rust::host::RecordSpan;
use libcompositing_rust::visual_context::CompositorScrollTable;
@@ -51,6 +54,8 @@ pub struct FfiDisplayListDumpOptions {
pub record_ids: 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.
+ pub jsonl: bool,
}
/// What a display list dump asks the document. The fields are private: the callbacks are reached
@@ -212,6 +217,17 @@ pub unsafe extern "C" fn painting_dump(
options: FfiDisplayListDumpOptions,
callbacks: FfiPaintingDumpCallbacks,
) {
+ let options = if options.jsonl {
+ FfiDisplayListDumpOptions {
+ owners: true,
+ text: true,
+ fonts: true,
+ record_ids: true,
+ ..options
+ }
+ } else {
+ options
+ };
// SAFETY: Guaranteed by the entry point's contract.
let main_thread = unsafe { main_thread(host) };
// SAFETY: As above.
@@ -265,28 +281,56 @@ pub unsafe extern "C" fn painting_dump(
} else {
DumpNames::numbering_nodes_in_print_order()
};
- let mut output = visual_context_tree.dump_nodes_reachable_from_runs(command_runs, &mut names, |kind, index| {
- let owner = owners.owner(kind, index)?;
- Some(callbacks.debug_description(&main_thread, owner))
- });
- dump_compositor_scroll_table(&mut output, &mut names, visual_context_tree.compositor_scroll_table());
let record_ids = options
.record_ids
.then(|| RecordIdsOfTopLevelRecords::of(tape, command_runs));
+ let nodes = visual_context_tree.reachable_nodes_in_print_order(command_runs, &mut names, |kind, index| {
+ let owner = owners.owner(kind, index)?;
+ Some(callbacks.debug_description(&main_thread, owner))
+ });
+ let mut output = String::new();
+ if options.jsonl {
+ push_json_line(
+ &mut output,
+ serde_json::json!({
+ "type": "header",
+ "format": "ladybird-display-list-dump",
+ "version": 1,
+ "viewport": json_int_rect(device_viewport_rect),
+ "node_names": if options.raw_node_indices { "raw-indices" } else { "print-order" },
+ "record_count": record_ids.as_ref().map_or(0, |record_ids| record_ids.record_count),
+ }),
+ );
+ for node in &nodes {
+ push_json_line(&mut output, json_node(node));
+ }
+ } else {
+ output = tree_section_text(&nodes);
+ }
+ dump_compositor_scroll_table(
+ &mut output,
+ &mut names,
+ visual_context_tree.compositor_scroll_table(),
+ options.jsonl,
+ );
let layer_plan = dump_layers_if_every_canvas_and_video_kept_updating(
&mut output,
- tape,
- command_runs,
+ &display_list,
visual_context_tree,
host.scroll_state().device_offsets(),
device_viewport_rect,
record_ids.as_ref(),
+ options.jsonl,
);
- output.push_str("\nDisplayList:\n");
+ if !options.jsonl {
+ output.push_str("\nDisplayList:\n");
+ }
let mut records = RecordDump {
output: &mut output,
names: &mut names,
- next_record_id: options.record_ids.then_some(1),
+ jsonl: options.jsonl,
+ prints_record_ids: options.record_ids,
+ record_count: 0,
record_notes: record_notes.map(|notes| RecordNotesInDumpOrder {
notes,
next_index: 0,
@@ -328,8 +372,105 @@ fn push_field(output: &mut String, names: &mut DumpNames, name: &str, value: Dum
push_value(output, &value, names);
}
+fn json_node(node: &DumpedNode) -> serde_json::Value {
+ let mut object = serde_json::Map::new();
+ object.insert("type".into(), serde_json::json!("node"));
+ object.insert(
+ "kind".into(),
+ serde_json::json!(match node.kind {
+ SlotKind::Spatial => "spatial",
+ SlotKind::Clip => "clip",
+ SlotKind::Effect => "effect",
+ }),
+ );
+ object.insert("name".into(), serde_json::json!(node.name));
+ object.insert("raw".into(), serde_json::json!(node.index));
+ object.insert("depth".into(), serde_json::json!(node.depth));
+ for (key, value) in [
+ ("parent", &node.parent),
+ ("space", &node.space),
+ ("output_clip", &node.output_clip),
+ ] {
+ if let Some(value) = value {
+ object.insert(key.into(), serde_json::json!(value));
+ }
+ }
+ object.insert("description".into(), serde_json::json!(node.description));
+ if let Some(owner) = &node.owner {
+ object.insert("owner".into(), serde_json::json!(owner));
+ }
+ serde_json::Value::Object(object)
+}
+
+fn json_scroll_node(names: &mut DumpNames, table: &CompositorScrollTable, node_index: usize) -> serde_json::Value {
+ use serde_json::json;
+ let node = &table.nodes[node_index];
+ let mut object = serde_json::Map::new();
+ object.insert("type".into(), json!("scroll_node"));
+ object.insert(
+ "scroll_node".into(),
+ json_name(names.spatial(node.scroll_node_index), node.scroll_node_index.0),
+ );
+ object.insert(
+ "parent".into(),
+ json_name(
+ names.spatial(node.parent_scroll_node_index),
+ node.parent_scroll_node_index.0,
+ ),
+ );
+ object.insert("scrollport_rect".into(), json_int_rect(node.scrollport_rect));
+ object.insert("min_scroll_offset".into(), json_float_point(node.min_scroll_offset));
+ object.insert("max_scroll_offset".into(), json_float_point(node.max_scroll_offset));
+ object.insert("is_viewport".into(), json!(node.is_viewport));
+ if let Ok(container_index) = table
+ .snap_containers
+ .binary_search_by_key(&node.scroll_node_index, |container| container.scroll_node_index)
+ {
+ let container = &table.snap_containers[container_index];
+ let first_area_index = container.first_area_index as usize;
+ let areas: Vec<serde_json::Value> = table.snap_areas
+ [first_area_index..first_area_index + container.area_count as usize]
+ .iter()
+ .map(|area| {
+ json!({
+ "pseudo_element_type": area.pseudo_element_type,
+ "rect": json_float_rect(css_pixel_rect(area.rect)),
+ "align_x": area.align_x,
+ "align_y": area.align_y,
+ "always_stop": area.always_stop,
+ })
+ })
+ .collect();
+ object.insert(
+ "snap_container".into(),
+ json!({
+ "snapport": json_float_rect(css_pixel_rect(container.snapport)),
+ "min_scroll_offset": json_float_point(css_pixel_point(container.min_scroll_offset)),
+ "max_scroll_offset": json_float_point(css_pixel_point(container.max_scroll_offset)),
+ "strictness": container.strictness,
+ "snaps_x": container.snaps_x,
+ "snaps_y": container.snaps_y,
+ "horizontal_writing_mode": container.horizontal_writing_mode,
+ "areas": areas,
+ }),
+ );
+ }
+ serde_json::Value::Object(object)
+}
+
// Lists every row, unlike the tree section above it, which shows only the nodes that command runs reach.
-fn dump_compositor_scroll_table(output: &mut String, names: &mut DumpNames, table: &CompositorScrollTable) {
+fn dump_compositor_scroll_table(
+ output: &mut String,
+ names: &mut DumpNames,
+ table: &CompositorScrollTable,
+ jsonl: bool,
+) {
+ if jsonl {
+ for node_index in 0..table.nodes.len() {
+ push_json_line(output, json_scroll_node(names, table, node_index));
+ }
+ return;
+ }
if table.nodes.is_empty() {
return;
}
@@ -419,13 +560,14 @@ fn dump_compositor_scroll_table(output: &mut String, names: &mut DumpNames, tabl
// A list that draws no canvas, video or nested context gets no section.
fn dump_layers_if_every_canvas_and_video_kept_updating(
output: &mut String,
- tape: &[u8],
- command_runs: &[DisplayListCommandRun],
+ display_list: &DisplayListStorage,
tree: &VisualContextTree,
scroll_offsets: &[FloatPoint],
device_viewport_rect: IntRect,
record_ids: Option<&RecordIdsOfTopLevelRecords>,
+ jsonl: bool,
) -> Option<LayerPlan> {
+ let (tape, command_runs) = (display_list.bytes(), display_list.command_runs());
let summary = summarize(tape, command_runs);
let mut active_media = Vec::new();
for live_content_record in &summary.live_content_records {
@@ -450,6 +592,39 @@ fn dump_layers_if_every_canvas_and_video_kept_updating(
active_media: &active_media,
});
match layer_plan {
+ Ok(layer_plan) if jsonl => {
+ for (index, layer) in layer_plan.layers.iter().enumerate() {
+ let mut object = serde_json::Map::new();
+ object.insert("type".into(), serde_json::json!("layer"));
+ object.insert("name".into(), serde_json::json!(format!("L{index}")));
+ object.insert("kind".into(), serde_json::json!(layer.kind.to_string()));
+ object.insert("rect".into(), json_int_rect(layer.rect));
+ if let Some(record_ids) = record_ids {
+ object.insert("records".into(), record_ids.json_spans(&layer.record_spans));
+ }
+ match &layer.window_server_placement {
+ Some(Ok(placement)) => {
+ object.insert(
+ "shown_by_the_window_server".into(),
+ serde_json::json!(placement.to_string()),
+ );
+ }
+ Some(Err(rejection)) => {
+ object.insert("replayed".into(), serde_json::json!(rejection.to_string()));
+ }
+ None => {}
+ }
+ push_json_line(output, serde_json::Value::Object(object));
+ }
+ Some(layer_plan)
+ }
+ Err(unlayered_reason) if jsonl => {
+ push_json_line(
+ output,
+ serde_json::json!({ "type": "unlayered", "reason": unlayered_reason.to_string() }),
+ );
+ None
+ }
Ok(layer_plan) => {
output.push_str("\nLayers:\n");
layer_plan
@@ -499,6 +674,15 @@ impl RecordIdsOfTopLevelRecords {
self.ids_by_offset[&offset]
}
+ fn json_spans(&self, spans: &[RecordSpan]) -> serde_json::Value {
+ serde_json::Value::Array(
+ spans
+ .iter()
+ .map(|span| serde_json::json!([self.id_at(span.begin_offset), self.id_at(span.end_offset) - 1]))
+ .collect(),
+ )
+ }
+
// Spans of top-level records as the ranges of the numbers of every record they hold.
fn describe_spans(&self, spans: &[RecordSpan]) -> String {
let mut text = String::new();
@@ -603,19 +787,53 @@ struct RecordNotesInDumpOrder {
struct RecordDump<'a> {
output: &'a mut String,
names: &'a mut DumpNames,
- // The number the next record is printed with, while records are numbered.
- next_record_id: Option<u32>,
+ jsonl: bool,
+ prints_record_ids: bool,
+ // How many records were dumped so far, which numbers the next one.
+ record_count: u32,
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>>,
}
+/// Where a record sits: how deep in other records, in which of them and as what, and in which layer.
+#[derive(Clone, Copy)]
+struct RecordPlace {
+ indent: usize,
+ depth: usize,
+ nested_in: Option<(u32, NestedRecordsRole)>,
+ layer: Option<usize>,
+ // The records of an SVG image take the origin of the record that draws the image.
+ origin_of_enclosing_vector_image: Option<Option<RecordOrigin>>,
+}
+
+impl RecordPlace {
+ const TOP_LEVEL: Self = Self {
+ indent: 0,
+ depth: 0,
+ nested_in: None,
+ layer: None,
+ origin_of_enclosing_vector_image: None,
+ };
+}
+
+fn nested_records_role_name(role: NestedRecordsRole) -> &'static str {
+ match role {
+ NestedRecordsRole::IsolatedGroupContent => "content",
+ NestedRecordsRole::IsolatedGroupMask => "mask",
+ NestedRecordsRole::RepeatedTile => "tile",
+ NestedRecordsRole::MaskContent => "mask-content",
+ NestedRecordsRole::PatternTile => "pattern-tile",
+ NestedRecordsRole::VectorImage => "vector-image",
+ }
+}
+
impl RecordDump<'_> {
fn dump_commands(&mut self, display_list: &DisplayListStorage) {
let (bytes, command_runs) = (display_list.bytes(), display_list.command_runs());
for run in command_runs {
let run_bytes = &bytes[run.offset as usize..(run.offset + run.size) as usize];
- self.dump_command_bytes(run_bytes, run.context, 0, None);
+ self.dump_command_bytes(run_bytes, run.context, RecordPlace::TOP_LEVEL);
}
}
@@ -625,10 +843,19 @@ impl RecordDump<'_> {
for run in command_runs {
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_label = format!("L{} ", layer_plan.layer_of_record(run.offset + offset_in_run as u32));
+ let layer = layer_plan.layer_of_record(run.offset + offset_in_run as u32);
let record_bytes = &run_bytes[offset_in_run..offset_in_run + HEADER_SIZE + payload.len()];
+ let place = RecordPlace {
+ layer: Some(layer),
+ ..RecordPlace::TOP_LEVEL
+ };
+ if self.jsonl {
+ self.dump_command_bytes(record_bytes, run.context, place);
+ return;
+ }
+ let layer_label = format!("L{layer} ");
let record_dump_start = self.output.len();
- self.dump_command_bytes(record_bytes, run.context, 0, None);
+ self.dump_command_bytes(record_bytes, run.context, place);
let record_dump = self.output.split_off(record_dump_start);
for (line_index, line) in record_dump.split_inclusive('\n').enumerate() {
if line_index == 0 {
@@ -642,16 +869,9 @@ impl RecordDump<'_> {
}
}
- // The records of an SVG image take the origin of the record that draws the image.
- fn dump_command_bytes(
- &mut self,
- command_bytes: &[u8],
- context: ContextRef,
- base_indent: usize,
- origin_of_enclosing_vector_image: Option<Option<RecordOrigin>>,
- ) {
+ fn dump_command_bytes(&mut self, command_bytes: &[u8], context: ContextRef, place: RecordPlace) {
for_each_command(command_bytes, |header, _, payload| {
- let note = match origin_of_enclosing_vector_image {
+ let note = match place.origin_of_enclosing_vector_image {
Some(origin) => RecordNote {
origin,
glyph_run_text: None,
@@ -662,33 +882,31 @@ impl RecordDump<'_> {
.map(RecordNotesInDumpOrder::take_next)
.unwrap_or_default(),
};
- push_indent(self.output, base_indent);
- if let Some(record_id) = &mut self.next_record_id {
- write!(self.output, "#{record_id} ").unwrap();
- *record_id += 1;
- }
- write!(self.output, "{}@", header.command_type.name()).unwrap();
- write_context(self.output, self.names, context);
- let fields = command_fields(header.command_type, payload);
- push_fields(self.output, &fields, self.names);
- if header.inline_clip_count > 0 {
- dump_inline_clips(self.output, self.names, header, payload);
- }
- if let Some(transform) = inline_transform_of(header, payload) {
- self.output.push_str(" inline_transform=");
- push_affine_transform(self.output, transform);
+ self.record_count += 1;
+ let record_id = self.record_count;
+ if self.jsonl {
+ self.push_json_record(record_id, header, payload, context, place, &note);
+ } else {
+ push_indent(self.output, place.indent);
+ if self.prints_record_ids {
+ write!(self.output, "#{record_id} ").unwrap();
+ }
+ write!(self.output, "{}@", header.command_type.name()).unwrap();
+ write_context(self.output, self.names, context);
+ let fields = command_fields(header.command_type, payload);
+ push_fields(self.output, &fields, self.names);
+ if header.inline_clip_count > 0 {
+ dump_inline_clips(self.output, self.names, header, payload);
+ }
+ if let Some(transform) = inline_transform_of(header, payload) {
+ self.output.push_str(" inline_transform=");
+ push_affine_transform(self.output, transform);
+ }
+ self.push_note(header.command_type, payload, &note);
+ self.output.push('\n');
}
- self.push_note(header.command_type, payload, &note);
- self.output.push('\n');
- self.dump_records_inside(
- header.command_type,
- payload,
- context,
- base_indent + 1,
- origin_of_enclosing_vector_image,
- note.origin,
- );
+ self.dump_records_inside(header.command_type, payload, context, place, record_id, note.origin);
});
}
@@ -697,8 +915,8 @@ impl RecordDump<'_> {
command_type: DisplayListCommandType,
payload: &[u8],
context: ContextRef,
- indent: usize,
- origin_of_enclosing_vector_image: Option<Option<RecordOrigin>>,
+ place: RecordPlace,
+ record_id: u32,
origin: Option<RecordOrigin>,
) {
for_each_nested_record_span(command_type, payload, |role, span| {
@@ -710,25 +928,42 @@ impl RecordDump<'_> {
| NestedRecordsRole::MaskContent
| NestedRecordsRole::VectorImage => None,
};
- let mut nested_indent = indent;
- if let Some(label) = label {
- push_indent(self.output, indent);
+ let mut nested_indent = place.indent + 1;
+ if let Some(label) = label
+ && !self.jsonl
+ {
+ push_indent(self.output, place.indent + 1);
self.output.push_str(label);
nested_indent += 1;
}
let origin_of_enclosing_vector_image = match role {
- NestedRecordsRole::VectorImage => origin_of_enclosing_vector_image.or(Some(origin)),
- _ => origin_of_enclosing_vector_image,
+ NestedRecordsRole::VectorImage => place.origin_of_enclosing_vector_image.or(Some(origin)),
+ _ => place.origin_of_enclosing_vector_image,
};
self.dump_command_bytes(
span_bytes(payload, span),
context,
- nested_indent,
- origin_of_enclosing_vector_image,
+ RecordPlace {
+ indent: nested_indent,
+ depth: place.depth + 1,
+ nested_in: Some((record_id, role)),
+ layer: place.layer,
+ origin_of_enclosing_vector_image,
+ },
);
});
}
+ fn font_description(&self, command_type: DisplayListCommandType, payload: &[u8]) -> Option<&String> {
+ let font_descriptions = self.font_descriptions.as_ref()?;
+ let font_id = match command_type {
+ DisplayListCommandType::DrawGlyphRun => read_command::<DrawGlyphRun>(payload).font_id,
+ DisplayListCommandType::PaintTextShadow => read_command::<PaintTextShadow>(payload).font_id,
+ _ => return None,
+ };
+ font_descriptions.get(&font_id.0)
+ }
+
// What the recording noted of the record, and the font a glyph run draws with: the text, the font and then the
// origin.
fn push_note(&mut self, command_type: DisplayListCommandType, payload: &[u8], note: &RecordNote) {
@@ -738,15 +973,9 @@ impl RecordDump<'_> {
if prints_glyph_run_texts && let Some(text) = &note.glyph_run_text {
push_glyph_run_text(self.output, text);
}
- if let Some(font_descriptions) = &self.font_descriptions {
- let font_id = match command_type {
- DisplayListCommandType::DrawGlyphRun => Some(read_command::<DrawGlyphRun>(payload).font_id),
- DisplayListCommandType::PaintTextShadow => Some(read_command::<PaintTextShadow>(payload).font_id),
- _ => None,
- };
- if let Some(description) = font_id.and_then(|font_id| font_descriptions.get(&font_id.0)) {
- write!(self.output, " font=\"{description}\"").unwrap();
- }
+ if let Some(description) = self.font_description(command_type, payload) {
+ let font = format!(" font=\"{description}\"");
+ self.output.push_str(&font);
}
let Some(origin) = note.origin.filter(|_| prints_owners) else {
return;
@@ -760,6 +989,109 @@ impl RecordDump<'_> {
}
write!(self.output, " phase={}", origin.phase).unwrap();
}
+
+ fn push_json_record(
+ &mut self,
+ record_id: u32,
+ header: &DisplayListCommandHeader,
+ payload: &[u8],
+ context: ContextRef,
+ place: RecordPlace,
+ note: &RecordNote,
+ ) {
+ use serde_json::{Value, json};
+ let mut record = serde_json::Map::new();
+ record.insert("type".into(), json!("record"));
+ record.insert("id".into(), json!(record_id));
+ record.insert("op".into(), json!(header.command_type.name()));
+ record.insert("depth".into(), json!(place.depth));
+ if let Some((parent_id, role)) = place.nested_in {
+ record.insert("parent".into(), json!(parent_id));
+ record.insert("role".into(), json!(nested_records_role_name(role)));
+ }
+ if let Some(layer) = place.layer {
+ record.insert("layer".into(), json!(format!("L{layer}")));
+ }
+ 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));
+ if header.inline_clip_count > 0 {
+ record.insert("inline_clips".into(), json_inline_clips(self.names, header, payload));
+ }
+ if let Some(transform) = inline_transform_of(header, payload) {
+ record.insert(
+ "inline_transform".into(),
+ Value::Array(transform.values.iter().map(|value| json_float(*value)).collect()),
+ );
+ }
+ if let Some(text) = &note.glyph_run_text {
+ record.insert("text".into(), json!(text));
+ }
+ if let Some(description) = self.font_description(header.command_type, payload) {
+ record.insert("font".into(), json!(description));
+ }
+ if let Some(origin) = note.origin {
+ let owner_label = self
+ .record_notes
+ .as_ref()
+ .and_then(|notes| notes.owner_labels.get(&origin.owner));
+ if let Some(owner_label) = owner_label {
+ record.insert("owner".into(), json!(owner_label));
+ }
+ record.insert("phase".into(), json!(origin.phase));
+ }
+ push_json_line(self.output, Value::Object(record));
+ }
+}
+
+fn push_json_line(output: &mut String, value: serde_json::Value) {
+ output.push_str(&value.to_string());
+ output.push('\n');
+}
+
+fn json_context(names: &mut DumpNames, context: ContextRef) -> serde_json::Value {
+ let mut object = serde_json::Map::new();
+ object.insert(
+ "spatial".into(),
+ json_name(names.spatial(context.spatial), context.spatial.0),
+ );
+ if !context.clip.is_none() {
+ object.insert("clip".into(), json_name(names.clip(context.clip), context.clip.0));
+ }
+ if !context.effect.is_none() {
+ object.insert(
+ "effect".into(),
+ json_name(names.effect(context.effect), context.effect.0),
+ );
+ }
+ serde_json::Value::Object(object)
+}
+
+fn json_inline_clips(names: &mut DumpNames, header: &DisplayListCommandHeader, payload: &[u8]) -> serde_json::Value {
+ use serde_json::json;
+ serde_json::Value::Array(
+ inline_clips_of(header, payload)
+ .map(|clip| {
+ let mut object = serde_json::Map::new();
+ object.insert("kind".into(), json!(format!("{:?}", clip.kind)));
+ object.insert("rect".into(), json_float_rect(clip.clip_rect_or_path_device_bounds));
+ if clip.kind == InlineClipKind::Path {
+ let path = Path::from_serialized_bytes(span_bytes(payload, clip.path_data));
+ object.insert("path".into(), json!(path_description(&path)));
+ object.insert("winding_rule".into(), json!(format!("{:?}", clip.path_winding_rule)));
+ } else if clip.corner_radii.has_any_radius() {
+ object.insert("corner_radii".into(), json_corner_radii(clip.corner_radii));
+ }
+ if clip.mode == ClipMode::Difference {
+ object.insert("mode".into(), json!("difference"));
+ }
+ if clip.has_own_space {
+ object.insert("space".into(), json_name(names.spatial(clip.space), clip.space.0));
+ }
+ serde_json::Value::Object(object)
+ })
+ .collect(),
+ )
}
impl RecordNotesInDumpOrder {
diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump_format.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump_format.rs
index 2765e6cd4c7..943c4375921 100644
--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump_format.rs
+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump_format.rs
@@ -619,3 +619,103 @@ pub(crate) fn push_fields(output: &mut String, fields: &[(&'static str, DumpValu
push_value(output, value, names);
}
}
+
+/// A float as the shortest decimal that reads back as it, which JSON holds as a number, or as text where it is not
+/// finite.
+pub(crate) fn json_float(value: f32) -> serde_json::Value {
+ let text = crate::painting::dump::format_float_like_ak(value);
+ match text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) {
+ Some(number) => serde_json::Value::Number(number),
+ None => serde_json::Value::String(text),
+ }
+}
+
+pub(crate) fn json_color(color: Color) -> serde_json::Value {
+ serde_json::Value::String(format!(
+ "#{:02x}{:02x}{:02x}{:02x}",
+ color.red(),
+ color.green(),
+ color.blue(),
+ color.alpha()
+ ))
+}
+
+pub(crate) fn json_int_rect(rect: IntRect) -> serde_json::Value {
+ serde_json::json!([rect.x, rect.y, rect.width, rect.height])
+}
+
+pub(crate) fn json_float_rect(rect: FloatRect) -> serde_json::Value {
+ serde_json::json!([
+ json_float(rect.x),
+ json_float(rect.y),
+ json_float(rect.width),
+ json_float(rect.height)
+ ])
+}
+
+pub(crate) fn json_float_point(point: FloatPoint) -> serde_json::Value {
+ serde_json::json!([json_float(point.x), json_float(point.y)])
+}
+
+pub(crate) fn json_corner_radii(radii: CornerRadii) -> serde_json::Value {
+ serde_json::Value::Array(
+ [radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left]
+ .iter()
+ .map(|corner| serde_json::json!([corner.horizontal_radius, corner.vertical_radius]))
+ .collect(),
+ )
+}
+
+/// A name the dump gives what the tape names by an index or id, with that index or id alongside.
+pub(crate) fn json_name(name: String, raw: impl Into<serde_json::Value>) -> serde_json::Value {
+ serde_json::json!({ "name": name, "raw": raw.into() })
+}
+
+pub(crate) fn json_value(value: &DumpValue, names: &mut DumpNames) -> serde_json::Value {
+ use serde_json::{Value, json};
+ match value {
+ DumpValue::Bool(value) => json!(value),
+ DumpValue::Integer(value) => json!(value),
+ DumpValue::Float(value) => json_float(*value),
+ DumpValue::Double(value) => {
+ serde_json::Number::from_f64(*value).map_or_else(|| Value::String(value.to_string()), Value::Number)
+ }
+ DumpValue::Color(value) => json_color(*value),
+ DumpValue::IntPoint(value) => json!([value.x, value.y]),
+ DumpValue::FloatPoint(value) => json_float_point(*value),
+ DumpValue::IntSize(value) => json!([value.width, value.height]),
+ DumpValue::FloatSize(value) => json!([json_float(value.width), json_float(value.height)]),
+ DumpValue::IntRect(value) => json_int_rect(*value),
+ DumpValue::FloatRect(value) => json_float_rect(*value),
+ DumpValue::CornerRadii(value) => json_corner_radii(*value),
+ DumpValue::AffineTransform(value) => {
+ Value::Array(value.values.iter().map(|value| json_float(*value)).collect())
+ }
+ DumpValue::Name(value) => json!(value),
+ DumpValue::SpatialNode(index) => json_name(names.spatial(*index), index.0),
+ DumpValue::EffectNode(index) => json_name(names.effect(*index), index.0),
+ DumpValue::Resource(kind, raw) => json_name(names.resource(*kind, *raw), *raw),
+ DumpValue::TimeOfThisProcess(raw) => json_name(names.time_of_this_process(*raw), *raw),
+ DumpValue::Path(description) => json!(description),
+ DumpValue::Filter(filter) => {
+ let mut text = String::new();
+ push_filter(&mut text, filter, names);
+ json!(text)
+ }
+ DumpValue::Unreadable(byte_count) => json!({ "unreadable_bytes": byte_count }),
+ DumpValue::Count(count) => json!(count),
+ DumpValue::List(values) => Value::Array(values.iter().map(|value| json_value(value, names)).collect()),
+ DumpValue::GradientColorStop(color, position) => {
+ json!({ "color": json_color(*color), "position": json_float(*position) })
+ }
+ DumpValue::Fields(fields) => json_fields(fields, names),
+ }
+}
+
+pub(crate) fn json_fields(fields: &[(&'static str, DumpValue)], names: &mut DumpNames) -> serde_json::Value {
+ let mut object = serde_json::Map::new();
+ for (name, value) in fields {
+ object.insert((*name).to_string(), json_value(value, names));
+ }
+ serde_json::Value::Object(object)
+}
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs
index 9e48db23135..1aae999278f 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/dump.rs
@@ -82,12 +82,12 @@ pub trait VisualContextTreeDump {
fn describe_effect_node(&self, index: EffectNodeIndex, names: &mut DumpNames) -> String;
// The nodes the runs record under, each tree in first-seen order. An effect's output clip
// chain counts as reachable, since replay enters it before the effect.
- fn dump_nodes_reachable_from_runs(
+ fn reachable_nodes_in_print_order(
&self,
command_runs: &[DisplayListCommandRun],
names: &mut DumpNames,
owner_label: impl FnMut(SlotKind, u32) -> Option<String>,
- ) -> String;
+ ) -> Vec<DumpedNode>;
}
impl VisualContextTreeDump for VisualContextTree {
@@ -305,12 +305,12 @@ impl VisualContextTreeDump for VisualContextTree {
text
}
- fn dump_nodes_reachable_from_runs(
+ fn reachable_nodes_in_print_order(
&self,
command_runs: &[DisplayListCommandRun],
names: &mut DumpNames,
mut owner_label: impl FnMut(SlotKind, u32) -> Option<String>,
- ) -> String {
+ ) -> Vec<DumpedNode> {
let effect_clips = crate::painting::display_list::effect_clip_plan::EffectClipPlan::new(self, command_runs)
.expect("dumped command runs reference live visual context nodes");
let mut visited_spatial_nodes: HashSet<u32> = HashSet::new();
@@ -357,100 +357,132 @@ impl VisualContextTreeDump for VisualContextTree {
}
}
- let mut text = String::from("AccumulatedVisualContext Tree:\n");
- let mut append_owner = |text: &mut String, kind: SlotKind, index: u32| {
- if let Some(label) = owner_label(kind, index) {
- let _ = write!(text, " ({label})");
- }
- text.push('\n');
- };
-
- fn dump_subtree(
- text: &mut String,
- names: &mut DumpNames,
- children: &HashMap<u32, Vec<u32>>,
- node_line: &impl Fn(u32, &mut DumpNames) -> String,
- append_owner: &mut impl FnMut(&mut String, u32),
- node_index: u32,
- indent: usize,
- ) {
- text.push_str(&" ".repeat(indent * 2));
- text.push_str(&node_line(node_index, names));
- append_owner(text, node_index);
- if let Some(child_indices) = children.get(&node_index) {
- for child in child_indices {
- dump_subtree(text, names, children, node_line, append_owner, *child, indent + 1);
- }
- }
- }
-
- text.push_str(" spatial:\n");
- dump_subtree(
- &mut text,
- names,
- &spatial_children,
- &|index: u32, names: &mut DumpNames| {
- let name = names.spatial(SpatialNodeIndex(index));
- format!(
- "[{name}] {}",
- self.describe_spatial_node(SpatialNodeIndex(index), names)
- )
- },
- &mut |text: &mut String, index: u32| append_owner(text, SlotKind::Spatial, index),
- VISUAL_VIEWPORT_NODE_INDEX.0,
- 2,
- );
- if !clip_roots.is_empty() {
- text.push_str(" clips:\n");
- for root in clip_roots {
- dump_subtree(
- &mut text,
- names,
- &clip_children,
- &|index: u32, names: &mut DumpNames| {
+ let mut nodes = Vec::new();
+ let mut walk = |kind: SlotKind,
+ root: u32,
+ children: &HashMap<u32, Vec<u32>>,
+ names: &mut DumpNames,
+ nodes: &mut Vec<DumpedNode>| {
+ let mut pending = vec![(root, 0)];
+ while let Some((index, depth)) = pending.pop() {
+ let mut node = match kind {
+ SlotKind::Spatial => {
+ let name = names.spatial(SpatialNodeIndex(index));
+ let parent = (index != VISUAL_VIEWPORT_NODE_INDEX.0)
+ .then(|| names.spatial(self.spatial_nodes[index as usize].parent));
+ DumpedNode {
+ kind,
+ index,
+ name,
+ depth,
+ parent,
+ space: None,
+ output_clip: None,
+ description: self.describe_spatial_node(SpatialNodeIndex(index), names),
+ owner: None,
+ }
+ }
+ SlotKind::Clip => {
+ let node = &self.clip_nodes[index as usize];
let name = names.clip(ClipNodeIndex(index));
- let space = names.spatial(self.clip_nodes[index as usize].spatial);
- format!(
- "[{name} in {space}] {}",
- self.describe_clip_node(ClipNodeIndex(index), names)
- )
- },
- &mut |text: &mut String, index: u32| append_owner(text, SlotKind::Clip, index),
- root,
- 2,
- );
- }
- }
- if !effect_roots.is_empty() {
- text.push_str(" effects:\n");
- for root in effect_roots {
- dump_subtree(
- &mut text,
- names,
- &effect_children,
- &|index: u32, names: &mut DumpNames| {
+ let space = names.spatial(node.spatial);
+ let parent = (!node.parent.is_none()).then(|| names.clip(node.parent));
+ DumpedNode {
+ kind,
+ index,
+ name,
+ depth,
+ parent,
+ space: Some(space),
+ output_clip: None,
+ description: self.describe_clip_node(ClipNodeIndex(index), names),
+ owner: None,
+ }
+ }
+ SlotKind::Effect => {
let node = &self.effect_nodes[index as usize];
let name = names.effect(EffectNodeIndex(index));
let space = names.spatial(node.spatial);
let resolved_clip = effect_clips.output_clip(EffectNodeIndex(index));
- let output_clip = if resolved_clip.is_none() {
- String::new()
- } else {
- format!(" out={}", names.clip(resolved_clip))
- };
- format!(
- "[{name} in {space}{output_clip}] {}",
- self.describe_effect_node(EffectNodeIndex(index), names)
- )
- },
- &mut |text: &mut String, index: u32| append_owner(text, SlotKind::Effect, index),
- root,
- 2,
- );
+ let output_clip = (!resolved_clip.is_none()).then(|| names.clip(resolved_clip));
+ let parent = (!node.parent.is_none()).then(|| names.effect(node.parent));
+ DumpedNode {
+ kind,
+ index,
+ name,
+ depth,
+ parent,
+ space: Some(space),
+ output_clip,
+ description: self.describe_effect_node(EffectNodeIndex(index), names),
+ owner: None,
+ }
+ }
+ };
+ node.owner = owner_label(kind, index);
+ nodes.push(node);
+ if let Some(child_indices) = children.get(&index) {
+ pending.extend(child_indices.iter().rev().map(|&child| (child, depth + 1)));
+ }
}
+ };
+ walk(
+ SlotKind::Spatial,
+ VISUAL_VIEWPORT_NODE_INDEX.0,
+ &spatial_children,
+ names,
+ &mut nodes,
+ );
+ for root in clip_roots {
+ walk(SlotKind::Clip, root, &clip_children, names, &mut nodes);
}
- text
+ for root in effect_roots {
+ walk(SlotKind::Effect, root, &effect_children, names, &mut nodes);
+ }
+ nodes
+ }
+}
+
+/// A node of the tree section of the display list dump, with the names the dump gives it and the nodes it names.
+pub(crate) struct DumpedNode {
+ pub(crate) kind: SlotKind,
+ pub(crate) index: u32,
+ pub(crate) name: String,
+ pub(crate) depth: usize,
+ pub(crate) parent: Option<String>,
+ pub(crate) space: Option<String>,
+ pub(crate) output_clip: Option<String>,
+ pub(crate) description: String,
+ pub(crate) owner: Option<String>,
+}
+
+pub(crate) fn tree_section_text(nodes: &[DumpedNode]) -> String {
+ let mut text = String::from("AccumulatedVisualContext Tree:\n");
+ let mut previous_kind = None;
+ for node in nodes {
+ if previous_kind != Some(node.kind) {
+ text.push_str(match node.kind {
+ SlotKind::Spatial => " spatial:\n",
+ SlotKind::Clip => " clips:\n",
+ SlotKind::Effect => " effects:\n",
+ });
+ previous_kind = Some(node.kind);
+ }
+ text.push_str(&" ".repeat((node.depth + 2) * 2));
+ let _ = write!(text, "[{}", node.name);
+ if let Some(space) = &node.space {
+ let _ = write!(text, " in {space}");
+ }
+ if let Some(output_clip) = &node.output_clip {
+ let _ = write!(text, " out={output_clip}");
+ }
+ let _ = write!(text, "] {}", node.description);
+ if let Some(owner) = &node.owner {
+ let _ = write!(text, " ({owner})");
+ }
+ text.push('\n');
}
+ text
}
#[cfg(test)]
@@ -751,7 +783,7 @@ mod node_dump_tests {
#[cfg(test)]
mod section_dump_tests {
- use super::{SlotKind, VisualContextTreeDump};
+ use super::{DumpedNode, SlotKind, VisualContextTreeDump, tree_section_text};
use crate::layout::node_data::NodeSlotId;
use crate::painting::display_list::commands::{ContextRef, DisplayListCommandRun, SpatialNodeIndex};
use crate::painting::display_list::dump_format::DumpNames;
@@ -762,6 +794,16 @@ mod section_dump_tests {
};
use libgfx_rust::{CompositingAndBlendingOperator, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, IntRect};
+ fn tree_section_text_of(
+ tree: &VisualContextTree,
+ runs: &[DisplayListCommandRun],
+ names: &mut DumpNames,
+ owner_label: impl FnMut(SlotKind, u32) -> Option<String>,
+ ) -> String {
+ let nodes: Vec<DumpedNode> = tree.reachable_nodes_in_print_order(runs, names, owner_label);
+ tree_section_text(&nodes)
+ }
+
fn run(spatial: SpatialNodeIndex, context: ContextRef) -> DisplayListCommandRun {
DisplayListCommandRun {
offset: 0,
@@ -846,7 +888,7 @@ mod section_dump_tests {
run(VISUAL_VIEWPORT_NODE_INDEX, ContextRef::default()),
];
let mut names = DumpNames::default();
- let text = tree.dump_nodes_reachable_from_runs(&runs, &mut names, |kind, index| match (kind, index) {
+ let text = tree_section_text_of(&tree, &runs, &mut names, |kind, index| match (kind, index) {
(SlotKind::Spatial, 1) => Some("BlockContainer<DIV>#scroller".to_string()),
(SlotKind::Clip, 0) => Some("BlockContainer<DIV>#scroller".to_string()),
(SlotKind::Effect, 0) => Some("BlockContainer<DIV>#faded".to_string()),
@@ -898,7 +940,7 @@ mod section_dump_tests {
..ContextRef::default()
},
)];
- let dump = |names: &mut DumpNames| tree.dump_nodes_reachable_from_runs(&runs, names, |_, _| None);
+ let dump = |names: &mut DumpNames| tree_section_text_of(&tree, &runs, names, |_, _| None);
assert_eq!(
dump(&mut DumpNames::numbering_nodes_in_print_order()),
"AccumulatedVisualContext Tree:\n spatial:\n [s0] transform=[1,0,0,1,0,0] origin=(0,0)\n [s1] scroll\n clips:\n [c0 in s1] clip=[1,2 3x4]\n"
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 23dad85f14c..67d1d233bf4 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -1250,7 +1250,7 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString request
if (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 });
+ auto display_list_dump = doc->dump_display_list({ .owners = true, .text = true, .fonts = true, .record_ids = true, .jsonl = argument == "jsonl" });
dbgln("{}", display_list_dump.to_utf8());
}
return;
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.txt
new file mode 100644
index 00000000000..8fe9b004f9b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/display_list/jsonl-dump-is-one-json-object-per-line.txt
@@ -0,0 +1,15 @@
+types: {"header":1,"node":5,"layer":2,"record":6}
+header: ladybird-display-list-dump version 1 viewport [0,0,800,600] print-order 6 records
+record 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>"}
+{"type":"node","kind":"spatial","name":"s1","raw":1,"depth":1,"parent":"s0","description":"scroll","owner":"Viewport<#document>"}
+{"type":"node","kind":"spatial","name":"s2","raw":2,"depth":2,"parent":"s1","description":"transform=[0.70710677,-0.70710677,0.70710677,0.70710677,0,0] origin=(325,45) bounds=[300,20 50x50]","owner":"BlockContainer<DIV>#transformed"}
+{"type":"node","kind":"effect","name":"e0","raw":0,"depth":0,"space":"s0","description":"effects=[]"}
+{"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"}
+{"id":6,"text":"some text","has_font":true,"owner":"BlockContainer<P>","phase":"foreground"}
diff --git a/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.html b/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.html
new file mode 100644
index 00000000000..0d7e898dffb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/display_list/jsonl-dump-is-one-json-object-per-line.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; }
+ canvas { position: absolute; left: 20px; top: 20px; }
+ #transformed { position: absolute; left: 300px; top: 20px; width: 50px; height: 50px; background: green; transform: rotate(45deg); }
+ #masked { position: absolute; left: 400px; top: 20px; width: 50px; height: 50px; background: blue; mask-image: linear-gradient(black, transparent); }
+</style>
+<canvas id="canvas" width="200" height="120"></canvas>
+<div id="transformed"></div>
+<div id="masked"></div>
+<p style="position: absolute; top: 200px">some text</p>
+<script>
+ test(() => {
+ const context = canvas.getContext("2d");
+ context.fillStyle = "blue";
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ const lines = internals.dumpDisplayList({ format: "jsonl" }).trimEnd().split("\n");
+ const objects = lines.map(line => JSON.parse(line));
+ const counts = {};
+ for (const object of objects)
+ counts[object.type] = (counts[object.type] ?? 0) + 1;
+ println(`types: ${JSON.stringify(counts)}`);
+ const header = objects[0];
+ println(`header: ${header.format} version ${header.version} viewport ${JSON.stringify(header.viewport)} ${header.node_names} ${header.record_count} records`);
+ const records = objects.filter(object => object.type === "record");
+ println(`record ids count up from 1: ${records.every((record, index) => record.id === index + 1)}`);
+ for (const object of objects) {
+ if (object.type === "node" || object.type === "layer")
+ println(JSON.stringify(object));
+ }
+ for (const record of records) {
+ if (record.op === "FillRect" || record.op === "DeclareMaskContent" || record.op === "PaintLinearGradient")
+ println(JSON.stringify(record));
+ if (record.op === "DrawGlyphRun")
+ println(JSON.stringify({ id: record.id, text: record.text, has_font: typeof record.font === "string", owner: record.owner, phase: record.phase }));
+ }
+ });
+</script>