Truly independent web browser
LibCompositing+LibWeb+Compositor: Add the 2D canvas commands to the tape
Andreas Klingd9a9766cd0ac
diff --git a/Libraries/LibCompositing/DisplayList/DisplayListCommand.h b/Libraries/LibCompositing/DisplayList/DisplayListCommand.hindex cda5f71bdd2..c162ddc5c5c 100644--- a/Libraries/LibCompositing/DisplayList/DisplayListCommand.h+++ b/Libraries/LibCompositing/DisplayList/DisplayListCommand.h@@ -48,6 +48,7 @@ static_assert(IsTriviallyCopyable<TextShadowLayer>);static_assert(IsTriviallyCopyable<command>); \static_assert(alignof(command) <= display_list_payload_alignment);ENUMERATE_DISPLAY_LIST_COMMANDS(VERIFY_DISPLAY_LIST_COMMAND)+ENUMERATE_CANVAS_2D_COMMANDS(VERIFY_DISPLAY_LIST_COMMAND)#undef VERIFY_DISPLAY_LIST_COMMAND}diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex 587dbaf50b1..b0cabc2a847 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -449,12 +449,21 @@ fn main() -> Result<(), Box<dyn Error>> {.into_iter().map(String::from).collect();- let mut after_includes = String::from("\n#define ENUMERATE_DISPLAY_LIST_COMMANDS(V)");- for name in display_list_command_type_variants(&commands_source)? {- after_includes.push_str(&format!(" \\\n V({name})"));+ // The commands of the canvas 2D stream go into a list of their own, as only the canvas player plays them.+ let variants = display_list_command_type_variants(&commands_source)?;+ let mut after_includes = String::new();+ for (macro_name, canvas_2d) in [+ ("ENUMERATE_DISPLAY_LIST_COMMANDS", false),+ ("ENUMERATE_CANVAS_2D_COMMANDS", true),+ ] {+ after_includes.push_str(&format!("\n#define {macro_name}(V)"));+ for name in variants.iter().filter(|name| name.starts_with("Canvas2D") == canvas_2d) {+ after_includes.push_str(&format!(" \\\n V({name})"));+ }+ after_includes.push('\n');}after_includes.push_str(&format!(- "\n\nnamespace Compositing {{\n\n// Every record and every payload starts at a multiple of this.\nconstexpr size_t display_list_payload_alignment = {};\n\n}}",+ "\nnamespace Compositing {{\n\n// Every record and every payload starts at a multiple of this.\nconstexpr size_t display_list_payload_alignment = {};\n\n}}",display_list_payload_alignment(&manifest_dir.join("src/display_list/builder.rs"))?));commands_config.after_includes = Some(after_includes);diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rsindex 445dfa221fe..6c95b459255 100644--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs@@ -54,11 +54,23 @@ pub enum DisplayListCommandType {CompositorSnapArea,CompositorScrollChainingBarrier,CompositorNestedContextWheelRegion,+ Canvas2DFillPath,+ Canvas2DStrokePath,+ Canvas2DDrawGlyphRun,+ Canvas2DClearRect,+ Canvas2DDrawImageFrame,+ Canvas2DDrawCanvas,+ Canvas2DDrawVideoFrame,+ Canvas2DSetTransform,+ Canvas2DSave,+ Canvas2DRestore,+ Canvas2DClipPath,+ Canvas2DReset,+ Canvas2DClearCanvas,}ffi_enum_bytes!(DisplayListCommandType as u8);-pub const DISPLAY_LIST_COMMAND_TYPE_COUNT: usize =- DisplayListCommandType::CompositorNestedContextWheelRegion as usize + 1;+pub const DISPLAY_LIST_COMMAND_TYPE_COUNT: usize = DisplayListCommandType::Canvas2DClearCanvas as usize + 1;impl DisplayListCommandType {pub fn from_u8(value: u8) -> Option<Self> {@@ -86,6 +98,29 @@ impl DisplayListCommandType {)}+ /// A command of the stream of a 2D canvas, which the canvas replays against its own surface in recording order,+ /// under the state that the commands before it saved, transformed, clipped and restored. Such a command draws no+ /// known rect, and the display list of a page never holds one. Its name starts with "Canvas2D", which is how the+ /// build script tells it apart.+ pub const fn is_canvas_2d(self) -> bool {+ matches!(+ self,+ Self::Canvas2DFillPath+ | Self::Canvas2DStrokePath+ | Self::Canvas2DDrawGlyphRun+ | Self::Canvas2DClearRect+ | Self::Canvas2DDrawImageFrame+ | Self::Canvas2DDrawCanvas+ | Self::Canvas2DDrawVideoFrame+ | Self::Canvas2DSetTransform+ | Self::Canvas2DSave+ | Self::Canvas2DRestore+ | Self::Canvas2DClipPath+ | Self::Canvas2DReset+ | Self::Canvas2DClearCanvas+ )+ }+pub const fn name(self) -> &'static str {match self {Self::DrawGlyphRun => "DrawGlyphRun",@@ -126,6 +161,19 @@ impl DisplayListCommandType {Self::CompositorSnapArea => "CompositorSnapArea",Self::CompositorScrollChainingBarrier => "CompositorScrollChainingBarrier",Self::CompositorNestedContextWheelRegion => "CompositorNestedContextWheelRegion",+ Self::Canvas2DFillPath => "Canvas2DFillPath",+ Self::Canvas2DStrokePath => "Canvas2DStrokePath",+ Self::Canvas2DDrawGlyphRun => "Canvas2DDrawGlyphRun",+ Self::Canvas2DClearRect => "Canvas2DClearRect",+ Self::Canvas2DDrawImageFrame => "Canvas2DDrawImageFrame",+ Self::Canvas2DDrawCanvas => "Canvas2DDrawCanvas",+ Self::Canvas2DDrawVideoFrame => "Canvas2DDrawVideoFrame",+ Self::Canvas2DSetTransform => "Canvas2DSetTransform",+ Self::Canvas2DSave => "Canvas2DSave",+ Self::Canvas2DRestore => "Canvas2DRestore",+ Self::Canvas2DClipPath => "Canvas2DClipPath",+ Self::Canvas2DReset => "Canvas2DReset",+ Self::Canvas2DClearCanvas => "Canvas2DClearCanvas",}}}@@ -630,11 +678,12 @@ ffi_bytes_fields!(Repeat { x, y });pub trait DisplayListCommand: Copy + FfiBytes {const COMMAND_TYPE: DisplayListCommandType;- // Encloses everything the command draws. Only compositor metadata, which draws nothing, has none.+ // Encloses everything the command draws. Only compositor metadata, which draws nothing, and the commands of the+ // canvas 2D stream, which draw under state that only replay knows, have none.fn bounding_rect(&self) -> Option<IntRect> {const {assert!(- Self::COMMAND_TYPE.is_compositor_metadata(),+ Self::COMMAND_TYPE.is_compositor_metadata() || Self::COMMAND_TYPE.is_canvas_2d(),"a draw command must report its bounding rect");};@@ -1653,6 +1702,330 @@ impl DisplayListCommand for PaintScrollBar {}}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(u8)]+pub enum Canvas2DPaintKind {+ #[default]+ Color,+ LinearGradient,+ RadialGradient,+ ConicGradient,+ Pattern,+}+ffi_enum_bytes!(Canvas2DPaintKind as u8);++// The values of Gfx::CanvasPatternPaintStyle::Repetition.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(u8)]+pub enum Canvas2DPatternRepetition {+ #[default]+ Repeat,+ RepeatX,+ RepeatY,+ NoRepeat,+}+ffi_enum_bytes!(Canvas2DPatternRepetition as u8);++/// The fill or stroke style of a 2D canvas draw. Only the fields of its kind are read: the color, the points and the+/// radii of a gradient, which are in the coordinates the draw is transformed from, or the image of a pattern. A+/// pattern without an image is one whose image was not available when script created it.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[repr(C)]+pub struct Canvas2DPaint {+ pub kind: Canvas2DPaintKind,+ pub pattern_repetition: Canvas2DPatternRepetition,+ pub pattern_has_image: bool,+ pub color: Color,+ pub start_point: FloatPoint,+ pub end_point: FloatPoint,+ pub start_radius: f32,+ pub end_radius: f32,+ pub start_angle: f32,+ pub color_stops: DisplayListGradientColorStops,+ pub pattern_image_id: ImageFrameResourceId,+ pub pattern_transform: OptionalAffineTransform,+}+ffi_bytes_fields!(Canvas2DPaint {+ kind,+ pattern_repetition,+ pattern_has_image,+ color,+ start_point,+ end_point,+ start_radius,+ end_radius,+ start_angle,+ color_stops,+ pattern_image_id,+ pattern_transform+});++/// How a 2D canvas draw composites onto the canvas: through the serialized filter graph of the context, if it has one,+/// with the global alpha of the context, and with its compositing and blending operator.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[repr(C)]+pub struct Canvas2DCompositing {+ pub filter: DisplayListDataSpan,+ pub has_filter: bool,+ pub global_alpha: f32,+ pub compositing_and_blending_operator: CompositingAndBlendingOperator,+}+ffi_bytes_fields!(Canvas2DCompositing {+ filter,+ has_filter,+ global_alpha,+ compositing_and_blending_operator+});++// A path fill. A solid color fill with a blur radius is a shadow, which is blurred and drawn without the filter and the+// global alpha.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DFillPath {+ pub path_data: DisplayListDataSpan,+ pub paint: Canvas2DPaint,+ pub winding_rule: WindingRule,+ pub blur_radius: f32,+ pub compositing: Canvas2DCompositing,+}+ffi_bytes_fields!(Canvas2DFillPath {+ path_data,+ paint,+ winding_rule,+ blur_radius,+ compositing+});++impl DisplayListCommand for Canvas2DFillPath {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DFillPath;+}++#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DStrokePath {+ pub path_data: DisplayListDataSpan,+ pub paint: Canvas2DPaint,+ pub thickness: f32,+ pub cap_style: CapStyle,+ pub join_style: JoinStyle,+ pub miter_limit: f32,+ pub dash_array: DisplayListDataSpan,+ pub dash_offset: f32,+ pub blur_radius: f32,+ pub compositing: Canvas2DCompositing,+}+ffi_bytes_fields!(Canvas2DStrokePath {+ path_data,+ paint,+ thickness,+ cap_style,+ join_style,+ miter_limit,+ dash_array,+ dash_offset,+ blur_radius,+ compositing+});++impl DisplayListCommand for Canvas2DStrokePath {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DStrokePath;+}++// The glyphs of one font, positioned relative to the translation, with the top of the line box at the glyph position.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DDrawGlyphRun {+ pub font_id: FontResourceId,+ pub glyphs: DisplayListDataSpan,+ pub translation: FloatPoint,+ pub paint: Canvas2DPaint,+ pub compositing: Canvas2DCompositing,+}+ffi_bytes_fields!(Canvas2DDrawGlyphRun {+ font_id,+ glyphs,+ translation,+ paint,+ compositing+});++impl DisplayListCommand for Canvas2DDrawGlyphRun {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DDrawGlyphRun;+}++#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DClearRect {+ pub rect: FloatRect,+ pub color: Color,+}+ffi_bytes_fields!(Canvas2DClearRect { rect, color });++impl DisplayListCommand for Canvas2DClearRect {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DClearRect;+}++#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DDrawImageFrame {+ pub frame_id: ImageFrameResourceId,+ pub dst_rect: FloatRect,+ pub src_rect: IntRect,+ pub scaling_mode: ScalingMode,+ pub compositing: Canvas2DCompositing,+}+ffi_bytes_fields!(Canvas2DDrawImageFrame {+ frame_id,+ dst_rect,+ src_rect,+ scaling_mode,+ compositing+});++impl DisplayListCommand for Canvas2DDrawImageFrame {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DDrawImageFrame;+}++// Draws what another canvas of the same connection holds at this point of the stream.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DDrawCanvas {+ pub source_canvas_id: CanvasId,+ pub dst_rect: FloatRect,+ pub src_rect: IntRect,+ pub scaling_mode: ScalingMode,+ pub compositing: Canvas2DCompositing,+}+ffi_bytes_fields!(Canvas2DDrawCanvas {+ source_canvas_id,+ dst_rect,+ src_rect,+ scaling_mode,+ compositing+});++impl DisplayListCommand for Canvas2DDrawCanvas {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DDrawCanvas;+}++// Draws a frame of a video that WebContent holds for the stream, named by the handle of its sink and its generation.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DDrawVideoFrame {+ pub video_sink_handle: u64,+ pub generation: u64,+ pub dst_rect: FloatRect,+ pub src_rect: IntRect,+ pub scaling_mode: ScalingMode,+ pub compositing: Canvas2DCompositing,+}+ffi_bytes_fields!(Canvas2DDrawVideoFrame {+ video_sink_handle,+ generation,+ dst_rect,+ src_rect,+ scaling_mode,+ compositing+});++impl DisplayListCommand for Canvas2DDrawVideoFrame {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DDrawVideoFrame;+}++#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DSetTransform {+ pub transform: AffineTransform,+}+ffi_bytes_fields!(Canvas2DSetTransform { transform });++impl DisplayListCommand for Canvas2DSetTransform {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DSetTransform;+}++// NB: C++ gives a struct without fields a size of one byte, so the commands that take no arguments carry padding to+// be the same size on both sides.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[repr(C)]+pub struct Canvas2DSave {+ pub padding: u32,+}+ffi_bytes_fields!(Canvas2DSave { padding });++impl DisplayListCommand for Canvas2DSave {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DSave;+}++#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[repr(C)]+pub struct Canvas2DRestore {+ pub padding: u32,+}+ffi_bytes_fields!(Canvas2DRestore { padding });++impl DisplayListCommand for Canvas2DRestore {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DRestore;+}++#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DClipPath {+ pub path_data: DisplayListDataSpan,+ pub winding_rule: WindingRule,+}+ffi_bytes_fields!(Canvas2DClipPath {+ path_data,+ winding_rule+});++impl DisplayListCommand for Canvas2DClipPath {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DClipPath;+}++// Drops every saved state and clip, back to the state the canvas was created with.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[repr(C)]+pub struct Canvas2DReset {+ pub padding: u32,+}+ffi_bytes_fields!(Canvas2DReset { padding });++impl DisplayListCommand for Canvas2DReset {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DReset;+}++// Sets every pixel of the canvas to the color, outside of any transform or clip.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct Canvas2DClearCanvas {+ pub color: Color,+}+ffi_bytes_fields!(Canvas2DClearCanvas { color });++impl DisplayListCommand for Canvas2DClearCanvas {+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DClearCanvas;+}+pub fn int_rect_from_two_points(a: IntPoint, b: IntPoint) -> IntRect {IntRect::new(a.x.min(b.x), a.y.min(b.y), (a.x - b.x).abs(), (a.y - b.y).abs())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_commands_of_the_canvas_2d_stream_are_the_ones_whose_names_say_so() {+ // The build script sorts the commands into the C++ lists by their names.+ for value in 0..DISPLAY_LIST_COMMAND_TYPE_COUNT {+ let command_type = DisplayListCommandType::from_u8(value as u8).unwrap();+ assert_eq!(+ command_type.is_canvas_2d(),+ command_type.name().starts_with("Canvas2D"),+ "{}",+ command_type.name()+ );+ assert!(!(command_type.is_canvas_2d() && command_type.is_compositor_metadata()));+ }+ }+}diff --git a/Libraries/LibCompositing/Rust/src/display_list/summary.rs b/Libraries/LibCompositing/Rust/src/display_list/summary.rsindex c3096528105..6c5cfeb7f36 100644--- a/Libraries/LibCompositing/Rust/src/display_list/summary.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/summary.rs@@ -136,7 +136,21 @@ fn note_referenced_ids(command_type: DisplayListCommandType, payload: &[u8], ids| T::CompositorSnapContainer| T::CompositorSnapArea| T::CompositorScrollChainingBarrier- | T::CompositorNestedContextWheelRegion => {}+ | T::CompositorNestedContextWheelRegion+ // The display list of a page holds none of the commands of the canvas 2D stream.+ | T::Canvas2DFillPath+ | T::Canvas2DStrokePath+ | T::Canvas2DDrawGlyphRun+ | T::Canvas2DClearRect+ | T::Canvas2DDrawImageFrame+ | T::Canvas2DDrawCanvas+ | T::Canvas2DDrawVideoFrame+ | T::Canvas2DSetTransform+ | T::Canvas2DSave+ | T::Canvas2DRestore+ | T::Canvas2DClipPath+ | T::Canvas2DReset+ | T::Canvas2DClearCanvas => {}}}@@ -274,7 +288,21 @@ fn command_blend(| T::CompositorSnapContainer| T::CompositorSnapArea| T::CompositorScrollChainingBarrier- | T::CompositorNestedContextWheelRegion => None,+ | T::CompositorNestedContextWheelRegion+ // The display list of a page holds none of the commands of the canvas 2D stream.+ | T::Canvas2DFillPath+ | T::Canvas2DStrokePath+ | T::Canvas2DDrawGlyphRun+ | T::Canvas2DClearRect+ | T::Canvas2DDrawImageFrame+ | T::Canvas2DDrawCanvas+ | T::Canvas2DDrawVideoFrame+ | T::Canvas2DSetTransform+ | T::Canvas2DSave+ | T::Canvas2DRestore+ | T::Canvas2DClipPath+ | T::Canvas2DReset+ | T::Canvas2DClearCanvas => None,}}diff --git a/Libraries/LibCompositing/Rust/src/display_list/validate.rs b/Libraries/LibCompositing/Rust/src/display_list/validate.rsindex 598238c0a65..43a7688a6ee 100644--- a/Libraries/LibCompositing/Rust/src/display_list/validate.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/validate.rs@@ -6,7 +6,8 @@//! Checks a display list tape that comes from another process before anything reads it. A tape that passes has//! well formed records, valid enum and bool bytes, and spans inside their payloads, so the typed reads that replay,-//! damage and the player make of it are sound.+//! damage and the player make of it are sound. The tape of a page and that of a 2D canvas each hold only the+//! commands of their own kind.use super::builder::{COMMAND_ALIGNMENT, HEADER_SIZE, read_header};use super::commands::*;@@ -50,6 +51,14 @@ tape_enum!(CompositorScrollNodeKind as u8 { Viewport, Element, PseudoElement });tape_enum!(PathPaintKind as u8 { Color, PaintStyle });tape_enum!(DisplayListPaintStyleType as u8 { None, LinearGradient, RadialGradient, Pattern });tape_enum!(DisplayListGradientSpreadMethod as u8 { Pad, Repeat, Reflect });+tape_enum!(Canvas2DPaintKind as u8 {+ Color,+ LinearGradient,+ RadialGradient,+ ConicGradient,+ Pattern,+});+tape_enum!(Canvas2DPatternRepetition as u8 { Repeat, RepeatX, RepeatY, NoRepeat });tape_enum!(WindingRule as i32 { Nonzero, EvenOdd });tape_enum!(LineStyle as u8 { Solid, Dotted, Dashed });tape_enum!(ScalingMode as i32 { None, Bilinear, BilinearMipmap, NearestNeighbor });@@ -107,6 +116,10 @@ impl Payload<'_> {i32::from_ne_bytes(self.bytes[offset..offset + 4].try_into().unwrap())}+ fn f32_at(self, offset: usize) -> f32 {+ f32::from_ne_bytes(self.bytes[offset..offset + 4].try_into().unwrap())+ }+fn bool_at(self, offset: usize) -> Result<(), ValidationError> {if self.u8_at(offset) > 1 {return Err("Display list command has an invalid bool");@@ -252,6 +265,31 @@ fn validate_paint_style(}}+fn validate_canvas_2d_paint(payload: Payload, offset: usize) -> Result<(), ValidationError> {+ payload.enum_at::<Canvas2DPaintKind>(offset + offset_of!(Canvas2DPaint, kind))?;+ payload.enum_at::<Canvas2DPatternRepetition>(offset + offset_of!(Canvas2DPaint, pattern_repetition))?;+ payload.bool_at(offset + offset_of!(Canvas2DPaint, pattern_has_image))?;+ validate_color_stops(payload, offset + offset_of!(Canvas2DPaint, color_stops), false)?;+ validate_optional_at(+ payload,+ offset + offset_of!(Canvas2DPaint, pattern_transform),+ offset_of!(OptionalAffineTransform, has_value),+ )+}++fn validate_canvas_2d_compositing(payload: Payload, offset: usize) -> Result<(), ValidationError> {+ payload.span_at(offset + offset_of!(Canvas2DCompositing, filter))?;+ payload.bool_at(offset + offset_of!(Canvas2DCompositing, has_filter))?;+ // The player turns the global alpha into a byte, which only a value from 0 to 1 converts to.+ let global_alpha = payload.f32_at(offset + offset_of!(Canvas2DCompositing, global_alpha));+ if !(0.0..=1.0).contains(&global_alpha) {+ return Err("Canvas 2D stream command has a global alpha outside 0 to 1");+ }+ payload.enum_at::<CompositingAndBlendingOperator>(+ offset + offset_of!(Canvas2DCompositing, compositing_and_blending_operator),+ )+}+fn command_struct_size(command_type: DisplayListCommandType) -> usize {use DisplayListCommandType as T;match command_type {@@ -293,6 +331,19 @@ fn command_struct_size(command_type: DisplayListCommandType) -> usize {T::CompositorSnapArea => size_of::<CompositorSnapArea>(),T::CompositorScrollChainingBarrier => size_of::<CompositorScrollChainingBarrier>(),T::CompositorNestedContextWheelRegion => size_of::<CompositorNestedContextWheelRegion>(),+ T::Canvas2DFillPath => size_of::<Canvas2DFillPath>(),+ T::Canvas2DStrokePath => size_of::<Canvas2DStrokePath>(),+ T::Canvas2DDrawGlyphRun => size_of::<Canvas2DDrawGlyphRun>(),+ T::Canvas2DClearRect => size_of::<Canvas2DClearRect>(),+ T::Canvas2DDrawImageFrame => size_of::<Canvas2DDrawImageFrame>(),+ T::Canvas2DDrawCanvas => size_of::<Canvas2DDrawCanvas>(),+ T::Canvas2DDrawVideoFrame => size_of::<Canvas2DDrawVideoFrame>(),+ T::Canvas2DSetTransform => size_of::<Canvas2DSetTransform>(),+ T::Canvas2DSave => size_of::<Canvas2DSave>(),+ T::Canvas2DRestore => size_of::<Canvas2DRestore>(),+ T::Canvas2DClipPath => size_of::<Canvas2DClipPath>(),+ T::Canvas2DReset => size_of::<Canvas2DReset>(),+ T::Canvas2DClearCanvas => size_of::<Canvas2DClearCanvas>(),}}@@ -476,6 +527,41 @@ fn validate_command_fields(p.u8_below(offset_of!(CompositorSnapArea, align_y), SNAP_ALIGN_COUNT)?;p.bool_at(offset_of!(CompositorSnapArea, always_stop))?;}+ T::Canvas2DFillPath => {+ p.span_at(offset_of!(Canvas2DFillPath, path_data))?;+ validate_canvas_2d_paint(p, offset_of!(Canvas2DFillPath, paint))?;+ p.enum_at::<WindingRule>(offset_of!(Canvas2DFillPath, winding_rule))?;+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DFillPath, compositing))?;+ }+ T::Canvas2DStrokePath => {+ p.span_at(offset_of!(Canvas2DStrokePath, path_data))?;+ validate_canvas_2d_paint(p, offset_of!(Canvas2DStrokePath, paint))?;+ p.enum_at::<CapStyle>(offset_of!(Canvas2DStrokePath, cap_style))?;+ p.enum_at::<JoinStyle>(offset_of!(Canvas2DStrokePath, join_style))?;+ p.array_span_at::<f32>(offset_of!(Canvas2DStrokePath, dash_array))?;+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DStrokePath, compositing))?;+ }+ T::Canvas2DDrawGlyphRun => {+ p.array_span_at::<DisplayListGlyph>(offset_of!(Canvas2DDrawGlyphRun, glyphs))?;+ validate_canvas_2d_paint(p, offset_of!(Canvas2DDrawGlyphRun, paint))?;+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DDrawGlyphRun, compositing))?;+ }+ T::Canvas2DDrawImageFrame => {+ p.enum_at::<ScalingMode>(offset_of!(Canvas2DDrawImageFrame, scaling_mode))?;+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DDrawImageFrame, compositing))?;+ }+ T::Canvas2DDrawCanvas => {+ p.enum_at::<ScalingMode>(offset_of!(Canvas2DDrawCanvas, scaling_mode))?;+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DDrawCanvas, compositing))?;+ }+ T::Canvas2DDrawVideoFrame => {+ p.enum_at::<ScalingMode>(offset_of!(Canvas2DDrawVideoFrame, scaling_mode))?;+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DDrawVideoFrame, compositing))?;+ }+ T::Canvas2DClipPath => {+ p.span_at(offset_of!(Canvas2DClipPath, path_data))?;+ p.enum_at::<WindingRule>(offset_of!(Canvas2DClipPath, winding_rule))?;+ }T::PaintOuterBoxShadow| T::PaintInnerBoxShadow| T::FillRectWithRoundedCorners@@ -487,7 +573,13 @@ fn validate_command_fields(| T::CompositorWheelHitTestTargetWithCornerRadii| T::CompositorMainThreadWheelEventRegion| T::CompositorBlockingWheelEventRegion- | T::CompositorNestedContextWheelRegion => {}+ | T::CompositorNestedContextWheelRegion+ | T::Canvas2DClearRect+ | T::Canvas2DSetTransform+ | T::Canvas2DSave+ | T::Canvas2DRestore+ | T::Canvas2DReset+ | T::Canvas2DClearCanvas => {}}Ok(())}@@ -525,7 +617,14 @@ impl RunSummary {}}-fn validate_header_bytes(bytes: &[u8]) -> Result<DisplayListCommandHeader, ValidationError> {+// The kind of tape whose records are checked, which decides the commands they may hold.+#[derive(Clone, Copy, PartialEq, Eq)]+enum TapeKind {+ DisplayList,+ Canvas2D,+}++fn validate_header_bytes(bytes: &[u8], kind: TapeKind) -> Result<DisplayListCommandHeader, ValidationError> {if bytes.len() < HEADER_SIZE {return Err("Display list ends inside a command header");}@@ -538,8 +637,28 @@ fn validate_header_bytes(bytes: &[u8]) -> Result<DisplayListCommandHeader, Validreturn Err("Display list command header has an invalid bool");}let header = read_header(bytes);- if !header.has_bounding_rect && !header.command_type.is_compositor_metadata() {- return Err("Display list draw command has no bounding rect");+ match kind {+ TapeKind::DisplayList => {+ if header.command_type.is_canvas_2d() {+ return Err("Display list holds a command of the canvas 2D stream");+ }+ if !header.has_bounding_rect && !header.command_type.is_compositor_metadata() {+ return Err("Display list draw command has no bounding rect");+ }+ }+ TapeKind::Canvas2D => {+ if !header.command_type.is_canvas_2d() {+ return Err("Canvas 2D stream holds a command of a display list");+ }+ // The canvas player plays commands one by one under the state of the canvas.+ if header.inline_clip_count != 0 || header.has_inline_transform {+ return Err("Canvas 2D stream command has inline clips or an inline transform");+ }+ // A command of the canvas draws under the state that the commands before it left, so no rect bounds it.+ if header.has_bounding_rect {+ return Err("Canvas 2D stream command has a bounding rect");+ }+ }}Ok(header)}@@ -547,12 +666,13 @@ fn validate_header_bytes(bytes: &[u8]) -> Result<DisplayListCommandHeader, Valid// Checks one stream of records, and pushes the nested record streams its commands hold onto `pending`.fn validate_records<'a>(records: &'a [u8],+ kind: TapeKind,pending: &mut Vec<&'a [u8]>,mut summary: Option<&mut RunSummary>,) -> Result<(), ValidationError> {let mut offset = 0;while offset < records.len() {- let header = validate_header_bytes(&records[offset..])?;+ let header = validate_header_bytes(&records[offset..], kind)?;let payload_size = header.payload_size as usize;let payload_start = offset + HEADER_SIZE;if !payload_size.is_multiple_of(COMMAND_ALIGNMENT) || payload_size > records.len() - payload_start {@@ -658,9 +778,14 @@ pub fn validate_tape(tape: &[u8], run_bytes: &[u8]) -> Result<Vec<DisplayListComreturn Err("Adjacent display list command runs share a visual context");}let mut summary = RunSummary::default();- validate_records(&tape[next_offset..next_offset + size], &mut pending, Some(&mut summary))?;+ validate_records(+ &tape[next_offset..next_offset + size],+ TapeKind::DisplayList,+ &mut pending,+ Some(&mut summary),+ )?;while let Some(records) = pending.pop() {- validate_records(records, &mut pending, None)?;+ validate_records(records, TapeKind::DisplayList, &mut pending, None)?;}if !summary.matches(&run) {return Err("Display list command run summary disagrees with its records");@@ -674,6 +799,21 @@ pub fn validate_tape(tape: &[u8], run_bytes: &[u8]) -> Result<Vec<DisplayListComOk(runs)}+/// Checks the tape of a segment of the canvas 2D stream, which is a run of records with no run table, each a command+/// of the canvas 2D stream that holds no nested records.+pub fn validate_canvas_2d_tape(tape: &[u8]) -> Result<(), ValidationError> {+ if !tape.len().is_multiple_of(COMMAND_ALIGNMENT) || u32::try_from(tape.len()).is_err() {+ return Err("Canvas 2D stream tape has an invalid size");+ }+ let mut pending = Vec::new();+ validate_records(tape, TapeKind::Canvas2D, &mut pending, None)?;+ debug_assert!(+ pending.is_empty(),+ "no command of the canvas 2D stream holds nested records"+ );+ Ok(())+}+#[cfg(test)]mod tests {use super::*;diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rsindex fc294a85fa0..d57213678fd 100644--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs@@ -664,6 +664,20 @@ fn dump_command(output: &mut String, command_type: DisplayListCommandType, paylo).unwrap();}+ // The display list of a page holds none of the commands of the canvas 2D stream.+ DisplayListCommandType::Canvas2DFillPath+ | DisplayListCommandType::Canvas2DStrokePath+ | DisplayListCommandType::Canvas2DDrawGlyphRun+ | DisplayListCommandType::Canvas2DClearRect+ | DisplayListCommandType::Canvas2DDrawImageFrame+ | DisplayListCommandType::Canvas2DDrawCanvas+ | DisplayListCommandType::Canvas2DDrawVideoFrame+ | DisplayListCommandType::Canvas2DSetTransform+ | DisplayListCommandType::Canvas2DSave+ | DisplayListCommandType::Canvas2DRestore+ | DisplayListCommandType::Canvas2DClipPath+ | DisplayListCommandType::Canvas2DReset+ | DisplayListCommandType::Canvas2DClearCanvas => {}}}diff --git a/Services/Compositor/DisplayListPlayer.cpp b/Services/Compositor/DisplayListPlayer.cppindex d25f0dbe18f..e63956ee8dc 100644--- a/Services/Compositor/DisplayListPlayer.cpp+++ b/Services/Compositor/DisplayListPlayer.cpp@@ -107,6 +107,11 @@ void DisplayListPlayer::play_command_bytes(DisplayListCommandType command_type,break;ENUMERATE_DISPLAY_LIST_COMMANDS(PLAY_DISPLAY_LIST_COMMAND)#undef PLAY_DISPLAY_LIST_COMMAND+#define REJECT_CANVAS_2D_COMMAND(command_type) case DisplayListCommandType::command_type:+ ENUMERATE_CANVAS_2D_COMMANDS(REJECT_CANVAS_2D_COMMAND)+#undef REJECT_CANVAS_2D_COMMAND+ // NB: The display list of a page never holds a command of the canvas 2D stream; validation rejects one.+ VERIFY_NOT_REACHED();}}