Skip to content

Truly independent web browser

Compositor: Keep the backing stores of contexts in Rust

Aliaksandr Kalenikc5d7e59f7247
diff --git a/Services/Compositor/BackingStoreFactory.cpp b/Services/Compositor/BackingStoreFactory.cpp
new file mode 100644
index 00000000000..44a8e0aa1df
--- /dev/null
+++ b/Services/Compositor/BackingStoreFactory.cpp
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AnyOf.h>
+#include <Compositor/BackingStoreFactory.h>
+#include <Compositor/PaintingSurface.h>
+#include <Compositor/SkiaBackendContext.h>
+#include <LibGfx/Bitmap.h>
+#include <LibGfx/SharedImageBuffer.h>
+
+#ifdef USE_VULKAN_DMABUF_IMAGES
+# include <AK/Array.h>
+# include <LibGfx/VulkanImage.h>
+# include <libdrm/drm_fourcc.h>
+#endif
+
+#ifdef USE_DIRECTX
+# include <LibGfx/D3DSharedTexture.h>
+#endif
+
+namespace Compositor {
+
+#if defined(USE_DIRECTX) || defined(USE_VULKAN)
+static NonnullRefPtr<Gfx::PaintingSurface> create_gpu_painting_surface_with_bitmap_flush(Gfx::IntSize size, Gfx::SharedImageBuffer& buffer, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
+{
+ auto surface = Gfx::PaintingSurface::create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context, {}, Gfx::PaintingSurface::TextAntialiasing::LCD);
+ auto bitmap = buffer.bitmap();
+ surface->set_on_flush([bitmap = move(bitmap)](auto& surface) {
+ surface.read_into_bitmap(*bitmap);
+ });
+ return surface;
+}
+#endif
+
+static NonnullRefPtr<Gfx::PaintingSurface> create_shareable_bitmap_backing_store([[maybe_unused]] Gfx::IntSize size, Gfx::SharedImageBuffer& buffer, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
+{
+#ifdef AK_OS_MACOS
+ if (skia_backend_context)
+ return Gfx::PaintingSurface::create_from_shared_image_buffer(buffer, *skia_backend_context);
+#else
+# if defined(USE_DIRECTX) || defined(USE_VULKAN)
+ if (skia_backend_context)
+ return create_gpu_painting_surface_with_bitmap_flush(size, buffer, skia_backend_context);
+# else
+ (void)skia_backend_context;
+# endif
+#endif
+
+ return Gfx::PaintingSurface::wrap_bitmap(*buffer.bitmap(), Gfx::PaintingSurface::TextAntialiasing::LCD);
+}
+
+#if defined(USE_VULKAN_DMABUF_IMAGES) || defined(USE_DIRECTX)
+struct GpuBackingStore {
+ RefPtr<Gfx::PaintingSurface> surface;
+ Gfx::SharedImage shared_image;
+};
+#endif
+
+static Vector<u64>& presentation_drm_format_modifiers()
+{
+ static Vector<u64> modifiers;
+ return modifiers;
+}
+
+void set_presentation_drm_format_modifiers(Vector<u64> modifiers)
+{
+ presentation_drm_format_modifiers() = move(modifiers);
+}
+
+#ifdef USE_VULKAN_DMABUF_IMAGES
+// A presentation on another GPU can only import a linear layout. On ours, the driver picks a layout that suits it among
+// those the presentation can import, which matters to GPUs such as NVIDIA's that cannot render to a linear one at all.
+static Vector<u64> shared_backing_store_drm_format_modifiers(Gfx::VulkanContext const& vulkan_context)
+{
+ if (!vulkan_context.is_preferred_device)
+ return { DRM_FORMAT_MOD_LINEAR };
+
+ auto modifiers = Gfx::renderable_drm_format_modifiers(vulkan_context, VK_FORMAT_B8G8R8A8_UNORM);
+ // NB: The presentation can still show frames that it cannot import, after the view reads them back.
+ auto const& importable_modifiers = presentation_drm_format_modifiers();
+ if (any_of(modifiers, [&](u64 modifier) { return importable_modifiers.contains_slow(modifier); }))
+ modifiers.remove_all_matching([&](u64 modifier) { return !importable_modifiers.contains_slow(modifier); });
+ // NB: A linear layout is the slowest to paint into, so it is only used when there is nothing else.
+ if (any_of(modifiers, [](u64 modifier) { return modifier != DRM_FORMAT_MOD_LINEAR; }))
+ modifiers.remove_all_matching([](u64 modifier) { return modifier == DRM_FORMAT_MOD_LINEAR; });
+ return modifiers;
+}
+
+static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize size, Gfx::SkiaBackendContext& skia_backend_context)
+{
+ auto const& vulkan_context = skia_backend_context.vulkan_context();
+ auto const modifiers = shared_backing_store_drm_format_modifiers(vulkan_context);
+ auto image = TRY(Gfx::create_shared_vulkan_image(vulkan_context, size.width(), size.height(), VK_FORMAT_B8G8R8A8_UNORM, modifiers.span()));
+ auto shared_image = Gfx::duplicate_shared_image(*image);
+
+ return GpuBackingStore {
+ .surface = Gfx::PaintingSurface::create_from_vkimage(skia_backend_context, move(image), Gfx::PaintingSurface::Origin::TopLeft, Gfx::PaintingSurface::TextAntialiasing::LCD),
+ .shared_image = move(shared_image),
+ };
+}
+#endif
+
+#ifdef USE_DIRECTX
+static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize size, Gfx::SkiaBackendContext& skia_backend_context)
+{
+ auto texture = TRY(Gfx::D3DSharedTexture::create(skia_backend_context.direct3d_context(), size));
+ auto shared_image = Gfx::duplicate_shared_image(*texture);
+
+ return GpuBackingStore {
+ .surface = TRY(Gfx::PaintingSurface::create_from_d3d_texture(skia_backend_context, move(texture))),
+ .shared_image = move(shared_image),
+ };
+}
+#endif
+
+static ErrorOr<NewBackingStore> create_shared_bitmap_backing_store(Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
+{
+ auto shared_image_buffer = make<Gfx::SharedImageBuffer>(Gfx::SharedImageBuffer::create(size));
+ auto surface = create_shareable_bitmap_backing_store(size, *shared_image_buffer, skia_backend_context);
+ auto shared_image = shared_image_buffer->export_shared_image();
+ return NewBackingStore {
+ .surface = move(surface),
+ .window_server_surface = nullptr,
+ .shared_image_buffer = move(shared_image_buffer),
+ .shared_image = move(shared_image),
+ };
+}
+
+static ErrorOr<NewBackingStore> create_shared_gpu_image_backing_store([[maybe_unused]] Gfx::IntSize size, [[maybe_unused]] RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
+{
+#if defined(USE_VULKAN_DMABUF_IMAGES) || defined(USE_DIRECTX)
+ if (!skia_backend_context)
+ return Error::from_string_literal("Shared GPU images need a GPU");
+ auto backing_store = create_shared_gpu_backing_store(size, *skia_backend_context);
+ if (backing_store.is_error()) {
+ static bool reported_failure = false;
+ if (!reported_failure) {
+ dbgln("Failed to allocate shared GPU backing store ({}), falling back to shareable bitmaps", backing_store.error());
+ reported_failure = true;
+ }
+ return backing_store.release_error();
+ }
+ auto store = backing_store.release_value();
+ return NewBackingStore {
+ .surface = store.surface.release_nonnull(),
+ .window_server_surface = nullptr,
+ .shared_image_buffer = nullptr,
+ .shared_image = move(store.shared_image),
+ };
+#else
+ return Error::from_string_literal("Shared GPU images are not supported on this platform");
+#endif
+}
+
+ErrorOr<NewBackingStore> create_backing_store(RustFFI::StoreKind kind, Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, WindowServer* window_server_showing_stores)
+{
+ switch (kind) {
+ case RustFFI::StoreKind::Offscreen:
+ return NewBackingStore {
+ .surface = TRY(Gfx::PaintingSurface::try_create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context)),
+ .window_server_surface = nullptr,
+ .shared_image_buffer = nullptr,
+ .shared_image = {},
+ };
+ case RustFFI::StoreKind::SharedBitmap:
+ return create_shared_bitmap_backing_store(size, skia_backend_context);
+ case RustFFI::StoreKind::SharedGpuImage:
+ return create_shared_gpu_image_backing_store(size, skia_backend_context);
+ case RustFFI::StoreKind::ShownByWindowServer: {
+ if (!window_server_showing_stores)
+ return Error::from_string_literal("No window server shows the stores");
+ auto surface = TRY(window_server_showing_stores->try_create_presentable_surface(size, skia_backend_context));
+ return NewBackingStore {
+ .surface = surface->painting_surface(),
+ .window_server_surface = move(surface),
+ .shared_image_buffer = nullptr,
+ .shared_image = {},
+ };
+ }
+ }
+ VERIFY_NOT_REACHED();
+}
+
+bool shared_image_buffer_is_in_use([[maybe_unused]] Gfx::SharedImageBuffer const& buffer)
+{
+#ifdef AK_OS_MACOS
+ // The send right exported to the UI counts as use as well, so a freshly published store reads as in use until the
+ // UI has imported it.
+ return buffer.iosurface_handle().is_in_use();
+#else
+ return false;
+#endif
+}
+
+}
diff --git a/Services/Compositor/BackingStoreFactory.h b/Services/Compositor/BackingStoreFactory.h
new file mode 100644
index 00000000000..445cc929d27
--- /dev/null
+++ b/Services/Compositor/BackingStoreFactory.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Error.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/OwnPtr.h>
+#include <AK/RefPtr.h>
+#include <AK/Vector.h>
+#include <Compositor/CompositorCoreRustFFI.h>
+#include <Compositor/PaintingSurface.h>
+#include <Compositor/PresentableSurface.h>
+#include <Compositor/WindowServer.h>
+#include <LibGfx/Forward.h>
+#include <LibGfx/SharedImage.h>
+#include <LibGfx/SharedImageBuffer.h>
+#include <LibGfx/Size.h>
+
+namespace Compositor {
+
+// A store of the kind that the backing stores of a context in the Rust core asked for: the surface frames are rendered
+// into, the surface the window server shows it as, the memory it shares with the presentation, and the image the
+// presentation imports it from.
+struct NewBackingStore {
+ NonnullRefPtr<Gfx::PaintingSurface> surface;
+ RefPtr<PresentableSurface> window_server_surface;
+ OwnPtr<Gfx::SharedImageBuffer> shared_image_buffer;
+ Optional<Gfx::SharedImage> shared_image;
+};
+
+// The layouts that the presentation can import shared GPU backing stores in. Any layout the GPU renders to goes while
+// this is empty.
+void set_presentation_drm_format_modifiers(Vector<u64>);
+
+ErrorOr<NewBackingStore> create_backing_store(RustFFI::StoreKind, Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&, WindowServer* window_server_showing_stores);
+
+// Whether something other than the compositor still holds the memory of a store, such as the window server, or the
+// presentation that has yet to import it.
+bool shared_image_buffer_is_in_use(Gfx::SharedImageBuffer const&);
+
+}
diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cpp
deleted file mode 100644
index ee852359f78..00000000000
--- a/Services/Compositor/BackingStoreManager.cpp
+++ /dev/null
@@ -1,556 +0,0 @@
-/*
- * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/AnyOf.h>
-#include <Compositor/BackingStoreManager.h>
-#include <Compositor/PaintingSurface.h>
-#include <Compositor/SkiaBackendContext.h>
-#include <LibGfx/Bitmap.h>
-#include <LibGfx/SharedImageBuffer.h>
-
-#ifdef USE_VULKAN_DMABUF_IMAGES
-# include <AK/Array.h>
-# include <LibGfx/VulkanImage.h>
-# include <libdrm/drm_fourcc.h>
-#endif
-
-#ifdef USE_DIRECTX
-# include <LibGfx/D3DSharedTexture.h>
-#endif
-
-namespace Compositor {
-
-#if defined(USE_DIRECTX) || defined(USE_VULKAN)
-static NonnullRefPtr<Gfx::PaintingSurface> create_gpu_painting_surface_with_bitmap_flush(Gfx::IntSize size, Gfx::SharedImageBuffer& buffer, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- auto surface = Gfx::PaintingSurface::create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context, {}, Gfx::PaintingSurface::TextAntialiasing::LCD);
- auto bitmap = buffer.bitmap();
- surface->set_on_flush([bitmap = move(bitmap)](auto& surface) {
- surface.read_into_bitmap(*bitmap);
- });
- return surface;
-}
-#endif
-
-static NonnullRefPtr<Gfx::PaintingSurface> create_shareable_bitmap_backing_store([[maybe_unused]] Gfx::IntSize size, Gfx::SharedImageBuffer& buffer, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
-#ifdef AK_OS_MACOS
- if (skia_backend_context)
- return Gfx::PaintingSurface::create_from_shared_image_buffer(buffer, *skia_backend_context);
-#else
-# if defined(USE_DIRECTX) || defined(USE_VULKAN)
- if (skia_backend_context)
- return create_gpu_painting_surface_with_bitmap_flush(size, buffer, skia_backend_context);
-# else
- (void)skia_backend_context;
-# endif
-#endif
-
- return Gfx::PaintingSurface::wrap_bitmap(*buffer.bitmap(), Gfx::PaintingSurface::TextAntialiasing::LCD);
-}
-
-#if defined(USE_VULKAN_DMABUF_IMAGES) || defined(USE_DIRECTX)
-struct GpuBackingStore {
- RefPtr<Gfx::PaintingSurface> surface;
- Gfx::SharedImage shared_image;
-};
-#endif
-
-static Vector<u64>& presentation_drm_format_modifiers()
-{
- static Vector<u64> modifiers;
- return modifiers;
-}
-
-void BackingStoreManager::set_presentation_drm_format_modifiers(Vector<u64> modifiers)
-{
- presentation_drm_format_modifiers() = move(modifiers);
-}
-
-#ifdef USE_VULKAN_DMABUF_IMAGES
-// A presentation on another GPU can only import a linear layout. On ours, the driver picks a layout that suits it among
-// those the presentation can import, which matters to GPUs such as NVIDIA's that cannot render to a linear one at all.
-static Vector<u64> shared_backing_store_drm_format_modifiers(Gfx::VulkanContext const& vulkan_context)
-{
- if (!vulkan_context.is_preferred_device)
- return { DRM_FORMAT_MOD_LINEAR };
-
- auto modifiers = Gfx::renderable_drm_format_modifiers(vulkan_context, VK_FORMAT_B8G8R8A8_UNORM);
- // NB: The presentation can still show frames that it cannot import, after the view reads them back.
- auto const& importable_modifiers = presentation_drm_format_modifiers();
- if (any_of(modifiers, [&](u64 modifier) { return importable_modifiers.contains_slow(modifier); }))
- modifiers.remove_all_matching([&](u64 modifier) { return !importable_modifiers.contains_slow(modifier); });
- // NB: A linear layout is the slowest to paint into, so it is only used when there is nothing else.
- if (any_of(modifiers, [](u64 modifier) { return modifier != DRM_FORMAT_MOD_LINEAR; }))
- modifiers.remove_all_matching([](u64 modifier) { return modifier == DRM_FORMAT_MOD_LINEAR; });
- return modifiers;
-}
-
-static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize size, Gfx::SkiaBackendContext& skia_backend_context)
-{
- auto const& vulkan_context = skia_backend_context.vulkan_context();
- auto const modifiers = shared_backing_store_drm_format_modifiers(vulkan_context);
- auto image = TRY(Gfx::create_shared_vulkan_image(vulkan_context, size.width(), size.height(), VK_FORMAT_B8G8R8A8_UNORM, modifiers.span()));
- auto shared_image = Gfx::duplicate_shared_image(*image);
-
- return GpuBackingStore {
- .surface = Gfx::PaintingSurface::create_from_vkimage(skia_backend_context, move(image), Gfx::PaintingSurface::Origin::TopLeft, Gfx::PaintingSurface::TextAntialiasing::LCD),
- .shared_image = move(shared_image),
- };
-}
-#endif
-
-#ifdef USE_DIRECTX
-static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize size, Gfx::SkiaBackendContext& skia_backend_context)
-{
- auto texture = TRY(Gfx::D3DSharedTexture::create(skia_backend_context.direct3d_context(), size));
- auto shared_image = Gfx::duplicate_shared_image(*texture);
-
- return GpuBackingStore {
- .surface = TRY(Gfx::PaintingSurface::create_from_d3d_texture(skia_backend_context, move(texture))),
- .shared_image = move(shared_image),
- };
-}
-#endif
-
-// A store shown on screen is let go of when the next one is shown, but on macOS the window server is handed the
-// surface itself, and keeps reading it until it has composited the replacement. A third store lets the compositor keep
-// rendering through that window instead of waiting for it.
-static size_t backing_store_count_for([[maybe_unused]] BackingStoreManager::PublicationMode publication_mode)
-{
-#ifdef AK_OS_MACOS
- if (publication_mode != BackingStoreManager::PublicationMode::Unpublished)
- return 3;
-#endif
- return 2;
-}
-
-Optional<BackingStoreManager::Allocation> BackingStoreManager::resize_backing_stores_if_needed(
- Gfx::IntSize viewport_size, Compositing::WindowResizingInProgress window_resize_in_progress, PublicationMode publication_mode)
-{
- if (viewport_size.is_empty())
- return {};
-
- auto allocation_size = viewport_size;
- bool needs_allocation = m_allocated_size.is_empty();
- if (window_resize_in_progress == Compositing::WindowResizingInProgress::Yes) {
- // Pad the backing stores we allocate so that we don't have to keep reallocating them while the window is being
- // resized. Ones that still hold the viewport are kept.
- allocation_size = { viewport_size.width() + 256, viewport_size.height() + 256 };
- needs_allocation |= !m_allocated_size.contains(viewport_size);
- } else {
- // If we're not in the middle of a resize, we can shrink the backing store size to match the viewport size.
- needs_allocation |= m_allocated_size != viewport_size;
- }
-
- if (needs_allocation) {
- m_allocated_size = allocation_size;
- auto buffer_count = backing_store_count_for(publication_mode);
- Vector<i32> bitmap_ids;
- bitmap_ids.ensure_capacity(buffer_count);
- for (size_t i = 0; i < buffer_count; ++i)
- bitmap_ids.append(m_next_bitmap_id++);
- return Allocation { .size = allocation_size, .bitmap_ids = move(bitmap_ids) };
- }
-
- return {};
-}
-
-ErrorOr<Optional<BackingStoreManager::Publication>> BackingStoreManager::allocate_backing_stores(Allocation const& allocation, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, PublicationMode publication_mode, [[maybe_unused]] GpuSharing gpu_sharing, RefPtr<WindowServer> window_server_showing_stores)
-{
- m_backing_stores.clear();
- m_rendering_store_index.clear();
- m_latest_rendered_store_index.clear();
- m_publication_mode = publication_mode;
- m_window_server_showing_stores = publication_mode == PublicationMode::ShownInRemoteLayer ? move(window_server_showing_stores) : nullptr;
-
- if (Gfx::Bitmap::size_would_overflow(Gfx::BitmapFormat::BGRA8888, allocation.size))
- return Optional<Publication> {};
-
- auto buffer_count = allocation.bitmap_ids.size();
- m_backing_store_size = allocation.size;
- m_initial_backing_store_count = buffer_count;
- m_backing_stores.ensure_capacity(buffer_count);
-
- if (publication_mode == PublicationMode::Unpublished) {
- for (size_t i = 0; i < buffer_count; ++i)
- m_backing_stores.append(create_offscreen_backing_store(allocation.size, allocation.bitmap_ids[i], skia_backend_context));
- return Optional<Publication> {};
- }
-
- if (publication_mode == PublicationMode::ShownInRemoteLayer) {
- for (size_t i = 0; i < buffer_count; ++i) {
- auto store = create_backing_store_shown_by_window_server(allocation.size, allocation.bitmap_ids[i], skia_backend_context);
- if (store.is_error()) {
- m_backing_stores.clear();
- invalidate();
- return store.release_error();
- }
- m_backing_stores.append(store.release_value());
- }
- return Optional<Publication> { Publication { .bitmap_ids = allocation.bitmap_ids, .shared_images = {} } };
- }
-
- // The UI installs the first published buffer as its initial front buffer.
- // Reserve it until the UI releases it after presenting another buffer.
- auto initial_buffer_state = [](size_t index) {
- return index == 0 ? BufferState::Presented : BufferState::Available;
- };
-
-#if defined(USE_VULKAN_DMABUF_IMAGES) || defined(USE_DIRECTX)
- if (skia_backend_context && gpu_sharing == GpuSharing::Allowed) {
- Vector<Gfx::SharedImage> shared_images;
- shared_images.ensure_capacity(buffer_count);
- bool allocation_succeeded = true;
- for (size_t i = 0; i < buffer_count; ++i) {
- auto backing_store = create_shared_gpu_backing_store(allocation.size, *skia_backend_context);
- if (backing_store.is_error()) {
- static bool reported_failure = false;
- if (!reported_failure) {
- dbgln("Failed to allocate shared GPU backing store ({}), falling back to shareable bitmaps", backing_store.error());
- reported_failure = true;
- }
- allocation_succeeded = false;
- break;
- }
-
- auto store = backing_store.release_value();
- m_backing_stores.append({
- .surface = move(store.surface),
- .shared_image_buffer = nullptr,
- .window_server_surface = nullptr,
- .bitmap_id = allocation.bitmap_ids[i],
- .state = initial_buffer_state(i),
- });
- shared_images.append(move(store.shared_image));
- }
-
- if (allocation_succeeded) {
- return Optional<Publication> { Publication {
- .bitmap_ids = allocation.bitmap_ids,
- .shared_images = move(shared_images),
- } };
- }
-
- m_backing_stores.clear();
- }
-#endif
-
- Vector<Gfx::SharedImage> shared_images;
- shared_images.ensure_capacity(buffer_count);
- for (size_t i = 0; i < buffer_count; ++i) {
- m_backing_stores.append(create_shareable_backing_store(allocation.size, allocation.bitmap_ids[i], initial_buffer_state(i), skia_backend_context));
- shared_images.append(m_backing_stores.last().shared_image_buffer->export_shared_image());
- }
-
- return Optional<Publication> { Publication {
- .bitmap_ids = allocation.bitmap_ids,
- .shared_images = move(shared_images),
- } };
-}
-
-BackingStoreManager::BackingStore BackingStoreManager::create_offscreen_backing_store(Gfx::IntSize size, i32 bitmap_id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- return {
- .surface = Gfx::PaintingSurface::create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context),
- .shared_image_buffer = nullptr,
- .window_server_surface = nullptr,
- .bitmap_id = bitmap_id,
- .state = BufferState::Available,
- };
-}
-
-BackingStoreManager::BackingStore BackingStoreManager::create_shareable_backing_store(Gfx::IntSize size, i32 bitmap_id, BufferState state, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- auto shared_image_buffer = make<Gfx::SharedImageBuffer>(Gfx::SharedImageBuffer::create(size));
- auto surface = create_shareable_bitmap_backing_store(size, *shared_image_buffer, skia_backend_context);
- return {
- .surface = move(surface),
- .shared_image_buffer = move(shared_image_buffer),
- .window_server_surface = nullptr,
- .bitmap_id = bitmap_id,
- .state = state,
- };
-}
-
-ErrorOr<BackingStoreManager::BackingStore> BackingStoreManager::create_backing_store_shown_by_window_server(Gfx::IntSize size, i32 bitmap_id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- VERIFY(m_window_server_showing_stores);
- auto surface = TRY(m_window_server_showing_stores->try_create_presentable_surface(size, skia_backend_context));
- return BackingStore {
- .surface = surface->painting_surface(),
- .shared_image_buffer = nullptr,
- .window_server_surface = move(surface),
- .bitmap_id = bitmap_id,
- .state = BufferState::Available,
- };
-}
-
-// GPU stores shared with the presentation are only ever allocated together, as the presentation installs them.
-bool BackingStoreManager::backing_stores_can_be_added_one_at_a_time() const
-{
- if (m_backing_stores.is_empty())
- return false;
- if (m_publication_mode != PublicationMode::Published)
- return true;
- return m_backing_stores.first().shared_image_buffer.ptr() != nullptr;
-}
-
-ErrorOr<BackingStoreManager::BackingStore> BackingStoreManager::create_backing_store_like_the_allocated_ones(i32 bitmap_id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- switch (m_publication_mode) {
- case PublicationMode::Unpublished:
- return create_offscreen_backing_store(m_backing_store_size, bitmap_id, skia_backend_context);
- case PublicationMode::Published:
- return create_shareable_backing_store(m_backing_store_size, bitmap_id, BufferState::Available, skia_backend_context);
- case PublicationMode::ShownInRemoteLayer:
- return create_backing_store_shown_by_window_server(m_backing_store_size, bitmap_id, skia_backend_context);
- }
- VERIFY_NOT_REACHED();
-}
-
-// The window server lets go of a store some time after the client replaced it on screen, which at high refresh rates
-// can be later than the next frame is due. Rather than hold that frame back, give it a store of its own. While the
-// client has yet to take a frame, or to release a store, there is no telling what the window server holds, and the
-// frame waits as it always did.
-Optional<BackingStoreManager::Publication> BackingStoreManager::add_backing_store_if_window_server_still_reads_every_released_store(RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- if (is_rendering() || !m_latest_rendered_store_index.has_value())
- return {};
- if (m_backing_stores.size() >= maximum_backing_store_count)
- return {};
-
- for (size_t i = 0; i < m_backing_stores.size(); ++i) {
- auto const& store = m_backing_stores[i];
- if (!store.shared_image_buffer && !store.window_server_surface)
- return {};
- bool client_displays_store = i == *m_latest_rendered_store_index;
- if (client_displays_store && store.state != BufferState::Presented)
- return {};
- if (!client_displays_store && (store.state != BufferState::Available || store_can_be_rendered_into(store)))
- return {};
- }
-
- auto bitmap_id = m_next_bitmap_id++;
- auto store = create_backing_store_like_the_allocated_ones(bitmap_id, skia_backend_context);
- if (store.is_error())
- return {};
- m_backing_stores.append(store.release_value());
-
- Vector<Gfx::SharedImage> shared_images;
- if (m_publication_mode == PublicationMode::Published)
- shared_images.append(m_backing_stores.last().shared_image_buffer->export_shared_image());
- return Publication {
- .bitmap_ids = { bitmap_id },
- .shared_images = move(shared_images),
- };
-}
-
-// A store added for a burst of frames is given back once a whole interval between two checks went by without it
-// being rendered into. The stores that stay are the ones first in line for the next frame.
-Vector<i32> BackingStoreManager::retire_idle_surplus_backing_stores()
-{
- Vector<i32> retired_bitmap_ids;
- if (is_rendering())
- return retired_bitmap_ids;
-
- for (size_t i = m_backing_stores.size(); i-- > 0 && has_surplus_backing_stores();) {
- auto const& store = m_backing_stores[i];
- if (m_latest_rendered_store_index == i)
- continue;
- if (store.state != BufferState::Available || store.was_rendered_into_since_last_retirement_check || shared_surface_is_in_use(store))
- continue;
-
- retired_bitmap_ids.append(store.bitmap_id);
- m_backing_stores.remove(i);
- if (m_latest_rendered_store_index.has_value() && *m_latest_rendered_store_index > i)
- m_latest_rendered_store_index = *m_latest_rendered_store_index - 1;
- }
-
- for (auto& store : m_backing_stores)
- store.was_rendered_into_since_last_retirement_check = false;
- return retired_bitmap_ids;
-}
-
-// A hidden context keeps only the store that holds its latest frame, which is what shows it until it is shown again,
-// and what a snapshot of it is taken from. Before any frame, the store reserved as the presentation's first front
-// store stays too.
-Vector<i32> BackingStoreManager::retire_backing_stores_except_the_latest_rendered()
-{
- Vector<i32> retired_bitmap_ids;
- if (is_rendering())
- return retired_bitmap_ids;
-
- for (size_t i = m_backing_stores.size(); i-- > 0;) {
- auto const& store = m_backing_stores[i];
- if (m_latest_rendered_store_index == i)
- continue;
- if (store.state != BufferState::Available || shared_surface_is_in_use(store))
- continue;
-
- retired_bitmap_ids.append(store.bitmap_id);
- m_backing_stores.remove(i);
- if (m_latest_rendered_store_index.has_value() && *m_latest_rendered_store_index > i)
- m_latest_rendered_store_index = *m_latest_rendered_store_index - 1;
- }
-
- // Stores that never held a frame are allocated anew when the context is shown.
- if (m_backing_stores.is_empty())
- invalidate();
- return retired_bitmap_ids;
-}
-
-// Whether a store that the hidden context does not keep is still rendered into, shown, or read by the window server,
-// and can be retired once it no longer is.
-bool BackingStoreManager::has_backing_stores_left_to_retire_while_hidden() const
-{
- for (size_t i = 0; i < m_backing_stores.size(); ++i) {
- if (m_latest_rendered_store_index == i)
- continue;
- auto const& store = m_backing_stores[i];
- switch (store.state) {
- case BufferState::Rendering:
- return true;
- case BufferState::Presented:
- // Before any frame, a presented store is the one reserved as the presentation's first front store, which
- // the presentation holds until it is shown a frame.
- if (m_latest_rendered_store_index.has_value())
- return true;
- break;
- case BufferState::Available:
- if (shared_surface_is_in_use(store))
- return true;
- break;
- }
- }
- return false;
-}
-
-// Gives a context that was shown again the stores it had before it was hidden. Answers nothing where they can't be
-// added to the ones it kept, or one could not be made, as the context then needs a whole new allocation.
-Optional<BackingStoreManager::Publication> BackingStoreManager::add_backing_stores_up_to_initial_count(RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
-{
- if (!backing_stores_can_be_added_one_at_a_time())
- return {};
-
- Publication publication;
- while (m_backing_stores.size() < m_initial_backing_store_count) {
- auto bitmap_id = m_next_bitmap_id++;
- auto store = create_backing_store_like_the_allocated_ones(bitmap_id, skia_backend_context);
- if (store.is_error())
- return {};
- m_backing_stores.append(store.release_value());
- publication.bitmap_ids.append(bitmap_id);
- if (m_publication_mode == PublicationMode::Published)
- publication.shared_images.append(m_backing_stores.last().shared_image_buffer->export_shared_image());
- }
- return publication;
-}
-
-bool BackingStoreManager::is_valid() const
-{
- return !m_backing_stores.is_empty();
-}
-
-bool BackingStoreManager::shared_surface_is_in_use(BackingStore const& store)
-{
- if (store.window_server_surface)
- return store.window_server_surface->is_read_by_window_server();
-#ifdef AK_OS_MACOS
- // The send right exported to the UI counts as use as well, so a freshly published store reads as in use until
- // the UI has imported it.
- return store.shared_image_buffer && store.shared_image_buffer->iosurface_handle().is_in_use();
-#else
- (void)store;
- return false;
-#endif
-}
-
-bool BackingStoreManager::store_can_be_rendered_into(BackingStore const& store)
-{
- if (store.state != BufferState::Available)
- return false;
- // Only a store shown on screen is handed to the window server, so whatever uses a store that never was is the
- // send right on its way to the client.
- if (!store.was_shown_on_screen)
- return true;
- return !shared_surface_is_in_use(store);
-}
-
-bool BackingStoreManager::has_available_buffer() const
-{
- return any_of(m_backing_stores, [](auto const& store) { return store_can_be_rendered_into(store); });
-}
-
-Optional<BackingStoreManager::RenderTarget> BackingStoreManager::acquire_render_target()
-{
- VERIFY(!m_rendering_store_index.has_value());
-
- for (size_t i = 0; i < m_backing_stores.size(); ++i) {
- auto& store = m_backing_stores[i];
- if (!store_can_be_rendered_into(store))
- continue;
-
- store.state = BufferState::Rendering;
- store.was_rendered_into_since_last_retirement_check = true;
- m_rendering_store_index = i;
- return RenderTarget { *store.surface, store.bitmap_id };
- }
- return {};
-}
-
-void BackingStoreManager::complete_rendering(i32 bitmap_id)
-{
- VERIFY(m_rendering_store_index.has_value());
- auto& store = m_backing_stores[*m_rendering_store_index];
- VERIFY(store.state == BufferState::Rendering);
- VERIFY(store.bitmap_id == bitmap_id);
-
- bool client_releases_presented_stores = m_publication_mode == PublicationMode::Published;
- if (!client_releases_presented_stores && m_latest_rendered_store_index.has_value())
- m_backing_stores[*m_latest_rendered_store_index].state = BufferState::Available;
-
- store.state = BufferState::Presented;
- if (m_publication_mode != PublicationMode::Unpublished)
- store.was_shown_on_screen = true;
- m_latest_rendered_store_index = m_rendering_store_index;
- m_rendering_store_index.clear();
-}
-
-bool BackingStoreManager::release_buffer(i32 bitmap_id)
-{
- for (auto& store : m_backing_stores) {
- if (store.bitmap_id != bitmap_id || store.state != BufferState::Presented)
- continue;
- store.state = BufferState::Available;
- return true;
- }
- return false;
-}
-
-void BackingStoreManager::release_all_presented_buffers()
-{
- for (auto& store : m_backing_stores) {
- if (store.state == BufferState::Presented)
- store.state = BufferState::Available;
- }
-}
-
-RefPtr<Gfx::PaintingSurface> BackingStoreManager::latest_rendered_surface() const
-{
- if (!m_latest_rendered_store_index.has_value())
- return nullptr;
- return m_backing_stores[*m_latest_rendered_store_index].surface;
-}
-
-PresentableSurface* BackingStoreManager::window_server_surface_of_latest_rendered_store() const
-{
- if (!m_latest_rendered_store_index.has_value())
- return nullptr;
- return m_backing_stores[*m_latest_rendered_store_index].window_server_surface.ptr();
-}
-
-}
diff --git a/Services/Compositor/BackingStoreManager.h b/Services/Compositor/BackingStoreManager.h
deleted file mode 100644
index 6061b1ae26c..00000000000
--- a/Services/Compositor/BackingStoreManager.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Noncopyable.h>
-#include <AK/Optional.h>
-#include <AK/OwnPtr.h>
-#include <AK/RefPtr.h>
-#include <AK/Types.h>
-#include <AK/Vector.h>
-#include <Compositor/Forward.h>
-#include <Compositor/PresentableSurface.h>
-#include <Compositor/WindowServer.h>
-#include <LibCompositing/Types.h>
-#include <LibGfx/Forward.h>
-#include <LibGfx/SharedImage.h>
-#include <LibGfx/SharedImageBuffer.h>
-#include <LibGfx/Size.h>
-
-namespace Compositor {
-
-class BackingStoreManager {
- AK_MAKE_NONCOPYABLE(BackingStoreManager);
- AK_MAKE_NONMOVABLE(BackingStoreManager);
-
-public:
- struct Allocation {
- Gfx::IntSize size;
- Vector<i32> bitmap_ids;
- };
- // The stores that were allocated or added, with the images the presentation imports, if it shows the stores.
- struct Publication {
- Vector<i32> bitmap_ids;
- Vector<Gfx::SharedImage> shared_images;
- };
- struct RenderTarget {
- Gfx::PaintingSurface& surface;
- i32 bitmap_id { -1 };
- };
-
- enum class PublicationMode {
- Unpublished,
- // The presentation shows the stores, and releases each when it shows another.
- Published,
- // The compositor shows the stores itself, in a remote layer, so a store is replaced on screen by the next one.
- ShownInRemoteLayer,
- };
-
- enum class GpuSharing {
- Disallowed,
- Allowed,
- };
-
- BackingStoreManager() = default;
-
- // The layouts that the presentation can import shared GPU backing stores in. Any layout the GPU renders to goes
- // while this is empty.
- static void set_presentation_drm_format_modifiers(Vector<u64>);
-
- Optional<Allocation> resize_backing_stores_if_needed(
- Gfx::IntSize viewport_size, Compositing::WindowResizingInProgress, PublicationMode);
- ErrorOr<Optional<Publication>> allocate_backing_stores(Allocation const&, RefPtr<Gfx::SkiaBackendContext> const&, PublicationMode, GpuSharing, RefPtr<WindowServer> window_server_showing_stores);
-
- void invalidate() { m_allocated_size = {}; }
-
- bool is_valid() const;
- bool is_rendering() const { return m_rendering_store_index.has_value(); }
- bool has_available_buffer() const;
- Optional<RenderTarget> acquire_render_target();
- void complete_rendering(i32 bitmap_id);
- bool release_buffer(i32 bitmap_id);
- void release_all_presented_buffers();
- RefPtr<Gfx::PaintingSurface> latest_rendered_surface() const;
- PresentableSurface* window_server_surface_of_latest_rendered_store() const;
- PublicationMode publication_mode() const { return m_publication_mode; }
-
- Optional<Publication> add_backing_store_if_window_server_still_reads_every_released_store(RefPtr<Gfx::SkiaBackendContext> const&);
- bool has_surplus_backing_stores() const { return m_backing_stores.size() > m_initial_backing_store_count; }
- Vector<i32> retire_idle_surplus_backing_stores();
-
- Vector<i32> retire_backing_stores_except_the_latest_rendered();
- bool has_backing_stores_left_to_retire_while_hidden() const;
- Optional<Publication> add_backing_stores_up_to_initial_count(RefPtr<Gfx::SkiaBackendContext> const&);
-
-private:
- enum class BufferState : u8 {
- Available,
- Rendering,
- Presented,
- };
-
- struct BackingStore {
- RefPtr<Gfx::PaintingSurface> surface;
- OwnPtr<Gfx::SharedImageBuffer> shared_image_buffer;
- RefPtr<PresentableSurface> window_server_surface;
- i32 bitmap_id { -1 };
- BufferState state { BufferState::Available };
- bool was_shown_on_screen { false };
- bool was_rendered_into_since_last_retirement_check { false };
- };
-
- static constexpr size_t maximum_backing_store_count = 8;
-
- static BackingStore create_offscreen_backing_store(Gfx::IntSize, i32 bitmap_id, RefPtr<Gfx::SkiaBackendContext> const&);
- static BackingStore create_shareable_backing_store(Gfx::IntSize, i32 bitmap_id, BufferState, RefPtr<Gfx::SkiaBackendContext> const&);
- ErrorOr<BackingStore> create_backing_store_shown_by_window_server(Gfx::IntSize, i32 bitmap_id, RefPtr<Gfx::SkiaBackendContext> const&);
- bool backing_stores_can_be_added_one_at_a_time() const;
- ErrorOr<BackingStore> create_backing_store_like_the_allocated_ones(i32 bitmap_id, RefPtr<Gfx::SkiaBackendContext> const&);
- static bool shared_surface_is_in_use(BackingStore const&);
- static bool store_can_be_rendered_into(BackingStore const&);
-
- int m_next_bitmap_id { 0 };
-
- // Used to track if backing stores need reallocation
- Gfx::IntSize m_allocated_size;
-
- Gfx::IntSize m_backing_store_size;
- PublicationMode m_publication_mode { PublicationMode::Unpublished };
- RefPtr<WindowServer> m_window_server_showing_stores;
- size_t m_initial_backing_store_count { 0 };
- Vector<BackingStore> m_backing_stores;
- Optional<size_t> m_rendering_store_index;
- Optional<size_t> m_latest_rendered_store_index;
-};
-
-}
diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txt
index 11833a423de..3c3780d70c8 100644
--- a/Services/Compositor/CMakeLists.txt
+++ b/Services/Compositor/CMakeLists.txt
@@ -1,6 +1,6 @@
set(SOURCES
AnimatedImage.cpp
- BackingStoreManager.cpp
+ BackingStoreFactory.cpp
BitmapExport.cpp
Canvas2DCommandPlayer.cpp
CanvasHost.cpp
diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cpp
index afc7939346e..102b0c6d44b 100644
--- a/Services/Compositor/CompositorState.cpp
+++ b/Services/Compositor/CompositorState.cpp
@@ -8,6 +8,7 @@
#include <AK/Random.h>
#include <AK/StdLibExtras.h>
#include <AK/TemporaryChange.h>
+#include <Compositor/BackingStoreFactory.h>
#include <Compositor/CanvasHost.h>
#include <Compositor/CompositorState.h>
#include <Compositor/SkiaUtils.h>
@@ -1089,96 +1090,68 @@ void CompositorState::end_painting()
m_display_list_players[--m_painting_depth]->end_painting();
}
-static BackingStoreManager::PublicationMode publication_mode_of(RustFFI::StorePublication publication)
-{
- switch (publication) {
- case RustFFI::StorePublication::Unpublished:
- return BackingStoreManager::PublicationMode::Unpublished;
- case RustFFI::StorePublication::Published:
- return BackingStoreManager::PublicationMode::Published;
- case RustFFI::StorePublication::ShownInRemoteLayer:
- return BackingStoreManager::PublicationMode::ShownInRemoteLayer;
- }
- VERIFY_NOT_REACHED();
+namespace {
+
+// An image of a store that the Rust core holds until it publishes the store.
+struct SharedImageToPublish {
+ AK_ALLOC_WITH_KMALLOC;
+
+ Gfx::SharedImage image;
+};
+
}
-RustFFI::StoreResizeOutcome CompositorState::resize_stores(Web::CompositorContextId context_id, RustFFI::FfiStoreResize const& resize)
+bool CompositorState::create_store(Web::CompositorContextId context_id, RustFFI::StoreKind kind, Gfx::IntSize size, RustFFI::FfiNewStore& new_store)
{
- auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();
- auto publication_mode = publication_mode_of(resize.publication);
- auto window_resize_in_progress = resize.window_resize_in_progress ? Compositing::WindowResizingInProgress::Yes : Compositing::WindowResizingInProgress::No;
- auto allocation = backing_stores.resize_backing_stores_if_needed(resize.raster_size, window_resize_in_progress, publication_mode);
- if (!allocation.has_value())
- return RustFFI::StoreResizeOutcome::Unchanged;
-
RefPtr<WindowServer> window_server_showing_stores;
- if (publication_mode == BackingStoreManager::PublicationMode::ShownInRemoteLayer) {
- auto* remote_layer = remote_layer_showing(context_id);
- VERIFY(remote_layer);
- window_server_showing_stores = remote_layer->window_server;
+ if (kind == RustFFI::StoreKind::ShownByWindowServer) {
+ if (auto* remote_layer = remote_layer_showing(context_id))
+ window_server_showing_stores = remote_layer->window_server;
}
- auto gpu_sharing = resize.gpu_sharing_allowed ? BackingStoreManager::GpuSharing::Allowed : BackingStoreManager::GpuSharing::Disallowed;
- auto publication = backing_stores.allocate_backing_stores(*allocation, m_skia_backend_context, publication_mode, gpu_sharing, move(window_server_showing_stores));
- if (publication.is_error()) {
- dbgln("Compositor: Failed to allocate the stores of context {} that a remote layer shows, which its presentation shows again: {}", context_id, publication.error());
- return RustFFI::StoreResizeOutcome::Failed;
+ auto store_or_error = create_backing_store(kind, size, m_skia_backend_context, window_server_showing_stores.ptr());
+ 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());
+ return false;
}
- if (!publication.value().has_value())
- return RustFFI::StoreResizeOutcome::ReallocatedOffscreen;
- if (publication_mode == BackingStoreManager::PublicationMode::Published) {
- auto* presentation = resize.has_presentation ? presentation_if_present(PresentationId { resize.presentation_id }) : nullptr;
- VERIFY(presentation);
- auto stores = publication.release_value().release_value();
- presentation->did_allocate_backing_stores(context_id, move(stores.bitmap_ids), move(stores.shared_images));
+ auto store = store_or_error.release_value();
+ new_store.surface = &store.surface.leak_ref();
+ if (store.window_server_surface)
+ new_store.window_server_surface = &store.window_server_surface.release_nonnull().leak_ref();
+ if (store.shared_image_buffer) {
+ new_store.shared_image_buffer = store.shared_image_buffer.leak_ptr();
+ new_store.shared_image_buffer_is_in_use = [](void* buffer) { return shared_image_buffer_is_in_use(*static_cast<Gfx::SharedImageBuffer const*>(buffer)); };
+ new_store.destroy_shared_image_buffer = [](void* buffer) { (void)adopt_own(*static_cast<Gfx::SharedImageBuffer*>(buffer)); };
}
- return RustFFI::StoreResizeOutcome::ReallocatedForViewer;
-}
-
-bool CompositorState::add_store_if_window_server_reads_every_released_store(Web::CompositorContextId context_id, Optional<PresentationId> publishing_presentation)
-{
- auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();
- auto publication = backing_stores.add_backing_store_if_window_server_still_reads_every_released_store(m_skia_backend_context);
- if (!publication.has_value())
- return false;
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} gained backing store {}, as the window server still reads every released one", context_id, publication->bitmap_ids);
- if (auto* presentation = publishing_presentation.has_value() ? presentation_if_present(*publishing_presentation) : nullptr)
- presentation->did_add_backing_stores(context_id, move(publication->bitmap_ids), move(publication->shared_images));
- return true;
-}
-
-bool CompositorState::retire_idle_surplus_stores(Web::CompositorContextId context_id, Optional<PresentationId> publishing_presentation)
-{
- auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();
- auto retired_bitmap_ids = backing_stores.retire_idle_surplus_backing_stores();
- if (auto* presentation = publishing_presentation.has_value() ? presentation_if_present(*publishing_presentation) : nullptr; presentation && !retired_bitmap_ids.is_empty()) {
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} retired idle backing stores {}", context_id, retired_bitmap_ids);
- presentation->did_retire_backing_stores(context_id, move(retired_bitmap_ids));
+ if (store.shared_image.has_value()) {
+ new_store.shared_image = make<SharedImageToPublish>(store.shared_image.release_value()).leak_ptr();
+ new_store.destroy_shared_image = [](void* image) { (void)adopt_own(*static_cast<SharedImageToPublish*>(image)); };
}
- return backing_stores.has_surplus_backing_stores();
+ return true;
}
-bool CompositorState::retire_stores_of_hidden_context(Web::CompositorContextId context_id, Optional<PresentationId> publishing_presentation)
+void CompositorState::publish_stores(PresentationId presentation_id, Web::CompositorContextId context_id, bool added, ReadonlySpan<i32> bitmap_ids, ReadonlySpan<void*> images)
{
- auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();
- auto retired_bitmap_ids = backing_stores.retire_backing_stores_except_the_latest_rendered();
- if (auto* presentation = publishing_presentation.has_value() ? presentation_if_present(*publishing_presentation) : nullptr; presentation && !retired_bitmap_ids.is_empty()) {
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} retired backing stores {} while hidden", context_id, retired_bitmap_ids);
- presentation->did_retire_backing_stores(context_id, move(retired_bitmap_ids));
+ Vector<Gfx::SharedImage> shared_images;
+ shared_images.ensure_capacity(images.size());
+ for (auto* image : images) {
+ auto owned_image = adopt_own(*static_cast<SharedImageToPublish*>(image));
+ shared_images.unchecked_append(move(owned_image->image));
}
- return backing_stores.has_backing_stores_left_to_retire_while_hidden();
+ auto* presentation = presentation_if_present(presentation_id);
+ if (!presentation)
+ return;
+ Vector<i32> ids { bitmap_ids };
+ if (added)
+ presentation->did_add_backing_stores(context_id, move(ids), move(shared_images));
+ else
+ presentation->did_allocate_backing_stores(context_id, move(ids), move(shared_images));
}
-bool CompositorState::restore_stores_retired_while_hidden(Web::CompositorContextId context_id, Optional<PresentationId> publishing_presentation)
+void CompositorState::retire_published_stores(PresentationId presentation_id, Web::CompositorContextId context_id, ReadonlySpan<i32> bitmap_ids)
{
- auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();
- auto publication = backing_stores.add_backing_stores_up_to_initial_count(m_skia_backend_context);
- if (!publication.has_value())
- return false;
- if (auto* presentation = publishing_presentation.has_value() ? presentation_if_present(*publishing_presentation) : nullptr; presentation && !publication->bitmap_ids.is_empty()) {
- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} regained backing stores {} as it was shown", context_id, publication->bitmap_ids);
- presentation->did_add_backing_stores(context_id, move(publication->bitmap_ids), move(publication->shared_images));
- }
- return true;
+ if (auto* presentation = presentation_if_present(presentation_id))
+ presentation->did_retire_backing_stores(context_id, Vector<i32> { bitmap_ids });
}
bool CompositorState::take_registered_image_frames(Web::CompositorContextId context_id, ReadonlySpan<u64> image_frame_ids)
@@ -1517,8 +1490,7 @@ Optional<PresentationId> CompositorState::show_frame_in_remote_layer(Web::Compos
if (!remote_layer)
return {};
auto& context = presented_context(context_id);
- auto* store = frame.uses_store ? context.raster_targets.backing_stores().window_server_surface_of_latest_rendered_store() : nullptr;
- VERIFY(store || !frame.uses_store);
+ auto* store = const_cast<PresentableSurface*>(frame.store);
auto remote_layer_id = *context.remote_layer_id;
auto shown = remote_layer->layer->show_frame({
@@ -1646,13 +1618,6 @@ static Optional<u64> display_of(bool has_display_id, u64 display_id)
return display_id;
}
-static Optional<PresentationId> presentation_of(bool has_presentation, u64 presentation_id)
-{
- if (!has_presentation)
- return {};
- return PresentationId { presentation_id };
-}
-
static MonotonicTime time_of(i64 nanoseconds)
{
return MonotonicTime {} + AK::Duration::from_nanoseconds(nanoseconds);
@@ -1688,27 +1653,9 @@ 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(); },
- .store_state = [](void* host, u64 context_id) -> RustFFI::FfiStoreState {
- auto const& backing_stores = state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores();
- return { .is_valid = backing_stores.is_valid(), .is_rendering = backing_stores.is_rendering(), .has_available_store = backing_stores.has_available_buffer() };
- },
- .resize_stores = [](void* host, u64 context_id, RustFFI::FfiStoreResize const* resize) { return state_of(host).resize_stores(Context { context_id }, *resize); },
- .invalidate_stores = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().invalidate(); },
- .acquire_store = [](void* host, u64 context_id, RustFFI::FfiAcquiredStore* acquired) {
- auto render_target = state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().acquire_render_target();
- if (!render_target.has_value())
- return false;
- acquired->bitmap_id = render_target->bitmap_id;
- acquired->surface = &render_target->surface;
- return true; },
- .complete_rendering = [](void* host, u64 context_id, i32 bitmap_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().complete_rendering(bitmap_id); },
- .release_store = [](void* host, u64 context_id, i32 bitmap_id) { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().release_buffer(bitmap_id); },
- .release_all_presented_stores = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().release_all_presented_buffers(); },
- .latest_rendered_store_surface = [](void* host, u64 context_id) -> Gfx::PaintingSurface const* { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().latest_rendered_surface().ptr(); },
- .add_store_if_window_server_reads_every_released_store = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).add_store_if_window_server_reads_every_released_store(Context { context_id }, presentation_of(has_presentation, presentation_id)); },
- .retire_idle_surplus_stores = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).retire_idle_surplus_stores(Context { context_id }, presentation_of(has_presentation, presentation_id)); },
- .retire_stores_of_hidden_context = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).retire_stores_of_hidden_context(Context { context_id }, presentation_of(has_presentation, presentation_id)); },
- .restore_stores_retired_while_hidden = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).restore_stores_retired_while_hidden(Context { context_id }, presentation_of(has_presentation, presentation_id)); },
+ .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); },
+ .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* {
auto surface = PresentableSurfacePool::create_surface(size, like->skia_backend_context());
if (surface.is_error())
diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.h
index 5fcede539f8..923974c1e8e 100644
--- a/Services/Compositor/CompositorState.h
+++ b/Services/Compositor/CompositorState.h
@@ -228,11 +228,9 @@ 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();
- RustFFI::StoreResizeOutcome resize_stores(Web::CompositorContextId, RustFFI::FfiStoreResize const&);
- bool add_store_if_window_server_reads_every_released_store(Web::CompositorContextId, Optional<PresentationId>);
- bool retire_idle_surplus_stores(Web::CompositorContextId, Optional<PresentationId>);
- bool retire_stores_of_hidden_context(Web::CompositorContextId, Optional<PresentationId>);
- bool restore_stores_retired_while_hidden(Web::CompositorContextId, Optional<PresentationId>);
+ bool create_store(Web::CompositorContextId, RustFFI::StoreKind, Gfx::IntSize, 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);
void set_drawn_image_frames(Web::CompositorContextId, ReadonlySpan<u64> image_frame_ids);
void set_drawn_video_sinks(Web::CompositorContextId, ReadonlySpan<u64> handles);
diff --git a/Services/Compositor/ContextRasterTargets.h b/Services/Compositor/ContextRasterTargets.h
index 1dadada7430..2f0ca40ff7e 100644
--- a/Services/Compositor/ContextRasterTargets.h
+++ b/Services/Compositor/ContextRasterTargets.h
@@ -13,7 +13,6 @@
#include <AK/RefPtr.h>
#include <AK/Span.h>
#include <AK/StringView.h>
-#include <Compositor/BackingStoreManager.h>
#include <Compositor/CanvasSurfaceRegistry.h>
#include <Compositor/CompositorCoreHost.h>
#include <Compositor/DisplayListRasterCache.h>
@@ -55,9 +54,6 @@ public:
// Shapes a label of the overlays, in a font that the overlays' fonts then hold.
Optional<OverlayLabel> shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text);
- BackingStoreManager& backing_stores() { return m_backing_stores; }
- BackingStoreManager const& backing_stores() const { return m_backing_stores; }
-
// The video sinks that the display list of the context draws. Answers whether these are other sinks than before.
bool set_drawn_video_sinks(ReadonlySpan<u64> handles);
HashTable<Media::VideoSinkHandle> const& drawn_video_sinks() const { return m_drawn_video_sinks; }
@@ -70,7 +66,6 @@ private:
OwnedCanvasSurfaces m_canvas_surfaces;
DrawnFonts m_overlay_fonts;
DisplayListRasterCache m_overlay_raster_cache;
- BackingStoreManager m_backing_stores;
HashTable<Media::VideoSinkHandle> m_drawn_video_sinks;
};
diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rs
index 228302aa5cd..a99dc685126 100644
--- a/Services/Compositor/Rust/build.rs
+++ b/Services/Compositor/Rust/build.rs
@@ -79,6 +79,7 @@ fn main() -> Result<(), Box<dyn Error>> {
"src/raster_host.rs",
"src/core/presenting.rs",
"src/core/mod.rs",
+ "src/backing_stores.rs",
"src/surfaces/painting_surface.rs",
"src/surfaces/presentable_surface.rs",
] {
diff --git a/Services/Compositor/Rust/src/backing_stores.rs b/Services/Compositor/Rust/src/backing_stores.rs
new file mode 100644
index 00000000000..c582faea5c0
--- /dev/null
+++ b/Services/Compositor/Rust/src/backing_stores.rs
@@ -0,0 +1,878 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The backing stores of a context: the surfaces its frames are rendered into, each of which is in turn rendered into,
+//! shown, and free again. The surfaces and the images they share with the presentation are made by the raster host.
+
+use crate::surfaces::painting_surface::PaintingSurface;
+use crate::surfaces::presentable_surface::PresentableSurface;
+use libgfx_rust::IntSize;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::rc::Rc;
+
+/// Who shows the backing stores of a context.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum StorePublication {
+ #[default]
+ Unpublished,
+ /// The presentation shows the stores, and releases each when it shows another.
+ Published,
+ /// The compositor shows the stores itself, in a remote layer, so a store is replaced on screen by the next one.
+ ShownInRemoteLayer,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StoreResizeOutcome {
+ Unchanged,
+ /// The stores were reallocated, and nothing that shows them was given them.
+ ReallocatedOffscreen,
+ /// The presentation or the remote layer that shows the stores was given the new ones.
+ ReallocatedForViewer,
+ /// The stores of a remote layer could not be allocated.
+ Failed,
+}
+
+/// How a store is made.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum StoreKind {
+ /// A surface nobody else sees.
+ Offscreen,
+ /// A bitmap in memory shared with the presentation, which a GPU surface is copied into on flush where there is one.
+ SharedBitmap,
+ /// A GPU image shared with the presentation, where the platform has those.
+ SharedGpuImage,
+ /// A surface the window server of the remote layer that shows the context shows by itself.
+ ShownByWindowServer,
+}
+
+/// The memory of a store that is shared with the presentation, which is C++ and which the store owns.
+pub struct SharedImageBuffer {
+ buffer: NonNull<c_void>,
+ is_in_use: unsafe extern "C" fn(*mut c_void) -> bool,
+ destroy: unsafe extern "C" fn(*mut c_void),
+}
+
+impl SharedImageBuffer {
+ fn is_in_use(&self) -> bool {
+ // SAFETY: The buffer is live for as long as this.
+ unsafe { (self.is_in_use)(self.buffer.as_ptr()) }
+ }
+}
+
+impl Drop for SharedImageBuffer {
+ fn drop(&mut self) {
+ // SAFETY: This owns the buffer.
+ unsafe { (self.destroy)(self.buffer.as_ptr()) };
+ }
+}
+
+/// An image of a store for the presentation to import, which is C++, and which is destroyed unless it is handed over.
+pub struct SharedImageToPublish {
+ image: NonNull<c_void>,
+ destroy: unsafe extern "C" fn(*mut c_void),
+}
+
+impl SharedImageToPublish {
+ /// Hands the image over to whoever publishes it.
+ pub fn into_raw(self) -> *mut c_void {
+ let image = self.image.as_ptr();
+ std::mem::forget(self);
+ image
+ }
+}
+
+impl Drop for SharedImageToPublish {
+ fn drop(&mut self) {
+ // SAFETY: This owns the image.
+ unsafe { (self.destroy)(self.image.as_ptr()) };
+ }
+}
+
+/// A store the raster host made, as it hands it over: one reference to each surface, and the C++ objects with the
+/// functions that answer for and destroy them.
+#[repr(C)]
+pub struct FfiNewStore {
+ pub surface: *const PaintingSurface,
+ /// Null for a store the window server does not show by itself.
+ pub window_server_surface: *const PresentableSurface,
+ /// Null for a store whose memory is not shared with the presentation.
+ pub shared_image_buffer: *mut c_void,
+ pub shared_image_buffer_is_in_use: Option<unsafe extern "C" fn(*mut c_void) -> bool>,
+ pub destroy_shared_image_buffer: Option<unsafe extern "C" fn(*mut c_void)>,
+ /// Null for a store the presentation does not import.
+ pub shared_image: *mut c_void,
+ pub destroy_shared_image: Option<unsafe extern "C" fn(*mut c_void)>,
+}
+
+impl Default for FfiNewStore {
+ fn default() -> Self {
+ Self {
+ surface: std::ptr::null(),
+ window_server_surface: std::ptr::null(),
+ shared_image_buffer: std::ptr::null_mut(),
+ shared_image_buffer_is_in_use: None,
+ destroy_shared_image_buffer: None,
+ shared_image: std::ptr::null_mut(),
+ destroy_shared_image: None,
+ }
+ }
+}
+
+pub struct NewStore {
+ pub surface: Rc<PaintingSurface>,
+ pub window_server_surface: Option<Rc<PresentableSurface>>,
+ pub shared_image_buffer: Option<SharedImageBuffer>,
+ pub shared_image: Option<SharedImageToPublish>,
+}
+
+impl NewStore {
+ /// # Safety
+ ///
+ /// Every pointer of the store must be live and handed over, with the functions that go with it.
+ pub unsafe fn adopt(store: FfiNewStore) -> Option<NewStore> {
+ // SAFETY: The caller hands over one reference to each surface, or null.
+ let (surface, window_server_surface) = unsafe {
+ (
+ PaintingSurface::adopted_from_ffi(store.surface),
+ PresentableSurface::adopted_from_ffi(store.window_server_surface),
+ )
+ };
+ let shared_image_buffer = NonNull::new(store.shared_image_buffer).map(|buffer| SharedImageBuffer {
+ buffer,
+ is_in_use: store
+ .shared_image_buffer_is_in_use
+ .expect("a shared buffer comes with its use check"),
+ destroy: store
+ .destroy_shared_image_buffer
+ .expect("a shared buffer comes with its destroy function"),
+ });
+ let shared_image = NonNull::new(store.shared_image).map(|image| SharedImageToPublish {
+ image,
+ destroy: store
+ .destroy_shared_image
+ .expect("a shared image comes with its destroy function"),
+ });
+ Some(NewStore {
+ surface: surface?,
+ window_server_surface,
+ shared_image_buffer,
+ shared_image,
+ })
+ }
+}
+
+/// Makes the stores of a context, or answers none where one could not be made.
+pub trait StoreFactory {
+ fn create_store(&mut self, kind: StoreKind, size: IntSize) -> Option<NewStore>;
+}
+
+impl<F: FnMut(StoreKind, IntSize) -> Option<NewStore>> StoreFactory for F {
+ fn create_store(&mut self, kind: StoreKind, size: IntSize) -> Option<NewStore> {
+ self(kind, size)
+ }
+}
+
+/// Stores that were allocated or added, with the images the presentation imports, if it shows the stores.
+#[derive(Default)]
+pub struct Publication {
+ pub bitmap_ids: Vec<i32>,
+ pub shared_images: Vec<SharedImageToPublish>,
+}
+
+pub enum AllocationOutcome {
+ /// Nothing that shows the stores was given them.
+ Offscreen,
+ /// The presentation or the remote layer that shows the stores is to be given the new ones.
+ ForViewer(Publication),
+ /// The stores of a remote layer could not be made.
+ Failed,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum StoreState {
+ Available,
+ Rendering,
+ Presented,
+}
+
+struct BackingStore {
+ surface: Rc<PaintingSurface>,
+ shared_image_buffer: Option<SharedImageBuffer>,
+ window_server_surface: Option<Rc<PresentableSurface>>,
+ bitmap_id: i32,
+ state: StoreState,
+ was_shown_on_screen: bool,
+ was_rendered_into_since_last_retirement_check: bool,
+}
+
+impl BackingStore {
+ fn new(store: NewStore, bitmap_id: i32, state: StoreState) -> (BackingStore, Option<SharedImageToPublish>) {
+ (
+ BackingStore {
+ surface: store.surface,
+ shared_image_buffer: store.shared_image_buffer,
+ window_server_surface: store.window_server_surface,
+ bitmap_id,
+ state,
+ was_shown_on_screen: false,
+ was_rendered_into_since_last_retirement_check: false,
+ },
+ store.shared_image,
+ )
+ }
+
+ fn shared_surface_is_in_use(&self) -> bool {
+ if let Some(window_server_surface) = &self.window_server_surface {
+ return window_server_surface.is_read_by_window_server();
+ }
+ // The share exported to the presentation counts as use too, so a store published a moment ago reads as in use
+ // until the presentation imported it.
+ self.shared_image_buffer
+ .as_ref()
+ .is_some_and(SharedImageBuffer::is_in_use)
+ }
+
+ fn can_be_rendered_into(&self) -> bool {
+ if self.state != StoreState::Available {
+ return false;
+ }
+ // Only a store shown on screen is handed to the window server, so whatever uses a store that never was is the
+ // share on its way to the presentation.
+ if !self.was_shown_on_screen {
+ return true;
+ }
+ !self.shared_surface_is_in_use()
+ }
+}
+
+const MAXIMUM_BACKING_STORE_COUNT: usize = 8;
+const RESIZE_PADDING: i32 = 256;
+
+// A store shown on screen is let go of when the next one is shown, but on macOS the window server is handed the surface
+// itself, and keeps reading it until it has composited the replacement. A third store lets the compositor keep
+// rendering through that window instead of waiting for it.
+fn backing_store_count_for(publication: StorePublication) -> usize {
+ if cfg!(target_os = "macos") && publication != StorePublication::Unpublished {
+ return 3;
+ }
+ 2
+}
+
+// Whether the memory of a 32-bit bitmap of the size could not be addressed.
+fn bitmap_size_would_overflow(size: IntSize) -> bool {
+ if size.width < 0 || size.height < 0 || size.width > i32::from(u16::MAX) || size.height > i32::from(u16::MAX) {
+ return true;
+ }
+ (size.width * 4).checked_mul(size.height).is_none()
+}
+
+/// An allocation of new stores of the size, which replaces the stores there are.
+pub struct Allocation {
+ size: IntSize,
+ bitmap_ids: Vec<i32>,
+}
+
+#[derive(Default)]
+pub struct BackingStores {
+ next_bitmap_id: i32,
+ // What the stores were allocated for, which a new allocation replaces. Empty when the stores need allocating.
+ allocated_size: IntSize,
+ store_size: IntSize,
+ publication: StorePublication,
+ initial_store_count: usize,
+ stores: Vec<BackingStore>,
+ rendering_store_index: Option<usize>,
+ latest_rendered_store_index: Option<usize>,
+}
+
+impl BackingStores {
+ pub fn invalidate(&mut self) {
+ self.allocated_size = IntSize::default();
+ }
+
+ pub fn publication(&self) -> StorePublication {
+ self.publication
+ }
+
+ pub fn is_valid(&self) -> bool {
+ !self.stores.is_empty()
+ }
+
+ pub fn is_rendering(&self) -> bool {
+ self.rendering_store_index.is_some()
+ }
+
+ pub fn has_available_store(&self) -> bool {
+ self.stores.iter().any(BackingStore::can_be_rendered_into)
+ }
+
+ pub fn has_surplus_stores(&self) -> bool {
+ self.stores.len() > self.initial_store_count
+ }
+
+ pub fn resize_if_needed(
+ &mut self,
+ viewport_size: IntSize,
+ window_resize_in_progress: bool,
+ publication: StorePublication,
+ ) -> Option<Allocation> {
+ if viewport_size.is_empty() {
+ return None;
+ }
+ let mut allocation_size = viewport_size;
+ let mut needs_allocation = self.allocated_size.is_empty();
+ if window_resize_in_progress {
+ // The stores are padded so that they need not be reallocated while the window is resized. Ones that still
+ // hold the viewport are kept.
+ allocation_size = IntSize {
+ width: viewport_size.width + RESIZE_PADDING,
+ height: viewport_size.height + RESIZE_PADDING,
+ };
+ needs_allocation |= !(self.allocated_size.width >= viewport_size.width
+ && self.allocated_size.height >= viewport_size.height);
+ } else {
+ needs_allocation |= self.allocated_size != viewport_size;
+ }
+ if !needs_allocation {
+ return None;
+ }
+ self.allocated_size = allocation_size;
+ let bitmap_ids = (0..backing_store_count_for(publication))
+ .map(|_| self.take_bitmap_id())
+ .collect();
+ Some(Allocation {
+ size: allocation_size,
+ bitmap_ids,
+ })
+ }
+
+ fn take_bitmap_id(&mut self) -> i32 {
+ let bitmap_id = self.next_bitmap_id;
+ self.next_bitmap_id += 1;
+ bitmap_id
+ }
+
+ pub fn allocate(
+ &mut self,
+ allocation: Allocation,
+ publication: StorePublication,
+ shares_gpu_images: bool,
+ factory: &mut dyn StoreFactory,
+ ) -> AllocationOutcome {
+ self.stores.clear();
+ self.rendering_store_index = None;
+ self.latest_rendered_store_index = None;
+ self.publication = publication;
+ if bitmap_size_would_overflow(allocation.size) {
+ return AllocationOutcome::Offscreen;
+ }
+ self.store_size = allocation.size;
+ self.initial_store_count = allocation.bitmap_ids.len();
+
+ match publication {
+ StorePublication::Unpublished => {
+ for &bitmap_id in &allocation.bitmap_ids {
+ let Some(store) = factory.create_store(StoreKind::Offscreen, allocation.size) else {
+ self.stores.clear();
+ self.invalidate();
+ break;
+ };
+ self.stores
+ .push(BackingStore::new(store, bitmap_id, StoreState::Available).0);
+ }
+ AllocationOutcome::Offscreen
+ }
+ StorePublication::ShownInRemoteLayer => {
+ for &bitmap_id in &allocation.bitmap_ids {
+ let Some(store) = factory.create_store(StoreKind::ShownByWindowServer, allocation.size) else {
+ self.stores.clear();
+ self.invalidate();
+ return AllocationOutcome::Failed;
+ };
+ self.stores
+ .push(BackingStore::new(store, bitmap_id, StoreState::Available).0);
+ }
+ AllocationOutcome::ForViewer(Publication {
+ bitmap_ids: allocation.bitmap_ids,
+ shared_images: Vec::new(),
+ })
+ }
+ StorePublication::Published => {
+ if shares_gpu_images
+ && let Some(publication) = self.allocate_published(&allocation, StoreKind::SharedGpuImage, factory)
+ {
+ return AllocationOutcome::ForViewer(publication);
+ }
+ match self.allocate_published(&allocation, StoreKind::SharedBitmap, factory) {
+ Some(publication) => AllocationOutcome::ForViewer(publication),
+ None => {
+ self.invalidate();
+ AllocationOutcome::Offscreen
+ }
+ }
+ }
+ }
+ }
+
+ // The presentation installs the first published store as its first front store, and keeps it until it presents
+ // another one.
+ fn allocate_published(
+ &mut self,
+ allocation: &Allocation,
+ kind: StoreKind,
+ factory: &mut dyn StoreFactory,
+ ) -> Option<Publication> {
+ let mut shared_images = Vec::with_capacity(allocation.bitmap_ids.len());
+ for (index, &bitmap_id) in allocation.bitmap_ids.iter().enumerate() {
+ let state = if index == 0 {
+ StoreState::Presented
+ } else {
+ StoreState::Available
+ };
+ let Some(store) = factory.create_store(kind, allocation.size) else {
+ self.stores.clear();
+ return None;
+ };
+ let (store, shared_image) = BackingStore::new(store, bitmap_id, state);
+ self.stores.push(store);
+ shared_images.push(shared_image.expect("a published store has an image for the presentation"));
+ }
+ Some(Publication {
+ bitmap_ids: allocation.bitmap_ids.clone(),
+ shared_images,
+ })
+ }
+
+ // GPU stores shared with the presentation are only ever allocated together, as the presentation installs them.
+ fn stores_can_be_added_one_at_a_time(&self) -> bool {
+ let Some(first) = self.stores.first() else {
+ return false;
+ };
+ self.publication != StorePublication::Published || first.shared_image_buffer.is_some()
+ }
+
+ fn kind_of_added_stores(&self) -> StoreKind {
+ match self.publication {
+ StorePublication::Unpublished => StoreKind::Offscreen,
+ StorePublication::Published => StoreKind::SharedBitmap,
+ StorePublication::ShownInRemoteLayer => StoreKind::ShownByWindowServer,
+ }
+ }
+
+ fn add_store(&mut self, factory: &mut dyn StoreFactory, publication: &mut Publication) -> bool {
+ let Some(store) = factory.create_store(self.kind_of_added_stores(), self.store_size) else {
+ return false;
+ };
+ let bitmap_id = self.take_bitmap_id();
+ let (store, shared_image) = BackingStore::new(store, bitmap_id, StoreState::Available);
+ self.stores.push(store);
+ publication.bitmap_ids.push(bitmap_id);
+ if self.publication == StorePublication::Published {
+ publication
+ .shared_images
+ .push(shared_image.expect("a published store has an image for the presentation"));
+ }
+ true
+ }
+
+ /// The window server lets go of a store some time after the presentation replaced it on screen, which at high
+ /// refresh rates can be later than the next frame is due. Rather than hold that frame back, it is given a store of
+ /// its own. While the presentation has yet to take a frame, or to release a store, there is no telling what the
+ /// window server holds, and the frame waits as it always did.
+ pub fn add_store_if_window_server_still_reads_every_released_store(
+ &mut self,
+ factory: &mut dyn StoreFactory,
+ ) -> Option<Publication> {
+ let latest_rendered_store_index = self.latest_rendered_store_index?;
+ if self.is_rendering() || self.stores.len() >= MAXIMUM_BACKING_STORE_COUNT {
+ return None;
+ }
+ for (index, store) in self.stores.iter().enumerate() {
+ if store.shared_image_buffer.is_none() && store.window_server_surface.is_none() {
+ return None;
+ }
+ let presentation_shows_store = index == latest_rendered_store_index;
+ if presentation_shows_store && store.state != StoreState::Presented {
+ return None;
+ }
+ if !presentation_shows_store && (store.state != StoreState::Available || store.can_be_rendered_into()) {
+ return None;
+ }
+ }
+ let mut publication = Publication::default();
+ self.add_store(factory, &mut publication).then_some(publication)
+ }
+
+ fn remove_store(&mut self, index: usize) -> i32 {
+ let store = self.stores.remove(index);
+ if let Some(latest) = self.latest_rendered_store_index
+ && latest > index
+ {
+ self.latest_rendered_store_index = Some(latest - 1);
+ }
+ store.bitmap_id
+ }
+
+ /// A store added for a burst of frames is given back once a whole interval between two checks went by without it
+ /// being rendered into. The stores that stay are the ones first in line for the next frame. Answers the stores
+ /// that were retired.
+ pub fn retire_idle_surplus_stores(&mut self) -> Vec<i32> {
+ let mut retired_bitmap_ids = Vec::new();
+ if self.is_rendering() {
+ return retired_bitmap_ids;
+ }
+ for index in (0..self.stores.len()).rev() {
+ if !self.has_surplus_stores() {
+ break;
+ }
+ let store = &self.stores[index];
+ if self.latest_rendered_store_index == Some(index)
+ || store.state != StoreState::Available
+ || store.was_rendered_into_since_last_retirement_check
+ || store.shared_surface_is_in_use()
+ {
+ continue;
+ }
+ retired_bitmap_ids.push(self.remove_store(index));
+ }
+ for store in &mut self.stores {
+ store.was_rendered_into_since_last_retirement_check = false;
+ }
+ retired_bitmap_ids
+ }
+
+ /// A hidden context keeps only the store that holds its latest frame, which is what shows it until it is shown
+ /// again, and what a snapshot of it is taken from. Before any frame, the store reserved as the presentation's first
+ /// front store stays too. Answers the stores that were retired.
+ pub fn retire_stores_except_the_latest_rendered(&mut self) -> Vec<i32> {
+ let mut retired_bitmap_ids = Vec::new();
+ if self.is_rendering() {
+ return retired_bitmap_ids;
+ }
+ for index in (0..self.stores.len()).rev() {
+ let store = &self.stores[index];
+ if self.latest_rendered_store_index == Some(index)
+ || store.state != StoreState::Available
+ || store.shared_surface_is_in_use()
+ {
+ continue;
+ }
+ retired_bitmap_ids.push(self.remove_store(index));
+ }
+ // Stores that never held a frame are allocated anew when the context is shown.
+ if self.stores.is_empty() {
+ self.invalidate();
+ }
+ retired_bitmap_ids
+ }
+
+ /// Whether a store that the hidden context does not keep is still rendered into, shown, or read by the window
+ /// server, and can be retired once it no longer is.
+ pub fn has_stores_left_to_retire_while_hidden(&self) -> bool {
+ self.stores.iter().enumerate().any(|(index, store)| {
+ if self.latest_rendered_store_index == Some(index) {
+ return false;
+ }
+ match store.state {
+ StoreState::Rendering => true,
+ // Before any frame, a presented store is the one reserved as the presentation's first front store,
+ // which the presentation holds until it is shown a frame.
+ StoreState::Presented => self.latest_rendered_store_index.is_some(),
+ StoreState::Available => store.shared_surface_is_in_use(),
+ }
+ })
+ }
+
+ /// Gives a context that was shown again the stores it had before it was hidden. Answers none where they can't be
+ /// added to the ones it kept, or one could not be made, as the context then needs a whole new allocation.
+ pub fn add_stores_up_to_initial_count(&mut self, factory: &mut dyn StoreFactory) -> Option<Publication> {
+ if !self.stores_can_be_added_one_at_a_time() {
+ return None;
+ }
+ let mut publication = Publication::default();
+ while self.stores.len() < self.initial_store_count {
+ if !self.add_store(factory, &mut publication) {
+ return None;
+ }
+ }
+ Some(publication)
+ }
+
+ pub fn acquire_render_target(&mut self) -> Option<(i32, Rc<PaintingSurface>)> {
+ assert!(
+ self.rendering_store_index.is_none(),
+ "one store is rendered into at a time"
+ );
+ let index = self.stores.iter().position(BackingStore::can_be_rendered_into)?;
+ let store = &mut self.stores[index];
+ store.state = StoreState::Rendering;
+ store.was_rendered_into_since_last_retirement_check = true;
+ self.rendering_store_index = Some(index);
+ Some((store.bitmap_id, store.surface.clone()))
+ }
+
+ pub fn complete_rendering(&mut self, bitmap_id: i32) {
+ let index = self.rendering_store_index.take().expect("a store is rendered into");
+ assert_eq!(
+ self.stores[index].bitmap_id, bitmap_id,
+ "the store rendered into completes"
+ );
+ assert_eq!(self.stores[index].state, StoreState::Rendering);
+ let presentation_releases_presented_stores = self.publication == StorePublication::Published;
+ if !presentation_releases_presented_stores && let Some(latest) = self.latest_rendered_store_index {
+ self.stores[latest].state = StoreState::Available;
+ }
+ let store = &mut self.stores[index];
+ store.state = StoreState::Presented;
+ if self.publication != StorePublication::Unpublished {
+ store.was_shown_on_screen = true;
+ }
+ self.latest_rendered_store_index = Some(index);
+ }
+
+ /// Answers whether a store that was presented became available.
+ pub fn release_store(&mut self, bitmap_id: i32) -> bool {
+ let Some(store) = self
+ .stores
+ .iter_mut()
+ .find(|store| store.bitmap_id == bitmap_id && store.state == StoreState::Presented)
+ else {
+ return false;
+ };
+ store.state = StoreState::Available;
+ true
+ }
+
+ pub fn release_all_presented_stores(&mut self) {
+ for store in &mut self.stores {
+ if store.state == StoreState::Presented {
+ store.state = StoreState::Available;
+ }
+ }
+ }
+
+ pub fn latest_rendered_surface(&self) -> Option<Rc<PaintingSurface>> {
+ Some(self.stores[self.latest_rendered_store_index?].surface.clone())
+ }
+
+ pub fn window_server_surface_of_latest_rendered_store(&self) -> Option<&Rc<PresentableSurface>> {
+ self.stores[self.latest_rendered_store_index?]
+ .window_server_surface
+ .as_ref()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::surfaces::painting_surface::testing::surface_for_testing;
+ use std::cell::Cell;
+
+ unsafe extern "C" fn destroy_nothing(_: *mut c_void) {}
+
+ thread_local! {
+ static SHARED_BUFFERS_IN_USE: Cell<bool> = const { Cell::new(false) };
+ }
+
+ unsafe extern "C" fn shared_buffer_in_use(_: *mut c_void) -> bool {
+ SHARED_BUFFERS_IN_USE.with(Cell::get)
+ }
+
+ fn factory(fail_kind: Option<StoreKind>) -> impl FnMut(StoreKind, IntSize) -> Option<NewStore> {
+ move |kind, size| {
+ if Some(kind) == fail_kind {
+ return None;
+ }
+ let shares_memory = kind == StoreKind::SharedBitmap;
+ let published = matches!(kind, StoreKind::SharedBitmap | StoreKind::SharedGpuImage);
+ Some(NewStore {
+ surface: surface_for_testing(size, 0),
+ window_server_surface: None,
+ shared_image_buffer: shares_memory.then(|| SharedImageBuffer {
+ buffer: NonNull::dangling(),
+ is_in_use: shared_buffer_in_use,
+ destroy: destroy_nothing,
+ }),
+ shared_image: published.then(|| SharedImageToPublish {
+ image: NonNull::dangling(),
+ destroy: destroy_nothing,
+ }),
+ })
+ }
+ }
+
+ const VIEWPORT: IntSize = IntSize { width: 100, height: 50 };
+
+ // Each store completes its frame before the next is rendered into, as many as the platform allocates.
+ fn render_into_every_available_store(stores: &mut BackingStores) -> Vec<i32> {
+ let mut rendered = Vec::new();
+ while let Some((bitmap_id, _)) = stores.acquire_render_target() {
+ stores.complete_rendering(bitmap_id);
+ rendered.push(bitmap_id);
+ }
+ rendered
+ }
+
+ fn allocated(publication: StorePublication, shares_gpu_images: bool) -> (BackingStores, AllocationOutcome) {
+ let mut stores = BackingStores::default();
+ let allocation = stores.resize_if_needed(VIEWPORT, false, publication).unwrap();
+ let outcome = stores.allocate(allocation, publication, shares_gpu_images, &mut factory(None));
+ (stores, outcome)
+ }
+
+ #[test]
+ fn stores_are_reallocated_only_when_the_viewport_changes() {
+ let (mut stores, _) = allocated(StorePublication::Unpublished, false);
+ assert!(
+ stores
+ .resize_if_needed(VIEWPORT, false, StorePublication::Unpublished)
+ .is_none()
+ );
+ let larger = IntSize { width: 120, height: 50 };
+ assert!(
+ stores
+ .resize_if_needed(larger, false, StorePublication::Unpublished)
+ .is_some()
+ );
+ }
+
+ #[test]
+ fn stores_are_padded_while_the_window_is_resized() {
+ let mut stores = BackingStores::default();
+ let allocation = stores
+ .resize_if_needed(VIEWPORT, true, StorePublication::Unpublished)
+ .unwrap();
+ assert_eq!(
+ allocation.size,
+ IntSize {
+ width: 356,
+ height: 306
+ }
+ );
+ stores.allocate(allocation, StorePublication::Unpublished, false, &mut factory(None));
+ let a_bit_larger = IntSize { width: 150, height: 80 };
+ assert!(
+ stores
+ .resize_if_needed(a_bit_larger, true, StorePublication::Unpublished)
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn the_first_published_store_is_held_by_the_presentation() {
+ let (mut stores, outcome) = allocated(StorePublication::Published, false);
+ let AllocationOutcome::ForViewer(publication) = outcome else {
+ panic!("published stores go to the presentation");
+ };
+ assert_eq!(publication.bitmap_ids.len(), publication.shared_images.len());
+ let (bitmap_id, _) = stores.acquire_render_target().unwrap();
+ assert_ne!(bitmap_id, publication.bitmap_ids[0]);
+ }
+
+ #[test]
+ fn shared_gpu_images_fall_back_to_shared_bitmaps() {
+ let mut stores = BackingStores::default();
+ let allocation = stores
+ .resize_if_needed(VIEWPORT, false, StorePublication::Published)
+ .unwrap();
+ let outcome = stores.allocate(
+ allocation,
+ StorePublication::Published,
+ true,
+ &mut factory(Some(StoreKind::SharedGpuImage)),
+ );
+ assert!(matches!(outcome, AllocationOutcome::ForViewer(_)));
+ assert!(stores.stores_can_be_added_one_at_a_time());
+ }
+
+ #[test]
+ fn stores_of_a_remote_layer_that_cannot_be_made_fail_the_allocation() {
+ let mut stores = BackingStores::default();
+ let allocation = stores
+ .resize_if_needed(VIEWPORT, false, StorePublication::ShownInRemoteLayer)
+ .unwrap();
+ let outcome = stores.allocate(
+ allocation,
+ StorePublication::ShownInRemoteLayer,
+ false,
+ &mut factory(Some(StoreKind::ShownByWindowServer)),
+ );
+ assert!(matches!(outcome, AllocationOutcome::Failed));
+ assert!(!stores.is_valid());
+ }
+
+ #[test]
+ fn an_unpublished_store_becomes_available_once_the_next_frame_completes() {
+ let (mut stores, _) = allocated(StorePublication::Unpublished, false);
+ let (first, _) = stores.acquire_render_target().unwrap();
+ stores.complete_rendering(first);
+ let (second, _) = stores.acquire_render_target().unwrap();
+ assert_ne!(first, second);
+ stores.complete_rendering(second);
+ let (third, _) = stores.acquire_render_target().unwrap();
+ assert_eq!(third, first);
+ }
+
+ #[test]
+ fn a_published_store_waits_for_the_presentation_to_release_it() {
+ let (mut stores, _) = allocated(StorePublication::Published, false);
+ let rendered = render_into_every_available_store(&mut stores);
+ assert!(!stores.has_available_store());
+ let latest = *rendered.last().unwrap();
+ assert!(stores.release_store(latest));
+ assert!(!stores.release_store(latest));
+ assert!(stores.has_available_store());
+ }
+
+ #[test]
+ fn surplus_stores_are_retired_after_an_idle_interval() {
+ let (mut stores, _) = allocated(StorePublication::Published, false);
+ let (rendered, _) = stores.acquire_render_target().unwrap();
+ stores.complete_rendering(rendered);
+ let first_front_store_bitmap_id = 0;
+ assert!(stores.release_store(first_front_store_bitmap_id));
+ // A store that is not shown is free, so no store is added.
+ assert!(
+ stores
+ .add_store_if_window_server_still_reads_every_released_store(&mut factory(None))
+ .is_none()
+ );
+ // Every store that is not shown was shown before, and the window server still reads it.
+ SHARED_BUFFERS_IN_USE.with(|in_use| in_use.set(true));
+ let latest_rendered_store_index = stores.latest_rendered_store_index;
+ for (index, store) in stores.stores.iter_mut().enumerate() {
+ if Some(index) != latest_rendered_store_index {
+ store.was_shown_on_screen = true;
+ }
+ }
+ let added = stores
+ .add_store_if_window_server_still_reads_every_released_store(&mut factory(None))
+ .unwrap();
+ SHARED_BUFFERS_IN_USE.with(|in_use| in_use.set(false));
+ assert_eq!(added.bitmap_ids.len(), 1);
+ assert!(stores.has_surplus_stores());
+ // The added store was not rendered into since it was added, so it goes at the next check.
+ assert_eq!(stores.retire_idle_surplus_stores(), added.bitmap_ids);
+ assert!(!stores.has_surplus_stores());
+ }
+
+ #[test]
+ fn a_hidden_context_keeps_only_its_latest_frame_and_gets_its_stores_back() {
+ let (mut stores, _) = allocated(StorePublication::Unpublished, false);
+ let (rendered, _) = stores.acquire_render_target().unwrap();
+ stores.complete_rendering(rendered);
+ assert_eq!(stores.retire_stores_except_the_latest_rendered().len(), 1);
+ assert!(!stores.has_stores_left_to_retire_while_hidden());
+ let restored = stores.add_stores_up_to_initial_count(&mut factory(None)).unwrap();
+ assert_eq!(restored.bitmap_ids.len(), 1);
+ assert_eq!(
+ stores.latest_rendered_surface().map(|surface| surface.size()),
+ Some(VIEWPORT)
+ );
+ }
+}
diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rs
index bea838e923b..fe619bf3cae 100644
--- a/Services/Compositor/Rust/src/core/mod.rs
+++ b/Services/Compositor/Rust/src/core/mod.rs
@@ -415,12 +415,7 @@ impl CompositorCore {
fn invalidate_and_resize_backing_stores(&self, context_id: CompositorContextId, now: MonotonicTime) {
if let Some(presenting) = self.presenting_of(context_id) {
- let environment = self.environment(
- context_id,
- now,
- &libcompositing_rust::display_list::replay::NoCompositedContexts,
- );
- presenting.borrow_mut().invalidate_backing_stores(&environment);
+ presenting.borrow_mut().invalidate_backing_stores();
}
self.resize_backing_stores_if_needed(context_id, now);
}
@@ -622,10 +617,10 @@ impl CompositorCore {
pub fn presented_store_released(&self, context_id: CompositorContextId, bitmap_id: i32, now: MonotonicTime) {
let _entered = self.enter();
- if self.presenting_of(context_id).is_none() {
+ let Some(presenting) = self.presenting_of(context_id) else {
return;
- }
- if !self.raster.release_store(context_id, bitmap_id) {
+ };
+ if !presenting.borrow_mut().release_presented_store(bitmap_id) {
return;
}
self.schedule_pending_present_frame_if_unblocked(context_id, now);
diff --git a/Services/Compositor/Rust/src/core/presenting.rs b/Services/Compositor/Rust/src/core/presenting.rs
index a20523b6231..58dfa31df3f 100644
--- a/Services/Compositor/Rust/src/core/presenting.rs
+++ b/Services/Compositor/Rust/src/core/presenting.rs
@@ -7,10 +7,11 @@
//! When the frames of the contexts are presented, the frames in flight on the GPU, and whom each is delivered to.
use super::CompositorCore;
+use crate::backing_stores::{StorePublication, StoreResizeOutcome};
use crate::context_state::ContextState;
use crate::host::{PendingFrame, PresentScheduling, PresentationId};
use crate::presenting::{ContextPresenting, NestedContexts, PresentingEnvironment};
-use crate::raster_host::{FfiRemoteLayerFrame, FrameHandOff, StorePublication, StoreResizeOutcome, SublayersHandle};
+use crate::raster_host::{FfiRemoteLayerFrame, FrameHandOff, SublayersHandle};
use crate::surfaces::painting_surface::PaintingSurface;
use libcompositing_rust::display_list::commands::CompositorContextId;
use libcompositing_rust::display_list::replay::{CompositedContexts, NoCompositedContexts, ResolvedCompositedContext};
@@ -330,10 +331,7 @@ impl CompositorCore {
let Some(presenting) = self.presenting_of(context_id) else {
return;
};
- if !presenting
- .borrow()
- .can_schedule_pending_present_frame_if_unblocked(&self.raster, context_id)
- {
+ if !presenting.borrow().can_schedule_pending_present_frame_if_unblocked() {
return;
}
if self.try_present_frame_during_resize(context_id, now) {
@@ -355,9 +353,7 @@ impl CompositorCore {
if !self.context_is_effectively_visible_inner(context_id) {
return false;
}
- let pending_frame = presenting
- .borrow_mut()
- .take_pending_present_frame_if_unblocked(&self.raster, context_id);
+ let pending_frame = presenting.borrow_mut().take_pending_present_frame_if_unblocked();
let Some(pending_frame) = pending_frame else {
return false;
};
@@ -528,7 +524,6 @@ impl CompositorCore {
else {
return;
};
- let environment = self.environment(context_id, now, &NoCompositedContexts);
let viewport_size = IntSize {
width: delivery.viewport_rect.width,
height: delivery.viewport_rect.height,
@@ -538,7 +533,7 @@ impl CompositorCore {
if delivery.keeps_shown_store {
presenting.did_deliver_frame_without_store();
} else {
- presenting.did_finish_gpu_present(&environment, delivery.bitmap_id, viewport_size);
+ presenting.did_finish_gpu_present(delivery.bitmap_id, viewport_size);
}
presenting.presents_to_client
};
@@ -582,16 +577,28 @@ impl CompositorCore {
fn show_frame_in_remote_layer(&self, delivery: &mut Delivery, viewport_size: IntSize, now: MonotonicTime) {
let context_id = delivery.context_id;
- let laid_out_by_page = self
- .presenting_of(context_id)
+ let presenting = self.presenting_of(context_id);
+ let laid_out_by_page = presenting
+ .as_ref()
.is_some_and(|presenting| presenting.borrow().size_laid_out_by_page == viewport_size);
+ let store = if delivery.keeps_shown_store {
+ None
+ } else {
+ let store = presenting.as_ref().and_then(|presenting| {
+ presenting
+ .borrow()
+ .window_server_surface_of_latest_rendered_store()
+ .cloned()
+ });
+ Some(store.expect("a frame shown in a remote layer was rendered into a store the window server shows"))
+ };
// The sublayers go with the frame, which keeps them.
let sublayers = delivery
.sublayers
.take()
.unwrap_or_else(|| self.raster.build_sublayers(context_id, &[]));
let frame = FfiRemoteLayerFrame {
- uses_store: !delivery.keeps_shown_store,
+ 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,
@@ -636,8 +643,7 @@ impl CompositorCore {
};
presenting.borrow_mut().shown_in_remote_layer = false;
self.stop_delivering_in_flight_frames_to_their_viewer(context_id);
- let environment = self.environment(context_id, now, &NoCompositedContexts);
- presenting.borrow_mut().invalidate_backing_stores(&environment);
+ presenting.borrow_mut().invalidate_backing_stores();
self.resize_backing_stores_if_needed(context_id, now);
self.schedule_pending_present_frame_if_unblocked(context_id, now);
}
@@ -649,9 +655,10 @@ impl CompositorCore {
presenting.borrow_mut().shown_in_remote_layer = true;
self.stop_delivering_in_flight_frames_to_their_viewer(context_id);
// The presentation no longer shows the stores it was given, so none of them is waiting to be released by it.
- self.raster.release_all_presented_stores(context_id);
- let environment = self.environment(context_id, now, &NoCompositedContexts);
- presenting.borrow_mut().invalidate_backing_stores(&environment);
+ if let Some(presenting) = self.presenting_of(context_id) {
+ presenting.borrow_mut().release_all_presented_stores();
+ }
+ presenting.borrow_mut().invalidate_backing_stores();
self.resize_backing_stores_if_needed(context_id, now);
self.schedule_pending_present_frame_if_unblocked(context_id, now);
}
@@ -729,16 +736,17 @@ impl CompositorCore {
if bound_presentation.is_none() && !presenting.shown_in_remote_layer {
return;
}
- if !presenting.wants_backing_store_for_pending_frame(display_list.as_ref(), &self.raster, context_id) {
+ if !presenting.wants_backing_store_for_pending_frame(display_list.as_ref()) {
return;
}
let publishing_presentation = bound_presentation
.filter(|_| presenting.store_publication() == StorePublication::Published)
.map(|presentation| presentation.0);
- if self
- .raster
- .add_store_if_window_server_reads_every_released_store(context_id, publishing_presentation)
- {
+ if presenting.add_store_if_window_server_still_reads_every_released_store(
+ &self.raster,
+ context_id,
+ publishing_presentation,
+ ) {
presenting.schedule_surplus_store_retirement(context_id, &self.host);
}
}
@@ -754,10 +762,7 @@ impl CompositorCore {
let publishing_presentation = bound_presentation
.filter(|_| presenting.store_publication() == StorePublication::Published)
.map(|presentation| presentation.0);
- if self
- .raster
- .retire_idle_surplus_stores(context_id, publishing_presentation)
- {
+ if presenting.retire_idle_surplus_stores(&self.raster, context_id, publishing_presentation) {
presenting.schedule_surplus_store_retirement(context_id, &self.host);
}
}
@@ -779,10 +784,7 @@ impl CompositorCore {
let publishing_presentation = bound_presentation
.filter(|_| presenting.store_publication() == StorePublication::Published)
.map(|presentation| presentation.0);
- if self
- .raster
- .retire_stores_of_hidden_context(context_id, publishing_presentation)
- {
+ if presenting.retire_stores_of_hidden_context(&self.raster, context_id, publishing_presentation) {
presenting.retry_hidden_store_retirement(context_id, &self.host);
}
}
@@ -809,14 +811,14 @@ impl CompositorCore {
let publishing_presentation = bound_presentation
.filter(|_| presenting.borrow().store_publication() == StorePublication::Published)
.map(|presentation| presentation.0);
- if self
- .raster
- .restore_stores_retired_while_hidden(context_id, publishing_presentation)
- {
+ if presenting.borrow_mut().restore_stores_retired_while_hidden(
+ &self.raster,
+ context_id,
+ publishing_presentation,
+ ) {
return;
}
- let environment = self.environment(context_id, now, &NoCompositedContexts);
- presenting.borrow_mut().invalidate_backing_stores(&environment);
+ presenting.borrow_mut().invalidate_backing_stores();
self.resize_backing_stores_if_needed(context_id, now);
}
@@ -858,11 +860,12 @@ impl CompositorCore {
}
}
// Nobody is left to release the buffers the presentation was showing.
- self.raster.release_all_presented_stores(context_id);
+ if let Some(presenting) = self.presenting_of(context_id) {
+ presenting.borrow_mut().release_all_presented_stores();
+ }
self.update_scroll_capabilities();
if let Some(presenting) = self.presenting_of(context_id) {
- let environment = self.environment(context_id, now, &NoCompositedContexts);
- presenting.borrow_mut().invalidate_backing_stores(&environment);
+ presenting.borrow_mut().invalidate_backing_stores();
}
self.resize_backing_stores_if_needed(context_id, now);
self.schedule_pending_present_frame_if_unblocked(context_id, now);
@@ -1156,9 +1159,7 @@ impl CompositorCore {
}
self.add_backing_store_for_pending_frame_if_needed(context_id);
- let pending_frame = presenting
- .borrow_mut()
- .take_pending_present_frame_if_unblocked(&self.raster, context_id);
+ let pending_frame = presenting.borrow_mut().take_pending_present_frame_if_unblocked();
let Some(pending_frame) = pending_frame else {
let present_is_scheduled = {
let presenting = presenting.borrow();
diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rs
index f2547d72cb0..032b7d1d423 100644
--- a/Services/Compositor/Rust/src/lib.rs
+++ b/Services/Compositor/Rust/src/lib.rs
@@ -16,6 +16,7 @@ mod rust_demangle;
mod rust_panic;
pub mod async_scroll_update_outbox;
+pub mod backing_stores;
pub mod context_scene;
pub mod context_state;
pub mod core;
diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rs
index 5679e5cd5ff..a634562b95a 100644
--- a/Services/Compositor/Rust/src/presenting/mod.rs
+++ b/Services/Compositor/Rust/src/presenting/mod.rs
@@ -12,12 +12,12 @@ mod damage;
mod layers;
pub mod pacing;
+use crate::backing_stores::{AllocationOutcome, BackingStores, Publication, StorePublication, StoreResizeOutcome};
use crate::frame_inputs::FrameInputs;
use crate::host::{ContextTimer, Host, PendingFrame};
-use crate::raster_host::{
- FfiStoreResize, FfiSublayer, PaintingResources, RasterHost, StorePublication, StoreResizeOutcome, SurfaceBlend,
-};
+use crate::raster_host::{FfiSublayer, PaintingResources, RasterHost, SurfaceBlend};
use crate::surfaces::painting_surface::PaintingSurface;
+use crate::surfaces::presentable_surface::PresentableSurface;
use damage::{PaintedFrame, StoreDamage};
use layers::ContextLayers;
use libcompositing_rust::display_list::commands::{CompositorContextId, EffectNodeIndex};
@@ -140,9 +140,8 @@ pub struct ContextPresenting {
presented_frame: Option<IntRect>,
frame_generation: u64,
- store_publication: StorePublication,
frame_without_store_in_flight: bool,
- latest_rendered_surface: Option<Rc<PaintingSurface>>,
+ backing_stores: BackingStores,
// The frame that the latest rendered surface holds, which the presented frame runs ahead of while its GPU work is in
// flight.
size_of_latest_rendered_frame: IntSize,
@@ -181,9 +180,8 @@ impl ContextPresenting {
pending_present_frame_scheduled: false,
presented_frame: None,
frame_generation: 0,
- store_publication: StorePublication::Unpublished,
frame_without_store_in_flight: false,
- latest_rendered_surface: None,
+ backing_stores: BackingStores::default(),
size_of_latest_rendered_frame: IntSize::default(),
store_damage: StoreDamage::default(),
damage_surface: None,
@@ -205,7 +203,7 @@ impl ContextPresenting {
}
pub fn store_publication(&self) -> StorePublication {
- self.store_publication
+ self.backing_stores.publication()
}
// The window server reads what it shows above the store straight from GPU memory.
@@ -262,23 +260,34 @@ impl ContextPresenting {
self.fit_surface_drawn_by_parent_to_viewport();
return StoreResizeOutcome::Unchanged;
}
- if env.raster.store_state(env.context_id).is_rendering {
+ if self.backing_stores.is_rendering() {
return StoreResizeOutcome::Unchanged;
}
- let outcome = env.raster.resize_stores(
- env.context_id,
- &FfiStoreResize {
- raster_size: self.raster_size(),
- window_resize_in_progress: self.window_resize_in_progress,
- publication,
- gpu_sharing_allowed,
- has_presentation: presentation_id.is_some(),
- presentation_id: presentation_id.unwrap_or_default(),
- },
- );
+ let Some(allocation) =
+ self.backing_stores
+ .resize_if_needed(self.raster_size(), self.window_resize_in_progress, publication)
+ else {
+ return StoreResizeOutcome::Unchanged;
+ };
+ let shares_gpu_images = env.has_gpu && gpu_sharing_allowed;
+ let outcome =
+ match self
+ .backing_stores
+ .allocate(allocation, publication, shares_gpu_images, &mut |kind, size| {
+ env.raster.create_store(env.context_id, kind, size)
+ }) {
+ AllocationOutcome::Offscreen => StoreResizeOutcome::ReallocatedOffscreen,
+ AllocationOutcome::Failed => StoreResizeOutcome::Failed,
+ AllocationOutcome::ForViewer(stores) => {
+ if publication == StorePublication::Published {
+ let presentation_id = presentation_id.expect("published stores have a presentation");
+ env.raster
+ .publish_stores(presentation_id, env.context_id, false, stores);
+ }
+ StoreResizeOutcome::ReallocatedForViewer
+ }
+ };
if outcome != StoreResizeOutcome::Unchanged {
- self.store_publication = publication;
- self.latest_rendered_surface = None;
self.painted_frame = None;
// A partial repaint must inherit the pixel geometry of the new backing stores.
self.damage_surface = None;
@@ -306,20 +315,115 @@ impl ContextPresenting {
}
}
- pub fn invalidate_backing_stores(&mut self, env: &PresentingEnvironment<'_>) {
- env.raster.invalidate_stores(env.context_id);
+ pub fn invalidate_backing_stores(&mut self) {
+ self.backing_stores.invalidate();
self.frame_without_store_in_flight = false;
}
- pub fn wants_backing_store_for_pending_frame(
- &self,
- display_list: Option<&Rc<DisplayList>>,
+ pub fn wants_backing_store_for_pending_frame(&self, display_list: Option<&Rc<DisplayList>>) -> bool {
+ self.presents_to_client && self.pending_present_frame.is_some() && self.can_render_frame(display_list)
+ }
+
+ /// Answers whether a store that was presented became available.
+ pub fn release_presented_store(&mut self, bitmap_id: i32) -> bool {
+ self.backing_stores.release_store(bitmap_id)
+ }
+
+ pub fn release_all_presented_stores(&mut self) {
+ self.backing_stores.release_all_presented_stores();
+ }
+
+ /// The store the remote layer shows the latest frame from.
+ pub fn window_server_surface_of_latest_rendered_store(&self) -> Option<&Rc<PresentableSurface>> {
+ self.backing_stores.window_server_surface_of_latest_rendered_store()
+ }
+
+ fn publish_added_stores(
+ raster: &RasterHost,
+ context_id: CompositorContextId,
+ presentation_id: Option<u64>,
+ stores: Publication,
+ ) {
+ if let Some(presentation_id) = presentation_id
+ && !stores.bitmap_ids.is_empty()
+ {
+ raster.publish_stores(presentation_id, context_id, true, stores);
+ }
+ }
+
+ fn report_retired_stores(
+ raster: &RasterHost,
+ context_id: CompositorContextId,
+ presentation_id: Option<u64>,
+ bitmap_ids: &[i32],
+ ) {
+ if let Some(presentation_id) = presentation_id
+ && !bitmap_ids.is_empty()
+ {
+ raster.retire_published_stores(presentation_id, context_id, bitmap_ids);
+ }
+ }
+
+ /// Answers whether a store was added, which the presentation that shows the stores, if one does, is given.
+ pub fn add_store_if_window_server_still_reads_every_released_store(
+ &mut self,
raster: &RasterHost,
context_id: CompositorContextId,
+ publishing_presentation: Option<u64>,
) -> bool {
- self.presents_to_client
- && self.pending_present_frame.is_some()
- && self.can_render_frame(display_list, raster, context_id)
+ 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)
+ })
+ else {
+ return false;
+ };
+ Self::publish_added_stores(raster, context_id, publishing_presentation, stores);
+ true
+ }
+
+ /// Answers whether surplus stores are left.
+ pub fn retire_idle_surplus_stores(
+ &mut self,
+ raster: &RasterHost,
+ context_id: CompositorContextId,
+ publishing_presentation: Option<u64>,
+ ) -> bool {
+ let retired_bitmap_ids = self.backing_stores.retire_idle_surplus_stores();
+ Self::report_retired_stores(raster, context_id, publishing_presentation, &retired_bitmap_ids);
+ self.backing_stores.has_surplus_stores()
+ }
+
+ /// Retires every store but the one that holds the latest frame, and answers whether a store is left that can be
+ /// retired once nothing renders into, shows or reads it.
+ pub fn retire_stores_of_hidden_context(
+ &mut self,
+ raster: &RasterHost,
+ context_id: CompositorContextId,
+ publishing_presentation: Option<u64>,
+ ) -> bool {
+ let retired_bitmap_ids = self.backing_stores.retire_stores_except_the_latest_rendered();
+ Self::report_retired_stores(raster, context_id, publishing_presentation, &retired_bitmap_ids);
+ self.backing_stores.has_stores_left_to_retire_while_hidden()
+ }
+
+ /// Answers false where the stores could not be added back to the one kept, so that the context needs a whole new
+ /// allocation.
+ pub fn restore_stores_retired_while_hidden(
+ &mut self,
+ raster: &RasterHost,
+ context_id: CompositorContextId,
+ publishing_presentation: Option<u64>,
+ ) -> bool {
+ let Some(stores) = self
+ .backing_stores
+ .add_stores_up_to_initial_count(&mut |kind, size| raster.create_store(context_id, kind, size))
+ else {
+ return false;
+ };
+ Self::publish_added_stores(raster, context_id, publishing_presentation, stores);
+ true
}
/// Schedules the retirement of the stores added for a burst of frames, unless it is scheduled already.
@@ -370,9 +474,8 @@ impl ContextPresenting {
std::mem::take(&mut self.stores_are_retired_while_hidden)
}
- pub fn did_finish_gpu_present(&mut self, env: &PresentingEnvironment<'_>, bitmap_id: i32, frame_size: IntSize) {
- env.raster.complete_rendering(env.context_id, bitmap_id);
- self.latest_rendered_surface = env.raster.latest_rendered_store_surface(env.context_id);
+ pub fn did_finish_gpu_present(&mut self, bitmap_id: i32, frame_size: IntSize) {
+ self.backing_stores.complete_rendering(bitmap_id);
self.size_of_latest_rendered_frame = frame_size;
}
@@ -485,22 +588,12 @@ impl ContextPresenting {
self.pending_present_frame_scheduled
}
- pub fn can_schedule_pending_present_frame_if_unblocked(
- &self,
- raster: &RasterHost,
- context_id: CompositorContextId,
- ) -> bool {
- !self.is_present_blocked(raster, context_id)
- && self.pending_present_frame.is_some()
- && !self.pending_present_frame_scheduled
+ pub fn can_schedule_pending_present_frame_if_unblocked(&self) -> bool {
+ !self.is_present_blocked() && self.pending_present_frame.is_some() && !self.pending_present_frame_scheduled
}
- pub fn take_pending_present_frame_if_unblocked(
- &mut self,
- raster: &RasterHost,
- context_id: CompositorContextId,
- ) -> Option<PendingFrame> {
- if self.is_present_blocked(raster, context_id) {
+ pub fn take_pending_present_frame_if_unblocked(&mut self) -> Option<PendingFrame> {
+ if self.is_present_blocked() {
return None;
}
self.pending_present_frame_scheduled = false;
@@ -541,18 +634,14 @@ impl ContextPresenting {
self.presented_frame = Some(viewport_rect);
}
- fn is_present_blocked(&self, raster: &RasterHost, context_id: CompositorContextId) -> bool {
- let state = raster.store_state(context_id);
- state.is_rendering || self.frame_without_store_in_flight || !state.has_available_store
+ fn is_present_blocked(&self) -> bool {
+ self.backing_stores.is_rendering()
+ || self.frame_without_store_in_flight
+ || !self.backing_stores.has_available_store()
}
- fn can_render_frame(
- &self,
- display_list: Option<&Rc<DisplayList>>,
- raster: &RasterHost,
- context_id: CompositorContextId,
- ) -> bool {
- display_list.is_some() && raster.store_state(context_id).is_valid
+ fn can_render_frame(&self, display_list: Option<&Rc<DisplayList>>) -> bool {
+ display_list.is_some() && self.backing_stores.is_valid()
}
fn raster_size(&self) -> IntSize {
@@ -596,11 +685,11 @@ impl ContextPresenting {
display_list: Option<&Rc<DisplayList>>,
frame_inputs: Option<FrameInputs>,
) -> Option<PreparedFrame> {
- if self.is_present_blocked(env.raster, env.context_id) {
+ if self.is_present_blocked() {
self.queue_present_frame(pending_frame);
return None;
}
- if !self.can_render_frame(display_list, env.raster, env.context_id) {
+ if !self.can_render_frame(display_list) {
self.presented_frame = Some(pending_frame.viewport_rect);
return None;
}
@@ -638,7 +727,7 @@ impl ContextPresenting {
});
}
let raster_damage_rect = self.raster_rect_of(damage_rect);
- let Some((bitmap_id, store)) = env.raster.acquire_store(env.context_id) else {
+ let Some((bitmap_id, store)) = self.backing_stores.acquire_render_target() else {
self.queue_present_frame(pending_frame);
return None;
};
@@ -743,7 +832,7 @@ impl ContextPresenting {
&mut self,
env: &PresentingEnvironment<'_>,
) -> Option<(Rc<PaintingSurface>, IntSize)> {
- let latest_rendered_surface = self.latest_rendered_surface.clone()?;
+ let latest_rendered_surface = self.backing_stores.latest_rendered_surface()?;
let mut source = latest_rendered_surface;
// The store then holds only what is under the canvases, videos and overlays that the window server shows above it.
if self.layers.window_server_shows_media()
@@ -888,7 +977,7 @@ impl ContextPresenting {
fn allows_lcd_text(&self, display_list: &DisplayList, frame_inputs: &FrameInputs) -> bool {
let tree = frame_inputs.visual_context_tree.as_arc();
// LCD coverage follows the physical pixel grid. Destination blending can erase pixels in the canvas fill.
- self.store_publication == StorePublication::Published
+ self.backing_stores.publication() == StorePublication::Published
&& !self.scales_frames_to_fit
&& self.device_pixel_ratio.fract() == 0.0
&& display_list.storage().summary().destination_blending_records.is_empty()
diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rs
index bf58fd2a499..2f923c75c29 100644
--- a/Services/Compositor/Rust/src/raster_host.rs
+++ b/Services/Compositor/Rust/src/raster_host.rs
@@ -8,6 +8,7 @@
//! stores of each context, the surfaces the window server shows, the media that live content comes from, GPU
//! submission, and the display ticks. None of these calls comes back into the core before it returns.
+use crate::backing_stores::{FfiNewStore, NewStore, Publication, SharedImageToPublish, StoreKind};
use crate::surfaces::painting_surface::PaintingSurface;
use crate::surfaces::presentable_surface::PresentableSurface;
use libcompositing_rust::display_list::commands::CompositorContextId;
@@ -40,30 +41,6 @@ pub enum PaintingResources {
Overlays,
}
-/// Who shows the backing stores of a context.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-#[repr(u8)]
-pub enum StorePublication {
- #[default]
- Unpublished,
- /// The presentation shows the stores, and releases each when it shows another.
- Published,
- /// The compositor shows the stores itself, in a remote layer, so a store is replaced on screen by the next one.
- ShownInRemoteLayer,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum StoreResizeOutcome {
- Unchanged,
- /// The stores were reallocated, and nothing that shows them was given them.
- ReallocatedOffscreen,
- /// The presentation or the remote layer that shows the stores was given the new ones.
- ReallocatedForViewer,
- /// The stores of a remote layer could not be allocated.
- Failed,
-}
-
/// When a frame can be handed to whoever shows it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
@@ -72,33 +49,6 @@ pub enum FrameHandOff {
OnceGpuWorkIsFinished,
}
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-#[repr(C)]
-pub struct FfiStoreState {
- pub is_valid: bool,
- pub is_rendering: bool,
- pub has_available_store: bool,
-}
-
-#[derive(Clone, Copy, Debug)]
-#[repr(C)]
-pub struct FfiStoreResize {
- pub raster_size: IntSize,
- pub window_resize_in_progress: bool,
- pub publication: StorePublication,
- pub gpu_sharing_allowed: bool,
- pub has_presentation: bool,
- pub presentation_id: u64,
-}
-
-#[derive(Clone, Copy, Debug)]
-#[repr(C)]
-pub struct FfiAcquiredStore {
- pub bitmap_id: i32,
- /// Lent for as long as the store lives.
- pub surface: *const PaintingSurface,
-}
-
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct FfiCanvasContent {
@@ -192,8 +142,8 @@ pub struct FfiSublayer {
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct FfiRemoteLayerFrame {
- /// Without the store, the frame shown before stays, and only the sublayers change.
- pub uses_store: bool,
+ /// Lent for the call. Without the store, the frame shown before stays, and only the sublayers change.
+ 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.
@@ -232,27 +182,13 @@ pub struct FfiRasterHost {
/// Lets the raster caches of the context's page drop what the frames before the one that starts did not use.
pub start_raster_cache_frame: unsafe extern "C" fn(*mut c_void, u64),
- pub store_state: unsafe extern "C" fn(*mut c_void, u64) -> FfiStoreState,
- pub resize_stores: unsafe extern "C" fn(*mut c_void, u64, *const FfiStoreResize) -> StoreResizeOutcome,
- pub invalidate_stores: unsafe extern "C" fn(*mut c_void, u64),
- pub acquire_store: unsafe extern "C" fn(*mut c_void, u64, *mut FfiAcquiredStore) -> bool,
- pub complete_rendering: unsafe extern "C" fn(*mut c_void, u64, i32),
- pub release_store: unsafe extern "C" fn(*mut c_void, u64, i32) -> bool,
- pub release_all_presented_stores: unsafe extern "C" fn(*mut c_void, u64),
- /// Lent; null before any store was rendered into.
- pub latest_rendered_store_surface: unsafe extern "C" fn(*mut c_void, u64) -> *const PaintingSurface,
- /// Arguments: the context, and the presentation that shows its stores, if it has one. Answers whether a store was
- /// added.
- pub add_store_if_window_server_reads_every_released_store:
- unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,
- /// The same arguments. Answers whether surplus stores are left.
- pub retire_idle_surplus_stores: unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,
- /// The same arguments. Retires every store but the one that holds the latest frame, and answers whether a store
- /// is left that can be retired once nothing renders into, shows or reads it.
- pub retire_stores_of_hidden_context: unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,
- /// The same arguments. Answers false where the stores could not be added back to the one kept, so that the context
- /// needs a whole new allocation.
- pub restore_stores_retired_while_hidden: unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,
+ /// 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 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>),
+ /// Arguments: the presentation, the context, and the stores that it no longer has.
+ pub retire_published_stores: unsafe extern "C" fn(*mut c_void, u64, u64, ak::Span<'_, i32>),
/// A new surface of the size, made like the one given, with one reference that the caller takes over, or null
/// where none could be made.
@@ -460,117 +396,45 @@ impl RasterHost {
unsafe { (self.0.end_painting)(self.host()) };
}
- pub fn store_state(&self, context_id: CompositorContextId) -> FfiStoreState {
- // SAFETY: The host outlives this.
- unsafe { (self.0.store_state)(self.host(), context_id.0) }
- }
-
- pub fn resize_stores(&self, context_id: CompositorContextId, resize: &FfiStoreResize) -> StoreResizeOutcome {
- // SAFETY: The host outlives this.
- unsafe { (self.0.resize_stores)(self.host(), context_id.0, resize) }
- }
-
- pub fn invalidate_stores(&self, context_id: CompositorContextId) {
- // SAFETY: The host outlives this.
- unsafe { (self.0.invalidate_stores)(self.host(), context_id.0) };
- }
-
- pub fn acquire_store(&self, context_id: CompositorContextId) -> Option<(i32, Rc<PaintingSurface>)> {
- let mut acquired = FfiAcquiredStore {
- bitmap_id: -1,
- surface: std::ptr::null(),
- };
- // SAFETY: The host outlives this.
- if !unsafe { (self.0.acquire_store)(self.host(), context_id.0, &raw mut acquired) }
- || acquired.surface.is_null()
- {
+ pub fn create_store(&self, context_id: CompositorContextId, kind: StoreKind, size: IntSize) -> 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) } {
return None;
}
- // SAFETY: The host lends the live surface of the store.
- Some((acquired.bitmap_id, unsafe {
- PaintingSurface::retained_from_ffi(acquired.surface)
- }))
- }
-
- pub fn complete_rendering(&self, context_id: CompositorContextId, bitmap_id: i32) {
- // SAFETY: The host outlives this.
- unsafe { (self.0.complete_rendering)(self.host(), context_id.0, bitmap_id) };
- }
-
- pub fn release_store(&self, context_id: CompositorContextId, bitmap_id: i32) -> bool {
- // SAFETY: The host outlives this.
- unsafe { (self.0.release_store)(self.host(), context_id.0, bitmap_id) }
+ // SAFETY: The host handed the store over.
+ unsafe { NewStore::adopt(store) }
}
- pub fn release_all_presented_stores(&self, context_id: CompositorContextId) {
- // SAFETY: The host outlives this.
- unsafe { (self.0.release_all_presented_stores)(self.host(), context_id.0) };
- }
-
- pub fn latest_rendered_store_surface(&self, context_id: CompositorContextId) -> Option<Rc<PaintingSurface>> {
- // SAFETY: The host outlives this.
- let surface = unsafe { (self.0.latest_rendered_store_surface)(self.host(), context_id.0) };
- // SAFETY: The host lends the live surface of the store, or null.
- (!surface.is_null()).then(|| unsafe { PaintingSurface::retained_from_ffi(surface) })
- }
-
- pub fn add_store_if_window_server_reads_every_released_store(
- &self,
- context_id: CompositorContextId,
- presentation_id: Option<u64>,
- ) -> bool {
- // SAFETY: The host outlives this.
- unsafe {
- (self.0.add_store_if_window_server_reads_every_released_store)(
- self.host(),
- context_id.0,
- presentation_id.is_some(),
- presentation_id.unwrap_or_default(),
- )
- }
- }
-
- pub fn retire_idle_surplus_stores(&self, context_id: CompositorContextId, presentation_id: Option<u64>) -> bool {
- // SAFETY: The host outlives this.
- unsafe {
- (self.0.retire_idle_surplus_stores)(
- self.host(),
- context_id.0,
- presentation_id.is_some(),
- presentation_id.unwrap_or_default(),
- )
- }
- }
-
- pub fn retire_stores_of_hidden_context(
+ pub fn publish_stores(
&self,
+ presentation_id: u64,
context_id: CompositorContextId,
- presentation_id: Option<u64>,
- ) -> bool {
- // SAFETY: The host outlives this.
+ added: bool,
+ publication: Publication,
+ ) {
+ let shared_images: Vec<*mut c_void> = publication
+ .shared_images
+ .into_iter()
+ .map(SharedImageToPublish::into_raw)
+ .collect();
+ // SAFETY: The host outlives this, and takes the images over.
unsafe {
- (self.0.retire_stores_of_hidden_context)(
+ (self.0.publish_stores)(
self.host(),
+ presentation_id,
context_id.0,
- presentation_id.is_some(),
- presentation_id.unwrap_or_default(),
- )
+ added,
+ ak::Span::new(&publication.bitmap_ids),
+ ak::Span::new(&shared_images),
+ );
}
}
- pub fn restore_stores_retired_while_hidden(
- &self,
- context_id: CompositorContextId,
- presentation_id: Option<u64>,
- ) -> bool {
+ pub fn retire_published_stores(&self, presentation_id: u64, context_id: CompositorContextId, bitmap_ids: &[i32]) {
// SAFETY: The host outlives this.
unsafe {
- (self.0.restore_stores_retired_while_hidden)(
- self.host(),
- context_id.0,
- presentation_id.is_some(),
- presentation_id.unwrap_or_default(),
- )
+ (self.0.retire_published_stores)(self.host(), presentation_id, context_id.0, ak::Span::new(bitmap_ids));
}
}
diff --git a/Services/Compositor/main.cpp b/Services/Compositor/main.cpp
index 62b5f1e9d43..70872ab8c40 100644
--- a/Services/Compositor/main.cpp
+++ b/Services/Compositor/main.cpp
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <Compositor/BackingStoreManager.h>
+#include <Compositor/BackingStoreFactory.h>
#include <Compositor/ConnectionFromClient.h>
#include <Compositor/FontSkia.h>
#include <Compositor/MainDispatchQueue.h>
@@ -79,7 +79,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
return Error::from_string_literal("Malformed DRM format modifier");
modifiers.append(*value);
}
- Compositor::BackingStoreManager::set_presentation_drm_format_modifiers(move(modifiers));
+ Compositor::set_presentation_drm_format_modifiers(move(modifiers));
}
if (crash_report_fd >= 0) {