Truly independent web browser
Compositor: Share painting and presentable surfaces with Rust
Aliaksandr Kalenik60081d9e2ade
diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cppindex 1fb572bc3cf..ee852359f78 100644--- a/Services/Compositor/BackingStoreManager.cpp+++ b/Services/Compositor/BackingStoreManager.cpp@@ -28,9 +28,9 @@ static NonnullRefPtr<Gfx::PaintingSurface> create_gpu_painting_surface_with_bitm{auto surface = Gfx::PaintingSurface::create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context, {}, Gfx::PaintingSurface::TextAntialiasing::LCD);auto bitmap = buffer.bitmap();- surface->on_flush = [bitmap = move(bitmap)](auto& surface) {+ surface->set_on_flush([bitmap = move(bitmap)](auto& surface) {surface.read_into_bitmap(*bitmap);- };+ });return surface;}#endifdiff --git a/Services/Compositor/CanvasSurfaceRegistry.h b/Services/Compositor/CanvasSurfaceRegistry.hindex cbd4a54557b..abb7b3077de 100644--- a/Services/Compositor/CanvasSurfaceRegistry.h+++ b/Services/Compositor/CanvasSurfaceRegistry.h@@ -9,7 +9,6 @@#include <AK/HashMap.h>#include <AK/Noncopyable.h>#include <AK/NonnullRefPtr.h>-#include <AK/WeakPtr.h>#include <Compositor/PaintingSurface.h>#include <Compositor/PresentableSurface.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>@@ -52,7 +51,7 @@ public:// The canvas shows the content of a surface that the window server can show as it is.void set_canvas_surface(Compositing::CanvasSurfaceOwnerId owner_id, Compositing::CanvasId id, PresentableSurface& surface){- set_entry(owner_id, id, surface.painting_surface(), surface.make_weak_ptr());+ set_entry(owner_id, id, surface.painting_surface(), WeakPresentableSurface { surface });}void remove_canvas_surface(Compositing::CanvasId id)@@ -83,11 +82,11 @@ private:struct Entry {Compositing::CanvasSurfaceOwnerId owner_id;NonnullRefPtr<Gfx::PaintingSurface> surface;- WeakPtr<PresentableSurface> presentable_surface;+ WeakPresentableSurface presentable_surface;u64 content_generation { 0 };};- void set_entry(Compositing::CanvasSurfaceOwnerId owner_id, Compositing::CanvasId id, NonnullRefPtr<Gfx::PaintingSurface> surface, WeakPtr<PresentableSurface> presentable_surface)+ void set_entry(Compositing::CanvasSurfaceOwnerId owner_id, Compositing::CanvasId id, NonnullRefPtr<Gfx::PaintingSurface> surface, WeakPresentableSurface presentable_surface){if (auto existing = m_entries.get(id); existing.has_value())VERIFY(existing->owner_id == owner_id);diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex a0e64158209..1456642ed97 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -284,11 +284,11 @@ bool CompositorCore::paint_screenshot(Web::CompositorContextId context_id, Gfx::Optional<CompositorCore::PresentedFrame> CompositorCore::presented_frame_for_snapshot(Web::CompositorContextId context_id){- void* surface = nullptr;Gfx::IntSize frame_size;- if (!RustFFI::compositor_core_presented_frame_for_snapshot(m_core, context_id.value(), now().nanoseconds(), &surface, &frame_size))+ auto const* surface = RustFFI::compositor_core_presented_frame_for_snapshot(m_core, context_id.value(), now().nanoseconds(), &frame_size);+ if (!surface)return {};- return PresentedFrame { adopt_ref(*static_cast<Gfx::PaintingSurface*>(surface)), frame_size };+ return PresentedFrame { adopt_ref(const_cast<Gfx::PaintingSurface&>(*surface)), frame_size };}void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer)diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex e34ab43af67..afc7939346e 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -1437,7 +1437,7 @@ Vector<RemoteSublayer>* CompositorState::build_sublayers(Web::CompositorContextIcontent = frame.release_nonnull();break;case RustFFI::SublayerContentKind::PresentableSurface:- content = static_cast<PresentableSurface*>(sublayer.presentable_surface)->lease();+ content = const_cast<PresentableSurface*>(sublayer.presentable_surface)->lease();break;}if (!content.has_value())@@ -1629,14 +1629,14 @@ static CompositorState& state_of(void* host)return *static_cast<CompositorState*>(host);}-static Gfx::PaintingSurface& painting_surface_of(void* surface)+static SkCanvas& canvas_of(Gfx::PaintingSurface const* surface){- return *static_cast<Gfx::PaintingSurface*>(surface);+ return surface->canvas();}-static SkCanvas& canvas_of(void* surface)+static Gfx::PaintingSurface& mutable_surface(Gfx::PaintingSurface const* surface){- return painting_surface_of(surface).canvas();+ return const_cast<Gfx::PaintingSurface&>(*surface);}static Optional<u64> display_of(bool has_display_id, u64 display_id)@@ -1663,11 +1663,8 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)using Context = Web::CompositorContextId;return {.host = &state,- .surface_retain = [](void* surface) { painting_surface_of(surface).ref(); },- .surface_release = [](void* surface) { painting_surface_of(surface).unref(); },- .surface_size = [](void* surface, Gfx::IntSize* size) { *size = painting_surface_of(surface).size(); },- .create_surface = [](void* host, Gfx::IntSize size, void* like, bool inherits_lcd_text) -> void* {- auto skia_backend_context = like ? painting_surface_of(like).skia_backend_context() : state_of(host).m_skia_backend_context;+ .create_surface = [](void* host, Gfx::IntSize size, Gfx::PaintingSurface const* like, bool inherits_lcd_text) -> Gfx::PaintingSurface const* {+ auto skia_backend_context = like ? like->skia_backend_context() : state_of(host).m_skia_backend_context;auto text_antialiasing = Gfx::PaintingSurface::TextAntialiasing::Grayscale;if (inherits_lcd_text && like && canvas_of(like).getBaseProps().pixelGeometry() != kUnknown_SkPixelGeometry)text_antialiasing = Gfx::PaintingSurface::TextAntialiasing::LCD;@@ -1676,21 +1673,19 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)return nullptr;return &surface.release_value().leak_ref();},- .surfaces_share_backend = [](void* a, void* b) { return painting_surface_of(a).skia_backend_context() == painting_surface_of(b).skia_backend_context(); },- .surface_uses_gpu = [](void* surface) { return painting_surface_of(surface).skia_backend_context() != nullptr; },- .surface_save = [](void* surface) { return canvas_of(surface).save(); },- .surface_restore_to_count = [](void* surface, i32 count) { canvas_of(surface).restoreToCount(count); },- .surface_translate = [](void* surface, float x, float y) { canvas_of(surface).translate(x, y); },- .surface_scale = [](void* surface, float x, float y) { canvas_of(surface).scale(x, y); },- .surface_clip_rect = [](void* surface, Gfx::IntRect rect) { canvas_of(surface).clipIRect(SkIRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height())); },- .surface_clear = [](void* surface, Gfx::Color color) { canvas_of(surface).clear(Gfx::to_skia_color(color)); },- .surface_draw_surface = [](void* target, void* source, Gfx::IntRect source_rect, Gfx::IntRect target_rect, RustFFI::SurfaceBlend blend) {- auto image = painting_surface_of(source).sk_image_snapshot<sk_sp<SkImage>>();+ .surface_save = [](Gfx::PaintingSurface const* surface) { return canvas_of(surface).save(); },+ .surface_restore_to_count = [](Gfx::PaintingSurface const* surface, i32 count) { canvas_of(surface).restoreToCount(count); },+ .surface_translate = [](Gfx::PaintingSurface const* surface, float x, float y) { canvas_of(surface).translate(x, y); },+ .surface_scale = [](Gfx::PaintingSurface const* surface, float x, float y) { canvas_of(surface).scale(x, y); },+ .surface_clip_rect = [](Gfx::PaintingSurface const* surface, Gfx::IntRect rect) { canvas_of(surface).clipIRect(SkIRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height())); },+ .surface_clear = [](Gfx::PaintingSurface const* surface, Gfx::Color color) { canvas_of(surface).clear(Gfx::to_skia_color(color)); },+ .surface_draw_surface = [](Gfx::PaintingSurface const* target, Gfx::PaintingSurface const* source, Gfx::IntRect source_rect, Gfx::IntRect target_rect, RustFFI::SurfaceBlend blend) {+ auto image = source->sk_image_snapshot<sk_sp<SkImage>>();SkPaint paint;paint.setBlendMode(blend == RustFFI::SurfaceBlend::Source ? SkBlendMode::kSrc : SkBlendMode::kSrcOver);canvas_of(target).drawImageRect(image.get(), Gfx::to_skia_rect(source_rect), Gfx::to_skia_rect(target_rect), SkSamplingOptions {}, &paint, SkCanvas::kStrict_SrcRectConstraint); },- .flush_surface = [](void*, void* surface) { DisplayListPlayerSkia::flush(painting_surface_of(surface)); },- .begin_painting = [](void* host, u64 context_id, void* surface, RustFFI::PaintingResources resources, bool allows_lcd_text, Compositing::RustFFI::FfiRasterPainter* painter) { *painter = state_of(host).begin_painting(Context { context_id }, painting_surface_of(surface), resources, allows_lcd_text); },+ .flush_surface = [](Gfx::PaintingSurface const* surface) { DisplayListPlayerSkia::flush(mutable_surface(surface)); },+ .begin_painting = [](void* host, u64 context_id, Gfx::PaintingSurface const* surface, RustFFI::PaintingResources resources, bool allows_lcd_text, Compositing::RustFFI::FfiRasterPainter* painter) { *painter = state_of(host).begin_painting(Context { context_id }, mutable_surface(surface), resources, allows_lcd_text); },.end_painting = [](void* host) { state_of(host).end_painting(); },.start_raster_cache_frame = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.raster_cache().drop_what_was_not_used_since_last_frame(); },.store_state = [](void* host, u64 context_id) -> RustFFI::FfiStoreState {@@ -1709,23 +1704,17 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state).complete_rendering = [](void* host, u64 context_id, i32 bitmap_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().complete_rendering(bitmap_id); },.release_store = [](void* host, u64 context_id, i32 bitmap_id) { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().release_buffer(bitmap_id); },.release_all_presented_stores = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().release_all_presented_buffers(); },- .latest_rendered_store_surface = [](void* host, u64 context_id) -> void* { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().latest_rendered_surface().ptr(); },+ .latest_rendered_store_surface = [](void* host, u64 context_id) -> Gfx::PaintingSurface const* { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().latest_rendered_surface().ptr(); },.add_store_if_window_server_reads_every_released_store = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).add_store_if_window_server_reads_every_released_store(Context { context_id }, presentation_of(has_presentation, presentation_id)); },.retire_idle_surplus_stores = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).retire_idle_surplus_stores(Context { context_id }, presentation_of(has_presentation, presentation_id)); },.retire_stores_of_hidden_context = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).retire_stores_of_hidden_context(Context { context_id }, presentation_of(has_presentation, presentation_id)); },.restore_stores_retired_while_hidden = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).restore_stores_retired_while_hidden(Context { context_id }, presentation_of(has_presentation, presentation_id)); },- .next_presentable_surface = [](void* host, u64 context_id, u32 pool, Gfx::IntSize size, void* like) -> void* {- auto& state = state_of(host);- auto skia_backend_context = like ? painting_surface_of(like).skia_backend_context() : state.m_skia_backend_context;- auto surface = state.presented_context(Context { context_id }).raster_targets.next_presentable_surface(pool, size, skia_backend_context);- if (!surface)+ .create_presentable_surface = [](void*, Gfx::IntSize size, Gfx::PaintingSurface const* like) -> PresentableSurface const* {+ auto surface = PresentableSurfacePool::create_surface(size, like->skia_backend_context());+ if (surface.is_error())return nullptr;- return surface.leak_ref();+ return &surface.release_value().leak_ref();},- .drop_presentable_surface_pool = [](void* host, u64 context_id, u32 pool) { state_of(host).presented_context(Context { context_id }).raster_targets.drop_presentable_surface_pool(pool); },- .presentable_surface_retain = [](void* surface) { static_cast<PresentableSurface*>(surface)->ref(); },- .presentable_surface_release = [](void* surface) { static_cast<PresentableSurface*>(surface)->unref(); },- .presentable_surface_painting_surface = [](void* surface) -> void* { return &static_cast<PresentableSurface*>(surface)->painting_surface(); },.live_content = [](void* host, u64 context_id, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*)) { state_of(host).report_live_content(Context { context_id }, canvas_ids, receiver, receive); },.remote_layer_can_show = [](void* host, u64 context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const* placement, double device_pixel_ratio) { return state_of(host).remote_layer_can_show(Context { context_id }, kind, media_id, *placement, device_pixel_ratio); },.build_sublayers = [](void* host, u64 context_id, ReadonlySpan<RustFFI::FfiSublayer> sublayers) -> void* {@@ -1735,7 +1724,7 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state).frame_hand_off = [](void* host, u64 context_id) { return state_of(host).frame_hand_off(Context { context_id }) == WindowServer::FrameHandOff::OnceGpuWorkIsScheduled? RustFFI::FrameHandOff::OnceGpuWorkIsScheduled: RustFFI::FrameHandOff::OnceGpuWorkIsFinished; },- .submit_frame = [](void* host, u64, void* surface) { return state_of(host).submit_frame(static_cast<Gfx::PaintingSurface*>(surface)); },+ .submit_frame = [](void* host, u64, Gfx::PaintingSurface const* surface) { return state_of(host).submit_frame(const_cast<Gfx::PaintingSurface*>(surface)); },.hand_off_once_gpu_work_is_scheduled = [](void* host, u64 token) { state_of(host).hand_off_once_gpu_work_is_scheduled(token); },.show_frame_in_remote_layer = [](void* host, u64 context_id, RustFFI::FfiRemoteLayerFrame const* frame, void* sublayers, u64* presentation_id) {auto shown_in = state_of(host).show_frame_in_remote_layer(Context { context_id }, *frame, adopt_own(*static_cast<Vector<RemoteSublayer>*>(sublayers)));diff --git a/Services/Compositor/ContextRasterTargets.cpp b/Services/Compositor/ContextRasterTargets.cppindex 93e5ef8ddad..3d3ff708177 100644--- a/Services/Compositor/ContextRasterTargets.cpp+++ b/Services/Compositor/ContextRasterTargets.cpp@@ -62,14 +62,6 @@ Optional<OverlayLabel> ContextRasterTargets::shape_overlay_label(Optional<Stringreturn label;}-RefPtr<PresentableSurface> ContextRasterTargets::next_presentable_surface(u32 pool, Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)-{- auto surface = m_presentable_surface_pools.ensure(pool).surface_for_next_content(size, skia_backend_context);- if (surface.is_error())- return nullptr;- return surface.release_value();-}-bool ContextRasterTargets::set_drawn_video_sinks(ReadonlySpan<u64> handles){HashTable<Media::VideoSinkHandle> drawn_video_sinks;diff --git a/Services/Compositor/ContextRasterTargets.h b/Services/Compositor/ContextRasterTargets.hindex 18f17da3e7b..1dadada7430 100644--- a/Services/Compositor/ContextRasterTargets.h+++ b/Services/Compositor/ContextRasterTargets.h@@ -58,10 +58,6 @@ public:BackingStoreManager& backing_stores() { return m_backing_stores; }BackingStoreManager const& backing_stores() const { return m_backing_stores; }- // A surface of the pool for the next content shown from it, which the window server is not busy with.- RefPtr<PresentableSurface> next_presentable_surface(u32 pool, Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&);- void drop_presentable_surface_pool(u32 pool) { m_presentable_surface_pools.remove(pool); }-// The video sinks that the display list of the context draws. Answers whether these are other sinks than before.bool set_drawn_video_sinks(ReadonlySpan<u64> handles);HashTable<Media::VideoSinkHandle> const& drawn_video_sinks() const { return m_drawn_video_sinks; }@@ -75,7 +71,6 @@ private:DrawnFonts m_overlay_fonts;DisplayListRasterCache m_overlay_raster_cache;BackingStoreManager m_backing_stores;- HashMap<u32, PresentableSurfacePool> m_presentable_surface_pools;HashTable<Media::VideoSinkHandle> m_drawn_video_sinks;};diff --git a/Services/Compositor/PaintingSurface.cpp b/Services/Compositor/PaintingSurface.cppindex bb6d1711d2b..1cba566afeb 100644--- a/Services/Compositor/PaintingSurface.cpp+++ b/Services/Compositor/PaintingSurface.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <Compositor/CompositorCoreRustFFI.h>#include <Compositor/FontSkia.h>#include <Compositor/PaintingSurface.h>#include <Compositor/SkiaUtils.h>@@ -40,12 +41,31 @@ struct PaintingSurface::Impl {AK_ALLOC_WITH_KMALLOC;RefPtr<SkiaBackendContext> context;- IntSize size;sk_sp<SkSurface> surface;RefPtr<Bitmap> bitmap;bool wraps_shared_image { false };+ Function<void(PaintingSurface&)> on_flush {};};+void PaintingSurface::destroy_impl(void* impl)+{+ auto* surface_impl = static_cast<PaintingSurface::Impl*>(impl);+ // NB: The surface may draw into the pixels of the bitmap, so it goes first.+ surface_impl->surface = nullptr;+ delete surface_impl;+}++NonnullRefPtr<PaintingSurface> PaintingSurface::adopt_impl(IntSize size, NonnullOwnPtr<Impl> impl)+{+ auto const* gpu_backend_context = impl->context.ptr();+ return adopt_ref(const_cast<PaintingSurface&>(*Compositor::RustFFI::compositor_painting_surface_create(size, gpu_backend_context, impl.leak_ptr(), destroy_impl)));+}++PaintingSurface::Impl& PaintingSurface::impl() const+{+ return *static_cast<Impl*>(Compositor::RustFFI::compositor_painting_surface_skia_surface(this));+}+#if defined(AK_OS_MACOS) || defined(USE_VULKAN_DMABUF_IMAGES) || defined(USE_DIRECTX)static GrSurfaceOrigin origin_to_sk_origin(PaintingSurface::Origin origin){@@ -102,7 +122,7 @@ NonnullRefPtr<PaintingSurface> PaintingSurface::create_from_vkimage(NonnullRefPtauto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDefault_Flag, text_antialiasing == TextAntialiasing::LCD);sk_sp<SkSurface> surface = SkSurfaces::WrapBackendRenderTarget(context->sk_context(), rt, origin_to_sk_origin(origin), vk_format_to_sk_color_type(vulkan_image->info.format),SkColorSpace::MakeSRGB(), &properties, release_vulkan_image, vulkan_image.ptr());- return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, nullptr, true)));+ return adopt_impl(size, make<Impl>(context, surface, nullptr, true));}#endif@@ -128,7 +148,7 @@ ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::create_from_d3d_texturekRGBA_8888_SkColorType, SkColorSpace::MakeSRGB(), nullptr, release_d3d_texture, texture.ptr());if (!surface)return Error::from_string_literal("Failed to wrap shared Direct3D texture in a Skia surface");- return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, nullptr, true)));+ return adopt_impl(size, make<Impl>(context, surface, nullptr, true));}#endif@@ -157,7 +177,7 @@ ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::try_create_with_size(Inauto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDynamicMSAA_Flag, text_antialiasing == TextAntialiasing::LCD);auto surface = SkSurfaces::RenderTarget(context->sk_context(), skgpu::Budgeted::kNo, image_info, 0, &properties);if (surface)- return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, nullptr)));+ return adopt_impl(size, make<Impl>(context, surface, nullptr));dbgln("Unable to create GPU surface for size {}x{}, falling back to CPU", size.width(), size.height());context = nullptr;}@@ -167,7 +187,7 @@ ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::try_create_with_size(Inauto surface = SkSurfaces::WrapPixels(image_info, bitmap->begin(), bitmap->pitch(), &properties);if (!surface)return Error::from_string_literal("Unable to create a surface for the bitmap");- return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, bitmap)));+ return adopt_impl(size, make<Impl>(context, surface, bitmap));}NonnullRefPtr<PaintingSurface> PaintingSurface::wrap_bitmap(Bitmap& bitmap, TextAntialiasing text_antialiasing)@@ -178,7 +198,7 @@ NonnullRefPtr<PaintingSurface> PaintingSurface::wrap_bitmap(Bitmap& bitmap, Textauto image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), color_type, alpha_type, SkColorSpace::MakeSRGB());auto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDefault_Flag, text_antialiasing == TextAntialiasing::LCD);auto surface = SkSurfaces::WrapPixels(image_info, bitmap.begin(), bitmap.pitch(), &properties);- return adopt_ref(*new PaintingSurface(make<Impl>(RefPtr<SkiaBackendContext> {}, size, surface, bitmap)));+ return adopt_impl(size, make<Impl>(RefPtr<SkiaBackendContext> {}, surface, bitmap));}#ifdef AK_OS_MACOS@@ -192,20 +212,10 @@ NonnullRefPtr<PaintingSurface> PaintingSurface::create_from_shared_image_buffer(mtl_info.fTexture = sk_ret_cfp(metal_texture->texture());auto backend_render_target = GrBackendRenderTargets::MakeMtl(metal_texture->width(), metal_texture->height(), mtl_info);auto surface = SkSurfaces::WrapBackendRenderTarget(context->sk_context(), backend_render_target, origin_to_sk_origin(origin), kBGRA_8888_SkColorType, SkColorSpace::MakeSRGB(), nullptr);- return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, nullptr, true)));+ return adopt_impl(size, make<Impl>(context, surface, nullptr, true));}#endif-PaintingSurface::PaintingSurface(NonnullOwnPtr<Impl>&& impl)- : m_impl(move(impl))-{-}--PaintingSurface::~PaintingSurface()-{- m_impl->surface = nullptr;-}-void PaintingSurface::read_into_bitmap(Bitmap& bitmap, IntPoint source_position, ColorSpace const& color_space) const{auto color_type = to_skia_color_type(bitmap.format());@@ -213,9 +223,9 @@ void PaintingSurface::read_into_bitmap(Bitmap& bitmap, IntPoint source_position,auto image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), color_type, alpha_type, skia_color_space_of_pixels(color_space));SkPixmap const pixmap(image_info, bitmap.begin(), bitmap.pitch());- auto surface_color_space = m_impl->surface->imageInfo().refColorSpace();+ auto surface_color_space = impl().surface->imageInfo().refColorSpace();if (SkColorSpace::Equals(surface_color_space.get(), image_info.colorSpace())) {- m_impl->surface->readPixels(pixmap, source_position.x(), source_position.y());+ impl().surface->readPixels(pixmap, source_position.x(), source_position.y());return;}@@ -236,7 +246,7 @@ void PaintingSurface::read_into_bitmap(Bitmap& bitmap, IntPoint source_position,for (int y = 0; y < bitmap.height(); y += strip_height) {auto rows = min(strip_height, bitmap.height() - y);SkPixmap const unpremultiplied_pixmap(strip_info.makeWH(bitmap.width(), rows), strip_pixels.value().data(), strip_info.minRowBytes());- if (!m_impl->surface->readPixels(unpremultiplied_pixmap, source_position.x(), source_position.y() + y))+ if (!impl().surface->readPixels(unpremultiplied_pixmap, source_position.x(), source_position.y() + y))return;auto components = Span<float> { reinterpret_cast<float*>(strip_pixels.value().data()), unpremultiplied_pixmap.computeByteSize() / sizeof(float) };for (auto& component : components)@@ -254,7 +264,7 @@ void PaintingSurface::write_from_bitmap(Bitmap const& bitmap, IntPoint destinatiauto alpha_type = to_skia_alpha_type(bitmap.format(), bitmap.alpha_type());auto image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), color_type, alpha_type, skia_color_space_of_pixels(color_space));SkPixmap const pixmap(image_info, bitmap.begin(), bitmap.pitch());- m_impl->surface->writePixels(pixmap, destination_position.x(), destination_position.y());+ impl().surface->writePixels(pixmap, destination_position.x(), destination_position.y());}void PaintingSurface::copy_from_surface(PaintingSurface& source)@@ -265,12 +275,12 @@ void PaintingSurface::copy_from_surface(PaintingSurface& source)// upload. A snapshot of them would copy them first, and the GPU would upload the copy into a texture// of its own before drawing it here.SkPixmap source_pixels;- if (source.size() == size() && source.m_impl->surface->peekPixels(&source_pixels)) {- m_impl->surface->writePixels(source_pixels, 0, 0);+ if (source.size() == size() && source.impl().surface->peekPixels(&source_pixels)) {+ impl().surface->writePixels(source_pixels, 0, 0);return;}- auto image = source.m_impl->surface->makeImageSnapshot();+ auto image = source.impl().surface->makeImageSnapshot();if (!image)return;@@ -287,49 +297,66 @@ void PaintingSurface::copy_from_surface(PaintingSurface& source)IntSize PaintingSurface::size() const{- return m_impl->size;+ IntSize size;+ Compositor::RustFFI::compositor_painting_surface_size(this, &size);+ return size;}IntRect PaintingSurface::rect() const{- return { {}, m_impl->size };+ return { {}, size() };}SkCanvas& PaintingSurface::canvas() const{- return *m_impl->surface->getCanvas();+ return *impl().surface->getCanvas();}SkSurface& PaintingSurface::sk_surface() const{- return *m_impl->surface;+ return *impl().surface;}void PaintingSurface::notify_content_will_change(){- m_impl->surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);+ impl().surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);}template<>sk_sp<SkImage> PaintingSurface::sk_image_snapshot() const{- return m_impl->surface->makeImageSnapshot();+ return impl().surface->makeImageSnapshot();}RefPtr<SkiaBackendContext> PaintingSurface::skia_backend_context() const{- return m_impl->context;+ return impl().context;}bool PaintingSurface::wraps_shared_image() const{- return m_impl->wraps_shared_image;+ return impl().wraps_shared_image;+}++void PaintingSurface::set_on_flush(Function<void(PaintingSurface&)> on_flush)+{+ impl().on_flush = move(on_flush);}void PaintingSurface::flush(){- if (on_flush)- on_flush(*this);+ if (impl().on_flush)+ impl().on_flush(*this);+}++void PaintingSurface::ref() const+{+ Compositor::RustFFI::compositor_painting_surface_retain(this);+}++void PaintingSurface::unref() const+{+ Compositor::RustFFI::compositor_painting_surface_release(this);}}diff --git a/Services/Compositor/PaintingSurface.h b/Services/Compositor/PaintingSurface.hindex f309db0a98c..a656b254483 100644--- a/Services/Compositor/PaintingSurface.h+++ b/Services/Compositor/PaintingSurface.h@@ -6,10 +6,11 @@#pragma once-#include <AK/AtomicRefCounted.h>#include <AK/Function.h>+#include <AK/Noncopyable.h>#include <AK/NonnullOwnPtr.h>#include <AK/RefPtr.h>+#include <AK/kmalloc.h>#include <Compositor/SkiaBackendContext.h>#include <LibGfx/Color.h>#include <LibGfx/ColorSpace.h>@@ -44,7 +45,12 @@ namespace Gfx {class SharedImage;-class PaintingSurface : public AtomicRefCounted<PaintingSurface> {+// A surface that the Compositor paints into. A pointer to it is the Rust core's surface itself, which the core and the+// C++ around it share by reference counting. Only the Compositor's main thread may reference or release it.+class PaintingSurface {+ AK_MAKE_NONCOPYABLE(PaintingSurface);+ AK_MAKE_NONMOVABLE(PaintingSurface);+public:enum class Origin {TopLeft,@@ -56,8 +62,6 @@ public:LCD,};- Function<void(PaintingSurface&)> on_flush;-// A surface whose pixels are in the color space, which is sRGB unless one is given.static NonnullRefPtr<PaintingSurface> create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> = {}, ColorSpace const& = {}, TextAntialiasing = TextAntialiasing::Grayscale);// Fails when neither a GPU surface nor a bitmap of the size can be allocated.@@ -98,16 +102,25 @@ public:// Whether the surface draws into an image shared with another process, rather than one Skia allocated.bool wraps_shared_image() const;+ // Runs after every flush.+ void set_on_flush(Function<void(PaintingSurface&)>);void flush();- ~PaintingSurface();+ void ref() const;+ void unref() const;++ PaintingSurface() = delete;+ ~PaintingSurface() = delete;private:struct Impl;- PaintingSurface(NonnullOwnPtr<Impl>&&);-- NonnullOwnPtr<Impl> m_impl;+ static NonnullRefPtr<PaintingSurface> adopt_impl(IntSize, NonnullOwnPtr<Impl>);+ static void destroy_impl(void*);+ Impl& impl() const;};}++template<>+inline constexpr bool AllocatedWithCustomAllocator<Gfx::PaintingSurface> = true;diff --git a/Services/Compositor/PresentableSurface.cpp b/Services/Compositor/PresentableSurface.cppindex ddd4604edb3..01988681c6e 100644--- a/Services/Compositor/PresentableSurface.cpp+++ b/Services/Compositor/PresentableSurface.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <Compositor/CompositorCoreRustFFI.h>#include <Compositor/PresentableSurface.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/WindowServer.h>@@ -11,34 +12,82 @@namespace Compositor {+static bool window_server_surface_may_be_read(void* surface)+{+ return static_cast<WindowServerSurface const*>(surface)->may_be_read_by_window_server();+}++static void destroy_window_server_surface(void* surface)+{+ delete static_cast<WindowServerSurface*>(surface);+}++static NonnullRefPtr<PresentableSurface> adopt_presentable_surface(PresentableSurface const* surface)+{+ return adopt_ref(const_cast<PresentableSurface&>(*surface));+}+NonnullRefPtr<PresentableSurface> PresentableSurface::create(NonnullRefPtr<Gfx::PaintingSurface> painting_surface, Gfx::PaintingSurface::Origin origin, OwnPtr<WindowServerSurface> window_server_surface){- return adopt_ref(*new PresentableSurface(move(painting_surface), origin, move(window_server_surface)));+ return adopt_presentable_surface(RustFFI::compositor_presentable_surface_create(+ painting_surface.ptr(),+ origin == Gfx::PaintingSurface::Origin::BottomLeft,+ window_server_surface.leak_ptr(),+ window_server_surface_may_be_read,+ destroy_window_server_surface));+}++Gfx::PaintingSurface& PresentableSurface::painting_surface() const+{+ return const_cast<Gfx::PaintingSurface&>(*RustFFI::compositor_presentable_surface_painting_surface(this));+}++bool PresentableSurface::content_is_upside_down() const+{+ return RustFFI::compositor_presentable_surface_content_is_upside_down(this);+}++WindowServerSurface const* PresentableSurface::window_server_surface() const+{+ return static_cast<WindowServerSurface const*>(RustFFI::compositor_presentable_surface_window_server_surface(this));}-PresentableSurface::PresentableSurface(NonnullRefPtr<Gfx::PaintingSurface> painting_surface, Gfx::PaintingSurface::Origin origin, OwnPtr<WindowServerSurface> window_server_surface)- : m_painting_surface(move(painting_surface))- , m_origin(origin)- , m_window_server_surface(move(window_server_surface))+void PresentableSurface::did_hand_to_window_server()+{+ RustFFI::compositor_presentable_surface_did_hand_to_window_server(this);+}++bool PresentableSurface::is_read_by_window_server() const{+ return RustFFI::compositor_presentable_surface_is_read_by_window_server(this);}-PresentableSurface::~PresentableSurface()+bool PresentableSurface::is_busy() const{- VERIFY(m_lease_count == 0);+ return RustFFI::compositor_presentable_surface_is_busy(this);+}++void PresentableSurface::ref() const+{+ RustFFI::compositor_presentable_surface_retain(this);+}++void PresentableSurface::unref() const+{+ RustFFI::compositor_presentable_surface_release(this);}PresentableSurface::Lease::Lease(PresentableSurface& surface): m_surface(surface){- ++surface.m_lease_count;+ RustFFI::compositor_presentable_surface_add_lease(m_surface.ptr());}PresentableSurface::Lease::Lease(Lease const& other): m_surface(other.m_surface){if (m_surface)- ++m_surface->m_lease_count;+ RustFFI::compositor_presentable_surface_add_lease(m_surface.ptr());}PresentableSurface::Lease::Lease(Lease&& other)@@ -53,7 +102,7 @@ PresentableSurface::Lease& PresentableSurface::Lease::operator=(Lease const& othrelease();m_surface = other.m_surface;if (m_surface)- ++m_surface->m_lease_count;+ RustFFI::compositor_presentable_surface_add_lease(m_surface.ptr());return *this;}@@ -75,14 +124,76 @@ void PresentableSurface::Lease::release(){if (!m_surface)return;- VERIFY(m_surface->m_lease_count > 0);- --m_surface->m_lease_count;+ RustFFI::compositor_presentable_surface_remove_lease(m_surface.ptr());m_surface = nullptr;}-bool PresentableSurface::is_read_by_window_server() const+WeakPresentableSurface::WeakPresentableSurface(PresentableSurface const& surface)+ : m_weak(RustFFI::compositor_presentable_surface_downgrade(&surface))+{+}++WeakPresentableSurface::WeakPresentableSurface(WeakPresentableSurface&& other)+ : m_weak(exchange(other.m_weak, nullptr)){- return m_was_handed_to_window_server && m_window_server_surface && m_window_server_surface->may_be_read_by_window_server();+}++WeakPresentableSurface& WeakPresentableSurface::operator=(WeakPresentableSurface&& other)+{+ if (this != &other) {+ RustFFI::compositor_weak_presentable_surface_destroy(m_weak);+ m_weak = exchange(other.m_weak, nullptr);+ }+ return *this;+}++WeakPresentableSurface::~WeakPresentableSurface()+{+ RustFFI::compositor_weak_presentable_surface_destroy(m_weak);+}++RefPtr<PresentableSurface> WeakPresentableSurface::strong_ref() const+{+ if (!m_weak)+ return nullptr;+ auto const* surface = RustFFI::compositor_weak_presentable_surface_upgrade(m_weak);+ if (!surface)+ return nullptr;+ return adopt_presentable_surface(surface);+}++PresentableSurfacePool::PresentableSurfacePool()+ : m_pool(RustFFI::compositor_presentable_surface_pool_create())+{+}++PresentableSurfacePool::PresentableSurfacePool(PresentableSurfacePool&& other)+ : m_pool(exchange(other.m_pool, nullptr))+{+}++PresentableSurfacePool& PresentableSurfacePool::operator=(PresentableSurfacePool&& other)+{+ if (this != &other) {+ RustFFI::compositor_presentable_surface_pool_destroy(m_pool);+ m_pool = exchange(other.m_pool, nullptr);+ }+ return *this;+}++PresentableSurfacePool::~PresentableSurfacePool()+{+ RustFFI::compositor_presentable_surface_pool_destroy(m_pool);+}++namespace {++struct SurfaceCreation {+ Gfx::IntSize size;+ RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context;+ Optional<Error> error;+};+}ErrorOr<NonnullRefPtr<PresentableSurface>> PresentableSurfacePool::create_surface(Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)@@ -95,30 +206,29 @@ ErrorOr<NonnullRefPtr<PresentableSurface>> PresentableSurfacePool::create_surfacreturn PresentableSurface::create(move(painting_surface), Gfx::PaintingSurface::Origin::TopLeft);}-ErrorOr<NonnullRefPtr<PresentableSurface>> PresentableSurfacePool::surface_for_next_content(Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)+static PresentableSurface const* create_surface_for_pool(void* context){- auto fits = [&](PresentableSurface const& surface) {- return surface.size() == size && surface.painting_surface().skia_backend_context() == skia_backend_context;- };- m_surfaces.remove_all_matching([&](auto const& surface) {- return !fits(*surface) && !surface->is_busy();- });-- auto take = [&](size_t index) {- auto surface = m_surfaces.take(index);- m_surfaces.append(surface);- return surface;- };- if (!m_surfaces.is_empty() && fits(*m_surfaces.last()) && !m_surfaces.last()->is_busy())- return m_surfaces.last();- for (size_t index = 0; index < m_surfaces.size(); ++index) {- if (fits(*m_surfaces[index]) && !m_surfaces[index]->is_busy())- return take(index);+ auto& creation = *static_cast<SurfaceCreation*>(context);+ auto surface = PresentableSurfacePool::create_surface(creation.size, creation.skia_backend_context);+ if (surface.is_error()) {+ creation.error = surface.release_error();+ return nullptr;}- if (m_surfaces.size() >= maximum_surface_count)+ return &surface.release_value().leak_ref();+}++ErrorOr<NonnullRefPtr<PresentableSurface>> PresentableSurfacePool::surface_for_next_content(Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)+{+ if (!m_pool)+ m_pool = RustFFI::compositor_presentable_surface_pool_create();+ SurfaceCreation creation { size, skia_backend_context, {} };+ auto const* surface = RustFFI::compositor_presentable_surface_pool_surface_for_next_content(m_pool, size, skia_backend_context.ptr(), create_surface_for_pool, &creation);+ if (!surface) {+ if (creation.error.has_value())+ return creation.error.release_value();return Error::from_string_literal("Every surface of the pool is busy");- m_surfaces.append(TRY(create_surface(size, skia_backend_context)));- return m_surfaces.last();+ }+ return adopt_presentable_surface(surface);}}diff --git a/Services/Compositor/PresentableSurface.h b/Services/Compositor/PresentableSurface.hindex 8f4a0a27007..90da3975fea 100644--- a/Services/Compositor/PresentableSurface.h+++ b/Services/Compositor/PresentableSurface.h@@ -6,13 +6,11 @@#pragma once+#include <AK/Error.h>#include <AK/Noncopyable.h>#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>#include <AK/OwnPtr.h>-#include <AK/RefCounted.h>-#include <AK/Vector.h>-#include <AK/Weakable.h>+#include <AK/RefPtr.h>#include <AK/kmalloc.h>#include <Compositor/PaintingSurface.h>#include <LibGfx/Forward.h>@@ -20,6 +18,10 @@namespace Compositor {+// The Rust core's halves of a weak surface reference and of a pool, which only it defines.+struct FfiWeakPresentableSurface;+struct FfiPresentableSurfacePool;+class WindowServerSurface {public:AK_ALLOC_WITH_KMALLOC;@@ -31,10 +33,10 @@ public:// A surface whose content the window server can show as it is, instead of after it is composited into a frame. While a// lease of it is held, as by a frame on its way to the window server and by the layer that shows it, or while the-// window server still reads it, the surface is busy, and its content must stay as it is.-class PresentableSurface final- : public RefCounted<PresentableSurface>- , public Weakable<PresentableSurface> {+// window server still reads it, the surface is busy, and its content must stay as it is. A pointer to it is the Rust+// core's surface itself, which the core and the C++ around it share by reference counting. Only the Compositor's main+// thread may use it.+class PresentableSurface {AK_MAKE_NONCOPYABLE(PresentableSurface);AK_MAKE_NONMOVABLE(PresentableSurface);@@ -60,31 +62,42 @@ public:};static NonnullRefPtr<PresentableSurface> create(NonnullRefPtr<Gfx::PaintingSurface>, Gfx::PaintingSurface::Origin, OwnPtr<WindowServerSurface> = {});- ~PresentableSurface();- Gfx::PaintingSurface& painting_surface() const { return *m_painting_surface; }- Gfx::IntSize size() const { return m_painting_surface->size(); }- bool content_is_upside_down() const { return m_origin == Gfx::PaintingSurface::Origin::BottomLeft; }+ Gfx::PaintingSurface& painting_surface() const;+ Gfx::IntSize size() const { return painting_surface().size(); }+ bool content_is_upside_down() const;// Null for a surface that draws into memory the window server cannot read.- WindowServerSurface const* window_server_surface() const { return m_window_server_surface.ptr(); }+ WindowServerSurface const* window_server_surface() const;// GPU work in flight on a surface counts as use too, so only a surface handed to the window server is checked.- void did_hand_to_window_server() { m_was_handed_to_window_server = true; }+ void did_hand_to_window_server();bool is_read_by_window_server() const;Lease lease() { return Lease { *this }; }- bool is_busy() const { return m_lease_count > 0 || is_read_by_window_server(); }+ bool is_busy() const;-private:- friend class PresentableSurfacePool;+ void ref() const;+ void unref() const;++ PresentableSurface() = delete;+ ~PresentableSurface() = delete;+};++// A weak reference to a surface, which tells whether anything still holds it.+class WeakPresentableSurface {+ AK_MAKE_NONCOPYABLE(WeakPresentableSurface);++public:+ WeakPresentableSurface() = default;+ explicit WeakPresentableSurface(PresentableSurface const&);+ WeakPresentableSurface(WeakPresentableSurface&&);+ WeakPresentableSurface& operator=(WeakPresentableSurface&&);+ ~WeakPresentableSurface();- PresentableSurface(NonnullRefPtr<Gfx::PaintingSurface>, Gfx::PaintingSurface::Origin, OwnPtr<WindowServerSurface>);+ RefPtr<PresentableSurface> strong_ref() const;- NonnullRefPtr<Gfx::PaintingSurface> m_painting_surface;- Gfx::PaintingSurface::Origin m_origin { Gfx::PaintingSurface::Origin::TopLeft };- bool m_was_handed_to_window_server { false };- size_t m_lease_count { 0 };- OwnPtr<WindowServerSurface> m_window_server_surface;+private:+ FfiWeakPresentableSurface* m_weak { nullptr };};// The surfaces that one piece of content, such as a canvas, is presented from in turn. The content goes into its@@ -92,26 +105,25 @@ private:// surface.class PresentableSurfacePool {AK_MAKE_NONCOPYABLE(PresentableSurfacePool);- AK_MAKE_DEFAULT_MOVABLE(PresentableSurfacePool);public:- // A surface is only added while every other one is busy, so a pool holds about as many as are on their way to the- // window server or still read by it at once, which is a few. The limit only stops a pool whose surfaces never stop- // being busy from growing without end.- static constexpr size_t maximum_surface_count = 8;-- PresentableSurfacePool() = default;- ~PresentableSurfacePool() = default;+ PresentableSurfacePool();+ PresentableSurfacePool(PresentableSurfacePool&&);+ PresentableSurfacePool& operator=(PresentableSurfacePool&&);+ ~PresentableSurfacePool();// A surface of the size for the next content, which is never one that is busy. Fails when every surface is busy and// the pool is full, or when no surface can be allocated, and the content then has to wait for a later turn.ErrorOr<NonnullRefPtr<PresentableSurface>> surface_for_next_content(Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&);-private:+ // A surface the window server can show by itself where it can, and one in memory or on the GPU otherwise.static ErrorOr<NonnullRefPtr<PresentableSurface>> create_surface(Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&);- // In the order the content went into them, the latest last.- Vector<NonnullRefPtr<PresentableSurface>> m_surfaces;+private:+ FfiPresentableSurfacePool* m_pool { nullptr };};}++template<>+inline constexpr bool AllocatedWithCustomAllocator<Compositor::PresentableSurface> = true;diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex a01028d5b7d..228302aa5cd 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -35,12 +35,28 @@ fn main() -> Result<(), Box<dyn Error>> {("RecordSpan", "Compositing::RustFFI::RecordSpan"),("CanvasId", "Compositing::CanvasId"),("ImageFrameResourceId", "Compositing::ImageFrameResourceId"),+ ("PaintingSurface", "Gfx::PaintingSurface"),+ ("PresentableSurface", "Compositor::PresentableSurface"),+ ("WeakPresentableSurface", "Compositor::FfiWeakPresentableSurface"),+ ("PresentableSurfacePool", "Compositor::FfiPresentableSurfacePool"),] {config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());}+ // The surfaces are the C++ classes that stand for them, and the C++ declares the rest, so they are only named.+ config.export.exclude.extend(+ [+ "PaintingSurface",+ "PresentableSurface",+ "WeakPresentableSurface",+ "PresentableSurfacePool",+ ]+ .map(String::from),+ );config.includes.extend(["AK/Span.h",+ "Compositor/PaintingSurface.h",+ "Compositor/PresentableSurface.h","LibCompositing/DisplayList/ContextRef.h","LibCompositing/DisplayList/DisplayListResourceIds.h","LibGfx/Color.h",@@ -63,6 +79,8 @@ fn main() -> Result<(), Box<dyn Error>> {"src/raster_host.rs","src/core/presenting.rs","src/core/mod.rs",+ "src/surfaces/painting_surface.rs",+ "src/surfaces/presentable_surface.rs",] {println!("cargo:rerun-if-changed={source}");builder = builder.with_src(manifest_dir.join(source));diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex 0b3ad2aca80..bea838e923b 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -19,7 +19,8 @@ use crate::host::{};use crate::overlays::UIOverlays;use crate::presenting::ContextPresenting;-use crate::raster_host::{RasterHost, SurfaceHandle};+use crate::raster_host::RasterHost;+use crate::surfaces::painting_surface::PaintingSurface;use crate::wheel_gesture_routing::WheelGestureIdAllocator;use libcompositing_rust::ipc_types::Compositing_ContextVisibility as ContextVisibility;use libcompositing_rust::scrolling::{@@ -684,7 +685,7 @@ impl CompositorCore {pub fn paint_screenshot(&self,context_id: CompositorContextId,- target: &SurfaceHandle,+ target: &Rc<PaintingSurface>,now: MonotonicTime,) -> bool {let _entered = self.enter();@@ -698,7 +699,7 @@ impl CompositorCore {&self,context_id: CompositorContextId,now: MonotonicTime,- ) -> Option<(SurfaceHandle, IntSize)> {+ ) -> Option<(Rc<PaintingSurface>, IntSize)> {let _entered = self.enter();self.presented_frame_for_snapshot_inner(context_id, now)diff --git a/Services/Compositor/Rust/src/core/presenting.rs b/Services/Compositor/Rust/src/core/presenting.rsindex b60b155b972..a20523b6231 100644--- a/Services/Compositor/Rust/src/core/presenting.rs+++ b/Services/Compositor/Rust/src/core/presenting.rs@@ -10,9 +10,8 @@ use super::CompositorCore;use crate::context_state::ContextState;use crate::host::{PendingFrame, PresentScheduling, PresentationId};use crate::presenting::{ContextPresenting, NestedContexts, PresentingEnvironment};-use crate::raster_host::{- FfiRemoteLayerFrame, FrameHandOff, StorePublication, StoreResizeOutcome, SublayersHandle, SurfaceHandle,-};+use crate::raster_host::{FfiRemoteLayerFrame, FrameHandOff, StorePublication, StoreResizeOutcome, SublayersHandle};+use crate::surfaces::painting_surface::PaintingSurface;use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::display_list::replay::{CompositedContexts, NoCompositedContexts, ResolvedCompositedContext};use libcompositing_rust::ipc_types::{@@ -23,6 +22,7 @@ use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{FloatMatrix4x4, FloatRect, IntRect, IntSize};use std::cell::RefCell;use std::io::Write;+use std::rc::Rc;/// A frame submitted to the GPU, which is delivered once its work is done, or once it is scheduled where the window/// server waits for it.@@ -1183,7 +1183,7 @@ impl CompositorCore {pub(super) fn paint_screenshot_inner(&self,context_id: CompositorContextId,- target: &SurfaceHandle,+ target: &Rc<PaintingSurface>,now: MonotonicTime,) -> bool {let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))@@ -1223,7 +1223,7 @@ impl CompositorCore {&self,context_id: CompositorContextId,now: MonotonicTime,- ) -> Option<(SurfaceHandle, IntSize)> {+ ) -> Option<(Rc<PaintingSurface>, IntSize)> {let presenting = self.presenting_of(context_id)?;if !presenting.borrow().presents_to_client {return None;diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex eed22abee38..2a1d1caca94 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -16,6 +16,7 @@ use crate::overlays::{UIOverlays,};use crate::raster_host::{FfiRasterHost, RasterHost};+use crate::surfaces::painting_surface::PaintingSurface;use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::ipc_types::{Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,@@ -23,7 +24,6 @@ use libcompositing_rust::ipc_types::{use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{IntRect, IntSize};use libipc_rust::cpp_connection::RawMessage;-use std::ffi::c_void;use std::rc::Rc;fn time(nanoseconds: i64) -> MonotonicTime {@@ -418,38 +418,35 @@ pub extern "C" fn compositor_core_canvas_content_changed(////// # Safety///-/// `surface` must be a live surface, which the call lends.+/// `surface` must be a live surface.#[unsafe(no_mangle)]pub unsafe extern "C" fn compositor_core_paint_screenshot(core: &CompositorCore,context_id: u64,- surface: *mut c_void,+ surface: *const PaintingSurface,now_nanoseconds: i64,) -> bool {- let Some(surface) = core.raster().retain_surface(surface) else {- return false;- };+ // SAFETY: The caller lends a live surface, which the painting holds while it lasts.+ let surface = unsafe { PaintingSurface::retained_from_ffi(surface) };core.paint_screenshot(CompositorContextId(context_id), &surface, time(now_nanoseconds))}/// The surface that holds the frame on screen as a whole, with one reference that the caller takes over, and the size-/// of the frame in it. Answers false where no frame is on screen.+/// of the frame in it. Answers null where no frame is on screen.#[unsafe(no_mangle)]pub extern "C" fn compositor_core_presented_frame_for_snapshot(core: &CompositorCore,context_id: u64,now_nanoseconds: i64,- surface: &mut *mut c_void,frame_size: &mut IntSize,-) -> bool {+) -> *const PaintingSurface {let Some((source, size)) =core.presented_frame_for_snapshot(CompositorContextId(context_id), time(now_nanoseconds))else {- return false;+ return std::ptr::null();};- *surface = core.raster().leak_surface(source);*frame_size = size;- true+ PaintingSurface::into_ffi(source)}/// Takes a message of the CompositorWebContentServer endpoint that is marked [RustReceiver].diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex d9a4c4e83fd..f2547d72cb0 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -33,6 +33,7 @@ pub mod raster_host;pub mod scroll_fling_controller;pub mod scroll_snap_controller;pub mod scrollbar_controller;+pub mod surfaces;pub mod wheel_gesture_routing;#[cfg(test)]diff --git a/Services/Compositor/Rust/src/presenting/layers.rs b/Services/Compositor/Rust/src/presenting/layers.rsindex 9c01b66b1cc..afbaea50efb 100644--- a/Services/Compositor/Rust/src/presenting/layers.rs+++ b/Services/Compositor/Rust/src/presenting/layers.rs@@ -12,17 +12,16 @@ use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, paint_overlays, rect_of_size, replay_into, replaying_only,};use crate::raster_host::{- FfiSublayer, FfiSublayerPlacement, LiveContent, MediaKind, PresentableSurfaceHandle, SublayerContentKind,- SurfaceBlend, SurfaceHandle,+ FfiSublayer, FfiSublayerPlacement, LiveContent, MediaKind, SublayerContentKind, SurfaceBlend,};+use crate::surfaces::painting_surface::PaintingSurface;+use crate::surfaces::presentable_surface::{PresentableSurface, PresentableSurfacePool};use libcompositing_rust::display_list::layers::{LayerKind, LayerPlan, LayerPlanInputs, build_layer_plan};use libcompositing_rust::display_list::summary::LiveContent as LiveMedia;use libcompositing_rust::display_list::window_server_placement::WindowServerPlacement;use libgfx_rust::{Color, IntRect, IntSize, ScalingMode};use std::collections::HashMap;--// The pool of presentable surfaces the overlays are shown from, apart from those of the painted layers.-const COMPOSITOR_OVERLAY_SURFACE_POOL: u32 = u32::MAX;+use std::rc::Rc;// Sublayers keep their identity from one frame to the next by what they show.const CANVAS_SUBLAYER_IDENTITY_TAG: u64 = 1 << 60;@@ -34,7 +33,7 @@ const MEDIA_DRAWING_INDEX_SHIFT: u32 = 44;#[derive(Default)]struct LayerSurface {- surface: Option<SurfaceHandle>,+ surface: Option<Rc<PaintingSurface>>,rect: IntRect,// Changes whenever anything is drawn into the surface.content_version: u64,@@ -43,7 +42,8 @@ struct LayerSurface {// The surface that the window server shows a painted layer from.#[derive(Default)]struct PaintedLayerPresentation {- latest_surface: Option<PresentableSurfaceHandle>,+ surface_pool: PresentableSurfacePool,+ latest_surface: Option<Rc<PresentableSurface>>,rect: IntRect,content_version: u64,}@@ -57,7 +57,9 @@ pub struct ContextLayers {// Whether the window server shows the canvases and videos of the latest frame above it.window_server_shows_media: bool,painted_layer_presentations: Vec<PaintedLayerPresentation>,- latest_overlay_surface: Option<PresentableSurfaceHandle>,+ // The surfaces the overlays are shown from, apart from those of the painted layers.+ overlay_surface_pool: PresentableSurfacePool,+ latest_overlay_surface: Option<Rc<PresentableSurface>>,overlay_rect: IntRect,}@@ -74,15 +76,9 @@ impl ContextLayers {self.window_server_shows_media}- pub fn drop_layers(&mut self, env: &PresentingEnvironment<'_>) {- if self.plan.is_none() && self.surfaces.is_empty() && self.painted_layer_presentations.is_empty() {- return;- }+ pub fn drop_layers(&mut self) {self.plan = None;self.surfaces.clear();- for pool in 0..self.painted_layer_presentations.len() {- env.raster.drop_presentable_surface_pool(env.context_id, pool as u32);- }self.painted_layer_presentations.clear();}}@@ -143,12 +139,12 @@ fn sublayer_placement_of(placement: &WindowServerPlacement) -> FfiSublayerPlacem}// A sublayer that shows a surface at its own rect, unclipped and untransformed.-fn surface_sublayer(identity: u64, surface: &PresentableSurfaceHandle, rect: IntRect) -> FfiSublayer {+fn surface_sublayer(identity: u64, surface: &Rc<PresentableSurface>, rect: IntRect) -> FfiSublayer {FfiSublayer {identity,content_kind: SublayerContentKind::PresentableSurface,media_id: 0,- presentable_surface: surface.as_ptr(),+ presentable_surface: surface.as_ffi(),placement: FfiSublayerPlacement {content_rect: rect,content_to_frame: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],@@ -242,11 +238,11 @@ impl ContextPresenting {true}- pub(super) fn commit_layer_update(&mut self, env: &PresentingEnvironment<'_>, layer_update: LayerUpdate) {+ pub(super) fn commit_layer_update(&mut self, layer_update: LayerUpdate) {let layers = &mut self.layers;layers.window_server_shows_media = layer_update.has_plan() && layer_update.shown_by_window_server;if !layer_update.has_plan() {- layers.drop_layers(env);+ layers.drop_layers();return;}if let Some(new_plan) = layer_update.new_plan {@@ -257,7 +253,7 @@ impl ContextPresenting {pub(super) fn paint_layered_frame(&mut self,env: &PresentingEnvironment<'_>,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,damage_rect: IntRect,layer_update: &LayerUpdate,@@ -282,7 +278,7 @@ impl ContextPresenting {fn paint_layers(&mut self,env: &PresentingEnvironment<'_>,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,damage_rect: IntRect,layer_update: &LayerUpdate,@@ -316,7 +312,7 @@ impl ContextPresenting {let shares_backend = layer_surface.surface.as_ref()- .is_some_and(|layer_surface| raster.surfaces_share_backend(layer_surface, surface));+ .is_some_and(|layer_surface| layer_surface.shares_backend_with(surface));if layer_surface.surface.is_none() || !surface_fits || !shares_backend {let Some(new_surface) = raster.create_surface(IntSize {@@ -401,7 +397,7 @@ impl ContextPresenting {pub(super) fn composite_layers_above_base(&self,env: &PresentingEnvironment<'_>,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,damage_rect: IntRect,) {@@ -414,7 +410,7 @@ impl ContextPresenting {fn composite_layers_above_base_with_plan(&self,env: &PresentingEnvironment<'_>,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,plan: &LayerPlan,damage_rect: IntRect,@@ -454,14 +450,11 @@ impl ContextPresenting {&mut self,env: &PresentingEnvironment<'_>,plan: &LayerPlan,- like: &SurfaceHandle,+ like: &Rc<PaintingSurface>,) -> bool {let raster = env.raster;let layers = &mut self.layers;// The surfaces of the layers that the plan no longer has go with them.- for pool in plan.layers.len()..layers.painted_layer_presentations.len() {- raster.drop_presentable_surface_pool(env.context_id, pool as u32);- }layers.painted_layer_presentations.resize_with(plan.layers.len(), PaintedLayerPresentation::default);@@ -487,11 +480,16 @@ impl ContextPresenting {width: layer.rect.width,height: layer.rect.height,};- let Some(presentable) = raster.next_presentable_surface(env.context_id, index as u32, layer_size, like)+ let Some(presentable) =+ presentation+ .surface_pool+ .surface_for_next_content(layer_size, like.gpu_backend_context(), || {+ raster.create_presentable_surface(layer_size, like)+ })else {return false;};- let target = raster.painting_surface_of(&presentable);+ let target = presentable.painting_surface();let source_rect = IntRect::new(layer.rect.x - layer_surface.rect.x,layer.rect.y - layer_surface.rect.y,@@ -499,7 +497,7 @@ impl ContextPresenting {layer.rect.height,);raster.draw_surface(- &target,+ target,source,source_rect,rect_of_size(layer_size),@@ -516,7 +514,7 @@ impl ContextPresenting {&mut self,env: &PresentingEnvironment<'_>,frame: &FrameToPaint<'_>,- like: &SurfaceHandle,+ like: &Rc<PaintingSurface>,) -> bool {let raster = env.raster;let bounds = frame.frame_inputs.overlays.bounds;@@ -530,16 +528,20 @@ impl ContextPresenting {height: bounds.height,};let Some(presentable) =- raster.next_presentable_surface(env.context_id, COMPOSITOR_OVERLAY_SURFACE_POOL, bounds_size, like)+ self.layers+ .overlay_surface_pool+ .surface_for_next_content(bounds_size, like.gpu_backend_context(), || {+ raster.create_presentable_surface(bounds_size, like)+ })else {return false;};- let target = raster.painting_surface_of(&presentable);- raster.clear(&target, Color::TRANSPARENT);- let save_count = raster.save(&target);- raster.translate(&target, -bounds.x as f32, -bounds.y as f32);- paint_overlays(env, &target, frame.frame_inputs, true);- raster.restore_to_count(&target, save_count);+ let target = presentable.painting_surface();+ raster.clear(target, Color::TRANSPARENT);+ let save_count = raster.save(target);+ raster.translate(target, -bounds.x as f32, -bounds.y as f32);+ paint_overlays(env, target, frame.frame_inputs, true);+ raster.restore_to_count(target, save_count);self.layers.latest_overlay_surface = Some(presentable);true}diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rsindex e7e0fc822be..5679e5cd5ff 100644--- a/Services/Compositor/Rust/src/presenting/mod.rs+++ b/Services/Compositor/Rust/src/presenting/mod.rs@@ -16,8 +16,8 @@ use crate::frame_inputs::FrameInputs;use crate::host::{ContextTimer, Host, PendingFrame};use crate::raster_host::{FfiStoreResize, FfiSublayer, PaintingResources, RasterHost, StorePublication, StoreResizeOutcome, SurfaceBlend,- SurfaceHandle,};+use crate::surfaces::painting_surface::PaintingSurface;use damage::{PaintedFrame, StoreDamage};use layers::ContextLayers;use libcompositing_rust::display_list::commands::{CompositorContextId, EffectNodeIndex};@@ -70,7 +70,7 @@ pub struct PresentingEnvironment<'a> {/// A frame drawn into a store, or for a frame that changes only what the window server shows above the frame on/// screen, into nothing.pub struct PreparedFrame {- pub rendered_surface: Option<SurfaceHandle>,+ pub rendered_surface: Option<Rc<PaintingSurface>>,pub bitmap_id: i32,pub damage_rect: IntRect,pub device_pixel_ratio: f64,@@ -142,18 +142,18 @@ pub struct ContextPresenting {store_publication: StorePublication,frame_without_store_in_flight: bool,- latest_rendered_surface: Option<SurfaceHandle>,+ latest_rendered_surface: Option<Rc<PaintingSurface>>,// The frame that the latest rendered surface holds, which the presented frame runs ahead of while its GPU work is in// flight.size_of_latest_rendered_frame: IntSize,store_damage: StoreDamage,- damage_surface: Option<SurfaceHandle>,+ damage_surface: Option<Rc<PaintingSurface>>,surplus_store_retirement_is_scheduled: bool,// The context was hidden long enough to keep only the store that holds its latest frame, and gets no new stores// until it is shown again.stores_are_retired_while_hidden: bool,- surface_drawn_by_parent: Option<SurfaceHandle>,+ surface_drawn_by_parent: Option<Rc<PaintingSurface>>,unbounded_raster_scale_of_embedding: FloatSize,raster_scale: FloatSize,raster_translation: FloatPoint,@@ -259,7 +259,7 @@ impl ContextPresenting {presentation_id: Option<u64>,) -> StoreResizeOutcome {if !self.presents_to_client {- self.fit_surface_drawn_by_parent_to_viewport(env);+ self.fit_surface_drawn_by_parent_to_viewport();return StoreResizeOutcome::Unchanged;}if env.raster.store_state(env.context_id).is_rendering {@@ -290,7 +290,7 @@ impl ContextPresenting {// A resize can arrive before the parent's next replay supplies the new embedding transform, so the existing// embedding's scale is bounded for the new viewport. Bounding the already bounded scale instead can round it// differently, which would discard the raster on every replay.- fn fit_surface_drawn_by_parent_to_viewport(&mut self, env: &PresentingEnvironment<'_>) {+ fn fit_surface_drawn_by_parent_to_viewport(&mut self) {let scale = bounded_composited_raster_scale(self.unbounded_raster_scale_of_embedding, self.viewport_size);if self.raster_scale != scale {self.raster_scale = scale;@@ -300,7 +300,7 @@ impl ContextPresenting {if self.surface_drawn_by_parent.as_ref()- .is_some_and(|surface| env.raster.surface_size(surface) != raster_size)+ .is_some_and(|surface| surface.size() != raster_size){self.surface_drawn_by_parent = None;}@@ -443,7 +443,7 @@ impl ContextPresenting {let surface = self.surface_drawn_by_parent.as_ref()?;let painted_frame = self.painted_frame.as_ref()?;Some(ResolvedCompositedContext {- surface: surface.as_ptr(),+ surface: surface.as_ffi().cast_mut().cast(),content_rect: FloatRect::new(self.raster_translation.x,self.raster_translation.y,@@ -617,7 +617,7 @@ impl ContextPresenting {if damage_rect.is_empty() && self.presented_frame == Some(pending_frame.viewport_rect) {let only_media_shown_by_window_server_changed =frame_damage.layers.shown_by_window_server && frame_damage.live_media_changed;- self.commit_layer_update(env, frame_damage.layers);+ self.commit_layer_update(frame_damage.layers);self.remember_painted_frame(env,pending_frame.viewport_rect,@@ -642,7 +642,7 @@ impl ContextPresenting {self.queue_present_frame(pending_frame);return None;};- let store_rect = rect_of_size(env.raster.surface_size(&store));+ let store_rect = rect_of_size(store.size());let repaint_rect = self.store_damage.take(bitmap_id, raster_damage_rect, store_rect);self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);let full_damage_rect = rect_of_size(IntSize {@@ -654,7 +654,7 @@ impl ContextPresenting {self.store_damage.add_damage_to_other_stores(bitmap_id, self.raster_rect_of(damage_rect));}- self.commit_layer_update(env, frame_damage.layers);+ self.commit_layer_update(frame_damage.layers);self.remember_painted_frame(env,pending_frame.viewport_rect,@@ -697,9 +697,7 @@ impl ContextPresenting {let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);let raster_size = self.raster_size();let (surface, repaint_rect) = match self.surface_drawn_by_parent.take() {- Some(surface) if env.raster.surface_size(&surface) == raster_size => {- (surface, self.raster_rect_of(frame_damage.rect))- }+ Some(surface) if surface.size() == raster_size => (surface, self.raster_rect_of(frame_damage.rect)),_ => {let Some(surface) = env.raster.create_surface(raster_size, None, false) else {return;@@ -708,7 +706,7 @@ impl ContextPresenting {}};self.paint_frame(env, &surface, &frame, repaint_rect, &mut frame_damage.layers);- self.commit_layer_update(env, frame_damage.layers);+ self.commit_layer_update(frame_damage.layers);self.remember_painted_frame(env,pending_frame.viewport_rect,@@ -727,7 +725,7 @@ impl ContextPresenting {pub fn paint_screenshot(&mut self,env: &PresentingEnvironment<'_>,- target: &SurfaceHandle,+ target: &Rc<PaintingSurface>,display_list: &Rc<DisplayList>,frame_inputs: &FrameInputs,) {@@ -744,7 +742,7 @@ impl ContextPresenting {pub fn presented_frame_for_snapshot(&mut self,env: &PresentingEnvironment<'_>,- ) -> Option<(SurfaceHandle, IntSize)> {+ ) -> Option<(Rc<PaintingSurface>, IntSize)> {let latest_rendered_surface = self.latest_rendered_surface.clone()?;let mut source = latest_rendered_surface;// The store then holds only what is under the canvases, videos and overlays that the window server shows above it.@@ -752,7 +750,7 @@ impl ContextPresenting {&& self.layers.has_plan()&& let Some(painted_frame) = self.painted_frame.take(){- let source_size = env.raster.surface_size(&source);+ let source_size = source.size();let composited = env.raster.create_surface(source_size, Some(&source), false);if let Some(composited) = composited {let source_rect = rect_of_size(source_size);@@ -772,7 +770,7 @@ impl ContextPresenting {}self.painted_frame = Some(painted_frame);}- let source_size = env.raster.surface_size(&source);+ let source_size = source.size();let frame_size = IntSize {width: self.size_of_latest_rendered_frame.width.min(source_size.width),height: self.size_of_latest_rendered_frame.height.min(source_size.height),@@ -786,7 +784,7 @@ impl ContextPresenting {fn paint_frame(&mut self,env: &PresentingEnvironment<'_>,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,mut damage_rect: IntRect,layer_update: &mut layers::LayerUpdate,@@ -801,7 +799,7 @@ impl ContextPresenting {layer_update.new_plan = None;layer_update.keeps_plan = false;layer_update.shown_by_window_server = false;- self.layers.drop_layers(env);+ self.layers.drop_layers();}// NB: Only a frame shown on screen ages the rasters it did not use, so a screenshot keeps them.env.raster.start_raster_cache_frame(env.context_id);@@ -811,7 +809,7 @@ impl ContextPresenting {fn paint_current_display_list(&mut self,env: &PresentingEnvironment<'_>,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,damage_rect: Option<IntRect>,paints_ui_overlays: bool,@@ -820,7 +818,7 @@ impl ContextPresenting {let raster = env.raster;let surface_clear_color = frame.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT);let allows_lcd_text = damage_rect.is_some() && self.allows_lcd_text(frame.display_list, frame.frame_inputs);- let paint_display_list = |target: &SurfaceHandle| {+ let paint_display_list = |target: &Rc<PaintingSurface>| {replay_into(env,target,@@ -839,8 +837,8 @@ impl ContextPresenting {&& (IntSize {width: damage_rect.width,height: damage_rect.height,- }) != raster.surface_size(surface)- && raster.surface_uses_gpu(surface)+ }) != surface.size()+ && surface.uses_gpu(){let damage_size = IntSize {width: damage_rect.width,@@ -849,7 +847,7 @@ impl ContextPresenting {if self.damage_surface.as_ref()- .is_none_or(|damage_surface| raster.surface_size(damage_surface) != damage_size)+ .is_none_or(|damage_surface| damage_surface.size() != damage_size){self.damage_surface = raster.create_surface(damage_size, Some(surface), true);}@@ -882,7 +880,7 @@ impl ContextPresenting {raster.restore_to_count(surface, save_count);}- fn apply_raster_transform(&self, raster: &RasterHost, surface: &SurfaceHandle) {+ fn apply_raster_transform(&self, raster: &RasterHost, surface: &Rc<PaintingSurface>) {raster.translate(surface, self.raster_translation.x, self.raster_translation.y);raster.scale(surface, self.raster_scale.width, self.raster_scale.height);}@@ -906,7 +904,7 @@ impl ContextPresenting {// Replays the frame's display list into the target, through the painter of the context's page.pub(crate) fn replay_into(env: &PresentingEnvironment<'_>,- target: &SurfaceHandle,+ target: &Rc<PaintingSurface>,frame: &FrameToPaint<'_>,selection: ReplaySelection<'_>,) {@@ -957,7 +955,7 @@ pub(crate) fn replaying_only(record_spans: &[RecordSpan], skip_root_isolation_la// browser.pub(crate) fn paint_overlays(env: &PresentingEnvironment<'_>,- target: &SurfaceHandle,+ target: &Rc<PaintingSurface>,frame_inputs: &FrameInputs,paints_ui_overlays: bool,) {diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex a2aeeee8831..bf58fd2a499 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -8,6 +8,8 @@//! stores of each context, the surfaces the window server shows, the media that live content comes from, GPU//! submission, and the display ticks. None of these calls comes back into the core before it returns.+use crate::surfaces::painting_surface::PaintingSurface;+use crate::surfaces::presentable_surface::PresentableSurface;use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::display_list::storage::{PackedChunkSize, ReceivedChunk, receive_packed_chunks_from_shared_memory,@@ -19,6 +21,7 @@ use libgfx_rust::{Color, FloatRect, IntRect, IntSize, ScalingMode};use std::collections::HashMap;use std::ffi::c_void;use std::ptr::NonNull;+use std::rc::Rc;/// How a surface is drawn into another.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -92,7 +95,8 @@ pub struct FfiStoreResize {#[repr(C)]pub struct FfiAcquiredStore {pub bitmap_id: i32,- pub surface: *mut c_void,+ /// Lent for as long as the store lives.+ pub surface: *const PaintingSurface,}#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]@@ -181,7 +185,7 @@ pub struct FfiSublayer {pub identity: u64,pub content_kind: SublayerContentKind,pub media_id: u64,- pub presentable_surface: *mut c_void,+ pub presentable_surface: *const PresentableSurface,pub placement: FfiSublayerPlacement,}@@ -203,31 +207,27 @@ pub struct FfiRemoteLayerFrame {pub struct FfiRasterHost {pub host: *mut c_void,- pub surface_retain: unsafe extern "C" fn(*mut c_void),- pub surface_release: unsafe extern "C" fn(*mut c_void),- /// Writes the size of the surface. NB: A C++ function returns Gfx::IntSize in memory rather than in a register- /// on Windows, so the size does not come back as the return value.- pub surface_size: unsafe extern "C" fn(*mut c_void, *mut IntSize),- /// Null where the surface could not be made. The surface is made like the one given, or for the GPU the compositor- /// renders with where none is given. The last argument also inherits LCD text for pixel-aligned copies.- pub create_surface: unsafe extern "C" fn(*mut c_void, IntSize, *mut c_void, bool) -> *mut c_void,- pub surfaces_share_backend: unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool,- pub surface_uses_gpu: unsafe extern "C" fn(*mut c_void) -> bool,- pub surface_save: unsafe extern "C" fn(*mut c_void) -> i32,- pub surface_restore_to_count: unsafe extern "C" fn(*mut c_void, i32),- pub surface_translate: unsafe extern "C" fn(*mut c_void, f32, f32),- pub surface_scale: unsafe extern "C" fn(*mut c_void, f32, f32),- pub surface_clip_rect: unsafe extern "C" fn(*mut c_void, IntRect),- pub surface_clear: unsafe extern "C" fn(*mut c_void, Color),+ /// A new surface with one reference that the caller takes over, or null where it could not be made. The surface is+ /// made like the one given, or for the GPU the compositor renders with where none is given. The last argument also+ /// inherits LCD text for pixel-aligned copies.+ pub create_surface:+ unsafe extern "C" fn(*mut c_void, IntSize, *const PaintingSurface, bool) -> *const PaintingSurface,+ pub surface_save: unsafe extern "C" fn(*const PaintingSurface) -> i32,+ pub surface_restore_to_count: unsafe extern "C" fn(*const PaintingSurface, i32),+ pub surface_translate: unsafe extern "C" fn(*const PaintingSurface, f32, f32),+ pub surface_scale: unsafe extern "C" fn(*const PaintingSurface, f32, f32),+ pub surface_clip_rect: unsafe extern "C" fn(*const PaintingSurface, IntRect),+ pub surface_clear: unsafe extern "C" fn(*const PaintingSurface, Color),/// Arguments: the target, the source, the rect of the source drawn, the rect of the target it is drawn into, and/// how it is blended.- pub surface_draw_surface: unsafe extern "C" fn(*mut c_void, *mut c_void, IntRect, IntRect, SurfaceBlend),- pub flush_surface: unsafe extern "C" fn(*mut c_void, *mut c_void),+ pub surface_draw_surface:+ unsafe extern "C" fn(*const PaintingSurface, *const PaintingSurface, IntRect, IntRect, SurfaceBlend),+ pub flush_surface: unsafe extern "C" fn(*const PaintingSurface),/// Arguments: the host, the context, the surface, whose resources it draws with, whether it allows LCD text,/// and where the painter is written. The painting lasts until `end_painting`, and paintings nest.pub begin_painting:- unsafe extern "C" fn(*mut c_void, u64, *mut c_void, PaintingResources, bool, *mut FfiRasterPainter),+ unsafe extern "C" fn(*mut c_void, u64, *const PaintingSurface, PaintingResources, bool, *mut FfiRasterPainter),pub end_painting: unsafe extern "C" fn(*mut c_void),/// Lets the raster caches of the context's page drop what the frames before the one that starts did not use.pub start_raster_cache_frame: unsafe extern "C" fn(*mut c_void, u64),@@ -240,7 +240,7 @@ pub struct FfiRasterHost {pub release_store: unsafe extern "C" fn(*mut c_void, u64, i32) -> bool,pub release_all_presented_stores: unsafe extern "C" fn(*mut c_void, u64),/// Lent; null before any store was rendered into.- pub latest_rendered_store_surface: unsafe extern "C" fn(*mut c_void, u64) -> *mut c_void,+ pub latest_rendered_store_surface: unsafe extern "C" fn(*mut c_void, u64) -> *const PaintingSurface,/// Arguments: the context, and the presentation that shows its stores, if it has one. Answers whether a store was/// added.pub add_store_if_window_server_reads_every_released_store:@@ -254,13 +254,10 @@ pub struct FfiRasterHost {/// needs a whole new allocation.pub restore_stores_retired_while_hidden: unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,- /// Arguments: the context, the pool, the size, and a surface the new one is made like. Null where none could be had.- pub next_presentable_surface: unsafe extern "C" fn(*mut c_void, u64, u32, IntSize, *mut c_void) -> *mut c_void,- pub drop_presentable_surface_pool: unsafe extern "C" fn(*mut c_void, u64, u32),- pub presentable_surface_retain: unsafe extern "C" fn(*mut c_void),- pub presentable_surface_release: unsafe extern "C" fn(*mut c_void),- /// Lent for as long as the presentable surface lives.- pub presentable_surface_painting_surface: unsafe extern "C" fn(*mut c_void) -> *mut c_void,+ /// A new surface of the size, made like the one given, with one reference that the caller takes over, or null+ /// where none could be made.+ pub create_presentable_surface:+ unsafe extern "C" fn(*mut c_void, IntSize, *const PaintingSurface) -> *const PresentableSurface,pub live_content: unsafe extern "C" fn(*mut c_void,@@ -279,7 +276,7 @@ pub struct FfiRasterHost {pub frame_hand_off: unsafe extern "C" fn(*mut c_void, u64) -> FrameHandOff,/// Submits the GPU work drawn into the surface, or into the surfaces the window server shows where it is null,/// answering a token that `compositor_core_gpu_work_finished` hands back once it is done, on a later turn.- pub submit_frame: unsafe extern "C" fn(*mut c_void, u64, *mut c_void) -> u64,+ pub submit_frame: unsafe extern "C" fn(*mut c_void, u64, *const PaintingSurface) -> u64,/// Calls `compositor_core_frame_ready_for_hand_off` with the token on a later turn, once the work is scheduled.pub hand_off_once_gpu_work_is_scheduled: unsafe extern "C" fn(*mut c_void, u64),/// Shows a frame in the remote layer that shows the context, with the sublayers given, which it takes over. Answers@@ -334,57 +331,6 @@ pub struct FfiRasterHost {pub finish_staged_rasterization: unsafe extern "C" fn(*mut c_void, u64, u64),}-/// A surface of the C++ side, which this keeps alive.-pub struct SurfaceHandle {- surface: NonNull<c_void>,- release: unsafe extern "C" fn(*mut c_void),- retain: unsafe extern "C" fn(*mut c_void),-}--impl SurfaceHandle {- pub fn as_ptr(&self) -> *mut c_void {- self.surface.as_ptr()- }-}--impl Clone for SurfaceHandle {- fn clone(&self) -> Self {- // SAFETY: The surface is live, as this holds it.- unsafe { (self.retain)(self.surface.as_ptr()) };- Self {- surface: self.surface,- release: self.release,- retain: self.retain,- }- }-}--impl Drop for SurfaceHandle {- fn drop(&mut self) {- // SAFETY: This holds the reference it gives back.- unsafe { (self.release)(self.surface.as_ptr()) };- }-}--/// A surface the window server shows, which this keeps alive.-pub struct PresentableSurfaceHandle {- surface: NonNull<c_void>,- release: unsafe extern "C" fn(*mut c_void),-}--impl PresentableSurfaceHandle {- pub fn as_ptr(&self) -> *mut c_void {- self.surface.as_ptr()- }-}--impl Drop for PresentableSurfaceHandle {- fn drop(&mut self) {- // SAFETY: This holds the reference it gives back.- unsafe { (self.release)(self.surface.as_ptr()) };- }-}-/// Sublayers whose content the C++ side resolved, which keep that content busy until they are shown or dropped.pub struct SublayersHandle {sublayers: NonNull<c_void>,@@ -420,60 +366,17 @@ impl RasterHost {self.0.host}- /// Takes a reference to a surface the C++ side lends.- pub fn retain_surface(&self, surface: *mut c_void) -> Option<SurfaceHandle> {- let surface = NonNull::new(surface)?;- // SAFETY: The C++ side lends a live surface.- unsafe { (self.0.surface_retain)(surface.as_ptr()) };- Some(SurfaceHandle {- surface,- release: self.0.surface_release,- retain: self.0.surface_retain,- })- }-- /// Hands the reference the handle holds over to the C++ side.- pub fn leak_surface(&self, surface: SurfaceHandle) -> *mut c_void {- let pointer = surface.as_ptr();- std::mem::forget(surface);- pointer- }-- // Adopts the reference the C++ side handed over with a new surface.- fn adopt_surface(&self, surface: *mut c_void) -> Option<SurfaceHandle> {- Some(SurfaceHandle {- surface: NonNull::new(surface)?,- release: self.0.surface_release,- retain: self.0.surface_retain,- })- }-- pub fn surface_size(&self, surface: &SurfaceHandle) -> IntSize {- let mut size = IntSize::default();- // SAFETY: The surface is live, and the host writes the size during the call.- unsafe { (self.0.surface_size)(surface.as_ptr(), &raw mut size) };- size- }-pub fn create_surface(&self,size: IntSize,- like: Option<&SurfaceHandle>,+ like: Option<&Rc<PaintingSurface>>,inherits_lcd_text: bool,- ) -> Option<SurfaceHandle> {- let like = like.map_or(std::ptr::null_mut(), SurfaceHandle::as_ptr);- // SAFETY: The host outlives this, and the surface it is made like is live.- self.adopt_surface(unsafe { (self.0.create_surface)(self.host(), size, like, inherits_lcd_text) })- }-- pub fn surfaces_share_backend(&self, a: &SurfaceHandle, b: &SurfaceHandle) -> bool {- // SAFETY: Both surfaces are live.- unsafe { (self.0.surfaces_share_backend)(a.as_ptr(), b.as_ptr()) }- }-- pub fn surface_uses_gpu(&self, surface: &SurfaceHandle) -> bool {- // SAFETY: The surface is live.- unsafe { (self.0.surface_uses_gpu)(surface.as_ptr()) }+ ) -> Option<Rc<PaintingSurface>> {+ let like = like.map_or(std::ptr::null(), Rc::as_ptr);+ // SAFETY: The host outlives this, and hands over a new surface or null.+ unsafe {+ PaintingSurface::adopted_from_ffi((self.0.create_surface)(self.host(), size, like, inherits_lcd_text))+ }}pub fn start_raster_cache_frame(&self, context_id: CompositorContextId) {@@ -481,58 +384,60 @@ impl RasterHost {unsafe { (self.0.start_raster_cache_frame)(self.host(), context_id.0) };}- pub fn save(&self, surface: &SurfaceHandle) -> i32 {+ pub fn save(&self, surface: &Rc<PaintingSurface>) -> i32 {// SAFETY: The surface is live.- unsafe { (self.0.surface_save)(surface.as_ptr()) }+ unsafe { (self.0.surface_save)(Rc::as_ptr(surface)) }}- pub fn restore_to_count(&self, surface: &SurfaceHandle, count: i32) {+ pub fn restore_to_count(&self, surface: &Rc<PaintingSurface>, count: i32) {// SAFETY: The surface is live.- unsafe { (self.0.surface_restore_to_count)(surface.as_ptr(), count) };+ unsafe { (self.0.surface_restore_to_count)(Rc::as_ptr(surface), count) };}- pub fn translate(&self, surface: &SurfaceHandle, x: f32, y: f32) {+ pub fn translate(&self, surface: &Rc<PaintingSurface>, x: f32, y: f32) {// SAFETY: The surface is live.- unsafe { (self.0.surface_translate)(surface.as_ptr(), x, y) };+ unsafe { (self.0.surface_translate)(Rc::as_ptr(surface), x, y) };}- pub fn scale(&self, surface: &SurfaceHandle, x: f32, y: f32) {+ pub fn scale(&self, surface: &Rc<PaintingSurface>, x: f32, y: f32) {// SAFETY: The surface is live.- unsafe { (self.0.surface_scale)(surface.as_ptr(), x, y) };+ unsafe { (self.0.surface_scale)(Rc::as_ptr(surface), x, y) };}- pub fn clip_rect(&self, surface: &SurfaceHandle, rect: IntRect) {+ pub fn clip_rect(&self, surface: &Rc<PaintingSurface>, rect: IntRect) {// SAFETY: The surface is live.- unsafe { (self.0.surface_clip_rect)(surface.as_ptr(), rect) };+ unsafe { (self.0.surface_clip_rect)(Rc::as_ptr(surface), rect) };}- pub fn clear(&self, surface: &SurfaceHandle, color: Color) {+ pub fn clear(&self, surface: &Rc<PaintingSurface>, color: Color) {// SAFETY: The surface is live.- unsafe { (self.0.surface_clear)(surface.as_ptr(), color) };+ unsafe { (self.0.surface_clear)(Rc::as_ptr(surface), color) };}pub fn draw_surface(&self,- target: &SurfaceHandle,- source: &SurfaceHandle,+ target: &Rc<PaintingSurface>,+ source: &Rc<PaintingSurface>,source_rect: IntRect,target_rect: IntRect,blend: SurfaceBlend,) {// SAFETY: Both surfaces are live.- unsafe { (self.0.surface_draw_surface)(target.as_ptr(), source.as_ptr(), source_rect, target_rect, blend) };+ unsafe {+ (self.0.surface_draw_surface)(Rc::as_ptr(target), Rc::as_ptr(source), source_rect, target_rect, blend);+ }}- pub fn flush(&self, surface: &SurfaceHandle) {- // SAFETY: The host outlives this, and the surface is live.- unsafe { (self.0.flush_surface)(self.host(), surface.as_ptr()) };+ pub fn flush(&self, surface: &Rc<PaintingSurface>) {+ // SAFETY: The surface is live.+ unsafe { (self.0.flush_surface)(Rc::as_ptr(surface)) };}/// Paints into the surface through a painter, which `paint` drives.pub fn paint(&self,context_id: CompositorContextId,- surface: &SurfaceHandle,+ surface: &Rc<PaintingSurface>,resources: PaintingResources,allows_lcd_text: bool,paint: impl FnOnce(&mut FfiRasterPainter),@@ -543,7 +448,7 @@ impl RasterHost {(self.0.begin_painting)(self.host(),context_id.0,- surface.as_ptr(),+ Rc::as_ptr(surface),resources,allows_lcd_text,painter.as_mut_ptr(),@@ -570,16 +475,21 @@ impl RasterHost {unsafe { (self.0.invalidate_stores)(self.host(), context_id.0) };}- pub fn acquire_store(&self, context_id: CompositorContextId) -> Option<(i32, SurfaceHandle)> {+ pub fn acquire_store(&self, context_id: CompositorContextId) -> Option<(i32, Rc<PaintingSurface>)> {let mut acquired = FfiAcquiredStore {bitmap_id: -1,- surface: std::ptr::null_mut(),+ surface: std::ptr::null(),};// SAFETY: The host outlives this.- if !unsafe { (self.0.acquire_store)(self.host(), context_id.0, &raw mut acquired) } {+ if !unsafe { (self.0.acquire_store)(self.host(), context_id.0, &raw mut acquired) }+ || acquired.surface.is_null()+ {return None;}- Some((acquired.bitmap_id, self.retain_surface(acquired.surface)?))+ // SAFETY: The host lends the live surface of the store.+ Some((acquired.bitmap_id, unsafe {+ PaintingSurface::retained_from_ffi(acquired.surface)+ }))}pub fn complete_rendering(&self, context_id: CompositorContextId, bitmap_id: i32) {@@ -597,9 +507,11 @@ impl RasterHost {unsafe { (self.0.release_all_presented_stores)(self.host(), context_id.0) };}- pub fn latest_rendered_store_surface(&self, context_id: CompositorContextId) -> Option<SurfaceHandle> {+ pub fn latest_rendered_store_surface(&self, context_id: CompositorContextId) -> Option<Rc<PaintingSurface>> {// SAFETY: The host outlives this.- self.retain_surface(unsafe { (self.0.latest_rendered_store_surface)(self.host(), context_id.0) })+ let surface = unsafe { (self.0.latest_rendered_store_surface)(self.host(), context_id.0) };+ // SAFETY: The host lends the live surface of the store, or null.+ (!surface.is_null()).then(|| unsafe { PaintingSurface::retained_from_ffi(surface) })}pub fn add_store_if_window_server_reads_every_released_store(@@ -662,31 +574,19 @@ impl RasterHost {}}- pub fn next_presentable_surface(+ pub fn create_presentable_surface(&self,- context_id: CompositorContextId,- pool: u32,size: IntSize,- like: &SurfaceHandle,- ) -> Option<PresentableSurfaceHandle> {- // SAFETY: The host outlives this, and the surface is live.- let surface =- unsafe { (self.0.next_presentable_surface)(self.host(), context_id.0, pool, size, like.as_ptr()) };- Some(PresentableSurfaceHandle {- surface: NonNull::new(surface)?,- release: self.0.presentable_surface_release,- })- }-- pub fn drop_presentable_surface_pool(&self, context_id: CompositorContextId, pool: u32) {- // SAFETY: The host outlives this.- unsafe { (self.0.drop_presentable_surface_pool)(self.host(), context_id.0, pool) };- }-- pub fn painting_surface_of(&self, surface: &PresentableSurfaceHandle) -> SurfaceHandle {- // SAFETY: The presentable surface is live, and lends its painting surface.- self.retain_surface(unsafe { (self.0.presentable_surface_painting_surface)(surface.as_ptr()) })- .expect("a presentable surface has a painting surface")+ like: &Rc<PaintingSurface>,+ ) -> Option<Rc<PresentableSurface>> {+ // SAFETY: The host outlives this, and hands over a new surface or null.+ unsafe {+ PresentableSurface::adopted_from_ffi((self.0.create_presentable_surface)(+ self.host(),+ size,+ Rc::as_ptr(like),+ ))+ }}pub fn live_content(&self, context_id: CompositorContextId, canvas_ids: &[u64]) -> LiveContent {@@ -752,8 +652,8 @@ impl RasterHost {unsafe { (self.0.frame_hand_off)(self.host(), context_id.0) }}- pub fn submit_frame(&self, context_id: CompositorContextId, surface: Option<&SurfaceHandle>) -> u64 {- let surface = surface.map_or(std::ptr::null_mut(), SurfaceHandle::as_ptr);+ pub fn submit_frame(&self, context_id: CompositorContextId, surface: Option<&Rc<PaintingSurface>>) -> u64 {+ let surface = surface.map_or(std::ptr::null(), Rc::as_ptr);// SAFETY: The host outlives this, and the surface is live.unsafe { (self.0.submit_frame)(self.host(), context_id.0, surface) }}diff --git a/Services/Compositor/Rust/src/surfaces/mod.rs b/Services/Compositor/Rust/src/surfaces/mod.rsnew file mode 100644index 00000000000..2380bcc3e56--- /dev/null+++ b/Services/Compositor/Rust/src/surfaces/mod.rs@@ -0,0 +1,8 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++pub mod painting_surface;+pub mod presentable_surface;diff --git a/Services/Compositor/Rust/src/surfaces/painting_surface.rs b/Services/Compositor/Rust/src/surfaces/painting_surface.rsnew file mode 100644index 00000000000..5b8c1b3bcb9--- /dev/null+++ b/Services/Compositor/Rust/src/surfaces/painting_surface.rs@@ -0,0 +1,192 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A surface the Compositor paints into, which the core and the C++ around it share by reference counting: a pointer to+//! a `Gfx::PaintingSurface` is the `PaintingSurface` of an `Rc`. The Skia part of the surface is C++, and the surface+//! owns it. Only the Compositor's main thread may retain, release or read a surface.++use libgfx_rust::IntSize;+use std::ffi::c_void;+use std::ptr::NonNull;+use std::rc::Rc;++pub struct PaintingSurface {+ size: IntSize,+ gpu_backend_context: *const c_void,+ skia_surface: NonNull<c_void>,+ destroy_skia_surface: unsafe extern "C" fn(*mut c_void),+}++impl PaintingSurface {+ pub fn size(&self) -> IntSize {+ self.size+ }++ pub fn uses_gpu(&self) -> bool {+ !self.gpu_backend_context.is_null()+ }++ pub fn shares_backend_with(&self, other: &PaintingSurface) -> bool {+ self.gpu_backend_context == other.gpu_backend_context+ }++ /// Null for a surface in memory.+ pub fn gpu_backend_context(&self) -> *const c_void {+ self.gpu_backend_context+ }++ pub fn as_ffi(self: &Rc<Self>) -> *const PaintingSurface {+ Rc::as_ptr(self)+ }++ /// # Safety+ ///+ /// `surface` must be a live surface, which then has one more owner.+ pub unsafe fn retained_from_ffi(surface: *const PaintingSurface) -> Rc<PaintingSurface> {+ assert!(!surface.is_null(), "the C++ side passes a surface");+ // SAFETY: The caller passes the PaintingSurface of a live Rc.+ unsafe {+ Rc::increment_strong_count(surface);+ Rc::from_raw(surface)+ }+ }++ /// # Safety+ ///+ /// `surface` must be a surface whose one reference the caller hands over, or null.+ pub unsafe fn adopted_from_ffi(surface: *const PaintingSurface) -> Option<Rc<PaintingSurface>> {+ if surface.is_null() {+ return None;+ }+ // SAFETY: The caller hands over one reference to the PaintingSurface of a live Rc.+ Some(unsafe { Rc::from_raw(surface) })+ }++ pub fn into_ffi(surface: Rc<PaintingSurface>) -> *const PaintingSurface {+ Rc::into_raw(surface)+ }+}++impl Drop for PaintingSurface {+ fn drop(&mut self) {+ // SAFETY: The surface owns its Skia part, which nothing uses once the last reference is gone.+ unsafe { (self.destroy_skia_surface)(self.skia_surface.as_ptr()) };+ }+}++/// A new surface whose one reference the caller owns and gives up with `compositor_painting_surface_release()`. It+/// takes over the Skia part, which it destroys with `destroy_skia_surface` once the last reference is gone. A GPU+/// surface names the backend context it renders with, which surfaces that can be drawn into each other share.+///+/// # Safety+///+/// `skia_surface` must be a live Skia part that `destroy_skia_surface` destroys.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_painting_surface_create(+ size: IntSize,+ gpu_backend_context: *const c_void,+ skia_surface: *mut c_void,+ destroy_skia_surface: unsafe extern "C" fn(*mut c_void),+) -> *const PaintingSurface {+ let skia_surface = NonNull::new(skia_surface).expect("the C++ side passes the Skia part of the surface");+ PaintingSurface::into_ffi(Rc::new(PaintingSurface {+ size,+ gpu_backend_context,+ skia_surface,+ destroy_skia_surface,+ }))+}++/// # Safety+///+/// `surface` must be a live surface.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_painting_surface_retain(surface: *const PaintingSurface) {+ assert!(!surface.is_null(), "the C++ side passes a surface");+ // SAFETY: The caller passes the PaintingSurface of a live Rc.+ unsafe { Rc::increment_strong_count(surface) };+}++/// # Safety+///+/// `surface` must be a live surface of which the caller owns a reference.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_painting_surface_release(surface: *const PaintingSurface) {+ assert!(!surface.is_null(), "the C++ side passes a surface");+ // SAFETY: The caller gives up one of its references to the PaintingSurface of a live Rc.+ unsafe { Rc::decrement_strong_count(surface) };+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_painting_surface_skia_surface(surface: &PaintingSurface) -> *mut c_void {+ surface.skia_surface.as_ptr()+}++/// NB: A C++ function returns Gfx::IntSize in memory rather than in a register on Windows, so the size is written.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_painting_surface_size(surface: &PaintingSurface, size: &mut IntSize) {+ *size = surface.size;+}++#[cfg(test)]+pub mod testing {+ use super::*;+ use std::cell::Cell;++ thread_local! {+ pub static DESTROYED_SKIA_SURFACES: Cell<usize> = const { Cell::new(0) };+ }++ unsafe extern "C" fn count_destroyed_skia_surface(_: *mut c_void) {+ DESTROYED_SKIA_SURFACES.with(|count| count.set(count.get() + 1));+ }++ pub fn surface_for_testing(size: IntSize, gpu_backend_context: usize) -> Rc<PaintingSurface> {+ // SAFETY: The Skia part is a dangling pointer that only the counting destroy function sees.+ let surface = unsafe {+ compositor_painting_surface_create(+ size,+ gpu_backend_context as *const c_void,+ NonNull::<u8>::dangling().as_ptr().cast(),+ count_destroyed_skia_surface,+ )+ };+ // SAFETY: The surface was just made with one reference, which this takes over.+ unsafe { PaintingSurface::adopted_from_ffi(surface) }.expect("a new surface")+ }+}++#[cfg(test)]+mod tests {+ use super::testing::*;+ use super::*;++ #[test]+ fn skia_part_is_destroyed_with_the_last_reference_from_either_side() {+ let before = DESTROYED_SKIA_SURFACES.with(|count| count.get());+ let surface = surface_for_testing(IntSize { width: 4, height: 3 }, 0);+ let pointer = surface.as_ffi();+ // SAFETY: The surface is live, and the reference taken here is given up below.+ unsafe { compositor_painting_surface_retain(pointer) };+ drop(surface);+ assert_eq!(DESTROYED_SKIA_SURFACES.with(|count| count.get()), before);+ // SAFETY: The reference taken above is given up.+ unsafe { compositor_painting_surface_release(pointer) };+ assert_eq!(DESTROYED_SKIA_SURFACES.with(|count| count.get()), before + 1);+ }++ #[test]+ fn surfaces_share_a_backend_by_its_context() {+ let size = IntSize { width: 1, height: 1 };+ let gpu = surface_for_testing(size, 0x10);+ let same_gpu = surface_for_testing(size, 0x10);+ let cpu = surface_for_testing(size, 0);+ assert!(gpu.uses_gpu());+ assert!(!cpu.uses_gpu());+ assert!(gpu.shares_backend_with(&same_gpu));+ assert!(!gpu.shares_backend_with(&cpu));+ }+}diff --git a/Services/Compositor/Rust/src/surfaces/presentable_surface.rs b/Services/Compositor/Rust/src/surfaces/presentable_surface.rsnew file mode 100644index 00000000000..25b7f60a645--- /dev/null+++ b/Services/Compositor/Rust/src/surfaces/presentable_surface.rs@@ -0,0 +1,435 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A surface whose content the window server can show as it is, instead of after it is composited into a frame, which+//! the core and the C++ around it share by reference counting: a pointer to a `Compositor::PresentableSurface` is the+//! `PresentableSurface` of an `Rc`. While a lease of it is held, as by a frame on its way to the window server and by+//! the layer that shows it, or while the window server still reads it, the surface is busy, and its content must stay+//! as it is. Only the Compositor's main thread may use a surface.++use crate::surfaces::painting_surface::PaintingSurface;+use libgfx_rust::IntSize;+use std::cell::Cell;+use std::ffi::c_void;+use std::ptr::NonNull;+use std::rc::{Rc, Weak};++/// The part of a presentable surface that the window server shows, which is C++ and which the surface owns.+pub struct WindowServerSurface {+ surface: NonNull<c_void>,+ may_be_read_by_window_server: unsafe extern "C" fn(*mut c_void) -> bool,+ destroy: unsafe extern "C" fn(*mut c_void),+}++impl Drop for WindowServerSurface {+ fn drop(&mut self) {+ // SAFETY: The presentable surface owns the window server's part, which nothing uses once it is gone.+ unsafe { (self.destroy)(self.surface.as_ptr()) };+ }+}++pub struct PresentableSurface {+ painting_surface: Rc<PaintingSurface>,+ content_is_upside_down: bool,+ window_server_surface: Option<WindowServerSurface>,+ was_handed_to_window_server: Cell<bool>,+ lease_count: Cell<usize>,+}++impl PresentableSurface {+ pub fn painting_surface(&self) -> &Rc<PaintingSurface> {+ &self.painting_surface+ }++ pub fn size(&self) -> IntSize {+ self.painting_surface.size()+ }++ pub fn as_ffi(self: &Rc<Self>) -> *const PresentableSurface {+ Rc::as_ptr(self)+ }++ /// # Safety+ ///+ /// `surface` must be a surface whose one reference the caller hands over, or null.+ pub unsafe fn adopted_from_ffi(surface: *const PresentableSurface) -> Option<Rc<PresentableSurface>> {+ if surface.is_null() {+ return None;+ }+ // SAFETY: The caller hands over one reference to the PresentableSurface of a live Rc.+ Some(unsafe { Rc::from_raw(surface) })+ }++ // GPU work in flight on a surface counts as use too, so only a surface handed to the window server is checked.+ pub fn is_read_by_window_server(&self) -> bool {+ self.was_handed_to_window_server.get()+ && self+ .window_server_surface+ .as_ref()+ .is_some_and(|window_server_surface| {+ // SAFETY: The window server's part is live for as long as the surface.+ unsafe {+ (window_server_surface.may_be_read_by_window_server)(window_server_surface.surface.as_ptr())+ }+ })+ }++ pub fn is_busy(&self) -> bool {+ self.lease_count.get() > 0 || self.is_read_by_window_server()+ }++ pub fn lease(self: &Rc<Self>) -> PresentableSurfaceLease {+ self.lease_count.set(self.lease_count.get() + 1);+ PresentableSurfaceLease(self.clone())+ }+}++impl Drop for PresentableSurface {+ fn drop(&mut self) {+ assert_eq!(self.lease_count.get(), 0, "a lease holds the surface");+ }+}++/// Keeps the content of the surface as it is for as long as it is held. Holding the surface itself does not.+pub struct PresentableSurfaceLease(Rc<PresentableSurface>);++impl PresentableSurfaceLease {+ pub fn surface(&self) -> &Rc<PresentableSurface> {+ &self.0+ }+}++impl Clone for PresentableSurfaceLease {+ fn clone(&self) -> Self {+ self.0.lease()+ }+}++impl Drop for PresentableSurfaceLease {+ fn drop(&mut self) {+ let count = self.0.lease_count.get();+ assert!(count > 0, "the lease counts towards the surface");+ self.0.lease_count.set(count - 1);+ }+}++/// The surfaces that one piece of content, such as a canvas, is presented from in turn. The content goes into its+/// latest surface again unless that one is busy, so content that is only ever composited into frames keeps a single+/// surface.+#[derive(Default)]+pub struct PresentableSurfacePool {+ // In the order the content went into them, the latest last.+ surfaces: Vec<Rc<PresentableSurface>>,+}++// A surface is only added while every other one is busy, so a pool holds about as many as are on their way to the+// window server or still read by it at once, which is a few. The limit only stops a pool whose surfaces never stop being+// busy from growing without end.+const MAXIMUM_SURFACE_COUNT_OF_POOL: usize = 8;++impl PresentableSurfacePool {+ /// A surface of the size for the next content, rendered with the GPU backend context given, which is never one that+ /// is busy. None when every surface is busy and the pool is full, or when `create` makes none, and the content then+ /// has to wait for a later turn.+ pub fn surface_for_next_content(+ &mut self,+ size: IntSize,+ gpu_backend_context: *const c_void,+ create: impl FnOnce() -> Option<Rc<PresentableSurface>>,+ ) -> Option<Rc<PresentableSurface>> {+ let fits = |surface: &PresentableSurface| {+ surface.size() == size && surface.painting_surface.gpu_backend_context() == gpu_backend_context+ };+ self.surfaces.retain(|surface| fits(surface) || surface.is_busy());++ let can_take_next_content = |surface: &PresentableSurface| fits(surface) && !surface.is_busy();+ if let Some(latest) = self.surfaces.last()+ && can_take_next_content(latest)+ {+ return Some(latest.clone());+ }+ if let Some(index) = self.surfaces.iter().position(|surface| can_take_next_content(surface)) {+ let surface = self.surfaces.remove(index);+ self.surfaces.push(surface.clone());+ return Some(surface);+ }++ if self.surfaces.len() >= MAXIMUM_SURFACE_COUNT_OF_POOL {+ return None;+ }+ let surface = create()?;+ self.surfaces.push(surface.clone());+ Some(surface)+ }+}++/// A new surface over the painting surface, whose one reference the caller owns and gives up with+/// `compositor_presentable_surface_release()`. It takes over the window server's part, if there is one, which it+/// destroys with `destroy_window_server_surface`.+///+/// # Safety+///+/// `painting_surface` must be a live surface. A window server's part must be live and destroyed by+/// `destroy_window_server_surface`, and `may_be_read_by_window_server` must answer for it.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_presentable_surface_create(+ painting_surface: *const PaintingSurface,+ content_is_upside_down: bool,+ window_server_surface: *mut c_void,+ may_be_read_by_window_server: unsafe extern "C" fn(*mut c_void) -> bool,+ destroy_window_server_surface: unsafe extern "C" fn(*mut c_void),+) -> *const PresentableSurface {+ // SAFETY: The caller passes a live surface, which the presentable surface holds.+ let painting_surface = unsafe { PaintingSurface::retained_from_ffi(painting_surface) };+ let window_server_surface = NonNull::new(window_server_surface).map(|surface| WindowServerSurface {+ surface,+ may_be_read_by_window_server,+ destroy: destroy_window_server_surface,+ });+ Rc::into_raw(Rc::new(PresentableSurface {+ painting_surface,+ content_is_upside_down,+ window_server_surface,+ was_handed_to_window_server: Cell::new(false),+ lease_count: Cell::new(0),+ }))+}++/// # Safety+///+/// `surface` must be a live surface.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_presentable_surface_retain(surface: *const PresentableSurface) {+ assert!(!surface.is_null(), "the C++ side passes a surface");+ // SAFETY: The caller passes the PresentableSurface of a live Rc.+ unsafe { Rc::increment_strong_count(surface) };+}++/// # Safety+///+/// `surface` must be a live surface of which the caller owns a reference.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_presentable_surface_release(surface: *const PresentableSurface) {+ assert!(!surface.is_null(), "the C++ side passes a surface");+ // SAFETY: The caller gives up one of its references to the PresentableSurface of a live Rc.+ unsafe { Rc::decrement_strong_count(surface) };+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_painting_surface(+ surface: &PresentableSurface,+) -> *const PaintingSurface {+ surface.painting_surface.as_ffi()+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_content_is_upside_down(surface: &PresentableSurface) -> bool {+ surface.content_is_upside_down+}++/// The window server's part of the surface, or null for a surface that draws into memory the window server cannot read.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_window_server_surface(surface: &PresentableSurface) -> *mut c_void {+ surface+ .window_server_surface+ .as_ref()+ .map_or(std::ptr::null_mut(), |window_server_surface| {+ window_server_surface.surface.as_ptr()+ })+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_did_hand_to_window_server(surface: &PresentableSurface) {+ surface.was_handed_to_window_server.set(true);+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_is_read_by_window_server(surface: &PresentableSurface) -> bool {+ surface.is_read_by_window_server()+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_is_busy(surface: &PresentableSurface) -> bool {+ surface.is_busy()+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_add_lease(surface: &PresentableSurface) {+ surface.lease_count.set(surface.lease_count.get() + 1);+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_remove_lease(surface: &PresentableSurface) {+ let count = surface.lease_count.get();+ assert!(count > 0, "the lease counts towards the surface");+ surface.lease_count.set(count - 1);+}++pub struct WeakPresentableSurface(Weak<PresentableSurface>);++/// A weak reference to the surface, which `compositor_weak_presentable_surface_destroy()` gives up.+///+/// # Safety+///+/// `surface` must be a live surface.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_presentable_surface_downgrade(+ surface: *const PresentableSurface,+) -> *mut WeakPresentableSurface {+ // SAFETY: The caller passes the PresentableSurface of a live Rc, which this borrows only to downgrade it.+ let surface = std::mem::ManuallyDrop::new(unsafe { Rc::from_raw(surface) });+ Box::into_raw(Box::new(WeakPresentableSurface(Rc::downgrade(&surface))))+}++/// A reference to the surface that the caller owns, or null once the surface is gone.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_weak_presentable_surface_upgrade(+ weak: &WeakPresentableSurface,+) -> *const PresentableSurface {+ weak.0.upgrade().map_or(std::ptr::null(), Rc::into_raw)+}++/// # Safety+///+/// `weak` must be null or a weak reference from `compositor_presentable_surface_downgrade()` that nothing uses+/// afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_weak_presentable_surface_destroy(weak: *mut WeakPresentableSurface) {+ if !weak.is_null() {+ // SAFETY: The caller hands over the weak reference.+ drop(unsafe { Box::from_raw(weak) });+ }+}++/// A pool of surfaces for C++ that presents content from one, which `compositor_presentable_surface_pool_destroy()`+/// destroys.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_presentable_surface_pool_create() -> *mut PresentableSurfacePool {+ Box::into_raw(Box::default())+}++/// # Safety+///+/// `pool` must be null or a pool from `compositor_presentable_surface_pool_create()` that nothing uses afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_presentable_surface_pool_destroy(pool: *mut PresentableSurfacePool) {+ if !pool.is_null() {+ // SAFETY: The caller hands over the pool.+ drop(unsafe { Box::from_raw(pool) });+ }+}++/// A surface of the pool for the next content, with one reference that the caller takes over, or null when the content+/// has to wait. A new surface comes from `create`, which hands over one reference to it or answers null.+///+/// # Safety+///+/// `create` must answer as described while the call runs, and must not use the pool.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_presentable_surface_pool_surface_for_next_content(+ pool: &mut PresentableSurfacePool,+ size: IntSize,+ gpu_backend_context: *const c_void,+ create: unsafe extern "C" fn(*mut c_void) -> *const PresentableSurface,+ create_context: *mut c_void,+) -> *const PresentableSurface {+ pool.surface_for_next_content(size, gpu_backend_context, || {+ // SAFETY: The caller's `create` hands over a new surface or answers null.+ unsafe { PresentableSurface::adopted_from_ffi(create(create_context)) }+ })+ .map_or(std::ptr::null(), Rc::into_raw)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::surfaces::painting_surface::testing::surface_for_testing;++ unsafe extern "C" fn never_read(_: *mut c_void) -> bool {+ false+ }++ unsafe extern "C" fn destroy_nothing(_: *mut c_void) {}++ fn presentable_surface(size: IntSize) -> Rc<PresentableSurface> {+ let painting_surface = surface_for_testing(size, 0x10);+ // SAFETY: The painting surface is live, and there is no window server's part.+ let surface = unsafe {+ compositor_presentable_surface_create(+ painting_surface.as_ffi(),+ false,+ std::ptr::null_mut(),+ never_read,+ destroy_nothing,+ )+ };+ // SAFETY: The surface was just made with one reference, which this takes over.+ unsafe { PresentableSurface::adopted_from_ffi(surface) }.expect("a new surface")+ }++ const SIZE: IntSize = IntSize { width: 8, height: 8 };+ const BACKEND: *const c_void = 0x10 as *const c_void;++ #[test]+ fn pool_reuses_its_latest_surface_while_nothing_holds_it() {+ let mut pool = PresentableSurfacePool::default();+ let first = pool+ .surface_for_next_content(SIZE, BACKEND, || Some(presentable_surface(SIZE)))+ .unwrap();+ let again = pool+ .surface_for_next_content(SIZE, BACKEND, || panic!("no new surface"))+ .unwrap();+ assert!(Rc::ptr_eq(&first, &again));+ }++ #[test]+ fn pool_adds_a_surface_while_the_others_are_leased() {+ let mut pool = PresentableSurfacePool::default();+ let first = pool+ .surface_for_next_content(SIZE, BACKEND, || Some(presentable_surface(SIZE)))+ .unwrap();+ let lease = first.lease();+ let second = pool+ .surface_for_next_content(SIZE, BACKEND, || Some(presentable_surface(SIZE)))+ .unwrap();+ assert!(!Rc::ptr_eq(&first, &second));+ drop(lease);+ let reused = pool+ .surface_for_next_content(SIZE, BACKEND, || panic!("no new surface"))+ .unwrap();+ assert!(Rc::ptr_eq(&second, &reused));+ }++ #[test]+ fn pool_stops_growing_when_every_surface_is_busy() {+ let mut pool = PresentableSurfacePool::default();+ let mut leases = Vec::new();+ for _ in 0..MAXIMUM_SURFACE_COUNT_OF_POOL {+ let surface = pool+ .surface_for_next_content(SIZE, BACKEND, || Some(presentable_surface(SIZE)))+ .unwrap();+ leases.push(surface.lease());+ }+ assert!(+ pool.surface_for_next_content(SIZE, BACKEND, || panic!("no new surface"))+ .is_none()+ );+ }++ #[test]+ fn pool_drops_idle_surfaces_of_another_size() {+ let mut pool = PresentableSurfacePool::default();+ let small = pool+ .surface_for_next_content(SIZE, BACKEND, || Some(presentable_surface(SIZE)))+ .unwrap();+ let weak = Rc::downgrade(&small);+ drop(small);+ let larger = IntSize { width: 16, height: 16 };+ pool.surface_for_next_content(larger, BACKEND, || Some(presentable_surface(larger)))+ .unwrap();+ assert!(weak.upgrade().is_none());+ }+}