Truly independent web browser
LibGfx+LibCompositing+Compositor: Let the window server clip by a path
Aliaksandr Kalenikfb777b47f73e
diff --git a/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rs b/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rsindex d6c130525b0..acd1a43c5a7 100644--- a/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/window_server_placement.rs@@ -6,7 +6,7 @@//! Where the window server can show by itself a canvas or a video that is a layer of its own. The window server places//! an image with a 2D affine transform and clips it to rectangles, one of which can have rounded corners of a single-//! radius. A media layer drawn under any other clip has to be replayed instead.+//! radius, and to one path. A media layer drawn under any other clip has to be replayed instead.//!//! Also how the window server composites by itself an effect around the layers of what the effect holds: within//! rectangles, rounded or not, at an opacity, or over what it shows below the effect's box run through a blur and@@ -19,28 +19,57 @@ use crate::display_list::commands::{};use crate::display_list::replay::backdrop_is_drawn_by_masks;use crate::display_list::tape::{DisplayListCommandHeader, DisplayListCommandRun, InlineClipKind};-use crate::visual_context::{ClipNodeData, EffectNodeData, VisualContextTree, WorldTransforms};+use crate::visual_context::{ClipNodeData, ClipPathData, EffectNodeData, VisualContextTree, WorldTransforms};use libgfx_rust::filter::Filter;+use libgfx_rust::path::Path;use libgfx_rust::{- AffineTransform, ColorFilterType, CompositingAndBlendingOperator, CornerRadii, CornerRadius, FloatRect, IntRect,- ScalingMode, multiply_affine,+ AffineTransform, ColorFilterType, CompositingAndBlendingOperator, CornerRadii, CornerRadius, FloatMatrix4x4,+ FloatRect, IntRect, ScalingMode, WindingRule, multiply_affine,};+use std::sync::Arc;const UNIFORM_SCALE_TOLERANCE: f32 = 0.0001;const RADIUS_TOLERANCE_IN_DEVICE_PIXELS: f32 = 0.01;-#[derive(Clone, Copy, Debug, PartialEq)]+#[derive(Clone, Debug, PartialEq)]pub struct WindowServerPlacement {/// Where the record draws its content, in the record's own space.pub content_rect: IntRect,pub content_to_viewport: AffineTransform,- /// The intersection of every clip the record is drawn under, rounded or not, in viewport pixels.+ /// The intersection of every clip the record is drawn under, rounded or not, and of the bounds of the path it is+ /// clipped by, in viewport pixels.pub clip_rect: FloatRect,pub rounded_clip: Option<RoundedClip>,+ pub path_clip: Option<PathClip>,pub scaling_mode: ScalingMode,}+/// A path the record is clipped by, which stays in the space of its clip node.+#[derive(Clone, Debug)]+pub struct PathClip {+ pub path: Arc<Path>,+ /// The bounds of the path, in its own space.+ pub bounding_rect: IntRect,+ pub path_to_viewport: AffineTransform,+ pub fill_rule: WindingRule,+}++impl PartialEq for PathClip {+ fn eq(&self, other: &Self) -> bool {+ self.path.identity() == other.path.identity()+ && self.bounding_rect == other.bounding_rect+ && self.path_to_viewport == other.path_to_viewport+ && self.fill_rule == other.fill_rule+ }+}++impl PathClip {+ pub fn bounds_in_viewport(&self) -> FloatRect {+ self.path_to_viewport.map_rect(self.bounding_rect.to_float())+ }+}+#[derive(Clone, Copy, Debug, PartialEq)]pub struct RoundedClip {pub rect: FloatRect,@@ -65,6 +94,7 @@ impl RoundedCorners {#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum WhyWindowServerCannotShowMedia {ClippedByPath,+ ClippedByMoreThanOnePath,ClippedByExcludingClip,ClippedInRotatedOrSkewedSpace,ClippedInSpaceTreeDoesNotHave,@@ -76,6 +106,7 @@ impl std::fmt::Display for WhyWindowServerCannotShowMedia {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {formatter.write_str(match self {WhyWindowServerCannotShowMedia::ClippedByPath => "clipped by a path",+ WhyWindowServerCannotShowMedia::ClippedByMoreThanOnePath => "clipped by more than one path",WhyWindowServerCannotShowMedia::ClippedByExcludingClip => "clipped by an excluding clip",WhyWindowServerCannotShowMedia::ClippedInRotatedOrSkewedSpace => "clipped in a rotated or skewed space",WhyWindowServerCannotShowMedia::ClippedInSpaceTreeDoesNotHave => {@@ -94,26 +125,32 @@ impl std::fmt::Display for WindowServerPlacement {write!(formatter, "transform=[{a},{b},{c},{d},{e},{f}] ")?;}write_float_rect(formatter, "clip", self.clip_rect)?;- let Some(rounded_clip) = self.rounded_clip else {- return Ok(());- };- formatter.write_str(" ")?;- write_float_rect(formatter, "rounded", rounded_clip.rect)?;- write!(formatter, " radius={}", rounded_clip.radius)?;- let corners = rounded_clip.rounded_corners;- if !corners.are_all_rounded() {- let names = [- (corners.top_left, "top-left"),- (corners.top_right, "top-right"),- (corners.bottom_right, "bottom-right"),- (corners.bottom_left, "bottom-left"),- ];- let rounded: Vec<&str> = names- .iter()- .filter(|(rounded, _)| *rounded)- .map(|(_, name)| *name)- .collect();- write!(formatter, " corners={}", rounded.join(","))?;+ if let Some(rounded_clip) = self.rounded_clip {+ formatter.write_str(" ")?;+ write_float_rect(formatter, "rounded", rounded_clip.rect)?;+ write!(formatter, " radius={}", rounded_clip.radius)?;+ let corners = rounded_clip.rounded_corners;+ if !corners.are_all_rounded() {+ let names = [+ (corners.top_left, "top-left"),+ (corners.top_right, "top-right"),+ (corners.bottom_right, "bottom-right"),+ (corners.bottom_left, "bottom-left"),+ ];+ let rounded: Vec<&str> = names+ .iter()+ .filter(|(rounded, _)| *rounded)+ .map(|(_, name)| *name)+ .collect();+ write!(formatter, " corners={}", rounded.join(","))?;+ }+ }+ if let Some(path_clip) = &self.path_clip {+ formatter.write_str(" ")?;+ write_float_rect(formatter, "path", path_clip.bounds_in_viewport())?;+ if path_clip.fill_rule == WindingRule::EvenOdd {+ formatter.write_str(" evenodd")?;+ }}Ok(())}@@ -218,10 +255,27 @@ fn clip_leaves_content_whole(!rounded_rect.rounded_corner_reaches_into(content_rect)}+/// The matrix from a space that a clip is in to the viewport, where the window server can clip in that space: one+/// that is 2D affine, without rotation or skew.+fn clip_space_to_viewport(+ world: &WorldTransforms,+ space: SpatialNodeIndex,+) -> Result<FloatMatrix4x4, WhyWindowServerCannotShowMedia> {+ let matrix = world+ .draw_matrix_if_known(space)+ .ok_or(WhyWindowServerCannotShowMedia::ClippedInSpaceTreeDoesNotHave)?;+ let elements = &matrix.elements;+ if !matrix.is_2d_affine() || elements[0][1] != 0.0 || elements[1][0] != 0.0 {+ return Err(WhyWindowServerCannotShowMedia::ClippedInRotatedOrSkewedSpace);+ }+ Ok(matrix)+}+#[derive(Default)]struct ClipsInViewport {rect_clips: Vec<FloatRect>,rounded_clips: Vec<RoundedRect>,+ path_clip: Option<PathClip>,}impl ClipsInViewport {@@ -236,13 +290,8 @@ impl ClipsInViewport {if mode == ClipMode::Difference {return Err(WhyWindowServerCannotShowMedia::ClippedByExcludingClip);}- let matrix = world- .draw_matrix_if_known(space)- .ok_or(WhyWindowServerCannotShowMedia::ClippedInSpaceTreeDoesNotHave)?;+ let matrix = clip_space_to_viewport(world, space)?;let elements = &matrix.elements;- if !matrix.is_2d_affine() || elements[0][1] != 0.0 || elements[1][0] != 0.0 {- return Err(WhyWindowServerCannotShowMedia::ClippedInRotatedOrSkewedSpace);- }let rect_in_viewport = matrix.extract_2d_affine().map_rect(rect);if !corner_radii.has_any_radius() {self.rect_clips.push(rect_in_viewport);@@ -278,6 +327,27 @@ impl ClipsInViewport {});Ok(())}++ /// Adds a clip by a path in `space`, whose bounds join the rect clips.+ fn add_path(+ &mut self,+ world: &WorldTransforms,+ space: SpatialNodeIndex,+ clip_path: &ClipPathData,+ ) -> Result<(), WhyWindowServerCannotShowMedia> {+ if self.path_clip.is_some() {+ return Err(WhyWindowServerCannotShowMedia::ClippedByMoreThanOnePath);+ }+ let path_clip = PathClip {+ path: clip_path.path.clone(),+ bounding_rect: clip_path.bounding_rect,+ path_to_viewport: clip_space_to_viewport(world, space)?.extract_2d_affine(),+ fill_rule: clip_path.fill_rule,+ };+ self.rect_clips.push(path_clip.bounds_in_viewport());+ self.path_clip = Some(path_clip);+ Ok(())+ }}/// How the window server composites an effect by itself around the layers of what the effect holds.@@ -721,7 +791,7 @@ pub fn window_server_placement(content_bounds_in_record_space,) => {}ClipNodeData::Rect(data) => clips.add(world, node.spatial, data.rect, data.corner_radii, data.mode)?,- ClipNodeData::Path(_) => return Err(WhyWindowServerCannotShowMedia::ClippedByPath),+ ClipNodeData::Path(data) => clips.add_path(world, node.spatial, data)?,ClipNodeData::Dead => {}}clip = node.parent;@@ -754,6 +824,7 @@ pub fn window_server_placement(content_to_viewport,clip_rect,rounded_clip,+ path_clip: clips.path_clip,scaling_mode,})}diff --git a/Libraries/LibGfx/Rust/src/path/ffi.rs b/Libraries/LibGfx/Rust/src/path/ffi.rsindex 1e11522494f..19f90e17e47 100644--- a/Libraries/LibGfx/Rust/src/path/ffi.rs+++ b/Libraries/LibGfx/Rust/src/path/ffi.rs@@ -15,6 +15,7 @@ use crate::geometry::FloatPoint;/// The contours of a path, valid until the path changes or is destroyed. A path without geometry has/// none.+#[derive(Clone, Copy, Debug)]#[repr(C)]pub struct PathGeometryData {pub verbs: *const u8,@@ -26,6 +27,21 @@ pub struct PathGeometryData {pub fill_rule: u8,}+/// No contours.+impl Default for PathGeometryData {+ fn default() -> Self {+ Self {+ verbs: std::ptr::null(),+ verb_count: 0,+ points: std::ptr::null(),+ point_count: 0,+ conic_weights: std::ptr::null(),+ conic_weight_count: 0,+ fill_rule: 0,+ }+ }+}+fn point(x: f32, y: f32) -> FloatPoint {FloatPoint { x, y }}diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 1b0944c19a7..5283b3247cc 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -1230,6 +1230,22 @@ static Gfx::AffineTransform content_to_frame_of(RustFFI::FfiSublayerPlacement coreturn { transform[0], transform[1], transform[2], transform[3], transform[4], transform[5] };}+static Optional<RemoteSublayer::PathClip> path_clip_of(RustFFI::FfiSublayerPlacement const& placement)+{+ if (!placement.is_clipped_by_path)+ return {};+ auto contours = Gfx::PathData::from_ffi(placement.clip_path_contours);+ auto const* path_to_frame = placement.clip_path_to_frame;+ RemoteSublayer::PathClip path_clip;+ path_clip.path_identity = placement.clip_path_identity;+ path_clip.verbs.append(contours.verbs.data(), contours.verbs.size());+ path_clip.points.append(contours.points.data(), contours.points.size());+ path_clip.conic_weights.append(contours.conic_weights.data(), contours.conic_weights.size());+ path_clip.winding_rule = placement.clip_path_fill_rule;+ path_clip.path_to_frame = { path_to_frame[0], path_to_frame[1], path_to_frame[2], path_to_frame[3], path_to_frame[4], path_to_frame[5] };+ return path_clip;+}+bool CompositorState::remote_layer_can_show(RemoteLayer& remote_layer, Web::CompositorContextId context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const& placement, double device_pixel_ratio){auto content = remote_layer_content(presented_context(context_id), kind, media_id);@@ -1240,6 +1256,7 @@ bool CompositorState::remote_layer_can_show(RemoteLayer& remote_layer, Web::Comp.content_to_viewport = content_to_frame_of(placement),.clip_rect = placement.clip_rect,.rounded_clip = rounded_clip_of(placement),+ .is_clipped_by_path = placement.is_clipped_by_path,.scaling_mode = placement.scaling_mode,};return remote_layer.can_show(window_server_placement, *content, device_pixel_ratio);@@ -1332,6 +1349,7 @@ Vector<RemoteSublayer>* CompositorState::build_sublayers(Web::CompositorContextI.content_to_frame = content_to_frame_of(placement),.clip_rect = placement.clip_rect,.rounded_clip = rounded_clip_of(placement),+ .path_clip = path_clip_of(placement),.scaling_mode = placement.scaling_mode,});}diff --git a/Services/Compositor/CoreAnimationWindowServer.h b/Services/Compositor/CoreAnimationWindowServer.hindex 687f21d0d9d..f6cb93fab56 100644--- a/Services/Compositor/CoreAnimationWindowServer.h+++ b/Services/Compositor/CoreAnimationWindowServer.h@@ -90,6 +90,10 @@ private:// content, or the one layer of a group, a tile or a color.void* outermost_layer { nullptr };void* rounded_clip_layer { nullptr };+ // The mask of the outermost layer of placed content clipped by a path, and the identity of the path its+ // outline was made of.+ void* path_clip_mask_layer { nullptr };+ Optional<u64> identity_of_path_in_clip_mask;void* content_layer { nullptr };Variant<Empty, NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease> content;// What a group, a tile or a color was last shown with, so that a frame sets only what it changes.@@ -108,6 +112,7 @@ private:ShownSublayer& shown_sublayer_of_kind(u64 identity, SublayerKind);void use_content_layer_of_kind_for(ShownSublayer&, RemoteSublayer const&);void update_shown_sublayer(ShownSublayer&, RemoteSublayer&);+ void update_path_clip_mask(ShownSublayer&, RemoteSublayer const&);void update_shown_group(ShownSublayer&, RemoteSublayer::Group const&);void update_shown_tile(ShownSublayer&, RemoteSublayer::Tile&, Gfx::IntRect);void update_shown_color(ShownSublayer&, Gfx::Color, Gfx::IntRect);diff --git a/Services/Compositor/CoreAnimationWindowServer.mm b/Services/Compositor/CoreAnimationWindowServer.mmindex feba157fcec..ccc21817689 100644--- a/Services/Compositor/CoreAnimationWindowServer.mm+++ b/Services/Compositor/CoreAnimationWindowServer.mm@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Array.h>#include <AK/HashTable.h>#include <AK/Math.h>#include <AK/ScopeGuard.h>@@ -15,6 +16,8 @@#include <LibGfx/SharedImageBuffer.h>#include <LibMediaCodecs/VideoSurface.h>+#include <core/SkPath.h>+#include <core/SkPoint.h>#include <dlfcn.h>#include <objc/runtime.h>@@ -534,6 +537,7 @@ void CoreAnimationRemoteLayer::update_shown_sublayer(ShownSublayer& shown_sublayuse_content_layer_of_kind_for(shown_sublayer, sublayer);auto* content_layer = as_layer(shown_sublayer.content_layer);clip_layer.frame = in_points(sublayer.clip_rect, device_pixel_ratio);+ update_path_clip_mask(shown_sublayer, sublayer);// The content layer is placed relative to the innermost layer that clips it.auto origin_of_content_parent = sublayer.clip_rect.location();@@ -592,6 +596,134 @@ void CoreAnimationRemoteLayer::update_shown_sublayer(ShownSublayer& shown_sublayshow_content(shown_sublayer, sublayer);}+// CoreGraphics has no conic curves, so a conic is drawn as quadratic curves that stray from it by at most this, in the+// units of the space of its path.+static constexpr float conic_tolerance_in_units_of_path = 0.1f;+static constexpr int most_halvings_of_conic_into_quadratic_curves = 5;++// How many times a conic is halved into quadratic curves for them to stay within the tolerance of it, by the bound on+// how far a single quadratic curve strays from it. Each halving quarters how far the curves stray.+static int halvings_of_conic_into_quadratic_curves(SkPoint start, SkPoint control, SkPoint end, float weight)+{+ auto weight_past_parabola = weight - 1;+ auto factor = weight_past_parabola / (4 * (2 + weight_past_parabola));+ auto x = factor * (start.x() - 2 * control.x() + end.x());+ auto y = factor * (start.y() - 2 * control.y() + end.y());+ auto distance_strayed = AK::sqrt(x * x + y * y);+ int halvings = 0;+ while (halvings < most_halvings_of_conic_into_quadratic_curves && distance_strayed > conic_tolerance_in_units_of_path) {+ distance_strayed *= 0.25f;+ ++halvings;+ }+ return halvings;+}++static void append_conic_as_quadratic_curves(CGMutablePathRef outline, Gfx::FloatPoint control, Gfx::FloatPoint end, float weight)+{+ auto current_point = CGPathGetCurrentPoint(outline);+ auto start = SkPoint::Make(current_point.x, current_point.y);+ auto skia_control = SkPoint::Make(control.x(), control.y());+ auto skia_end = SkPoint::Make(end.x(), end.y());+ auto halvings = halvings_of_conic_into_quadratic_curves(start, skia_control, skia_end, weight);+ Array<SkPoint, 1 + 2 * (1 << most_halvings_of_conic_into_quadratic_curves)> quadratic_curve_points;+ auto quadratic_curve_count = SkPath::ConvertConicToQuads(start, skia_control, skia_end, weight, quadratic_curve_points.data(), halvings);+ for (int index = 0; index < quadratic_curve_count; ++index) {+ auto const& curve_control = quadratic_curve_points[1 + 2 * index];+ auto const& curve_end = quadratic_curve_points[2 + 2 * index];+ CGPathAddQuadCurveToPoint(outline, nullptr, curve_control.x(), curve_control.y(), curve_end.x(), curve_end.y());+ }+}++// The outline of the path in its own space.+static CGPathRef create_outline_of_path(RemoteSublayer::PathClip const& path_clip)+{+ auto* outline = CGPathCreateMutable();+ auto const& points = path_clip.points;+ size_t index_of_next_point = 0;+ size_t index_of_next_conic_weight = 0;+ auto next_point = [&] { return points[index_of_next_point++]; };+ for (auto verb : path_clip.verbs) {+ switch (verb) {+ case Gfx::PathVerb::Move: {+ auto point = next_point();+ CGPathMoveToPoint(outline, nullptr, point.x(), point.y());+ break;+ }+ case Gfx::PathVerb::Line: {+ auto point = next_point();+ CGPathAddLineToPoint(outline, nullptr, point.x(), point.y());+ break;+ }+ case Gfx::PathVerb::Quad: {+ auto control = next_point();+ auto end = next_point();+ CGPathAddQuadCurveToPoint(outline, nullptr, control.x(), control.y(), end.x(), end.y());+ break;+ }+ case Gfx::PathVerb::Conic: {+ auto control = next_point();+ auto end = next_point();+ append_conic_as_quadratic_curves(outline, control, end, path_clip.conic_weights[index_of_next_conic_weight++]);+ break;+ }+ case Gfx::PathVerb::Cubic: {+ auto first_control = next_point();+ auto second_control = next_point();+ auto end = next_point();+ CGPathAddCurveToPoint(outline, nullptr, first_control.x(), first_control.y(), second_control.x(), second_control.y(), end.x(), end.y());+ break;+ }+ case Gfx::PathVerb::Close:+ CGPathCloseSubpath(outline);+ break;+ }+ }+ return outline;+}++// The mask stays in the space of the path, and its transform maps that space into the clip layer, whose points have+// their origin at the origin of the clip rect: from the path's space to the frame's pixels, then to pixels from the+// origin of the clip rect, then to points. With its anchor point and position at the origin, the mask is placed by+// that transform alone.+void CoreAnimationRemoteLayer::update_path_clip_mask(ShownSublayer& shown_sublayer, RemoteSublayer const& sublayer)+{+ auto* clip_layer = as_layer(shown_sublayer.outermost_layer);+ if (!sublayer.path_clip.has_value()) {+ if (shown_sublayer.path_clip_mask_layer) {+ clip_layer.mask = nil;+ [as_layer(shown_sublayer.path_clip_mask_layer) release];+ shown_sublayer.path_clip_mask_layer = nullptr;+ shown_sublayer.identity_of_path_in_clip_mask = {};+ }+ return;+ }+ auto const& path_clip = *sublayer.path_clip;+ if (!shown_sublayer.path_clip_mask_layer) {+ auto* mask_layer = [[CAShapeLayer alloc] init];+ mask_layer.anchorPoint = CGPointZero;+ mask_layer.position = CGPointZero;+ clip_layer.mask = mask_layer;+ shown_sublayer.path_clip_mask_layer = mask_layer;+ }+ auto* mask_layer = static_cast<CAShapeLayer*>(shown_sublayer.path_clip_mask_layer);+ if (shown_sublayer.identity_of_path_in_clip_mask != path_clip.path_identity) {+ auto* outline = create_outline_of_path(path_clip);+ mask_layer.path = outline;+ CGPathRelease(outline);+ shown_sublayer.identity_of_path_in_clip_mask = path_clip.path_identity;+ }+ auto* fill_rule = path_clip.winding_rule == Gfx::WindingRule::EvenOdd ? kCAFillRuleEvenOdd : kCAFillRuleNonZero;+ if (![mask_layer.fillRule isEqualToString:fill_rule])+ mask_layer.fillRule = fill_rule;++ auto device_pixel_ratio = m_device_pixel_ratio;+ auto origin_of_clip_rect = sublayer.clip_rect.location();+ auto path_to_clip_layer = to_core_graphics(path_clip.path_to_frame);+ path_to_clip_layer = CGAffineTransformConcat(path_to_clip_layer, CGAffineTransformMakeTranslation(-origin_of_clip_rect.x(), -origin_of_clip_rect.y()));+ path_to_clip_layer = CGAffineTransformConcat(path_to_clip_layer, CGAffineTransformMakeScale(1 / device_pixel_ratio, 1 / device_pixel_ratio));+ mask_layer.affineTransform = path_to_clip_layer;+}+static CGPoint in_points(Gfx::FloatPoint point, double device_pixel_ratio){return CGPointMake(point.x() / device_pixel_ratio, point.y() / device_pixel_ratio);@@ -1004,6 +1136,8 @@ void CoreAnimationRemoteLayer::stop_showing_sublayer(ShownSublayer& shown_sublay[as_layer(shown_sublayer.content_layer) release];if (shown_sublayer.rounded_clip_layer)[as_layer(shown_sublayer.rounded_clip_layer) release];+ if (shown_sublayer.path_clip_mask_layer)+ [as_layer(shown_sublayer.path_clip_mask_layer) release];[as_layer(shown_sublayer.outermost_layer) release];}diff --git a/Services/Compositor/DirectCompositionWindowServer.cpp b/Services/Compositor/DirectCompositionWindowServer.cppindex 00bb752bd11..c9d4a99578f 100644--- a/Services/Compositor/DirectCompositionWindowServer.cpp+++ b/Services/Compositor/DirectCompositionWindowServer.cpp@@ -646,8 +646,10 @@ Compositing::RemoteLayerHostHandle DirectCompositionRemoteLayer::host_handle() creturn { .kind = Compositing::RemoteLayerHostKind::Win32ChildWindow, .id = static_cast<u64>(reinterpret_cast<uintptr_t>(m_window)) };}-bool DirectCompositionRemoteLayer::can_show(WindowServerPlacement const&, Content const& content, double) const+bool DirectCompositionRemoteLayer::can_show(WindowServerPlacement const& placement, Content const& content, double) const{+ if (placement.is_clipped_by_path)+ return false;return content.visit([&](NonnullRefPtr<PresentableSurface> const& surface) {return surface->window_server_surface() != nullptr && surface->painting_surface().skia_backend_context() == window_server_impl().skia_backend_context.ptr();diff --git a/Services/Compositor/RemoteSublayer.h b/Services/Compositor/RemoteSublayer.hindex defb5f7d8fe..9a5dfc77913 100644--- a/Services/Compositor/RemoteSublayer.h+++ b/Services/Compositor/RemoteSublayer.h@@ -16,9 +16,12 @@#include <LibGfx/AffineTransform.h>#include <LibGfx/Color.h>#include <LibGfx/CornerRadii.h>+#include <LibGfx/PathData.h>+#include <LibGfx/Point.h>#include <LibGfx/Rect.h>#include <LibGfx/ScalingMode.h>#include <LibGfx/Size.h>+#include <LibGfx/WindingRule.h>#include <LibMediaCodecs/VideoFrame.h>namespace Compositor {@@ -36,6 +39,19 @@ struct RemoteSublayer {bool rounds_bottom_left { false };};+ // A path that clips the content, with a copy of its contours, as the path the copy is of may be gone by the time+ // the frame is shown. The contours are in a space of their own, which the transform maps into the frame.+ struct PathClip {+ // Tells the path apart from every other path of the process, so that a frame that clips by the same path as+ // the one before does not make its outline again.+ u64 path_identity { 0 };+ Vector<Gfx::PathVerb> verbs;+ Vector<Gfx::FloatPoint> points;+ Vector<float> conic_weights;+ Gfx::WindingRule winding_rule { Gfx::WindingRule::Nonzero };+ Gfx::AffineTransform path_to_frame;+ };+// Holds the sublayers that name it as their group.struct Group {// From the pixels of the group to those of the group it is in, or to those of the frame.@@ -88,6 +104,7 @@ struct RemoteSublayer {Gfx::AffineTransform content_to_frame;Gfx::FloatRect clip_rect;Optional<RoundedClip> rounded_clip;+ Optional<PathClip> path_clip;Gfx::ScalingMode scaling_mode { Gfx::ScalingMode::Bilinear };};@@ -97,6 +114,7 @@ struct WindowServerPlacement {Gfx::AffineTransform content_to_viewport;Gfx::FloatRect clip_rect;Optional<RemoteSublayer::RoundedClip> rounded_clip;+ bool is_clipped_by_path { false };Gfx::ScalingMode scaling_mode { Gfx::ScalingMode::Bilinear };};diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex 6c9be8bf323..d80c6c8ef82 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -61,6 +61,8 @@ fn main() -> Result<(), Box<dyn Error>> {("IntRect", "Gfx::IntRect"),("IntSize", "Gfx::IntSize"),("ScalingMode", "Gfx::ScalingMode"),+ ("WindingRule", "Gfx::WindingRule"),+ ("PathGeometryData", "Gfx::FFI::PathGeometryData"),("SpatialNodeIndex", "Compositing::SpatialNodeIndex"),("RawAttachment", "IPC::RawAttachment"),("RawMessage", "IPC::FfiRawMessage"),@@ -102,8 +104,10 @@ fn main() -> Result<(), Box<dyn Error>> {"LibGfx/CornerRadii.h","LibGfx/Point.h","LibGfx/Rect.h",+ "LibGfx/RustFFI.h","LibGfx/ScalingMode.h","LibGfx/Size.h",+ "LibGfx/WindingRule.h","LibIPC/RawAttachment.h","LibCompositing/RustFFI.h","LibIPC/RawMessage.h",diff --git a/Services/Compositor/Rust/src/presenting/window_server.rs b/Services/Compositor/Rust/src/presenting/window_server.rsindex b714775d675..4871d329260 100644--- a/Services/Compositor/Rust/src/presenting/window_server.rs+++ b/Services/Compositor/Rust/src/presenting/window_server.rs@@ -184,8 +184,10 @@ impl WindowServerLayers {}}+/// The placement as the window server is handed it, whose path contours are lent from `placement`.fn sublayer_placement_of(placement: &WindowServerPlacement) -> FfiSublayerPlacement {let rounded_clip = placement.rounded_clip;+ let path_clip = placement.path_clip.as_ref();FfiSublayerPlacement {content_rect: placement.content_rect,content_to_frame: placement.content_to_viewport.values,@@ -197,6 +199,11 @@ fn sublayer_placement_of(placement: &WindowServerPlacement) -> FfiSublayerPlacemrounds_top_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_right),rounds_bottom_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_right),rounds_bottom_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_left),+ is_clipped_by_path: path_clip.is_some(),+ clip_path_identity: path_clip.map_or(0, |clip| clip.path.identity()),+ clip_path_fill_rule: path_clip.map(|clip| clip.fill_rule).unwrap_or_default(),+ clip_path_to_frame: path_clip.map_or([0.0; 6], |clip| clip.path_to_viewport.values),+ clip_path_contours: path_clip.map(|clip| clip.path.geometry_data()).unwrap_or_default(),scaling_mode: placement.scaling_mode,}}diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex 724f9fef2f7..b2657eb6c11 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -29,7 +29,8 @@ use libcompositing_rust::ipc_types::{};use libcompositing_rust::time::MonotonicTime;use libcompositing_rust::webgl::ImageSource;-use libgfx_rust::{Color, CornerRadii, FloatRect, IntRect, IntSize, ScalingMode};+use libgfx_rust::path::ffi::PathGeometryData;+use libgfx_rust::{Color, CornerRadii, FloatRect, IntRect, IntSize, ScalingMode, WindingRule};use std::collections::HashMap;use std::ffi::{CStr, c_char, c_void};use std::ptr::NonNull;@@ -113,7 +114,7 @@ pub enum MediaKind {}/// Where the window server shows a sublayer, and how it clips it, in device pixels.-#[derive(Clone, Copy, Debug, Default, PartialEq)]+#[derive(Clone, Copy, Debug, Default)]#[repr(C)]pub struct FfiSublayerPlacement {pub content_rect: IntRect,@@ -127,9 +128,59 @@ pub struct FfiSublayerPlacement {pub rounds_top_right: bool,pub rounds_bottom_right: bool,pub rounds_bottom_left: bool,+ /// Whether the content is also clipped by a path, which is in a space of its own.+ pub is_clipped_by_path: bool,+ pub clip_path_identity: u64,+ pub clip_path_fill_rule: WindingRule,+ /// The a, b, c, d, e and f of the affine transform from the space of the path to the frame.+ pub clip_path_to_frame: [f32; 6],+ /// Lent for the call that builds the sublayers, or that asks whether a remote layer can show the placement: the+ /// window server placement this is made from holds the path, and that of a sublayer lives in the layers of the+ /// frame painted last. A copy kept past that call, as the sublayers of the latest frame are, is never read+ /// through, so placements are told apart by the identity of the path, never by these contours.+ pub clip_path_contours: PathGeometryData,pub scaling_mode: ScalingMode,}+impl PartialEq for FfiSublayerPlacement {+ fn eq(&self, other: &Self) -> bool {+ // Each field is named, so a new field does not compile until it is compared too.+ let Self {+ content_rect,+ content_to_frame,+ clip_rect,+ has_rounded_clip,+ rounded_clip_rect,+ rounded_clip_radius,+ rounds_top_left,+ rounds_top_right,+ rounds_bottom_right,+ rounds_bottom_left,+ is_clipped_by_path,+ clip_path_identity,+ clip_path_fill_rule,+ clip_path_to_frame,+ clip_path_contours: _,+ scaling_mode,+ } = self;+ *content_rect == other.content_rect+ && *content_to_frame == other.content_to_frame+ && *clip_rect == other.clip_rect+ && *has_rounded_clip == other.has_rounded_clip+ && *rounded_clip_rect == other.rounded_clip_rect+ && *rounded_clip_radius == other.rounded_clip_radius+ && *rounds_top_left == other.rounds_top_left+ && *rounds_top_right == other.rounds_top_right+ && *rounds_bottom_right == other.rounds_bottom_right+ && *rounds_bottom_left == other.rounds_bottom_left+ && *is_clipped_by_path == other.is_clipped_by_path+ && *clip_path_identity == other.clip_path_identity+ && *clip_path_fill_rule == other.clip_path_fill_rule+ && *clip_path_to_frame == other.clip_path_to_frame+ && *scaling_mode == other.scaling_mode+ }+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]pub enum SublayerContentKind {diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-squircle-box.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-squircle-box.txtnew file mode 100644index 00000000000..ed52d9938d2--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-in-squircle-box.txt@@ -0,0 +1,4 @@+Layers (for a window server that shows tiles and filters what is below layers):+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[17,17 206x126] can be shown by the window server: clip=[20,20 200x120] path=[20,20 200x120]+diff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txtindex a4599b20721..147a2ff598b 100644--- a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txt+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-clip-path.txt@@ -8,8 +8,8 @@ AccumulatedVisualContext Tree:[e0 in s0] effects=[]Layers (for a window server that shows tiles and filters what is below layers):- [L0] base space=viewport held by the frame: it is under a layer the frame holds- [L1] canvas #0 space=viewport region=[67,27 106x106] replayed: clipped by a path+ [L0] base space=viewport+ [L1] canvas #0 space=viewport region=[67,27 106x106] can be shown by the window server: clip=[70,30 100x100] path=[70,30 100x100]DisplayList:L1 DrawCanvas@s1/c0/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foregrounddiff --git a/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-two-clip-paths.txt b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-two-clip-paths.txtnew file mode 100644index 00000000000..2f5ae3ab80d--- /dev/null+++ b/Tests/LibWeb/Text/expected/display_list/compositing-layers-canvas-under-two-clip-paths.txt@@ -0,0 +1,17 @@+AccumulatedVisualContext Tree:+ spatial:+ [s0] transform=[1,0,0,1,0,0] origin=(0,0) (Viewport<#document>)+ [s1] scroll (Viewport<#document>)+ clips:+ [c0 in s1] clip_path=[bounds: 60,20 120x120, curved path: 129 commands] (BlockContainer<DIV>#outer)+ [c1 in s1] clip_path=[bounds: 30,30 180x100, curved path: 129 commands] (CanvasBox<CANVAS>#canvas)+ effects:+ [e0 in s0] effects=[]++Layers (for a window server that shows tiles and filters what is below layers):+ [L0] base space=viewport held by the frame: it is under a layer the frame holds+ [L1] canvas #0 space=viewport region=[57,27 126x106] replayed: clipped by more than one path++DisplayList:+L1 DrawCanvas@s1/c1/e0 dst_rect=[20,20 200x120] canvas_id=canvas1 scaling_mode=Bilinear owner=CanvasBox<CANVAS>#canvas phase=foreground+diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-squircle-box.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-squircle-box.htmlnew file mode 100644index 00000000000..daa1ba1a5dd--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-in-squircle-box.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ #box { position: absolute; left: 20px; top: 20px; width: 200px; height: 120px; overflow: hidden; border-radius: 40px; corner-shape: squircle; }+ canvas { display: block; }+</style>+<div id="box"><canvas id="canvas" width="200" height="120"></canvas></div>+<script>+ test(() => {+ const context = canvas.getContext("2d");+ context.fillStyle = "blue";+ context.fillRect(0, 0, canvas.width, canvas.height);+ const dump = internals.dumpDisplayList();+ println(dump.slice(dump.indexOf("\nLayers") + 1, dump.indexOf("\nDisplayList:")));+ });+</script>diff --git a/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-two-clip-paths.html b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-two-clip-paths.htmlnew file mode 100644index 00000000000..c7b2cf045f9--- /dev/null+++ b/Tests/LibWeb/Text/input/display_list/compositing-layers-canvas-under-two-clip-paths.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ body { margin: 0; }+ #outer { position: absolute; left: 20px; top: 20px; clip-path: circle(60px at 100px 60px); }+ canvas { display: block; clip-path: ellipse(90px 50px at 100px 60px); }+</style>+<div id="outer"><canvas id="canvas" width="200" height="120"></canvas></div>+<script>+ test(() => {+ const context = canvas.getContext("2d");+ context.fillStyle = "blue";+ context.fillRect(0, 0, canvas.width, canvas.height);+ println(internals.dumpDisplayList());+ });+</script>