diff -urpN webkitgtk-2.40.2.orig/Source/cmake/OptionsGTK.cmake webkitgtk-2.40.2/Source/cmake/OptionsGTK.cmake
--- webkitgtk-2.40.2.orig/Source/cmake/OptionsGTK.cmake	2023-05-29 03:31:46.880082600 -0500
+++ webkitgtk-2.40.2/Source/cmake/OptionsGTK.cmake	2023-06-03 18:19:05.825706376 -0500
@@ -77,6 +77,7 @@ WEBKIT_OPTION_DEFINE(USE_OPENGL_OR_ES "W
 WEBKIT_OPTION_DEFINE(USE_OPENJPEG "Whether to enable support for JPEG2000 images." PUBLIC ON)
 WEBKIT_OPTION_DEFINE(USE_SOUP2 "Whether to enable usage of Soup 2 instead of Soup 3." PUBLIC OFF)
 WEBKIT_OPTION_DEFINE(USE_WOFF2 "Whether to enable support for WOFF2 Web Fonts." PUBLIC ON)
+WEBKIT_OPTION_DEFINE(USE_WPE_RENDERER "Whether to enable WPE rendering" PUBLIC ON)
 
 WEBKIT_OPTION_DEPEND(ENABLE_DOCUMENTATION ENABLE_INTROSPECTION)
 WEBKIT_OPTION_DEPEND(ENABLE_3D_TRANSFORMS USE_OPENGL_OR_ES)
@@ -85,6 +86,8 @@ WEBKIT_OPTION_DEPEND(ENABLE_GLES2 USE_OP
 WEBKIT_OPTION_DEPEND(ENABLE_WEBGL USE_OPENGL_OR_ES)
 WEBKIT_OPTION_DEPEND(USE_GBM USE_OPENGL_OR_ES)
 WEBKIT_OPTION_DEPEND(USE_GSTREAMER_GL USE_OPENGL_OR_ES)
+WEBKIT_OPTION_DEPEND(USE_WPE_RENDERER USE_OPENGL_OR_ES)
+WEBKIT_OPTION_DEPEND(USE_WPE_RENDERER ENABLE_WAYLAND_TARGET)
 
 WEBKIT_OPTION_CONFLICT(USE_GTK4 USE_SOUP2)
 
@@ -307,6 +310,18 @@ if (PC_GLIB_VERSION VERSION_GREATER "2.6
     SET_AND_EXPOSE_TO_BUILD(HAVE_GURI 1)
 endif ()
 
+if (USE_WPE_RENDERER)
+    find_package(WPE 1.3.0)
+    if (NOT WPE_FOUND)
+        message(FATAL_ERROR "libwpe is required for USE_WPE_RENDERER")
+    endif ()
+
+    find_package(WPEBackend_fdo 1.6.0)
+    if (NOT WPEBACKEND_FDO_FOUND)
+        message(FATAL_ERROR "WPEBackend-fdo is required for USE_WPE_RENDERER")
+    endif ()
+endif ()
+
 if (ENABLE_GAMEPAD)
     find_package(Manette 0.2.4)
     if (NOT Manette_FOUND)
@@ -385,20 +400,6 @@ if (USE_OPENGL_OR_ES)
         SET_AND_EXPOSE_TO_BUILD(USE_GLX TRUE)
     endif ()
 
-    if (ENABLE_WAYLAND_TARGET AND EGL_FOUND)
-        find_package(WPE 1.3.0)
-        if (NOT WPE_FOUND)
-            message(FATAL_ERROR "libwpe is required for ENABLE_WAYLAND_TARGET")
-        endif ()
-
-        find_package(WPEBackend_fdo 1.6.0)
-        if (NOT WPEBACKEND_FDO_FOUND)
-            message(FATAL_ERROR "WPEBackend-fdo is required for ENABLE_WAYLAND_TARGET")
-        endif ()
-
-        SET_AND_EXPOSE_TO_BUILD(USE_WPE_RENDERER ON)
-    endif ()
-
     SET_AND_EXPOSE_TO_BUILD(USE_COORDINATED_GRAPHICS TRUE)
     SET_AND_EXPOSE_TO_BUILD(USE_NICOSIA TRUE)
     SET_AND_EXPOSE_TO_BUILD(USE_ANGLE ${ENABLE_WEBGL})
diff -urpN webkitgtk-2.40.2.orig/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.cpp webkitgtk-2.40.2/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.cpp
--- webkitgtk-2.40.2.orig/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.cpp	2023-02-20 03:22:19.005744000 -0600
+++ webkitgtk-2.40.2/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.cpp	2023-06-03 18:19:05.825706376 -0500
@@ -128,6 +128,7 @@ void PlatformDisplayWayland::initialize(
     wl_registry_add_listener(m_registry.get(), &s_registryListener, this);
     wl_display_roundtrip(m_display);
 
+#if USE(EGL)
 #if defined(EGL_KHR_platform_wayland) || defined(EGL_EXT_platform_wayland)
     const char* extensions = eglQueryString(nullptr, EGL_EXTENSIONS);
 #if defined(EGL_KHR_platform_wayland)
@@ -147,6 +148,7 @@ void PlatformDisplayWayland::initialize(
         m_eglDisplay = eglGetDisplay(m_display);
 
     PlatformDisplay::initializeEGLDisplay();
+#endif
 }
 
 void PlatformDisplayWayland::registryGlobal(const char* interface, uint32_t name)
diff -urpN webkitgtk-2.40.2.orig/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.h webkitgtk-2.40.2/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.h
--- webkitgtk-2.40.2.orig/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.h	2023-02-20 03:22:19.005744000 -0600
+++ webkitgtk-2.40.2/Source/WebCore/platform/graphics/wayland/PlatformDisplayWayland.h	2023-06-03 18:19:05.825706376 -0500
@@ -51,8 +51,6 @@ private:
 
     Type type() const final { return PlatformDisplay::Type::Wayland; }
 
-    void registryGlobal(const char* interface, uint32_t name);
-
 protected:
     explicit PlatformDisplayWayland(struct wl_display*);
 #if PLATFORM(GTK)
@@ -63,7 +61,8 @@ protected:
 
     void initialize();
 
-private:
+    virtual void registryGlobal(const char* interface, uint32_t name);
+
     struct wl_display* m_display;
     WlUniquePtr<struct wl_registry> m_registry;
     WlUniquePtr<struct wl_compositor> m_compositor;
diff -urpN webkitgtk-2.40.2.orig/Source/WebCore/PlatformGTK.cmake webkitgtk-2.40.2/Source/WebCore/PlatformGTK.cmake
--- webkitgtk-2.40.2.orig/Source/WebCore/PlatformGTK.cmake	2023-05-29 02:59:44.776171200 -0500
+++ webkitgtk-2.40.2/Source/WebCore/PlatformGTK.cmake	2023-06-05 11:56:33.540727937 -0500
@@ -27,7 +27,6 @@ list(APPEND WebCore_PRIVATE_INCLUDE_DIRE
     "${WEBCORE_DIR}/platform/graphics/gbm"
     "${WEBCORE_DIR}/platform/graphics/gstreamer"
     "${WEBCORE_DIR}/platform/graphics/gtk"
-    "${WEBCORE_DIR}/platform/graphics/libwpe"
     "${WEBCORE_DIR}/platform/graphics/opengl"
     "${WEBCORE_DIR}/platform/graphics/opentype"
     "${WEBCORE_DIR}/platform/graphics/wayland"
@@ -40,6 +39,12 @@ list(APPEND WebCore_PRIVATE_INCLUDE_DIRE
     "${WEBCORE_DIR}/platform/text/gtk"
 )
 
+if (USE_WPE_RENDERER)
+    list(APPEND WebCore_INCLUDE_DIRECTORIES
+        "${WEBCORE_DIR}/platform/graphics/libwpe"
+    )
+endif ()
+
 list(APPEND WebCore_PRIVATE_FRAMEWORK_HEADERS
     accessibility/atspi/AccessibilityAtspi.h
     accessibility/atspi/AccessibilityAtspiEnums.h
@@ -85,6 +90,12 @@ list(APPEND WebCore_LIBRARIES
     GTK::GTK
 )
 
+if (USE_WPE_RENDERER)
+    list(APPEND WebCore_LIBRARIES
+        WPE::libwpe
+    )
+endif ()
+
 list(APPEND WebCore_SYSTEM_INCLUDE_DIRECTORIES
     ${ENCHANT_INCLUDE_DIRS}
     ${GIO_UNIX_INCLUDE_DIRS}
@@ -94,7 +105,7 @@ list(APPEND WebCore_SYSTEM_INCLUDE_DIREC
     ${UPOWERGLIB_INCLUDE_DIRS}
 )
 
-if (USE_OPENGL AND NOT USE_LIBEPOXY)
+if (USE_OPENGL)
     list(APPEND WebCore_SOURCES
         platform/graphics/OpenGLShims.cpp
     )
@@ -110,7 +121,6 @@ if (ENABLE_WAYLAND_TARGET)
     )
     list(APPEND WebCore_LIBRARIES
         ${WAYLAND_LIBRARIES}
-        WPE::libwpe
     )
 endif ()
 
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/CMakeLists.txt webkitgtk-2.40.2/Source/WebKit/CMakeLists.txt
--- webkitgtk-2.40.2.orig/Source/WebKit/CMakeLists.txt	2023-02-20 03:22:20.489750000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/CMakeLists.txt	2023-06-05 17:10:12.584084228 -0500
@@ -376,18 +376,16 @@ elseif (USE_ANGLE_EGL)
         ANGLE::GLES
         ANGLE::EGL
     )
-else ()
-    if (USE_EGL)
-        list(APPEND WebKit_SYSTEM_INCLUDE_DIRECTORIES
-            ${EGL_INCLUDE_DIRS}
-        )
-        list(APPEND WebKit_PRIVATE_LIBRARIES
-            ${EGL_LIBRARIES}
-        )
-        add_definitions(${EGL_DEFINITIONS})
-    endif ()
 endif ()
 
+list(APPEND WebKit_SYSTEM_INCLUDE_DIRECTORIES
+    ${EGL_INCLUDE_DIRS}
+)
+list(APPEND WebKit_PRIVATE_LIBRARIES
+    ${EGL_LIBRARIES}
+)
+add_definitions(${EGL_DEFINITIONS})
+
 if (USE_LIBWEBRTC)
     list(APPEND WebKit_SYSTEM_INCLUDE_DIRECTORIES "${THIRDPARTY_DIR}/libwebrtc/Source/"
         "${THIRDPARTY_DIR}/libwebrtc/Source/webrtc"
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/PlatformGTK.cmake webkitgtk-2.40.2/Source/WebKit/PlatformGTK.cmake
--- webkitgtk-2.40.2.orig/Source/WebKit/PlatformGTK.cmake	2023-05-29 02:59:22.203536000 -0500
+++ webkitgtk-2.40.2/Source/WebKit/PlatformGTK.cmake	2023-06-04 12:17:31.175262655 -0500
@@ -68,6 +68,7 @@ list(APPEND WebKit_DERIVED_SOURCES
 
 if (ENABLE_WAYLAND_TARGET)
     list(APPEND WebKit_DERIVED_SOURCES
+        ${WebKitGTK_DERIVED_SOURCES_DIR}/WebKitWaylandClientProtocol.c
         ${WebKitGTK_DERIVED_SOURCES_DIR}/pointer-constraints-unstable-v1-protocol.c
         ${WebKitGTK_DERIVED_SOURCES_DIR}/relative-pointer-unstable-v1-protocol.c
     )
@@ -450,6 +451,16 @@ add_custom_command(
 )
 
 if (ENABLE_WAYLAND_TARGET)
+    # Wayland protocol extension.
+    add_custom_command(
+        OUTPUT ${WebKitGTK_DERIVED_SOURCES_DIR}/WebKitWaylandClientProtocol.c
+        DEPENDS ${WEBKIT_DIR}/Shared/gtk/WebKitWaylandProtocol.xml
+        COMMAND ${WAYLAND_SCANNER} server-header ${WEBKIT_DIR}/Shared/gtk/WebKitWaylandProtocol.xml ${WebKitGTK_DERIVED_SOURCES_DIR}/WebKitWaylandServerProtocol.h
+        COMMAND ${WAYLAND_SCANNER} client-header ${WEBKIT_DIR}/Shared/gtk/WebKitWaylandProtocol.xml ${WebKitGTK_DERIVED_SOURCES_DIR}/WebKitWaylandClientProtocol.h
+        COMMAND ${WAYLAND_SCANNER} code ${WEBKIT_DIR}/Shared/gtk/WebKitWaylandProtocol.xml ${WebKitGTK_DERIVED_SOURCES_DIR}/WebKitWaylandClientProtocol.c
+        VERBATIM
+    )
+
     add_custom_command(
         OUTPUT ${WebKitGTK_DERIVED_SOURCES_DIR}/pointer-constraints-unstable-v1-protocol.c
         DEPENDS ${WAYLAND_PROTOCOLS_DATADIR}/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/Shared/CoordinatedGraphics/threadedcompositor/ThreadedCompositor.cpp webkitgtk-2.40.2/Source/WebKit/Shared/CoordinatedGraphics/threadedcompositor/ThreadedCompositor.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/Shared/CoordinatedGraphics/threadedcompositor/ThreadedCompositor.cpp	2023-03-08 03:00:32.718699000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/Shared/CoordinatedGraphics/threadedcompositor/ThreadedCompositor.cpp	2023-06-03 18:19:05.829706397 -0500
@@ -186,8 +186,13 @@ void ThreadedCompositor::updateViewport(
 
 void ThreadedCompositor::forceRepaint()
 {
-    // FIXME: Implement this once it's possible to do these forced updates
+    // FIXME: Enable this for WPE once it's possible to do these forced updates
     // in a way that doesn't starve out the underlying graphics buffers.
+#if PLATFORM(GTK) && !USE(WPE_RENDERER)
+    m_compositingRunLoop->performTaskSync([this, protectedThis = Ref { *this }] {
+        renderLayerTree();
+    });
+#endif
 }
 
 void ThreadedCompositor::renderLayerTree()
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/Shared/gtk/WebKitWaylandProtocol.xml webkitgtk-2.40.2/Source/WebKit/Shared/gtk/WebKitWaylandProtocol.xml
--- webkitgtk-2.40.2.orig/Source/WebKit/Shared/gtk/WebKitWaylandProtocol.xml	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/Shared/gtk/WebKitWaylandProtocol.xml	2023-06-03 18:19:05.829706397 -0500
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="wl_webkitgtk">
+
+  <copyright>
+    Copyright © 2014 Igalia S.L.
+
+    Permission to use, copy, modify, distribute, and sell this
+    software and its documentation for any purpose is hereby granted
+    without fee, provided that the above copyright notice appear in
+    all copies and that both that copyright notice and this permission
+    notice appear in supporting documentation, and that the name of
+    the copyright holders not be used in advertising or publicity
+    pertaining to distribution of the software without specific,
+    written prior permission.  The copyright holders make no
+    representations about the suitability of this software for any
+    purpose.  It is provided "as is" without express or implied
+    warranty.
+
+    THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
+    SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+    FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
+    SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
+    AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+    ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+    THIS SOFTWARE.
+  </copyright>
+
+  <interface name="wl_webkitgtk" version="1">
+    <request name="bind_surface_to_page">
+      <arg name="surface" type="object" interface="wl_surface"/>
+      <arg name="page_id" type="uint"/>
+    </request>
+
+  </interface>
+
+</protocol>
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/SourcesGTK.txt webkitgtk-2.40.2/Source/WebKit/SourcesGTK.txt
--- webkitgtk-2.40.2.orig/Source/WebKit/SourcesGTK.txt	2023-05-29 02:59:22.203536000 -0500
+++ webkitgtk-2.40.2/Source/WebKit/SourcesGTK.txt	2023-06-03 18:19:05.829706397 -0500
@@ -278,6 +278,7 @@ UIProcess/gtk/TextCheckerGtk.cpp @no-uni
 UIProcess/gtk/ViewSnapshotStoreGtk3.cpp @no-unify
 UIProcess/gtk/ViewSnapshotStoreGtk4.cpp @no-unify
 UIProcess/gtk/ViewGestureControllerGtk.cpp
+UIProcess/gtk/WaylandCompositor.cpp @no-unify
 UIProcess/gtk/WebColorPickerGtk.cpp
 UIProcess/gtk/WebContextMenuProxyGtk.cpp
 UIProcess/gtk/WebDataListSuggestionsDropdownGtk.cpp
@@ -328,6 +329,7 @@ WebProcess/WebPage/CoordinatedGraphics/L
 
 WebProcess/WebPage/glib/WebPageGLib.cpp
 
+WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.cpp
 WebProcess/WebPage/gtk/AcceleratedSurfaceX11.cpp @no-unify
 WebProcess/WebPage/gtk/WebPageGtk.cpp
 WebProcess/WebPage/gtk/WebPrintOperationGtk.cpp
@@ -337,4 +339,5 @@ WebProcess/WebPage/libwpe/AcceleratedSur
 WebProcess/glib/WebProcessGLib.cpp
 
 WebProcess/gtk/GtkSettingsManagerProxy.cpp
+WebProcess/gtk/WaylandCompositorDisplay.cpp
 WebProcess/gtk/WebProcessMainGtk.cpp
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/API/glib/WebKitProtocolHandler.cpp webkitgtk-2.40.2/Source/WebKit/UIProcess/API/glib/WebKitProtocolHandler.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/API/glib/WebKitProtocolHandler.cpp	2023-05-29 02:59:44.936175800 -0500
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/API/glib/WebKitProtocolHandler.cpp	2023-06-03 18:19:05.829706397 -0500
@@ -45,7 +45,7 @@
 #if PLATFORM(GTK)
 #include <gtk/gtk.h>
 
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(WPE_RENDERER)
 #include <wpe/wpe.h>
 #include <wpe/fdo.h>
 #endif
@@ -228,7 +228,7 @@ void WebKitProtocolHandler::handleGPU(We
 #if PLATFORM(GTK)
     addTableRow(versionObject, "GTK version"_s, makeString(GTK_MAJOR_VERSION, '.', GTK_MINOR_VERSION, '.', GTK_MICRO_VERSION, " (build) "_s, gtk_get_major_version(), '.', gtk_get_minor_version(), '.', gtk_get_micro_version(), " (runtime)"_s));
 
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(WPE_RENDERER)
     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland) {
         addTableRow(versionObject, "WPE version"_s, makeString(WPE_MAJOR_VERSION, '.', WPE_MINOR_VERSION, '.', WPE_MICRO_VERSION, " (build) "_s, wpe_get_major_version(), '.', wpe_get_minor_version(), '.', wpe_get_micro_version(), " (runtime)"_s));
 
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/glib/WebProcessPoolGLib.cpp webkitgtk-2.40.2/Source/WebKit/UIProcess/glib/WebProcessPoolGLib.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/glib/WebProcessPoolGLib.cpp	2023-02-20 03:22:21.789755000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/glib/WebProcessPoolGLib.cpp	2023-06-03 18:19:05.829706397 -0500
@@ -45,7 +45,11 @@
 #endif
 
 #if PLATFORM(WAYLAND)
+#if USE(WPE_RENDERER)
 #include "AcceleratedBackingStoreWayland.h"
+#else
+#include "WaylandCompositor.h"
+#endif
 #endif
 
 #if USE(WPE_RENDERER)
@@ -84,11 +88,15 @@ void WebProcessPool::platformInitializeW
 
 #if PLATFORM(WAYLAND)
     if (WebCore::PlatformDisplay::sharedDisplay().type() == WebCore::PlatformDisplay::Type::Wayland) {
+#if USE(WPE_RENDERER)
         wpe_loader_init("libWPEBackend-fdo-1.0.so.1");
         if (AcceleratedBackingStoreWayland::checkRequirements()) {
             parameters.hostClientFileDescriptor = UnixFileDescriptor { wpe_renderer_host_create_client(), UnixFileDescriptor::Adopt };
             parameters.implementationLibraryName = FileSystem::fileSystemRepresentation(String::fromLatin1(wpe_loader_get_loaded_implementation_library_name()));
         }
+#elif USE(EGL)
+        parameters.waylandCompositorDisplayName = WaylandCompositor::singleton().displayName();
+#endif
     }
 #endif
 
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/AcceleratedBackingStore.cpp webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/AcceleratedBackingStore.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/AcceleratedBackingStore.cpp	2023-02-20 03:22:21.793755000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/AcceleratedBackingStore.cpp	2023-06-03 18:19:05.829706397 -0500
@@ -44,7 +44,7 @@ using namespace WebCore;
 
 bool AcceleratedBackingStore::checkRequirements()
 {
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(EGL)
     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland)
         return AcceleratedBackingStoreWayland::checkRequirements();
 #endif
@@ -61,7 +61,7 @@ std::unique_ptr<AcceleratedBackingStore>
     if (!HardwareAccelerationManager::singleton().canUseHardwareAcceleration())
         return nullptr;
 
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(EGL)
     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland)
         return AcceleratedBackingStoreWayland::create(webPage);
 #endif
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.cpp webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.cpp	2023-02-20 03:22:21.793755000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.cpp	2023-06-03 18:19:05.829706397 -0500
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "AcceleratedBackingStoreWayland.h"
 
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(EGL)
 
 #include "LayerTreeContext.h"
 #include "WebPageProxy.h"
@@ -56,18 +56,24 @@
 #include <WebCore/OpenGLShims.h>
 #endif
 
+#if USE(WPE_RENDERER)
 #include <wpe/wpe.h>
 #include <wpe/fdo-egl.h>
 #if WPE_FDO_CHECK_VERSION(1, 7, 0)
 #include <wayland-server.h>
 #include <wpe/unstable/fdo-shm.h>
 #endif
+#else
+#include "WaylandCompositor.h"
+#endif
 
+#if USE(WPE_RENDERER)
 #if !defined(PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)
 typedef void (*PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES);
 #endif
 
 static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glImageTargetTexture2D;
+#endif
 
 namespace WebKit {
 using namespace WebCore;
@@ -75,6 +81,7 @@ using namespace WebCore;
 enum class WaylandImpl { Unsupported, EGL, SHM };
 static std::optional<WaylandImpl> s_waylandImpl;
 
+#if USE(WPE_RENDERER)
 static bool isEGLImageAvailable(bool useIndexedGetString)
 {
 #if USE(OPENGL_ES)
@@ -144,9 +151,11 @@ static bool tryInitializeSHM()
     return false;
 #endif
 }
+#endif // USE(WPE_RENDERER)
 
 bool AcceleratedBackingStoreWayland::checkRequirements()
 {
+#if USE(WPE_RENDERER)
     if (s_waylandImpl)
         return s_waylandImpl.value() != WaylandImpl::Unsupported;
 
@@ -157,6 +166,13 @@ bool AcceleratedBackingStoreWayland::che
         return true;
 
     WTFLogAlways("AcceleratedBackingStoreWayland requires glEGLImageTargetTexture2D or shm interface");
+#else
+    if (WaylandCompositor::singleton().isRunning()) {
+        s_waylandImpl = WaylandImpl::EGL;
+        return true;
+    }
+#endif
+
     s_waylandImpl = WaylandImpl::Unsupported;
     return false;
 }
@@ -170,6 +186,7 @@ std::unique_ptr<AcceleratedBackingStoreW
 AcceleratedBackingStoreWayland::AcceleratedBackingStoreWayland(WebPageProxy& webPage)
     : AcceleratedBackingStore(webPage)
 {
+#if USE(WPE_RENDERER)
     static struct wpe_view_backend_exportable_fdo_egl_client exportableEGLClient = {
         // export_egl_image
         nullptr,
@@ -213,10 +230,14 @@ AcceleratedBackingStoreWayland::Accelera
     }
 
     wpe_view_backend_initialize(wpe_view_backend_exportable_fdo_get_view_backend(m_exportable));
+#else
+    WaylandCompositor::singleton().registerWebPage(m_webPage);
+#endif
 }
 
 AcceleratedBackingStoreWayland::~AcceleratedBackingStoreWayland()
 {
+#if USE(WPE_RENDERER)
     if (s_waylandImpl.value() == WaylandImpl::EGL) {
         if (m_egl.pendingImage)
             wpe_view_backend_exportable_fdo_egl_dispatch_release_exported_image(m_exportable, m_egl.pendingImage);
@@ -228,16 +249,27 @@ AcceleratedBackingStoreWayland::~Acceler
         }
     }
     wpe_view_backend_exportable_fdo_destroy(m_exportable);
+#else
+    WaylandCompositor::singleton().unregisterWebPage(m_webPage);
+#endif
 
     if (m_gdkGLContext && m_gdkGLContext.get() == gdk_gl_context_get_current())
         gdk_gl_context_clear_current();
 }
 
+void AcceleratedBackingStoreWayland::realize()
+{
+#if !USE(WPE_RENDERER)
+    WaylandCompositor::singleton().bindWebPage(m_webPage);
+#endif
+}
+
 void AcceleratedBackingStoreWayland::unrealize()
 {
     if (!m_glContextInitialized)
         return;
 
+#if USE(WPE_RENDERER)
     if (s_waylandImpl.value() == WaylandImpl::EGL) {
         if (m_egl.viewTexture) {
             if (makeContextCurrent())
@@ -245,6 +277,9 @@ void AcceleratedBackingStoreWayland::unr
             m_egl.viewTexture = 0;
         }
     }
+#else
+    WaylandCompositor::singleton().unbindWebPage(m_webPage);
+#endif
 
     if (m_gdkGLContext && m_gdkGLContext.get() == gdk_gl_context_get_current())
         gdk_gl_context_clear_current();
@@ -292,6 +327,7 @@ bool AcceleratedBackingStoreWayland::mak
     return m_glContext ? m_glContext->makeContextCurrent() : false;
 }
 
+#if USE(WPE_RENDERER)
 void AcceleratedBackingStoreWayland::update(const LayerTreeContext& context)
 {
     if (m_surfaceID == context.contextID)
@@ -394,10 +430,12 @@ void AcceleratedBackingStoreWayland::dis
     m_webPage.setViewNeedsDisplay(IntRect(IntPoint::zero(), m_webPage.viewSize()));
 }
 #endif
+#endif
 
 bool AcceleratedBackingStoreWayland::tryEnsureTexture(unsigned& texture, IntSize& textureSize)
 {
     ASSERT(s_waylandImpl.value() == WaylandImpl::EGL);
+#if USE(WPE_RENDERER)
     if (!makeContextCurrent())
         return false;
 
@@ -426,6 +464,10 @@ bool AcceleratedBackingStoreWayland::try
 
     texture = m_egl.viewTexture;
     textureSize = { static_cast<int>(wpe_fdo_egl_exported_image_get_width(m_egl.committedImage)), static_cast<int>(wpe_fdo_egl_exported_image_get_height(m_egl.committedImage)) };
+#else
+    if (!WaylandCompositor::singleton().getTexture(m_webPage, texture, textureSize))
+        return false;
+#endif
 
     return true;
 }
@@ -498,6 +540,7 @@ void AcceleratedBackingStoreWayland::sna
         break;
     }
     case WaylandImpl::SHM:
+#if USE(WPE_RENDERER)
 #if WPE_FDO_CHECK_VERSION(1, 7, 0)
         if (m_shm.pendingFrame) {
             wpe_view_backend_exportable_fdo_dispatch_frame_complete(m_exportable);
@@ -510,6 +553,9 @@ void AcceleratedBackingStoreWayland::sna
 #else
         FALLTHROUGH;
 #endif // WPE_FDO_CHECK_VERSION
+#else
+        FALLTHROUGH;
+#endif
     case WaylandImpl::Unsupported:
         RELEASE_ASSERT_NOT_REACHED();
     }
@@ -544,6 +590,7 @@ bool AcceleratedBackingStoreWayland::pai
         break;
     }
     case WaylandImpl::SHM:
+#if USE(WPE_RENDERER)
 #if WPE_FDO_CHECK_VERSION(1, 7, 0)
         if (m_shm.pendingFrame) {
             wpe_view_backend_exportable_fdo_dispatch_frame_complete(m_exportable);
@@ -558,6 +605,9 @@ bool AcceleratedBackingStoreWayland::pai
 #else
         FALLTHROUGH;
 #endif // WPE_FDO_CHECK_VERSION
+#else
+        FALLTHROUGH;
+#endif // USE(WPE_RENDERER)
     case WaylandImpl::Unsupported:
         RELEASE_ASSERT_NOT_REACHED();
     }
@@ -582,4 +632,4 @@ bool AcceleratedBackingStoreWayland::pai
 
 } // namespace WebKit
 
-#endif // PLATFORM(WAYLAND)
+#endif // PLATFORM(WAYLAND) && USE(EGL)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.h webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.h
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.h	2023-02-20 03:22:21.793755000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/AcceleratedBackingStoreWayland.h	2023-06-03 18:19:05.829706397 -0500
@@ -31,9 +31,12 @@
 
 #include <WebCore/RefPtrCairo.h>
 #include <gtk/gtk.h>
-#include <wpe/fdo.h>
 #include <wtf/glib/GRefPtr.h>
 
+#if USE(WPE_RENDERER)
+#include <wpe/fdo.h>
+#endif
+
 typedef void* EGLImageKHR;
 typedef struct _GdkGLContext GdkGLContext;
 struct wpe_fdo_egl_exported_image;
@@ -59,10 +62,12 @@ private:
     AcceleratedBackingStoreWayland(WebPageProxy&);
 
     void tryEnsureGLContext();
+#if USE(WPE_RENDERER)
     void displayImage(struct wpe_fdo_egl_exported_image*);
 #if WPE_FDO_CHECK_VERSION(1,7,0)
     void displayBuffer(struct wpe_fdo_shm_exported_buffer*);
 #endif
+#endif
     bool tryEnsureTexture(unsigned&, WebCore::IntSize&);
     void downloadTexture(unsigned, const WebCore::IntSize&);
 
@@ -71,16 +76,20 @@ private:
 #else
     bool paint(cairo_t*, const WebCore::IntRect&) override;
 #endif
+    void realize() override;
     void unrealize() override;
     bool makeContextCurrent() override;
+#if USE(WPE_RENDERER)
     void update(const LayerTreeContext&) override;
     int renderHostFileDescriptor() override;
+#endif
 
     RefPtr<cairo_surface_t> m_surface;
     bool m_glContextInitialized { false };
     GRefPtr<GdkGLContext> m_gdkGLContext;
     std::unique_ptr<WebCore::GLContext> m_glContext;
 
+#if USE(WPE_RENDERER)
     struct wpe_view_backend_exportable_fdo* m_exportable { nullptr };
     uint64_t m_surfaceID { 0 };
     struct {
@@ -94,6 +103,7 @@ private:
         bool pendingFrame { false };
     } m_shm;
 #endif
+#endif
 };
 
 } // namespace WebKit
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/WaylandCompositor.cpp webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/WaylandCompositor.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/WaylandCompositor.cpp	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/WaylandCompositor.cpp	2023-06-03 18:19:05.833706419 -0500
@@ -0,0 +1,626 @@
+/*
+ * Copyright (C) 2016 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "WaylandCompositor.h"
+
+#if PLATFORM(WAYLAND) && USE(EGL) && !USE(WPE_RENDERER)
+
+#include "ProvisionalPageProxy.h"
+#include "WebKitWaylandServerProtocol.h"
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <WebCore/GLContext.h>
+#include <WebCore/PlatformDisplayWayland.h>
+#include <WebCore/Region.h>
+#include <gtk/gtk.h>
+#include <wayland-server-protocol.h>
+#include <wtf/UUID.h>
+
+#if USE(OPENGL_ES)
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+#else
+#include <WebCore/OpenGLShims.h>
+#endif
+
+namespace WebKit {
+using namespace WebCore;
+
+#if !defined(PFNEGLBINDWAYLANDDISPLAYWL)
+typedef EGLBoolean (*PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay, struct wl_display*);
+#endif
+
+#if !defined(PFNEGLUNBINDWAYLANDDISPLAYWL)
+typedef EGLBoolean (*PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay, struct wl_display*);
+#endif
+
+#if !defined(EGL_WAYLAND_BUFFER_WL)
+#define EGL_WAYLAND_BUFFER_WL 0x31D5
+#endif
+
+#if !defined(PFNEGLQUERYWAYLANDBUFFERWL)
+typedef EGLBoolean (*PFNEGLQUERYWAYLANDBUFFERWL) (EGLDisplay, struct wl_resource*, EGLint attribute, EGLint* value);
+#endif
+
+#if !defined(PFNEGLCREATEIMAGEKHRPROC)
+typedef EGLImageKHR (*PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay, EGLContext, EGLenum target, EGLClientBuffer, const EGLint* attribList);
+#endif
+
+#if !defined(PFNEGLDESTROYIMAGEKHRPROC)
+typedef EGLBoolean (*PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay, EGLImageKHR);
+#endif
+
+#if !defined(PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)
+typedef void (*PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES);
+#endif
+
+static PFNEGLBINDWAYLANDDISPLAYWL eglBindWaylandDisplay;
+static PFNEGLUNBINDWAYLANDDISPLAYWL eglUnbindWaylandDisplay;
+static PFNEGLQUERYWAYLANDBUFFERWL eglQueryWaylandBuffer;
+static PFNEGLCREATEIMAGEKHRPROC eglCreateImage;
+static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImage;
+static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glImageTargetTexture2D;
+
+WaylandCompositor& WaylandCompositor::singleton()
+{
+    static NeverDestroyed<WaylandCompositor> waylandCompositor;
+    return waylandCompositor;
+}
+
+WaylandCompositor::Buffer* WaylandCompositor::Buffer::getOrCreate(struct wl_resource* resource)
+{
+    if (struct wl_listener* listener = wl_resource_get_destroy_listener(resource, destroyListenerCallback)) {
+        WaylandCompositor::Buffer* buffer;
+        return wl_container_of(listener, buffer, m_destroyListener);
+    }
+
+    return new WaylandCompositor::Buffer(resource);
+}
+
+WaylandCompositor::Buffer::Buffer(struct wl_resource* resource)
+    : m_resource(resource)
+{
+    wl_list_init(&m_destroyListener.link);
+    m_destroyListener.notify = destroyListenerCallback;
+    wl_resource_add_destroy_listener(m_resource, &m_destroyListener);
+}
+
+WaylandCompositor::Buffer::~Buffer()
+{
+    wl_list_remove(&m_destroyListener.link);
+}
+
+void WaylandCompositor::Buffer::destroyListenerCallback(struct wl_listener* listener, void*)
+{
+    WaylandCompositor::Buffer* buffer;
+    buffer = wl_container_of(listener, buffer, m_destroyListener);
+    delete buffer;
+}
+
+void WaylandCompositor::Buffer::use()
+{
+    m_busyCount++;
+}
+
+void WaylandCompositor::Buffer::unuse()
+{
+    m_busyCount--;
+    if (!m_busyCount)
+        wl_resource_queue_event(m_resource, WL_BUFFER_RELEASE);
+}
+
+EGLImageKHR WaylandCompositor::Buffer::createImage() const
+{
+    return static_cast<EGLImageKHR*>(eglCreateImage(PlatformDisplay::sharedDisplay().eglDisplay(), EGL_NO_CONTEXT, EGL_WAYLAND_BUFFER_WL, m_resource, nullptr));
+}
+
+IntSize WaylandCompositor::Buffer::size() const
+{
+    EGLDisplay eglDisplay = PlatformDisplay::sharedDisplay().eglDisplay();
+    int width, height;
+    eglQueryWaylandBuffer(eglDisplay, m_resource, EGL_WIDTH, &width);
+    eglQueryWaylandBuffer(eglDisplay, m_resource, EGL_HEIGHT, &height);
+
+    return { width, height };
+}
+
+WaylandCompositor::Surface::Surface()
+    : m_image(EGL_NO_IMAGE_KHR)
+{
+}
+
+WaylandCompositor::Surface::~Surface()
+{
+    setWebPage(nullptr);
+
+    // Destroy pending frame callbacks.
+    auto pendingList = WTFMove(m_pendingFrameCallbackList);
+    for (auto* resource : pendingList)
+        wl_resource_destroy(resource);
+    auto list = WTFMove(m_frameCallbackList);
+    for (auto* resource : list)
+        wl_resource_destroy(resource);
+
+    if (m_buffer)
+        m_buffer->unuse();
+}
+
+void WaylandCompositor::Surface::setWebPage(WebPageProxy* webPage)
+{
+    if (m_webPage == webPage)
+        return;
+
+    if (m_webPage) {
+        flushPendingFrameCallbacks();
+        flushFrameCallbacks();
+        gtk_widget_remove_tick_callback(m_webPage->viewWidget(), m_tickCallbackID);
+        m_tickCallbackID = 0;
+
+        if (m_webPage->makeGLContextCurrent()) {
+            if (m_image != EGL_NO_IMAGE_KHR)
+                eglDestroyImage(PlatformDisplay::sharedDisplay().eglDisplay(), m_image);
+            if (m_texture)
+                glDeleteTextures(1, &m_texture);
+        }
+
+        m_image = EGL_NO_IMAGE_KHR;
+        m_texture = 0;
+    }
+
+    m_webPage = webPage;
+    if (!m_webPage)
+        return;
+
+    if (m_webPage->makeGLContextCurrent()) {
+        glGenTextures(1, &m_texture);
+        glBindTexture(GL_TEXTURE_2D, m_texture);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+    }
+
+    m_tickCallbackID = gtk_widget_add_tick_callback(m_webPage->viewWidget(), [](GtkWidget*, GdkFrameClock*, gpointer userData) -> gboolean {
+        auto* surface = static_cast<Surface*>(userData);
+        surface->flushFrameCallbacks();
+        return G_SOURCE_CONTINUE;
+    }, this, nullptr);
+}
+
+void WaylandCompositor::Surface::makePendingBufferCurrent()
+{
+    if (m_pendingBuffer == m_buffer)
+        return;
+
+    if (m_buffer)
+        m_buffer->unuse();
+
+    if (m_pendingBuffer)
+        m_pendingBuffer->use();
+
+    m_buffer = m_pendingBuffer;
+}
+
+void WaylandCompositor::Surface::attachBuffer(struct wl_resource* buffer)
+{
+    if (m_pendingBuffer)
+        m_pendingBuffer = nullptr;
+
+    if (buffer) {
+        auto* compositorBuffer = WaylandCompositor::Buffer::getOrCreate(buffer);
+        m_pendingBuffer = *compositorBuffer;
+    }
+}
+
+void WaylandCompositor::Surface::requestFrame(struct wl_resource* resource)
+{
+    wl_resource_set_implementation(resource, nullptr, this, [](struct wl_resource* resource) {
+        auto* surface = static_cast<WaylandCompositor::Surface*>(wl_resource_get_user_data(resource));
+        if (size_t item = surface->m_pendingFrameCallbackList.find(resource) != notFound)
+            surface->m_pendingFrameCallbackList.remove(item);
+    });
+    m_pendingFrameCallbackList.append(resource);
+}
+
+bool WaylandCompositor::Surface::prepareTextureForPainting(unsigned& texture, IntSize& textureSize)
+{
+    if (!m_texture || m_image == EGL_NO_IMAGE_KHR)
+        return false;
+
+    if (!m_webPage || !m_webPage->makeGLContextCurrent())
+        return false;
+
+    glBindTexture(GL_TEXTURE_2D, m_texture);
+    glImageTargetTexture2D(GL_TEXTURE_2D, m_image);
+
+    texture = m_texture;
+    textureSize = m_imageSize;
+    return true;
+}
+
+void WaylandCompositor::Surface::flushFrameCallbacks()
+{
+    auto list = WTFMove(m_frameCallbackList);
+    for (auto* resource : list) {
+        wl_callback_send_done(resource, 0);
+        wl_resource_destroy(resource);
+    }
+}
+
+void WaylandCompositor::Surface::flushPendingFrameCallbacks()
+{
+    auto list = WTFMove(m_pendingFrameCallbackList);
+    for (auto* resource : list) {
+        wl_callback_send_done(resource, 0);
+        wl_resource_destroy(resource);
+    }
+}
+
+void WaylandCompositor::Surface::commit()
+{
+    if (!m_webPage || !m_webPage->makeGLContextCurrent()) {
+        makePendingBufferCurrent();
+        flushPendingFrameCallbacks();
+        return;
+    }
+
+    EGLDisplay eglDisplay = PlatformDisplay::sharedDisplay().eglDisplay();
+    if (m_image != EGL_NO_IMAGE_KHR)
+        eglDestroyImage(eglDisplay, m_image);
+    m_image = m_pendingBuffer->createImage();
+    if (m_image == EGL_NO_IMAGE_KHR)
+        return;
+
+    m_imageSize = m_pendingBuffer->size();
+
+    makePendingBufferCurrent();
+
+    m_webPage->setViewNeedsDisplay(IntRect(IntPoint::zero(), m_webPage->viewSize()));
+
+    auto list = WTFMove(m_pendingFrameCallbackList);
+    m_frameCallbackList.appendVector(list);
+}
+
+static const struct wl_surface_interface surfaceInterface = {
+    // destroyCallback
+    [](struct wl_client*, struct wl_resource* resource)
+    {
+        wl_resource_destroy(resource);
+    },
+    // attachCallback
+    [](struct wl_client* client, struct wl_resource* resource, struct wl_resource* buffer, int32_t sx, int32_t sy)
+    {
+        auto* surface = static_cast<WaylandCompositor::Surface*>(wl_resource_get_user_data(resource));
+        if (!surface)
+            return;
+
+        EGLint format;
+        if (!eglQueryWaylandBuffer(PlatformDisplay::sharedDisplay().eglDisplay(), buffer, EGL_TEXTURE_FORMAT, &format)
+            || (format != EGL_TEXTURE_RGB && format != EGL_TEXTURE_RGBA))
+            return;
+
+        surface->attachBuffer(buffer);
+    },
+    // damageCallback
+    [](struct wl_client*, struct wl_resource*, int32_t, int32_t, int32_t, int32_t) { },
+    // frameCallback
+    [](struct wl_client* client, struct wl_resource* resource, uint32_t id)
+    {
+        auto* surface = static_cast<WaylandCompositor::Surface*>(wl_resource_get_user_data(resource));
+        if (!surface)
+            return;
+
+        if (struct wl_resource* callbackResource = wl_resource_create(client, &wl_callback_interface, 1, id))
+            surface->requestFrame(callbackResource);
+        else
+            wl_client_post_no_memory(client);
+    },
+    // setOpaqueRegionCallback
+    [](struct wl_client*, struct wl_resource*, struct wl_resource*) { },
+    // setInputRegionCallback
+    [](struct wl_client*, struct wl_resource*, struct wl_resource*) { },
+    // commitCallback
+    [](struct wl_client* client, struct wl_resource* resource)
+    {
+        auto* surface = static_cast<WaylandCompositor::Surface*>(wl_resource_get_user_data(resource));
+        if (!surface)
+            return;
+        surface->commit();
+    },
+    // setBufferTransformCallback
+    [](struct wl_client*, struct wl_resource*, int32_t) { },
+    // setBufferScaleCallback
+    [](struct wl_client*, struct wl_resource*, int32_t) { },
+#if WAYLAND_VERSION_MAJOR > 1 || (WAYLAND_VERSION_MAJOR == 1 && WAYLAND_VERSION_MINOR >= 10)
+    // damageBufferCallback
+    [](struct wl_client*, struct wl_resource*, int32_t, int32_t, int32_t, int32_t) { },
+#endif
+};
+
+static const struct wl_compositor_interface compositorInterface = {
+    // createSurfaceCallback
+    [](struct wl_client* client, struct wl_resource* resource, uint32_t id)
+    {
+        if (struct wl_resource* surfaceResource = wl_resource_create(client, &wl_surface_interface, 1, id)) {
+            wl_resource_set_implementation(surfaceResource, &surfaceInterface, new WaylandCompositor::Surface(),
+                [](struct wl_resource* resource) {
+                    auto* surface = static_cast<WaylandCompositor::Surface*>(wl_resource_get_user_data(resource));
+                    delete surface;
+                });
+        } else
+            wl_client_post_no_memory(client);
+    },
+    // createRegionCallback
+    [](struct wl_client*, struct wl_resource*, uint32_t) { }
+};
+
+static const struct wl_webkitgtk_interface webkitgtkInterface = {
+    // bindSurfaceToPageCallback
+    [](struct wl_client*, struct wl_resource* resource, struct wl_resource* surfaceResource, uint32_t pageID)
+    {
+        auto* surface = static_cast<WaylandCompositor::Surface*>(wl_resource_get_user_data(surfaceResource));
+        if (!surface)
+            return;
+
+        auto* compositor = static_cast<WaylandCompositor*>(wl_resource_get_user_data(resource));
+        compositor->bindSurfaceToWebPage(surface, makeObjectIdentifier<PageIdentifierType>(pageID));
+    }
+};
+
+// FIXME: Merge with AcceleratedBackingStoreWayland::isEGLImageAvailable.
+static bool isEGLImageAvailable(bool useIndexedGetString)
+{
+#if USE(OPENGL_ES)
+    UNUSED_PARAM(useIndexedGetString);
+#else
+    if (useIndexedGetString) {
+        GLint numExtensions = 0;
+        ::glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
+        for (GLint i = 0; i < numExtensions; ++i) {
+            String extension = String::fromLatin1(reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i)));
+            if (extension == "GL_OES_EGL_image"_s || extension == "GL_OES_EGL_image_external"_s)
+                return true;
+        }
+    } else
+#endif
+    {
+        String extensionsString = String::fromLatin1(reinterpret_cast<const char*>(::glGetString(GL_EXTENSIONS)));
+        for (auto& extension : extensionsString.split(' ')) {
+            if (extension == "GL_OES_EGL_image"_s || extension == "GL_OES_EGL_image_external"_s)
+                return true;
+        }
+    }
+
+    return false;
+}
+
+bool WaylandCompositor::initializeEGL()
+{
+    const char* extensions = eglQueryString(PlatformDisplay::sharedDisplay().eglDisplay(), EGL_EXTENSIONS);
+
+    if (PlatformDisplay::sharedDisplay().eglCheckVersion(1, 5)) {
+        eglCreateImage = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImage"));
+        eglDestroyImage = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImage"));
+    } else {
+        if (GLContext::isExtensionSupported(extensions, "EGL_KHR_image_base")) {
+            eglCreateImage = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
+            eglDestroyImage = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImageKHR"));
+        }
+    }
+    if (!eglCreateImage || !eglDestroyImage) {
+        WTFLogAlways("WaylandCompositor requires eglCreateImage and eglDestroyImage.");
+        return false;
+    }
+
+    if (GLContext::isExtensionSupported(extensions, "EGL_WL_bind_wayland_display")) {
+        eglBindWaylandDisplay = reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglBindWaylandDisplayWL"));
+        eglUnbindWaylandDisplay = reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglUnbindWaylandDisplayWL"));
+        eglQueryWaylandBuffer = reinterpret_cast<PFNEGLQUERYWAYLANDBUFFERWL>(eglGetProcAddress("eglQueryWaylandBufferWL"));
+    }
+    if (!eglBindWaylandDisplay || !eglUnbindWaylandDisplay || !eglQueryWaylandBuffer) {
+        WTFLogAlways("WaylandCompositor requires eglBindWaylandDisplayWL, eglUnbindWaylandDisplayWL and eglQueryWaylandBuffer.");
+        return false;
+    }
+
+    std::unique_ptr<WebCore::GLContext> eglContext = GLContext::createOffscreenContext();
+    if (!eglContext)
+        return false;
+
+    if (!eglContext->makeContextCurrent())
+        return false;
+
+#if USE(OPENGL_ES)
+    if (isEGLImageAvailable(false))
+#else
+    if (isEGLImageAvailable(GLContext::current()->version() >= 320))
+#endif
+        glImageTargetTexture2D = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));
+
+    if (!glImageTargetTexture2D) {
+        WTFLogAlways("WaylandCompositor requires glEGLImageTargetTexture2D.");
+        return false;
+    }
+
+    return true;
+}
+
+typedef struct {
+    GSource source;
+    gpointer fdTag;
+    struct wl_display* display;
+} WaylandLoopSource;
+
+static const unsigned waylandLoopSourceCondition = G_IO_IN | G_IO_HUP | G_IO_ERR;
+
+static GSourceFuncs waylandLoopSourceFunctions = {
+    // prepare
+    [](GSource *source, int *timeout) -> gboolean
+    {
+        *timeout = -1;
+        auto* wlLoopSource = reinterpret_cast<WaylandLoopSource*>(source);
+        wl_display_flush_clients(wlLoopSource->display);
+        return FALSE;
+    },
+    nullptr, // check
+    // dispatch
+    [](GSource* source, GSourceFunc callback, gpointer userData) -> gboolean
+    {
+        auto* wlLoopSource = reinterpret_cast<WaylandLoopSource*>(source);
+        unsigned events = g_source_query_unix_fd(source, wlLoopSource->fdTag) & waylandLoopSourceCondition;
+        if (events & G_IO_HUP || events & G_IO_ERR) {
+            WTFLogAlways("Wayland Display Event Source: lost connection to nested Wayland compositor");
+            return G_SOURCE_REMOVE;
+        }
+
+        if (events & G_IO_IN)
+            wl_event_loop_dispatch(wl_display_get_event_loop(wlLoopSource->display), 0);
+        return G_SOURCE_CONTINUE;
+    },
+    nullptr, // finalize
+    nullptr, // closure_callback
+    nullptr, // closure_marshall
+};
+
+static GRefPtr<GSource> createWaylandLoopSource(struct wl_display* display)
+{
+    GRefPtr<GSource> source = adoptGRef(g_source_new(&waylandLoopSourceFunctions, sizeof(WaylandLoopSource)));
+    g_source_set_name(source.get(), "Nested Wayland compositor display event source");
+
+    auto* wlLoopSource = reinterpret_cast<WaylandLoopSource*>(source.get());
+    wlLoopSource->display = display;
+    wlLoopSource->fdTag = g_source_add_unix_fd(source.get(), wl_event_loop_get_fd(wl_display_get_event_loop(display)), static_cast<GIOCondition>(waylandLoopSourceCondition));
+    g_source_attach(source.get(), nullptr);
+
+    return source;
+}
+
+WaylandCompositor::WaylandCompositor()
+{
+    std::unique_ptr<struct wl_display, DisplayDeleter> display(wl_display_create());
+    if (!display) {
+        WTFLogAlways("Nested Wayland compositor could not create display object");
+        return;
+    }
+
+    String displayName = makeString("webkitgtk-wayland-compositor-"_s, UUID::createVersion4());
+    if (wl_display_add_socket(display.get(), displayName.utf8().data()) == -1) {
+        WTFLogAlways("Nested Wayland compositor could not create display socket");
+        return;
+    }
+
+    WlUniquePtr<struct wl_global> compositorGlobal(wl_global_create(display.get(), &wl_compositor_interface, wl_compositor_interface.version, this,
+        [](struct wl_client* client, void* data, uint32_t version, uint32_t id) {
+            if (struct wl_resource* resource = wl_resource_create(client, &wl_compositor_interface, std::min(static_cast<int>(version), 3), id))
+                wl_resource_set_implementation(resource, &compositorInterface, static_cast<WaylandCompositor*>(data), nullptr);
+            else
+                wl_client_post_no_memory(client);
+        }));
+    if (!compositorGlobal) {
+        WTFLogAlways("Nested Wayland compositor could not register compositor global");
+        return;
+    }
+
+    WlUniquePtr<struct wl_global> webkitgtkGlobal(wl_global_create(display.get(), &wl_webkitgtk_interface, 1, this,
+        [](struct wl_client* client, void* data, uint32_t version, uint32_t id) {
+            if (struct wl_resource* resource = wl_resource_create(client, &wl_webkitgtk_interface, 1, id))
+                wl_resource_set_implementation(resource, &webkitgtkInterface, static_cast<WaylandCompositor*>(data), nullptr);
+            else
+                wl_client_post_no_memory(client);
+        }));
+    if (!webkitgtkGlobal) {
+        WTFLogAlways("Nested Wayland compositor could not register webkitgtk global");
+        return;
+    }
+
+    if (!initializeEGL()) {
+        WTFLogAlways("Nested Wayland compositor could not initialize EGL");
+        return;
+    }
+
+    if (!eglBindWaylandDisplay(PlatformDisplay::sharedDisplay().eglDisplay(), display.get())) {
+        WTFLogAlways("Nested Wayland compositor could not bind nested display");
+        return;
+    }
+
+    m_displayName = WTFMove(displayName);
+    m_display = WTFMove(display);
+    m_compositorGlobal = WTFMove(compositorGlobal);
+    m_webkitgtkGlobal = WTFMove(webkitgtkGlobal);
+    m_eventSource = createWaylandLoopSource(m_display.get());
+}
+
+bool WaylandCompositor::getTexture(WebPageProxy& webPage, unsigned& texture, IntSize& textureSize)
+{
+    if (WeakPtr<Surface> surface = m_pageMap.get(&webPage))
+        return surface->prepareTextureForPainting(texture, textureSize);
+    return false;
+}
+
+void WaylandCompositor::bindSurfaceToWebPage(WaylandCompositor::Surface* surface, WebCore::PageIdentifier pageID)
+{
+    WebPageProxy* webPage = nullptr;
+    for (auto* page : m_pageMap.keys()) {
+        auto* provisionalPage = page->provisionalPageProxy();
+        auto webPageID = provisionalPage ? provisionalPage->webPageID() : page->webPageID();
+        if (webPageID == pageID) {
+            webPage = page;
+            break;
+        }
+    }
+    if (!webPage)
+        return;
+
+    unbindWebPage(*webPage);
+    surface->setWebPage(webPage);
+    m_pageMap.set(webPage, *surface);
+}
+
+void WaylandCompositor::bindWebPage(WebPageProxy& webPage)
+{
+    if (WeakPtr<Surface> surface = m_pageMap.get(&webPage))
+        surface->setWebPage(&webPage);
+}
+
+void WaylandCompositor::unbindWebPage(WebPageProxy& webPage)
+{
+    if (WeakPtr<Surface> surface = m_pageMap.get(&webPage))
+        surface->setWebPage(nullptr);
+}
+
+void WaylandCompositor::registerWebPage(WebPageProxy& webPage)
+{
+    m_pageMap.add(&webPage, nullptr);
+}
+
+void WaylandCompositor::unregisterWebPage(WebPageProxy& webPage)
+{
+    if (WeakPtr<Surface> surface = m_pageMap.take(&webPage))
+        surface->setWebPage(nullptr);
+}
+
+} // namespace WebKit
+
+#endif // PLATFORM(WAYLAND) && USE(EGL) && !USE(WPE_RENDERER)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/WaylandCompositor.h webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/WaylandCompositor.h
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/gtk/WaylandCompositor.h	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/gtk/WaylandCompositor.h	2023-06-03 18:19:05.833706419 -0500
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2016 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if PLATFORM(WAYLAND) && USE(EGL) && !USE(WPE_RENDERER)
+
+#include "WebPageProxy.h"
+#include <WebCore/RefPtrCairo.h>
+#include <WebCore/WlUniquePtr.h>
+#include <wayland-server.h>
+#include <wtf/HashMap.h>
+#include <wtf/NeverDestroyed.h>
+#include <wtf/Noncopyable.h>
+#include <wtf/WeakPtr.h>
+#include <wtf/glib/GRefPtr.h>
+#include <wtf/text/WTFString.h>
+
+typedef void *EGLImageKHR;
+
+namespace WebKit {
+
+class WebPageProxy;
+
+class WaylandCompositor {
+    WTF_MAKE_NONCOPYABLE(WaylandCompositor);
+    friend NeverDestroyed<WaylandCompositor>;
+public:
+    static WaylandCompositor& singleton();
+
+    class Buffer : public CanMakeWeakPtr<Buffer> {
+        WTF_MAKE_NONCOPYABLE(Buffer); WTF_MAKE_FAST_ALLOCATED;
+    public:
+        static Buffer* getOrCreate(struct wl_resource*);
+        ~Buffer();
+
+        void use();
+        void unuse();
+
+        EGLImageKHR createImage() const;
+        WebCore::IntSize size() const;
+
+    private:
+        Buffer(struct wl_resource*);
+        static void destroyListenerCallback(struct wl_listener*, void*);
+
+        struct wl_resource* m_resource { nullptr };
+        struct wl_listener m_destroyListener;
+        uint32_t m_busyCount { 0 };
+    };
+
+    class Surface : public CanMakeWeakPtr<Surface> {
+        WTF_MAKE_NONCOPYABLE(Surface); WTF_MAKE_FAST_ALLOCATED;
+    public:
+        Surface();
+        ~Surface();
+
+        void attachBuffer(struct wl_resource*);
+        void requestFrame(struct wl_resource*);
+        void commit();
+
+        void setWebPage(WebPageProxy*);
+        bool prepareTextureForPainting(unsigned&, WebCore::IntSize&);
+
+    private:
+        void flushFrameCallbacks();
+        void flushPendingFrameCallbacks();
+        void makePendingBufferCurrent();
+
+        WeakPtr<Buffer> m_buffer;
+        WeakPtr<Buffer> m_pendingBuffer;
+        unsigned m_texture { 0 };
+        EGLImageKHR m_image;
+        WebCore::IntSize m_imageSize;
+        Vector<wl_resource*> m_pendingFrameCallbackList;
+        Vector<wl_resource*> m_frameCallbackList;
+        WebPageProxy* m_webPage { nullptr };
+        unsigned m_tickCallbackID { 0 };
+    };
+
+    bool isRunning() const { return !!m_display; }
+    String displayName() const { return m_displayName; }
+
+    void bindSurfaceToWebPage(Surface*, WebCore::PageIdentifier);
+    void bindWebPage(WebPageProxy&);
+    void unbindWebPage(WebPageProxy&);
+    void registerWebPage(WebPageProxy&);
+    void unregisterWebPage(WebPageProxy&);
+
+    bool getTexture(WebPageProxy&, unsigned&, WebCore::IntSize&);
+
+private:
+    WaylandCompositor();
+
+    bool initializeEGL();
+
+    String m_displayName;
+
+    struct DisplayDeleter {
+        void operator() (struct wl_display* display) { wl_display_destroy(display); }
+    };
+    std::unique_ptr<struct wl_display, DisplayDeleter> m_display;
+
+    WebCore::WlUniquePtr<struct wl_global> m_compositorGlobal;
+    WebCore::WlUniquePtr<struct wl_global> m_webkitgtkGlobal;
+    GRefPtr<GSource> m_eventSource;
+    HashMap<WebPageProxy*, WeakPtr<Surface>> m_pageMap;
+};
+
+} // namespace WebKit
+
+#endif // PLATFORM(WAYLAND) && USE(EGL) && !USE(WPE_RENDERER)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/Launcher/glib/BubblewrapLauncher.cpp webkitgtk-2.40.2/Source/WebKit/UIProcess/Launcher/glib/BubblewrapLauncher.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/UIProcess/Launcher/glib/BubblewrapLauncher.cpp	2023-05-29 02:59:44.944176000 -0500
+++ webkitgtk-2.40.2/Source/WebKit/UIProcess/Launcher/glib/BubblewrapLauncher.cpp	2023-06-03 18:19:05.833706419 -0500
@@ -40,6 +40,10 @@
 
 #include "Syscalls.h"
 
+#if PLATFORM(GTK)
+#include "WaylandCompositor.h"
+#endif
+
 #if !defined(MFD_ALLOW_SEALING) && HAVE(LINUX_MEMFD_H)
 
 // These defines were added in glibc 2.27, the same release that added memfd_create.
@@ -250,7 +254,7 @@ static void bindX11(Vector<CString>& arg
 }
 #endif
 
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(EGL)
 static void bindWayland(Vector<CString>& args)
 {
     const char* display = g_getenv("WAYLAND_DISPLAY");
@@ -260,6 +264,14 @@ static void bindWayland(Vector<CString>&
     const char* runtimeDir = g_get_user_runtime_dir();
     GUniquePtr<char> waylandRuntimeFile(g_build_filename(runtimeDir, display, nullptr));
     bindIfExists(args, waylandRuntimeFile.get(), BindFlags::ReadWrite);
+
+#if !USE(WPE_RENDERER)
+    if (WaylandCompositor::singleton().isRunning()) {
+        String displayName = WaylandCompositor::singleton().displayName();
+        waylandRuntimeFile.reset(g_build_filename(runtimeDir, displayName.utf8().data(), nullptr));
+        bindIfExists(args, waylandRuntimeFile.get(), BindFlags::ReadWrite);
+    }
+#endif
 }
 #endif
 
@@ -787,7 +799,7 @@ GRefPtr<GSubprocess> bubblewrapSpawn(GSu
     }
 
     if (launchOptions.processType == ProcessLauncher::ProcessType::Web) {
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(EGL)
         if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland) {
             bindWayland(sandboxArgs);
             sandboxArgs.append("--unshare-ipc");
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/glib/WebProcessGLib.cpp webkitgtk-2.40.2/Source/WebKit/WebProcess/glib/WebProcessGLib.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/glib/WebProcessGLib.cpp	2023-03-08 00:53:12.554624600 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/glib/WebProcessGLib.cpp	2023-06-03 18:23:15.235022927 -0500
@@ -43,6 +43,10 @@
 #include <WebCore/ApplicationGLib.h>
 #include <WebCore/MemoryCache.h>
 
+#if PLATFORM(WAYLAND)
+#include "WaylandCompositorDisplay.h"
+#endif
+
 #if USE(WPE_RENDERER)
 #include <WebCore/PlatformDisplayLibWPE.h>
 #include <wpe/wpe.h>
@@ -120,15 +124,19 @@ void WebProcess::platformInitializeWebPr
 #endif
 
 #if PLATFORM(WAYLAND)
-    if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland && !parameters.isServiceWorkerProcess) {
-        auto hostClientFileDescriptor = parameters.hostClientFileDescriptor.release();
-        if (hostClientFileDescriptor != -1) {
-            wpe_loader_init(parameters.implementationLibraryName.data());
-            m_wpeDisplay = WebCore::PlatformDisplayLibWPE::create();
-            if (!m_wpeDisplay->initialize(hostClientFileDescriptor))
-                m_wpeDisplay = nullptr;
-        }
-    }
+    if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland) {
+#if USE(WPE_RENDERER)
+        if (!parameters.isServiceWorkerProcess) {
+            auto hostClientFileDescriptor = parameters.hostClientFileDescriptor.release().release();
+            if (hostClientFileDescriptor != -1) {
+                wpe_loader_init(parameters.implementationLibraryName.data());
+                m_wpeDisplay = WebCore::PlatformDisplayLibWPE::create();
+                if (!m_wpeDisplay->initialize(hostClientFileDescriptor))
+                    m_wpeDisplay = nullptr;
+#else
+        m_waylandCompositorDisplay = WaylandCompositorDisplay::create(parameters.waylandCompositorDisplayName);
+#endif
+            }
 #endif
 
 #if USE(GSTREAMER)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.cpp webkitgtk-2.40.2/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.cpp	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.cpp	2023-06-03 18:19:05.833706419 -0500
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2017 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "WaylandCompositorDisplay.h"
+
+#if PLATFORM(WAYLAND)
+
+#include "WebKitWaylandClientProtocol.h"
+#include "WebPage.h"
+
+namespace WebKit {
+using namespace WebCore;
+
+std::unique_ptr<WaylandCompositorDisplay> WaylandCompositorDisplay::create(const String& displayName)
+{
+    if (displayName.isNull())
+        return nullptr;
+
+    if (PlatformDisplay::sharedDisplay().type() != PlatformDisplay::Type::Wayland)
+        return nullptr;
+
+    struct wl_display* display = wl_display_connect(displayName.utf8().data());
+    if (!display) {
+        WTFLogAlways("WaylandCompositorDisplay initialization: failed to connect to the Wayland display: %s", displayName.utf8().data());
+        return nullptr;
+    }
+
+    auto compositorDisplay = std::unique_ptr<WaylandCompositorDisplay>(new WaylandCompositorDisplay(display));
+    compositorDisplay->initialize();
+    return compositorDisplay;
+}
+
+void WaylandCompositorDisplay::bindSurfaceToPage(struct wl_surface* surface, WebPage& page)
+{
+    if (!m_webkitgtk)
+        return;
+
+    wl_webkitgtk_bind_surface_to_page(reinterpret_cast<struct wl_webkitgtk*>(m_webkitgtk.get()), surface, page.identifier().toUInt64());
+    wl_display_roundtrip(m_display);
+}
+
+WaylandCompositorDisplay::WaylandCompositorDisplay(struct wl_display* display)
+    : PlatformDisplayWayland(display)
+{
+    PlatformDisplay::setSharedDisplayForCompositing(*this);
+}
+
+void WaylandCompositorDisplay::registryGlobal(const char* interface, uint32_t name)
+{
+    PlatformDisplayWayland::registryGlobal(interface, name);
+    if (!std::strcmp(interface, "wl_webkitgtk"))
+        m_webkitgtk.reset(static_cast<struct wl_proxy*>(wl_registry_bind(m_registry.get(), name, &wl_webkitgtk_interface, 1)));
+}
+
+} // namespace WebKit
+
+#endif // PLATFORM(WAYLAND)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.h webkitgtk-2.40.2/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.h
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.h	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/gtk/WaylandCompositorDisplay.h	2023-06-03 18:19:05.833706419 -0500
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if PLATFORM(WAYLAND)
+
+#include <WebCore/PlatformDisplayWayland.h>
+#include <WebCore/WlUniquePtr.h>
+#include <wtf/text/WTFString.h>
+
+namespace WebKit {
+
+class WebPage;
+
+class WaylandCompositorDisplay final : public WebCore::PlatformDisplayWayland {
+    WTF_MAKE_NONCOPYABLE(WaylandCompositorDisplay);
+public:
+    static std::unique_ptr<WaylandCompositorDisplay> create(const String&);
+    ~WaylandCompositorDisplay() = default;
+    void bindSurfaceToPage(struct wl_surface*, WebPage&);
+
+private:
+    WaylandCompositorDisplay(struct wl_display*);
+    void registryGlobal(const char*, uint32_t) override;
+
+    WebCore::WlUniquePtr<struct wl_proxy> m_webkitgtk;
+};
+
+} // namespace WebKit
+
+#endif // PLATFORM(WAYLAND)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/AcceleratedSurface.cpp webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/AcceleratedSurface.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/AcceleratedSurface.cpp	2023-02-20 03:22:22.057756000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/AcceleratedSurface.cpp	2023-06-03 18:19:05.833706419 -0500
@@ -29,6 +29,10 @@
 #include "WebPage.h"
 #include <WebCore/PlatformDisplay.h>
 
+#if PLATFORM(WAYLAND)
+#include "AcceleratedSurfaceWayland.h"
+#endif
+
 #if PLATFORM(X11)
 #include "AcceleratedSurfaceX11.h"
 #endif
@@ -44,7 +48,11 @@ std::unique_ptr<AcceleratedSurface> Acce
 {
 #if PLATFORM(WAYLAND)
     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland)
+#if USE(WPE_RENDERER)
         return AcceleratedSurfaceLibWPE::create(webPage, client);
+#else
+        return AcceleratedSurfaceWayland::create(webPage, client);
+#endif
 #endif
 #if PLATFORM(X11)
     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::X11)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/CoordinatedGraphics/DrawingAreaCoordinatedGraphics.cpp webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/CoordinatedGraphics/DrawingAreaCoordinatedGraphics.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/CoordinatedGraphics/DrawingAreaCoordinatedGraphics.cpp	2023-05-29 02:59:44.976177000 -0500
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/CoordinatedGraphics/DrawingAreaCoordinatedGraphics.cpp	2023-06-03 18:19:05.833706419 -0500
@@ -233,7 +233,7 @@ void DrawingAreaCoordinatedGraphics::set
 void DrawingAreaCoordinatedGraphics::updatePreferences(const WebPreferencesStore& store)
 {
     Settings& settings = m_webPage.corePage()->settings();
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(WPE_RENDERER)
     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland
         && &PlatformDisplay::sharedDisplayForCompositing() == &PlatformDisplay::sharedDisplay()) {
         // We failed to create the shared display for compositing, disable accelerated compositing.
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.cpp webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.cpp	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.cpp	2023-06-03 18:19:05.833706419 -0500
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2016 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "AcceleratedSurfaceWayland.h"
+
+#if PLATFORM(WAYLAND)
+
+#include "WaylandCompositorDisplay.h"
+#include "WebProcess.h"
+#include <wayland-egl.h>
+
+namespace WebKit {
+using namespace WebCore;
+
+std::unique_ptr<AcceleratedSurfaceWayland> AcceleratedSurfaceWayland::create(WebPage& webPage, Client& client)
+{
+    return WebProcess::singleton().waylandCompositorDisplay() ? std::unique_ptr<AcceleratedSurfaceWayland>(new AcceleratedSurfaceWayland(webPage, client)) : nullptr;
+}
+
+AcceleratedSurfaceWayland::AcceleratedSurfaceWayland(WebPage& webPage, Client& client)
+    : AcceleratedSurface(webPage, client)
+{
+}
+
+void AcceleratedSurfaceWayland::initialize()
+{
+    m_surface = WebProcess::singleton().waylandCompositorDisplay()->createSurface();
+    m_window = wl_egl_window_create(m_surface.get(), std::max(1, m_size.width()), std::max(1, m_size.height()));
+    WebProcess::singleton().waylandCompositorDisplay()->bindSurfaceToPage(m_surface.get(), m_webPage);
+}
+
+void AcceleratedSurfaceWayland::finalize()
+{
+    wl_egl_window_destroy(m_window);
+}
+
+void AcceleratedSurfaceWayland::clientResize(const IntSize& size)
+{
+    wl_egl_window_resize(m_window, m_size.width(), m_size.height(), 0, 0);
+}
+
+void AcceleratedSurfaceWayland::didRenderFrame()
+{
+    // FIXME: frameComplete() should be called when the frame was actually rendered in the screen.
+    m_client.frameComplete();
+}
+
+} // namespace WebKit
+
+#endif // PLATFORM(WAYLAND)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.h webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.h
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.h	1969-12-31 18:00:00.000000000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/WebPage/gtk/AcceleratedSurfaceWayland.h	2023-06-03 18:19:05.833706419 -0500
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2016 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if PLATFORM(WAYLAND)
+
+#include "AcceleratedSurface.h"
+#include "WebPage.h"
+#include <WebCore/WlUniquePtr.h>
+#include <wayland-egl.h>
+
+namespace WebKit {
+
+class AcceleratedSurfaceWayland final : public AcceleratedSurface {
+    WTF_MAKE_NONCOPYABLE(AcceleratedSurfaceWayland); WTF_MAKE_FAST_ALLOCATED;
+public:
+    static std::unique_ptr<AcceleratedSurfaceWayland> create(WebPage&, Client&);
+    ~AcceleratedSurfaceWayland() = default;
+
+    uint64_t window() const override { return reinterpret_cast<uint64_t>(m_window); }
+    uint64_t surfaceID() const override { return m_webPage.identifier().toUInt64(); }
+    void clientResize(const WebCore::IntSize&) override;
+    bool shouldPaintMirrored() const override { return true; }
+
+    void initialize() override;
+    void finalize() override;
+    void didRenderFrame() override;
+
+private:
+    AcceleratedSurfaceWayland(WebPage&, Client&);
+
+    WebCore::WlUniquePtr<struct wl_surface> m_surface;
+    struct wl_egl_window* m_window { nullptr };
+};
+
+} // namespace WebKit
+
+#endif // PLATFORM(WAYLAND)
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebProcess.cpp webkitgtk-2.40.2/Source/WebKit/WebProcess/WebProcess.cpp
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebProcess.cpp	2023-03-03 04:22:14.804082000 -0600
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/WebProcess.cpp	2023-06-03 18:19:05.837706440 -0500
@@ -163,6 +163,10 @@
 #include <unistd.h>
 #endif
 
+#if PLATFORM(WAYLAND)
+#include "WaylandCompositorDisplay.h"
+#endif
+
 #if PLATFORM(COCOA)
 #include "ObjCObjectGraph.h"
 #include "UserMediaCaptureManager.h"
diff -urpN webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebProcess.h webkitgtk-2.40.2/Source/WebKit/WebProcess/WebProcess.h
--- webkitgtk-2.40.2.orig/Source/WebKit/WebProcess/WebProcess.h	2023-05-29 02:59:44.984177000 -0500
+++ webkitgtk-2.40.2/Source/WebKit/WebProcess/WebProcess.h	2023-06-03 18:19:05.837706440 -0500
@@ -74,7 +74,7 @@
 #include <WebCore/PlatformDisplay.h>
 #endif
 
-#if PLATFORM(WAYLAND)
+#if PLATFORM(WAYLAND) && USE(WPE_RENDERER)
 #include <WebCore/PlatformDisplayLibWPE.h>
 #endif
 
@@ -131,6 +131,7 @@ class RemoteLegacyCDMFactory;
 class RemoteMediaEngineConfigurationFactory;
 class StorageAreaMap;
 class UserData;
+class WaylandCompositorDisplay;
 class WebAutomationSessionProxy;
 class WebBadgeClient;
 class WebBroadcastChannelRegistry;
@@ -300,6 +301,10 @@ public:
 
     void isJITEnabled(CompletionHandler<void(bool)>&&);
 
+#if PLATFORM(WAYLAND)
+    WaylandCompositorDisplay* waylandCompositorDisplay() const { return m_waylandCompositorDisplay.get(); }
+#endif
+
     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
 
@@ -710,6 +715,10 @@ private:
     WeakHashMap<WebCore::UserGestureToken, uint64_t> m_userGestureTokens;
 
 #if PLATFORM(WAYLAND)
+    std::unique_ptr<WaylandCompositorDisplay> m_waylandCompositorDisplay;
+#endif
+
+#if PLATFORM(WAYLAND) && USE(WPE_RENDERER)
     std::unique_ptr<WebCore::PlatformDisplayLibWPE> m_wpeDisplay;
 #endif
 
