Truly independent web browser
Compositor: Keep remote layers and window resizes in Rust
Aliaksandr Kalenik6fca7daebe8b
diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex a20fa8adb2c..937f4bbee5f 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -312,6 +312,10 @@ fn generate_ipc_definitions(manifest_dir: &Path, out_dir: &Path) -> Result<(), B"Services/Compositor/CompositorWebContentServer.ipc","CompositorWebContentServerEndpoint.rs",),+ (+ "Services/Compositor/CompositorControlServer.ipc",+ "CompositorControlServerEndpoint.rs",+ ),("Services/Compositor/CompositorPresentationClient.ipc","CompositorPresentationClientEndpoint.rs",diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex 1e3de4a5252..c8da76fbe6e 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -131,6 +131,7 @@ include!(concat!(env!("OUT_DIR"), "/MouseButton.rs"));include!(concat!(env!("OUT_DIR"), "/TextEditingCommand.rs"));include!(concat!(env!("OUT_DIR"), "/Types.rs"));+include!(concat!(env!("OUT_DIR"), "/CompositorControlServerEndpoint.rs"));include!(concat!(env!("OUT_DIR"), "/CompositorPresentationClientEndpoint.rs"));include!(concat!(env!("OUT_DIR"), "/CompositorPresentationServerEndpoint.rs"));include!(concat!(env!("OUT_DIR"), "/CompositorWebContentClientEndpoint.rs"));diff --git a/Services/Compositor/CompositorControlServer.ipc b/Services/Compositor/CompositorControlServer.ipcindex a4b931f5634..c3016d6a373 100644--- a/Services/Compositor/CompositorControlServer.ipc+++ b/Services/Compositor/CompositorControlServer.ipc@@ -18,13 +18,13 @@ endpoint CompositorControlServercreate_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 host handle's kind is None where the presentation has no remote layers.- create_remote_layer(u64 presentation_id, u64 remote_layer_id) => (Compositing::RemoteLayerHostHandle host_handle)- destroy_remote_layer(u64 remote_layer_id) =|- show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId> context_id) =|- set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within) =|- begin_synchronized_resize(u64 remote_layer_id, u64 token) =|- await_synchronized_resize_frame(u64 remote_layer_id, u64 token, Gfx::IntSize size) =|- commit_synchronized_resize(u64 remote_layer_id, u64 token) =|+ [RustReceiver] create_remote_layer(u64 presentation_id, u64 remote_layer_id) => (Compositing::RemoteLayerHostHandle host_handle)+ [RustReceiver] destroy_remote_layer(u64 remote_layer_id) =|+ [RustReceiver] show_context_in_remote_layer(u64 remote_layer_id, Optional<Web::CompositorContextId> context_id) =|+ [RustReceiver] set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within) =|+ [RustReceiver] begin_synchronized_resize(u64 remote_layer_id, u64 token) =|+ [RustReceiver] await_synchronized_resize_frame(u64 remote_layer_id, u64 token, Gfx::IntSize size) =|+ [RustReceiver] commit_synchronized_resize(u64 remote_layer_id, u64 token) =|create_context(Web::CompositorContextId context_id, Optional<u64> page_id, i32 web_content_connection_id) => ()diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex 1456642ed97..fda383eac4e 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -38,14 +38,19 @@ static void post_message_to_presentation(void* host, u64 presentation_id, Readonstatic_cast<CompositorCoreHost*>(host)->post_message_to_presentation(PresentationId { presentation_id }, buffer);}-static void set_timer(void* host, u64 context_id, ContextTimer timer, i64 delay_nanoseconds)+static void set_timer(void* host, u64 timer_number, i64 delay_nanoseconds){- static_cast<CompositorCoreHost*>(host)->set_timer(Web::CompositorContextId { context_id }, timer, AK::Duration::from_nanoseconds(delay_nanoseconds));+ static_cast<CompositorCoreHost*>(host)->set_timer(timer_number, AK::Duration::from_nanoseconds(delay_nanoseconds));}-static void cancel_timer(void* host, u64 context_id, ContextTimer timer)+static void cancel_timer(void* host, u64 timer_number){- static_cast<CompositorCoreHost*>(host)->cancel_timer(Web::CompositorContextId { context_id }, timer);+ static_cast<CompositorCoreHost*>(host)->cancel_timer(timer_number);+}++static void destroy_timer(void* host, u64 timer_number)+{+ static_cast<CompositorCoreHost*>(host)->destroy_timer(timer_number);}static void shape_overlay_label(void* host, u64 context_id, bool has_font_family, ReadonlyBytes font_family, double device_pixel_ratio, ReadonlyBytes text, void* receiver, void (*receive)(void*, RustFFI::FfiOverlayLabel const*))@@ -82,6 +87,7 @@ CompositorCore::CompositorCore(CompositorCoreHost& host, RustFFI::FfiRasterHost.post_message_to_presentation = Compositor::post_message_to_presentation,.set_timer = Compositor::set_timer,.cancel_timer = Compositor::cancel_timer,+ .destroy_timer = Compositor::destroy_timer,.shape_overlay_label = Compositor::shape_overlay_label,};m_core = RustFFI::compositor_core_create(ffi_host, raster_host, scrollbars_always_shown, gpu);@@ -202,11 +208,6 @@ void CompositorCore::bind_presentation(Web::CompositorContextId context_id, PresRustFFI::compositor_core_bind_presentation(m_core, context_id.value(), presentation_id.value(), now().nanoseconds());}-void CompositorCore::set_shown_in_remote_layer(Web::CompositorContextId context_id, bool shown)-{- RustFFI::compositor_core_set_shown_in_remote_layer(m_core, context_id.value(), shown, now().nanoseconds());-}-void CompositorCore::set_display_metadata(Web::CompositorContextId context_id, Optional<u64> display_id, double refresh_rate){RustFFI::compositor_core_set_display_metadata(m_core, context_id.value(), display_id.has_value(), display_id.value_or(0), refresh_rate, now().nanoseconds());@@ -291,9 +292,9 @@ Optional<CompositorCore::PresentedFrame> CompositorCore::presented_frame_for_snareturn PresentedFrame { adopt_ref(const_cast<Gfx::PaintingSurface&>(*surface)), frame_size };}-void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer)+void CompositorCore::timer_fired(u64 timer_number){- RustFFI::compositor_core_timer_fired(m_core, context_id.value(), timer, now().nanoseconds());+ RustFFI::compositor_core_timer_fired(m_core, timer_number, now().nanoseconds());}IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_web_content(WebContentClientId client_id, IPC::RawMessage& message)@@ -303,6 +304,13 @@ IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_web_content(W});}+IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_control(IPC::RawMessage& message)+{+ return message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {+ RustFFI::compositor_core_handle_control_message(m_core, raw_message, now().nanoseconds());+ });+}+IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_presentation(PresentationId presentation_id, IPC::RawMessage& message){return message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.hindex dad382162ab..cc3ebff8124 100644--- a/Services/Compositor/CompositorCore.h+++ b/Services/Compositor/CompositorCore.h@@ -55,7 +55,6 @@ public:void set_presentation_gpu_capability(PresentationId, bool supported, u64 adapter_luid);void set_scrollbar_track_press_jumps(PresentationId, bool jumps);void bind_presentation(Web::CompositorContextId, PresentationId);- void set_shown_in_remote_layer(Web::CompositorContextId, bool shown);void set_display_metadata(Web::CompositorContextId, Optional<u64> display_id, double refresh_rate);void set_window_server_may_show_high_dynamic_range(bool);void set_presents_from_cpu_memory(Web::CompositorContextId, bool);@@ -82,11 +81,13 @@ public:// The surface that holds the frame on screen as a whole, and the size of the frame in it.Optional<PresentedFrame> presented_frame_for_snapshot(Web::CompositorContextId);- void timer_fired(Web::CompositorContextId, ContextTimer);+ void timer_fired(u64 timer_number);- // The messages of CompositorWebContentServer and CompositorPresentationServer that are marked [RustReceiver].+ // The messages of CompositorWebContentServer, CompositorPresentationServer and CompositorControlServer that are marked+ // [RustReceiver].IPC::RawMessage::OutcomeInRust handle_message_from_web_content(WebContentClientId, IPC::RawMessage&);IPC::RawMessage::OutcomeInRust handle_message_from_presentation(PresentationId, IPC::RawMessage&);+ IPC::RawMessage::OutcomeInRust handle_message_from_control(IPC::RawMessage&);private:RustFFI::CompositorCore* m_core { nullptr };diff --git a/Services/Compositor/CompositorCoreHost.h b/Services/Compositor/CompositorCoreHost.hindex 68490761660..c54fdb18606 100644--- a/Services/Compositor/CompositorCoreHost.h+++ b/Services/Compositor/CompositorCoreHost.h@@ -20,8 +20,6 @@ namespace Compositor {AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, WebContentClientId);AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, PresentationId);-using ContextTimer = RustFFI::ContextTimer;-// A label of an overlay, shaped in a font that the overlays' resources of its context hold: the glyphs, where each goes// along the line in device pixels, and the metrics of the font that placing the line needs.struct OverlayLabel {@@ -48,9 +46,11 @@ public:virtual void post_message_to_render_clock_of_web_content(WebContentClientId, IPC::MessageBuffer&) = 0;// A message for a presentation that is gone is dropped.virtual void post_message_to_presentation(PresentationId, IPC::MessageBuffer&) = 0;- // Each timer of a context fires once after the delay, and setting it again replaces the delay.- virtual void set_timer(Web::CompositorContextId, ContextTimer, AK::Duration delay) = 0;- virtual void cancel_timer(Web::CompositorContextId, ContextTimer) = 0;+ // A timer, which the core knows by its number, fires once after the delay, and setting it again replaces the delay.+ virtual void set_timer(u64 timer_number, AK::Duration delay) = 0;+ virtual void cancel_timer(u64 timer_number) = 0;+ // The timer is not set again.+ virtual void destroy_timer(u64 timer_number) = 0;// In the font family given, or the default one. Empty where no font draws the label.virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, double device_pixel_ratio, StringView text) = 0;};diff --git a/Services/Compositor/CompositorPresentationClient.ipc b/Services/Compositor/CompositorPresentationClient.ipcindex cd3aacc1cb1..890d021bfc9 100644--- a/Services/Compositor/CompositorPresentationClient.ipc+++ b/Services/Compositor/CompositorPresentationClient.ipc@@ -11,8 +11,8 @@ endpoint CompositorPresentationClient[RustSender] did_present_frame(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) =|[RustSender] did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) =|did_take_frame_snapshot(u64 request_id, Optional<Gfx::ShareableBitmap> snapshot) =|- did_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) =|- did_commit_synchronized_resize(u64 remote_layer_id, u64 token) =|+ [RustSender] did_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) =|+ [RustSender] did_commit_synchronized_resize(u64 remote_layer_id, u64 token) =|[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 102b0c6d44b..825a5dcd952 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -64,6 +64,11 @@ IPC::RawMessage::OutcomeInRust CompositorState::handle_message_from_presentationreturn m_core.handle_message_from_presentation(presentation_id, message);}+IPC::RawMessage::OutcomeInRust CompositorState::handle_message_from_control(IPC::RawMessage& message)+{+ return m_core.handle_message_from_control(message);+}+CompositorState::PresentedContext::PresentedContext(CompositorStateWebContentClient& web_content_client, OwnedCanvasSurfaces canvas_surfaces): web_content_client(web_content_client), raster_targets(canvas_surfaces)@@ -113,38 +118,36 @@ CompositorStateClient* CompositorState::presentation_if_present(PresentationId preturn m_presentations_by_id.get(presentation_id).value_or(nullptr);}-void CompositorState::set_timer(Web::CompositorContextId context_id, ContextTimer timer, AK::Duration delay)+void CompositorState::set_timer(u64 timer_number, AK::Duration delay){- auto& context_timer = m_context_timers.ensure(context_id).ensure(timer, [&] {- return Core::Timer::create_single_shot(delay, [this, context_id, timer] {- context_timer_fired(context_id, timer);+ auto& timer = m_timers.ensure(timer_number, [&] {+ return Core::Timer::create_single_shot(delay, [this, timer_number] {+ m_core.timer_fired(timer_number);});});- context_timer->restart(delay);+ timer->restart(delay);}-void CompositorState::cancel_timer(Web::CompositorContextId context_id, ContextTimer timer)+void CompositorState::cancel_timer(u64 timer_number){- auto timers = m_context_timers.find(context_id);- if (timers == m_context_timers.end())- return;- if (auto context_timer = timers->value.get(timer); context_timer.has_value())- (*context_timer)->stop();+ if (auto timer = m_timers.get(timer_number); timer.has_value())+ (*timer)->stop();}-void CompositorState::context_timer_fired(Web::CompositorContextId context_id, ContextTimer timer)+void CompositorState::destroy_timer(u64 timer_number){- if (!presented_context_if_present(context_id))+ auto timer = m_timers.take(timer_number);+ if (!timer.has_value())return;- m_core.timer_fired(context_id, timer);+ (*timer)->stop();+ // NB: The timer may be the one whose callback is running.+ Core::deferred_invoke([timer = timer.release_value()] { });}PresentationId CompositorState::register_presentation(CompositorStateClient& presentation, PresentationCapabilities capabilities){PresentationId presentation_id { m_next_presentation_id++ };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());m_core.register_presentation(presentation_id,{.synthesizes_scroll_momentum = capabilities.synthesizes_scroll_momentum,@@ -159,18 +162,6 @@ 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);- 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();- }-m_core.unregister_presentation(presentation.presentation_id());m_presentations_by_id.remove(presentation.presentation_id());}@@ -183,146 +174,6 @@ void CompositorState::bind_presentation(Web::CompositorContextId context_id, Comm_core.bind_presentation(context_id, presentation.presentation_id());}-Compositing::RemoteLayerHostHandle CompositorState::create_remote_layer(CompositorStateClient& presentation, u64 remote_layer_id)-{- VERIFY(presentation_if_present(presentation.presentation_id()) == &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 {};- }- auto window_server = m_window_servers.get(&presentation);- if (!window_server.has_value())- return {};- auto layer = (*window_server)->try_create_remote_layer(remote_layer_id);- if (!layer)- return {};- auto host_handle = layer->host_handle();- 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 host_handle;-}--void CompositorState::destroy_remote_layer(u64 remote_layer_id)-{- show_context_in_remote_layer(remote_layer_id, {});- m_remote_layers.remove(remote_layer_id);- auto had_synchronized_resizes = !m_synchronized_resizes.is_empty();- m_synchronized_resizes.remove_all_matching([&](auto const& resize) { return resize.remote_layer_id == remote_layer_id; });- if (had_synchronized_resizes && m_synchronized_resizes.is_empty())- release_synchronized_resize_hold();-}--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;-- remote_layer->value.size_of_shown_frame_laid_out_by_page = {};- 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)) {- shown_context->remote_layer_id = {};- m_core.set_shown_in_remote_layer(*shown_context_id, false);- }- }- if (!context_id.has_value())- return;-- auto* context = presented_context_if_present(*context_id);- if (!context || !m_core.presents_to_client(*context_id)) {- 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 = {};- other_remote_layer->value.size_of_shown_frame_laid_out_by_page = {};- }- }-- remote_layer->value.shown_context_id = context_id;- context->remote_layer_id = remote_layer_id;- m_core.set_shown_in_remote_layer(*context_id, true);-}--void CompositorState::set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within)-{- auto remote_layer = m_remote_layers.find(remote_layer_id);- if (remote_layer == m_remote_layers.end() || remote_layer->value.fit_within == fit_within)- return;- remote_layer->value.fit_within = fit_within;- remote_layer->value.layer->place_frame(fit_within);-}--// A UI that never commits its resize, as one that crashed, would otherwise freeze every window of the browser.-static constexpr auto SYNCHRONIZED_RESIZE_HOLD_LIMIT = AK::Duration::from_seconds(1);--void CompositorState::begin_synchronized_resize(u64 remote_layer_id, u64 token)-{- auto remote_layer = m_remote_layers.find(remote_layer_id);- if (remote_layer == m_remote_layers.end())- return;- 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_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 });-}--void CompositorState::await_synchronized_resize_frame(u64 remote_layer_id, u64 token, Gfx::IntSize size)-{- for (auto& resize : m_synchronized_resizes) {- if (resize.remote_layer_id == remote_layer_id && resize.token == token)- resize.awaited_size = size;- }- report_held_synchronized_resize_frames(remote_layer_id);-}--void CompositorState::report_held_synchronized_resize_frames(u64 remote_layer_id)-{- auto remote_layer = m_remote_layers.find(remote_layer_id);- if (remote_layer == m_remote_layers.end())- return;- auto shown_size = remote_layer->value.size_of_shown_frame_laid_out_by_page;- for (auto& resize : m_synchronized_resizes) {- if (resize.remote_layer_id != remote_layer_id || resize.frame_is_held || !resize.awaited_size.has_value() || resize.awaited_size != shown_size)- continue;- resize.frame_is_held = true;- remote_layer->value.presentation->did_hold_synchronized_resize_frame(remote_layer_id, resize.token);- }-}--void CompositorState::commit_synchronized_resize(u64 remote_layer_id, u64 token)-{- m_synchronized_resizes.remove_all_matching([&](auto const& resize) {- return resize.remote_layer_id == remote_layer_id && resize.token == token;- });- if (m_synchronized_resizes.is_empty())- release_synchronized_resize_hold();- if (auto remote_layer = m_remote_layers.find(remote_layer_id); remote_layer != m_remote_layers.end())- remote_layer->value.presentation->did_commit_synchronized_resize(remote_layer_id, token);-}--void CompositorState::release_synchronized_resize_hold()-{- if (m_synchronized_resize_hold_timeout)- m_synchronized_resize_hold_timeout->stop();- m_synchronized_resizes.clear();- for (auto& window_server : exchange(m_window_servers_holding_changes, {}))- window_server->release_changes_held_off_screen();-}-CompositorStateClient* CompositorState::presentation_for_context(Web::CompositorContextId context_id) const{auto presentation_id = m_core.bound_presentation(context_id);@@ -449,20 +300,8 @@ void CompositorState::create_context(Web::CompositorContextId context_id, Optionvoid CompositorState::destroy_context(Web::CompositorContextId context_id){- auto& context = presented_context(context_id);+ VERIFY(presented_context_if_present(context_id));m_core.destroy_context(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 = {};- timer->stop();- }- m_context_timers.remove(timers);- }m_presented_contexts.remove(context_id);update_unpainted_video_update_scheduling();}@@ -1101,14 +940,9 @@ struct SharedImageToPublish {}-bool CompositorState::create_store(Web::CompositorContextId context_id, RustFFI::StoreKind kind, Gfx::IntSize size, RustFFI::FfiNewStore& new_store)+bool CompositorState::create_store(Web::CompositorContextId context_id, RustFFI::StoreKind kind, Gfx::IntSize size, WindowServer* window_server_showing_stores, RustFFI::FfiNewStore& new_store){- RefPtr<WindowServer> window_server_showing_stores;- if (kind == RustFFI::StoreKind::ShownByWindowServer) {- if (auto* remote_layer = remote_layer_showing(context_id))- window_server_showing_stores = remote_layer->window_server;- }- auto store_or_error = create_backing_store(kind, size, m_skia_backend_context, window_server_showing_stores.ptr());+ auto store_or_error = create_backing_store(kind, size, m_skia_backend_context, window_server_showing_stores);if (store_or_error.is_error()) {if (kind == RustFFI::StoreKind::ShownByWindowServer)dbgln("Compositor: Failed to allocate a store of context {} that a remote layer shows, which its presentation shows again: {}", context_id, store_or_error.error());@@ -1329,17 +1163,6 @@ void CompositorState::report_live_content(Web::CompositorContextId context_id, Rreceive(receiver, &content);}-CompositorState::RemoteLayerState* CompositorState::remote_layer_showing(Web::CompositorContextId context_id)-{- auto* context = presented_context_if_present(context_id);- if (!context || !context->remote_layer_id.has_value())- return nullptr;- auto remote_layer = m_remote_layers.find(*context->remote_layer_id);- if (remote_layer == m_remote_layers.end())- return nullptr;- return &remote_layer->value;-}-Optional<RemoteLayer::Content> CompositorState::remote_layer_content(PresentedContext& context, RustFFI::MediaKind kind, u64 media_id){switch (kind) {@@ -1375,11 +1198,8 @@ static Gfx::AffineTransform content_to_frame_of(RustFFI::FfiSublayerPlacement coreturn { transform[0], transform[1], transform[2], transform[3], transform[4], transform[5] };}-bool CompositorState::remote_layer_can_show(Web::CompositorContextId context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const& placement, double device_pixel_ratio)+bool CompositorState::remote_layer_can_show(RemoteLayer& remote_layer, Web::CompositorContextId context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const& placement, double device_pixel_ratio){- auto* remote_layer = remote_layer_showing(context_id);- if (!remote_layer)- return false;auto content = remote_layer_content(presented_context(context_id), kind, media_id);if (!content.has_value())return false;@@ -1390,7 +1210,7 @@ bool CompositorState::remote_layer_can_show(Web::CompositorContextId context_id,.rounded_clip = rounded_clip_of(placement),.scaling_mode = placement.scaling_mode,};- return remote_layer->layer->can_show(window_server_placement, *content, device_pixel_ratio);+ return remote_layer.can_show(window_server_placement, *content, device_pixel_ratio);}Vector<RemoteSublayer>* CompositorState::build_sublayers(Web::CompositorContextId context_id, ReadonlySpan<RustFFI::FfiSublayer> sublayers_to_build)@@ -1429,13 +1249,6 @@ Vector<RemoteSublayer>* CompositorState::build_sublayers(Web::CompositorContextIreturn sublayers.leak_ptr();}-WindowServer::FrameHandOff CompositorState::frame_hand_off(Web::CompositorContextId context_id)-{- if (auto* remote_layer = remote_layer_showing(context_id))- return remote_layer->window_server->frame_hand_off();- return WindowServer::frame_hand_off_through_presentation();-}-u64 CompositorState::submit_frame(Gfx::PaintingSurface* surface){auto token = m_next_gpu_work_token++;@@ -1484,44 +1297,6 @@ void CompositorState::hand_off_once_gpu_work_is_scheduled([[maybe_unused]] u64 t#endif}-Optional<PresentationId> CompositorState::show_frame_in_remote_layer(Web::CompositorContextId context_id, RustFFI::FfiRemoteLayerFrame const& frame, NonnullOwnPtr<Vector<RemoteSublayer>> sublayers)-{- auto* remote_layer = remote_layer_showing(context_id);- if (!remote_layer)- return {};- auto& context = presented_context(context_id);- auto* store = const_cast<PresentableSurface*>(frame.store);-- auto remote_layer_id = *context.remote_layer_id;- auto shown = remote_layer->layer->show_frame({- .store = store ? Optional<PresentableSurface::Lease> { store->lease() } : OptionalNone {},- .painted_size = frame.painted_size,- .device_pixel_ratio = frame.device_pixel_ratio,- .fit_within = remote_layer->fit_within,- .sublayers = move(*sublayers),- });- if (!shown) {- dbgln("Compositor: Remote layer {} failed to show a frame of context {}, which its presentation shows again", remote_layer_id, context_id);- stop_showing_in_remote_layer(context_id);- return {};- }- remote_layer->size_of_shown_frame_laid_out_by_page = frame.laid_out_by_page ? Optional<Gfx::IntSize> { frame.painted_size } : OptionalNone {};- report_held_synchronized_resize_frames(remote_layer_id);- return remote_layer->presentation->presentation_id();-}--void CompositorState::stop_showing_in_remote_layer(Web::CompositorContextId context_id)-{- auto& context = presented_context(context_id);- auto remote_layer_id = exchange(context.remote_layer_id, {});- if (!remote_layer_id.has_value())- return;- if (auto remote_layer = m_remote_layers.find(*remote_layer_id); remote_layer != m_remote_layers.end()) {- remote_layer->value.shown_context_id = {};- remote_layer->value.size_of_shown_frame_laid_out_by_page = {};- }-}-void CompositorState::release_store_later(Web::CompositorContextId context_id, i32 bitmap_id){Core::deferred_invoke([self = NonnullRefPtr { *this }, context_id, bitmap_id] {@@ -1653,7 +1428,7 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state).begin_painting = [](void* host, u64 context_id, Gfx::PaintingSurface const* surface, RustFFI::PaintingResources resources, bool allows_lcd_text, Compositing::RustFFI::FfiRasterPainter* painter) { *painter = state_of(host).begin_painting(Context { context_id }, mutable_surface(surface), resources, allows_lcd_text); },.end_painting = [](void* host) { state_of(host).end_painting(); },.start_raster_cache_frame = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.raster_cache().drop_what_was_not_used_since_last_frame(); },- .create_store = [](void* host, u64 context_id, RustFFI::StoreKind kind, Gfx::IntSize size, RustFFI::FfiNewStore* new_store) { return state_of(host).create_store(Context { context_id }, kind, size, *new_store); },+ .create_store = [](void* host, u64 context_id, RustFFI::StoreKind kind, Gfx::IntSize size, void* window_server, RustFFI::FfiNewStore* new_store) { return state_of(host).create_store(Context { context_id }, kind, size, static_cast<WindowServer*>(window_server), *new_store); },.publish_stores = [](void* host, u64 presentation_id, u64 context_id, bool added, ReadonlySpan<i32> bitmap_ids, ReadonlySpan<void*> images) { state_of(host).publish_stores(PresentationId { presentation_id }, Context { context_id }, added, bitmap_ids, images); },.retire_published_stores = [](void* host, u64 presentation_id, u64 context_id, ReadonlySpan<i32> bitmap_ids) { state_of(host).retire_published_stores(PresentationId { presentation_id }, Context { context_id }, bitmap_ids); },.create_presentable_surface = [](void*, Gfx::IntSize size, Gfx::PaintingSurface const* like) -> PresentableSurface const* {@@ -1663,23 +1438,49 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)return &surface.release_value().leak_ref();},.live_content = [](void* host, u64 context_id, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*)) { state_of(host).report_live_content(Context { context_id }, canvas_ids, receiver, receive); },- .remote_layer_can_show = [](void* host, u64 context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const* placement, double device_pixel_ratio) { return state_of(host).remote_layer_can_show(Context { context_id }, kind, media_id, *placement, device_pixel_ratio); },+ .remote_layer_can_show = [](void* host, void* remote_layer, u64 context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const* placement, double device_pixel_ratio) { return state_of(host).remote_layer_can_show(*static_cast<RemoteLayer*>(remote_layer), Context { context_id }, kind, media_id, *placement, device_pixel_ratio); },.build_sublayers = [](void* host, u64 context_id, ReadonlySpan<RustFFI::FfiSublayer> sublayers) -> void* {return state_of(host).build_sublayers(Context { context_id }, sublayers);},.destroy_sublayers = [](void* sublayers) { delete static_cast<Vector<RemoteSublayer>*>(sublayers); },- .frame_hand_off = [](void* host, u64 context_id) { return state_of(host).frame_hand_off(Context { context_id }) == WindowServer::FrameHandOff::OnceGpuWorkIsScheduled- ? RustFFI::FrameHandOff::OnceGpuWorkIsScheduled- : RustFFI::FrameHandOff::OnceGpuWorkIsFinished; },.submit_frame = [](void* host, u64, Gfx::PaintingSurface const* surface) { return state_of(host).submit_frame(const_cast<Gfx::PaintingSurface*>(surface)); },.hand_off_once_gpu_work_is_scheduled = [](void* host, u64 token) { state_of(host).hand_off_once_gpu_work_is_scheduled(token); },- .show_frame_in_remote_layer = [](void* host, u64 context_id, RustFFI::FfiRemoteLayerFrame const* frame, void* sublayers, u64* presentation_id) {- auto shown_in = state_of(host).show_frame_in_remote_layer(Context { context_id }, *frame, adopt_own(*static_cast<Vector<RemoteSublayer>*>(sublayers)));- if (!shown_in.has_value())+ .create_window_server = [](void*, RustFFI::FfiCppObject* window_server) {+ auto created = WindowServer::try_create_for_presentation();+ if (!created)+ return false;+ window_server->object = &created.release_nonnull().leak_ref();+ window_server->destroy = [](void* object) { static_cast<WindowServer*>(object)->unref(); };+ return true; },+ .window_server_frame_hand_off = [](void* window_server) { return static_cast<WindowServer*>(window_server)->frame_hand_off() == WindowServer::FrameHandOff::OnceGpuWorkIsScheduled+ ? RustFFI::FrameHandOff::OnceGpuWorkIsScheduled+ : RustFFI::FrameHandOff::OnceGpuWorkIsFinished; },+ .window_server_hold_changes_on_screen = [](void* window_server) { static_cast<WindowServer*>(window_server)->hold_changes_on_screen(); },+ .window_server_release_changes_held_off_screen = [](void* window_server) { static_cast<WindowServer*>(window_server)->release_changes_held_off_screen(); },+ .create_remote_layer = [](void* window_server, u64 remote_layer_id, RustFFI::FfiCppObject* remote_layer, RustFFI::FfiRemoteLayerHostHandle* host_handle) {+ auto layer = static_cast<WindowServer*>(window_server)->try_create_remote_layer(remote_layer_id);+ if (!layer)return false;- *presentation_id = shown_in->value();+ auto handle = layer->host_handle();+ host_handle->kind = to_underlying(handle.kind);+ host_handle->id = handle.id;+ remote_layer->object = layer.leak_ptr();+ remote_layer->destroy = [](void* object) { (void)adopt_own(*static_cast<RemoteLayer*>(object)); };return true; },- .stop_showing_in_remote_layer = [](void* host, u64 context_id) { state_of(host).stop_showing_in_remote_layer(Context { context_id }); },+ .remote_layer_place_frame = [](void* remote_layer, bool has_fit_within, Gfx::IntSize fit_within) { static_cast<RemoteLayer*>(remote_layer)->place_frame(has_fit_within ? Optional<Gfx::IntSize> { fit_within } : OptionalNone {}); },+ .remote_layer_show_frame = [](void* remote_layer, RustFFI::FfiRemoteLayerFrame const* frame, void* sublayers) {+ auto owned_sublayers = adopt_own(*static_cast<Vector<RemoteSublayer>*>(sublayers));+ auto* store = const_cast<PresentableSurface*>(frame->store);+ auto shown = static_cast<RemoteLayer*>(remote_layer)->show_frame({+ .store = store ? Optional<PresentableSurface::Lease> { store->lease() } : OptionalNone {},+ .painted_size = frame->painted_size,+ .device_pixel_ratio = frame->device_pixel_ratio,+ .fit_within = frame->has_fit_within ? Optional<Gfx::IntSize> { frame->fit_within } : OptionalNone {},+ .sublayers = move(*owned_sublayers),+ });+ if (!shown)+ dbgln("Compositor: A remote layer failed to show a frame, which its presentation shows again");+ return shown; },.log_presented_frame = [](void*, u64 page_id, Gfx::IntRect damage_rect) { log_presented_frame(page_id, damage_rect); },.release_store_later = [](void* host, u64 context_id, i32 bitmap_id) { state_of(host).release_store_later(Context { context_id }, bitmap_id); },.request_vsync = [](void* host, bool has_display_id, u64 display_id, double refresh_rate) { state_of(host).vsync_scheduler_for_display(display_of(has_display_id, display_id)).schedule(refresh_rate); },diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 923974c1e8e..da380ae9a3f 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -47,8 +47,6 @@ public:// The stores join the ones allocated last, and leave them again once retired.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_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) = 0;- virtual void did_commit_synchronized_resize(u64 remote_layer_id, u64 token) = 0;};class CompositorStateWebContentClient {@@ -137,6 +135,7 @@ public:// The messages of WebContent and of a presentation that the scroll and input logic takes undecoded.IPC::RawMessage::OutcomeInRust handle_message_from_web_content(WebContentClientId, IPC::RawMessage&);IPC::RawMessage::OutcomeInRust handle_message_from_presentation(PresentationId, IPC::RawMessage&);+ IPC::RawMessage::OutcomeInRust handle_message_from_control(IPC::RawMessage&);void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize, double device_pixel_ratio, Compositing::WindowResizingInProgress);void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second);void set_ui_overlays(Web::CompositorContextId, Compositing::UIOverlays);@@ -163,20 +162,6 @@ public:// A remote layer shows the frames of one root context at a time, in a view of the presentation it was created// for. Answers how that view finds the layer, whose kind is None where the presentation has no remote layers.- Compositing::RemoteLayerHostHandle 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>);- // A view that scales the frames to fit it gives its size, in device pixels.- void set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within);-- // A window resize is shown together with the page's frame of the new size: the remote layers hold their changes- // off screen from when the resize begins until the window commits it, and the presentation hears once the layer- // holds a frame that the page laid out at the size it awaits.- void begin_synchronized_resize(u64 remote_layer_id, u64 token);- void await_synchronized_resize_frame(u64 remote_layer_id, u64 token, Gfx::IntSize);- void commit_synchronized_resize(u64 remote_layer_id, u64 token);-struct PlaceholderCanvasAllocation {Compositing::CanvasId canvas_id;u64 secret { 0 };@@ -197,10 +182,10 @@ private:virtual void post_message_to_web_content(WebContentClientId, IPC::MessageBuffer&) override;virtual void post_message_to_render_clock_of_web_content(WebContentClientId, IPC::MessageBuffer&) override;virtual void post_message_to_presentation(PresentationId, IPC::MessageBuffer&) override;- virtual void set_timer(Web::CompositorContextId, ContextTimer, AK::Duration delay) override;- virtual void cancel_timer(Web::CompositorContextId, ContextTimer) override;+ virtual void set_timer(u64 timer_number, AK::Duration delay) override;+ virtual void cancel_timer(u64 timer_number) override;+ virtual void destroy_timer(u64 timer_number) override;virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, double device_pixel_ratio, StringView text) override;- void context_timer_fired(Web::CompositorContextId, ContextTimer);// What the compositor keeps of a context to paint and present its frames.struct PresentedContext {@@ -214,7 +199,6 @@ private:CompositorStateWebContentClient& web_content_client;ContextRasterTargets raster_targets;- Optional<u64> remote_layer_id;};PresentedContext* presented_context_if_present(Web::CompositorContextId);@@ -228,7 +212,7 @@ private:static RustFFI::GpuBackend gpu_backend(RefPtr<Gfx::SkiaBackendContext> const&);Compositing::RustFFI::FfiRasterPainter begin_painting(Web::CompositorContextId, Gfx::PaintingSurface&, RustFFI::PaintingResources, bool allows_lcd_text);void end_painting();- bool create_store(Web::CompositorContextId, RustFFI::StoreKind, Gfx::IntSize, RustFFI::FfiNewStore&);+ bool create_store(Web::CompositorContextId, RustFFI::StoreKind, Gfx::IntSize, WindowServer* window_server_showing_stores, RustFFI::FfiNewStore&);void publish_stores(PresentationId, Web::CompositorContextId, bool added, ReadonlySpan<i32> bitmap_ids, ReadonlySpan<void*> images);void retire_published_stores(PresentationId, Web::CompositorContextId, ReadonlySpan<i32> bitmap_ids);bool take_registered_image_frames(Web::CompositorContextId, ReadonlySpan<u64> image_frame_ids);@@ -244,13 +228,10 @@ private:void finish_staged_rasterization(WebContentClientId, u64 token);void report_live_content(Web::CompositorContextId, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*));Optional<RemoteLayer::Content> remote_layer_content(PresentedContext&, RustFFI::MediaKind, u64 media_id);- bool remote_layer_can_show(Web::CompositorContextId, RustFFI::MediaKind, u64 media_id, RustFFI::FfiSublayerPlacement const&, double device_pixel_ratio);+ bool remote_layer_can_show(RemoteLayer&, Web::CompositorContextId, RustFFI::MediaKind, u64 media_id, RustFFI::FfiSublayerPlacement const&, double device_pixel_ratio);Vector<RemoteSublayer>* build_sublayers(Web::CompositorContextId, ReadonlySpan<RustFFI::FfiSublayer>);- WindowServer::FrameHandOff frame_hand_off(Web::CompositorContextId);u64 submit_frame(Gfx::PaintingSurface*);void hand_off_once_gpu_work_is_scheduled(u64 token);- Optional<PresentationId> show_frame_in_remote_layer(Web::CompositorContextId, RustFFI::FfiRemoteLayerFrame const&, NonnullOwnPtr<Vector<RemoteSublayer>>);- void stop_showing_in_remote_layer(Web::CompositorContextId);void release_store_later(Web::CompositorContextId, i32 bitmap_id);void gpu_work_finished(u64 token);void schedule_gpu_completion_check();@@ -303,7 +284,7 @@ private:u64 m_next_screenshot_preparation_id { 1 };u64 m_next_web_content_client_id { 1 };HashMap<WebContentClientId, CompositorStateWebContentClient*> m_web_content_clients;- HashMap<Web::CompositorContextId, HashMap<ContextTimer, NonnullRefPtr<Core::Timer>>> m_context_timers;+ HashMap<u64, NonnullRefPtr<Core::Timer>> m_timers;RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;CanvasSurfaceRegistry m_canvas_surface_registry;@@ -321,32 +302,6 @@ private:u64 m_next_presentation_id { 1 };HashMap<PresentationId, CompositorStateClient*> m_presentations_by_id;- 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;- // The size the page laid out the frame on display at, if it is the size of the frame.- Optional<Gfx::IntSize> size_of_shown_frame_laid_out_by_page;- };-- struct SynchronizedResize {- u64 remote_layer_id { 0 };- u64 token { 0 };- Optional<Gfx::IntSize> awaited_size;- bool frame_is_held { false };- };- RemoteLayerState* remote_layer_showing(Web::CompositorContextId);- void report_held_synchronized_resize_frames(u64 remote_layer_id);- void release_synchronized_resize_hold();- Vector<SynchronizedResize> m_synchronized_resizes;- Vector<NonnullRefPtr<WindowServer>> m_window_servers_holding_changes;- RefPtr<Core::Timer> m_synchronized_resize_hold_timeout;- 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 761ea3f0540..e51070f2ea2 100644--- a/Services/Compositor/ConnectionFromClient.cpp+++ b/Services/Compositor/ConnectionFromClient.cpp@@ -65,7 +65,6 @@ void ConnectionFromClient::connect_video_presentation(i32 web_content_connectionMessages::CompositorControlServer::CreatePresentationConnectionResponse ConnectionFromClient::create_presentation_connection(bool synthesizes_scroll_momentum, bool scrolls_elastically, Optional<u64> gpu_presentation_adapter_luid){auto paired_transport = MUST(IPC::Transport::create_paired());- auto presentation_id = m_next_presentation_id++;// NB: The capabilities come with the connection, so the first backing stores of a context bound to it match them.auto capabilities = CompositorState::PresentationCapabilities {.synthesizes_scroll_momentum = synthesizes_scroll_momentum,@@ -73,6 +72,7 @@ Messages::CompositorControlServer::CreatePresentationConnectionResponse Connecti.gpu_presentation_adapter_luid = gpu_presentation_adapter_luid,};auto connection = ConnectionFromPresentation::construct(move(paired_transport.local), m_compositor_state, capabilities);+ auto presentation_id = connection->presentation_id().value();connection->set_on_death([this, presentation_id] {m_presentation_connections.remove(presentation_id);});@@ -90,33 +90,14 @@ 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)+ErrorOr<OwnPtr<IPC::MessageBuffer>> ConnectionFromClient::handle_raw(IPC::RawMessage& message){- 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 Compositing::RemoteLayerHostHandle {};- }- 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::set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within)-{- if (fit_within.has_value() && fit_within->is_empty()) {- did_misbehave("Empty size for a remote layer to fit frames within");- return;+ auto outcome = m_compositor_state->handle_message_from_control(message);+ if (outcome.misbehavior.has_value()) {+ did_misbehave(outcome.misbehavior->characters());+ return nullptr;}- m_compositor_state->set_remote_layer_fit(remote_layer_id, fit_within);+ return move(outcome.response);}void ConnectionFromClient::create_context(Web::CompositorContextId context_id, Optional<u64> page_id, i32 web_content_connection_id)diff --git a/Services/Compositor/ConnectionFromClient.h b/Services/Compositor/ConnectionFromClient.hindex abca639f594..b95b8920997 100644--- a/Services/Compositor/ConnectionFromClient.h+++ b/Services/Compositor/ConnectionFromClient.h@@ -36,13 +36,7 @@ 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 set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within) override;- virtual void begin_synchronized_resize(u64 remote_layer_id, u64 token) override { m_compositor_state->begin_synchronized_resize(remote_layer_id, token); }- virtual void await_synchronized_resize_frame(u64 remote_layer_id, u64 token, Gfx::IntSize size) override { m_compositor_state->await_synchronized_resize_frame(remote_layer_id, token, size); }- virtual void commit_synchronized_resize(u64 remote_layer_id, u64 token) override { m_compositor_state->commit_synchronized_resize(remote_layer_id, token); }+ virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage&) 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;@@ -57,7 +51,6 @@ private:HashMap<i32, NonnullRefPtr<ConnectionFromWebContent>> m_web_content_connections;NonnullRefPtr<CompositorState> m_compositor_state;HashMap<u64, NonnullRefPtr<ConnectionFromPresentation>> m_presentation_connections;- u64 m_next_presentation_id { 1 };};}diff --git a/Services/Compositor/ConnectionFromPresentation.h b/Services/Compositor/ConnectionFromPresentation.hindex eeafe21d880..b80808e93bd 100644--- a/Services/Compositor/ConnectionFromPresentation.h+++ b/Services/Compositor/ConnectionFromPresentation.h@@ -25,18 +25,16 @@ public:void set_on_death(Function<void()> on_death) { m_on_death = move(on_death); }+ virtual PresentationId presentation_id() const override { return m_presentation_id; }+private:ConnectionFromPresentation(NonnullOwnPtr<IPC::Transport>, NonnullRefPtr<CompositorState>, CompositorState::PresentationCapabilities);virtual void die() override;-- virtual PresentationId presentation_id() const override { return m_presentation_id; }virtual void post_message_to_presentation(IPC::MessageBuffer&) override;virtual void did_allocate_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage>&& backing_stores) override;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_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) override { async_did_hold_synchronized_resize_frame(remote_layer_id, token); }- virtual void did_commit_synchronized_resize(u64 remote_layer_id, u64 token) override { async_did_commit_synchronized_resize(remote_layer_id, token); }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/Rust/build.rs b/Services/Compositor/Rust/build.rsindex a99dc685126..f93c9f55f87 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -80,6 +80,7 @@ fn main() -> Result<(), Box<dyn Error>> {"src/core/presenting.rs","src/core/mod.rs","src/backing_stores.rs",+ "src/cpp_object.rs","src/surfaces/painting_surface.rs","src/surfaces/presentable_surface.rs",] {diff --git a/Services/Compositor/Rust/src/context_state/scrolling.rs b/Services/Compositor/Rust/src/context_state/scrolling.rsindex 9d0f8604bf9..e88cc8d6b31 100644--- a/Services/Compositor/Rust/src/context_state/scrolling.rs+++ b/Services/Compositor/Rust/src/context_state/scrolling.rs@@ -1132,8 +1132,9 @@ mod tests {}}- unsafe extern "C" fn set_timer(_: *mut c_void, _: u64, _: ContextTimer, _: i64) {}- unsafe extern "C" fn cancel_timer(_: *mut c_void, _: u64, _: ContextTimer) {}+ unsafe extern "C" fn set_timer(_: *mut c_void, _: u64, _: i64) {}+ unsafe extern "C" fn cancel_timer(_: *mut c_void, _: u64) {}+ unsafe extern "C" fn destroy_timer(_: *mut c_void, _: u64) {}unsafe extern "C" fn shape_overlay_label(_: *mut c_void,_: u64,@@ -1164,6 +1165,7 @@ mod tests {post_message_to_presentation: record_completions,set_timer,cancel_timer,+ destroy_timer,shape_overlay_label,})};diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex 1d96de66278..f68409f5bbd 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -13,6 +13,10 @@ use crate::host::{PresentationId, WebContentClientId};use libcompositing_rust::display_list::replay::{ReplayFrame, ReplaySelection, replay_display_list};use libcompositing_rust::display_list::storage::DisplayListStorage;use libcompositing_rust::display_list::window::RecordedWindow;+use libcompositing_rust::ipc_types::compositor_control_server::messages::{+ AwaitSynchronizedResizeFrame, BeginSynchronizedResize, CommitSynchronizedResize, CreateRemoteLayer,+ CreateRemoteLayerResponse, DestroyRemoteLayer, SetRemoteLayerFit, ShowContextInRemoteLayer,+};use libcompositing_rust::ipc_types::compositor_presentation_client::messages::DidNotDispatchInputEvent;use libcompositing_rust::ipc_types::compositor_presentation_server::messages::{HandleAndDispatchKeyEvent, HandleAndDispatchMouseEvent, HandleAndDispatchPinchEvent,@@ -29,8 +33,9 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,};use libcompositing_rust::ipc_types::{+ Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind,Compositing_WheelEventAnswer as WheelEventAnswer, Compositing_WheelStepLetThrough as WheelStepLetThrough,- SharedDisplayList, compositor_presentation_server, compositor_web_content_server,+ SharedDisplayList, compositor_control_server, compositor_presentation_server, compositor_web_content_server,};use libcompositing_rust::scrolling::async_scrolling_state::AsyncScrollOperationID;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, DisplayList};@@ -39,7 +44,7 @@ use libcompositing_rust::scrolling::{PinchEvent, ScrollRequest,};use libcompositing_rust::time::MonotonicTime;-use libgfx_rust::FloatPoint;+use libgfx_rust::{FloatPoint, IntSize};use libipc_rust::Misbehavior;use std::io::Write;use std::rc::Rc;@@ -688,3 +693,67 @@ impl compositor_presentation_server::Stub for MessagesFromPresentation<'_> {Ok(())}}++pub struct MessagesFromControl<'a> {+ pub core: &'a CompositorCore,+ pub now: MonotonicTime,+}++impl compositor_control_server::Stub for MessagesFromControl<'_> {+ fn create_remote_layer(&mut self, message: CreateRemoteLayer) -> Result<CreateRemoteLayerResponse, Misbehavior> {+ let host_handle = self+ .core+ .create_remote_layer(PresentationId(message.presentation_id), message.remote_layer_id)+ .unwrap_or_else(|| {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Ignoring remote layer {} for presentation {}, which is already gone",+ message.remote_layer_id,+ message.presentation_id+ );+ Compositing_RemoteLayerHostHandle {+ kind: Compositing_RemoteLayerHostKind::None,+ id: 0,+ }+ });+ Ok(CreateRemoteLayerResponse { host_handle })+ }++ fn destroy_remote_layer(&mut self, message: DestroyRemoteLayer) -> Result<(), Misbehavior> {+ self.core.destroy_remote_layer(message.remote_layer_id, self.now);+ Ok(())+ }++ fn show_context_in_remote_layer(&mut self, message: ShowContextInRemoteLayer) -> Result<(), Misbehavior> {+ self.core+ .show_context_in_remote_layer(message.remote_layer_id, message.context_id, self.now);+ Ok(())+ }++ fn set_remote_layer_fit(&mut self, message: SetRemoteLayerFit) -> Result<(), Misbehavior> {+ if message.fit_within.is_some_and(IntSize::is_empty) {+ return Err(Misbehavior("Empty size for a remote layer to fit frames within"));+ }+ self.core+ .set_remote_layer_fit(message.remote_layer_id, message.fit_within);+ Ok(())+ }++ fn begin_synchronized_resize(&mut self, message: BeginSynchronizedResize) -> Result<(), Misbehavior> {+ self.core+ .begin_synchronized_resize(message.remote_layer_id, message.token);+ Ok(())+ }++ fn await_synchronized_resize_frame(&mut self, message: AwaitSynchronizedResizeFrame) -> Result<(), Misbehavior> {+ self.core+ .await_synchronized_resize_frame(message.remote_layer_id, message.token, message.size);+ Ok(())+ }++ fn commit_synchronized_resize(&mut self, message: CommitSynchronizedResize) -> Result<(), Misbehavior> {+ self.core+ .commit_synchronized_resize(message.remote_layer_id, message.token);+ Ok(())+ }+}diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex fe619bf3cae..b32a2016f01 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -9,17 +9,19 @@mod input;pub mod messages;pub mod presenting;+mod remote_layers;mod testing;mod wheel;use crate::context_state::{ContextState, ContextUpdateResult, FirstWheelStepRoute};use crate::host::{ContextTimer, DisplayTickInputs, DisplayTickResult, Host, PendingFrame, PresentRequest, PresentScheduling,- PresentationId, WebContentClientId,+ PresentationId, Timer, WebContentClientId,};use crate::overlays::UIOverlays;use crate::presenting::ContextPresenting;use crate::raster_host::RasterHost;+use crate::remote_layers::RemoteLayers;use crate::surfaces::painting_surface::PaintingSurface;use crate::wheel_gesture_routing::WheelGestureIdAllocator;use libcompositing_rust::ipc_types::Compositing_ContextVisibility as ContextVisibility;@@ -47,6 +49,7 @@ pub struct CompositorCore {wheel_gesture_id_allocator: Rc<WheelGestureIdAllocator>,scrollbars_always_shown: bool,display_list_chunk_stores: RefCell<crate::display_list_chunk_stores::DisplayListChunkStores>,+ remote_layers: RefCell<RemoteLayers>,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -119,6 +122,7 @@ impl CompositorCore {wheel_gesture_id_allocator: Rc::new(WheelGestureIdAllocator::default()),scrollbars_always_shown,display_list_chunk_stores: RefCell::default(),+ remote_layers: RefCell::default(),}}@@ -198,6 +202,9 @@ impl CompositorCore {}self.contexts.remove(&context_id);self.presenting.remove(&context_id);+ self.remote_layers.borrow_mut().context_destroyed(context_id);+ self.host+ .destroy_timers(|timer| matches!(timer, Timer::Context(id, _) if *id == context_id));self.display_list_chunk_stores.borrow_mut().forget_context(context_id);self.update_scroll_capabilities();self.raster@@ -349,12 +356,25 @@ impl CompositorCore {let _entered = self.enter();self.presentations.borrow_mut().insert(presentation_id, capabilities);+ self.remote_layers+ .borrow_mut()+ .register_presentation(presentation_id, &self.raster);}// Leaves every context bound to the presentation unbound.pub fn unregister_presentation(&self, presentation_id: PresentationId, now: MonotonicTime) {let _entered = self.enter();+ let was_holding_changes = self.remote_layers.borrow().is_holding_changes();+ let stopped = self+ .remote_layers+ .borrow_mut()+ .unregister_presentation(presentation_id, &self.raster);+ self.update_synchronized_resize_hold_timer(was_holding_changes);+ for context_id in stopped {+ self.stop_showing_context_in_remote_layer(context_id, now);+ }+let bound_context_ids: Vec<CompositorContextId> = self.contexts.iter()@@ -453,17 +473,6 @@ impl CompositorCore {self.finish_entry(now);}- pub fn set_shown_in_remote_layer(&self, context_id: CompositorContextId, shown: bool, now: MonotonicTime) {- let _entered = self.enter();-- if shown {- self.start_showing_context_in_remote_layer(context_id, now);- } else {- self.stop_showing_context_in_remote_layer(context_id, now);- }- self.finish_entry(now);- }-pub fn set_display_metadata(&self,context_id: CompositorContextId,@@ -799,9 +808,18 @@ impl CompositorCore {became_visible}- pub fn timer_fired(&self, context_id: CompositorContextId, timer: ContextTimer, now: MonotonicTime) {+ pub fn timer_fired(&self, number: u64, now: MonotonicTime) {let _entered = self.enter();+ match self.host.timer_of_number(number) {+ Some(Timer::Context(context_id, timer)) => self.context_timer_fired(context_id, timer, now),+ Some(Timer::SynchronizedResizeHold) => self.synchronized_resize_hold_timed_out(),+ None => {}+ }+ self.finish_entry(now);+ }++ fn context_timer_fired(&self, context_id: CompositorContextId, timer: ContextTimer, now: MonotonicTime) {let Some(context) = self.context_if_present(context_id) else {return;};@@ -826,7 +844,6 @@ impl CompositorCore {}}}- self.finish_entry(now);}pub(super) fn context_still_nested_in(diff --git a/Services/Compositor/Rust/src/core/presenting.rs b/Services/Compositor/Rust/src/core/presenting.rsindex 58dfa31df3f..60c74ac6db5 100644--- a/Services/Compositor/Rust/src/core/presenting.rs+++ b/Services/Compositor/Rust/src/core/presenting.rs@@ -9,9 +9,10 @@use super::CompositorCore;use crate::backing_stores::{StorePublication, StoreResizeOutcome};use crate::context_state::ContextState;-use crate::host::{PendingFrame, PresentScheduling, PresentationId};+use crate::host::{PendingFrame, PresentScheduling};use crate::presenting::{ContextPresenting, NestedContexts, PresentingEnvironment};-use crate::raster_host::{FfiRemoteLayerFrame, FrameHandOff, SublayersHandle};+use crate::raster_host::{FfiRemoteLayerFrame, FrameHandOff, RasterHost, SublayersHandle};+use crate::remote_layers::{RemoteLayer, ResizeNotice, WindowServerObject};use crate::surfaces::painting_surface::PaintingSurface;use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::display_list::replay::{CompositedContexts, NoCompositedContexts, ResolvedCompositedContext};@@ -128,6 +129,11 @@ impl CompositorCore {) -> PresentingEnvironment<'a> {PresentingEnvironment {context_id,+ remote_layer: self+ .remote_layers+ .borrow()+ .layer_showing(context_id)+ .map(RemoteLayer::showing_layer),raster: &self.raster,host: &self.host,now,@@ -460,7 +466,7 @@ impl CompositorCore {let hands_off_early = presenting.presents_to_client&& self.gpu.has_gpu&& !presenting.presents_from_cpu_memory- && self.raster.frame_hand_off(context_id) == FrameHandOff::OnceGpuWorkIsScheduled;+ && self.frame_hand_off(context_id) == FrameHandOff::OnceGpuWorkIsScheduled;drop(presenting);if hands_off_early {self.raster.hand_off_once_gpu_work_is_scheduled(token);@@ -577,6 +583,21 @@ impl CompositorCore {fn show_frame_in_remote_layer(&self, delivery: &mut Delivery, viewport_size: IntSize, now: MonotonicTime) {let context_id = delivery.context_id;+ let shown_in = self+ .remote_layers+ .borrow()+ .layer_showing(context_id)+ .map(|remote_layer| {+ (+ remote_layer.showing_layer(),+ remote_layer.presentation(),+ remote_layer.fit_within(),+ )+ });+ let Some((remote_layer, presentation, fit_within)) = shown_in else {+ self.stop_showing_context_in_remote_layer(context_id, now);+ return;+ };let presenting = self.presenting_of(context_id);let laid_out_by_page = presenting.as_ref()@@ -601,20 +622,58 @@ impl CompositorCore {store: store.as_ref().map_or(std::ptr::null(), |store| store.as_ffi()),painted_size: viewport_size,device_pixel_ratio: delivery.device_pixel_ratio,- laid_out_by_page,+ has_fit_within: fit_within.is_some(),+ fit_within: fit_within.unwrap_or_default(),};- let shown = self.raster.show_frame_in_remote_layer(context_id, &frame, sublayers);- match shown {- None => self.stop_showing_context_in_remote_layer(context_id, now),- Some(presentation_id) => self.host.post_to_presentation(- PresentationId(presentation_id),- compositor_presentation_client::messages::DidPresentFrameInRemoteLayer {- context_id,- content_rect: delivery.viewport_rect,- damage_rect: delivery.damage_rect,- device_pixel_ratio: delivery.device_pixel_ratio,+ if !self+ .raster+ .remote_layer_show_frame(&remote_layer.layer, &frame, sublayers)+ {+ self.remote_layers.borrow_mut().stop_showing_context(context_id);+ self.stop_showing_context_in_remote_layer(context_id, now);+ return;+ }+ let held = self+ .remote_layers+ .borrow_mut()+ .did_show_frame(context_id, viewport_size, laid_out_by_page);+ self.tell_of_held_synchronized_resize_frames(held);+ self.host.post_to_presentation(+ presentation,+ compositor_presentation_client::messages::DidPresentFrameInRemoteLayer {+ context_id,+ content_rect: delivery.viewport_rect,+ damage_rect: delivery.damage_rect,+ device_pixel_ratio: delivery.device_pixel_ratio,+ },+ );+ }++ pub(super) fn tell_of_held_synchronized_resize_frames(&self, held: Vec<ResizeNotice>) {+ for notice in held {+ self.host.post_to_presentation(+ notice.presentation,+ compositor_presentation_client::messages::DidHoldSynchronizedResizeFrame {+ remote_layer_id: notice.remote_layer_id,+ token: notice.token,},- ),+ );+ }+ }++ fn window_server_showing(&self, context_id: CompositorContextId) -> Option<Rc<WindowServerObject>> {+ self.remote_layers+ .borrow()+ .layer_showing(context_id)+ .map(|remote_layer| remote_layer.showing_layer().window_server)+ }++ pub(super) fn frame_hand_off(&self, context_id: CompositorContextId) -> FrameHandOff {+ match self.remote_layers.borrow().layer_showing(context_id) {+ Some(remote_layer) => self+ .raster+ .window_server_frame_hand_off(&remote_layer.showing_layer().window_server),+ None => RasterHost::frame_hand_off_through_presentation(),}}@@ -716,7 +775,7 @@ impl CompositorCore {StoreResizeOutcome::Unchanged | StoreResizeOutcome::ReallocatedOffscreen => {}StoreResizeOutcome::ReallocatedForViewer => self.present_current_frame(context_id, now),StoreResizeOutcome::Failed => {- self.raster.stop_showing_in_remote_layer(context_id);+ self.remote_layers.borrow_mut().stop_showing_context(context_id);self.stop_showing_context_in_remote_layer(context_id, now);}}@@ -742,10 +801,12 @@ impl CompositorCore {let publishing_presentation = bound_presentation.filter(|_| presenting.store_publication() == StorePublication::Published).map(|presentation| presentation.0);+ let window_server = self.window_server_showing(context_id);if presenting.add_store_if_window_server_still_reads_every_released_store(&self.raster,context_id,publishing_presentation,+ window_server.as_deref(),) {presenting.schedule_surplus_store_retirement(context_id, &self.host);}@@ -811,10 +872,12 @@ impl CompositorCore {let publishing_presentation = bound_presentation.filter(|_| presenting.borrow().store_publication() == StorePublication::Published).map(|presentation| presentation.0);+ let window_server = self.window_server_showing(context_id);if presenting.borrow_mut().restore_stores_retired_while_hidden(&self.raster,context_id,publishing_presentation,+ window_server.as_deref(),) {return;}diff --git a/Services/Compositor/Rust/src/core/remote_layers.rs b/Services/Compositor/Rust/src/core/remote_layers.rsnew file mode 100644index 00000000000..64b1b91789b--- /dev/null+++ b/Services/Compositor/Rust/src/core/remote_layers.rs@@ -0,0 +1,154 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the presentations ask of the remote layers that show their root contexts.++use super::CompositorCore;+use crate::host::{PresentationId, Timer};+use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::ipc_types::{Compositing_RemoteLayerHostHandle, compositor_presentation_client};+use libcompositing_rust::time::{Duration, MonotonicTime};+use libgfx_rust::IntSize;+use std::io::Write;++// A presentation that never commits its resize, as one that crashed, would otherwise freeze every window of the browser.+const SYNCHRONIZED_RESIZE_HOLD_LIMIT: Duration = Duration::from_milliseconds(1000);++impl CompositorCore {+ pub fn create_remote_layer(+ &self,+ presentation_id: PresentationId,+ remote_layer_id: u64,+ ) -> Option<Compositing_RemoteLayerHostHandle> {+ let _entered = self.enter();++ if !self.presentations.borrow().contains_key(&presentation_id) {+ return None;+ }+ Some(+ self.remote_layers+ .borrow_mut()+ .create_remote_layer(presentation_id, remote_layer_id, &self.raster),+ )+ }++ pub fn destroy_remote_layer(&self, remote_layer_id: u64, now: MonotonicTime) {+ let _entered = self.enter();++ let was_holding_changes = self.remote_layers.borrow().is_holding_changes();+ let stopped = self+ .remote_layers+ .borrow_mut()+ .destroy_remote_layer(remote_layer_id, &self.raster);+ self.update_synchronized_resize_hold_timer(was_holding_changes);+ if let Some(context_id) = stopped {+ self.stop_showing_context_in_remote_layer(context_id, now);+ }+ self.finish_entry(now);+ }++ pub fn show_context_in_remote_layer(+ &self,+ remote_layer_id: u64,+ context_id: Option<CompositorContextId>,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ let change =+ self.remote_layers+ .borrow_mut()+ .show_context_in_remote_layer(remote_layer_id, context_id, |context_id| {+ let is_root_context = self+ .context_if_present(context_id)+ .is_some_and(|context| context.borrow().presents_to_client());+ if !is_root_context {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Ignoring context {} for remote layer {}, as it is not a root context",+ context_id.0,+ remote_layer_id+ );+ }+ is_root_context+ });+ if let Some(stopped) = change.stopped {+ self.stop_showing_context_in_remote_layer(stopped, now);+ }+ if let Some(started) = change.started {+ self.start_showing_context_in_remote_layer(started, now);+ }+ self.finish_entry(now);+ }++ pub fn set_remote_layer_fit(&self, remote_layer_id: u64, fit_within: Option<IntSize>) {+ let _entered = self.enter();++ self.remote_layers+ .borrow_mut()+ .set_remote_layer_fit(remote_layer_id, fit_within, &self.raster);+ }++ pub fn begin_synchronized_resize(&self, remote_layer_id: u64, token: u64) {+ let _entered = self.enter();++ let was_holding_changes = self.remote_layers.borrow().is_holding_changes();+ self.remote_layers+ .borrow_mut()+ .begin_synchronized_resize(remote_layer_id, token, &self.raster);+ self.update_synchronized_resize_hold_timer(was_holding_changes);+ }++ pub fn await_synchronized_resize_frame(&self, remote_layer_id: u64, token: u64, size: IntSize) {+ let _entered = self.enter();++ let held = self+ .remote_layers+ .borrow_mut()+ .await_synchronized_resize_frame(remote_layer_id, token, size);+ self.tell_of_held_synchronized_resize_frames(held);+ }++ pub fn commit_synchronized_resize(&self, remote_layer_id: u64, token: u64) {+ let _entered = self.enter();++ let was_holding_changes = self.remote_layers.borrow().is_holding_changes();+ let committed =+ self.remote_layers+ .borrow_mut()+ .commit_synchronized_resize(remote_layer_id, token, &self.raster);+ self.update_synchronized_resize_hold_timer(was_holding_changes);+ if let Some(notice) = committed {+ self.host.post_to_presentation(+ notice.presentation,+ compositor_presentation_client::messages::DidCommitSynchronizedResize {+ remote_layer_id: notice.remote_layer_id,+ token: notice.token,+ },+ );+ }+ }++ pub(super) fn synchronized_resize_hold_timed_out(&self) {+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Releasing the window resize that was never committed"+ );+ self.remote_layers+ .borrow_mut()+ .release_synchronized_resize_hold(&self.raster);+ }++ pub(super) fn update_synchronized_resize_hold_timer(&self, was_holding_changes: bool) {+ let is_holding_changes = self.remote_layers.borrow().is_holding_changes();+ if is_holding_changes && !was_holding_changes {+ self.host+ .schedule(Timer::SynchronizedResizeHold, SYNCHRONIZED_RESIZE_HOLD_LIMIT);+ } else if !is_holding_changes && was_holding_changes {+ self.host.unschedule(Timer::SynchronizedResizeHold);+ }+ }+}diff --git a/Services/Compositor/Rust/src/cpp_object.rs b/Services/Compositor/Rust/src/cpp_object.rsnew file mode 100644index 00000000000..bb7d2fd1284--- /dev/null+++ b/Services/Compositor/Rust/src/cpp_object.rs@@ -0,0 +1,70 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A C++ object that the core owns, such as a window server or a remote layer, which it only hands back to the C++ that+//! made it and destroys with the function that came with it.++use std::ffi::c_void;+use std::ptr::NonNull;++/// A C++ object as the C++ side hands it over, or null for none.+#[repr(C)]+pub struct FfiCppObject {+ pub object: *mut c_void,+ pub destroy: Option<unsafe extern "C" fn(*mut c_void)>,+}++impl Default for FfiCppObject {+ fn default() -> Self {+ Self {+ object: std::ptr::null_mut(),+ destroy: None,+ }+ }+}++pub struct CppObject {+ object: NonNull<c_void>,+ destroy: unsafe extern "C" fn(*mut c_void),+}++impl CppObject {+ /// # Safety+ ///+ /// A non-null object must be live and handed over, and its destroy function must destroy it.+ pub unsafe fn adopt(object: FfiCppObject) -> Option<CppObject> {+ Some(CppObject {+ object: NonNull::new(object.object)?,+ destroy: object.destroy.expect("a C++ object comes with its destroy function"),+ })+ }++ pub fn as_ptr(&self) -> *mut c_void {+ self.object.as_ptr()+ }+}++impl Drop for CppObject {+ fn drop(&mut self) {+ // SAFETY: This owns the object.+ unsafe { (self.destroy)(self.object.as_ptr()) };+ }+}++#[cfg(test)]+pub mod testing {+ use super::*;++ unsafe extern "C" fn destroy_nothing(_: *mut c_void) {}++ /// An object that stands for one of the C++ side, which is told apart by its address.+ pub fn object_for_testing(address: usize) -> CppObject {+ CppObject {+ object: NonNull::new(address as *mut c_void).expect("an address"),+ destroy: destroy_nothing,+ }+ }+}diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex 2a1d1caca94..93e20e91da4 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -7,10 +7,10 @@//! The entry points of the compositor's logic for the C++ of the Compositor around it, which calls them from its event//! loop only.-use crate::core::messages::{MessagesFromPresentation, MessagesFromWebContent};+use crate::core::messages::{MessagesFromControl, MessagesFromPresentation, MessagesFromWebContent};use crate::core::presenting::{GpuBackend, PresentationCapabilities};use crate::core::{CompositorCore, ContextOwnerCheckResult};-use crate::host::{ContextTimer, FfiCompositorCoreHost, Host, PresentationId, WebContentClientId};+use crate::host::{FfiCompositorCoreHost, Host, PresentationId, WebContentClientId};use crate::overlays::{PausedDebuggerOverlayAction, PausedDebuggerOverlayState, PictureInPictureControl, PictureInPictureControlsState,UIOverlays,@@ -19,7 +19,8 @@ use crate::raster_host::{FfiRasterHost, RasterHost};use crate::surfaces::painting_surface::PaintingSurface;use libcompositing_rust::display_list::commands::CompositorContextId;use libcompositing_rust::ipc_types::{- Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,+ Compositing_ContextVisibility as ContextVisibility, compositor_control_server, compositor_presentation_server,+ compositor_web_content_server,};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{IntRect, IntSize};@@ -250,16 +251,6 @@ pub extern "C" fn compositor_core_bind_presentation();}-#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_set_shown_in_remote_layer(- core: &CompositorCore,- context_id: u64,- shown: bool,- now_nanoseconds: i64,-) {- core.set_shown_in_remote_layer(CompositorContextId(context_id), shown, time(now_nanoseconds));-}-#[unsafe(no_mangle)]pub extern "C" fn compositor_core_set_display_metadata(core: &CompositorCore,@@ -497,6 +488,28 @@ pub unsafe extern "C" fn compositor_core_handle_presentation_message(core.finish_message(time(now_nanoseconds));}+/// Takes a message of the CompositorControlServer endpoint that is marked [RustReceiver].+///+/// # Safety+///+/// `message` must be one `IPC::RawMessage::hand_to_rust()` made.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_handle_control_message(+ core: &CompositorCore,+ message: RawMessage<'_>,+ now_nanoseconds: i64,+) {+ let mut stub = MessagesFromControl {+ core,+ now: time(now_nanoseconds),+ };+ // SAFETY: The caller hands over a message of that endpoint.+ unsafe {+ message.hand_to(|bytes, attachments| compositor_control_server::dispatch(&mut stub, bytes, attachments));+ };+ core.finish_message(time(now_nanoseconds));+}+/// What the browser draws over a context's page. An action or control is none where it is out of range.#[repr(C)]pub struct FfiUIOverlays<'a> {@@ -531,17 +544,8 @@ pub extern "C" fn compositor_core_set_visibility(}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_timer_fired(- core: &CompositorCore,- context_id: u64,- timer: ContextTimer,- now_nanoseconds: i64,-) {- core.timer_fired(- CompositorContextId(context_id),- timer,- MonotonicTime::from_nanoseconds(now_nanoseconds),- );+pub extern "C" fn compositor_core_timer_fired(core: &CompositorCore, timer_number: u64, now_nanoseconds: i64) {+ core.timer_fired(timer_number, MonotonicTime::from_nanoseconds(now_nanoseconds));}#[unsafe(no_mangle)]diff --git a/Services/Compositor/Rust/src/host.rs b/Services/Compositor/Rust/src/host.rsindex fc8b5267e74..7dd719cf960 100644--- a/Services/Compositor/Rust/src/host.rs+++ b/Services/Compositor/Rust/src/host.rs@@ -14,6 +14,7 @@ use libgfx_rust::IntRect;use libipc_rust::cpp_connection::RawAttachment;use libipc_rust::wire::EndpointMessage;use std::cell::RefCell;+use std::collections::HashMap;use std::ffi::c_void;#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]@@ -22,8 +23,7 @@ pub struct WebContentClientId(pub u64);#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]pub struct PresentationId(pub u64);-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub enum ContextTimer {ScrollStepGestureInput,ScrollbarPaging,@@ -34,6 +34,22 @@ pub enum ContextTimer {HiddenStoreRetirement,}+/// A timer of the compositor, which fires once after the delay it is set to, until it is set again.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Timer {+ Context(CompositorContextId, ContextTimer),+ /// Releases what the window servers hold off screen for a window resize that its presentation never commits.+ SynchronizedResizeHold,+}++// The host knows a timer by a number of its own, which stays the same for as long as the timer exists.+#[derive(Default)]+struct TimerNumbers {+ next_number: u64,+ number_of_timer: HashMap<Timer, u64>,+ timer_of_number: HashMap<u64, Timer>,+}+#[derive(Clone, Copy, Debug, PartialEq)]pub struct PendingFrame {pub viewport_rect: IntRect,@@ -116,8 +132,12 @@ pub struct FfiCompositorCoreHost {unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),pub post_message_to_presentation:unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),- pub set_timer: unsafe extern "C" fn(*mut c_void, u64, ContextTimer, i64),- pub cancel_timer: unsafe extern "C" fn(*mut c_void, u64, ContextTimer),+ /// Arguments: the number of the timer, and the delay in nanoseconds. Setting a timer again replaces its delay, and+ /// a timer that fires calls `compositor_core_timer_fired` with its number.+ pub set_timer: unsafe extern "C" fn(*mut c_void, u64, i64),+ pub cancel_timer: unsafe extern "C" fn(*mut c_void, u64),+ /// The timer is not set again, so the host forgets it.+ pub destroy_timer: unsafe extern "C" fn(*mut c_void, u64),/// Arguments: the context, whether a font family is given, the font family, the device pixel ratio, the text, and/// what receives the shaped label, which is not called where no font draws the label.pub shape_overlay_label: unsafe extern "C" fn(@@ -134,14 +154,22 @@ pub struct FfiCompositorCoreHost {type PostEncodedMessage = unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>);-pub struct Host(FfiCompositorCoreHost, RefCell<Vec<CompositorContextId>>);+pub struct Host {+ ffi: FfiCompositorCoreHost,+ display_tick_requests: RefCell<Vec<CompositorContextId>>,+ timer_numbers: RefCell<TimerNumbers>,+}impl Host {/// # Safety////// `ffi.host` must outlive the `Host`, and none of its entry points may call back into the core.pub unsafe fn new(ffi: FfiCompositorCoreHost) -> Self {- Self(ffi, RefCell::new(Vec::new()))+ Self {+ ffi,+ display_tick_requests: RefCell::new(Vec::new()),+ timer_numbers: RefCell::default(),+ }}fn post<M: EndpointMessage>(&self, post_encoded_message: PostEncodedMessage, receiver_id: u64, message: M) {@@ -152,7 +180,7 @@ impl Host {// SAFETY: The host outlives this, copies the bytes and takes every attachment over.unsafe {post_encoded_message(- self.0.host,+ self.ffi.host,receiver_id,ak::Span::new(&bytes),ak::Span::new(&raw_attachments),@@ -162,42 +190,100 @@ impl Host {/// A message for a client that is gone is dropped.pub fn post_to_web_content<M: EndpointMessage>(&self, client_id: WebContentClientId, message: M) {- self.post(self.0.post_message_to_web_content, client_id.0, message);+ self.post(self.ffi.post_message_to_web_content, client_id.0, message);}/// A client without a render clock channel hears nothing.pub fn post_to_render_clock_of_web_content<M: EndpointMessage>(&self, client_id: WebContentClientId, message: M) {- self.post(self.0.post_message_to_render_clock_of_web_content, client_id.0, message);+ self.post(+ self.ffi.post_message_to_render_clock_of_web_content,+ client_id.0,+ message,+ );}/// A message for a presentation that is gone is dropped.pub fn post_to_presentation<M: EndpointMessage>(&self, presentation_id: PresentationId, message: M) {- self.post(self.0.post_message_to_presentation, presentation_id.0, message);+ self.post(self.ffi.post_message_to_presentation, presentation_id.0, message);}/// Display ticks reach a context whose scroll and input logic says it needs animation frames, while it is visible./// The core asks for them once the call that wants them is done.pub fn request_display_ticks(&self, context_id: CompositorContextId) {- self.1.borrow_mut().push(context_id);+ self.display_tick_requests.borrow_mut().push(context_id);}/// The contexts that asked for display ticks since the last call.pub fn take_display_tick_requests(&self) -> Vec<CompositorContextId> {- std::mem::take(&mut *self.1.borrow_mut())+ std::mem::take(&mut *self.display_tick_requests.borrow_mut())}/// Each timer of a context fires once after the delay, and setting it again replaces the delay.pub fn set_timer(&self, context_id: CompositorContextId, timer: ContextTimer, delay: Duration) {- // SAFETY: The host outlives this.- unsafe { (self.0.set_timer)(self.0.host, context_id.0, timer, delay.nanoseconds()) };+ self.schedule(Timer::Context(context_id, timer), delay);}pub fn cancel_timer(&self, context_id: CompositorContextId, timer: ContextTimer) {+ self.unschedule(Timer::Context(context_id, timer));+ }++ pub fn schedule(&self, timer: Timer, delay: Duration) {+ let number = {+ let mut numbers = self.timer_numbers.borrow_mut();+ match numbers.number_of_timer.get(&timer) {+ Some(&number) => number,+ None => {+ numbers.next_number += 1;+ let number = numbers.next_number;+ numbers.number_of_timer.insert(timer, number);+ numbers.timer_of_number.insert(number, timer);+ number+ }+ }+ };+ // SAFETY: The host outlives this.+ unsafe { (self.ffi.set_timer)(self.ffi.host, number, delay.nanoseconds()) };+ }++ pub fn unschedule(&self, timer: Timer) {+ let Some(number) = self.timer_numbers.borrow().number_of_timer.get(&timer).copied() else {+ return;+ };// SAFETY: The host outlives this.- unsafe { (self.0.cancel_timer)(self.0.host, context_id.0, timer) };+ unsafe { (self.ffi.cancel_timer)(self.ffi.host, number) };+ }++ /// Forgets the timers that match, which are not set again.+ pub fn destroy_timers(&self, matches: impl Fn(&Timer) -> bool) {+ let numbers: Vec<u64> = {+ let mut timer_numbers = self.timer_numbers.borrow_mut();+ let TimerNumbers {+ number_of_timer,+ timer_of_number,+ ..+ } = &mut *timer_numbers;+ let numbers: Vec<u64> = timer_of_number+ .iter()+ .filter(|(_, timer)| matches(timer))+ .map(|(&number, _)| number)+ .collect();+ for number in &numbers {+ if let Some(timer) = timer_of_number.remove(number) {+ number_of_timer.remove(&timer);+ }+ }+ numbers+ };+ for number in numbers {+ // SAFETY: The host outlives this.+ unsafe { (self.ffi.destroy_timer)(self.ffi.host, number) };+ }+ }++ pub fn timer_of_number(&self, number: u64) -> Option<Timer> {+ self.timer_numbers.borrow().timer_of_number.get(&number).copied()}- /// Shapes the labels of the context's overlays, in fonts that the overlays' resources of the context then hold.pub fn overlay_label_shaper(&self, context_id: CompositorContextId) -> ContextOverlayLabelShaper<'_> {ContextOverlayLabelShaper { host: self, context_id }}@@ -231,8 +317,8 @@ impl OverlayLabelShaper for ContextOverlayLabelShaper<'_> {let mut label: Option<OverlayLabel> = None;// SAFETY: The host outlives this, shapes synchronously and never calls back into the core.unsafe {- (self.host.0.shape_overlay_label)(- self.host.0.host,+ (self.host.ffi.shape_overlay_label)(+ self.host.ffi.host,self.context_id.0,font_family.is_some(),ak::Span::new(font_family.unwrap_or_default().as_bytes()),diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex 032b7d1d423..faa89c303f2 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -20,6 +20,7 @@ pub mod backing_stores;pub mod context_scene;pub mod context_state;pub mod core;+pub mod cpp_object;pub mod display_list_chunk_stores;pub mod display_list_coverage_watch;pub mod elastic_overscroll_controller;@@ -31,6 +32,7 @@ pub mod keyboard_scroll_controller;pub mod overlays;pub mod presenting;pub mod raster_host;+pub mod remote_layers;pub mod scroll_fling_controller;pub mod scroll_snap_controller;pub mod scrollbar_controller;diff --git a/Services/Compositor/Rust/src/presenting/layers.rs b/Services/Compositor/Rust/src/presenting/layers.rsindex afbaea50efb..7125b42689e 100644--- a/Services/Compositor/Rust/src/presenting/layers.rs+++ b/Services/Compositor/Rust/src/presenting/layers.rs@@ -225,7 +225,11 @@ impl ContextPresenting {}LiveMedia::ImageFrame(_) | LiveMedia::CompositedContext(_) => return false,};+ let Some(remote_layer) = &env.remote_layer else {+ return false;+ };if !env.raster.remote_layer_can_show(+ &remote_layer.layer,env.context_id,kind,id,diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rsindex a634562b95a..aecec86a672 100644--- a/Services/Compositor/Rust/src/presenting/mod.rs+++ b/Services/Compositor/Rust/src/presenting/mod.rs@@ -16,6 +16,7 @@ use crate::backing_stores::{AllocationOutcome, BackingStores, Publication, Storeuse crate::frame_inputs::FrameInputs;use crate::host::{ContextTimer, Host, PendingFrame};use crate::raster_host::{FfiSublayer, PaintingResources, RasterHost, SurfaceBlend};+use crate::remote_layers::{ShowingLayer, WindowServerObject};use crate::surfaces::painting_surface::PaintingSurface;use crate::surfaces::presentable_surface::PresentableSurface;use damage::{PaintedFrame, StoreDamage};@@ -59,6 +60,8 @@ impl NestedContexts for NoCompositedContexts {/// What presenting a frame of a context works with besides the context's own state.pub struct PresentingEnvironment<'a> {pub context_id: CompositorContextId,+ /// The remote layer that shows the context, if one does.+ pub remote_layer: Option<ShowingLayer>,pub raster: &'a RasterHost,pub host: &'a Host,pub now: MonotonicTime,@@ -67,6 +70,14 @@ pub struct PresentingEnvironment<'a> {pub nested_contexts: &'a dyn NestedContexts,}+impl PresentingEnvironment<'_> {+ pub fn window_server_showing_context(&self) -> Option<&WindowServerObject> {+ self.remote_layer+ .as_ref()+ .map(|remote_layer| &*remote_layer.window_server)+ }+}+/// A frame drawn into a store, or for a frame that changes only what the window server shows above the frame on/// screen, into nothing.pub struct PreparedFrame {@@ -274,7 +285,8 @@ impl ContextPresenting {match self.backing_stores.allocate(allocation, publication, shares_gpu_images, &mut |kind, size| {- env.raster.create_store(env.context_id, kind, size)+ env.raster+ .create_store(env.context_id, kind, size, env.window_server_showing_context())}) {AllocationOutcome::Offscreen => StoreResizeOutcome::ReallocatedOffscreen,AllocationOutcome::Failed => StoreResizeOutcome::Failed,@@ -370,11 +382,12 @@ impl ContextPresenting {raster: &RasterHost,context_id: CompositorContextId,publishing_presentation: Option<u64>,+ window_server: Option<&WindowServerObject>,) -> bool {let Some(stores) = self.backing_stores.add_store_if_window_server_still_reads_every_released_store(&mut |kind, size| {- raster.create_store(context_id, kind, size)+ raster.create_store(context_id, kind, size, window_server)})else {return false;@@ -415,11 +428,11 @@ impl ContextPresenting {raster: &RasterHost,context_id: CompositorContextId,publishing_presentation: Option<u64>,+ window_server: Option<&WindowServerObject>,) -> bool {- let Some(stores) = self- .backing_stores- .add_stores_up_to_initial_count(&mut |kind, size| raster.create_store(context_id, kind, size))- else {+ let Some(stores) = self.backing_stores.add_stores_up_to_initial_count(&mut |kind, size| {+ raster.create_store(context_id, kind, size, window_server)+ }) else {return false;};Self::publish_added_stores(raster, context_id, publishing_presentation, stores);@@ -851,6 +864,7 @@ impl ContextPresenting {};let snapshot_env = PresentingEnvironment {nested_contexts: &NoCompositedContexts,+ remote_layer: env.remote_layer.clone(),..*env};self.composite_layers_above_base(&snapshot_env, &composited, &frame, source_rect);diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex 2f923c75c29..f550566482a 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -9,6 +9,8 @@//! submission, and the display ticks. None of these calls comes back into the core before it returns.use crate::backing_stores::{FfiNewStore, NewStore, Publication, SharedImageToPublish, StoreKind};+use crate::cpp_object::FfiCppObject;+use crate::remote_layers::{RemoteLayerHost, RemoteLayerObject, WindowServerObject};use crate::surfaces::painting_surface::PaintingSurface;use crate::surfaces::presentable_surface::PresentableSurface;use libcompositing_rust::display_list::commands::CompositorContextId;@@ -16,7 +18,9 @@ use libcompositing_rust::display_list::storage::{PackedChunkSize, ReceivedChunk, receive_packed_chunks_from_shared_memory,};use libcompositing_rust::host::FfiRasterPainter;-use libcompositing_rust::ipc_types::Core_AnonymousBuffer;+use libcompositing_rust::ipc_types::{+ Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind, Core_AnonymousBuffer,+};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{Color, FloatRect, IntRect, IntSize, ScalingMode};use std::collections::HashMap;@@ -146,8 +150,18 @@ pub struct FfiRemoteLayerFrame {pub store: *const PresentableSurface,pub painted_size: IntSize,pub device_pixel_ratio: f64,- /// Whether the page laid out the frame at the size it is painted at.- pub laid_out_by_page: bool,+ /// Where the frame is scaled to fit within the view, in device pixels, rather than shown at its own size.+ pub has_fit_within: bool,+ pub fit_within: IntSize,+}++/// How the presentation shows a remote layer: the kind of its host handle, which is that of+/// `Compositing::RemoteLayerHostKind`, and its id.+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct FfiRemoteLayerHostHandle {+ pub kind: u8,+ pub id: u64,}/// The entry points of the mechanism the core drives, and the object they are called on:@@ -183,7 +197,9 @@ pub struct FfiRasterHost {pub start_raster_cache_frame: unsafe extern "C" fn(*mut c_void, u64),/// Makes a store of the context, writing what it made. Answers false where none could be made.- pub create_store: unsafe extern "C" fn(*mut c_void, u64, StoreKind, IntSize, *mut FfiNewStore) -> bool,+ /// Arguments: the context, the kind and size of the store, the window server that shows it, if one does, and where+ /// the store is written.+ pub create_store: unsafe extern "C" fn(*mut c_void, u64, StoreKind, IntSize, *mut c_void, *mut FfiNewStore) -> bool,/// Arguments: the presentation, the context, whether the stores were added to those it has rather than replacing/// them, and the stores with their images, which it takes over.pub publish_stores: unsafe extern "C" fn(*mut c_void, u64, u64, bool, ak::Span<'_, i32>, ak::Span<'_, *mut c_void>),@@ -202,25 +218,35 @@ pub struct FfiRasterHost {*mut c_void,unsafe extern "C" fn(*mut c_void, *const FfiLiveContent<'_>),),+ /// Arguments: the remote layer, the context, the media, where it is placed, and the device pixel ratio.pub remote_layer_can_show:- unsafe extern "C" fn(*mut c_void, u64, MediaKind, u64, *const FfiSublayerPlacement, f64) -> bool,+ unsafe extern "C" fn(*mut c_void, *mut c_void, u64, MediaKind, u64, *const FfiSublayerPlacement, f64) -> bool,/// Resolves the content of the sublayers, which the window server then holds busy until the list is destroyed or/// shown.pub build_sublayers: unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, FfiSublayer>) -> *mut c_void,pub destroy_sublayers: unsafe extern "C" fn(*mut c_void),- pub frame_hand_off: unsafe extern "C" fn(*mut c_void, u64) -> FrameHandOff,/// Submits the GPU work drawn into the surface, or into the surfaces the window server shows where it is null,/// answering a token that `compositor_core_gpu_work_finished` hands back once it is done, on a later turn.pub submit_frame: unsafe extern "C" fn(*mut c_void, u64, *const PaintingSurface) -> u64,/// Calls `compositor_core_frame_ready_for_hand_off` with the token on a later turn, once the work is scheduled.pub hand_off_once_gpu_work_is_scheduled: unsafe extern "C" fn(*mut c_void, u64),- /// Shows a frame in the remote layer that shows the context, with the sublayers given, which it takes over. Answers- /// false where the layer could not show it, after which the context is no longer shown in it. Writes the- /// presentation the layer is in.- pub show_frame_in_remote_layer:- unsafe extern "C" fn(*mut c_void, u64, *const FfiRemoteLayerFrame, *mut c_void, *mut u64) -> bool,- pub stop_showing_in_remote_layer: unsafe extern "C" fn(*mut c_void, u64),+ /// Writes the window server of a new presentation, or nothing where frames reach the screen only through the+ /// presentation.+ pub create_window_server: unsafe extern "C" fn(*mut c_void, *mut FfiCppObject) -> bool,+ pub window_server_frame_hand_off: unsafe extern "C" fn(*mut c_void) -> FrameHandOff,+ /// While held, what every remote layer of the window server shows changes nowhere on screen, and changes all at+ /// once when released.+ pub window_server_hold_changes_on_screen: unsafe extern "C" fn(*mut c_void),+ pub window_server_release_changes_held_off_screen: unsafe extern "C" fn(*mut c_void),+ /// Arguments: the window server, the id of the layer, and where the layer and its host handle are written.+ pub create_remote_layer:+ unsafe extern "C" fn(*mut c_void, u64, *mut FfiCppObject, *mut FfiRemoteLayerHostHandle) -> bool,+ /// Arguments: the layer, whether the frame is scaled to fit, and the size it fits within.+ pub remote_layer_place_frame: unsafe extern "C" fn(*mut c_void, bool, IntSize),+ /// Shows the frame in the layer with the sublayers given, which it takes over. Answers false where the layer could+ /// not show it.+ pub remote_layer_show_frame: unsafe extern "C" fn(*mut c_void, *const FfiRemoteLayerFrame, *mut c_void) -> bool,pub log_presented_frame: unsafe extern "C" fn(*mut c_void, u64, IntRect),/// Calls `compositor_core_presented_store_released` on a later turn.pub release_store_later: unsafe extern "C" fn(*mut c_void, u64, i32),@@ -396,10 +422,17 @@ impl RasterHost {unsafe { (self.0.end_painting)(self.host()) };}- pub fn create_store(&self, context_id: CompositorContextId, kind: StoreKind, size: IntSize) -> Option<NewStore> {+ pub fn create_store(+ &self,+ context_id: CompositorContextId,+ kind: StoreKind,+ size: IntSize,+ window_server: Option<&WindowServerObject>,+ ) -> Option<NewStore> {let mut store = FfiNewStore::default();- // SAFETY: The host outlives this, and writes the store it made.- if !unsafe { (self.0.create_store)(self.host(), context_id.0, kind, size, &raw mut store) } {+ let window_server = window_server.map_or(std::ptr::null_mut(), WindowServerObject::as_ptr);+ // SAFETY: The host outlives this, the window server is live, and the host writes the store it made.+ if !unsafe { (self.0.create_store)(self.host(), context_id.0, kind, size, window_server, &raw mut store) } {return None;}// SAFETY: The host handed the store over.@@ -492,14 +525,25 @@ impl RasterHost {pub fn remote_layer_can_show(&self,+ remote_layer: &RemoteLayerObject,context_id: CompositorContextId,kind: MediaKind,id: u64,placement: &FfiSublayerPlacement,device_pixel_ratio: f64,) -> bool {- // SAFETY: The host outlives this.- unsafe { (self.0.remote_layer_can_show)(self.host(), context_id.0, kind, id, placement, device_pixel_ratio) }+ // SAFETY: The host outlives this, and the layer is live.+ unsafe {+ (self.0.remote_layer_can_show)(+ self.host(),+ remote_layer.as_ptr(),+ context_id.0,+ kind,+ id,+ placement,+ device_pixel_ratio,+ )+ }}pub fn build_sublayers(&self, context_id: CompositorContextId, sublayers: &[FfiSublayer]) -> SublayersHandle {@@ -511,9 +555,18 @@ impl RasterHost {}}- pub fn frame_hand_off(&self, context_id: CompositorContextId) -> FrameHandOff {- // SAFETY: The host outlives this.- unsafe { (self.0.frame_hand_off)(self.host(), context_id.0) }+ /// When a frame shown through the presentation can be handed to it.+ pub fn frame_hand_off_through_presentation() -> FrameHandOff {+ if cfg!(target_os = "macos") {+ FrameHandOff::OnceGpuWorkIsScheduled+ } else {+ FrameHandOff::OnceGpuWorkIsFinished+ }+ }++ pub fn window_server_frame_hand_off(&self, window_server: &WindowServerObject) -> FrameHandOff {+ // SAFETY: The window server is live.+ unsafe { (self.0.window_server_frame_hand_off)(window_server.as_ptr()) }}pub fn submit_frame(&self, context_id: CompositorContextId, surface: Option<&Rc<PaintingSurface>>) -> u64 {@@ -527,30 +580,14 @@ impl RasterHost {unsafe { (self.0.hand_off_once_gpu_work_is_scheduled)(self.host(), token) };}- /// Answers the presentation of the remote layer that showed the frame, or none where it could not show it.- pub fn show_frame_in_remote_layer(+ pub fn remote_layer_show_frame(&self,- context_id: CompositorContextId,+ remote_layer: &RemoteLayerObject,frame: &FfiRemoteLayerFrame,sublayers: SublayersHandle,- ) -> Option<u64> {- let mut presentation_id = 0;- // SAFETY: The host outlives this, and takes the sublayers over.- let shown = unsafe {- (self.0.show_frame_in_remote_layer)(- self.host(),- context_id.0,- frame,- sublayers.into_raw(),- &raw mut presentation_id,- )- };- shown.then_some(presentation_id)- }-- pub fn stop_showing_in_remote_layer(&self, context_id: CompositorContextId) {- // SAFETY: The host outlives this.- unsafe { (self.0.stop_showing_in_remote_layer)(self.host(), context_id.0) };+ ) -> bool {+ // SAFETY: The layer is live, and takes the sublayers over.+ unsafe { (self.0.remote_layer_show_frame)(remote_layer.as_ptr(), frame, sublayers.into_raw()) }}pub fn log_presented_frame(&self, page_id: u64, damage_rect: IntRect) {@@ -725,3 +762,70 @@ impl RasterHost {began}}++impl RemoteLayerHost for RasterHost {+ fn create_window_server(&self) -> Option<WindowServerObject> {+ let mut window_server = FfiCppObject::default();+ // SAFETY: The host outlives this, and writes the window server it made.+ if !unsafe { (self.0.create_window_server)(self.host(), &raw mut window_server) } {+ return None;+ }+ // SAFETY: The host handed a window server over.+ unsafe { WindowServerObject::adopt(window_server) }+ }++ fn create_remote_layer(+ &self,+ window_server: &WindowServerObject,+ remote_layer_id: u64,+ ) -> Option<(RemoteLayerObject, Compositing_RemoteLayerHostHandle)> {+ let mut layer = FfiCppObject::default();+ let mut host_handle = FfiRemoteLayerHostHandle::default();+ // SAFETY: The window server is live, and the host writes the layer it made with its handle.+ if !unsafe {+ (self.0.create_remote_layer)(+ window_server.as_ptr(),+ remote_layer_id,+ &raw mut layer,+ &raw mut host_handle,+ )+ } {+ return None;+ }+ // SAFETY: The host handed the layer over.+ let layer = unsafe { RemoteLayerObject::adopt(layer) }?;+ let kind = match host_handle.kind {+ 1 => Compositing_RemoteLayerHostKind::CoreAnimationContext,+ 2 => Compositing_RemoteLayerHostKind::Win32ChildWindow,+ _ => return None,+ };+ Some((+ layer,+ Compositing_RemoteLayerHostHandle {+ kind,+ id: host_handle.id,+ },+ ))+ }++ fn place_frame(&self, remote_layer: &RemoteLayerObject, fit_within: Option<IntSize>) {+ // SAFETY: The layer is live.+ unsafe {+ (self.0.remote_layer_place_frame)(+ remote_layer.as_ptr(),+ fit_within.is_some(),+ fit_within.unwrap_or_default(),+ );+ }+ }++ fn hold_changes_on_screen(&self, window_server: &WindowServerObject) {+ // SAFETY: The window server is live.+ unsafe { (self.0.window_server_hold_changes_on_screen)(window_server.as_ptr()) };+ }++ fn release_changes_held_off_screen(&self, window_server: &WindowServerObject) {+ // SAFETY: The window server is live.+ unsafe { (self.0.window_server_release_changes_held_off_screen)(window_server.as_ptr()) };+ }+}diff --git a/Services/Compositor/Rust/src/remote_layers.rs b/Services/Compositor/Rust/src/remote_layers.rsnew file mode 100644index 00000000000..0c0c1d939e7--- /dev/null+++ b/Services/Compositor/Rust/src/remote_layers.rs@@ -0,0 +1,564 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The remote layers that root contexts are shown in, which the window server of the presentation that made them shows+//! in views of their own, and the window resizes that hold what the window servers show until the presentation commits+//! them. The window servers and the layers are C++ objects, which the raster host works on.++use crate::cpp_object::{CppObject, FfiCppObject};+use crate::host::PresentationId;+use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::ipc_types::{Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind};+use libgfx_rust::IntSize;+use std::collections::HashMap;+use std::rc::Rc;++/// A `Compositor::WindowServer`, of which the core owns a reference.+pub struct WindowServerObject(CppObject);++impl WindowServerObject {+ /// # Safety+ ///+ /// A non-null object must be a live `Compositor::WindowServer` that is handed over, with the function that gives up+ /// the reference.+ pub unsafe fn adopt(object: FfiCppObject) -> Option<Self> {+ // SAFETY: The caller hands over the window server.+ unsafe { CppObject::adopt(object) }.map(Self)+ }++ pub fn as_ptr(&self) -> *mut std::ffi::c_void {+ self.0.as_ptr()+ }+}++/// A `Compositor::RemoteLayer`, which the core owns.+pub struct RemoteLayerObject(CppObject);++impl RemoteLayerObject {+ /// # Safety+ ///+ /// A non-null object must be a live `Compositor::RemoteLayer` that is handed over, with the function that destroys+ /// it.+ pub unsafe fn adopt(object: FfiCppObject) -> Option<Self> {+ // SAFETY: The caller hands over the layer.+ unsafe { CppObject::adopt(object) }.map(Self)+ }++ pub fn as_ptr(&self) -> *mut std::ffi::c_void {+ self.0.as_ptr()+ }+}++/// What is done to the window servers and the layers.+pub trait RemoteLayerHost {+ fn create_window_server(&self) -> Option<WindowServerObject>;+ fn create_remote_layer(+ &self,+ window_server: &WindowServerObject,+ remote_layer_id: u64,+ ) -> Option<(RemoteLayerObject, Compositing_RemoteLayerHostHandle)>;+ fn place_frame(&self, remote_layer: &RemoteLayerObject, fit_within: Option<IntSize>);+ fn hold_changes_on_screen(&self, window_server: &WindowServerObject);+ fn release_changes_held_off_screen(&self, window_server: &WindowServerObject);+}++/// A resize of a remote layer that the presentation is to hear of.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ResizeNotice {+ pub presentation: PresentationId,+ pub remote_layer_id: u64,+ pub token: u64,+}++/// The contexts that a change of what a remote layer shows starts or stops showing in one.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct ShownContextChange {+ pub stopped: Option<CompositorContextId>,+ pub started: Option<CompositorContextId>,+}++/// The layer that shows a context, and the window server it is in.+#[derive(Clone)]+pub struct ShowingLayer {+ pub layer: Rc<RemoteLayerObject>,+ pub window_server: Rc<WindowServerObject>,+}++pub struct RemoteLayer {+ presentation: PresentationId,+ layer: Rc<RemoteLayerObject>,+ window_server: Rc<WindowServerObject>,+ shown_context: Option<CompositorContextId>,+ fit_within: Option<IntSize>,+ // The size of the frame shown, where the page laid it out at that size.+ size_of_shown_frame_laid_out_by_page: Option<IntSize>,+}++impl RemoteLayer {+ pub fn showing_layer(&self) -> ShowingLayer {+ ShowingLayer {+ layer: self.layer.clone(),+ window_server: self.window_server.clone(),+ }+ }++ pub fn presentation(&self) -> PresentationId {+ self.presentation+ }++ pub fn fit_within(&self) -> Option<IntSize> {+ self.fit_within+ }+}++struct SynchronizedResize {+ remote_layer_id: u64,+ token: u64,+ awaited_size: Option<IntSize>,+ frame_is_held: bool,+}++#[derive(Default)]+pub struct RemoteLayers {+ window_servers: HashMap<PresentationId, Rc<WindowServerObject>>,+ layers: HashMap<u64, RemoteLayer>,+ layer_showing_context: HashMap<CompositorContextId, u64>,+ synchronized_resizes: Vec<SynchronizedResize>,+ window_servers_holding_changes: Vec<Rc<WindowServerObject>>,+}++fn no_host_handle() -> Compositing_RemoteLayerHostHandle {+ Compositing_RemoteLayerHostHandle {+ kind: Compositing_RemoteLayerHostKind::None,+ id: 0,+ }+}++impl RemoteLayers {+ pub fn register_presentation(&mut self, presentation: PresentationId, host: &dyn RemoteLayerHost) {+ if let Some(window_server) = host.create_window_server() {+ self.window_servers.insert(presentation, Rc::new(window_server));+ }+ }++ /// Destroys the layers of the presentation, answering the contexts that were shown in them.+ pub fn unregister_presentation(+ &mut self,+ presentation: PresentationId,+ host: &dyn RemoteLayerHost,+ ) -> Vec<CompositorContextId> {+ let mut remote_layer_ids: Vec<u64> = self+ .layers+ .iter()+ .filter(|(_, layer)| layer.presentation == presentation)+ .map(|(&id, _)| id)+ .collect();+ remote_layer_ids.sort_unstable();+ let stopped = remote_layer_ids+ .into_iter()+ .filter_map(|remote_layer_id| self.destroy_remote_layer(remote_layer_id, host))+ .collect();+ if let Some(window_server) = self.window_servers.remove(&presentation)+ && let Some(index) = self+ .window_servers_holding_changes+ .iter()+ .position(|holding| Rc::ptr_eq(holding, &window_server))+ {+ self.window_servers_holding_changes.remove(index);+ host.release_changes_held_off_screen(&window_server);+ }+ stopped+ }++ /// The host handle that the presentation shows the layer by, whose kind is none where the presentation has no+ /// remote layers or the layer exists already.+ pub fn create_remote_layer(+ &mut self,+ presentation: PresentationId,+ remote_layer_id: u64,+ host: &dyn RemoteLayerHost,+ ) -> Compositing_RemoteLayerHostHandle {+ if self.layers.contains_key(&remote_layer_id) {+ return no_host_handle();+ }+ let Some(window_server) = self.window_servers.get(&presentation).cloned() else {+ return no_host_handle();+ };+ let Some((layer, host_handle)) = host.create_remote_layer(&window_server, remote_layer_id) else {+ return no_host_handle();+ };+ self.layers.insert(+ remote_layer_id,+ RemoteLayer {+ presentation,+ layer: Rc::new(layer),+ window_server,+ shown_context: None,+ fit_within: None,+ size_of_shown_frame_laid_out_by_page: None,+ },+ );+ host_handle+ }++ /// Answers the context that the layer showed.+ pub fn destroy_remote_layer(+ &mut self,+ remote_layer_id: u64,+ host: &dyn RemoteLayerHost,+ ) -> Option<CompositorContextId> {+ let stopped = self+ .show_context_in_remote_layer(remote_layer_id, None, |_| false)+ .stopped;+ self.layers.remove(&remote_layer_id);+ let had_synchronized_resizes = !self.synchronized_resizes.is_empty();+ self.synchronized_resizes+ .retain(|resize| resize.remote_layer_id != remote_layer_id);+ if had_synchronized_resizes && self.synchronized_resizes.is_empty() {+ self.release_synchronized_resize_hold(host);+ }+ stopped+ }++ /// Shows the context in the layer instead of what it showed, where `can_be_shown` lets it. A context moves from+ /// any other layer it was shown in.+ pub fn show_context_in_remote_layer(+ &mut self,+ remote_layer_id: u64,+ context_id: Option<CompositorContextId>,+ can_be_shown: impl FnOnce(CompositorContextId) -> bool,+ ) -> ShownContextChange {+ let mut change = ShownContextChange::default();+ let Some(layer) = self.layers.get_mut(&remote_layer_id) else {+ return change;+ };+ if layer.shown_context == context_id {+ return change;+ }+ layer.size_of_shown_frame_laid_out_by_page = None;+ if let Some(shown_context) = layer.shown_context.take() {+ self.layer_showing_context.remove(&shown_context);+ change.stopped = Some(shown_context);+ }+ let Some(context_id) = context_id else {+ return change;+ };+ if !can_be_shown(context_id) {+ return change;+ }+ if let Some(other_remote_layer_id) = self.layer_showing_context.get(&context_id).copied()+ && let Some(other_layer) = self.layers.get_mut(&other_remote_layer_id)+ {+ other_layer.shown_context = None;+ other_layer.size_of_shown_frame_laid_out_by_page = None;+ }+ if let Some(layer) = self.layers.get_mut(&remote_layer_id) {+ layer.shown_context = Some(context_id);+ }+ self.layer_showing_context.insert(context_id, remote_layer_id);+ change.started = Some(context_id);+ change+ }++ /// The layer keeps the last frame of a context that is gone until another context is shown in it.+ pub fn context_destroyed(&mut self, context_id: CompositorContextId) {+ if let Some(remote_layer_id) = self.layer_showing_context.remove(&context_id)+ && let Some(layer) = self.layers.get_mut(&remote_layer_id)+ {+ layer.shown_context = None;+ }+ }++ /// The context is no longer shown in the layer that showed it, as when the layer could not show its frame.+ pub fn stop_showing_context(&mut self, context_id: CompositorContextId) {+ if let Some(remote_layer_id) = self.layer_showing_context.remove(&context_id)+ && let Some(layer) = self.layers.get_mut(&remote_layer_id)+ {+ layer.shown_context = None;+ layer.size_of_shown_frame_laid_out_by_page = None;+ }+ }++ pub fn layer_showing(&self, context_id: CompositorContextId) -> Option<&RemoteLayer> {+ self.layers.get(self.layer_showing_context.get(&context_id)?)+ }++ pub fn set_remote_layer_fit(+ &mut self,+ remote_layer_id: u64,+ fit_within: Option<IntSize>,+ host: &dyn RemoteLayerHost,+ ) {+ let Some(layer) = self.layers.get_mut(&remote_layer_id) else {+ return;+ };+ if layer.fit_within == fit_within {+ return;+ }+ layer.fit_within = fit_within;+ host.place_frame(&layer.layer, fit_within);+ }++ pub fn is_holding_changes(&self) -> bool {+ !self.window_servers_holding_changes.is_empty()+ }++ pub fn begin_synchronized_resize(&mut self, remote_layer_id: u64, token: u64, host: &dyn RemoteLayerHost) {+ let Some(layer) = self.layers.get(&remote_layer_id) else {+ return;+ };+ if !self+ .window_servers_holding_changes+ .iter()+ .any(|holding| Rc::ptr_eq(holding, &layer.window_server))+ {+ self.window_servers_holding_changes.push(layer.window_server.clone());+ host.hold_changes_on_screen(&layer.window_server);+ }+ self.synchronized_resizes.push(SynchronizedResize {+ remote_layer_id,+ token,+ awaited_size: None,+ frame_is_held: false,+ });+ }++ pub fn await_synchronized_resize_frame(+ &mut self,+ remote_layer_id: u64,+ token: u64,+ size: IntSize,+ ) -> Vec<ResizeNotice> {+ for resize in &mut self.synchronized_resizes {+ if resize.remote_layer_id == remote_layer_id && resize.token == token {+ resize.awaited_size = Some(size);+ }+ }+ self.held_synchronized_resize_frames(remote_layer_id)+ }++ /// The resizes of the layer whose frame it now shows, which the presentation is told of once.+ fn held_synchronized_resize_frames(&mut self, remote_layer_id: u64) -> Vec<ResizeNotice> {+ let mut held = Vec::new();+ let Some(layer) = self.layers.get(&remote_layer_id) else {+ return held;+ };+ let shown_size = layer.size_of_shown_frame_laid_out_by_page;+ for resize in &mut self.synchronized_resizes {+ if resize.remote_layer_id != remote_layer_id+ || resize.frame_is_held+ || resize.awaited_size.is_none()+ || resize.awaited_size != shown_size+ {+ continue;+ }+ resize.frame_is_held = true;+ held.push(ResizeNotice {+ presentation: layer.presentation,+ remote_layer_id,+ token: resize.token,+ });+ }+ held+ }++ pub fn commit_synchronized_resize(+ &mut self,+ remote_layer_id: u64,+ token: u64,+ host: &dyn RemoteLayerHost,+ ) -> Option<ResizeNotice> {+ self.synchronized_resizes+ .retain(|resize| !(resize.remote_layer_id == remote_layer_id && resize.token == token));+ if self.synchronized_resizes.is_empty() {+ self.release_synchronized_resize_hold(host);+ }+ let layer = self.layers.get(&remote_layer_id)?;+ Some(ResizeNotice {+ presentation: layer.presentation,+ remote_layer_id,+ token,+ })+ }++ pub fn release_synchronized_resize_hold(&mut self, host: &dyn RemoteLayerHost) {+ self.synchronized_resizes.clear();+ for window_server in std::mem::take(&mut self.window_servers_holding_changes) {+ host.release_changes_held_off_screen(&window_server);+ }+ }++ /// The layer that shows the context showed a frame of it, which the page laid out at the size it was painted at+ /// where `laid_out_by_page` says so. Answers the resizes whose frame the layer now shows.+ pub fn did_show_frame(+ &mut self,+ context_id: CompositorContextId,+ painted_size: IntSize,+ laid_out_by_page: bool,+ ) -> Vec<ResizeNotice> {+ let Some(remote_layer_id) = self.layer_showing_context.get(&context_id).copied() else {+ return Vec::new();+ };+ if let Some(layer) = self.layers.get_mut(&remote_layer_id) {+ layer.size_of_shown_frame_laid_out_by_page = laid_out_by_page.then_some(painted_size);+ }+ self.held_synchronized_resize_frames(remote_layer_id)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::cpp_object::testing::object_for_testing;+ use std::cell::{Cell, RefCell};++ #[derive(Default)]+ struct RecordingHost {+ next_address: Cell<usize>,+ held: RefCell<Vec<usize>>,+ released: RefCell<Vec<usize>>,+ placed: RefCell<Vec<Option<IntSize>>>,+ }++ impl RecordingHost {+ fn next_object(&self) -> CppObject {+ self.next_address.set(self.next_address.get() + 0x10);+ object_for_testing(self.next_address.get())+ }+ }++ impl RemoteLayerHost for RecordingHost {+ fn create_window_server(&self) -> Option<WindowServerObject> {+ Some(WindowServerObject(self.next_object()))+ }++ fn create_remote_layer(+ &self,+ _: &WindowServerObject,+ remote_layer_id: u64,+ ) -> Option<(RemoteLayerObject, Compositing_RemoteLayerHostHandle)> {+ Some((+ RemoteLayerObject(self.next_object()),+ Compositing_RemoteLayerHostHandle {+ kind: Compositing_RemoteLayerHostKind::CoreAnimationContext,+ id: remote_layer_id,+ },+ ))+ }++ fn place_frame(&self, _: &RemoteLayerObject, fit_within: Option<IntSize>) {+ self.placed.borrow_mut().push(fit_within);+ }++ fn hold_changes_on_screen(&self, window_server: &WindowServerObject) {+ self.held.borrow_mut().push(window_server.as_ptr() as usize);+ }++ fn release_changes_held_off_screen(&self, window_server: &WindowServerObject) {+ self.released.borrow_mut().push(window_server.as_ptr() as usize);+ }+ }++ const PRESENTATION: PresentationId = PresentationId(1);+ const CONTEXT: CompositorContextId = CompositorContextId(7);+ const SIZE: IntSize = IntSize {+ width: 800,+ height: 600,+ };++ fn layers_with_one_layer(host: &RecordingHost) -> RemoteLayers {+ let mut layers = RemoteLayers::default();+ layers.register_presentation(PRESENTATION, host);+ let handle = layers.create_remote_layer(PRESENTATION, 1, host);+ assert_eq!(handle.id, 1);+ layers+ }++ #[test]+ fn a_layer_is_created_once_per_id() {+ let host = RecordingHost::default();+ let mut layers = layers_with_one_layer(&host);+ assert_eq!(+ layers.create_remote_layer(PRESENTATION, 1, &host).kind,+ Compositing_RemoteLayerHostKind::None+ );+ assert_eq!(+ layers.create_remote_layer(PresentationId(2), 2, &host).kind,+ Compositing_RemoteLayerHostKind::None+ );+ }++ #[test]+ fn a_context_moves_between_layers() {+ let host = RecordingHost::default();+ let mut layers = layers_with_one_layer(&host);+ layers.create_remote_layer(PRESENTATION, 2, &host);+ assert_eq!(+ layers.show_context_in_remote_layer(1, Some(CONTEXT), |_| true),+ ShownContextChange {+ stopped: None,+ started: Some(CONTEXT)+ }+ );+ layers.show_context_in_remote_layer(2, Some(CONTEXT), |_| true);+ assert_eq!(layers.layers[&1].shown_context, None);+ assert_eq!(+ layers.layer_showing(CONTEXT).map(|layer| layer.presentation()),+ Some(PRESENTATION)+ );+ assert_eq!(layers.destroy_remote_layer(2, &host), Some(CONTEXT));+ assert!(layers.layer_showing(CONTEXT).is_none());+ }++ #[test]+ fn a_context_that_cannot_be_shown_is_ignored() {+ let host = RecordingHost::default();+ let mut layers = layers_with_one_layer(&host);+ let change = layers.show_context_in_remote_layer(1, Some(CONTEXT), |_| false);+ assert_eq!(change, ShownContextChange::default());+ assert!(layers.layer_showing(CONTEXT).is_none());+ }++ #[test]+ fn a_resize_is_held_until_the_frame_of_its_size_is_shown_and_released_when_committed() {+ let host = RecordingHost::default();+ let mut layers = layers_with_one_layer(&host);+ layers.show_context_in_remote_layer(1, Some(CONTEXT), |_| true);+ layers.begin_synchronized_resize(1, 5, &host);+ assert!(layers.is_holding_changes());+ assert_eq!(host.held.borrow().len(), 1);+ assert!(layers.await_synchronized_resize_frame(1, 5, SIZE).is_empty());+ assert!(layers.did_show_frame(CONTEXT, SIZE, false).is_empty());+ let held = layers.did_show_frame(CONTEXT, SIZE, true);+ assert_eq!(held.len(), 1);+ assert_eq!(held[0].token, 5);+ assert!(layers.did_show_frame(CONTEXT, SIZE, true).is_empty());+ let committed = layers.commit_synchronized_resize(1, 5, &host);+ assert_eq!(committed.map(|notice| notice.token), Some(5));+ assert!(!layers.is_holding_changes());+ assert_eq!(host.released.borrow().len(), 1);+ }++ #[test]+ fn destroying_the_presentation_releases_what_its_window_server_holds() {+ let host = RecordingHost::default();+ let mut layers = layers_with_one_layer(&host);+ layers.show_context_in_remote_layer(1, Some(CONTEXT), |_| true);+ layers.begin_synchronized_resize(1, 5, &host);+ assert_eq!(layers.unregister_presentation(PRESENTATION, &host), vec![CONTEXT]);+ assert!(!layers.is_holding_changes());+ assert_eq!(host.released.borrow().len(), 1);+ }++ #[test]+ fn the_frame_is_placed_again_only_when_the_fit_changes() {+ let host = RecordingHost::default();+ let mut layers = layers_with_one_layer(&host);+ layers.set_remote_layer_fit(1, Some(SIZE), &host);+ layers.set_remote_layer_fit(1, Some(SIZE), &host);+ assert_eq!(*host.placed.borrow(), vec![Some(SIZE)]);+ }+}