Truly independent web browser
Compositor: Reach remote layers through a window server
Aliaksandr Kalenik3477738a5f1e
diff --git a/Libraries/LibCompositing/Types.h b/Libraries/LibCompositing/Types.hindex fa30a697bd5..398db57cae6 100644--- a/Libraries/LibCompositing/Types.h+++ b/Libraries/LibCompositing/Types.h@@ -38,6 +38,18 @@ enum class ContextVisibility : u8 {Hidden,};+enum class RemoteLayerHostKind : u8 {+ None,+ CoreAnimationContext,+};++struct RemoteLayerHostHandle {+ RemoteLayerHostKind kind { RemoteLayerHostKind::None };+ u64 id { 0 };++ bool operator==(RemoteLayerHostHandle const&) const = default;+};+// Where a reader of the compositor's async scroll updates takes them from: the ones the compositor pushed// (already here, in order with the input it forwarded), or the compositor's state as of now, asked for// synchronously, for a reader that routes input against the offsets the compositor holds this instant.diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 893793a09ad..062e4f432c1 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -32,6 +32,7 @@ set(SOURCESVideoFrameSkia.cppVSyncScheduler.cppWebGLObjectMap.cpp+ WindowServer.cpp)invoke_py_generator(@@ -101,7 +102,7 @@ if (USE_VULKAN_DMABUF_IMAGES)endif()if (APPLE)- target_sources(compositorservice PRIVATE MainDispatchQueue.mm RemoteLayer.mm VideoFrameSkia.mm)+ target_sources(compositorservice PRIVATE CoreAnimationWindowServer.mm MainDispatchQueue.mm VideoFrameSkia.mm)target_link_libraries(compositorservice PUBLIC "-framework AVFoundation" "-framework CoreGraphics" "-framework CoreMedia" "-framework CoreVideo" "-framework QuartzCore")endif()diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 8b3fc3e419b..16446bb21b3 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -127,6 +127,8 @@ PresentationId CompositorState::register_presentation(CompositorStateClient& prePresentationId presentation_id { m_next_presentation_id++ };m_presentations.set(&presentation, capabilities);m_presentations_by_id.set(presentation_id, &presentation);+ if (auto window_server = WindowServer::try_create_for_presentation())+ m_window_servers.set(&presentation, window_server.release_nonnull());return presentation_id;}@@ -139,6 +141,10 @@ void CompositorState::unregister_presentation(CompositorStateClient& presentatio}for (auto remote_layer_id : remote_layer_ids)destroy_remote_layer(remote_layer_id);+ if (auto window_server = m_window_servers.take(&presentation); window_server.has_value()) {+ if (m_window_servers_holding_changes.remove_first_matching([&](auto const& holding) { return holding.ptr() == window_server->ptr(); }))+ (*window_server)->release_changes_held_off_screen();+ }Vector<Web::CompositorContextId> bound_context_ids;for (auto const& [context_id, bound_presentation] : m_context_presentations) {@@ -200,12 +206,16 @@ u32 CompositorState::create_remote_layer(CompositorStateClient& presentation, u6dbgln("Compositor: Ignoring creation of remote layer {}, which already exists", remote_layer_id);return 0;}- auto layer = RemoteLayer::try_create();+ auto window_server = m_window_servers.get(&presentation);+ if (!window_server.has_value())+ return 0;+ auto layer = (*window_server)->try_create_remote_layer(remote_layer_id);if (!layer)return 0;- auto core_animation_context_id = layer->core_animation_context_id();- m_remote_layers.set(remote_layer_id, { .presentation = &presentation, .layer = move(layer), .shown_context_id = {}, .fit_within = {}, .size_of_shown_frame_laid_out_by_page = {} });- return core_animation_context_id;+ auto host_handle = layer->host_handle();+ VERIFY(host_handle.kind == Compositing::RemoteLayerHostKind::CoreAnimationContext);+ m_remote_layers.set(remote_layer_id, { .presentation = &presentation, .window_server = **window_server, .layer = move(layer), .shown_context_id = {}, .fit_within = {}, .size_of_shown_frame_laid_out_by_page = {} });+ return static_cast<u32>(host_handle.id);}void CompositorState::destroy_remote_layer(u64 remote_layer_id)@@ -270,18 +280,22 @@ static constexpr auto SYNCHRONIZED_RESIZE_HOLD_LIMIT = AK::Duration::from_secondvoid CompositorState::begin_synchronized_resize(u64 remote_layer_id, u64 token){- if (!m_remote_layers.contains(remote_layer_id))+ auto remote_layer = m_remote_layers.find(remote_layer_id);+ if (remote_layer == m_remote_layers.end())return;- if (!m_remote_layer_changes_are_held) {- m_remote_layer_changes_are_held = true;- RemoteLayer::hold_changes_on_screen();- if (!m_synchronized_resize_hold_timeout) {- m_synchronized_resize_hold_timeout = Core::Timer::create_single_shot(SYNCHRONIZED_RESIZE_HOLD_LIMIT, [this] {- dbgln("Compositor: Releasing the window resize that was never committed");- release_synchronized_resize_hold();- });+ auto& window_server = remote_layer->value.window_server;+ if (!m_window_servers_holding_changes.contains_slow(window_server)) {+ if (m_window_servers_holding_changes.is_empty()) {+ if (!m_synchronized_resize_hold_timeout) {+ m_synchronized_resize_hold_timeout = Core::Timer::create_single_shot(SYNCHRONIZED_RESIZE_HOLD_LIMIT, [this] {+ dbgln("Compositor: Releasing the window resize that was never committed");+ release_synchronized_resize_hold();+ });+ }+ m_synchronized_resize_hold_timeout->start();}- m_synchronized_resize_hold_timeout->start();+ m_window_servers_holding_changes.append(window_server);+ window_server->hold_changes_on_screen();}m_synchronized_resizes.append({ .remote_layer_id = remote_layer_id, .token = token, .awaited_size = {}, .frame_is_held = false });}@@ -325,8 +339,8 @@ void CompositorState::release_synchronized_resize_hold()if (m_synchronized_resize_hold_timeout)m_synchronized_resize_hold_timeout->stop();m_synchronized_resizes.clear();- if (exchange(m_remote_layer_changes_are_held, false))- RemoteLayer::release_changes_held_off_screen();+ for (auto& window_server : exchange(m_window_servers_holding_changes, {}))+ window_server->release_changes_held_off_screen();}void CompositorState::stop_showing_context_in_remote_layer(Web::CompositorContextId context_id, PresentedContext& context)@@ -1255,24 +1269,41 @@ void CompositorState::present_frame(Web::CompositorContextId context_id, Presentelsem_skia_backend_context->flush_and_submit_async(move(did_finish));context.presenter.did_submit_prepared_frame(pending_frame.viewport_rect);+ // Handing the frame to the client before its GPU work finishes keeps it ahead of the window server's deadline for+ // the next refresh. A client that reads frames from CPU memory does not wait for that work, so it gets each frame+ // once it is done.+ if (context.presenter.presents_to_client() && m_skia_backend_context && !context.presents_from_cpu_memory && frame_hand_off_for(context) == WindowServer::FrameHandOff::OnceGpuWorkIsScheduled)+ hand_off_frame_once_gpu_work_is_scheduled(*pending_present);+ schedule_gpu_completion_check();+}++WindowServer::FrameHandOff CompositorState::frame_hand_off_for(PresentedContext const& context) const+{+ if (context.remote_layer_id.has_value()) {+ if (auto remote_layer = m_remote_layers.find(*context.remote_layer_id); remote_layer != m_remote_layers.end())+ return remote_layer->value.window_server->frame_hand_off();+ }+ return WindowServer::frame_hand_off_through_presentation();+}++void CompositorState::hand_off_frame_once_gpu_work_is_scheduled([[maybe_unused]] PendingAsyncPresent& pending_present)+{#ifdef AK_OS_MACOS- // The window server's reads of an IOSurface wait for GPU work that is already scheduled to write it. Handing the- // frame to the client before that work finishes keeps it ahead of the window server's deadline for the next refresh.- // A client that reads frames from CPU memory does not wait for that work, so it gets each frame once it is done.- if (context.presenter.presents_to_client() && m_skia_backend_context && !context.presents_from_cpu_memory) {- m_skia_backend_context->metal_context().when_committed_work_is_scheduled([self = NonnullRefPtr { *this }, &event_loop, pending_present]() mutable {- event_loop.deferred_invoke([self = move(self), pending_present] {- for (auto& entry : self->m_pending_async_presents) {- if (&entry == pending_present) {- self->deliver_rendered_frame(entry);- return;- }+ // The window server's reads of an IOSurface wait for GPU work that is already scheduled to write it.+ auto& event_loop = Core::EventLoop::current();+ m_skia_backend_context->metal_context().when_committed_work_is_scheduled([self = NonnullRefPtr { *this }, &event_loop, pending_present = &pending_present]() mutable {+ event_loop.deferred_invoke([self = move(self), pending_present] {+ for (auto& entry : self->m_pending_async_presents) {+ if (&entry == pending_present) {+ self->deliver_rendered_frame(entry);+ return;}- });+ }});- }+ });+#else+ VERIFY_NOT_REACHED();#endif- schedule_gpu_completion_check();}void CompositorState::schedule_requested_presents()@@ -1623,7 +1654,13 @@ void CompositorState::show_frame_in_remote_layer(Web::CompositorContextId contexVERIFY(shared_image_buffer || pending_present.keeps_shown_store);auto frame_size = pending_present.viewport_rect.size();- remote_layer->value.layer->show_frame(shared_image_buffer, frame_size, pending_present.device_pixel_ratio, remote_layer->value.fit_within, move(pending_present.sublayers));+ remote_layer->value.layer->show_frame({+ .store = shared_image_buffer,+ .painted_size = frame_size,+ .device_pixel_ratio = pending_present.device_pixel_ratio,+ .fit_within = remote_layer->value.fit_within,+ .sublayers = move(pending_present.sublayers),+ });remote_layer->value.size_of_shown_frame_laid_out_by_page = frame_size == context.size_laid_out_by_page ? Optional<Gfx::IntSize> { frame_size } : OptionalNone {};report_held_synchronized_resize_frames(remote_layer->key);remote_layer->value.presentation->did_present_frame_in_remote_layer(context_id, pending_present.viewport_rect, pending_present.damage_rect, pending_present.device_pixel_ratio);@@ -1776,7 +1813,12 @@ void CompositorState::resize_backing_stores_if_needed(Web::CompositorContextId cpublication_mode = BackingStoreManager::PublicationMode::Published;// The window server reads what it shows above the store straight from GPU memory.- context.presenter.set_window_server_may_show_media(publication_mode == BackingStoreManager::PublicationMode::ShownInRemoteLayer && m_skia_backend_context && !context.presents_from_cpu_memory);+ RemoteLayer const* remote_layer_that_may_show_media = nullptr;+ if (publication_mode == BackingStoreManager::PublicationMode::ShownInRemoteLayer && m_skia_backend_context && !context.presents_from_cpu_memory) {+ if (auto remote_layer = m_remote_layers.find(*context.remote_layer_id); remote_layer != m_remote_layers.end())+ remote_layer_that_may_show_media = remote_layer->value.layer.ptr();+ }+ context.presenter.set_remote_layer_that_may_show_media(remote_layer_that_may_show_media);if (auto publication = context.presenter.resize_backing_stores_if_needed(m_skia_backend_context, gpu_sharing_for_context(context_id), publication_mode); publication.has_value()) {if (publication_mode == BackingStoreManager::PublicationMode::Published)publish_backing_stores(context_id, context, publication.release_value());diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 9b4ac304469..881a8c40505 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -19,9 +19,9 @@#include <Compositor/ContextPresenter.h>#include <Compositor/DisplayListPlayerSkia.h>#include <Compositor/FramePacer.h>-#include <Compositor/RemoteLayer.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/VSyncScheduler.h>+#include <Compositor/WindowServer.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>@@ -312,6 +312,8 @@ private:void unbind_presentation(Web::CompositorContextId);void stop_showing_context_in_remote_layer(Web::CompositorContextId, PresentedContext&);void stop_delivering_in_flight_frames_to_their_viewer(Web::CompositorContextId);+ WindowServer::FrameHandOff frame_hand_off_for(PresentedContext const&) const;+ void hand_off_frame_once_gpu_work_is_scheduled(PendingAsyncPresent&);void show_frame_in_remote_layer(Web::CompositorContextId, PresentedContext&, PendingAsyncPresent&);void update_scroll_capabilities();void did_finish_async_present(PendingAsyncPresent&);@@ -349,8 +351,11 @@ private:HashMap<PresentationId, CompositorStateClient*> m_presentations_by_id;HashMap<Web::CompositorContextId, CompositorStateClient*> m_context_presentations;+ HashMap<CompositorStateClient*, NonnullRefPtr<WindowServer>> m_window_servers;+struct RemoteLayerState {CompositorStateClient* presentation { nullptr };+ NonnullRefPtr<WindowServer> window_server;OwnPtr<RemoteLayer> layer;Optional<Web::CompositorContextId> shown_context_id;Optional<Gfx::IntSize> fit_within;@@ -367,7 +372,7 @@ private:void report_held_synchronized_resize_frames(u64 remote_layer_id);void release_synchronized_resize_hold();Vector<SynchronizedResize> m_synchronized_resizes;- bool m_remote_layer_changes_are_held { false };+ Vector<NonnullRefPtr<WindowServer>> m_window_servers_holding_changes;bool m_window_server_may_show_high_dynamic_range { true };RefPtr<Core::Timer> m_synchronized_resize_hold_timeout;HashMap<u64, RemoteLayerState> m_remote_layers;diff --git a/Services/Compositor/ContextLayers.h b/Services/Compositor/ContextLayers.hindex 3d4da3c9e7b..5c722ebf0f9 100644--- a/Services/Compositor/ContextLayers.h+++ b/Services/Compositor/ContextLayers.h@@ -15,7 +15,7 @@#include <AK/kmalloc.h>#include <Compositor/CompositorCoreRustFFI.h>#include <Compositor/FrameInputs.h>-#include <Compositor/RemoteLayer.h>+#include <Compositor/RemoteSublayer.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibGfx/Rect.h>@@ -37,14 +37,7 @@ public:static OwnPtr<LayerPlan> build(FrameInputs const&, Compositing::DisplayList const&, Gfx::IntRect viewport_rect, ReadonlySpan<LiveMedia> active_media);~LayerPlan();- // Where the window server can show the content of a media layer by itself, in viewport pixels.- struct WindowServerPlacement {- Gfx::IntRect content_rect;- Gfx::AffineTransform content_to_viewport;- Gfx::FloatRect clip_rect;- Optional<RemoteSublayer::RoundedClip> rounded_clip;- Gfx::ScalingMode scaling_mode { Gfx::ScalingMode::Bilinear };- };+ using WindowServerPlacement = Compositor::WindowServerPlacement;struct Layer {LayerKind kind;diff --git a/Services/Compositor/ContextPresenter.cpp b/Services/Compositor/ContextPresenter.cppindex e30debfcb9b..fd731e35ae1 100644--- a/Services/Compositor/ContextPresenter.cpp+++ b/Services/Compositor/ContextPresenter.cpp@@ -660,7 +660,7 @@ ContextPresenter::LayerUpdate ContextPresenter::layer_update_for(FrameInputs conlayers.active_media = m_media_activity.active_media(now);// An HDR video is a layer from its first frame for as long as it is drawn, even while paused, so that the window// server keeps showing it brighter than SDR white instead of it going back into the frame, which holds SDR.- if (m_window_server_may_show_media && m_window_server_may_show_high_dynamic_range) {+ if (m_remote_layer_that_may_show_media && m_remote_layer_that_may_show_media->can_show_high_dynamic_range() && m_window_server_may_show_high_dynamic_range) {for (auto id : m_display_list->referenced_resource_ids().video_sinks) {LiveMedia media { RustFFI::FfiLiveMediaKind::Video, id };auto is_active = any_of(layers.active_media, [&](auto const& active) { return active.kind == media.kind && active.id == media.id; });@@ -882,32 +882,26 @@ void ContextPresenter::composite_layers_above_base(DisplayListPlayerSkia& displabool ContextPresenter::window_server_can_show_media_layers_of(LayerPlan const& plan){-#ifdef AK_OS_MACOS- if (!m_window_server_may_show_media)+ if (!m_remote_layer_that_may_show_media)return false;for (auto const& layer : plan.layers()) {if (layer.kind != LayerKind::Media)continue;if (!layer.window_server_placement.has_value())return false;+ Optional<RemoteLayer::Content> content;if (layer.media.kind == RustFFI::FfiLiveMediaKind::Canvas) {- auto surface = m_canvas_surfaces.presentable_canvas_surface(Compositing::CanvasId { layer.media.id });- if (!surface || !surface->iosurface())- return false;- } else {- // A frame that a decoder left in memory has no surface that the window server could read.- auto frame = current_video_frame(Compositing::VideoSinkResourceId { layer.media.id });- if (!frame || !frame->surface())- return false;+ if (auto surface = m_canvas_surfaces.presentable_canvas_surface(Compositing::CanvasId { layer.media.id }))+ content = surface.release_nonnull();+ } else if (auto frame = current_video_frame(Compositing::VideoSinkResourceId { layer.media.id })) {if (!m_window_server_may_show_high_dynamic_range && video_frame_holds_high_dynamic_range(*frame))return false;+ content = frame.release_nonnull();}+ if (!content.has_value() || !m_remote_layer_that_may_show_media->can_show(*layer.window_server_placement, *content, m_device_pixel_ratio))+ return false;}return true;-#else- (void)plan;- return false;-#endif}// Each painted layer goes to the window server as its own surface, which is copied from its raster when the rasterdiff --git a/Services/Compositor/ContextPresenter.h b/Services/Compositor/ContextPresenter.hindex 6abe4411230..7afcafcf82e 100644--- a/Services/Compositor/ContextPresenter.h+++ b/Services/Compositor/ContextPresenter.h@@ -73,9 +73,9 @@ public:bool presents_to_client() const { return m_presents_to_client; }void stop_presenting_to_client() { m_presents_to_client = false; }- // Whether the window server may show the canvases and videos of the frames above them, instead of the frames- // holding them.- void set_window_server_may_show_media(bool may_show_media) { m_window_server_may_show_media = may_show_media; }+ // The remote layer that may show the canvases and videos of the frames above them, instead of the frames holding+ // them.+ void set_remote_layer_that_may_show_media(RemoteLayer const* remote_layer) { m_remote_layer_that_may_show_media = remote_layer; }// Otherwise, the frame draws HDR content tone-mapped to SDR.void set_window_server_may_show_high_dynamic_range(bool may_show) { m_window_server_may_show_high_dynamic_range = may_show; }void did_deliver_frame_without_store() { m_frame_without_store_in_flight = false; }@@ -247,7 +247,7 @@ private:u64 m_last_layer_content_version { 0 };bool m_repaint_everything_after_dropping_layers { false };- bool m_window_server_may_show_media { false };+ RemoteLayer const* m_remote_layer_that_may_show_media { nullptr };bool m_window_server_may_show_high_dynamic_range { true };// Whether the window server shows the canvases and videos of the latest frame above it.bool m_window_server_shows_media { false };diff --git a/Services/Compositor/CoreAnimationWindowServer.h b/Services/Compositor/CoreAnimationWindowServer.hnew file mode 100644index 00000000000..cadcf45d1b6--- /dev/null+++ b/Services/Compositor/CoreAnimationWindowServer.h@@ -0,0 +1,92 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/HashMap.h>+#include <AK/NonnullRefPtr.h>+#include <AK/Optional.h>+#include <AK/OwnPtr.h>+#include <AK/Time.h>+#include <AK/Types.h>+#include <AK/Variant.h>+#include <AK/Vector.h>+#include <Compositor/PresentableSurface.h>+#include <Compositor/RemoteLayer.h>+#include <Compositor/WindowServer.h>+#include <LibCore/Forward.h>+#include <LibGfx/Size.h>+#include <LibMediaCodecs/VideoFrame.h>++namespace Compositor {++class CoreAnimationWindowServer final : public WindowServer {+public:+ // None where the layer trees that another process shows by the ID of their context are not available.+ static RefPtr<CoreAnimationWindowServer> try_create();++ virtual OwnPtr<RemoteLayer> try_create_remote_layer(u64 remote_layer_id) override;+ virtual FrameHandOff frame_hand_off() const override { return FrameHandOff::OnceGpuWorkIsScheduled; }+ virtual void hold_changes_on_screen() override;+ virtual void release_changes_held_off_screen() override;++private:+ CoreAnimationWindowServer() = default;+};++// A CoreAnimation layer tree that this process commits frames into, and that another process shows in a view of its+// own by the ID of the tree's context.+class CoreAnimationRemoteLayer final : public RemoteLayer {+public:+ static OwnPtr<CoreAnimationRemoteLayer> try_create();+ virtual ~CoreAnimationRemoteLayer() override;++ virtual Compositing::RemoteLayerHostHandle host_handle() const override;+ virtual bool can_show(WindowServerPlacement const&, Content const&, double device_pixel_ratio) const override;+ virtual bool can_show_high_dynamic_range() const override { return true; }+ virtual void show_frame(Frame) override;+ virtual void place_frame(Optional<Gfx::IntSize> fit_within) override;++private:+ CoreAnimationRemoteLayer() = default;++ struct ShownSublayer {+ void* clip_layer { nullptr };+ void* rounded_clip_layer { nullptr };+ void* content_layer { nullptr };+ Variant<Empty, NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease> content;+ };++ void lay_out_frame(Optional<Gfx::IntSize> fit_within);+ void show_sublayers(Vector<RemoteSublayer>&);+ void use_content_layer_of_kind_for(ShownSublayer&, RemoteSublayer const&);+ void update_shown_sublayer(ShownSublayer&, RemoteSublayer&);+ void show_content(ShownSublayer&, RemoteSublayer&);+ void stop_showing_content(ShownSublayer&);+ void stop_showing_sublayer(ShownSublayer&);+ void keep_video_frame_until_window_server_lets_go(NonnullRefPtr<Media::VideoFrame>);+ void release_video_frames_window_server_let_go_of();++ void* m_context { nullptr };+ void* m_root_layer { nullptr };+ void* m_frame_layer { nullptr };+ void* m_content_layer { nullptr };+ Gfx::IntSize m_painted_size;+ double m_device_pixel_ratio { 1.0 };+ HashMap<u64, ShownSublayer> m_shown_sublayers;+ // A decoder decodes into the surface of a frame again once nothing holds the frame, so a replaced frame is held+ // until the window server can no longer be reading it. Its surface reads as in use for as long as the decoder's+ // pixel buffer lives, which is as long as the frame does, so that cannot tell.+ struct ReplacedVideoFrame {+ NonnullRefPtr<Media::VideoFrame> frame;+ MonotonicTime replaced_at;+ };+ Vector<ReplacedVideoFrame> m_replaced_video_frames;+ RefPtr<Core::Timer> m_video_frame_release_timer;+ u32 m_core_animation_context_id { 0 };+};++}diff --git a/Services/Compositor/RemoteLayer.mm b/Services/Compositor/CoreAnimationWindowServer.mmsimilarity index 91%rename from Services/Compositor/RemoteLayer.mmrename to Services/Compositor/CoreAnimationWindowServer.mmindex 94a5012f663..2262a3b8ff6 100644--- a/Services/Compositor/RemoteLayer.mm+++ b/Services/Compositor/CoreAnimationWindowServer.mm@@ -7,7 +7,7 @@#include <AK/HashTable.h>#include <AK/ScopeGuard.h>#include <AK/StdLibExtras.h>-#include <Compositor/RemoteLayer.h>+#include <Compositor/CoreAnimationWindowServer.h>#include <LibCompositing/FrameFitting.h>#include <LibCore/Timer.h>#include <LibGfx/SharedImageBuffer.h>@@ -77,13 +77,13 @@ static MonotonicTime s_changes_last_released_on_screen;// The transactions of each change nest in this one until it is committed, so none of them reaches the window server// before then.-void RemoteLayer::hold_changes_on_screen()+void CoreAnimationWindowServer::hold_changes_on_screen(){[CATransaction begin];s_changes_are_held_off_screen = true;}-void RemoteLayer::release_changes_held_off_screen()+void CoreAnimationWindowServer::release_changes_held_off_screen(){[CATransaction commit];[CATransaction flush];@@ -96,14 +96,26 @@ static CALayer* as_layer(void* layer)return static_cast<CALayer*>(layer);}-OwnPtr<RemoteLayer> RemoteLayer::try_create()+RefPtr<CoreAnimationWindowServer> CoreAnimationWindowServer::try_create()+{+ if (!main_window_server_connection_id_function() || !core_animation_context_class())+ return nullptr;+ return adopt_ref(*new CoreAnimationWindowServer);+}++OwnPtr<RemoteLayer> CoreAnimationWindowServer::try_create_remote_layer(u64)+{+ return CoreAnimationRemoteLayer::try_create();+}++OwnPtr<CoreAnimationRemoteLayer> CoreAnimationRemoteLayer::try_create(){auto* connection_id_function = main_window_server_connection_id_function();Class context_class = core_animation_context_class();if (!connection_id_function || !context_class)return nullptr;- auto remote_layer = adopt_own(*new RemoteLayer);+ auto remote_layer = adopt_own(*new CoreAnimationRemoteLayer);commit_layer_changes([&] {auto* root_layer = [[CALayer alloc] init];root_layer.anchorPoint = CGPointZero;@@ -133,7 +145,7 @@ OwnPtr<RemoteLayer> RemoteLayer::try_create()return remote_layer;}-RemoteLayer::~RemoteLayer()+CoreAnimationRemoteLayer::~CoreAnimationRemoteLayer(){commit_layer_changes([&] {for (auto& it : m_shown_sublayers)@@ -149,6 +161,23 @@ RemoteLayer::~RemoteLayer()m_video_frame_release_timer->stop();}+Compositing::RemoteLayerHostHandle CoreAnimationRemoteLayer::host_handle() const+{+ return { .kind = Compositing::RemoteLayerHostKind::CoreAnimationContext, .id = m_core_animation_context_id };+}++bool CoreAnimationRemoteLayer::can_show(WindowServerPlacement const&, Content const& content, double) const+{+ return content.visit(+ [](NonnullRefPtr<PresentableSurface> const& surface) {+ return surface->iosurface() != nullptr;+ },+ [](NonnullRefPtr<Media::VideoFrame> const& frame) {+ // A frame that a decoder left in memory has no surface that the window server could read.+ return frame->surface() != nullptr;+ });+}+static CGRect in_points(Gfx::FloatRect rect, double device_pixel_ratio){return CGRectMake(rect.x() / device_pixel_ratio, rect.y() / device_pixel_ratio, rect.width() / device_pixel_ratio, rect.height() / device_pixel_ratio);@@ -160,7 +189,7 @@ static CGRect in_points(Gfx::IntRect rect, double device_pixel_ratio)}// The root layer spans the view a frame is fitted into, as its y-axis is flipped within its own height.-void RemoteLayer::lay_out_frame(Optional<Gfx::IntSize> fit_within)+void CoreAnimationRemoteLayer::lay_out_frame(Optional<Gfx::IntSize> fit_within){Gfx::IntRect frame_rect { {}, m_painted_size };Gfx::IntRect root_rect { {}, fit_within.value_or(m_painted_size) };@@ -176,7 +205,7 @@ void RemoteLayer::lay_out_frame(Optional<Gfx::IntSize> fit_within)as_layer(m_content_layer).frame = in_points(frame_rect, m_device_pixel_ratio);}-void RemoteLayer::place_frame(Optional<Gfx::IntSize> fit_within)+void CoreAnimationRemoteLayer::place_frame(Optional<Gfx::IntSize> fit_within){if (m_painted_size.is_empty())return;@@ -195,8 +224,13 @@ static CGRect unit_rect_of_surface_part(CALayer* layer, Gfx::IntSize part_size,: CGRectMake(0, 1 - unit_height, unit_width, unit_height);}-void RemoteLayer::show_frame(Gfx::SharedImageBuffer const* buffer, Gfx::IntSize painted_size, double device_pixel_ratio, Optional<Gfx::IntSize> fit_within, Vector<RemoteSublayer> sublayers)+void CoreAnimationRemoteLayer::show_frame(Frame frame){+ auto const* buffer = frame.store;+ auto painted_size = frame.painted_size;+ auto device_pixel_ratio = frame.device_pixel_ratio;+ auto fit_within = frame.fit_within;+ auto& sublayers = frame.sublayers;Gfx::IntSize surface_size;if (buffer) {auto const& iosurface = buffer->iosurface_handle();@@ -225,7 +259,7 @@ void RemoteLayer::show_frame(Gfx::SharedImageBuffer const* buffer, Gfx::IntSizerelease_video_frames_window_server_let_go_of();}-void RemoteLayer::show_sublayers(Vector<RemoteSublayer>& sublayers)+void CoreAnimationRemoteLayer::show_sublayers(Vector<RemoteSublayer>& sublayers){HashTable<u64> shown_identities;auto* ordered_layers = [NSMutableArray arrayWithObject:as_layer(m_content_layer)];@@ -309,7 +343,7 @@ static void let_layer_show_high_dynamic_range(CALayer* layer, bool shows_high_dy}}-void RemoteLayer::use_content_layer_of_kind_for(ShownSublayer& shown_sublayer, RemoteSublayer const& sublayer)+void CoreAnimationRemoteLayer::use_content_layer_of_kind_for(ShownSublayer& shown_sublayer, RemoteSublayer const& sublayer){auto* content_layer = as_layer(shown_sublayer.content_layer);auto wants_sample_buffers = is_shown_through_sample_buffers(sublayer);@@ -337,7 +371,7 @@ void RemoteLayer::use_content_layer_of_kind_for(ShownSublayer& shown_sublayer, Rshown_sublayer.content_layer = replacement;}-void RemoteLayer::update_shown_sublayer(ShownSublayer& shown_sublayer, RemoteSublayer& sublayer)+void CoreAnimationRemoteLayer::update_shown_sublayer(ShownSublayer& shown_sublayer, RemoteSublayer& sublayer){auto device_pixel_ratio = m_device_pixel_ratio;auto* clip_layer = as_layer(shown_sublayer.clip_layer);@@ -512,7 +546,7 @@ static void enqueue_video_surface(AVSampleBufferDisplayLayer* layer, IOSurfaceRedbgln("AVFoundation failed to show a video surface: {}", renderer.error.description.UTF8String);}-void RemoteLayer::show_content(ShownSublayer& shown_sublayer, RemoteSublayer& sublayer)+void CoreAnimationRemoteLayer::show_content(ShownSublayer& shown_sublayer, RemoteSublayer& sublayer){auto* content_layer = as_layer(shown_sublayer.content_layer);sublayer.content.visit(@@ -556,7 +590,7 @@ void RemoteLayer::show_content(ShownSublayer& shown_sublayer, RemoteSublayer& su});}-void RemoteLayer::stop_showing_content(ShownSublayer& shown_sublayer)+void CoreAnimationRemoteLayer::stop_showing_content(ShownSublayer& shown_sublayer){if (auto const* shown_frame = shown_sublayer.content.get_pointer<NonnullRefPtr<Media::VideoFrame>>())keep_video_frame_until_window_server_lets_go(*shown_frame);@@ -565,7 +599,7 @@ void RemoteLayer::stop_showing_content(ShownSublayer& shown_sublayer)[sample_buffer_layer.sampleBufferRenderer flushWithRemovalOfDisplayedImage:YES completionHandler:nil];}-void RemoteLayer::stop_showing_sublayer(ShownSublayer& shown_sublayer)+void CoreAnimationRemoteLayer::stop_showing_sublayer(ShownSublayer& shown_sublayer){stop_showing_content(shown_sublayer);[as_layer(shown_sublayer.clip_layer) removeFromSuperlayer];@@ -575,7 +609,7 @@ void RemoteLayer::stop_showing_sublayer(ShownSublayer& shown_sublayer)[as_layer(shown_sublayer.clip_layer) release];}-void RemoteLayer::keep_video_frame_until_window_server_lets_go(NonnullRefPtr<Media::VideoFrame> frame)+void CoreAnimationRemoteLayer::keep_video_frame_until_window_server_lets_go(NonnullRefPtr<Media::VideoFrame> frame){m_replaced_video_frames.append({ move(frame), MonotonicTime::now() });if (!m_video_frame_release_timer) {@@ -591,7 +625,7 @@ void RemoteLayer::keep_video_frame_until_window_server_lets_go(NonnullRefPtr<Med// still be reading the frame replaced. A few refreshes later, even at 60 Hz, it has let go of it.static constexpr AK::Duration time_window_server_may_read_a_replaced_surface = AK::Duration::from_milliseconds(50);-void RemoteLayer::release_video_frames_window_server_let_go_of()+void CoreAnimationRemoteLayer::release_video_frames_window_server_let_go_of(){// A replacement made while changes are held off screen reaches the window server only once they are released.if (s_changes_are_held_off_screen)diff --git a/Services/Compositor/RemoteLayer.h b/Services/Compositor/RemoteLayer.hindex 31797a724d0..dc353bd9a76 100644--- a/Services/Compositor/RemoteLayer.h+++ b/Services/Compositor/RemoteLayer.h@@ -6,53 +6,23 @@#pragma once-#include <AK/HashMap.h>#include <AK/Noncopyable.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>-#include <AK/OwnPtr.h>-#include <AK/Platform.h>-#include <AK/Time.h>-#include <AK/Types.h>#include <AK/Variant.h>#include <AK/Vector.h>#include <AK/kmalloc.h>#include <Compositor/PresentableSurface.h>-#include <LibCore/Forward.h>-#include <LibGfx/AffineTransform.h>+#include <Compositor/RemoteSublayer.h>+#include <LibCompositing/Types.h>#include <LibGfx/Forward.h>-#include <LibGfx/Rect.h>-#include <LibGfx/ScalingMode.h>#include <LibGfx/Size.h>#include <LibMediaCodecs/VideoFrame.h>namespace Compositor {-// Content that the window server shows above the frame as it is, placed and clipped as drawing it into the frame would-// have placed and clipped it. Geometry is in device pixels.-struct RemoteSublayer {- struct RoundedClip {- Gfx::FloatRect rect;- float radius { 0 };- bool rounds_top_left { false };- bool rounds_top_right { false };- bool rounds_bottom_right { false };- bool rounds_bottom_left { false };- };-- // Tells a sublayer apart from the others from one frame to the next, so that a frame changes only what moved.- u64 identity { 0 };- Variant<NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease> content;- // Where the content is drawn, in its own space, which the transform maps into the frame.- Gfx::IntRect content_rect;- Gfx::AffineTransform content_to_frame;- Gfx::FloatRect clip_rect;- Optional<RoundedClip> rounded_clip;- Gfx::ScalingMode scaling_mode { Gfx::ScalingMode::Bilinear };-};--// A CoreAnimation layer tree that this process commits frames into, and that another process shows in a view of its-// own by the ID of the tree's context. Frames then reach the screen without passing through that process.+// A layer that this process commits frames into, and that the UI shows in a view of its own by the layer's host handle.+// Frames then reach the screen without passing through the UI.class RemoteLayer {AK_MAKE_NONCOPYABLE(RemoteLayer);AK_MAKE_NONMOVABLE(RemoteLayer);@@ -60,88 +30,30 @@ class RemoteLayer {public:AK_ALLOC_WITH_KMALLOC;- // None where the platform offers no such layer trees.- static OwnPtr<RemoteLayer> try_create();- ~RemoteLayer();+ virtual ~RemoteLayer() = default;++ virtual Compositing::RemoteLayerHostHandle host_handle() const = 0;- u32 core_animation_context_id() const { return m_core_animation_context_id; }+ using Content = Variant<NonnullRefPtr<Media::VideoFrame>, NonnullRefPtr<PresentableSurface>>;+ virtual bool can_show(WindowServerPlacement const&, Content const&, double device_pixel_ratio) const = 0;+ virtual bool can_show_high_dynamic_range() const { return false; }- // Shows the part of the buffer that the frame was painted into, at the top left of the layer at its own size, or+ struct Frame {+ // Without a store, the frame shown before stays, and only the sublayers change.+ Gfx::SharedImageBuffer const* store { nullptr };+ Gfx::IntSize painted_size;+ double device_pixel_ratio { 1.0 };+ Optional<Gfx::IntSize> fit_within;+ Vector<RemoteSublayer> sublayers;+ };+ // Shows the part of the store that the frame was painted into, at the top left of the layer at its own size, or// scaled to fit within the size of the view given, in device pixels, with the sublayers above it, bottom to top.- // Without a buffer, the frame shown before stays, and only the sublayers change.- void show_frame(Gfx::SharedImageBuffer const*, Gfx::IntSize painted_size, double device_pixel_ratio, Optional<Gfx::IntSize> fit_within, Vector<RemoteSublayer>);+ virtual void show_frame(Frame) = 0;// Places the frame on display again, as when the view that it is scaled into changes size.- void place_frame(Optional<Gfx::IntSize> fit_within);+ virtual void place_frame(Optional<Gfx::IntSize> fit_within) = 0;- // While held, what every remote layer of this process shows changes nowhere on screen, and changes all at once- // when released.- static void hold_changes_on_screen();- static void release_changes_held_off_screen();--private:+protected:RemoteLayer() = default;--#ifdef AK_OS_MACOS- struct ShownSublayer {- void* clip_layer { nullptr };- void* rounded_clip_layer { nullptr };- void* content_layer { nullptr };- Variant<Empty, NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease> content;- };-- void lay_out_frame(Optional<Gfx::IntSize> fit_within);- void show_sublayers(Vector<RemoteSublayer>&);- void use_content_layer_of_kind_for(ShownSublayer&, RemoteSublayer const&);- void update_shown_sublayer(ShownSublayer&, RemoteSublayer&);- void show_content(ShownSublayer&, RemoteSublayer&);- void stop_showing_content(ShownSublayer&);- void stop_showing_sublayer(ShownSublayer&);- void keep_video_frame_until_window_server_lets_go(NonnullRefPtr<Media::VideoFrame>);- void release_video_frames_window_server_let_go_of();-- void* m_context { nullptr };- void* m_root_layer { nullptr };- void* m_frame_layer { nullptr };- void* m_content_layer { nullptr };- Gfx::IntSize m_painted_size;- double m_device_pixel_ratio { 1.0 };- HashMap<u64, ShownSublayer> m_shown_sublayers;- // A decoder decodes into the surface of a frame again once nothing holds the frame, so a replaced frame is held- // until the window server can no longer be reading it. Its surface reads as in use for as long as the decoder's- // pixel buffer lives, which is as long as the frame does, so that cannot tell.- struct ReplacedVideoFrame {- NonnullRefPtr<Media::VideoFrame> frame;- MonotonicTime replaced_at;- };- Vector<ReplacedVideoFrame> m_replaced_video_frames;- RefPtr<Core::Timer> m_video_frame_release_timer;-#endif- u32 m_core_animation_context_id { 0 };};-#ifndef AK_OS_MACOS-inline OwnPtr<RemoteLayer> RemoteLayer::try_create()-{- return nullptr;-}--inline RemoteLayer::~RemoteLayer() = default;--inline void RemoteLayer::show_frame(Gfx::SharedImageBuffer const*, Gfx::IntSize, double, Optional<Gfx::IntSize>, Vector<RemoteSublayer>)-{-}--inline void RemoteLayer::place_frame(Optional<Gfx::IntSize>)-{-}--inline void RemoteLayer::hold_changes_on_screen()-{-}--inline void RemoteLayer::release_changes_held_off_screen()-{-}-#endif-}diff --git a/Services/Compositor/RemoteSublayer.h b/Services/Compositor/RemoteSublayer.hnew file mode 100644index 00000000000..ffd560f7a59--- /dev/null+++ b/Services/Compositor/RemoteSublayer.h@@ -0,0 +1,53 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/NonnullRefPtr.h>+#include <AK/Optional.h>+#include <AK/Types.h>+#include <AK/Variant.h>+#include <Compositor/PresentableSurface.h>+#include <LibGfx/AffineTransform.h>+#include <LibGfx/Rect.h>+#include <LibGfx/ScalingMode.h>+#include <LibMediaCodecs/VideoFrame.h>++namespace Compositor {++// Content that the window server shows above the frame as it is, placed and clipped as drawing it into the frame would+// have placed and clipped it. Geometry is in device pixels.+struct RemoteSublayer {+ struct RoundedClip {+ Gfx::FloatRect rect;+ float radius { 0 };+ bool rounds_top_left { false };+ bool rounds_top_right { false };+ bool rounds_bottom_right { false };+ bool rounds_bottom_left { false };+ };++ // Tells a sublayer apart from the others from one frame to the next, so that a frame changes only what moved.+ u64 identity { 0 };+ Variant<NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease> content;+ // Where the content is drawn, in its own space, which the transform maps into the frame.+ Gfx::IntRect content_rect;+ Gfx::AffineTransform content_to_frame;+ Gfx::FloatRect clip_rect;+ Optional<RoundedClip> rounded_clip;+ Gfx::ScalingMode scaling_mode { Gfx::ScalingMode::Bilinear };+};++// Where the window server can show the content of a media layer by itself, in viewport pixels.+struct WindowServerPlacement {+ Gfx::IntRect content_rect;+ Gfx::AffineTransform content_to_viewport;+ Gfx::FloatRect clip_rect;+ Optional<RemoteSublayer::RoundedClip> rounded_clip;+ Gfx::ScalingMode scaling_mode { Gfx::ScalingMode::Bilinear };+};++}diff --git a/Services/Compositor/WindowServer.cpp b/Services/Compositor/WindowServer.cppnew file mode 100644index 00000000000..5e6527901a1--- /dev/null+++ b/Services/Compositor/WindowServer.cpp@@ -0,0 +1,33 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <Compositor/WindowServer.h>++#ifdef AK_OS_MACOS+# include <Compositor/CoreAnimationWindowServer.h>+#endif++namespace Compositor {++RefPtr<WindowServer> WindowServer::try_create_for_presentation()+{+#ifdef AK_OS_MACOS+ return CoreAnimationWindowServer::try_create();+#else+ return nullptr;+#endif+}++WindowServer::FrameHandOff WindowServer::frame_hand_off_through_presentation()+{+#ifdef AK_OS_MACOS+ return FrameHandOff::OnceGpuWorkIsScheduled;+#else+ return FrameHandOff::OnceGpuWorkIsFinished;+#endif+}++}diff --git a/Services/Compositor/WindowServer.h b/Services/Compositor/WindowServer.hnew file mode 100644index 00000000000..78dd4efbbfd--- /dev/null+++ b/Services/Compositor/WindowServer.h@@ -0,0 +1,52 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Noncopyable.h>+#include <AK/OwnPtr.h>+#include <AK/RefCounted.h>+#include <AK/RefPtr.h>+#include <AK/Types.h>+#include <AK/Weakable.h>+#include <AK/kmalloc.h>+#include <Compositor/RemoteLayer.h>++namespace Compositor {++// The window server, as this process reaches it for the views of one presentation.+class WindowServer+ : public RefCounted<WindowServer>+ , public Weakable<WindowServer> {+ AK_MAKE_NONCOPYABLE(WindowServer);+ AK_MAKE_NONMOVABLE(WindowServer);++public:+ AK_ALLOC_WITH_KMALLOC;++ // None where frames reach the screen only through the presentation.+ static RefPtr<WindowServer> try_create_for_presentation();+ virtual ~WindowServer() = default;++ virtual OwnPtr<RemoteLayer> try_create_remote_layer(u64 remote_layer_id) = 0;++ enum class FrameHandOff : u8 {+ OnceGpuWorkIsScheduled,+ OnceGpuWorkIsFinished,+ };+ virtual FrameHandOff frame_hand_off() const = 0;+ static FrameHandOff frame_hand_off_through_presentation();++ // While held, what every remote layer of this window server shows changes nowhere on screen, and changes all at once+ // when released.+ virtual void hold_changes_on_screen() = 0;+ virtual void release_changes_held_off_screen() = 0;++protected:+ WindowServer() = default;+};++}