diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index 73592d75..0f19d2ec 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -176,6 +176,8 @@ if(LINUX) ruisapp_declare_variant(opengles wayland) ruisapp_declare_variant(opengl sdl) ruisapp_declare_variant(opengles sdl) + ruisapp_declare_variant(vulkan xorg) + ruisapp_declare_variant(vulkan wayland) # Compatibility aliases: for now ruisapp-opengl / ruisapp-opengles refer to the xorg variants. # Note: the namespaced alias refers to the plain (non-namespaced) target, the same @@ -283,6 +285,8 @@ if(LINUX) ${name}-opengles-wayland ${name}-opengl-sdl ${name}-opengles-sdl + ${name}-vulkan-xorg + ${name}-vulkan-wayland ) elseif(ruisapp_build_opengl_variant AND ruisapp_build_opengles_variant) myci_export( @@ -333,6 +337,8 @@ if(LINUX) ruisapp_declare_test_app(${renderer} ${backend}) endforeach() endforeach() + ruisapp_declare_test_app(vulkan xorg) + ruisapp_declare_test_app(vulkan wayland) else() if(ruisapp_build_opengl_variant) myci_declare_application(${name}-opengl-test diff --git a/src/ruisapp/application.cpp b/src/ruisapp/application.cpp index 9b9274ed..4fd1e64d 100644 --- a/src/ruisapp/application.cpp +++ b/src/ruisapp/application.cpp @@ -132,7 +132,7 @@ ruisapp::window& application::make_window(window_parameters window_params) // By choice, the VSYNC is enabled by default. // This call will synchornize the is_vsync_enabled_v field of the native window // with the actual VSYNC state of the newly created window. - win.gui.context.get().ren().ctx().set_vsync_enabled(true); + win.gui.ctx().ren().ctx().set_vsync_enabled(true); if (!this->get_shared_style_provider()) { // The platform does not support shared style_provider. @@ -140,7 +140,7 @@ ruisapp::window& application::make_window(window_parameters window_params) // The platform should support only one window which has just been created. utki::assert(this->get_windows().size() == size_t(1)); - auto& sp = win.gui.context.get().style(); + auto& sp = win.gui.ctx().style(); if (this->mount_ruis_res_pack) { // The platform doesn't have shared style provider, so we need to @@ -165,7 +165,7 @@ const std::shared_ptr& application::get_default_style_prov auto windows = this->get_windows(); if (!windows.empty()) { - return windows.front().get().gui.context.get().style_provider.to_shared_ptr(); + return windows.front().get().gui.ctx().style_provider.to_shared_ptr(); } // return nullptr because shared style provider is nullptr diff --git a/src/ruisapp/glue/android/application.cxx b/src/ruisapp/glue/android/application.cxx index 7fe36595..056c4418 100644 --- a/src/ruisapp/glue/android/application.cxx +++ b/src/ruisapp/glue/android/application.cxx @@ -22,6 +22,7 @@ along with this program. If not, see . #include "application.hxx" #include +#include #include #include @@ -107,13 +108,14 @@ app_window& application_glue::make_window(ruisapp::window_parameters window_para // status bar and the navigation bar. ruis_native_window.get().set_fullscreen(fullscreen); - auto rendering_context = utki::make_shared(ruis_native_window); + auto rendering_factory = utki::make_shared(ruis_native_window); + auto rendering_context = utki::make_shared(ruis_native_window, rendering_factory); - auto common_render_objects = utki::make_shared(rendering_context); - auto common_shaders = rendering_context.get().make_shaders(); + auto common_render_objects = utki::make_shared(rendering_factory.get()); + auto common_shaders = rendering_factory.get().make_shaders(); auto ruis_resource_loader = utki::make_shared( - rendering_context, // + rendering_factory, // common_render_objects ); diff --git a/src/ruisapp/glue/ios/application.cxx b/src/ruisapp/glue/ios/application.cxx index 6dced284..6b311e95 100644 --- a/src/ruisapp/glue/ios/application.cxx +++ b/src/ruisapp/glue/ios/application.cxx @@ -85,13 +85,14 @@ app_window& application_glue::make_window(ruisapp::window_parameters window_para std::move(window_params) ); - auto rendering_context = utki::make_shared(ruis_native_window); + auto rendering_factory = utki::make_shared(ruis_native_window); + auto rendering_context = utki::make_shared(ruis_native_window, rendering_factory); - auto common_render_objects = utki::make_shared(rendering_context); - auto common_shaders = rendering_context.get().make_shaders(); + auto common_render_objects = utki::make_shared(rendering_factory.get()); + auto common_shaders = rendering_factory.get().make_shaders(); auto ruis_resource_loader = utki::make_shared( - rendering_context, // + rendering_factory, // common_render_objects ); diff --git a/src/ruisapp/glue/ios/glue.mm b/src/ruisapp/glue/ios/glue.mm index 4ed5c494..97d45633 100644 --- a/src/ruisapp/glue/ios/glue.mm +++ b/src/ruisapp/glue/ios/glue.mm @@ -32,6 +32,7 @@ #include #include +#include // include implementations #include "application.cxx" diff --git a/src/ruisapp/glue/linux/wayland/application.cxx b/src/ruisapp/glue/linux/wayland/application.cxx index ad0e4182..94ddab33 100644 --- a/src/ruisapp/glue/linux/wayland/application.cxx +++ b/src/ruisapp/glue/linux/wayland/application.cxx @@ -29,6 +29,8 @@ along with this program. If not, see . #elif defined(RUISAPP_RENDER_OPENGLES) # include +#elif defined(RUISAPP_RENDER_VULKAN) +# include #else # error "Unknown graphics API" #endif @@ -200,12 +202,49 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window { utki::logcat_debug("application_glue::make_window(): enter", '\n'); - auto ruis_native_window = utki::make_shared( +#ifdef RUISAPP_RENDER_VULKAN + auto ruis_native_window = utki::make_shared( + this->display, // + window_params + ); +#else + auto ruis_native_window = utki::make_shared( this->display, // this->gl_version, window_params, &this->shared_gl_context_native_window.get() ); +#endif + + // create the render context before the ruis::context so we can save a pointer + // to it without a static_cast later (needed for Vulkan swap_frame_buffers) +#ifdef RUISAPP_RENDER_VULKAN + auto render_context = [this](auto&& win_ref) -> utki::shared_ref { + auto wl_surf = win_ref.get().get_wl_surface(); + auto wl_disp = win_ref.get().get_wl_display(); + auto& vdev = this->device.get(); + VkWaylandSurfaceCreateInfoKHR sci{}; + sci.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; + sci.display = wl_disp; + sci.surface = wl_surf; + VkSurfaceKHR vk_surf = VK_NULL_HANDLE; + vkCreateWaylandSurfaceKHR(vdev.get_instance(), &sci, nullptr, &vk_surf); + auto sp = utki::make_shared(vdev, vk_surf); + return utki::make_shared(win_ref, sp, this->render_factory); + }(ruis_native_window); +#elif defined(RUISAPP_RENDER_OPENGL) + auto render_context = utki::make_shared( + ruis_native_window, // + this->render_factory + ); +#elif defined(RUISAPP_RENDER_OPENGLES) + auto render_context = utki::make_shared( + ruis_native_window, // + this->render_factory + ); +#else +# error "Unknown graphics API" +#endif auto ruis_context = utki::make_shared(ruis::context::parameters{ .post_to_ui_thread_function = @@ -214,13 +253,7 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window }, .updater = this->updater, .renderer = utki::make_shared( -#ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(ruis_native_window), -#elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(ruis_native_window), -#else -# error "Unknown graphics API" -#endif + std::move(render_context), this->common_shaders, this->common_render_objects ), @@ -263,6 +296,7 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window auto& ret_win = res.first->second.get(); +#if defined(RUISAPP_RENDER_OPENGL) || defined(RUISAPP_RENDER_OPENGLES) // EGL surface for the window is not created yet at this point. // In Wayland the EGL surface is created asynchronously. // Some further calls (e.g. set_vsync_enabled()) rely on the EGL surface to be created, @@ -278,6 +312,11 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window } utki::assert(ret_win.ruis_native_window.get().is_egl_surface_created(), SL); +#elif defined(RUISAPP_RENDER_VULKAN) + // A roundtrip ensures the compositor has processed the toplevel and the + // surface is mapped, so the Vulkan surface created from it is valid. + wl_display_roundtrip(this->display.get().wayland_display.display); +#endif return ret_win; } diff --git a/src/ruisapp/glue/linux/wayland/application.hxx b/src/ruisapp/glue/linux/wayland/application.hxx index 617df436..680d8f3d 100644 --- a/src/ruisapp/glue/linux/wayland/application.hxx +++ b/src/ruisapp/glue/linux/wayland/application.hxx @@ -30,7 +30,13 @@ along with this program. If not, see . #include "../../../window.hpp" #include "../../unix_common.hxx" -#include "window.hxx" +#ifdef RUISAPP_RENDER_VULKAN +# include "vulkan_window.hxx" +using native_window_type = vulkan_native_window; +#else +# include "opengles_window.hxx" +using native_window_type = opengles_native_window; +#endif namespace { class app_window : public ruisapp::window @@ -44,11 +50,11 @@ public: bool activated = false; } actual_state; - utki::shared_ref ruis_native_window; + utki::shared_ref ruis_native_window; app_window( utki::shared_ref ruis_context, // - utki::shared_ref ruis_native_window + utki::shared_ref ruis_native_window ) : ruisapp::window(std::move(ruis_context)), ruis_native_window(std::move(ruis_native_window)) @@ -100,6 +106,21 @@ private: } // namespace namespace { +#ifdef RUISAPP_RENDER_VULKAN +const utki::shared_ref make_device() +{ + std::vector instance_extensions = { + VK_KHR_SURFACE_EXTENSION_NAME, + VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME + }; + std::vector device_extensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; + return utki::make_shared( + instance_extensions, // + device_extensions // + ); +} +#endif + class application_glue : public utki::destructable { public: @@ -126,16 +147,28 @@ public: const utki::version_duplet gl_version; // TODO: make windowless shared egl context - const utki::shared_ref shared_gl_context_native_window; - const utki::shared_ref resource_loader_ruis_rendering_context; - const utki::shared_ref common_shaders; + const utki::shared_ref shared_gl_context_native_window; +#ifdef RUISAPP_RENDER_VULKAN + // The Vulkan device is shared between the factory (resource creation) and the windows (surface creation). + // Surface extensions are needed for creating Vulkan surfaces (one per window) for presenting frames. + const utki::shared_ref device; +#endif + // concrete factory type, #ifdef by renderer +#ifdef RUISAPP_RENDER_VULKAN + const utki::shared_ref render_factory; +#elif defined(RUISAPP_RENDER_OPENGL) + const utki::shared_ref render_factory; +#elif defined(RUISAPP_RENDER_OPENGLES) + const utki::shared_ref render_factory; +#endif + const utki::shared_ref common_shaders; const utki::shared_ref common_render_objects; const utki::shared_ref ruis_resource_loader; const utki::shared_ref ruis_style_provider; private: std::map< - native_window::window_id_type, // + native_window_type::window_id_type, // utki::shared_ref // > windows; @@ -148,7 +181,7 @@ public: return this->windows; } - native_window::window_id_type get_shared_gl_context_window_id() const noexcept + native_window_type::window_id_type get_shared_gl_context_window_id() const noexcept { return this->shared_gl_context_native_window.get().get_id(); } @@ -156,39 +189,62 @@ public: application_glue(const utki::version_duplet& gl_version) : waitable(this->display.get().wayland_display), gl_version(gl_version), - shared_gl_context_native_window( // - utki::make_shared( + shared_gl_context_native_window( + // create a 1x1 hidden window; for Vulkan it is not used by the factory, + // but the member is a shared_ref which cannot be null +#ifdef RUISAPP_RENDER_VULKAN + utki::make_shared( + this->display, // + ruisapp::window_parameters{ + .dims = {1, 1}, + .title = {}, + .fullscreen = false, + .taskbar = false + } + ) +#else + utki::make_shared( this->display, // this->gl_version, ruisapp::window_parameters{ .dims = {1, 1}, .title = {}, - .fullscreen = false - }, - nullptr // no shared gl context + .fullscreen = false, + .taskbar = false +}, + nullptr ) +#endif ), - resource_loader_ruis_rendering_context( -#ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(this->shared_gl_context_native_window) +#ifdef RUISAPP_RENDER_VULKAN + device(make_device()), +#endif + render_factory( +#ifdef RUISAPP_RENDER_VULKAN + // Vulkan has no "current context" — a null surface is sufficient for the factory (resource creation) + utki::make_shared( + utki::make_shared(this->device.get(), VK_NULL_HANDLE) + ) +#elif defined(RUISAPP_RENDER_OPENGL) + utki::make_shared(this->shared_gl_context_native_window) #elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(this->shared_gl_context_native_window) + utki::make_shared(this->shared_gl_context_native_window) #else # error "Unknown graphics API" #endif ), common_shaders( // [&]() { - utki::assert(this->resource_loader_ruis_rendering_context.to_shared_ptr(), SL); - return this->resource_loader_ruis_rendering_context.get().make_shaders(); + utki::assert(this->render_factory.to_shared_ptr(), SL); + return this->render_factory.get().make_shaders(); }() ), common_render_objects( // - utki::make_shared(this->resource_loader_ruis_rendering_context) + utki::make_shared(this->render_factory.get()) ), ruis_resource_loader( // utki::make_shared( - this->resource_loader_ruis_rendering_context, // + this->render_factory, // this->common_render_objects ) ), @@ -200,7 +256,7 @@ public: ruisapp::window& make_window(ruisapp::window_parameters window_params); void destroy_window(app_window& w); - app_window* get_window(native_window::window_id_type id) + app_window* get_window(native_window_type::window_id_type id) { auto i = this->windows.find(id); if (i == this->windows.end()) { diff --git a/src/ruisapp/glue/linux/wayland/glue.cxx b/src/ruisapp/glue/linux/wayland/glue.cxx index f6dacbc0..5806b15b 100644 --- a/src/ruisapp/glue/linux/wayland/glue.cxx +++ b/src/ruisapp/glue/linux/wayland/glue.cxx @@ -32,11 +32,19 @@ along with this program. If not, see . #ifdef RUISAPP_RENDER_OPENGL # include # include +# include + +#elif defined(RUISAPP_RENDER_VULKAN) +# include +# include +# include +# include #elif defined(RUISAPP_RENDER_OPENGLES) # include # include # include +# include #else # error "Unknown graphics API" diff --git a/src/ruisapp/glue/linux/wayland/opengles_window.hxx b/src/ruisapp/glue/linux/wayland/opengles_window.hxx new file mode 100644 index 00000000..9ddd6714 --- /dev/null +++ b/src/ruisapp/glue/linux/wayland/opengles_window.hxx @@ -0,0 +1,154 @@ +/* +ruisapp - ruis GUI adaptation layer + +Copyright (C) 2016-2025 Ivan Gagis + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +/* ================ LICENSE END ================ */ + +#pragma once + +#include // Wayland EGL MUST be included before EGL headers + +#include "../../egl_utils.hxx" + +#include "wayland_window.hxx" + +namespace { +// OpenGL ES-specific native window for Wayland. +class opengles_native_window : public wayland_window +{ + egl_config_wrapper egl_config; + egl_context_wrapper egl_context; + // An offscreen pbuffer surface used as a fallback for the shared GL context + // when no real window surface is available (e.g. during resource loading). + std::optional egl_dummy_surface; + std::optional egl_surface; + +public: + opengles_native_window( + utki::shared_ref display, + const utki::version_duplet& gl_version, + const ruisapp::window_parameters& window_params, + opengles_native_window* shared_gl_context_native_window + ) : + wayland_window( + std::move(display), // + window_params + ), + egl_config( + this->display.get().egl_display, // + gl_version, + window_params + ), + egl_context( + this->display.get().egl_display, // + gl_version, + this->egl_config, + shared_gl_context_native_window ? shared_gl_context_native_window->egl_context.context : EGL_NO_CONTEXT + ) + {} + + void create_egl_surface() + { + utki::assert(!this->is_egl_surface_created(), [](auto& o) { + o << "create_egl_surface() must not be called more than once"; + }); + + this->egl_surface.emplace( + this->display.get().egl_display, // + this->egl_config, + this->wayland_egl_window.window + ); + + // The rendering context was made current with EGL_NO_SURFACE in its constructor, + // before the surface existed. Now that the surface exists, re-bind the context to + // it, so that rendering (and the initial eglSwapBuffers) actually reaches the + // window's buffer. Without this, context::apply() would skip the bind (the context + // is already "current" on the context stack) and the swap would fail. + this->bind_rendering_context(); + } + + bool is_egl_surface_created() const noexcept + { + return this->egl_surface.has_value(); + } + + void swap_frame_buffers() override + { + if (this->egl_surface.has_value()) { + this->egl_surface.value().swap_frame_buffers(); + } + } + + void bind_rendering_context() override + { + auto& egl_display = this->display.get().egl_display; + + if (this->egl_surface.has_value()) { + if (eglMakeCurrent( + egl_display.display, + this->egl_surface.value().surface, + this->egl_surface.value().surface, + this->egl_context.context + ) == EGL_FALSE) + { + throw std::runtime_error("eglMakeCurrent() failed"); + } + } else { + if (egl_display.extensions.get(egl::extension::khr_surfaceless_context)) { + eglMakeCurrent( + egl_display.display, // + EGL_NO_SURFACE, + EGL_NO_SURFACE, + this->egl_context.context + ); + } else { + // KHR_surfaceless_context EGL extension is not available, create a dummy pbuffer surface to make the context current + if (!this->egl_dummy_surface.has_value()) { + this->egl_dummy_surface.emplace( + egl_display, // + this->egl_config + ); + } + eglMakeCurrent( + egl_display.display, // + this->egl_dummy_surface.value().surface, + this->egl_dummy_surface.value().surface, + this->egl_context.context + ); + } + } + } + + bool is_rendering_context_bound() const noexcept override + { + return eglGetCurrentContext() == this->egl_context.context; + } + + void set_vsync_enabled_internal(bool enabled) override + { + utki::assert( + [this]() { + return this->is_rendering_context_bound(); + }, + SL + ); + + this->egl_context.set_vsync_enabled(enabled); + } +}; +} // namespace diff --git a/src/ruisapp/glue/linux/wayland/vulkan_window.hxx b/src/ruisapp/glue/linux/wayland/vulkan_window.hxx new file mode 100644 index 00000000..811aeeb6 --- /dev/null +++ b/src/ruisapp/glue/linux/wayland/vulkan_window.hxx @@ -0,0 +1,65 @@ +/* +ruisapp - ruis GUI adaptation layer + +Copyright (C) 2016-2025 Ivan Gagis + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +/* ================ LICENSE END ================ */ + +#pragma once + +#include +#include + +#include "wayland_window.hxx" + +namespace { +// Vulkan-specific native window for Wayland. +class vulkan_native_window : public wayland_window +{ +public: + vulkan_native_window( + utki::shared_ref display, + const ruisapp::window_parameters& window_params + ) : + wayland_window( + std::move(display), // + window_params + ) + {} + + void bind_rendering_context() override + { + // For Vulkan, there's no concept of binding a rendering context. + // The Vulkan context is thread-safe and doesn't need to be made current. + } + + bool is_rendering_context_bound() const noexcept override + { + // For Vulkan, the context is always "bound" (thread-safe) + return true; + } + + void set_vsync_enabled_internal(bool enabled) override + { + (void)enabled; + // VSync is handled by the Vulkan present mode (a swapchain creation parameter, + // not a runtime setting). ensure_swapchain_valid() is called every frame and if + // it detects a change in is_vsync_enabled() it re-creates the swapchain with + // the actual vsync state. See ruis-render-vulkan/src/ruis/render/vulkan/context.cpp + } +}; +} // namespace diff --git a/src/ruisapp/glue/linux/wayland/window.hxx b/src/ruisapp/glue/linux/wayland/wayland_window.hxx similarity index 57% rename from src/ruisapp/glue/linux/wayland/window.hxx rename to src/ruisapp/glue/linux/wayland/wayland_window.hxx index fd353aa0..26a7b9aa 100644 --- a/src/ruisapp/glue/linux/wayland/window.hxx +++ b/src/ruisapp/glue/linux/wayland/wayland_window.hxx @@ -22,9 +22,6 @@ along with this program. If not, see . #pragma once #include -#include // Wayland EGL MUST be included before EGL headers - -#include "../../egl_utils.hxx" #include "display.hxx" #include "wayland_egl_window.hxx" @@ -33,31 +30,22 @@ along with this program. If not, see . #include "xdg_toplevel.hxx" namespace { -class native_window : public ruis::render::native_window +// Base class for the Wayland native window. Contains the common Wayland +// surface, xdg-toplevel, and cursor handling. The graphics-specific code +// (EGL or Vulkan) is in the derived leaf classes. +class wayland_window : public ruis::render::native_window { +protected: const utki::shared_ref display; - wayland_surface_wrapper wayland_surface; xdg_surface_wrapper xdg_surface; xdg_toplevel_wrapper xdg_toplevel; wayland_egl_window_wrapper wayland_egl_window; - - egl_config_wrapper egl_config; - egl_context_wrapper egl_context; - - std::optional egl_dummy_surface; - std::optional egl_surface; - wayland_surface_wrapper::scale_and_dpi scale_and_dpi; + ruis::mouse_cursor cur_mouse_cursor = ruis::mouse_cursor::arrow; + bool mouse_cursor_visible = true; public: - const unsigned sequence_number = []() { - static unsigned next_sequence_number = 0; - auto ret = next_sequence_number; - ++next_sequence_number; - return ret; - }(); - // keep track of current window dimensions for restoring them after fullscreen mode r4::vector2 cur_window_dims; @@ -67,12 +55,14 @@ public: using window_id_type = const wl_surface*; - native_window( - utki::shared_ref display, - const utki::version_duplet& gl_version, - const ruisapp::window_parameters& window_params, - native_window* shared_gl_context_native_window - ) : + const unsigned sequence_number = []() { + static unsigned next_sequence_number = 0; + auto ret = next_sequence_number; + ++next_sequence_number; + return ret; + }(); + + wayland_window(utki::shared_ref display, const ruisapp::window_parameters& window_params) : display(std::move(display)), wayland_surface(this->display.get().wayland_compositor), xdg_surface( @@ -88,21 +78,10 @@ public: this->wayland_surface, // window_params.dims ), - egl_config( - this->display.get().egl_display, // - gl_version, - window_params - ), - egl_context( - this->display.get().egl_display, // - gl_version, - this->egl_config, - shared_gl_context_native_window ? shared_gl_context_native_window->egl_context.context : EGL_NO_CONTEXT - ), cur_window_dims(window_params.dims) { utki::log_debug([](auto& o) { - o << "native_window constructed" << std::endl; + o << "wayland_window constructed" << std::endl; }); } @@ -123,74 +102,21 @@ public: return this->wayland_surface.surface; } - void create_egl_surface() - { - utki::assert(!this->is_egl_surface_created(), [](auto& o) { - o << "create_egl_surface() must not be called more than once"; - }); - - this->egl_surface.emplace( - this->display.get().egl_display, // - this->egl_config, - this->wayland_egl_window.window - ); - } - - bool is_egl_surface_created() const noexcept + // get the raw wl_surface pointer for Vulkan surface creation + wl_surface* get_wl_surface() const noexcept { - return this->egl_surface.has_value(); - } - - void swap_frame_buffers() override - { - if (this->egl_surface.has_value()) { - this->egl_surface.value().swap_frame_buffers(); - } + return this->wayland_surface.surface; } - void bind_rendering_context() override + // get the raw wl_display pointer for Vulkan surface creation + wl_display* get_wl_display() const noexcept { - auto& egl_display = this->display.get().egl_display; - - if (this->egl_surface.has_value()) { - if (eglMakeCurrent( - egl_display.display, - this->egl_surface.value().surface, - this->egl_surface.value().surface, - this->egl_context.context - ) == EGL_FALSE) - { - throw std::runtime_error("eglMakeCurrent() failed"); - } - } else { - if (egl_display.extensions.get(egl::extension::khr_surfaceless_context)) { - eglMakeCurrent( - egl_display.display, // - EGL_NO_SURFACE, - EGL_NO_SURFACE, - this->egl_context.context - ); - } else { - // KHR_surfaceless_context EGL extension is not available, create a dummy pbuffer surface to make the context current - if (!this->egl_dummy_surface.has_value()) { - this->egl_dummy_surface.emplace( - egl_display, // - this->egl_config - ); - } - eglMakeCurrent( - egl_display.display, // - this->egl_dummy_surface.value().surface, - this->egl_dummy_surface.value().surface, - this->egl_context.context - ); - } - } + return this->display.get().wayland_display.display; } - bool is_rendering_context_bound() const noexcept override + r4::vector2 get_dims() const noexcept override { - return eglGetCurrentContext() == this->egl_context.context; + return this->cur_window_dims * this->scale_and_dpi.scale; } void set_fullscreen_internal(bool enable) override @@ -209,11 +135,6 @@ public: } } -private: - ruis::mouse_cursor cur_mouse_cursor = ruis::mouse_cursor::arrow; - bool mouse_cursor_visible = true; - -public: void update_mouse_cursor() { auto& wayland_pointer = this->display.get().wayland_seat.wayland_pointer; @@ -237,18 +158,6 @@ public: this->update_mouse_cursor(); } - void set_vsync_enabled_internal(bool enabled) override - { - utki::assert( - [this]() { - return this->is_rendering_context_bound(); - }, - SL - ); - - this->egl_context.set_vsync_enabled(enabled); - } - wl_callback* make_frame_callback() { return wl_surface_frame(this->wayland_surface.surface); diff --git a/src/ruisapp/glue/linux/wayland/window.cxx b/src/ruisapp/glue/linux/wayland/window.cxx index 3b9cd205..a7f4d643 100644 --- a/src/ruisapp/glue/linux/wayland/window.cxx +++ b/src/ruisapp/glue/linux/wayland/window.cxx @@ -19,9 +19,9 @@ along with this program. If not, see . /* ================ LICENSE END ================ */ -#include "window.hxx" +#include "wayland_window.hxx" -void native_window::resize(const r4::vector2& dims) +void wayland_window::resize(const r4::vector2& dims) { utki::logcat_debug("native_window::resize(): dims = ", dims, '\n'); this->cur_window_dims = dims; diff --git a/src/ruisapp/glue/linux/wayland/xdg_surface.cxx b/src/ruisapp/glue/linux/wayland/xdg_surface.cxx index 71ee05cb..95c04f44 100644 --- a/src/ruisapp/glue/linux/wayland/xdg_surface.cxx +++ b/src/ruisapp/glue/linux/wayland/xdg_surface.cxx @@ -88,8 +88,9 @@ void xdg_surface_wrapper::xdg_surface_configure( } auto& win = *window; - auto& natwin = win.ruis_native_window.get(); +#if defined(RUISAPP_RENDER_OPENGL) || defined(RUISAPP_RENDER_OPENGLES) + auto& natwin = win.ruis_native_window.get(); // The configure event can come several times for the same xdg_surface // because we do several surface commits during the initial configuration, // and each commit can trigger a configure event. @@ -98,14 +99,15 @@ void xdg_surface_wrapper::xdg_surface_configure( if (!natwin.is_egl_surface_created()) { natwin.create_egl_surface(); } +#endif // After initial configure event we need to do the initial surface commit, // otherwise the surface will not be mapped to the screen. - // In case of EGL we have to call eglSwapBuffers(), which will do the surface commit for us. - // This makes the surface to be mapped to the screen. - // swap EGL frame buffers with the window's EGL context made current + // For EGL this calls eglSwapBuffers() which does the surface commit for us. + // For Vulkan this presents a frame (the compositor fires the frame callback + // only after compositing a surface that has a buffer). win.gui.context.get().ren().ctx().apply([&]() { - natwin.swap_frame_buffers(); + win.gui.context.get().ren().ctx().swap_frame_buffers(); }); // on some Wayland implementations just swapping EGL buffers is not enough and surface commit is needed diff --git a/src/ruisapp/glue/linux/xorg/display.hxx b/src/ruisapp/glue/linux/xorg/display.hxx index 0033907d..371df675 100644 --- a/src/ruisapp/glue/linux/xorg/display.hxx +++ b/src/ruisapp/glue/linux/xorg/display.hxx @@ -103,6 +103,12 @@ public: auto surf = gdk_surface_new_toplevel(disp); utki::assert(surf, SL); auto mon = gdk_display_get_monitor_at_surface(disp, surf); + if (!mon) { + // Fallback: use the first monitor + auto monitors = gdk_display_get_monitors(disp); + mon = GDK_MONITOR(g_list_model_get_item(monitors, 0)); + g_object_unref(monitors); + } utki::assert(mon, SL); int sf = gdk_monitor_get_scale_factor(mon); diff --git a/src/ruisapp/glue/linux/xorg/glue.cxx b/src/ruisapp/glue/linux/xorg/glue.cxx index c5240a30..c17db4bd 100644 --- a/src/ruisapp/glue/linux/xorg/glue.cxx +++ b/src/ruisapp/glue/linux/xorg/glue.cxx @@ -29,9 +29,19 @@ along with this program. If not, see . #ifdef RUISAPP_RENDER_OPENGL # include +# include #elif defined(RUISAPP_RENDER_OPENGLES) # include +# include + +#elif defined(RUISAPP_RENDER_VULKAN) +# include +# include +# include +# include +# include +# include #else # error "Unknown graphics API" @@ -43,22 +53,50 @@ along with this program. If not, see . #include "cursor.hxx" #include "display.hxx" #include "key_code_map.hxx" -#include "window.hxx" +#ifdef RUISAPP_RENDER_VULKAN +# include "vulkan_window.hxx" +#elif defined(RUISAPP_RENDER_OPENGL) +# include "opengl_window.hxx" +#elif defined(RUISAPP_RENDER_OPENGLES) +# include "opengles_window.hxx" +#endif using namespace std::string_literals; using namespace std::string_view_literals; using namespace ruisapp; +#ifdef RUISAPP_RENDER_VULKAN +using native_window_type = vulkan_native_window; +#elif defined(RUISAPP_RENDER_OPENGL) +using native_window_type = opengl_native_window; +#elif defined(RUISAPP_RENDER_OPENGLES) +using native_window_type = opengles_native_window; +#endif + +#ifdef RUISAPP_RENDER_VULKAN +namespace { +const utki::shared_ref make_device() +{ + std::vector instance_extensions = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XLIB_SURFACE_EXTENSION_NAME}; + std::vector device_extensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; + return utki::make_shared( + instance_extensions, // + device_extensions // + ); +} +} // namespace +#endif + namespace { class app_window : public ruisapp::window { public: - utki::shared_ref ruis_native_window; + utki::shared_ref ruis_native_window; app_window( utki::shared_ref ruis_context, // - utki::shared_ref ruis_native_window + utki::shared_ref ruis_native_window ) : ruisapp::window(std::move(ruis_context)), ruis_native_window(std::move(ruis_native_window)) @@ -84,11 +122,25 @@ class application_glue : public utki::destructable const utki::shared_ref display = utki::make_shared(); private: +#ifdef RUISAPP_RENDER_VULKAN + // The Vulkan device is shared between the factory (resource creation) and the windows (surface creation). + // Surface extensions are needed for creating Vulkan surfaces (one per window) for presenting frames. + const utki::shared_ref device; +#endif utki::version_duplet gl_version; - utki::shared_ref shared_gl_context_native_window; - utki::shared_ref resource_loader_ruis_rendering_context; - utki::shared_ref common_shaders; + utki::shared_ref shared_gl_context_native_window; + + // concrete factory type, #ifdef by renderer +#ifdef RUISAPP_RENDER_VULKAN + const utki::shared_ref render_factory; +#elif defined(RUISAPP_RENDER_OPENGL) + const utki::shared_ref render_factory; +#elif defined(RUISAPP_RENDER_OPENGLES) + const utki::shared_ref render_factory; +#endif + + const utki::shared_ref common_shaders; utki::shared_ref common_render_objects; utki::shared_ref ruis_resource_loader; @@ -97,7 +149,7 @@ class application_glue : public utki::destructable private: std::map< - native_window::window_id_type, // + native_window_type::window_id_type, // utki::shared_ref // > windows; @@ -111,40 +163,51 @@ class application_glue : public utki::destructable std::vector> windows_to_destroy; application_glue(const utki::version_duplet& gl_version) : +#ifdef RUISAPP_RENDER_VULKAN + device(make_device()), +#endif gl_version(gl_version), shared_gl_context_native_window( // - utki::make_shared( + utki::make_shared( this->display, // this->gl_version, ruisapp::window_parameters{ .dims = {1, 1}, .title = {}, - .fullscreen = false + .fullscreen = false, + .taskbar = false }, nullptr ) ), - resource_loader_ruis_rendering_context( -#ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(this->shared_gl_context_native_window) + // one shared render factory per application + render_factory( +#ifdef RUISAPP_RENDER_VULKAN + // Vulkan has no "current context" — all GPU resources live on the VkDevice and + // are inherently shareable. No surface is needed for the shared factory. + utki::make_shared( + utki::make_shared(this->device.get(), VK_NULL_HANDLE) + ) +#elif defined(RUISAPP_RENDER_OPENGL) + utki::make_shared(this->shared_gl_context_native_window) #elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(this->shared_gl_context_native_window) + utki::make_shared(this->shared_gl_context_native_window) #else # error "Unknown graphics API" #endif ), common_shaders( // [&]() { - utki::assert(this->resource_loader_ruis_rendering_context.to_shared_ptr(), SL); - return this->resource_loader_ruis_rendering_context.get().make_shaders(); + utki::assert(this->render_factory.to_shared_ptr(), SL); + return this->render_factory.get().make_shaders(); }() ), common_render_objects( // - utki::make_shared(this->resource_loader_ruis_rendering_context) + utki::make_shared(this->render_factory.get()) ), ruis_resource_loader( // utki::make_shared( - this->resource_loader_ruis_rendering_context, // + this->render_factory, // this->common_render_objects ) ), @@ -161,13 +224,48 @@ class application_glue : public utki::destructable app_window& make_window(ruisapp::window_parameters window_params) { - auto ruis_native_window = utki::make_shared( + auto ruis_native_window = utki::make_shared( this->display, // this->gl_version, window_params, &this->shared_gl_context_native_window.get() ); + // create the render context before the ruis::context so we can save a pointer + // to it without a static_cast later (needed for Vulkan swap_frame_buffers) +#ifdef RUISAPP_RENDER_VULKAN + auto win_surface = utki::make_shared(this->device.get(), [&]() { + VkXlibSurfaceCreateInfoKHR ci{}; + ci.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; + ci.dpy = this->display.get().xorg_display.display; + ci.window = ruis_native_window.get().get_id(); + VkSurfaceKHR surface = VK_NULL_HANDLE; + + ::ruis::render::vulkan::check_vk_result( + vkCreateXlibSurfaceKHR(this->device.get().get_instance(), &ci, nullptr, &surface), + "vkCreateXlibSurfaceKHR" + ); + return surface; + }()); + auto render_context = utki::make_shared( + ruis_native_window, // + std::move(win_surface), // + this->render_factory + ); +#elif defined(RUISAPP_RENDER_OPENGL) + auto render_context = utki::make_shared( + ruis_native_window, // + this->render_factory + ); +#elif defined(RUISAPP_RENDER_OPENGLES) + auto render_context = utki::make_shared( + ruis_native_window, // + this->render_factory + ); +#else +# error "Unknown graphics API" +#endif + auto ruis_context = utki::make_shared(ruis::context::parameters{ .post_to_ui_thread_function = [this](std::function proc) { @@ -175,13 +273,7 @@ class application_glue : public utki::destructable }, .updater = this->updater, .renderer = utki::make_shared( -#ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(ruis_native_window), -#elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(ruis_native_window), -#else -# error "Unknown graphics API" -#endif + std::move(render_context), this->common_shaders, this->common_render_objects ), @@ -213,6 +305,8 @@ class application_glue : public utki::destructable std::move(ruis_native_window) ); + auto& nw = ruisapp_window.get().ruis_native_window.get(); + ruisapp_window.get().gui.set_viewport( // ruis::rect( 0, // @@ -224,7 +318,7 @@ class application_glue : public utki::destructable auto res = this->windows.insert( // std::make_pair( - ruisapp_window.get().ruis_native_window.get().get_id(), // + nw.get_id(), // std::move(ruisapp_window) ) ); @@ -235,8 +329,11 @@ class application_glue : public utki::destructable void destroy_window(app_window& w) { - auto i = this->windows.find(w.ruis_native_window.get().get_id()); - utki::assert(i != this->windows.end(), SL); + auto id = w.ruis_native_window.get().get_id(); + auto i = this->windows.find(id); + if (i == this->windows.end()) { + return; + } // Defer actual window object destruction until next main loop cycle, // for that put the window to the list of windows to destroy. @@ -245,7 +342,7 @@ class application_glue : public utki::destructable this->windows.erase(i); } - app_window* get_window(native_window::window_id_type id) + app_window* get_window(native_window_type::window_id_type id) { auto i = this->windows.find(id); if (i == this->windows.end()) { @@ -323,13 +420,13 @@ ruis::mouse_button button_number_to_enum(unsigned number) class key_event_unicode_provider : public ruis::gui::input_string_provider { - const native_window& window; + const native_window_type& window; // NOLINTNEXTLINE(clang-analyzer-webkit.NoUncountedMemberChecker, "false-positive") XKeyEvent& event; public: key_event_unicode_provider( - const native_window& window, // + const native_window_type& window, // XKeyEvent& event ) : window(window), @@ -490,6 +587,7 @@ int main(int argc, const char** argv) w.new_win_dims.x() = ruis::real(event.xconfigure.width); w.new_win_dims.y() = ruis::real(event.xconfigure.height); break; + break; case KeyPress: { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) diff --git a/src/ruisapp/glue/linux/xorg/opengl_window.hxx b/src/ruisapp/glue/linux/xorg/opengl_window.hxx new file mode 100644 index 00000000..578a1d25 --- /dev/null +++ b/src/ruisapp/glue/linux/xorg/opengl_window.hxx @@ -0,0 +1,476 @@ +// this file is part of ruisapp application framework +// +// this file is licensed under the terms of the MIT license, which can be found in the LICENSE file +// +// SPDX-License-Identifier: MIT + +// OpenGL-specific native window implementation. +// The gl_visual_info base class holds the computed GLXFBConfig + X11 visual. It is +// inherited before xorg_window so that the base class can use the visual when +// creating the X11 window (base classes are initialized before members, so the +// visual cannot be a member of the derived class). + +#include +#include +#include + +#include "xorg_window.hxx" + +namespace { + +// Holds the computed GLXFBConfig + X11 visual. This is a base class of native_window +// (inherited before xorg_window) so that the visual is available when the +// xorg_window base creates the X11 window. +class gl_visual_info +{ +public: + GLXFBConfig fb_config; + XVisualInfo* const visual_info; + xorg_visual xvisual; + + gl_visual_info( + display_wrapper& display, // + const utki::version_duplet&, + const ruisapp::window_parameters& window_params + ) : + fb_config([&]() { + GLXFBConfig best_fb_config = nullptr; + std::vector visual_attribs; + visual_attribs.push_back(GLX_X_RENDERABLE); + visual_attribs.push_back(True); + visual_attribs.push_back(GLX_X_VISUAL_TYPE); + visual_attribs.push_back(GLX_TRUE_COLOR); + visual_attribs.push_back(GLX_DRAWABLE_TYPE); + visual_attribs.push_back(GLX_WINDOW_BIT); + visual_attribs.push_back(GLX_RENDER_TYPE); + visual_attribs.push_back(GLX_RGBA_BIT); + visual_attribs.push_back(GLX_DOUBLEBUFFER); + visual_attribs.push_back(True); + visual_attribs.push_back(GLX_RED_SIZE); + visual_attribs.push_back(utki::byte_bits); + visual_attribs.push_back(GLX_GREEN_SIZE); + visual_attribs.push_back(utki::byte_bits); + visual_attribs.push_back(GLX_BLUE_SIZE); + visual_attribs.push_back(utki::byte_bits); + visual_attribs.push_back(GLX_ALPHA_SIZE); + visual_attribs.push_back(utki::byte_bits); + + if (window_params.buffers.get(ruisapp::buffer::depth)) { + visual_attribs.push_back(GLX_DEPTH_SIZE); + visual_attribs.push_back(utki::byte_bits * 3); // 24 bits per pixel for depth buffer + } + if (window_params.buffers.get(ruisapp::buffer::stencil)) { + visual_attribs.push_back(GLX_STENCIL_SIZE); + visual_attribs.push_back(utki::byte_bits); + } + + visual_attribs.push_back(None); + + utki::span fb_configs = [&]() { + int fbcount = 0; + GLXFBConfig* fb_configs = glXChooseFBConfig( + display.xorg_display.display, + display.xorg_display.get_default_screen(), + visual_attribs.data(), + &fbcount + ); + if (!fb_configs) { + throw std::runtime_error("glXChooseFBConfig() returned empty list"); + } + return utki::make_span(fb_configs, fbcount); + }(); + + utki::scope_exit scope_exit_fbc([&fb_configs]() { + // NOLINTNEXTLINE(bugprone-multi-level-implicit-pointer-conversion) + XFree(fb_configs.data()); + }); + + GLXFBConfig worst_fb_config = nullptr; + int best_num_samp = -1; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) + int worst_num_samp = 999; + + for (auto fb_config : fb_configs) { + XVisualInfo* vi = glXGetVisualFromFBConfig( + display.xorg_display.display, // + fb_config + ); + if (!vi) { + continue; + } + + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + int samp_buf; + glXGetFBConfigAttrib( + display.xorg_display.display, // + fb_config, + GLX_SAMPLE_BUFFERS, + &samp_buf + ); + + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + int samples; + glXGetFBConfigAttrib( + display.xorg_display.display, // + fb_config, + GLX_SAMPLES, + &samples + ); + + if (!best_fb_config || (samp_buf && samples > best_num_samp)) { + best_fb_config = fb_config; + best_num_samp = samples; + } + if (!worst_fb_config || !samp_buf || samples < worst_num_samp) { + worst_fb_config = fb_config; + worst_num_samp = samples; + } + + XFree(vi); + } + + utki::assert(best_fb_config, SL); + return best_fb_config; + }()), + visual_info([&]() { + auto visual_info = glXGetVisualFromFBConfig( + display.xorg_display.display, // + this->fb_config + ); + if (!visual_info) { + throw std::runtime_error("glXGetVisualFromFBConfig() failed"); + } + return visual_info; + }()), + xvisual([this]() { + return xorg_visual{ + .visual = this->visual_info->visual, // + .depth = unsigned(this->visual_info->depth) + }; + }()) + {} + + gl_visual_info(const gl_visual_info&) = delete; + gl_visual_info& operator=(const gl_visual_info&) = delete; + + gl_visual_info(gl_visual_info&&) = delete; + gl_visual_info& operator=(gl_visual_info&&) = delete; + + ~gl_visual_info() + { + XFree(this->visual_info); + } +}; + +// Creates the GLX context +struct glx_context_wrapper { + display_wrapper& display; + + enum class glx_extension { + glx_arb_create_context, + glx_ext_swap_control, + glx_mesa_swap_control, + + enum_size + }; + + // glXGetProcAddressARB() will return non-null pointer even if extension is + // not supported, so we need to explicitly check for supported extensions. + // SOURCE: + // https://dri.freedesktop.org/wiki/glXGetProcAddressNeverReturnsNULL/ + const utki::flags supported_extensions; + + const GLXContext context; + + glx_context_wrapper( + display_wrapper& display, // + XVisualInfo* visual_info, + const utki::version_duplet& gl_version, + GLXFBConfig fb_config, + GLXContext shared_glx_context + ) : + display(display), + supported_extensions([&]() { + utki::flags supported = false; + + auto glx_extensions_string = std::string_view(glXQueryExtensionsString( + this->display.xorg_display.display, // + visual_info->screen + )); + utki::log_debug([&](auto& o) { + o << "glx_extensions_string = " << glx_extensions_string << std::endl; + }); + + auto glx_extensions = utki::split(glx_extensions_string); + + using namespace std::string_view_literals; + + if (std::ranges::find( + glx_extensions, // + "GLX_ARB_create_context"sv + ) != glx_extensions.end()) + { + supported.set(glx_extension::glx_arb_create_context); + } + + if (std::ranges::find( + glx_extensions, // + "GLX_EXT_swap_control"sv + ) != glx_extensions.end()) + { + supported.set(glx_extension::glx_ext_swap_control); + } + + if (std::ranges::find( // + glx_extensions, + "GLX_MESA_swap_control"sv + ) != glx_extensions.end()) + { + supported.set(glx_extension::glx_mesa_swap_control); + } + + return supported; + }()), + context([&]() { + GLXContext gl_context = nullptr; + + if (this->supported_extensions.get(glx_extension::glx_arb_create_context)) { + // GLX_ARB_create_context is supported + + // NOTE: glXGetProcAddressARB() is guaranteed to be present in all GLX + // versions. + // glXGetProcAddress() is not guaranteed. + // SOURCE: + // https://dri.freedesktop.org/wiki/glXGetProcAddressNeverReturnsNULL/ + + auto glx_create_context_attribs_arb = PFNGLXCREATECONTEXTATTRIBSARBPROC(glXGetProcAddressARB( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast("glXCreateContextAttribsARB") + )); + + if (!glx_create_context_attribs_arb) { + throw std::runtime_error("glXCreateContextAttribsARB() not found"); + } + + auto graphics_api_version = [&ver = gl_version]() { + if (ver.to_uint32_t() == 0) { + // default OpenGL version is 2.0 + return utki::version_duplet{ + .major = 2, // + .minor = 0 + }; + } + if (ver.major < 2) { + throw std::invalid_argument( + utki::cat("minimal supported OpenGL version is 2.0, requested: ", ver) + ); + } + return ver; + }(); + + static const std::array context_attribs = { + GLX_CONTEXT_MAJOR_VERSION_ARB, + graphics_api_version.major, + GLX_CONTEXT_MINOR_VERSION_ARB, + graphics_api_version.minor, + GLX_CONTEXT_PROFILE_MASK_ARB, + // we don't need compatibility context + GLX_CONTEXT_CORE_PROFILE_BIT_ARB, + None + }; + + gl_context = glx_create_context_attribs_arb( + this->display.xorg_display.display, // + fb_config, + shared_glx_context, + GL_TRUE, + context_attribs.data() + ); + } else { + // GLX_ARB_create_context is not supported + gl_context = glXCreateContext( + this->display.xorg_display.display, // + visual_info, + shared_glx_context, + GL_TRUE + ); + } + + // sync to ensure any errors generated are processed + XSync( + this->display.xorg_display.display, // + False + ); + + if (gl_context == nullptr) { + throw std::runtime_error("glXCreateContext() failed"); + } + + return gl_context; + }()) + {} + + glx_context_wrapper(const glx_context_wrapper&) = delete; + glx_context_wrapper& operator=(const glx_context_wrapper&) = delete; + + glx_context_wrapper(glx_context_wrapper&&) = delete; + glx_context_wrapper& operator=(glx_context_wrapper&&) = delete; + + ~glx_context_wrapper() + { + if (glXGetCurrentContext() == this->context) { + glXMakeCurrent( + this->display.xorg_display.display, // + None, + nullptr + ); + } + glXDestroyContext( + this->display.xorg_display.display, // + this->context + ); + } +}; + +class opengl_native_window : public gl_visual_info, public xorg_window +{ +public: + opengl_native_window( + utki::shared_ref display, // + const utki::version_duplet& gl_version, + const ruisapp::window_parameters& window_params, + opengl_native_window* shared_gl_context_native_window + ) : + gl_visual_info( + display.get(), // + gl_version, + window_params + ), + xorg_window( + display, // + window_params, + shared_gl_context_native_window, + this->xvisual + ), + glx_context( + this->display.get(), // + this->visual_info, + gl_version, + this->fb_config, + shared_gl_context_native_window ? shared_gl_context_native_window->glx_context.context : nullptr + ) + { + // if there is no any GL context current, then set this one before calling glewInit() + if (glXGetCurrentContext() == nullptr) { + this->bind_rendering_context(); + } + if (glewInit() != GLEW_OK) { + throw std::runtime_error("GLEW initialization failed"); + } + } + + opengl_native_window(const opengl_native_window&) = delete; + opengl_native_window& operator=(const opengl_native_window&) = delete; + + opengl_native_window(opengl_native_window&&) = delete; + opengl_native_window& operator=(opengl_native_window&&) = delete; + + ~opengl_native_window() override = default; + + void bind_rendering_context() override + { + glXMakeCurrent( + this->display.get().xorg_display.display, // + this->window.window, + this->glx_context.context + ); + } + + bool is_rendering_context_bound() const noexcept override + { + return glXGetCurrentContext() == this->glx_context.context; + } + + void swap_frame_buffers() override + { + glXSwapBuffers( + this->display.get().xorg_display.display, // + this->window.window + ); + if (this->is_vsync_enabled()) { + // With glFinish() call here it works better when VSYNC is enabled. + // This is noticable when an app renders a mouse cursor itself, + // the cursor moves with less latency. + // For some reason, the effect is only present if calling the glFinish() + // right after swapping buffers, if calling it before swapping buffers, + // the effect is not present. + glFinish(); + } + } + + void set_vsync_enabled_internal(bool enable) override + { + utki::assert( + [this]() { + return this->is_rendering_context_bound(); + }, + SL + ); + + // disable v-sync via swap control extension + if (this->glx_context.supported_extensions.get(glx_context_wrapper::glx_extension::glx_ext_swap_control)) { + utki::log_debug([](auto& o) { + o << "GLX_EXT_swap_control is supported\n"; + }); + + auto glx_swap_interval_ext = PFNGLXSWAPINTERVALEXTPROC(glXGetProcAddressARB( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast("glXSwapIntervalEXT") + )); + + utki::assert(glx_swap_interval_ext, SL); + + // disable v-sync + glx_swap_interval_ext( + this->display.get().xorg_display.display, // + this->window.window, + enable ? 1 : 0 // swap interval in vsync frames + ); + } else if (this->glx_context.supported_extensions.get(glx_context_wrapper::glx_extension::glx_mesa_swap_control + )) + { + utki::log_debug([](auto& o) { + o << "GLX_MESA_swap_control is supported\n"; + }); + + auto glx_swap_interval_mesa = PFNGLXSWAPINTERVALMESAPROC(glXGetProcAddressARB( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast("glXSwapIntervalMESA") + )); + + utki::assert(glx_swap_interval_mesa, SL); + + // disable v-sync + if (glx_swap_interval_mesa( + enable ? 1 : 0 // swap interval in vsync frames + ) != 0) + { + utki::logcat("WARNING: glXSwapIntervalMESA(", enable, ") failed"); + } + } else { + std::cout << "none of GLX_EXT_swap_control, GLX_MESA_swap_control GLX " + << "extensions are supported. Not disabling v-sync." << std::endl; + } + + // sync to ensure any errors generated are processed + XSync( + this->display.get().xorg_display.display, // + False + ); + } + +private: + const glx_context_wrapper glx_context; +}; + +} // namespace diff --git a/src/ruisapp/glue/linux/xorg/opengles_window.hxx b/src/ruisapp/glue/linux/xorg/opengles_window.hxx new file mode 100644 index 00000000..497149d8 --- /dev/null +++ b/src/ruisapp/glue/linux/xorg/opengles_window.hxx @@ -0,0 +1,178 @@ +// this file is part of ruisapp application framework +// +// this file is licensed under the terms of the MIT license, which can be found in the LICENSE file +// +// SPDX-License-Identifier: MIT + +// OpenGL ES-specific native window implementation. +// The gl_visual_info base class holds the computed EGLConfig + X11 visual. It is +// inherited before xorg_window so that the base class can use the visual when +// creating the X11 window (base classes are initialized before members, so the +// visual cannot be a member of the derived class). + +#include +#include +#include + +#include "../../egl_utils.hxx" + +#include "xorg_window.hxx" + +namespace { + +// Holds the computed EGLConfig + X11 visual. This is a base class of native_window +// (inherited before xorg_window) so that the visual is available when the +// xorg_window base creates the X11 window. +class gl_visual_info +{ +public: + const egl_config_wrapper egl_config; + XVisualInfo* const visual_info; + xorg_visual xvisual; + + gl_visual_info( + display_wrapper& display, // + const utki::version_duplet& gl_version, + const ruisapp::window_parameters& window_params + ) : + egl_config( + display.egl_display, // + gl_version, + window_params + ), + visual_info([&]() { + EGLint vid = 0; + + if (!eglGetConfigAttrib( + display.egl_display.display, // + this->egl_config.config, + EGL_NATIVE_VISUAL_ID, + &vid + )) + { + throw std::runtime_error("eglGetConfigAttrib() failed"); + } + + int num_visuals = 0; + XVisualInfo vis_template; + vis_template.visualid = vid; + auto visual_info = XGetVisualInfo( + display.xorg_display.display, // + VisualIDMask, + &vis_template, + &num_visuals + ); + if (!visual_info) { + throw std::runtime_error("XGetVisualInfo() failed"); + } + return visual_info; + }()), + xvisual([this]() { + return xorg_visual{ + .visual = this->visual_info->visual, // + .depth = unsigned(this->visual_info->depth) + }; + }()) + {} + + gl_visual_info(const gl_visual_info&) = delete; + gl_visual_info& operator=(const gl_visual_info&) = delete; + + gl_visual_info(gl_visual_info&&) = delete; + gl_visual_info& operator=(gl_visual_info&&) = delete; + + ~gl_visual_info() + { + XFree(this->visual_info); + } +}; + +class opengles_native_window : public gl_visual_info, public xorg_window +{ +public: + opengles_native_window( + utki::shared_ref display, // + const utki::version_duplet& gl_version, + const ruisapp::window_parameters& window_params, + opengles_native_window* shared_gl_context_native_window + ) : + gl_visual_info( + display.get(), // + gl_version, + window_params + ), + xorg_window( + display, // + window_params, + shared_gl_context_native_window, + this->xvisual + ), + egl_surface( + this->display.get().egl_display, // + this->egl_config, + this->window.window + ), + egl_context( + this->display.get().egl_display, // + gl_version, + this->egl_config, + shared_gl_context_native_window ? shared_gl_context_native_window->egl_context.context : EGL_NO_CONTEXT + ) + {} + + opengles_native_window(const opengles_native_window&) = delete; + opengles_native_window& operator=(const opengles_native_window&) = delete; + + opengles_native_window(opengles_native_window&&) = delete; + opengles_native_window& operator=(opengles_native_window&&) = delete; + + ~opengles_native_window() override = default; + + void bind_rendering_context() override + { + if (eglMakeCurrent( + this->display.get().egl_display.display, + this->egl_surface.surface, + this->egl_surface.surface, + this->egl_context.context + ) == EGL_FALSE) + { + throw std::runtime_error("eglMakeCurrent() failed"); + } + } + + bool is_rendering_context_bound() const noexcept override + { + return eglGetCurrentContext() == this->egl_context.context; + } + + void swap_frame_buffers() override + { + this->egl_surface.swap_frame_buffers(); + } + + void set_vsync_enabled_internal(bool enable) override + { + utki::assert( + [this]() { + return this->is_rendering_context_bound(); + }, + SL + ); + + utki::logcat_debug("eglSwapInterval(", enable ? "true" : "false", ")\n"); + if (eglSwapInterval( + this->display.get().egl_display.display, // + enable ? 1 : 0 // swap interval in vsync frames + ) != EGL_TRUE) + { + utki::logcat("WARNING: eglSwapInterval(", enable, ") failed"); + } + } + +private: + egl_surface_wrapper egl_surface; + egl_context_wrapper egl_context; +}; + +} // namespace diff --git a/src/ruisapp/glue/linux/xorg/vulkan_window.hxx b/src/ruisapp/glue/linux/xorg/vulkan_window.hxx new file mode 100644 index 00000000..03911e6f --- /dev/null +++ b/src/ruisapp/glue/linux/xorg/vulkan_window.hxx @@ -0,0 +1,72 @@ +/* +ruisapp - ruis GUI adaptation layer + +Copyright (C) 2016-2025 Ivan Gagis + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +/* ================ LICENSE END ================ */ + +// The Vulkan native window. Inherits from xorg_window (the graphics-agnostic +// base) and adds the Vulkan-specific parts: the present callback. Unlike the +// OpenGL window it uses the default X11 visual (not an FBConfig-based one) and +// does not create any GL context. The Vulkan surface is created by the glue +// from the X11 window and the shared Vulkan instance. + +#include + +#include +#include + +#include "xorg_window.hxx" + +namespace { + +class vulkan_native_window : public xorg_window +{ +public: + vulkan_native_window( + utki::shared_ref display, // + const utki::version_duplet&, // the GL version is not used by Vulkan + const ruisapp::window_parameters& window_params, + vulkan_native_window* shared + ) : + xorg_window( + display, // + window_params, + shared, + xorg_visual{ + .visual = DefaultVisual( + display.get().xorg_display.display, // + display.get().xorg_display.get_default_screen() + ), + .depth = DefaultDepth( + display.get().xorg_display.display, // + display.get().xorg_display.get_default_screen() + ) + } + ) + {} + + vulkan_native_window(const vulkan_native_window&) = delete; + vulkan_native_window& operator=(const vulkan_native_window&) = delete; + + vulkan_native_window(vulkan_native_window&&) = delete; + vulkan_native_window& operator=(vulkan_native_window&&) = delete; + + ~vulkan_native_window() override = default; +}; + +} // namespace diff --git a/src/ruisapp/glue/linux/xorg/window.hxx b/src/ruisapp/glue/linux/xorg/window.hxx deleted file mode 100644 index 14e8848a..00000000 --- a/src/ruisapp/glue/linux/xorg/window.hxx +++ /dev/null @@ -1,977 +0,0 @@ -/* -ruisapp - ruis GUI adaptation layer - -Copyright (C) 2016-2025 Ivan Gagis - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -*/ - -/* ================ LICENSE END ================ */ - -#pragma once - -#include -#include - -#ifdef RUISAPP_RENDER_OPENGL -# include - -#elif defined(RUISAPP_RENDER_OPENGLES) -# include -# include "../../egl_utils.hxx" - -#else -# error "Unknown graphics API" -#endif - -#include "display.hxx" - -namespace { - -class native_window : public ruis::render::native_window -{ - utki::shared_ref display; - -#ifdef RUISAPP_RENDER_OPENGL - struct fb_config_wrapper { - GLXFBConfig config; - - fb_config_wrapper( - display_wrapper& display, // - const utki::version_duplet&, - const ruisapp::window_parameters& window_params - ) : - config([&]() { - GLXFBConfig best_fb_config = nullptr; - std::vector visual_attribs; - visual_attribs.push_back(GLX_X_RENDERABLE); - visual_attribs.push_back(True); - visual_attribs.push_back(GLX_X_VISUAL_TYPE); - visual_attribs.push_back(GLX_TRUE_COLOR); - visual_attribs.push_back(GLX_DRAWABLE_TYPE); - visual_attribs.push_back(GLX_WINDOW_BIT); - visual_attribs.push_back(GLX_RENDER_TYPE); - visual_attribs.push_back(GLX_RGBA_BIT); - visual_attribs.push_back(GLX_DOUBLEBUFFER); - visual_attribs.push_back(True); - visual_attribs.push_back(GLX_RED_SIZE); - visual_attribs.push_back(utki::byte_bits); - visual_attribs.push_back(GLX_GREEN_SIZE); - visual_attribs.push_back(utki::byte_bits); - visual_attribs.push_back(GLX_BLUE_SIZE); - visual_attribs.push_back(utki::byte_bits); - visual_attribs.push_back(GLX_ALPHA_SIZE); - visual_attribs.push_back(utki::byte_bits); - - if (window_params.buffers.get(ruisapp::buffer::depth)) { - visual_attribs.push_back(GLX_DEPTH_SIZE); - visual_attribs.push_back(utki::byte_bits * 3); // 24 bits per pixel for depth buffer - } - if (window_params.buffers.get(ruisapp::buffer::stencil)) { - visual_attribs.push_back(GLX_STENCIL_SIZE); - visual_attribs.push_back(utki::byte_bits); - } - - visual_attribs.push_back(None); - - utki::span fb_configs = [&]() { - int fbcount = 0; - GLXFBConfig* fb_configs = glXChooseFBConfig( - display.xorg_display.display, - display.xorg_display.get_default_screen(), - visual_attribs.data(), - &fbcount - ); - if (!fb_configs) { - throw std::runtime_error("glXChooseFBConfig() returned empty list"); - } - return utki::make_span(fb_configs, fbcount); - }(); - - utki::scope_exit scope_exit_fbc([&fb_configs]() { - // NOLINTNEXTLINE(bugprone-multi-level-implicit-pointer-conversion) - XFree(fb_configs.data()); - }); - - GLXFBConfig worst_fb_config = nullptr; - int best_num_samp = -1; - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - int worst_num_samp = 999; - - for (auto fb_config : fb_configs) { - XVisualInfo* vi = glXGetVisualFromFBConfig( - display.xorg_display.display, // - fb_config - ); - if (!vi) { - continue; - } - - // NOLINTNEXTLINE(cppcoreguidelines-init-variables) - int samp_buf; - glXGetFBConfigAttrib( - display.xorg_display.display, // - fb_config, - GLX_SAMPLE_BUFFERS, - &samp_buf - ); - - // NOLINTNEXTLINE(cppcoreguidelines-init-variables) - int samples; - glXGetFBConfigAttrib( - display.xorg_display.display, // - fb_config, - GLX_SAMPLES, - &samples - ); - - if (!best_fb_config || (samp_buf && samples > best_num_samp)) { - best_fb_config = fb_config; - best_num_samp = samples; - } - if (!worst_fb_config || !samp_buf || samples < worst_num_samp) { - worst_fb_config = fb_config; - worst_num_samp = samples; - } - - XFree(vi); - } - - utki::assert(best_fb_config, SL); - return best_fb_config; - }()) - {} - - fb_config_wrapper(const fb_config_wrapper&) = delete; - fb_config_wrapper& operator=(const fb_config_wrapper&) = delete; - - fb_config_wrapper(fb_config_wrapper&&) = delete; - fb_config_wrapper& operator=(fb_config_wrapper&&) = delete; - - // no need to free fb config - ~fb_config_wrapper() = default; - } fb_config; -#elif defined(RUISAPP_RENDER_OPENGLES) - using fb_config_wrapper = egl_config_wrapper; - fb_config_wrapper fb_config; -#endif - - struct xorg_visual_info_wrapper { - XVisualInfo* const visual_info; - - xorg_visual_info_wrapper( - display_wrapper& display, // - fb_config_wrapper& fb_config - ) : - visual_info([&]() { -#ifdef RUISAPP_RENDER_OPENGL - auto visual_info = glXGetVisualFromFBConfig( - display.xorg_display.display, // - fb_config.config - ); - if (!visual_info) { - throw std::runtime_error("glXGetVisualFromFBConfig() failed"); - } - return visual_info; -#elif defined(RUISAPP_RENDER_OPENGLES) - EGLint vid = 0; - - if (!eglGetConfigAttrib( - display.egl_display.display, // - fb_config.config, - EGL_NATIVE_VISUAL_ID, - &vid - )) - { - throw std::runtime_error("eglGetConfigAttrib() failed"); - } - - int num_visuals = 0; - XVisualInfo vis_template; - vis_template.visualid = vid; - auto visual_info = XGetVisualInfo( - display.xorg_display.display, // - VisualIDMask, - &vis_template, - &num_visuals - ); - if (!visual_info) { - throw std::runtime_error("XGetVisualInfo() failed"); - } - return visual_info; -#else -# error "Unknown graphics API" -#endif - }()) - {} - - xorg_visual_info_wrapper(const xorg_visual_info_wrapper&) = delete; - xorg_visual_info_wrapper& operator=(const xorg_visual_info_wrapper&) = delete; - - xorg_visual_info_wrapper(xorg_visual_info_wrapper&&) = delete; - xorg_visual_info_wrapper& operator=(xorg_visual_info_wrapper&&) = delete; - - ~xorg_visual_info_wrapper() - { - XFree(this->visual_info); - } - } xorg_visual_info; - - struct xorg_color_map_wrapper { - display_wrapper& display; - - const Colormap color_map; - - xorg_color_map_wrapper( - display_wrapper& display, // - xorg_visual_info_wrapper& visual_info - ) : - display(display), - color_map([&]() { - auto cm = XCreateColormap( - this->display.xorg_display.display, - this->display.xorg_display.get_root_window(visual_info.visual_info->screen), - visual_info.visual_info->visual, - AllocNone - ); - if (cm == None) { - // TODO: use XSetErrorHandler() to get error code - throw std::runtime_error("XCreateColormap(): failed"); - } - return cm; - }()) - {} - - xorg_color_map_wrapper(const xorg_color_map_wrapper&) = delete; - xorg_color_map_wrapper& operator=(const xorg_color_map_wrapper&) = delete; - - xorg_color_map_wrapper(xorg_color_map_wrapper&&) = delete; - xorg_color_map_wrapper& operator=(xorg_color_map_wrapper&&) = delete; - - ~xorg_color_map_wrapper() - { - XFreeColormap( - display.xorg_display.display, // - this->color_map - ); - } - } xorg_color_map; - - struct xorg_window_wrapper { - display_wrapper& display; - - const ::Window window; - - xorg_window_wrapper( - display_wrapper& display, // - const ruisapp::window_parameters& window_params, - xorg_color_map_wrapper& color_map, - xorg_visual_info_wrapper& visual_info, - bool visible - ) : - display(display), - window([&]() { - XSetWindowAttributes attr; - attr.colormap = color_map.color_map; - attr.border_pixel = 0; - attr.background_pixmap = None; - attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | - PointerMotionMask | ButtonMotionMask | StructureNotifyMask | EnterWindowMask | LeaveWindowMask; - unsigned long fields = CWBorderPixel | CWColormap | CWEventMask | CWBackPixmap; - - auto dims = (this->display.scale_factor * window_params.dims.to()).to(); - - auto w = XCreateWindow( - this->display.xorg_display.display, - this->display.xorg_display.get_root_window(visual_info.visual_info->screen), // parent window - 0, // x position - 0, // y position - dims.x(), // width - dims.y(), // height - 0, // border width - visual_info.visual_info->depth, // window's depth - InputOutput, // window's class - visual_info.visual_info->visual, - fields, // defined attributes - &attr - ); - if (!w) { - throw std::runtime_error("Failed to create window"); - } - return w; - }()) - { - { // we want to handle WM_DELETE_WINDOW event to know when window is closed - Atom a = XInternAtom( - this->display.xorg_display.display, // - "WM_DELETE_WINDOW", - True - ); - XSetWMProtocols( - this->display.xorg_display.display, // - this->window, - &a, - 1 - ); - } - - if (!window_params.taskbar) { - Atom wm_state = XInternAtom( - this->display.xorg_display.display, // - "_NET_WM_STATE", - False - ); - Atom skip_taskbar = XInternAtom( - this->display.xorg_display.display, // - "_NET_WM_STATE_SKIP_TASKBAR", - False - ); - - static_assert(sizeof(skip_taskbar) >= 4, "Atom must be of at least 32-bit size"); - XChangeProperty( - this->display.xorg_display.display, // - this->window, - wm_state, - XA_ATOM, // type of data - 4 * utki::byte_bits, // data is a list of 32-bit values - PropModeReplace, - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast, "using C API") - reinterpret_cast(&skip_taskbar), // data - 1 // only one value in the data - ); - } - - if (visible) { - XMapWindow( - this->display.xorg_display.display, // - this->window - ); - } - - this->display.xorg_display.flush(); - - if (!window_params.title.empty()) { - XStoreName( - this->display.xorg_display.display, // - this->window, - window_params.title.c_str() - ); - } - } - - xorg_window_wrapper(const xorg_window_wrapper&) = delete; - xorg_window_wrapper& operator=(const xorg_window_wrapper&) = delete; - - xorg_window_wrapper(xorg_window_wrapper&&) = delete; - xorg_window_wrapper& operator=(xorg_window_wrapper&&) = delete; - - ~xorg_window_wrapper() - { - XDestroyWindow( - this->display.xorg_display.display, // - this->window - ); - } - } xorg_window; - -#ifdef RUISAPP_RENDER_OPENGL - struct glx_context_wrapper { - display_wrapper& display; - - enum class glx_extension { - glx_arb_create_context, - glx_ext_swap_control, - glx_mesa_swap_control, - - enum_size - }; - - // glXGetProcAddressARB() will return non-null pointer even if extension is - // not supported, so we need to explicitly check for supported extensions. - // SOURCE: - // https://dri.freedesktop.org/wiki/glXGetProcAddressNeverReturnsNULL/ - const utki::flags supported_extensions; - - const GLXContext context; - - glx_context_wrapper( - display_wrapper& display, // - const xorg_visual_info_wrapper& visual_info, - const utki::version_duplet& gl_version, - const fb_config_wrapper& fb_config, - native_window* shared_gl_context_native_window - ) : - display(display), - supported_extensions([&]() { - utki::flags supported = false; - - auto glx_extensions_string = std::string_view(glXQueryExtensionsString( - this->display.xorg_display.display, // - visual_info.visual_info->screen - )); - utki::log_debug([&](auto& o) { - o << "glx_extensions_string = " << glx_extensions_string << std::endl; - }); - - auto glx_extensions = utki::split(glx_extensions_string); - - using namespace std::string_view_literals; - - if (std::ranges::find( - glx_extensions, // - "GLX_ARB_create_context"sv - ) != glx_extensions.end()) - { - supported.set(glx_extension::glx_arb_create_context); - } - - if (std::ranges::find( - glx_extensions, // - "GLX_EXT_swap_control"sv - ) != glx_extensions.end()) - { - supported.set(glx_extension::glx_ext_swap_control); - } - - if (std::ranges::find( // - glx_extensions, - "GLX_MESA_swap_control"sv - ) != glx_extensions.end()) - { - supported.set(glx_extension::glx_mesa_swap_control); - } - - return supported; - }()), - context([&]() { - GLXContext gl_context = nullptr; - - GLXContext shared_glx_context = [&]() -> GLXContext { - if (shared_gl_context_native_window) { - return shared_gl_context_native_window->glx_context.context; - } - return nullptr; - }(); - - if (this->supported_extensions.get(glx_extension::glx_arb_create_context)) { - // GLX_ARB_create_context is supported - - // NOTE: glXGetProcAddressARB() is guaranteed to be present in all GLX - // versions. - // glXGetProcAddress() is not guaranteed. - // SOURCE: - // https://dri.freedesktop.org/wiki/glXGetProcAddressNeverReturnsNULL/ - - auto glx_create_context_attribs_arb = PFNGLXCREATECONTEXTATTRIBSARBPROC(glXGetProcAddressARB( - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast("glXCreateContextAttribsARB") - )); - - if (!glx_create_context_attribs_arb) { - // this should not happen since we checked extension presence, and - // anyway, glXGetProcAddressARB() never returns nullptr according to - // https://dri.freedesktop.org/wiki/glXGetProcAddressNeverReturnsNULL/ - // so, this check for null is just in case future version of GLX may - // return null - throw std::runtime_error("glXCreateContextAttribsARB() not found"); - } - - auto graphics_api_version = [&ver = gl_version]() { - if (ver.to_uint32_t() == 0) { - // default OpenGL version is 2.0 - return utki::version_duplet{ - .major = 2, // - .minor = 0 - }; - } - if (ver.major < 2) { - throw std::invalid_argument( - utki::cat("minimal supported OpenGL version is 2.0, requested: ", ver) - ); - } - return ver; - }(); - - static const std::array context_attribs = { - GLX_CONTEXT_MAJOR_VERSION_ARB, - graphics_api_version.major, - GLX_CONTEXT_MINOR_VERSION_ARB, - graphics_api_version.minor, - GLX_CONTEXT_PROFILE_MASK_ARB, - // we don't need compatibility context - GLX_CONTEXT_CORE_PROFILE_BIT_ARB, - None - }; - - gl_context = glx_create_context_attribs_arb( - this->display.xorg_display.display, // - fb_config.config, - shared_glx_context, - GL_TRUE, - context_attribs.data() - ); - } else { - // GLX_ARB_create_context is not supported - gl_context = glXCreateContext( - this->display.xorg_display.display, // - visual_info.visual_info, - shared_glx_context, - GL_TRUE - ); - } - - // sync to ensure any errors generated are processed - XSync( - this->display.xorg_display.display, // - False - ); - - if (gl_context == nullptr) { - throw std::runtime_error("glXCreateContext() failed"); - } - - return gl_context; - }()) - {} - - glx_context_wrapper(const glx_context_wrapper&) = delete; - glx_context_wrapper& operator=(const glx_context_wrapper&) = delete; - - glx_context_wrapper(glx_context_wrapper&&) = delete; - glx_context_wrapper& operator=(glx_context_wrapper&&) = delete; - - ~glx_context_wrapper() - { - if (glXGetCurrentContext() == this->context) { - glXMakeCurrent( - this->display.xorg_display.display, // - None, - nullptr - ); - } - glXDestroyContext( - this->display.xorg_display.display, // - this->context - ); - } - } glx_context; - -#elif defined(RUISAPP_RENDER_OPENGLES) - egl_surface_wrapper egl_surface; - egl_context_wrapper egl_context; -#endif - - struct xorg_input_context_wrapper { - const XIC input_context; - - xorg_input_context_wrapper( - const display_wrapper& display, // - const xorg_window_wrapper& window - ) : - input_context([&]() { - auto ic = - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg, "using C API") - XCreateIC( - display.xorg_input_method.xim, - XNClientWindow, - window.window, - XNFocusWindow, - window.window, - XNInputStyle, - XIMPreeditNothing | XIMStatusNothing, - nullptr - ); - if (ic == nullptr) { - throw std::runtime_error("XCreateIC() failed"); - } - return ic; - }()) - {} - - xorg_input_context_wrapper(const xorg_input_context_wrapper&) = delete; - xorg_input_context_wrapper& operator=(const xorg_input_context_wrapper&) = delete; - - xorg_input_context_wrapper(xorg_input_context_wrapper&&) = delete; - xorg_input_context_wrapper& operator=(xorg_input_context_wrapper&&) = delete; - - ~xorg_input_context_wrapper() - { - XUnsetICFocus(this->input_context); - XDestroyIC(this->input_context); - } - } xorg_input_context; - -public: - native_window( - utki::shared_ref display, // - const utki::version_duplet& gl_version, - const ruisapp::window_parameters& window_params, - native_window* shared_gl_context_native_window - ) : - display(std::move(display)), - fb_config( -#ifdef RUISAPP_RENDER_OPENGL - this->display, -#elif defined(RUISAPP_RENDER_OPENGLES) - this->display.get().egl_display, -#endif - gl_version, - window_params - ), - xorg_visual_info( - this->display, // - this->fb_config - ), - xorg_color_map( - this->display, // - this->xorg_visual_info - ), - xorg_window( - this->display, // - window_params, - this->xorg_color_map, - this->xorg_visual_info, - shared_gl_context_native_window != nullptr - ), -#ifdef RUISAPP_RENDER_OPENGL - glx_context( - this->display, // - this->xorg_visual_info, - gl_version, - this->fb_config, - shared_gl_context_native_window - ), -#elif defined(RUISAPP_RENDER_OPENGLES) - egl_surface( - this->display.get().egl_display, // - this->fb_config, - this->xorg_window.window - ), - egl_context( - this->display.get().egl_display, // - gl_version, - this->fb_config, - shared_gl_context_native_window ? shared_gl_context_native_window->egl_context.context : EGL_NO_CONTEXT - ), -#endif - xorg_input_context( - this->display, // - this->xorg_window - ) - { -#ifdef RUISAPP_RENDER_OPENGL - // if there is no any GL context current, then set this one before calling glewInit() - if (glXGetCurrentContext() == nullptr) { - this->bind_rendering_context(); - } - if (glewInit() != GLEW_OK) { - throw std::runtime_error("GLEW initialization failed"); - } -#endif - } - - native_window(const native_window&) = delete; - native_window& operator=(const native_window&) = delete; - - native_window(native_window&&) = delete; - native_window& operator=(native_window&&) = delete; - - ~native_window() override = default; - - void set_vsync_enabled_internal(bool enable) override - { - utki::assert( - [this]() { - return this->is_rendering_context_bound(); - }, - SL - ); - -#ifdef RUISAPP_RENDER_OPENGL - // disable v-sync via swap control extension - if (this->glx_context.supported_extensions.get(glx_context_wrapper::glx_extension::glx_ext_swap_control)) { - utki::log_debug([](auto& o) { - o << "GLX_EXT_swap_control is supported\n"; - }); - - auto glx_swap_interval_ext = PFNGLXSWAPINTERVALEXTPROC(glXGetProcAddressARB( - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast("glXSwapIntervalEXT") - )); - - utki::assert(glx_swap_interval_ext, SL); - - // disable v-sync - glx_swap_interval_ext( - this->display.get().xorg_display.display, // - this->xorg_window.window, - enable ? 1 : 0 // swap interval in vsync frames - ); - } else if (this->glx_context.supported_extensions.get(glx_context_wrapper::glx_extension::glx_mesa_swap_control - )) - { - utki::log_debug([](auto& o) { - o << "GLX_MESA_swap_control is supported\n"; - }); - - auto glx_swap_interval_mesa = PFNGLXSWAPINTERVALMESAPROC(glXGetProcAddressARB( - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast("glXSwapIntervalMESA") - )); - - utki::assert(glx_swap_interval_mesa, SL); - - // disable v-sync - if (glx_swap_interval_mesa( - enable ? 1 : 0 // swap interval in vsync frames - ) != 0) - { - utki::logcat("WARNING: glXSwapIntervalMESA(", enable, ") failed"); - } - } else { - std::cout << "none of GLX_EXT_swap_control, GLX_MESA_swap_control GLX " - << "extensions are supported. Not disabling v-sync." << std::endl; - } - - // sync to ensure any errors generated are processed - XSync( - this->display.get().xorg_display.display, // - False - ); -#elif defined(RUISAPP_RENDER_OPENGLES) - utki::logcat_debug("eglSwapInterval(", enable ? "true" : "false", ")\n"); - if (eglSwapInterval( - this->display.get().egl_display.display, // - enable ? 1 : 0 // swap interval in vsync frames - ) != EGL_TRUE) - { - utki::logcat("WARNING: eglSwapInterval(", enable, ") failed"); - } -#endif - } - - void swap_frame_buffers() override - { -#ifdef RUISAPP_RENDER_OPENGL - glXSwapBuffers( - this->display.get().xorg_display.display, // - this->xorg_window.window - ); - if (this->is_vsync_enabled()) { - // With glFinish() call here it works better when VSYNC is enabled. - // This is noticable when an app renders a mouse cursor itself, - // the cursor moves with less latency. - // For some reason, the effect is only present if calling the glFinish() - // right after swapping buffers, if calling it before swapping buffers, - // the effect is not present. - glFinish(); - } -#elif defined(RUISAPP_RENDER_OPENGLES) - this->egl_surface.swap_frame_buffers(); -#else -# error "Unknown graphics API" -#endif - } - - static_assert(std::is_integral_v<::Window>, "xorg lib's Window type is unexpectedly not integral"); - using window_id_type = ::Window; - - window_id_type get_id() const noexcept - { - return this->xorg_window.window; - } - - void set_fullscreen_internal(bool enable) override - { - Atom state_atom = XInternAtom( - this->display.get().xorg_display.display, // - "_NET_WM_STATE", - False - ); - Atom atom = XInternAtom( - this->display.get().xorg_display.display, // - "_NET_WM_STATE_FULLSCREEN", - False - ); - - XEvent event; - event.xclient.type = ClientMessage; - event.xclient.serial = 0; - event.xclient.send_event = True; - event.xclient.window = this->xorg_window.window; - event.xclient.message_type = state_atom; - - // data should be viewed as list of longs - event.xclient.format = utki::byte_bits * 4; - - // use union from third-party code - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) - event.xclient.data.l[0] = enable ? 1 : 0; - - // use union from third-party code - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) - event.xclient.data.l[1] = long(atom); - - // use union from third-party code - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) - event.xclient.data.l[2] = 0; - - XSendEvent( - this->display.get().xorg_display.display, // - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast, cppcoreguidelines-pro-bounds-pointer-arithmetic) - this->display.get().xorg_display.get_default_root_window(), - False, - SubstructureRedirectMask | SubstructureNotifyMask, - &event - ); - - this->display.get().xorg_display.flush(); - } - - void set_mouse_cursor(ruis::mouse_cursor c) override - { - this->cur_cursor = &this->display.get().get_cursor(c); - - if (this->cursor_visible) { - this->apply_cursor(*this->cur_cursor); - } - } - - void set_mouse_cursor_visible(bool visible) override - { - this->cursor_visible = visible; - if (visible) { - if (this->cur_cursor) { - this->apply_cursor(*this->cur_cursor); - } else { - XUndefineCursor( - this->display.get().xorg_display.display, // - this->xorg_window.window - ); - } - } else { - this->apply_cursor(this->display.get().get_cursor(ruis::mouse_cursor::none)); - } - } - - std::u32string get_string(XKeyEvent& event) const - { -#ifndef X_HAVE_UTF8_STRING -# error "no Xutf8stringlookup()" -#endif - constexpr auto static_buf_size = 32; - - // the array is used to get data, so no need to initialize it - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) - std::array static_buf; - - std::vector arr; - auto buf = utki::make_span(static_buf); - - // the variable is initialized via output argument, so no need to initialize - // it here NOLINTNEXTLINE(cppcoreguidelines-init-variables) - Status status; - - int size = Xutf8LookupString( - this->xorg_input_context.input_context, // - &event, - buf.data(), - int(buf.size() - 1), - nullptr, - &status - ); - if (status == XBufferOverflow) { - // allocate enough memory - arr.resize(size + 1); - buf = utki::make_span(arr); - size = Xutf8LookupString( - this->xorg_input_context.input_context, // - &event, - buf.data(), - int(buf.size() - 1), - nullptr, - &status - ); - } - utki::assert(size >= 0, SL); - utki::assert(buf.size() != 0, SL); - utki::assert(buf.size() > unsigned(size), SL); - - buf[size] = 0; // null-terminate - - switch (status) { - case XLookupChars: - case XLookupBoth: - if (size == 0) { - return {}; - } - return utki::to_utf32(buf.data()); - default: - case XBufferOverflow: - utki::assert(false, SL); - case XLookupKeySym: - case XLookupNone: - break; - } - - return {}; - } - -private: - // NOLINTNEXTLINE(clang-analyzer-webkit.NoUncountedMemberChecker, "false-positive") - cursor_wrapper* cur_cursor = nullptr; - bool cursor_visible = true; - - void apply_cursor(cursor_wrapper& c) - { - // set the cursor to xorg window - XDefineCursor( - this->display.get().xorg_display.display, // - this->xorg_window.window, - c.cursor - ); - } - - void bind_rendering_context() override - { -#ifdef RUISAPP_RENDER_OPENGL - glXMakeCurrent( - this->display.get().xorg_display.display, // - this->xorg_window.window, - this->glx_context.context - ); -#elif defined(RUISAPP_RENDER_OPENGLES) - if (eglMakeCurrent( - this->display.get().egl_display.display, - this->egl_surface.surface, - this->egl_surface.surface, - this->egl_context.context - ) == EGL_FALSE) - { - throw std::runtime_error("eglMakeCurrent() failed"); - } -#endif - } - - bool is_rendering_context_bound() const noexcept override - { -#ifdef RUISAPP_RENDER_OPENGL - return glXGetCurrentContext() == this->glx_context.context; -#elif defined(RUISAPP_RENDER_OPENGLES) - return eglGetCurrentContext() == this->egl_context.context; -#endif - } -}; - -} // namespace diff --git a/src/ruisapp/glue/linux/xorg/xorg_window.hxx b/src/ruisapp/glue/linux/xorg/xorg_window.hxx new file mode 100644 index 00000000..34be86f9 --- /dev/null +++ b/src/ruisapp/glue/linux/xorg/xorg_window.hxx @@ -0,0 +1,509 @@ +/* +ruisapp - ruis GUI adaptation layer + +Copyright (C) 2016-2025 Ivan Gagis + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +/* ================ LICENSE END ================ */ + +// A base X11 native window that implements everything that is not related to +// the graphics API: X11 window creation, keyboard input (via XIM/IME), mouse +// cursor handling, fullscreen, cascading, etc. +// +// The graphics-specific parts (visual selection, graphics context creation, +// swap_frame_buffers, bind_rendering_context) are implemented by the derived +// classes (see window.hxx for OpenGL/OpenGL ES and vulkan_window.hxx for +// Vulkan). + +#pragma once + +#include +#include +#include +#include + +#include "display.hxx" + +namespace { + +// new windows are cascaded to prevent overlap +constexpr unsigned cascade_max_columns = 15; +constexpr int cascade_step_px = 60; +constexpr int cascade_hint_step_px = 40; + +// the cascade offset (in pixels) for the window at the given index +inline int cascade_offset(unsigned index, int step_px) +{ + return int(index % cascade_max_columns) * step_px; +} + +// the X11 visual info needed to create a window. The graphics API determines +// which visual to use (OpenGL/OpenGL ES pick an FBConfig-based visual, Vulkan +// uses the default visual) +struct xorg_visual { + Visual* visual; + unsigned depth; +}; + +class xorg_window : public ruis::render::native_window +{ + struct xorg_color_map_wrapper { + display_wrapper& display; + + const Colormap color_map; + + xorg_color_map_wrapper( + display_wrapper& display, // + Visual* visual + ) : + display(display), + color_map([&]() { + auto cm = XCreateColormap( + this->display.xorg_display.display, + this->display.xorg_display.get_root_window(this->display.xorg_display.get_default_screen()), + visual, + AllocNone + ); + if (cm == None) { + // TODO: use XSetErrorHandler() to get error code + throw std::runtime_error("XCreateColormap(): failed"); + } + return cm; + }()) + {} + + xorg_color_map_wrapper(const xorg_color_map_wrapper&) = delete; + xorg_color_map_wrapper& operator=(const xorg_color_map_wrapper&) = delete; + + xorg_color_map_wrapper(xorg_color_map_wrapper&&) = delete; + xorg_color_map_wrapper& operator=(const xorg_color_map_wrapper&&) = delete; + + ~xorg_color_map_wrapper() + { + XFreeColormap( + this->display.xorg_display.display, // + this->color_map + ); + } + }; + + struct xorg_window_wrapper { + display_wrapper& display; + + const ::Window window; + mutable bool destroyed = false; + + xorg_window_wrapper( + display_wrapper& display, // + const ruisapp::window_parameters& window_params, + const xorg_color_map_wrapper& color_map, + Visual* visual, + unsigned depth, + bool visible, + int cascade_px, + int hint_px + ) : + display(display), + window([&]() { + XSetWindowAttributes attr; + attr.colormap = color_map.color_map; + attr.border_pixel = 0; + attr.background_pixmap = None; + attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | + PointerMotionMask | ButtonMotionMask | StructureNotifyMask | EnterWindowMask | LeaveWindowMask; + unsigned long fields = CWBorderPixel | CWColormap | CWEventMask | CWBackPixmap; + + auto dims = (this->display.scale_factor * window_params.dims.to()).to(); + + auto w = XCreateWindow( + this->display.xorg_display.display, + this->display.xorg_display.get_root_window(this->display.xorg_display.get_default_screen() + ), // parent + cascade_px, // x position + cascade_px, // y position + dims.x(), // width + dims.y(), // height + 0, // border width + depth, // window's depth + InputOutput, // window's class + visual, + fields, // defined attributes + &attr + ); + if (!w) { + throw std::runtime_error("Failed to create window"); + } + return w; + }()) + { + { // we want to handle WM_DELETE_WINDOW event to know when window is closed + Atom a = XInternAtom( + this->display.xorg_display.display, // + "WM_DELETE_WINDOW", + True + ); + XSetWMProtocols( + this->display.xorg_display.display, // + this->window, + &a, + 1 + ); + } + + { + // set the window position hint so the WM respects the cascading position + auto* hints = XAllocSizeHints(); + hints->flags = USPosition; + hints->x = hint_px; + hints->y = hint_px; + XSetWMNormalHints(this->display.xorg_display.display, this->window, hints); + XFree(hints); + } + + if (!window_params.taskbar) { + Atom wm_state = XInternAtom( + this->display.xorg_display.display, // + "_NET_WM_STATE", + False + ); + Atom skip_taskbar = + XInternAtom(this->display.xorg_display.display, "_NET_WM_STATE_SKIP_TASKBAR", False); + + static_assert(sizeof(skip_taskbar) >= 4, "Atom must be of at least 32-bit size"); + XChangeProperty( + this->display.xorg_display.display, // + this->window, + wm_state, + XA_ATOM, // type of data + 4 * utki::byte_bits, // data is a list of 32-bit values + PropModeReplace, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast, "using C API") + reinterpret_cast(&skip_taskbar), // data + 1 // only one value in the data + ); + } + + if (visible) { + XMapWindow( + this->display.xorg_display.display, // + this->window + ); + } + + this->display.xorg_display.flush(); + + if (!window_params.title.empty()) { + XStoreName( + this->display.xorg_display.display, // + this->window, + window_params.title.c_str() + ); + } + + // force the cascading position (WM may ignore position hints) + XMoveWindow( + this->display.xorg_display.display, // + this->window, + cascade_px, + cascade_px + ); + } + + xorg_window_wrapper(const xorg_window_wrapper&) = delete; + xorg_window_wrapper& operator=(const xorg_window_wrapper&) = delete; + + xorg_window_wrapper(xorg_window_wrapper&&) = delete; + xorg_window_wrapper& operator=(const xorg_window_wrapper&&) = delete; + + ~xorg_window_wrapper() + { + this->destroy(); + } + + void destroy() const + { + if (!this->destroyed) { + XDestroyWindow( + this->display.xorg_display.display, // + this->window + ); + XFlush(this->display.xorg_display.display); + this->destroyed = true; + } + } + }; + + struct xorg_input_context_wrapper { + const XIC input_context; + + xorg_input_context_wrapper( + const display_wrapper& display, // + const xorg_window_wrapper& window + ) : + input_context([&]() { + auto ic = + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg, "using C API") + XCreateIC( + display.xorg_input_method.xim, + XNClientWindow, + window.window, + XNFocusWindow, + window.window, + XNInputStyle, + XIMPreeditNothing | XIMStatusNothing, + nullptr + ); + if (ic == nullptr) { + throw std::runtime_error("XCreateIC() failed"); + } + return ic; + }()) + {} + + xorg_input_context_wrapper(const xorg_input_context_wrapper&) = delete; + xorg_input_context_wrapper& operator=(const xorg_input_context_wrapper&) = delete; + + xorg_input_context_wrapper(xorg_input_context_wrapper&&) = delete; + xorg_input_context_wrapper& operator=(const xorg_input_context_wrapper&&) = delete; + + ~xorg_input_context_wrapper() + { + XUnsetICFocus(this->input_context); + XDestroyIC(this->input_context); + } + }; + +public: + // counter for cascading new windows to prevent overlap + static inline unsigned s_window_count = 0; + + xorg_window( + utki::shared_ref display, // + const ruisapp::window_parameters& window_params, + const xorg_window* shared, + const xorg_visual& visual + ) : + display(std::move(display)), + colormap( + this->display, // + visual.visual + ), + window( + this->display, // + window_params, + this->colormap, + visual.visual, + visual.depth, + shared != nullptr, // visible + cascade_offset(s_window_count, cascade_step_px), + cascade_offset(s_window_count, cascade_hint_step_px) + ), + input_context( + this->display, // + this->window + ), + current_dims((this->display.get().scale_factor * window_params.dims.to()).to()) + { + s_window_count++; + } + + xorg_window(const xorg_window&) = delete; + xorg_window& operator=(const xorg_window&) = delete; + + xorg_window(xorg_window&&) = delete; + xorg_window& operator=(const xorg_window&&) = delete; + + ~xorg_window() override = default; + + static_assert(std::is_integral_v<::Window>, "xorg lib's Window type is unexpectedly not integral"); + using window_id_type = ::Window; + + window_id_type get_id() const noexcept + { + return this->window.window; + } + + r4::vector2 get_dims() const noexcept override + { + return this->current_dims; + } + + void set_dims(const r4::vector2 dims) const noexcept override + { + XResizeWindow(this->display.get().xorg_display.display, this->window.window, dims.x(), dims.y()); + this->current_dims = dims; + } + + void set_fullscreen_internal(bool enable) override + { + Atom state_atom = XInternAtom( + this->display.get().xorg_display.display, // + "_NET_WM_STATE", + False + ); + Atom atom = XInternAtom( + this->display.get().xorg_display.display, // + "_NET_WM_STATE_FULLSCREEN", + False + ); + + XEvent event; + event.xclient.type = ClientMessage; + event.xclient.serial = 0; + event.xclient.send_event = True; + event.xclient.window = this->window.window; + event.xclient.message_type = state_atom; + + // data should be viewed as list of longs + event.xclient.format = utki::byte_bits * 4; + + // use union from third-party code + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) + event.xclient.data.l[0] = enable ? 1 : 0; + + // use union from third-party code + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) + event.xclient.data.l[1] = long(atom); + + // use union from third-party code + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) + event.xclient.data.l[2] = 0; + + XSendEvent( + this->display.get().xorg_display.display, // + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast, cppcoreguidelines-pro-bounds-pointer-arithmetic) + this->display.get().xorg_display.get_default_root_window(), + False, + SubstructureRedirectMask | SubstructureNotifyMask, + &event + ); + + this->display.get().xorg_display.flush(); + } + + void set_mouse_cursor(ruis::mouse_cursor c) override + { + this->cur_cursor = &this->display.get().get_cursor(c); + + if (this->cursor_visible) { + this->apply_cursor(*this->cur_cursor); + } + } + + void set_mouse_cursor_visible(bool visible) override + { + this->cursor_visible = visible; + if (visible) { + if (this->cur_cursor) { + this->apply_cursor(*this->cur_cursor); + } else { + XUndefineCursor( + this->display.get().xorg_display.display, // + this->window.window + ); + } + } else { + this->apply_cursor(this->display.get().get_cursor(ruis::mouse_cursor::none)); + } + } + + std::u32string get_string(XKeyEvent& event) const + { +#ifndef X_HAVE_UTF8_STRING +# error "no Xutf8stringlookup()" +#endif + constexpr auto static_buf_size = 32; + + // the array is used to get data, so no need to initialize it + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + std::array static_buf; + + std::vector arr; + auto buf = utki::make_span(static_buf); + + // the variable is initialized via output argument, so no need to initialize + // it here NOLINTNEXTLINE(cppcoreguidelines-init-variables) + Status status; + + int size = Xutf8LookupString( + this->input_context.input_context, // + &event, + buf.data(), + int(buf.size() - 1), + nullptr, + &status + ); + if (status == XBufferOverflow) { + // allocate enough memory + arr.resize(size + 1); + buf = utki::make_span(arr); + size = Xutf8LookupString( + this->input_context.input_context, // + &event, + buf.data(), + int(buf.size() - 1), + nullptr, + &status + ); + } + utki::assert(size >= 0, SL); + utki::assert(buf.size() != 0, SL); + utki::assert(buf.size() > unsigned(size), SL); + + buf[size] = 0; // null-terminate + + switch (status) { + case XLookupChars: + case XLookupBoth: + if (size == 0) { + return {}; + } + return utki::to_utf32(buf.data()); + default: + case XBufferOverflow: + utki::assert(false, SL); + case XLookupKeySym: + case XLookupNone: + break; + } + + return {}; + } + +protected: + const utki::shared_ref display; + const xorg_color_map_wrapper colormap; + const xorg_window_wrapper window; + const xorg_input_context_wrapper input_context; + mutable r4::vector2 current_dims; + +private: + // NOLINTNEXTLINE(clang-analyzer-webkit.NoUncountedMemberChecker, "false-positive") + cursor_wrapper* cur_cursor = nullptr; + bool cursor_visible = true; + + void apply_cursor(cursor_wrapper& c) + { + // set the cursor to xorg window + XDefineCursor( + this->display.get().xorg_display.display, // + this->window.window, + c.cursor + ); + } +}; + +} // namespace diff --git a/src/ruisapp/glue/macos/application.cxx b/src/ruisapp/glue/macos/application.cxx index 7182d1bf..13f804ab 100644 --- a/src/ruisapp/glue/macos/application.cxx +++ b/src/ruisapp/glue/macos/application.cxx @@ -22,6 +22,7 @@ along with this program. If not, see . #include "application.hxx" #include +#include #include namespace { @@ -94,19 +95,17 @@ application_glue::application_glue(const utki::version_duplet& gl_version) : }, nullptr // no shared gl context )), - resource_loader_ruis_rendering_context([&]() { + render_factory([&]() { utki::logcat_debug("application_glue::application_glue(): creating shared gl context", '\n'); - auto c = utki::make_shared(this->shared_gl_context_native_window); + auto c = utki::make_shared(this->shared_gl_context_native_window); utki::logcat_debug("application_glue::application_glue(): shared gl context created", '\n'); return c; }()), - common_shaders(this->resource_loader_ruis_rendering_context.get().make_shaders()), - common_render_objects( - utki::make_shared(this->resource_loader_ruis_rendering_context) - ), + common_shaders(this->render_factory.get().make_shaders()), + common_render_objects(utki::make_shared(this->render_factory.get())), ruis_resource_loader( // utki::make_shared( - this->resource_loader_ruis_rendering_context, // + this->render_factory, // this->common_render_objects ) ), @@ -134,7 +133,7 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window }, .updater = this->updater, .renderer = utki::make_shared( - utki::make_shared(ruis_native_window), // + utki::make_shared(ruis_native_window, this->render_factory), // this->common_shaders, this->common_render_objects ), diff --git a/src/ruisapp/glue/macos/application.hxx b/src/ruisapp/glue/macos/application.hxx index ebcbfaaf..71b532eb 100644 --- a/src/ruisapp/glue/macos/application.hxx +++ b/src/ruisapp/glue/macos/application.hxx @@ -65,8 +65,8 @@ class application_glue : public utki::destructable const utki::version_duplet gl_version; const utki::shared_ref shared_gl_context_native_window; - const utki::shared_ref resource_loader_ruis_rendering_context; - const utki::shared_ref common_shaders; + const utki::shared_ref render_factory; + const utki::shared_ref common_shaders; const utki::shared_ref common_render_objects; const utki::shared_ref ruis_resource_loader; diff --git a/src/ruisapp/glue/sdl/application.cxx b/src/ruisapp/glue/sdl/application.cxx index af02932b..f786047e 100644 --- a/src/ruisapp/glue/sdl/application.cxx +++ b/src/ruisapp/glue/sdl/application.cxx @@ -26,9 +26,11 @@ along with this program. If not, see . #ifdef RUISAPP_RENDER_OPENGL // # include # include +# include #elif defined(RUISAPP_RENDER_OPENGLES) // # include # include +# include #else # error "Unknown graphics API" #endif @@ -51,27 +53,27 @@ application_glue::application_glue(const utki::version_duplet& gl_version) : nullptr // no shared gl context ) ), - resource_loader_ruis_rendering_context( + render_factory( # ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(this->shared_gl_context_native_window) + utki::make_shared(this->shared_gl_context_native_window) # elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(this->shared_gl_context_native_window) + utki::make_shared(this->shared_gl_context_native_window) # else # error "Unknown graphics API" # endif ), common_shaders( // [&]() { - utki::assert(this->resource_loader_ruis_rendering_context.to_shared_ptr(), SL); - return this->resource_loader_ruis_rendering_context.get().make_shaders(); + utki::assert(this->render_factory.to_shared_ptr(), SL); + return this->render_factory.get().make_shaders(); }() ), common_render_objects( // - utki::make_shared(this->resource_loader_ruis_rendering_context) + utki::make_shared(this->render_factory.get()) ), ruis_resource_loader( // utki::make_shared( - this->resource_loader_ruis_rendering_context, // + this->render_factory, // this->common_render_objects ) ), @@ -146,13 +148,13 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window ); #if CFG_OS_NAME == CFG_OS_NAME_EMSCRIPTEN - auto rendering_context = utki::make_shared(ruis_native_window); + auto render_factory = utki::make_shared(ruis_native_window); - auto common_render_objects = utki::make_shared(rendering_context); - auto common_shaders = rendering_context.get().make_shaders(); + auto common_render_objects = utki::make_shared(*render_factory); + auto common_shaders = render_factory.get().make_shaders(); auto ruis_resource_loader = utki::make_shared( - rendering_context, // + render_factory, // common_render_objects ); @@ -171,16 +173,16 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window .renderer = #if CFG_OS_NAME == CFG_OS_NAME_EMSCRIPTEN utki::make_shared( - std::move(rendering_context), + utki::make_shared(ruis_native_window, render_factory), std::move(common_shaders), std::move(common_render_objects) ), #else utki::make_shared( # ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(ruis_native_window), + utki::make_shared(ruis_native_window, this->render_factory), # elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(ruis_native_window), + utki::make_shared(ruis_native_window, this->render_factory), # else # error "Unknown graphics API" # endif diff --git a/src/ruisapp/glue/sdl/application.hxx b/src/ruisapp/glue/sdl/application.hxx index 5395b4e6..0cd12cd9 100644 --- a/src/ruisapp/glue/sdl/application.hxx +++ b/src/ruisapp/glue/sdl/application.hxx @@ -69,8 +69,8 @@ public: // only one window allowed on emscripten, so we don't create hidden window for shared GL context #if CFG_OS_NAME != CFG_OS_NAME_EMSCRIPTEN const utki::shared_ref shared_gl_context_native_window; - const utki::shared_ref resource_loader_ruis_rendering_context; - const utki::shared_ref common_shaders; + const utki::shared_ref render_factory; + const utki::shared_ref common_shaders; const utki::shared_ref common_render_objects; const utki::shared_ref ruis_resource_loader; const utki::shared_ref ruis_style_provider; diff --git a/src/ruisapp/glue/windows/application.cxx b/src/ruisapp/glue/windows/application.cxx index c5f1a1b0..6c20deba 100644 --- a/src/ruisapp/glue/windows/application.cxx +++ b/src/ruisapp/glue/windows/application.cxx @@ -110,26 +110,24 @@ application_glue::application_glue(const utki::version_duplet& gl_version) : }, nullptr // no shared gl context )), - resource_loader_ruis_rendering_context([&]() { + render_factory([&]() { utki::logcat_debug("application_glue::application_glue(): creating shared gl context", '\n'); #ifdef RUISAPP_RENDER_OPENGL - using context_type = ruis::render::opengl::context; + using factory_type = ruis::render::opengl::factory; #elif defined(RUISAPP_RENDER_OPENGLES) - using context_type = ruis::render::opengles::context; + using factory_type = ruis::render::opengles::factory; #else # error "Unknown graphics API" #endif - auto c = utki::make_shared(this->shared_gl_context_native_window); + auto c = utki::make_shared(this->shared_gl_context_native_window); utki::logcat_debug("application_glue::application_glue(): shared gl context created", '\n'); return c; }()), - common_shaders(this->resource_loader_ruis_rendering_context.get().make_shaders()), - common_render_objects( - utki::make_shared(this->resource_loader_ruis_rendering_context) - ), + common_shaders(this->render_factory.get().make_shaders()), + common_render_objects(utki::make_shared(this->render_factory.get())), ruis_resource_loader( // utki::make_shared( - this->resource_loader_ruis_rendering_context, // + this->render_factory, // this->common_render_objects ) ), @@ -187,9 +185,9 @@ ruisapp::window& application_glue::make_window(ruisapp::window_parameters window .updater = this->updater, .renderer = utki::make_shared( #ifdef RUISAPP_RENDER_OPENGL - utki::make_shared(ruis_native_window), + utki::make_shared(ruis_native_window, this->render_factory), #elif defined(RUISAPP_RENDER_OPENGLES) - utki::make_shared(ruis_native_window), + utki::make_shared(ruis_native_window, this->render_factory), #else # error "Unknown graphics API" #endif diff --git a/src/ruisapp/glue/windows/application.hxx b/src/ruisapp/glue/windows/application.hxx index 8aa3d352..2f82ff9f 100644 --- a/src/ruisapp/glue/windows/application.hxx +++ b/src/ruisapp/glue/windows/application.hxx @@ -75,8 +75,8 @@ class application_glue : public utki::destructable utki::shared_ref display = utki::make_shared(); const utki::shared_ref shared_gl_context_native_window; - const utki::shared_ref resource_loader_ruis_rendering_context; - const utki::shared_ref common_shaders; + const utki::shared_ref render_factory; + const utki::shared_ref common_shaders; const utki::shared_ref common_render_objects; const utki::shared_ref ruis_resource_loader; diff --git a/src/ruisapp/glue/windows/glue.cxx b/src/ruisapp/glue/windows/glue.cxx index 6e1a1f29..16793eff 100644 --- a/src/ruisapp/glue/windows/glue.cxx +++ b/src/ruisapp/glue/windows/glue.cxx @@ -29,9 +29,11 @@ along with this program. If not, see . #ifdef RUISAPP_RENDER_OPENGL # include +# include #elif defined(RUISAPP_RENDER_OPENGLES) # include # include +# include #else # error "Unknown graphics API" #endif diff --git a/src/ruisapp/window.cpp b/src/ruisapp/window.cpp index 55b7b6ec..d4a453a2 100644 --- a/src/ruisapp/window.cpp +++ b/src/ruisapp/window.cpp @@ -38,7 +38,7 @@ void window::render() this->gui.render(this->gui.context.get().ren().ctx().initial_matrix); // std::cout << "swap frame buffers" << std::endl; - this->gui.context.get().window().swap_frame_buffers(); + this->gui.ctx().ren().ctx().swap_frame_buffers(); // std::cout << "swapped" << std::endl; }); } diff --git a/tests/app/src/cube_widget.cpp b/tests/app/src/cube_widget.cpp index dae17bd0..8c3ebd58 100644 --- a/tests/app/src/cube_widget.cpp +++ b/tests/app/src/cube_widget.cpp @@ -23,8 +23,7 @@ cube_widget::cube_widget( ruis::vec3(-1, -1, 1), ruis::vec3(-1, -1, 1), ruis::vec3(1, -1, -1), ruis::vec3(1, -1, 1)} }; - auto pos_vbo = - this->context.get().renderer.get().rendering_context.get().make_vertex_buffer(utki::make_span(cube_pos)); + auto pos_vbo = this->ctx().ren().ctx().fac().make_vertex_buffer(utki::make_span(cube_pos)); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) std::array cube_tex = { @@ -37,7 +36,7 @@ cube_widget::cube_widget( }; auto tex_vbo = - this->context.get().renderer.get().rendering_context.get().make_vertex_buffer(utki::make_span(cube_tex)); + this->context.get().renderer.get().rendering_context.get().fac().make_vertex_buffer(utki::make_span(cube_tex)); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) std::array indices = { @@ -48,12 +47,13 @@ cube_widget::cube_widget( }; auto cube_indices = - this->context.get().renderer.get().rendering_context.get().make_index_buffer(utki::make_span(indices)); + this->context.get().renderer.get().rendering_context.get().fac().make_index_buffer(utki::make_span(indices)); this->cubeVAO = this->context.get() .renderer.get() .rendering_context.get() + .fac() .make_vertex_array({pos_vbo, tex_vbo}, cube_indices, ruis::render::vertex_array::mode::triangles) .to_shared_ptr(); diff --git a/tests/app/src/new_native_window.cpp b/tests/app/src/new_native_window.cpp new file mode 100644 index 00000000..ba29f7a1 --- /dev/null +++ b/tests/app/src/new_native_window.cpp @@ -0,0 +1,87 @@ +#include "new_native_window.hpp" + +#include +#include +#include +#include +#include +#include + +#include "style.hpp" + +using namespace std::string_literals; +using namespace std::string_view_literals; + +utki::shared_ref make_new_native_window_root_widget( + const utki::shared_ref& c, // + ruisapp::window& win +) +{ + // clang-format off + auto button = m::push_button(c, + { + .layout_params{ + .dims{ruis::dim::fill, ruis::dim::fill}, + .weight = 1 + } + }, + { + m::text(c, {}, U"the button"s) + } + ); + // clang-format on + + button.get().click_handler = [](ruis::push_button& b) { + utki::logcat("the button clicked", '\n'); + }; + + // clang-format off + auto close_button = m::push_button(c, + {}, + { + m::text(c, {}, U"X"s) + } + ); + // clang-format on + + auto* win_ptr = &win; + close_button.get().click_handler = [win_ptr](auto& b) { + ruisapp::inst().destroy_window(*win_ptr); + }; + + // clang-format off + return m::column(c, + {}, + { + m::row(c, + { + .layout_params{ + .align = {ruis::align::front, ruis::align::center} + } + }, + { + m::text(c, {}, U"Native window"s), + std::move(close_button) + } + ), + m::text_field(c, + { + .layout_params{ + .dims{ruis::dim::max, ruis::dim::min} + }, + .widget{ + .id = "text_input"s + }, + .text_input{ + .text{ + .color = c.get().style().get_color_text() + } + } + }, + U"Hello Wrodl!!!"s + ), + std::move(button) + } + ); + // clang-format on +} diff --git a/tests/app/src/new_native_window.hpp b/tests/app/src/new_native_window.hpp new file mode 100644 index 00000000..32a4ff29 --- /dev/null +++ b/tests/app/src/new_native_window.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +utki::shared_ref make_new_native_window_root_widget( + const utki::shared_ref& c, // + ruisapp::window& win +); diff --git a/tests/app/src/text_input_window.cpp b/tests/app/src/text_input_window.cpp index b9cdb58f..c8720e70 100644 --- a/tests/app/src/text_input_window.cpp +++ b/tests/app/src/text_input_window.cpp @@ -7,7 +7,9 @@ #include #include #include +#include +#include "new_native_window.hpp" #include "style.hpp" using namespace std::string_literals; @@ -55,6 +57,40 @@ utki::shared_ref make_text_input_window(const utki::shared_ref make_text_input_window(const utki::shared_ref