Truly independent web browser
Compositor+LibWebView: Show frames in remote CoreAnimation layers
Aliaksandr Kalenik2ba868066d7e
diff --git a/Libraries/LibWebView/CompositorPresentationClient.cpp b/Libraries/LibWebView/CompositorPresentationClient.cppindex 050cbf133f9..37c7dfe5d51 100644--- a/Libraries/LibWebView/CompositorPresentationClient.cpp+++ b/Libraries/LibWebView/CompositorPresentationClient.cpp@@ -70,6 +70,12 @@ static WebContentPage* page_for_compositor_context_id(Web::CompositorContextId creturn web_content_client->page(*page_id);}+void CompositorPresentationClient::did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio)+{+ if (auto* page = page_for_compositor_context_id(context_id))+ page->did_present_frame_in_remote_layer(content_rect, damage_rect, device_pixel_ratio);+}+void CompositorPresentationClient::did_add_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores){if (auto* page = page_for_compositor_context_id(context_id))diff --git a/Libraries/LibWebView/CompositorPresentationClient.h b/Libraries/LibWebView/CompositorPresentationClient.hindex cdb457def6f..7b4a94f9686 100644--- a/Libraries/LibWebView/CompositorPresentationClient.h+++ b/Libraries/LibWebView/CompositorPresentationClient.h@@ -35,6 +35,7 @@ private:virtual void did_add_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) override;virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) override;virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) override;+ virtual void did_present_frame_in_remote_layer(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) override;virtual void did_consume_input_event(Web::CompositorContextId, u64 event_id) override;virtual void did_not_dispatch_input_event(Web::CompositorContextId, u64 event_id) override;virtual void did_dispatch_input_event(Web::CompositorContextId, u64 event_id, bool performed_default_action) override;diff --git a/Libraries/LibWebView/PageBackingStores.cpp b/Libraries/LibWebView/PageBackingStores.cppindex 047dfa862ad..1195ab14fb8 100644--- a/Libraries/LibWebView/PageBackingStores.cpp+++ b/Libraries/LibWebView/PageBackingStores.cpp@@ -10,6 +10,8 @@ namespace WebView {Optional<PageBackingStores::Frame> PageBackingStores::displayed_frame() const{+ if (m_frame_shown_in_remote_layer.has_value())+ return Frame { nullptr, m_frame_shown_in_remote_layer->size, m_frame_shown_in_remote_layer->device_pixel_ratio, {} };if (m_has_usable_front_bitmap)return Frame { m_front_bitmap.shared_image_buffer.ptr(), m_front_bitmap.last_painted_size.to_type<int>(), m_front_bitmap.last_painted_device_pixel_ratio, m_front_bitmap.id };if (m_has_backup)@@ -34,6 +36,7 @@ Vector<Gfx::SharedImageBuffer const*> PageBackingStores::shared_image_buffers()void PageBackingStores::track_installed_backing_stores(ReadonlySpan<i32> bitmap_ids){VERIFY(!bitmap_ids.is_empty());+ m_frame_shown_in_remote_layer = {};// NOTE: We keep the outgoing front bitmap as a backup so we have something to paint until we get a new one.PageBackingStores::keep_front_as_backup();@@ -91,6 +94,12 @@ PageBackingStores::PresentationResult PageBackingStores::present(i32 bitmap_id,return { .did_swap = true, .bitmap_id_to_release = previous_front_bitmap_id };}+void PageBackingStores::present_frame_shown_in_remote_layer(Gfx::IntSize size, double device_pixel_ratio)+{+ m_frame_shown_in_remote_layer = FrameShownInRemoteLayer { size, device_pixel_ratio };+ PageBackingStores::clear_backup();+}+void PageBackingStores::keep_front_as_backup(){if (!m_has_usable_front_bitmap)diff --git a/Libraries/LibWebView/PageBackingStores.h b/Libraries/LibWebView/PageBackingStores.hindex eaa77f427f5..e1521c07311 100644--- a/Libraries/LibWebView/PageBackingStores.h+++ b/Libraries/LibWebView/PageBackingStores.h@@ -55,6 +55,9 @@ public:// Makes the backing store with this ID the front backing store, unless it is no longer one of ours.virtual PresentationResult present(i32 bitmap_id, Gfx::IntSize, double device_pixel_ratio);+ // Records a frame that the Compositor shows itself, in a remote layer, rather than in one of these backing stores.+ void present_frame_shown_in_remote_layer(Gfx::IntSize, double device_pixel_ratio);+// Keeps the frame on display, so there is something to show until a new frame arrives.virtual void keep_front_as_backup();virtual void clear_backup();@@ -80,6 +83,12 @@ private:bool m_has_usable_front_bitmap { false };SharedBitmap m_backup;bool m_has_backup { false };++ struct FrameShownInRemoteLayer {+ Gfx::IntSize size;+ double device_pixel_ratio { 1.0 };+ };+ Optional<FrameShownInRemoteLayer> m_frame_shown_in_remote_layer;};}diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 34d4118f2ec..ff37b1d48b7 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -442,6 +442,14 @@ void ViewImplementation::server_did_paint(Badge<WebContentPage>, i32 bitmap_id,on_ready_to_paint();}+void ViewImplementation::server_did_present_frame_in_remote_layer(Badge<WebContentPage>, Gfx::IntSize size, Gfx::IntRect, double device_pixel_ratio)+{+ m_backing_stores->present_frame_shown_in_remote_layer(size, device_pixel_ratio);+ if (m_crash_state.has_value() && m_crash_state->recovery_started)+ set_crash_state({});+ TabPerformanceMonitor::did_present(view_id());+}+void ViewImplementation::release_backing_store(i32 bitmap_id){page().release_presented_bitmap(bitmap_id);diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex 900d4d354b7..67856a0bdf3 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -224,6 +224,8 @@ public:String const& handle() const { return m_window_handle; }void server_did_paint(Badge<WebContentPage>, i32 bitmap_id, Gfx::IntSize size, Gfx::IntRect damage_rect, double device_pixel_ratio);+ // The Compositor showed the frame itself, in the remote layer of this view.+ void server_did_present_frame_in_remote_layer(Badge<WebContentPage>, Gfx::IntSize size, Gfx::IntRect damage_rect, double device_pixel_ratio);void set_window_position(Gfx::IntPoint);void set_window_size(Gfx::IntSize);diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex ee2918dc055..880c98b9c8d 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -585,6 +585,12 @@ void WebContentPage::did_present_bitmap(Gfx::IntRect content_rect, Gfx::IntRectrelease_presented_bitmap(bitmap_id);}+void WebContentPage::did_present_frame_in_remote_layer(Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio)+{+ if (displays_tab())+ view().server_did_present_frame_in_remote_layer({}, content_rect.size(), damage_rect, device_pixel_ratio);+}+void WebContentPage::did_present_backing_stores(Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores){dbgln_if(COMPOSITOR_DEBUG, "[Compositor] UI received {} backing stores for page {}", backing_stores.size(), m_id);diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 188406081c9..2ad4f4dbaaf 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -169,6 +169,7 @@ public:void did_not_dispatch_input_event_through_compositor(u64 event_id);void did_dispatch_input_event_through_compositor(u64 event_id, bool performed_default_action);void did_present_bitmap(Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio);+ void did_present_frame_in_remote_layer(Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio);void did_present_backing_stores(Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores);void did_add_backing_stores(Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores);void did_retire_backing_stores(ReadonlySpan<i32> bitmap_ids);diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cppindex 337d4814dc5..69232c94e30 100644--- a/Services/Compositor/BackingStoreManager.cpp+++ b/Services/Compositor/BackingStoreManager.cpp@@ -116,13 +116,13 @@ static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize siz}#endif-// A published store is released by the UI when it presents the next one, but on macOS the UI hands the-// surface itself to the window server, which keeps reading it until it has composited the replacement.-// A third store lets the compositor keep rendering through that window instead of waiting for it.+// A store shown on screen is let go of when the next one is shown, but on macOS the window server is handed the+// surface itself, and keeps reading it until it has composited the replacement. A third store lets the compositor keep+// rendering through that window instead of waiting for it.static size_t backing_store_count_for([[maybe_unused]] BackingStoreManager::PublicationMode publication_mode){#ifdef AK_OS_MACOS- if (publication_mode == BackingStoreManager::PublicationMode::Published)+ if (publication_mode != BackingStoreManager::PublicationMode::Unpublished)return 3;#endifreturn 2;@@ -178,7 +178,7 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::allocate_backingfor (size_t i = 0; i < buffer_count; ++i) {m_backing_stores.append({.surface = Gfx::PaintingSurface::create_with_size(allocation.size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context),- .published_shared_image_buffer = nullptr,+ .shared_image_buffer = nullptr,.bitmap_id = allocation.bitmap_ids[i],.state = BufferState::Available,.accumulated_damage = { {}, allocation.size },@@ -187,6 +187,12 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::allocate_backingreturn {};}+ if (publication_mode == PublicationMode::ShownInRemoteLayer) {+ for (size_t i = 0; i < buffer_count; ++i)+ m_backing_stores.append(create_shareable_backing_store(allocation.size, allocation.bitmap_ids[i], BufferState::Available, skia_backend_context));+ return Publication { .bitmap_ids = allocation.bitmap_ids, .shared_images = {} };+ }+// The UI installs the first published buffer as its initial front buffer.// Reserve it until the UI releases it after presenting another buffer.auto initial_buffer_state = [](size_t index) {@@ -213,7 +219,7 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::allocate_backingauto store = backing_store.release_value();m_backing_stores.append({.surface = move(store.surface),- .published_shared_image_buffer = nullptr,+ .shared_image_buffer = nullptr,.bitmap_id = allocation.bitmap_ids[i],.state = initial_buffer_state(i),.accumulated_damage = { {}, allocation.size },@@ -235,8 +241,8 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::allocate_backingVector<Gfx::SharedImage> shared_images;shared_images.ensure_capacity(buffer_count);for (size_t i = 0; i < buffer_count; ++i) {- m_backing_stores.append(create_published_shareable_backing_store(allocation.size, allocation.bitmap_ids[i], initial_buffer_state(i), skia_backend_context));- shared_images.append(m_backing_stores.last().published_shared_image_buffer->export_shared_image());+ m_backing_stores.append(create_shareable_backing_store(allocation.size, allocation.bitmap_ids[i], initial_buffer_state(i), skia_backend_context));+ shared_images.append(m_backing_stores.last().shared_image_buffer->export_shared_image());}return Publication {@@ -245,13 +251,13 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::allocate_backing};}-BackingStoreManager::BackingStore BackingStoreManager::create_published_shareable_backing_store(Gfx::IntSize size, i32 bitmap_id, BufferState state, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)+BackingStoreManager::BackingStore BackingStoreManager::create_shareable_backing_store(Gfx::IntSize size, i32 bitmap_id, BufferState state, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context){auto shared_image_buffer = make<Gfx::SharedImageBuffer>(Gfx::SharedImageBuffer::create(size));auto surface = create_shareable_bitmap_backing_store(size, *shared_image_buffer, skia_backend_context);return {.surface = move(surface),- .published_shared_image_buffer = move(shared_image_buffer),+ .shared_image_buffer = move(shared_image_buffer),.bitmap_id = bitmap_id,.state = state,.accumulated_damage = { {}, size },@@ -271,7 +277,7 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::add_backing_storfor (size_t i = 0; i < m_backing_stores.size(); ++i) {auto const& store = m_backing_stores[i];- if (!store.published_shared_image_buffer)+ if (!store.shared_image_buffer)return {};bool client_displays_store = i == *m_latest_rendered_store_index;if (client_displays_store && store.state != BufferState::Presented)@@ -281,10 +287,11 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::add_backing_stor}auto bitmap_id = m_next_bitmap_id++;- m_backing_stores.append(create_published_shareable_backing_store(m_backing_store_size, bitmap_id, BufferState::Available, skia_backend_context));+ m_backing_stores.append(create_shareable_backing_store(m_backing_store_size, bitmap_id, BufferState::Available, skia_backend_context));Vector<Gfx::SharedImage> shared_images;- shared_images.append(m_backing_stores.last().published_shared_image_buffer->export_shared_image());+ if (m_publication_mode == PublicationMode::Published)+ shared_images.append(m_backing_stores.last().shared_image_buffer->export_shared_image());return Publication {.bitmap_ids = { bitmap_id },.shared_images = move(shared_images),@@ -303,7 +310,7 @@ Vector<i32> BackingStoreManager::retire_idle_surplus_backing_stores()auto const& store = m_backing_stores[i];if (m_latest_rendered_store_index == i)continue;- if (store.state != BufferState::Available || store.was_rendered_into_since_last_retirement_check || published_surface_is_in_use(store))+ if (store.state != BufferState::Available || store.was_rendered_into_since_last_retirement_check || shared_surface_is_in_use(store))continue;retired_bitmap_ids.append(store.bitmap_id);@@ -322,12 +329,12 @@ bool BackingStoreManager::is_valid() constreturn !m_backing_stores.is_empty();}-bool BackingStoreManager::published_surface_is_in_use(BackingStore const& store)+bool BackingStoreManager::shared_surface_is_in_use(BackingStore const& store){#ifdef AK_OS_MACOS// The send right exported to the UI counts as use as well, so a freshly published store reads as in use until// the UI has imported it.- return store.published_shared_image_buffer && store.published_shared_image_buffer->iosurface_handle().is_in_use();+ return store.shared_image_buffer && store.shared_image_buffer->iosurface_handle().is_in_use();#else(void)store;return false;@@ -338,11 +345,11 @@ bool BackingStoreManager::store_can_be_rendered_into(BackingStore const& store){if (store.state != BufferState::Available)return false;- // Only the client hands a store to the window server, so whatever uses a store the client was never presented- // is the send right still on its way there.- if (!store.was_presented_to_client)+ // Only a store shown on screen is handed to the window server, so whatever uses a store that never was is the+ // send right on its way to the client.+ if (!store.was_shown_on_screen)return true;- return !published_surface_is_in_use(store);+ return !shared_surface_is_in_use(store);}bool BackingStoreManager::has_available_buffer() const@@ -383,8 +390,8 @@ void BackingStoreManager::complete_rendering(i32 bitmap_id)m_backing_stores[*m_latest_rendered_store_index].state = BufferState::Available;store.state = BufferState::Presented;- if (client_releases_presented_stores)- store.was_presented_to_client = true;+ if (m_publication_mode != PublicationMode::Unpublished)+ store.was_shown_on_screen = true;m_latest_rendered_store_index = m_rendering_store_index;m_rendering_store_index.clear();}@@ -415,4 +422,11 @@ RefPtr<Gfx::PaintingSurface> BackingStoreManager::latest_rendered_surface() consreturn m_backing_stores[*m_latest_rendered_store_index].surface;}+Gfx::SharedImageBuffer const* BackingStoreManager::shared_image_buffer_of_latest_rendered_store() const+{+ if (!m_latest_rendered_store_index.has_value())+ return nullptr;+ return m_backing_stores[*m_latest_rendered_store_index].shared_image_buffer.ptr();+}+}diff --git a/Services/Compositor/BackingStoreManager.h b/Services/Compositor/BackingStoreManager.hindex b8441af9dda..473d4299061 100644--- a/Services/Compositor/BackingStoreManager.h+++ b/Services/Compositor/BackingStoreManager.h@@ -30,6 +30,7 @@ public:Gfx::IntSize size;Vector<i32> bitmap_ids;};+ // The stores that were allocated or added, with the images the presentation imports, if it shows the stores.struct Publication {Vector<i32> bitmap_ids;Vector<Gfx::SharedImage> shared_images;@@ -42,7 +43,10 @@ public:enum class PublicationMode {Unpublished,+ // The presentation shows the stores, and releases each when it shows another.Published,+ // The compositor shows the stores itself, in a remote layer, so a store is replaced on screen by the next one.+ ShownInRemoteLayer,};enum class GpuSharing {@@ -70,6 +74,8 @@ public:bool release_buffer(i32 bitmap_id);void release_all_presented_buffers();RefPtr<Gfx::PaintingSurface> latest_rendered_surface() const;+ Gfx::SharedImageBuffer const* shared_image_buffer_of_latest_rendered_store() const;+ PublicationMode publication_mode() const { return m_publication_mode; }Optional<Publication> add_backing_store_if_window_server_still_reads_every_released_store(RefPtr<Gfx::SkiaBackendContext> const&);bool has_surplus_backing_stores() const { return m_backing_stores.size() > m_initial_backing_store_count; }@@ -84,18 +90,18 @@ private:struct BackingStore {RefPtr<Gfx::PaintingSurface> surface;- OwnPtr<Gfx::SharedImageBuffer> published_shared_image_buffer;+ OwnPtr<Gfx::SharedImageBuffer> shared_image_buffer;i32 bitmap_id { -1 };BufferState state { BufferState::Available };Gfx::IntRect accumulated_damage;- bool was_presented_to_client { false };+ bool was_shown_on_screen { false };bool was_rendered_into_since_last_retirement_check { false };};static constexpr size_t maximum_backing_store_count = 8;- static BackingStore create_published_shareable_backing_store(Gfx::IntSize, i32 bitmap_id, BufferState, RefPtr<Gfx::SkiaBackendContext> const&);- static bool published_surface_is_in_use(BackingStore const&);+ static BackingStore create_shareable_backing_store(Gfx::IntSize, i32 bitmap_id, BufferState, RefPtr<Gfx::SkiaBackendContext> const&);+ static bool shared_surface_is_in_use(BackingStore const&);static bool store_can_be_rendered_into(BackingStore const&);int m_next_bitmap_id { 0 };diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex fb7251dbb77..fa2fe082a01 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -99,8 +99,8 @@ if (USE_VULKAN_DMABUF_IMAGES)endif()if (APPLE)- target_sources(compositorservice PRIVATE VideoFrameSkia.mm)- target_link_libraries(compositorservice PUBLIC "-framework CoreGraphics" "-framework CoreVideo")+ target_sources(compositorservice PRIVATE RemoteLayer.mm VideoFrameSkia.mm)+ target_link_libraries(compositorservice PUBLIC "-framework CoreGraphics" "-framework CoreVideo" "-framework QuartzCore")endif()if (WIN32)diff --git a/Services/Compositor/CompositorControlServer.ipc b/Services/Compositor/CompositorControlServer.ipcindex d63239c72cb..920a2893ee5 100644--- a/Services/Compositor/CompositorControlServer.ipc+++ b/Services/Compositor/CompositorControlServer.ipc@@ -15,6 +15,10 @@ endpoint CompositorControlServerconnect_video_presentation(i32 web_content_connection_id, IPC::TransportHandle handle) =|create_presentation_connection(bool synthesizes_scroll_momentum, bool scrolls_elastically, Optional<u64> gpu_presentation_adapter_luid) => (IPC::TransportHandle handle, u64 presentation_id)bind_presentation(Web::CompositorContextId context_id, u64 presentation_id) => ()+ // The ID of the layer's CoreAnimation context is 0 where the platform has no remote layers.+ create_remote_layer(u64 presentation_id, u64 remote_layer_id) => (u32 core_animation_context_id)+ destroy_remote_layer(u64 remote_layer_id) =|+ show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId> context_id) =|create_context(Web::CompositorContextId context_id, Optional<u64> page_id, i32 web_content_connection_id) => ()diff --git a/Services/Compositor/CompositorPresentationClient.ipc b/Services/Compositor/CompositorPresentationClient.ipcindex 6aaa62ea045..a145595c8b8 100644--- a/Services/Compositor/CompositorPresentationClient.ipc+++ b/Services/Compositor/CompositorPresentationClient.ipc@@ -8,6 +8,7 @@ endpoint CompositorPresentationClientdid_add_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) =|did_retire_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids) =|did_present_frame(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) =|+ did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) =|[RustSender] did_consume_input_event(Web::CompositorContextId context_id, u64 event_id) =|[RustSender] did_not_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id) =|[RustSender] did_dispatch_input_event(Web::CompositorContextId context_id, u64 event_id, bool performed_default_action) =|diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex c0c63ae802e..31b6300b0d3 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -132,6 +132,14 @@ PresentationId CompositorState::register_presentation(CompositorStateClient& prevoid CompositorState::unregister_presentation(CompositorStateClient& presentation){+ Vector<u64> remote_layer_ids;+ for (auto const& [remote_layer_id, remote_layer] : m_remote_layers) {+ if (remote_layer.presentation == &presentation)+ remote_layer_ids.append(remote_layer_id);+ }+ for (auto remote_layer_id : remote_layer_ids)+ destroy_remote_layer(remote_layer_id);+Vector<Web::CompositorContextId> bound_context_ids;for (auto const& [context_id, bound_presentation] : m_context_presentations) {if (bound_presentation == &presentation)@@ -185,6 +193,82 @@ void CompositorState::unbind_presentation(Web::CompositorContextId context_id)schedule_pending_present_frame_if_unblocked(context_id, *context);}+u32 CompositorState::create_remote_layer(CompositorStateClient& presentation, u64 remote_layer_id)+{+ VERIFY(m_presentations.contains(&presentation));+ if (auto existing = m_remote_layers.find(remote_layer_id); existing != m_remote_layers.end()) {+ dbgln("Compositor: Ignoring creation of remote layer {}, which already exists", remote_layer_id);+ return 0;+ }+ auto layer = RemoteLayer::try_create();+ 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 = {} });+ return core_animation_context_id;+}++void CompositorState::destroy_remote_layer(u64 remote_layer_id)+{+ show_context_in_remote_layer(remote_layer_id, {});+ m_remote_layers.remove(remote_layer_id);+}++void CompositorState::show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId> context_id)+{+ auto remote_layer = m_remote_layers.find(remote_layer_id);+ if (remote_layer == m_remote_layers.end())+ return;+ if (remote_layer->value.shown_context_id == context_id)+ return;++ if (auto shown_context_id = exchange(remote_layer->value.shown_context_id, {}); shown_context_id.has_value()) {+ if (auto* shown_context = presented_context_if_present(*shown_context_id))+ stop_showing_context_in_remote_layer(*shown_context_id, *shown_context);+ }+ if (!context_id.has_value())+ return;++ auto* context = presented_context_if_present(*context_id);+ if (!context || !context->presenter.presents_to_client()) {+ dbgln("Compositor: Ignoring context {} for remote layer {}, as it is not a root context", *context_id, remote_layer_id);+ return;+ }+ if (context->remote_layer_id.has_value()) {+ if (auto other_remote_layer = m_remote_layers.find(*context->remote_layer_id); other_remote_layer != m_remote_layers.end())+ other_remote_layer->value.shown_context_id = {};+ }++ remote_layer->value.shown_context_id = context_id;+ context->remote_layer_id = remote_layer_id;+ stop_delivering_in_flight_frames_to_their_viewer(*context_id);+ // The presentation no longer shows the stores it was given, so none of them is waiting to be released by it.+ context->presenter.acknowledge_all_presented_bitmaps();+ context->presenter.invalidate_backing_stores();+ resize_backing_stores_if_needed(*context_id, *context);+ schedule_pending_present_frame_if_unblocked(*context_id, *context);+}++void CompositorState::stop_showing_context_in_remote_layer(Web::CompositorContextId context_id, PresentedContext& context)+{+ context.remote_layer_id = {};+ stop_delivering_in_flight_frames_to_their_viewer(context_id);+ context.presenter.invalidate_backing_stores();+ resize_backing_stores_if_needed(context_id, context);+ schedule_pending_present_frame_if_unblocked(context_id, context);+}++// The frames were drawn into stores of the way the context was shown before, so they are released without being shown.+void CompositorState::stop_delivering_in_flight_frames_to_their_viewer(Web::CompositorContextId context_id)+{+ for (auto& pending_present : m_pending_async_presents) {+ if (pending_present.context_id != context_id)+ continue;+ pending_present.publish_to_presentation = false;+ pending_present.shows_in_remote_layer = false;+ }+}+CompositorStateClient* CompositorState::presentation_for_context(Web::CompositorContextId context_id) const{return m_context_presentations.get(context_id).value_or(nullptr);@@ -305,6 +389,11 @@ void CompositorState::destroy_context(Web::CompositorContextId context_id)possible_child_context.parent_context_id = {};}m_context_presentations.remove(context_id);+ if (context->remote_layer_id.has_value()) {+ // The layer keeps the context's last frame until another context is shown in it.+ if (auto remote_layer = m_remote_layers.find(*context->remote_layer_id); remote_layer != m_remote_layers.end())+ remote_layer->value.shown_context_id = {};+ }if (auto timers = m_context_timers.find(context_id); timers != m_context_timers.end()) {for (auto& [_, timer] : timers->value) {timer->on_timeout = {};@@ -1037,7 +1126,8 @@ void CompositorState::present_frame(Web::CompositorContextId context_id, Presentm_pending_async_presents.append(context_id, pending_frame.viewport_rect, prepared_frame->damage_rect, prepared_frame->bitmap_id, prepared_frame->device_pixel_ratio);auto* pending_present = &m_pending_async_presents.last();- pending_present->publish_to_presentation = presentation_for_context(context_id) != nullptr;+ pending_present->shows_in_remote_layer = context.presenter.backing_store_publication_mode() == BackingStoreManager::PublicationMode::ShownInRemoteLayer;+ pending_present->publish_to_presentation = !pending_present->shows_in_remote_layer && presentation_for_context(context_id) != nullptr;auto& event_loop = Core::EventLoop::current();auto self = NonnullRefPtr { *this };@@ -1297,6 +1387,33 @@ void CompositorState::did_finish_async_present(PendingAsyncPresent& pending_presdeliver_rendered_frame(finished_present);}+static void log_presented_frame(Optional<u64> page_id, Gfx::IntRect damage)+{+ auto* log = Core::StatsLog::the();+ if (!log || !page_id.has_value())+ return;+ JsonObject data;+ data.set("page_id"sv, *page_id);+ data.set("changed"sv, !damage.is_empty());+ data.set("damage_x"sv, damage.x());+ data.set("damage_y"sv, damage.y());+ data.set("damage_width"sv, damage.width());+ data.set("damage_height"sv, damage.height());+ log->event("frame"sv, move(data));+}++void CompositorState::show_frame_in_remote_layer(Web::CompositorContextId context_id, PresentedContext& context, PendingAsyncPresent const& pending_present)+{+ VERIFY(context.remote_layer_id.has_value());+ auto remote_layer = m_remote_layers.find(*context.remote_layer_id);+ VERIFY(remote_layer != m_remote_layers.end());+ auto const* shared_image_buffer = context.presenter.shared_image_buffer_of_latest_rendered_store();+ VERIFY(shared_image_buffer);++ remote_layer->value.layer->show_frame(*shared_image_buffer, pending_present.viewport_rect.size(), pending_present.device_pixel_ratio);+ 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);+}+void CompositorState::deliver_rendered_frame(PendingAsyncPresent& pending_present){if (pending_present.was_cancelled || exchange(pending_present.was_delivered, true))@@ -1308,23 +1425,16 @@ void CompositorState::deliver_rendered_frame(PendingAsyncPresent& pending_presencontext->presenter.did_finish_gpu_present(pending_present.bitmap_id);auto* presentation = pending_present.publish_to_presentation ? presentation_for_context(context_id) : nullptr;- if (context->presenter.presents_to_client() && !presentation) {+ if (pending_present.shows_in_remote_layer) {+ log_presented_frame(context->page_id, pending_present.damage_rect);+ show_frame_in_remote_layer(context_id, *context, pending_present);+ } else if (context->presenter.presents_to_client() && !presentation) {// Nobody shows the frame, so it is released here, on another turn, as a presentation would release it.Core::deferred_invoke([self = NonnullRefPtr { *this }, context_id, bitmap_id = pending_present.bitmap_id] {self->presented_bitmap_ready_to_paint(context_id, bitmap_id);});} else if (context->presenter.presents_to_client()) {- if (auto* log = Core::StatsLog::the(); log && context->page_id.has_value()) {- auto const& damage = pending_present.damage_rect;- JsonObject data;- data.set("page_id"sv, *context->page_id);- data.set("changed"sv, !damage.is_empty());- data.set("damage_x"sv, damage.x());- data.set("damage_y"sv, damage.y());- data.set("damage_width"sv, damage.width());- data.set("damage_height"sv, damage.height());- log->event("frame"sv, move(data));- }+ log_presented_frame(context->page_id, pending_present.damage_rect);presentation->did_present_frame(context_id, pending_present.viewport_rect, pending_present.damage_rect, pending_present.bitmap_id, pending_present.device_pixel_ratio);}resize_backing_stores_if_needed(context_id, *context);@@ -1437,9 +1547,15 @@ CompositedContextSurface CompositorState::resolve_composited_context(Web::Composvoid CompositorState::resize_backing_stores_if_needed(Web::CompositorContextId context_id, PresentedContext& context){- auto publication_mode = presentation_for_context(context_id) ? BackingStoreManager::PublicationMode::Published : BackingStoreManager::PublicationMode::Unpublished;+ auto publication_mode = BackingStoreManager::PublicationMode::Unpublished;+ if (context.remote_layer_id.has_value())+ publication_mode = BackingStoreManager::PublicationMode::ShownInRemoteLayer;+ else if (presentation_for_context(context_id))+ publication_mode = BackingStoreManager::PublicationMode::Published;+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()) {- publish_backing_stores(context_id, context, publication.release_value());+ if (publication_mode == BackingStoreManager::PublicationMode::Published)+ publish_backing_stores(context_id, context, publication.release_value());present_current_frame(context_id, context);}}@@ -1524,14 +1640,15 @@ void CompositorState::shrink_backing_stores_after_resize(Web::CompositorContextIvoid CompositorState::add_backing_store_for_pending_frame_if_needed(Web::CompositorContextId context_id, PresentedContext& context){auto* presentation = presentation_for_context(context_id);- if (!presentation)+ if (!presentation && !context.remote_layer_id.has_value())return;auto publication = context.presenter.add_backing_store_for_pending_frame_if_needed(m_skia_backend_context);if (!publication.has_value())return;dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} gained backing store {}, as the window server still reads every released one", context_id, publication->bitmap_ids);- presentation->did_add_backing_stores(context_id, move(publication->bitmap_ids), move(publication->shared_images));+ if (presentation && context.presenter.backing_store_publication_mode() == BackingStoreManager::PublicationMode::Published)+ presentation->did_add_backing_stores(context_id, move(publication->bitmap_ids), move(publication->shared_images));schedule_surplus_backing_store_retirement(context_id, context);}@@ -1549,7 +1666,8 @@ void CompositorState::retire_idle_surplus_backing_stores(Web::CompositorContextIreturn;auto retired_bitmap_ids = context->presenter.retire_idle_surplus_backing_stores();- if (auto* presentation = presentation_for_context(context_id); presentation && !retired_bitmap_ids.is_empty()) {+ auto shows_stores_to_presentation = context->presenter.backing_store_publication_mode() == BackingStoreManager::PublicationMode::Published;+ if (auto* presentation = presentation_for_context(context_id); presentation && shows_stores_to_presentation && !retired_bitmap_ids.is_empty()) {dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} retired idle backing stores {}", context_id, retired_bitmap_ids);presentation->did_retire_backing_stores(context_id, move(retired_bitmap_ids));}diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 9f0a02e299d..c771f34db9e 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -19,6 +19,7 @@#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 <LibCompositing/DisplayList/AccumulatedVisualContext.h>@@ -50,6 +51,8 @@ public:virtual void did_add_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage>&& backing_stores) = 0;virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) = 0;virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) = 0;+ // The frame is on screen already, in the remote layer that shows the context.+ virtual void did_present_frame_in_remote_layer(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) = 0;};class CompositorStateWebContentClient {@@ -153,6 +156,13 @@ public:void set_client_gpu_presentation_capability(CompositorStateClient&, bool supported, u64 adapter_luid);void set_scrollbar_track_press_jumps(CompositorStateClient&, bool jumps);+ // A remote layer shows the frames of one root context at a time, in a view of the presentation it was created+ // for. Answers the ID of its CoreAnimation context, or 0 where the platform has no remote layers.+ u32 create_remote_layer(CompositorStateClient&, u64 remote_layer_id);+ void destroy_remote_layer(u64 remote_layer_id);+ // The layer keeps the frame it shows until the context it is given next presents one.+ void show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId>);+struct PlaceholderCanvasAllocation {Compositing::CanvasId canvas_id;u64 secret { 0 };@@ -197,6 +207,7 @@ private:double display_refresh_rate { 60.0 };// Whether the presentation shows this context's frames from CPU memory for now, as when the UI paints it itself.bool presents_from_cpu_memory { false };+ Optional<u64> remote_layer_id;PacedTickRequest rendering_opportunity_request;PacedTickRequest clock_tick_request;};@@ -220,6 +231,7 @@ private:bool was_delivered { false };// A frame that started rendering before its context was bound has no published buffer to present to.bool publish_to_presentation { true };+ bool shows_in_remote_layer { false };};public:@@ -274,6 +286,9 @@ private:void publish_backing_stores(Web::CompositorContextId, PresentedContext&, BackingStoreManager::Publication&&);BackingStoreManager::GpuSharing gpu_sharing_for_context(Web::CompositorContextId) const;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);+ void show_frame_in_remote_layer(Web::CompositorContextId, PresentedContext&, PendingAsyncPresent const&);void update_scroll_capabilities();void did_finish_async_present(PendingAsyncPresent&);void deliver_rendered_frame(PendingAsyncPresent&);@@ -298,6 +313,13 @@ private:HashMap<PresentationId, CompositorStateClient*> m_presentations_by_id;HashMap<Web::CompositorContextId, CompositorStateClient*> m_context_presentations;+ struct RemoteLayerState {+ CompositorStateClient* presentation { nullptr };+ OwnPtr<RemoteLayer> layer;+ Optional<Web::CompositorContextId> shown_context_id;+ };+ HashMap<u64, RemoteLayerState> m_remote_layers;+struct VideoSinkState {RefPtr<Media::DisplayingVideoSink> sink;bool should_tick { true };diff --git a/Services/Compositor/ConnectionFromClient.cpp b/Services/Compositor/ConnectionFromClient.cppindex e499f3cd4d6..e6c555e513e 100644--- a/Services/Compositor/ConnectionFromClient.cpp+++ b/Services/Compositor/ConnectionFromClient.cpp@@ -90,6 +90,26 @@ void ConnectionFromClient::bind_presentation(Web::CompositorContextId context_idm_compositor_state->bind_presentation(context_id, **connection);}+Messages::CompositorControlServer::CreateRemoteLayerResponse ConnectionFromClient::create_remote_layer(u64 presentation_id, u64 remote_layer_id)+{+ auto connection = m_presentation_connections.get(presentation_id);+ if (!connection.has_value()) {+ dbgln("Compositor: Ignoring remote layer {} for presentation {}, which is already gone", remote_layer_id, presentation_id);+ return 0u;+ }+ return m_compositor_state->create_remote_layer(**connection, remote_layer_id);+}++void ConnectionFromClient::destroy_remote_layer(u64 remote_layer_id)+{+ m_compositor_state->destroy_remote_layer(remote_layer_id);+}++void ConnectionFromClient::show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId> context_id)+{+ m_compositor_state->show_context_in_remote_layer(remote_layer_id, context_id);+}+void ConnectionFromClient::create_context(Web::CompositorContextId context_id, Optional<u64> page_id, i32 web_content_connection_id){auto* connection = web_content_connection(web_content_connection_id);diff --git a/Services/Compositor/ConnectionFromClient.h b/Services/Compositor/ConnectionFromClient.hindex 1516166ef40..b911b10d218 100644--- a/Services/Compositor/ConnectionFromClient.h+++ b/Services/Compositor/ConnectionFromClient.h@@ -35,6 +35,9 @@ private:virtual void connect_video_presentation(i32 web_content_connection_id, IPC::TransportHandle) override;virtual Messages::CompositorControlServer::CreatePresentationConnectionResponse create_presentation_connection(bool synthesizes_scroll_momentum, bool scrolls_elastically, Optional<u64> gpu_presentation_adapter_luid) override;virtual void bind_presentation(Web::CompositorContextId, u64 presentation_id) override;+ virtual Messages::CompositorControlServer::CreateRemoteLayerResponse create_remote_layer(u64 presentation_id, u64 remote_layer_id) override;+ virtual void destroy_remote_layer(u64 remote_layer_id) override;+ virtual void show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId>) override;virtual void create_context(Web::CompositorContextId, Optional<u64> page_id, i32 web_content_connection_id) override;virtual void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize, double device_pixel_ratio, Compositing::WindowResizingInProgress) override;virtual void set_ui_overlays(Web::CompositorContextId, Compositing::UIOverlays) override;diff --git a/Services/Compositor/ConnectionFromPresentation.cpp b/Services/Compositor/ConnectionFromPresentation.cppindex cd9ceb40ce2..57ca722fe74 100644--- a/Services/Compositor/ConnectionFromPresentation.cpp+++ b/Services/Compositor/ConnectionFromPresentation.cpp@@ -54,6 +54,11 @@ void ConnectionFromPresentation::did_present_frame(Web::CompositorContextId contasync_did_present_frame(context_id, content_rect, damage_rect, bitmap_id, device_pixel_ratio);}+void ConnectionFromPresentation::did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio)+{+ async_did_present_frame_in_remote_layer(context_id, content_rect, damage_rect, device_pixel_ratio);+}+void ConnectionFromPresentation::post_message_to_presentation(IPC::MessageBuffer& buffer){(void)post_message(buffer);diff --git a/Services/Compositor/ConnectionFromPresentation.h b/Services/Compositor/ConnectionFromPresentation.hindex 8ba52bf5640..b602f955b8d 100644--- a/Services/Compositor/ConnectionFromPresentation.h+++ b/Services/Compositor/ConnectionFromPresentation.h@@ -36,6 +36,7 @@ private:virtual void did_add_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage>&& backing_stores) override;virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) override;virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) override;+ virtual void did_present_frame_in_remote_layer(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) override;virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage&) override;virtual void presented_bitmap_ready_to_paint(Web::CompositorContextId, i32 bitmap_id) override;diff --git a/Services/Compositor/ContextPresenter.h b/Services/Compositor/ContextPresenter.hindex 13c73faa4ce..7d6d7908787 100644--- a/Services/Compositor/ContextPresenter.h+++ b/Services/Compositor/ContextPresenter.h@@ -91,6 +91,8 @@ public:void acknowledge_all_presented_bitmaps() { m_backing_store_manager.release_all_presented_buffers(); }void did_finish_gpu_present(i32 bitmap_id);RefPtr<Gfx::PaintingSurface> latest_rendered_surface() const { return m_latest_rendered_surface; }+ Gfx::SharedImageBuffer const* shared_image_buffer_of_latest_rendered_store() const { return m_backing_store_manager.shared_image_buffer_of_latest_rendered_store(); }+ BackingStoreManager::PublicationMode backing_store_publication_mode() const { return m_backing_store_manager.publication_mode(); }bool update_composited_raster_transform(Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& canvas_transform);CompositedContextSurface composited_surface() const;diff --git a/Services/Compositor/RemoteLayer.h b/Services/Compositor/RemoteLayer.hnew file mode 100644index 00000000000..e416d106c6d--- /dev/null+++ b/Services/Compositor/RemoteLayer.h@@ -0,0 +1,61 @@+/*+ * 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/Platform.h>+#include <AK/Types.h>+#include <AK/kmalloc.h>+#include <LibGfx/Forward.h>+#include <LibGfx/Size.h>++namespace Compositor {++// 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.+class RemoteLayer {+ AK_MAKE_NONCOPYABLE(RemoteLayer);+ AK_MAKE_NONMOVABLE(RemoteLayer);++public:+ AK_ALLOC_WITH_KMALLOC;++ // None where the platform offers no such layer trees.+ static OwnPtr<RemoteLayer> try_create();+ ~RemoteLayer();++ u32 core_animation_context_id() const { return m_core_animation_context_id; }++ // Shows the part of the buffer that the frame was painted into, at the top left of the layer.+ void show_frame(Gfx::SharedImageBuffer const&, Gfx::IntSize painted_size, double device_pixel_ratio);++private:+ RemoteLayer() = default;++#ifdef AK_OS_MACOS+ void* m_context { nullptr };+ void* m_root_layer { nullptr };+ void* m_content_layer { nullptr };+#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)+{+}+#endif++}diff --git a/Services/Compositor/RemoteLayer.mm b/Services/Compositor/RemoteLayer.mmnew file mode 100644index 00000000000..44752564ab2--- /dev/null+++ b/Services/Compositor/RemoteLayer.mm@@ -0,0 +1,140 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/StdLibExtras.h>+#include <Compositor/RemoteLayer.h>+#include <LibGfx/SharedImageBuffer.h>++#include <dlfcn.h>+#include <objc/runtime.h>++#import <QuartzCore/QuartzCore.h>++// A CAContext carries a layer tree to the window server, where a CALayerHost in another process shows it by the+// context's ID. Neither is public API, so the context is reached through the runtime and checked before use.+@protocol LadybirdCoreAnimationContext <NSObject>+@property (readonly) uint32_t contextId;+@property (retain) CALayer* layer;+@end++@protocol LadybirdCoreAnimationContextClass <NSObject>++ (id<LadybirdCoreAnimationContext>)contextWithCGSConnection:(uint32_t)connection options:(NSDictionary*)options;+@end++namespace Compositor {++using WindowServerConnectionIDFunction = uint32_t (*)();++static WindowServerConnectionIDFunction main_window_server_connection_id_function()+{+ static auto function = reinterpret_cast<WindowServerConnectionIDFunction>(dlsym(RTLD_DEFAULT, "CGSMainConnectionID"));+ return function;+}++static Class core_animation_context_class()+{+ static Class context_class = []() -> Class {+ Class context_class = NSClassFromString(@"CAContext");+ if (!context_class || ![context_class respondsToSelector:@selector(contextWithCGSConnection:options:)])+ return nil;+ // The properties are generated at run time, so instances do not answer to their selectors before one exists.+ if (!class_getProperty(context_class, "contextId") || !class_getProperty(context_class, "layer"))+ return nil;+ return context_class;+ }();+ return context_class;+}++// Changes made outside an explicit transaction open an implicit one, which only a run loop commits, and while it is+// open it holds back the explicit ones nested in it as well. This process has no run loop, so every change is made in+// an explicit transaction, and any implicit one that something opened anyway is flushed after it.+template<typename Callback>+static void commit_layer_changes(Callback callback)+{+ @autoreleasepool {+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ callback();+ [CATransaction commit];+ [CATransaction flush];+ }+}++static CALayer* as_layer(void* layer)+{+ return static_cast<CALayer*>(layer);+}++OwnPtr<RemoteLayer> RemoteLayer::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);+ commit_layer_changes([&] {+ auto* root_layer = [[CALayer alloc] init];+ root_layer.anchorPoint = CGPointZero;+ // Frames are laid out from the top left, as the view that hosts the tree is.+ root_layer.geometryFlipped = YES;++ auto* content_layer = [[CALayer alloc] init];+ content_layer.anchorPoint = CGPointZero;+ [root_layer addSublayer:content_layer];++ id<LadybirdCoreAnimationContext> context = [(Class<LadybirdCoreAnimationContextClass>)context_class contextWithCGSConnection:connection_id_function() options:@ {}];+ context.layer = root_layer;++ remote_layer->m_context = [context retain];+ remote_layer->m_root_layer = root_layer;+ remote_layer->m_content_layer = content_layer;+ remote_layer->m_core_animation_context_id = context.contextId;+ });+ if (remote_layer->m_core_animation_context_id == 0)+ return nullptr;+ return remote_layer;+}++RemoteLayer::~RemoteLayer()+{+ commit_layer_changes([&] {+ auto context = static_cast<id<LadybirdCoreAnimationContext>>(m_context);+ context.layer = nil;+ [context release];+ [as_layer(m_content_layer) release];+ [as_layer(m_root_layer) release];+ });+}++void RemoteLayer::show_frame(Gfx::SharedImageBuffer const& buffer, Gfx::IntSize painted_size, double device_pixel_ratio)+{+ auto const& iosurface = buffer.iosurface_handle();+ auto surface_width = static_cast<int>(iosurface.width());+ auto surface_height = static_cast<int>(iosurface.height());+ auto painted_width = min(painted_size.width(), surface_width);+ auto painted_height = min(painted_size.height(), surface_height);+ if (painted_width <= 0 || painted_height <= 0)+ return;++ commit_layer_changes([&] {+ auto* content_layer = as_layer(m_content_layer);+ auto painted_unit_width = static_cast<CGFloat>(painted_width) / surface_width;+ auto painted_unit_height = static_cast<CGFloat>(painted_height) / surface_height;+ // A store can be larger than the frame painted into it, as while the window is resized. The unit rectangle+ // that picks the painted part turns upside down along with the layer's y-axis.+ content_layer.contentsRect = content_layer.contentsAreFlipped+ ? CGRectMake(0, 0, painted_unit_width, painted_unit_height)+ : CGRectMake(0, 1 - painted_unit_height, painted_unit_width, painted_unit_height);+ content_layer.contentsScale = device_pixel_ratio;+ auto frame = CGRectMake(0, 0, painted_width / device_pixel_ratio, painted_height / device_pixel_ratio);+ content_layer.frame = frame;+ as_layer(m_root_layer).frame = frame;+ content_layer.contents = (__bridge id)iosurface.core_foundation_pointer();+ });+}++}