Truly independent web browser
LibGfx+Compositor: Make the canvas player draw with Skia directly
Aliaksandr Kalenikeba724ef4725
diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rsindex b5a65f8ff44..d47b009a19b 100644--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs@@ -1751,7 +1751,6 @@ pub enum Canvas2DPaintKind {}ffi_enum_bytes!(Canvas2DPaintKind as u8);-// The values of Gfx::CanvasPatternPaintStyle::Repetition.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]#[repr(u8)]pub enum Canvas2DPatternRepetition {diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txtindex 47f7571e082..a2af26f8f6e 100644--- a/Libraries/LibGfx/CMakeLists.txt+++ b/Libraries/LibGfx/CMakeLists.txt@@ -29,7 +29,6 @@ set(SOURCESRustProcessState.cppImageFormats/JPEGWriter.cppImageFormats/PNGWriter.cpp- PaintStyle.cppPalette.cppPathData.cppPoint.cppdiff --git a/Libraries/LibGfx/Gradients.h b/Libraries/LibGfx/Gradients.hindex 58be7c00fa2..79ec9badee1 100644--- a/Libraries/LibGfx/Gradients.h+++ b/Libraries/LibGfx/Gradients.h@@ -7,19 +7,10 @@#pragma once#include <AK/Math.h>-#include <LibGfx/Color.h>#include <LibGfx/Size.h>namespace Gfx {-struct ColorStop {- Color color;- float position = AK::NaN<float>;- Optional<float> transition_hint = {};-- bool operator==(ColorStop const&) const = default;-};-inline float normalized_gradient_angle_radians(float gradient_angle){// Adjust angle so 0 degrees is bottomdiff --git a/Libraries/LibGfx/PaintStyle.cpp b/Libraries/LibGfx/PaintStyle.cppdeleted file mode 100644index fee19b2f3d1..00000000000--- a/Libraries/LibGfx/PaintStyle.cpp+++ /dev/null@@ -1,52 +0,0 @@-/*- * Copyright (c) 2023, MacDue <[email protected]>- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGfx/DecodedImageFrame.h>-#include <LibGfx/PaintStyle.h>--namespace Gfx {--// NB: Keep canvas paint-style factories in LibGfx so the objects use the same RTTI-// as the dynamic casts in canvas command conversion. Inlined factories in-// libraries with hidden visibility can produce separate copies of the RTTI.-ErrorOr<NonnullRefPtr<SolidColorPaintStyle>> SolidColorPaintStyle::create(Color color)-{- return adopt_nonnull_ref_or_enomem(new (nothrow) SolidColorPaintStyle(color));-}--CanvasPatternPaintStyle::CanvasPatternPaintStyle(Optional<DecodedImageFrame> image, Repetition repetition)- : m_image(move(image))- , m_repetition(repetition)-{-}--ErrorOr<NonnullRefPtr<CanvasPatternPaintStyle>> CanvasPatternPaintStyle::create(Optional<DecodedImageFrame> image, Repetition repetition)-{- return adopt_nonnull_ref_or_enomem(new (nothrow) CanvasPatternPaintStyle(move(image), repetition));-}--Optional<DecodedImageFrame> CanvasPatternPaintStyle::image() const-{- return m_image;-}--ErrorOr<NonnullRefPtr<CanvasLinearGradientPaintStyle>> CanvasLinearGradientPaintStyle::create(FloatPoint p0, FloatPoint p1)-{- return adopt_nonnull_ref_or_enomem(new (nothrow) CanvasLinearGradientPaintStyle(p0, p1));-}--ErrorOr<NonnullRefPtr<CanvasConicGradientPaintStyle>> CanvasConicGradientPaintStyle::create(FloatPoint center, float start_angle)-{- return adopt_nonnull_ref_or_enomem(new (nothrow) CanvasConicGradientPaintStyle(center, start_angle));-}--ErrorOr<NonnullRefPtr<CanvasRadialGradientPaintStyle>> CanvasRadialGradientPaintStyle::create(FloatPoint start_center, float start_radius, FloatPoint end_center, float end_radius)-{- return adopt_nonnull_ref_or_enomem(new (nothrow) CanvasRadialGradientPaintStyle(start_center, start_radius, end_center, end_radius));-}--}diff --git a/Libraries/LibGfx/PaintStyle.h b/Libraries/LibGfx/PaintStyle.hdeleted file mode 100644index 1f936ae6e5d..00000000000--- a/Libraries/LibGfx/PaintStyle.h+++ /dev/null@@ -1,162 +0,0 @@-/*- * Copyright (c) 2023, MacDue <[email protected]>- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <AK/QuickSort.h>-#include <AK/RefCounted.h>-#include <AK/Vector.h>-#include <LibGfx/AffineTransform.h>-#include <LibGfx/Color.h>-#include <LibGfx/DecodedImageFrame.h>-#include <LibGfx/Forward.h>-#include <LibGfx/Gradients.h>-#include <LibGfx/Rect.h>--namespace Gfx {--class PaintStyle : public RefCounted<PaintStyle> {-public:- virtual ~PaintStyle() = default;- virtual bool is_visible() const { return true; }-};--class SolidColorPaintStyle : public PaintStyle {-public:- static ErrorOr<NonnullRefPtr<SolidColorPaintStyle>> create(Color color);-- bool is_visible() const override { return m_color.alpha() > 0; }-- Color const& color() const { return m_color; }--private:- SolidColorPaintStyle(Color color)- : m_color(color)- {- }-- Color m_color;-};--class GradientPaintStyle : public PaintStyle {-public:- ErrorOr<void> add_color_stop(float position, Color color, Optional<float> transition_hint = {})- {- return add_color_stop(ColorStop { color, position, transition_hint });- }-- ErrorOr<void> add_color_stop(ColorStop stop, bool sort = true)- {- TRY(m_color_stops.try_append(stop));- if (sort)- quick_sort(m_color_stops, [](auto& a, auto& b) { return a.position < b.position; });- return {};- }-- ReadonlySpan<ColorStop> color_stops() const { return m_color_stops; }- void set_color_stops(Vector<ColorStop>&& color_stops) { m_color_stops = move(color_stops); }-- bool is_visible() const override- {- return any_of(m_color_stops, [](auto& stop) { return stop.color.alpha() > 0; });- }--private:- Vector<ColorStop, 4> m_color_stops;-};--class CanvasPatternPaintStyle : public PaintStyle {-public:- enum class Repetition : u8 {- Repeat,- RepeatX,- RepeatY,- NoRepeat- };-- static ErrorOr<NonnullRefPtr<CanvasPatternPaintStyle>> create(Optional<DecodedImageFrame> image, Repetition repetition);-- Optional<DecodedImageFrame> image() const;- Repetition repetition() const { return m_repetition; }- Optional<AffineTransform> const& transform() const { return m_transform; }- void set_transform(AffineTransform const& transform) { m_transform = transform; }--private:- CanvasPatternPaintStyle(Optional<DecodedImageFrame> image, Repetition repetition);-- Optional<DecodedImageFrame> m_image;- Repetition m_repetition { Repetition::Repeat };- Optional<AffineTransform> m_transform;-};--// The following paint styles implement the gradients required for the HTML canvas.-// These gradients are (unlike CSS ones) not relative to the painted shape, and do not-// support premultiplied alpha.--class CanvasLinearGradientPaintStyle : public GradientPaintStyle {-public:- static ErrorOr<NonnullRefPtr<CanvasLinearGradientPaintStyle>> create(FloatPoint p0, FloatPoint p1);-- FloatPoint start_point() const { return m_p0; }- FloatPoint end_point() const { return m_p1; }--private:- CanvasLinearGradientPaintStyle(FloatPoint p0, FloatPoint p1)- : m_p0(p0)- , m_p1(p1)- {- }-- FloatPoint m_p0;- FloatPoint m_p1;-};--class CanvasConicGradientPaintStyle : public GradientPaintStyle {-public:- static ErrorOr<NonnullRefPtr<CanvasConicGradientPaintStyle>> create(FloatPoint center, float start_angle = 0.0f);-- FloatPoint center() const { return m_center; }- float start_angle() const { return m_start_angle; }--private:- CanvasConicGradientPaintStyle(FloatPoint center, float start_angle)- : m_center(center)- , m_start_angle(start_angle)- {- }-- FloatPoint m_center;- float m_start_angle { 0.0f };-};--class CanvasRadialGradientPaintStyle : public GradientPaintStyle {-public:- static ErrorOr<NonnullRefPtr<CanvasRadialGradientPaintStyle>> create(FloatPoint start_center, float start_radius, FloatPoint end_center, float end_radius);-- Gfx::FloatPoint start_center() const { return m_start_center; }- float start_radius() const { return m_start_radius; }- Gfx::FloatPoint end_center() const { return m_end_center; }- float end_radius() const { return m_end_radius; }--private:- CanvasRadialGradientPaintStyle(FloatPoint start_center, float start_radius, FloatPoint end_center, float end_radius)- : m_start_center(start_center)- , m_start_radius(start_radius)- , m_end_center(end_center)- , m_end_radius(end_radius)- {- }-- FloatPoint m_start_center;- float m_start_radius { 0.0f };- FloatPoint m_end_center;- float m_end_radius { 0.0f };-};--}diff --git a/Libraries/LibWeb/SVG/SVGGraphicsElement.h b/Libraries/LibWeb/SVG/SVGGraphicsElement.hindex 3990a3f42f0..9833e44a614 100644--- a/Libraries/LibWeb/SVG/SVGGraphicsElement.h+++ b/Libraries/LibWeb/SVG/SVGGraphicsElement.h@@ -8,7 +8,6 @@#pragma once#include <LibGfx/Matrix4x4.h>-#include <LibGfx/PaintStyle.h>#include <LibWeb/CSS/URL.h>#include <LibWeb/Export.h>#include <LibWeb/SVG/AttributeParsing.h>diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 486095b478a..0bc48ab12c8 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -23,7 +23,6 @@ set(SOURCESHostWebGLContext.cppKeyboardScrollController.cppOpenGLContext.cpp- PainterSkia.cppPaintingSurface.cppPausedDebuggerOverlay.cppPictureInPictureControls.cppdiff --git a/Services/Compositor/Canvas2DCommandPlayer.cpp b/Services/Compositor/Canvas2DCommandPlayer.cppindex 3298dd6041e..a3aaec1581f 100644--- a/Services/Compositor/Canvas2DCommandPlayer.cpp+++ b/Services/Compositor/Canvas2DCommandPlayer.cpp@@ -1,12 +1,18 @@/*- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>+ * Copyright (c) 2024, Andreas Kling <[email protected]>+ * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>+ * Copyright (c) 2024, Lucien Fiorini <[email protected]>+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>** SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Array.h>#include <AK/Assertions.h>+#include <AK/GenericShorthands.h>+#include <AK/Math.h>#include <Compositor/Canvas2DCommandPlayer.h>-#include <Compositor/PainterSkia.h>+#include <Compositor/FontSkia.h>#include <Compositor/PaintingSurface.h>#include <Compositor/SkiaUtils.h>#include <LibCompositing/DisplayList/Canvas2DTape.h>@@ -14,9 +20,18 @@#include <LibGfx/Bitmap.h>#include <LibGfx/Color.h>#include <LibGfx/DecodedImageFrame.h>-#include <LibGfx/PaintStyle.h>+#include <LibGfx/Font/Font.h>#include <core/SkCanvas.h>+#include <core/SkColorSpace.h>+#include <core/SkFont.h>+#include <core/SkImage.h>#include <core/SkPaint.h>+#include <core/SkPath.h>+#include <core/SkPathBuilder.h>+#include <core/SkSurface.h>+#include <effects/SkDashPathEffect.h>+#include <effects/SkGradient.h>+#include <effects/SkImageFilters.h>namespace Compositor {@@ -31,7 +46,7 @@ ErrorOr<NonnullOwnPtr<Canvas2DCommandPlayer>> Canvas2DCommandPlayer::create(RefPCanvas2DCommandPlayer::Canvas2DCommandPlayer(NonnullRefPtr<Gfx::PaintingSurface> surface, Gfx::ColorSpace const& color_space, Resolvers resolvers): m_color_space(color_space), m_surface(move(surface))- , m_painter(make<Gfx::PainterSkia>(*m_surface))+ , m_initial_save_count(m_surface->canvas().save()), m_resolvers(move(resolvers)){}@@ -45,7 +60,7 @@ NonnullRefPtr<Gfx::PaintingSurface> Canvas2DCommandPlayer::surface() constvoid Canvas2DCommandPlayer::clear(Gfx::Color color){- m_painter->clear_rect({ {}, m_surface->size().to_type<float>() }, color);+ clear_rect({ {}, m_surface->size().to_type<float>() }, color);}void Canvas2DCommandPlayer::play(ReadonlyBytes tape)@@ -98,109 +113,347 @@ sk_sp<SkImageFilter> Canvas2DCommandPlayer::image_filter_from(Canvas2DCompositin});}-static Optional<Gfx::CanvasShadow> shadow_from(Canvas2DCompositing const& compositing)+SkColorSpace* Canvas2DCommandPlayer::surface_color_space() const{- if (!compositing.has_shadow)- return {};- return Gfx::CanvasShadow {- .color = compositing.shadow.color,- .offset_x = compositing.shadow.offset_x,- .offset_y = compositing.shadow.offset_y,- .blur = compositing.shadow.blur,- };+ return m_surface->sk_surface().imageInfo().colorSpace();}-RefPtr<Gfx::PaintStyle> Canvas2DCommandPlayer::paint_style_from(Canvas2DPaint const& paint) const+Optional<SkPaint> Canvas2DCommandPlayer::paint_from(Canvas2DPaint const& style, Canvas2DCompositing const& compositing) const{- auto with_color_stops = [&](auto paint_style) -> NonnullRefPtr<Gfx::PaintStyle> {- auto colors = inline_objects<Gfx::Color>(inline_data(paint.color_stops.colors));- auto positions = inline_objects<float>(inline_data(paint.color_stops.positions));- Vector<Gfx::ColorStop> color_stops;- color_stops.ensure_capacity(colors.size());- for (size_t i = 0; i < colors.size(); ++i)- color_stops.unchecked_append({ .color = colors[i], .position = positions[i] });- paint_style->set_color_stops(move(color_stops));- return paint_style;+ SkPaint paint;+ auto* color_space = surface_color_space();++ auto set_shader_with_color_stops = [&](auto make_shader) {+ auto stop_colors = inline_objects<Gfx::Color>(inline_data(style.color_stops.colors));+ auto positions = inline_objects<float>(inline_data(style.color_stops.positions));+ Vector<SkColor4f> colors;+ colors.ensure_capacity(stop_colors.size());+ for (auto const& color : stop_colors)+ colors.unchecked_append(Gfx::to_skia_color4f(color));+ SkGradient gradient { SkGradient::Colors { { colors.data(), colors.size() }, { positions.data(), positions.size() }, SkTileMode::kClamp, sk_ref_sp(color_space) }, {} };+ paint.setShader(make_shader(gradient));};- switch (paint.kind) {+ switch (style.kind) {case Canvas2DPaintKind::Color:- return MUST(Gfx::SolidColorPaintStyle::create(paint.color));- case Canvas2DPaintKind::LinearGradient:- return with_color_stops(MUST(Gfx::CanvasLinearGradientPaintStyle::create(paint.start_point, paint.end_point)));+ paint.setColor(Gfx::to_skia_color4f(style.color), color_space);+ break;+ case Canvas2DPaintKind::LinearGradient: {+ // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createlineargradient+ // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.+ if (style.start_point == style.end_point) {+ paint.setColor(SK_ColorTRANSPARENT);+ break;+ }+ Array points { Gfx::to_skia_point(style.start_point), Gfx::to_skia_point(style.end_point) };+ set_shader_with_color_stops([&](SkGradient const& gradient) {+ return SkShaders::LinearGradient(points.data(), gradient);+ });+ break;+ }case Canvas2DPaintKind::RadialGradient:- return with_color_stops(MUST(Gfx::CanvasRadialGradientPaintStyle::create(paint.start_point, paint.start_radius, paint.end_point, paint.end_radius)));- case Canvas2DPaintKind::ConicGradient:- return with_color_stops(MUST(Gfx::CanvasConicGradientPaintStyle::create(paint.start_point, paint.start_angle)));- case Canvas2DPaintKind::Pattern: {- Optional<Gfx::DecodedImageFrame> image;- if (paint.pattern_has_image) {- auto const* frame = m_resolvers.image_frame(paint.pattern_image_id.value());- if (!frame)- return nullptr;- image = *frame;+ // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient+ // 1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.+ if (style.start_point == style.end_point && style.start_radius == style.end_radius) {+ paint.setColor(SK_ColorTRANSPARENT);+ break;}- auto repetition = static_cast<Gfx::CanvasPatternPaintStyle::Repetition>(to_underlying(paint.pattern_repetition));- auto paint_style = MUST(Gfx::CanvasPatternPaintStyle::create(move(image), repetition));- if (paint.pattern_transform.has_value())- paint_style->set_transform(*paint.pattern_transform);- return paint_style;+ set_shader_with_color_stops([&](SkGradient const& gradient) {+ return SkShaders::TwoPointConicalGradient(Gfx::to_skia_point(style.start_point), style.start_radius, Gfx::to_skia_point(style.end_point), style.end_radius, gradient);+ });+ break;+ case Canvas2DPaintKind::ConicGradient: {+ // NB: The angles of a Skia sweep gradient pick where its colors start and end, and every angle outside of them+ // takes the color of the nearest end. So the gradient is rotated to its start angle instead.+ SkMatrix rotation_to_start_angle;+ rotation_to_start_angle.setRotate(AK::to_degrees(style.start_angle), style.start_point.x(), style.start_point.y());+ set_shader_with_color_stops([&](SkGradient const& gradient) {+ return SkShaders::SweepGradient(Gfx::to_skia_point(style.start_point), 0, 360, gradient, &rotation_to_start_angle);+ });+ break;+ }+ case Canvas2DPaintKind::Pattern: {+ if (!style.pattern_has_image)+ break;+ auto const* frame = m_resolvers.image_frame(style.pattern_image_id.value());+ if (!frame)+ return {};+ auto image = Gfx::sk_image_from_bitmap(frame->bitmap(), frame->color_space());+ if (!image)+ break;++ auto repeat_x = first_is_one_of(style.pattern_repetition, Canvas2DPatternRepetition::Repeat, Canvas2DPatternRepetition::RepeatX);+ auto repeat_y = first_is_one_of(style.pattern_repetition, Canvas2DPatternRepetition::Repeat, Canvas2DPatternRepetition::RepeatY);++ // FIXME: Implement sampling configuration.+ SkSamplingOptions sampling_options { SkFilterMode::kLinear };+ Optional<SkMatrix> pattern_matrix;+ if (style.pattern_transform.has_value())+ pattern_matrix = Gfx::to_skia_matrix(*style.pattern_transform);+ paint.setShader(image->makeShader(+ repeat_x ? SkTileMode::kRepeat : SkTileMode::kDecal,+ repeat_y ? SkTileMode::kRepeat : SkTileMode::kDecal,+ sampling_options,+ pattern_matrix.has_value() ? &pattern_matrix.value() : nullptr));+ break;+ }+ }++ paint.setAlphaf(paint.getAlphaf() * compositing.global_alpha);+ paint.setImageFilter(image_filter_from(compositing));+ return paint;+}++// NB: These operators change the destination even where the source is fully transparent, which makes them affect+// pixels that the source does not cover.+static bool affects_pixels_not_covered_by_source(Gfx::CompositingAndBlendingOperator compositing_and_blending_operator)+{+ return first_is_one_of(compositing_and_blending_operator,+ Gfx::CompositingAndBlendingOperator::Copy,+ Gfx::CompositingAndBlendingOperator::SourceIn,+ Gfx::CompositingAndBlendingOperator::SourceOut,+ Gfx::CompositingAndBlendingOperator::DestinationIn,+ Gfx::CompositingAndBlendingOperator::DestinationATop);+}++// https://html.spec.whatwg.org/multipage/canvas.html#drawing-model+template<typename Callback>+static void draw_with_compositing(SkCanvas& canvas, SkPaint& paint, Canvas2DCompositing const& compositing, Callback draw)+{+ auto compositing_and_blending_operator = compositing.compositing_and_blending_operator;++ // 5. When shadows are drawn, render the shadow from image B, using the current shadow styles, creating image C.+ // 6. When shadows are drawn, composite C within the clipping region over the current output bitmap using the+ // current compositing and blending operator.+ // NB: The current transformation matrix does not affect the offset and the blur of a shadow, so the source is+ // drawn into a layer whose filter makes the shadow in the coordinates of the canvas. The paint carries the+ // global alpha and the filter of the context, so the layer holds image B.+ if (compositing.has_shadow) {+ auto const& shadow = compositing.shadow;+ auto matrix = canvas.getTotalMatrix();+ canvas.save();+ canvas.resetMatrix();+ auto sigma = shadow.blur / 2;+ SkPaint shadow_layer_paint;+ shadow_layer_paint.setImageFilter(SkImageFilters::DropShadowOnly(shadow.offset_x, shadow.offset_y, sigma, sigma, Gfx::to_skia_color4f(shadow.color), sk_ref_sp(canvas.imageInfo().colorSpace()), nullptr));+ shadow_layer_paint.setBlender(Gfx::to_skia_blender(compositing_and_blending_operator));+ canvas.saveLayer(nullptr, &shadow_layer_paint);+ canvas.setMatrix(matrix);+ draw(canvas, paint);+ canvas.restore();+ canvas.restore();}++ // 7. Composite B within the clipping region over the current output bitmap using the current compositing and+ // blending operator.+ // NB: A Skia blend mode only touches the pixels that a draw covers. For the operators that also affect uncovered+ // pixels, the source is drawn into a transparent layer, which is then composited onto all of the destination+ // inside the clip.+ if (!affects_pixels_not_covered_by_source(compositing_and_blending_operator)) {+ paint.setBlender(Gfx::to_skia_blender(compositing_and_blending_operator));+ draw(canvas, paint);+ return;}- VERIFY_NOT_REACHED();++ SkPaint layer_paint;+ layer_paint.setBlender(Gfx::to_skia_blender(compositing_and_blending_operator));+ canvas.saveLayer(nullptr, &layer_paint);+ draw(canvas, paint);+ canvas.restore();+}++// https://html.spec.whatwg.org/multipage/canvas.html#trace-a-path+static SkPath prune_path_for_stroking(SkPath const& path)+{+ // 2. Prune all zero-length line segments from path.+ // 3. Remove from path any subpaths containing no lines (i.e. subpaths with just one point).+ // NB: Skia strokes a zero-length segment with caps, so such segments and the subpaths that are left with no+ // lines are removed before the path is stroked.+ auto is_zero_length = [](SkSpan<SkPoint const> points) {+ for (size_t i = 1; i < points.size(); ++i) {+ if (points[i] != points[0])+ return false;+ }+ return true;+ };++ SkPathBuilder builder(path.getFillType());+ bool subpath_has_lines = false;+ auto iterator = path.iter();+ while (auto record = iterator.next()) {+ auto points = record->fPoints;+ switch (record->fVerb) {+ case SkPathVerb::kMove:+ subpath_has_lines = false;+ continue;+ case SkPathVerb::kClose:+ if (subpath_has_lines)+ builder.close();+ subpath_has_lines = false;+ continue;+ case SkPathVerb::kLine:+ case SkPathVerb::kQuad:+ case SkPathVerb::kConic:+ case SkPathVerb::kCubic:+ break;+ }++ if (is_zero_length(points))+ continue;+ if (!subpath_has_lines) {+ builder.moveTo(points[0]);+ subpath_has_lines = true;+ }+ switch (record->fVerb) {+ case SkPathVerb::kLine:+ builder.lineTo(points[1]);+ break;+ case SkPathVerb::kQuad:+ builder.quadTo(points[1], points[2]);+ break;+ case SkPathVerb::kConic:+ builder.conicTo(points[1], points[2], record->conicWeight());+ break;+ case SkPathVerb::kCubic:+ builder.cubicTo(points[1], points[2], points[3]);+ break;+ default:+ VERIFY_NOT_REACHED();+ }+ }+ return builder.detach();}void Canvas2DCommandPlayer::play_command(Canvas2DFillPath const& command){auto path = path_from(command.path_data);- auto paint_style = paint_style_from(command.paint);- if (!paint_style)+ path.setFillType(Gfx::to_skia_path_fill_type(command.winding_rule));+ auto paint = paint_from(command.paint, command.compositing);+ if (!paint.has_value())return;- m_painter->fill_path(move(path), *paint_style, image_filter_from(command.compositing), command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, command.winding_rule, shadow_from(command.compositing));+ paint->setAntiAlias(true);+ draw_with_compositing(m_surface->canvas(), *paint, command.compositing, [&](SkCanvas& canvas, SkPaint const& paint) {+ canvas.drawPath(path, paint);+ });}void Canvas2DCommandPlayer::play_command(Canvas2DStrokePath const& command){- auto path = path_from(command.path_data);+ // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.+ if (command.thickness <= 0)+ return;++ auto path = prune_path_for_stroking(path_from(command.path_data));auto dash_array = inline_objects<float>(inline_data(command.dash_array));- auto paint_style = paint_style_from(command.paint);- if (!paint_style)+ auto paint = paint_from(command.paint, command.compositing);+ if (!paint.has_value())return;- m_painter->stroke_path(path, *paint_style, image_filter_from(command.compositing), command.thickness, command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, command.cap_style, command.join_style, command.miter_limit, dash_array, command.dash_offset, shadow_from(command.compositing));+ paint->setAntiAlias(true);+ paint->setStyle(SkPaint::Style::kStroke_Style);+ paint->setStrokeWidth(command.thickness);+ paint->setStrokeCap(Gfx::to_skia_cap(command.cap_style));+ paint->setStrokeJoin(Gfx::to_skia_join(command.join_style));+ paint->setStrokeMiter(command.miter_limit);+ paint->setPathEffect(SkDashPathEffect::Make({ dash_array.data(), dash_array.size() }, command.dash_offset));+ draw_with_compositing(m_surface->canvas(), *paint, command.compositing, [&](SkCanvas& canvas, SkPaint const& paint) {+ canvas.drawPath(path, paint);+ });}void Canvas2DCommandPlayer::play_command(Canvas2DDrawGlyphRuns const& command){if (!m_resolvers.font)return;- auto paint_style = paint_style_from(command.paint);- if (!paint_style)+ auto paint = paint_from(command.paint, command.compositing);+ if (!paint.has_value())return;- auto tape_glyphs = inline_objects<DisplayListGlyph>(inline_data(command.glyphs));- Vector<Gfx::CanvasGlyph> glyphs;- glyphs.ensure_capacity(tape_glyphs.size());- for (auto const& glyph : tape_glyphs)- glyphs.unchecked_append({ .position = glyph.position, .glyph_id = glyph.glyph_id });+ struct SkiaGlyphRun {+ SkFont font;+ Vector<SkGlyphID, 32> glyph_ids;+ Vector<SkPoint, 32> glyph_positions;+ };++ auto tape_glyphs = inline_objects<DisplayListGlyph>(inline_data(command.glyphs));auto tape_runs = inline_objects<Canvas2DGlyphRun>(inline_data(command.runs));- Vector<Gfx::CanvasGlyphRun, 2> runs;- runs.ensure_capacity(tape_runs.size());+ Vector<SkiaGlyphRun, 2> skia_runs;+ skia_runs.ensure_capacity(tape_runs.size());size_t first_glyph = 0;for (auto const& run : tape_runs) {// NB: The tape validation guarantees that the runs split the glyphs exactly.- auto run_glyphs = glyphs.span().slice(first_glyph, run.glyph_count);+ auto run_glyphs = tape_glyphs.span().slice(first_glyph, run.glyph_count);first_glyph += run.glyph_count;auto const* font = m_resolvers.font(run.font_id.value());- if (!font)+ if (!font || run_glyphs.is_empty() || font->is_invisible())+ continue;++ auto sk_font = skia_font(*font, 1);+ if (!sk_font.has_value())continue;- runs.unchecked_append({ .font = *font, .glyphs = run_glyphs });++ SkiaGlyphRun skia_run { .font = sk_font.release_value(), .glyph_ids = {}, .glyph_positions = {} };++ // NB: Preserve canvas text's fractional baseline and unhinted outline geometry.+ skia_run.font.setHinting(SkFontHinting::kNone);+ skia_run.font.setForceAutoHinting(false);+ skia_run.font.setBaselineSnap(false);++ // NB: The scale goes on the font rather than the canvas, as it must not scale the paint of the text.+ skia_run.font.setScaleX(skia_run.font.getScaleX() * command.horizontal_scale);++ skia_run.glyph_ids.ensure_capacity(run_glyphs.size());+ skia_run.glyph_positions.ensure_capacity(run_glyphs.size());+ auto font_ascent = font->pixel_metrics().ascent;+ for (auto const& glyph : run_glyphs) {+ skia_run.glyph_ids.unchecked_append(static_cast<SkGlyphID>(glyph.glyph_id));+ skia_run.glyph_positions.unchecked_append({ glyph.position.x() * command.horizontal_scale, glyph.position.y() + font_ascent });+ }+ skia_runs.unchecked_append(move(skia_run));}- m_painter->draw_glyph_runs(runs, command.translation, command.horizontal_scale, *paint_style, image_filter_from(command.compositing), command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, shadow_from(command.compositing));++ // NB: Not drawTextBlob(). Skia caches a drawn SkTextBlob once per subpixel origin, and finds a cached entry by+ // scanning every entry of that blob. Canvas text is often redrawn at moving fractional positions, which+ // piles up thousands of entries per blob and makes each draw scan all of them.+ draw_with_compositing(m_surface->canvas(), *paint, command.compositing, [&](SkCanvas& canvas, SkPaint const& paint) {+ auto draw_runs = [&](SkPaint const& run_paint) {+ for (auto const& run : skia_runs)+ canvas.drawGlyphs({ run.glyph_ids.data(), run.glyph_ids.size() }, { run.glyph_positions.data(), run.glyph_positions.size() }, Gfx::to_skia_point(command.translation), run.font, run_paint);+ };++ if (skia_runs.size() <= 1 || !paint.getImageFilter()) {+ draw_runs(paint);+ return;+ }++ // NB: The filter of the context applies to the text as a whole, so it goes on a layer that holds all runs.+ // Otherwise, what the filter makes of one run would land on top of the other runs.+ SkPaint layer_paint;+ layer_paint.setImageFilter(paint.refImageFilter());+ layer_paint.setBlender(paint.refBlender());+ SkPaint run_paint = paint;+ run_paint.setImageFilter(nullptr);+ run_paint.setBlender(nullptr);+ canvas.saveLayer(nullptr, &layer_paint);+ draw_runs(run_paint);+ canvas.restore();+ });+}++void Canvas2DCommandPlayer::clear_rect(Gfx::FloatRect const& rect, Gfx::Color color)+{+ auto& canvas = m_surface->canvas();+ canvas.save();+ canvas.clipRect(Gfx::to_skia_rect(rect));+ SkPaint paint;+ paint.setColor(Gfx::to_skia_color4f(color), surface_color_space());+ paint.setBlendMode(SkBlendMode::kSrc);+ canvas.drawPaint(paint);+ canvas.restore();}void Canvas2DCommandPlayer::play_command(Canvas2DClearRect const& command){- m_painter->clear_rect(command.rect, command.color);+ clear_rect(command.rect, command.color);}void Canvas2DCommandPlayer::play_command(Canvas2DDrawImageFrame const& command)@@ -208,7 +461,10 @@ void Canvas2DCommandPlayer::play_command(Canvas2DDrawImageFrame const& command)auto const* frame = m_resolvers.image_frame(command.frame_id.value());if (!frame)return;- m_painter->draw_bitmap(command.dst_rect, *frame, command.src_rect, command.scaling_mode, image_filter_from(command.compositing), command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, shadow_from(command.compositing));+ auto image = Gfx::sk_image_from_bitmap(frame->bitmap(), frame->color_space());+ if (!image)+ return;+ draw_image(*image, command.dst_rect, command.src_rect, command.scaling_mode, command.compositing);}void Canvas2DCommandPlayer::play_command(Canvas2DDrawCanvas const& command)@@ -238,32 +494,48 @@ void Canvas2DCommandPlayer::play_command(Canvas2DDrawVideoFrame const& command)void Canvas2DCommandPlayer::draw_image(SkImage const& image, Gfx::FloatRect const& dst_rect, Gfx::FloatRect const& src_rect, Gfx::ScalingMode scaling_mode, Canvas2DCompositing const& compositing){- m_painter->draw_image(image, dst_rect, src_rect, scaling_mode, image_filter_from(compositing), compositing.global_alpha, compositing.compositing_and_blending_operator, shadow_from(compositing));+ SkPaint paint;+ paint.setImageFilter(image_filter_from(compositing));+ paint.setAlpha(static_cast<u8>(compositing.global_alpha * 255));++ draw_with_compositing(m_surface->canvas(), paint, compositing, [&](SkCanvas& canvas, SkPaint const& paint) {+ canvas.drawImageRect(+ &image,+ Gfx::to_skia_rect(src_rect),+ Gfx::to_skia_rect(dst_rect),+ Gfx::to_skia_sampling_options(scaling_mode),+ &paint,+ SkCanvas::kStrict_SrcRectConstraint);+ });}void Canvas2DCommandPlayer::play_command(Canvas2DSetTransform const& command){- m_painter->set_transform(command.transform);+ m_surface->canvas().setMatrix(Gfx::to_skia_matrix(command.transform));}void Canvas2DCommandPlayer::play_command(Canvas2DSave const&){- m_painter->save();+ m_surface->canvas().save();}void Canvas2DCommandPlayer::play_command(Canvas2DRestore const&){- m_painter->restore();+ m_surface->canvas().restore();}void Canvas2DCommandPlayer::play_command(Canvas2DClipPath const& command){- m_painter->clip(path_from(command.path_data), command.winding_rule);+ auto path = path_from(command.path_data);+ path.setFillType(Gfx::to_skia_path_fill_type(command.winding_rule));+ m_surface->canvas().clipPath(path, SkClipOp::kIntersect, true);}void Canvas2DCommandPlayer::play_command(Canvas2DReset const&){- m_painter->reset();+ auto& canvas = m_surface->canvas();+ canvas.restoreToCount(m_initial_save_count);+ canvas.save();}void Canvas2DCommandPlayer::play_command(Canvas2DClearCanvas const& command)diff --git a/Services/Compositor/Canvas2DCommandPlayer.h b/Services/Compositor/Canvas2DCommandPlayer.hindex 1893b93fe33..145cbd98ca6 100644--- a/Services/Compositor/Canvas2DCommandPlayer.h+++ b/Services/Compositor/Canvas2DCommandPlayer.h@@ -17,12 +17,13 @@#include <LibCompositing/DisplayList/DisplayListCommandsGenerated.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/Forward.h>-#include <LibGfx/PaintStyle.h>#include <LibGfx/Rect.h>#include <LibGfx/ScalingMode.h>+class SkColorSpace;class SkImage;class SkImageFilter;+class SkPaint;class SkPath;template<typename T>class sk_sp;@@ -68,16 +69,20 @@ private:ENUMERATE_CANVAS_2D_COMMANDS(DECLARE_PLAY_COMMAND)#undef DECLARE_PLAY_COMMAND+ void clear_rect(Gfx::FloatRect const&, Gfx::Color);void draw_image(SkImage const&, Gfx::FloatRect const& dst_rect, Gfx::FloatRect const& src_rect, Gfx::ScalingMode, Compositing::Canvas2DCompositing const&);ReadonlyBytes inline_data(Compositing::DisplayListDataSpan) const;SkPath path_from(Compositing::DisplayListDataSpan) const;sk_sp<SkImageFilter> image_filter_from(Compositing::Canvas2DCompositing const&) const;- RefPtr<Gfx::PaintStyle> paint_style_from(Compositing::Canvas2DPaint const&) const;+ // The colors of a canvas are in the color space of its surface.+ SkColorSpace* surface_color_space() const;+ // Has no value if the image of a pattern can't be resolved.+ Optional<SkPaint> paint_from(Compositing::Canvas2DPaint const& style, Compositing::Canvas2DCompositing const&) const;Gfx::ColorSpace m_color_space;NonnullRefPtr<Gfx::PaintingSurface> m_surface;- NonnullOwnPtr<Gfx::PainterSkia> m_painter;+ int m_initial_save_count { 0 };Resolvers m_resolvers;// The payload of the record that plays, which the spans of its command address.ReadonlyBytes m_payload;diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 7bd4775da3d..3e7c6e7633a 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -43,6 +43,7 @@#include <LibGfx/Bitmap.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/DecodedImageFrame.h>+#include <LibGfx/Gradients.h>namespace Compositor {@@ -106,20 +107,6 @@ static void clip_to_rounded_rect(SkCanvas& canvas, auto const& rect, Gfx::Cornercanvas.clipRect(to_skia_rect(rect), clip_op, true);}-static SkMatrix to_skia_matrix(Gfx::AffineTransform const& affine_transform)-{- SkScalar affine[6];- affine[0] = affine_transform.a();- affine[1] = affine_transform.b();- affine[2] = affine_transform.c();- affine[3] = affine_transform.d();- affine[4] = affine_transform.e();- affine[5] = affine_transform.f();-- SkMatrix matrix;- matrix.setAffine(affine);- return matrix;-}static SkM44 to_skia_matrix4x4(Gfx::FloatMatrix4x4 const& matrix){return SkM44(diff --git a/Services/Compositor/Forward.h b/Services/Compositor/Forward.hindex eb2e3b55c67..85f17911e65 100644--- a/Services/Compositor/Forward.h+++ b/Services/Compositor/Forward.h@@ -8,7 +8,6 @@namespace Gfx {-class PainterSkia;class PaintingSurface;class SkiaBackendContext;diff --git a/Services/Compositor/PainterSkia.cpp b/Services/Compositor/PainterSkia.cppdeleted file mode 100644index b59bb7922d2..00000000000--- a/Services/Compositor/PainterSkia.cpp+++ /dev/null@@ -1,485 +0,0 @@-/*- * Copyright (c) 2024, Andreas Kling <[email protected]>- * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>- * Copyright (c) 2024, Lucien Fiorini <[email protected]>- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#define AK_DONT_REPLACE_STD--#include <AK/GenericShorthands.h>-#include <AK/String.h>-#include <AK/TypeCasts.h>-#include <Compositor/FontSkia.h>-#include <Compositor/PainterSkia.h>-#include <Compositor/SkiaUtils.h>-#include <LibGfx/DecodedImageFrame.h>-#include <LibGfx/Font/Font.h>--#include <core/SkCanvas.h>-#include <core/SkColorSpace.h>-#include <core/SkFont.h>-#include <core/SkImage.h>-#include <core/SkPath.h>-#include <core/SkPathBuilder.h>-#include <core/SkSurface.h>-#include <effects/SkDashPathEffect.h>-#include <effects/SkGradient.h>-#include <effects/SkImageFilters.h>--namespace Gfx {--static sk_sp<SkImage> sk_image_for_decoded_image_frame(DecodedImageFrame const& frame)-{- return sk_image_from_bitmap(frame.bitmap(), frame.color_space());-}--// NB: The colors of a canvas are in the color space of its surface.-static void set_color(SkPaint& paint, Color color, SkColorSpace* color_space)-{- paint.setColor(to_skia_color4f(color), color_space);-}--static void apply_paint_style(SkPaint& paint, PaintStyle const& style, SkColorSpace* color_space)-{- if (auto const& solid_color = as_if<SolidColorPaintStyle>(style)) {- set_color(paint, solid_color->color(), color_space);- } else if (auto const& linear_gradient = as_if<Gfx::CanvasLinearGradientPaintStyle>(style)) {- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createlineargradient- // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.- if (linear_gradient->start_point() == linear_gradient->end_point()) {- paint.setColor(SK_ColorTRANSPARENT);- return;- }-- auto const& color_stops = linear_gradient->color_stops();-- Vector<SkColor4f> colors;- colors.ensure_capacity(color_stops.size());- Vector<SkScalar> positions;- positions.ensure_capacity(color_stops.size());- for (auto const& color_stop : color_stops) {- colors.unchecked_append(to_skia_color4f(color_stop.color));- positions.unchecked_append(color_stop.position);- }-- Array points { to_skia_point(linear_gradient->start_point()), to_skia_point(linear_gradient->end_point()) };-- SkMatrix matrix;- SkGradient gradient { SkGradient::Colors { { colors.data(), colors.size() }, { positions.data(), positions.size() }, SkTileMode::kClamp, sk_ref_sp(color_space) }, {} };- auto shader = SkShaders::LinearGradient(points.data(), gradient, &matrix);- paint.setShader(shader);- } else if (auto const* radial_gradient = as_if<CanvasRadialGradientPaintStyle>(style)) {- // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient- // 1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.- if (radial_gradient->start_center() == radial_gradient->end_center() && radial_gradient->start_radius() == radial_gradient->end_radius()) {- paint.setColor(SK_ColorTRANSPARENT);- return;- }-- auto const& color_stops = radial_gradient->color_stops();-- Vector<SkColor4f> colors;- colors.ensure_capacity(color_stops.size());- Vector<SkScalar> positions;- positions.ensure_capacity(color_stops.size());- for (auto const& color_stop : color_stops) {- colors.unchecked_append(to_skia_color4f(color_stop.color));- positions.unchecked_append(color_stop.position);- }-- auto start_center = radial_gradient->start_center();- auto end_center = radial_gradient->end_center();- auto start_radius = radial_gradient->start_radius();- auto end_radius = radial_gradient->end_radius();-- auto start_sk_point = to_skia_point(start_center);- auto end_sk_point = to_skia_point(end_center);-- SkMatrix matrix;- SkGradient gradient { SkGradient::Colors { { colors.data(), colors.size() }, { positions.data(), positions.size() }, SkTileMode::kClamp, sk_ref_sp(color_space) }, {} };- auto shader = SkShaders::TwoPointConicalGradient(start_sk_point, start_radius, end_sk_point, end_radius, gradient, &matrix);- paint.setShader(shader);- } else if (auto const* conic_gradient = as_if<CanvasConicGradientPaintStyle>(style)) {- auto const& color_stops = conic_gradient->color_stops();-- Vector<SkColor4f> colors;- colors.ensure_capacity(color_stops.size());- Vector<SkScalar> positions;- positions.ensure_capacity(color_stops.size());- for (auto const& color_stop : color_stops) {- colors.unchecked_append(to_skia_color4f(color_stop.color));- positions.unchecked_append(color_stop.position);- }-- auto center = conic_gradient->center();- auto start_angle_degrees = AK::to_degrees(conic_gradient->start_angle());-- // NB: The angles of a Skia sweep gradient pick where its colors start and end, and every angle outside of them- // takes the color of the nearest end. So the gradient is rotated to its start angle instead.- SkMatrix matrix;- matrix.setRotate(start_angle_degrees, center.x(), center.y());- SkGradient gradient { SkGradient::Colors { { colors.data(), colors.size() }, { positions.data(), positions.size() }, SkTileMode::kClamp, sk_ref_sp(color_space) }, {} };- auto shader = SkShaders::SweepGradient(to_skia_point(center), 0, 360, gradient, &matrix);- paint.setShader(shader);- } else if (auto const* canvas_pattern = as_if<CanvasPatternPaintStyle>(style)) {- auto frame = canvas_pattern->image();- if (!frame.has_value())- return;- auto sk_image = sk_image_for_decoded_image_frame(*frame);- if (!sk_image)- return;-- auto repetition = canvas_pattern->repetition();- auto repeat_x = first_is_one_of(repetition, CanvasPatternPaintStyle::Repetition::Repeat, CanvasPatternPaintStyle::Repetition::RepeatX);- auto repeat_y = first_is_one_of(repetition, CanvasPatternPaintStyle::Repetition::Repeat, CanvasPatternPaintStyle::Repetition::RepeatY);-- // FIXME: Implement sampling configuration.- SkSamplingOptions sk_sampling_options { SkFilterMode::kLinear };- Optional<SkMatrix> transformation_matrix;-- if (canvas_pattern->transform().has_value()) {- auto const& transform = canvas_pattern->transform().value();- transformation_matrix = SkMatrix::MakeAll(- transform.a(), transform.c(), transform.e(),- transform.b(), transform.d(), transform.f(),- 0, 0, 1);- }- auto shader = sk_image->makeShader(- repeat_x ? SkTileMode::kRepeat : SkTileMode::kDecal,- repeat_y ? SkTileMode::kRepeat : SkTileMode::kDecal,- sk_sampling_options, transformation_matrix.has_value() ? &transformation_matrix.value() : nullptr);- paint.setShader(move(shader));- } else {- dbgln("FIXME: Unsupported PaintStyle");- }-}--static SkPaint to_skia_paint(Gfx::PaintStyle const& style, sk_sp<SkImageFilter> image_filter, SkColorSpace* color_space)-{- SkPaint paint;-- apply_paint_style(paint, style, color_space);- paint.setImageFilter(move(image_filter));-- return paint;-}--// NB: These operators change the destination even where the source is fully transparent, which makes them affect-// pixels that the source does not cover.-static bool affects_pixels_not_covered_by_source(CompositingAndBlendingOperator compositing_and_blending_operator)-{- return first_is_one_of(compositing_and_blending_operator,- CompositingAndBlendingOperator::Copy,- CompositingAndBlendingOperator::SourceIn,- CompositingAndBlendingOperator::SourceOut,- CompositingAndBlendingOperator::DestinationIn,- CompositingAndBlendingOperator::DestinationATop);-}--// https://html.spec.whatwg.org/multipage/canvas.html#drawing-model-template<typename Callback>-static void draw_with_compositing(SkCanvas& canvas, SkPaint& paint, CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const& shadow, Callback draw)-{- // 5. When shadows are drawn, render the shadow from image B, using the current shadow styles, creating image C.- // 6. When shadows are drawn, composite C within the clipping region over the current output bitmap using the- // current compositing and blending operator.- // NB: The current transformation matrix does not affect the offset and the blur of a shadow, so the source is- // drawn into a layer whose filter makes the shadow in the coordinates of the canvas. The paint carries the- // global alpha and the filter of the context, so the layer holds image B.- if (shadow.has_value()) {- auto matrix = canvas.getTotalMatrix();- canvas.save();- canvas.resetMatrix();- auto sigma = shadow->blur / 2;- SkPaint shadow_layer_paint;- shadow_layer_paint.setImageFilter(SkImageFilters::DropShadowOnly(shadow->offset_x, shadow->offset_y, sigma, sigma, to_skia_color4f(shadow->color), sk_ref_sp(canvas.imageInfo().colorSpace()), nullptr));- shadow_layer_paint.setBlender(to_skia_blender(compositing_and_blending_operator));- canvas.saveLayer(nullptr, &shadow_layer_paint);- canvas.setMatrix(matrix);- draw(canvas, paint);- canvas.restore();- canvas.restore();- }-- // 7. Composite B within the clipping region over the current output bitmap using the current compositing and- // blending operator.- // NB: A Skia blend mode only touches the pixels that a draw covers. For the operators that also affect uncovered- // pixels, the source is drawn into a transparent layer, which is then composited onto all of the destination- // inside the clip.- if (!affects_pixels_not_covered_by_source(compositing_and_blending_operator)) {- paint.setBlender(to_skia_blender(compositing_and_blending_operator));- draw(canvas, paint);- return;- }-- SkPaint layer_paint;- layer_paint.setBlender(to_skia_blender(compositing_and_blending_operator));- canvas.saveLayer(nullptr, &layer_paint);- draw(canvas, paint);- canvas.restore();-}--// https://html.spec.whatwg.org/multipage/canvas.html#trace-a-path-static SkPath prune_path_for_stroking(SkPath const& path)-{- // 2. Prune all zero-length line segments from path.- // 3. Remove from path any subpaths containing no lines (i.e. subpaths with just one point).- // NB: Skia strokes a zero-length segment with caps, so such segments and the subpaths that are left with no- // lines are removed before the path is stroked.- auto is_zero_length = [](SkSpan<SkPoint const> points) {- for (size_t i = 1; i < points.size(); ++i) {- if (points[i] != points[0])- return false;- }- return true;- };-- SkPathBuilder builder(path.getFillType());- bool subpath_has_lines = false;- auto iterator = path.iter();- while (auto record = iterator.next()) {- auto points = record->fPoints;- switch (record->fVerb) {- case SkPathVerb::kMove:- subpath_has_lines = false;- continue;- case SkPathVerb::kClose:- if (subpath_has_lines)- builder.close();- subpath_has_lines = false;- continue;- case SkPathVerb::kLine:- case SkPathVerb::kQuad:- case SkPathVerb::kConic:- case SkPathVerb::kCubic:- break;- }-- if (is_zero_length(points))- continue;- if (!subpath_has_lines) {- builder.moveTo(points[0]);- subpath_has_lines = true;- }- switch (record->fVerb) {- case SkPathVerb::kLine:- builder.lineTo(points[1]);- break;- case SkPathVerb::kQuad:- builder.quadTo(points[1], points[2]);- break;- case SkPathVerb::kConic:- builder.conicTo(points[1], points[2], record->conicWeight());- break;- case SkPathVerb::kCubic:- builder.cubicTo(points[1], points[2], points[3]);- break;- default:- VERIFY_NOT_REACHED();- }- }- return builder.detach();-}--PainterSkia::PainterSkia(NonnullRefPtr<Gfx::PaintingSurface> painting_surface)- : m_painting_surface(move(painting_surface))-{- m_initial_save_count = m_painting_surface->canvas().save();-}--PainterSkia::~PainterSkia() = default;--SkColorSpace* PainterSkia::color_space() const-{- return m_painting_surface->sk_surface().imageInfo().colorSpace();-}--void PainterSkia::clear_rect(Gfx::FloatRect const& rect, Gfx::Color color)-{- auto& canvas = m_painting_surface->canvas();- canvas.save();- canvas.clipRect(to_skia_rect(rect));- SkPaint paint;- set_color(paint, color, color_space());- paint.setBlendMode(SkBlendMode::kSrc);- canvas.drawPaint(paint);- canvas.restore();-}--void PainterSkia::fill_rect(Gfx::FloatRect const& rect, Color color)-{- SkPaint paint;- set_color(paint, color, color_space());- auto& canvas = m_painting_surface->canvas();- canvas.drawRect(to_skia_rect(rect), paint);-}--void PainterSkia::draw_bitmap(Gfx::FloatRect const& dst_rect, Gfx::DecodedImageFrame const& source, Gfx::FloatRect const& src_rect, Gfx::ScalingMode scaling_mode, sk_sp<SkImageFilter> image_filter, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const& shadow)-{- auto sk_image = sk_image_for_decoded_image_frame(source);- if (!sk_image)- return;- draw_image(*sk_image, dst_rect, src_rect, scaling_mode, move(image_filter), global_alpha, compositing_and_blending_operator, shadow);-}--void PainterSkia::draw_image(SkImage const& image, Gfx::FloatRect const& dst_rect, Gfx::FloatRect const& src_rect, Gfx::ScalingMode scaling_mode, sk_sp<SkImageFilter> image_filter, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const& shadow)-{- SkPaint paint;- paint.setImageFilter(move(image_filter));- paint.setAlpha(static_cast<u8>(global_alpha * 255));-- draw_with_compositing(m_painting_surface->canvas(), paint, compositing_and_blending_operator, shadow, [&](SkCanvas& canvas, SkPaint const& paint) {- canvas.drawImageRect(- &image,- to_skia_rect(src_rect),- to_skia_rect(dst_rect),- to_skia_sampling_options(scaling_mode),- &paint,- SkCanvas::kStrict_SrcRectConstraint);- });-}--void PainterSkia::set_transform(Gfx::AffineTransform const& transform)-{- auto matrix = SkMatrix::MakeAll(- transform.a(), transform.c(), transform.e(),- transform.b(), transform.d(), transform.f(),- 0, 0, 1);-- auto& canvas = m_painting_surface->canvas();- canvas.setMatrix(matrix);-}--void PainterSkia::stroke_path(SkPath const& path, Gfx::PaintStyle const& paint_style, sk_sp<SkImageFilter> image_filter, float thickness, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Gfx::CapStyle const& cap_style, Gfx::JoinStyle const& join_style, float miter_limit, Vector<float> const& dash_array, float dash_offset, Optional<CanvasShadow> const& shadow)-{- // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.- if (thickness <= 0)- return;-- auto pruned_path = prune_path_for_stroking(path);- auto paint = to_skia_paint(paint_style, move(image_filter), color_space());- paint.setAntiAlias(true);- float alpha = paint.getAlphaf();- paint.setAlphaf(alpha * global_alpha);- paint.setStyle(SkPaint::Style::kStroke_Style);- paint.setStrokeWidth(thickness);- paint.setStrokeCap(to_skia_cap(cap_style));- paint.setStrokeJoin(to_skia_join(join_style));- paint.setStrokeMiter(miter_limit);- paint.setPathEffect(SkDashPathEffect::Make({ dash_array.data(), dash_array.size() }, dash_offset));- draw_with_compositing(m_painting_surface->canvas(), paint, compositing_and_blending_operator, shadow, [&](SkCanvas& canvas, SkPaint const& paint) {- canvas.drawPath(pruned_path, paint);- });-}--void PainterSkia::fill_path(SkPath path, Gfx::PaintStyle const& paint_style, sk_sp<SkImageFilter> image_filter, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Gfx::WindingRule winding_rule, Optional<CanvasShadow> const& shadow)-{- path.setFillType(to_skia_path_fill_type(winding_rule));- auto paint = to_skia_paint(paint_style, move(image_filter), color_space());- paint.setAntiAlias(true);- float alpha = paint.getAlphaf();- paint.setAlphaf(alpha * global_alpha);- draw_with_compositing(m_painting_surface->canvas(), paint, compositing_and_blending_operator, shadow, [&](SkCanvas& canvas, SkPaint const& paint) {- canvas.drawPath(path, paint);- });-}--void PainterSkia::draw_glyph_runs(ReadonlySpan<CanvasGlyphRun> runs, FloatPoint translation, float horizontal_scale, PaintStyle const& style, sk_sp<SkImageFilter> image_filter, float global_alpha, CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const& shadow)-{- struct SkiaGlyphRun {- SkFont font;- Vector<SkGlyphID, 32> glyph_ids;- Vector<SkPoint, 32> glyph_positions;- };-- Vector<SkiaGlyphRun, 2> skia_runs;- skia_runs.ensure_capacity(runs.size());- for (auto const& run : runs) {- if (run.glyphs.is_empty() || run.font.is_invisible())- continue;-- auto sk_font = Compositor::skia_font(run.font, 1);- if (!sk_font.has_value())- continue;-- SkiaGlyphRun skia_run { .font = sk_font.release_value(), .glyph_ids = {}, .glyph_positions = {} };-- // NB: Preserve canvas text's fractional baseline and unhinted outline geometry.- skia_run.font.setHinting(SkFontHinting::kNone);- skia_run.font.setForceAutoHinting(false);- skia_run.font.setBaselineSnap(false);-- // NB: The scale goes on the font rather than the canvas, as it must not scale the paint of the text.- skia_run.font.setScaleX(skia_run.font.getScaleX() * horizontal_scale);-- skia_run.glyph_ids.ensure_capacity(run.glyphs.size());- skia_run.glyph_positions.ensure_capacity(run.glyphs.size());- auto font_ascent = run.font.pixel_metrics().ascent;- for (auto const& glyph : run.glyphs) {- skia_run.glyph_ids.unchecked_append(static_cast<SkGlyphID>(glyph.glyph_id));- skia_run.glyph_positions.unchecked_append({ glyph.position.x() * horizontal_scale, glyph.position.y() + font_ascent });- }- skia_runs.unchecked_append(move(skia_run));- }-- auto paint = to_skia_paint(style, move(image_filter), color_space());- paint.setAlphaf(paint.getAlphaf() * global_alpha);-- // NB: Not drawTextBlob(). Skia caches a drawn SkTextBlob once per subpixel origin, and finds a cached entry by- // scanning every entry of that blob. Canvas text is often redrawn at moving fractional positions, which- // piles up thousands of entries per blob and makes each draw scan all of them.- draw_with_compositing(m_painting_surface->canvas(), paint, compositing_and_blending_operator, shadow, [&](SkCanvas& canvas, SkPaint const& paint) {- auto draw_runs = [&](SkPaint const& run_paint) {- for (auto const& run : skia_runs)- canvas.drawGlyphs({ run.glyph_ids.data(), run.glyph_ids.size() }, { run.glyph_positions.data(), run.glyph_positions.size() }, to_skia_point(translation), run.font, run_paint);- };-- if (skia_runs.size() <= 1 || !paint.getImageFilter()) {- draw_runs(paint);- return;- }-- // NB: The filter of the context applies to the text as a whole, so it goes on a layer that holds all runs.- // Otherwise, what the filter makes of one run would land on top of the other runs.- SkPaint layer_paint;- layer_paint.setImageFilter(paint.refImageFilter());- layer_paint.setBlender(paint.refBlender());- SkPaint run_paint = paint;- run_paint.setImageFilter(nullptr);- run_paint.setBlender(nullptr);- canvas.saveLayer(nullptr, &layer_paint);- draw_runs(run_paint);- canvas.restore();- });-}--void PainterSkia::save()-{- auto& canvas = m_painting_surface->canvas();- canvas.save();-}--void PainterSkia::restore()-{- auto& canvas = m_painting_surface->canvas();- canvas.restore();-}--void PainterSkia::clip(SkPath path, Gfx::WindingRule winding_rule)-{- path.setFillType(to_skia_path_fill_type(winding_rule));- auto& canvas = m_painting_surface->canvas();- canvas.clipPath(path, SkClipOp::kIntersect, true);-}--void PainterSkia::reset()-{- auto& canvas = m_painting_surface->canvas();- canvas.restoreToCount(m_initial_save_count);- canvas.save();-}--}diff --git a/Services/Compositor/PainterSkia.h b/Services/Compositor/PainterSkia.hdeleted file mode 100644index 1e95953f015..00000000000--- a/Services/Compositor/PainterSkia.h+++ /dev/null@@ -1,77 +0,0 @@-/*- * Copyright (c) 2024, Andreas Kling <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <AK/Span.h>-#include <Compositor/PaintingSurface.h>-#include <LibGfx/Color.h>-#include <LibGfx/CompositingAndBlendingOperator.h>-#include <LibGfx/Forward.h>-#include <LibGfx/PaintStyle.h>-#include <LibGfx/Point.h>-#include <LibGfx/ScalingMode.h>-#include <LibGfx/StrokeStyle.h>-#include <LibGfx/WindingRule.h>--class SkColorSpace;-class SkImage;-class SkImageFilter;-class SkPath;-template<typename T>-class sk_sp;--namespace Gfx {--// The shadow that a canvas draw casts, with its offset and blur in the coordinates of the canvas.-struct CanvasShadow {- Color color;- float offset_x { 0 };- float offset_y { 0 };- float blur { 0 };-};--struct CanvasGlyph {- FloatPoint position;- u32 glyph_id { 0 };-};--struct CanvasGlyphRun {- Font const& font;- ReadonlySpan<CanvasGlyph> glyphs;-};--class PainterSkia final {-public:- AK_ALLOC_WITH_KMALLOC;-- explicit PainterSkia(NonnullRefPtr<Gfx::PaintingSurface>);- ~PainterSkia();-- void clear_rect(Gfx::FloatRect const&, Color);- void fill_rect(Gfx::FloatRect const&, Color);- void draw_bitmap(Gfx::FloatRect const& dst_rect, Gfx::DecodedImageFrame const& source, Gfx::FloatRect const& src_rect, Gfx::ScalingMode, sk_sp<SkImageFilter>, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const&);- void draw_image(SkImage const&, Gfx::FloatRect const& dst_rect, Gfx::FloatRect const& src_rect, Gfx::ScalingMode, sk_sp<SkImageFilter>, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const&);- void stroke_path(SkPath const&, Gfx::PaintStyle const&, sk_sp<SkImageFilter>, float thickness, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Gfx::CapStyle const&, Gfx::JoinStyle const&, float miter_limit, Vector<float> const&, float dash_offset, Optional<CanvasShadow> const&);- void fill_path(SkPath, Gfx::PaintStyle const&, sk_sp<SkImageFilter>, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Gfx::WindingRule, Optional<CanvasShadow> const&);- void draw_glyph_runs(ReadonlySpan<CanvasGlyphRun>, FloatPoint translation, float horizontal_scale, PaintStyle const&, sk_sp<SkImageFilter>, float global_alpha, CompositingAndBlendingOperator, Optional<CanvasShadow> const&);- void set_transform(Gfx::AffineTransform const&);- void save();- void restore();- void clip(SkPath, Gfx::WindingRule);- void reset();--private:- // NB: The colors that the painter is given are in the color space of the surface.- SkColorSpace* color_space() const;-- NonnullRefPtr<PaintingSurface> m_painting_surface;- u32 m_initial_save_count { 0 };-};--}diff --git a/Services/Compositor/SkiaUtils.cpp b/Services/Compositor/SkiaUtils.cppindex 0a0390bd07b..d6a01c11c17 100644--- a/Services/Compositor/SkiaUtils.cpp+++ b/Services/Compositor/SkiaUtils.cpp@@ -39,6 +39,21 @@ static_assert(to_underlying(PathVerb::Close) == to_underlying(SkPathVerb::kClosestatic_assert(sizeof(PathVerb) == sizeof(SkPathVerb));static_assert(sizeof(FloatPoint) == sizeof(SkPoint));+SkMatrix to_skia_matrix(AffineTransform const& affine_transform)+{+ SkScalar affine[6];+ affine[0] = affine_transform.a();+ affine[1] = affine_transform.b();+ affine[2] = affine_transform.c();+ affine[3] = affine_transform.d();+ affine[4] = affine_transform.e();+ affine[5] = affine_transform.f();++ SkMatrix matrix;+ matrix.setAffine(affine);+ return matrix;+}+SkPath to_skia_path(PathData const& data){return SkPath::Raw(diff --git a/Services/Compositor/SkiaUtils.h b/Services/Compositor/SkiaUtils.hindex 55f873ef3ef..4aec34296d3 100644--- a/Services/Compositor/SkiaUtils.h+++ b/Services/Compositor/SkiaUtils.h@@ -11,9 +11,11 @@#include <AK/Assertions.h>#include <AK/Function.h>#include <AK/Optional.h>+#include <LibGfx/AffineTransform.h>#include <LibGfx/Bitmap.h>+#include <LibGfx/Color.h>#include <LibGfx/CompositingAndBlendingOperator.h>-#include <LibGfx/PaintStyle.h>+#include <LibGfx/Forward.h>#include <LibGfx/ScalingMode.h>#include <LibGfx/StrokeStyle.h>#include <LibGfx/WindingRule.h>@@ -23,6 +25,7 @@#include <core/SkColorType.h>#include <core/SkImage.h>#include <core/SkImageFilter.h>+#include <core/SkMatrix.h>#include <core/SkPaint.h>#include <core/SkPath.h>#include <core/SkSamplingOptions.h>@@ -139,6 +142,7 @@ constexpr SkSamplingOptions to_skia_sampling_options(ScalingMode scaling_mode)VERIFY_NOT_REACHED();}+SkMatrix to_skia_matrix(AffineTransform const&);SkPath to_skia_path(PathData const&);SkPath skia_path_from_serialized_bytes(ReadonlyBytes);// Builds the SkImageFilter tree a serialized filter graph describes; `image_frame` supplies the