Truly independent web browser
Compositor+LibWebView+UI/Qt: Hand the page's frames to Wayland
Andreas Klingb08b005b7f2e
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex ffb3b68c77c..57e2fecad4a 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -148,6 +148,9 @@ public:virtual Vector<String> platform_preferred_languages() const { return {}; }// The GPU the platform presents on, which the compositor paints on too, so that it can share its frames without a copy.virtual Optional<Gfx::GpuDeviceIdentity> platform_presentation_gpu_device() const { return {}; }+ // The DRM format modifiers the platform can present frames in that are shared from that GPU, or empty if it does+ // not say.+ virtual Vector<u64> platform_presentation_drm_format_modifiers() const { return {}; }virtual OwnPtr<PictureInPictureWindow> create_picture_in_picture_window(WebContentPage& requesting_page, CanonicalTraversable&, Gfx::IntSize video_size);diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex 7d8991d83a2..30b27b691b2 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -7,6 +7,7 @@#include <AK/Enumerate.h>#include <AK/NeverDestroyed.h>#include <AK/ScopeGuard.h>+#include <AK/StringBuilder.h>#include <LibCore/ElapsedTimer.h>#include <LibCore/File.h>#include <LibCore/Process.h>@@ -541,6 +542,16 @@ ErrorOr<NonnullRefPtr<WebView::CompositorClient>> launch_compositor_process()arguments.append("--gpu-device"sv);arguments.append(gpu_device->to_byte_string());}+ if (auto modifiers = WebView::Application::the().platform_presentation_drm_format_modifiers(); !modifiers.is_empty()) {+ StringBuilder builder;+ for (auto modifier : modifiers) {+ if (!builder.is_empty())+ builder.append(',');+ builder.appendff("{:x}", modifier);+ }+ arguments.append("--drm-format-modifiers"sv);+ arguments.append(builder.to_byte_string());+ }if (auto server = mach_server_name(); server.has_value()) {arguments.append("--mach-server-name"sv);arguments.append(server.value());diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex cdc784267f5..69b627114b2 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -643,7 +643,9 @@ protected:virtual void insert_clipboard_item(Web::Clipboard::SystemClipboardItem);virtual void did_accept_presented_backing_store(i32, Gfx::IntRect) { }- void release_backing_store(i32 bitmap_id);+ // Lets the Compositor paint into a backing store again. A view whose frames something else still reads may wait+ // for that to finish first.+ virtual void release_backing_store(i32 bitmap_id);static Gfx::IntRect rect_fitting_frame(Gfx::IntSize frame_size, Gfx::IntSize target_size);static constexpr auto ZOOM_STEP = 0.1;diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cppindex e2421fb7dfc..9b29091ac9f 100644--- a/Services/Compositor/BackingStoreManager.cpp+++ b/Services/Compositor/BackingStoreManager.cpp@@ -59,14 +59,40 @@ struct GpuBackingStore {};#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();- // A presentation on another GPU can only import a linear layout. On ours, the driver picks the layout that suits it,- // which matters to GPUs such as NVIDIA's that cannot render to a linear one at all.- static constexpr Array<u64, 1> linear_modifiers = { DRM_FORMAT_MOD_LINEAR };- auto const modifiers = vulkan_context.is_preferred_device ? Gfx::renderable_drm_format_modifiers(vulkan_context, VK_FORMAT_B8G8R8A8_UNORM) : Vector<u64>(linear_modifiers.span());+ 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);diff --git a/Services/Compositor/BackingStoreManager.h b/Services/Compositor/BackingStoreManager.hindex cc0f00afc79..5fa223f4661 100644--- a/Services/Compositor/BackingStoreManager.h+++ b/Services/Compositor/BackingStoreManager.h@@ -52,6 +52,10 @@ public: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, bool should_publish);Optional<Publication> allocate_backing_stores(Allocation const&, RefPtr<Gfx::SkiaBackendContext> const&, bool should_publish, GpuSharing);diff --git a/Services/Compositor/main.cpp b/Services/Compositor/main.cppindex 15ea71cb507..dad98161b6d 100644--- a/Services/Compositor/main.cpp+++ b/Services/Compositor/main.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <Compositor/BackingStoreManager.h>#include <Compositor/ConnectionFromClient.h>#include <Compositor/FontSkia.h>#include <Compositor/Sandbox.h>@@ -50,6 +51,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(force_fontconfig, "Force using fontconfig for font loading", "force-fontconfig");args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.add_option(gpu_device, "The GPU to paint on, as the presentation identifies it", "gpu-device", 0, "identity");+ StringView drm_format_modifiers;+ args_parser.add_option(drm_format_modifiers, "The DRM format modifiers the presentation can import from that GPU", "drm-format-modifiers", 0, "hex,...");args_parser.parse(arguments);auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "Compositor"sv));@@ -64,6 +67,17 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)return Error::from_string_literal("Malformed GPU device identity");}+ if (!drm_format_modifiers.is_empty()) {+ Vector<u64> modifiers;+ for (auto modifier : drm_format_modifiers.split_view(',')) {+ auto value = modifier.to_number<u64>(TrimWhitespace::No, 16);+ if (!value.has_value())+ return Error::from_string_literal("Malformed DRM format modifier");+ modifiers.append(*value);+ }+ Compositor::BackingStoreManager::set_presentation_drm_format_modifiers(move(modifiers));+ }+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());diff --git a/Tests/UI/Qt/CMakeLists.txt b/Tests/UI/Qt/CMakeLists.txtindex be27bc7b735..70f8360b9fc 100644--- a/Tests/UI/Qt/CMakeLists.txt+++ b/Tests/UI/Qt/CMakeLists.txt@@ -3,6 +3,8 @@ if (NOT Qt6_FOUND)return()endif()+ladybird_test("TestBackingStoreRelease.cpp" UI/Qt)+# The chrome's styles take their colors from the theme, which follows the system's appearance.function(add_chrome_style_sources target)target_sources(${target} PRIVATEdiff --git a/Tests/UI/Qt/TestBackingStoreRelease.cpp b/Tests/UI/Qt/TestBackingStoreRelease.cppnew file mode 100644index 00000000000..e70b9e3f89b--- /dev/null+++ b/Tests/UI/Qt/TestBackingStoreRelease.cpp@@ -0,0 +1,71 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/RefPtr.h>+#include <LibTest/TestCase.h>+#include <UI/Qt/BackingStoreRelease.h>++TEST_CASE(view_finished_before_compositor)+{+ size_t releases = 0;+ auto hold = make_ref_counted<Ladybird::BackingStoreRelease>([&] { ++releases; });+ hold->view_finished_reading();+ hold->view_finished_reading();+ EXPECT_EQ(releases, 0u);+ hold->compositor_finished_reading();+ EXPECT_EQ(releases, 1u);+ hold->compositor_finished_reading();+ hold->view_finished_reading();+ EXPECT_EQ(releases, 1u);+}++TEST_CASE(compositor_finished_before_view)+{+ size_t releases = 0;+ auto hold = make_ref_counted<Ladybird::BackingStoreRelease>([&] { ++releases; });+ hold->compositor_finished_reading();+ EXPECT_EQ(releases, 0u);+ hold->view_finished_reading();+ EXPECT_EQ(releases, 1u);+}++TEST_CASE(retired_buffer_outlives_view)+{+ size_t releases = 0;+ RefPtr<Ladybird::BackingStoreRelease> view_hold = make_ref_counted<Ladybird::BackingStoreRelease>([&] { ++releases; });+ Function<void()> on_buffer_release = [buffer_hold = view_hold] { buffer_hold->compositor_finished_reading(); };+ view_hold->view_finished_reading();+ view_hold = nullptr;+ EXPECT_EQ(releases, 0u);+ on_buffer_release();+ EXPECT_EQ(releases, 1u);+}++TEST_CASE(fallback_keeps_current_and_old_page_backup_until_view_finishes)+{+ size_t releases = 0;+ auto current = make_ref_counted<Ladybird::BackingStoreRelease>([&] { ++releases; });+ auto old_page_backup = make_ref_counted<Ladybird::BackingStoreRelease>([&] { ++releases; });+ current->compositor_finished_reading();+ old_page_backup->compositor_finished_reading();+ EXPECT_EQ(releases, 0u);+ current->view_finished_reading();+ EXPECT_EQ(releases, 1u);+ old_page_backup->view_finished_reading();+ EXPECT_EQ(releases, 2u);+}++TEST_CASE(completed_lease_does_not_consume_release_for_reused_backing_store)+{+ size_t releases = 0;+ auto old_lease = make_ref_counted<Ladybird::BackingStoreRelease>([&] { ++releases; });+ EXPECT(old_lease->view_finished_reading());+ old_lease->compositor_finished_reading();+ EXPECT_EQ(releases, 1u);+ EXPECT(old_lease->is_released());+ EXPECT(!old_lease->view_finished_reading());+ EXPECT_EQ(releases, 1u);+}diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex ad9f9658bbe..b577b0f6017 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -720,6 +720,15 @@ Optional<Gfx::GpuDeviceIdentity> Application::platform_presentation_gpu_device()#endif}+Vector<u64> Application::platform_presentation_drm_format_modifiers() const+{+#ifdef LADYBIRD_QT_USE_VULKAN_WINDOW+ return WebContentView::presentation_drm_format_modifiers();+#else+ return {};+#endif+}+#if !defined(AK_OS_MACOS)// On macOS, WebContent resolves system-ui with CoreText, so the system font family is not sent there.Optional<String> Application::system_font_family() constdiff --git a/UI/Qt/Application.h b/UI/Qt/Application.hindex 94e58d3c953..308cad1aff8 100644--- a/UI/Qt/Application.h+++ b/UI/Qt/Application.h@@ -193,6 +193,7 @@ private:virtual bool platform_scrollbar_track_press_jumps() const override;virtual Vector<String> platform_preferred_languages() const override;virtual Optional<Gfx::GpuDeviceIdentity> platform_presentation_gpu_device() const override;+ virtual Vector<u64> platform_presentation_drm_format_modifiers() const override;virtual void update_tabs_display() const override;diff --git a/UI/Qt/BackingStoreRelease.h b/UI/Qt/BackingStoreRelease.hnew file mode 100644index 00000000000..5b1ed53e76f--- /dev/null+++ b/UI/Qt/BackingStoreRelease.h@@ -0,0 +1,54 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/RefCounted.h>++namespace Ladybird {++// A backing store is reusable only after both the view and the display server have stopped reading it.+class BackingStoreRelease final : public RefCounted<BackingStoreRelease> {+public:+ explicit BackingStoreRelease(Function<void()> release)+ : m_release(move(release))+ {+ }++ // False means this lease is already complete, so a later use of the same backing store needs its own release.+ bool view_finished_reading()+ {+ if (!m_release)+ return false;+ m_view_finished_reading = true;+ release_if_ready();+ return true;+ }++ void compositor_finished_reading()+ {+ m_compositor_finished_reading = true;+ release_if_ready();+ }++ bool is_released() const { return !m_release; }++private:+ void release_if_ready()+ {+ if (!m_view_finished_reading || !m_compositor_finished_reading || !m_release)+ return;+ auto release = move(m_release);+ release();+ }++ Function<void()> m_release;+ bool m_view_finished_reading { false };+ bool m_compositor_finished_reading { false };+};++}diff --git a/UI/Qt/CMakeLists.txt b/UI/Qt/CMakeLists.txtindex 9633f6bf4fe..4aabbf2ce51 100644--- a/UI/Qt/CMakeLists.txt+++ b/UI/Qt/CMakeLists.txt@@ -94,28 +94,33 @@ if (LINUX AND NOT ANDROID)target_link_libraries(ladybird PRIVATE PkgConfig::WAYLAND_CLIENT)target_compile_definitions(ladybird PRIVATE LADYBIRD_HAS_WAYLAND_CLIENT)endif()- if (WAYLAND_CLIENT_FOUND AND WAYLAND_SCANNER_FOUND)+ if (WAYLAND_CLIENT_FOUND AND WAYLAND_SCANNER_FOUND AND USE_VULKAN_DMABUF_IMAGES)pkg_get_variable(WAYLAND_SCANNER_EXECUTABLE wayland-scanner wayland_scanner)- set(LINUX_DMABUF_PROTOCOL "${CMAKE_CURRENT_SOURCE_DIR}/Protocols/linux-dmabuf-v1.xml")- set(LINUX_DMABUF_PROTOCOL_HEADER "${CMAKE_CURRENT_BINARY_DIR}/linux-dmabuf-v1-client-protocol.h")- set(LINUX_DMABUF_PROTOCOL_CODE "${CMAKE_CURRENT_BINARY_DIR}/linux-dmabuf-v1-protocol.c")- add_custom_command(- OUTPUT "${LINUX_DMABUF_PROTOCOL_HEADER}"- COMMAND "${WAYLAND_SCANNER_EXECUTABLE}" client-header "${LINUX_DMABUF_PROTOCOL}" "${LINUX_DMABUF_PROTOCOL_HEADER}"- DEPENDS "${LINUX_DMABUF_PROTOCOL}"- VERBATIM- )- add_custom_command(- OUTPUT "${LINUX_DMABUF_PROTOCOL_CODE}"- COMMAND "${WAYLAND_SCANNER_EXECUTABLE}" private-code "${LINUX_DMABUF_PROTOCOL}" "${LINUX_DMABUF_PROTOCOL_CODE}"- DEPENDS "${LINUX_DMABUF_PROTOCOL}"- VERBATIM- )+ foreach(protocol linux-dmabuf-v1 viewporter)+ set(protocol_xml "${CMAKE_CURRENT_SOURCE_DIR}/Protocols/${protocol}.xml")+ set(protocol_header "${CMAKE_CURRENT_BINARY_DIR}/${protocol}-client-protocol.h")+ set(protocol_code "${CMAKE_CURRENT_BINARY_DIR}/${protocol}-protocol.c")+ add_custom_command(+ OUTPUT "${protocol_header}"+ COMMAND "${WAYLAND_SCANNER_EXECUTABLE}" client-header "${protocol_xml}" "${protocol_header}"+ DEPENDS "${protocol_xml}"+ VERBATIM+ )+ add_custom_command(+ OUTPUT "${protocol_code}"+ COMMAND "${WAYLAND_SCANNER_EXECUTABLE}" private-code "${protocol_xml}" "${protocol_code}"+ DEPENDS "${protocol_xml}"+ VERBATIM+ )+ target_sources(ladybird PRIVATE "${protocol_header}" "${protocol_code}")+ endforeach()target_sources(ladybird PRIVATEWaylandGpu.cppWaylandGpu.h- "${LINUX_DMABUF_PROTOCOL_HEADER}"- "${LINUX_DMABUF_PROTOCOL_CODE}"+ WaylandPageSurface.cpp+ WaylandPageSurface.h+ WaylandRegistry.cpp+ WaylandRegistry.h)target_include_directories(ladybird PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")target_compile_definitions(ladybird PRIVATE LADYBIRD_HAS_WAYLAND_GPU_QUERY)diff --git a/UI/Qt/Protocols/viewporter.xml b/UI/Qt/Protocols/viewporter.xmlnew file mode 100644index 00000000000..1374aeca065--- /dev/null+++ b/UI/Qt/Protocols/viewporter.xml@@ -0,0 +1,177 @@+<?xml version="1.0" encoding="UTF-8"?>+<protocol name="viewporter">++ <copyright>+ Copyright © 2013-2016 Collabora, Ltd.++ Permission is hereby granted, free of charge, to any person obtaining a+ copy of this software and associated documentation files (the "Software"),+ to deal in the Software without restriction, including without limitation+ the rights to use, copy, modify, merge, publish, distribute, sublicense,+ and/or sell copies of the Software, and to permit persons to whom the+ Software is furnished to do so, subject to the following conditions:++ The above copyright notice and this permission notice (including the next+ paragraph) shall be included in all copies or substantial portions of the+ Software.++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ DEALINGS IN THE SOFTWARE.+ </copyright>++ <interface name="wp_viewporter" version="1">+ <description summary="surface cropping and scaling">+ The global interface exposing surface cropping and scaling+ capabilities is used to instantiate an interface extension for a+ wl_surface object. This extended interface will then allow+ cropping and scaling the surface contents, effectively+ disconnecting the direct relationship between the buffer and the+ surface size.+ </description>++ <request name="destroy" type="destructor">+ <description summary="unbind from the cropping and scaling interface">+ Informs the server that the client will not be using this+ protocol object anymore. This does not affect any other objects,+ wp_viewport objects included.+ </description>+ </request>++ <enum name="error">+ <entry name="viewport_exists" value="0"+ summary="the surface already has a viewport object associated"/>+ </enum>++ <request name="get_viewport">+ <description summary="extend surface interface for crop and scale">+ Instantiate an interface extension for the given wl_surface to+ crop and scale its content. If the given wl_surface already has+ a wp_viewport object associated, the viewport_exists+ protocol error is raised.+ </description>+ <arg name="id" type="new_id" interface="wp_viewport"+ summary="the new viewport interface id"/>+ <arg name="surface" type="object" interface="wl_surface"+ summary="the surface"/>+ </request>+ </interface>++ <interface name="wp_viewport" version="1">+ <description summary="crop and scale interface to a wl_surface">+ An additional interface to a wl_surface object, which allows the+ client to specify the cropping and scaling of the surface+ contents.++ This interface works with two concepts: the source rectangle (src_x,+ src_y, src_width, src_height), and the destination size (dst_width,+ dst_height). The contents of the source rectangle are scaled to the+ destination size, and content outside the source rectangle is ignored.+ This state is double-buffered, see wl_surface.commit.++ The two parts of crop and scale state are independent: the source+ rectangle, and the destination size. Initially both are unset, that+ is, no scaling is applied. The whole of the current wl_buffer is+ used as the source, and the surface size is as defined in+ wl_surface.attach.++ If the destination size is set, it causes the surface size to become+ dst_width, dst_height. The source (rectangle) is scaled to exactly+ this size. This overrides whatever the attached wl_buffer size is,+ unless the wl_buffer is NULL. If the wl_buffer is NULL, the surface+ has no content and therefore no size. Otherwise, the size is always+ at least 1x1 in surface local coordinates.++ If the source rectangle is set, it defines what area of the wl_buffer is+ taken as the source. If the source rectangle is set and the destination+ size is not set, then src_width and src_height must be integers, and the+ surface size becomes the source rectangle size. This results in cropping+ without scaling. If src_width or src_height are not integers and+ destination size is not set, the bad_size protocol error is raised when+ the surface state is applied.++ The coordinate transformations from buffer pixel coordinates up to+ the surface-local coordinates happen in the following order:+ 1. buffer_transform (wl_surface.set_buffer_transform)+ 2. buffer_scale (wl_surface.set_buffer_scale)+ 3. crop and scale (wp_viewport.set*)+ This means, that the source rectangle coordinates of crop and scale+ are given in the coordinates after the buffer transform and scale,+ i.e. in the coordinates that would be the surface-local coordinates+ if the crop and scale was not applied.++ If src_x or src_y are negative, the bad_value protocol error is raised.+ Otherwise, if the source rectangle is partially or completely outside of+ the non-NULL wl_buffer, then the out_of_buffer protocol error is raised+ when the surface state is applied. A NULL wl_buffer does not raise the+ out_of_buffer error.++ If the wl_surface associated with the wp_viewport is destroyed,+ all wp_viewport requests except 'destroy' raise the protocol error+ no_surface.++ If the wp_viewport object is destroyed, the crop and scale+ state is removed from the wl_surface. The change will be applied+ on the next wl_surface.commit.+ </description>++ <request name="destroy" type="destructor">+ <description summary="remove scaling and cropping from the surface">+ The associated wl_surface's crop and scale state is removed.+ The change is applied on the next wl_surface.commit.+ </description>+ </request>++ <enum name="error">+ <entry name="bad_value" value="0"+ summary="negative or zero values in width or height"/>+ <entry name="bad_size" value="1"+ summary="destination size is not integer"/>+ <entry name="out_of_buffer" value="2"+ summary="source rectangle extends outside of the content area"/>+ <entry name="no_surface" value="3"+ summary="the wl_surface was destroyed"/>+ </enum>++ <request name="set_source">+ <description summary="set the source rectangle for cropping">+ Set the source rectangle of the associated wl_surface. See+ wp_viewport for the description, and relation to the wl_buffer+ size.++ If all of x, y, width and height are -1.0, the source rectangle is+ unset instead. Any other set of values where width or height are zero+ or negative, or x or y are negative, raise the bad_value protocol+ error.++ The crop and scale state is double-buffered, see wl_surface.commit.+ </description>+ <arg name="x" type="fixed" summary="source rectangle x"/>+ <arg name="y" type="fixed" summary="source rectangle y"/>+ <arg name="width" type="fixed" summary="source rectangle width"/>+ <arg name="height" type="fixed" summary="source rectangle height"/>+ </request>++ <request name="set_destination">+ <description summary="set the surface size for scaling">+ Set the destination size of the associated wl_surface. See+ wp_viewport for the description, and relation to the wl_buffer+ size.++ If width is -1 and height is -1, the destination size is unset+ instead. Any other pair of values for width and height that+ contains zero or negative values raises the bad_value protocol+ error.++ The crop and scale state is double-buffered, see wl_surface.commit.+ </description>+ <arg name="width" type="int" summary="surface width"/>+ <arg name="height" type="int" summary="surface height"/>+ </request>+ </interface>++</protocol>diff --git a/UI/Qt/WaylandGpu.cpp b/UI/Qt/WaylandGpu.cppindex 040754b27dd..10a8e84bf9c 100644--- a/UI/Qt/WaylandGpu.cpp+++ b/UI/Qt/WaylandGpu.cpp@@ -5,10 +5,11 @@*/#include <UI/Qt/WaylandGpu.h>+#include <UI/Qt/WaylandRegistry.h>-#include <QGuiApplication>-+#include <libdrm/drm_fourcc.h>#include <string.h>+#include <sys/mman.h>#include <unistd.h>#include <wayland-client.h>@@ -20,59 +21,88 @@namespace Ladybird {-Optional<dev_t> wayland_compositor_main_device()+namespace {++struct DmaBufFeedback {+ Optional<dev_t> main_device;+ ReadonlyBytes format_table;+ Optional<dev_t> tranche_device;+ Vector<u64> tranche_modifiers;+ Vector<u64> xrgb8888_modifiers;+};++Optional<dev_t> device_from_array(wl_array const& array){- auto* wayland_application = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();- if (!wayland_application || !wayland_application->display())+ dev_t device;+ if (array.size != sizeof(device))return {};+ memcpy(&device, array.data, sizeof(device));+ return device;+}- // NB: The objects live on a queue of our own, so that Qt's queue never sees their events.- auto* display = wayland_application->display();- auto* queue = wl_display_create_queue(display);- auto* display_on_queue = static_cast<wl_display*>(wl_proxy_create_wrapper(display));- wl_proxy_set_queue(reinterpret_cast<wl_proxy*>(display_on_queue), queue);- auto* registry = wl_display_get_registry(display_on_queue);+}- // The default feedback is new in version 4.- zwp_linux_dmabuf_v1* dmabuf = nullptr;- static wl_registry_listener const registry_listener {- .global = [](void* data, wl_registry* registry, uint32_t name, char const* interface, uint32_t version) {- if (strcmp(interface, zwp_linux_dmabuf_v1_interface.name) == 0 && version >= 4)- *static_cast<zwp_linux_dmabuf_v1**>(data) = static_cast<zwp_linux_dmabuf_v1*>(wl_registry_bind(registry, name, &zwp_linux_dmabuf_v1_interface, 4)); },- .global_remove = [](void*, wl_registry*, uint32_t) { },- };- wl_registry_add_listener(registry, ®istry_listener, &dmabuf);- wl_display_roundtrip_queue(display, queue);+Optional<WaylandCompositorDevice> wayland_compositor_main_device()+{+ auto registry = WaylandRegistry::create();+ if (!registry)+ return {};- Optional<dev_t> main_device;+ // The default feedback is new in version 4.+ auto* dmabuf = registry->bind<zwp_linux_dmabuf_v1>(zwp_linux_dmabuf_v1_interface, 4);+ if (!dmabuf)+ return {};- if (dmabuf) {- static zwp_linux_dmabuf_feedback_v1_listener const feedback_listener {- .done = [](void*, zwp_linux_dmabuf_feedback_v1*) { },- .format_table = [](void*, zwp_linux_dmabuf_feedback_v1*, int32_t fd, uint32_t) { ::close(fd); },- .main_device = [](void* data, zwp_linux_dmabuf_feedback_v1*, wl_array* device) {- dev_t main_device;- if (device->size != sizeof(main_device))- return;- memcpy(&main_device, device->data, sizeof(main_device));- *static_cast<Optional<dev_t>*>(data) = main_device; },- .tranche_done = [](void*, zwp_linux_dmabuf_feedback_v1*) { },- .tranche_target_device = [](void*, zwp_linux_dmabuf_feedback_v1*, wl_array*) { },- .tranche_formats = [](void*, zwp_linux_dmabuf_feedback_v1*, wl_array*) { },- .tranche_flags = [](void*, zwp_linux_dmabuf_feedback_v1*, uint32_t) { },- };- auto* default_feedback = zwp_linux_dmabuf_v1_get_default_feedback(dmabuf);- zwp_linux_dmabuf_feedback_v1_add_listener(default_feedback, &feedback_listener, &main_device);- // The compositor sends the whole feedback as soon as it is asked for, so it all arrives within one roundtrip.- wl_display_roundtrip_queue(display, queue);- zwp_linux_dmabuf_feedback_v1_destroy(default_feedback);- zwp_linux_dmabuf_v1_destroy(dmabuf);- }+ DmaBufFeedback feedback;+ static zwp_linux_dmabuf_feedback_v1_listener const feedback_listener {+ .done = [](void*, zwp_linux_dmabuf_feedback_v1*) { },+ .format_table = [](void* data, zwp_linux_dmabuf_feedback_v1*, int32_t fd, uint32_t size) {+ auto& feedback = *static_cast<DmaBufFeedback*>(data);+ auto* table = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);+ ::close(fd);+ if (table != MAP_FAILED)+ feedback.format_table = { static_cast<u8 const*>(table), size }; },+ .main_device = [](void* data, zwp_linux_dmabuf_feedback_v1*, wl_array* device) { static_cast<DmaBufFeedback*>(data)->main_device = device_from_array(*device); },+ .tranche_done = [](void* data, zwp_linux_dmabuf_feedback_v1*) {+ auto& feedback = *static_cast<DmaBufFeedback*>(data);+ if (feedback.tranche_device.has_value() && feedback.tranche_device == feedback.main_device) {+ for (auto modifier : feedback.tranche_modifiers) {+ if (!feedback.xrgb8888_modifiers.contains_slow(modifier))+ feedback.xrgb8888_modifiers.append(modifier);+ }+ }+ feedback.tranche_device.clear();+ feedback.tranche_modifiers.clear(); },+ .tranche_target_device = [](void* data, zwp_linux_dmabuf_feedback_v1*, wl_array* device) { static_cast<DmaBufFeedback*>(data)->tranche_device = device_from_array(*device); },+ .tranche_formats = [](void* data, zwp_linux_dmabuf_feedback_v1*, wl_array* indices) {+ // Each entry of the format table is a 32-bit format, 32 bits of padding and a 64-bit modifier.+ static constexpr size_t entry_size = 16;+ auto& feedback = *static_cast<DmaBufFeedback*>(data);+ ReadonlySpan<u16> entry_indices { static_cast<u16 const*>(indices->data), indices->size / sizeof(u16) };+ for (auto index : entry_indices) {+ if ((index + 1) * entry_size > feedback.format_table.size())+ continue;+ u32 format;+ u64 modifier;+ memcpy(&format, feedback.format_table.data() + index * entry_size, sizeof(format));+ memcpy(&modifier, feedback.format_table.data() + index * entry_size + 8, sizeof(modifier));+ if (format == DRM_FORMAT_XRGB8888)+ feedback.tranche_modifiers.append(modifier);+ } },+ .tranche_flags = [](void*, zwp_linux_dmabuf_feedback_v1*, uint32_t) { },+ };+ auto* default_feedback = zwp_linux_dmabuf_v1_get_default_feedback(dmabuf);+ zwp_linux_dmabuf_feedback_v1_add_listener(default_feedback, &feedback_listener, &feedback);+ // The compositor sends the whole feedback as soon as it is asked for, so it all arrives within one roundtrip.+ registry->roundtrip();+ zwp_linux_dmabuf_feedback_v1_destroy(default_feedback);+ zwp_linux_dmabuf_v1_destroy(dmabuf);+ if (!feedback.format_table.is_empty())+ munmap(const_cast<u8*>(feedback.format_table.data()), feedback.format_table.size());- wl_registry_destroy(registry);- wl_proxy_wrapper_destroy(display_on_queue);- wl_event_queue_destroy(queue);- return main_device;+ if (!feedback.main_device.has_value())+ return {};+ return WaylandCompositorDevice { .device = *feedback.main_device, .xrgb8888_modifiers = move(feedback.xrgb8888_modifiers) };}}diff --git a/UI/Qt/WaylandGpu.h b/UI/Qt/WaylandGpu.hindex 49f1f399148..c0704871bb3 100644--- a/UI/Qt/WaylandGpu.h+++ b/UI/Qt/WaylandGpu.h@@ -7,13 +7,20 @@#pragma once#include <AK/Optional.h>+#include <AK/Vector.h>#include <sys/types.h>namespace Ladybird {+struct WaylandCompositorDevice {+ dev_t device { 0 };+ // The modifiers of the opaque 32-bit RGB dma-bufs that the compositor can import on the device.+ Vector<u64> xrgb8888_modifiers;+};+// The DRM device the Wayland compositor presents on, as it names it in its default dma-buf feedback. It is unknown off// Wayland, and when the compositor does not send dma-buf feedback.-Optional<dev_t> wayland_compositor_main_device();+Optional<WaylandCompositorDevice> wayland_compositor_main_device();}diff --git a/UI/Qt/WaylandPageSurface.cpp b/UI/Qt/WaylandPageSurface.cppnew file mode 100644index 00000000000..14bf3d36dbe--- /dev/null+++ b/UI/Qt/WaylandPageSurface.cpp@@ -0,0 +1,394 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Debug.h>+#include <AK/Format.h>+#include <LibGfx/SharedImageBuffer.h>+#include <UI/Qt/WaylandPageSurface.h>+#include <UI/Qt/WaylandRegistry.h>++#include <QGuiApplication>+#include <QWindow>+#include <qpa/qplatformwindow_p.h>++#include <libdrm/drm_fourcc.h>+#include <sys/stat.h>+#include <wayland-client.h>++// NB: The generated listener functions cast the const away from the listeners they pass to libwayland.+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wcast-qual"+#include <linux-dmabuf-v1-client-protocol.h>+#include <viewporter-client-protocol.h>+#pragma GCC diagnostic pop++namespace Ladybird {++// NB: The page is opaque. Telling the compositor so lets it skip what is behind the page, or scan the frame out.+static u32 opaque_drm_format(u32 drm_format)+{+ if (drm_format == DRM_FORMAT_ARGB8888)+ return DRM_FORMAT_XRGB8888;+ if (drm_format == DRM_FORMAT_ABGR8888)+ return DRM_FORMAT_XBGR8888;+ return drm_format;+}++OwnPtr<WaylandPageSurface> WaylandPageSurface::create()+{+ static Optional<Globals> const globals = []() -> Optional<Globals> {+ auto* wayland_application = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();+ auto registry = WaylandRegistry::create();+ if (!registry || !wayland_application->compositor())+ return {};++ Globals globals {+ .compositor = wayland_application->compositor(),+ .subcompositor = registry->bind<wl_subcompositor>(wl_subcompositor_interface, 1),+ .viewporter = registry->bind<wp_viewporter>(wp_viewporter_interface, 1),+ .dmabuf = registry->bind<zwp_linux_dmabuf_v1>(zwp_linux_dmabuf_v1_interface, 3),+ };+ for (void* proxy : { static_cast<void*>(globals.subcompositor), static_cast<void*>(globals.viewporter), static_cast<void*>(globals.dmabuf) }) {+ if (proxy)+ WaylandRegistry::move_to_qt_queue(proxy);+ }+ if (!globals.subcompositor || !globals.viewporter || !globals.dmabuf)+ return {};+ return globals;+ }();++ if (!globals.has_value())+ return nullptr;+ return adopt_own(*new WaylandPageSurface(*globals));+}++WaylandPageSurface::WaylandPageSurface(Globals globals)+ : m_globals(globals)+{+ m_surface = wl_compositor_create_surface(m_globals.compositor);+ m_viewport = wp_viewporter_get_viewport(m_globals.viewporter, m_surface);++ // NB: Input goes to the browser window underneath, where Qt delivers it to the view.+ auto* empty_region = wl_compositor_create_region(m_globals.compositor);+ wl_surface_set_input_region(m_surface, empty_region);+ wl_region_destroy(empty_region);+}++WaylandPageSurface::~WaylandPageSurface()+{+ on_backing_store_released = nullptr;+ on_ready_to_present = nullptr;+ destroy_subsurface();+ QObject::disconnect(m_parent_surface_created_connection);+ for (auto& buffer : m_buffers)+ destroy_buffer(*buffer);+ wp_viewport_destroy(m_viewport);+ wl_surface_destroy(m_surface);+}++bool WaylandPageSurface::ensure_subsurface(QWindow& parent)+{+ auto* wayland_window = parent.nativeInterface<QNativeInterface::Private::QWaylandWindow>();+ auto* parent_surface = wayland_window ? wayland_window->surface() : nullptr;+ if (!parent_surface) {+ destroy_subsurface();+ if (wayland_window)+ wait_for_parent_surface(*wayland_window);+ return false;+ }+ if (m_subsurface && m_parent == &parent && m_parent_surface == parent_surface)+ return true;++ destroy_subsurface();+ m_subsurface = wl_subcompositor_get_subsurface(m_globals.subcompositor, m_surface, parent_surface);+ // NB: A desynchronized subsurface shows each frame as soon as it is committed, without waiting for the browser+ // window to commit too.+ if (m_is_synchronized)+ wl_subsurface_set_sync(m_subsurface);+ else+ wl_subsurface_set_desync(m_subsurface);+ m_parent = &parent;+ m_parent_surface = parent_surface;+ m_parent_surface_destroyed_connection = QObject::connect(wayland_window, &QNativeInterface::Private::QWaylandWindow::surfaceDestroyed, [this, wayland_window] {+ destroy_subsurface();+ wait_for_parent_surface(*wayland_window);+ });+ return true;+}++// NB: Qt destroys the window's surface while the window is hidden, and creates a new one when it is shown again.+void WaylandPageSurface::wait_for_parent_surface(QNativeInterface::Private::QWaylandWindow& wayland_window)+{+ QObject::disconnect(m_parent_surface_created_connection);+ m_parent_surface_created_connection = QObject::connect(&wayland_window, &QNativeInterface::Private::QWaylandWindow::surfaceCreated, [this] {+ QObject::disconnect(m_parent_surface_created_connection);+ if (on_ready_to_present)+ on_ready_to_present();+ });+}++void WaylandPageSurface::destroy_subsurface()+{+ QObject::disconnect(m_parent_surface_destroyed_connection);+ if (m_subsurface) {+ wl_subsurface_destroy(m_subsurface);+ m_subsurface = nullptr;+ }+ m_parent = nullptr;+ m_parent_surface = nullptr;+ m_position.clear();+ hide();+}++WaylandPageSurface::Buffer* WaylandPageSurface::buffer_for(Frame const& frame)+{+ if (frame.dmabuf.objects.is_empty() || frame.dmabuf.planes.is_empty())+ return nullptr;+ for (auto const& plane : frame.dmabuf.planes) {+ if (plane.object_index >= frame.dmabuf.objects.size())+ return nullptr;+ }++ // NB: A backing store can be freed and another one allocated at the same address, so the dma-buf itself is what+ // identifies the buffer.+ struct stat object_stat {};+ if (fstat(frame.dmabuf.objects[0].fd(), &object_stat) < 0)+ return nullptr;++ for (size_t i = 0; i < m_buffers.size(); ++i) {+ auto& buffer = *m_buffers[i];+ if (buffer.shared_image_buffer != &frame.shared_image_buffer)+ continue;+ if (buffer.device == object_stat.st_dev && buffer.inode == object_stat.st_ino) {+ // NB: A view keeps showing a frame after its backing stores are gone, and it no longer has an ID for it+ // then. The compositor's release of the buffer is still the release of the backing store it held.+ if (frame.bitmap_id >= 0 || !buffer.is_held_by_compositor) {+ buffer.page_id = frame.page_id;+ buffer.bitmap_id = frame.bitmap_id;+ }+ return &buffer;+ }+ retire_buffer(i);+ break;+ }++ auto buffer = make<Buffer>();+ buffer->surface = this;+ buffer->shared_image_buffer = &frame.shared_image_buffer;+ buffer->device = object_stat.st_dev;+ buffer->inode = object_stat.st_ino;+ buffer->page_id = frame.page_id;+ buffer->bitmap_id = frame.bitmap_id;+ buffer->drm_format = opaque_drm_format(frame.dmabuf.drm_format);+ buffer->modifier = frame.dmabuf.modifier;++ buffer->params = zwp_linux_dmabuf_v1_create_params(m_globals.dmabuf);+ for (size_t plane_index = 0; plane_index < frame.dmabuf.planes.size(); ++plane_index) {+ auto const& plane = frame.dmabuf.planes[plane_index];+ zwp_linux_buffer_params_v1_add(buffer->params, frame.dmabuf.objects[plane.object_index].fd(), plane_index, plane.offset, plane.pitch,+ static_cast<u32>(frame.dmabuf.modifier >> 32), static_cast<u32>(frame.dmabuf.modifier & 0xffffffff));+ }+ static zwp_linux_buffer_params_v1_listener const params_listener {+ .created = buffer_created,+ .failed = buffer_failed,+ };+ zwp_linux_buffer_params_v1_add_listener(buffer->params, ¶ms_listener, buffer.ptr());+ zwp_linux_buffer_params_v1_create(buffer->params, frame.dmabuf.size.width(), frame.dmabuf.size.height(), buffer->drm_format, 0);++ m_buffers.append(move(buffer));+ return m_buffers.last().ptr();+}++void WaylandPageSurface::retire_buffer(size_t index)+{+ // NB: The surface shows nothing at all while its buffer is destroyed, so one on screen lives until it is released.+ auto& buffer = *m_buffers[index];+ if (buffer.is_held_by_compositor) {+ buffer.shared_image_buffer = nullptr;+ return;+ }+ destroy_buffer(buffer);+ m_buffers.remove(index);+}++void WaylandPageSurface::forget_buffers_except(ReadonlySpan<Gfx::SharedImageBuffer const*> backing_stores)+{+ for (size_t i = m_buffers.size(); i-- > 0;) {+ auto const* backing_store = m_buffers[i]->shared_image_buffer;+ if (!backing_store || !backing_stores.contains_slow(backing_store))+ retire_buffer(i);+ }+}++void WaylandPageSurface::destroy_buffer(Buffer& buffer)+{+ VERIFY(!buffer.is_held_by_compositor);+ if (buffer.params) {+ zwp_linux_buffer_params_v1_destroy(buffer.params);+ buffer.params = nullptr;+ }+ if (buffer.buffer) {+ wl_buffer_destroy(buffer.buffer);+ buffer.buffer = nullptr;+ }+}++void WaylandPageSurface::retire_buffers(Function<Function<void()>(HeldBackingStore const&)> make_release_callback)+{+ on_ready_to_present = nullptr;+ hide();+ for (size_t i = m_buffers.size(); i-- > 0;) {+ if (!m_buffers[i]->is_held_by_compositor)+ continue;+ auto buffer = m_buffers.take(i);+ VERIFY(buffer->buffer && !buffer->params);+ buffer->on_retired_buffer_released = make_release_callback({ buffer->page_id, buffer->bitmap_id, buffer->device, buffer->inode });+ buffer->surface = nullptr;+ buffer->shared_image_buffer = nullptr;+ // NB: The wl_buffer's listener now owns this record. Destroying the surface or the view does not make the+ // backing store reusable: only wl_buffer.release does. The listener destroys the record after that event.+ (void)buffer.leak_ptr();+ }+}++void WaylandPageSurface::buffer_created(void* data, zwp_linux_buffer_params_v1*, wl_buffer* wayland_buffer)+{+ auto& buffer = *static_cast<Buffer*>(data);+ zwp_linux_buffer_params_v1_destroy(buffer.params);+ buffer.params = nullptr;+ buffer.buffer = wayland_buffer;+ buffer.state = BufferState::Ready;++ static wl_buffer_listener const buffer_listener {+ .release = buffer_released,+ };+ wl_buffer_add_listener(wayland_buffer, &buffer_listener, &buffer);++ if (auto& callback = buffer.surface->on_ready_to_present)+ callback();+}++void WaylandPageSurface::buffer_failed(void* data, zwp_linux_buffer_params_v1*)+{+ auto& buffer = *static_cast<Buffer*>(data);+ zwp_linux_buffer_params_v1_destroy(buffer.params);+ buffer.params = nullptr;+ buffer.state = BufferState::Failed;+ dbgln("WaylandPageSurface: The compositor cannot show a page frame in a dma-buf of format {:#x} with modifier {:#x}", buffer.drm_format, buffer.modifier);++ if (auto& callback = buffer.surface->on_ready_to_present)+ callback();+}++void WaylandPageSurface::buffer_released(void* data, wl_buffer*)+{+ auto& buffer = *static_cast<Buffer*>(data);+ if (!buffer.surface) {+ auto retired_buffer = adopt_own(buffer);+ retired_buffer->is_held_by_compositor = false;+ wl_buffer_destroy(retired_buffer->buffer);+ retired_buffer->buffer = nullptr;+ if (retired_buffer->on_retired_buffer_released)+ retired_buffer->on_retired_buffer_released();+ return;+ }+ auto& surface = *buffer.surface;+ buffer.is_held_by_compositor = false;+ auto page_id = buffer.page_id;+ auto bitmap_id = buffer.bitmap_id;++ // NB: A buffer whose backing store is gone was only kept for as long as it was on screen.+ if (!buffer.shared_image_buffer)+ surface.retire_buffer(*surface.m_buffers.find_first_index_if([&](auto const& candidate) { return candidate.ptr() == &buffer; }));++ // NB: A new Compositor process reuses the IDs of backing stores, so another buffer on screen can carry the same+ // ones. Its own release reports the backing store once it is the last.+ if (surface.holds_backing_store(page_id, bitmap_id))+ return;++ if (auto& callback = surface.on_backing_store_released)+ callback(page_id, bitmap_id);+}++WaylandPageSurface::PresentResult WaylandPageSurface::present(QWindow& parent, Frame const& frame)+{+ // NB: The source has to lie within the buffer, or the compositor disconnects us.+ auto source = frame.source.intersected(QRect { 0, 0, frame.dmabuf.size.width(), frame.dmabuf.size.height() });+ if (source.isEmpty() || frame.destination.isEmpty()) {+ hide();+ return PresentResult::Presented;+ }++ auto* buffer = buffer_for(frame);+ if (!buffer)+ return PresentResult::Failed;+ if (buffer->state == BufferState::Creating)+ return PresentResult::Pending;+ if (buffer->state == BufferState::Failed)+ return PresentResult::Failed;++ if (!ensure_subsurface(parent))+ return PresentResult::Pending;++ // NB: The position belongs to the browser window's state, and takes effect when it commits next.+ m_position_needs_parent_commit = m_position != frame.position;+ if (m_position_needs_parent_commit) {+ wl_subsurface_set_position(m_subsurface, frame.position.x(), frame.position.y());+ m_position = frame.position;+ }++ wp_viewport_set_source(m_viewport, wl_fixed_from_int(source.x()), wl_fixed_from_int(source.y()), wl_fixed_from_int(source.width()), wl_fixed_from_int(source.height()));+ wp_viewport_set_destination(m_viewport, frame.destination.width(), frame.destination.height());++ auto* opaque_region = wl_compositor_create_region(m_globals.compositor);+ wl_region_add(opaque_region, 0, 0, frame.destination.width(), frame.destination.height());+ wl_surface_set_opaque_region(m_surface, opaque_region);+ wl_region_destroy(opaque_region);++ wl_surface_attach(m_surface, buffer->buffer, 0, 0);+ wl_surface_damage_buffer(m_surface, 0, 0, INT32_MAX, INT32_MAX);+ wl_surface_commit(m_surface);+ ++m_commit_count;+ buffer->is_held_by_compositor = true;+ m_is_attached = true;+ return PresentResult::Presented;+}++void WaylandPageSurface::hide()+{+ if (!m_is_attached)+ return;+ wl_surface_attach(m_surface, nullptr, 0, 0);+ wl_surface_commit(m_surface);+ ++m_commit_count;+ m_is_attached = false;+}++void WaylandPageSurface::set_synchronized(bool synchronized)+{+ if (m_is_synchronized == synchronized)+ return;+ m_is_synchronized = synchronized;+ if (!m_subsurface)+ return;+ // NB: The compositor applies what the surface committed while synchronized as soon as it is desynchronized, so+ // that has to wait until the parent has committed.+ if (synchronized)+ wl_subsurface_set_sync(m_subsurface);+ else+ wl_subsurface_set_desync(m_subsurface);+}++bool WaylandPageSurface::holds_backing_store(u64 page_id, i32 bitmap_id) const+{+ for (auto const& buffer : m_buffers) {+ if (buffer->page_id == page_id && buffer->bitmap_id == bitmap_id && buffer->is_held_by_compositor)+ return true;+ }+ return false;+}++}diff --git a/UI/Qt/WaylandPageSurface.h b/UI/Qt/WaylandPageSurface.hnew file mode 100644index 00000000000..a2bae65f56c--- /dev/null+++ b/UI/Qt/WaylandPageSurface.h@@ -0,0 +1,172 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/NonnullOwnPtr.h>+#include <AK/OwnPtr.h>+#include <AK/Vector.h>+#include <AK/kmalloc.h>+#include <LibGfx/Forward.h>+#include <LibGfx/LinuxDmaBufHandle.h>++#include <QMetaObject>+#include <QPoint>+#include <QPointer>+#include <QRect>+#include <QSize>++#include <sys/types.h>++class QWindow;++namespace QNativeInterface::Private {++struct QWaylandWindow;++}++struct wl_buffer;+struct wl_compositor;+struct wl_subcompositor;+struct wl_subsurface;+struct wl_surface;+struct wp_viewport;+struct wp_viewporter;+struct zwp_linux_buffer_params_v1;+struct zwp_linux_dmabuf_v1;++namespace Ladybird {++// A Wayland subsurface of the browser window that shows the page's frames by attaching the dma-bufs the Compositor+// painted them into, so that the compositor of the desktop composites, or even scans out, the frames as they are.+class WaylandPageSurface {+public:+ AK_ALLOC_WITH_KMALLOC;++ static OwnPtr<WaylandPageSurface> create();+ ~WaylandPageSurface();++ struct Frame {+ Gfx::SharedImageBuffer const& shared_image_buffer;+ Gfx::LinuxDmaBufHandle const& dmabuf;+ // The page whose backing store the frame is in. Each page numbers its backing stores from the same start.+ u64 page_id { 0 };+ i32 bitmap_id { -1 };+ // The part of the dma-buf to show, in its pixels.+ QRect source;+ // Where to show it, in the logical coordinates of the window's surface.+ QPoint position;+ QSize destination;+ };++ enum class PresentResult {+ Presented,+ // The buffer for the frame is still being created, or the window has no surface for the moment;+ // on_ready_to_present is called once the frame can be presented.+ Pending,+ // The compositor cannot show this dma-buf.+ Failed,+ };+ PresentResult present(QWindow& parent, Frame const&);+ // Whether the last present takes effect only once the parent commits, because it moved the surface or because the+ // surface is synchronized.+ bool needs_parent_commit() const { return m_position_needs_parent_commit || m_is_synchronized; }+ void hide();+ // Whether the surface shows a frame, or will once the parent commits.+ bool is_showing() const { return m_is_attached; }++ // Lets go of the buffers of every backing store not listed, once the compositor no longer shows them.+ void forget_buffers_except(ReadonlySpan<Gfx::SharedImageBuffer const*> backing_stores);++ // A synchronized surface shows what it commits only when the parent commits next, so that both change on screen+ // together. Otherwise, it shows each commit at once.+ void set_synchronized(bool);+ bool is_synchronized() const { return m_is_synchronized; }+ // Counts what the page surface commits, so that a commit after the parent's last one can be told apart.+ u64 commit_count() const { return m_commit_count; }++ // Whether the compositor may still read the buffer that shows this backing store.+ bool holds_backing_store(u64 page_id, i32 bitmap_id) const;++ struct HeldBackingStore {+ u64 page_id;+ i32 bitmap_id;+ dev_t device;+ ino_t inode;+ };+ // Keeps the held wl_buffers alive independently of this surface, until their actual release events arrive.+ void retire_buffers(Function<Function<void()>(HeldBackingStore const&)> make_release_callback);++ Function<void(u64 page_id, i32 bitmap_id)> on_backing_store_released;+ Function<void()> on_ready_to_present;++private:+ struct Globals {+ wl_compositor* compositor { nullptr };+ wl_subcompositor* subcompositor { nullptr };+ wp_viewporter* viewporter { nullptr };+ zwp_linux_dmabuf_v1* dmabuf { nullptr };+ };++ enum class BufferState {+ Creating,+ Ready,+ Failed,+ };++ struct Buffer {+ AK_ALLOC_WITH_KMALLOC;++ WaylandPageSurface* surface { nullptr };+ // Null once the backing store is gone, while the compositor still shows the buffer.+ Gfx::SharedImageBuffer const* shared_image_buffer { nullptr };+ dev_t device { 0 };+ ino_t inode { 0 };+ u64 page_id { 0 };+ i32 bitmap_id { -1 };+ u32 drm_format { 0 };+ u64 modifier { 0 };+ BufferState state { BufferState::Creating };+ zwp_linux_buffer_params_v1* params { nullptr };+ wl_buffer* buffer { nullptr };+ // Attached since the compositor last released it.+ bool is_held_by_compositor { false };+ Function<void()> on_retired_buffer_released;+ };++ explicit WaylandPageSurface(Globals);++ Buffer* buffer_for(Frame const&);+ void destroy_buffer(Buffer&);+ void retire_buffer(size_t index);+ bool ensure_subsurface(QWindow& parent);+ void wait_for_parent_surface(QNativeInterface::Private::QWaylandWindow&);+ void destroy_subsurface();++ static void buffer_created(void*, zwp_linux_buffer_params_v1*, wl_buffer*);+ static void buffer_failed(void*, zwp_linux_buffer_params_v1*);+ static void buffer_released(void*, wl_buffer*);++ Globals m_globals;+ wl_surface* m_surface { nullptr };+ wp_viewport* m_viewport { nullptr };+ wl_subsurface* m_subsurface { nullptr };+ QPointer<QWindow> m_parent;+ wl_surface* m_parent_surface { nullptr };+ QMetaObject::Connection m_parent_surface_destroyed_connection;+ QMetaObject::Connection m_parent_surface_created_connection;+ Optional<QPoint> m_position;+ bool m_position_needs_parent_commit { false };+ bool m_is_synchronized { false };+ bool m_is_attached { false };+ u64 m_commit_count { 0 };++ Vector<NonnullOwnPtr<Buffer>> m_buffers;+};++}diff --git a/UI/Qt/WaylandRegistry.cpp b/UI/Qt/WaylandRegistry.cppnew file mode 100644index 00000000000..99f33b6fdef--- /dev/null+++ b/UI/Qt/WaylandRegistry.cpp@@ -0,0 +1,65 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/WaylandRegistry.h>++#include <QGuiApplication>++#include <wayland-client.h>++namespace Ladybird {++OwnPtr<WaylandRegistry> WaylandRegistry::create()+{+ auto* wayland_application = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();+ if (!wayland_application || !wayland_application->display())+ return nullptr;+ return adopt_own(*new WaylandRegistry(wayland_application->display()));+}++WaylandRegistry::WaylandRegistry(wl_display* display)+ : m_display(display)+ , m_queue(wl_display_create_queue(display))+ , m_display_on_queue(static_cast<wl_display*>(wl_proxy_create_wrapper(display)))+{+ wl_proxy_set_queue(reinterpret_cast<wl_proxy*>(m_display_on_queue), m_queue);+ m_registry = wl_display_get_registry(m_display_on_queue);++ static wl_registry_listener const listener {+ .global = [](void* data, wl_registry*, uint32_t name, char const* interface, uint32_t version) { static_cast<Vector<Global>*>(data)->append({ name, interface, version }); },+ .global_remove = [](void*, wl_registry*, uint32_t) { },+ };+ wl_registry_add_listener(m_registry, &listener, &m_globals);+ roundtrip();+}++WaylandRegistry::~WaylandRegistry()+{+ wl_registry_destroy(m_registry);+ wl_proxy_wrapper_destroy(m_display_on_queue);+ wl_event_queue_destroy(m_queue);+}++void* WaylandRegistry::bind_proxy(wl_interface const& interface, u32 version)+{+ for (auto const& global : m_globals) {+ if (global.interface == interface.name && global.version >= version)+ return wl_registry_bind(m_registry, global.name, &interface, version);+ }+ return nullptr;+}++void WaylandRegistry::roundtrip()+{+ wl_display_roundtrip_queue(m_display, m_queue);+}++void WaylandRegistry::move_to_qt_queue(void* proxy)+{+ wl_proxy_set_queue(static_cast<wl_proxy*>(proxy), nullptr);+}++}diff --git a/UI/Qt/WaylandRegistry.h b/UI/Qt/WaylandRegistry.hnew file mode 100644index 00000000000..2171fe0e72a--- /dev/null+++ b/UI/Qt/WaylandRegistry.h@@ -0,0 +1,63 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/ByteString.h>+#include <AK/Noncopyable.h>+#include <AK/OwnPtr.h>+#include <AK/Vector.h>+#include <AK/kmalloc.h>++struct wl_display;+struct wl_event_queue;+struct wl_interface;+struct wl_registry;++namespace Ladybird {++// The globals of the Wayland compositor that Qt is connected to. They are listed on an event queue of our own, as are+// the objects bound from them, so that Qt's queue never sees their events.+class WaylandRegistry {+ AK_MAKE_NONCOPYABLE(WaylandRegistry);+ AK_MAKE_NONMOVABLE(WaylandRegistry);++public:+ AK_ALLOC_WITH_KMALLOC;++ // Off Wayland, there is no registry.+ static OwnPtr<WaylandRegistry> create();+ ~WaylandRegistry();++ // Null if the compositor lacks the global, or has only an older version of it.+ template<typename T>+ T* bind(wl_interface const& interface, u32 version) { return static_cast<T*>(bind_proxy(interface, version)); }++ // Waits until the compositor has sent every event for our queue that it sends in response to what we asked so far.+ void roundtrip();++ // An object that outlives the registry has to be dispatched by Qt, on the main thread.+ static void move_to_qt_queue(void* proxy);++private:+ explicit WaylandRegistry(wl_display*);++ void* bind_proxy(wl_interface const&, u32 version);++ struct Global {+ u32 name { 0 };+ ByteString interface;+ u32 version { 0 };+ };++ wl_display* m_display { nullptr };+ wl_event_queue* m_queue { nullptr };+ wl_display* m_display_on_queue { nullptr };+ wl_registry* m_registry { nullptr };+ Vector<Global> m_globals;+};++}diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cppindex 0ecbcc582c0..d8083a6d968 100644--- a/UI/Qt/WebContentView.cpp+++ b/UI/Qt/WebContentView.cpp@@ -51,6 +51,9 @@#include <UI/Qt/SystemAppearance.h>#include <UI/Qt/Theme.h>#include <UI/Qt/WebContentView.h>+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+# include <UI/Qt/WaylandPageSurface.h>+#endif#if defined(Q_OS_MACOS)# include "WebContentViewAccessibility.h"@@ -152,7 +155,10 @@ WebContentView::WebContentView(QWidget* window, Optional<WebView::CanonicalTravesetFocusPolicy(Qt::FocusPolicy::StrongFocus);#ifdef LADYBIRD_QT_USE_VULKAN_WINDOW- create_vulkan_window();+# ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (!create_page_surface())+# endif+ create_vulkan_window();#endifm_device_pixel_ratio = devicePixelRatio();@@ -420,7 +426,15 @@ WebContentView::~WebContentView()#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYERdestroy_iosurface_layer();#elif defined(LADYBIRD_QT_USE_VULKAN_WINDOW)+# ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ // NB: The page can outlive the view, and must get back the backing stores the compositor of the desktop held.+ if (m_page_surface)+ destroy_page_surface();+# endifdestroy_vulkan_window();+# ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ release_all_retired_backing_stores();+# endif#endif#if !defined(Q_OS_WIN)@@ -1109,11 +1123,15 @@ Optional<WebContentView::Paintable> WebContentView::current_paintable() const{Gfx::SharedImageBuffer const* shared_image_buffer = nullptr;Gfx::IntSize bitmap_size;+ i32 bitmap_id = -1;+ u64 page_id = 0;if (m_has_usable_bitmap) {VERIFY(m_front_bitmap.shared_image_buffer);shared_image_buffer = m_front_bitmap.shared_image_buffer.ptr();bitmap_size = m_front_bitmap.last_painted_size.to_type<int>();+ bitmap_id = m_front_bitmap.id;+ page_id = page().id().value();} else if (m_backup_shared_image_buffer) {shared_image_buffer = m_backup_shared_image_buffer.ptr();bitmap_size = m_backup_bitmap_size.to_type<int>();@@ -1121,12 +1139,15 @@ Optional<WebContentView::Paintable> WebContentView::current_paintable() constif (!shared_image_buffer)return {};- return Paintable { shared_image_buffer, bitmap_size };+ return Paintable { shared_image_buffer, bitmap_size, bitmap_id, page_id };}void WebContentView::schedule_repaint(){#if defined(LADYBIRD_QT_USE_VULKAN_WINDOW)+# ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ release_retired_backing_stores_no_longer_painted();+# endifm_frame_read_from_gpu = {};++m_page_window_content_serial;schedule_vulkan_window_update();@@ -1178,6 +1199,18 @@ void WebContentView::did_accept_presented_backing_store(i32, Gfx::IntRect damage#if !defined(LADYBIRD_QT_USE_RHI_WIDGET) && !defined(LADYBIRD_QT_USE_IOSURFACE_LAYER)void WebContentView::paintEvent(QPaintEvent*){+# ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ // NB: Qt commits the browser window right after it paints it, which shows what the page surface committed while+ // synchronized. After that, the page surface can show each frame at once again, unless it committed more in+ // the meantime, which only the browser window's next commit may show.+ if (m_page_surface && m_page_surface->is_synchronized()) {+ QTimer::singleShot(0, this, [this, commit_count = m_page_surface->commit_count()] {+ if (m_page_surface && m_page_surface->commit_count() == commit_count)+ m_page_surface->set_synchronized(false);+ });+ }+# endif+QPainter painter(this);painter.scale(1 / m_device_pixel_ratio, 1 / m_device_pixel_ratio);@@ -1835,6 +1868,14 @@ void WebContentView::resizeEvent(QResizeEvent* event)#endif#ifdef LADYBIRD_QT_USE_VULKAN_WINDOWupdate_vulkan_window_geometry();+#endif+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ // NB: The page surface would stick out of a browser window that shrinks, so it is cropped to the view, and shows+ // that only together with the browser window's next commit at its new size.+ if (m_page_surface && !QRect { QPoint { 0, 0 }, size() * m_device_pixel_ratio }.contains(m_page_surface_rect)) {+ m_page_surface->set_synchronized(true);+ update_page_surface();+ }#endif// One window resize reaches the view as several resize events in one turn of the event loop// (the chrome around it settles after it). The page gets one viewport size per turn: the size@@ -1940,6 +1981,10 @@ void WebContentView::showEvent(QShowEvent* event)// A frame may have arrived before this view had a native view to attach its layer to.present_current_paintable_as_layer_contents();#endif+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (m_page_surface)+ schedule_vulkan_window_update();+#endif}#if !defined(Q_OS_MACOS) && !defined(Q_OS_WIN)@@ -1957,6 +2002,10 @@ void WebContentView::hideEvent(QHideEvent* event){WebContentViewBase::hideEvent(event);set_system_visibility_state(Web::HTML::VisibilityState::Hidden);+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (m_page_surface)+ hide_page_surface();+#endif// Qt sends no Leave to a view hidden under the pointer (a tab switched away from with the keyboard, e.g.). So, tell// WebContent the pointer left. Otherwise, it keeps hovering the link under the pointer — and won't report the hover@@ -2274,9 +2323,11 @@ Gfx::IntPoint WebContentView::to_widget_position(Gfx::IntPoint content_position)return content_position;}-#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER-// NB: Qt places this native view when the view moves within its parent, but not when a widget it is in moves, such as-// the page sliding along with the sidebar. The view watches the widgets it is in, and is placed again when they move.+#if defined(LADYBIRD_QT_USE_IOSURFACE_LAYER) || defined(LADYBIRD_HAS_WAYLAND_GPU_QUERY)+// NB: Qt places this native view when the view moves within its parent, but not when a widget it is in moves or resizes,+// such as while the page slides along with the sidebar. The view watches the widgets it is in, and is placed again+// when they do.+// Qt knows nothing of the Wayland page surface at all, so that also has to follow the view itself.void WebContentView::watch_ancestors_for_moves(){for (auto& ancestor : m_watched_ancestors) {@@ -2293,11 +2344,22 @@ void WebContentView::watch_ancestors_for_moves()bool WebContentView::eventFilter(QObject* watched, QEvent* event){- if (event->type() == QEvent::Move && watched != this)+ if ((event->type() == QEvent::Move || event->type() == QEvent::Resize) && watched != this)place_native_view_again();return WebContentViewBase::eventFilter(watched, event);}+#endif++#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+void WebContentView::place_native_view_again()+{+ // NB: Presenting the frame again places it, and crops it to what the widgets the view is in still show of it.+ if (m_page_surface && m_page_surface->is_showing())+ update_page_surface();+}+#endif+#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYERvoid WebContentView::place_native_view_again(){auto* native_view = windowHandle();@@ -2339,10 +2401,14 @@ bool WebContentView::event(QEvent* event)}}-#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER+#if defined(LADYBIRD_QT_USE_IOSURFACE_LAYER) || defined(LADYBIRD_HAS_WAYLAND_GPU_QUERY)if (event->type() == QEvent::ParentChange || event->type() == QEvent::Show)watch_ancestors_for_moves();#endif+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (event->type() == QEvent::Move)+ place_native_view_again();+#endifif (event->type() == QEvent::PaletteChange || event->type() == QEvent::ApplicationPaletteChange || event->type() == QEvent::ThemeChange) {QTimer::singleShot(0, this, [this] {diff --git a/UI/Qt/WebContentView.h b/UI/Qt/WebContentView.hindex ff1783e3792..e2a7aa34a11 100644--- a/UI/Qt/WebContentView.h+++ b/UI/Qt/WebContentView.h@@ -28,6 +28,7 @@#include <LibWebView/BrowsingSession.h>#include <LibWebView/ViewImplementation.h>#include <LibWebView/WebCompatReport.h>+#include <UI/Qt/BackingStoreRelease.h>#include <UI/Qt/ScreenshotSelectionOverlay.h>#include <LibWebCommon/Page/QueuedInputEvent.h>@@ -81,6 +82,12 @@ struct WindowsD3DHandle;namespace Ladybird {+class WaylandPageSurface;++}++namespace Ladybird {+#ifdef LADYBIRD_QT_USE_RHI_WIDGETusing WebContentViewBase = QRhiWidget;#else@@ -123,6 +130,7 @@ public:#ifdef LADYBIRD_QT_USE_VULKAN_WINDOW// The GPU that the views present on, when the window system says which one it presents on.static Optional<Gfx::GpuDeviceIdentity> presentation_gpu_device();+ static Vector<u64> presentation_drm_format_modifiers();#endif#if !defined(LADYBIRD_QT_USE_RHI_WIDGET)@@ -220,6 +228,10 @@ private:struct Paintable {Gfx::SharedImageBuffer const* shared_image_buffer { nullptr };Gfx::IntSize bitmap_size;+ // The backing store's ID, or -1 for a frame kept from backing stores that are gone.+ i32 bitmap_id { -1 };+ // The page that the backing store belongs to.+ u64 page_id { 0 };};Optional<Paintable> current_paintable() const;@@ -328,11 +340,14 @@ private:quint64 m_last_wheel_event_timestamp { 0 };#endif-#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER+#if defined(LADYBIRD_QT_USE_IOSURFACE_LAYER) || defined(LADYBIRD_HAS_WAYLAND_GPU_QUERY)virtual bool eventFilter(QObject*, QEvent*) override;void watch_ancestors_for_moves();void place_native_view_again();Vector<QPointer<QWidget>> m_watched_ancestors;+#endif++#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYERbool ensure_iosurface_layer_attached_to_native_view();void present_current_paintable_as_layer_contents();@@ -392,9 +407,50 @@ private:bool vulkan_window_update_would_only_resize() const;void remap_unexposed_vulkan_window();+ virtual void release_backing_store(i32 bitmap_id) override;++# ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ bool create_page_surface();+ void update_page_surface();+ void hide_page_surface();+ bool page_surface_can_show_frames() const;+ void fall_back_from_page_surface();+ void destroy_page_surface();+ void release_retired_backing_stores_no_longer_painted();+ void release_all_retired_backing_stores();+ Vector<Gfx::SharedImageBuffer const*> backing_stores() const;+ QRect rect_shown_in_window() const;++ // Shows the page's frames on Wayland by handing their dma-bufs to the compositor of the desktop. Without it, the+ // page's window draws them in a swap chain of its own.+ OwnPtr<WaylandPageSurface> m_page_surface;+ bool m_page_surface_failed { false };+ // Where the page surface shows a frame, in device pixels of the view.+ QRect m_page_surface_rect;+ // Where the page surface last showed a frame, in the logical coordinates of the browser window.+ QPoint m_page_surface_position;+ // The backing stores the view is done with that the compositor of the desktop may still read. The page they belong+ // to can stop displaying the tab before the compositor is done.+ struct BackingStoreWaitingForRelease {+ NonnullRefPtr<WebView::WebContentPage> page;+ i32 bitmap_id { -1 };+ };+ Vector<BackingStoreWaitingForRelease> m_backing_stores_waiting_for_release;+ struct RetiredBackingStore {+ u64 page_id;+ i32 bitmap_id;+ u64 device;+ u64 inode;+ NonnullRefPtr<BackingStoreRelease> release;+ };+ Vector<RetiredBackingStore> m_retired_backing_stores;+# endif+VulkanWindow* m_vulkan_window { nullptr };QWidget* m_vulkan_window_container { nullptr };Optional<bool> m_vulkan_window_supports_alpha_blending;+ // Whether frames come in a format or layout that the page's window can never import.+ bool m_vulkan_window_cannot_import_frames { false };bool m_remapped_unexposed_vulkan_window { false };QTimer m_unexposed_vulkan_window_timer;// Waits for the browser window to be exposed again, before the page's window is mapped again.diff --git a/UI/Qt/WebContentViewLinux.cpp b/UI/Qt/WebContentViewLinux.cppindex f2339855a23..50d16704c2f 100644--- a/UI/Qt/WebContentViewLinux.cpp+++ b/UI/Qt/WebContentViewLinux.cpp@@ -18,10 +18,12 @@#include <LibGfx/VulkanContext.h>#include <LibGfx/VulkanImage.h>#include <LibWebView/Application.h>+#include <LibWebView/WebContentClient.h>#include <UI/Qt/NativeWindowContainer.h>#include <UI/Qt/WebContentView.h>#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY# include <UI/Qt/WaylandGpu.h>+# include <UI/Qt/WaylandPageSurface.h>#endif#include <QByteArrayList>@@ -80,6 +82,13 @@ static QVulkanInstance* vulkan_instance()struct PresentationGpu {int physical_device_index { 0 };Gfx::GpuDeviceIdentity identity;+ // The layouts the window system can import frames in, or empty if it does not say.+ Vector<u64> drm_format_modifiers;+};++struct PresentationDrmDevice {+ dev_t device { 0 };+ Vector<u64> drm_format_modifiers;};static bool device_has_extension(VkPhysicalDevice physical_device, char const* extension_name)@@ -97,11 +106,11 @@ static bool device_has_extension(VkPhysicalDevice physical_device, char const* e// The DRM device that the window system presents on. When it does not say, as on X11, LADYBIRD_RENDER_DEVICE can name// one. A device that the window system does not present on would have to copy every frame over to it, which not// every driver can do, so the window system's own answer always wins.-static Optional<dev_t> presentation_drm_device()+static Optional<PresentationDrmDevice> presentation_drm_device(){#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERYif (auto device = wayland_compositor_main_device(); device.has_value())- return device;+ return PresentationDrmDevice { .device = device->device, .drm_format_modifiers = move(device->xrgb8888_modifiers) };#endifif (auto const* path = getenv("LADYBIRD_RENDER_DEVICE"); path && *path) {struct stat device_stat;@@ -109,7 +118,7 @@ static Optional<dev_t> presentation_drm_device()warnln("LADYBIRD_RENDER_DEVICE does not name a device: {}", path);return {};}- return device_stat.st_rdev;+ return PresentationDrmDevice { .device = device_stat.st_rdev, .drm_format_modifiers = {} };}return {};}@@ -146,10 +155,15 @@ static Optional<PresentationGpu> const& presentation_gpu()vkGetPhysicalDeviceProperties2(physical_device, &properties);// The device may be named by either of its nodes.- auto is_primary_node = drm_properties.hasPrimary && makedev(drm_properties.primaryMajor, drm_properties.primaryMinor) == *main_device;- auto is_render_node = drm_properties.hasRender && makedev(drm_properties.renderMajor, drm_properties.renderMinor) == *main_device;- if (is_primary_node || is_render_node)- return PresentationGpu { .physical_device_index = static_cast<int>(i), .identity = Gfx::gpu_device_identity_of(physical_device) };+ auto is_primary_node = drm_properties.hasPrimary && makedev(drm_properties.primaryMajor, drm_properties.primaryMinor) == main_device->device;+ auto is_render_node = drm_properties.hasRender && makedev(drm_properties.renderMajor, drm_properties.renderMinor) == main_device->device;+ if (is_primary_node || is_render_node) {+ return PresentationGpu {+ .physical_device_index = static_cast<int>(i),+ .identity = Gfx::gpu_device_identity_of(physical_device),+ .drm_format_modifiers = main_device->drm_format_modifiers,+ };+ }}return {};}();@@ -163,6 +177,13 @@ Optional<Gfx::GpuDeviceIdentity> WebContentView::presentation_gpu_device()return {};}+Vector<u64> WebContentView::presentation_drm_format_modifiers()+{+ if (auto const& gpu = presentation_gpu(); gpu.has_value())+ return gpu->drm_format_modifiers;+ return {};+}+// A device of our own to read frames back from GPU memory with, since a view's window has no device while it is hidden.static Gfx::VulkanContext const* readback_vulkan_context(){@@ -179,15 +200,12 @@ static Gfx::VulkanContext const* readback_vulkan_context()RefPtr<Gfx::Bitmap const> WebContentView::cpu_bitmap_to_paint(Paintable const& paintable) const{- if (auto bitmap = paintable.shared_image_buffer->bitmap_if_present())- return bitmap;-// NB: Qt repaints this widget at every step of a resize. While the page's window covers the widget, nobody sees- // what it paints, and reading each frame back from GPU memory for it would be slow. The strips that hover-- // expanded chrome punches out of the page's window are the only part of the page that shows through.- bool page_window_covers_widget = m_vulkan_window_container && m_vulkan_window_container->isVisible()- && m_vertical_tab_overlay_left == 0 && m_vertical_tab_overlay_right == 0 && m_bookmarks_bar_overlay_height == 0;- if (page_window_covers_widget)+ // what it paints, and painting the frame there would be slow: from GPU memory it has to be read back, and a+ // linear frame is mapped from memory that is slow to read.+ QRect visible_frame { 0, 0, paintable.bitmap_size.width(), paintable.bitmap_size.height() };+ visible_frame &= QRect { QPoint { 0, 0 }, size() * m_device_pixel_ratio };+ if (visible_frame.isEmpty() || rect_covered_by_page_window().contains(visible_frame))return {};return cpu_bitmap_of(paintable);}@@ -878,10 +896,12 @@ struct WebContentView::VulkanWindowRenderer final : public QVulkanWindowRenderer&& m_renderer.prepare(m_window);if (can_render && !m_renderer.can_render(*paintable->shared_image_buffer)) {// NB: Reading every frame back from GPU memory would be slow, so a frame in a format or layout we cannot- // import makes the Compositor share its frames as bitmaps instead. A frame kept from backing stores- // that are gone may be from an old allocation, and says nothing about the frames to come.- if (!paintable->shared_image_buffer->bitmap_if_present() && paintable->bitmap_id >= 0 && m_renderer.cannot_import_frames_like(*paintable->shared_image_buffer))- WebView::Application::the().notify_compositor_gpu_presentation_unavailable();+ // import makes the Compositor share this view's frames as bitmaps instead. A frame kept from backing+ // stores that are gone may be from an old allocation, and says nothing about the frames to come.+ if (!paintable->shared_image_buffer->bitmap_if_present() && paintable->bitmap_id >= 0 && m_renderer.cannot_import_frames_like(*paintable->shared_image_buffer)) {+ m_view.m_vulkan_window_cannot_import_frames = true;+ m_view.set_presents_from_cpu_memory(true);+ }can_render = false;}if (!can_render) {@@ -1113,11 +1133,13 @@ bool WebContentView::vulkan_window_update_would_only_resize() constQRect WebContentView::rect_covered_by_page_window() const{- // NB: Hover-expanded chrome punches strips out of the page's window, and the page shows through them.+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (m_page_surface)+ return m_page_surface_rect;+#endif+ // NB: Hover-expanded chrome punches strips out of the page's window, but it covers them itself.if (!m_vulkan_window_container || !m_vulkan_window_container->isVisible())return {};- if (m_vertical_tab_overlay_left != 0 || m_vertical_tab_overlay_right != 0 || m_bookmarks_bar_overlay_height != 0)- return {};return { QPoint { 0, 0 }, m_presented_page_window_size };}@@ -1199,9 +1221,21 @@ bool WebContentView::current_paintable_can_use_vulkan_window() constvoid WebContentView::schedule_vulkan_window_update(){+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (m_page_surface) {+ // NB: Qt paints the page itself while an overlay covers it, which is fastest from CPU memory. Switching costs+ // the page all its backing stores, so a hidden view keeps them, and so does one under a floating surface+ // such as a hover card, which comes and goes quickly. Qt reads the frame back from GPU memory then.+ if (isVisible())+ set_presents_from_cpu_memory(is_page_covered_by_overlay());+ update_page_surface();+ return;+ }+#endif+// NB: Qt paints the page itself while something covers it. Reading every frame back from GPU memory for that would// be slow, so the Compositor shares the frames in CPU memory until the page is uncovered.- set_presents_from_cpu_memory(!m_vulkan_window || is_page_covered_by_overlay() || has_floating_surface_over_page());+ set_presents_from_cpu_memory(!m_vulkan_window || m_vulkan_window_cannot_import_frames || is_page_covered_by_overlay());if (is_page_covered_by_overlay()) {QTimer::singleShot(0, this, [this] {@@ -1229,6 +1263,247 @@ void WebContentView::schedule_vulkan_window_update()update();}+void WebContentView::release_backing_store(i32 bitmap_id)+{+#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+ if (auto index = m_retired_backing_stores.find_first_index_if([&](auto const& store) { return store.page_id == page().id().value() && store.bitmap_id == bitmap_id; }); index.has_value()) {+ auto& release = *m_retired_backing_stores[*index].release;+ auto handled = release.view_finished_reading();+ if (release.is_released())+ m_retired_backing_stores.remove(*index);+ if (handled)+ return;+ }+ // NB: The compositor of the desktop may read a frame until it releases its buffer, which it does once another frame+ // replaced it on screen. The Compositor must not paint into the backing store until then.+ if (m_page_surface && m_page_surface->holds_backing_store(page().id().value(), bitmap_id)) {+ auto& page = this->page();+ if (!m_backing_stores_waiting_for_release.contains([&](auto const& store) { return store.page.ptr() == &page && store.bitmap_id == bitmap_id; }))+ m_backing_stores_waiting_for_release.append({ page, bitmap_id });+ return;+ }+#endif+ WebView::ViewImplementation::release_backing_store(bitmap_id);+}++#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY+bool WebContentView::create_page_surface()+{+ m_page_surface = WaylandPageSurface::create();+ if (!m_page_surface)+ return false;++ m_page_surface->on_backing_store_released = [this](u64 page_id, i32 bitmap_id) {+ auto index = m_backing_stores_waiting_for_release.find_first_index_if([&](auto const& store) {+ return store.page->id().value() == page_id && store.bitmap_id == bitmap_id;+ });+ if (!index.has_value())+ return;+ auto store = m_backing_stores_waiting_for_release.take(*index);+ store.page->release_presented_bitmap(store.bitmap_id);+ };+ m_page_surface->on_ready_to_present = [this] {+ schedule_vulkan_window_update();+ };+ return true;+}++bool WebContentView::page_surface_can_show_frames() const+{+ if (!m_page_surface || m_page_surface_failed || !isVisible())+ return false;+ // NB: Whatever Qt paints over the page has to be under the page surface, so Qt paints the page then.+ if (is_page_covered_by_overlay() || has_floating_surface_over_page())+ return false;+ // NB: The page surface leaves the strips that hover-expanded chrome covers to Qt, except for a frame scaled to fit.+ auto has_hover_expanded_chrome = m_vertical_tab_overlay_left != 0 || m_vertical_tab_overlay_right != 0 || m_bookmarks_bar_overlay_height != 0;+ return !m_scales_frames_to_fit || !has_hover_expanded_chrome;+}++void WebContentView::hide_page_surface()+{+ m_page_surface->hide();+ if (!m_page_surface_rect.isEmpty()) {+ m_page_surface_rect = {};+ update();+ }+}++void WebContentView::update_page_surface()+{+ auto paintable = current_paintable();+ auto const* dmabuf = paintable.has_value() ? paintable->shared_image_buffer->linux_dmabuf_handle() : nullptr;+ auto* parent = window()->windowHandle();+ if (!page_surface_can_show_frames() || !dmabuf || !parent || paintable->bitmap_size.is_empty() || m_viewport_size.is_empty()) {+ hide_page_surface();+ update();+ return;+ }++ // The frame is shown one dma-buf pixel per device pixel from the top left of the view, unless frames are scaled to+ // fit. A frame can be smaller than the view while it catches up with a resize, and the view paints the rest.+ // Where the frame goes in the view, in device pixels, and the part of the frame that the page surface shows.+ auto bitmap_size = paintable->bitmap_size;+ QRect frame_rect;+ QRect source;+ QRect target;+ if (m_scales_frames_to_fit) {+ auto fitted = rect_fitting_frame(bitmap_size, m_viewport_size);+ frame_rect = { fitted.x(), fitted.y(), fitted.width(), fitted.height() };+ source = { 0, 0, bitmap_size.width(), bitmap_size.height() };+ target = frame_rect;+ } else {+ // NB: The view can already be smaller than the viewport the page has, and the compositor doesn't clip the+ // page surface to the browser window.+ auto view_size = size() * m_device_pixel_ratio;+ frame_rect = { 0, 0, min(min(bitmap_size.width(), m_viewport_size.width()), view_size.width()), min(min(bitmap_size.height(), m_viewport_size.height()), view_size.height()) };+ // NB: Hover-expanded chrome paints in the view over strips of the page, which the page surface would cover.+ auto left = qRound(m_vertical_tab_overlay_left * m_device_pixel_ratio);+ auto right = qRound(m_vertical_tab_overlay_right * m_device_pixel_ratio);+ auto top = qRound(m_bookmarks_bar_overlay_height * m_device_pixel_ratio);+ source = frame_rect.intersected({ left, top, view_size.width() - left - right, view_size.height() - top });+ // NB: Qt clips the view to the widgets it is in, such as while the page slides along with a toggling sidebar,+ // but the compositor clips the page surface to nothing.+ auto shown = rect_shown_in_window();+ source &= QRect { qRound(shown.x() * m_device_pixel_ratio), qRound(shown.y() * m_device_pixel_ratio), qRound(shown.width() * m_device_pixel_ratio), qRound(shown.height() * m_device_pixel_ratio) };+ target = source;+ }++ auto to_logical = [&](int device_pixels) { return max(1, qRound(device_pixels / m_device_pixel_ratio)); };+ auto view_position = mapTo(window(), QPoint { 0, 0 });+ WaylandPageSurface::Frame frame {+ .shared_image_buffer = *paintable->shared_image_buffer,+ .dmabuf = *dmabuf,+ .page_id = paintable->page_id,+ .bitmap_id = paintable->bitmap_id,+ .source = source,+ .position = view_position + QPoint { qRound(target.x() / m_device_pixel_ratio), qRound(target.y() / m_device_pixel_ratio) },+ .destination = { to_logical(target.width()), to_logical(target.height()) },+ };++ // NB: The position of the page surface changes when the browser window commits next, so whatever else changes in+ // the frame waits for that commit too.+ if (m_page_surface->is_showing() && frame.position != m_page_surface_position)+ m_page_surface->set_synchronized(true);++ m_page_surface->forget_buffers_except(backing_stores());+ auto result = m_page_surface->present(*parent, frame);+ if (result == WaylandPageSurface::PresentResult::Failed) {+ m_page_surface_failed = true;+ hide_page_surface();+ update();+ // NB: This may run in a callback of the page surface, which cannot be destroyed until that returns.+ QTimer::singleShot(0, this, [this] { fall_back_from_page_surface(); });+ return;+ }++ // NB: The view paints what the page surface leaves bare, which only grows when the surface shows less. The strips+ // that the surface leaves to hover-expanded chrome are covered by that chrome.+ QRect covered_rect;+ if (m_page_surface->is_showing())+ covered_rect = result == WaylandPageSurface::PresentResult::Presented ? frame_rect : m_page_surface_rect;+ if (!covered_rect.contains(m_page_surface_rect))+ update();+ // NB: Nothing else may make the browser window commit, so have Qt repaint a pixel of it.+ else if (result == WaylandPageSurface::PresentResult::Presented && m_page_surface->needs_parent_commit())+ update(0, 0, 1, 1);+ m_page_surface_rect = covered_rect;+ if (result == WaylandPageSurface::PresentResult::Presented)+ m_page_surface_position = frame.position;+}++// The part of the view that the widgets it is in do not clip away, in its coordinates.+QRect WebContentView::rect_shown_in_window() const+{+ auto shown = rect();+ for (auto* ancestor = parentWidget(); ancestor && !ancestor->isWindow(); ancestor = ancestor->parentWidget())+ shown &= QRect { mapFrom(ancestor, QPoint { 0, 0 }), ancestor->size() };+ return shown;+}++Vector<Gfx::SharedImageBuffer const*> WebContentView::backing_stores() const+{+ Vector<Gfx::SharedImageBuffer const*> backing_stores;+ if (m_front_bitmap.shared_image_buffer)+ backing_stores.append(m_front_bitmap.shared_image_buffer.ptr());+ for (auto const& bitmap : m_other_bitmaps) {+ if (bitmap.shared_image_buffer)+ backing_stores.append(bitmap.shared_image_buffer.ptr());+ }+ if (m_backup_shared_image_buffer)+ backing_stores.append(m_backup_shared_image_buffer.ptr());+ return backing_stores;+}++void WebContentView::destroy_page_surface()+{+ m_page_surface->retire_buffers([this](WaylandPageSurface::HeldBackingStore const& held) -> Function<void()> {+ RefPtr<WebView::WebContentPage> owner;+ bool view_finished_reading = false;+ if (auto index = m_backing_stores_waiting_for_release.find_first_index_if([&](auto const& store) { return store.page->id().value() == held.page_id && store.bitmap_id == held.bitmap_id; }); index.has_value()) {+ owner = m_backing_stores_waiting_for_release.take(*index).page;+ view_finished_reading = true;+ } else if (auto client = WebView::WebContentClient::client_for_compositor_context_id(Web::compositor_context_id_for_page(Web::PageId { held.page_id })); client.has_value()) {+ owner = client->page(Web::PageId { held.page_id });+ }+ if (!owner || held.bitmap_id < 0)+ return {};+ auto release = make_ref_counted<BackingStoreRelease>([owner = owner.release_nonnull(), bitmap_id = held.bitmap_id] { owner->release_presented_bitmap(bitmap_id); });+ if (view_finished_reading)+ release->view_finished_reading();+ else+ m_retired_backing_stores.append({ held.page_id, held.bitmap_id, static_cast<u64>(held.device), static_cast<u64>(held.inode), release });+ return [release = AK::move(release)] { release->compositor_finished_reading(); };+ });+ m_page_surface = nullptr;+ m_page_surface_rect = {};+ // NB: Unheld stores do not need to wait for a Wayland release. Held stores moved their acknowledgements above.+ for (auto& store : exchange(m_backing_stores_waiting_for_release, {}))+ store.page->release_presented_bitmap(store.bitmap_id);+ release_retired_backing_stores_no_longer_painted();+}++void WebContentView::release_retired_backing_stores_no_longer_painted()+{+ // NB: A completed lease must not intercept the release of a later presentation of the same backing store.+ m_retired_backing_stores.remove_all_matching([](auto const& store) { return store.release->is_released(); });+ // NB: A backup frame has no page/bitmap IDs in Paintable. Its dma-buf identity still identifies the old page's+ // store, which the view may read after it has switched pages and while the Vulkan fallback shows the backup.+ auto paintable = current_paintable();+ auto const* dmabuf = paintable.has_value() ? paintable->shared_image_buffer->linux_dmabuf_handle() : nullptr;+ struct stat object_stat {};+ bool has_identity = dmabuf && !dmabuf->objects.is_empty() && fstat(dmabuf->objects.first().fd(), &object_stat) == 0;+ if (dmabuf && !has_identity)+ return;+ for (size_t i = m_retired_backing_stores.size(); i-- > 0;) {+ auto const& store = m_retired_backing_stores[i];+ if (has_identity && store.device == static_cast<u64>(object_stat.st_dev) && store.inode == static_cast<u64>(object_stat.st_ino))+ continue;+ store.release->view_finished_reading();+ if (store.release->is_released())+ m_retired_backing_stores.remove(i);+ }+}++void WebContentView::release_all_retired_backing_stores()+{+ for (auto& store : exchange(m_retired_backing_stores, {}))+ store.release->view_finished_reading();+}++// The page's window can still show frames that the compositor of the desktop cannot import itself, by drawing them in+// a swap chain of its own.+void WebContentView::fall_back_from_page_surface()+{+ if (!m_page_surface)+ return;+ destroy_page_surface();+ create_vulkan_window();+ schedule_vulkan_window_update();+ update();+}+#endif+void WebContentView::update_vulkan_window_geometry(){if (m_vulkan_window_container)