From 1e689e88b1e692f721c9a150c87dbf69b2515a40 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 00:43:41 +0300 Subject: [PATCH 01/35] add native Wayland window backend Wayland support was missing a proper windowing layer: the GLFW backend leaves the known platform gaps (cursor themes, window icon, window position, fullscreen output selection). The new backend talks to the compositor directly: - xdg-shell, EGL, xkbcommon (keyboard, repeat, layout) instead of GLFW; - cursors through wp_cursor_shape_manager_v1, so no cursor theme lookup is required and no "standard cursor shape unavailable" errors appear; - window icon and title are drawn by the engine itself, since Wayland has no window icon protocol and GNOME provides no server-side decorations; - fullscreen requests the current output (set_fullscreen with NULL), so the window no longer jumps to another monitor; - interactive resize presents a cached frame scaled to the new size while the pointer is down and refreshes the real frame when the drag pauses, keeping the window glued to the cursor. libdecor is not used: libdecor_frame_commit() redraws the whole decoration and acks the configure in the same call, and mutter sends 200-330 configures per second during an interactive resize, so the decoration was redrawn hundreds of times per second (measured: 2 s of work per second, loop stalls up to 6 s). The decorations are drawn by the engine instead, which measured 2.3 ms average configure-to-present latency during a real drag. GLFW stays the backend for X11 and Windows; VOXEL_WINDOW_BACKEND=x11 forces it on Wayland sessions. --- src/CMakeLists.txt | 61 + src/engine/Mainloop.cpp | 2 +- src/engine/WindowControl.cpp | 8 +- src/window/Window.cpp | 41 + src/window/Window.hpp | 7 + src/window/detail/BaseInput.cpp | 152 ++ src/window/detail/BaseInput.hpp | 58 + src/window/detail/GLFWWindow.cpp | 227 +- src/window/detail/WaylandWindow.cpp | 2421 +++++++++++++++++ src/window/detail/WindowBackends.hpp | 17 + src/window/input.cpp | 606 ++--- .../wayland/protocols/cursor-shape-v1.xml | 162 ++ .../protocols/idle-inhibit-unstable-v1.xml | 83 + .../pointer-constraints-unstable-v1.xml | 334 +++ .../relative-pointer-unstable-v1.xml | 136 + .../wayland/protocols/tablet-unstable-v2.xml | 1182 ++++++++ .../protocols/xdg-decoration-unstable-v1.xml | 176 ++ src/window/wayland/protocols/xdg-shell.xml | 1420 ++++++++++ 18 files changed, 6567 insertions(+), 526 deletions(-) create mode 100644 src/window/Window.cpp create mode 100644 src/window/detail/BaseInput.cpp create mode 100644 src/window/detail/BaseInput.hpp create mode 100644 src/window/detail/WaylandWindow.cpp create mode 100644 src/window/detail/WindowBackends.hpp create mode 100644 src/window/wayland/protocols/cursor-shape-v1.xml create mode 100644 src/window/wayland/protocols/idle-inhibit-unstable-v1.xml create mode 100644 src/window/wayland/protocols/pointer-constraints-unstable-v1.xml create mode 100644 src/window/wayland/protocols/relative-pointer-unstable-v1.xml create mode 100644 src/window/wayland/protocols/tablet-unstable-v2.xml create mode 100644 src/window/wayland/protocols/xdg-decoration-unstable-v1.xml create mode 100644 src/window/wayland/protocols/xdg-shell.xml diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8eae55c33..3540fb3d2 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -72,6 +72,67 @@ endif() target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +option(VOXELENGINE_WAYLAND "Build the native Wayland window backend" ON) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) + find_package(PkgConfig REQUIRED) + pkg_check_modules(wayland-client IMPORTED_TARGET wayland-client) + pkg_check_modules(xkbcommon IMPORTED_TARGET xkbcommon) + pkg_check_modules(egl IMPORTED_TARGET egl) + find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1) + find_program(WAYLAND_SCANNER wayland-scanner) + + if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND + OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER) + message(STATUS "Wayland backend is off: dependencies are not found") + else() + set(WAYLAND_PROTOCOLS ${CMAKE_CURRENT_SOURCE_DIR}/window/wayland/protocols) + set(WAYLAND_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/wayland-protocols) + file(MAKE_DIRECTORY ${WAYLAND_GENERATED}) + set(WAYLAND_SOURCES) + + function(voxel_wayland_protocol XML NAME) + add_custom_command( + OUTPUT ${WAYLAND_GENERATED}/${NAME}-client-protocol.h + ${WAYLAND_GENERATED}/${NAME}-protocol.c + COMMAND ${WAYLAND_SCANNER} client-header + ${WAYLAND_PROTOCOLS}/${XML} + ${WAYLAND_GENERATED}/${NAME}-client-protocol.h + COMMAND ${WAYLAND_SCANNER} private-code + ${WAYLAND_PROTOCOLS}/${XML} + ${WAYLAND_GENERATED}/${NAME}-protocol.c + DEPENDS ${WAYLAND_PROTOCOLS}/${XML} + VERBATIM) + set(WAYLAND_SOURCES ${WAYLAND_SOURCES} + ${WAYLAND_GENERATED}/${NAME}-protocol.c + PARENT_SCOPE) + endfunction() + + voxel_wayland_protocol(xdg-shell.xml xdg-shell) + voxel_wayland_protocol(cursor-shape-v1.xml cursor-shape-v1) + voxel_wayland_protocol(idle-inhibit-unstable-v1.xml + idle-inhibit-unstable-v1) + voxel_wayland_protocol(pointer-constraints-unstable-v1.xml + pointer-constraints-unstable-v1) + voxel_wayland_protocol(relative-pointer-unstable-v1.xml + relative-pointer-unstable-v1) + voxel_wayland_protocol(xdg-decoration-unstable-v1.xml + xdg-decoration-unstable-v1) + # tablet is referenced by cursor-shape-v1 + voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) + + target_sources(VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES}) + target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) + target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) + target_link_libraries( + VoxelCoreSrc + PRIVATE PkgConfig::wayland-client + PkgConfig::xkbcommon + PkgConfig::egl + ${WAYLAND_EGL_LIBRARY}) + message(STATUS "Wayland backend is on") + endif() +endif() + target_link_libraries( VoxelCoreSrc PRIVATE glfw diff --git a/src/engine/Mainloop.cpp b/src/engine/Mainloop.cpp index aa505a9ba..aecf5b071 100644 --- a/src/engine/Mainloop.cpp +++ b/src/engine/Mainloop.cpp @@ -48,7 +48,7 @@ void Mainloop::run() { engine.applicationTick(); engine.updateFrontend(); - if (!window.isIconified()) { + if (!window.isIconified() && window.isFrameRequired()) { engine.renderFrame(); } engine.postUpdate(); diff --git a/src/engine/WindowControl.cpp b/src/engine/WindowControl.cpp index 5a14c02ba..19119fb12 100644 --- a/src/engine/WindowControl.cpp +++ b/src/engine/WindowControl.cpp @@ -59,9 +59,11 @@ WindowControl::Result WindowControl::initialize() { throw initialize_error("could not initialize window"); } window->setFramerate(settings.display.framerate.get()); - if (auto icon = load_icon()) { - icon->flipY(); - window->setIcon(icon.get()); + if (window->isIconSupported()) { + if (auto icon = load_icon()) { + icon->flipY(); + window->setIcon(icon.get()); + } } return Result {std::move(window), std::move(input)}; diff --git a/src/window/Window.cpp b/src/window/Window.cpp new file mode 100644 index 000000000..59338380a --- /dev/null +++ b/src/window/Window.cpp @@ -0,0 +1,41 @@ +#include "Window.hpp" + +#include "debug/Logger.hpp" +#include "detail/WindowBackends.hpp" +#include "window/input.hpp" + +#include +#include + +static debug::Logger logger("window"); + +#ifdef VOXELENGINE_WAYLAND +static bool prefer_wayland() { + const char* backend = getenv("VOXEL_WINDOW_BACKEND"); + if (backend != nullptr) { + return strcmp(backend, "wayland") == 0; + } + const char* display = getenv("WAYLAND_DISPLAY"); + if (display != nullptr && *display) { + return true; + } + return getenv("DISPLAY") == nullptr; +} +#endif + +std::tuple< + std::unique_ptr, + std::unique_ptr +> Window::initialize(DisplaySettings* settings, std::string title) { + input_util::initialize(); +#ifdef VOXELENGINE_WAYLAND + if (prefer_wayland()) { + auto result = wayland_window_initialize(settings, title); + if (std::get<0>(result) && std::get<1>(result)) { + return result; + } + logger.warning() << "could not initialize the Wayland backend"; + } +#endif + return glfw_window_initialize(settings, std::move(title)); +} diff --git a/src/window/Window.hpp b/src/window/Window.hpp index f5a50a731..c34024cdf 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -32,6 +32,10 @@ public: virtual bool isShouldClose() const = 0; virtual void setShouldClose(bool flag) = 0; + virtual bool isFrameRequired() const { + return true; + } + virtual void setCursor(CursorShape shape) = 0; virtual void setMode(WindowMode mode) = 0; virtual WindowMode getMode() const = 0; @@ -39,6 +43,9 @@ public: virtual void focus() = 0; virtual void setTitle(const std::string& title) = 0; + + virtual bool isIconSupported() const = 0; + virtual void setIcon(const ImageData* image) = 0; virtual void pushScissor(glm::vec4 area) = 0; diff --git a/src/window/detail/BaseInput.cpp b/src/window/detail/BaseInput.cpp new file mode 100644 index 000000000..887bec818 --- /dev/null +++ b/src/window/detail/BaseInput.cpp @@ -0,0 +1,152 @@ +#include "BaseInput.hpp" + +void BaseInput::onKeyCallback(int key, bool pressed) { + bool prevPressed = keys[key]; + keys[key] = pressed; + frames[key] = currentFrame; + if (pressed && !prevPressed) { + const auto& callbacks = keyCallbacks.find(static_cast(key)); + if (callbacks != keyCallbacks.end()) { + callbacks->second.notify(); + } + } + if (pressed && key < MOUSE_KEYS_OFFSET) { + pressedKeys.push_back(static_cast(key)); + } +} + +void BaseInput::onMouseCallback(int button, bool pressed) { + onKeyCallback(button + MOUSE_KEYS_OFFSET, pressed); +} + +bool BaseInput::isCursorLocked() const { + return cursorLocked; +} + +void BaseInput::setCursorPosition(double xpos, double ypos) { + if (cursorDrag) { + delta.x += xpos - cursor.x; + delta.y += ypos - cursor.y; + } else { + cursorDrag = true; + } + cursor.x = xpos; + cursor.y = ypos; +} + +Bindings& BaseInput::getBindings() { + return bindings; +} + +const Bindings& BaseInput::getBindings() const { + return bindings; +} + +ObserverHandler BaseInput::addKeyCallback(Keycode key, InputCallback callback) { + return keyCallbacks[key].add(std::move(callback)); +} + +ObserverHandler BaseInput::addMouseCallback(Mousecode button, InputCallback callback) { + return addKeyCallback( + static_cast(MOUSE_KEYS_OFFSET + static_cast(button)), + std::move(callback) + ); +} + +const std::vector& BaseInput::getPressedKeys() const { + return pressedKeys; +} + +const std::vector& BaseInput::getCodepoints() const { + return codepoints; +} + +CursorState BaseInput::getCursor() const { + return {isCursorLocked(), cursor, delta}; +} + +int BaseInput::getScroll() { + return scroll; +} + +bool BaseInput::pressed(Keycode key) const { + int keycode = static_cast(key); + if (keycode < 0 || keycode >= KEYS_BUFFER_SIZE) { + return false; + } + return keys[keycode]; +} + +bool BaseInput::jpressed(Keycode keycode) const { + return pressed(keycode) && + frames[static_cast(keycode)] == currentFrame; +} + +bool BaseInput::clicked(Mousecode code) const { + return pressed( + static_cast(MOUSE_KEYS_OFFSET + static_cast(code)) + ); +} + +bool BaseInput::jclicked(Mousecode code) const { + return clicked(code) && + frames[static_cast(code) + MOUSE_KEYS_OFFSET] == currentFrame; +} + +void BaseInput::simulateKey(Keycode key, bool pressed) { + onKeyCallback(static_cast(key), pressed); +} + +void BaseInput::simulateClick(int button, bool pressed) { + onMouseCallback(button, pressed); +} + +void BaseInput::simulateCursorPos(double xpos, double ypos) { + setCursorPosition(xpos, ypos); +} + +void BaseInput::simulateCodepoint(uint codepoint) { + codepoints.push_back(codepoint); +} + +void BaseInput::beginFrame() { + delta.x = 0.0f; + delta.y = 0.0f; + scroll = 0; + currentFrame++; + codepoints.clear(); + pressedKeys.clear(); +} + +void BaseInput::updateBindings() { + for (auto& [_, binding] : bindings.getAll()) { + if (!binding.enabled) { + binding.state = false; + continue; + } + binding.justChanged = false; + + bool newstate = false; + switch (binding.type) { + case InputType::KEYBOARD: + newstate = pressed(static_cast(binding.code)); + break; + case InputType::MOUSE: + newstate = clicked(static_cast(binding.code)); + break; + } + + if (newstate) { + if (!binding.state) { + binding.state = true; + binding.justChanged = true; + binding.onactived.notify(); + } + } else { + if (binding.state) { + binding.state = false; + binding.justChanged = true; + } + } + } +} diff --git a/src/window/detail/BaseInput.hpp b/src/window/detail/BaseInput.hpp new file mode 100644 index 000000000..92f86b3a9 --- /dev/null +++ b/src/window/detail/BaseInput.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include "window/input.hpp" + +#include +#include +#include + +inline constexpr short KEYS_BUFFER_SIZE = 1036; +inline constexpr short MOUSE_KEYS_OFFSET = 1024; + +class BaseInput : public Input { +public: + std::vector codepoints; + int scroll = 0; + + void onKeyCallback(int key, bool pressed); + void onMouseCallback(int button, bool pressed); + + bool isCursorLocked() const override; + void setCursorPosition(double xpos, double ypos); + + Bindings& getBindings() override; + const Bindings& getBindings() const override; + + ObserverHandler addKeyCallback(Keycode key, InputCallback callback) override; + ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) override; + + const std::vector& getPressedKeys() const override; + const std::vector& getCodepoints() const override; + + CursorState getCursor() const override; + int getScroll() override; + + bool pressed(Keycode key) const override; + bool jpressed(Keycode keycode) const override; + bool clicked(Mousecode code) const override; + bool jclicked(Mousecode code) const override; + + void simulateKey(Keycode key, bool pressed) override; + void simulateClick(int button, bool pressed) override; + void simulateCursorPos(double xpos, double ypos) override; + void simulateCodepoint(uint codepoint) override; +protected: + void beginFrame(); + void updateBindings(); + + uint currentFrame = 0; + uint frames[KEYS_BUFFER_SIZE] {}; + std::vector pressedKeys; + Bindings bindings; + bool keys[KEYS_BUFFER_SIZE] {}; + std::unordered_map> keyCallbacks; + bool cursorLocked = false; + bool cursorDrag = false; + glm::vec2 delta {}; + glm::vec2 cursor {}; +}; diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 08b39bd07..9fe04b82c 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -1,4 +1,6 @@ #include "window/Window.hpp" +#include "window/detail/BaseInput.hpp" +#include "window/detail/WindowBackends.hpp" #include #include @@ -18,9 +20,42 @@ static debug::Logger logger("window"); +static const char* get_platform_name() { +#if GLFW_VERSION_MAJOR > 3 || (GLFW_VERSION_MAJOR == 3 && GLFW_VERSION_MINOR >= 4) + switch (glfwGetPlatform()) { + case GLFW_PLATFORM_WIN32: return "Win32"; + case GLFW_PLATFORM_COCOA: return "Cocoa"; + case GLFW_PLATFORM_WAYLAND: return "Wayland (GLFW)"; + case GLFW_PLATFORM_X11: return "X11"; + case GLFW_PLATFORM_NULL: return "Null"; + } +#endif + return "unknown"; +} + static std::unordered_set supported_gl_extensions; static void window_size_callback(GLFWwindow* window, int width, int height); +static GLFWmonitor* get_window_monitor(GLFWwindow* window) { + int x = 0, y = 0, width = 0, height = 0; + glfwGetWindowPos(window, &x, &y); + glfwGetWindowSize(window, &width, &height); + x += width / 2; + y += height / 2; + int count = 0; + GLFWmonitor** monitors = glfwGetMonitors(&count); + for (int i = 0; i < count; i++) { + int monitorX = 0, monitorY = 0; + glfwGetMonitorPos(monitors[i], &monitorX, &monitorY); + const GLFWvidmode* mode = glfwGetVideoMode(monitors[i]); + if (mode && x >= monitorX && x < monitorX + mode->width && + y >= monitorY && y < monitorY + mode->height) { + return monitors[i]; + } + } + return glfwGetPrimaryMonitor(); +} + static void init_gl_extensions_list() { GLint numExtensions = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); @@ -85,21 +120,6 @@ static void GLAPIENTRY gl_message_callback( #endif static bool initialize_gl(int width, int height) { - glewExperimental = GL_TRUE; - - GLenum glewErr = glewInit(); - if (glewErr != GLEW_OK) { - if (glewErr == GLEW_ERROR_NO_GLX_DISPLAY) { - // see issue #240 - logger.warning() - << "glewInit() returned GLEW_ERROR_NO_GLX_DISPLAY; ignored"; - } else { - logger.error() << "failed to initialize GLEW:\n" - << glewGetErrorString(glewErr); - return true; - } - } - #ifndef __APPLE__ glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(gl_message_callback, nullptr); @@ -163,137 +183,8 @@ static void glfw_error_callback(int error, const char* description) { } } -inline constexpr short KEYS_BUFFER_SIZE = 1036; -inline constexpr short MOUSE_KEYS_OFFSET = 1024; - static GLFWcursor* standard_cursors[static_cast(CursorShape::LAST) + 1] = {}; -class BaseInput : public Input { -public: - std::vector codepoints; - int scroll = 0; - - void onKeyCallback(int key, bool pressed) { - bool prevPressed = keys[key]; - keys[key] = pressed; - frames[key] = currentFrame; - if (pressed && !prevPressed) { - const auto& callbacks = keyCallbacks.find(static_cast(key)); - if (callbacks != keyCallbacks.end()) { - callbacks->second.notify(); - } - } - if (pressed && key < MOUSE_KEYS_OFFSET) { - pressedKeys.push_back(static_cast(key)); - } - } - - void onMouseCallback(int button, bool pressed) { - int key = button + MOUSE_KEYS_OFFSET; - onKeyCallback(key, pressed); - } - - bool isCursorLocked() const override { - return cursorLocked; - } - - void setCursorPosition(double xpos, double ypos) { - if (cursorDrag) { - delta.x += xpos - cursor.x; - delta.y += ypos - cursor.y; - } else { - cursorDrag = true; - } - cursor.x = xpos; - cursor.y = ypos; - } - - Bindings& getBindings() override { - return bindings; - } - - const Bindings& getBindings() const override { - return bindings; - } - - ObserverHandler addKeyCallback(Keycode key, InputCallback callback) override { - return keyCallbacks[key].add(std::move(callback)); - } - - ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) override { - return addKeyCallback( - static_cast(MOUSE_KEYS_OFFSET + static_cast(button)), - std::move(callback) - ); - } - - const std::vector& getPressedKeys() const override { - return pressedKeys; - } - - const std::vector& getCodepoints() const override { - return codepoints; - } - - CursorState getCursor() const override { - return {isCursorLocked(), cursor, delta}; - } - - int getScroll() override { - return scroll; - } - - bool pressed(Keycode key) const override { - int keycode = static_cast(key); - if (keycode < 0 || keycode >= KEYS_BUFFER_SIZE) { - return false; - } - return keys[keycode]; - } - bool jpressed(Keycode keycode) const override { - return pressed(keycode) && - frames[static_cast(keycode)] == currentFrame; - } - - bool clicked(Mousecode code) const override { - return pressed( - static_cast(MOUSE_KEYS_OFFSET + static_cast(code)) - ); - } - bool jclicked(Mousecode code) const override { - return clicked(code) && - frames[static_cast(code) + MOUSE_KEYS_OFFSET] == - currentFrame; - } - - void simulateKey(Keycode key, bool pressed) override { - onKeyCallback(static_cast(key), pressed); - } - - void simulateClick(int button, bool pressed) override { - onMouseCallback(static_cast(button), pressed); - } - - void simulateCursorPos(double xpos, double ypos) override { - setCursorPosition(xpos, ypos); - } - - void simulateCodepoint(uint codepoint) override { - codepoints.push_back(codepoint); - } -protected: - uint currentFrame = 0; - uint frames[KEYS_BUFFER_SIZE] {}; - std::vector pressedKeys; - Bindings bindings; - bool keys[KEYS_BUFFER_SIZE] {}; - std::unordered_map> keyCallbacks; - bool cursorLocked = false; - bool cursorDrag = false; - glm::vec2 delta {}; - glm::vec2 cursor {}; -}; - class GLFWInput : public BaseInput { public: GLFWInput(GLFWwindow* window) @@ -301,48 +192,14 @@ public: } void pollEvents(bool waitForRefresh) override { - delta.x = 0.0f; - delta.y = 0.0f; - scroll = 0; - currentFrame++; - codepoints.clear(); - pressedKeys.clear(); + beginFrame(); if (waitForRefresh) { glfwWaitEventsTimeout(0.5); } else { glfwPollEvents(); } - for (auto& [_, binding] : bindings.getAll()) { - if (!binding.enabled) { - binding.state = false; - continue; - } - binding.justChanged = false; - - bool newstate = false; - switch (binding.type) { - case InputType::KEYBOARD: - newstate = pressed(static_cast(binding.code)); - break; - case InputType::MOUSE: - newstate = clicked(static_cast(binding.code)); - break; - } - - if (newstate) { - if (!binding.state) { - binding.state = true; - binding.justChanged = true; - binding.onactived.notify(); - } - } else { - if (binding.state) { - binding.state = false; - binding.justChanged = true; - } - } - } + updateBindings(); } const char* getClipboardText() const override { @@ -455,7 +312,7 @@ public: void setMode(WindowMode mode) override { Window::mode = mode; - GLFWmonitor* monitor = glfwGetPrimaryMonitor(); + GLFWmonitor* monitor = get_window_monitor(window); const GLFWvidmode* glfwMode = glfwGetVideoMode(monitor); if (input.isCursorLocked()){ @@ -507,6 +364,10 @@ public: glfwSetWindowTitle(window, title.c_str()); } + bool isIconSupported() const override { + return true; + } + void setIcon(const ImageData* image) override { if (image == nullptr) { glfwSetWindowIcon(window, 0, nullptr); @@ -709,7 +570,7 @@ static void setup_callbacks(GLFWwindow* window) { std::tuple< std::unique_ptr, std::unique_ptr -> Window::initialize(DisplaySettings* settings, std::string title) { +> glfw_window_initialize(DisplaySettings* settings, std::string title) { int width = settings->width.get(); int height = settings->height.get(); @@ -718,6 +579,7 @@ std::tuple< logger.error() << "failed to initialize GLFW"; return {nullptr, nullptr}; } + logger.info() << "windowing platform: " << get_platform_name(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); @@ -782,7 +644,6 @@ std::tuple< setup_callbacks(window); glfwSwapInterval(1); - input_util::initialize(); create_standard_cursors(); glm::vec2 scale; diff --git a/src/window/detail/WaylandWindow.cpp b/src/window/detail/WaylandWindow.cpp new file mode 100644 index 000000000..0d110820d --- /dev/null +++ b/src/window/detail/WaylandWindow.cpp @@ -0,0 +1,2421 @@ +#include "window/Window.hpp" +#include "window/detail/BaseInput.hpp" +#include "window/detail/WindowBackends.hpp" + +#include "debug/Logger.hpp" +#include "graphics/core/ImageData.hpp" +#include "graphics/core/Texture.hpp" +#include "settings.hpp" +#include "util/platform.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "cursor-shape-v1-client-protocol.h" +#include "idle-inhibit-unstable-v1-client-protocol.h" +#include "pointer-constraints-unstable-v1-client-protocol.h" +#include "relative-pointer-unstable-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +static debug::Logger logger("window"); + +struct WaylandState { + wl_display* display = nullptr; + wl_registry* registry = nullptr; + wl_compositor* compositor = nullptr; + wl_surface* surface = nullptr; + xdg_wm_base* wmBase = nullptr; + xdg_surface* xdgSurface = nullptr; + xdg_toplevel* toplevel = nullptr; + zxdg_toplevel_decoration_v1* decoration = nullptr; + wl_seat* seat = nullptr; + wl_pointer* pointer = nullptr; + wl_keyboard* keyboard = nullptr; + wl_data_device_manager* dataDeviceManager = nullptr; + wl_data_device* dataDevice = nullptr; + wp_cursor_shape_manager_v1* cursorShapeManager = nullptr; + wp_cursor_shape_device_v1* cursorShapeDevice = nullptr; + zwp_pointer_constraints_v1* pointerConstraints = nullptr; + zwp_relative_pointer_manager_v1* relativePointerManager = nullptr; + zwp_relative_pointer_v1* relativePointer = nullptr; + zwp_locked_pointer_v1* lockedPointer = nullptr; + zwp_idle_inhibit_manager_v1* idleInhibitManager = nullptr; + zwp_idle_inhibitor_v1* idleInhibitor = nullptr; + zxdg_decoration_manager_v1* decorationManager = nullptr; + xkb_context* xkbContext = nullptr; + xkb_keymap* xkbKeymap = nullptr; + xkb_state* xkbState = nullptr; + uint32_t pointerSerial = 0; + uint32_t inputSerial = 0; + uint32_t repeatRate = 25; + uint32_t repeatDelay = 400; + bool entered = false; +}; + +static WaylandState state; + +class WaylandInput; +class WaylandWindow; + +static WaylandInput* input = nullptr; +static WaylandWindow* window = nullptr; + +template +static void ignore_event(Args...) { +} + +static bool decorations_enabled() { + const char* value = getenv("VOXEL_DECORATIONS"); + return value == nullptr || strcmp(value, "none") != 0; +} + +static constexpr int BAR_HEIGHT = 30; +static constexpr int BAR_BUTTON = 30; +static constexpr int BAR_EDGE = 5; +static constexpr int BAR_ICON_SIZE = 16; +static constexpr int BAR_FONT_W = 8; +static constexpr int BAR_FONT_H = 8; +static constexpr int BAR_GLYPHS = 159; + +static const uint8_t BAR_FONT[BAR_GLYPHS][BAR_FONT_H] { + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x50, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x14, 0x14, 0x7e, 0x28, 0xfe, 0x28, 0x68}, + {0x00, 0x10, 0x78, 0x70, 0x78, 0x7c, 0x1c, 0x78}, + {0x00, 0x62, 0xf4, 0xfc, 0x6b, 0x1f, 0x17, 0x23}, + {0x00, 0x38, 0x60, 0x30, 0x7a, 0xde, 0x6c, 0x7e}, + {0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x20, 0x60, 0x60, 0x40, 0x40, 0x60, 0x60, 0x20}, + {0x40, 0x60, 0x20, 0x20, 0x20, 0x20, 0x60, 0x40}, + {0x00, 0x20, 0xf0, 0x70, 0xf0, 0x20, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x10, 0x10, 0x7e, 0x10, 0x10}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x40}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60}, + {0x00, 0x20, 0x20, 0x60, 0x40, 0x40, 0xc0, 0x80}, + {0x00, 0x38, 0x6c, 0xcc, 0xcc, 0xcc, 0x6c, 0x38}, + {0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x7c}, + {0x00, 0x78, 0x18, 0x18, 0x18, 0x30, 0x60, 0x7c}, + {0x00, 0x78, 0x18, 0x18, 0x38, 0x1c, 0x1c, 0xf8}, + {0x00, 0x18, 0x38, 0x78, 0x58, 0xd8, 0xfc, 0x18}, + {0x00, 0x78, 0x40, 0x40, 0x78, 0x0c, 0x0c, 0x78}, + {0x00, 0x38, 0x60, 0x40, 0xf8, 0x6c, 0x6c, 0x38}, + {0x00, 0xfc, 0x18, 0x18, 0x18, 0x30, 0x30, 0x60}, + {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x78}, + {0x00, 0x78, 0xc8, 0xcc, 0x7c, 0x0c, 0x18, 0x70}, + {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x00, 0x00, 0x06, 0x3c, 0x60, 0x3c, 0x06}, + {0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00}, + {0x00, 0x00, 0x00, 0x60, 0x3c, 0x0e, 0x3c, 0x60}, + {0x00, 0x70, 0x18, 0x30, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x1e, 0x63, 0x5d, 0x55, 0x57, 0x5e, 0x62}, + {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, + {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, + {0x00, 0x7c, 0x6e, 0x66, 0x66, 0x66, 0x6e, 0x7c}, + {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, + {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x60}, + {0x00, 0x3c, 0x62, 0xc0, 0xce, 0xc6, 0x66, 0x3e}, + {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x6e, 0x7c, 0x78, 0x70, 0x78, 0x6c, 0x66}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7c}, + {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, + {0x00, 0x66, 0x76, 0x76, 0x7e, 0x7e, 0x6e, 0x6e}, + {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, + {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, + {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, + {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x66}, + {0x00, 0x78, 0x68, 0x60, 0x78, 0x0c, 0x4c, 0x78}, + {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0x3c}, + {0x00, 0xc6, 0xc6, 0x6c, 0x6c, 0x78, 0x38, 0x38}, + {0x00, 0xcc, 0xcc, 0x7d, 0x7f, 0x77, 0x73, 0x33}, + {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, + {0x00, 0xcc, 0x6c, 0x78, 0x38, 0x30, 0x30, 0x30}, + {0x00, 0xfc, 0x1c, 0x18, 0x30, 0x70, 0x60, 0xfc}, + {0x70, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x70}, + {0x00, 0x80, 0xc0, 0x40, 0x40, 0x60, 0x20, 0x20}, + {0xe0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe0}, + {0x00, 0x38, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x40, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, + {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, + {0x0c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, + {0x70, 0x60, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, + {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, + {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x40, 0x40, 0x40, 0x4c, 0x78, 0x70, 0x78, 0x4c}, + {0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x00, 0x00, 0x00, 0x7f, 0x6d, 0x4d, 0x4d, 0x4d}, + {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, + {0x00, 0x00, 0x00, 0x78, 0x60, 0x40, 0x40, 0x40}, + {0x00, 0x00, 0x00, 0x78, 0xe0, 0x78, 0x18, 0xf8}, + {0x00, 0x00, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x70}, + {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x6c, 0x7c}, + {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x70, 0x30}, + {0x00, 0x00, 0x00, 0xdb, 0x5b, 0x7e, 0x7e, 0x76}, + {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, + {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, + {0x00, 0x00, 0x00, 0xf8, 0x38, 0x30, 0x60, 0xf8}, + {0x18, 0x30, 0x30, 0x70, 0x30, 0x30, 0x30, 0x18}, + {0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x70, 0x30, 0x30, 0x18, 0x30, 0x30, 0x30, 0x70}, + {0x00, 0x00, 0x00, 0x00, 0x72, 0x1c, 0x00, 0x00}, + {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, + {0x00, 0x7c, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x7c, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x3e, 0x36, 0x36, 0x36, 0x26, 0x66, 0xff}, + {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, + {0x00, 0x64, 0x35, 0x3f, 0x3f, 0x3f, 0x64, 0xc4}, + {0x00, 0x78, 0x0c, 0x0c, 0x38, 0x0c, 0x0c, 0xf8}, + {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, + {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, + {0x00, 0x66, 0x6c, 0x78, 0x78, 0x7c, 0x6c, 0x66}, + {0x00, 0x3e, 0x36, 0x36, 0x36, 0x36, 0x66, 0xc6}, + {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, + {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, + {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, + {0x00, 0x7e, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}, + {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, + {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, + {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, + {0x00, 0xc6, 0x6c, 0x7c, 0x38, 0x38, 0x30, 0x70}, + {0x00, 0x18, 0x7e, 0x7b, 0xd9, 0x7b, 0x7e, 0x18}, + {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, + {0x00, 0x66, 0x66, 0x66, 0x7e, 0x06, 0x06, 0x06}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, + {0x00, 0x70, 0xf0, 0x30, 0x3e, 0x3b, 0x3b, 0x3e}, + {0x00, 0x61, 0x61, 0x61, 0x7d, 0x6d, 0x6d, 0x7d}, + {0x00, 0x60, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x70, 0xf8, 0x0c, 0x7c, 0x0c, 0x1c, 0x78}, + {0x00, 0x67, 0x6c, 0x78, 0x78, 0x78, 0x6c, 0x67}, + {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x3c, 0x6c, 0x6c}, + {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, + {0x38, 0x40, 0xc0, 0xf8, 0xec, 0xcc, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x48, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x40, 0x40, 0x40, 0x40}, + {0x00, 0x00, 0x00, 0x3c, 0x2c, 0x6c, 0x6c, 0xfe}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, + {0x00, 0x00, 0x00, 0x6b, 0x3e, 0x3e, 0x7f, 0xc9}, + {0x00, 0x00, 0x00, 0x70, 0x18, 0x70, 0x18, 0xf0}, + {0x00, 0x00, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, + {0x00, 0x30, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, + {0x00, 0x00, 0x00, 0x58, 0x70, 0x70, 0x78, 0x4c}, + {0x00, 0x00, 0x00, 0x7c, 0x6c, 0x6c, 0x6c, 0xcc}, + {0x00, 0x00, 0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x46}, + {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x7c, 0x4c, 0x4c}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, + {0x00, 0x00, 0x00, 0x7c, 0x4c, 0x4c, 0x4c, 0x4c}, + {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, + {0x00, 0x00, 0x00, 0xf8, 0x30, 0x30, 0x30, 0x30}, + {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, + {0x08, 0x08, 0x08, 0x7f, 0x7b, 0xc9, 0x7b, 0x7f}, + {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, + {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x7c}, + {0x00, 0x00, 0x00, 0xd8, 0xd8, 0x78, 0x18, 0x18}, + {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, + {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, + {0x00, 0x00, 0x00, 0xf0, 0x30, 0x3c, 0x34, 0x3c}, + {0x00, 0x00, 0x00, 0x43, 0x43, 0x7b, 0x4f, 0x7b}, + {0x00, 0x00, 0x00, 0x40, 0x40, 0x78, 0x48, 0x78}, + {0x00, 0x00, 0x00, 0x70, 0x18, 0x78, 0x18, 0x70}, + {0x00, 0x00, 0x00, 0x4e, 0x5b, 0x79, 0x5b, 0x4e}, + {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x78, 0xd8}, +}; + +static int bar_glyph_index(uint32_t codepoint) { + if (codepoint >= 32 && codepoint < 127) { + return static_cast(codepoint) - 32; + } + if (codepoint >= 0x410 && codepoint <= 0x44F) { + return 95 + static_cast(codepoint - 0x410); + } + if (codepoint == 0x401) { + return 95 + 6; + } + if (codepoint == 0x451) { + return 95 + 37; + } + return -1; +} + +static std::vector decode_utf8(const std::string& text) { + std::vector codepoints; + for (size_t i = 0; i < text.size();) { + const uint8_t byte = static_cast(text[i]); + uint32_t codepoint = byte; + size_t length = 1; + if ((byte & 0xE0) == 0xC0) { + codepoint = byte & 0x1F; + length = 2; + } else if ((byte & 0xF0) == 0xE0) { + codepoint = byte & 0x0F; + length = 3; + } else if ((byte & 0xF8) == 0xF0) { + codepoint = byte & 0x07; + length = 4; + } + if (i + length > text.size()) { + break; + } + for (size_t k = 1; k < length; k++) { + codepoint = + (codepoint << 6) | (static_cast(text[i + k]) & 0x3F); + } + codepoints.push_back(codepoint); + i += length; + } + return codepoints; +} + +static GLuint compile_program(const char* vertexSource, const char* fragmentSource) { + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertexShader, 1, &vertexSource, nullptr); + glCompileShader(vertexShader); + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); + glCompileShader(fragmentShader); + GLuint program = glCreateProgram(); + glAttachShader(program, vertexShader); + glAttachShader(program, fragmentShader); + glLinkProgram(program); + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + return program; +} + +static void push_quad( + std::vector& target, float x, float y, float w, float h, float u0, + float v0, float u1, float v1, const glm::vec4& color +) { + const float x1 = x + w; + const float y1 = y + h; + const float vertices[] { + x, y, u0, v0, color.r, color.g, color.b, color.a, + x1, y, u1, v0, color.r, color.g, color.b, color.a, + x, y1, u0, v1, color.r, color.g, color.b, color.a, + x1, y, u1, v0, color.r, color.g, color.b, color.a, + x1, y1, u1, v1, color.r, color.g, color.b, color.a, + x, y1, u0, v1, color.r, color.g, color.b, color.a + }; + target.insert(target.end(), vertices, vertices + 48); +} + +static bool serverDecorations = false; + +static void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +); + +static void on_display_error(); + +static int keycode_from_keysym(xkb_keysym_t sym) { + switch (sym) { + case XKB_KEY_Escape: return GLFW_KEY_ESCAPE; + case XKB_KEY_Return: return GLFW_KEY_ENTER; + case XKB_KEY_Tab: return GLFW_KEY_TAB; + case XKB_KEY_BackSpace: return GLFW_KEY_BACKSPACE; + case XKB_KEY_Insert: return GLFW_KEY_INSERT; + case XKB_KEY_Delete: return GLFW_KEY_DELETE; + case XKB_KEY_Left: return GLFW_KEY_LEFT; + case XKB_KEY_Right: return GLFW_KEY_RIGHT; + case XKB_KEY_Up: return GLFW_KEY_UP; + case XKB_KEY_Down: return GLFW_KEY_DOWN; + case XKB_KEY_Page_Up: return GLFW_KEY_PAGE_UP; + case XKB_KEY_Page_Down: return GLFW_KEY_PAGE_DOWN; + case XKB_KEY_Home: return GLFW_KEY_HOME; + case XKB_KEY_End: return GLFW_KEY_END; + case XKB_KEY_Caps_Lock: return GLFW_KEY_CAPS_LOCK; + case XKB_KEY_Scroll_Lock: return GLFW_KEY_SCROLL_LOCK; + case XKB_KEY_Num_Lock: return GLFW_KEY_NUM_LOCK; + case XKB_KEY_Print: return GLFW_KEY_PRINT_SCREEN; + case XKB_KEY_Pause: return GLFW_KEY_PAUSE; + case XKB_KEY_Menu: return GLFW_KEY_MENU; + case XKB_KEY_Shift_L: return GLFW_KEY_LEFT_SHIFT; + case XKB_KEY_Control_L: return GLFW_KEY_LEFT_CONTROL; + case XKB_KEY_Alt_L: return GLFW_KEY_LEFT_ALT; + case XKB_KEY_Super_L: return GLFW_KEY_LEFT_SUPER; + case XKB_KEY_Shift_R: return GLFW_KEY_RIGHT_SHIFT; + case XKB_KEY_Control_R: return GLFW_KEY_RIGHT_CONTROL; + case XKB_KEY_Alt_R: return GLFW_KEY_RIGHT_ALT; + case XKB_KEY_Super_R: return GLFW_KEY_RIGHT_SUPER; + case XKB_KEY_space: return GLFW_KEY_SPACE; + case XKB_KEY_apostrophe: return GLFW_KEY_APOSTROPHE; + case XKB_KEY_comma: return GLFW_KEY_COMMA; + case XKB_KEY_minus: return GLFW_KEY_MINUS; + case XKB_KEY_period: return GLFW_KEY_PERIOD; + case XKB_KEY_slash: return GLFW_KEY_SLASH; + case XKB_KEY_semicolon: return GLFW_KEY_SEMICOLON; + case XKB_KEY_equal: return GLFW_KEY_EQUAL; + case XKB_KEY_bracketleft: return GLFW_KEY_LEFT_BRACKET; + case XKB_KEY_backslash: return GLFW_KEY_BACKSLASH; + case XKB_KEY_bracketright: return GLFW_KEY_RIGHT_BRACKET; + case XKB_KEY_grave: return GLFW_KEY_GRAVE_ACCENT; + case XKB_KEY_KP_0: return GLFW_KEY_KP_0; + case XKB_KEY_KP_1: return GLFW_KEY_KP_1; + case XKB_KEY_KP_2: return GLFW_KEY_KP_2; + case XKB_KEY_KP_3: return GLFW_KEY_KP_3; + case XKB_KEY_KP_4: return GLFW_KEY_KP_4; + case XKB_KEY_KP_5: return GLFW_KEY_KP_5; + case XKB_KEY_KP_6: return GLFW_KEY_KP_6; + case XKB_KEY_KP_7: return GLFW_KEY_KP_7; + case XKB_KEY_KP_8: return GLFW_KEY_KP_8; + case XKB_KEY_KP_9: return GLFW_KEY_KP_9; + case XKB_KEY_KP_Decimal: return GLFW_KEY_KP_DECIMAL; + case XKB_KEY_KP_Divide: return GLFW_KEY_KP_DIVIDE; + case XKB_KEY_KP_Multiply: return GLFW_KEY_KP_MULTIPLY; + case XKB_KEY_KP_Subtract: return GLFW_KEY_KP_SUBTRACT; + case XKB_KEY_KP_Add: return GLFW_KEY_KP_ADD; + case XKB_KEY_KP_Enter: return GLFW_KEY_KP_ENTER; + case XKB_KEY_KP_Equal: return GLFW_KEY_KP_EQUAL; + } + if (sym >= XKB_KEY_a && sym <= XKB_KEY_z) { + return GLFW_KEY_A + (sym - XKB_KEY_a); + } + if (sym >= XKB_KEY_A && sym <= XKB_KEY_Z) { + return GLFW_KEY_A + (sym - XKB_KEY_A); + } + if (sym >= XKB_KEY_0 && sym <= XKB_KEY_9) { + return GLFW_KEY_0 + (sym - XKB_KEY_0); + } + if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F12) { + return GLFW_KEY_F1 + (sym - XKB_KEY_F1); + } + return 0; +} + +static void dispatch_events(int timeoutMs) { + wl_display_flush(state.display); + while (wl_display_prepare_read(state.display) != 0) { + wl_display_dispatch_pending(state.display); + wl_display_flush(state.display); + } + pollfd descriptor {wl_display_get_fd(state.display), POLLIN, 0}; + if (poll(&descriptor, 1, timeoutMs) > 0) { + if (wl_display_read_events(state.display) == -1) { + wl_display_cancel_read(state.display); + } + } else { + wl_display_cancel_read(state.display); + } + wl_display_dispatch_pending(state.display); + if (wl_display_get_error(state.display) != 0) { + on_display_error(); + } +} + +class WaylandInput : public BaseInput { +public: + void pollEvents(bool waitForRefresh) override; + + const char* getClipboardText() const override { + if (state.dataDevice == nullptr || selection == nullptr) { + return clipboard.c_str(); + } + const char* mime = pickMime(); + if (mime == nullptr) { + return clipboard.c_str(); + } + int fds[2]; + if (pipe(fds) == -1) { + return clipboard.c_str(); + } + wl_data_offer_receive(selection, mime, fds[1]); + close(fds[1]); + wl_display_flush(state.display); + + clipboard.clear(); + char buffer[4096]; + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(500); + while (std::chrono::steady_clock::now() < deadline) { + pollfd descriptor {fds[0], POLLIN, 0}; + if (poll(&descriptor, 1, 50) <= 0) { + wl_display_dispatch_pending(state.display); + continue; + } + ssize_t length = read(fds[0], buffer, sizeof(buffer)); + if (length <= 0) { + break; + } + clipboard.append(buffer, length); + } + close(fds[0]); + return clipboard.c_str(); + } + + void setClipboardText(const char* text) override { + if (state.dataDeviceManager == nullptr || state.dataDevice == nullptr) { + return; + } + auto* source = wl_data_device_manager_create_data_source( + state.dataDeviceManager + ); + wl_data_source_add_listener(source, &sourceListener(), nullptr); + wl_data_source_offer(source, "text/plain;charset=utf-8"); + wl_data_source_offer(source, "text/plain"); + wl_data_source_offer(source, "UTF8_STRING"); + sourceText = text ? text : ""; + wl_data_device_set_selection(state.dataDevice, source, state.inputSerial); + wl_display_flush(state.display); + } + + void toggleCursor() override { + cursorDrag = false; + if (cursorLocked) { + if (state.lockedPointer) { + zwp_locked_pointer_v1_destroy(state.lockedPointer); + state.lockedPointer = nullptr; + } + if (state.relativePointer) { + zwp_relative_pointer_v1_destroy(state.relativePointer); + state.relativePointer = nullptr; + } + cursorLocked = false; + applyCursor(); + return; + } + if (state.pointerConstraints && state.pointer && state.surface) { + state.lockedPointer = zwp_pointer_constraints_v1_lock_pointer( + state.pointerConstraints, + state.surface, + state.pointer, + nullptr, + ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT + ); + } + if (state.relativePointerManager && state.pointer) { + state.relativePointer = + zwp_relative_pointer_manager_v1_get_relative_pointer( + state.relativePointerManager, state.pointer + ); + zwp_relative_pointer_v1_add_listener( + state.relativePointer, &relativePointerListener(), nullptr + ); + } + if (state.pointer && state.entered) { + wl_pointer_set_cursor( + state.pointer, state.pointerSerial, nullptr, 0, 0 + ); + } + cursorLocked = true; + } + + void setCursorShape(CursorShape shape) { + if (cursor == shape) { + return; + } + cursor = shape; + applyCursor(); + } + + void applyCursor() { + if (cursorLocked || !state.entered || !state.cursorShapeDevice) { + return; + } + wp_cursor_shape_device_v1_set_shape( + state.cursorShapeDevice, state.pointerSerial, + shapeId(overrideCursor ? *overrideCursor : cursor) + ); + } + + void setOverrideCursor(std::optional shape) { + if (overrideCursor == shape) { + return; + } + overrideCursor = shape; + applyCursor(); + } + + void onRelativeMotion(double dx, double dy) { + delta.x += dx; + delta.y += dy; + } + + void onKey(uint32_t key, bool pressed) { + if (state.xkbState == nullptr || state.xkbKeymap == nullptr) { + return; + } + xkb_keycode_t code = key + 8; + const xkb_keysym_t* syms = nullptr; + if (xkb_keymap_key_get_syms_by_level( + state.xkbKeymap, code, 0, 0, &syms + ) > 0) { + int keycode = keycode_from_keysym(syms[0]); + if (keycode != 0) { + onKeyCallback(keycode, pressed); + } + if (pressed) { + repeatKeycode = code; + repeatTime = now(); + lastRepeat = repeatTime; + } else if (code == repeatKeycode) { + repeatKeycode = 0; + } + } + if (pressed) { + appendCodepoints(code); + } + xkb_state_update_key( + state.xkbState, code, pressed ? XKB_KEY_DOWN : XKB_KEY_UP + ); + } + + void refreshWindow(); + + wl_data_offer* selection = nullptr; + std::vector selectionMimes; + std::vector pendingMimes; + mutable std::string clipboard; + std::string sourceText; +private: + static uint32_t shapeId(CursorShape shape) { + switch (shape) { + case CursorShape::ARROW: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + case CursorShape::TEXT: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT; + case CursorShape::CROSSHAIR: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR; + case CursorShape::POINTER: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER; + case CursorShape::EW_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE; + case CursorShape::NS_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE; + case CursorShape::NWSE_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE; + case CursorShape::NESW_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE; + case CursorShape::ALL_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE; + case CursorShape::NOT_ALLOWED: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED; + } + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + } + + static void dispatch(bool block) { + dispatch_events(block ? 500 : 0); + } + + static double now() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); + } + + void appendCodepoints(xkb_keycode_t code) { + char buffer[64]; + int length = xkb_state_key_get_utf8( + state.xkbState, code, buffer, sizeof(buffer) + ); + if (length <= 0) { + return; + } + const auto* bytes = reinterpret_cast(buffer); + uint codepoint = 0; + for (int i = 0; i < length; i++) { + if ((bytes[i] & 0xC0) == 0x80) { + codepoint = (codepoint << 6) | (bytes[i] & 0x3F); + continue; + } + if (codepoint != 0) { + codepoints.push_back(codepoint); + } + codepoint = (bytes[i] & 0x80) ? (bytes[i] & 0x1F) : bytes[i]; + } + if (codepoint != 0) { + codepoints.push_back(codepoint); + } + } + + void updateRepeat() { + if (repeatKeycode == 0 || !state.xkbState) { + return; + } + int keycode = 0; + const xkb_keysym_t* syms = nullptr; + if (xkb_keymap_key_get_syms_by_level( + state.xkbKeymap, repeatKeycode, 0, 0, &syms + ) > 0) { + keycode = keycode_from_keysym(syms[0]); + } + if (keycode == 0 || !pressed(static_cast(keycode))) { + return; + } + double time = now(); + if (time - repeatTime < state.repeatDelay / 1000.0) { + return; + } + double interval = 1.0 / std::max(state.repeatRate, 1); + if (time - lastRepeat < interval) { + return; + } + lastRepeat = time; + onKeyCallback(keycode, true); + appendCodepoints(repeatKeycode); + } + + const char* pickMime() const { + for (const auto& mime : selectionMimes) { + if (mime == "text/plain;charset=utf-8" || mime == "text/plain" || + mime == "UTF8_STRING") { + return mime.c_str(); + } + } + return nullptr; + } + + static const wl_data_source_listener& sourceListener() { + static wl_data_source_listener listener {}; + static bool initialized = false; + if (!initialized) { + initialized = true; + listener.send = [] ( + void*, wl_data_source*, const char*, int32_t fd + ) { + if (input) { + const std::string& text = input->sourceText; + if (!text.empty() && write(fd, text.data(), text.size()) < 0) { + logger.warning() << "could not write to the clipboard"; + } + } + close(fd); + }; + listener.cancelled = [] (void*, wl_data_source* source) { + wl_data_source_destroy(source); + }; + listener.target = ignore_event<>; + listener.dnd_drop_performed = ignore_event<>; + listener.dnd_finished = ignore_event<>; + listener.action = ignore_event<>; + } + return listener; + } + + static const zwp_relative_pointer_v1_listener& relativePointerListener() { + static zwp_relative_pointer_v1_listener listener {}; + static bool initialized = false; + if (!initialized) { + initialized = true; + listener.relative_motion = [] ( + void*, zwp_relative_pointer_v1*, uint32_t, uint32_t, + wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t, wl_fixed_t + ) { + if (input) { + input->onRelativeMotion( + wl_fixed_to_double(dx), wl_fixed_to_double(dy) + ); + } + }; + } + return listener; + } + + CursorShape cursor = CursorShape::ARROW; + std::optional overrideCursor; + xkb_keycode_t repeatKeycode = 0; + double repeatTime = 0.0; + double lastRepeat = 0.0; +}; + +class WaylandWindow : public Window { +public: + WaylandInput& input; + DisplaySettings* settings; + + WaylandWindow( + WaylandInput& input, DisplaySettings* settings, int width, int height + ) + : Window({width, height}), input(input), settings(settings) { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); + } + + ~WaylandWindow() override { + if (state.idleInhibitor) { + zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); + } + if (state.lockedPointer) { + zwp_locked_pointer_v1_destroy(state.lockedPointer); + } + if (state.relativePointer) { + zwp_relative_pointer_v1_destroy(state.relativePointer); + } + if (state.cursorShapeDevice) { + wp_cursor_shape_device_v1_destroy(state.cursorShapeDevice); + } + if (frameCallback) { + wl_callback_destroy(frameCallback); + frameCallback = nullptr; + } + if (cacheTexture) { + glDeleteTextures(1, &cacheTexture); + } + if (cacheFbo) { + glDeleteFramebuffers(1, &cacheFbo); + } + if (stretchProgram) { + glDeleteProgram(stretchProgram); + } + if (stretchVbo) { + glDeleteBuffers(1, &stretchVbo); + } + if (stretchVao) { + glDeleteVertexArrays(1, &stretchVao); + } + if (barFontTexture) { + glDeleteTextures(1, &barFontTexture); + } + if (barIconTexture) { + glDeleteTextures(1, &barIconTexture); + } + if (barProgram) { + glDeleteProgram(barProgram); + } + if (barVbo) { + glDeleteBuffers(1, &barVbo); + } + if (barVao) { + glDeleteVertexArrays(1, &barVao); + } + if (state.dataDevice) { + wl_data_device_destroy(state.dataDevice); + } + if (state.decoration) { + zxdg_toplevel_decoration_v1_destroy(state.decoration); + } + if (state.toplevel) { + xdg_toplevel_destroy(state.toplevel); + } + if (state.xdgSurface) { + xdg_surface_destroy(state.xdgSurface); + } + if (eglSurface != EGL_NO_SURFACE) { + eglDestroySurface(eglDisplay, eglSurface); + } + if (eglWindow) { + wl_egl_window_destroy(eglWindow); + } + if (state.surface) { + wl_surface_destroy(state.surface); + } + if (eglContext != EGL_NO_CONTEXT) { + eglDestroyContext(eglDisplay, eglContext); + } + if (eglDisplay != EGL_NO_DISPLAY) { + eglTerminate(eglDisplay); + } + } + + double time() override { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); + } + + void swapBuffers() override { + updateResizing(); + if (resizing && !presentPending && !frameDone) { + resetScissor(); + return; + } + if (resizing) { + if (renderPending) { + cacheContent(); + renderPending = false; + } else { + drawStretched(); + } + } else { + cacheContent(); + } + drawBar(); + requestFrame(); + eglSwapBuffers(eglDisplay, eglSurface); + resetScissor(); + frameDone = false; + presentPending = false; + const double current = now(); + if (lastPresent > 0.0) { + const double interval = current - lastPresent; + if (interval > 0.001 && interval < 1.0 && !resizing && + frameOnCallback) { + frameInterval = std::clamp( + frameInterval > 0.0 ? frameInterval * 0.8 + interval * 0.2 + : interval, + 1.0 / 240.0, + 1.0 / 30.0 + ); + } + if (resizeLogging) { + summarySum += interval; + summaryMax = std::max(summaryMax, interval); + } + } + lastPresent = current; + nextFrameTime = current + frameInterval; + if (resizeLogging) { + summaryFrames++; + } + if (resizing) { + const double elapsed = now() - configureTime; + resizeTimeSum += elapsed; + resizeTimeMax = std::max(resizeTimeMax, elapsed); + resizePresents++; + } + lastSwapEnd = now(); + if (framerate > 0 && !resizing) { + auto elapsed = time() - prevSwap; + auto frameTime = 1.0 / framerate; + if (elapsed < frameTime) { + platform::sleep( + static_cast((frameTime - elapsed) * 1000) + ); + } + } + prevSwap = time(); + } + + void setShouldRefresh() override { + shouldRefresh = true; + } + + bool checkShouldRefresh() override { + if (shouldRefresh) { + shouldRefresh = false; + return true; + } + return false; + } + + bool isMaximized() const override { + return maximized; + } + + bool isFocused() const override { + return activated; + } + + bool isIconified() const override { + return suspended; + } + + bool isFrameRequired() const override { + return !resizing || renderPending; + } + + bool isShouldClose() const override { + return shouldClose; + } + + void setShouldClose(bool flag) override { + shouldClose = flag; + } + + void setCursor(CursorShape shape) override { + input.setCursorShape(shape); + } + + void setMode(WindowMode mode) override { + Window::mode = mode; + if (input.isCursorLocked()) { + input.toggleCursor(); + } + switch (mode) { + case WindowMode::FULLSCREEN: + setFullscreen(true); + setIdleInhibit(true); + break; + case WindowMode::BORDERLESS: + setFullscreen(false); + setMaximized(true); + setIdleInhibit(true); + break; + case WindowMode::WINDOWED: + setFullscreen(false); + setMaximized(false); + setIdleInhibit(false); + resize(settings->width.get(), settings->height.get()); + break; + } + wl_surface_commit(state.surface); + } + + WindowMode getMode() const override { + return mode; + } + + void focus() override { + if (!focusWarning) { + focusWarning = true; + logger.warning() << "raising windows is not allowed on Wayland"; + } + } + + void setTitle(const std::string& title) override { + this->title = title; + xdg_toplevel_set_title(state.toplevel, title.c_str()); + } + + void setFullscreen(bool enabled) { + fullscreen = enabled; + if (enabled) { + xdg_toplevel_set_fullscreen(state.toplevel, nullptr); + } else { + xdg_toplevel_unset_fullscreen(state.toplevel); + } + } + + void setMaximized(bool enabled) { + if (enabled) { + xdg_toplevel_set_maximized(state.toplevel); + } else { + xdg_toplevel_unset_maximized(state.toplevel); + } + } + + bool isIconSupported() const override { + return true; + } + + void setIcon(const ImageData* image) override { + if (image == nullptr || image->getData() == nullptr) { + return; + } + iconWidth = static_cast(image->getWidth()); + iconHeight = static_cast(image->getHeight()); + if (iconWidth <= 0 || iconHeight <= 0) { + return; + } + const size_t pixels = static_cast(iconWidth) * iconHeight; + const bool alpha = image->getFormat() == ImageFormat::RGBA8888; + iconPixels.resize(pixels * 4); + for (size_t i = 0; i < pixels; i++) { + iconPixels[i * 4] = image->getData()[i * (alpha ? 4 : 3)]; + iconPixels[i * 4 + 1] = image->getData()[i * (alpha ? 4 : 3) + 1]; + iconPixels[i * 4 + 2] = image->getData()[i * (alpha ? 4 : 3) + 2]; + iconPixels[i * 4 + 3] = alpha ? image->getData()[i * 4 + 3] : 255; + } + if (barIconTexture != 0) { + glDeleteTextures(1, &barIconTexture); + barIconTexture = 0; + } + } + + void resize(int width, int height) { + if (width <= 0 || height <= 0) { + return; + } + if (size.x != width || size.y != height) { + markResizing(); + } + configureTime = now(); + presentPending = true; + if (eglWindow) { + wl_egl_window_resize(eglWindow, width, height, 0, 0); + } + glViewport(0, 0, width, height); + size = {width, height}; + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); + } + + void onConfigure(int32_t width, int32_t height, wl_array* states) { + pendingWidth = width; + pendingHeight = height; + stateMaximized = false; + stateSuspended = false; + stateActivated = false; + const auto* values = static_cast(states->data); + for (size_t i = 0; i < states->size / sizeof(uint32_t); i++) { + switch (values[i]) { + case XDG_TOPLEVEL_STATE_MAXIMIZED: + stateMaximized = true; + break; + case XDG_TOPLEVEL_STATE_SUSPENDED: + stateSuspended = true; + break; + case XDG_TOPLEVEL_STATE_ACTIVATED: + stateActivated = true; + break; + } + } + } + + void applyConfigure() { + if (pendingWidth > 0 && pendingHeight > 0) { + resize(pendingWidth, pendingHeight); + } + maximized = stateMaximized; + suspended = stateSuspended; + activated = stateActivated; + configured = true; + setShouldRefresh(); + } + + void pushScissor(glm::vec4 area) override { + if (scissorStack.empty()) { + glEnable(GL_SCISSOR_TEST); + } + scissorStack.push(scissorArea); + + area.z += glm::ceil(area.x); + area.w += glm::ceil(area.y); + + area.x = glm::max(area.x, scissorArea.x); + area.y = glm::max(area.y, scissorArea.y); + + area.z = glm::min(area.z, scissorArea.z); + area.w = glm::min(area.w, scissorArea.w); + + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(glm::ceil(area.z - area.x))), + std::max(0, static_cast(glm::ceil(area.w - area.y))) + ); + } + scissorArea = area; + } + + void popScissor() override { + if (scissorStack.empty()) { + logger.warning() << "extra Window::popScissor call"; + return; + } + glm::vec4 area = scissorStack.top(); + scissorStack.pop(); + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(area.z - area.x)), + std::max(0, static_cast(area.w - area.y)) + ); + } + if (scissorStack.empty()) { + glDisable(GL_SCISSOR_TEST); + } + scissorArea = area; + } + + void resetScissor() override { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); + scissorStack = std::stack(); + glDisable(GL_SCISSOR_TEST); + } + + std::unique_ptr takeScreenshot() override { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + auto data = std::make_unique(size.x * size.y * 3); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); + return std::make_unique( + ImageFormat::RGB888, size.x, size.y, data.release() + ); + } + + void setFramerate(int framerate) override { + this->framerate = framerate; + } + + void initStretchRenderer() { + static const char* vertexSource = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "out vec2 vUV;\n" + "void main() {\n" + " vUV = aPos * 0.5 + 0.5;\n" + " gl_Position = vec4(aPos, 0.0, 1.0);\n" + "}\n"; + static const char* fragmentSource = + "#version 330 core\n" + "in vec2 vUV;\n" + "out vec4 color;\n" + "uniform sampler2D uTexture;\n" + "void main() {\n" + " color = texture(uTexture, vUV);\n" + "}\n"; + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertexShader, 1, &vertexSource, nullptr); + glCompileShader(vertexShader); + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); + glCompileShader(fragmentShader); + stretchProgram = glCreateProgram(); + glAttachShader(stretchProgram, vertexShader); + glAttachShader(stretchProgram, fragmentShader); + glLinkProgram(stretchProgram); + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + + const float vertices[] {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f}; + glGenVertexArrays(1, &stretchVao); + glGenBuffers(1, &stretchVbo); + glBindVertexArray(stretchVao); + glBindBuffer(GL_ARRAY_BUFFER, stretchVbo); + glBufferData( + GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW + ); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); + glBindVertexArray(0); + glGenFramebuffers(1, &cacheFbo); + glGenTextures(1, &cacheTexture); + } + + void resizeCache(int width, int height) { + if (cacheWidth == width && cacheHeight == height) { + return; + } + cacheWidth = width; + cacheHeight = height; + glBindTexture(GL_TEXTURE_2D, cacheTexture); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, nullptr + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindFramebuffer(GL_FRAMEBUFFER, cacheFbo); + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cacheTexture, + 0 + ); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindTexture(GL_TEXTURE_2D, 0); + } + + void cacheContent() { + if (stretchProgram == 0) { + return; + } + resizeCache(size.x, size.y); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, cacheFbo); + glBlitFramebuffer( + 0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT, + GL_NEAREST + ); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + lastCacheTime = now(); + } + + void drawStretched() { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, size.x, size.y); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + if (stretchProgram == 0 || cacheWidth == 0) { + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + return; + } + glUseProgram(stretchProgram); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, cacheTexture); + glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glBindVertexArray(stretchVao); + glDrawArrays(GL_TRIANGLES, 0, 3); + glBindVertexArray(0); + glUseProgram(0); + } + + // libdecor redraws the whole decoration inside libdecor_frame_commit, + // which is also the only place where it acks the configure + void enableOwnDecorations() { + if (!decorations_enabled()) { + return; + } + barEnabled = true; + setShouldRefresh(); + } + + bool barVisible() const { + return barEnabled && !fullscreen && Window::mode != WindowMode::BORDERLESS; + } + + void initBarRenderer() { + if (barProgram != 0) { + return; + } + static const char* vertexSource = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "layout(location = 1) in vec2 aUv;\n" + "layout(location = 2) in vec4 aColor;\n" + "uniform vec2 uViewport;\n" + "out vec2 vUv;\n" + "out vec4 vColor;\n" + "void main() {\n" + " vec2 ndc = vec2(aPos.x / uViewport.x * 2.0 - 1.0," + " 1.0 - aPos.y / uViewport.y * 2.0);\n" + " gl_Position = vec4(ndc, 0.0, 1.0);\n" + " vUv = aUv;\n" + " vColor = aColor;\n" + "}\n"; + static const char* fragmentSource = + "#version 330 core\n" + "in vec2 vUv;\n" + "in vec4 vColor;\n" + "out vec4 outColor;\n" + "uniform sampler2D uTexture;\n" + "uniform int uMode;\n" + "void main() {\n" + " if (uMode == 1) {\n" + " outColor = vec4(vColor.rgb," + " vColor.a * texture(uTexture, vUv).r);\n" + " } else if (uMode == 2) {\n" + " outColor = texture(uTexture, vUv) * vColor;\n" + " } else {\n" + " outColor = vColor;\n" + " }\n" + "}\n"; + barProgram = compile_program(vertexSource, fragmentSource); + barViewportLoc = glGetUniformLocation(barProgram, "uViewport"); + barTextureLoc = glGetUniformLocation(barProgram, "uTexture"); + barModeLoc = glGetUniformLocation(barProgram, "uMode"); + glGenVertexArrays(1, &barVao); + glGenBuffers(1, &barVbo); + glBindVertexArray(barVao); + glBindBuffer(GL_ARRAY_BUFFER, barVbo); + glEnableVertexAttribArray(0); + glVertexAttribPointer( + 0, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr + ); + glEnableVertexAttribArray(1); + glVertexAttribPointer( + 1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), + reinterpret_cast(2 * sizeof(float)) + ); + glEnableVertexAttribArray(2); + glVertexAttribPointer( + 2, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), + reinterpret_cast(4 * sizeof(float)) + ); + glBindVertexArray(0); + glGenTextures(1, &barFontTexture); + glBindTexture(GL_TEXTURE_2D, barFontTexture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + std::vector pixels(BAR_GLYPHS * BAR_FONT_W * BAR_FONT_H, 0); + for (int glyph = 0; glyph < BAR_GLYPHS; glyph++) { + for (int y = 0; y < BAR_FONT_H; y++) { + for (int x = 0; x < BAR_FONT_W; x++) { + if (BAR_FONT[glyph][y] & (1 << (7 - x))) { + pixels[y * BAR_GLYPHS * BAR_FONT_W + glyph * BAR_FONT_W + x] = + 255; + } + } + } + } + glTexImage2D( + GL_TEXTURE_2D, 0, GL_R8, BAR_GLYPHS * BAR_FONT_W, BAR_FONT_H, 0, + GL_RED, GL_UNSIGNED_BYTE, pixels.data() + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindTexture(GL_TEXTURE_2D, 0); + } + + void initBarIconTexture() { + if (iconPixels.empty() || barIconTexture != 0) { + return; + } + glGenTextures(1, &barIconTexture); + glBindTexture(GL_TEXTURE_2D, barIconTexture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA8, iconWidth, iconHeight, 0, GL_RGBA, + GL_UNSIGNED_BYTE, iconPixels.data() + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindTexture(GL_TEXTURE_2D, 0); + } + + void barDrawText( + float x, float y, const std::vector& codepoints, int maxChars, + const glm::vec4& color + ) { + const float step = 1.0f / static_cast(BAR_GLYPHS * BAR_FONT_W); + float cursor = x; + for (int i = 0; i < static_cast(codepoints.size()) && i < maxChars; i++) { + const int index = bar_glyph_index(codepoints[i]); + if (index >= 0) { + push_quad( + barText, cursor, y, BAR_FONT_W, BAR_FONT_H, + index * BAR_FONT_W * step, 0.0f, + (index * BAR_FONT_W + BAR_FONT_W) * step, 1.0f, color + ); + } + cursor += BAR_FONT_W; + } + } + + void barDrawBatch(const std::vector& data, int mode, GLuint texture) { + if (data.empty()) { + return; + } + glUniform1i(barModeLoc, mode); + glBindTexture(GL_TEXTURE_2D, texture); + glBufferData( + GL_ARRAY_BUFFER, data.size() * sizeof(float), data.data(), + GL_STREAM_DRAW + ); + glDrawArrays(GL_TRIANGLES, 0, static_cast(data.size() / 8)); + } + + void barFlush() { + glUseProgram(barProgram); + glUniform2f( + barViewportLoc, static_cast(size.x), static_cast(size.y) + ); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindVertexArray(barVao); + glBindBuffer(GL_ARRAY_BUFFER, barVbo); + glActiveTexture(GL_TEXTURE0); + glUniform1i(barTextureLoc, 0); + barDrawBatch(barRects, 0, barFontTexture); + barDrawBatch(barIcons, 2, barIconTexture); + barDrawBatch(barText, 1, barFontTexture); + glBindVertexArray(0); + glDisable(GL_BLEND); + } + + // the bar is drawn over the content surface, so the window size + // reported to the engine stays the same + void drawBar() { + if (!barVisible()) { + return; + } + initBarRenderer(); + initBarIconTexture(); + barRects.clear(); + barText.clear(); + barIcons.clear(); + + const float width = static_cast(size.x); + const float height = static_cast(BAR_HEIGHT); + const glm::vec4 background(0.16f, 0.16f, 0.17f, 1.0f); + const glm::vec4 border(0.09f, 0.09f, 0.10f, 1.0f); + const glm::vec4 ink(0.87f, 0.87f, 0.88f, 1.0f); + const glm::vec4 hover(0.27f, 0.27f, 0.29f, 1.0f); + const glm::vec4 closeHover(0.72f, 0.16f, 0.11f, 1.0f); + + push_quad(barRects, 0, 0, width, height, 0, 0, 0, 0, background); + push_quad(barRects, 0, height - 1, width, 1, 0, 0, 0, 0, border); + + float textX = 10.0f; + if (barIconTexture != 0 && iconWidth > 0) { + push_quad( + barIcons, 7, (height - BAR_ICON_SIZE) * 0.5f, BAR_ICON_SIZE, + BAR_ICON_SIZE, 0, 1, 1, 0, glm::vec4(1.0f) + ); + textX = 7 + BAR_ICON_SIZE + 8; + } + const float buttonsX = width - BAR_BUTTON * 3; + const int maxChars = + static_cast((buttonsX - 8 - textX) / BAR_FONT_W); + if (maxChars > 0) { + barDrawText( + textX, (height - BAR_FONT_H) * 0.5f, decode_utf8(title), + maxChars, ink + ); + } + + for (int i = 0; i < 3; i++) { + const float bx = width - BAR_BUTTON * (i + 1); + if (hoveredButton == i) { + push_quad( + barRects, bx, 0, BAR_BUTTON, height - 1, 0, 0, 0, 0, + i == 0 ? closeHover : hover + ); + } + const float cx = bx + BAR_BUTTON * 0.5f; + const float cy = height * 0.5f; + if (i == 0) { + for (int s = 0; s < 7; s++) { + push_quad(barRects, cx - 4 + s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 3 - s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); + } + } else if (i == 1 && !maximized) { + push_quad(barRects, cx - 4.5f, cy - 4.5f, 9, 1.6f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 4.5f, cy + 2.9f, 9, 1.6f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 4.5f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 2.9f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); + } else if (i == 1) { + push_quad(barRects, cx - 3.5f, cy - 5.5f, 8, 1.4f, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 3.1f, cy - 5.5f, 1.4f, 5.5f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 5.5f, cy - 1.2f, 8, 1.4f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 5.5f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 1.1f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 5.5f, cy + 3.6f, 8, 1.4f, 0, 0, 0, 0, ink); + } else { + push_quad(barRects, cx - 5, cy - 0.8f, 10, 1.6f, 0, 0, 0, 0, ink); + } + } + barFlush(); + } + + int barButtonAt(double x, double y) const { + if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { + return -1; + } + for (int i = 0; i < 3; i++) { + const double bx = size.x - BAR_BUTTON * (i + 1); + if (x >= bx && x < bx + BAR_BUTTON) { + return i; + } + } + return -1; + } + + uint32_t barEdgeAt(double x, double y) const { + uint32_t edges = 0; + if (x < BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT; + } else if (x >= size.x - BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; + } + if (barVisible() && y < BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; + } else if (y >= size.y - BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; + } + return edges; + } + + static CursorShape edgeCursor(uint32_t edges) { + const bool left = edges & XDG_TOPLEVEL_RESIZE_EDGE_LEFT; + const bool right = edges & XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; + const bool top = edges & XDG_TOPLEVEL_RESIZE_EDGE_TOP; + const bool bottom = edges & XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; + if ((left && top) || (right && bottom)) { + return CursorShape::NWSE_RESIZE; + } + if ((right && top) || (left && bottom)) { + return CursorShape::NESW_RESIZE; + } + if (left || right) { + return CursorShape::EW_RESIZE; + } + if (top || bottom) { + return CursorShape::NS_RESIZE; + } + return CursorShape::ARROW; + } + + bool handleBarMotion(double x, double y) { + pointerX = x; + pointerY = y; + const int button = barButtonAt(x, y); + if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { + hoveredButton = button; + input.setOverrideCursor( + button >= 0 ? CursorShape::POINTER : CursorShape::ARROW + ); + return true; + } + hoveredButton = -1; + const uint32_t edges = barEdgeAt(x, y); + input.setOverrideCursor( + edges != 0 ? std::optional(edgeCursor(edges)) + : std::nullopt + ); + return false; + } + + bool handleBarButton(uint32_t serial, bool pressed) { + const double x = pointerX; + const double y = pointerY; + const int button = barButtonAt(x, y); + if (button >= 0) { + if (pressed) { + if (button == 0) { + setShouldClose(true); + } else if (button == 1) { + setMaximized(!maximized); + } else { + xdg_toplevel_set_minimized(state.toplevel); + } + } + return true; + } + if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { + if (pressed) { + const double current = now(); + if (current - lastBarPress < 0.4) { + lastBarPress = 0.0; + setMaximized(!maximized); + } else { + lastBarPress = current; + xdg_toplevel_move(state.toplevel, state.seat, serial); + } + } + return true; + } + const uint32_t edges = barEdgeAt(x, y); + if (pressed && edges != 0) { + xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); + return true; + } + return false; + } + + void onPointerLeave() { + hoveredButton = -1; + input.setOverrideCursor(std::nullopt); + } + + void onFrameDone() { + frameCallback = nullptr; + frameDone = true; + } + + void requestFrame() { + if (state.surface == nullptr || frameCallback != nullptr) { + return; + } + frameCallback = wl_surface_frame(state.surface); + wl_callback_add_listener(frameCallback, &frameListener(), this); + } + + void paceFrame() { + frameOnCallback = frameDone; + if (lastSwapEnd > 0.0) { + const double cost = now() - lastSwapEnd; + if (cost > 0.0 && cost < 2.0) { + frameCost = frameCost > 0.0 ? frameCost * 0.8 + cost * 0.2 : cost; + cacheTimeout = std::clamp( + frameCost * 16.0, MIN_CACHE_TIMEOUT, MAX_CACHE_TIMEOUT + ); + } + } + updateResizing(); + logSummary(); + if (resizing) { + if (!renderPending && now() - lastResize > RESIZE_PAUSE && + now() - lastCacheTime > cacheTimeout) { + renderPending = true; + } + dispatch_events(frameDone || presentPending ? 0 : 8); + frameOnCallback = frameDone; + return; + } + if (framerate != -1 || frameCallback == nullptr || frameDone) { + return; + } + const double deadline = now() + FRAME_TIMEOUT; + while (!frameDone && !resizing && now() < deadline) { + dispatch_events(5); + } + while (!frameDone && !resizing && now() < nextFrameTime) { + dispatch_events(5); + } + nextFrameTime = now() + frameInterval; + frameOnCallback = frameDone; + } + + void logSummary() { + const double current = now(); + if (resizeLogging) { + if (lastLoop > 0.0) { + loopGapMax = std::max(loopGapMax, current - lastLoop); + } + lastLoop = current; + loopCount++; + } + if (!resizeLogging || lastSummary <= 0.0) { + if (resizeLogging) { + lastSummary = current; + } + return; + } + if (current - lastSummary < 1.0) { + return; + } + logger.info() << "loop " << loopCount << "/s (max gap " + << loopGapMax * 1000.0 << " ms), presents " + << summaryFrames << "/s (max gap " + << summaryMax * 1000.0 << " ms), resizing " + << (resizing ? "yes" : "no"); + lastSummary = current; + loopCount = 0; + loopGapMax = 0.0; + summaryFrames = 0; + summarySum = 0.0; + summaryMax = 0.0; + } + + void markResizing() { + lastResize = now(); + if (!resizing) { + resizing = true; + resizePresents = 0; + resizeTimeSum = 0.0; + resizeTimeMax = 0.0; + if (resizeLogging) { + logger.info() << "resize started"; + } + setShouldRefresh(); + } + } + + void updateResizing() { + if (resizing && now() - lastResize > RESIZE_TIMEOUT) { + resizing = false; + renderPending = true; + if (resizeLogging) { + double average = resizePresents > 0 + ? resizeTimeSum / resizePresents + : 0.0; + logger.info() + << "resize finished, presented " << resizePresents + << ", avg " << average * 1000.0 << " ms, max " + << resizeTimeMax * 1000.0 << " ms"; + } + } + } + + void setIdleInhibit(bool enabled) { + if (enabled == (state.idleInhibitor != nullptr)) { + return; + } + if (enabled && state.idleInhibitManager) { + state.idleInhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor( + state.idleInhibitManager, state.surface + ); + } else if (state.idleInhibitor) { + zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); + state.idleInhibitor = nullptr; + } + } + + EGLDisplay eglDisplay = EGL_NO_DISPLAY; + EGLContext eglContext = EGL_NO_CONTEXT; + EGLSurface eglSurface = EGL_NO_SURFACE; + wl_egl_window* eglWindow = nullptr; + int32_t pendingWidth = 0; + int32_t pendingHeight = 0; + bool stateMaximized = false; + bool stateSuspended = false; + bool stateActivated = true; + bool configured = false; +private: + static constexpr double RESIZE_TIMEOUT = 0.4; + static constexpr double FRAME_TIMEOUT = 0.025; + static constexpr double RESIZE_PAUSE = 0.12; + static constexpr double MIN_CACHE_TIMEOUT = 0.3; + static constexpr double MAX_CACHE_TIMEOUT = 3.0; + + static const wl_callback_listener& frameListener() { + static wl_callback_listener listener = [] { + wl_callback_listener value {}; + value.done = [] (void* data, wl_callback* callback, uint32_t) { + wl_callback_destroy(callback); + static_cast(data)->onFrameDone(); + }; + return value; + }(); + return listener; + } + + static double now() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); + } + + int framerate = -1; + double prevSwap = 0.0; + double lastResize = 0.0; + static inline bool resizeLogging = getenv("VOXEL_LOG_RESIZE") != nullptr; + bool barEnabled = false; + bool fullscreen = false; + std::string title = "VoxelCore"; + std::vector iconPixels; + int iconWidth = 0; + int iconHeight = 0; + int hoveredButton = -1; + double lastBarPress = 0.0; + double pointerX = 0.0; + double pointerY = 0.0; + GLuint barProgram = 0; + GLuint barVao = 0; + GLuint barVbo = 0; + GLuint barFontTexture = 0; + GLuint barIconTexture = 0; + GLint barViewportLoc = -1; + GLint barTextureLoc = -1; + GLint barModeLoc = -1; + std::vector barRects; + std::vector barText; + std::vector barIcons; + bool frameOnCallback = false; + double frameInterval = 0.0; + double nextFrameTime = 0.0; + double frameCost = 0.0; + double cacheTimeout = 0.5; + bool resizing = false; + bool renderPending = true; + bool presentPending = true; + int resizePresents = 0; + double configureTime = 0.0; + double resizeTimeSum = 0.0; + double resizeTimeMax = 0.0; + double lastPresent = 0.0; + double lastSummary = 0.0; + double summarySum = 0.0; + double summaryMax = 0.0; + int summaryFrames = 0; + double lastLoop = 0.0; + double loopGapMax = 0.0; + int loopCount = 0; + wl_callback* frameCallback = nullptr; + bool frameDone = false; + GLuint stretchProgram = 0; + GLuint stretchVao = 0; + GLuint stretchVbo = 0; + GLuint cacheFbo = 0; + GLuint cacheTexture = 0; + int cacheWidth = 0; + int cacheHeight = 0; + double lastCacheTime = 0.0; + double lastSwapEnd = 0.0; + bool shouldRefresh = true; + bool shouldClose = false; + bool maximized = false; + bool suspended = false; + bool activated = true; + bool focusWarning = false; + std::stack scissorStack; + glm::vec4 scissorArea {}; +}; + +void WaylandInput::pollEvents(bool waitForRefresh) { + beginFrame(); + dispatch(waitForRefresh); + if (window) { + window->paceFrame(); + } + updateRepeat(); + updateBindings(); +} + +static void on_display_error() { + logger.error() << "the Wayland connection was lost"; + if (window) { + window->setShouldClose(true); + } +} + +void WaylandInput::refreshWindow() { + if (window) { + window->setShouldRefresh(); + } +} + +static void pointer_enter( + void*, wl_pointer*, uint32_t serial, wl_surface* surface, wl_fixed_t sx, + wl_fixed_t sy +) { + state.pointerSerial = serial; + state.entered = surface == state.surface; + const double x = wl_fixed_to_double(sx); + const double y = wl_fixed_to_double(sy); + if (state.entered && window && window->handleBarMotion(x, y)) { + return; + } + if (input) { + input->setCursorPosition(x, y); + if (state.entered) { + input->applyCursor(); + } + input->refreshWindow(); + } +} + +static void pointer_leave(void*, wl_pointer*, uint32_t, wl_surface*) { + state.entered = false; + if (window) { + window->onPointerLeave(); + } +} + +static void pointer_motion( + void*, wl_pointer*, uint32_t, wl_fixed_t sx, wl_fixed_t sy +) { + const double x = wl_fixed_to_double(sx); + const double y = wl_fixed_to_double(sy); + if (window && window->handleBarMotion(x, y)) { + return; + } + if (input) { + input->setCursorPosition(x, y); + input->refreshWindow(); + } +} + +static void pointer_button( + void*, wl_pointer*, uint32_t serial, uint32_t, uint32_t button, + uint32_t buttonState +) { + state.inputSerial = serial; + int index = -1; + switch (button) { + case 0x110: index = 0; break; + case 0x111: index = 1; break; + case 0x112: index = 2; break; + case 0x113: index = 3; break; + case 0x114: index = 4; break; + case 0x115: index = 5; break; + case 0x116: index = 6; break; + case 0x117: index = 7; break; + } + const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; + if (index == 0 && window && window->handleBarButton(serial, pressed)) { + return; + } + if (index >= 0 && input) { + input->onMouseCallback(index, pressed); + input->refreshWindow(); + } +} + +static void pointer_axis( + void*, wl_pointer*, uint32_t, uint32_t axis, wl_fixed_t value +) { + if (input && axis == WL_POINTER_AXIS_VERTICAL_SCROLL) { + input->scroll += wl_fixed_to_double(value) > 0 ? -1 : 1; + input->refreshWindow(); + } +} + +static void keyboard_keymap( + void*, wl_keyboard*, uint32_t format, int32_t fd, uint32_t size +) { + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { + close(fd); + return; + } + char* data = static_cast( + mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0) + ); + close(fd); + if (data == MAP_FAILED) { + return; + } + if (state.xkbContext == nullptr) { + state.xkbContext = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + } + xkb_keymap* keymap = xkb_keymap_new_from_string( + state.xkbContext, data, XKB_KEYMAP_FORMAT_TEXT_V1, + XKB_KEYMAP_COMPILE_NO_FLAGS + ); + munmap(data, size); + if (keymap == nullptr) { + logger.error() << "could not parse the keyboard keymap"; + return; + } + if (state.xkbState) { + xkb_state_unref(state.xkbState); + } + if (state.xkbKeymap) { + xkb_keymap_unref(state.xkbKeymap); + } + state.xkbKeymap = keymap; + state.xkbState = xkb_state_new(keymap); +} + +static void keyboard_enter( + void*, wl_keyboard*, uint32_t serial, wl_surface*, wl_array* +) { + state.inputSerial = serial; +} + +static void keyboard_leave(void*, wl_keyboard*, uint32_t, wl_surface*) { +} + +static void keyboard_key( + void*, wl_keyboard*, uint32_t serial, uint32_t, uint32_t key, + uint32_t keyState +) { + state.inputSerial = serial; + if (input) { + input->onKey(key, keyState == WL_KEYBOARD_KEY_STATE_PRESSED); + input->refreshWindow(); + } +} + +static void keyboard_modifiers( + void*, wl_keyboard*, uint32_t serial, uint32_t depressed, uint32_t latched, + uint32_t locked, uint32_t group +) { + state.inputSerial = serial; + if (state.xkbState) { + xkb_state_update_mask( + state.xkbState, depressed, latched, locked, 0, 0, group + ); + } +} + +static void keyboard_repeat_info(void*, wl_keyboard*, int32_t rate, int32_t delay) { + state.repeatRate = rate > 0 ? rate : 25; + state.repeatDelay = delay > 0 ? delay : 400; +} + +static void seat_capabilities(void*, wl_seat* seat, uint32_t capabilities) { + static const wl_pointer_listener pointerListener = [] { + wl_pointer_listener listener {}; + listener.enter = pointer_enter; + listener.leave = pointer_leave; + listener.motion = pointer_motion; + listener.button = pointer_button; + listener.axis = pointer_axis; + listener.frame = ignore_event<>; + listener.axis_source = ignore_event<>; + listener.axis_stop = ignore_event<>; + listener.axis_discrete = ignore_event<>; + listener.axis_value120 = ignore_event<>; + listener.axis_relative_direction = ignore_event<>; + return listener; + }(); + + static const wl_keyboard_listener keyboardListener = [] { + wl_keyboard_listener listener {}; + listener.keymap = keyboard_keymap; + listener.enter = keyboard_enter; + listener.leave = keyboard_leave; + listener.key = keyboard_key; + listener.modifiers = keyboard_modifiers; + listener.repeat_info = keyboard_repeat_info; + return listener; + }(); + + bool hasPointer = capabilities & WL_SEAT_CAPABILITY_POINTER; + bool hasKeyboard = capabilities & WL_SEAT_CAPABILITY_KEYBOARD; + if (hasPointer && state.pointer == nullptr) { + state.pointer = wl_seat_get_pointer(seat); + wl_pointer_add_listener(state.pointer, &pointerListener, nullptr); + if (state.cursorShapeManager) { + state.cursorShapeDevice = wp_cursor_shape_manager_v1_get_pointer( + state.cursorShapeManager, state.pointer + ); + } + } else if (!hasPointer && state.pointer) { + if (state.cursorShapeDevice) { + wp_cursor_shape_device_v1_destroy(state.cursorShapeDevice); + state.cursorShapeDevice = nullptr; + } + wl_pointer_destroy(state.pointer); + state.pointer = nullptr; + } + if (hasKeyboard && state.keyboard == nullptr) { + state.keyboard = wl_seat_get_keyboard(seat); + wl_keyboard_add_listener(state.keyboard, &keyboardListener, nullptr); + } else if (!hasKeyboard && state.keyboard) { + wl_keyboard_destroy(state.keyboard); + state.keyboard = nullptr; + } +} + +static void seat_name(void*, wl_seat*, const char*) { +} + +static void wm_base_ping(void*, xdg_wm_base* base, uint32_t serial) { + xdg_wm_base_pong(base, serial); +} + +static void toplevel_configure( + void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states +) { + if (window) { + window->onConfigure(width, height, states); + } +} + +static void toplevel_close(void*, xdg_toplevel*) { + if (window) { + window->setShouldClose(true); + } +} + +static void toplevel_configure_bounds(void*, xdg_toplevel*, int32_t, int32_t) { +} + +static void toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*) { +} + +static void xdg_surface_configure(void*, xdg_surface* surface, uint32_t serial) { + xdg_surface_ack_configure(surface, serial); + if (window) { + window->applyConfigure(); + } +} + +static void data_offer_offer(void*, wl_data_offer*, const char* mime) { + if (input) { + input->pendingMimes.push_back(mime); + } +} + +static void data_device_data_offer(void*, wl_data_device*, wl_data_offer* offer) { + static const wl_data_offer_listener listener = [] { + wl_data_offer_listener value {}; + value.offer = data_offer_offer; + value.source_actions = ignore_event<>; + value.action = ignore_event<>; + return value; + }(); + wl_data_offer_add_listener(offer, &listener, nullptr); +} + +static void data_device_selection(void*, wl_data_device*, wl_data_offer* offer) { + if (input == nullptr) { + return; + } + if (input->selection) { + wl_data_offer_destroy(input->selection); + } + input->selection = offer; + input->selectionMimes = std::move(input->pendingMimes); + input->pendingMimes.clear(); +} + +static void registry_global( + void*, wl_registry* registry, uint32_t name, const char* interface, + uint32_t version +) { + if (strcmp(interface, wl_compositor_interface.name) == 0) { + state.compositor = static_cast(wl_registry_bind( + registry, name, &wl_compositor_interface, std::min(version, 4u) + )); + } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { + state.wmBase = static_cast(wl_registry_bind( + registry, name, &xdg_wm_base_interface, std::min(version, 6u) + )); + static const xdg_wm_base_listener listener = [] { + xdg_wm_base_listener value {}; + value.ping = wm_base_ping; + return value; + }(); + xdg_wm_base_add_listener(state.wmBase, &listener, nullptr); + } else if (strcmp(interface, wl_seat_interface.name) == 0) { + state.seat = static_cast(wl_registry_bind( + registry, name, &wl_seat_interface, std::min(version, 7u) + )); + static const wl_seat_listener listener = [] { + wl_seat_listener value {}; + value.capabilities = seat_capabilities; + value.name = seat_name; + return value; + }(); + wl_seat_add_listener(state.seat, &listener, nullptr); + } else if (strcmp(interface, wl_data_device_manager_interface.name) == 0) { + state.dataDeviceManager = static_cast( + wl_registry_bind( + registry, name, &wl_data_device_manager_interface, + std::min(version, 3u) + ) + ); + } else if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) { + state.cursorShapeManager = static_cast( + wl_registry_bind( + registry, name, &wp_cursor_shape_manager_v1_interface, + std::min(version, 2u) + ) + ); + } else if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) { + state.pointerConstraints = static_cast( + wl_registry_bind( + registry, name, &zwp_pointer_constraints_v1_interface, 1 + ) + ); + } else if ( + strcmp(interface, zwp_relative_pointer_manager_v1_interface.name) == 0 + ) { + state.relativePointerManager = + static_cast(wl_registry_bind( + registry, name, &zwp_relative_pointer_manager_v1_interface, 1 + )); + } else if ( + strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0 + ) { + state.idleInhibitManager = static_cast( + wl_registry_bind( + registry, name, &zwp_idle_inhibit_manager_v1_interface, 1 + ) + ); + } else if ( + strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0 + ) { + state.decorationManager = static_cast( + wl_registry_bind( + registry, name, &zxdg_decoration_manager_v1_interface, 1 + ) + ); + } +} + +static void registry_global_remove(void*, wl_registry*, uint32_t) { +} + +static void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +) { + serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; + if (!serverDecorations && window != nullptr) { + window->enableOwnDecorations(); + } +} + +std::tuple, std::unique_ptr> +wayland_window_initialize(DisplaySettings* settings, std::string title) { + state.display = wl_display_connect(nullptr); + if (state.display == nullptr) { + logger.error() << "could not connect to the Wayland display"; + return {nullptr, nullptr}; + } + static const wl_registry_listener registryListener = [] { + wl_registry_listener value {}; + value.global = registry_global; + value.global_remove = registry_global_remove; + return value; + }(); + state.registry = wl_display_get_registry(state.display); + wl_registry_add_listener(state.registry, ®istryListener, nullptr); + wl_display_roundtrip(state.display); + if (state.compositor == nullptr || state.wmBase == nullptr) { + logger.error() << "the compositor does not provide xdg-shell"; + wl_display_disconnect(state.display); + state.display = nullptr; + return {nullptr, nullptr}; + } + + state.surface = wl_compositor_create_surface(state.compositor); + + auto inputPtr = std::make_unique(); + input = inputPtr.get(); + auto windowPtr = std::make_unique( + *inputPtr, settings, settings->width.get(), settings->height.get() + ); + window = windowPtr.get(); + + static const wl_data_device_listener deviceListener = [] { + wl_data_device_listener value {}; + value.data_offer = data_device_data_offer; + value.enter = ignore_event<>; + value.leave = ignore_event<>; + value.motion = ignore_event<>; + value.drop = ignore_event<>; + value.selection = data_device_selection; + return value; + }(); + if (state.dataDeviceManager && state.seat) { + state.dataDevice = wl_data_device_manager_get_data_device( + state.dataDeviceManager, state.seat + ); + wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); + } + + { + state.xdgSurface = xdg_wm_base_get_xdg_surface( + state.wmBase, state.surface + ); + state.toplevel = xdg_surface_get_toplevel(state.xdgSurface); + window->setTitle(title); + xdg_toplevel_set_app_id(state.toplevel, "VoxelCore"); + if (state.decorationManager) { + state.decoration = + zxdg_decoration_manager_v1_get_toplevel_decoration( + state.decorationManager, state.toplevel + ); + static const zxdg_toplevel_decoration_v1_listener listener = [] { + zxdg_toplevel_decoration_v1_listener value {}; + value.configure = zxdg_decoration_configure; + return value; + }(); + zxdg_toplevel_decoration_v1_add_listener( + state.decoration, &listener, nullptr + ); + zxdg_toplevel_decoration_v1_set_mode( + state.decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE + ); + } + if (state.decorationManager == nullptr) { + window->enableOwnDecorations(); + } + static const xdg_surface_listener surfaceListener = [] { + xdg_surface_listener value {}; + value.configure = xdg_surface_configure; + return value; + }(); + static const xdg_toplevel_listener toplevelListener = [] { + xdg_toplevel_listener value {}; + value.configure = toplevel_configure; + value.close = toplevel_close; + value.configure_bounds = toplevel_configure_bounds; + value.wm_capabilities = toplevel_wm_capabilities; + return value; + }(); + xdg_surface_add_listener(state.xdgSurface, &surfaceListener, nullptr); + xdg_toplevel_add_listener(state.toplevel, &toplevelListener, nullptr); + wl_surface_commit(state.surface); + } + + while (!window->configured) { + if (wl_display_dispatch(state.display) == -1) { + logger.error() << "the Wayland connection was lost"; + return {nullptr, nullptr}; + } + } + + window->eglDisplay = eglGetPlatformDisplay( + EGL_PLATFORM_WAYLAND_KHR, state.display, nullptr + ); + if (window->eglDisplay == EGL_NO_DISPLAY || + eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { + logger.error() << "could not initialize EGL"; + return {nullptr, nullptr}; + } + eglBindAPI(EGL_OPENGL_API); + + EGLint samples = settings->samples.get(); + EGLConfig config = nullptr; + EGLint configCount = 0; + const EGLint configAttributes[] { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, + EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_SAMPLES, samples > 0 ? samples : 0, + EGL_NONE + }; + eglChooseConfig(window->eglDisplay, configAttributes, &config, 1, &configCount); + if (samples > 0 && configCount == 0) { + logger.warning() << "multisampling is not available"; + const EGLint fallbackAttributes[] { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, + EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_NONE + }; + eglChooseConfig( + window->eglDisplay, fallbackAttributes, &config, 1, &configCount + ); + } + if (configCount == 0) { + logger.error() << "no suitable EGL config"; + return {nullptr, nullptr}; + } + + const EGLint contextAttributes[] { + EGL_CONTEXT_MAJOR_VERSION, 3, + EGL_CONTEXT_MINOR_VERSION, 3, + EGL_NONE + }; + window->eglContext = eglCreateContext( + window->eglDisplay, config, EGL_NO_CONTEXT, contextAttributes + ); + window->eglWindow = wl_egl_window_create( + state.surface, window->getSize().x, window->getSize().y + ); + window->eglSurface = eglCreateWindowSurface( + window->eglDisplay, config, + reinterpret_cast(window->eglWindow), nullptr + ); + if (window->eglContext == EGL_NO_CONTEXT || + window->eglSurface == EGL_NO_SURFACE || + eglMakeCurrent( + window->eglDisplay, window->eglSurface, window->eglSurface, + window->eglContext + ) == EGL_FALSE) { + logger.error() << "could not create the OpenGL context"; + return {nullptr, nullptr}; + } + eglSwapInterval(window->eglDisplay, 0); + + glewExperimental = GL_TRUE; + GLenum glewError = glewInit(); + if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { + logger.error() << "failed to initialize GLEW:\n" + << glewGetErrorString(glewError); + return {nullptr, nullptr}; + } + + window->initStretchRenderer(); + glViewport(0, 0, window->getSize().x, window->getSize().y); + glClearColor(0.0f, 0.0f, 0.0f, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + GLint maxTextureSize[1] {static_cast(Texture::MAX_RESOLUTION)}; + glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); + if (maxTextureSize[0] > 0) { + Texture::MAX_RESOLUTION = maxTextureSize[0]; + logger.info() << "max texture size is " << Texture::MAX_RESOLUTION; + } + logger.info() << "GL Vendor: " + << reinterpret_cast(glGetString(GL_VENDOR)); + logger.info() << "GL Renderer: " + << reinterpret_cast(glGetString(GL_RENDERER)); + logger.info() << "windowing platform: Wayland (native)"; + + return {std::move(windowPtr), std::move(inputPtr)}; +} diff --git a/src/window/detail/WindowBackends.hpp b/src/window/detail/WindowBackends.hpp new file mode 100644 index 000000000..0d546c14c --- /dev/null +++ b/src/window/detail/WindowBackends.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include + +class Window; +class Input; +struct DisplaySettings; + +std::tuple, std::unique_ptr> +glfw_window_initialize(DisplaySettings* settings, std::string title); + +#ifdef VOXELENGINE_WAYLAND +std::tuple, std::unique_ptr> +wayland_window_initialize(DisplaySettings* settings, std::string title); +#endif diff --git a/src/window/input.cpp b/src/window/input.cpp index cbb05a888..cc07b7bb3 100644 --- a/src/window/input.cpp +++ b/src/window/input.cpp @@ -1,339 +1,267 @@ -#include "input.hpp" - -#include "debug/Logger.hpp" -#include "util/stringutil.hpp" -#include "data/dv.hpp" - -#include - -#include - -#ifdef _WIN32 -#include -#endif // _WIN32 - -static debug::Logger logger("input"); - -static std::unordered_map keycodes { - {"enter", GLFW_KEY_ENTER}, - {"space", GLFW_KEY_SPACE}, - {"backspace", GLFW_KEY_BACKSPACE}, - {"caps-lock", GLFW_KEY_CAPS_LOCK}, - {"escape", GLFW_KEY_ESCAPE}, - {"delete", GLFW_KEY_DELETE}, - {"home", GLFW_KEY_HOME}, - {"end", GLFW_KEY_END}, - {"tab", GLFW_KEY_TAB}, - {"insert", GLFW_KEY_INSERT}, - {"page-down", GLFW_KEY_PAGE_DOWN}, - {"page-up", GLFW_KEY_PAGE_UP}, - {"left-shift", GLFW_KEY_LEFT_SHIFT}, - {"right-shift", GLFW_KEY_RIGHT_SHIFT}, - {"left-ctrl", GLFW_KEY_LEFT_CONTROL}, - {"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, - {"left-alt", GLFW_KEY_LEFT_ALT}, - {"right-alt", GLFW_KEY_RIGHT_ALT}, - {"left-super", GLFW_KEY_LEFT_SUPER}, - {"right-super", GLFW_KEY_RIGHT_SUPER}, - {"grave-accent", GLFW_KEY_GRAVE_ACCENT}, - {"left", GLFW_KEY_LEFT}, - {"right", GLFW_KEY_RIGHT}, - {"down", GLFW_KEY_DOWN}, - {"up", GLFW_KEY_UP}, - {"num-lock", GLFW_KEY_NUM_LOCK}, - {"print-screen", GLFW_KEY_PRINT_SCREEN}, - {"num-add", GLFW_KEY_KP_ADD}, - {"num-multiply", GLFW_KEY_KP_MULTIPLY}, - {"num-divide", GLFW_KEY_KP_DIVIDE}, - {"num-subtract", GLFW_KEY_KP_SUBTRACT}, - {"num-enter", GLFW_KEY_KP_ENTER}, - {"num-equal", GLFW_KEY_KP_EQUAL}, - {"num-decimal", GLFW_KEY_KP_DECIMAL}, -}; - -static std::unordered_map mousecodes { - {"left", GLFW_MOUSE_BUTTON_1}, - {"right", GLFW_MOUSE_BUTTON_2}, - {"middle", GLFW_MOUSE_BUTTON_3}, - {"side1", GLFW_MOUSE_BUTTON_4}, - {"side2", GLFW_MOUSE_BUTTON_5}, - {"side3", GLFW_MOUSE_BUTTON_6}, - {"side4", GLFW_MOUSE_BUTTON_7}, - {"side5", GLFW_MOUSE_BUTTON_8}, -}; - -static std::unordered_map keynames {}; -static std::unordered_map buttonsnames{}; - -std::string input_util::get_name(Mousecode code) { - const auto found = buttonsnames.find(static_cast(code)); - if (found == buttonsnames.end()) { - return "unknown"; - } - return found->second; -} - -std::string input_util::get_name(Keycode code) { - const auto found = keynames.find(static_cast(code)); - if (found == keynames.end()) { - return "unknown"; - } - return found->second; -} - -void Binding::reset(InputType type, int code) { - this->type = type; - this->code = code; -} - -void Binding::reset(Keycode code) { - reset(InputType::KEYBOARD, static_cast(code)); -} - -void Binding::reset(Mousecode code) { - reset(InputType::MOUSE, static_cast(code)); -} - -void input_util::initialize() { - for (int i = 0; i <= 9; i++) { - keycodes[std::to_string(i)] = GLFW_KEY_0 + i; - } - for (int i = 0; i < 25; i++) { - keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; - } - for (char i = 'a'; i <= 'z'; i++) { - keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; - } - for (int i = 0; i <= 9; i++) { - keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; - } - for (const auto& entry : keycodes) { - keynames[entry.second] = entry.first; - } - for (const auto& entry : mousecodes) { - buttonsnames[entry.second] = entry.first; - } -} - -Keycode input_util::keycode_from(const std::string& name) { - const auto& found = keycodes.find(name); - if (found == keycodes.end()) { - return Keycode::UNKNOWN; - } - return static_cast(found->second); -} - -Mousecode input_util::mousecode_from(const std::string& name) { - const auto& found = mousecodes.find(name); - if (found == mousecodes.end()) { - return Mousecode::UNKNOWN; - } - return static_cast(found->second); -} - -static const char* numpad_key_names[] { - "Num 0", - "Num 1", - "Num 2", - "Num 3", - "Num 4", - "Num 5", - "Num 6", - "Num 7", - "Num 8", - "Num 9", - "Num .", - "Num /", - "Num *", - "Num -", - "Num +", - "Num Enter", - "Num =", -}; - -std::string input_util::to_string(Keycode code) { - int icode_repr = static_cast(code); - if (icode_repr == -1) { - return "Unknown"; - } - if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { - return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; - } - const char* name = - glfwGetKeyName(icode_repr, glfwGetKeyScancode(icode_repr)); - if (name == nullptr) { - switch (icode_repr) { - case GLFW_KEY_TAB: - return "Tab"; - case GLFW_KEY_LEFT_CONTROL: - return "Left Ctrl"; - case GLFW_KEY_RIGHT_CONTROL: - return "Right Ctrl"; - case GLFW_KEY_LEFT_ALT: - return "Left Alt"; - case GLFW_KEY_RIGHT_ALT: - return "Right Alt"; - case GLFW_KEY_LEFT_SHIFT: - return "Left Shift"; - case GLFW_KEY_RIGHT_SHIFT: - return "Right Shift"; - case GLFW_KEY_CAPS_LOCK: - return "Caps-Lock"; - case GLFW_KEY_SPACE: - return "Space"; - case GLFW_KEY_ESCAPE: - return "Esc"; - case GLFW_KEY_ENTER: - return "Enter"; - case GLFW_KEY_UP: - return "Up"; - case GLFW_KEY_DOWN: - return "Down"; - case GLFW_KEY_LEFT: - return "Left"; - case GLFW_KEY_RIGHT: - return "Right"; - case GLFW_KEY_BACKSPACE: - return "Backspace"; - case GLFW_KEY_F1: - return "F1"; - case GLFW_KEY_F2: - return "F2"; - case GLFW_KEY_F3: - return "F3"; - case GLFW_KEY_F4: - return "F4"; - case GLFW_KEY_F5: - return "F5"; - case GLFW_KEY_F6: - return "F6"; - case GLFW_KEY_F7: - return "F7"; - case GLFW_KEY_F8: - return "F8"; - case GLFW_KEY_F9: - return "F9"; - case GLFW_KEY_F10: - return "F10"; - case GLFW_KEY_F11: - return "F11"; - case GLFW_KEY_F12: - return "F12"; - case GLFW_KEY_DELETE: - return "Delete"; - case GLFW_KEY_HOME: - return "Home"; - case GLFW_KEY_END: - return "End"; - case GLFW_KEY_LEFT_SUPER: - return "Left Super"; - case GLFW_KEY_RIGHT_SUPER: - return "Right Super"; - case GLFW_KEY_PAGE_UP: - return "Page Up"; - case GLFW_KEY_PAGE_DOWN: - return "Page Down"; - case GLFW_KEY_INSERT: - return "Insert"; - case GLFW_KEY_PRINT_SCREEN: - return "Print Screen"; - case GLFW_KEY_NUM_LOCK: - return "Num Lock"; - case GLFW_KEY_MENU: - return "Menu"; - case GLFW_KEY_PAUSE: - return "Pause"; - default: - return "Unknown"; - } - } - return std::string(name); -} - -std::string input_util::to_string(Mousecode code) { - switch (code) { - case Mousecode::BUTTON_1: - return "LMB"; - case Mousecode::BUTTON_2: - return "RMB"; - case Mousecode::BUTTON_3: - return "MMB"; - case Mousecode::BUTTON_4: - case Mousecode::BUTTON_5: - case Mousecode::BUTTON_6: - case Mousecode::BUTTON_7: - case Mousecode::BUTTON_8: - return "XButton " + std::to_string(static_cast(code) - - static_cast(Mousecode::BUTTON_3)); - default: - return "unknown button"; - } -} - -const Binding& Bindings::require(const std::string& name) const { - if (const auto found = get(name)) { - return *found; - } - throw std::runtime_error("binding '" + name + "' does not exist"); -} - -Binding& Bindings::require(const std::string& name) { - if (const auto found = get(name)) { - return *found; - } - throw std::runtime_error("binding '" + name + "' does not exist"); -} - -void Bindings::read(const dv::value& map, BindType bindType) { - for (auto& [sectionName, section] : map.asObject()) { - for (auto& [name, value] : section.asObject()) { - auto key = sectionName + "." + name; - auto [prefix, codename] = util::split_at(value.asString(), ':'); - InputType type; - int code; - if (prefix == "key") { - type = InputType::KEYBOARD; - code = static_cast(input_util::keycode_from(codename)); - } else if (prefix == "mouse") { - type = InputType::MOUSE; - code = static_cast(input_util::mousecode_from(codename)); - } else { - logger.error() - << "unknown input type: " << prefix << " (binding " - << util::quote(key) << ")"; - continue; - } - if (bindType == BindType::BIND) { - bind(key, type, code); - } else if (bindType == BindType::REBIND) { - rebind(key, type, code); - } - } - } -} - -#include "coders/toml.hpp" - -std::string Bindings::write() const { - auto obj = dv::object(); - for (auto& entry : bindings) { - const auto& binding = entry.second; - std::string value; - switch (binding.type) { - case InputType::KEYBOARD: - value = - "key:" + - input_util::get_name(static_cast(binding.code)); - break; - case InputType::MOUSE: - value = - "mouse:" + - input_util::get_name(static_cast(binding.code)); - break; - default: - throw std::runtime_error("unsupported control type"); - } - obj[entry.first] = std::move(value); - } - return toml::stringify(obj); -} +#include "input.hpp" + +#include "debug/Logger.hpp" +#include "util/stringutil.hpp" +#include "data/dv.hpp" + +#include + +#include +#include + +#ifdef _WIN32 +#include +#endif // _WIN32 + +static debug::Logger logger("input"); + +static std::unordered_map keycodes { + {"enter", GLFW_KEY_ENTER}, + {"space", GLFW_KEY_SPACE}, + {"backspace", GLFW_KEY_BACKSPACE}, + {"caps-lock", GLFW_KEY_CAPS_LOCK}, + {"escape", GLFW_KEY_ESCAPE}, + {"delete", GLFW_KEY_DELETE}, + {"home", GLFW_KEY_HOME}, + {"end", GLFW_KEY_END}, + {"tab", GLFW_KEY_TAB}, + {"insert", GLFW_KEY_INSERT}, + {"page-down", GLFW_KEY_PAGE_DOWN}, + {"page-up", GLFW_KEY_PAGE_UP}, + {"left-shift", GLFW_KEY_LEFT_SHIFT}, + {"right-shift", GLFW_KEY_RIGHT_SHIFT}, + {"left-ctrl", GLFW_KEY_LEFT_CONTROL}, + {"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, + {"left-alt", GLFW_KEY_LEFT_ALT}, + {"right-alt", GLFW_KEY_RIGHT_ALT}, + {"left-super", GLFW_KEY_LEFT_SUPER}, + {"right-super", GLFW_KEY_RIGHT_SUPER}, + {"grave-accent", GLFW_KEY_GRAVE_ACCENT}, + {"left", GLFW_KEY_LEFT}, + {"right", GLFW_KEY_RIGHT}, + {"down", GLFW_KEY_DOWN}, + {"up", GLFW_KEY_UP}, + {"num-lock", GLFW_KEY_NUM_LOCK}, + {"print-screen", GLFW_KEY_PRINT_SCREEN}, + {"num-add", GLFW_KEY_KP_ADD}, + {"num-multiply", GLFW_KEY_KP_MULTIPLY}, + {"num-divide", GLFW_KEY_KP_DIVIDE}, + {"num-subtract", GLFW_KEY_KP_SUBTRACT}, + {"num-enter", GLFW_KEY_KP_ENTER}, + {"num-equal", GLFW_KEY_KP_EQUAL}, + {"num-decimal", GLFW_KEY_KP_DECIMAL}, +}; + +static std::unordered_map mousecodes { + {"left", GLFW_MOUSE_BUTTON_1}, + {"right", GLFW_MOUSE_BUTTON_2}, + {"middle", GLFW_MOUSE_BUTTON_3}, + {"side1", GLFW_MOUSE_BUTTON_4}, + {"side2", GLFW_MOUSE_BUTTON_5}, + {"side3", GLFW_MOUSE_BUTTON_6}, + {"side4", GLFW_MOUSE_BUTTON_7}, + {"side5", GLFW_MOUSE_BUTTON_8}, +}; + +static std::unordered_map keynames {}; +static std::unordered_map buttonsnames{}; + +std::string input_util::get_name(Mousecode code) { + const auto found = buttonsnames.find(static_cast(code)); + if (found == buttonsnames.end()) { + return "unknown"; + } + return found->second; +} + +std::string input_util::get_name(Keycode code) { + const auto found = keynames.find(static_cast(code)); + if (found == keynames.end()) { + return "unknown"; + } + return found->second; +} + +void Binding::reset(InputType type, int code) { + this->type = type; + this->code = code; +} + +void Binding::reset(Keycode code) { + reset(InputType::KEYBOARD, static_cast(code)); +} + +void Binding::reset(Mousecode code) { + reset(InputType::MOUSE, static_cast(code)); +} + +void input_util::initialize() { + for (int i = 0; i <= 9; i++) { + keycodes[std::to_string(i)] = GLFW_KEY_0 + i; + } + for (int i = 0; i < 25; i++) { + keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; + } + for (char i = 'a'; i <= 'z'; i++) { + keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; + } + for (int i = 0; i <= 9; i++) { + keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; + } + for (const auto& entry : keycodes) { + keynames[entry.second] = entry.first; + } + for (const auto& entry : mousecodes) { + buttonsnames[entry.second] = entry.first; + } +} + +Keycode input_util::keycode_from(const std::string& name) { + const auto& found = keycodes.find(name); + if (found == keycodes.end()) { + return Keycode::UNKNOWN; + } + return static_cast(found->second); +} + +Mousecode input_util::mousecode_from(const std::string& name) { + const auto& found = mousecodes.find(name); + if (found == mousecodes.end()) { + return Mousecode::UNKNOWN; + } + return static_cast(found->second); +} + +static const char* numpad_key_names[] { + "Num 0", + "Num 1", + "Num 2", + "Num 3", + "Num 4", + "Num 5", + "Num 6", + "Num 7", + "Num 8", + "Num 9", + "Num .", + "Num /", + "Num *", + "Num -", + "Num +", + "Num Enter", + "Num =", +}; + +std::string input_util::to_string(Keycode code) { + int icode_repr = static_cast(code); + if (icode_repr == -1) { + return "Unknown"; + } + if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { + return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; + } + const auto found = keynames.find(icode_repr); + if (found == keynames.end()) { + return "Unknown"; + } + std::string result; + bool capitalize = true; + for (char c : found->second) { + if (c == '-') { + result += ' '; + capitalize = true; + continue; + } + result += capitalize ? static_cast(std::toupper(c)) : c; + capitalize = false; + } + return result; +} + +std::string input_util::to_string(Mousecode code) { + switch (code) { + case Mousecode::BUTTON_1: + return "LMB"; + case Mousecode::BUTTON_2: + return "RMB"; + case Mousecode::BUTTON_3: + return "MMB"; + case Mousecode::BUTTON_4: + case Mousecode::BUTTON_5: + case Mousecode::BUTTON_6: + case Mousecode::BUTTON_7: + case Mousecode::BUTTON_8: + return "XButton " + std::to_string(static_cast(code) - + static_cast(Mousecode::BUTTON_3)); + default: + return "unknown button"; + } +} + +const Binding& Bindings::require(const std::string& name) const { + if (const auto found = get(name)) { + return *found; + } + throw std::runtime_error("binding '" + name + "' does not exist"); +} + +Binding& Bindings::require(const std::string& name) { + if (const auto found = get(name)) { + return *found; + } + throw std::runtime_error("binding '" + name + "' does not exist"); +} + +void Bindings::read(const dv::value& map, BindType bindType) { + for (auto& [sectionName, section] : map.asObject()) { + for (auto& [name, value] : section.asObject()) { + auto key = sectionName + "." + name; + auto [prefix, codename] = util::split_at(value.asString(), ':'); + InputType type; + int code; + if (prefix == "key") { + type = InputType::KEYBOARD; + code = static_cast(input_util::keycode_from(codename)); + } else if (prefix == "mouse") { + type = InputType::MOUSE; + code = static_cast(input_util::mousecode_from(codename)); + } else { + logger.error() + << "unknown input type: " << prefix << " (binding " + << util::quote(key) << ")"; + continue; + } + if (bindType == BindType::BIND) { + bind(key, type, code); + } else if (bindType == BindType::REBIND) { + rebind(key, type, code); + } + } + } +} + +#include "coders/toml.hpp" + +std::string Bindings::write() const { + auto obj = dv::object(); + for (auto& entry : bindings) { + const auto& binding = entry.second; + std::string value; + switch (binding.type) { + case InputType::KEYBOARD: + value = + "key:" + + input_util::get_name(static_cast(binding.code)); + break; + case InputType::MOUSE: + value = + "mouse:" + + input_util::get_name(static_cast(binding.code)); + break; + default: + throw std::runtime_error("unsupported control type"); + } + obj[entry.first] = std::move(value); + } + return toml::stringify(obj); +} diff --git a/src/window/wayland/protocols/cursor-shape-v1.xml b/src/window/wayland/protocols/cursor-shape-v1.xml new file mode 100644 index 000000000..64b2f9b2c --- /dev/null +++ b/src/window/wayland/protocols/cursor-shape-v1.xml @@ -0,0 +1,162 @@ + + + + Copyright 2018 The Chromium Authors + Copyright 2023 Simon Ser + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + This global offers an alternative, optional way to set cursor images. This + new way uses enumerated cursors instead of a wl_surface like + wl_pointer.set_cursor does. + + Warning! The protocol described in this file is currently in the testing + phase. Backward compatible changes may be added together with the + corresponding interface version bump. Backward incompatible changes can + only be done by creating a new major version of the extension. + + + + + Destroy the cursor shape manager. + + + + + + Obtain a wp_cursor_shape_device_v1 for a wl_pointer object. + + When the pointer capability is removed from the wl_seat, the + wp_cursor_shape_device_v1 object becomes inert. + + + + + + + + Obtain a wp_cursor_shape_device_v1 for a zwp_tablet_tool_v2 object. + + When the zwp_tablet_tool_v2 is removed, the wp_cursor_shape_device_v1 + object becomes inert. + + + + + + + + + This interface allows clients to set the cursor shape. + + + + + This enum describes cursor shapes. + + The names are taken from the CSS W3C specification: + https://w3c.github.io/csswg-drafts/css-ui/#cursor + with a few additions. + + Note that there are some groups of cursor shapes that are related: + The first group is drag-and-drop cursors which are used to indicate + the selected action during dnd operations. The second group is resize + cursors which are used to indicate resizing and moving possibilities + on window borders. It is recommended that the shapes in these groups + should use visually compatible images and metaphors. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Destroy the cursor shape device. + + The device cursor shape remains unchanged. + + + + + + Sets the device cursor to the specified shape. The compositor will + change the cursor image based on the specified shape. + + The cursor actually changes only if the input device focus is one of + the requesting client's surfaces. If any, the previous cursor image + (surface or shape) is replaced. + + The "shape" argument must be a valid enum entry, otherwise the + invalid_shape protocol error is raised. + + This is similar to the wl_pointer.set_cursor and + zwp_tablet_tool_v2.set_cursor requests, but this request accepts a + shape instead of contents in the form of a surface. Clients can mix + set_cursor and set_shape requests. + + The serial parameter must match the latest wl_pointer.enter or + zwp_tablet_tool_v2.proximity_in serial number sent to the client. + Otherwise the request will be ignored. + + + + + + diff --git a/src/window/wayland/protocols/idle-inhibit-unstable-v1.xml b/src/window/wayland/protocols/idle-inhibit-unstable-v1.xml new file mode 100644 index 000000000..9c06cdcba --- /dev/null +++ b/src/window/wayland/protocols/idle-inhibit-unstable-v1.xml @@ -0,0 +1,83 @@ + + + + + Copyright © 2015 Samsung Electronics Co., Ltd + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + This interface permits inhibiting the idle behavior such as screen + blanking, locking, and screensaving. The client binds the idle manager + globally, then creates idle-inhibitor objects for each surface. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + Destroy the inhibit manager. + + + + + + Create a new inhibitor object associated with the given surface. + + + + + + + + + + An idle inhibitor prevents the output that the associated surface is + visible on from being set to a state where it is not visually usable due + to lack of user interaction (e.g. blanked, dimmed, locked, set to power + save, etc.) Any screensaver processes are also blocked from displaying. + + If the surface is destroyed, unmapped, becomes occluded, loses + visibility, or otherwise becomes not visually relevant for the user, the + idle inhibitor will not be honored by the compositor; if the surface + subsequently regains visibility the inhibitor takes effect once again. + Likewise, the inhibitor isn't honored if the system was already idled at + the time the inhibitor was established, although if the system later + de-idles and re-idles the inhibitor will take effect. + + + + + Remove the inhibitor effect from the associated wl_surface. + + + + + diff --git a/src/window/wayland/protocols/pointer-constraints-unstable-v1.xml b/src/window/wayland/protocols/pointer-constraints-unstable-v1.xml new file mode 100644 index 000000000..83b0a1c2c --- /dev/null +++ b/src/window/wayland/protocols/pointer-constraints-unstable-v1.xml @@ -0,0 +1,334 @@ + + + + + Copyright © 2014 Jonas Ådahl + Copyright © 2015 Red Hat Inc. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol specifies a set of interfaces used for adding constraints to + the motion of a pointer. Possible constraints include confining pointer + motions to a given region, or locking it to its current position. + + In order to constrain the pointer, a client must first bind the global + interface "wp_pointer_constraints" which, if a compositor supports pointer + constraints, is exposed by the registry. Using the bound global object, the + client uses the request that corresponds to the type of constraint it wants + to make. See wp_pointer_constraints for more details. + + Warning! The protocol described in this file is experimental and backward + incompatible changes may be made. Backward compatible changes may be added + together with the corresponding interface version bump. Backward + incompatible changes are done by bumping the version number in the protocol + and interface names and resetting the interface version. Once the protocol + is to be declared stable, the 'z' prefix and the version number in the + protocol and interface names are removed and the interface version number is + reset. + + + + + The global interface exposing pointer constraining functionality. It + exposes two requests: lock_pointer for locking the pointer to its + position, and confine_pointer for locking the pointer to a region. + + The lock_pointer and confine_pointer requests create the objects + wp_locked_pointer and wp_confined_pointer respectively, and the client can + use these objects to interact with the lock. + + For any surface, only one lock or confinement may be active across all + wl_pointer objects of the same seat. If a lock or confinement is requested + when another lock or confinement is active or requested on the same surface + and with any of the wl_pointer objects of the same seat, an + 'already_constrained' error will be raised. + + + + + These errors can be emitted in response to wp_pointer_constraints + requests. + + + + + + + These values represent different lifetime semantics. They are passed + as arguments to the factory requests to specify how the constraint + lifetimes should be managed. + + + + A oneshot pointer constraint will never reactivate once it has been + deactivated. See the corresponding deactivation event + (wp_locked_pointer.unlocked and wp_confined_pointer.unconfined) for + details. + + + + + A persistent pointer constraint may again reactivate once it has + been deactivated. See the corresponding deactivation event + (wp_locked_pointer.unlocked and wp_confined_pointer.unconfined) for + details. + + + + + + + Used by the client to notify the server that it will no longer use this + pointer constraints object. + + + + + + The lock_pointer request lets the client request to disable movements of + the virtual pointer (i.e. the cursor), effectively locking the pointer + to a position. This request may not take effect immediately; in the + future, when the compositor deems implementation-specific constraints + are satisfied, the pointer lock will be activated and the compositor + sends a locked event. + + The protocol provides no guarantee that the constraints are ever + satisfied, and does not require the compositor to send an error if the + constraints cannot ever be satisfied. It is thus possible to request a + lock that will never activate. + + There may not be another pointer constraint of any kind requested or + active on the surface for any of the wl_pointer objects of the seat of + the passed pointer when requesting a lock. If there is, an error will be + raised. See general pointer lock documentation for more details. + + The intersection of the region passed with this request and the input + region of the surface is used to determine where the pointer must be + in order for the lock to activate. It is up to the compositor whether to + warp the pointer or require some kind of user interaction for the lock + to activate. If the region is null the surface input region is used. + + A surface may receive pointer focus without the lock being activated. + + The request creates a new object wp_locked_pointer which is used to + interact with the lock as well as receive updates about its state. See + the the description of wp_locked_pointer for further information. + + Note that while a pointer is locked, the wl_pointer objects of the + corresponding seat will not emit any wl_pointer.motion events, but + relative motion events will still be emitted via wp_relative_pointer + objects of the same seat. wl_pointer.axis and wl_pointer.button events + are unaffected. + + + + + + + + + + + The confine_pointer request lets the client request to confine the + pointer cursor to a given region. This request may not take effect + immediately; in the future, when the compositor deems implementation- + specific constraints are satisfied, the pointer confinement will be + activated and the compositor sends a confined event. + + The intersection of the region passed with this request and the input + region of the surface is used to determine where the pointer must be + in order for the confinement to activate. It is up to the compositor + whether to warp the pointer or require some kind of user interaction for + the confinement to activate. If the region is null the surface input + region is used. + + The request will create a new object wp_confined_pointer which is used + to interact with the confinement as well as receive updates about its + state. See the the description of wp_confined_pointer for further + information. + + + + + + + + + + + + The wp_locked_pointer interface represents a locked pointer state. + + While the lock of this object is active, the wl_pointer objects of the + associated seat will not emit any wl_pointer.motion events. + + This object will send the event 'locked' when the lock is activated. + Whenever the lock is activated, it is guaranteed that the locked surface + will already have received pointer focus and that the pointer will be + within the region passed to the request creating this object. + + To unlock the pointer, send the destroy request. This will also destroy + the wp_locked_pointer object. + + If the compositor decides to unlock the pointer the unlocked event is + sent. See wp_locked_pointer.unlock for details. + + When unlocking, the compositor may warp the cursor position to the set + cursor position hint. If it does, it will not result in any relative + motion events emitted via wp_relative_pointer. + + If the surface the lock was requested on is destroyed and the lock is not + yet activated, the wp_locked_pointer object is now defunct and must be + destroyed. + + + + + Destroy the locked pointer object. If applicable, the compositor will + unlock the pointer. + + + + + + Set the cursor position hint relative to the top left corner of the + surface. + + If the client is drawing its own cursor, it should update the position + hint to the position of its own cursor. A compositor may use this + information to warp the pointer upon unlock in order to avoid pointer + jumps. + + The cursor position hint is double-buffered state, see + wl_surface.commit. + + + + + + + + Set a new region used to lock the pointer. + + The new lock region is double-buffered, see wl_surface.commit. + + For details about the lock region, see wp_locked_pointer. + + + + + + + Notification that the pointer lock of the seat's pointer is activated. + + + + + + Notification that the pointer lock of the seat's pointer is no longer + active. If this is a oneshot pointer lock (see + wp_pointer_constraints.lifetime) this object is now defunct and should + be destroyed. If this is a persistent pointer lock (see + wp_pointer_constraints.lifetime) this pointer lock may again + reactivate in the future. + + + + + + + The wp_confined_pointer interface represents a confined pointer state. + + This object will send the event 'confined' when the confinement is + activated. Whenever the confinement is activated, it is guaranteed that + the surface the pointer is confined to will already have received pointer + focus and that the pointer will be within the region passed to the request + creating this object. It is up to the compositor to decide whether this + requires some user interaction and if the pointer will warp to within the + passed region if outside. + + To unconfine the pointer, send the destroy request. This will also destroy + the wp_confined_pointer object. + + If the compositor decides to unconfine the pointer the unconfined event is + sent. The wp_confined_pointer object is at this point defunct and should + be destroyed. + + + + + Destroy the confined pointer object. If applicable, the compositor will + unconfine the pointer. + + + + + + Set a new region used to confine the pointer. + + The new confine region is double-buffered, see wl_surface.commit. + + If the confinement is active when the new confinement region is applied + and the pointer ends up outside of newly applied region, the pointer may + warped to a position within the new confinement region. If warped, a + wl_pointer.motion event will be emitted, but no + wp_relative_pointer.relative_motion event. + + The compositor may also, instead of using the new region, unconfine the + pointer. + + For details about the confine region, see wp_confined_pointer. + + + + + + + Notification that the pointer confinement of the seat's pointer is + activated. + + + + + + Notification that the pointer confinement of the seat's pointer is no + longer active. If this is a oneshot pointer confinement (see + wp_pointer_constraints.lifetime) this object is now defunct and should + be destroyed. If this is a persistent pointer confinement (see + wp_pointer_constraints.lifetime) this pointer confinement may again + reactivate in the future. + + + + + diff --git a/src/window/wayland/protocols/relative-pointer-unstable-v1.xml b/src/window/wayland/protocols/relative-pointer-unstable-v1.xml new file mode 100644 index 000000000..ca6f81d12 --- /dev/null +++ b/src/window/wayland/protocols/relative-pointer-unstable-v1.xml @@ -0,0 +1,136 @@ + + + + + Copyright © 2014 Jonas Ådahl + Copyright © 2015 Red Hat Inc. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol specifies a set of interfaces used for making clients able to + receive relative pointer events not obstructed by barriers (such as the + monitor edge or other pointer barriers). + + To start receiving relative pointer events, a client must first bind the + global interface "wp_relative_pointer_manager" which, if a compositor + supports relative pointer motion events, is exposed by the registry. After + having created the relative pointer manager proxy object, the client uses + it to create the actual relative pointer object using the + "get_relative_pointer" request given a wl_pointer. The relative pointer + motion events will then, when applicable, be transmitted via the proxy of + the newly created relative pointer object. See the documentation of the + relative pointer interface for more details. + + Warning! The protocol described in this file is experimental and backward + incompatible changes may be made. Backward compatible changes may be added + together with the corresponding interface version bump. Backward + incompatible changes are done by bumping the version number in the protocol + and interface names and resetting the interface version. Once the protocol + is to be declared stable, the 'z' prefix and the version number in the + protocol and interface names are removed and the interface version number is + reset. + + + + + A global interface used for getting the relative pointer object for a + given pointer. + + + + + Used by the client to notify the server that it will no longer use this + relative pointer manager object. + + + + + + Create a relative pointer interface given a wl_pointer object. See the + wp_relative_pointer interface for more details. + + + + + + + + + A wp_relative_pointer object is an extension to the wl_pointer interface + used for emitting relative pointer events. It shares the same focus as + wl_pointer objects of the same seat and will only emit events when it has + focus. + + + + + + + + + Relative x/y pointer motion from the pointer of the seat associated with + this object. + + A relative motion is in the same dimension as regular wl_pointer motion + events, except they do not represent an absolute position. For example, + moving a pointer from (x, y) to (x', y') would have the equivalent + relative motion (x' - x, y' - y). If a pointer motion caused the + absolute pointer position to be clipped by for example the edge of the + monitor, the relative motion is unaffected by the clipping and will + represent the unclipped motion. + + This event also contains non-accelerated motion deltas. The + non-accelerated delta is, when applicable, the regular pointer motion + delta as it was before having applied motion acceleration and other + transformations such as normalization. + + Note that the non-accelerated delta does not represent 'raw' events as + they were read from some device. Pointer motion acceleration is device- + and configuration-specific and non-accelerated deltas and accelerated + deltas may have the same value on some devices. + + Relative motions are not coupled to wl_pointer.motion events, and can be + sent in combination with such events, but also independently. There may + also be scenarios where wl_pointer.motion is sent, but there is no + relative motion. The order of an absolute and relative motion event + originating from the same physical motion is not guaranteed. + + If the client needs button events or focus state, it can receive them + from a wl_pointer object of the same seat that the wp_relative_pointer + object is associated with. + + + + + + + + + + + diff --git a/src/window/wayland/protocols/tablet-unstable-v2.xml b/src/window/wayland/protocols/tablet-unstable-v2.xml new file mode 100644 index 000000000..d78b141fb --- /dev/null +++ b/src/window/wayland/protocols/tablet-unstable-v2.xml @@ -0,0 +1,1182 @@ + + + + + Copyright 2014 © Stephen "Lyude" Chandler Paul + Copyright 2015-2016 © Red Hat, Inc. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice (including the + next paragraph) shall be included in all copies or substantial + portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + + + This description provides a high-level overview of the interplay between + the interfaces defined this protocol. For details, see the protocol + specification. + + More than one tablet may exist, and device-specifics matter. Tablets are + not represented by a single virtual device like wl_pointer. A client + binds to the tablet manager object which is just a proxy object. From + that, the client requests wp_tablet_manager.get_tablet_seat(wl_seat) + and that returns the actual interface that has all the tablets. With + this indirection, we can avoid merging wp_tablet into the actual Wayland + protocol, a long-term benefit. + + The wp_tablet_seat sends a "tablet added" event for each tablet + connected. That event is followed by descriptive events about the + hardware; currently that includes events for name, vid/pid and + a wp_tablet.path event that describes a local path. This path can be + used to uniquely identify a tablet or get more information through + libwacom. Emulated or nested tablets can skip any of those, e.g. a + virtual tablet may not have a vid/pid. The sequence of descriptive + events is terminated by a wp_tablet.done event to signal that a client + may now finalize any initialization for that tablet. + + Events from tablets require a tool in proximity. Tools are also managed + by the tablet seat; a "tool added" event is sent whenever a tool is new + to the compositor. That event is followed by a number of descriptive + events about the hardware; currently that includes capabilities, + hardware id and serial number, and tool type. Similar to the tablet + interface, a wp_tablet_tool.done event is sent to terminate that initial + sequence. + + Any event from a tool happens on the wp_tablet_tool interface. When the + tool gets into proximity of the tablet, a proximity_in event is sent on + the wp_tablet_tool interface, listing the tablet and the surface. That + event is followed by a motion event with the coordinates. After that, + it's the usual motion, axis, button, etc. events. The protocol's + serialisation means events are grouped by wp_tablet_tool.frame events. + + Two special events (that don't exist in X) are down and up. They signal + "tip touching the surface". For tablets without real proximity + detection, the sequence is: proximity_in, motion, down, frame. + + When the tool leaves proximity, a proximity_out event is sent. If any + button is still down, a button release event is sent before this + proximity event. These button events are sent in the same frame as the + proximity event to signal to the client that the buttons were held when + the tool left proximity. + + If the tool moves out of the surface but stays in proximity (i.e. + between windows), compositor-specific grab policies apply. This usually + means that the proximity-out is delayed until all buttons are released. + + Moving a tool physically from one tablet to the other has no real effect + on the protocol, since we already have the tool object from the "tool + added" event. All the information is already there and the proximity + events on both tablets are all a client needs to reconstruct what + happened. + + Some extra axes are normalized, i.e. the client knows the range as + specified in the protocol (e.g. [0, 65535]), the granularity however is + unknown. The current normalized axes are pressure, distance, and slider. + + Other extra axes are in physical units as specified in the protocol. + The current extra axes with physical units are tilt, rotation and + wheel rotation. + + Since tablets work independently of the pointer controlled by the mouse, + the focus handling is independent too and controlled by proximity. + The wp_tablet_tool.set_cursor request sets a tool-specific cursor. + This cursor surface may be the same as the mouse cursor, and it may be + the same across tools but it is possible to be more fine-grained. For + example, a client may set different cursors for the pen and eraser. + + Tools are generally independent of tablets and it is + compositor-specific policy when a tool can be removed. Common approaches + will likely include some form of removing a tool when all tablets the + tool was used on are removed. + + Disclaimer: This protocol extension has been marked stable. This copy is + no longer used and only retained for backwards compatibility. The + canonical version can be found in the stable/ directory. + + + + + An object that provides access to the graphics tablets available on this + system. All tablets are associated with a seat, to get access to the + actual tablets, use wp_tablet_manager.get_tablet_seat. + + + + + Get the wp_tablet_seat object for the given seat. This object + provides access to all graphics tablets in this seat. + + + + + + + + Destroy the wp_tablet_manager object. Objects created from this + object are unaffected and should be destroyed separately. + + + + + + + An object that provides access to the graphics tablets available on this + seat. After binding to this interface, the compositor sends a set of + wp_tablet_seat.tablet_added and wp_tablet_seat.tool_added events. + + + + + Destroy the wp_tablet_seat object. Objects created from this + object are unaffected and should be destroyed separately. + + + + + + This event is sent whenever a new tablet becomes available on this + seat. This event only provides the object id of the tablet, any + static information about the tablet (device name, vid/pid, etc.) is + sent through the wp_tablet interface. + + + + + + + This event is sent whenever a tool that has not previously been used + with a tablet comes into use. This event only provides the object id + of the tool; any static information about the tool (capabilities, + type, etc.) is sent through the wp_tablet_tool interface. + + + + + + + This event is sent whenever a new pad is known to the system. Typically, + pads are physically attached to tablets and a pad_added event is + sent immediately after the wp_tablet_seat.tablet_added. + However, some standalone pad devices logically attach to tablets at + runtime, and the client must wait for wp_tablet_pad.enter to know + the tablet a pad is attached to. + + This event only provides the object id of the pad. All further + features (buttons, strips, rings) are sent through the wp_tablet_pad + interface. + + + + + + + + An object that represents a physical tool that has been, or is + currently in use with a tablet in this seat. Each wp_tablet_tool + object stays valid until the client destroys it; the compositor + reuses the wp_tablet_tool object to indicate that the object's + respective physical tool has come into proximity of a tablet again. + + A wp_tablet_tool object's relation to a physical tool depends on the + tablet's ability to report serial numbers. If the tablet supports + this capability, then the object represents a specific physical tool + and can be identified even when used on multiple tablets. + + A tablet tool has a number of static characteristics, e.g. tool type, + hardware_serial and capabilities. These capabilities are sent in an + event sequence after the wp_tablet_seat.tool_added event before any + actual events from this tool. This initial event sequence is + terminated by a wp_tablet_tool.done event. + + Tablet tool events are grouped by wp_tablet_tool.frame events. + Any events received before a wp_tablet_tool.frame event should be + considered part of the same hardware state change. + + + + + Sets the surface of the cursor used for this tool on the given + tablet. This request only takes effect if the tool is in proximity + of one of the requesting client's surfaces or the surface parameter + is the current pointer surface. If there was a previous surface set + with this request it is replaced. If surface is NULL, the cursor + image is hidden. + + The parameters hotspot_x and hotspot_y define the position of the + pointer surface relative to the pointer location. Its top-left corner + is always at (x, y) - (hotspot_x, hotspot_y), where (x, y) are the + coordinates of the pointer location, in surface-local coordinates. + + On surface.attach requests to the pointer surface, hotspot_x and + hotspot_y are decremented by the x and y parameters passed to the + request. Attach must be confirmed by wl_surface.commit as usual. + + The hotspot can also be updated by passing the currently set pointer + surface to this request with new values for hotspot_x and hotspot_y. + + The current and pending input regions of the wl_surface are cleared, + and wl_surface.set_input_region is ignored until the wl_surface is no + longer used as the cursor. When the use as a cursor ends, the current + and pending input regions become undefined, and the wl_surface is + unmapped. + + This request gives the surface the role of a wp_tablet_tool cursor. A + surface may only ever be used as the cursor surface for one + wp_tablet_tool. If the surface already has another role or has + previously been used as cursor surface for a different tool, a + protocol error is raised. + + + + + + + + + + This destroys the client's resource for this tool object. + + + + + + Describes the physical type of a tool. The physical type of a tool + generally defines its base usage. + + The mouse tool represents a mouse-shaped tool that is not a relative + device but bound to the tablet's surface, providing absolute + coordinates. + + The lens tool is a mouse-shaped tool with an attached lens to + provide precision focus. + + + + + + + + + + + + + + The tool type is the high-level type of the tool and usually decides + the interaction expected from this tool. + + This event is sent in the initial burst of events before the + wp_tablet_tool.done event. + + + + + + + If the physical tool can be identified by a unique 64-bit serial + number, this event notifies the client of this serial number. + + If multiple tablets are available in the same seat and the tool is + uniquely identifiable by the serial number, that tool may move + between tablets. + + Otherwise, if the tool has no serial number and this event is + missing, the tool is tied to the tablet it first comes into + proximity with. Even if the physical tool is used on multiple + tablets, separate wp_tablet_tool objects will be created, one per + tablet. + + This event is sent in the initial burst of events before the + wp_tablet_tool.done event. + + + + + + + + This event notifies the client of a hardware id available on this tool. + + The hardware id is a device-specific 64-bit id that provides extra + information about the tool in use, beyond the wl_tool.type + enumeration. The format of the id is specific to tablets made by + Wacom Inc. For example, the hardware id of a Wacom Grip + Pen (a stylus) is 0x802. + + This event is sent in the initial burst of events before the + wp_tablet_tool.done event. + + + + + + + + Describes extra capabilities on a tablet. + + Any tool must provide x and y values, extra axes are + device-specific. + + + + + + + + + + + + This event notifies the client of any capabilities of this tool, + beyond the main set of x/y axes and tip up/down detection. + + One event is sent for each extra capability available on this tool. + + This event is sent in the initial burst of events before the + wp_tablet_tool.done event. + + + + + + + This event signals the end of the initial burst of descriptive + events. A client may consider the static description of the tool to + be complete and finalize initialization of the tool. + + + + + + This event is sent when the tool is removed from the system and will + send no further events. Should the physical tool come back into + proximity later, a new wp_tablet_tool object will be created. + + It is compositor-dependent when a tool is removed. A compositor may + remove a tool on proximity out, tablet removal or any other reason. + A compositor may also keep a tool alive until shutdown. + + If the tool is currently in proximity, a proximity_out event will be + sent before the removed event. See wp_tablet_tool.proximity_out for + the handling of any buttons logically down. + + When this event is received, the client must wp_tablet_tool.destroy + the object. + + + + + + Notification that this tool is focused on a certain surface. + + This event can be received when the tool has moved from one surface to + another, or when the tool has come back into proximity above the + surface. + + If any button is logically down when the tool comes into proximity, + the respective button event is sent after the proximity_in event but + within the same frame as the proximity_in event. + + + + + + + + + Notification that this tool has either left proximity, or is no + longer focused on a certain surface. + + When the tablet tool leaves proximity of the tablet, button release + events are sent for each button that was held down at the time of + leaving proximity. These events are sent before the proximity_out + event but within the same wp_tablet.frame. + + If the tool stays within proximity of the tablet, but the focus + changes from one surface to another, a button release event may not + be sent until the button is actually released or the tool leaves the + proximity of the tablet. + + + + + + Sent whenever the tablet tool comes in contact with the surface of the + tablet. + + If the tool is already in contact with the tablet when entering the + input region, the client owning said region will receive a + wp_tablet.proximity_in event, followed by a wp_tablet.down + event and a wp_tablet.frame event. + + Note that this event describes logical contact, not physical + contact. On some devices, a compositor may not consider a tool in + logical contact until a minimum physical pressure threshold is + exceeded. + + + + + + + Sent whenever the tablet tool stops making contact with the surface of + the tablet, or when the tablet tool moves out of the input region + and the compositor grab (if any) is dismissed. + + If the tablet tool moves out of the input region while in contact + with the surface of the tablet and the compositor does not have an + ongoing grab on the surface, the client owning said region will + receive a wp_tablet.up event, followed by a wp_tablet.proximity_out + event and a wp_tablet.frame event. If the compositor has an ongoing + grab on this device, this event sequence is sent whenever the grab + is dismissed in the future. + + Note that this event describes logical contact, not physical + contact. On some devices, a compositor may not consider a tool out + of logical contact until physical pressure falls below a specific + threshold. + + + + + + Sent whenever a tablet tool moves. + + + + + + + + Sent whenever the pressure axis on a tool changes. The value of this + event is normalized to a value between 0 and 65535. + + Note that pressure may be nonzero even when a tool is not in logical + contact. See the down and up events for more details. + + + + + + + Sent whenever the distance axis on a tool changes. The value of this + event is normalized to a value between 0 and 65535. + + Note that distance may be nonzero even when a tool is not in logical + contact. See the down and up events for more details. + + + + + + + Sent whenever one or both of the tilt axes on a tool change. Each tilt + value is in degrees, relative to the z-axis of the tablet. + The angle is positive when the top of a tool tilts along the + positive x or y axis. + + + + + + + + Sent whenever the z-rotation axis on the tool changes. The + rotation value is in degrees clockwise from the tool's + logical neutral position. + + + + + + + Sent whenever the slider position on the tool changes. The + value is normalized between -65535 and 65535, with 0 as the logical + neutral position of the slider. + + The slider is available on e.g. the Wacom Airbrush tool. + + + + + + + Sent whenever the wheel on the tool emits an event. This event + contains two values for the same axis change. The degrees value is + in the same orientation as the wl_pointer.vertical_scroll axis. The + clicks value is in discrete logical clicks of the mouse wheel. This + value may be zero if the movement of the wheel was less + than one logical click. + + Clients should choose either value and avoid mixing degrees and + clicks. The compositor may accumulate values smaller than a logical + click and emulate click events when a certain threshold is met. + Thus, wl_tablet_tool.wheel events with non-zero clicks values may + have different degrees values. + + + + + + + + Describes the physical state of a button that produced the button event. + + + + + + + + Sent whenever a button on the tool is pressed or released. + + If a button is held down when the tool moves in or out of proximity, + button events are generated by the compositor. See + wp_tablet_tool.proximity_in and wp_tablet_tool.proximity_out for + details. + + + + + + + + + Marks the end of a series of axis and/or button updates from the + tablet. The Wayland protocol requires axis updates to be sent + sequentially, however all events within a frame should be considered + one hardware event. + + + + + + + + + + + + The wp_tablet interface represents one graphics tablet device. The + tablet interface itself does not generate events; all events are + generated by wp_tablet_tool objects when in proximity above a tablet. + + A tablet has a number of static characteristics, e.g. device name and + pid/vid. These capabilities are sent in an event sequence after the + wp_tablet_seat.tablet_added event. This initial event sequence is + terminated by a wp_tablet.done event. + + + + + This destroys the client's resource for this tablet object. + + + + + + A descriptive name for the tablet device. + + If the device has no descriptive name, this event is not sent. + + This event is sent in the initial burst of events before the + wp_tablet.done event. + + + + + + + The USB vendor and product IDs for the tablet device. + + If the device has no USB vendor/product ID, this event is not sent. + This can happen for virtual devices or non-USB devices, for instance. + + This event is sent in the initial burst of events before the + wp_tablet.done event. + + + + + + + + A system-specific device path that indicates which device is behind + this wp_tablet. This information may be used to gather additional + information about the device, e.g. through libwacom. + + A device may have more than one device path. If so, multiple + wp_tablet.path events are sent. A device may be emulated and not + have a device path, and in that case this event will not be sent. + + The format of the path is unspecified, it may be a device node, a + sysfs path, or some other identifier. It is up to the client to + identify the string provided. + + This event is sent in the initial burst of events before the + wp_tablet.done event. + + + + + + + This event is sent immediately to signal the end of the initial + burst of descriptive events. A client may consider the static + description of the tablet to be complete and finalize initialization + of the tablet. + + + + + + Sent when the tablet has been removed from the system. When a tablet + is removed, some tools may be removed. + + When this event is received, the client must wp_tablet.destroy + the object. + + + + + + + A circular interaction area, such as the touch ring on the Wacom Intuos + Pro series tablets. + + Events on a ring are logically grouped by the wl_tablet_pad_ring.frame + event. + + + + + Request that the compositor use the provided feedback string + associated with this ring. This request should be issued immediately + after a wp_tablet_pad_group.mode_switch event from the corresponding + group is received, or whenever the ring is mapped to a different + action. See wp_tablet_pad_group.mode_switch for more details. + + Clients are encouraged to provide context-aware descriptions for + the actions associated with the ring; compositors may use this + information to offer visual feedback about the button layout + (eg. on-screen displays). + + The provided string 'description' is a UTF-8 encoded string to be + associated with this ring, and is considered user-visible; general + internationalization rules apply. + + The serial argument will be that of the last + wp_tablet_pad_group.mode_switch event received for the group of this + ring. Requests providing other serials than the most recent one will be + ignored. + + + + + + + + This destroys the client's resource for this ring object. + + + + + + Describes the source types for ring events. This indicates to the + client how a ring event was physically generated; a client may + adjust the user interface accordingly. For example, events + from a "finger" source may trigger kinetic scrolling. + + + + + + + Source information for ring events. + + This event does not occur on its own. It is sent before a + wp_tablet_pad_ring.frame event and carries the source information + for all events within that frame. + + The source specifies how this event was generated. If the source is + wp_tablet_pad_ring.source.finger, a wp_tablet_pad_ring.stop event + will be sent when the user lifts the finger off the device. + + This event is optional. If the source is unknown for an interaction, + no event is sent. + + + + + + + Sent whenever the angle on a ring changes. + + The angle is provided in degrees clockwise from the logical + north of the ring in the pad's current rotation. + + + + + + + Stop notification for ring events. + + For some wp_tablet_pad_ring.source types, a wp_tablet_pad_ring.stop + event is sent to notify a client that the interaction with the ring + has terminated. This enables the client to implement kinetic scrolling. + See the wp_tablet_pad_ring.source documentation for information on + when this event may be generated. + + Any wp_tablet_pad_ring.angle events with the same source after this + event should be considered as the start of a new interaction. + + + + + + Indicates the end of a set of ring events that logically belong + together. A client is expected to accumulate the data in all events + within the frame before proceeding. + + All wp_tablet_pad_ring events before a wp_tablet_pad_ring.frame event belong + logically together. For example, on termination of a finger interaction + on a ring the compositor will send a wp_tablet_pad_ring.source event, + a wp_tablet_pad_ring.stop event and a wp_tablet_pad_ring.frame event. + + A wp_tablet_pad_ring.frame event is sent for every logical event + group, even if the group only contains a single wp_tablet_pad_ring + event. Specifically, a client may get a sequence: angle, frame, + angle, frame, etc. + + + + + + + + A linear interaction area, such as the strips found in Wacom Cintiq + models. + + Events on a strip are logically grouped by the wl_tablet_pad_strip.frame + event. + + + + + Requests the compositor to use the provided feedback string + associated with this strip. This request should be issued immediately + after a wp_tablet_pad_group.mode_switch event from the corresponding + group is received, or whenever the strip is mapped to a different + action. See wp_tablet_pad_group.mode_switch for more details. + + Clients are encouraged to provide context-aware descriptions for + the actions associated with the strip, and compositors may use this + information to offer visual feedback about the button layout + (eg. on-screen displays). + + The provided string 'description' is a UTF-8 encoded string to be + associated with this ring, and is considered user-visible; general + internationalization rules apply. + + The serial argument will be that of the last + wp_tablet_pad_group.mode_switch event received for the group of this + strip. Requests providing other serials than the most recent one will be + ignored. + + + + + + + + This destroys the client's resource for this strip object. + + + + + + Describes the source types for strip events. This indicates to the + client how a strip event was physically generated; a client may + adjust the user interface accordingly. For example, events + from a "finger" source may trigger kinetic scrolling. + + + + + + + Source information for strip events. + + This event does not occur on its own. It is sent before a + wp_tablet_pad_strip.frame event and carries the source information + for all events within that frame. + + The source specifies how this event was generated. If the source is + wp_tablet_pad_strip.source.finger, a wp_tablet_pad_strip.stop event + will be sent when the user lifts their finger off the device. + + This event is optional. If the source is unknown for an interaction, + no event is sent. + + + + + + + Sent whenever the position on a strip changes. + + The position is normalized to a range of [0, 65535], the 0-value + represents the top-most and/or left-most position of the strip in + the pad's current rotation. + + + + + + + Stop notification for strip events. + + For some wp_tablet_pad_strip.source types, a wp_tablet_pad_strip.stop + event is sent to notify a client that the interaction with the strip + has terminated. This enables the client to implement kinetic + scrolling. See the wp_tablet_pad_strip.source documentation for + information on when this event may be generated. + + Any wp_tablet_pad_strip.position events with the same source after this + event should be considered as the start of a new interaction. + + + + + + Indicates the end of a set of events that represent one logical + hardware strip event. A client is expected to accumulate the data + in all events within the frame before proceeding. + + All wp_tablet_pad_strip events before a wp_tablet_pad_strip.frame event belong + logically together. For example, on termination of a finger interaction + on a strip the compositor will send a wp_tablet_pad_strip.source event, + a wp_tablet_pad_strip.stop event and a wp_tablet_pad_strip.frame + event. + + A wp_tablet_pad_strip.frame event is sent for every logical event + group, even if the group only contains a single wp_tablet_pad_strip + event. Specifically, a client may get a sequence: position, frame, + position, frame, etc. + + + + + + + + A pad group describes a distinct (sub)set of buttons, rings and strips + present in the tablet. The criteria of this grouping is usually positional, + eg. if a tablet has buttons on the left and right side, 2 groups will be + presented. The physical arrangement of groups is undisclosed and may + change on the fly. + + Pad groups will announce their features during pad initialization. Between + the corresponding wp_tablet_pad.group event and wp_tablet_pad_group.done, the + pad group will announce the buttons, rings and strips contained in it, + plus the number of supported modes. + + Modes are a mechanism to allow multiple groups of actions for every element + in the pad group. The number of groups and available modes in each is + persistent across device plugs. The current mode is user-switchable, it + will be announced through the wp_tablet_pad_group.mode_switch event both + whenever it is switched, and after wp_tablet_pad.enter. + + The current mode logically applies to all elements in the pad group, + although it is at clients' discretion whether to actually perform different + actions, and/or issue the respective .set_feedback requests to notify the + compositor. See the wp_tablet_pad_group.mode_switch event for more details. + + + + + Destroy the wp_tablet_pad_group object. Objects created from this object + are unaffected and should be destroyed separately. + + + + + + Sent on wp_tablet_pad_group initialization to announce the available + buttons in the group. Button indices start at 0, a button may only be + in one group at a time. + + This event is first sent in the initial burst of events before the + wp_tablet_pad_group.done event. + + Some buttons are reserved by the compositor. These buttons may not be + assigned to any wp_tablet_pad_group. Compositors may broadcast this + event in the case of changes to the mapping of these reserved buttons. + If the compositor happens to reserve all buttons in a group, this event + will be sent with an empty array. + + + + + + + Sent on wp_tablet_pad_group initialization to announce available rings. + One event is sent for each ring available on this pad group. + + This event is sent in the initial burst of events before the + wp_tablet_pad_group.done event. + + + + + + + Sent on wp_tablet_pad initialization to announce available strips. + One event is sent for each strip available on this pad group. + + This event is sent in the initial burst of events before the + wp_tablet_pad_group.done event. + + + + + + + Sent on wp_tablet_pad_group initialization to announce that the pad + group may switch between modes. A client may use a mode to store a + specific configuration for buttons, rings and strips and use the + wl_tablet_pad_group.mode_switch event to toggle between these + configurations. Mode indices start at 0. + + Switching modes is compositor-dependent. See the + wp_tablet_pad_group.mode_switch event for more details. + + This event is sent in the initial burst of events before the + wp_tablet_pad_group.done event. This event is only sent when more than + more than one mode is available. + + + + + + + This event is sent immediately to signal the end of the initial + burst of descriptive events. A client may consider the static + description of the tablet to be complete and finalize initialization + of the tablet group. + + + + + + Notification that the mode was switched. + + A mode applies to all buttons, rings and strips in a group + simultaneously, but a client is not required to assign different actions + for each mode. For example, a client may have mode-specific button + mappings but map the ring to vertical scrolling in all modes. Mode + indices start at 0. + + Switching modes is compositor-dependent. The compositor may provide + visual cues to the client about the mode, e.g. by toggling LEDs on + the tablet device. Mode-switching may be software-controlled or + controlled by one or more physical buttons. For example, on a Wacom + Intuos Pro, the button inside the ring may be assigned to switch + between modes. + + The compositor will also send this event after wp_tablet_pad.enter on + each group in order to notify of the current mode. Groups that only + feature one mode will use mode=0 when emitting this event. + + If a button action in the new mode differs from the action in the + previous mode, the client should immediately issue a + wp_tablet_pad.set_feedback request for each changed button. + + If a ring or strip action in the new mode differs from the action + in the previous mode, the client should immediately issue a + wp_tablet_ring.set_feedback or wp_tablet_strip.set_feedback request + for each changed ring or strip. + + + + + + + + + + A pad device is a set of buttons, rings and strips + usually physically present on the tablet device itself. Some + exceptions exist where the pad device is physically detached, e.g. the + Wacom ExpressKey Remote. + + Pad devices have no axes that control the cursor and are generally + auxiliary devices to the tool devices used on the tablet surface. + + A pad device has a number of static characteristics, e.g. the number + of rings. These capabilities are sent in an event sequence after the + wp_tablet_seat.pad_added event before any actual events from this pad. + This initial event sequence is terminated by a wp_tablet_pad.done + event. + + All pad features (buttons, rings and strips) are logically divided into + groups and all pads have at least one group. The available groups are + notified through the wp_tablet_pad.group event; the compositor will + emit one event per group before emitting wp_tablet_pad.done. + + Groups may have multiple modes. Modes allow clients to map multiple + actions to a single pad feature. Only one mode can be active per group, + although different groups may have different active modes. + + + + + Requests the compositor to use the provided feedback string + associated with this button. This request should be issued immediately + after a wp_tablet_pad_group.mode_switch event from the corresponding + group is received, or whenever a button is mapped to a different + action. See wp_tablet_pad_group.mode_switch for more details. + + Clients are encouraged to provide context-aware descriptions for + the actions associated with each button, and compositors may use + this information to offer visual feedback on the button layout + (e.g. on-screen displays). + + Button indices start at 0. Setting the feedback string on a button + that is reserved by the compositor (i.e. not belonging to any + wp_tablet_pad_group) does not generate an error but the compositor + is free to ignore the request. + + The provided string 'description' is a UTF-8 encoded string to be + associated with this ring, and is considered user-visible; general + internationalization rules apply. + + The serial argument will be that of the last + wp_tablet_pad_group.mode_switch event received for the group of this + button. Requests providing other serials than the most recent one will + be ignored. + + + + + + + + + Destroy the wp_tablet_pad object. Objects created from this object + are unaffected and should be destroyed separately. + + + + + + Sent on wp_tablet_pad initialization to announce available groups. + One event is sent for each pad group available. + + This event is sent in the initial burst of events before the + wp_tablet_pad.done event. At least one group will be announced. + + + + + + + A system-specific device path that indicates which device is behind + this wp_tablet_pad. This information may be used to gather additional + information about the device, e.g. through libwacom. + + The format of the path is unspecified, it may be a device node, a + sysfs path, or some other identifier. It is up to the client to + identify the string provided. + + This event is sent in the initial burst of events before the + wp_tablet_pad.done event. + + + + + + + Sent on wp_tablet_pad initialization to announce the available + buttons. + + This event is sent in the initial burst of events before the + wp_tablet_pad.done event. This event is only sent when at least one + button is available. + + + + + + + This event signals the end of the initial burst of descriptive + events. A client may consider the static description of the pad to + be complete and finalize initialization of the pad. + + + + + + Describes the physical state of a button that caused the button + event. + + + + + + + + Sent whenever the physical state of a button changes. + + + + + + + + + Notification that this pad is focused on the specified surface. + + + + + + + + + Notification that this pad is no longer focused on the specified + surface. + + + + + + + + Sent when the pad has been removed from the system. When a tablet + is removed its pad(s) will be removed too. + + When this event is received, the client must destroy all rings, strips + and groups that were offered by this pad, and issue wp_tablet_pad.destroy + the pad itself. + + + + diff --git a/src/window/wayland/protocols/xdg-decoration-unstable-v1.xml b/src/window/wayland/protocols/xdg-decoration-unstable-v1.xml new file mode 100644 index 000000000..023589ad0 --- /dev/null +++ b/src/window/wayland/protocols/xdg-decoration-unstable-v1.xml @@ -0,0 +1,176 @@ + + + + Copyright © 2018 Simon Ser + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + This interface allows a compositor to announce support for server-side + decorations. + + A window decoration is a set of window controls as deemed appropriate by + the party managing them, such as user interface components used to move, + resize and change a window's state. + + A client can use this protocol to request being decorated by a supporting + compositor. + + If compositor and client do not negotiate the use of a server-side + decoration using this protocol, clients continue to self-decorate as they + see fit. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + Destroy the decoration manager. This doesn't destroy objects created + with the manager. + + + + + + Create a new decoration object associated with the given toplevel. + + For objects of version 1, creating an xdg_toplevel_decoration from an + xdg_toplevel which has a buffer attached or committed is a client + error, and any attempts by a client to attach or manipulate a buffer + prior to the first xdg_toplevel_decoration.configure event must also be + treated as errors. + + For objects of version 2 or newer, creating an xdg_toplevel_decoration + from an xdg_toplevel which has a buffer attached or committed is + allowed. The initial decoration mode of the surface if a buffer is + already attached depends on whether a xdg_toplevel_decoration object + has been associated with the surface or not prior to this request. + + If an xdg_toplevel_decoration was associated with the surface, then + destroyed without a surface commit, the previous decoration mode is + retained. + + If no xdg_toplevel_decoration was associated with the surface prior to + this request, or if a surface commit has been performed after a previous + xdg_toplevel_decoration object associated with the surface was + destroyed, the decoration mode is assumed to be client-side. + + + + + + + + + The decoration object allows the compositor to toggle server-side window + decorations for a toplevel surface. The client can request to switch to + another mode. + + The xdg_toplevel_decoration object must be destroyed before its + xdg_toplevel. + + + + + + + + + + + + Switch back to a mode without any server-side decorations at the next + commit, unless a new xdg_toplevel_decoration is created for the surface + first. + + + + + + These values describe window decoration modes. + + + + + + + + Set the toplevel surface decoration mode. This informs the compositor + that the client prefers the provided decoration mode. + + After requesting a decoration mode, the compositor will respond by + emitting an xdg_surface.configure event. The client should then update + its content, drawing it without decorations if the received mode is + server-side decorations. The client must also acknowledge the configure + when committing the new content (see xdg_surface.ack_configure). + + The compositor can decide not to use the client's mode and enforce a + different mode instead. + + Clients whose decoration mode depend on the xdg_toplevel state may send + a set_mode request in response to an xdg_surface.configure event and wait + for the next xdg_surface.configure event to prevent unwanted state. + Such clients are responsible for preventing configure loops and must + make sure not to send multiple successive set_mode requests with the + same decoration mode. + + If an invalid mode is supplied by the client, the invalid_mode protocol + error is raised by the compositor. + + + + + + + Unset the toplevel surface decoration mode. This informs the compositor + that the client doesn't prefer a particular decoration mode. + + This request has the same semantics as set_mode. + + + + + + The configure event configures the effective decoration mode. The + configured state should not be applied immediately. Clients must send an + ack_configure in response to this event. See xdg_surface.configure and + xdg_surface.ack_configure for details. + + A configure event can be sent at any time. The specified mode must be + obeyed by the client. + + + + + diff --git a/src/window/wayland/protocols/xdg-shell.xml b/src/window/wayland/protocols/xdg-shell.xml new file mode 100644 index 000000000..f8b78eea7 --- /dev/null +++ b/src/window/wayland/protocols/xdg-shell.xml @@ -0,0 +1,1420 @@ + + + + + Copyright © 2008-2013 Kristian Høgsberg + Copyright © 2013 Rafael Antognolli + Copyright © 2013 Jasper St. Pierre + Copyright © 2010-2013 Intel Corporation + Copyright © 2015-2017 Samsung Electronics Co., Ltd + Copyright © 2015-2017 Red Hat Inc. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + The xdg_wm_base interface is exposed as a global object enabling clients + to turn their wl_surfaces into windows in a desktop environment. It + defines the basic functionality needed for clients and the compositor to + create windows that can be dragged, resized, maximized, etc, as well as + creating transient windows such as popup menus. + + + + + + + + + + + + + + + Destroy this xdg_wm_base object. + + Destroying a bound xdg_wm_base object while there are surfaces + still alive created by this xdg_wm_base object instance is illegal + and will result in a defunct_surfaces error. + + + + + + Create a positioner object. A positioner object is used to position + surfaces relative to some parent surface. See the interface description + and xdg_surface.get_popup for details. + + + + + + + This creates an xdg_surface for the given surface. An xdg_surface is + used as basis to define a role to a given surface, such as xdg_toplevel + or xdg_popup. It also manages functionality shared between xdg_surface + based surface roles. + + While xdg_surface itself is not a role, the corresponding surface may + only be assigned a role extending xdg_surface, such as xdg_toplevel or + xdg_popup. It is illegal to create an xdg_surface for a wl_surface which + already has anassigned role and this will result in a role error. + + See the documentation of xdg_surface for more details about what an + xdg_surface is and how it is used. + + + + + + + + A client must respond to a ping event with a pong request or + the client may be deemed unresponsive. See xdg_wm_base.ping + and xdg_wm_base.error.unresponsive. + + + + + + + The ping event asks the client if it's still alive. Pass the + serial specified in the event back to the compositor by sending + a "pong" request back with the specified serial. See xdg_wm_base.pong. + + Compositors can use this to determine if the client is still + alive. It's unspecified what will happen if the client doesn't + respond to the ping request, or in what timeframe. Clients should + try to respond in a reasonable amount of time. The “unresponsive” + error is provided for compositors that wish to disconnect unresponsive + clients. + + A compositor is free to ping in any way it wants, but a client must + always respond to any xdg_wm_base object it created. + + + + + + + + The xdg_positioner provides a collection of rules for the placement of a + child surface relative to a parent surface. Rules can be defined to ensure + the child surface remains within the visible area's borders, and to + specify how the child surface changes its position, such as sliding along + an axis, or flipping around a rectangle. These positioner-created rules are + constrained by the requirement that a child surface must intersect with or + be at least partially adjacent to its parent surface. + + See the various requests for details about possible rules. + + At the time of the request, the compositor makes a copy of the rules + specified by the xdg_positioner. Thus, after the request is complete the + xdg_positioner object can be destroyed or reused; further changes to the + object will have no effect on previous usages. + + For an xdg_positioner object to be considered complete, it must have a + non-zero size set by set_size, and a non-zero anchor rectangle set by + set_anchor_rect. Passing an incomplete xdg_positioner object when + positioning a surface raises an invalid_positioner error. + + + + + + + + + Notify the compositor that the xdg_positioner will no longer be used. + + + + + + Set the size of the surface that is to be positioned with the positioner + object. The size is in surface-local coordinates and corresponds to the + window geometry. See xdg_surface.set_window_geometry. + + If a zero or negative size is set the invalid_input error is raised. + + + + + + + + Specify the anchor rectangle within the parent surface that the child + surface will be placed relative to. The rectangle is relative to the + window geometry as defined by xdg_surface.set_window_geometry of the + parent surface. + + When the xdg_positioner object is used to position a child surface, the + anchor rectangle may not extend outside the window geometry of the + positioned child's parent surface. + + If a negative size is set the invalid_input error is raised. + + + + + + + + + + + + + + + + + + + + + + Defines the anchor point for the anchor rectangle. The specified anchor + is used to derive an anchor point that the child surface will be + positioned relative to. If a corner anchor is set (e.g. 'top_left' or + 'bottom_right'), the anchor point will be at the specified corner; + otherwise, the derived anchor point will be centered on the specified + edge, or in the center of the anchor rectangle if no edge is specified. + + + + + + + + + + + + + + + + + + + Defines in what direction a surface should be positioned, relative to + the anchor point of the parent surface. If a corner gravity is + specified (e.g. 'bottom_right' or 'top_left'), then the child surface + will be placed towards the specified gravity; otherwise, the child + surface will be centered over the anchor point on any axis that had no + gravity specified. If the gravity is not in the ‘gravity’ enum, an + invalid_input error is raised. + + + + + + + The constraint adjustment value define ways the compositor will adjust + the position of the surface, if the unadjusted position would result + in the surface being partly constrained. + + Whether a surface is considered 'constrained' is left to the compositor + to determine. For example, the surface may be partly outside the + compositor's defined 'work area', thus necessitating the child surface's + position be adjusted until it is entirely inside the work area. + + The adjustments can be combined, according to a defined precedence: 1) + Flip, 2) Slide, 3) Resize. + + + + Don't alter the surface position even if it is constrained on some + axis, for example partially outside the edge of an output. + + + + + Slide the surface along the x axis until it is no longer constrained. + + First try to slide towards the direction of the gravity on the x axis + until either the edge in the opposite direction of the gravity is + unconstrained or the edge in the direction of the gravity is + constrained. + + Then try to slide towards the opposite direction of the gravity on the + x axis until either the edge in the direction of the gravity is + unconstrained or the edge in the opposite direction of the gravity is + constrained. + + + + + Slide the surface along the y axis until it is no longer constrained. + + First try to slide towards the direction of the gravity on the y axis + until either the edge in the opposite direction of the gravity is + unconstrained or the edge in the direction of the gravity is + constrained. + + Then try to slide towards the opposite direction of the gravity on the + y axis until either the edge in the direction of the gravity is + unconstrained or the edge in the opposite direction of the gravity is + constrained. + + + + + Invert the anchor and gravity on the x axis if the surface is + constrained on the x axis. For example, if the left edge of the + surface is constrained, the gravity is 'left' and the anchor is + 'left', change the gravity to 'right' and the anchor to 'right'. + + If the adjusted position also ends up being constrained, the resulting + position of the flip_x adjustment will be the one before the + adjustment. + + + + + Invert the anchor and gravity on the y axis if the surface is + constrained on the y axis. For example, if the bottom edge of the + surface is constrained, the gravity is 'bottom' and the anchor is + 'bottom', change the gravity to 'top' and the anchor to 'top'. + + The adjusted position is calculated given the original anchor + rectangle and offset, but with the new flipped anchor and gravity + values. + + If the adjusted position also ends up being constrained, the resulting + position of the flip_y adjustment will be the one before the + adjustment. + + + + + Resize the surface horizontally so that it is completely + unconstrained. + + + + + Resize the surface vertically so that it is completely unconstrained. + + + + + + + Specify how the window should be positioned if the originally intended + position caused the surface to be constrained, meaning at least + partially outside positioning boundaries set by the compositor. The + adjustment is set by constructing a bitmask describing the adjustment to + be made when the surface is constrained on that axis. + + If no bit for one axis is set, the compositor will assume that the child + surface should not change its position on that axis when constrained. + + If more than one bit for one axis is set, the order of how adjustments + are applied is specified in the corresponding adjustment descriptions. + + The default adjustment is none. + + + + + + + Specify the surface position offset relative to the position of the + anchor on the anchor rectangle and the anchor on the surface. For + example if the anchor of the anchor rectangle is at (x, y), the surface + has the gravity bottom|right, and the offset is (ox, oy), the calculated + surface position will be (x + ox, y + oy). The offset position of the + surface is the one used for constraint testing. See + set_constraint_adjustment. + + An example use case is placing a popup menu on top of a user interface + element, while aligning the user interface element of the parent surface + with some user interface element placed somewhere in the popup surface. + + + + + + + + + + When set reactive, the surface is reconstrained if the conditions used + for constraining changed, e.g. the parent window moved. + + If the conditions changed and the popup was reconstrained, an + xdg_popup.configure event is sent with updated geometry, followed by an + xdg_surface.configure event. + + + + + + Set the parent window geometry the compositor should use when + positioning the popup. The compositor may use this information to + determine the future state the popup should be constrained using. If + this doesn't match the dimension of the parent the popup is eventually + positioned against, the behavior is undefined. + + The arguments are given in the surface-local coordinate space. + + + + + + + + Set the serial of an xdg_surface.configure event this positioner will be + used in response to. The compositor may use this information together + with set_parent_size to determine what future state the popup should be + constrained using. + + + + + + + + An interface that may be implemented by a wl_surface, for + implementations that provide a desktop-style user interface. + + It provides a base set of functionality required to construct user + interface elements requiring management by the compositor, such as + toplevel windows, menus, etc. The types of functionality are split into + xdg_surface roles. + + Creating an xdg_surface does not set the role for a wl_surface. In order + to map an xdg_surface, the client must create a role-specific object + using, e.g., get_toplevel, get_popup. The wl_surface for any given + xdg_surface can have at most one role, and may not be assigned any role + not based on xdg_surface. + + A role must be assigned before any other requests are made to the + xdg_surface object. + + The client must call wl_surface.commit on the corresponding wl_surface + for the xdg_surface state to take effect. + + Creating an xdg_surface from a wl_surface which has a buffer attached or + committed is a client error, and any attempts by a client to attach or + manipulate a buffer prior to the first xdg_surface.configure call must + also be treated as errors. + + After creating a role-specific object and setting it up (e.g. by sending + the title, app ID, size constraints, parent, etc), the client must + perform an initial commit without any buffer attached. The compositor + will reply with initial wl_surface state such as + wl_surface.preferred_buffer_scale followed by an xdg_surface.configure + event. The client must acknowledge it and is then allowed to attach a + buffer to map the surface. + + Mapping an xdg_surface-based role surface is defined as making it + possible for the surface to be shown by the compositor. Note that + a mapped surface is not guaranteed to be visible once it is mapped. + + For an xdg_surface to be mapped by the compositor, the following + conditions must be met: + (1) the client has assigned an xdg_surface-based role to the surface + (2) the client has set and committed the xdg_surface state and the + role-dependent state to the surface + (3) the client has committed a buffer to the surface + + A newly-unmapped surface is considered to have met condition (1) out + of the 3 required conditions for mapping a surface if its role surface + has not been destroyed, i.e. the client must perform the initial commit + again before attaching a buffer. + + + + + + + + + + + + + + Destroy the xdg_surface object. An xdg_surface must only be destroyed + after its role object has been destroyed, otherwise + a defunct_role_object error is raised. + + + + + + This creates an xdg_toplevel object for the given xdg_surface and gives + the associated wl_surface the xdg_toplevel role. + + See the documentation of xdg_toplevel for more details about what an + xdg_toplevel is and how it is used. + + + + + + + This creates an xdg_popup object for the given xdg_surface and gives + the associated wl_surface the xdg_popup role. + + If null is passed as a parent, a parent surface must be specified using + some other protocol, before committing the initial state. + + See the documentation of xdg_popup for more details about what an + xdg_popup is and how it is used. + + + + + + + + + The window geometry of a surface is its "visible bounds" from the + user's perspective. Client-side decorations often have invisible + portions like drop-shadows which should be ignored for the + purposes of aligning, placing and constraining windows. Note that + in some situations, compositors may clip rendering to the window + geometry, so the client should avoid putting functional elements + outside of it. + + The window geometry is double-buffered state, see wl_surface.commit. + + When maintaining a position, the compositor should treat the (x, y) + coordinate of the window geometry as the top left corner of the window. + A client changing the (x, y) window geometry coordinate should in + general not alter the position of the window. + + Once the window geometry of the surface is set, it is not possible to + unset it, and it will remain the same until set_window_geometry is + called again, even if a new subsurface or buffer is attached. + + If never set, the value is the full bounds of the surface, + including any subsurfaces. This updates dynamically on every + commit. This unset is meant for extremely simple clients. + + The arguments are given in the surface-local coordinate space of + the wl_surface associated with this xdg_surface, and may extend outside + of the wl_surface itself to mark parts of the subsurface tree as part of + the window geometry. + + When applied, the effective window geometry will be the set window + geometry clamped to the bounding rectangle of the combined + geometry of the surface of the xdg_surface and the associated + subsurfaces. + + The effective geometry will not be recalculated unless a new call to + set_window_geometry is done and the new pending surface state is + subsequently applied. + + The width and height of the effective window geometry must be + greater than zero. Setting an invalid size will raise an + invalid_size error. + + + + + + + + + + When a configure event is received, if a client commits the + surface in response to the configure event, then the client + must make an ack_configure request sometime before the commit + request, passing along the serial of the configure event. + + For instance, for toplevel surfaces the compositor might use this + information to move a surface to the top left only when the client has + drawn itself for the maximized or fullscreen state. + + If the client receives multiple configure events before it + can respond to one, it only has to ack the last configure event. + Acking a configure event that was never sent raises an invalid_serial + error. + + A client is not required to commit immediately after sending + an ack_configure request - it may even ack_configure several times + before its next surface commit. + + A client may send multiple ack_configure requests before committing, but + only the last request sent before a commit indicates which configure + event the client really is responding to. + + Sending an ack_configure request consumes the serial number sent with + the request, as well as serial numbers sent by all configure events + sent on this xdg_surface prior to the configure event referenced by + the committed serial. + + It is an error to issue multiple ack_configure requests referencing a + serial from the same configure event, or to issue an ack_configure + request referencing a serial from a configure event issued before the + event identified by the last ack_configure request for the same + xdg_surface. Doing so will raise an invalid_serial error. + + + + + + + The configure event marks the end of a configure sequence. A configure + sequence is a set of one or more events configuring the state of the + xdg_surface, including the final xdg_surface.configure event. + + Where applicable, xdg_surface surface roles will during a configure + sequence extend this event as a latched state sent as events before the + xdg_surface.configure event. Such events should be considered to make up + a set of atomically applied configuration states, where the + xdg_surface.configure commits the accumulated state. + + Clients should arrange their surface for the new states, and then send + an ack_configure request with the serial sent in this configure event at + some point before committing the new surface. + + If the client receives multiple configure events before it can respond + to one, it is free to discard all but the last event it received. + + + + + + + + + This interface defines an xdg_surface role which allows a surface to, + among other things, set window-like properties such as maximize, + fullscreen, and minimize, set application-specific metadata like title and + id, and well as trigger user interactive operations such as interactive + resize and move. + + An xdg_toplevel by default is responsible for providing the full intended + visual representation of the toplevel, which depending on the window + state, may mean things like a title bar, window controls and drop shadow. + + Unmapping an xdg_toplevel means that the surface cannot be shown + by the compositor until it is explicitly mapped again. + All active operations (e.g., move, resize) are canceled and all + attributes (e.g. title, state, stacking, ...) are discarded for + an xdg_toplevel surface when it is unmapped. The xdg_toplevel returns to + the state it had right after xdg_surface.get_toplevel. The client + can re-map the toplevel by performing a commit without any buffer + attached, waiting for a configure event and handling it as usual (see + xdg_surface description). + + Attaching a null buffer to a toplevel unmaps the surface. + + + + + This request destroys the role surface and unmaps the surface; + see "Unmapping" behavior in interface section for details. + + + + + + + + + + + + Set the "parent" of this surface. This surface should be stacked + above the parent surface and all other ancestor surfaces. + + Parent surfaces should be set on dialogs, toolboxes, or other + "auxiliary" surfaces, so that the parent is raised when the dialog + is raised. + + Setting a null parent for a child surface unsets its parent. Setting + a null parent for a surface which currently has no parent is a no-op. + + Only mapped surfaces can have child surfaces. Setting a parent which + is not mapped is equivalent to setting a null parent. If a surface + becomes unmapped, its children's parent is set to the parent of + the now-unmapped surface. If the now-unmapped surface has no parent, + its children's parent is unset. If the now-unmapped surface becomes + mapped again, its parent-child relationship is not restored. + + The parent toplevel must not be one of the child toplevel's + descendants, and the parent must be different from the child toplevel, + otherwise the invalid_parent protocol error is raised. + + + + + + + Set a short title for the surface. + + This string may be used to identify the surface in a task bar, + window list, or other user interface elements provided by the + compositor. + + The string must be encoded in UTF-8. + + + + + + + Set an application identifier for the surface. + + The app ID identifies the general class of applications to which + the surface belongs. The compositor can use this to group multiple + surfaces together, or to determine how to launch a new application. + + For D-Bus activatable applications, the app ID is used as the D-Bus + service name. + + The compositor shell will try to group application surfaces together + by their app ID. As a best practice, it is suggested to select app + ID's that match the basename of the application's .desktop file. + For example, "org.freedesktop.FooViewer" where the .desktop file is + "org.freedesktop.FooViewer.desktop". + + Like other properties, a set_app_id request can be sent after the + xdg_toplevel has been mapped to update the property. + + See the desktop-entry specification [0] for more details on + application identifiers and how they relate to well-known D-Bus + names and .desktop files. + + [0] https://standards.freedesktop.org/desktop-entry-spec/ + + + + + + + Clients implementing client-side decorations might want to show + a context menu when right-clicking on the decorations, giving the + user a menu that they can use to maximize or minimize the window. + + This request asks the compositor to pop up such a window menu at + the given position, relative to the local surface coordinates of + the parent surface. There are no guarantees as to what menu items + the window menu contains, or even if a window menu will be drawn + at all. + + This request must be used in response to some sort of user action + like a button press, key press, or touch down event. + + + + + + + + + + Start an interactive, user-driven move of the surface. + + This request must be used in response to some sort of user action + like a button press, key press, or touch down event. The passed + serial is used to determine the type of interactive move (touch, + pointer, etc). + + The server may ignore move requests depending on the state of + the surface (e.g. fullscreen or maximized), or if the passed serial + is no longer valid. + + If triggered, the surface will lose the focus of the device + (wl_pointer, wl_touch, etc) used for the move. It is up to the + compositor to visually indicate that the move is taking place, such as + updating a pointer cursor, during the move. There is no guarantee + that the device focus will return when the move is completed. + + + + + + + + These values are used to indicate which edge of a surface + is being dragged in a resize operation. + + + + + + + + + + + + + + + Start a user-driven, interactive resize of the surface. + + This request must be used in response to some sort of user action + like a button press, key press, or touch down event. The passed + serial is used to determine the type of interactive resize (touch, + pointer, etc). + + The server may ignore resize requests depending on the state of + the surface (e.g. fullscreen or maximized). + + If triggered, the client will receive configure events with the + "resize" state enum value and the expected sizes. See the "resize" + enum value for more details about what is required. The client + must also acknowledge configure events using "ack_configure". After + the resize is completed, the client will receive another "configure" + event without the resize state. + + If triggered, the surface also will lose the focus of the device + (wl_pointer, wl_touch, etc) used for the resize. It is up to the + compositor to visually indicate that the resize is taking place, + such as updating a pointer cursor, during the resize. There is no + guarantee that the device focus will return when the resize is + completed. + + The edges parameter specifies how the surface should be resized, and + is one of the values of the resize_edge enum. Values not matching + a variant of the enum will cause the invalid_resize_edge protocol error. + The compositor may use this information to update the surface position + for example when dragging the top left corner. The compositor may also + use this information to adapt its behavior, e.g. choose an appropriate + cursor image. + + + + + + + + + The different state values used on the surface. This is designed for + state values like maximized, fullscreen. It is paired with the + configure event to ensure that both the client and the compositor + setting the state can be synchronized. + + States set in this way are double-buffered, see wl_surface.commit. + + + + The surface is maximized. The window geometry specified in the configure + event must be obeyed by the client, or the xdg_wm_base.invalid_surface_state + error is raised. + + The client should draw without shadow or other + decoration outside of the window geometry. + + + + + The surface is fullscreen. The window geometry specified in the + configure event is a maximum; the client cannot resize beyond it. For + a surface to cover the whole fullscreened area, the geometry + dimensions must be obeyed by the client. For more details, see + xdg_toplevel.set_fullscreen. + + + + + The surface is being resized. The window geometry specified in the + configure event is a maximum; the client cannot resize beyond it. + Clients that have aspect ratio or cell sizing configuration can use + a smaller size, however. + + + + + Client window decorations should be painted as if the window is + active. Do not assume this means that the window actually has + keyboard or pointer focus. + + + + + The window is currently in a tiled layout and the left edge is + considered to be adjacent to another part of the tiling grid. + + The client should draw without shadow or other decoration outside of + the window geometry on the left edge. + + + + + The window is currently in a tiled layout and the right edge is + considered to be adjacent to another part of the tiling grid. + + The client should draw without shadow or other decoration outside of + the window geometry on the right edge. + + + + + The window is currently in a tiled layout and the top edge is + considered to be adjacent to another part of the tiling grid. + + The client should draw without shadow or other decoration outside of + the window geometry on the top edge. + + + + + The window is currently in a tiled layout and the bottom edge is + considered to be adjacent to another part of the tiling grid. + + The client should draw without shadow or other decoration outside of + the window geometry on the bottom edge. + + + + + The surface is currently not ordinarily being repainted; for + example because its content is occluded by another window, or its + outputs are switched off due to screen locking. + + + + + The left edge of the window is currently constrained, meaning it + shouldn't attempt to resize from that edge. It can for example mean + it's tiled next to a monitor edge on the constrained side of the + window. + + + + + The right edge of the window is currently constrained, meaning it + shouldn't attempt to resize from that edge. It can for example mean + it's tiled next to a monitor edge on the constrained side of the + window. + + + + + The top edge of the window is currently constrained, meaning it + shouldn't attempt to resize from that edge. It can for example mean + it's tiled next to a monitor edge on the constrained side of the + window. + + + + + The bottom edge of the window is currently constrained, meaning it + shouldn't attempt to resize from that edge. It can for example mean + it's tiled next to a monitor edge on the constrained side of the + window. + + + + + + + Set a maximum size for the window. + + The client can specify a maximum size so that the compositor does + not try to configure the window beyond this size. + + The width and height arguments are in window geometry coordinates. + See xdg_surface.set_window_geometry. + + Values set in this way are double-buffered, see wl_surface.commit. + + The compositor can use this information to allow or disallow + different states like maximize or fullscreen and draw accurate + animations. + + Similarly, a tiling window manager may use this information to + place and resize client windows in a more effective way. + + The client should not rely on the compositor to obey the maximum + size. The compositor may decide to ignore the values set by the + client and request a larger size. + + If never set, or a value of zero in the request, means that the + client has no expected maximum size in the given dimension. + As a result, a client wishing to reset the maximum size + to an unspecified state can use zero for width and height in the + request. + + Requesting a maximum size to be smaller than the minimum size of + a surface is illegal and will result in an invalid_size error. + + The width and height must be greater than or equal to zero. Using + strictly negative values for width or height will result in an + invalid_size error. + + + + + + + + Set a minimum size for the window. + + The client can specify a minimum size so that the compositor does + not try to configure the window below this size. + + The width and height arguments are in window geometry coordinates. + See xdg_surface.set_window_geometry. + + Values set in this way are double-buffered, see wl_surface.commit. + + The compositor can use this information to allow or disallow + different states like maximize or fullscreen and draw accurate + animations. + + Similarly, a tiling window manager may use this information to + place and resize client windows in a more effective way. + + The client should not rely on the compositor to obey the minimum + size. The compositor may decide to ignore the values set by the + client and request a smaller size. + + If never set, or a value of zero in the request, means that the + client has no expected minimum size in the given dimension. + As a result, a client wishing to reset the minimum size + to an unspecified state can use zero for width and height in the + request. + + Requesting a minimum size to be larger than the maximum size of + a surface is illegal and will result in an invalid_size error. + + The width and height must be greater than or equal to zero. Using + strictly negative values for width and height will result in an + invalid_size error. + + + + + + + + Maximize the surface. + + After requesting that the surface should be maximized, the compositor + will respond by emitting a configure event. Whether this configure + actually sets the window maximized is subject to compositor policies. + The client must then update its content, drawing in the configured + state. The client must also acknowledge the configure when committing + the new content (see ack_configure). + + It is up to the compositor to decide how and where to maximize the + surface, for example which output and what region of the screen should + be used. + + If the surface was already maximized, the compositor will still emit + a configure event with the "maximized" state. + + If the surface is in a fullscreen state, this request has no direct + effect. It may alter the state the surface is returned to when + unmaximized unless overridden by the compositor. + + + + + + Unmaximize the surface. + + After requesting that the surface should be unmaximized, the compositor + will respond by emitting a configure event. Whether this actually + un-maximizes the window is subject to compositor policies. + If available and applicable, the compositor will include the window + geometry dimensions the window had prior to being maximized in the + configure event. The client must then update its content, drawing it in + the configured state. The client must also acknowledge the configure + when committing the new content (see ack_configure). + + It is up to the compositor to position the surface after it was + unmaximized; usually the position the surface had before maximizing, if + applicable. + + If the surface was already not maximized, the compositor will still + emit a configure event without the "maximized" state. + + If the surface is in a fullscreen state, this request has no direct + effect. It may alter the state the surface is returned to when + unmaximized unless overridden by the compositor. + + + + + + Make the surface fullscreen. + + After requesting that the surface should be fullscreened, the + compositor will respond by emitting a configure event. Whether the + client is actually put into a fullscreen state is subject to compositor + policies. The client must also acknowledge the configure when + committing the new content (see ack_configure). + + The output passed by the request indicates the client's preference as + to which display it should be set fullscreen on. If this value is NULL, + it's up to the compositor to choose which display will be used to map + this surface. + + If the surface doesn't cover the whole output, the compositor will + position the surface in the center of the output and compensate with + border fill covering the rest of the output. The content of the + border fill is undefined, but should be assumed to be in some way that + attempts to blend into the surrounding area (e.g. solid black). + + If the fullscreened surface is not opaque, the compositor must make + sure that other screen content not part of the same surface tree (made + up of subsurfaces, popups or similarly coupled surfaces) are not + visible below the fullscreened surface. + + + + + + + Make the surface no longer fullscreen. + + After requesting that the surface should be unfullscreened, the + compositor will respond by emitting a configure event. + Whether this actually removes the fullscreen state of the client is + subject to compositor policies. + + Making a surface unfullscreen sets states for the surface based on the following: + * the state(s) it may have had before becoming fullscreen + * any state(s) decided by the compositor + * any state(s) requested by the client while the surface was fullscreen + + The compositor may include the previous window geometry dimensions in + the configure event, if applicable. + + The client must also acknowledge the configure when committing the new + content (see ack_configure). + + + + + + Request that the compositor minimize your surface. There is no + way to know if the surface is currently minimized, nor is there + any way to unset minimization on this surface. + + If you are looking to throttle redrawing when minimized, please + instead use the wl_surface.frame event for this, as this will + also work with live previews on windows in Alt-Tab, Expose or + similar compositor features. + + + + + + This configure event asks the client to resize its toplevel surface or + to change its state. The configured state should not be applied + immediately. See xdg_surface.configure for details. + + The width and height arguments specify a hint to the window + about how its surface should be resized in window geometry + coordinates. See set_window_geometry. + + If the width or height arguments are zero, it means the client + should decide its own window dimension. This may happen when the + compositor needs to configure the state of the surface but doesn't + have any information about any previous or expected dimension. + + The states listed in the event specify how the width/height + arguments should be interpreted, and possibly how it should be + drawn. + + The states are sent as an array of 32-bit unsigned integers in + native endianness. State values are defined in the state enum. + + Clients must send an ack_configure in response to this event. See + xdg_surface.configure and xdg_surface.ack_configure for details. + + + + + + + + + The close event is sent by the compositor when the user + wants the surface to be closed. This should be equivalent to + the user clicking the close button in client-side decorations, + if your application has any. + + This is only a request that the user intends to close the + window. The client may choose to ignore this request, or show + a dialog to ask the user to save their data, etc. + + + + + + + + The configure_bounds event may be sent prior to a xdg_toplevel.configure + event to communicate the bounds a window geometry size is recommended + to constrain to. + + The passed width and height are in surface coordinate space. If width + and height are 0, it means bounds is unknown and equivalent to as if no + configure_bounds event was ever sent for this surface. + + The bounds can for example correspond to the size of a monitor excluding + any panels or other shell components, so that a surface isn't created in + a way that it cannot fit. + + The bounds may change at any point, and in such a case, a new + xdg_toplevel.configure_bounds will be sent, followed by + xdg_toplevel.configure and xdg_surface.configure. + + + + + + + + + + + + + + + + + This event advertises the capabilities supported by the compositor. If + a capability isn't supported, clients should hide or disable the UI + elements that expose this functionality. For instance, if the + compositor doesn't advertise support for minimized toplevels, a button + triggering the set_minimized request should not be displayed. + + The compositor will ignore requests it doesn't support. For instance, + a compositor which doesn't advertise support for minimized will ignore + set_minimized requests. + + Compositors must send this event once before the first + xdg_surface.configure event. When the capabilities change, compositors + must send this event again and then send an xdg_surface.configure + event. + + The configured state should not be applied immediately. See + xdg_surface.configure for details. + + The capabilities are sent as an array of 32-bit unsigned integers in + native endianness. Capability values are defined in the wm_capabilities enum. + + + + + + + + A popup surface is a short-lived, temporary surface. It can be used to + implement for example menus, popovers, tooltips and other similar user + interface concepts. + + A popup can be made to take an explicit grab. See xdg_popup.grab for + details. + + When the popup is dismissed, a popup_done event will be sent out, and at + the same time the surface will be unmapped. See the xdg_popup.popup_done + event for details. + + Explicitly destroying the xdg_popup object will also dismiss the popup and + unmap the surface. Clients that want to dismiss the popup when another + surface of their own is clicked should dismiss the popup using the destroy + request. + + A newly created xdg_popup will be stacked on top of all previously created + xdg_popup surfaces associated with the same xdg_toplevel. + + The parent of an xdg_popup must be mapped (see the xdg_surface + description) before the xdg_popup itself. + + The client must call wl_surface.commit on the corresponding wl_surface + for the xdg_popup state to take effect. + + + + + + + + + This destroys the popup. Explicitly destroying the xdg_popup + object will also dismiss the popup, and unmap the surface. + + If this xdg_popup is not the "topmost" popup, the + xdg_wm_base.not_the_topmost_popup protocol error will be sent. + + + + + + This request makes the created popup take an explicit grab. An explicit + grab will be dismissed when the user dismisses the popup, or when the + client destroys the xdg_popup. This can be done by the user clicking + outside the surface, using the keyboard, or even locking the screen + through closing the lid or a timeout. + + If the compositor denies the grab, the popup will be immediately + dismissed. + + This request must be used in response to some sort of user action like a + button press, key press, or touch down event. The serial number of the + event should be passed as 'serial'. + + The parent of a grabbing popup must either be an xdg_toplevel surface or + another xdg_popup with an explicit grab. If the parent is another + xdg_popup it means that the popups are nested, with this popup now being + the topmost popup. + + Nested popups must be destroyed in the reverse order they were created + in, e.g. the only popup you are allowed to destroy at all times is the + topmost one. + + When compositors choose to dismiss a popup, they may dismiss every + nested grabbing popup as well. When a compositor dismisses popups, it + will follow the same dismissing order as required from the client. + + If the topmost grabbing popup is destroyed, the grab will be returned to + the parent of the popup, if that parent previously had an explicit grab. + + If the parent is a grabbing popup which has already been dismissed, this + popup will be immediately dismissed. If the parent is a popup that did + not take an explicit grab, an error will be raised. + + During a popup grab, the client owning the grab will receive pointer + and touch events for all their surfaces as normal (similar to an + "owner-events" grab in X11 parlance), while the top most grabbing popup + will always have keyboard focus. + + + + + + + + This event asks the popup surface to configure itself given the + configuration. The configured state should not be applied immediately. + See xdg_surface.configure for details. + + The x and y arguments represent the position the popup was placed at + given the xdg_positioner rule, relative to the upper left corner of the + window geometry of the parent surface. + + For version 2 or older, the configure event for an xdg_popup is only + ever sent once for the initial configuration. Starting with version 3, + it may be sent again if the popup is setup with an xdg_positioner with + set_reactive requested, or in response to xdg_popup.reposition requests. + + + + + + + + + + The popup_done event is sent out when a popup is dismissed by the + compositor. The client should destroy the xdg_popup object at this + point. + + + + + + + + Reposition an already-mapped popup. The popup will be placed given the + details in the passed xdg_positioner object, and a + xdg_popup.repositioned followed by xdg_popup.configure and + xdg_surface.configure will be emitted in response. Any parameters set + by the previous positioner will be discarded. + + The passed token will be sent in the corresponding + xdg_popup.repositioned event. The new popup position will not take + effect until the corresponding configure event is acknowledged by the + client. See xdg_popup.repositioned for details. The token itself is + opaque, and has no other special meaning. + + If multiple reposition requests are sent, the compositor may skip all + but the last one. + + If the popup is repositioned in response to a configure event for its + parent, the client should send an xdg_positioner.set_parent_configure + and possibly an xdg_positioner.set_parent_size request to allow the + compositor to properly constrain the popup. + + If the popup is repositioned together with a parent that is being + resized, but not in response to a configure event, the client should + send an xdg_positioner.set_parent_size request. + + + + + + + + The repositioned event is sent as part of a popup configuration + sequence, together with xdg_popup.configure and lastly + xdg_surface.configure to notify the completion of a reposition request. + + The repositioned event is to notify about the completion of a + xdg_popup.reposition request. The token argument is the token passed + in the xdg_popup.reposition request. + + Immediately after this event is emitted, xdg_popup.configure and + xdg_surface.configure will be sent with the updated size and position, + as well as a new configure serial. + + The client should optionally update the content of the popup, but must + acknowledge the new popup configuration for the new position to take + effect. See xdg_surface.ack_configure for details. + + + + + + From cf92ebba7602d2e81655457cb3fb6494287671a6 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 00:45:18 +0300 Subject: [PATCH 02/35] split the Wayland backend into files WaylandWindow.cpp held the protocol bindings, the shared compositor state, the input implementation, the window itself, the free event listeners and the initialization code in one 2400-line file. Moved out of it: - WaylandCommon.hpp/.cpp: shared compositor state, the display event loop, keysym mapping and the window logger; - WaylandInput.hpp: the input implementation (keyboard, clipboard, cursors, key repeat). No functional change. --- src/window/detail/WaylandWindow.cpp | 559 +++------------------------ src/window/wayland/WaylandCommon.cpp | 118 ++++++ src/window/wayland/WaylandCommon.hpp | 77 ++++ src/window/wayland/WaylandInput.hpp | 332 ++++++++++++++++ 4 files changed, 573 insertions(+), 513 deletions(-) create mode 100644 src/window/wayland/WaylandCommon.cpp create mode 100644 src/window/wayland/WaylandCommon.hpp create mode 100644 src/window/wayland/WaylandInput.hpp diff --git a/src/window/detail/WaylandWindow.cpp b/src/window/detail/WaylandWindow.cpp index 0d110820d..094ed95bb 100644 --- a/src/window/detail/WaylandWindow.cpp +++ b/src/window/detail/WaylandWindow.cpp @@ -1,3 +1,6 @@ +#include "window/wayland/WaylandCommon.hpp" +#include "window/wayland/WaylandInput.hpp" + #include "window/Window.hpp" #include "window/detail/BaseInput.hpp" #include "window/detail/WindowBackends.hpp" @@ -39,58 +42,6 @@ #include #include -static debug::Logger logger("window"); - -struct WaylandState { - wl_display* display = nullptr; - wl_registry* registry = nullptr; - wl_compositor* compositor = nullptr; - wl_surface* surface = nullptr; - xdg_wm_base* wmBase = nullptr; - xdg_surface* xdgSurface = nullptr; - xdg_toplevel* toplevel = nullptr; - zxdg_toplevel_decoration_v1* decoration = nullptr; - wl_seat* seat = nullptr; - wl_pointer* pointer = nullptr; - wl_keyboard* keyboard = nullptr; - wl_data_device_manager* dataDeviceManager = nullptr; - wl_data_device* dataDevice = nullptr; - wp_cursor_shape_manager_v1* cursorShapeManager = nullptr; - wp_cursor_shape_device_v1* cursorShapeDevice = nullptr; - zwp_pointer_constraints_v1* pointerConstraints = nullptr; - zwp_relative_pointer_manager_v1* relativePointerManager = nullptr; - zwp_relative_pointer_v1* relativePointer = nullptr; - zwp_locked_pointer_v1* lockedPointer = nullptr; - zwp_idle_inhibit_manager_v1* idleInhibitManager = nullptr; - zwp_idle_inhibitor_v1* idleInhibitor = nullptr; - zxdg_decoration_manager_v1* decorationManager = nullptr; - xkb_context* xkbContext = nullptr; - xkb_keymap* xkbKeymap = nullptr; - xkb_state* xkbState = nullptr; - uint32_t pointerSerial = 0; - uint32_t inputSerial = 0; - uint32_t repeatRate = 25; - uint32_t repeatDelay = 400; - bool entered = false; -}; - -static WaylandState state; - -class WaylandInput; -class WaylandWindow; - -static WaylandInput* input = nullptr; -static WaylandWindow* window = nullptr; - -template -static void ignore_event(Args...) { -} - -static bool decorations_enabled() { - const char* value = getenv("VOXEL_DECORATIONS"); - return value == nullptr || strcmp(value, "none") != 0; -} - static constexpr int BAR_HEIGHT = 30; static constexpr int BAR_BUTTON = 30; static constexpr int BAR_EDGE = 5; @@ -339,425 +290,6 @@ static void push_quad( target.insert(target.end(), vertices, vertices + 48); } -static bool serverDecorations = false; - -static void zxdg_decoration_configure( - void*, zxdg_toplevel_decoration_v1*, uint32_t mode -); - -static void on_display_error(); - -static int keycode_from_keysym(xkb_keysym_t sym) { - switch (sym) { - case XKB_KEY_Escape: return GLFW_KEY_ESCAPE; - case XKB_KEY_Return: return GLFW_KEY_ENTER; - case XKB_KEY_Tab: return GLFW_KEY_TAB; - case XKB_KEY_BackSpace: return GLFW_KEY_BACKSPACE; - case XKB_KEY_Insert: return GLFW_KEY_INSERT; - case XKB_KEY_Delete: return GLFW_KEY_DELETE; - case XKB_KEY_Left: return GLFW_KEY_LEFT; - case XKB_KEY_Right: return GLFW_KEY_RIGHT; - case XKB_KEY_Up: return GLFW_KEY_UP; - case XKB_KEY_Down: return GLFW_KEY_DOWN; - case XKB_KEY_Page_Up: return GLFW_KEY_PAGE_UP; - case XKB_KEY_Page_Down: return GLFW_KEY_PAGE_DOWN; - case XKB_KEY_Home: return GLFW_KEY_HOME; - case XKB_KEY_End: return GLFW_KEY_END; - case XKB_KEY_Caps_Lock: return GLFW_KEY_CAPS_LOCK; - case XKB_KEY_Scroll_Lock: return GLFW_KEY_SCROLL_LOCK; - case XKB_KEY_Num_Lock: return GLFW_KEY_NUM_LOCK; - case XKB_KEY_Print: return GLFW_KEY_PRINT_SCREEN; - case XKB_KEY_Pause: return GLFW_KEY_PAUSE; - case XKB_KEY_Menu: return GLFW_KEY_MENU; - case XKB_KEY_Shift_L: return GLFW_KEY_LEFT_SHIFT; - case XKB_KEY_Control_L: return GLFW_KEY_LEFT_CONTROL; - case XKB_KEY_Alt_L: return GLFW_KEY_LEFT_ALT; - case XKB_KEY_Super_L: return GLFW_KEY_LEFT_SUPER; - case XKB_KEY_Shift_R: return GLFW_KEY_RIGHT_SHIFT; - case XKB_KEY_Control_R: return GLFW_KEY_RIGHT_CONTROL; - case XKB_KEY_Alt_R: return GLFW_KEY_RIGHT_ALT; - case XKB_KEY_Super_R: return GLFW_KEY_RIGHT_SUPER; - case XKB_KEY_space: return GLFW_KEY_SPACE; - case XKB_KEY_apostrophe: return GLFW_KEY_APOSTROPHE; - case XKB_KEY_comma: return GLFW_KEY_COMMA; - case XKB_KEY_minus: return GLFW_KEY_MINUS; - case XKB_KEY_period: return GLFW_KEY_PERIOD; - case XKB_KEY_slash: return GLFW_KEY_SLASH; - case XKB_KEY_semicolon: return GLFW_KEY_SEMICOLON; - case XKB_KEY_equal: return GLFW_KEY_EQUAL; - case XKB_KEY_bracketleft: return GLFW_KEY_LEFT_BRACKET; - case XKB_KEY_backslash: return GLFW_KEY_BACKSLASH; - case XKB_KEY_bracketright: return GLFW_KEY_RIGHT_BRACKET; - case XKB_KEY_grave: return GLFW_KEY_GRAVE_ACCENT; - case XKB_KEY_KP_0: return GLFW_KEY_KP_0; - case XKB_KEY_KP_1: return GLFW_KEY_KP_1; - case XKB_KEY_KP_2: return GLFW_KEY_KP_2; - case XKB_KEY_KP_3: return GLFW_KEY_KP_3; - case XKB_KEY_KP_4: return GLFW_KEY_KP_4; - case XKB_KEY_KP_5: return GLFW_KEY_KP_5; - case XKB_KEY_KP_6: return GLFW_KEY_KP_6; - case XKB_KEY_KP_7: return GLFW_KEY_KP_7; - case XKB_KEY_KP_8: return GLFW_KEY_KP_8; - case XKB_KEY_KP_9: return GLFW_KEY_KP_9; - case XKB_KEY_KP_Decimal: return GLFW_KEY_KP_DECIMAL; - case XKB_KEY_KP_Divide: return GLFW_KEY_KP_DIVIDE; - case XKB_KEY_KP_Multiply: return GLFW_KEY_KP_MULTIPLY; - case XKB_KEY_KP_Subtract: return GLFW_KEY_KP_SUBTRACT; - case XKB_KEY_KP_Add: return GLFW_KEY_KP_ADD; - case XKB_KEY_KP_Enter: return GLFW_KEY_KP_ENTER; - case XKB_KEY_KP_Equal: return GLFW_KEY_KP_EQUAL; - } - if (sym >= XKB_KEY_a && sym <= XKB_KEY_z) { - return GLFW_KEY_A + (sym - XKB_KEY_a); - } - if (sym >= XKB_KEY_A && sym <= XKB_KEY_Z) { - return GLFW_KEY_A + (sym - XKB_KEY_A); - } - if (sym >= XKB_KEY_0 && sym <= XKB_KEY_9) { - return GLFW_KEY_0 + (sym - XKB_KEY_0); - } - if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F12) { - return GLFW_KEY_F1 + (sym - XKB_KEY_F1); - } - return 0; -} - -static void dispatch_events(int timeoutMs) { - wl_display_flush(state.display); - while (wl_display_prepare_read(state.display) != 0) { - wl_display_dispatch_pending(state.display); - wl_display_flush(state.display); - } - pollfd descriptor {wl_display_get_fd(state.display), POLLIN, 0}; - if (poll(&descriptor, 1, timeoutMs) > 0) { - if (wl_display_read_events(state.display) == -1) { - wl_display_cancel_read(state.display); - } - } else { - wl_display_cancel_read(state.display); - } - wl_display_dispatch_pending(state.display); - if (wl_display_get_error(state.display) != 0) { - on_display_error(); - } -} - -class WaylandInput : public BaseInput { -public: - void pollEvents(bool waitForRefresh) override; - - const char* getClipboardText() const override { - if (state.dataDevice == nullptr || selection == nullptr) { - return clipboard.c_str(); - } - const char* mime = pickMime(); - if (mime == nullptr) { - return clipboard.c_str(); - } - int fds[2]; - if (pipe(fds) == -1) { - return clipboard.c_str(); - } - wl_data_offer_receive(selection, mime, fds[1]); - close(fds[1]); - wl_display_flush(state.display); - - clipboard.clear(); - char buffer[4096]; - auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(500); - while (std::chrono::steady_clock::now() < deadline) { - pollfd descriptor {fds[0], POLLIN, 0}; - if (poll(&descriptor, 1, 50) <= 0) { - wl_display_dispatch_pending(state.display); - continue; - } - ssize_t length = read(fds[0], buffer, sizeof(buffer)); - if (length <= 0) { - break; - } - clipboard.append(buffer, length); - } - close(fds[0]); - return clipboard.c_str(); - } - - void setClipboardText(const char* text) override { - if (state.dataDeviceManager == nullptr || state.dataDevice == nullptr) { - return; - } - auto* source = wl_data_device_manager_create_data_source( - state.dataDeviceManager - ); - wl_data_source_add_listener(source, &sourceListener(), nullptr); - wl_data_source_offer(source, "text/plain;charset=utf-8"); - wl_data_source_offer(source, "text/plain"); - wl_data_source_offer(source, "UTF8_STRING"); - sourceText = text ? text : ""; - wl_data_device_set_selection(state.dataDevice, source, state.inputSerial); - wl_display_flush(state.display); - } - - void toggleCursor() override { - cursorDrag = false; - if (cursorLocked) { - if (state.lockedPointer) { - zwp_locked_pointer_v1_destroy(state.lockedPointer); - state.lockedPointer = nullptr; - } - if (state.relativePointer) { - zwp_relative_pointer_v1_destroy(state.relativePointer); - state.relativePointer = nullptr; - } - cursorLocked = false; - applyCursor(); - return; - } - if (state.pointerConstraints && state.pointer && state.surface) { - state.lockedPointer = zwp_pointer_constraints_v1_lock_pointer( - state.pointerConstraints, - state.surface, - state.pointer, - nullptr, - ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT - ); - } - if (state.relativePointerManager && state.pointer) { - state.relativePointer = - zwp_relative_pointer_manager_v1_get_relative_pointer( - state.relativePointerManager, state.pointer - ); - zwp_relative_pointer_v1_add_listener( - state.relativePointer, &relativePointerListener(), nullptr - ); - } - if (state.pointer && state.entered) { - wl_pointer_set_cursor( - state.pointer, state.pointerSerial, nullptr, 0, 0 - ); - } - cursorLocked = true; - } - - void setCursorShape(CursorShape shape) { - if (cursor == shape) { - return; - } - cursor = shape; - applyCursor(); - } - - void applyCursor() { - if (cursorLocked || !state.entered || !state.cursorShapeDevice) { - return; - } - wp_cursor_shape_device_v1_set_shape( - state.cursorShapeDevice, state.pointerSerial, - shapeId(overrideCursor ? *overrideCursor : cursor) - ); - } - - void setOverrideCursor(std::optional shape) { - if (overrideCursor == shape) { - return; - } - overrideCursor = shape; - applyCursor(); - } - - void onRelativeMotion(double dx, double dy) { - delta.x += dx; - delta.y += dy; - } - - void onKey(uint32_t key, bool pressed) { - if (state.xkbState == nullptr || state.xkbKeymap == nullptr) { - return; - } - xkb_keycode_t code = key + 8; - const xkb_keysym_t* syms = nullptr; - if (xkb_keymap_key_get_syms_by_level( - state.xkbKeymap, code, 0, 0, &syms - ) > 0) { - int keycode = keycode_from_keysym(syms[0]); - if (keycode != 0) { - onKeyCallback(keycode, pressed); - } - if (pressed) { - repeatKeycode = code; - repeatTime = now(); - lastRepeat = repeatTime; - } else if (code == repeatKeycode) { - repeatKeycode = 0; - } - } - if (pressed) { - appendCodepoints(code); - } - xkb_state_update_key( - state.xkbState, code, pressed ? XKB_KEY_DOWN : XKB_KEY_UP - ); - } - - void refreshWindow(); - - wl_data_offer* selection = nullptr; - std::vector selectionMimes; - std::vector pendingMimes; - mutable std::string clipboard; - std::string sourceText; -private: - static uint32_t shapeId(CursorShape shape) { - switch (shape) { - case CursorShape::ARROW: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; - case CursorShape::TEXT: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT; - case CursorShape::CROSSHAIR: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR; - case CursorShape::POINTER: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER; - case CursorShape::EW_RESIZE: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE; - case CursorShape::NS_RESIZE: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE; - case CursorShape::NWSE_RESIZE: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE; - case CursorShape::NESW_RESIZE: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE; - case CursorShape::ALL_RESIZE: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE; - case CursorShape::NOT_ALLOWED: - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED; - } - return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; - } - - static void dispatch(bool block) { - dispatch_events(block ? 500 : 0); - } - - static double now() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); - } - - void appendCodepoints(xkb_keycode_t code) { - char buffer[64]; - int length = xkb_state_key_get_utf8( - state.xkbState, code, buffer, sizeof(buffer) - ); - if (length <= 0) { - return; - } - const auto* bytes = reinterpret_cast(buffer); - uint codepoint = 0; - for (int i = 0; i < length; i++) { - if ((bytes[i] & 0xC0) == 0x80) { - codepoint = (codepoint << 6) | (bytes[i] & 0x3F); - continue; - } - if (codepoint != 0) { - codepoints.push_back(codepoint); - } - codepoint = (bytes[i] & 0x80) ? (bytes[i] & 0x1F) : bytes[i]; - } - if (codepoint != 0) { - codepoints.push_back(codepoint); - } - } - - void updateRepeat() { - if (repeatKeycode == 0 || !state.xkbState) { - return; - } - int keycode = 0; - const xkb_keysym_t* syms = nullptr; - if (xkb_keymap_key_get_syms_by_level( - state.xkbKeymap, repeatKeycode, 0, 0, &syms - ) > 0) { - keycode = keycode_from_keysym(syms[0]); - } - if (keycode == 0 || !pressed(static_cast(keycode))) { - return; - } - double time = now(); - if (time - repeatTime < state.repeatDelay / 1000.0) { - return; - } - double interval = 1.0 / std::max(state.repeatRate, 1); - if (time - lastRepeat < interval) { - return; - } - lastRepeat = time; - onKeyCallback(keycode, true); - appendCodepoints(repeatKeycode); - } - - const char* pickMime() const { - for (const auto& mime : selectionMimes) { - if (mime == "text/plain;charset=utf-8" || mime == "text/plain" || - mime == "UTF8_STRING") { - return mime.c_str(); - } - } - return nullptr; - } - - static const wl_data_source_listener& sourceListener() { - static wl_data_source_listener listener {}; - static bool initialized = false; - if (!initialized) { - initialized = true; - listener.send = [] ( - void*, wl_data_source*, const char*, int32_t fd - ) { - if (input) { - const std::string& text = input->sourceText; - if (!text.empty() && write(fd, text.data(), text.size()) < 0) { - logger.warning() << "could not write to the clipboard"; - } - } - close(fd); - }; - listener.cancelled = [] (void*, wl_data_source* source) { - wl_data_source_destroy(source); - }; - listener.target = ignore_event<>; - listener.dnd_drop_performed = ignore_event<>; - listener.dnd_finished = ignore_event<>; - listener.action = ignore_event<>; - } - return listener; - } - - static const zwp_relative_pointer_v1_listener& relativePointerListener() { - static zwp_relative_pointer_v1_listener listener {}; - static bool initialized = false; - if (!initialized) { - initialized = true; - listener.relative_motion = [] ( - void*, zwp_relative_pointer_v1*, uint32_t, uint32_t, - wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t, wl_fixed_t - ) { - if (input) { - input->onRelativeMotion( - wl_fixed_to_double(dx), wl_fixed_to_double(dy) - ); - } - }; - } - return listener; - } - - CursorShape cursor = CursorShape::ARROW; - std::optional overrideCursor; - xkb_keycode_t repeatKeycode = 0; - double repeatTime = 0.0; - double lastRepeat = 0.0; -}; - class WaylandWindow : public Window { public: WaylandInput& input; @@ -987,7 +519,7 @@ public: void focus() override { if (!focusWarning) { focusWarning = true; - logger.warning() << "raising windows is not allowed on Wayland"; + waylandLogger.warning() << "raising windows is not allowed on Wayland"; } } @@ -1121,7 +653,7 @@ public: void popScissor() override { if (scissorStack.empty()) { - logger.warning() << "extra Window::popScissor call"; + waylandLogger.warning() << "extra Window::popScissor call"; return; } glm::vec4 area = scissorStack.top(); @@ -1689,7 +1221,7 @@ public: if (current - lastSummary < 1.0) { return; } - logger.info() << "loop " << loopCount << "/s (max gap " + waylandLogger.info() << "loop " << loopCount << "/s (max gap " << loopGapMax * 1000.0 << " ms), presents " << summaryFrames << "/s (max gap " << summaryMax * 1000.0 << " ms), resizing " @@ -1710,7 +1242,7 @@ public: resizeTimeSum = 0.0; resizeTimeMax = 0.0; if (resizeLogging) { - logger.info() << "resize started"; + waylandLogger.info() << "resize started"; } setShouldRefresh(); } @@ -1724,7 +1256,7 @@ public: double average = resizePresents > 0 ? resizeTimeSum / resizePresents : 0.0; - logger.info() + waylandLogger.info() << "resize finished, presented " << resizePresents << ", avg " << average * 1000.0 << " ms, max " << resizeTimeMax * 1000.0 << " ms"; @@ -1847,29 +1379,6 @@ private: glm::vec4 scissorArea {}; }; -void WaylandInput::pollEvents(bool waitForRefresh) { - beginFrame(); - dispatch(waitForRefresh); - if (window) { - window->paceFrame(); - } - updateRepeat(); - updateBindings(); -} - -static void on_display_error() { - logger.error() << "the Wayland connection was lost"; - if (window) { - window->setShouldClose(true); - } -} - -void WaylandInput::refreshWindow() { - if (window) { - window->setShouldRefresh(); - } -} - static void pointer_enter( void*, wl_pointer*, uint32_t serial, wl_surface* surface, wl_fixed_t sx, wl_fixed_t sy @@ -1969,7 +1478,7 @@ static void keyboard_keymap( ); munmap(data, size); if (keymap == nullptr) { - logger.error() << "could not parse the keyboard keymap"; + waylandLogger.error() << "could not parse the keyboard keymap"; return; } if (state.xkbState) { @@ -2215,7 +1724,7 @@ static void registry_global( static void registry_global_remove(void*, wl_registry*, uint32_t) { } -static void zxdg_decoration_configure( +void zxdg_decoration_configure( void*, zxdg_toplevel_decoration_v1*, uint32_t mode ) { serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; @@ -2224,11 +1733,12 @@ static void zxdg_decoration_configure( } } + std::tuple, std::unique_ptr> wayland_window_initialize(DisplaySettings* settings, std::string title) { state.display = wl_display_connect(nullptr); if (state.display == nullptr) { - logger.error() << "could not connect to the Wayland display"; + waylandLogger.error() << "could not connect to the Wayland display"; return {nullptr, nullptr}; } static const wl_registry_listener registryListener = [] { @@ -2241,7 +1751,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { wl_registry_add_listener(state.registry, ®istryListener, nullptr); wl_display_roundtrip(state.display); if (state.compositor == nullptr || state.wmBase == nullptr) { - logger.error() << "the compositor does not provide xdg-shell"; + waylandLogger.error() << "the compositor does not provide xdg-shell"; wl_display_disconnect(state.display); state.display = nullptr; return {nullptr, nullptr}; @@ -2320,7 +1830,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { while (!window->configured) { if (wl_display_dispatch(state.display) == -1) { - logger.error() << "the Wayland connection was lost"; + waylandLogger.error() << "the Wayland connection was lost"; return {nullptr, nullptr}; } } @@ -2330,7 +1840,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { ); if (window->eglDisplay == EGL_NO_DISPLAY || eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { - logger.error() << "could not initialize EGL"; + waylandLogger.error() << "could not initialize EGL"; return {nullptr, nullptr}; } eglBindAPI(EGL_OPENGL_API); @@ -2348,7 +1858,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { }; eglChooseConfig(window->eglDisplay, configAttributes, &config, 1, &configCount); if (samples > 0 && configCount == 0) { - logger.warning() << "multisampling is not available"; + waylandLogger.warning() << "multisampling is not available"; const EGLint fallbackAttributes[] { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, @@ -2361,7 +1871,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { ); } if (configCount == 0) { - logger.error() << "no suitable EGL config"; + waylandLogger.error() << "no suitable EGL config"; return {nullptr, nullptr}; } @@ -2386,7 +1896,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { window->eglDisplay, window->eglSurface, window->eglSurface, window->eglContext ) == EGL_FALSE) { - logger.error() << "could not create the OpenGL context"; + waylandLogger.error() << "could not create the OpenGL context"; return {nullptr, nullptr}; } eglSwapInterval(window->eglDisplay, 0); @@ -2394,7 +1904,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { - logger.error() << "failed to initialize GLEW:\n" + waylandLogger.error() << "failed to initialize GLEW:\n" << glewGetErrorString(glewError); return {nullptr, nullptr}; } @@ -2409,13 +1919,36 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); if (maxTextureSize[0] > 0) { Texture::MAX_RESOLUTION = maxTextureSize[0]; - logger.info() << "max texture size is " << Texture::MAX_RESOLUTION; + waylandLogger.info() << "max texture size is " << Texture::MAX_RESOLUTION; } - logger.info() << "GL Vendor: " + waylandLogger.info() << "GL Vendor: " << reinterpret_cast(glGetString(GL_VENDOR)); - logger.info() << "GL Renderer: " + waylandLogger.info() << "GL Renderer: " << reinterpret_cast(glGetString(GL_RENDERER)); - logger.info() << "windowing platform: Wayland (native)"; + waylandLogger.info() << "windowing platform: Wayland (native)"; return {std::move(windowPtr), std::move(inputPtr)}; } + +void on_display_error() { + waylandLogger.error() << "the Wayland connection was lost"; + if (window) { + window->setShouldClose(true); + } +} + +void WaylandInput::pollEvents(bool waitForRefresh) { + beginFrame(); + dispatch(waitForRefresh); + if (window) { + window->paceFrame(); + } + updateRepeat(); + updateBindings(); +} + +void WaylandInput::refreshWindow() { + if (window) { + window->setShouldRefresh(); + } +} diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp new file mode 100644 index 000000000..a1b91293d --- /dev/null +++ b/src/window/wayland/WaylandCommon.cpp @@ -0,0 +1,118 @@ +#include "window/wayland/WaylandCommon.hpp" + +#include +#include + +debug::Logger waylandLogger("window"); + + +WaylandState state; + +class WaylandInput; +class WaylandWindow; + +WaylandInput* input = nullptr; +WaylandWindow* window = nullptr; + +bool decorations_enabled() { + const char* value = getenv("VOXEL_DECORATIONS"); + return value == nullptr || strcmp(value, "none") != 0; +} + +bool serverDecorations = false; + +int keycode_from_keysym(xkb_keysym_t sym) { + switch (sym) { + case XKB_KEY_Escape: return GLFW_KEY_ESCAPE; + case XKB_KEY_Return: return GLFW_KEY_ENTER; + case XKB_KEY_Tab: return GLFW_KEY_TAB; + case XKB_KEY_BackSpace: return GLFW_KEY_BACKSPACE; + case XKB_KEY_Insert: return GLFW_KEY_INSERT; + case XKB_KEY_Delete: return GLFW_KEY_DELETE; + case XKB_KEY_Left: return GLFW_KEY_LEFT; + case XKB_KEY_Right: return GLFW_KEY_RIGHT; + case XKB_KEY_Up: return GLFW_KEY_UP; + case XKB_KEY_Down: return GLFW_KEY_DOWN; + case XKB_KEY_Page_Up: return GLFW_KEY_PAGE_UP; + case XKB_KEY_Page_Down: return GLFW_KEY_PAGE_DOWN; + case XKB_KEY_Home: return GLFW_KEY_HOME; + case XKB_KEY_End: return GLFW_KEY_END; + case XKB_KEY_Caps_Lock: return GLFW_KEY_CAPS_LOCK; + case XKB_KEY_Scroll_Lock: return GLFW_KEY_SCROLL_LOCK; + case XKB_KEY_Num_Lock: return GLFW_KEY_NUM_LOCK; + case XKB_KEY_Print: return GLFW_KEY_PRINT_SCREEN; + case XKB_KEY_Pause: return GLFW_KEY_PAUSE; + case XKB_KEY_Menu: return GLFW_KEY_MENU; + case XKB_KEY_Shift_L: return GLFW_KEY_LEFT_SHIFT; + case XKB_KEY_Control_L: return GLFW_KEY_LEFT_CONTROL; + case XKB_KEY_Alt_L: return GLFW_KEY_LEFT_ALT; + case XKB_KEY_Super_L: return GLFW_KEY_LEFT_SUPER; + case XKB_KEY_Shift_R: return GLFW_KEY_RIGHT_SHIFT; + case XKB_KEY_Control_R: return GLFW_KEY_RIGHT_CONTROL; + case XKB_KEY_Alt_R: return GLFW_KEY_RIGHT_ALT; + case XKB_KEY_Super_R: return GLFW_KEY_RIGHT_SUPER; + case XKB_KEY_space: return GLFW_KEY_SPACE; + case XKB_KEY_apostrophe: return GLFW_KEY_APOSTROPHE; + case XKB_KEY_comma: return GLFW_KEY_COMMA; + case XKB_KEY_minus: return GLFW_KEY_MINUS; + case XKB_KEY_period: return GLFW_KEY_PERIOD; + case XKB_KEY_slash: return GLFW_KEY_SLASH; + case XKB_KEY_semicolon: return GLFW_KEY_SEMICOLON; + case XKB_KEY_equal: return GLFW_KEY_EQUAL; + case XKB_KEY_bracketleft: return GLFW_KEY_LEFT_BRACKET; + case XKB_KEY_backslash: return GLFW_KEY_BACKSLASH; + case XKB_KEY_bracketright: return GLFW_KEY_RIGHT_BRACKET; + case XKB_KEY_grave: return GLFW_KEY_GRAVE_ACCENT; + case XKB_KEY_KP_0: return GLFW_KEY_KP_0; + case XKB_KEY_KP_1: return GLFW_KEY_KP_1; + case XKB_KEY_KP_2: return GLFW_KEY_KP_2; + case XKB_KEY_KP_3: return GLFW_KEY_KP_3; + case XKB_KEY_KP_4: return GLFW_KEY_KP_4; + case XKB_KEY_KP_5: return GLFW_KEY_KP_5; + case XKB_KEY_KP_6: return GLFW_KEY_KP_6; + case XKB_KEY_KP_7: return GLFW_KEY_KP_7; + case XKB_KEY_KP_8: return GLFW_KEY_KP_8; + case XKB_KEY_KP_9: return GLFW_KEY_KP_9; + case XKB_KEY_KP_Decimal: return GLFW_KEY_KP_DECIMAL; + case XKB_KEY_KP_Divide: return GLFW_KEY_KP_DIVIDE; + case XKB_KEY_KP_Multiply: return GLFW_KEY_KP_MULTIPLY; + case XKB_KEY_KP_Subtract: return GLFW_KEY_KP_SUBTRACT; + case XKB_KEY_KP_Add: return GLFW_KEY_KP_ADD; + case XKB_KEY_KP_Enter: return GLFW_KEY_KP_ENTER; + case XKB_KEY_KP_Equal: return GLFW_KEY_KP_EQUAL; + } + if (sym >= XKB_KEY_a && sym <= XKB_KEY_z) { + return GLFW_KEY_A + (sym - XKB_KEY_a); + } + if (sym >= XKB_KEY_A && sym <= XKB_KEY_Z) { + return GLFW_KEY_A + (sym - XKB_KEY_A); + } + if (sym >= XKB_KEY_0 && sym <= XKB_KEY_9) { + return GLFW_KEY_0 + (sym - XKB_KEY_0); + } + if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F12) { + return GLFW_KEY_F1 + (sym - XKB_KEY_F1); + } + return 0; +} + +void dispatch_events(int timeoutMs) { + wl_display_flush(state.display); + while (wl_display_prepare_read(state.display) != 0) { + wl_display_dispatch_pending(state.display); + wl_display_flush(state.display); + } + pollfd descriptor {wl_display_get_fd(state.display), POLLIN, 0}; + if (poll(&descriptor, 1, timeoutMs) > 0) { + if (wl_display_read_events(state.display) == -1) { + wl_display_cancel_read(state.display); + } + } else { + wl_display_cancel_read(state.display); + } + wl_display_dispatch_pending(state.display); + if (wl_display_get_error(state.display) != 0) { + on_display_error(); + } +} + diff --git a/src/window/wayland/WaylandCommon.hpp b/src/window/wayland/WaylandCommon.hpp new file mode 100644 index 000000000..36b6a8dab --- /dev/null +++ b/src/window/wayland/WaylandCommon.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include + +#include "debug/Logger.hpp" + +#include +#include +#include + +#include "cursor-shape-v1-client-protocol.h" +#include "idle-inhibit-unstable-v1-client-protocol.h" +#include "pointer-constraints-unstable-v1-client-protocol.h" +#include "relative-pointer-unstable-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" + +#include +#include + +extern debug::Logger waylandLogger; + +struct WaylandState { + wl_display* display = nullptr; + wl_registry* registry = nullptr; + wl_compositor* compositor = nullptr; + wl_surface* surface = nullptr; + xdg_wm_base* wmBase = nullptr; + xdg_surface* xdgSurface = nullptr; + xdg_toplevel* toplevel = nullptr; + zxdg_toplevel_decoration_v1* decoration = nullptr; + wl_seat* seat = nullptr; + wl_pointer* pointer = nullptr; + wl_keyboard* keyboard = nullptr; + wl_data_device_manager* dataDeviceManager = nullptr; + wl_data_device* dataDevice = nullptr; + wp_cursor_shape_manager_v1* cursorShapeManager = nullptr; + wp_cursor_shape_device_v1* cursorShapeDevice = nullptr; + zwp_pointer_constraints_v1* pointerConstraints = nullptr; + zwp_relative_pointer_manager_v1* relativePointerManager = nullptr; + zwp_relative_pointer_v1* relativePointer = nullptr; + zwp_locked_pointer_v1* lockedPointer = nullptr; + zwp_idle_inhibit_manager_v1* idleInhibitManager = nullptr; + zwp_idle_inhibitor_v1* idleInhibitor = nullptr; + zxdg_decoration_manager_v1* decorationManager = nullptr; + xkb_context* xkbContext = nullptr; + xkb_keymap* xkbKeymap = nullptr; + xkb_state* xkbState = nullptr; + uint32_t pointerSerial = 0; + uint32_t inputSerial = 0; + uint32_t repeatRate = 25; + uint32_t repeatDelay = 400; + bool entered = false; +}; + +extern WaylandState state; + +class WaylandInput; +class WaylandWindow; + +extern WaylandInput* input; +extern WaylandWindow* window; + +template +void ignore_event(Args...) { +} + +bool decorations_enabled(); +void dispatch_events(int timeoutMs); +int keycode_from_keysym(xkb_keysym_t sym); + +extern bool serverDecorations; + +void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +); +void on_display_error(); diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp new file mode 100644 index 000000000..048bfac8e --- /dev/null +++ b/src/window/wayland/WaylandInput.hpp @@ -0,0 +1,332 @@ +#pragma once + +#include "window/wayland/WaylandCommon.hpp" + +#include "window/detail/BaseInput.hpp" + +#include "window/Window.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +class WaylandInput : public BaseInput { +public: + void pollEvents(bool waitForRefresh) override; + + const char* getClipboardText() const override { + if (state.dataDevice == nullptr || selection == nullptr) { + return clipboard.c_str(); + } + const char* mime = pickMime(); + if (mime == nullptr) { + return clipboard.c_str(); + } + int fds[2]; + if (pipe(fds) == -1) { + return clipboard.c_str(); + } + wl_data_offer_receive(selection, mime, fds[1]); + close(fds[1]); + wl_display_flush(state.display); + + clipboard.clear(); + char buffer[4096]; + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(500); + while (std::chrono::steady_clock::now() < deadline) { + pollfd descriptor {fds[0], POLLIN, 0}; + if (poll(&descriptor, 1, 50) <= 0) { + wl_display_dispatch_pending(state.display); + continue; + } + ssize_t length = read(fds[0], buffer, sizeof(buffer)); + if (length <= 0) { + break; + } + clipboard.append(buffer, length); + } + close(fds[0]); + return clipboard.c_str(); + } + + void setClipboardText(const char* text) override { + if (state.dataDeviceManager == nullptr || state.dataDevice == nullptr) { + return; + } + auto* source = wl_data_device_manager_create_data_source( + state.dataDeviceManager + ); + wl_data_source_add_listener(source, &sourceListener(), nullptr); + wl_data_source_offer(source, "text/plain;charset=utf-8"); + wl_data_source_offer(source, "text/plain"); + wl_data_source_offer(source, "UTF8_STRING"); + sourceText = text ? text : ""; + wl_data_device_set_selection(state.dataDevice, source, state.inputSerial); + wl_display_flush(state.display); + } + + void toggleCursor() override { + cursorDrag = false; + if (cursorLocked) { + if (state.lockedPointer) { + zwp_locked_pointer_v1_destroy(state.lockedPointer); + state.lockedPointer = nullptr; + } + if (state.relativePointer) { + zwp_relative_pointer_v1_destroy(state.relativePointer); + state.relativePointer = nullptr; + } + cursorLocked = false; + applyCursor(); + return; + } + if (state.pointerConstraints && state.pointer && state.surface) { + state.lockedPointer = zwp_pointer_constraints_v1_lock_pointer( + state.pointerConstraints, + state.surface, + state.pointer, + nullptr, + ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT + ); + } + if (state.relativePointerManager && state.pointer) { + state.relativePointer = + zwp_relative_pointer_manager_v1_get_relative_pointer( + state.relativePointerManager, state.pointer + ); + zwp_relative_pointer_v1_add_listener( + state.relativePointer, &relativePointerListener(), nullptr + ); + } + if (state.pointer && state.entered) { + wl_pointer_set_cursor( + state.pointer, state.pointerSerial, nullptr, 0, 0 + ); + } + cursorLocked = true; + } + + void setCursorShape(CursorShape shape) { + if (cursor == shape) { + return; + } + cursor = shape; + applyCursor(); + } + + void applyCursor() { + if (cursorLocked || !state.entered || !state.cursorShapeDevice) { + return; + } + wp_cursor_shape_device_v1_set_shape( + state.cursorShapeDevice, state.pointerSerial, + shapeId(overrideCursor ? *overrideCursor : cursor) + ); + } + + void setOverrideCursor(std::optional shape) { + if (overrideCursor == shape) { + return; + } + overrideCursor = shape; + applyCursor(); + } + + void onRelativeMotion(double dx, double dy) { + delta.x += dx; + delta.y += dy; + } + + void onKey(uint32_t key, bool pressed) { + if (state.xkbState == nullptr || state.xkbKeymap == nullptr) { + return; + } + xkb_keycode_t code = key + 8; + const xkb_keysym_t* syms = nullptr; + if (xkb_keymap_key_get_syms_by_level( + state.xkbKeymap, code, 0, 0, &syms + ) > 0) { + int keycode = keycode_from_keysym(syms[0]); + if (keycode != 0) { + onKeyCallback(keycode, pressed); + } + if (pressed) { + repeatKeycode = code; + repeatTime = now(); + lastRepeat = repeatTime; + } else if (code == repeatKeycode) { + repeatKeycode = 0; + } + } + if (pressed) { + appendCodepoints(code); + } + xkb_state_update_key( + state.xkbState, code, pressed ? XKB_KEY_DOWN : XKB_KEY_UP + ); + } + + void refreshWindow(); + + wl_data_offer* selection = nullptr; + std::vector selectionMimes; + std::vector pendingMimes; + mutable std::string clipboard; + std::string sourceText; +private: + static uint32_t shapeId(CursorShape shape) { + switch (shape) { + case CursorShape::ARROW: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + case CursorShape::TEXT: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT; + case CursorShape::CROSSHAIR: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR; + case CursorShape::POINTER: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER; + case CursorShape::EW_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE; + case CursorShape::NS_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE; + case CursorShape::NWSE_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE; + case CursorShape::NESW_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE; + case CursorShape::ALL_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE; + case CursorShape::NOT_ALLOWED: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED; + } + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + } + + static void dispatch(bool block) { + dispatch_events(block ? 500 : 0); + } + + static double now() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); + } + + void appendCodepoints(xkb_keycode_t code) { + char buffer[64]; + int length = xkb_state_key_get_utf8( + state.xkbState, code, buffer, sizeof(buffer) + ); + if (length <= 0) { + return; + } + const auto* bytes = reinterpret_cast(buffer); + uint codepoint = 0; + for (int i = 0; i < length; i++) { + if ((bytes[i] & 0xC0) == 0x80) { + codepoint = (codepoint << 6) | (bytes[i] & 0x3F); + continue; + } + if (codepoint != 0) { + codepoints.push_back(codepoint); + } + codepoint = (bytes[i] & 0x80) ? (bytes[i] & 0x1F) : bytes[i]; + } + if (codepoint != 0) { + codepoints.push_back(codepoint); + } + } + + void updateRepeat() { + if (repeatKeycode == 0 || !state.xkbState) { + return; + } + int keycode = 0; + const xkb_keysym_t* syms = nullptr; + if (xkb_keymap_key_get_syms_by_level( + state.xkbKeymap, repeatKeycode, 0, 0, &syms + ) > 0) { + keycode = keycode_from_keysym(syms[0]); + } + if (keycode == 0 || !pressed(static_cast(keycode))) { + return; + } + double time = now(); + if (time - repeatTime < state.repeatDelay / 1000.0) { + return; + } + double interval = 1.0 / std::max(state.repeatRate, 1); + if (time - lastRepeat < interval) { + return; + } + lastRepeat = time; + onKeyCallback(keycode, true); + appendCodepoints(repeatKeycode); + } + + const char* pickMime() const { + for (const auto& mime : selectionMimes) { + if (mime == "text/plain;charset=utf-8" || mime == "text/plain" || + mime == "UTF8_STRING") { + return mime.c_str(); + } + } + return nullptr; + } + + static const wl_data_source_listener& sourceListener() { + static wl_data_source_listener listener {}; + static bool initialized = false; + if (!initialized) { + initialized = true; + listener.send = [] ( + void*, wl_data_source*, const char*, int32_t fd + ) { + if (input) { + const std::string& text = input->sourceText; + if (!text.empty() && write(fd, text.data(), text.size()) < 0) { + waylandLogger.warning() << "could not write to the clipboard"; + } + } + close(fd); + }; + listener.cancelled = [] (void*, wl_data_source* source) { + wl_data_source_destroy(source); + }; + listener.target = ignore_event<>; + listener.dnd_drop_performed = ignore_event<>; + listener.dnd_finished = ignore_event<>; + listener.action = ignore_event<>; + } + return listener; + } + + static const zwp_relative_pointer_v1_listener& relativePointerListener() { + static zwp_relative_pointer_v1_listener listener {}; + static bool initialized = false; + if (!initialized) { + initialized = true; + listener.relative_motion = [] ( + void*, zwp_relative_pointer_v1*, uint32_t, uint32_t, + wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t, wl_fixed_t + ) { + if (input) { + input->onRelativeMotion( + wl_fixed_to_double(dx), wl_fixed_to_double(dy) + ); + } + }; + } + return listener; + } + + CursorShape cursor = CursorShape::ARROW; + std::optional overrideCursor; + xkb_keycode_t repeatKeycode = 0; + double repeatTime = 0.0; + double lastRepeat = 0.0; +}; From b934e033b33ad26c3c1964fc4c286cb4afe088ba Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 00:51:44 +0300 Subject: [PATCH 03/35] split the rest of the Wayland backend WaylandWindow.cpp kept the window class with all methods defined in place, the decorations, the free event listeners and the initialization in one file. Now: - WaylandWindow.hpp: the class declaration; - WaylandWindow.cpp: surface, EGL, resize and frame pacing; - WaylandBar.cpp: the window decorations (bar, font, buttons, dragging, edge resizing); - WaylandListeners.cpp/.hpp: the free Wayland event handlers; - WaylandInit.cpp: wayland_window_initialize. No functional change. --- src/window/detail/WaylandWindow.cpp | 1954 ----------------------- src/window/wayland/WaylandBar.cpp | 614 +++++++ src/window/wayland/WaylandCommon.cpp | 16 + src/window/wayland/WaylandCommon.hpp | 21 + src/window/wayland/WaylandInit.cpp | 228 +++ src/window/wayland/WaylandListeners.cpp | 359 +++++ src/window/wayland/WaylandListeners.hpp | 14 + src/window/wayland/WaylandWindow.cpp | 624 ++++++++ src/window/wayland/WaylandWindow.hpp | 153 ++ 9 files changed, 2029 insertions(+), 1954 deletions(-) delete mode 100644 src/window/detail/WaylandWindow.cpp create mode 100644 src/window/wayland/WaylandBar.cpp create mode 100644 src/window/wayland/WaylandInit.cpp create mode 100644 src/window/wayland/WaylandListeners.cpp create mode 100644 src/window/wayland/WaylandListeners.hpp create mode 100644 src/window/wayland/WaylandWindow.cpp create mode 100644 src/window/wayland/WaylandWindow.hpp diff --git a/src/window/detail/WaylandWindow.cpp b/src/window/detail/WaylandWindow.cpp deleted file mode 100644 index 094ed95bb..000000000 --- a/src/window/detail/WaylandWindow.cpp +++ /dev/null @@ -1,1954 +0,0 @@ -#include "window/wayland/WaylandCommon.hpp" -#include "window/wayland/WaylandInput.hpp" - -#include "window/Window.hpp" -#include "window/detail/BaseInput.hpp" -#include "window/detail/WindowBackends.hpp" - -#include "debug/Logger.hpp" -#include "graphics/core/ImageData.hpp" -#include "graphics/core/Texture.hpp" -#include "settings.hpp" -#include "util/platform.hpp" - -#include -#include -#include -#include -#include -#include -#include - -#include "cursor-shape-v1-client-protocol.h" -#include "idle-inhibit-unstable-v1-client-protocol.h" -#include "pointer-constraints-unstable-v1-client-protocol.h" -#include "relative-pointer-unstable-v1-client-protocol.h" -#include "xdg-decoration-unstable-v1-client-protocol.h" -#include "xdg-shell-client-protocol.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -static constexpr int BAR_HEIGHT = 30; -static constexpr int BAR_BUTTON = 30; -static constexpr int BAR_EDGE = 5; -static constexpr int BAR_ICON_SIZE = 16; -static constexpr int BAR_FONT_W = 8; -static constexpr int BAR_FONT_H = 8; -static constexpr int BAR_GLYPHS = 159; - -static const uint8_t BAR_FONT[BAR_GLYPHS][BAR_FONT_H] { - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x50, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x14, 0x14, 0x7e, 0x28, 0xfe, 0x28, 0x68}, - {0x00, 0x10, 0x78, 0x70, 0x78, 0x7c, 0x1c, 0x78}, - {0x00, 0x62, 0xf4, 0xfc, 0x6b, 0x1f, 0x17, 0x23}, - {0x00, 0x38, 0x60, 0x30, 0x7a, 0xde, 0x6c, 0x7e}, - {0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x20, 0x60, 0x60, 0x40, 0x40, 0x60, 0x60, 0x20}, - {0x40, 0x60, 0x20, 0x20, 0x20, 0x20, 0x60, 0x40}, - {0x00, 0x20, 0xf0, 0x70, 0xf0, 0x20, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x10, 0x10, 0x7e, 0x10, 0x10}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x40}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60}, - {0x00, 0x20, 0x20, 0x60, 0x40, 0x40, 0xc0, 0x80}, - {0x00, 0x38, 0x6c, 0xcc, 0xcc, 0xcc, 0x6c, 0x38}, - {0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x7c}, - {0x00, 0x78, 0x18, 0x18, 0x18, 0x30, 0x60, 0x7c}, - {0x00, 0x78, 0x18, 0x18, 0x38, 0x1c, 0x1c, 0xf8}, - {0x00, 0x18, 0x38, 0x78, 0x58, 0xd8, 0xfc, 0x18}, - {0x00, 0x78, 0x40, 0x40, 0x78, 0x0c, 0x0c, 0x78}, - {0x00, 0x38, 0x60, 0x40, 0xf8, 0x6c, 0x6c, 0x38}, - {0x00, 0xfc, 0x18, 0x18, 0x18, 0x30, 0x30, 0x60}, - {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x78}, - {0x00, 0x78, 0xc8, 0xcc, 0x7c, 0x0c, 0x18, 0x70}, - {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x00, 0x00, 0x06, 0x3c, 0x60, 0x3c, 0x06}, - {0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00}, - {0x00, 0x00, 0x00, 0x60, 0x3c, 0x0e, 0x3c, 0x60}, - {0x00, 0x70, 0x18, 0x30, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x1e, 0x63, 0x5d, 0x55, 0x57, 0x5e, 0x62}, - {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, - {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, - {0x00, 0x7c, 0x6e, 0x66, 0x66, 0x66, 0x6e, 0x7c}, - {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, - {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x60}, - {0x00, 0x3c, 0x62, 0xc0, 0xce, 0xc6, 0x66, 0x3e}, - {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x6e, 0x7c, 0x78, 0x70, 0x78, 0x6c, 0x66}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7c}, - {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, - {0x00, 0x66, 0x76, 0x76, 0x7e, 0x7e, 0x6e, 0x6e}, - {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, - {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, - {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, - {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x66}, - {0x00, 0x78, 0x68, 0x60, 0x78, 0x0c, 0x4c, 0x78}, - {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0x3c}, - {0x00, 0xc6, 0xc6, 0x6c, 0x6c, 0x78, 0x38, 0x38}, - {0x00, 0xcc, 0xcc, 0x7d, 0x7f, 0x77, 0x73, 0x33}, - {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, - {0x00, 0xcc, 0x6c, 0x78, 0x38, 0x30, 0x30, 0x30}, - {0x00, 0xfc, 0x1c, 0x18, 0x30, 0x70, 0x60, 0xfc}, - {0x70, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x70}, - {0x00, 0x80, 0xc0, 0x40, 0x40, 0x60, 0x20, 0x20}, - {0xe0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe0}, - {0x00, 0x38, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x40, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, - {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, - {0x0c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, - {0x70, 0x60, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, - {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, - {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x40, 0x40, 0x40, 0x4c, 0x78, 0x70, 0x78, 0x4c}, - {0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x00, 0x00, 0x00, 0x7f, 0x6d, 0x4d, 0x4d, 0x4d}, - {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, - {0x00, 0x00, 0x00, 0x78, 0x60, 0x40, 0x40, 0x40}, - {0x00, 0x00, 0x00, 0x78, 0xe0, 0x78, 0x18, 0xf8}, - {0x00, 0x00, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x70}, - {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x6c, 0x7c}, - {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x70, 0x30}, - {0x00, 0x00, 0x00, 0xdb, 0x5b, 0x7e, 0x7e, 0x76}, - {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, - {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, - {0x00, 0x00, 0x00, 0xf8, 0x38, 0x30, 0x60, 0xf8}, - {0x18, 0x30, 0x30, 0x70, 0x30, 0x30, 0x30, 0x18}, - {0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x70, 0x30, 0x30, 0x18, 0x30, 0x30, 0x30, 0x70}, - {0x00, 0x00, 0x00, 0x00, 0x72, 0x1c, 0x00, 0x00}, - {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, - {0x00, 0x7c, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x7c, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x3e, 0x36, 0x36, 0x36, 0x26, 0x66, 0xff}, - {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, - {0x00, 0x64, 0x35, 0x3f, 0x3f, 0x3f, 0x64, 0xc4}, - {0x00, 0x78, 0x0c, 0x0c, 0x38, 0x0c, 0x0c, 0xf8}, - {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, - {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, - {0x00, 0x66, 0x6c, 0x78, 0x78, 0x7c, 0x6c, 0x66}, - {0x00, 0x3e, 0x36, 0x36, 0x36, 0x36, 0x66, 0xc6}, - {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, - {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, - {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, - {0x00, 0x7e, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}, - {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, - {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, - {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, - {0x00, 0xc6, 0x6c, 0x7c, 0x38, 0x38, 0x30, 0x70}, - {0x00, 0x18, 0x7e, 0x7b, 0xd9, 0x7b, 0x7e, 0x18}, - {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, - {0x00, 0x66, 0x66, 0x66, 0x7e, 0x06, 0x06, 0x06}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, - {0x00, 0x70, 0xf0, 0x30, 0x3e, 0x3b, 0x3b, 0x3e}, - {0x00, 0x61, 0x61, 0x61, 0x7d, 0x6d, 0x6d, 0x7d}, - {0x00, 0x60, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x70, 0xf8, 0x0c, 0x7c, 0x0c, 0x1c, 0x78}, - {0x00, 0x67, 0x6c, 0x78, 0x78, 0x78, 0x6c, 0x67}, - {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x3c, 0x6c, 0x6c}, - {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, - {0x38, 0x40, 0xc0, 0xf8, 0xec, 0xcc, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x48, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x40, 0x40, 0x40, 0x40}, - {0x00, 0x00, 0x00, 0x3c, 0x2c, 0x6c, 0x6c, 0xfe}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, - {0x00, 0x00, 0x00, 0x6b, 0x3e, 0x3e, 0x7f, 0xc9}, - {0x00, 0x00, 0x00, 0x70, 0x18, 0x70, 0x18, 0xf0}, - {0x00, 0x00, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, - {0x00, 0x30, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, - {0x00, 0x00, 0x00, 0x58, 0x70, 0x70, 0x78, 0x4c}, - {0x00, 0x00, 0x00, 0x7c, 0x6c, 0x6c, 0x6c, 0xcc}, - {0x00, 0x00, 0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x46}, - {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x7c, 0x4c, 0x4c}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, - {0x00, 0x00, 0x00, 0x7c, 0x4c, 0x4c, 0x4c, 0x4c}, - {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, - {0x00, 0x00, 0x00, 0xf8, 0x30, 0x30, 0x30, 0x30}, - {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, - {0x08, 0x08, 0x08, 0x7f, 0x7b, 0xc9, 0x7b, 0x7f}, - {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, - {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x7c}, - {0x00, 0x00, 0x00, 0xd8, 0xd8, 0x78, 0x18, 0x18}, - {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, - {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, - {0x00, 0x00, 0x00, 0xf0, 0x30, 0x3c, 0x34, 0x3c}, - {0x00, 0x00, 0x00, 0x43, 0x43, 0x7b, 0x4f, 0x7b}, - {0x00, 0x00, 0x00, 0x40, 0x40, 0x78, 0x48, 0x78}, - {0x00, 0x00, 0x00, 0x70, 0x18, 0x78, 0x18, 0x70}, - {0x00, 0x00, 0x00, 0x4e, 0x5b, 0x79, 0x5b, 0x4e}, - {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x78, 0xd8}, -}; - -static int bar_glyph_index(uint32_t codepoint) { - if (codepoint >= 32 && codepoint < 127) { - return static_cast(codepoint) - 32; - } - if (codepoint >= 0x410 && codepoint <= 0x44F) { - return 95 + static_cast(codepoint - 0x410); - } - if (codepoint == 0x401) { - return 95 + 6; - } - if (codepoint == 0x451) { - return 95 + 37; - } - return -1; -} - -static std::vector decode_utf8(const std::string& text) { - std::vector codepoints; - for (size_t i = 0; i < text.size();) { - const uint8_t byte = static_cast(text[i]); - uint32_t codepoint = byte; - size_t length = 1; - if ((byte & 0xE0) == 0xC0) { - codepoint = byte & 0x1F; - length = 2; - } else if ((byte & 0xF0) == 0xE0) { - codepoint = byte & 0x0F; - length = 3; - } else if ((byte & 0xF8) == 0xF0) { - codepoint = byte & 0x07; - length = 4; - } - if (i + length > text.size()) { - break; - } - for (size_t k = 1; k < length; k++) { - codepoint = - (codepoint << 6) | (static_cast(text[i + k]) & 0x3F); - } - codepoints.push_back(codepoint); - i += length; - } - return codepoints; -} - -static GLuint compile_program(const char* vertexSource, const char* fragmentSource) { - GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexSource, nullptr); - glCompileShader(vertexShader); - GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); - glCompileShader(fragmentShader); - GLuint program = glCreateProgram(); - glAttachShader(program, vertexShader); - glAttachShader(program, fragmentShader); - glLinkProgram(program); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); - return program; -} - -static void push_quad( - std::vector& target, float x, float y, float w, float h, float u0, - float v0, float u1, float v1, const glm::vec4& color -) { - const float x1 = x + w; - const float y1 = y + h; - const float vertices[] { - x, y, u0, v0, color.r, color.g, color.b, color.a, - x1, y, u1, v0, color.r, color.g, color.b, color.a, - x, y1, u0, v1, color.r, color.g, color.b, color.a, - x1, y, u1, v0, color.r, color.g, color.b, color.a, - x1, y1, u1, v1, color.r, color.g, color.b, color.a, - x, y1, u0, v1, color.r, color.g, color.b, color.a - }; - target.insert(target.end(), vertices, vertices + 48); -} - -class WaylandWindow : public Window { -public: - WaylandInput& input; - DisplaySettings* settings; - - WaylandWindow( - WaylandInput& input, DisplaySettings* settings, int width, int height - ) - : Window({width, height}), input(input), settings(settings) { - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - } - - ~WaylandWindow() override { - if (state.idleInhibitor) { - zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); - } - if (state.lockedPointer) { - zwp_locked_pointer_v1_destroy(state.lockedPointer); - } - if (state.relativePointer) { - zwp_relative_pointer_v1_destroy(state.relativePointer); - } - if (state.cursorShapeDevice) { - wp_cursor_shape_device_v1_destroy(state.cursorShapeDevice); - } - if (frameCallback) { - wl_callback_destroy(frameCallback); - frameCallback = nullptr; - } - if (cacheTexture) { - glDeleteTextures(1, &cacheTexture); - } - if (cacheFbo) { - glDeleteFramebuffers(1, &cacheFbo); - } - if (stretchProgram) { - glDeleteProgram(stretchProgram); - } - if (stretchVbo) { - glDeleteBuffers(1, &stretchVbo); - } - if (stretchVao) { - glDeleteVertexArrays(1, &stretchVao); - } - if (barFontTexture) { - glDeleteTextures(1, &barFontTexture); - } - if (barIconTexture) { - glDeleteTextures(1, &barIconTexture); - } - if (barProgram) { - glDeleteProgram(barProgram); - } - if (barVbo) { - glDeleteBuffers(1, &barVbo); - } - if (barVao) { - glDeleteVertexArrays(1, &barVao); - } - if (state.dataDevice) { - wl_data_device_destroy(state.dataDevice); - } - if (state.decoration) { - zxdg_toplevel_decoration_v1_destroy(state.decoration); - } - if (state.toplevel) { - xdg_toplevel_destroy(state.toplevel); - } - if (state.xdgSurface) { - xdg_surface_destroy(state.xdgSurface); - } - if (eglSurface != EGL_NO_SURFACE) { - eglDestroySurface(eglDisplay, eglSurface); - } - if (eglWindow) { - wl_egl_window_destroy(eglWindow); - } - if (state.surface) { - wl_surface_destroy(state.surface); - } - if (eglContext != EGL_NO_CONTEXT) { - eglDestroyContext(eglDisplay, eglContext); - } - if (eglDisplay != EGL_NO_DISPLAY) { - eglTerminate(eglDisplay); - } - } - - double time() override { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); - } - - void swapBuffers() override { - updateResizing(); - if (resizing && !presentPending && !frameDone) { - resetScissor(); - return; - } - if (resizing) { - if (renderPending) { - cacheContent(); - renderPending = false; - } else { - drawStretched(); - } - } else { - cacheContent(); - } - drawBar(); - requestFrame(); - eglSwapBuffers(eglDisplay, eglSurface); - resetScissor(); - frameDone = false; - presentPending = false; - const double current = now(); - if (lastPresent > 0.0) { - const double interval = current - lastPresent; - if (interval > 0.001 && interval < 1.0 && !resizing && - frameOnCallback) { - frameInterval = std::clamp( - frameInterval > 0.0 ? frameInterval * 0.8 + interval * 0.2 - : interval, - 1.0 / 240.0, - 1.0 / 30.0 - ); - } - if (resizeLogging) { - summarySum += interval; - summaryMax = std::max(summaryMax, interval); - } - } - lastPresent = current; - nextFrameTime = current + frameInterval; - if (resizeLogging) { - summaryFrames++; - } - if (resizing) { - const double elapsed = now() - configureTime; - resizeTimeSum += elapsed; - resizeTimeMax = std::max(resizeTimeMax, elapsed); - resizePresents++; - } - lastSwapEnd = now(); - if (framerate > 0 && !resizing) { - auto elapsed = time() - prevSwap; - auto frameTime = 1.0 / framerate; - if (elapsed < frameTime) { - platform::sleep( - static_cast((frameTime - elapsed) * 1000) - ); - } - } - prevSwap = time(); - } - - void setShouldRefresh() override { - shouldRefresh = true; - } - - bool checkShouldRefresh() override { - if (shouldRefresh) { - shouldRefresh = false; - return true; - } - return false; - } - - bool isMaximized() const override { - return maximized; - } - - bool isFocused() const override { - return activated; - } - - bool isIconified() const override { - return suspended; - } - - bool isFrameRequired() const override { - return !resizing || renderPending; - } - - bool isShouldClose() const override { - return shouldClose; - } - - void setShouldClose(bool flag) override { - shouldClose = flag; - } - - void setCursor(CursorShape shape) override { - input.setCursorShape(shape); - } - - void setMode(WindowMode mode) override { - Window::mode = mode; - if (input.isCursorLocked()) { - input.toggleCursor(); - } - switch (mode) { - case WindowMode::FULLSCREEN: - setFullscreen(true); - setIdleInhibit(true); - break; - case WindowMode::BORDERLESS: - setFullscreen(false); - setMaximized(true); - setIdleInhibit(true); - break; - case WindowMode::WINDOWED: - setFullscreen(false); - setMaximized(false); - setIdleInhibit(false); - resize(settings->width.get(), settings->height.get()); - break; - } - wl_surface_commit(state.surface); - } - - WindowMode getMode() const override { - return mode; - } - - void focus() override { - if (!focusWarning) { - focusWarning = true; - waylandLogger.warning() << "raising windows is not allowed on Wayland"; - } - } - - void setTitle(const std::string& title) override { - this->title = title; - xdg_toplevel_set_title(state.toplevel, title.c_str()); - } - - void setFullscreen(bool enabled) { - fullscreen = enabled; - if (enabled) { - xdg_toplevel_set_fullscreen(state.toplevel, nullptr); - } else { - xdg_toplevel_unset_fullscreen(state.toplevel); - } - } - - void setMaximized(bool enabled) { - if (enabled) { - xdg_toplevel_set_maximized(state.toplevel); - } else { - xdg_toplevel_unset_maximized(state.toplevel); - } - } - - bool isIconSupported() const override { - return true; - } - - void setIcon(const ImageData* image) override { - if (image == nullptr || image->getData() == nullptr) { - return; - } - iconWidth = static_cast(image->getWidth()); - iconHeight = static_cast(image->getHeight()); - if (iconWidth <= 0 || iconHeight <= 0) { - return; - } - const size_t pixels = static_cast(iconWidth) * iconHeight; - const bool alpha = image->getFormat() == ImageFormat::RGBA8888; - iconPixels.resize(pixels * 4); - for (size_t i = 0; i < pixels; i++) { - iconPixels[i * 4] = image->getData()[i * (alpha ? 4 : 3)]; - iconPixels[i * 4 + 1] = image->getData()[i * (alpha ? 4 : 3) + 1]; - iconPixels[i * 4 + 2] = image->getData()[i * (alpha ? 4 : 3) + 2]; - iconPixels[i * 4 + 3] = alpha ? image->getData()[i * 4 + 3] : 255; - } - if (barIconTexture != 0) { - glDeleteTextures(1, &barIconTexture); - barIconTexture = 0; - } - } - - void resize(int width, int height) { - if (width <= 0 || height <= 0) { - return; - } - if (size.x != width || size.y != height) { - markResizing(); - } - configureTime = now(); - presentPending = true; - if (eglWindow) { - wl_egl_window_resize(eglWindow, width, height, 0, 0); - } - glViewport(0, 0, width, height); - size = {width, height}; - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - } - - void onConfigure(int32_t width, int32_t height, wl_array* states) { - pendingWidth = width; - pendingHeight = height; - stateMaximized = false; - stateSuspended = false; - stateActivated = false; - const auto* values = static_cast(states->data); - for (size_t i = 0; i < states->size / sizeof(uint32_t); i++) { - switch (values[i]) { - case XDG_TOPLEVEL_STATE_MAXIMIZED: - stateMaximized = true; - break; - case XDG_TOPLEVEL_STATE_SUSPENDED: - stateSuspended = true; - break; - case XDG_TOPLEVEL_STATE_ACTIVATED: - stateActivated = true; - break; - } - } - } - - void applyConfigure() { - if (pendingWidth > 0 && pendingHeight > 0) { - resize(pendingWidth, pendingHeight); - } - maximized = stateMaximized; - suspended = stateSuspended; - activated = stateActivated; - configured = true; - setShouldRefresh(); - } - - void pushScissor(glm::vec4 area) override { - if (scissorStack.empty()) { - glEnable(GL_SCISSOR_TEST); - } - scissorStack.push(scissorArea); - - area.z += glm::ceil(area.x); - area.w += glm::ceil(area.y); - - area.x = glm::max(area.x, scissorArea.x); - area.y = glm::max(area.y, scissorArea.y); - - area.z = glm::min(area.z, scissorArea.z); - area.w = glm::min(area.w, scissorArea.w); - - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(glm::ceil(area.z - area.x))), - std::max(0, static_cast(glm::ceil(area.w - area.y))) - ); - } - scissorArea = area; - } - - void popScissor() override { - if (scissorStack.empty()) { - waylandLogger.warning() << "extra Window::popScissor call"; - return; - } - glm::vec4 area = scissorStack.top(); - scissorStack.pop(); - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(area.z - area.x)), - std::max(0, static_cast(area.w - area.y)) - ); - } - if (scissorStack.empty()) { - glDisable(GL_SCISSOR_TEST); - } - scissorArea = area; - } - - void resetScissor() override { - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - scissorStack = std::stack(); - glDisable(GL_SCISSOR_TEST); - } - - std::unique_ptr takeScreenshot() override { - glBindFramebuffer(GL_FRAMEBUFFER, 0); - auto data = std::make_unique(size.x * size.y * 3); - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); - return std::make_unique( - ImageFormat::RGB888, size.x, size.y, data.release() - ); - } - - void setFramerate(int framerate) override { - this->framerate = framerate; - } - - void initStretchRenderer() { - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "out vec2 vUV;\n" - "void main() {\n" - " vUV = aPos * 0.5 + 0.5;\n" - " gl_Position = vec4(aPos, 0.0, 1.0);\n" - "}\n"; - static const char* fragmentSource = - "#version 330 core\n" - "in vec2 vUV;\n" - "out vec4 color;\n" - "uniform sampler2D uTexture;\n" - "void main() {\n" - " color = texture(uTexture, vUV);\n" - "}\n"; - GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexSource, nullptr); - glCompileShader(vertexShader); - GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); - glCompileShader(fragmentShader); - stretchProgram = glCreateProgram(); - glAttachShader(stretchProgram, vertexShader); - glAttachShader(stretchProgram, fragmentShader); - glLinkProgram(stretchProgram); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); - - const float vertices[] {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f}; - glGenVertexArrays(1, &stretchVao); - glGenBuffers(1, &stretchVbo); - glBindVertexArray(stretchVao); - glBindBuffer(GL_ARRAY_BUFFER, stretchVbo); - glBufferData( - GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW - ); - glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); - glBindVertexArray(0); - glGenFramebuffers(1, &cacheFbo); - glGenTextures(1, &cacheTexture); - } - - void resizeCache(int width, int height) { - if (cacheWidth == width && cacheHeight == height) { - return; - } - cacheWidth = width; - cacheHeight = height; - glBindTexture(GL_TEXTURE_2D, cacheTexture); - glTexImage2D( - GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, - GL_UNSIGNED_BYTE, nullptr - ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindFramebuffer(GL_FRAMEBUFFER, cacheFbo); - glFramebufferTexture2D( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cacheTexture, - 0 - ); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glBindTexture(GL_TEXTURE_2D, 0); - } - - void cacheContent() { - if (stretchProgram == 0) { - return; - } - resizeCache(size.x, size.y); - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, cacheFbo); - glBlitFramebuffer( - 0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT, - GL_NEAREST - ); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - lastCacheTime = now(); - } - - void drawStretched() { - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glViewport(0, 0, size.x, size.y); - glDisable(GL_DEPTH_TEST); - glDisable(GL_BLEND); - glDisable(GL_CULL_FACE); - glDisable(GL_SCISSOR_TEST); - if (stretchProgram == 0 || cacheWidth == 0) { - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - return; - } - glUseProgram(stretchProgram); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, cacheTexture); - glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); - glBindVertexArray(stretchVao); - glDrawArrays(GL_TRIANGLES, 0, 3); - glBindVertexArray(0); - glUseProgram(0); - } - - // libdecor redraws the whole decoration inside libdecor_frame_commit, - // which is also the only place where it acks the configure - void enableOwnDecorations() { - if (!decorations_enabled()) { - return; - } - barEnabled = true; - setShouldRefresh(); - } - - bool barVisible() const { - return barEnabled && !fullscreen && Window::mode != WindowMode::BORDERLESS; - } - - void initBarRenderer() { - if (barProgram != 0) { - return; - } - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "layout(location = 1) in vec2 aUv;\n" - "layout(location = 2) in vec4 aColor;\n" - "uniform vec2 uViewport;\n" - "out vec2 vUv;\n" - "out vec4 vColor;\n" - "void main() {\n" - " vec2 ndc = vec2(aPos.x / uViewport.x * 2.0 - 1.0," - " 1.0 - aPos.y / uViewport.y * 2.0);\n" - " gl_Position = vec4(ndc, 0.0, 1.0);\n" - " vUv = aUv;\n" - " vColor = aColor;\n" - "}\n"; - static const char* fragmentSource = - "#version 330 core\n" - "in vec2 vUv;\n" - "in vec4 vColor;\n" - "out vec4 outColor;\n" - "uniform sampler2D uTexture;\n" - "uniform int uMode;\n" - "void main() {\n" - " if (uMode == 1) {\n" - " outColor = vec4(vColor.rgb," - " vColor.a * texture(uTexture, vUv).r);\n" - " } else if (uMode == 2) {\n" - " outColor = texture(uTexture, vUv) * vColor;\n" - " } else {\n" - " outColor = vColor;\n" - " }\n" - "}\n"; - barProgram = compile_program(vertexSource, fragmentSource); - barViewportLoc = glGetUniformLocation(barProgram, "uViewport"); - barTextureLoc = glGetUniformLocation(barProgram, "uTexture"); - barModeLoc = glGetUniformLocation(barProgram, "uMode"); - glGenVertexArrays(1, &barVao); - glGenBuffers(1, &barVbo); - glBindVertexArray(barVao); - glBindBuffer(GL_ARRAY_BUFFER, barVbo); - glEnableVertexAttribArray(0); - glVertexAttribPointer( - 0, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr - ); - glEnableVertexAttribArray(1); - glVertexAttribPointer( - 1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), - reinterpret_cast(2 * sizeof(float)) - ); - glEnableVertexAttribArray(2); - glVertexAttribPointer( - 2, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), - reinterpret_cast(4 * sizeof(float)) - ); - glBindVertexArray(0); - glGenTextures(1, &barFontTexture); - glBindTexture(GL_TEXTURE_2D, barFontTexture); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - std::vector pixels(BAR_GLYPHS * BAR_FONT_W * BAR_FONT_H, 0); - for (int glyph = 0; glyph < BAR_GLYPHS; glyph++) { - for (int y = 0; y < BAR_FONT_H; y++) { - for (int x = 0; x < BAR_FONT_W; x++) { - if (BAR_FONT[glyph][y] & (1 << (7 - x))) { - pixels[y * BAR_GLYPHS * BAR_FONT_W + glyph * BAR_FONT_W + x] = - 255; - } - } - } - } - glTexImage2D( - GL_TEXTURE_2D, 0, GL_R8, BAR_GLYPHS * BAR_FONT_W, BAR_FONT_H, 0, - GL_RED, GL_UNSIGNED_BYTE, pixels.data() - ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindTexture(GL_TEXTURE_2D, 0); - } - - void initBarIconTexture() { - if (iconPixels.empty() || barIconTexture != 0) { - return; - } - glGenTextures(1, &barIconTexture); - glBindTexture(GL_TEXTURE_2D, barIconTexture); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D( - GL_TEXTURE_2D, 0, GL_RGBA8, iconWidth, iconHeight, 0, GL_RGBA, - GL_UNSIGNED_BYTE, iconPixels.data() - ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindTexture(GL_TEXTURE_2D, 0); - } - - void barDrawText( - float x, float y, const std::vector& codepoints, int maxChars, - const glm::vec4& color - ) { - const float step = 1.0f / static_cast(BAR_GLYPHS * BAR_FONT_W); - float cursor = x; - for (int i = 0; i < static_cast(codepoints.size()) && i < maxChars; i++) { - const int index = bar_glyph_index(codepoints[i]); - if (index >= 0) { - push_quad( - barText, cursor, y, BAR_FONT_W, BAR_FONT_H, - index * BAR_FONT_W * step, 0.0f, - (index * BAR_FONT_W + BAR_FONT_W) * step, 1.0f, color - ); - } - cursor += BAR_FONT_W; - } - } - - void barDrawBatch(const std::vector& data, int mode, GLuint texture) { - if (data.empty()) { - return; - } - glUniform1i(barModeLoc, mode); - glBindTexture(GL_TEXTURE_2D, texture); - glBufferData( - GL_ARRAY_BUFFER, data.size() * sizeof(float), data.data(), - GL_STREAM_DRAW - ); - glDrawArrays(GL_TRIANGLES, 0, static_cast(data.size() / 8)); - } - - void barFlush() { - glUseProgram(barProgram); - glUniform2f( - barViewportLoc, static_cast(size.x), static_cast(size.y) - ); - glDisable(GL_DEPTH_TEST); - glDisable(GL_CULL_FACE); - glDisable(GL_SCISSOR_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glBindVertexArray(barVao); - glBindBuffer(GL_ARRAY_BUFFER, barVbo); - glActiveTexture(GL_TEXTURE0); - glUniform1i(barTextureLoc, 0); - barDrawBatch(barRects, 0, barFontTexture); - barDrawBatch(barIcons, 2, barIconTexture); - barDrawBatch(barText, 1, barFontTexture); - glBindVertexArray(0); - glDisable(GL_BLEND); - } - - // the bar is drawn over the content surface, so the window size - // reported to the engine stays the same - void drawBar() { - if (!barVisible()) { - return; - } - initBarRenderer(); - initBarIconTexture(); - barRects.clear(); - barText.clear(); - barIcons.clear(); - - const float width = static_cast(size.x); - const float height = static_cast(BAR_HEIGHT); - const glm::vec4 background(0.16f, 0.16f, 0.17f, 1.0f); - const glm::vec4 border(0.09f, 0.09f, 0.10f, 1.0f); - const glm::vec4 ink(0.87f, 0.87f, 0.88f, 1.0f); - const glm::vec4 hover(0.27f, 0.27f, 0.29f, 1.0f); - const glm::vec4 closeHover(0.72f, 0.16f, 0.11f, 1.0f); - - push_quad(barRects, 0, 0, width, height, 0, 0, 0, 0, background); - push_quad(barRects, 0, height - 1, width, 1, 0, 0, 0, 0, border); - - float textX = 10.0f; - if (barIconTexture != 0 && iconWidth > 0) { - push_quad( - barIcons, 7, (height - BAR_ICON_SIZE) * 0.5f, BAR_ICON_SIZE, - BAR_ICON_SIZE, 0, 1, 1, 0, glm::vec4(1.0f) - ); - textX = 7 + BAR_ICON_SIZE + 8; - } - const float buttonsX = width - BAR_BUTTON * 3; - const int maxChars = - static_cast((buttonsX - 8 - textX) / BAR_FONT_W); - if (maxChars > 0) { - barDrawText( - textX, (height - BAR_FONT_H) * 0.5f, decode_utf8(title), - maxChars, ink - ); - } - - for (int i = 0; i < 3; i++) { - const float bx = width - BAR_BUTTON * (i + 1); - if (hoveredButton == i) { - push_quad( - barRects, bx, 0, BAR_BUTTON, height - 1, 0, 0, 0, 0, - i == 0 ? closeHover : hover - ); - } - const float cx = bx + BAR_BUTTON * 0.5f; - const float cy = height * 0.5f; - if (i == 0) { - for (int s = 0; s < 7; s++) { - push_quad(barRects, cx - 4 + s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 3 - s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); - } - } else if (i == 1 && !maximized) { - push_quad(barRects, cx - 4.5f, cy - 4.5f, 9, 1.6f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 4.5f, cy + 2.9f, 9, 1.6f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 4.5f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 2.9f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); - } else if (i == 1) { - push_quad(barRects, cx - 3.5f, cy - 5.5f, 8, 1.4f, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 3.1f, cy - 5.5f, 1.4f, 5.5f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 5.5f, cy - 1.2f, 8, 1.4f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 5.5f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 1.1f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 5.5f, cy + 3.6f, 8, 1.4f, 0, 0, 0, 0, ink); - } else { - push_quad(barRects, cx - 5, cy - 0.8f, 10, 1.6f, 0, 0, 0, 0, ink); - } - } - barFlush(); - } - - int barButtonAt(double x, double y) const { - if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { - return -1; - } - for (int i = 0; i < 3; i++) { - const double bx = size.x - BAR_BUTTON * (i + 1); - if (x >= bx && x < bx + BAR_BUTTON) { - return i; - } - } - return -1; - } - - uint32_t barEdgeAt(double x, double y) const { - uint32_t edges = 0; - if (x < BAR_EDGE) { - edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT; - } else if (x >= size.x - BAR_EDGE) { - edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; - } - if (barVisible() && y < BAR_EDGE) { - edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; - } else if (y >= size.y - BAR_EDGE) { - edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; - } - return edges; - } - - static CursorShape edgeCursor(uint32_t edges) { - const bool left = edges & XDG_TOPLEVEL_RESIZE_EDGE_LEFT; - const bool right = edges & XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; - const bool top = edges & XDG_TOPLEVEL_RESIZE_EDGE_TOP; - const bool bottom = edges & XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; - if ((left && top) || (right && bottom)) { - return CursorShape::NWSE_RESIZE; - } - if ((right && top) || (left && bottom)) { - return CursorShape::NESW_RESIZE; - } - if (left || right) { - return CursorShape::EW_RESIZE; - } - if (top || bottom) { - return CursorShape::NS_RESIZE; - } - return CursorShape::ARROW; - } - - bool handleBarMotion(double x, double y) { - pointerX = x; - pointerY = y; - const int button = barButtonAt(x, y); - if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { - hoveredButton = button; - input.setOverrideCursor( - button >= 0 ? CursorShape::POINTER : CursorShape::ARROW - ); - return true; - } - hoveredButton = -1; - const uint32_t edges = barEdgeAt(x, y); - input.setOverrideCursor( - edges != 0 ? std::optional(edgeCursor(edges)) - : std::nullopt - ); - return false; - } - - bool handleBarButton(uint32_t serial, bool pressed) { - const double x = pointerX; - const double y = pointerY; - const int button = barButtonAt(x, y); - if (button >= 0) { - if (pressed) { - if (button == 0) { - setShouldClose(true); - } else if (button == 1) { - setMaximized(!maximized); - } else { - xdg_toplevel_set_minimized(state.toplevel); - } - } - return true; - } - if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { - if (pressed) { - const double current = now(); - if (current - lastBarPress < 0.4) { - lastBarPress = 0.0; - setMaximized(!maximized); - } else { - lastBarPress = current; - xdg_toplevel_move(state.toplevel, state.seat, serial); - } - } - return true; - } - const uint32_t edges = barEdgeAt(x, y); - if (pressed && edges != 0) { - xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); - return true; - } - return false; - } - - void onPointerLeave() { - hoveredButton = -1; - input.setOverrideCursor(std::nullopt); - } - - void onFrameDone() { - frameCallback = nullptr; - frameDone = true; - } - - void requestFrame() { - if (state.surface == nullptr || frameCallback != nullptr) { - return; - } - frameCallback = wl_surface_frame(state.surface); - wl_callback_add_listener(frameCallback, &frameListener(), this); - } - - void paceFrame() { - frameOnCallback = frameDone; - if (lastSwapEnd > 0.0) { - const double cost = now() - lastSwapEnd; - if (cost > 0.0 && cost < 2.0) { - frameCost = frameCost > 0.0 ? frameCost * 0.8 + cost * 0.2 : cost; - cacheTimeout = std::clamp( - frameCost * 16.0, MIN_CACHE_TIMEOUT, MAX_CACHE_TIMEOUT - ); - } - } - updateResizing(); - logSummary(); - if (resizing) { - if (!renderPending && now() - lastResize > RESIZE_PAUSE && - now() - lastCacheTime > cacheTimeout) { - renderPending = true; - } - dispatch_events(frameDone || presentPending ? 0 : 8); - frameOnCallback = frameDone; - return; - } - if (framerate != -1 || frameCallback == nullptr || frameDone) { - return; - } - const double deadline = now() + FRAME_TIMEOUT; - while (!frameDone && !resizing && now() < deadline) { - dispatch_events(5); - } - while (!frameDone && !resizing && now() < nextFrameTime) { - dispatch_events(5); - } - nextFrameTime = now() + frameInterval; - frameOnCallback = frameDone; - } - - void logSummary() { - const double current = now(); - if (resizeLogging) { - if (lastLoop > 0.0) { - loopGapMax = std::max(loopGapMax, current - lastLoop); - } - lastLoop = current; - loopCount++; - } - if (!resizeLogging || lastSummary <= 0.0) { - if (resizeLogging) { - lastSummary = current; - } - return; - } - if (current - lastSummary < 1.0) { - return; - } - waylandLogger.info() << "loop " << loopCount << "/s (max gap " - << loopGapMax * 1000.0 << " ms), presents " - << summaryFrames << "/s (max gap " - << summaryMax * 1000.0 << " ms), resizing " - << (resizing ? "yes" : "no"); - lastSummary = current; - loopCount = 0; - loopGapMax = 0.0; - summaryFrames = 0; - summarySum = 0.0; - summaryMax = 0.0; - } - - void markResizing() { - lastResize = now(); - if (!resizing) { - resizing = true; - resizePresents = 0; - resizeTimeSum = 0.0; - resizeTimeMax = 0.0; - if (resizeLogging) { - waylandLogger.info() << "resize started"; - } - setShouldRefresh(); - } - } - - void updateResizing() { - if (resizing && now() - lastResize > RESIZE_TIMEOUT) { - resizing = false; - renderPending = true; - if (resizeLogging) { - double average = resizePresents > 0 - ? resizeTimeSum / resizePresents - : 0.0; - waylandLogger.info() - << "resize finished, presented " << resizePresents - << ", avg " << average * 1000.0 << " ms, max " - << resizeTimeMax * 1000.0 << " ms"; - } - } - } - - void setIdleInhibit(bool enabled) { - if (enabled == (state.idleInhibitor != nullptr)) { - return; - } - if (enabled && state.idleInhibitManager) { - state.idleInhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor( - state.idleInhibitManager, state.surface - ); - } else if (state.idleInhibitor) { - zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); - state.idleInhibitor = nullptr; - } - } - - EGLDisplay eglDisplay = EGL_NO_DISPLAY; - EGLContext eglContext = EGL_NO_CONTEXT; - EGLSurface eglSurface = EGL_NO_SURFACE; - wl_egl_window* eglWindow = nullptr; - int32_t pendingWidth = 0; - int32_t pendingHeight = 0; - bool stateMaximized = false; - bool stateSuspended = false; - bool stateActivated = true; - bool configured = false; -private: - static constexpr double RESIZE_TIMEOUT = 0.4; - static constexpr double FRAME_TIMEOUT = 0.025; - static constexpr double RESIZE_PAUSE = 0.12; - static constexpr double MIN_CACHE_TIMEOUT = 0.3; - static constexpr double MAX_CACHE_TIMEOUT = 3.0; - - static const wl_callback_listener& frameListener() { - static wl_callback_listener listener = [] { - wl_callback_listener value {}; - value.done = [] (void* data, wl_callback* callback, uint32_t) { - wl_callback_destroy(callback); - static_cast(data)->onFrameDone(); - }; - return value; - }(); - return listener; - } - - static double now() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); - } - - int framerate = -1; - double prevSwap = 0.0; - double lastResize = 0.0; - static inline bool resizeLogging = getenv("VOXEL_LOG_RESIZE") != nullptr; - bool barEnabled = false; - bool fullscreen = false; - std::string title = "VoxelCore"; - std::vector iconPixels; - int iconWidth = 0; - int iconHeight = 0; - int hoveredButton = -1; - double lastBarPress = 0.0; - double pointerX = 0.0; - double pointerY = 0.0; - GLuint barProgram = 0; - GLuint barVao = 0; - GLuint barVbo = 0; - GLuint barFontTexture = 0; - GLuint barIconTexture = 0; - GLint barViewportLoc = -1; - GLint barTextureLoc = -1; - GLint barModeLoc = -1; - std::vector barRects; - std::vector barText; - std::vector barIcons; - bool frameOnCallback = false; - double frameInterval = 0.0; - double nextFrameTime = 0.0; - double frameCost = 0.0; - double cacheTimeout = 0.5; - bool resizing = false; - bool renderPending = true; - bool presentPending = true; - int resizePresents = 0; - double configureTime = 0.0; - double resizeTimeSum = 0.0; - double resizeTimeMax = 0.0; - double lastPresent = 0.0; - double lastSummary = 0.0; - double summarySum = 0.0; - double summaryMax = 0.0; - int summaryFrames = 0; - double lastLoop = 0.0; - double loopGapMax = 0.0; - int loopCount = 0; - wl_callback* frameCallback = nullptr; - bool frameDone = false; - GLuint stretchProgram = 0; - GLuint stretchVao = 0; - GLuint stretchVbo = 0; - GLuint cacheFbo = 0; - GLuint cacheTexture = 0; - int cacheWidth = 0; - int cacheHeight = 0; - double lastCacheTime = 0.0; - double lastSwapEnd = 0.0; - bool shouldRefresh = true; - bool shouldClose = false; - bool maximized = false; - bool suspended = false; - bool activated = true; - bool focusWarning = false; - std::stack scissorStack; - glm::vec4 scissorArea {}; -}; - -static void pointer_enter( - void*, wl_pointer*, uint32_t serial, wl_surface* surface, wl_fixed_t sx, - wl_fixed_t sy -) { - state.pointerSerial = serial; - state.entered = surface == state.surface; - const double x = wl_fixed_to_double(sx); - const double y = wl_fixed_to_double(sy); - if (state.entered && window && window->handleBarMotion(x, y)) { - return; - } - if (input) { - input->setCursorPosition(x, y); - if (state.entered) { - input->applyCursor(); - } - input->refreshWindow(); - } -} - -static void pointer_leave(void*, wl_pointer*, uint32_t, wl_surface*) { - state.entered = false; - if (window) { - window->onPointerLeave(); - } -} - -static void pointer_motion( - void*, wl_pointer*, uint32_t, wl_fixed_t sx, wl_fixed_t sy -) { - const double x = wl_fixed_to_double(sx); - const double y = wl_fixed_to_double(sy); - if (window && window->handleBarMotion(x, y)) { - return; - } - if (input) { - input->setCursorPosition(x, y); - input->refreshWindow(); - } -} - -static void pointer_button( - void*, wl_pointer*, uint32_t serial, uint32_t, uint32_t button, - uint32_t buttonState -) { - state.inputSerial = serial; - int index = -1; - switch (button) { - case 0x110: index = 0; break; - case 0x111: index = 1; break; - case 0x112: index = 2; break; - case 0x113: index = 3; break; - case 0x114: index = 4; break; - case 0x115: index = 5; break; - case 0x116: index = 6; break; - case 0x117: index = 7; break; - } - const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; - if (index == 0 && window && window->handleBarButton(serial, pressed)) { - return; - } - if (index >= 0 && input) { - input->onMouseCallback(index, pressed); - input->refreshWindow(); - } -} - -static void pointer_axis( - void*, wl_pointer*, uint32_t, uint32_t axis, wl_fixed_t value -) { - if (input && axis == WL_POINTER_AXIS_VERTICAL_SCROLL) { - input->scroll += wl_fixed_to_double(value) > 0 ? -1 : 1; - input->refreshWindow(); - } -} - -static void keyboard_keymap( - void*, wl_keyboard*, uint32_t format, int32_t fd, uint32_t size -) { - if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { - close(fd); - return; - } - char* data = static_cast( - mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0) - ); - close(fd); - if (data == MAP_FAILED) { - return; - } - if (state.xkbContext == nullptr) { - state.xkbContext = xkb_context_new(XKB_CONTEXT_NO_FLAGS); - } - xkb_keymap* keymap = xkb_keymap_new_from_string( - state.xkbContext, data, XKB_KEYMAP_FORMAT_TEXT_V1, - XKB_KEYMAP_COMPILE_NO_FLAGS - ); - munmap(data, size); - if (keymap == nullptr) { - waylandLogger.error() << "could not parse the keyboard keymap"; - return; - } - if (state.xkbState) { - xkb_state_unref(state.xkbState); - } - if (state.xkbKeymap) { - xkb_keymap_unref(state.xkbKeymap); - } - state.xkbKeymap = keymap; - state.xkbState = xkb_state_new(keymap); -} - -static void keyboard_enter( - void*, wl_keyboard*, uint32_t serial, wl_surface*, wl_array* -) { - state.inputSerial = serial; -} - -static void keyboard_leave(void*, wl_keyboard*, uint32_t, wl_surface*) { -} - -static void keyboard_key( - void*, wl_keyboard*, uint32_t serial, uint32_t, uint32_t key, - uint32_t keyState -) { - state.inputSerial = serial; - if (input) { - input->onKey(key, keyState == WL_KEYBOARD_KEY_STATE_PRESSED); - input->refreshWindow(); - } -} - -static void keyboard_modifiers( - void*, wl_keyboard*, uint32_t serial, uint32_t depressed, uint32_t latched, - uint32_t locked, uint32_t group -) { - state.inputSerial = serial; - if (state.xkbState) { - xkb_state_update_mask( - state.xkbState, depressed, latched, locked, 0, 0, group - ); - } -} - -static void keyboard_repeat_info(void*, wl_keyboard*, int32_t rate, int32_t delay) { - state.repeatRate = rate > 0 ? rate : 25; - state.repeatDelay = delay > 0 ? delay : 400; -} - -static void seat_capabilities(void*, wl_seat* seat, uint32_t capabilities) { - static const wl_pointer_listener pointerListener = [] { - wl_pointer_listener listener {}; - listener.enter = pointer_enter; - listener.leave = pointer_leave; - listener.motion = pointer_motion; - listener.button = pointer_button; - listener.axis = pointer_axis; - listener.frame = ignore_event<>; - listener.axis_source = ignore_event<>; - listener.axis_stop = ignore_event<>; - listener.axis_discrete = ignore_event<>; - listener.axis_value120 = ignore_event<>; - listener.axis_relative_direction = ignore_event<>; - return listener; - }(); - - static const wl_keyboard_listener keyboardListener = [] { - wl_keyboard_listener listener {}; - listener.keymap = keyboard_keymap; - listener.enter = keyboard_enter; - listener.leave = keyboard_leave; - listener.key = keyboard_key; - listener.modifiers = keyboard_modifiers; - listener.repeat_info = keyboard_repeat_info; - return listener; - }(); - - bool hasPointer = capabilities & WL_SEAT_CAPABILITY_POINTER; - bool hasKeyboard = capabilities & WL_SEAT_CAPABILITY_KEYBOARD; - if (hasPointer && state.pointer == nullptr) { - state.pointer = wl_seat_get_pointer(seat); - wl_pointer_add_listener(state.pointer, &pointerListener, nullptr); - if (state.cursorShapeManager) { - state.cursorShapeDevice = wp_cursor_shape_manager_v1_get_pointer( - state.cursorShapeManager, state.pointer - ); - } - } else if (!hasPointer && state.pointer) { - if (state.cursorShapeDevice) { - wp_cursor_shape_device_v1_destroy(state.cursorShapeDevice); - state.cursorShapeDevice = nullptr; - } - wl_pointer_destroy(state.pointer); - state.pointer = nullptr; - } - if (hasKeyboard && state.keyboard == nullptr) { - state.keyboard = wl_seat_get_keyboard(seat); - wl_keyboard_add_listener(state.keyboard, &keyboardListener, nullptr); - } else if (!hasKeyboard && state.keyboard) { - wl_keyboard_destroy(state.keyboard); - state.keyboard = nullptr; - } -} - -static void seat_name(void*, wl_seat*, const char*) { -} - -static void wm_base_ping(void*, xdg_wm_base* base, uint32_t serial) { - xdg_wm_base_pong(base, serial); -} - -static void toplevel_configure( - void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states -) { - if (window) { - window->onConfigure(width, height, states); - } -} - -static void toplevel_close(void*, xdg_toplevel*) { - if (window) { - window->setShouldClose(true); - } -} - -static void toplevel_configure_bounds(void*, xdg_toplevel*, int32_t, int32_t) { -} - -static void toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*) { -} - -static void xdg_surface_configure(void*, xdg_surface* surface, uint32_t serial) { - xdg_surface_ack_configure(surface, serial); - if (window) { - window->applyConfigure(); - } -} - -static void data_offer_offer(void*, wl_data_offer*, const char* mime) { - if (input) { - input->pendingMimes.push_back(mime); - } -} - -static void data_device_data_offer(void*, wl_data_device*, wl_data_offer* offer) { - static const wl_data_offer_listener listener = [] { - wl_data_offer_listener value {}; - value.offer = data_offer_offer; - value.source_actions = ignore_event<>; - value.action = ignore_event<>; - return value; - }(); - wl_data_offer_add_listener(offer, &listener, nullptr); -} - -static void data_device_selection(void*, wl_data_device*, wl_data_offer* offer) { - if (input == nullptr) { - return; - } - if (input->selection) { - wl_data_offer_destroy(input->selection); - } - input->selection = offer; - input->selectionMimes = std::move(input->pendingMimes); - input->pendingMimes.clear(); -} - -static void registry_global( - void*, wl_registry* registry, uint32_t name, const char* interface, - uint32_t version -) { - if (strcmp(interface, wl_compositor_interface.name) == 0) { - state.compositor = static_cast(wl_registry_bind( - registry, name, &wl_compositor_interface, std::min(version, 4u) - )); - } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { - state.wmBase = static_cast(wl_registry_bind( - registry, name, &xdg_wm_base_interface, std::min(version, 6u) - )); - static const xdg_wm_base_listener listener = [] { - xdg_wm_base_listener value {}; - value.ping = wm_base_ping; - return value; - }(); - xdg_wm_base_add_listener(state.wmBase, &listener, nullptr); - } else if (strcmp(interface, wl_seat_interface.name) == 0) { - state.seat = static_cast(wl_registry_bind( - registry, name, &wl_seat_interface, std::min(version, 7u) - )); - static const wl_seat_listener listener = [] { - wl_seat_listener value {}; - value.capabilities = seat_capabilities; - value.name = seat_name; - return value; - }(); - wl_seat_add_listener(state.seat, &listener, nullptr); - } else if (strcmp(interface, wl_data_device_manager_interface.name) == 0) { - state.dataDeviceManager = static_cast( - wl_registry_bind( - registry, name, &wl_data_device_manager_interface, - std::min(version, 3u) - ) - ); - } else if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) { - state.cursorShapeManager = static_cast( - wl_registry_bind( - registry, name, &wp_cursor_shape_manager_v1_interface, - std::min(version, 2u) - ) - ); - } else if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) { - state.pointerConstraints = static_cast( - wl_registry_bind( - registry, name, &zwp_pointer_constraints_v1_interface, 1 - ) - ); - } else if ( - strcmp(interface, zwp_relative_pointer_manager_v1_interface.name) == 0 - ) { - state.relativePointerManager = - static_cast(wl_registry_bind( - registry, name, &zwp_relative_pointer_manager_v1_interface, 1 - )); - } else if ( - strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0 - ) { - state.idleInhibitManager = static_cast( - wl_registry_bind( - registry, name, &zwp_idle_inhibit_manager_v1_interface, 1 - ) - ); - } else if ( - strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0 - ) { - state.decorationManager = static_cast( - wl_registry_bind( - registry, name, &zxdg_decoration_manager_v1_interface, 1 - ) - ); - } -} - -static void registry_global_remove(void*, wl_registry*, uint32_t) { -} - -void zxdg_decoration_configure( - void*, zxdg_toplevel_decoration_v1*, uint32_t mode -) { - serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; - if (!serverDecorations && window != nullptr) { - window->enableOwnDecorations(); - } -} - - -std::tuple, std::unique_ptr> -wayland_window_initialize(DisplaySettings* settings, std::string title) { - state.display = wl_display_connect(nullptr); - if (state.display == nullptr) { - waylandLogger.error() << "could not connect to the Wayland display"; - return {nullptr, nullptr}; - } - static const wl_registry_listener registryListener = [] { - wl_registry_listener value {}; - value.global = registry_global; - value.global_remove = registry_global_remove; - return value; - }(); - state.registry = wl_display_get_registry(state.display); - wl_registry_add_listener(state.registry, ®istryListener, nullptr); - wl_display_roundtrip(state.display); - if (state.compositor == nullptr || state.wmBase == nullptr) { - waylandLogger.error() << "the compositor does not provide xdg-shell"; - wl_display_disconnect(state.display); - state.display = nullptr; - return {nullptr, nullptr}; - } - - state.surface = wl_compositor_create_surface(state.compositor); - - auto inputPtr = std::make_unique(); - input = inputPtr.get(); - auto windowPtr = std::make_unique( - *inputPtr, settings, settings->width.get(), settings->height.get() - ); - window = windowPtr.get(); - - static const wl_data_device_listener deviceListener = [] { - wl_data_device_listener value {}; - value.data_offer = data_device_data_offer; - value.enter = ignore_event<>; - value.leave = ignore_event<>; - value.motion = ignore_event<>; - value.drop = ignore_event<>; - value.selection = data_device_selection; - return value; - }(); - if (state.dataDeviceManager && state.seat) { - state.dataDevice = wl_data_device_manager_get_data_device( - state.dataDeviceManager, state.seat - ); - wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); - } - - { - state.xdgSurface = xdg_wm_base_get_xdg_surface( - state.wmBase, state.surface - ); - state.toplevel = xdg_surface_get_toplevel(state.xdgSurface); - window->setTitle(title); - xdg_toplevel_set_app_id(state.toplevel, "VoxelCore"); - if (state.decorationManager) { - state.decoration = - zxdg_decoration_manager_v1_get_toplevel_decoration( - state.decorationManager, state.toplevel - ); - static const zxdg_toplevel_decoration_v1_listener listener = [] { - zxdg_toplevel_decoration_v1_listener value {}; - value.configure = zxdg_decoration_configure; - return value; - }(); - zxdg_toplevel_decoration_v1_add_listener( - state.decoration, &listener, nullptr - ); - zxdg_toplevel_decoration_v1_set_mode( - state.decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE - ); - } - if (state.decorationManager == nullptr) { - window->enableOwnDecorations(); - } - static const xdg_surface_listener surfaceListener = [] { - xdg_surface_listener value {}; - value.configure = xdg_surface_configure; - return value; - }(); - static const xdg_toplevel_listener toplevelListener = [] { - xdg_toplevel_listener value {}; - value.configure = toplevel_configure; - value.close = toplevel_close; - value.configure_bounds = toplevel_configure_bounds; - value.wm_capabilities = toplevel_wm_capabilities; - return value; - }(); - xdg_surface_add_listener(state.xdgSurface, &surfaceListener, nullptr); - xdg_toplevel_add_listener(state.toplevel, &toplevelListener, nullptr); - wl_surface_commit(state.surface); - } - - while (!window->configured) { - if (wl_display_dispatch(state.display) == -1) { - waylandLogger.error() << "the Wayland connection was lost"; - return {nullptr, nullptr}; - } - } - - window->eglDisplay = eglGetPlatformDisplay( - EGL_PLATFORM_WAYLAND_KHR, state.display, nullptr - ); - if (window->eglDisplay == EGL_NO_DISPLAY || - eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { - waylandLogger.error() << "could not initialize EGL"; - return {nullptr, nullptr}; - } - eglBindAPI(EGL_OPENGL_API); - - EGLint samples = settings->samples.get(); - EGLConfig config = nullptr; - EGLint configCount = 0; - const EGLint configAttributes[] { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, - EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, - EGL_SAMPLES, samples > 0 ? samples : 0, - EGL_NONE - }; - eglChooseConfig(window->eglDisplay, configAttributes, &config, 1, &configCount); - if (samples > 0 && configCount == 0) { - waylandLogger.warning() << "multisampling is not available"; - const EGLint fallbackAttributes[] { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, - EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, - EGL_NONE - }; - eglChooseConfig( - window->eglDisplay, fallbackAttributes, &config, 1, &configCount - ); - } - if (configCount == 0) { - waylandLogger.error() << "no suitable EGL config"; - return {nullptr, nullptr}; - } - - const EGLint contextAttributes[] { - EGL_CONTEXT_MAJOR_VERSION, 3, - EGL_CONTEXT_MINOR_VERSION, 3, - EGL_NONE - }; - window->eglContext = eglCreateContext( - window->eglDisplay, config, EGL_NO_CONTEXT, contextAttributes - ); - window->eglWindow = wl_egl_window_create( - state.surface, window->getSize().x, window->getSize().y - ); - window->eglSurface = eglCreateWindowSurface( - window->eglDisplay, config, - reinterpret_cast(window->eglWindow), nullptr - ); - if (window->eglContext == EGL_NO_CONTEXT || - window->eglSurface == EGL_NO_SURFACE || - eglMakeCurrent( - window->eglDisplay, window->eglSurface, window->eglSurface, - window->eglContext - ) == EGL_FALSE) { - waylandLogger.error() << "could not create the OpenGL context"; - return {nullptr, nullptr}; - } - eglSwapInterval(window->eglDisplay, 0); - - glewExperimental = GL_TRUE; - GLenum glewError = glewInit(); - if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { - waylandLogger.error() << "failed to initialize GLEW:\n" - << glewGetErrorString(glewError); - return {nullptr, nullptr}; - } - - window->initStretchRenderer(); - glViewport(0, 0, window->getSize().x, window->getSize().y); - glClearColor(0.0f, 0.0f, 0.0f, 1); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - GLint maxTextureSize[1] {static_cast(Texture::MAX_RESOLUTION)}; - glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); - if (maxTextureSize[0] > 0) { - Texture::MAX_RESOLUTION = maxTextureSize[0]; - waylandLogger.info() << "max texture size is " << Texture::MAX_RESOLUTION; - } - waylandLogger.info() << "GL Vendor: " - << reinterpret_cast(glGetString(GL_VENDOR)); - waylandLogger.info() << "GL Renderer: " - << reinterpret_cast(glGetString(GL_RENDERER)); - waylandLogger.info() << "windowing platform: Wayland (native)"; - - return {std::move(windowPtr), std::move(inputPtr)}; -} - -void on_display_error() { - waylandLogger.error() << "the Wayland connection was lost"; - if (window) { - window->setShouldClose(true); - } -} - -void WaylandInput::pollEvents(bool waitForRefresh) { - beginFrame(); - dispatch(waitForRefresh); - if (window) { - window->paceFrame(); - } - updateRepeat(); - updateBindings(); -} - -void WaylandInput::refreshWindow() { - if (window) { - window->setShouldRefresh(); - } -} diff --git a/src/window/wayland/WaylandBar.cpp b/src/window/wayland/WaylandBar.cpp new file mode 100644 index 000000000..e362baa60 --- /dev/null +++ b/src/window/wayland/WaylandBar.cpp @@ -0,0 +1,614 @@ +#include "window/wayland/WaylandWindow.hpp" + +#include "settings.hpp" + +static constexpr int BAR_HEIGHT = 30; +static constexpr int BAR_BUTTON = 30; +static constexpr int BAR_EDGE = 5; +static constexpr int BAR_ICON_SIZE = 16; +static constexpr int BAR_FONT_W = 8; +static constexpr int BAR_FONT_H = 8; +static constexpr int BAR_GLYPHS = 159; + +static const uint8_t BAR_FONT[BAR_GLYPHS][BAR_FONT_H] { + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x50, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x14, 0x14, 0x7e, 0x28, 0xfe, 0x28, 0x68}, + {0x00, 0x10, 0x78, 0x70, 0x78, 0x7c, 0x1c, 0x78}, + {0x00, 0x62, 0xf4, 0xfc, 0x6b, 0x1f, 0x17, 0x23}, + {0x00, 0x38, 0x60, 0x30, 0x7a, 0xde, 0x6c, 0x7e}, + {0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x20, 0x60, 0x60, 0x40, 0x40, 0x60, 0x60, 0x20}, + {0x40, 0x60, 0x20, 0x20, 0x20, 0x20, 0x60, 0x40}, + {0x00, 0x20, 0xf0, 0x70, 0xf0, 0x20, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x10, 0x10, 0x7e, 0x10, 0x10}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x40}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60}, + {0x00, 0x20, 0x20, 0x60, 0x40, 0x40, 0xc0, 0x80}, + {0x00, 0x38, 0x6c, 0xcc, 0xcc, 0xcc, 0x6c, 0x38}, + {0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x7c}, + {0x00, 0x78, 0x18, 0x18, 0x18, 0x30, 0x60, 0x7c}, + {0x00, 0x78, 0x18, 0x18, 0x38, 0x1c, 0x1c, 0xf8}, + {0x00, 0x18, 0x38, 0x78, 0x58, 0xd8, 0xfc, 0x18}, + {0x00, 0x78, 0x40, 0x40, 0x78, 0x0c, 0x0c, 0x78}, + {0x00, 0x38, 0x60, 0x40, 0xf8, 0x6c, 0x6c, 0x38}, + {0x00, 0xfc, 0x18, 0x18, 0x18, 0x30, 0x30, 0x60}, + {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x78}, + {0x00, 0x78, 0xc8, 0xcc, 0x7c, 0x0c, 0x18, 0x70}, + {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x00, 0x00, 0x06, 0x3c, 0x60, 0x3c, 0x06}, + {0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00}, + {0x00, 0x00, 0x00, 0x60, 0x3c, 0x0e, 0x3c, 0x60}, + {0x00, 0x70, 0x18, 0x30, 0x60, 0x00, 0x60, 0x60}, + {0x00, 0x1e, 0x63, 0x5d, 0x55, 0x57, 0x5e, 0x62}, + {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, + {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, + {0x00, 0x7c, 0x6e, 0x66, 0x66, 0x66, 0x6e, 0x7c}, + {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, + {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x60}, + {0x00, 0x3c, 0x62, 0xc0, 0xce, 0xc6, 0x66, 0x3e}, + {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x6e, 0x7c, 0x78, 0x70, 0x78, 0x6c, 0x66}, + {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7c}, + {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, + {0x00, 0x66, 0x76, 0x76, 0x7e, 0x7e, 0x6e, 0x6e}, + {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, + {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, + {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, + {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x66}, + {0x00, 0x78, 0x68, 0x60, 0x78, 0x0c, 0x4c, 0x78}, + {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0x3c}, + {0x00, 0xc6, 0xc6, 0x6c, 0x6c, 0x78, 0x38, 0x38}, + {0x00, 0xcc, 0xcc, 0x7d, 0x7f, 0x77, 0x73, 0x33}, + {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, + {0x00, 0xcc, 0x6c, 0x78, 0x38, 0x30, 0x30, 0x30}, + {0x00, 0xfc, 0x1c, 0x18, 0x30, 0x70, 0x60, 0xfc}, + {0x70, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x70}, + {0x00, 0x80, 0xc0, 0x40, 0x40, 0x60, 0x20, 0x20}, + {0xe0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe0}, + {0x00, 0x38, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x40, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, + {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, + {0x0c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, + {0x70, 0x60, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, + {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, + {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x40, 0x40, 0x40, 0x4c, 0x78, 0x70, 0x78, 0x4c}, + {0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x00, 0x00, 0x00, 0x7f, 0x6d, 0x4d, 0x4d, 0x4d}, + {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, + {0x00, 0x00, 0x00, 0x78, 0x60, 0x40, 0x40, 0x40}, + {0x00, 0x00, 0x00, 0x78, 0xe0, 0x78, 0x18, 0xf8}, + {0x00, 0x00, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x70}, + {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x6c, 0x7c}, + {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x70, 0x30}, + {0x00, 0x00, 0x00, 0xdb, 0x5b, 0x7e, 0x7e, 0x76}, + {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, + {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, + {0x00, 0x00, 0x00, 0xf8, 0x38, 0x30, 0x60, 0xf8}, + {0x18, 0x30, 0x30, 0x70, 0x30, 0x30, 0x30, 0x18}, + {0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, + {0x70, 0x30, 0x30, 0x18, 0x30, 0x30, 0x30, 0x70}, + {0x00, 0x00, 0x00, 0x00, 0x72, 0x1c, 0x00, 0x00}, + {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, + {0x00, 0x7c, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x7c, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, + {0x00, 0x3e, 0x36, 0x36, 0x36, 0x26, 0x66, 0xff}, + {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, + {0x00, 0x64, 0x35, 0x3f, 0x3f, 0x3f, 0x64, 0xc4}, + {0x00, 0x78, 0x0c, 0x0c, 0x38, 0x0c, 0x0c, 0xf8}, + {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, + {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, + {0x00, 0x66, 0x6c, 0x78, 0x78, 0x7c, 0x6c, 0x66}, + {0x00, 0x3e, 0x36, 0x36, 0x36, 0x36, 0x66, 0xc6}, + {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, + {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, + {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, + {0x00, 0x7e, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}, + {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, + {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, + {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, + {0x00, 0xc6, 0x6c, 0x7c, 0x38, 0x38, 0x30, 0x70}, + {0x00, 0x18, 0x7e, 0x7b, 0xd9, 0x7b, 0x7e, 0x18}, + {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, + {0x00, 0x66, 0x66, 0x66, 0x7e, 0x06, 0x06, 0x06}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, + {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, + {0x00, 0x70, 0xf0, 0x30, 0x3e, 0x3b, 0x3b, 0x3e}, + {0x00, 0x61, 0x61, 0x61, 0x7d, 0x6d, 0x6d, 0x7d}, + {0x00, 0x60, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, + {0x00, 0x70, 0xf8, 0x0c, 0x7c, 0x0c, 0x1c, 0x78}, + {0x00, 0x67, 0x6c, 0x78, 0x78, 0x78, 0x6c, 0x67}, + {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x3c, 0x6c, 0x6c}, + {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, + {0x38, 0x40, 0xc0, 0xf8, 0xec, 0xcc, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x48, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x40, 0x40, 0x40, 0x40}, + {0x00, 0x00, 0x00, 0x3c, 0x2c, 0x6c, 0x6c, 0xfe}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, + {0x00, 0x00, 0x00, 0x6b, 0x3e, 0x3e, 0x7f, 0xc9}, + {0x00, 0x00, 0x00, 0x70, 0x18, 0x70, 0x18, 0xf0}, + {0x00, 0x00, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, + {0x00, 0x30, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, + {0x00, 0x00, 0x00, 0x58, 0x70, 0x70, 0x78, 0x4c}, + {0x00, 0x00, 0x00, 0x7c, 0x6c, 0x6c, 0x6c, 0xcc}, + {0x00, 0x00, 0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x46}, + {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x7c, 0x4c, 0x4c}, + {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, + {0x00, 0x00, 0x00, 0x7c, 0x4c, 0x4c, 0x4c, 0x4c}, + {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, + {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, + {0x00, 0x00, 0x00, 0xf8, 0x30, 0x30, 0x30, 0x30}, + {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, + {0x08, 0x08, 0x08, 0x7f, 0x7b, 0xc9, 0x7b, 0x7f}, + {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, + {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x7c}, + {0x00, 0x00, 0x00, 0xd8, 0xd8, 0x78, 0x18, 0x18}, + {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, + {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, + {0x00, 0x00, 0x00, 0xf0, 0x30, 0x3c, 0x34, 0x3c}, + {0x00, 0x00, 0x00, 0x43, 0x43, 0x7b, 0x4f, 0x7b}, + {0x00, 0x00, 0x00, 0x40, 0x40, 0x78, 0x48, 0x78}, + {0x00, 0x00, 0x00, 0x70, 0x18, 0x78, 0x18, 0x70}, + {0x00, 0x00, 0x00, 0x4e, 0x5b, 0x79, 0x5b, 0x4e}, + {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x78, 0xd8}, +}; + +static int bar_glyph_index(uint32_t codepoint) { + if (codepoint >= 32 && codepoint < 127) { + return static_cast(codepoint) - 32; + } + if (codepoint >= 0x410 && codepoint <= 0x44F) { + return 95 + static_cast(codepoint - 0x410); + } + if (codepoint == 0x401) { + return 95 + 6; + } + if (codepoint == 0x451) { + return 95 + 37; + } + return -1; +} + +static std::vector decode_utf8(const std::string& text) { + std::vector codepoints; + for (size_t i = 0; i < text.size();) { + const uint8_t byte = static_cast(text[i]); + uint32_t codepoint = byte; + size_t length = 1; + if ((byte & 0xE0) == 0xC0) { + codepoint = byte & 0x1F; + length = 2; + } else if ((byte & 0xF0) == 0xE0) { + codepoint = byte & 0x0F; + length = 3; + } else if ((byte & 0xF8) == 0xF0) { + codepoint = byte & 0x07; + length = 4; + } + if (i + length > text.size()) { + break; + } + for (size_t k = 1; k < length; k++) { + codepoint = + (codepoint << 6) | (static_cast(text[i + k]) & 0x3F); + } + codepoints.push_back(codepoint); + i += length; + } + return codepoints; +} + + +static void push_quad( + std::vector& target, float x, float y, float w, float h, float u0, + float v0, float u1, float v1, const glm::vec4& color +) { + const float x1 = x + w; + const float y1 = y + h; + const float vertices[] { + x, y, u0, v0, color.r, color.g, color.b, color.a, + x1, y, u1, v0, color.r, color.g, color.b, color.a, + x, y1, u0, v1, color.r, color.g, color.b, color.a, + x1, y, u1, v0, color.r, color.g, color.b, color.a, + x1, y1, u1, v1, color.r, color.g, color.b, color.a, + x, y1, u0, v1, color.r, color.g, color.b, color.a + }; + target.insert(target.end(), vertices, vertices + 48); +} + +bool WaylandWindow::isIconSupported() const { + return true; +} + +void WaylandWindow::setIcon(const ImageData* image) { + if (image == nullptr || image->getData() == nullptr) { + return; + } + iconWidth = static_cast(image->getWidth()); + iconHeight = static_cast(image->getHeight()); + if (iconWidth <= 0 || iconHeight <= 0) { + return; + } + const size_t pixels = static_cast(iconWidth) * iconHeight; + const bool alpha = image->getFormat() == ImageFormat::RGBA8888; + iconPixels.resize(pixels * 4); + for (size_t i = 0; i < pixels; i++) { + iconPixels[i * 4] = image->getData()[i * (alpha ? 4 : 3)]; + iconPixels[i * 4 + 1] = image->getData()[i * (alpha ? 4 : 3) + 1]; + iconPixels[i * 4 + 2] = image->getData()[i * (alpha ? 4 : 3) + 2]; + iconPixels[i * 4 + 3] = alpha ? image->getData()[i * 4 + 3] : 255; + } + if (barIconTexture != 0) { + glDeleteTextures(1, &barIconTexture); + barIconTexture = 0; + } +} + +void WaylandWindow::enableOwnDecorations() { + if (!decorations_enabled()) { + return; + } + barEnabled = true; + setShouldRefresh(); +} + +bool WaylandWindow::barVisible() const { + return barEnabled && !fullscreen && Window::mode != WindowMode::BORDERLESS; +} + +void WaylandWindow::initBarRenderer() { + if (barProgram != 0) { + return; + } + static const char* vertexSource = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "layout(location = 1) in vec2 aUv;\n" + "layout(location = 2) in vec4 aColor;\n" + "uniform vec2 uViewport;\n" + "out vec2 vUv;\n" + "out vec4 vColor;\n" + "void main() {\n" + " vec2 ndc = vec2(aPos.x / uViewport.x * 2.0 - 1.0," + " 1.0 - aPos.y / uViewport.y * 2.0);\n" + " gl_Position = vec4(ndc, 0.0, 1.0);\n" + " vUv = aUv;\n" + " vColor = aColor;\n" + "}\n"; + static const char* fragmentSource = + "#version 330 core\n" + "in vec2 vUv;\n" + "in vec4 vColor;\n" + "out vec4 outColor;\n" + "uniform sampler2D uTexture;\n" + "uniform int uMode;\n" + "void main() {\n" + " if (uMode == 1) {\n" + " outColor = vec4(vColor.rgb," + " vColor.a * texture(uTexture, vUv).r);\n" + " } else if (uMode == 2) {\n" + " outColor = texture(uTexture, vUv) * vColor;\n" + " } else {\n" + " outColor = vColor;\n" + " }\n" + "}\n"; + barProgram = compile_program(vertexSource, fragmentSource); + barViewportLoc = glGetUniformLocation(barProgram, "uViewport"); + barTextureLoc = glGetUniformLocation(barProgram, "uTexture"); + barModeLoc = glGetUniformLocation(barProgram, "uMode"); + glGenVertexArrays(1, &barVao); + glGenBuffers(1, &barVbo); + glBindVertexArray(barVao); + glBindBuffer(GL_ARRAY_BUFFER, barVbo); + glEnableVertexAttribArray(0); + glVertexAttribPointer( + 0, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr + ); + glEnableVertexAttribArray(1); + glVertexAttribPointer( + 1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), + reinterpret_cast(2 * sizeof(float)) + ); + glEnableVertexAttribArray(2); + glVertexAttribPointer( + 2, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), + reinterpret_cast(4 * sizeof(float)) + ); + glBindVertexArray(0); + glGenTextures(1, &barFontTexture); + glBindTexture(GL_TEXTURE_2D, barFontTexture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + std::vector pixels(BAR_GLYPHS * BAR_FONT_W * BAR_FONT_H, 0); + for (int glyph = 0; glyph < BAR_GLYPHS; glyph++) { + for (int y = 0; y < BAR_FONT_H; y++) { + for (int x = 0; x < BAR_FONT_W; x++) { + if (BAR_FONT[glyph][y] & (1 << (7 - x))) { + pixels[y * BAR_GLYPHS * BAR_FONT_W + glyph * BAR_FONT_W + x] = + 255; + } + } + } + } + glTexImage2D( + GL_TEXTURE_2D, 0, GL_R8, BAR_GLYPHS * BAR_FONT_W, BAR_FONT_H, 0, + GL_RED, GL_UNSIGNED_BYTE, pixels.data() + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void WaylandWindow::initBarIconTexture() { + if (iconPixels.empty() || barIconTexture != 0) { + return; + } + glGenTextures(1, &barIconTexture); + glBindTexture(GL_TEXTURE_2D, barIconTexture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA8, iconWidth, iconHeight, 0, GL_RGBA, + GL_UNSIGNED_BYTE, iconPixels.data() + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void WaylandWindow::barDrawText( + float x, float y, const std::vector& codepoints, int maxChars, + const glm::vec4& color +) { + const float step = 1.0f / static_cast(BAR_GLYPHS * BAR_FONT_W); + float cursor = x; + for (int i = 0; i < static_cast(codepoints.size()) && i < maxChars; i++) { + const int index = bar_glyph_index(codepoints[i]); + if (index >= 0) { + push_quad( + barText, cursor, y, BAR_FONT_W, BAR_FONT_H, + index * BAR_FONT_W * step, 0.0f, + (index * BAR_FONT_W + BAR_FONT_W) * step, 1.0f, color + ); + } + cursor += BAR_FONT_W; + } +} + +void WaylandWindow::barDrawBatch(const std::vector& data, int mode, GLuint texture) { + if (data.empty()) { + return; + } + glUniform1i(barModeLoc, mode); + glBindTexture(GL_TEXTURE_2D, texture); + glBufferData( + GL_ARRAY_BUFFER, data.size() * sizeof(float), data.data(), + GL_STREAM_DRAW + ); + glDrawArrays(GL_TRIANGLES, 0, static_cast(data.size() / 8)); +} + +void WaylandWindow::barFlush() { + glUseProgram(barProgram); + glUniform2f( + barViewportLoc, static_cast(size.x), static_cast(size.y) + ); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindVertexArray(barVao); + glBindBuffer(GL_ARRAY_BUFFER, barVbo); + glActiveTexture(GL_TEXTURE0); + glUniform1i(barTextureLoc, 0); + barDrawBatch(barRects, 0, barFontTexture); + barDrawBatch(barIcons, 2, barIconTexture); + barDrawBatch(barText, 1, barFontTexture); + glBindVertexArray(0); + glDisable(GL_BLEND); +} + +void WaylandWindow::drawBar() { + if (!barVisible()) { + return; + } + initBarRenderer(); + initBarIconTexture(); + barRects.clear(); + barText.clear(); + barIcons.clear(); + + const float width = static_cast(size.x); + const float height = static_cast(BAR_HEIGHT); + const glm::vec4 background(0.16f, 0.16f, 0.17f, 1.0f); + const glm::vec4 border(0.09f, 0.09f, 0.10f, 1.0f); + const glm::vec4 ink(0.87f, 0.87f, 0.88f, 1.0f); + const glm::vec4 hover(0.27f, 0.27f, 0.29f, 1.0f); + const glm::vec4 closeHover(0.72f, 0.16f, 0.11f, 1.0f); + + push_quad(barRects, 0, 0, width, height, 0, 0, 0, 0, background); + push_quad(barRects, 0, height - 1, width, 1, 0, 0, 0, 0, border); + + float textX = 10.0f; + if (barIconTexture != 0 && iconWidth > 0) { + push_quad( + barIcons, 7, (height - BAR_ICON_SIZE) * 0.5f, BAR_ICON_SIZE, + BAR_ICON_SIZE, 0, 1, 1, 0, glm::vec4(1.0f) + ); + textX = 7 + BAR_ICON_SIZE + 8; + } + const float buttonsX = width - BAR_BUTTON * 3; + const int maxChars = + static_cast((buttonsX - 8 - textX) / BAR_FONT_W); + if (maxChars > 0) { + barDrawText( + textX, (height - BAR_FONT_H) * 0.5f, decode_utf8(title), + maxChars, ink + ); + } + + for (int i = 0; i < 3; i++) { + const float bx = width - BAR_BUTTON * (i + 1); + if (hoveredButton == i) { + push_quad( + barRects, bx, 0, BAR_BUTTON, height - 1, 0, 0, 0, 0, + i == 0 ? closeHover : hover + ); + } + const float cx = bx + BAR_BUTTON * 0.5f; + const float cy = height * 0.5f; + if (i == 0) { + for (int s = 0; s < 7; s++) { + push_quad(barRects, cx - 4 + s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 3 - s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); + } + } else if (i == 1 && !maximized) { + push_quad(barRects, cx - 4.5f, cy - 4.5f, 9, 1.6f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 4.5f, cy + 2.9f, 9, 1.6f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 4.5f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 2.9f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); + } else if (i == 1) { + push_quad(barRects, cx - 3.5f, cy - 5.5f, 8, 1.4f, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 3.1f, cy - 5.5f, 1.4f, 5.5f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 5.5f, cy - 1.2f, 8, 1.4f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 5.5f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); + push_quad(barRects, cx + 1.1f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); + push_quad(barRects, cx - 5.5f, cy + 3.6f, 8, 1.4f, 0, 0, 0, 0, ink); + } else { + push_quad(barRects, cx - 5, cy - 0.8f, 10, 1.6f, 0, 0, 0, 0, ink); + } + } + barFlush(); +} + +int WaylandWindow::barButtonAt(double x, double y) const { + if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { + return -1; + } + for (int i = 0; i < 3; i++) { + const double bx = size.x - BAR_BUTTON * (i + 1); + if (x >= bx && x < bx + BAR_BUTTON) { + return i; + } + } + return -1; +} + +uint32_t WaylandWindow::barEdgeAt(double x, double y) const { + uint32_t edges = 0; + if (x < BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT; + } else if (x >= size.x - BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; + } + if (barVisible() && y < BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; + } else if (y >= size.y - BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; + } + return edges; +} + +CursorShape WaylandWindow::edgeCursor(uint32_t edges) { + const bool left = edges & XDG_TOPLEVEL_RESIZE_EDGE_LEFT; + const bool right = edges & XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; + const bool top = edges & XDG_TOPLEVEL_RESIZE_EDGE_TOP; + const bool bottom = edges & XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; + if ((left && top) || (right && bottom)) { + return CursorShape::NWSE_RESIZE; + } + if ((right && top) || (left && bottom)) { + return CursorShape::NESW_RESIZE; + } + if (left || right) { + return CursorShape::EW_RESIZE; + } + if (top || bottom) { + return CursorShape::NS_RESIZE; + } + return CursorShape::ARROW; +} + +bool WaylandWindow::handleBarMotion(double x, double y) { + pointerX = x; + pointerY = y; + const int button = barButtonAt(x, y); + if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { + hoveredButton = button; + input.setOverrideCursor( + button >= 0 ? CursorShape::POINTER : CursorShape::ARROW + ); + return true; + } + hoveredButton = -1; + const uint32_t edges = barEdgeAt(x, y); + input.setOverrideCursor( + edges != 0 ? std::optional(edgeCursor(edges)) + : std::nullopt + ); + return false; +} + +bool WaylandWindow::handleBarButton(uint32_t serial, bool pressed) { + const double x = pointerX; + const double y = pointerY; + const int button = barButtonAt(x, y); + if (button >= 0) { + if (pressed) { + if (button == 0) { + setShouldClose(true); + } else if (button == 1) { + setMaximized(!maximized); + } else { + xdg_toplevel_set_minimized(state.toplevel); + } + } + return true; + } + if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { + if (pressed) { + const double current = now(); + if (current - lastBarPress < 0.4) { + lastBarPress = 0.0; + setMaximized(!maximized); + } else { + lastBarPress = current; + xdg_toplevel_move(state.toplevel, state.seat, serial); + } + } + return true; + } + const uint32_t edges = barEdgeAt(x, y); + if (pressed && edges != 0) { + xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); + return true; + } + return false; +} + +void WaylandWindow::onPointerLeave() { + hoveredButton = -1; + input.setOverrideCursor(std::nullopt); +} diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp index a1b91293d..5da49c6e0 100644 --- a/src/window/wayland/WaylandCommon.cpp +++ b/src/window/wayland/WaylandCommon.cpp @@ -6,6 +6,22 @@ debug::Logger waylandLogger("window"); +GLuint compile_program(const char* vertexSource, const char* fragmentSource) { + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertexShader, 1, &vertexSource, nullptr); + glCompileShader(vertexShader); + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); + glCompileShader(fragmentShader); + GLuint program = glCreateProgram(); + glAttachShader(program, vertexShader); + glAttachShader(program, fragmentShader); + glLinkProgram(program); + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + return program; +} + WaylandState state; class WaylandInput; diff --git a/src/window/wayland/WaylandCommon.hpp b/src/window/wayland/WaylandCommon.hpp index 36b6a8dab..6bbb5df1e 100644 --- a/src/window/wayland/WaylandCommon.hpp +++ b/src/window/wayland/WaylandCommon.hpp @@ -15,9 +15,30 @@ #include "xdg-decoration-unstable-v1-client-protocol.h" #include "xdg-shell-client-protocol.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include #include +const wl_registry_listener& registry_listener(); +const wl_data_device_listener& data_device_listener(); +const xdg_surface_listener& surface_listener(); +const xdg_toplevel_listener& toplevel_listener(); + +GLuint compile_program(const char* vertexSource, const char* fragmentSource); + extern debug::Logger waylandLogger; struct WaylandState { diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp new file mode 100644 index 000000000..f41996fc9 --- /dev/null +++ b/src/window/wayland/WaylandInit.cpp @@ -0,0 +1,228 @@ +#include "window/wayland/WaylandWindow.hpp" +#include "window/wayland/WaylandInput.hpp" +#include "window/wayland/WaylandListeners.hpp" + +#include "settings.hpp" +#include "graphics/core/Texture.hpp" +#include + +std::tuple, std::unique_ptr> +wayland_window_initialize(DisplaySettings* settings, std::string title) { + state.display = wl_display_connect(nullptr); + if (state.display == nullptr) { + waylandLogger.error() << "could not connect to the Wayland display"; + return {nullptr, nullptr}; + } + state.registry = wl_display_get_registry(state.display); + static const wl_registry_listener registryListener = [] { + wl_registry_listener value {}; + value.global = registry_global; + value.global_remove = registry_global_remove; + return value; + }(); + + wl_registry_add_listener(state.registry, ®istryListener, nullptr); + wl_display_roundtrip(state.display); + if (state.compositor == nullptr || state.wmBase == nullptr) { + waylandLogger.error() << "the compositor does not provide xdg-shell"; + wl_display_disconnect(state.display); + state.display = nullptr; + return {nullptr, nullptr}; + } + + state.surface = wl_compositor_create_surface(state.compositor); + + auto inputPtr = std::make_unique(); + input = inputPtr.get(); + auto windowPtr = std::make_unique( + *inputPtr, settings, settings->width.get(), settings->height.get() + ); + window = windowPtr.get(); + + if (state.dataDeviceManager && state.seat) { + state.dataDevice = wl_data_device_manager_get_data_device( + state.dataDeviceManager, state.seat + ); + static const wl_data_device_listener deviceListener = [] { + wl_data_device_listener value {}; + value.data_offer = data_device_data_offer; + value.enter = ignore_event<>; + value.leave = ignore_event<>; + value.motion = ignore_event<>; + value.drop = ignore_event<>; + value.selection = data_device_selection; + return value; + }(); + + wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); + } + + { + state.xdgSurface = xdg_wm_base_get_xdg_surface( + state.wmBase, state.surface + ); + state.toplevel = xdg_surface_get_toplevel(state.xdgSurface); + window->setTitle(title); + xdg_toplevel_set_app_id(state.toplevel, "VoxelCore"); + if (state.decorationManager) { + state.decoration = + zxdg_decoration_manager_v1_get_toplevel_decoration( + state.decorationManager, state.toplevel + ); + static const zxdg_toplevel_decoration_v1_listener listener = [] { + zxdg_toplevel_decoration_v1_listener value {}; + value.configure = zxdg_decoration_configure; + return value; + }(); + zxdg_toplevel_decoration_v1_add_listener( + state.decoration, &listener, nullptr + ); + zxdg_toplevel_decoration_v1_set_mode( + state.decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE + ); + } + if (state.decorationManager == nullptr) { + window->enableOwnDecorations(); + } + static const xdg_surface_listener surfaceListener = [] { + xdg_surface_listener value {}; + value.configure = xdg_surface_configure; + return value; + }(); + static const xdg_toplevel_listener toplevelListener = [] { + xdg_toplevel_listener value {}; + value.configure = toplevel_configure; + value.close = toplevel_close; + value.configure_bounds = toplevel_configure_bounds; + value.wm_capabilities = toplevel_wm_capabilities; + return value; + }(); + xdg_surface_add_listener(state.xdgSurface, &surfaceListener, nullptr); + xdg_toplevel_add_listener(state.toplevel, &toplevelListener, nullptr); + wl_surface_commit(state.surface); + } + + while (!window->configured) { + if (wl_display_dispatch(state.display) == -1) { + waylandLogger.error() << "the Wayland connection was lost"; + return {nullptr, nullptr}; + } + } + + window->eglDisplay = eglGetPlatformDisplay( + EGL_PLATFORM_WAYLAND_KHR, state.display, nullptr + ); + if (window->eglDisplay == EGL_NO_DISPLAY || + eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { + waylandLogger.error() << "could not initialize EGL"; + return {nullptr, nullptr}; + } + eglBindAPI(EGL_OPENGL_API); + + EGLint samples = settings->samples.get(); + EGLConfig config = nullptr; + EGLint configCount = 0; + const EGLint configAttributes[] { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, + EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_SAMPLES, samples > 0 ? samples : 0, + EGL_NONE + }; + eglChooseConfig(window->eglDisplay, configAttributes, &config, 1, &configCount); + if (samples > 0 && configCount == 0) { + waylandLogger.warning() << "multisampling is not available"; + const EGLint fallbackAttributes[] { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, + EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_NONE + }; + eglChooseConfig( + window->eglDisplay, fallbackAttributes, &config, 1, &configCount + ); + } + if (configCount == 0) { + waylandLogger.error() << "no suitable EGL config"; + return {nullptr, nullptr}; + } + + const EGLint contextAttributes[] { + EGL_CONTEXT_MAJOR_VERSION, 3, + EGL_CONTEXT_MINOR_VERSION, 3, + EGL_NONE + }; + window->eglContext = eglCreateContext( + window->eglDisplay, config, EGL_NO_CONTEXT, contextAttributes + ); + window->eglWindow = wl_egl_window_create( + state.surface, window->getSize().x, window->getSize().y + ); + window->eglSurface = eglCreateWindowSurface( + window->eglDisplay, config, + reinterpret_cast(window->eglWindow), nullptr + ); + if (window->eglContext == EGL_NO_CONTEXT || + window->eglSurface == EGL_NO_SURFACE || + eglMakeCurrent( + window->eglDisplay, window->eglSurface, window->eglSurface, + window->eglContext + ) == EGL_FALSE) { + waylandLogger.error() << "could not create the OpenGL context"; + return {nullptr, nullptr}; + } + eglSwapInterval(window->eglDisplay, 0); + + glewExperimental = GL_TRUE; + GLenum glewError = glewInit(); + if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { + waylandLogger.error() << "failed to initialize GLEW:\n" + << glewGetErrorString(glewError); + return {nullptr, nullptr}; + } + + window->initStretchRenderer(); + glViewport(0, 0, window->getSize().x, window->getSize().y); + glClearColor(0.0f, 0.0f, 0.0f, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + GLint maxTextureSize[1] {static_cast(Texture::MAX_RESOLUTION)}; + glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); + if (maxTextureSize[0] > 0) { + Texture::MAX_RESOLUTION = maxTextureSize[0]; + waylandLogger.info() << "max texture size is " << Texture::MAX_RESOLUTION; + } + waylandLogger.info() << "GL Vendor: " + << reinterpret_cast(glGetString(GL_VENDOR)); + waylandLogger.info() << "GL Renderer: " + << reinterpret_cast(glGetString(GL_RENDERER)); + waylandLogger.info() << "windowing platform: Wayland (native)"; + + return {std::move(windowPtr), std::move(inputPtr)}; +} + +void on_display_error() { + waylandLogger.error() << "the Wayland connection was lost"; + if (window) { + window->setShouldClose(true); + } +} + +void WaylandInput::pollEvents(bool waitForRefresh) { + beginFrame(); + dispatch(waitForRefresh); + if (window) { + window->paceFrame(); + } + updateRepeat(); + updateBindings(); +} + +void WaylandInput::refreshWindow() { + if (window) { + window->setShouldRefresh(); + } +} diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp new file mode 100644 index 000000000..395d30b7f --- /dev/null +++ b/src/window/wayland/WaylandListeners.cpp @@ -0,0 +1,359 @@ +#include "window/wayland/WaylandWindow.hpp" +#include "window/wayland/WaylandInput.hpp" + +#include + +static void pointer_enter( + void*, wl_pointer*, uint32_t serial, wl_surface* surface, wl_fixed_t sx, + wl_fixed_t sy +) { + state.pointerSerial = serial; + state.entered = surface == state.surface; + const double x = wl_fixed_to_double(sx); + const double y = wl_fixed_to_double(sy); + if (state.entered && window && window->handleBarMotion(x, y)) { + return; + } + if (input) { + input->setCursorPosition(x, y); + if (state.entered) { + input->applyCursor(); + } + input->refreshWindow(); + } +} + +static void pointer_leave(void*, wl_pointer*, uint32_t, wl_surface*) { + state.entered = false; + if (window) { + window->onPointerLeave(); + } +} + +static void pointer_motion( + void*, wl_pointer*, uint32_t, wl_fixed_t sx, wl_fixed_t sy +) { + const double x = wl_fixed_to_double(sx); + const double y = wl_fixed_to_double(sy); + if (window && window->handleBarMotion(x, y)) { + return; + } + if (input) { + input->setCursorPosition(x, y); + input->refreshWindow(); + } +} + +static void pointer_button( + void*, wl_pointer*, uint32_t serial, uint32_t, uint32_t button, + uint32_t buttonState +) { + state.inputSerial = serial; + int index = -1; + switch (button) { + case 0x110: index = 0; break; + case 0x111: index = 1; break; + case 0x112: index = 2; break; + case 0x113: index = 3; break; + case 0x114: index = 4; break; + case 0x115: index = 5; break; + case 0x116: index = 6; break; + case 0x117: index = 7; break; + } + const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; + if (index == 0 && window && window->handleBarButton(serial, pressed)) { + return; + } + if (index >= 0 && input) { + input->onMouseCallback(index, pressed); + input->refreshWindow(); + } +} + +static void pointer_axis( + void*, wl_pointer*, uint32_t, uint32_t axis, wl_fixed_t value +) { + if (input && axis == WL_POINTER_AXIS_VERTICAL_SCROLL) { + input->scroll += wl_fixed_to_double(value) > 0 ? -1 : 1; + input->refreshWindow(); + } +} + +static void keyboard_keymap( + void*, wl_keyboard*, uint32_t format, int32_t fd, uint32_t size +) { + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { + close(fd); + return; + } + char* data = static_cast( + mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0) + ); + close(fd); + if (data == MAP_FAILED) { + return; + } + if (state.xkbContext == nullptr) { + state.xkbContext = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + } + xkb_keymap* keymap = xkb_keymap_new_from_string( + state.xkbContext, data, XKB_KEYMAP_FORMAT_TEXT_V1, + XKB_KEYMAP_COMPILE_NO_FLAGS + ); + munmap(data, size); + if (keymap == nullptr) { + waylandLogger.error() << "could not parse the keyboard keymap"; + return; + } + if (state.xkbState) { + xkb_state_unref(state.xkbState); + } + if (state.xkbKeymap) { + xkb_keymap_unref(state.xkbKeymap); + } + state.xkbKeymap = keymap; + state.xkbState = xkb_state_new(keymap); +} + +static void keyboard_enter( + void*, wl_keyboard*, uint32_t serial, wl_surface*, wl_array* +) { + state.inputSerial = serial; +} + +static void keyboard_leave(void*, wl_keyboard*, uint32_t, wl_surface*) { +} + +static void keyboard_key( + void*, wl_keyboard*, uint32_t serial, uint32_t, uint32_t key, + uint32_t keyState +) { + state.inputSerial = serial; + if (input) { + input->onKey(key, keyState == WL_KEYBOARD_KEY_STATE_PRESSED); + input->refreshWindow(); + } +} + +static void keyboard_modifiers( + void*, wl_keyboard*, uint32_t serial, uint32_t depressed, uint32_t latched, + uint32_t locked, uint32_t group +) { + state.inputSerial = serial; + if (state.xkbState) { + xkb_state_update_mask( + state.xkbState, depressed, latched, locked, 0, 0, group + ); + } +} + +static void keyboard_repeat_info(void*, wl_keyboard*, int32_t rate, int32_t delay) { + state.repeatRate = rate > 0 ? rate : 25; + state.repeatDelay = delay > 0 ? delay : 400; +} + +static void seat_capabilities(void*, wl_seat* seat, uint32_t capabilities) { + static const wl_pointer_listener pointerListener = [] { + wl_pointer_listener listener {}; + listener.enter = pointer_enter; + listener.leave = pointer_leave; + listener.motion = pointer_motion; + listener.button = pointer_button; + listener.axis = pointer_axis; + listener.frame = ignore_event<>; + listener.axis_source = ignore_event<>; + listener.axis_stop = ignore_event<>; + listener.axis_discrete = ignore_event<>; + listener.axis_value120 = ignore_event<>; + listener.axis_relative_direction = ignore_event<>; + return listener; + }(); + + static const wl_keyboard_listener keyboardListener = [] { + wl_keyboard_listener listener {}; + listener.keymap = keyboard_keymap; + listener.enter = keyboard_enter; + listener.leave = keyboard_leave; + listener.key = keyboard_key; + listener.modifiers = keyboard_modifiers; + listener.repeat_info = keyboard_repeat_info; + return listener; + }(); + + bool hasPointer = capabilities & WL_SEAT_CAPABILITY_POINTER; + bool hasKeyboard = capabilities & WL_SEAT_CAPABILITY_KEYBOARD; + if (hasPointer && state.pointer == nullptr) { + state.pointer = wl_seat_get_pointer(seat); + wl_pointer_add_listener(state.pointer, &pointerListener, nullptr); + if (state.cursorShapeManager) { + state.cursorShapeDevice = wp_cursor_shape_manager_v1_get_pointer( + state.cursorShapeManager, state.pointer + ); + } + } else if (!hasPointer && state.pointer) { + if (state.cursorShapeDevice) { + wp_cursor_shape_device_v1_destroy(state.cursorShapeDevice); + state.cursorShapeDevice = nullptr; + } + wl_pointer_destroy(state.pointer); + state.pointer = nullptr; + } + if (hasKeyboard && state.keyboard == nullptr) { + state.keyboard = wl_seat_get_keyboard(seat); + wl_keyboard_add_listener(state.keyboard, &keyboardListener, nullptr); + } else if (!hasKeyboard && state.keyboard) { + wl_keyboard_destroy(state.keyboard); + state.keyboard = nullptr; + } +} + +static void seat_name(void*, wl_seat*, const char*) { +} + +static void wm_base_ping(void*, xdg_wm_base* base, uint32_t serial) { + xdg_wm_base_pong(base, serial); +} + +void toplevel_configure( + void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states +) { + if (window) { + window->onConfigure(width, height, states); + } +} + +void toplevel_close(void*, xdg_toplevel*) { + if (window) { + window->setShouldClose(true); + } +} + +void toplevel_configure_bounds(void*, xdg_toplevel*, int32_t, int32_t) { +} + +void toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*) { +} + +void xdg_surface_configure(void*, xdg_surface* surface, uint32_t serial) { + xdg_surface_ack_configure(surface, serial); + if (window) { + window->applyConfigure(); + } +} + +static void data_offer_offer(void*, wl_data_offer*, const char* mime) { + if (input) { + input->pendingMimes.push_back(mime); + } +} + +void data_device_data_offer(void*, wl_data_device*, wl_data_offer* offer) { + static const wl_data_offer_listener listener = [] { + wl_data_offer_listener value {}; + value.offer = data_offer_offer; + value.source_actions = ignore_event<>; + value.action = ignore_event<>; + return value; + }(); + wl_data_offer_add_listener(offer, &listener, nullptr); +} + +void data_device_selection(void*, wl_data_device*, wl_data_offer* offer) { + if (input == nullptr) { + return; + } + if (input->selection) { + wl_data_offer_destroy(input->selection); + } + input->selection = offer; + input->selectionMimes = std::move(input->pendingMimes); + input->pendingMimes.clear(); +} + +void registry_global( + void*, wl_registry* registry, uint32_t name, const char* interface, + uint32_t version +) { + if (strcmp(interface, wl_compositor_interface.name) == 0) { + state.compositor = static_cast(wl_registry_bind( + registry, name, &wl_compositor_interface, std::min(version, 4u) + )); + } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { + state.wmBase = static_cast(wl_registry_bind( + registry, name, &xdg_wm_base_interface, std::min(version, 6u) + )); + static const xdg_wm_base_listener listener = [] { + xdg_wm_base_listener value {}; + value.ping = wm_base_ping; + return value; + }(); + xdg_wm_base_add_listener(state.wmBase, &listener, nullptr); + } else if (strcmp(interface, wl_seat_interface.name) == 0) { + state.seat = static_cast(wl_registry_bind( + registry, name, &wl_seat_interface, std::min(version, 7u) + )); + static const wl_seat_listener listener = [] { + wl_seat_listener value {}; + value.capabilities = seat_capabilities; + value.name = seat_name; + return value; + }(); + wl_seat_add_listener(state.seat, &listener, nullptr); + } else if (strcmp(interface, wl_data_device_manager_interface.name) == 0) { + state.dataDeviceManager = static_cast( + wl_registry_bind( + registry, name, &wl_data_device_manager_interface, + std::min(version, 3u) + ) + ); + } else if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) { + state.cursorShapeManager = static_cast( + wl_registry_bind( + registry, name, &wp_cursor_shape_manager_v1_interface, + std::min(version, 2u) + ) + ); + } else if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) { + state.pointerConstraints = static_cast( + wl_registry_bind( + registry, name, &zwp_pointer_constraints_v1_interface, 1 + ) + ); + } else if ( + strcmp(interface, zwp_relative_pointer_manager_v1_interface.name) == 0 + ) { + state.relativePointerManager = + static_cast(wl_registry_bind( + registry, name, &zwp_relative_pointer_manager_v1_interface, 1 + )); + } else if ( + strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0 + ) { + state.idleInhibitManager = static_cast( + wl_registry_bind( + registry, name, &zwp_idle_inhibit_manager_v1_interface, 1 + ) + ); + } else if ( + strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0 + ) { + state.decorationManager = static_cast( + wl_registry_bind( + registry, name, &zxdg_decoration_manager_v1_interface, 1 + ) + ); + } +} + +void registry_global_remove(void*, wl_registry*, uint32_t) { +} + +void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +) { + serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; + if (!serverDecorations && window != nullptr) { + window->enableOwnDecorations(); + } +} + diff --git a/src/window/wayland/WaylandListeners.hpp b/src/window/wayland/WaylandListeners.hpp new file mode 100644 index 000000000..a8ea8bf28 --- /dev/null +++ b/src/window/wayland/WaylandListeners.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include "window/wayland/WaylandCommon.hpp" + +void toplevel_configure(void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states); +void toplevel_close(void*, xdg_toplevel*); +void toplevel_configure_bounds(void*, xdg_toplevel*, int32_t, int32_t); +void toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*); +void xdg_surface_configure(void*, xdg_surface* surface, uint32_t serial); +void data_device_data_offer(void*, wl_data_device*, wl_data_offer* offer); +void data_device_selection(void*, wl_data_device*, wl_data_offer* offer); +void registry_global(void*, wl_registry* registry, uint32_t name, const char* interface, uint32_t version); +void registry_global_remove(void*, wl_registry*, uint32_t); +void zxdg_decoration_configure(void*, zxdg_toplevel_decoration_v1*, uint32_t mode); diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp new file mode 100644 index 000000000..51c8a86b5 --- /dev/null +++ b/src/window/wayland/WaylandWindow.cpp @@ -0,0 +1,624 @@ +#include "window/wayland/WaylandWindow.hpp" + +#include "settings.hpp" +#include "graphics/core/Texture.hpp" +#include "util/platform.hpp" + +WaylandWindow::WaylandWindow( + WaylandInput& input, DisplaySettings* settings, int width, int height +) + : Window({width, height}), input(input), settings(settings) { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); +} + +WaylandWindow::~WaylandWindow() { + if (state.idleInhibitor) { + zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); + } + if (state.lockedPointer) { + zwp_locked_pointer_v1_destroy(state.lockedPointer); + } + if (state.relativePointer) { + zwp_relative_pointer_v1_destroy(state.relativePointer); + } + if (state.cursorShapeDevice) { + wp_cursor_shape_device_v1_destroy(state.cursorShapeDevice); + } + if (frameCallback) { + wl_callback_destroy(frameCallback); + frameCallback = nullptr; + } + if (cacheTexture) { + glDeleteTextures(1, &cacheTexture); + } + if (cacheFbo) { + glDeleteFramebuffers(1, &cacheFbo); + } + if (stretchProgram) { + glDeleteProgram(stretchProgram); + } + if (stretchVbo) { + glDeleteBuffers(1, &stretchVbo); + } + if (stretchVao) { + glDeleteVertexArrays(1, &stretchVao); + } + if (barFontTexture) { + glDeleteTextures(1, &barFontTexture); + } + if (barIconTexture) { + glDeleteTextures(1, &barIconTexture); + } + if (barProgram) { + glDeleteProgram(barProgram); + } + if (barVbo) { + glDeleteBuffers(1, &barVbo); + } + if (barVao) { + glDeleteVertexArrays(1, &barVao); + } + if (state.dataDevice) { + wl_data_device_destroy(state.dataDevice); + } + if (state.decoration) { + zxdg_toplevel_decoration_v1_destroy(state.decoration); + } + if (state.toplevel) { + xdg_toplevel_destroy(state.toplevel); + } + if (state.xdgSurface) { + xdg_surface_destroy(state.xdgSurface); + } + if (eglSurface != EGL_NO_SURFACE) { + eglDestroySurface(eglDisplay, eglSurface); + } + if (eglWindow) { + wl_egl_window_destroy(eglWindow); + } + if (state.surface) { + wl_surface_destroy(state.surface); + } + if (eglContext != EGL_NO_CONTEXT) { + eglDestroyContext(eglDisplay, eglContext); + } + if (eglDisplay != EGL_NO_DISPLAY) { + eglTerminate(eglDisplay); + } +} + +double WaylandWindow::time() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); +} + +void WaylandWindow::swapBuffers() { + updateResizing(); + if (resizing && !presentPending && !frameDone) { + resetScissor(); + return; + } + if (resizing) { + if (renderPending) { + cacheContent(); + renderPending = false; + } else { + drawStretched(); + } + } else { + cacheContent(); + } + drawBar(); + requestFrame(); + eglSwapBuffers(eglDisplay, eglSurface); + resetScissor(); + frameDone = false; + presentPending = false; + const double current = now(); + if (lastPresent > 0.0) { + const double interval = current - lastPresent; + if (interval > 0.001 && interval < 1.0 && !resizing && + frameOnCallback) { + frameInterval = std::clamp( + frameInterval > 0.0 ? frameInterval * 0.8 + interval * 0.2 + : interval, + 1.0 / 240.0, + 1.0 / 30.0 + ); + } + if (resizeLogging) { + summarySum += interval; + summaryMax = std::max(summaryMax, interval); + } + } + lastPresent = current; + nextFrameTime = current + frameInterval; + if (resizeLogging) { + summaryFrames++; + } + if (resizing) { + const double elapsed = now() - configureTime; + resizeTimeSum += elapsed; + resizeTimeMax = std::max(resizeTimeMax, elapsed); + resizePresents++; + } + lastSwapEnd = now(); + if (framerate > 0 && !resizing) { + auto elapsed = time() - prevSwap; + auto frameTime = 1.0 / framerate; + if (elapsed < frameTime) { + platform::sleep( + static_cast((frameTime - elapsed) * 1000) + ); + } + } + prevSwap = time(); +} + +void WaylandWindow::setShouldRefresh() { + shouldRefresh = true; +} + +bool WaylandWindow::checkShouldRefresh() { + if (shouldRefresh) { + shouldRefresh = false; + return true; + } + return false; +} + +bool WaylandWindow::isMaximized() const { + return maximized; +} + +bool WaylandWindow::isFocused() const { + return activated; +} + +bool WaylandWindow::isIconified() const { + return suspended; +} + +bool WaylandWindow::isFrameRequired() const { + return !resizing || renderPending; +} + +bool WaylandWindow::isShouldClose() const { + return shouldClose; +} + +void WaylandWindow::setShouldClose(bool flag) { + shouldClose = flag; +} + +void WaylandWindow::setCursor(CursorShape shape) { + input.setCursorShape(shape); +} + +void WaylandWindow::setMode(WindowMode mode) { + Window::mode = mode; + if (input.isCursorLocked()) { + input.toggleCursor(); + } + switch (mode) { + case WindowMode::FULLSCREEN: + setFullscreen(true); + setIdleInhibit(true); + break; + case WindowMode::BORDERLESS: + setFullscreen(false); + setMaximized(true); + setIdleInhibit(true); + break; + case WindowMode::WINDOWED: + setFullscreen(false); + setMaximized(false); + setIdleInhibit(false); + resize(settings->width.get(), settings->height.get()); + break; + } + wl_surface_commit(state.surface); +} + +WindowMode WaylandWindow::getMode() const { + return mode; +} + +void WaylandWindow::focus() { + if (!focusWarning) { + focusWarning = true; + waylandLogger.warning() << "raising windows is not allowed on Wayland"; + } +} + +void WaylandWindow::setTitle(const std::string& title) { + this->title = title; + xdg_toplevel_set_title(state.toplevel, title.c_str()); +} + +void WaylandWindow::setFullscreen(bool enabled) { + fullscreen = enabled; + if (enabled) { + xdg_toplevel_set_fullscreen(state.toplevel, nullptr); + } else { + xdg_toplevel_unset_fullscreen(state.toplevel); + } +} + +void WaylandWindow::setMaximized(bool enabled) { + if (enabled) { + xdg_toplevel_set_maximized(state.toplevel); + } else { + xdg_toplevel_unset_maximized(state.toplevel); + } +} + +void WaylandWindow::resize(int width, int height) { + if (width <= 0 || height <= 0) { + return; + } + if (size.x != width || size.y != height) { + markResizing(); + } + configureTime = now(); + presentPending = true; + if (eglWindow) { + wl_egl_window_resize(eglWindow, width, height, 0, 0); + } + glViewport(0, 0, width, height); + size = {width, height}; + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); +} + +void WaylandWindow::onConfigure(int32_t width, int32_t height, wl_array* states) { + pendingWidth = width; + pendingHeight = height; + stateMaximized = false; + stateSuspended = false; + stateActivated = false; + const auto* values = static_cast(states->data); + for (size_t i = 0; i < states->size / sizeof(uint32_t); i++) { + switch (values[i]) { + case XDG_TOPLEVEL_STATE_MAXIMIZED: + stateMaximized = true; + break; + case XDG_TOPLEVEL_STATE_SUSPENDED: + stateSuspended = true; + break; + case XDG_TOPLEVEL_STATE_ACTIVATED: + stateActivated = true; + break; + } + } +} + +void WaylandWindow::applyConfigure() { + if (pendingWidth > 0 && pendingHeight > 0) { + resize(pendingWidth, pendingHeight); + } + maximized = stateMaximized; + suspended = stateSuspended; + activated = stateActivated; + configured = true; + setShouldRefresh(); +} + +void WaylandWindow::pushScissor(glm::vec4 area) { + if (scissorStack.empty()) { + glEnable(GL_SCISSOR_TEST); + } + scissorStack.push(scissorArea); + + area.z += glm::ceil(area.x); + area.w += glm::ceil(area.y); + + area.x = glm::max(area.x, scissorArea.x); + area.y = glm::max(area.y, scissorArea.y); + + area.z = glm::min(area.z, scissorArea.z); + area.w = glm::min(area.w, scissorArea.w); + + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(glm::ceil(area.z - area.x))), + std::max(0, static_cast(glm::ceil(area.w - area.y))) + ); + } + scissorArea = area; +} + +void WaylandWindow::popScissor() { + if (scissorStack.empty()) { + waylandLogger.warning() << "extra Window::popScissor call"; + return; + } + glm::vec4 area = scissorStack.top(); + scissorStack.pop(); + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(area.z - area.x)), + std::max(0, static_cast(area.w - area.y)) + ); + } + if (scissorStack.empty()) { + glDisable(GL_SCISSOR_TEST); + } + scissorArea = area; +} + +void WaylandWindow::resetScissor() { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); + scissorStack = std::stack(); + glDisable(GL_SCISSOR_TEST); +} + +std::unique_ptr WaylandWindow::takeScreenshot() { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + auto data = std::make_unique(size.x * size.y * 3); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); + return std::make_unique( + ImageFormat::RGB888, size.x, size.y, data.release() + ); +} + +void WaylandWindow::setFramerate(int framerate) { + this->framerate = framerate; +} + +void WaylandWindow::initStretchRenderer() { + static const char* vertexSource = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "out vec2 vUV;\n" + "void main() {\n" + " vUV = aPos * 0.5 + 0.5;\n" + " gl_Position = vec4(aPos, 0.0, 1.0);\n" + "}\n"; + static const char* fragmentSource = + "#version 330 core\n" + "in vec2 vUV;\n" + "out vec4 color;\n" + "uniform sampler2D uTexture;\n" + "void main() {\n" + " color = texture(uTexture, vUV);\n" + "}\n"; + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vertexShader, 1, &vertexSource, nullptr); + glCompileShader(vertexShader); + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); + glCompileShader(fragmentShader); + stretchProgram = glCreateProgram(); + glAttachShader(stretchProgram, vertexShader); + glAttachShader(stretchProgram, fragmentShader); + glLinkProgram(stretchProgram); + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + + const float vertices[] {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f}; + glGenVertexArrays(1, &stretchVao); + glGenBuffers(1, &stretchVbo); + glBindVertexArray(stretchVao); + glBindBuffer(GL_ARRAY_BUFFER, stretchVbo); + glBufferData( + GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW + ); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); + glBindVertexArray(0); + glGenFramebuffers(1, &cacheFbo); + glGenTextures(1, &cacheTexture); +} + +void WaylandWindow::resizeCache(int width, int height) { + if (cacheWidth == width && cacheHeight == height) { + return; + } + cacheWidth = width; + cacheHeight = height; + glBindTexture(GL_TEXTURE_2D, cacheTexture); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, nullptr + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glBindFramebuffer(GL_FRAMEBUFFER, cacheFbo); + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cacheTexture, + 0 + ); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void WaylandWindow::cacheContent() { + if (stretchProgram == 0) { + return; + } + resizeCache(size.x, size.y); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, cacheFbo); + glBlitFramebuffer( + 0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT, + GL_NEAREST + ); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + lastCacheTime = now(); +} + +void WaylandWindow::drawStretched() { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, size.x, size.y); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + if (stretchProgram == 0 || cacheWidth == 0) { + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + return; + } + glUseProgram(stretchProgram); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, cacheTexture); + glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glBindVertexArray(stretchVao); + glDrawArrays(GL_TRIANGLES, 0, 3); + glBindVertexArray(0); + glUseProgram(0); +} + +void WaylandWindow::onFrameDone() { + frameCallback = nullptr; + frameDone = true; +} + +void WaylandWindow::requestFrame() { + if (state.surface == nullptr || frameCallback != nullptr) { + return; + } + frameCallback = wl_surface_frame(state.surface); + wl_callback_add_listener(frameCallback, &frameListener(), this); +} + +void WaylandWindow::paceFrame() { + frameOnCallback = frameDone; + if (lastSwapEnd > 0.0) { + const double cost = now() - lastSwapEnd; + if (cost > 0.0 && cost < 2.0) { + frameCost = frameCost > 0.0 ? frameCost * 0.8 + cost * 0.2 : cost; + cacheTimeout = std::clamp( + frameCost * 16.0, MIN_CACHE_TIMEOUT, MAX_CACHE_TIMEOUT + ); + } + } + updateResizing(); + logSummary(); + if (resizing) { + if (!renderPending && now() - lastResize > RESIZE_PAUSE && + now() - lastCacheTime > cacheTimeout) { + renderPending = true; + } + dispatch_events(frameDone || presentPending ? 0 : 8); + frameOnCallback = frameDone; + return; + } + if (framerate != -1 || frameCallback == nullptr || frameDone) { + return; + } + const double deadline = now() + FRAME_TIMEOUT; + while (!frameDone && !resizing && now() < deadline) { + dispatch_events(5); + } + while (!frameDone && !resizing && now() < nextFrameTime) { + dispatch_events(5); + } + nextFrameTime = now() + frameInterval; + frameOnCallback = frameDone; +} + +void WaylandWindow::logSummary() { + const double current = now(); + if (resizeLogging) { + if (lastLoop > 0.0) { + loopGapMax = std::max(loopGapMax, current - lastLoop); + } + lastLoop = current; + loopCount++; + } + if (!resizeLogging || lastSummary <= 0.0) { + if (resizeLogging) { + lastSummary = current; + } + return; + } + if (current - lastSummary < 1.0) { + return; + } + waylandLogger.info() << "loop " << loopCount << "/s (max gap " + << loopGapMax * 1000.0 << " ms), presents " + << summaryFrames << "/s (max gap " + << summaryMax * 1000.0 << " ms), resizing " + << (resizing ? "yes" : "no"); + lastSummary = current; + loopCount = 0; + loopGapMax = 0.0; + summaryFrames = 0; + summarySum = 0.0; + summaryMax = 0.0; +} + +void WaylandWindow::markResizing() { + lastResize = now(); + if (!resizing) { + resizing = true; + resizePresents = 0; + resizeTimeSum = 0.0; + resizeTimeMax = 0.0; + if (resizeLogging) { + waylandLogger.info() << "resize started"; + } + setShouldRefresh(); + } +} + +void WaylandWindow::updateResizing() { + if (resizing && now() - lastResize > RESIZE_TIMEOUT) { + resizing = false; + renderPending = true; + if (resizeLogging) { + double average = resizePresents > 0 + ? resizeTimeSum / resizePresents + : 0.0; + waylandLogger.info() + << "resize finished, presented " << resizePresents + << ", avg " << average * 1000.0 << " ms, max " + << resizeTimeMax * 1000.0 << " ms"; + } + } +} + +void WaylandWindow::setIdleInhibit(bool enabled) { + if (enabled == (state.idleInhibitor != nullptr)) { + return; + } + if (enabled && state.idleInhibitManager) { + state.idleInhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor( + state.idleInhibitManager, state.surface + ); + } else if (state.idleInhibitor) { + zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); + state.idleInhibitor = nullptr; + } +} + +const wl_callback_listener& WaylandWindow::frameListener() { + static wl_callback_listener listener = [] { + wl_callback_listener value {}; + value.done = [] (void* data, wl_callback* callback, uint32_t) { + wl_callback_destroy(callback); + static_cast(data)->onFrameDone(); + }; + return value; + }(); + return listener; +} + +double WaylandWindow::now() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); +} diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp new file mode 100644 index 000000000..76c426399 --- /dev/null +++ b/src/window/wayland/WaylandWindow.hpp @@ -0,0 +1,153 @@ +#pragma once + +#include "window/wayland/WaylandCommon.hpp" +#include "window/wayland/WaylandInput.hpp" + +#include "graphics/core/ImageData.hpp" +#include "window/Window.hpp" + +#include + +#include +#include + +class WaylandWindow : public Window { +public: +WaylandInput& input; +DisplaySettings* settings; +EGLDisplay eglDisplay = EGL_NO_DISPLAY; +EGLContext eglContext = EGL_NO_CONTEXT; +EGLSurface eglSurface = EGL_NO_SURFACE; +wl_egl_window* eglWindow = nullptr; +int32_t pendingWidth = 0; +int32_t pendingHeight = 0; +bool stateMaximized = false; +bool stateSuspended = false; +bool stateActivated = true; +bool configured = false; +static constexpr double RESIZE_TIMEOUT = 0.4; +static constexpr double FRAME_TIMEOUT = 0.025; +static constexpr double RESIZE_PAUSE = 0.12; +static constexpr double MIN_CACHE_TIMEOUT = 0.3; +static constexpr double MAX_CACHE_TIMEOUT = 3.0; +int framerate = -1; +double prevSwap = 0.0; +double lastResize = 0.0; +static inline bool resizeLogging = getenv("VOXEL_LOG_RESIZE") != nullptr; +bool barEnabled = false; +bool fullscreen = false; +std::string title = "VoxelCore"; +std::vector iconPixels; +int iconWidth = 0; +int iconHeight = 0; +int hoveredButton = -1; +double lastBarPress = 0.0; +double pointerX = 0.0; +double pointerY = 0.0; +GLuint barProgram = 0; +GLuint barVao = 0; +GLuint barVbo = 0; +GLuint barFontTexture = 0; +GLuint barIconTexture = 0; +GLint barViewportLoc = -1; +GLint barTextureLoc = -1; +GLint barModeLoc = -1; +std::vector barRects; +std::vector barText; +std::vector barIcons; +bool frameOnCallback = false; +double frameInterval = 0.0; +double nextFrameTime = 0.0; +double frameCost = 0.0; +double cacheTimeout = 0.5; +bool resizing = false; +bool renderPending = true; +bool presentPending = true; +int resizePresents = 0; +double configureTime = 0.0; +double resizeTimeSum = 0.0; +double resizeTimeMax = 0.0; +double lastPresent = 0.0; +double lastSummary = 0.0; +double summarySum = 0.0; +double summaryMax = 0.0; +int summaryFrames = 0; +double lastLoop = 0.0; +double loopGapMax = 0.0; +int loopCount = 0; +wl_callback* frameCallback = nullptr; +bool frameDone = false; +GLuint stretchProgram = 0; +GLuint stretchVao = 0; +GLuint stretchVbo = 0; +GLuint cacheFbo = 0; +GLuint cacheTexture = 0; +int cacheWidth = 0; +int cacheHeight = 0; +double lastCacheTime = 0.0; +double lastSwapEnd = 0.0; +bool shouldRefresh = true; +bool shouldClose = false; +bool maximized = false; +bool suspended = false; +bool activated = true; +bool focusWarning = false; +std::stack scissorStack; +glm::vec4 scissorArea {}; + WaylandWindow( WaylandInput& input, DisplaySettings* settings, int width, int height ); + ~WaylandWindow() override; + double time() override; + void swapBuffers() override; + void setShouldRefresh() override; + bool checkShouldRefresh() override; + bool isMaximized() const override; + bool isFocused() const override; + bool isIconified() const override; + bool isFrameRequired() const override; + bool isShouldClose() const override; + void setShouldClose(bool flag) override; + void setCursor(CursorShape shape) override; + void setMode(WindowMode mode) override; + WindowMode getMode() const override; + void focus() override; + void setTitle(const std::string& title) override; + void setFullscreen(bool enabled); + void setMaximized(bool enabled); + bool isIconSupported() const override; + void setIcon(const ImageData* image) override; + void resize(int width, int height); + void onConfigure(int32_t width, int32_t height, wl_array* states); + void applyConfigure(); + void pushScissor(glm::vec4 area) override; + void popScissor() override; + void resetScissor() override; + std::unique_ptr takeScreenshot() override; + void setFramerate(int framerate) override; + void initStretchRenderer(); + void resizeCache(int width, int height); + void cacheContent(); + void drawStretched(); + void enableOwnDecorations(); + bool barVisible() const; + void initBarRenderer(); + void initBarIconTexture(); + void barDrawText( float x, float y, const std::vector& codepoints, int maxChars, const glm::vec4& color ); + void barDrawBatch(const std::vector& data, int mode, GLuint texture); + void barFlush(); + void drawBar(); + int barButtonAt(double x, double y) const; + uint32_t barEdgeAt(double x, double y) const; + static CursorShape edgeCursor(uint32_t edges); + bool handleBarMotion(double x, double y); + bool handleBarButton(uint32_t serial, bool pressed); + void onPointerLeave(); + void onFrameDone(); + void requestFrame(); + void paceFrame(); + void logSummary(); + void markResizing(); + void updateResizing(); + void setIdleInhibit(bool enabled); + static const wl_callback_listener& frameListener(); + static double now(); +}; From 3b337241f5b7637cb5995099097329232a863caf Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 01:18:13 +0300 Subject: [PATCH 04/35] draw window decorations with the engine GUI The bar used to be drawn by the Wayland backend with its own shader, bitmap font and textures, straight into the engine's GL frame. That leaked GL state (the batch caches bound textures, so the engine kept sampling the backend texture and all text turned into solid white rectangles) and it duplicated fonts and styling. Now the backend only owns the behaviour: hit zones, cursor shapes, click interception and the compositor requests (move, resize, minimize, maximize/restore, close). The bar itself is drawn by the engine in WindowBar.cpp through the regular Batch2D/Font path, so it looks like the rest of the UI. Window gained getTitle(), getDecorationHeight() and getDecorationHoveredButton(); GLFW keeps the defaults, so X11 and Windows are unaffected. The backend's decoration drawing (bitmap font, shader, quad batches) is removed: WaylandBar.cpp went from 630 to 140 lines. Fixes found while debugging: - GlStateGuard was defined but never used after the file split, so the stretched frame left its texture bound and broke text rendering after a window mode change; it is now applied around the cache capture and the stretched frame; - takeScreenshot() now reads the front buffer and restores the read buffer afterwards. --- src/engine/Engine.cpp | 960 ++++++++++++++------------- src/engine/WindowBar.cpp | 88 +++ src/engine/WindowBar.hpp | 5 + src/graphics/ui/GUI.hpp | 382 +++++------ src/window/Window.hpp | 10 + src/window/detail/GLFWWindow.cpp | 7 + src/window/wayland/WaylandBar.cpp | 486 +------------- src/window/wayland/WaylandCommon.cpp | 72 ++ src/window/wayland/WaylandCommon.hpp | 11 + src/window/wayland/WaylandWindow.cpp | 22 +- src/window/wayland/WaylandWindow.hpp | 34 +- 11 files changed, 890 insertions(+), 1187 deletions(-) create mode 100644 src/engine/WindowBar.cpp create mode 100644 src/engine/WindowBar.hpp diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index b3185f371..9f33892b9 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,479 +1,481 @@ -#include "Engine.hpp" - -#ifndef GLEW_STATIC -#define GLEW_STATIC -#endif - -#include "AssetsManagement.hpp" -#include "audio/audio.hpp" -#include "coders/commons.hpp" -#include "coders/GLSLExtension.hpp" -#include "coders/toml.hpp" -#include "coders/vector_fonts.hpp" -#include "content/ContentControl.hpp" -#include "core_defs.hpp" -#include "debug/Logger.hpp" -#include "devtools/AppScriptsControl.hpp" -#include "devtools/DebuggingServer.hpp" -#include "devtools/Editor.hpp" -#include "devtools/Project.hpp" -#include "devtools/stdin_cmd_reader.hpp" -#include "EnginePaths.hpp" -#include "frontend/locale.hpp" -#include "frontend/menu.hpp" -#include "frontend/screens/Screen.hpp" -#include "graphics/core/DrawContext.hpp" -#include "graphics/core/Shader.hpp" -#include "graphics/ui/elements/Menu.hpp" -#include "graphics/ui/GUI.hpp" -#include "io/io.hpp" -#include "io/settings_io.hpp" -#include "logic/CommandsInterpreter.hpp" -#include "logic/EngineController.hpp" -#include "logic/scripting/scripting_hud.hpp" -#include "logic/scripting/scripting.hpp" -#include "Mainloop.hpp" -#include "network/Network.hpp" -#include "ServerMainloop.hpp" -#include "util/platform.hpp" -#include "util/stringutil.hpp" -#include "window/input.hpp" -#include "window/Window.hpp" -#include "WindowControl.hpp" -#include "world/Level.hpp" - -#include -#include -#include -#include - -static debug::Logger logger("engine"); - -Engine::Engine() = default; -Engine::~Engine() = default; - -static std::unique_ptr instance = nullptr; - -Engine& Engine::getInstance() { - if (!instance) { - instance = std::make_unique(); - } - return *instance; -} - -void Engine::onContentLoad() { - editor->loadTools(); - langs::setup(langs::get_current(), paths->resPaths.collectRoots()); - - if (isHeadless()) { - return; - } - for (auto& pack : content->getAllContentPacks()) { - auto configFolder = pack.folder / "config"; - auto bindsFile = configFolder / "bindings.toml"; - logger.info() << "loading bindings: " << bindsFile.string(); - if (io::is_regular_file(bindsFile)) { - input->getBindings().read( - toml::parse( - bindsFile.string(), io::read_string(bindsFile) - ), - BindType::BIND - ); - } - } - loadAssets(); -} - -void Engine::initializeClient() { - assets = std::make_unique(*this); - windowControl = std::make_unique(*this); - auto [window, input] = windowControl->initialize(); - - this->window = std::move(window); - this->input = std::move(input); - - loadControls(); - - gui = std::make_unique(*this); - if (ENGINE_DEBUG_BUILD) { - menus::create_version_label(*gui); - } - keepAlive(settings.display.windowMode.observe( - [this](int value) { - WindowMode mode = static_cast(value); - if (mode != this->window->getMode()) { - this->window->setMode(mode); - } - }, - true - )); - keepAlive(settings.debug.doTraceShaders.observe( - [](bool value) { - Shader::preprocessor->setTraceOutput(value); - }, - true - )); - - keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { - auto& menu = *gui->getMenu(); - if (menu.hasOpenPage() && menu.back()) { - return true; - } - return false; - })); -} - -void Engine::initialize(CoreParameters coreParameters) { - params = std::move(coreParameters); - settingsHandler = std::make_unique(settings); - - logger.info() << "engine version: " << ENGINE_VERSION_STRING; - if (params.headless) { - logger.info() << "engine runs in headless mode"; - } - if (params.projectFolder.empty()) { - params.projectFolder = params.resFolder; - } - paths = std::make_unique(params); - loadProject(); - paths->setupProject(*project); - - editor = std::make_unique(*this); - cmd = std::make_unique(); - - if (project->permissions.has(Permissions::NETWORK) || - !params.debugServerString.empty()) { - network = network::Network::create(settings.network); - } - - if (!params.debugServerString.empty()) { - try { - debuggingServer = std::make_unique( - *this, params.debugServerString - ); - } catch (const std::runtime_error& err) { - throw initialize_error( - "debugging server error: " + std::string(err.what()) - ); - } - } - loadSettings(); - - controller = std::make_unique(*this); - if (!params.headless) { - initializeClient(); - } - audio::initialize( - !params.headless, - project->permissions.has(Permissions::RECORD_AUDIO), - settings.audio - ); - - vector_fonts::initialize(); - - if (settings.ui.language.get() == "auto") { - settings.ui.language.set( - langs::locale_by_envlocale(platform::detect_locale()) - ); - } - content = std::make_unique( - *project, *paths, input.get(), [this]() { onContentLoad(); } - ); - scripting::initialize(*this); - - if (!isHeadless()) { - gui->getMenu()->setPageLoader(scripting::create_page_loader()); - } - keepAlive(settings.ui.language.observe([this](auto lang) { - langs::setup(lang, paths->resPaths.collectRoots()); - }, true)); - - keepAlive(settings.audio.inputDevice.observe([](auto name) { - audio::set_input_device(name == "auto" ? "" : name); - })); - - appScripts = std::make_unique(params); - - if (params.stdinCommands) { - cmd::start_stdin_cmd_reader(*this); - } -} - -void Engine::loadSettings() { - io::path settings_file = EnginePaths::SETTINGS_FILE; - if (io::is_regular_file(settings_file)) { - logger.info() << "loading settings"; - std::string text = io::read_string(settings_file); - try { - toml::parse(*settingsHandler, settings_file.string(), text); - } catch (const parsing_error& err) { - logger.error() << err.errorLog(); - throw; - } - } -} - -void Engine::loadControls() { - io::path controls_file = EnginePaths::CONTROLS_FILE; - if (io::is_regular_file(controls_file)) { - logger.info() << "loading controls"; - std::string text = io::read_string(controls_file); - input->getBindings().read( - toml::parse(controls_file.string(), text), BindType::BIND - ); - } -} - -void Engine::updateHotkeys() { - if (input->jpressed(Keycode::F2)) { - windowControl->saveScreenshot(); - } - if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && - input->jpressed(Keycode::U)) { - gui->toggleDebug(); - } - if (input->jpressed(Keycode::F11)) { - windowControl->toggleFullscreen(); - } -} - -void Engine::run() { - if (params.headless) { - ServerMainloop(*this).run(); - } else { - Mainloop(*this).run(); - } -} - -void Engine::postUpdate() { - if (network) { - network->update(); - } - postRunnables.run(); - scripting::process_post_runnables(); - - if (debuggingServer) { - debuggingServer->update(); - } -} - -void Engine::detachDebugger() { - debuggingServer.reset(); -} - -void Engine::applicationTick() { - appScripts->tick(); -} - -void Engine::updateFrontend() { - double delta = time.getDelta(); - assets->update(); - updateHotkeys(); - audio::update(delta); - gui->act(delta, window->getSize()); - screen->update(delta); - gui->postAct(); -} - -void Engine::nextFrame(bool waitForRefresh) { - windowControl->nextFrame(waitForRefresh); -} - -void Engine::startPauseLoop() { - assert (network != nullptr); - - bool initialCursorLocked = false; - if (!isHeadless()) { - initialCursorLocked = input->isCursorLocked(); - if (initialCursorLocked) { - input->toggleCursor(); - } - } - while (!isQuitSignal() && debuggingServer) { - network->update(); - if (debuggingServer->update()) { - break; - } - if (isHeadless()) { - platform::sleep(1.0 / params.tps * 1000); - } else { - nextFrame(false); - } - } - if (initialCursorLocked) { - input->toggleCursor(); - } -} - -void Engine::renderFrame() { - if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { - input->toggleCursor(); - } - screen->draw(time.getDelta()); - - DrawContext ctx(nullptr, *window, nullptr); - gui->draw(ctx, *assets->getStorage()); -} - -void Engine::saveSettings() { - logger.info() << "saving settings"; - io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); - if (!params.headless) { - logger.info() << "saving bindings"; - if (input) { - io::write_string( - EnginePaths::CONTROLS_FILE, input->getBindings().write() - ); - } - } -} - -void Engine::close() { - saveSettings(); - logger.info() << "shutting down"; - if (screen) { - screen->onEngineShutdown(); - screen.reset(); - } - content.reset(); - assets.reset(); - cmd.reset(); - if (gui) { - gui.reset(); - logger.info() << "gui finished"; - } - if (!isHeadless()) { - vector_fonts::finalize(); - } - audio::close(); - debuggingServer.reset(); - network.reset(); - clearKeepedObjects(); - project.reset(); - appScripts.reset(); - scripting::close(); - logger.info() << "scripting finished"; - if (!params.headless) { - window.reset(); - logger.info() << "window closed"; - } - logger.info() << "engine finished"; -} - -void Engine::terminate() { - instance->close(); - instance.reset(); -} - -EngineController* Engine::getController() { - return controller.get(); -} - -void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { - this->levelConsumer = std::move(levelConsumer); -} - -void Engine::loadAssets() { - assets->loadAssets(content->get()); -} - -void Engine::loadProject() { - io::path projectFile = "project:project.toml"; - project = std::make_unique(); - project->path = "project:"; - project->deserialize(io::read_object(projectFile)); - logger.info() << "loaded project " << util::quote(project->name); -} - -void Engine::setScreen(std::shared_ptr screen) { - if (this->screen) { - appScripts->onScreenChange(this->screen->getName(), false); - } - // reset audio channels (stop all sources) - audio::reset_channel(audio::get_channel_index("regular")); - audio::reset_channel(audio::get_channel_index("ambient")); - this->screen = std::move(screen); - if (this->screen) { - this->screen->onOpen(); - } - if (this->screen) { - appScripts->onScreenChange(this->screen->getName(), true); - window->setShouldRefresh(); - } -} - -void Engine::onWorldOpen(std::unique_ptr level, int64_t localPlayer) { - logger.info() << "world open"; - levelConsumer(std::move(level), localPlayer); -} - -void Engine::onWorldClosed() { - logger.info() << "world closed"; - levelConsumer(nullptr, -1); -} - -void Engine::quit() { - logger.info() << "quitSignal set to true"; - quitSignal = true; - if (!isHeadless()) { - window->setShouldClose(true); - } -} - -bool Engine::isQuitSignal() const { - return quitSignal; -} - -EngineSettings& Engine::getSettings() { - return settings; -} - -Assets* Engine::getAssets() { - return assets ? assets->getStorage() : nullptr; -} - -Assets& Engine::requireAssets() { - if (isHeadless()) { - throw std::runtime_error("assets are not available in headless mode"); - } - return *assets->getStorage(); -} - -AssetsLoader& Engine::acquireBackgroundLoader() { - if (isHeadless()) { - throw std::runtime_error("assets are not available in headless mode"); - } - return assets->acquireBackgroundLoader(); -} - -EnginePaths& Engine::getPaths() { - return *paths; -} - -ResPaths& Engine::getResPaths() { - return paths->resPaths; -} - -std::shared_ptr Engine::getScreen() { - return screen; -} - -SettingsHandler& Engine::getSettingsHandler() { - return *settingsHandler; -} - -Time& Engine::getTime() { - return time; -} - -const CoreParameters& Engine::getCoreParameters() const { - return params; -} - -bool Engine::isHeadless() const { - return params.headless; -} - -ContentControl& Engine::getContentControl() { - return *content; -} +#include "Engine.hpp" +#include "WindowBar.hpp" + +#ifndef GLEW_STATIC +#define GLEW_STATIC +#endif + +#include "AssetsManagement.hpp" +#include "audio/audio.hpp" +#include "coders/commons.hpp" +#include "coders/GLSLExtension.hpp" +#include "coders/toml.hpp" +#include "coders/vector_fonts.hpp" +#include "content/ContentControl.hpp" +#include "core_defs.hpp" +#include "debug/Logger.hpp" +#include "devtools/AppScriptsControl.hpp" +#include "devtools/DebuggingServer.hpp" +#include "devtools/Editor.hpp" +#include "devtools/Project.hpp" +#include "devtools/stdin_cmd_reader.hpp" +#include "EnginePaths.hpp" +#include "frontend/locale.hpp" +#include "frontend/menu.hpp" +#include "frontend/screens/Screen.hpp" +#include "graphics/core/DrawContext.hpp" +#include "graphics/core/Shader.hpp" +#include "graphics/ui/elements/Menu.hpp" +#include "graphics/ui/GUI.hpp" +#include "io/io.hpp" +#include "io/settings_io.hpp" +#include "logic/CommandsInterpreter.hpp" +#include "logic/EngineController.hpp" +#include "logic/scripting/scripting_hud.hpp" +#include "logic/scripting/scripting.hpp" +#include "Mainloop.hpp" +#include "network/Network.hpp" +#include "ServerMainloop.hpp" +#include "util/platform.hpp" +#include "util/stringutil.hpp" +#include "window/input.hpp" +#include "window/Window.hpp" +#include "WindowControl.hpp" +#include "world/Level.hpp" + +#include +#include +#include +#include + +static debug::Logger logger("engine"); + +Engine::Engine() = default; +Engine::~Engine() = default; + +static std::unique_ptr instance = nullptr; + +Engine& Engine::getInstance() { + if (!instance) { + instance = std::make_unique(); + } + return *instance; +} + +void Engine::onContentLoad() { + editor->loadTools(); + langs::setup(langs::get_current(), paths->resPaths.collectRoots()); + + if (isHeadless()) { + return; + } + for (auto& pack : content->getAllContentPacks()) { + auto configFolder = pack.folder / "config"; + auto bindsFile = configFolder / "bindings.toml"; + logger.info() << "loading bindings: " << bindsFile.string(); + if (io::is_regular_file(bindsFile)) { + input->getBindings().read( + toml::parse( + bindsFile.string(), io::read_string(bindsFile) + ), + BindType::BIND + ); + } + } + loadAssets(); +} + +void Engine::initializeClient() { + assets = std::make_unique(*this); + windowControl = std::make_unique(*this); + auto [window, input] = windowControl->initialize(); + + this->window = std::move(window); + this->input = std::move(input); + + loadControls(); + + gui = std::make_unique(*this); + if (ENGINE_DEBUG_BUILD) { + menus::create_version_label(*gui); + } + keepAlive(settings.display.windowMode.observe( + [this](int value) { + WindowMode mode = static_cast(value); + if (mode != this->window->getMode()) { + this->window->setMode(mode); + } + }, + true + )); + keepAlive(settings.debug.doTraceShaders.observe( + [](bool value) { + Shader::preprocessor->setTraceOutput(value); + }, + true + )); + + keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { + auto& menu = *gui->getMenu(); + if (menu.hasOpenPage() && menu.back()) { + return true; + } + return false; + })); +} + +void Engine::initialize(CoreParameters coreParameters) { + params = std::move(coreParameters); + settingsHandler = std::make_unique(settings); + + logger.info() << "engine version: " << ENGINE_VERSION_STRING; + if (params.headless) { + logger.info() << "engine runs in headless mode"; + } + if (params.projectFolder.empty()) { + params.projectFolder = params.resFolder; + } + paths = std::make_unique(params); + loadProject(); + paths->setupProject(*project); + + editor = std::make_unique(*this); + cmd = std::make_unique(); + + if (project->permissions.has(Permissions::NETWORK) || + !params.debugServerString.empty()) { + network = network::Network::create(settings.network); + } + + if (!params.debugServerString.empty()) { + try { + debuggingServer = std::make_unique( + *this, params.debugServerString + ); + } catch (const std::runtime_error& err) { + throw initialize_error( + "debugging server error: " + std::string(err.what()) + ); + } + } + loadSettings(); + + controller = std::make_unique(*this); + if (!params.headless) { + initializeClient(); + } + audio::initialize( + !params.headless, + project->permissions.has(Permissions::RECORD_AUDIO), + settings.audio + ); + + vector_fonts::initialize(); + + if (settings.ui.language.get() == "auto") { + settings.ui.language.set( + langs::locale_by_envlocale(platform::detect_locale()) + ); + } + content = std::make_unique( + *project, *paths, input.get(), [this]() { onContentLoad(); } + ); + scripting::initialize(*this); + + if (!isHeadless()) { + gui->getMenu()->setPageLoader(scripting::create_page_loader()); + } + keepAlive(settings.ui.language.observe([this](auto lang) { + langs::setup(lang, paths->resPaths.collectRoots()); + }, true)); + + keepAlive(settings.audio.inputDevice.observe([](auto name) { + audio::set_input_device(name == "auto" ? "" : name); + })); + + appScripts = std::make_unique(params); + + if (params.stdinCommands) { + cmd::start_stdin_cmd_reader(*this); + } +} + +void Engine::loadSettings() { + io::path settings_file = EnginePaths::SETTINGS_FILE; + if (io::is_regular_file(settings_file)) { + logger.info() << "loading settings"; + std::string text = io::read_string(settings_file); + try { + toml::parse(*settingsHandler, settings_file.string(), text); + } catch (const parsing_error& err) { + logger.error() << err.errorLog(); + throw; + } + } +} + +void Engine::loadControls() { + io::path controls_file = EnginePaths::CONTROLS_FILE; + if (io::is_regular_file(controls_file)) { + logger.info() << "loading controls"; + std::string text = io::read_string(controls_file); + input->getBindings().read( + toml::parse(controls_file.string(), text), BindType::BIND + ); + } +} + +void Engine::updateHotkeys() { + if (input->jpressed(Keycode::F2)) { + windowControl->saveScreenshot(); + } + if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && + input->jpressed(Keycode::U)) { + gui->toggleDebug(); + } + if (input->jpressed(Keycode::F11)) { + windowControl->toggleFullscreen(); + } +} + +void Engine::run() { + if (params.headless) { + ServerMainloop(*this).run(); + } else { + Mainloop(*this).run(); + } +} + +void Engine::postUpdate() { + if (network) { + network->update(); + } + postRunnables.run(); + scripting::process_post_runnables(); + + if (debuggingServer) { + debuggingServer->update(); + } +} + +void Engine::detachDebugger() { + debuggingServer.reset(); +} + +void Engine::applicationTick() { + appScripts->tick(); +} + +void Engine::updateFrontend() { + double delta = time.getDelta(); + assets->update(); + updateHotkeys(); + audio::update(delta); + gui->act(delta, window->getSize()); + screen->update(delta); + gui->postAct(); +} + +void Engine::nextFrame(bool waitForRefresh) { + windowControl->nextFrame(waitForRefresh); +} + +void Engine::startPauseLoop() { + assert (network != nullptr); + + bool initialCursorLocked = false; + if (!isHeadless()) { + initialCursorLocked = input->isCursorLocked(); + if (initialCursorLocked) { + input->toggleCursor(); + } + } + while (!isQuitSignal() && debuggingServer) { + network->update(); + if (debuggingServer->update()) { + break; + } + if (isHeadless()) { + platform::sleep(1.0 / params.tps * 1000); + } else { + nextFrame(false); + } + } + if (initialCursorLocked) { + input->toggleCursor(); + } +} + +void Engine::renderFrame() { + if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { + input->toggleCursor(); + } + screen->draw(time.getDelta()); + + DrawContext ctx(nullptr, *window, nullptr); + gui->draw(ctx, *assets->getStorage()); + draw_window_bar(*this); +} + +void Engine::saveSettings() { + logger.info() << "saving settings"; + io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); + if (!params.headless) { + logger.info() << "saving bindings"; + if (input) { + io::write_string( + EnginePaths::CONTROLS_FILE, input->getBindings().write() + ); + } + } +} + +void Engine::close() { + saveSettings(); + logger.info() << "shutting down"; + if (screen) { + screen->onEngineShutdown(); + screen.reset(); + } + content.reset(); + assets.reset(); + cmd.reset(); + if (gui) { + gui.reset(); + logger.info() << "gui finished"; + } + if (!isHeadless()) { + vector_fonts::finalize(); + } + audio::close(); + debuggingServer.reset(); + network.reset(); + clearKeepedObjects(); + project.reset(); + appScripts.reset(); + scripting::close(); + logger.info() << "scripting finished"; + if (!params.headless) { + window.reset(); + logger.info() << "window closed"; + } + logger.info() << "engine finished"; +} + +void Engine::terminate() { + instance->close(); + instance.reset(); +} + +EngineController* Engine::getController() { + return controller.get(); +} + +void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { + this->levelConsumer = std::move(levelConsumer); +} + +void Engine::loadAssets() { + assets->loadAssets(content->get()); +} + +void Engine::loadProject() { + io::path projectFile = "project:project.toml"; + project = std::make_unique(); + project->path = "project:"; + project->deserialize(io::read_object(projectFile)); + logger.info() << "loaded project " << util::quote(project->name); +} + +void Engine::setScreen(std::shared_ptr screen) { + if (this->screen) { + appScripts->onScreenChange(this->screen->getName(), false); + } + // reset audio channels (stop all sources) + audio::reset_channel(audio::get_channel_index("regular")); + audio::reset_channel(audio::get_channel_index("ambient")); + this->screen = std::move(screen); + if (this->screen) { + this->screen->onOpen(); + } + if (this->screen) { + appScripts->onScreenChange(this->screen->getName(), true); + window->setShouldRefresh(); + } +} + +void Engine::onWorldOpen(std::unique_ptr level, int64_t localPlayer) { + logger.info() << "world open"; + levelConsumer(std::move(level), localPlayer); +} + +void Engine::onWorldClosed() { + logger.info() << "world closed"; + levelConsumer(nullptr, -1); +} + +void Engine::quit() { + logger.info() << "quitSignal set to true"; + quitSignal = true; + if (!isHeadless()) { + window->setShouldClose(true); + } +} + +bool Engine::isQuitSignal() const { + return quitSignal; +} + +EngineSettings& Engine::getSettings() { + return settings; +} + +Assets* Engine::getAssets() { + return assets ? assets->getStorage() : nullptr; +} + +Assets& Engine::requireAssets() { + if (isHeadless()) { + throw std::runtime_error("assets are not available in headless mode"); + } + return *assets->getStorage(); +} + +AssetsLoader& Engine::acquireBackgroundLoader() { + if (isHeadless()) { + throw std::runtime_error("assets are not available in headless mode"); + } + return assets->acquireBackgroundLoader(); +} + +EnginePaths& Engine::getPaths() { + return *paths; +} + +ResPaths& Engine::getResPaths() { + return paths->resPaths; +} + +std::shared_ptr Engine::getScreen() { + return screen; +} + +SettingsHandler& Engine::getSettingsHandler() { + return *settingsHandler; +} + +Time& Engine::getTime() { + return time; +} + +const CoreParameters& Engine::getCoreParameters() const { + return params; +} + +bool Engine::isHeadless() const { + return params.headless; +} + +ContentControl& Engine::getContentControl() { + return *content; +} diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp new file mode 100644 index 000000000..661b30d4c --- /dev/null +++ b/src/engine/WindowBar.cpp @@ -0,0 +1,88 @@ +#include "WindowBar.hpp" + +#include "Engine.hpp" +#include "graphics/core/Batch2D.hpp" +#include "graphics/core/Font.hpp" +#include "graphics/ui/GUI.hpp" +#include "window/Window.hpp" +#include "assets/Assets.hpp" + +#include +#include + +namespace { + std::wstring to_wide(const std::string& text) { + std::wstring_convert> converter; + return converter.from_bytes(text); + } + + constexpr const char* BAR_FONT = "normal"; +} + +void draw_window_bar(Engine& engine) { + auto& window = engine.getWindow(); + const int height = window.getDecorationHeight(); + if (height <= 0) { + return; + } + auto* batch = engine.getGUI().getBatch2D(); + auto font = engine.requireAssets().getShared(BAR_FONT); + if (batch == nullptr || font == nullptr) { + return; + } + const auto size = window.getSize(); + const float barHeight = static_cast(height); + + batch->begin(); + batch->setColor(glm::vec4(0.0f, 0.0f, 0.0f, 0.82f)); + batch->rect(0.0f, 0.0f, size.x, barHeight); + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.10f)); + batch->rect(0.0f, barHeight - 1.0f, size.x, 1.0f); + + const std::wstring title = to_wide(window.getTitle()); + const int textX = static_cast(barHeight * 0.4f); + const int textY = (height - font->getLineHeight()) / 2; + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f)); + font->draw(*batch, title, textX, textY, nullptr, 0); + batch->untexture(); + + const float button = barHeight; + const int hovered = window.getDecorationHoveredButton(); + for (int i = 0; i < 3; i++) { + const float x = size.x - button * (i + 1); + const float cx = x + button * 0.5f; + const float cy = barHeight * 0.5f; + if (hovered == i) { + batch->setColor( + i == 0 ? glm::vec4(0.62f, 0.13f, 0.09f, 0.9f) + : glm::vec4(1.0f, 1.0f, 1.0f, 0.16f) + ); + batch->rect(x, 0.0f, button, barHeight - 1.0f); + } + const float ink = hovered == i ? 1.0f : 0.8f; + const float thickness = 2.0f; + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink)); + if (i == 0) { + for (int s = 0; s < 8; s++) { + batch->rect(cx - 5.0f + s, cy - 5.0f + s, thickness, thickness); + batch->rect(cx + 3.0f - s, cy - 5.0f + s, thickness, thickness); + } + } else if (i == 1 && !window.isMaximized()) { + batch->rect(cx - 6.0f, cy - 6.0f, 12.0f, thickness); + batch->rect(cx - 6.0f, cy + 4.0f, 12.0f, thickness); + batch->rect(cx - 6.0f, cy - 6.0f, thickness, 12.0f); + batch->rect(cx + 4.0f, cy - 6.0f, thickness, 12.0f); + } else if (i == 1) { + batch->rect(cx - 7.0f, cy + 1.0f, 11.0f, thickness); + batch->rect(cx - 7.0f, cy + 1.0f, thickness, 6.0f); + batch->rect(cx + 2.0f, cy + 1.0f, thickness, 6.0f); + batch->rect(cx - 7.0f, cy + 5.0f, 11.0f, thickness); + batch->rect(cx - 2.0f, cy - 5.0f, 9.0f, thickness); + batch->rect(cx - 2.0f, cy - 5.0f, thickness, 6.0f); + batch->rect(cx + 5.0f, cy - 5.0f, thickness, 6.0f); + } else { + batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness); + } + } + batch->flush(); +} diff --git a/src/engine/WindowBar.hpp b/src/engine/WindowBar.hpp new file mode 100644 index 000000000..be3df317b --- /dev/null +++ b/src/engine/WindowBar.hpp @@ -0,0 +1,5 @@ +#pragma once + +class Engine; + +void draw_window_bar(Engine& engine); diff --git a/src/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index 997b67bea..3cf8406fb 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -1,189 +1,193 @@ -#pragma once - -#include "delegates.hpp" - -#include -#include -#include -#include -#include -#include -#include - -class DrawContext; -class Assets; -class Camera; -class Batch2D; -struct CursorState; -class Engine; -class Input; -class Window; -struct FontStylesScheme; - -namespace devtools { - class Editor; -} - -class UiDocument; - -/* - Some info about padding and margin. - Padding is element inner space, margin is outer - glm::vec4 usage: - x - left - y - top - z - right - w - bottom - - Outer element - +======================================================================+ - | . . . . | - | .padding.y . . . | - | padding.x . . . . padding.z | - |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | - | . . . . | - | . .margin.y . . | - | .margin.x . . margin.z. | - |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | - | . | Inner element | . | - |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | - | . . . . | - | . .margin.w . . | - | . . . . | - |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | - | . . . . | - | .padding.w . . . | - | . . . . | - +======================================================================+ -*/ - -namespace gui { - class UINode; - class Container; - class Menu; - class Frame; - - /// @brief The main UI controller - class GUI { - Engine& engine; - Input& input; - std::unique_ptr batch2D; - std::shared_ptr container; - std::shared_ptr hover; - std::shared_ptr pressed; - std::shared_ptr focus; - const UINode* focusedOnStart = nullptr; - std::shared_ptr tooltip; - std::shared_ptr rootDocument; - std::unique_ptr syntaxColorScheme; - std::unordered_map> storage; - std::shared_ptr activeFrame; - - std::unique_ptr uicamera; - std::shared_ptr menu; - std::queue postRunnables; - std::vector> mouseOver; - std::unordered_map> frames; - vec2supplier cursorLocator; - - float tooltipTimer = 0.0f; - float doubleClickTimer = 0.0f; - float doubleClickDelay = 0.5f; - bool doubleClicked = false; - bool debug = false; - - void actMouse(Frame& frame, float delta, const CursorState& cursor); - void actFocused(); - void updateTooltip(float delta); - void resetTooltip(); - public: - static inline std::string CORE_MAIN = "core:main"; - static constexpr int CONTEXT_MENU_ZINDEX = 999; - - GUI(Engine& engine); - ~GUI(); - - /// @brief Get the main menu (Menu) node - std::shared_ptr getMenu(); - - /// @brief Get current focused node - /// @return focused node or nullptr - std::shared_ptr getFocused() const; - - /// @brief Check if all user input is caught by some element like TextBox - bool isFocusCaught() const; - - /// @brief Main input handling and logic update method - /// @param delta delta time - /// @param viewport window size - void act(float delta, const glm::uvec2& viewport); - - /// @brief Draw all visible elements on main container - /// @param pctx parent graphics context - /// @param assets active assets storage - void draw(const DrawContext& pctx, Assets& assets); - - void postAct(); - - /// @brief Add element to the main container - /// @param node UI element - void add(std::shared_ptr node); - - void addFrame(std::shared_ptr frame); - - void setActiveFrame( - const std::string& id, vec2supplier cursorLocator = nullptr - ); - - std::shared_ptr getActiveFrame() const; - - std::shared_ptr getFrame(const std::string& id); - - /// @brief Remove node from the main container - void remove(UINode* node) noexcept; - - void remove(const std::shared_ptr& node) noexcept { - return remove(node.get()); - } - - /// @brief Store node in the GUI nodes dictionary - /// (does not add node to the main container) - /// @param name node key - /// @param node target node - void store(const std::string& name, std::shared_ptr node); - - /// @brief Get node from the GUI nodes dictionary - /// @param name node key - /// @return stored node or nullptr - std::shared_ptr get(const std::string& name) noexcept; - - /// @brief Remove node from the GUI nodes dictionary - /// @param name node key - void remove(const std::string& name) noexcept; - - /// @brief Set node as focused - /// @param node new focused node or nullptr to remove focus - void setFocus(std::shared_ptr node); - - /// @brief Get the main container - /// @deprecated - std::shared_ptr getContainer() const; - - void setSyntaxColorScheme(std::unique_ptr scheme); - FontStylesScheme* getSyntaxColorScheme() const; - - void onAssetsLoad(Assets* assets); - - void postRunnable(const runnable& callback); - - void setDoubleClickDelay(float delay); - float getDoubleClickDelay() const; - - void toggleDebug(); - const Input& getInput() const; - Input& getInput(); - Window& getWindow(); - devtools::Editor& getEditor(); - Engine& getEngine(); - }; -} +#pragma once + +#include "delegates.hpp" + +#include +#include +#include +#include +#include +#include +#include + +class DrawContext; +class Assets; +class Camera; +class Batch2D; +struct CursorState; +class Engine; +class Input; +class Window; +struct FontStylesScheme; + +namespace devtools { + class Editor; +} + +class UiDocument; + +/* + Some info about padding and margin. + Padding is element inner space, margin is outer + glm::vec4 usage: + x - left + y - top + z - right + w - bottom + + Outer element + +======================================================================+ + | . . . . | + | .padding.y . . . | + | padding.x . . . . padding.z | + |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | + | . . . . | + | . .margin.y . . | + | .margin.x . . margin.z. | + |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | + | . | Inner element | . | + |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | + | . . . . | + | . .margin.w . . | + | . . . . | + |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | + | . . . . | + | .padding.w . . . | + | . . . . | + +======================================================================+ +*/ + +namespace gui { + class UINode; + class Container; + class Menu; + class Frame; + + /// @brief The main UI controller + class GUI { + Engine& engine; + Input& input; + std::unique_ptr batch2D; + std::shared_ptr container; + std::shared_ptr hover; + std::shared_ptr pressed; + std::shared_ptr focus; + const UINode* focusedOnStart = nullptr; + std::shared_ptr tooltip; + std::shared_ptr rootDocument; + std::unique_ptr syntaxColorScheme; + std::unordered_map> storage; + std::shared_ptr activeFrame; + + std::unique_ptr uicamera; + std::shared_ptr menu; + std::queue postRunnables; + std::vector> mouseOver; + std::unordered_map> frames; + vec2supplier cursorLocator; + + float tooltipTimer = 0.0f; + float doubleClickTimer = 0.0f; + float doubleClickDelay = 0.5f; + bool doubleClicked = false; + bool debug = false; + + void actMouse(Frame& frame, float delta, const CursorState& cursor); + void actFocused(); + void updateTooltip(float delta); + void resetTooltip(); + public: + static inline std::string CORE_MAIN = "core:main"; + static constexpr int CONTEXT_MENU_ZINDEX = 999; + + GUI(Engine& engine); + ~GUI(); + + /// @brief Get the main menu (Menu) node + std::shared_ptr getMenu(); + + /// @brief Get current focused node + /// @return focused node or nullptr + std::shared_ptr getFocused() const; + + /// @brief Check if all user input is caught by some element like TextBox + bool isFocusCaught() const; + + /// @brief Main input handling and logic update method + /// @param delta delta time + /// @param viewport window size + void act(float delta, const glm::uvec2& viewport); + + /// @brief Draw all visible elements on main container + /// @param pctx parent graphics context + /// @param assets active assets storage + void draw(const DrawContext& pctx, Assets& assets); + + Batch2D* getBatch2D() { + return batch2D.get(); + } + + void postAct(); + + /// @brief Add element to the main container + /// @param node UI element + void add(std::shared_ptr node); + + void addFrame(std::shared_ptr frame); + + void setActiveFrame( + const std::string& id, vec2supplier cursorLocator = nullptr + ); + + std::shared_ptr getActiveFrame() const; + + std::shared_ptr getFrame(const std::string& id); + + /// @brief Remove node from the main container + void remove(UINode* node) noexcept; + + void remove(const std::shared_ptr& node) noexcept { + return remove(node.get()); + } + + /// @brief Store node in the GUI nodes dictionary + /// (does not add node to the main container) + /// @param name node key + /// @param node target node + void store(const std::string& name, std::shared_ptr node); + + /// @brief Get node from the GUI nodes dictionary + /// @param name node key + /// @return stored node or nullptr + std::shared_ptr get(const std::string& name) noexcept; + + /// @brief Remove node from the GUI nodes dictionary + /// @param name node key + void remove(const std::string& name) noexcept; + + /// @brief Set node as focused + /// @param node new focused node or nullptr to remove focus + void setFocus(std::shared_ptr node); + + /// @brief Get the main container + /// @deprecated + std::shared_ptr getContainer() const; + + void setSyntaxColorScheme(std::unique_ptr scheme); + FontStylesScheme* getSyntaxColorScheme() const; + + void onAssetsLoad(Assets* assets); + + void postRunnable(const runnable& callback); + + void setDoubleClickDelay(float delay); + float getDoubleClickDelay() const; + + void toggleDebug(); + const Input& getInput() const; + Input& getInput(); + Window& getWindow(); + devtools::Editor& getEditor(); + Engine& getEngine(); + }; +} diff --git a/src/window/Window.hpp b/src/window/Window.hpp index c34024cdf..a41c53535 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -44,6 +44,16 @@ public: virtual void setTitle(const std::string& title) = 0; + virtual const std::string& getTitle() const = 0; + + virtual int getDecorationHeight() const { + return 0; + } + + virtual int getDecorationHoveredButton() const { + return -1; + } + virtual bool isIconSupported() const = 0; virtual void setIcon(const ImageData* image) = 0; diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 9fe04b82c..59f637fb1 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -360,7 +360,14 @@ public: glfwFocusWindow(window); } + std::string title; + + const std::string& getTitle() const override { + return title; + } + void setTitle(const std::string& title) override { + this->title = title; glfwSetWindowTitle(window, title.c_str()); } diff --git a/src/window/wayland/WaylandBar.cpp b/src/window/wayland/WaylandBar.cpp index e362baa60..ab2f221de 100644 --- a/src/window/wayland/WaylandBar.cpp +++ b/src/window/wayland/WaylandBar.cpp @@ -5,262 +5,16 @@ static constexpr int BAR_HEIGHT = 30; static constexpr int BAR_BUTTON = 30; static constexpr int BAR_EDGE = 5; -static constexpr int BAR_ICON_SIZE = 16; -static constexpr int BAR_FONT_W = 8; -static constexpr int BAR_FONT_H = 8; -static constexpr int BAR_GLYPHS = 159; - -static const uint8_t BAR_FONT[BAR_GLYPHS][BAR_FONT_H] { - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x50, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x14, 0x14, 0x7e, 0x28, 0xfe, 0x28, 0x68}, - {0x00, 0x10, 0x78, 0x70, 0x78, 0x7c, 0x1c, 0x78}, - {0x00, 0x62, 0xf4, 0xfc, 0x6b, 0x1f, 0x17, 0x23}, - {0x00, 0x38, 0x60, 0x30, 0x7a, 0xde, 0x6c, 0x7e}, - {0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x20, 0x60, 0x60, 0x40, 0x40, 0x60, 0x60, 0x20}, - {0x40, 0x60, 0x20, 0x20, 0x20, 0x20, 0x60, 0x40}, - {0x00, 0x20, 0xf0, 0x70, 0xf0, 0x20, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x10, 0x10, 0x7e, 0x10, 0x10}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x40}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60}, - {0x00, 0x20, 0x20, 0x60, 0x40, 0x40, 0xc0, 0x80}, - {0x00, 0x38, 0x6c, 0xcc, 0xcc, 0xcc, 0x6c, 0x38}, - {0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x7c}, - {0x00, 0x78, 0x18, 0x18, 0x18, 0x30, 0x60, 0x7c}, - {0x00, 0x78, 0x18, 0x18, 0x38, 0x1c, 0x1c, 0xf8}, - {0x00, 0x18, 0x38, 0x78, 0x58, 0xd8, 0xfc, 0x18}, - {0x00, 0x78, 0x40, 0x40, 0x78, 0x0c, 0x0c, 0x78}, - {0x00, 0x38, 0x60, 0x40, 0xf8, 0x6c, 0x6c, 0x38}, - {0x00, 0xfc, 0x18, 0x18, 0x18, 0x30, 0x30, 0x60}, - {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x78}, - {0x00, 0x78, 0xc8, 0xcc, 0x7c, 0x0c, 0x18, 0x70}, - {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x00, 0x00, 0x06, 0x3c, 0x60, 0x3c, 0x06}, - {0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00}, - {0x00, 0x00, 0x00, 0x60, 0x3c, 0x0e, 0x3c, 0x60}, - {0x00, 0x70, 0x18, 0x30, 0x60, 0x00, 0x60, 0x60}, - {0x00, 0x1e, 0x63, 0x5d, 0x55, 0x57, 0x5e, 0x62}, - {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, - {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, - {0x00, 0x7c, 0x6e, 0x66, 0x66, 0x66, 0x6e, 0x7c}, - {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, - {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x60}, - {0x00, 0x3c, 0x62, 0xc0, 0xce, 0xc6, 0x66, 0x3e}, - {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x6e, 0x7c, 0x78, 0x70, 0x78, 0x6c, 0x66}, - {0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7c}, - {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, - {0x00, 0x66, 0x76, 0x76, 0x7e, 0x7e, 0x6e, 0x6e}, - {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, - {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, - {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, - {0x00, 0x78, 0x6c, 0x6c, 0x78, 0x6c, 0x6c, 0x66}, - {0x00, 0x78, 0x68, 0x60, 0x78, 0x0c, 0x4c, 0x78}, - {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0x3c}, - {0x00, 0xc6, 0xc6, 0x6c, 0x6c, 0x78, 0x38, 0x38}, - {0x00, 0xcc, 0xcc, 0x7d, 0x7f, 0x77, 0x73, 0x33}, - {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, - {0x00, 0xcc, 0x6c, 0x78, 0x38, 0x30, 0x30, 0x30}, - {0x00, 0xfc, 0x1c, 0x18, 0x30, 0x70, 0x60, 0xfc}, - {0x70, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x70}, - {0x00, 0x80, 0xc0, 0x40, 0x40, 0x60, 0x20, 0x20}, - {0xe0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe0}, - {0x00, 0x38, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x40, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, - {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, - {0x0c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, - {0x70, 0x60, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, - {0x40, 0x40, 0x40, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, - {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x40, 0x40, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x40, 0x40, 0x40, 0x4c, 0x78, 0x70, 0x78, 0x4c}, - {0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x00, 0x00, 0x00, 0x7f, 0x6d, 0x4d, 0x4d, 0x4d}, - {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x4c, 0x4c}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0xcc, 0x7c}, - {0x00, 0x00, 0x00, 0x78, 0x60, 0x40, 0x40, 0x40}, - {0x00, 0x00, 0x00, 0x78, 0xe0, 0x78, 0x18, 0xf8}, - {0x00, 0x00, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x70}, - {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x6c, 0x7c}, - {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x70, 0x30}, - {0x00, 0x00, 0x00, 0xdb, 0x5b, 0x7e, 0x7e, 0x76}, - {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, - {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, - {0x00, 0x00, 0x00, 0xf8, 0x38, 0x30, 0x60, 0xf8}, - {0x18, 0x30, 0x30, 0x70, 0x30, 0x30, 0x30, 0x18}, - {0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40}, - {0x70, 0x30, 0x30, 0x18, 0x30, 0x30, 0x30, 0x70}, - {0x00, 0x00, 0x00, 0x00, 0x72, 0x1c, 0x00, 0x00}, - {0x00, 0x38, 0x38, 0x78, 0x6c, 0x6c, 0xfe, 0xc6}, - {0x00, 0x7c, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x78, 0x6c, 0x6c, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x7c, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60}, - {0x00, 0x3e, 0x36, 0x36, 0x36, 0x26, 0x66, 0xff}, - {0x00, 0x7c, 0x60, 0x60, 0x78, 0x60, 0x60, 0x7c}, - {0x00, 0x64, 0x35, 0x3f, 0x3f, 0x3f, 0x64, 0xc4}, - {0x00, 0x78, 0x0c, 0x0c, 0x38, 0x0c, 0x0c, 0xf8}, - {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, - {0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x76, 0x76, 0x66}, - {0x00, 0x66, 0x6c, 0x78, 0x78, 0x7c, 0x6c, 0x66}, - {0x00, 0x3e, 0x36, 0x36, 0x36, 0x36, 0x66, 0xc6}, - {0x00, 0x63, 0x77, 0x77, 0x7f, 0x7f, 0x6b, 0x63}, - {0x00, 0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66}, - {0x00, 0x3c, 0x66, 0xc6, 0xc6, 0xc6, 0x66, 0x3c}, - {0x00, 0x7e, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}, - {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x60, 0x60, 0x60}, - {0x00, 0x3c, 0x64, 0xc0, 0xc0, 0xc0, 0x64, 0x3c}, - {0x00, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, - {0x00, 0xc6, 0x6c, 0x7c, 0x38, 0x38, 0x30, 0x70}, - {0x00, 0x18, 0x7e, 0x7b, 0xd9, 0x7b, 0x7e, 0x18}, - {0x00, 0xcc, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, - {0x00, 0x66, 0x66, 0x66, 0x7e, 0x06, 0x06, 0x06}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, - {0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7f}, - {0x00, 0x70, 0xf0, 0x30, 0x3e, 0x3b, 0x3b, 0x3e}, - {0x00, 0x61, 0x61, 0x61, 0x7d, 0x6d, 0x6d, 0x7d}, - {0x00, 0x60, 0x60, 0x60, 0x7c, 0x6c, 0x6c, 0x7c}, - {0x00, 0x70, 0xf8, 0x0c, 0x7c, 0x0c, 0x1c, 0x78}, - {0x00, 0x67, 0x6c, 0x78, 0x78, 0x78, 0x6c, 0x67}, - {0x00, 0x7c, 0x6c, 0x6c, 0x7c, 0x3c, 0x6c, 0x6c}, - {0x00, 0x00, 0x00, 0x78, 0x08, 0x78, 0xd8, 0x78}, - {0x38, 0x40, 0xc0, 0xf8, 0xec, 0xcc, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x48, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x40, 0x40, 0x40, 0x40}, - {0x00, 0x00, 0x00, 0x3c, 0x2c, 0x6c, 0x6c, 0xfe}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x7c}, - {0x00, 0x00, 0x00, 0x6b, 0x3e, 0x3e, 0x7f, 0xc9}, - {0x00, 0x00, 0x00, 0x70, 0x18, 0x70, 0x18, 0xf0}, - {0x00, 0x00, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, - {0x00, 0x30, 0x00, 0x5c, 0x7c, 0x7c, 0x6c, 0x6c}, - {0x00, 0x00, 0x00, 0x58, 0x70, 0x70, 0x78, 0x4c}, - {0x00, 0x00, 0x00, 0x7c, 0x6c, 0x6c, 0x6c, 0xcc}, - {0x00, 0x00, 0x00, 0x6e, 0x6e, 0x7e, 0x7e, 0x46}, - {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x7c, 0x4c, 0x4c}, - {0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78}, - {0x00, 0x00, 0x00, 0x7c, 0x4c, 0x4c, 0x4c, 0x4c}, - {0x00, 0x00, 0x00, 0x78, 0x6c, 0x4c, 0x6c, 0x78}, - {0x00, 0x00, 0x00, 0x78, 0x60, 0xc0, 0x60, 0x78}, - {0x00, 0x00, 0x00, 0xf8, 0x30, 0x30, 0x30, 0x30}, - {0x00, 0x00, 0x00, 0xcc, 0x48, 0x78, 0x78, 0x30}, - {0x08, 0x08, 0x08, 0x7f, 0x7b, 0xc9, 0x7b, 0x7f}, - {0x00, 0x00, 0x00, 0xd8, 0x78, 0x30, 0x78, 0xc8}, - {0x00, 0x00, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x7c}, - {0x00, 0x00, 0x00, 0xd8, 0xd8, 0x78, 0x18, 0x18}, - {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, - {0x00, 0x00, 0x00, 0x4d, 0x4d, 0x4d, 0x4d, 0x7f}, - {0x00, 0x00, 0x00, 0xf0, 0x30, 0x3c, 0x34, 0x3c}, - {0x00, 0x00, 0x00, 0x43, 0x43, 0x7b, 0x4f, 0x7b}, - {0x00, 0x00, 0x00, 0x40, 0x40, 0x78, 0x48, 0x78}, - {0x00, 0x00, 0x00, 0x70, 0x18, 0x78, 0x18, 0x70}, - {0x00, 0x00, 0x00, 0x4e, 0x5b, 0x79, 0x5b, 0x4e}, - {0x00, 0x00, 0x00, 0x78, 0x58, 0x78, 0x78, 0xd8}, -}; - -static int bar_glyph_index(uint32_t codepoint) { - if (codepoint >= 32 && codepoint < 127) { - return static_cast(codepoint) - 32; - } - if (codepoint >= 0x410 && codepoint <= 0x44F) { - return 95 + static_cast(codepoint - 0x410); - } - if (codepoint == 0x401) { - return 95 + 6; - } - if (codepoint == 0x451) { - return 95 + 37; - } - return -1; +const std::string& WaylandWindow::getTitle() const { + return title; } -static std::vector decode_utf8(const std::string& text) { - std::vector codepoints; - for (size_t i = 0; i < text.size();) { - const uint8_t byte = static_cast(text[i]); - uint32_t codepoint = byte; - size_t length = 1; - if ((byte & 0xE0) == 0xC0) { - codepoint = byte & 0x1F; - length = 2; - } else if ((byte & 0xF0) == 0xE0) { - codepoint = byte & 0x0F; - length = 3; - } else if ((byte & 0xF8) == 0xF0) { - codepoint = byte & 0x07; - length = 4; - } - if (i + length > text.size()) { - break; - } - for (size_t k = 1; k < length; k++) { - codepoint = - (codepoint << 6) | (static_cast(text[i + k]) & 0x3F); - } - codepoints.push_back(codepoint); - i += length; - } - return codepoints; +int WaylandWindow::getDecorationHeight() const { + return barVisible() ? BAR_HEIGHT : 0; } - -static void push_quad( - std::vector& target, float x, float y, float w, float h, float u0, - float v0, float u1, float v1, const glm::vec4& color -) { - const float x1 = x + w; - const float y1 = y + h; - const float vertices[] { - x, y, u0, v0, color.r, color.g, color.b, color.a, - x1, y, u1, v0, color.r, color.g, color.b, color.a, - x, y1, u0, v1, color.r, color.g, color.b, color.a, - x1, y, u1, v0, color.r, color.g, color.b, color.a, - x1, y1, u1, v1, color.r, color.g, color.b, color.a, - x, y1, u0, v1, color.r, color.g, color.b, color.a - }; - target.insert(target.end(), vertices, vertices + 48); -} - -bool WaylandWindow::isIconSupported() const { - return true; -} - -void WaylandWindow::setIcon(const ImageData* image) { - if (image == nullptr || image->getData() == nullptr) { - return; - } - iconWidth = static_cast(image->getWidth()); - iconHeight = static_cast(image->getHeight()); - if (iconWidth <= 0 || iconHeight <= 0) { - return; - } - const size_t pixels = static_cast(iconWidth) * iconHeight; - const bool alpha = image->getFormat() == ImageFormat::RGBA8888; - iconPixels.resize(pixels * 4); - for (size_t i = 0; i < pixels; i++) { - iconPixels[i * 4] = image->getData()[i * (alpha ? 4 : 3)]; - iconPixels[i * 4 + 1] = image->getData()[i * (alpha ? 4 : 3) + 1]; - iconPixels[i * 4 + 2] = image->getData()[i * (alpha ? 4 : 3) + 2]; - iconPixels[i * 4 + 3] = alpha ? image->getData()[i * 4 + 3] : 255; - } - if (barIconTexture != 0) { - glDeleteTextures(1, &barIconTexture); - barIconTexture = 0; - } +int WaylandWindow::getDecorationHoveredButton() const { + return hoveredButton; } void WaylandWindow::enableOwnDecorations() { @@ -275,234 +29,6 @@ bool WaylandWindow::barVisible() const { return barEnabled && !fullscreen && Window::mode != WindowMode::BORDERLESS; } -void WaylandWindow::initBarRenderer() { - if (barProgram != 0) { - return; - } - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "layout(location = 1) in vec2 aUv;\n" - "layout(location = 2) in vec4 aColor;\n" - "uniform vec2 uViewport;\n" - "out vec2 vUv;\n" - "out vec4 vColor;\n" - "void main() {\n" - " vec2 ndc = vec2(aPos.x / uViewport.x * 2.0 - 1.0," - " 1.0 - aPos.y / uViewport.y * 2.0);\n" - " gl_Position = vec4(ndc, 0.0, 1.0);\n" - " vUv = aUv;\n" - " vColor = aColor;\n" - "}\n"; - static const char* fragmentSource = - "#version 330 core\n" - "in vec2 vUv;\n" - "in vec4 vColor;\n" - "out vec4 outColor;\n" - "uniform sampler2D uTexture;\n" - "uniform int uMode;\n" - "void main() {\n" - " if (uMode == 1) {\n" - " outColor = vec4(vColor.rgb," - " vColor.a * texture(uTexture, vUv).r);\n" - " } else if (uMode == 2) {\n" - " outColor = texture(uTexture, vUv) * vColor;\n" - " } else {\n" - " outColor = vColor;\n" - " }\n" - "}\n"; - barProgram = compile_program(vertexSource, fragmentSource); - barViewportLoc = glGetUniformLocation(barProgram, "uViewport"); - barTextureLoc = glGetUniformLocation(barProgram, "uTexture"); - barModeLoc = glGetUniformLocation(barProgram, "uMode"); - glGenVertexArrays(1, &barVao); - glGenBuffers(1, &barVbo); - glBindVertexArray(barVao); - glBindBuffer(GL_ARRAY_BUFFER, barVbo); - glEnableVertexAttribArray(0); - glVertexAttribPointer( - 0, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), nullptr - ); - glEnableVertexAttribArray(1); - glVertexAttribPointer( - 1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), - reinterpret_cast(2 * sizeof(float)) - ); - glEnableVertexAttribArray(2); - glVertexAttribPointer( - 2, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), - reinterpret_cast(4 * sizeof(float)) - ); - glBindVertexArray(0); - glGenTextures(1, &barFontTexture); - glBindTexture(GL_TEXTURE_2D, barFontTexture); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - std::vector pixels(BAR_GLYPHS * BAR_FONT_W * BAR_FONT_H, 0); - for (int glyph = 0; glyph < BAR_GLYPHS; glyph++) { - for (int y = 0; y < BAR_FONT_H; y++) { - for (int x = 0; x < BAR_FONT_W; x++) { - if (BAR_FONT[glyph][y] & (1 << (7 - x))) { - pixels[y * BAR_GLYPHS * BAR_FONT_W + glyph * BAR_FONT_W + x] = - 255; - } - } - } - } - glTexImage2D( - GL_TEXTURE_2D, 0, GL_R8, BAR_GLYPHS * BAR_FONT_W, BAR_FONT_H, 0, - GL_RED, GL_UNSIGNED_BYTE, pixels.data() - ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindTexture(GL_TEXTURE_2D, 0); -} - -void WaylandWindow::initBarIconTexture() { - if (iconPixels.empty() || barIconTexture != 0) { - return; - } - glGenTextures(1, &barIconTexture); - glBindTexture(GL_TEXTURE_2D, barIconTexture); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D( - GL_TEXTURE_2D, 0, GL_RGBA8, iconWidth, iconHeight, 0, GL_RGBA, - GL_UNSIGNED_BYTE, iconPixels.data() - ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindTexture(GL_TEXTURE_2D, 0); -} - -void WaylandWindow::barDrawText( - float x, float y, const std::vector& codepoints, int maxChars, - const glm::vec4& color -) { - const float step = 1.0f / static_cast(BAR_GLYPHS * BAR_FONT_W); - float cursor = x; - for (int i = 0; i < static_cast(codepoints.size()) && i < maxChars; i++) { - const int index = bar_glyph_index(codepoints[i]); - if (index >= 0) { - push_quad( - barText, cursor, y, BAR_FONT_W, BAR_FONT_H, - index * BAR_FONT_W * step, 0.0f, - (index * BAR_FONT_W + BAR_FONT_W) * step, 1.0f, color - ); - } - cursor += BAR_FONT_W; - } -} - -void WaylandWindow::barDrawBatch(const std::vector& data, int mode, GLuint texture) { - if (data.empty()) { - return; - } - glUniform1i(barModeLoc, mode); - glBindTexture(GL_TEXTURE_2D, texture); - glBufferData( - GL_ARRAY_BUFFER, data.size() * sizeof(float), data.data(), - GL_STREAM_DRAW - ); - glDrawArrays(GL_TRIANGLES, 0, static_cast(data.size() / 8)); -} - -void WaylandWindow::barFlush() { - glUseProgram(barProgram); - glUniform2f( - barViewportLoc, static_cast(size.x), static_cast(size.y) - ); - glDisable(GL_DEPTH_TEST); - glDisable(GL_CULL_FACE); - glDisable(GL_SCISSOR_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glBindVertexArray(barVao); - glBindBuffer(GL_ARRAY_BUFFER, barVbo); - glActiveTexture(GL_TEXTURE0); - glUniform1i(barTextureLoc, 0); - barDrawBatch(barRects, 0, barFontTexture); - barDrawBatch(barIcons, 2, barIconTexture); - barDrawBatch(barText, 1, barFontTexture); - glBindVertexArray(0); - glDisable(GL_BLEND); -} - -void WaylandWindow::drawBar() { - if (!barVisible()) { - return; - } - initBarRenderer(); - initBarIconTexture(); - barRects.clear(); - barText.clear(); - barIcons.clear(); - - const float width = static_cast(size.x); - const float height = static_cast(BAR_HEIGHT); - const glm::vec4 background(0.16f, 0.16f, 0.17f, 1.0f); - const glm::vec4 border(0.09f, 0.09f, 0.10f, 1.0f); - const glm::vec4 ink(0.87f, 0.87f, 0.88f, 1.0f); - const glm::vec4 hover(0.27f, 0.27f, 0.29f, 1.0f); - const glm::vec4 closeHover(0.72f, 0.16f, 0.11f, 1.0f); - - push_quad(barRects, 0, 0, width, height, 0, 0, 0, 0, background); - push_quad(barRects, 0, height - 1, width, 1, 0, 0, 0, 0, border); - - float textX = 10.0f; - if (barIconTexture != 0 && iconWidth > 0) { - push_quad( - barIcons, 7, (height - BAR_ICON_SIZE) * 0.5f, BAR_ICON_SIZE, - BAR_ICON_SIZE, 0, 1, 1, 0, glm::vec4(1.0f) - ); - textX = 7 + BAR_ICON_SIZE + 8; - } - const float buttonsX = width - BAR_BUTTON * 3; - const int maxChars = - static_cast((buttonsX - 8 - textX) / BAR_FONT_W); - if (maxChars > 0) { - barDrawText( - textX, (height - BAR_FONT_H) * 0.5f, decode_utf8(title), - maxChars, ink - ); - } - - for (int i = 0; i < 3; i++) { - const float bx = width - BAR_BUTTON * (i + 1); - if (hoveredButton == i) { - push_quad( - barRects, bx, 0, BAR_BUTTON, height - 1, 0, 0, 0, 0, - i == 0 ? closeHover : hover - ); - } - const float cx = bx + BAR_BUTTON * 0.5f; - const float cy = height * 0.5f; - if (i == 0) { - for (int s = 0; s < 7; s++) { - push_quad(barRects, cx - 4 + s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 3 - s, cy - 4 + s, 1.6f, 1.6f, 0, 0, 0, 0, ink); - } - } else if (i == 1 && !maximized) { - push_quad(barRects, cx - 4.5f, cy - 4.5f, 9, 1.6f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 4.5f, cy + 2.9f, 9, 1.6f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 4.5f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 2.9f, cy - 4.5f, 1.6f, 9, 0, 0, 0, 0, ink); - } else if (i == 1) { - push_quad(barRects, cx - 3.5f, cy - 5.5f, 8, 1.4f, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 3.1f, cy - 5.5f, 1.4f, 5.5f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 5.5f, cy - 1.2f, 8, 1.4f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 5.5f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); - push_quad(barRects, cx + 1.1f, cy - 1.2f, 1.4f, 6.2f, 0, 0, 0, 0, ink); - push_quad(barRects, cx - 5.5f, cy + 3.6f, 8, 1.4f, 0, 0, 0, 0, ink); - } else { - push_quad(barRects, cx - 5, cy - 0.8f, 10, 1.6f, 0, 0, 0, 0, ink); - } - } - barFlush(); -} - int WaylandWindow::barButtonAt(double x, double y) const { if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { return -1; diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp index 5da49c6e0..5ea51bbae 100644 --- a/src/window/wayland/WaylandCommon.cpp +++ b/src/window/wayland/WaylandCommon.cpp @@ -6,6 +6,78 @@ debug::Logger waylandLogger("window"); +GlStateGuard::GlStateGuard() { + glGetIntegerv(GL_CURRENT_PROGRAM, &values[0]); + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &values[1]); + glGetIntegerv(GL_ACTIVE_TEXTURE, &values[2]); + glGetIntegerv(GL_TEXTURE_BINDING_2D, &values[3]); + glGetIntegerv(GL_UNPACK_ALIGNMENT, &values[4]); + glGetIntegerv(GL_BLEND_SRC_RGB, &values[5]); + glGetIntegerv(GL_BLEND_DST_RGB, &values[6]); + glGetIntegerv(GL_BLEND_SRC_ALPHA, &values[7]); + glGetIntegerv(GL_BLEND_DST_ALPHA, &values[8]); + glGetIntegerv(GL_BLEND_EQUATION_RGB, &values[9]); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &values[10]); + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &values[11]); + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &values[12]); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &values[13]); + glGetIntegerv(GL_DEPTH_WRITEMASK, &values[14]); + glGetIntegerv(GL_VIEWPORT, viewport); + glGetIntegerv(GL_COLOR_WRITEMASK, colorMask); + for (int i = 0; i < 3; i++) { + attribFlags[i] = glIsEnabled(GL_VERTEX_ATTRIB_ARRAY_ENABLED + i); + glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &attribs[i][0]); + glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &attribs[i][1]); + glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &attribs[i][2]); + glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &attribs[i][3]); + glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][5]); + void* pointer = nullptr; + glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer); + attribs[i][6] = static_cast(reinterpret_cast(pointer)); + } + flags[0] = glIsEnabled(GL_BLEND); + flags[1] = glIsEnabled(GL_DEPTH_TEST); + flags[2] = glIsEnabled(GL_CULL_FACE); + flags[3] = glIsEnabled(GL_SCISSOR_TEST); +} + +GlStateGuard::~GlStateGuard() { + glUseProgram(values[0]); + glBindVertexArray(values[1]); + glActiveTexture(values[2]); + glBindTexture(GL_TEXTURE_2D, values[3]); + glPixelStorei(GL_UNPACK_ALIGNMENT, values[4]); + glBlendFuncSeparate(values[5], values[6], values[7], values[8]); + glBlendEquationSeparate(values[9], values[10]); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, values[12]); + glBindFramebuffer(GL_READ_FRAMEBUFFER, values[13]); + glDepthMask(values[14]); + glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]); + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + const GLenum cap[] {GL_BLEND, GL_DEPTH_TEST, GL_CULL_FACE, GL_SCISSOR_TEST}; + for (int i = 0; i < 4; i++) { + if (flags[i]) { + glEnable(cap[i]); + } else { + glDisable(cap[i]); + } + } + for (int i = 0; i < 3; i++) { + glBindBuffer(GL_ARRAY_BUFFER, static_cast(attribs[i][5])); + glVertexAttribPointer( + i, attribs[i][0], static_cast(attribs[i][1]), + attribs[i][2], attribs[i][3], + reinterpret_cast(static_cast(attribs[i][6])) + ); + if (attribFlags[i]) { + glEnableVertexAttribArray(i); + } else { + glDisableVertexAttribArray(i); + } + } + glBindBuffer(GL_ARRAY_BUFFER, static_cast(values[11])); +} + GLuint compile_program(const char* vertexSource, const char* fragmentSource) { GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, nullptr); diff --git a/src/window/wayland/WaylandCommon.hpp b/src/window/wayland/WaylandCommon.hpp index 6bbb5df1e..3407a0ef1 100644 --- a/src/window/wayland/WaylandCommon.hpp +++ b/src/window/wayland/WaylandCommon.hpp @@ -37,6 +37,17 @@ const wl_data_device_listener& data_device_listener(); const xdg_surface_listener& surface_listener(); const xdg_toplevel_listener& toplevel_listener(); +struct GlStateGuard { + GLint values[16] {}; + GLint attribs[3][7] {}; + GLint viewport[4] {}; + GLint colorMask[4] {}; + GLboolean flags[6] {}; + GLboolean attribFlags[3] {}; + GlStateGuard(); + ~GlStateGuard(); +}; + GLuint compile_program(const char* vertexSource, const char* fragmentSource); extern debug::Logger waylandLogger; diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index 51c8a86b5..f24b0a5f8 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -43,21 +43,6 @@ WaylandWindow::~WaylandWindow() { if (stretchVao) { glDeleteVertexArrays(1, &stretchVao); } - if (barFontTexture) { - glDeleteTextures(1, &barFontTexture); - } - if (barIconTexture) { - glDeleteTextures(1, &barIconTexture); - } - if (barProgram) { - glDeleteProgram(barProgram); - } - if (barVbo) { - glDeleteBuffers(1, &barVbo); - } - if (barVao) { - glDeleteVertexArrays(1, &barVao); - } if (state.dataDevice) { wl_data_device_destroy(state.dataDevice); } @@ -109,7 +94,6 @@ void WaylandWindow::swapBuffers() { } else { cacheContent(); } - drawBar(); requestFrame(); eglSwapBuffers(eglDisplay, eglSurface); resetScissor(); @@ -363,12 +347,16 @@ void WaylandWindow::resetScissor() { std::unique_ptr WaylandWindow::takeScreenshot() { glBindFramebuffer(GL_FRAMEBUFFER, 0); + GLint readBuffer = 0; + glGetIntegerv(GL_READ_BUFFER, &readBuffer); + glReadBuffer(GL_FRONT); auto data = std::make_unique(size.x * size.y * 3); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); return std::make_unique( ImageFormat::RGB888, size.x, size.y, data.release() ); + glReadBuffer(static_cast(readBuffer)); } void WaylandWindow::setFramerate(int framerate) { @@ -445,6 +433,7 @@ void WaylandWindow::resizeCache(int width, int height) { } void WaylandWindow::cacheContent() { + GlStateGuard state; if (stretchProgram == 0) { return; } @@ -460,6 +449,7 @@ void WaylandWindow::cacheContent() { } void WaylandWindow::drawStretched() { + GlStateGuard state; glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, size.x, size.y); glDisable(GL_DEPTH_TEST); diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 76c426399..1df0e861d 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -37,24 +37,10 @@ static inline bool resizeLogging = getenv("VOXEL_LOG_RESIZE") != nullptr; bool barEnabled = false; bool fullscreen = false; std::string title = "VoxelCore"; -std::vector iconPixels; -int iconWidth = 0; -int iconHeight = 0; int hoveredButton = -1; double lastBarPress = 0.0; double pointerX = 0.0; double pointerY = 0.0; -GLuint barProgram = 0; -GLuint barVao = 0; -GLuint barVbo = 0; -GLuint barFontTexture = 0; -GLuint barIconTexture = 0; -GLint barViewportLoc = -1; -GLint barTextureLoc = -1; -GLint barModeLoc = -1; -std::vector barRects; -std::vector barText; -std::vector barIcons; bool frameOnCallback = false; double frameInterval = 0.0; double nextFrameTime = 0.0; @@ -111,10 +97,18 @@ glm::vec4 scissorArea {}; WindowMode getMode() const override; void focus() override; void setTitle(const std::string& title) override; + const std::string& getTitle() const override; + int getDecorationHeight() const override; + int getDecorationHoveredButton() const override; + + bool isIconSupported() const override { + return false; + } + + void setIcon(const ImageData*) override { + } void setFullscreen(bool enabled); void setMaximized(bool enabled); - bool isIconSupported() const override; - void setIcon(const ImageData* image) override; void resize(int width, int height); void onConfigure(int32_t width, int32_t height, wl_array* states); void applyConfigure(); @@ -129,13 +123,7 @@ glm::vec4 scissorArea {}; void drawStretched(); void enableOwnDecorations(); bool barVisible() const; - void initBarRenderer(); - void initBarIconTexture(); - void barDrawText( float x, float y, const std::vector& codepoints, int maxChars, const glm::vec4& color ); - void barDrawBatch(const std::vector& data, int mode, GLuint texture); - void barFlush(); - void drawBar(); - int barButtonAt(double x, double y) const; + int barButtonAt(double x, double y) const; uint32_t barEdgeAt(double x, double y) const; static CursorShape edgeCursor(uint32_t edges); bool handleBarMotion(double x, double y); From 14fa7e5fd2882df764d3a8af9cbd15d159bc0a08 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 01:20:42 +0300 Subject: [PATCH 05/35] fix building without the Wayland backend The backend sources live in window/wayland and were picked up by the global source glob, so a build with VOXELENGINE_WAYLAND=OFF (and any non-Linux build, where the option is skipped entirely) tried to compile them and failed on the generated protocol headers. They are now collected separately and added to the target only when the backend is enabled. Also restores the CRLF line endings of Engine.cpp, GUI.hpp and input.cpp, which were rewritten with LF and made their diffs look like whole-file rewrites. --- src/CMakeLists.txt | 7 +- src/engine/Engine.cpp | 962 ++++++++++++++++++++-------------------- src/graphics/ui/GUI.hpp | 386 ++++++++-------- src/window/input.cpp | 534 +++++++++++----------- 4 files changed, 947 insertions(+), 942 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3540fb3d2..6be8a91ea 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,6 +4,10 @@ file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp) file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) +file(GLOB_RECURSE wayland_sources + ${CMAKE_CURRENT_SOURCE_DIR}/window/wayland/*.cpp) +list(REMOVE_ITEM sources ${wayland_sources}) + add_library(VoxelCoreSrc STATIC ${sources} ${headers}) find_package(OpenGL REQUIRED) @@ -120,7 +124,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) # tablet is referenced by cursor-shape-v1 voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) - target_sources(VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES}) + target_sources( + VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) target_link_libraries( diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index 9f33892b9..4f39f9356 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,481 +1,481 @@ -#include "Engine.hpp" -#include "WindowBar.hpp" - -#ifndef GLEW_STATIC -#define GLEW_STATIC -#endif - -#include "AssetsManagement.hpp" -#include "audio/audio.hpp" -#include "coders/commons.hpp" -#include "coders/GLSLExtension.hpp" -#include "coders/toml.hpp" -#include "coders/vector_fonts.hpp" -#include "content/ContentControl.hpp" -#include "core_defs.hpp" -#include "debug/Logger.hpp" -#include "devtools/AppScriptsControl.hpp" -#include "devtools/DebuggingServer.hpp" -#include "devtools/Editor.hpp" -#include "devtools/Project.hpp" -#include "devtools/stdin_cmd_reader.hpp" -#include "EnginePaths.hpp" -#include "frontend/locale.hpp" -#include "frontend/menu.hpp" -#include "frontend/screens/Screen.hpp" -#include "graphics/core/DrawContext.hpp" -#include "graphics/core/Shader.hpp" -#include "graphics/ui/elements/Menu.hpp" -#include "graphics/ui/GUI.hpp" -#include "io/io.hpp" -#include "io/settings_io.hpp" -#include "logic/CommandsInterpreter.hpp" -#include "logic/EngineController.hpp" -#include "logic/scripting/scripting_hud.hpp" -#include "logic/scripting/scripting.hpp" -#include "Mainloop.hpp" -#include "network/Network.hpp" -#include "ServerMainloop.hpp" -#include "util/platform.hpp" -#include "util/stringutil.hpp" -#include "window/input.hpp" -#include "window/Window.hpp" -#include "WindowControl.hpp" -#include "world/Level.hpp" - -#include -#include -#include -#include - -static debug::Logger logger("engine"); - -Engine::Engine() = default; -Engine::~Engine() = default; - -static std::unique_ptr instance = nullptr; - -Engine& Engine::getInstance() { - if (!instance) { - instance = std::make_unique(); - } - return *instance; -} - -void Engine::onContentLoad() { - editor->loadTools(); - langs::setup(langs::get_current(), paths->resPaths.collectRoots()); - - if (isHeadless()) { - return; - } - for (auto& pack : content->getAllContentPacks()) { - auto configFolder = pack.folder / "config"; - auto bindsFile = configFolder / "bindings.toml"; - logger.info() << "loading bindings: " << bindsFile.string(); - if (io::is_regular_file(bindsFile)) { - input->getBindings().read( - toml::parse( - bindsFile.string(), io::read_string(bindsFile) - ), - BindType::BIND - ); - } - } - loadAssets(); -} - -void Engine::initializeClient() { - assets = std::make_unique(*this); - windowControl = std::make_unique(*this); - auto [window, input] = windowControl->initialize(); - - this->window = std::move(window); - this->input = std::move(input); - - loadControls(); - - gui = std::make_unique(*this); - if (ENGINE_DEBUG_BUILD) { - menus::create_version_label(*gui); - } - keepAlive(settings.display.windowMode.observe( - [this](int value) { - WindowMode mode = static_cast(value); - if (mode != this->window->getMode()) { - this->window->setMode(mode); - } - }, - true - )); - keepAlive(settings.debug.doTraceShaders.observe( - [](bool value) { - Shader::preprocessor->setTraceOutput(value); - }, - true - )); - - keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { - auto& menu = *gui->getMenu(); - if (menu.hasOpenPage() && menu.back()) { - return true; - } - return false; - })); -} - -void Engine::initialize(CoreParameters coreParameters) { - params = std::move(coreParameters); - settingsHandler = std::make_unique(settings); - - logger.info() << "engine version: " << ENGINE_VERSION_STRING; - if (params.headless) { - logger.info() << "engine runs in headless mode"; - } - if (params.projectFolder.empty()) { - params.projectFolder = params.resFolder; - } - paths = std::make_unique(params); - loadProject(); - paths->setupProject(*project); - - editor = std::make_unique(*this); - cmd = std::make_unique(); - - if (project->permissions.has(Permissions::NETWORK) || - !params.debugServerString.empty()) { - network = network::Network::create(settings.network); - } - - if (!params.debugServerString.empty()) { - try { - debuggingServer = std::make_unique( - *this, params.debugServerString - ); - } catch (const std::runtime_error& err) { - throw initialize_error( - "debugging server error: " + std::string(err.what()) - ); - } - } - loadSettings(); - - controller = std::make_unique(*this); - if (!params.headless) { - initializeClient(); - } - audio::initialize( - !params.headless, - project->permissions.has(Permissions::RECORD_AUDIO), - settings.audio - ); - - vector_fonts::initialize(); - - if (settings.ui.language.get() == "auto") { - settings.ui.language.set( - langs::locale_by_envlocale(platform::detect_locale()) - ); - } - content = std::make_unique( - *project, *paths, input.get(), [this]() { onContentLoad(); } - ); - scripting::initialize(*this); - - if (!isHeadless()) { - gui->getMenu()->setPageLoader(scripting::create_page_loader()); - } - keepAlive(settings.ui.language.observe([this](auto lang) { - langs::setup(lang, paths->resPaths.collectRoots()); - }, true)); - - keepAlive(settings.audio.inputDevice.observe([](auto name) { - audio::set_input_device(name == "auto" ? "" : name); - })); - - appScripts = std::make_unique(params); - - if (params.stdinCommands) { - cmd::start_stdin_cmd_reader(*this); - } -} - -void Engine::loadSettings() { - io::path settings_file = EnginePaths::SETTINGS_FILE; - if (io::is_regular_file(settings_file)) { - logger.info() << "loading settings"; - std::string text = io::read_string(settings_file); - try { - toml::parse(*settingsHandler, settings_file.string(), text); - } catch (const parsing_error& err) { - logger.error() << err.errorLog(); - throw; - } - } -} - -void Engine::loadControls() { - io::path controls_file = EnginePaths::CONTROLS_FILE; - if (io::is_regular_file(controls_file)) { - logger.info() << "loading controls"; - std::string text = io::read_string(controls_file); - input->getBindings().read( - toml::parse(controls_file.string(), text), BindType::BIND - ); - } -} - -void Engine::updateHotkeys() { - if (input->jpressed(Keycode::F2)) { - windowControl->saveScreenshot(); - } - if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && - input->jpressed(Keycode::U)) { - gui->toggleDebug(); - } - if (input->jpressed(Keycode::F11)) { - windowControl->toggleFullscreen(); - } -} - -void Engine::run() { - if (params.headless) { - ServerMainloop(*this).run(); - } else { - Mainloop(*this).run(); - } -} - -void Engine::postUpdate() { - if (network) { - network->update(); - } - postRunnables.run(); - scripting::process_post_runnables(); - - if (debuggingServer) { - debuggingServer->update(); - } -} - -void Engine::detachDebugger() { - debuggingServer.reset(); -} - -void Engine::applicationTick() { - appScripts->tick(); -} - -void Engine::updateFrontend() { - double delta = time.getDelta(); - assets->update(); - updateHotkeys(); - audio::update(delta); - gui->act(delta, window->getSize()); - screen->update(delta); - gui->postAct(); -} - -void Engine::nextFrame(bool waitForRefresh) { - windowControl->nextFrame(waitForRefresh); -} - -void Engine::startPauseLoop() { - assert (network != nullptr); - - bool initialCursorLocked = false; - if (!isHeadless()) { - initialCursorLocked = input->isCursorLocked(); - if (initialCursorLocked) { - input->toggleCursor(); - } - } - while (!isQuitSignal() && debuggingServer) { - network->update(); - if (debuggingServer->update()) { - break; - } - if (isHeadless()) { - platform::sleep(1.0 / params.tps * 1000); - } else { - nextFrame(false); - } - } - if (initialCursorLocked) { - input->toggleCursor(); - } -} - -void Engine::renderFrame() { - if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { - input->toggleCursor(); - } - screen->draw(time.getDelta()); - - DrawContext ctx(nullptr, *window, nullptr); - gui->draw(ctx, *assets->getStorage()); - draw_window_bar(*this); -} - -void Engine::saveSettings() { - logger.info() << "saving settings"; - io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); - if (!params.headless) { - logger.info() << "saving bindings"; - if (input) { - io::write_string( - EnginePaths::CONTROLS_FILE, input->getBindings().write() - ); - } - } -} - -void Engine::close() { - saveSettings(); - logger.info() << "shutting down"; - if (screen) { - screen->onEngineShutdown(); - screen.reset(); - } - content.reset(); - assets.reset(); - cmd.reset(); - if (gui) { - gui.reset(); - logger.info() << "gui finished"; - } - if (!isHeadless()) { - vector_fonts::finalize(); - } - audio::close(); - debuggingServer.reset(); - network.reset(); - clearKeepedObjects(); - project.reset(); - appScripts.reset(); - scripting::close(); - logger.info() << "scripting finished"; - if (!params.headless) { - window.reset(); - logger.info() << "window closed"; - } - logger.info() << "engine finished"; -} - -void Engine::terminate() { - instance->close(); - instance.reset(); -} - -EngineController* Engine::getController() { - return controller.get(); -} - -void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { - this->levelConsumer = std::move(levelConsumer); -} - -void Engine::loadAssets() { - assets->loadAssets(content->get()); -} - -void Engine::loadProject() { - io::path projectFile = "project:project.toml"; - project = std::make_unique(); - project->path = "project:"; - project->deserialize(io::read_object(projectFile)); - logger.info() << "loaded project " << util::quote(project->name); -} - -void Engine::setScreen(std::shared_ptr screen) { - if (this->screen) { - appScripts->onScreenChange(this->screen->getName(), false); - } - // reset audio channels (stop all sources) - audio::reset_channel(audio::get_channel_index("regular")); - audio::reset_channel(audio::get_channel_index("ambient")); - this->screen = std::move(screen); - if (this->screen) { - this->screen->onOpen(); - } - if (this->screen) { - appScripts->onScreenChange(this->screen->getName(), true); - window->setShouldRefresh(); - } -} - -void Engine::onWorldOpen(std::unique_ptr level, int64_t localPlayer) { - logger.info() << "world open"; - levelConsumer(std::move(level), localPlayer); -} - -void Engine::onWorldClosed() { - logger.info() << "world closed"; - levelConsumer(nullptr, -1); -} - -void Engine::quit() { - logger.info() << "quitSignal set to true"; - quitSignal = true; - if (!isHeadless()) { - window->setShouldClose(true); - } -} - -bool Engine::isQuitSignal() const { - return quitSignal; -} - -EngineSettings& Engine::getSettings() { - return settings; -} - -Assets* Engine::getAssets() { - return assets ? assets->getStorage() : nullptr; -} - -Assets& Engine::requireAssets() { - if (isHeadless()) { - throw std::runtime_error("assets are not available in headless mode"); - } - return *assets->getStorage(); -} - -AssetsLoader& Engine::acquireBackgroundLoader() { - if (isHeadless()) { - throw std::runtime_error("assets are not available in headless mode"); - } - return assets->acquireBackgroundLoader(); -} - -EnginePaths& Engine::getPaths() { - return *paths; -} - -ResPaths& Engine::getResPaths() { - return paths->resPaths; -} - -std::shared_ptr Engine::getScreen() { - return screen; -} - -SettingsHandler& Engine::getSettingsHandler() { - return *settingsHandler; -} - -Time& Engine::getTime() { - return time; -} - -const CoreParameters& Engine::getCoreParameters() const { - return params; -} - -bool Engine::isHeadless() const { - return params.headless; -} - -ContentControl& Engine::getContentControl() { - return *content; -} +#include "Engine.hpp" +#include "WindowBar.hpp" + +#ifndef GLEW_STATIC +#define GLEW_STATIC +#endif + +#include "AssetsManagement.hpp" +#include "audio/audio.hpp" +#include "coders/commons.hpp" +#include "coders/GLSLExtension.hpp" +#include "coders/toml.hpp" +#include "coders/vector_fonts.hpp" +#include "content/ContentControl.hpp" +#include "core_defs.hpp" +#include "debug/Logger.hpp" +#include "devtools/AppScriptsControl.hpp" +#include "devtools/DebuggingServer.hpp" +#include "devtools/Editor.hpp" +#include "devtools/Project.hpp" +#include "devtools/stdin_cmd_reader.hpp" +#include "EnginePaths.hpp" +#include "frontend/locale.hpp" +#include "frontend/menu.hpp" +#include "frontend/screens/Screen.hpp" +#include "graphics/core/DrawContext.hpp" +#include "graphics/core/Shader.hpp" +#include "graphics/ui/elements/Menu.hpp" +#include "graphics/ui/GUI.hpp" +#include "io/io.hpp" +#include "io/settings_io.hpp" +#include "logic/CommandsInterpreter.hpp" +#include "logic/EngineController.hpp" +#include "logic/scripting/scripting_hud.hpp" +#include "logic/scripting/scripting.hpp" +#include "Mainloop.hpp" +#include "network/Network.hpp" +#include "ServerMainloop.hpp" +#include "util/platform.hpp" +#include "util/stringutil.hpp" +#include "window/input.hpp" +#include "window/Window.hpp" +#include "WindowControl.hpp" +#include "world/Level.hpp" + +#include +#include +#include +#include + +static debug::Logger logger("engine"); + +Engine::Engine() = default; +Engine::~Engine() = default; + +static std::unique_ptr instance = nullptr; + +Engine& Engine::getInstance() { + if (!instance) { + instance = std::make_unique(); + } + return *instance; +} + +void Engine::onContentLoad() { + editor->loadTools(); + langs::setup(langs::get_current(), paths->resPaths.collectRoots()); + + if (isHeadless()) { + return; + } + for (auto& pack : content->getAllContentPacks()) { + auto configFolder = pack.folder / "config"; + auto bindsFile = configFolder / "bindings.toml"; + logger.info() << "loading bindings: " << bindsFile.string(); + if (io::is_regular_file(bindsFile)) { + input->getBindings().read( + toml::parse( + bindsFile.string(), io::read_string(bindsFile) + ), + BindType::BIND + ); + } + } + loadAssets(); +} + +void Engine::initializeClient() { + assets = std::make_unique(*this); + windowControl = std::make_unique(*this); + auto [window, input] = windowControl->initialize(); + + this->window = std::move(window); + this->input = std::move(input); + + loadControls(); + + gui = std::make_unique(*this); + if (ENGINE_DEBUG_BUILD) { + menus::create_version_label(*gui); + } + keepAlive(settings.display.windowMode.observe( + [this](int value) { + WindowMode mode = static_cast(value); + if (mode != this->window->getMode()) { + this->window->setMode(mode); + } + }, + true + )); + keepAlive(settings.debug.doTraceShaders.observe( + [](bool value) { + Shader::preprocessor->setTraceOutput(value); + }, + true + )); + + keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { + auto& menu = *gui->getMenu(); + if (menu.hasOpenPage() && menu.back()) { + return true; + } + return false; + })); +} + +void Engine::initialize(CoreParameters coreParameters) { + params = std::move(coreParameters); + settingsHandler = std::make_unique(settings); + + logger.info() << "engine version: " << ENGINE_VERSION_STRING; + if (params.headless) { + logger.info() << "engine runs in headless mode"; + } + if (params.projectFolder.empty()) { + params.projectFolder = params.resFolder; + } + paths = std::make_unique(params); + loadProject(); + paths->setupProject(*project); + + editor = std::make_unique(*this); + cmd = std::make_unique(); + + if (project->permissions.has(Permissions::NETWORK) || + !params.debugServerString.empty()) { + network = network::Network::create(settings.network); + } + + if (!params.debugServerString.empty()) { + try { + debuggingServer = std::make_unique( + *this, params.debugServerString + ); + } catch (const std::runtime_error& err) { + throw initialize_error( + "debugging server error: " + std::string(err.what()) + ); + } + } + loadSettings(); + + controller = std::make_unique(*this); + if (!params.headless) { + initializeClient(); + } + audio::initialize( + !params.headless, + project->permissions.has(Permissions::RECORD_AUDIO), + settings.audio + ); + + vector_fonts::initialize(); + + if (settings.ui.language.get() == "auto") { + settings.ui.language.set( + langs::locale_by_envlocale(platform::detect_locale()) + ); + } + content = std::make_unique( + *project, *paths, input.get(), [this]() { onContentLoad(); } + ); + scripting::initialize(*this); + + if (!isHeadless()) { + gui->getMenu()->setPageLoader(scripting::create_page_loader()); + } + keepAlive(settings.ui.language.observe([this](auto lang) { + langs::setup(lang, paths->resPaths.collectRoots()); + }, true)); + + keepAlive(settings.audio.inputDevice.observe([](auto name) { + audio::set_input_device(name == "auto" ? "" : name); + })); + + appScripts = std::make_unique(params); + + if (params.stdinCommands) { + cmd::start_stdin_cmd_reader(*this); + } +} + +void Engine::loadSettings() { + io::path settings_file = EnginePaths::SETTINGS_FILE; + if (io::is_regular_file(settings_file)) { + logger.info() << "loading settings"; + std::string text = io::read_string(settings_file); + try { + toml::parse(*settingsHandler, settings_file.string(), text); + } catch (const parsing_error& err) { + logger.error() << err.errorLog(); + throw; + } + } +} + +void Engine::loadControls() { + io::path controls_file = EnginePaths::CONTROLS_FILE; + if (io::is_regular_file(controls_file)) { + logger.info() << "loading controls"; + std::string text = io::read_string(controls_file); + input->getBindings().read( + toml::parse(controls_file.string(), text), BindType::BIND + ); + } +} + +void Engine::updateHotkeys() { + if (input->jpressed(Keycode::F2)) { + windowControl->saveScreenshot(); + } + if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && + input->jpressed(Keycode::U)) { + gui->toggleDebug(); + } + if (input->jpressed(Keycode::F11)) { + windowControl->toggleFullscreen(); + } +} + +void Engine::run() { + if (params.headless) { + ServerMainloop(*this).run(); + } else { + Mainloop(*this).run(); + } +} + +void Engine::postUpdate() { + if (network) { + network->update(); + } + postRunnables.run(); + scripting::process_post_runnables(); + + if (debuggingServer) { + debuggingServer->update(); + } +} + +void Engine::detachDebugger() { + debuggingServer.reset(); +} + +void Engine::applicationTick() { + appScripts->tick(); +} + +void Engine::updateFrontend() { + double delta = time.getDelta(); + assets->update(); + updateHotkeys(); + audio::update(delta); + gui->act(delta, window->getSize()); + screen->update(delta); + gui->postAct(); +} + +void Engine::nextFrame(bool waitForRefresh) { + windowControl->nextFrame(waitForRefresh); +} + +void Engine::startPauseLoop() { + assert (network != nullptr); + + bool initialCursorLocked = false; + if (!isHeadless()) { + initialCursorLocked = input->isCursorLocked(); + if (initialCursorLocked) { + input->toggleCursor(); + } + } + while (!isQuitSignal() && debuggingServer) { + network->update(); + if (debuggingServer->update()) { + break; + } + if (isHeadless()) { + platform::sleep(1.0 / params.tps * 1000); + } else { + nextFrame(false); + } + } + if (initialCursorLocked) { + input->toggleCursor(); + } +} + +void Engine::renderFrame() { + if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { + input->toggleCursor(); + } + screen->draw(time.getDelta()); + + DrawContext ctx(nullptr, *window, nullptr); + gui->draw(ctx, *assets->getStorage()); + draw_window_bar(*this); +} + +void Engine::saveSettings() { + logger.info() << "saving settings"; + io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); + if (!params.headless) { + logger.info() << "saving bindings"; + if (input) { + io::write_string( + EnginePaths::CONTROLS_FILE, input->getBindings().write() + ); + } + } +} + +void Engine::close() { + saveSettings(); + logger.info() << "shutting down"; + if (screen) { + screen->onEngineShutdown(); + screen.reset(); + } + content.reset(); + assets.reset(); + cmd.reset(); + if (gui) { + gui.reset(); + logger.info() << "gui finished"; + } + if (!isHeadless()) { + vector_fonts::finalize(); + } + audio::close(); + debuggingServer.reset(); + network.reset(); + clearKeepedObjects(); + project.reset(); + appScripts.reset(); + scripting::close(); + logger.info() << "scripting finished"; + if (!params.headless) { + window.reset(); + logger.info() << "window closed"; + } + logger.info() << "engine finished"; +} + +void Engine::terminate() { + instance->close(); + instance.reset(); +} + +EngineController* Engine::getController() { + return controller.get(); +} + +void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { + this->levelConsumer = std::move(levelConsumer); +} + +void Engine::loadAssets() { + assets->loadAssets(content->get()); +} + +void Engine::loadProject() { + io::path projectFile = "project:project.toml"; + project = std::make_unique(); + project->path = "project:"; + project->deserialize(io::read_object(projectFile)); + logger.info() << "loaded project " << util::quote(project->name); +} + +void Engine::setScreen(std::shared_ptr screen) { + if (this->screen) { + appScripts->onScreenChange(this->screen->getName(), false); + } + // reset audio channels (stop all sources) + audio::reset_channel(audio::get_channel_index("regular")); + audio::reset_channel(audio::get_channel_index("ambient")); + this->screen = std::move(screen); + if (this->screen) { + this->screen->onOpen(); + } + if (this->screen) { + appScripts->onScreenChange(this->screen->getName(), true); + window->setShouldRefresh(); + } +} + +void Engine::onWorldOpen(std::unique_ptr level, int64_t localPlayer) { + logger.info() << "world open"; + levelConsumer(std::move(level), localPlayer); +} + +void Engine::onWorldClosed() { + logger.info() << "world closed"; + levelConsumer(nullptr, -1); +} + +void Engine::quit() { + logger.info() << "quitSignal set to true"; + quitSignal = true; + if (!isHeadless()) { + window->setShouldClose(true); + } +} + +bool Engine::isQuitSignal() const { + return quitSignal; +} + +EngineSettings& Engine::getSettings() { + return settings; +} + +Assets* Engine::getAssets() { + return assets ? assets->getStorage() : nullptr; +} + +Assets& Engine::requireAssets() { + if (isHeadless()) { + throw std::runtime_error("assets are not available in headless mode"); + } + return *assets->getStorage(); +} + +AssetsLoader& Engine::acquireBackgroundLoader() { + if (isHeadless()) { + throw std::runtime_error("assets are not available in headless mode"); + } + return assets->acquireBackgroundLoader(); +} + +EnginePaths& Engine::getPaths() { + return *paths; +} + +ResPaths& Engine::getResPaths() { + return paths->resPaths; +} + +std::shared_ptr Engine::getScreen() { + return screen; +} + +SettingsHandler& Engine::getSettingsHandler() { + return *settingsHandler; +} + +Time& Engine::getTime() { + return time; +} + +const CoreParameters& Engine::getCoreParameters() const { + return params; +} + +bool Engine::isHeadless() const { + return params.headless; +} + +ContentControl& Engine::getContentControl() { + return *content; +} diff --git a/src/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index 3cf8406fb..e8b284a65 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -1,193 +1,193 @@ -#pragma once - -#include "delegates.hpp" - -#include -#include -#include -#include -#include -#include -#include - -class DrawContext; -class Assets; -class Camera; -class Batch2D; -struct CursorState; -class Engine; -class Input; -class Window; -struct FontStylesScheme; - -namespace devtools { - class Editor; -} - -class UiDocument; - -/* - Some info about padding and margin. - Padding is element inner space, margin is outer - glm::vec4 usage: - x - left - y - top - z - right - w - bottom - - Outer element - +======================================================================+ - | . . . . | - | .padding.y . . . | - | padding.x . . . . padding.z | - |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | - | . . . . | - | . .margin.y . . | - | .margin.x . . margin.z. | - |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | - | . | Inner element | . | - |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | - | . . . . | - | . .margin.w . . | - | . . . . | - |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | - | . . . . | - | .padding.w . . . | - | . . . . | - +======================================================================+ -*/ - -namespace gui { - class UINode; - class Container; - class Menu; - class Frame; - - /// @brief The main UI controller - class GUI { - Engine& engine; - Input& input; - std::unique_ptr batch2D; - std::shared_ptr container; - std::shared_ptr hover; - std::shared_ptr pressed; - std::shared_ptr focus; - const UINode* focusedOnStart = nullptr; - std::shared_ptr tooltip; - std::shared_ptr rootDocument; - std::unique_ptr syntaxColorScheme; - std::unordered_map> storage; - std::shared_ptr activeFrame; - - std::unique_ptr uicamera; - std::shared_ptr menu; - std::queue postRunnables; - std::vector> mouseOver; - std::unordered_map> frames; - vec2supplier cursorLocator; - - float tooltipTimer = 0.0f; - float doubleClickTimer = 0.0f; - float doubleClickDelay = 0.5f; - bool doubleClicked = false; - bool debug = false; - - void actMouse(Frame& frame, float delta, const CursorState& cursor); - void actFocused(); - void updateTooltip(float delta); - void resetTooltip(); - public: - static inline std::string CORE_MAIN = "core:main"; - static constexpr int CONTEXT_MENU_ZINDEX = 999; - - GUI(Engine& engine); - ~GUI(); - - /// @brief Get the main menu (Menu) node - std::shared_ptr getMenu(); - - /// @brief Get current focused node - /// @return focused node or nullptr - std::shared_ptr getFocused() const; - - /// @brief Check if all user input is caught by some element like TextBox - bool isFocusCaught() const; - - /// @brief Main input handling and logic update method - /// @param delta delta time - /// @param viewport window size - void act(float delta, const glm::uvec2& viewport); - - /// @brief Draw all visible elements on main container - /// @param pctx parent graphics context - /// @param assets active assets storage - void draw(const DrawContext& pctx, Assets& assets); - - Batch2D* getBatch2D() { - return batch2D.get(); - } - - void postAct(); - - /// @brief Add element to the main container - /// @param node UI element - void add(std::shared_ptr node); - - void addFrame(std::shared_ptr frame); - - void setActiveFrame( - const std::string& id, vec2supplier cursorLocator = nullptr - ); - - std::shared_ptr getActiveFrame() const; - - std::shared_ptr getFrame(const std::string& id); - - /// @brief Remove node from the main container - void remove(UINode* node) noexcept; - - void remove(const std::shared_ptr& node) noexcept { - return remove(node.get()); - } - - /// @brief Store node in the GUI nodes dictionary - /// (does not add node to the main container) - /// @param name node key - /// @param node target node - void store(const std::string& name, std::shared_ptr node); - - /// @brief Get node from the GUI nodes dictionary - /// @param name node key - /// @return stored node or nullptr - std::shared_ptr get(const std::string& name) noexcept; - - /// @brief Remove node from the GUI nodes dictionary - /// @param name node key - void remove(const std::string& name) noexcept; - - /// @brief Set node as focused - /// @param node new focused node or nullptr to remove focus - void setFocus(std::shared_ptr node); - - /// @brief Get the main container - /// @deprecated - std::shared_ptr getContainer() const; - - void setSyntaxColorScheme(std::unique_ptr scheme); - FontStylesScheme* getSyntaxColorScheme() const; - - void onAssetsLoad(Assets* assets); - - void postRunnable(const runnable& callback); - - void setDoubleClickDelay(float delay); - float getDoubleClickDelay() const; - - void toggleDebug(); - const Input& getInput() const; - Input& getInput(); - Window& getWindow(); - devtools::Editor& getEditor(); - Engine& getEngine(); - }; -} +#pragma once + +#include "delegates.hpp" + +#include +#include +#include +#include +#include +#include +#include + +class DrawContext; +class Assets; +class Camera; +class Batch2D; +struct CursorState; +class Engine; +class Input; +class Window; +struct FontStylesScheme; + +namespace devtools { + class Editor; +} + +class UiDocument; + +/* + Some info about padding and margin. + Padding is element inner space, margin is outer + glm::vec4 usage: + x - left + y - top + z - right + w - bottom + + Outer element + +======================================================================+ + | . . . . | + | .padding.y . . . | + | padding.x . . . . padding.z | + |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | + | . . . . | + | . .margin.y . . | + | .margin.x . . margin.z. | + |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | + | . | Inner element | . | + |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | + | . . . . | + | . .margin.w . . | + | . . . . | + |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | + | . . . . | + | .padding.w . . . | + | . . . . | + +======================================================================+ +*/ + +namespace gui { + class UINode; + class Container; + class Menu; + class Frame; + + /// @brief The main UI controller + class GUI { + Engine& engine; + Input& input; + std::unique_ptr batch2D; + std::shared_ptr container; + std::shared_ptr hover; + std::shared_ptr pressed; + std::shared_ptr focus; + const UINode* focusedOnStart = nullptr; + std::shared_ptr tooltip; + std::shared_ptr rootDocument; + std::unique_ptr syntaxColorScheme; + std::unordered_map> storage; + std::shared_ptr activeFrame; + + std::unique_ptr uicamera; + std::shared_ptr menu; + std::queue postRunnables; + std::vector> mouseOver; + std::unordered_map> frames; + vec2supplier cursorLocator; + + float tooltipTimer = 0.0f; + float doubleClickTimer = 0.0f; + float doubleClickDelay = 0.5f; + bool doubleClicked = false; + bool debug = false; + + void actMouse(Frame& frame, float delta, const CursorState& cursor); + void actFocused(); + void updateTooltip(float delta); + void resetTooltip(); + public: + static inline std::string CORE_MAIN = "core:main"; + static constexpr int CONTEXT_MENU_ZINDEX = 999; + + GUI(Engine& engine); + ~GUI(); + + /// @brief Get the main menu (Menu) node + std::shared_ptr getMenu(); + + /// @brief Get current focused node + /// @return focused node or nullptr + std::shared_ptr getFocused() const; + + /// @brief Check if all user input is caught by some element like TextBox + bool isFocusCaught() const; + + /// @brief Main input handling and logic update method + /// @param delta delta time + /// @param viewport window size + void act(float delta, const glm::uvec2& viewport); + + /// @brief Draw all visible elements on main container + /// @param pctx parent graphics context + /// @param assets active assets storage + void draw(const DrawContext& pctx, Assets& assets); + + Batch2D* getBatch2D() { + return batch2D.get(); + } + + void postAct(); + + /// @brief Add element to the main container + /// @param node UI element + void add(std::shared_ptr node); + + void addFrame(std::shared_ptr frame); + + void setActiveFrame( + const std::string& id, vec2supplier cursorLocator = nullptr + ); + + std::shared_ptr getActiveFrame() const; + + std::shared_ptr getFrame(const std::string& id); + + /// @brief Remove node from the main container + void remove(UINode* node) noexcept; + + void remove(const std::shared_ptr& node) noexcept { + return remove(node.get()); + } + + /// @brief Store node in the GUI nodes dictionary + /// (does not add node to the main container) + /// @param name node key + /// @param node target node + void store(const std::string& name, std::shared_ptr node); + + /// @brief Get node from the GUI nodes dictionary + /// @param name node key + /// @return stored node or nullptr + std::shared_ptr get(const std::string& name) noexcept; + + /// @brief Remove node from the GUI nodes dictionary + /// @param name node key + void remove(const std::string& name) noexcept; + + /// @brief Set node as focused + /// @param node new focused node or nullptr to remove focus + void setFocus(std::shared_ptr node); + + /// @brief Get the main container + /// @deprecated + std::shared_ptr getContainer() const; + + void setSyntaxColorScheme(std::unique_ptr scheme); + FontStylesScheme* getSyntaxColorScheme() const; + + void onAssetsLoad(Assets* assets); + + void postRunnable(const runnable& callback); + + void setDoubleClickDelay(float delay); + float getDoubleClickDelay() const; + + void toggleDebug(); + const Input& getInput() const; + Input& getInput(); + Window& getWindow(); + devtools::Editor& getEditor(); + Engine& getEngine(); + }; +} diff --git a/src/window/input.cpp b/src/window/input.cpp index cc07b7bb3..27c9f63e5 100644 --- a/src/window/input.cpp +++ b/src/window/input.cpp @@ -1,267 +1,267 @@ -#include "input.hpp" - -#include "debug/Logger.hpp" -#include "util/stringutil.hpp" -#include "data/dv.hpp" - -#include - -#include -#include - -#ifdef _WIN32 -#include -#endif // _WIN32 - -static debug::Logger logger("input"); - -static std::unordered_map keycodes { - {"enter", GLFW_KEY_ENTER}, - {"space", GLFW_KEY_SPACE}, - {"backspace", GLFW_KEY_BACKSPACE}, - {"caps-lock", GLFW_KEY_CAPS_LOCK}, - {"escape", GLFW_KEY_ESCAPE}, - {"delete", GLFW_KEY_DELETE}, - {"home", GLFW_KEY_HOME}, - {"end", GLFW_KEY_END}, - {"tab", GLFW_KEY_TAB}, - {"insert", GLFW_KEY_INSERT}, - {"page-down", GLFW_KEY_PAGE_DOWN}, - {"page-up", GLFW_KEY_PAGE_UP}, - {"left-shift", GLFW_KEY_LEFT_SHIFT}, - {"right-shift", GLFW_KEY_RIGHT_SHIFT}, - {"left-ctrl", GLFW_KEY_LEFT_CONTROL}, - {"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, - {"left-alt", GLFW_KEY_LEFT_ALT}, - {"right-alt", GLFW_KEY_RIGHT_ALT}, - {"left-super", GLFW_KEY_LEFT_SUPER}, - {"right-super", GLFW_KEY_RIGHT_SUPER}, - {"grave-accent", GLFW_KEY_GRAVE_ACCENT}, - {"left", GLFW_KEY_LEFT}, - {"right", GLFW_KEY_RIGHT}, - {"down", GLFW_KEY_DOWN}, - {"up", GLFW_KEY_UP}, - {"num-lock", GLFW_KEY_NUM_LOCK}, - {"print-screen", GLFW_KEY_PRINT_SCREEN}, - {"num-add", GLFW_KEY_KP_ADD}, - {"num-multiply", GLFW_KEY_KP_MULTIPLY}, - {"num-divide", GLFW_KEY_KP_DIVIDE}, - {"num-subtract", GLFW_KEY_KP_SUBTRACT}, - {"num-enter", GLFW_KEY_KP_ENTER}, - {"num-equal", GLFW_KEY_KP_EQUAL}, - {"num-decimal", GLFW_KEY_KP_DECIMAL}, -}; - -static std::unordered_map mousecodes { - {"left", GLFW_MOUSE_BUTTON_1}, - {"right", GLFW_MOUSE_BUTTON_2}, - {"middle", GLFW_MOUSE_BUTTON_3}, - {"side1", GLFW_MOUSE_BUTTON_4}, - {"side2", GLFW_MOUSE_BUTTON_5}, - {"side3", GLFW_MOUSE_BUTTON_6}, - {"side4", GLFW_MOUSE_BUTTON_7}, - {"side5", GLFW_MOUSE_BUTTON_8}, -}; - -static std::unordered_map keynames {}; -static std::unordered_map buttonsnames{}; - -std::string input_util::get_name(Mousecode code) { - const auto found = buttonsnames.find(static_cast(code)); - if (found == buttonsnames.end()) { - return "unknown"; - } - return found->second; -} - -std::string input_util::get_name(Keycode code) { - const auto found = keynames.find(static_cast(code)); - if (found == keynames.end()) { - return "unknown"; - } - return found->second; -} - -void Binding::reset(InputType type, int code) { - this->type = type; - this->code = code; -} - -void Binding::reset(Keycode code) { - reset(InputType::KEYBOARD, static_cast(code)); -} - -void Binding::reset(Mousecode code) { - reset(InputType::MOUSE, static_cast(code)); -} - -void input_util::initialize() { - for (int i = 0; i <= 9; i++) { - keycodes[std::to_string(i)] = GLFW_KEY_0 + i; - } - for (int i = 0; i < 25; i++) { - keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; - } - for (char i = 'a'; i <= 'z'; i++) { - keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; - } - for (int i = 0; i <= 9; i++) { - keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; - } - for (const auto& entry : keycodes) { - keynames[entry.second] = entry.first; - } - for (const auto& entry : mousecodes) { - buttonsnames[entry.second] = entry.first; - } -} - -Keycode input_util::keycode_from(const std::string& name) { - const auto& found = keycodes.find(name); - if (found == keycodes.end()) { - return Keycode::UNKNOWN; - } - return static_cast(found->second); -} - -Mousecode input_util::mousecode_from(const std::string& name) { - const auto& found = mousecodes.find(name); - if (found == mousecodes.end()) { - return Mousecode::UNKNOWN; - } - return static_cast(found->second); -} - -static const char* numpad_key_names[] { - "Num 0", - "Num 1", - "Num 2", - "Num 3", - "Num 4", - "Num 5", - "Num 6", - "Num 7", - "Num 8", - "Num 9", - "Num .", - "Num /", - "Num *", - "Num -", - "Num +", - "Num Enter", - "Num =", -}; - -std::string input_util::to_string(Keycode code) { - int icode_repr = static_cast(code); - if (icode_repr == -1) { - return "Unknown"; - } - if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { - return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; - } - const auto found = keynames.find(icode_repr); - if (found == keynames.end()) { - return "Unknown"; - } - std::string result; - bool capitalize = true; - for (char c : found->second) { - if (c == '-') { - result += ' '; - capitalize = true; - continue; - } - result += capitalize ? static_cast(std::toupper(c)) : c; - capitalize = false; - } - return result; -} - -std::string input_util::to_string(Mousecode code) { - switch (code) { - case Mousecode::BUTTON_1: - return "LMB"; - case Mousecode::BUTTON_2: - return "RMB"; - case Mousecode::BUTTON_3: - return "MMB"; - case Mousecode::BUTTON_4: - case Mousecode::BUTTON_5: - case Mousecode::BUTTON_6: - case Mousecode::BUTTON_7: - case Mousecode::BUTTON_8: - return "XButton " + std::to_string(static_cast(code) - - static_cast(Mousecode::BUTTON_3)); - default: - return "unknown button"; - } -} - -const Binding& Bindings::require(const std::string& name) const { - if (const auto found = get(name)) { - return *found; - } - throw std::runtime_error("binding '" + name + "' does not exist"); -} - -Binding& Bindings::require(const std::string& name) { - if (const auto found = get(name)) { - return *found; - } - throw std::runtime_error("binding '" + name + "' does not exist"); -} - -void Bindings::read(const dv::value& map, BindType bindType) { - for (auto& [sectionName, section] : map.asObject()) { - for (auto& [name, value] : section.asObject()) { - auto key = sectionName + "." + name; - auto [prefix, codename] = util::split_at(value.asString(), ':'); - InputType type; - int code; - if (prefix == "key") { - type = InputType::KEYBOARD; - code = static_cast(input_util::keycode_from(codename)); - } else if (prefix == "mouse") { - type = InputType::MOUSE; - code = static_cast(input_util::mousecode_from(codename)); - } else { - logger.error() - << "unknown input type: " << prefix << " (binding " - << util::quote(key) << ")"; - continue; - } - if (bindType == BindType::BIND) { - bind(key, type, code); - } else if (bindType == BindType::REBIND) { - rebind(key, type, code); - } - } - } -} - -#include "coders/toml.hpp" - -std::string Bindings::write() const { - auto obj = dv::object(); - for (auto& entry : bindings) { - const auto& binding = entry.second; - std::string value; - switch (binding.type) { - case InputType::KEYBOARD: - value = - "key:" + - input_util::get_name(static_cast(binding.code)); - break; - case InputType::MOUSE: - value = - "mouse:" + - input_util::get_name(static_cast(binding.code)); - break; - default: - throw std::runtime_error("unsupported control type"); - } - obj[entry.first] = std::move(value); - } - return toml::stringify(obj); -} +#include "input.hpp" + +#include "debug/Logger.hpp" +#include "util/stringutil.hpp" +#include "data/dv.hpp" + +#include + +#include +#include + +#ifdef _WIN32 +#include +#endif // _WIN32 + +static debug::Logger logger("input"); + +static std::unordered_map keycodes { + {"enter", GLFW_KEY_ENTER}, + {"space", GLFW_KEY_SPACE}, + {"backspace", GLFW_KEY_BACKSPACE}, + {"caps-lock", GLFW_KEY_CAPS_LOCK}, + {"escape", GLFW_KEY_ESCAPE}, + {"delete", GLFW_KEY_DELETE}, + {"home", GLFW_KEY_HOME}, + {"end", GLFW_KEY_END}, + {"tab", GLFW_KEY_TAB}, + {"insert", GLFW_KEY_INSERT}, + {"page-down", GLFW_KEY_PAGE_DOWN}, + {"page-up", GLFW_KEY_PAGE_UP}, + {"left-shift", GLFW_KEY_LEFT_SHIFT}, + {"right-shift", GLFW_KEY_RIGHT_SHIFT}, + {"left-ctrl", GLFW_KEY_LEFT_CONTROL}, + {"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, + {"left-alt", GLFW_KEY_LEFT_ALT}, + {"right-alt", GLFW_KEY_RIGHT_ALT}, + {"left-super", GLFW_KEY_LEFT_SUPER}, + {"right-super", GLFW_KEY_RIGHT_SUPER}, + {"grave-accent", GLFW_KEY_GRAVE_ACCENT}, + {"left", GLFW_KEY_LEFT}, + {"right", GLFW_KEY_RIGHT}, + {"down", GLFW_KEY_DOWN}, + {"up", GLFW_KEY_UP}, + {"num-lock", GLFW_KEY_NUM_LOCK}, + {"print-screen", GLFW_KEY_PRINT_SCREEN}, + {"num-add", GLFW_KEY_KP_ADD}, + {"num-multiply", GLFW_KEY_KP_MULTIPLY}, + {"num-divide", GLFW_KEY_KP_DIVIDE}, + {"num-subtract", GLFW_KEY_KP_SUBTRACT}, + {"num-enter", GLFW_KEY_KP_ENTER}, + {"num-equal", GLFW_KEY_KP_EQUAL}, + {"num-decimal", GLFW_KEY_KP_DECIMAL}, +}; + +static std::unordered_map mousecodes { + {"left", GLFW_MOUSE_BUTTON_1}, + {"right", GLFW_MOUSE_BUTTON_2}, + {"middle", GLFW_MOUSE_BUTTON_3}, + {"side1", GLFW_MOUSE_BUTTON_4}, + {"side2", GLFW_MOUSE_BUTTON_5}, + {"side3", GLFW_MOUSE_BUTTON_6}, + {"side4", GLFW_MOUSE_BUTTON_7}, + {"side5", GLFW_MOUSE_BUTTON_8}, +}; + +static std::unordered_map keynames {}; +static std::unordered_map buttonsnames{}; + +std::string input_util::get_name(Mousecode code) { + const auto found = buttonsnames.find(static_cast(code)); + if (found == buttonsnames.end()) { + return "unknown"; + } + return found->second; +} + +std::string input_util::get_name(Keycode code) { + const auto found = keynames.find(static_cast(code)); + if (found == keynames.end()) { + return "unknown"; + } + return found->second; +} + +void Binding::reset(InputType type, int code) { + this->type = type; + this->code = code; +} + +void Binding::reset(Keycode code) { + reset(InputType::KEYBOARD, static_cast(code)); +} + +void Binding::reset(Mousecode code) { + reset(InputType::MOUSE, static_cast(code)); +} + +void input_util::initialize() { + for (int i = 0; i <= 9; i++) { + keycodes[std::to_string(i)] = GLFW_KEY_0 + i; + } + for (int i = 0; i < 25; i++) { + keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; + } + for (char i = 'a'; i <= 'z'; i++) { + keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; + } + for (int i = 0; i <= 9; i++) { + keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; + } + for (const auto& entry : keycodes) { + keynames[entry.second] = entry.first; + } + for (const auto& entry : mousecodes) { + buttonsnames[entry.second] = entry.first; + } +} + +Keycode input_util::keycode_from(const std::string& name) { + const auto& found = keycodes.find(name); + if (found == keycodes.end()) { + return Keycode::UNKNOWN; + } + return static_cast(found->second); +} + +Mousecode input_util::mousecode_from(const std::string& name) { + const auto& found = mousecodes.find(name); + if (found == mousecodes.end()) { + return Mousecode::UNKNOWN; + } + return static_cast(found->second); +} + +static const char* numpad_key_names[] { + "Num 0", + "Num 1", + "Num 2", + "Num 3", + "Num 4", + "Num 5", + "Num 6", + "Num 7", + "Num 8", + "Num 9", + "Num .", + "Num /", + "Num *", + "Num -", + "Num +", + "Num Enter", + "Num =", +}; + +std::string input_util::to_string(Keycode code) { + int icode_repr = static_cast(code); + if (icode_repr == -1) { + return "Unknown"; + } + if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { + return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; + } + const auto found = keynames.find(icode_repr); + if (found == keynames.end()) { + return "Unknown"; + } + std::string result; + bool capitalize = true; + for (char c : found->second) { + if (c == '-') { + result += ' '; + capitalize = true; + continue; + } + result += capitalize ? static_cast(std::toupper(c)) : c; + capitalize = false; + } + return result; +} + +std::string input_util::to_string(Mousecode code) { + switch (code) { + case Mousecode::BUTTON_1: + return "LMB"; + case Mousecode::BUTTON_2: + return "RMB"; + case Mousecode::BUTTON_3: + return "MMB"; + case Mousecode::BUTTON_4: + case Mousecode::BUTTON_5: + case Mousecode::BUTTON_6: + case Mousecode::BUTTON_7: + case Mousecode::BUTTON_8: + return "XButton " + std::to_string(static_cast(code) - + static_cast(Mousecode::BUTTON_3)); + default: + return "unknown button"; + } +} + +const Binding& Bindings::require(const std::string& name) const { + if (const auto found = get(name)) { + return *found; + } + throw std::runtime_error("binding '" + name + "' does not exist"); +} + +Binding& Bindings::require(const std::string& name) { + if (const auto found = get(name)) { + return *found; + } + throw std::runtime_error("binding '" + name + "' does not exist"); +} + +void Bindings::read(const dv::value& map, BindType bindType) { + for (auto& [sectionName, section] : map.asObject()) { + for (auto& [name, value] : section.asObject()) { + auto key = sectionName + "." + name; + auto [prefix, codename] = util::split_at(value.asString(), ':'); + InputType type; + int code; + if (prefix == "key") { + type = InputType::KEYBOARD; + code = static_cast(input_util::keycode_from(codename)); + } else if (prefix == "mouse") { + type = InputType::MOUSE; + code = static_cast(input_util::mousecode_from(codename)); + } else { + logger.error() + << "unknown input type: " << prefix << " (binding " + << util::quote(key) << ")"; + continue; + } + if (bindType == BindType::BIND) { + bind(key, type, code); + } else if (bindType == BindType::REBIND) { + rebind(key, type, code); + } + } + } +} + +#include "coders/toml.hpp" + +std::string Bindings::write() const { + auto obj = dv::object(); + for (auto& entry : bindings) { + const auto& binding = entry.second; + std::string value; + switch (binding.type) { + case InputType::KEYBOARD: + value = + "key:" + + input_util::get_name(static_cast(binding.code)); + break; + case InputType::MOUSE: + value = + "mouse:" + + input_util::get_name(static_cast(binding.code)); + break; + default: + throw std::runtime_error("unsupported control type"); + } + obj[entry.first] = std::move(value); + } + return toml::stringify(obj); +} From 1dbd445027e115e850391ca4897bb9bfca7e483b Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 01:21:24 +0300 Subject: [PATCH 06/35] give Window::getTitle a default implementation Keeps the interface non-breaking for other window backends: the decoration height and hovered button already have defaults, and now so does the title. --- src/window/Window.hpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/window/Window.hpp b/src/window/Window.hpp index a41c53535..0109faf7b 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -44,7 +44,10 @@ public: virtual void setTitle(const std::string& title) = 0; - virtual const std::string& getTitle() const = 0; + virtual const std::string& getTitle() const { + static const std::string empty; + return empty; + } virtual int getDecorationHeight() const { return 0; From 6a5e485bcacad39c0586cae360ddc99cb3ef72f0 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 01:35:45 +0300 Subject: [PATCH 07/35] drop the environment switches The backend, decoration and resize-logging switches were only used while working on this, and undocumented ones should not stay: - VOXEL_WINDOW_BACKEND: the backend is still chosen by WAYLAND_DISPLAY, and GLFW is used when it is not set; - VOXEL_DECORATIONS: own decorations are always enabled when the compositor provides none; - VOXEL_LOG_RESIZE: the resize statistics are removed together with the counters they needed. WaylandDecorations.cpp replaces WaylandBar.cpp: drawing moved to the engine, the file only holds the decoration behaviour now. --- src/window/Window.cpp | 5 -- ...{WaylandBar.cpp => WaylandDecorations.cpp} | 0 src/window/wayland/WaylandWindow.cpp | 63 +------------------ src/window/wayland/WaylandWindow.hpp | 13 ---- 4 files changed, 1 insertion(+), 80 deletions(-) rename src/window/wayland/{WaylandBar.cpp => WaylandDecorations.cpp} (100%) diff --git a/src/window/Window.cpp b/src/window/Window.cpp index 59338380a..48ba76076 100644 --- a/src/window/Window.cpp +++ b/src/window/Window.cpp @@ -5,16 +5,11 @@ #include "window/input.hpp" #include -#include static debug::Logger logger("window"); #ifdef VOXELENGINE_WAYLAND static bool prefer_wayland() { - const char* backend = getenv("VOXEL_WINDOW_BACKEND"); - if (backend != nullptr) { - return strcmp(backend, "wayland") == 0; - } const char* display = getenv("WAYLAND_DISPLAY"); if (display != nullptr && *display) { return true; diff --git a/src/window/wayland/WaylandBar.cpp b/src/window/wayland/WaylandDecorations.cpp similarity index 100% rename from src/window/wayland/WaylandBar.cpp rename to src/window/wayland/WaylandDecorations.cpp diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index f24b0a5f8..5a69e7a1a 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -111,22 +111,9 @@ void WaylandWindow::swapBuffers() { 1.0 / 30.0 ); } - if (resizeLogging) { - summarySum += interval; - summaryMax = std::max(summaryMax, interval); - } - } +} lastPresent = current; nextFrameTime = current + frameInterval; - if (resizeLogging) { - summaryFrames++; - } - if (resizing) { - const double elapsed = now() - configureTime; - resizeTimeSum += elapsed; - resizeTimeMax = std::max(resizeTimeMax, elapsed); - resizePresents++; - } lastSwapEnd = now(); if (framerate > 0 && !resizing) { auto elapsed = time() - prevSwap; @@ -245,7 +232,6 @@ void WaylandWindow::resize(int width, int height) { if (size.x != width || size.y != height) { markResizing(); } - configureTime = now(); presentPending = true; if (eglWindow) { wl_egl_window_resize(eglWindow, width, height, 0, 0); @@ -496,7 +482,6 @@ void WaylandWindow::paceFrame() { } } updateResizing(); - logSummary(); if (resizing) { if (!renderPending && now() - lastResize > RESIZE_PAUSE && now() - lastCacheTime > cacheTimeout) { @@ -520,47 +505,10 @@ void WaylandWindow::paceFrame() { frameOnCallback = frameDone; } -void WaylandWindow::logSummary() { - const double current = now(); - if (resizeLogging) { - if (lastLoop > 0.0) { - loopGapMax = std::max(loopGapMax, current - lastLoop); - } - lastLoop = current; - loopCount++; - } - if (!resizeLogging || lastSummary <= 0.0) { - if (resizeLogging) { - lastSummary = current; - } - return; - } - if (current - lastSummary < 1.0) { - return; - } - waylandLogger.info() << "loop " << loopCount << "/s (max gap " - << loopGapMax * 1000.0 << " ms), presents " - << summaryFrames << "/s (max gap " - << summaryMax * 1000.0 << " ms), resizing " - << (resizing ? "yes" : "no"); - lastSummary = current; - loopCount = 0; - loopGapMax = 0.0; - summaryFrames = 0; - summarySum = 0.0; - summaryMax = 0.0; -} - void WaylandWindow::markResizing() { lastResize = now(); if (!resizing) { resizing = true; - resizePresents = 0; - resizeTimeSum = 0.0; - resizeTimeMax = 0.0; - if (resizeLogging) { - waylandLogger.info() << "resize started"; - } setShouldRefresh(); } } @@ -569,15 +517,6 @@ void WaylandWindow::updateResizing() { if (resizing && now() - lastResize > RESIZE_TIMEOUT) { resizing = false; renderPending = true; - if (resizeLogging) { - double average = resizePresents > 0 - ? resizeTimeSum / resizePresents - : 0.0; - waylandLogger.info() - << "resize finished, presented " << resizePresents - << ", avg " << average * 1000.0 << " ms, max " - << resizeTimeMax * 1000.0 << " ms"; - } } } diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 1df0e861d..aadfd9fb2 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -33,7 +33,6 @@ static constexpr double MAX_CACHE_TIMEOUT = 3.0; int framerate = -1; double prevSwap = 0.0; double lastResize = 0.0; -static inline bool resizeLogging = getenv("VOXEL_LOG_RESIZE") != nullptr; bool barEnabled = false; bool fullscreen = false; std::string title = "VoxelCore"; @@ -49,18 +48,7 @@ double cacheTimeout = 0.5; bool resizing = false; bool renderPending = true; bool presentPending = true; -int resizePresents = 0; -double configureTime = 0.0; -double resizeTimeSum = 0.0; -double resizeTimeMax = 0.0; double lastPresent = 0.0; -double lastSummary = 0.0; -double summarySum = 0.0; -double summaryMax = 0.0; -int summaryFrames = 0; -double lastLoop = 0.0; -double loopGapMax = 0.0; -int loopCount = 0; wl_callback* frameCallback = nullptr; bool frameDone = false; GLuint stretchProgram = 0; @@ -132,7 +120,6 @@ glm::vec4 scissorArea {}; void onFrameDone(); void requestFrame(); void paceFrame(); - void logSummary(); void markResizing(); void updateResizing(); void setIdleInhibit(bool enabled); From d9794afa674c1672fe05641be094867c6f74cf76 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 01:48:53 +0300 Subject: [PATCH 08/35] read the clipboard asynchronously getClipboardText() used to open a pipe, ask the selection owner for the text and poll it with a 500 ms deadline, so every paste blocked the UI thread (TextBox calls it directly) and a slow owner meant a visible hang. The selection is now fetched in the background: when the selection changes, the backend requests the text into a non-blocking pipe and getClipboardText() only returns the buffer, which the event loop fills in as the data arrives. Pasting no longer blocks, and a source that never answers simply leaves the previous buffer in place. Also clears the advertised MIME list when a new selection offer arrives, so a request is never made with MIME types of a previous owner. --- src/window/wayland/WaylandInit.cpp | 1 + src/window/wayland/WaylandInput.hpp | 63 ++++++++++++++++--------- src/window/wayland/WaylandListeners.cpp | 1 + 3 files changed, 42 insertions(+), 23 deletions(-) diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp index f41996fc9..fdd52b942 100644 --- a/src/window/wayland/WaylandInit.cpp +++ b/src/window/wayland/WaylandInit.cpp @@ -212,6 +212,7 @@ void on_display_error() { } void WaylandInput::pollEvents(bool waitForRefresh) { + updateClipboard(); beginFrame(); dispatch(waitForRefresh); if (window) { diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp index 048bfac8e..b04bde572 100644 --- a/src/window/wayland/WaylandInput.hpp +++ b/src/window/wayland/WaylandInput.hpp @@ -6,6 +6,7 @@ #include "window/Window.hpp" +#include #include #include @@ -20,39 +21,49 @@ public: void pollEvents(bool waitForRefresh) override; const char* getClipboardText() const override { + return clipboard.c_str(); + } + + void requestClipboardText() { if (state.dataDevice == nullptr || selection == nullptr) { - return clipboard.c_str(); + return; } const char* mime = pickMime(); if (mime == nullptr) { - return clipboard.c_str(); + clipboard.clear(); + return; } int fds[2]; if (pipe(fds) == -1) { - return clipboard.c_str(); + return; } + if (clipboardFd >= 0) { + close(clipboardFd); + } + clipboard.clear(); + clipboardFd = fds[0]; + fcntl(clipboardFd, F_SETFL, O_NONBLOCK); wl_data_offer_receive(selection, mime, fds[1]); close(fds[1]); - wl_display_flush(state.display); - - clipboard.clear(); - char buffer[4096]; - auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(500); - while (std::chrono::steady_clock::now() < deadline) { - pollfd descriptor {fds[0], POLLIN, 0}; - if (poll(&descriptor, 1, 50) <= 0) { - wl_display_dispatch_pending(state.display); - continue; - } - ssize_t length = read(fds[0], buffer, sizeof(buffer)); - if (length <= 0) { - break; - } - clipboard.append(buffer, length); + if (state.display) { + wl_display_flush(state.display); + } + } + + void updateClipboard() { + if (clipboardFd < 0) { + return; + } + char buffer[4096]; + const ssize_t length = read(clipboardFd, buffer, sizeof(buffer)); + if (length > 0) { + clipboard.append(buffer, length); + return; + } + if (length == 0) { + close(clipboardFd); + clipboardFd = -1; } - close(fds[0]); - return clipboard.c_str(); } void setClipboardText(const char* text) override { @@ -67,6 +78,11 @@ public: wl_data_source_offer(source, "text/plain"); wl_data_source_offer(source, "UTF8_STRING"); sourceText = text ? text : ""; + clipboard = sourceText; + if (clipboardFd >= 0) { + close(clipboardFd); + clipboardFd = -1; + } wl_data_device_set_selection(state.dataDevice, source, state.inputSerial); wl_display_flush(state.display); } @@ -177,7 +193,8 @@ public: wl_data_offer* selection = nullptr; std::vector selectionMimes; std::vector pendingMimes; - mutable std::string clipboard; + std::string clipboard; + int clipboardFd = -1; std::string sourceText; private: static uint32_t shapeId(CursorShape shape) { diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index 395d30b7f..8c9742920 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -268,6 +268,7 @@ void data_device_selection(void*, wl_data_device*, wl_data_offer* offer) { input->selection = offer; input->selectionMimes = std::move(input->pendingMimes); input->pendingMimes.clear(); + input->requestClipboardText(); } void registry_global( From 918051cd5d5d2e932a2119ae3e16753112045c10 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 01:49:41 +0300 Subject: [PATCH 09/35] allow running the Windows build manually The workflow only ran for pushes to main/release and for pull requests, so a topic branch could not be built without opening a pull request first. --- .github/workflows/windows.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ec5322bc0..bcd9ff18e 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -5,6 +5,7 @@ on: branches: [ "main", "release-**"] pull_request: branches: [ "main", "dev" ] + workflow_dispatch: jobs: build-windows: From 4731ac0706e85dbaa35d2f5f80ce6ebefaccfcc3 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 16:25:14 +0300 Subject: [PATCH 10/35] keep the window framebuffer opaque Both backends asked for an alpha channel (GLFW defaults to 8 alpha bits, the Wayland EGL config requested 8), so everything the engine draws with alpha - the UI panels, the water post effect - lowered the window's own alpha and the compositor blended the desktop through it. Visible on wine/Proton, where the whole window is composited. Both now ask for an opaque framebuffer: GLFW_ALPHA_BITS 0, and EGL_ALPHA_SIZE 0 with a fallback to an alpha config if the driver provides none. Checked the result through the back buffer attachment: alpha size is 0 on Wayland and on X11. --- src/window/detail/GLFWWindow.cpp | 3 +++ src/window/wayland/WaylandInit.cpp | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 59f637fb1..88161de93 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -603,6 +603,9 @@ std::tuple< #endif glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, settings->samples.get()); + // opaque window: the UI is drawn with alpha and would otherwise + // blend with the desktop behind the window + glfwWindowHint(GLFW_ALPHA_BITS, 0); auto window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); if (window == nullptr) { diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp index fdd52b942..667a71523 100644 --- a/src/window/wayland/WaylandInit.cpp +++ b/src/window/wayland/WaylandInit.cpp @@ -126,7 +126,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, EGL_SAMPLES, samples > 0 ? samples : 0, EGL_NONE }; @@ -137,7 +137,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, EGL_NONE }; eglChooseConfig( From 6c2192b5d846e09b5f847be85a6aaee502b6f25a Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 20:56:55 +0300 Subject: [PATCH 11/35] Draw the window title bar by the engine The native Wayland backend had no window controls: no title, no close button, no way to move or resize the window, and the fullscreen toggle could throw the window to another monitor. GNOME does not implement zxdg_decoration_manager_v1, so there is nobody to draw a frame for us: the backend now falls back to its own decorations when the compositor offers no server side ones, and the engine draws the visible part. The bar itself is drawn by the engine (WindowBar.cpp) through the usual batch and font, so it uses the same assets as the rest of the UI and the backend only owns the behaviour: hit zones, cursor shapes, click interception and the xdg-shell requests. Its geometry follows the desktop's button layout, read and subscribed through xdg-desktop-portal over sd-bus (libsystemd is an optional dependency, gsettings is only a startup fallback). Controls behave like they do elsewhere: - pressing anywhere on the bar starts a move once the pointer leaves a 5 px radius, so dragging works from the buttons as well; - a button acts on release, only if the pointer stayed on it; - a double click on the bar toggles maximize; - the top edge and the top corners resize, the top 8 px of the sides, the sides and the bottom are 8 px wide resize strips; - right and middle clicks and the scroll wheel over the bar never reach the game. The in-game user interface is offset below the bar while menus keep the whole window, so the translucent bar shows the menu background through itself and never covers the HUD. The HUD lays its elements out against the content height and the cursor is translated once, which fixes items following the mouse one row above the pointer in game. The window size is now written to the settings when the window is resized in windowed mode and applied on the first configure, so the window opens with the size it was left with, and leaving fullscreen or borderless mode restores it instead of overwriting the settings with the fullscreen size (an unconditional unmaximize made the compositor restore the maximized geometry). Measured: menu layout unchanged (706 bright pixels in the same place), gui viewport 1123x751 in menus against 1123x721 in game, 1123x751 -> 2560x1080 -> 1123x751 round trip keeps the settings, a saved 1000x640 opens as 1000x640, no errors in the log. --- src/CMakeLists.txt | 8 + src/engine/Engine.cpp | 16 ++ src/engine/WindowBar.cpp | 103 +++++-- src/frontend/hud.cpp | 5 +- src/graphics/core/DrawContext.hpp | 4 + src/graphics/ui/GUI.cpp | 11 +- src/graphics/ui/GUI.hpp | 10 + src/window/Window.hpp | 19 ++ src/window/wayland/WaylandDecorations.cpp | 321 ++++++++++++++++++---- src/window/wayland/WaylandListeners.cpp | 5 +- src/window/wayland/WaylandSettings.cpp | 176 ++++++++++++ src/window/wayland/WaylandSettings.hpp | 23 ++ src/window/wayland/WaylandWindow.cpp | 37 ++- src/window/wayland/WaylandWindow.hpp | 41 ++- 14 files changed, 685 insertions(+), 94 deletions(-) create mode 100644 src/window/wayland/WaylandSettings.cpp create mode 100644 src/window/wayland/WaylandSettings.hpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 6be8a91ea..3ee250a4d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -84,6 +84,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) pkg_check_modules(egl IMPORTED_TARGET egl) find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1) find_program(WAYLAND_SCANNER wayland-scanner) + pkg_check_modules(libsystemd IMPORTED_TARGET libsystemd) if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER) @@ -128,6 +129,13 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) + if(libsystemd_FOUND) + target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_SDBUS=1) + target_link_libraries(VoxelCoreSrc PRIVATE PkgConfig::libsystemd) + message(STATUS "Wayland backend: sd-bus settings are on") + else() + message(STATUS "Wayland backend: sd-bus settings are off") + endif() target_link_libraries( VoxelCoreSrc PRIVATE PkgConfig::wayland-client diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index 4f39f9356..3e5edb371 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,4 +1,9 @@ +#include + +#include + #include "Engine.hpp" +#include "frontend/screens/MenuScreen.hpp" #include "WindowBar.hpp" #ifndef GLEW_STATIC @@ -310,9 +315,20 @@ void Engine::renderFrame() { if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { input->toggleCursor(); } + glViewport( + 0, + 0, + static_cast(window->getSize().x), + static_cast(window->getSize().y) + ); screen->draw(time.getDelta()); DrawContext ctx(nullptr, *window, nullptr); + gui->setContentInset( + dynamic_cast(screen.get()) != nullptr + ? 0 + : window->getDecorationHeight() + ); gui->draw(ctx, *assets->getStorage()); draw_window_bar(*this); } diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp index 661b30d4c..ff0f33ecd 100644 --- a/src/engine/WindowBar.cpp +++ b/src/engine/WindowBar.cpp @@ -1,12 +1,18 @@ #include "WindowBar.hpp" #include "Engine.hpp" +#include "debug/Logger.hpp" #include "graphics/core/Batch2D.hpp" +#include +#include +#include "graphics/core/Shader.hpp" #include "graphics/core/Font.hpp" #include "graphics/ui/GUI.hpp" #include "window/Window.hpp" #include "assets/Assets.hpp" +#include +#include #include #include @@ -33,46 +39,85 @@ void draw_window_bar(Engine& engine) { const auto size = window.getSize(); const float barHeight = static_cast(height); + glViewport(0, 0, static_cast(size.x), static_cast(size.y)); + if (auto shader = engine.requireAssets().get("ui"); shader != nullptr) { + shader->use(); + shader->uniformMatrix( + "u_projview", + glm::ortho( + 0.0f, + static_cast(size.x), + static_cast(size.y), + 0.0f, + -1.0f, + 1.0f + ) + ); + } + batch->begin(); batch->setColor(glm::vec4(0.0f, 0.0f, 0.0f, 0.82f)); batch->rect(0.0f, 0.0f, size.x, barHeight); - batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.10f)); - batch->rect(0.0f, barHeight - 1.0f, size.x, 1.0f); - const std::wstring title = to_wide(window.getTitle()); - const int textX = static_cast(barHeight * 0.4f); - const int textY = (height - font->getLineHeight()) / 2; - batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f)); - font->draw(*batch, title, textX, textY, nullptr, 0); - batch->untexture(); - - const float button = barHeight; + const auto& buttons = window.getDecorationButtons(); const int hovered = window.getDecorationHoveredButton(); - for (int i = 0; i < 3; i++) { - const float x = size.x - button * (i + 1); - const float cx = x + button * 0.5f; - const float cy = barHeight * 0.5f; - if (hovered == i) { - batch->setColor( - i == 0 ? glm::vec4(0.62f, 0.13f, 0.09f, 0.9f) - : glm::vec4(1.0f, 1.0f, 1.0f, 0.16f) - ); - batch->rect(x, 0.0f, button, barHeight - 1.0f); + + float titleLeft = static_cast(barHeight * 0.4f); + float titleRight = size.x - 8.0f; + for (const auto& item : buttons) { + if (item.x + item.width * 0.5f < size.x * 0.5f) { + titleLeft = std::max(titleLeft, item.x + item.width + 8.0f); + } else { + titleRight = std::min(titleRight, item.x - 8.0f); } - const float ink = hovered == i ? 1.0f : 0.8f; - const float thickness = 2.0f; + } + const std::wstring title = to_wide(window.getTitle()); + const float available = std::max(0.0f, titleRight - titleLeft); + size_t titleLength = title.size(); + while (titleLength > 0 && font->calcWidth(title, titleLength) > available) { + titleLength--; + } + if (titleLength > 0) { + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f)); + font->draw( + *batch, std::wstring_view(title).substr(0, titleLength), + static_cast(titleLeft), + (height - font->getLineHeight()) / 2, + nullptr, 0 + ); + batch->untexture(); + } + + const float thickness = 2.0f; + for (size_t i = 0; i < buttons.size(); i++) { + const auto& item = buttons[i]; + const float x = item.x; + const float cx = x + item.width * 0.5f; + const float cy = barHeight * 0.5f; + const bool isHovered = hovered == static_cast(i); + if (isHovered) { + batch->setColor( + item.button == DecorationButton::CLOSE + ? glm::vec4(0.62f, 0.13f, 0.09f, 0.9f) + : glm::vec4(1.0f, 1.0f, 1.0f, 0.16f) + ); + batch->rect(x, 0.0f, item.width, barHeight); + } + const float ink = isHovered ? 1.0f : 0.8f; batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink)); - if (i == 0) { - for (int s = 0; s < 8; s++) { - batch->rect(cx - 5.0f + s, cy - 5.0f + s, thickness, thickness); - batch->rect(cx + 3.0f - s, cy - 5.0f + s, thickness, thickness); + if (item.button == DecorationButton::CLOSE) { + for (int step = 0; step < 8; step++) { + batch->rect(cx - 5.0f + step, cy - 5.0f + step, thickness, thickness); + batch->rect(cx + 3.0f - step, cy - 5.0f + step, thickness, thickness); } - } else if (i == 1 && !window.isMaximized()) { + } else if (item.button == DecorationButton::MINIMIZE) { + batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness); + } else if (!window.isMaximized()) { batch->rect(cx - 6.0f, cy - 6.0f, 12.0f, thickness); batch->rect(cx - 6.0f, cy + 4.0f, 12.0f, thickness); batch->rect(cx - 6.0f, cy - 6.0f, thickness, 12.0f); batch->rect(cx + 4.0f, cy - 6.0f, thickness, 12.0f); - } else if (i == 1) { + } else { batch->rect(cx - 7.0f, cy + 1.0f, 11.0f, thickness); batch->rect(cx - 7.0f, cy + 1.0f, thickness, 6.0f); batch->rect(cx + 2.0f, cy + 1.0f, thickness, 6.0f); @@ -80,8 +125,6 @@ void draw_window_bar(Engine& engine) { batch->rect(cx - 2.0f, cy - 5.0f, 9.0f, thickness); batch->rect(cx - 2.0f, cy - 5.0f, thickness, 6.0f); batch->rect(cx + 5.0f, cy - 5.0f, thickness, 6.0f); - } else { - batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness); } } batch->flush(); diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index 6751b885c..50748323e 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -625,8 +625,9 @@ void Hud::setDebug(bool flag) { void Hud::draw(const DrawContext& ctx){ const auto& viewport = ctx.getViewport(); + uint inset = static_cast(ctx.getWindow().getDecorationHeight()); - updateElementsPosition(viewport); + updateElementsPosition(glm::uvec2(viewport.x, viewport.y - inset)); uicamera->setFov(viewport.y); uicamera->setAspectRatio(viewport.x / static_cast(viewport.y)); @@ -698,7 +699,7 @@ void Hud::updateElementsPosition(const glm::uvec2& viewport) { } } if (exchangeSlot != nullptr) { - exchangeSlot->setPos(input.getCursor().pos); + exchangeSlot->setPos(gui.getCursorPosition()); } hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); hotbarView->setSelected(player.getChosenSlot()); diff --git a/src/graphics/core/DrawContext.hpp b/src/graphics/core/DrawContext.hpp index 7e568e337..38b597929 100644 --- a/src/graphics/core/DrawContext.hpp +++ b/src/graphics/core/DrawContext.hpp @@ -36,6 +36,10 @@ public: Batch2D* getBatch2D() const; const glm::uvec2& getViewport() const; + + Window& getWindow() const { + return window; + } [[nodiscard]] DrawContext sub(Flushable* flushable=nullptr) const; void setViewport(const glm::uvec2& viewport); diff --git a/src/graphics/ui/GUI.cpp b/src/graphics/ui/GUI.cpp index a5f3010ff..d80c03d71 100644 --- a/src/graphics/ui/GUI.cpp +++ b/src/graphics/ui/GUI.cpp @@ -109,7 +109,7 @@ void GUI::updateTooltip(float delta) { tooltip->setVisible(true); label->setText(langs::get(text)); auto size = label->getSize() + glm::vec2(4.0f); - auto pos = cursor.pos + glm::vec2(10.0f); + auto pos = getCursorPosition() + glm::vec2(10.0f); auto rootSize = container->getSize(); pos.x = glm::min(pos.x, rootSize.x - size.x); pos.y = glm::min(pos.y, rootSize.y - size.y); @@ -242,7 +242,9 @@ void GUI::actFocused() { } void GUI::act(float delta, const glm::uvec2& vp) { - container->setSize(vp); + const uint inset = static_cast(viewportOffset); + container->setPos({0.0f, static_cast(inset)}); + container->setSize({vp.x, vp.y > inset ? vp.y - inset : vp.y}); for (auto& pair : frames) { pair.second->act(delta); } @@ -276,6 +278,11 @@ void GUI::postAct() { focusedOnStart = focus.get(); } +glm::vec2 GUI::getCursorPosition() const { + const auto& cursor = input.getCursor(); + return {cursor.pos.x, cursor.pos.y - static_cast(viewportOffset)}; +} + void GUI::draw(const DrawContext& pctx, Assets& assets) { auto ctx = pctx.sub(batch2D.get()); diff --git a/src/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index e8b284a65..4ccc51147 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -123,6 +123,16 @@ namespace gui { /// @param assets active assets storage void draw(const DrawContext& pctx, Assets& assets); + int viewportOffset = 0; + + /// @brief Get the cursor position in the main container coordinates + glm::vec2 getCursorPosition() const; + + /// @brief Shift the main container down by the given number of pixels + void setContentInset(int inset) { + viewportOffset = inset; + } + Batch2D* getBatch2D() { return batch2D.get(); } diff --git a/src/window/Window.hpp b/src/window/Window.hpp index 0109faf7b..020e36c0a 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include "graphics/core/commons.hpp" #include "typedefs.hpp" @@ -10,6 +12,18 @@ class ImageData; class Input; struct DisplaySettings; +enum class DecorationButton { + CLOSE, + MINIMIZE, + MAXIMIZE, +}; + +struct DecorationButtonLayout { + DecorationButton button; + float x; + float width; +}; + enum class WindowMode { WINDOWED, FULLSCREEN, @@ -57,6 +71,11 @@ public: return -1; } + virtual const std::vector& getDecorationButtons() const { + static const std::vector empty; + return empty; + } + virtual bool isIconSupported() const = 0; virtual void setIcon(const ImageData* image) = 0; diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp index ab2f221de..d72544f11 100644 --- a/src/window/wayland/WaylandDecorations.cpp +++ b/src/window/wayland/WaylandDecorations.cpp @@ -2,9 +2,172 @@ #include "settings.hpp" -static constexpr int BAR_HEIGHT = 30; -static constexpr int BAR_BUTTON = 30; -static constexpr int BAR_EDGE = 5; +#include +#include +#include +#include +#include +#include + +namespace { + constexpr const char* LAYOUT_SCHEMA = "org.gnome.desktop.wm.preferences"; + constexpr const char* LAYOUT_KEY = "button-layout"; + + std::vector parse_buttons(const std::string& text) { + std::vector buttons; + size_t start = 0; + while (start <= text.size()) { + const size_t end = text.find(',', start); + const std::string name = text.substr( + start, end == std::string::npos ? std::string::npos : end - start + ); + if (name == "close") { + buttons.push_back(DecorationButton::CLOSE); + } else if (name == "minimize" || name == "min") { + buttons.push_back(DecorationButton::MINIMIZE); + } else if (name == "maximize" || name == "max") { + buttons.push_back(DecorationButton::MAXIMIZE); + } + if (end == std::string::npos) { + break; + } + start = end + 1; + } + return buttons; + } + + bool read_button_layout( + std::vector& left, std::vector& right + ) { + FILE* pipe = popen( + "gsettings get org.gnome.desktop.wm.preferences button-layout" + " 2>/dev/null", + "r" + ); + if (pipe == nullptr) { + return false; + } + char buffer[256] {}; + const char* line = fgets(buffer, sizeof(buffer), pipe); + const int status = pclose(pipe); + if (line == nullptr || status != 0) { + return false; + } + std::string value(buffer); + value.erase( + std::remove_if(value.begin(), value.end(), [] (char c) { + return c == '\'' || c == '"' || c == '\n' || c == '\r'; + }), + value.end() + ); + const size_t separator = value.find(':'); + if (separator == std::string::npos) { + left.clear(); + right = parse_buttons(value); + } else { + left = parse_buttons(value.substr(0, separator)); + right = parse_buttons(value.substr(separator + 1)); + } + return true; + } + + constexpr double DRAG_THRESHOLD = 5.0; + constexpr double DOUBLE_CLICK_TIME = 0.4; + constexpr double DOUBLE_CLICK_DISTANCE = 8.0; +} + +void WaylandWindow::applyLayoutValue(const std::string& rawValue) { + std::string value = rawValue; + value.erase( + std::remove_if(value.begin(), value.end(), [] (char c) { + return c == '\'' || c == '"' || c == '\n' || c == '\r'; + }), + value.end() + ); + const size_t separator = value.find(':'); + std::vector left; + std::vector right; + if (separator == std::string::npos) { + right = parse_buttons(value); + } else { + left = parse_buttons(value.substr(0, separator)); + right = parse_buttons(value.substr(separator + 1)); + } + if (left == leftButtons && right == rightButtons) { + return; + } + leftButtons = std::move(left); + rightButtons = std::move(right); + updateBarGeometry(); + setShouldRefresh(); +} + +void WaylandWindow::updateButtonLayout() { + if (!layoutRead) { + layoutRead = true; + std::string initial; + if (settingsWatcher.read(LAYOUT_SCHEMA, LAYOUT_KEY, initial)) { + applyLayoutValue(initial); + } else { + std::vector left; + std::vector right; + if (read_button_layout(left, right)) { + leftButtons = std::move(left); + rightButtons = std::move(right); + updateBarGeometry(); + } + } + } + std::string value; + if (settingsWatcher.poll(LAYOUT_SCHEMA, LAYOUT_KEY, value)) { + applyLayoutValue(value); + return; + } + if (settingsWatcher.isAvailable()) { + return; + } + const double current = now(); + if (current - lastLayoutCheck < 2.0) { + return; + } + lastLayoutCheck = current; + std::vector left; + std::vector right; + if (!read_button_layout(left, right)) { + return; + } + if (left == leftButtons && right == rightButtons) { + return; + } + leftButtons = std::move(left); + rightButtons = std::move(right); + updateBarGeometry(); +} + +void WaylandWindow::updateBarGeometry() { + barButtons.clear(); + const float width = static_cast(size.x); + for (size_t i = 0; i < leftButtons.size(); i++) { + const float x = static_cast(i) * BAR_BUTTON; + if (x + BAR_BUTTON > width) { + break; + } + barButtons.push_back({leftButtons[i], x, BAR_BUTTON}); + } + for (size_t i = 0; i < rightButtons.size(); i++) { + const float x = width - + static_cast(rightButtons.size() - i) * BAR_BUTTON; + if (x < 0.0f) { + break; + } + barButtons.push_back({rightButtons[i], x, BAR_BUTTON}); + } +} + +const std::vector& WaylandWindow::getDecorationButtons() const { + return barButtons; +} + const std::string& WaylandWindow::getTitle() const { return title; } @@ -33,27 +196,34 @@ int WaylandWindow::barButtonAt(double x, double y) const { if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { return -1; } - for (int i = 0; i < 3; i++) { - const double bx = size.x - BAR_BUTTON * (i + 1); - if (x >= bx && x < bx + BAR_BUTTON) { - return i; + for (size_t i = 0; i < barButtons.size(); i++) { + const auto& item = barButtons[i]; + if (x >= item.x && x < item.x + item.width) { + return static_cast(i); } } return -1; } uint32_t WaylandWindow::barEdgeAt(double x, double y) const { + if (barButtonAt(x, y) >= 0) { + return 0; + } + const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; uint32_t edges = 0; + if (y < BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; + } else if (y >= size.y - BAR_EDGE) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; + } + if (inBar && y >= BAR_EDGE) { + return edges; + } if (x < BAR_EDGE) { edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT; } else if (x >= size.x - BAR_EDGE) { edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; } - if (barVisible() && y < BAR_EDGE) { - edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; - } else if (y >= size.y - BAR_EDGE) { - edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; - } return edges; } @@ -80,61 +250,110 @@ CursorShape WaylandWindow::edgeCursor(uint32_t edges) { bool WaylandWindow::handleBarMotion(double x, double y) { pointerX = x; pointerY = y; - const int button = barButtonAt(x, y); - if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { - hoveredButton = button; + if (barPressed && !barDragging && + (std::abs(x - barPressX) > DRAG_THRESHOLD || + std::abs(y - barPressY) > DRAG_THRESHOLD)) { + barDragging = true; + hoveredButton = -1; + xdg_toplevel_move(state.toplevel, state.seat, barPressSerial); + } + const uint32_t edges = barEdgeAt(x, y); + if (edges != 0) { + hoveredButton = -1; + pointerInBar = false; + input.setOverrideCursor(edgeCursor(edges)); + return true; + } + const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; + if (inBar && !pointerInBar) { + lastLayoutCheck = 0.0; + } + pointerInBar = inBar; + if (inBar) { + hoveredButton = barDragging ? -1 : barButtonAt(x, y); input.setOverrideCursor( - button >= 0 ? CursorShape::POINTER : CursorShape::ARROW + hoveredButton >= 0 ? CursorShape::POINTER : CursorShape::ARROW ); return true; } hoveredButton = -1; - const uint32_t edges = barEdgeAt(x, y); - input.setOverrideCursor( - edges != 0 ? std::optional(edgeCursor(edges)) - : std::nullopt - ); + input.setOverrideCursor(std::nullopt); return false; } -bool WaylandWindow::handleBarButton(uint32_t serial, bool pressed) { +bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) { const double x = pointerX; const double y = pointerY; - const int button = barButtonAt(x, y); - if (button >= 0) { - if (pressed) { - if (button == 0) { - setShouldClose(true); - } else if (button == 1) { - setMaximized(!maximized); - } else { - xdg_toplevel_set_minimized(state.toplevel); - } - } - return true; - } - if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { - if (pressed) { - const double current = now(); - if (current - lastBarPress < 0.4) { - lastBarPress = 0.0; - setMaximized(!maximized); - } else { - lastBarPress = current; - xdg_toplevel_move(state.toplevel, state.seat, serial); - } - } - return true; - } const uint32_t edges = barEdgeAt(x, y); - if (pressed && edges != 0) { - xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); + const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; + if (button != 0) { + return inBar || edges != 0; + } + if (edges != 0) { + if (pressed) { + xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); + } return true; } - return false; + if (!inBar) { + return false; + } + if (pressed) { + const double current = now(); + const bool doubleClick = + current - lastBarPress < DOUBLE_CLICK_TIME && + std::abs(x - lastBarPressX) < DOUBLE_CLICK_DISTANCE && + std::abs(y - lastBarPressY) < DOUBLE_CLICK_DISTANCE; + lastBarPress = current; + lastBarPressX = x; + lastBarPressY = y; + if (doubleClick) { + lastBarPress = 0.0; + setMaximized(!maximized); + return true; + } + barPressed = true; + barDragging = false; + barPressedButton = barButtonAt(x, y); + barPressX = x; + barPressY = y; + barPressSerial = serial; + hoveredButton = barPressedButton; + return true; + } + const int releasedButton = barPressedButton; + const bool dragged = barDragging; + barPressed = false; + barDragging = false; + barPressedButton = -1; + if (!dragged && releasedButton >= 0 && + releasedButton < static_cast(barButtons.size()) && + barButtonAt(x, y) == releasedButton) { + switch (barButtons[releasedButton].button) { + case DecorationButton::CLOSE: + setShouldClose(true); + break; + case DecorationButton::MAXIMIZE: + setMaximized(!maximized); + break; + case DecorationButton::MINIMIZE: + xdg_toplevel_set_minimized(state.toplevel); + break; + } + } + return true; +} + +bool WaylandWindow::handleBarScroll() const { + return (barVisible() && pointerY >= 0.0 && pointerY < BAR_HEIGHT) || + barEdgeAt(pointerX, pointerY) != 0; } void WaylandWindow::onPointerLeave() { hoveredButton = -1; + pointerInBar = false; + barPressed = false; + barDragging = false; + barPressedButton = -1; input.setOverrideCursor(std::nullopt); } diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index 8c9742920..d92393678 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -61,7 +61,7 @@ static void pointer_button( case 0x117: index = 7; break; } const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; - if (index == 0 && window && window->handleBarButton(serial, pressed)) { + if (index >= 0 && window && window->handleBarButton(serial, index, pressed)) { return; } if (index >= 0 && input) { @@ -74,6 +74,9 @@ static void pointer_axis( void*, wl_pointer*, uint32_t, uint32_t axis, wl_fixed_t value ) { if (input && axis == WL_POINTER_AXIS_VERTICAL_SCROLL) { + if (window && window->handleBarScroll()) { + return; + } input->scroll += wl_fixed_to_double(value) > 0 ? -1 : 1; input->refreshWindow(); } diff --git a/src/window/wayland/WaylandSettings.cpp b/src/window/wayland/WaylandSettings.cpp new file mode 100644 index 000000000..58817b16f --- /dev/null +++ b/src/window/wayland/WaylandSettings.cpp @@ -0,0 +1,176 @@ +#include "window/wayland/WaylandSettings.hpp" + +#include "window/wayland/WaylandCommon.hpp" + +#include + +#ifdef VOXELENGINE_SDBUS +#include +#endif + +namespace { + constexpr const char* PORTAL_SERVICE = "org.freedesktop.portal.Desktop"; + constexpr const char* PORTAL_PATH = "/org/freedesktop/portal/desktop"; + constexpr const char* PORTAL_INTERFACE = "org.freedesktop.portal.Settings"; + +#ifdef VOXELENGINE_SDBUS + std::string readVariant(sd_bus_message* message) { + const char* contents = nullptr; + char type = 0; + if (sd_bus_message_peek_type(message, &type, &contents) < 0) { + return {}; + } + if (type == 'v') { + if (sd_bus_message_enter_container(message, 'v', nullptr) < 0) { + return {}; + } + const std::string result = readVariant(message); + sd_bus_message_exit_container(message); + return result; + } + if (type == 's') { + const char* text = nullptr; + if (sd_bus_message_read(message, "s", &text) < 0 || text == nullptr) { + return {}; + } + return text; + } + return {}; + } +#endif +} + +struct SettingsWatcher::Impl { +#ifdef VOXELENGINE_SDBUS + sd_bus* bus = nullptr; + std::string changedKey; + std::string changedValue; + bool changed = false; + + static int onSettingChanged( + sd_bus_message* message, void* userdata, sd_bus_error* + ) { + auto* self = static_cast(userdata); + const char* schema = nullptr; + const char* key = nullptr; + if (sd_bus_message_read(message, "ss", &schema, &key) < 0) { + return 0; + } + const std::string value = readVariant(message); + if (key != nullptr && !value.empty()) { + self->changedKey = key; + self->changedValue = value; + self->changed = true; + } + return 0; + } +#endif +}; + +SettingsWatcher::SettingsWatcher() : impl(new Impl()) { + open(); +} + +SettingsWatcher::~SettingsWatcher() { + close(); + delete impl; +} + +bool SettingsWatcher::open() { +#ifdef VOXELENGINE_SDBUS + if (impl->bus != nullptr) { + return true; + } + if (sd_bus_default_user(&impl->bus) < 0) { + impl->bus = nullptr; + return false; + } + sd_bus_match_signal( + impl->bus, nullptr, nullptr, PORTAL_PATH, PORTAL_INTERFACE, + "SettingChanged", &Impl::onSettingChanged, impl + ); + return true; +#else + return false; +#endif +} + +void SettingsWatcher::close() { +#ifdef VOXELENGINE_SDBUS + if (impl->bus != nullptr) { + sd_bus_flush_close_unref(impl->bus); + impl->bus = nullptr; + } +#endif +} + +bool SettingsWatcher::isAvailable() const { +#ifdef VOXELENGINE_SDBUS + return impl->bus != nullptr; +#else + return false; +#endif +} + +bool SettingsWatcher::read( + const char* schema, const char* key, std::string& value +) { +#ifdef VOXELENGINE_SDBUS + if (impl->bus == nullptr) { + return false; + } + sd_bus_error error = SD_BUS_ERROR_NULL; + sd_bus_message* reply = nullptr; + const int result = sd_bus_call_method( + impl->bus, PORTAL_SERVICE, PORTAL_PATH, PORTAL_INTERFACE, "Read", + &error, &reply, "ss", schema, key + ); + bool success = false; + if (result >= 0) { + if (sd_bus_message_enter_container(reply, 'v', nullptr) >= 0) { + const std::string text = readVariant(reply); + if (!text.empty()) { + value = text; + success = true; + } + sd_bus_message_exit_container(reply); + } + } + if (reply != nullptr) { + sd_bus_message_unref(reply); + } + sd_bus_error_free(&error); + return success; +#else + return false; +#endif +} + +bool SettingsWatcher::poll( + const char* schema, const char* key, std::string& value +) { +#ifdef VOXELENGINE_SDBUS + if (impl->bus == nullptr) { + open(); + return false; + } + sd_bus_message* message = nullptr; + int result = 0; + while ((result = sd_bus_process(impl->bus, &message)) > 0) { + if (message != nullptr) { + sd_bus_message_unref(message); + message = nullptr; + } + } + if (!impl->changed || impl->changedKey != key) { + return false; + } + impl->changed = false; + value = impl->changedValue; + (void)schema; + (void)key; + return true; +#else + return false; +#endif +} diff --git a/src/window/wayland/WaylandSettings.hpp b/src/window/wayland/WaylandSettings.hpp new file mode 100644 index 000000000..30012e9e3 --- /dev/null +++ b/src/window/wayland/WaylandSettings.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include + +class SettingsWatcher { +public: + SettingsWatcher(); + ~SettingsWatcher(); + + bool isAvailable() const; + + bool read(const char* schema, const char* key, std::string& value); + + bool poll(const char* schema, const char* key, std::string& value); + +private: + bool open(); + void close(); + bool handleMessage(const char* schema, const char* key, std::string& value); + + struct Impl; + Impl* impl = nullptr; +}; diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index 5a69e7a1a..3c4748d8d 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -1,5 +1,9 @@ #include "window/wayland/WaylandWindow.hpp" +#include +#include +#include + #include "settings.hpp" #include "graphics/core/Texture.hpp" #include "util/platform.hpp" @@ -7,7 +11,11 @@ WaylandWindow::WaylandWindow( WaylandInput& input, DisplaySettings* settings, int width, int height ) - : Window({width, height}), input(input), settings(settings) { + : Window({width, height}), + input(input), + settings(settings), + initialWidth(width), + initialHeight(height) { scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); } @@ -184,9 +192,10 @@ void WaylandWindow::setMode(WindowMode mode) { break; case WindowMode::WINDOWED: setFullscreen(false); - setMaximized(false); + if (maximized) { + setMaximized(false); + } setIdleInhibit(false); - resize(settings->width.get(), settings->height.get()); break; } wl_surface_commit(state.surface); @@ -238,6 +247,11 @@ void WaylandWindow::resize(int width, int height) { } glViewport(0, 0, width, height); size = {width, height}; + if (Window::mode == WindowMode::WINDOWED && !maximized) { + settings->width.set(width); + settings->height.set(height); + } + updateBarGeometry(); scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); } @@ -264,11 +278,19 @@ void WaylandWindow::onConfigure(int32_t width, int32_t height, wl_array* states) } void WaylandWindow::applyConfigure() { - if (pendingWidth > 0 && pendingHeight > 0) { - resize(pendingWidth, pendingHeight); - } maximized = stateMaximized; suspended = stateSuspended; + if (pendingWidth > 0 && pendingHeight > 0) { + if (!configured && Window::mode == WindowMode::WINDOWED && !maximized && + initialWidth > 0 && initialHeight > 0) { + pendingWidth = initialWidth; + pendingHeight = initialHeight; + } + resize(pendingWidth, pendingHeight); + } + if (stateActivated && !activated) { + lastLayoutCheck = 0.0; + } activated = stateActivated; configured = true; setShouldRefresh(); @@ -339,10 +361,10 @@ std::unique_ptr WaylandWindow::takeScreenshot() { auto data = std::make_unique(size.x * size.y * 3); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); + glReadBuffer(static_cast(readBuffer)); return std::make_unique( ImageFormat::RGB888, size.x, size.y, data.release() ); - glReadBuffer(static_cast(readBuffer)); } void WaylandWindow::setFramerate(int framerate) { @@ -471,6 +493,7 @@ void WaylandWindow::requestFrame() { } void WaylandWindow::paceFrame() { + updateButtonLayout(); frameOnCallback = frameDone; if (lastSwapEnd > 0.0) { const double cost = now() - lastSwapEnd; diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index aadfd9fb2..6186b9433 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -1,6 +1,9 @@ #pragma once #include "window/wayland/WaylandCommon.hpp" + +#include +#include "window/wayland/WaylandSettings.hpp" #include "window/wayland/WaylandInput.hpp" #include "graphics/core/ImageData.hpp" @@ -37,7 +40,25 @@ bool barEnabled = false; bool fullscreen = false; std::string title = "VoxelCore"; int hoveredButton = -1; +bool pointerInBar = false; +SettingsWatcher settingsWatcher; +bool layoutRead = false; +void applyLayoutValue(const std::string& value); + std::vector leftButtons; + std::vector rightButtons; + std::vector barButtons; + double lastLayoutCheck = 0.0; double lastBarPress = 0.0; +double lastBarPressX = 0.0; +double lastBarPressY = 0.0; +double barPressX = 0.0; +double barPressY = 0.0; +uint32_t barPressSerial = 0; +bool barPressed = false; +bool barDragging = false; +int barPressedButton = -1; +int initialWidth = 0; +int initialHeight = 0; double pointerX = 0.0; double pointerY = 0.0; bool frameOnCallback = false; @@ -89,6 +110,23 @@ glm::vec4 scissorArea {}; int getDecorationHeight() const override; int getDecorationHoveredButton() const override; + + + + static constexpr int BAR_HEIGHT = 30; + static constexpr int BAR_BUTTON = 30; + static constexpr int BAR_EDGE = 8; + + int decorationOffset() const { + return barVisible() ? BAR_HEIGHT : 0; + } + + const std::vector& getDecorationButtons() const override; + + void updateButtonLayout(); + + void updateBarGeometry(); + bool isIconSupported() const override { return false; } @@ -115,7 +153,8 @@ glm::vec4 scissorArea {}; uint32_t barEdgeAt(double x, double y) const; static CursorShape edgeCursor(uint32_t edges); bool handleBarMotion(double x, double y); - bool handleBarButton(uint32_t serial, bool pressed); + bool handleBarButton(uint32_t serial, int button, bool pressed); + bool handleBarScroll() const; void onPointerLeave(); void onFrameDone(); void requestFrame(); From c269d6efb315a351db6e00f42cc416038b4f5916 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 22:27:18 +0300 Subject: [PATCH 12/35] Give the Wayland window an Adwaita-like frame The engine-drawn title bar grew to 48 px with 24x24 window controls, 12 px away from the edge and from each other, all sharing one hover highlight. The controls use textures now (gui/cross, gui/minimize_w, gui/maximize_w and gui/restore_w when maximized) with the vector icons kept as a fallback, and the title is centred in the bar, clamped to the free space between the button groups. The bar now sits inside invisible margins that carry a drop shadow, so the window is resizable from outside the visible frame: the surface is content plus twice SHADOW_MARGIN and xdg_surface.set_window_geometry tells the compositor which part is the window. The shadow follows Adwaita's window shadow: a Gaussian blur of 7 px (sigma 3.5) expanded by 1 px, rgba(0,0,0,0.5) focused and 0.3 in the backdrop, plus a 1 px hairline, symmetric on all four sides - a 16 px wide frame would show a fatter tail than the reference. Margins exist only while the window is decorated by us and not maximized or fullscreen. The engine composes the frame itself: it renders exactly as before, then the backend copies the frame into a texture, clears the surface, draws the shadow and puts the content in place with alpha forced to 1, which keeps the frame opaque without touching a single render pass. Only frames the engine actually drew are cached, and the EGL window is resized before its surface size is asked for, so no frame is composed from a buffer the compositor just replaced - that was the one frame blink after a resize. Resize cursors match GNOME: directional shapes for edges and corners (w/e/n/s/ne/nw/se/sw) instead of the double-headed diagonals, with the extra CursorShape values appended so the existing GLFW indices stay. Measured: window 1123x751 opens as saved, fullscreen round trip returns the same size with the settings untouched, the shadow alpha profile is 0.20/0.10/0.03 at 1/4/7 px from the edge against Adwaita's 0.21/0.095/ 0.055, all four sides equal, menu layout baseline unchanged (706), no errors in the log. --- res/textures/gui/maximize_w.png | Bin 0 -> 186 bytes res/textures/gui/minimize_w.png | Bin 0 -> 178 bytes res/textures/gui/restore_w.png | Bin 0 -> 182 bytes src/engine/WindowBar.cpp | 41 +++- src/graphics/core/commons.hpp | 17 ++ src/window/wayland/WaylandDecorations.cpp | 80 ++++++-- src/window/wayland/WaylandInit.cpp | 53 +++-- src/window/wayland/WaylandInput.hpp | 16 ++ src/window/wayland/WaylandListeners.cpp | 8 +- src/window/wayland/WaylandWindow.cpp | 238 +++++++++++++++++++++- src/window/wayland/WaylandWindow.hpp | 39 +++- 11 files changed, 434 insertions(+), 58 deletions(-) create mode 100644 res/textures/gui/maximize_w.png create mode 100644 res/textures/gui/minimize_w.png create mode 100644 res/textures/gui/restore_w.png diff --git a/res/textures/gui/maximize_w.png b/res/textures/gui/maximize_w.png new file mode 100644 index 0000000000000000000000000000000000000000..c710bf8145156dda07a3813ff1ae500b1cbd82f5 GIT binary patch literal 186 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jPK-BC>eK@{Ea{HEjtmSN z`?>!lvI6-E$sR$z3=CCj3=9n|3=F@3LJcn%7)lKo7+xhXFj&oCU=S~uvn$XBC}H90 z;uvCaIypfi;{ZqUpa1{=+j~k$0)d2t#0-s6MsB^yg^VTBgWfa+GP5-^>a;wX`Akou af`Oq#nn$9ID`pkY3eK@{Ea{HEjtmSN z`?>!lvI6-E$sR$z3=CCj3=9n|3=F@3LJcn%7)lKo7+xhXFj&oCU=S~uvn$XBC}H5~ z;uvCaIypgtb#a1-0SFwD_zwjBliYxS4G7d$q)p0gdzpCfnba;OhCT1OnB~3&?F8y& N@O1TaS?83{1OR>UF$n+w literal 0 HcmV?d00001 diff --git a/res/textures/gui/restore_w.png b/res/textures/gui/restore_w.png new file mode 100644 index 0000000000000000000000000000000000000000..fc245c1a614695e500ac553ce992aef0170753af GIT binary patch literal 182 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jPK-BC>eK@{Ea{HEjtmSN z`?>!lvI6-E$sR$z3=CCj3=9n|3=F@3LJcn%7)lKo7+xhXFj&oCU=S~uvn$XBC}HC1 z;uvCaIypgtwdV!Xe<0`&XI573l2h}FJ>ay)cSnrdMsBuy40944G|W~!YYIGYfPuj> Wm`C8)oaG%r{S2P2elF{r5}E*?elv&w literal 0 HcmV?d00001 diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp index ff0f33ecd..618df3a1e 100644 --- a/src/engine/WindowBar.cpp +++ b/src/engine/WindowBar.cpp @@ -7,6 +7,7 @@ #include #include "graphics/core/Shader.hpp" #include "graphics/core/Font.hpp" +#include "graphics/core/Texture.hpp" #include "graphics/ui/GUI.hpp" #include "window/Window.hpp" #include "assets/Assets.hpp" @@ -78,10 +79,19 @@ void draw_window_bar(Engine& engine) { titleLength--; } if (titleLength > 0) { + const float textWidth = static_cast( + font->calcWidth(title, titleLength) + ); + const float centered = (static_cast(size.x) - textWidth) * 0.5f; + const float titleX = std::clamp( + centered, + titleLeft, + std::max(titleLeft, titleRight - textWidth) + ); batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f)); font->draw( *batch, std::wstring_view(title).substr(0, titleLength), - static_cast(titleLeft), + static_cast(titleX), (height - font->getLineHeight()) / 2, nullptr, 0 ); @@ -96,15 +106,34 @@ void draw_window_bar(Engine& engine) { const float cy = barHeight * 0.5f; const bool isHovered = hovered == static_cast(i); if (isHovered) { - batch->setColor( - item.button == DecorationButton::CLOSE - ? glm::vec4(0.62f, 0.13f, 0.09f, 0.9f) - : glm::vec4(1.0f, 1.0f, 1.0f, 0.16f) + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.16f)); + const float button = item.width; + batch->rect( + item.x, (barHeight - button) * 0.5f, item.width, button ); - batch->rect(x, 0.0f, item.width, barHeight); } const float ink = isHovered ? 1.0f : 0.8f; batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink)); + const char* iconName = + item.button == DecorationButton::CLOSE + ? "gui/cross" + : item.button == DecorationButton::MINIMIZE + ? "gui/minimize_w" + : window.isMaximized() ? "gui/restore_w" + : "gui/maximize_w"; + auto icon = engine.requireAssets().getShared(iconName); + if (icon != nullptr) { + const float iconSize = std::min( + 16.0f, static_cast(icon->getWidth()) + ); + batch->texture(icon.get()); + batch->rect( + cx - iconSize * 0.5f, cy - iconSize * 0.5f, iconSize, + iconSize, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, ink + ); + batch->untexture(); + continue; + } if (item.button == DecorationButton::CLOSE) { for (int step = 0; step < 8; step++) { batch->rect(cx - 5.0f + step, cy - 5.0f + step, thickness, thickness); diff --git a/src/graphics/core/commons.hpp b/src/graphics/core/commons.hpp index 0ca5a6470..6c09d5b43 100644 --- a/src/graphics/core/commons.hpp +++ b/src/graphics/core/commons.hpp @@ -46,6 +46,15 @@ enum class CursorShape { ALL_RESIZE, /// @brief Operation not allowed NOT_ALLOWED, + /// @brief Corner resize arrows + N_RESIZE, + S_RESIZE, + E_RESIZE, + W_RESIZE, + NE_RESIZE, + NW_RESIZE, + SE_RESIZE, + SW_RESIZE, LAST=NOT_ALLOWED }; @@ -74,6 +83,14 @@ VC_ENUM_METADATA(CursorShape) {"nesw-resize", CursorShape::NESW_RESIZE}, {"all-resize", CursorShape::ALL_RESIZE}, {"not-allowed", CursorShape::NOT_ALLOWED}, + {"n-resize", CursorShape::N_RESIZE}, + {"s-resize", CursorShape::S_RESIZE}, + {"e-resize", CursorShape::E_RESIZE}, + {"w-resize", CursorShape::W_RESIZE}, + {"ne-resize", CursorShape::NE_RESIZE}, + {"nw-resize", CursorShape::NW_RESIZE}, + {"se-resize", CursorShape::SE_RESIZE}, + {"sw-resize", CursorShape::SW_RESIZE}, VC_ENUM_END class Flushable { diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp index d72544f11..ead71b136 100644 --- a/src/window/wayland/WaylandDecorations.cpp +++ b/src/window/wayland/WaylandDecorations.cpp @@ -147,16 +147,18 @@ void WaylandWindow::updateButtonLayout() { void WaylandWindow::updateBarGeometry() { barButtons.clear(); const float width = static_cast(size.x); + constexpr float pitch = BAR_BUTTON + BAR_GAP; for (size_t i = 0; i < leftButtons.size(); i++) { - const float x = static_cast(i) * BAR_BUTTON; + const float x = BAR_PADDING + static_cast(i) * pitch; if (x + BAR_BUTTON > width) { break; } barButtons.push_back({leftButtons[i], x, BAR_BUTTON}); } for (size_t i = 0; i < rightButtons.size(); i++) { - const float x = width - - static_cast(rightButtons.size() - i) * BAR_BUTTON; + const float x = width - BAR_PADDING - + static_cast(rightButtons.size() - i) * pitch + + BAR_GAP; if (x < 0.0f) { break; } @@ -193,7 +195,8 @@ bool WaylandWindow::barVisible() const { } int WaylandWindow::barButtonAt(double x, double y) const { - if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { + constexpr int top = (BAR_HEIGHT - BAR_BUTTON) / 2; + if (!barVisible() || y < top || y >= top + BAR_BUTTON) { return -1; } for (size_t i = 0; i < barButtons.size(); i++) { @@ -232,21 +235,56 @@ CursorShape WaylandWindow::edgeCursor(uint32_t edges) { const bool right = edges & XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; const bool top = edges & XDG_TOPLEVEL_RESIZE_EDGE_TOP; const bool bottom = edges & XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; - if ((left && top) || (right && bottom)) { - return CursorShape::NWSE_RESIZE; + if (left && top) { + return CursorShape::NW_RESIZE; } - if ((right && top) || (left && bottom)) { - return CursorShape::NESW_RESIZE; + if (right && top) { + return CursorShape::NE_RESIZE; } - if (left || right) { - return CursorShape::EW_RESIZE; + if (left && bottom) { + return CursorShape::SW_RESIZE; } - if (top || bottom) { - return CursorShape::NS_RESIZE; + if (right && bottom) { + return CursorShape::SE_RESIZE; + } + if (left) { + return CursorShape::W_RESIZE; + } + if (right) { + return CursorShape::E_RESIZE; + } + if (top) { + return CursorShape::N_RESIZE; + } + if (bottom) { + return CursorShape::S_RESIZE; } return CursorShape::ARROW; } +uint32_t WaylandWindow::pointerEdges() const { + const int margin = marginSize(); + uint32_t edges = 0; + if (margin > 0) { + const auto surface = surfaceSize(); + const int edge = margin + RESIZE_GRAB_EXTRA; + if (pointerX < edge) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT; + } else if (pointerX >= surface.x - edge) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; + } + if (pointerY < edge) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; + } else if (pointerY >= surface.y - edge) { + edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM; + } + } + if (edges == 0 && margin == 0) { + edges = barEdgeAt(contentX(pointerX), contentY(pointerY)); + } + return edges; +} + bool WaylandWindow::handleBarMotion(double x, double y) { pointerX = x; pointerY = y; @@ -257,20 +295,22 @@ bool WaylandWindow::handleBarMotion(double x, double y) { hoveredButton = -1; xdg_toplevel_move(state.toplevel, state.seat, barPressSerial); } - const uint32_t edges = barEdgeAt(x, y); + const uint32_t edges = pointerEdges(); if (edges != 0) { hoveredButton = -1; pointerInBar = false; input.setOverrideCursor(edgeCursor(edges)); return true; } - const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; + const double contentY = this->contentY(y); + const bool inBar = barVisible() && contentY >= 0.0 && contentY < BAR_HEIGHT; if (inBar && !pointerInBar) { lastLayoutCheck = 0.0; } pointerInBar = inBar; if (inBar) { - hoveredButton = barDragging ? -1 : barButtonAt(x, y); + hoveredButton = + barDragging ? -1 : barButtonAt(contentX(x), contentY); input.setOverrideCursor( hoveredButton >= 0 ? CursorShape::POINTER : CursorShape::ARROW ); @@ -282,9 +322,9 @@ bool WaylandWindow::handleBarMotion(double x, double y) { } bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) { - const double x = pointerX; - const double y = pointerY; - const uint32_t edges = barEdgeAt(x, y); + const double x = contentX(pointerX); + const double y = contentY(pointerY); + const uint32_t edges = pointerEdges(); const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; if (button != 0) { return inBar || edges != 0; @@ -345,8 +385,8 @@ bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) { } bool WaylandWindow::handleBarScroll() const { - return (barVisible() && pointerY >= 0.0 && pointerY < BAR_HEIGHT) || - barEdgeAt(pointerX, pointerY) != 0; + const double y = contentY(pointerY); + return (barVisible() && y >= 0.0 && y < BAR_HEIGHT) || pointerEdges() != 0; } void WaylandWindow::onPointerLeave() { diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp index 667a71523..d8904a487 100644 --- a/src/window/wayland/WaylandInit.cpp +++ b/src/window/wayland/WaylandInit.cpp @@ -120,33 +120,46 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { eglBindAPI(EGL_OPENGL_API); EGLint samples = settings->samples.get(); + const EGLint requestedSamples = samples > 0 ? samples : 0; EGLConfig config = nullptr; EGLint configCount = 0; - const EGLint configAttributes[] { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, - EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, - EGL_SAMPLES, samples > 0 ? samples : 0, - EGL_NONE - }; - eglChooseConfig(window->eglDisplay, configAttributes, &config, 1, &configCount); - if (samples > 0 && configCount == 0) { - waylandLogger.warning() << "multisampling is not available"; - const EGLint fallbackAttributes[] { + const auto chooseConfig = [&] (EGLint alpha, EGLint sampleCount) { + const EGLint attributes[] { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_ALPHA_SIZE, alpha, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_SAMPLES, sampleCount, EGL_NONE }; + config = nullptr; + configCount = 0; eglChooseConfig( - window->eglDisplay, fallbackAttributes, &config, 1, &configCount + window->eglDisplay, attributes, &config, 1, &configCount ); - } - if (configCount == 0) { - waylandLogger.error() << "no suitable EGL config"; - return {nullptr, nullptr}; + if (configCount == 0) { + return false; + } + EGLint value = 0; + eglGetConfigAttrib( + window->eglDisplay, config, EGL_ALPHA_SIZE, &value + ); + window->shadowEnabled = value >= 8; + return true; + }; + if (!chooseConfig(8, requestedSamples)) { + if (requestedSamples > 0) { + waylandLogger.warning() << "multisampling is not available"; + } + if (!chooseConfig(8, 0)) { + waylandLogger.warning() + << "no EGL config with alpha, the drop shadow is off"; + if (!chooseConfig(0, requestedSamples) && !chooseConfig(0, 0)) { + waylandLogger.error() << "no suitable EGL config"; + return {nullptr, nullptr}; + } + window->shadowEnabled = false; + } } const EGLint contextAttributes[] { @@ -157,8 +170,9 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { window->eglContext = eglCreateContext( window->eglDisplay, config, EGL_NO_CONTEXT, contextAttributes ); + const auto surfaceSize = window->surfaceSize(); window->eglWindow = wl_egl_window_create( - state.surface, window->getSize().x, window->getSize().y + state.surface, surfaceSize.x, surfaceSize.y ); window->eglSurface = eglCreateWindowSurface( window->eglDisplay, config, @@ -184,6 +198,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { } window->initStretchRenderer(); + window->initShadowRenderer(); glViewport(0, 0, window->getSize().x, window->getSize().y); glClearColor(0.0f, 0.0f, 0.0f, 1); glEnable(GL_BLEND); diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp index b04bde572..a83e52d84 100644 --- a/src/window/wayland/WaylandInput.hpp +++ b/src/window/wayland/WaylandInput.hpp @@ -217,6 +217,22 @@ private: return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE; case CursorShape::ALL_RESIZE: return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE; + case CursorShape::N_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_N_RESIZE; + case CursorShape::S_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_S_RESIZE; + case CursorShape::E_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_E_RESIZE; + case CursorShape::W_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_W_RESIZE; + case CursorShape::NE_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NE_RESIZE; + case CursorShape::NW_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NW_RESIZE; + case CursorShape::SE_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SE_RESIZE; + case CursorShape::SW_RESIZE: + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SW_RESIZE; case CursorShape::NOT_ALLOWED: return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED; } diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index d92393678..ed2efe249 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -15,7 +15,9 @@ static void pointer_enter( return; } if (input) { - input->setCursorPosition(x, y); + input->setCursorPosition( + window ? window->contentX(x) : x, window ? window->contentY(y) : y + ); if (state.entered) { input->applyCursor(); } @@ -39,7 +41,9 @@ static void pointer_motion( return; } if (input) { - input->setCursorPosition(x, y); + input->setCursorPosition( + window ? window->contentX(x) : x, window ? window->contentY(y) : y + ); input->refreshWindow(); } } diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index 3c4748d8d..aa4eb1474 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -45,6 +45,9 @@ WaylandWindow::~WaylandWindow() { if (stretchProgram) { glDeleteProgram(stretchProgram); } + if (shadowProgram) { + glDeleteProgram(shadowProgram); + } if (stretchVbo) { glDeleteBuffers(1, &stretchVbo); } @@ -96,14 +99,21 @@ void WaylandWindow::swapBuffers() { if (renderPending) { cacheContent(); renderPending = false; - } else { + } else if (marginSize() == 0) { drawStretched(); } - } else { + } else if (frameRendered) { cacheContent(); } + frameRendered = false; + composeFrame(); requestFrame(); eglSwapBuffers(eglDisplay, eglSurface); + if (sizeChanged) { + sizeChanged = false; + composeFrame(); + eglSwapBuffers(eglDisplay, eglSurface); + } resetScissor(); frameDone = false; presentPending = false; @@ -119,7 +129,7 @@ void WaylandWindow::swapBuffers() { 1.0 / 30.0 ); } -} + } lastPresent = current; nextFrameTime = current + frameInterval; lastSwapEnd = now(); @@ -160,7 +170,11 @@ bool WaylandWindow::isIconified() const { } bool WaylandWindow::isFrameRequired() const { - return !resizing || renderPending; + const bool required = !resizing || renderPending; + if (required) { + frameRendered = true; + } + return required; } bool WaylandWindow::isShouldClose() const { @@ -234,19 +248,47 @@ void WaylandWindow::setMaximized(bool enabled) { } } +int WaylandWindow::marginSize() const { + if (!barEnabled || !shadowEnabled) { + return 0; + } + if (fullscreen || maximized || Window::mode != WindowMode::WINDOWED) { + return 0; + } + return SHADOW_MARGIN; +} + +glm::ivec2 WaylandWindow::surfaceSize() const { + const int margin = marginSize() * 2; + return {size.x + margin, size.y + margin}; +} + +void WaylandWindow::updateWindowGeometry() { + if (state.xdgSurface == nullptr) { + return; + } + const int margin = marginSize(); + xdg_surface_set_window_geometry( + state.xdgSurface, margin, margin, size.x, size.y + ); +} + void WaylandWindow::resize(int width, int height) { if (width <= 0 || height <= 0) { return; } if (size.x != width || size.y != height) { markResizing(); + sizeChanged = true; } presentPending = true; + size = {width, height}; if (eglWindow) { - wl_egl_window_resize(eglWindow, width, height, 0, 0); + const auto surface = surfaceSize(); + wl_egl_window_resize(eglWindow, surface.x, surface.y, 0, 0); } glViewport(0, 0, width, height); - size = {width, height}; + updateWindowGeometry(); if (Window::mode == WindowMode::WINDOWED && !maximized) { settings->width.set(width); settings->height.set(height); @@ -281,11 +323,12 @@ void WaylandWindow::applyConfigure() { maximized = stateMaximized; suspended = stateSuspended; if (pendingWidth > 0 && pendingHeight > 0) { - if (!configured && Window::mode == WindowMode::WINDOWED && !maximized && - initialWidth > 0 && initialHeight > 0) { + if (!initialSizeApplied && Window::mode == WindowMode::WINDOWED && + !maximized && initialWidth > 0 && initialHeight > 0) { pendingWidth = initialWidth; pendingHeight = initialHeight; } + initialSizeApplied = true; resize(pendingWidth, pendingHeight); } if (stateActivated && !activated) { @@ -358,9 +401,18 @@ std::unique_ptr WaylandWindow::takeScreenshot() { GLint readBuffer = 0; glGetIntegerv(GL_READ_BUFFER, &readBuffer); glReadBuffer(GL_FRONT); + const int margin = marginSize(); auto data = std::make_unique(size.x * size.y * 3); glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); + glReadPixels( + margin, + margin, + size.x, + size.y, + GL_RGB, + GL_UNSIGNED_BYTE, + data.get() + ); glReadBuffer(static_cast(readBuffer)); return std::make_unique( ImageFormat::RGB888, size.x, size.y, data.release() @@ -416,6 +468,174 @@ void WaylandWindow::initStretchRenderer() { glGenTextures(1, &cacheTexture); } +void WaylandWindow::initShadowRenderer() { + if (!shadowEnabled) { + return; + } + static const char* vertexSource = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "out vec2 vUV;\n" + "void main() {\n" + " vUV = aPos * 0.5 + 0.5;\n" + " gl_Position = vec4(aPos, 0.0, 1.0);\n" + "}\n"; + static const char* fragmentSource = + "#version 330 core\n" + "in vec2 vUV;\n" + "out vec4 color;\n" + "uniform vec2 uSurface;\n" + "uniform vec4 uRect;\n" + "uniform float uBlur;\n" + "uniform float uStrength;\n" + "uniform float uOffset;\n" + "uniform float uSpread;\n" + "uniform float uBorder;\n" + "uniform float uRadius;\n" + "float erfcApprox(float x) {\n" + " float t = 1.0 / (1.0 + 0.5 * abs(x));\n" + " float tau = t * exp(-x * x - 1.26551223 +\n" + " t * (1.00002368 +\n" + " t * (0.37409196 +\n" + " t * (0.09678418 +\n" + " t * (-0.18628806 +\n" + " t * (0.27886807 +\n" + " t * (-1.13520398 +\n" + " t * (1.48851587 +\n" + " t * (-0.82215223 +\n" + " t * 0.17087277)))))))));\n" + " return x >= 0.0 ? tau : 2.0 - tau;\n" + "}\n" + "float boxDistance(vec2 p, vec2 center, vec2 halfSize, float radius) {\n" + " vec2 q = abs(p - center) - (halfSize - vec2(radius));\n" + " return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;\n" + "}\n" + "void main() {\n" + " vec2 p = vUV * uSurface;\n" + " vec2 halfSize = uRect.zw * 0.5;\n" + " vec2 center = uRect.xy + halfSize;\n" + " float shadow = boxDistance(\n" + " p, center + vec2(0.0, -uOffset), halfSize + uSpread,\n" + " uRadius + uSpread\n" + " );\n" + " float sigma = max(uBlur * 0.5, 0.001);\n" + " float alpha = uStrength * 0.5 * erfcApprox(shadow / (sigma * 1.41421356));\n" + " float side = boxDistance(p, center, halfSize, uRadius);\n" + " float border = side > 0.0 && side <= 1.0 ? uBorder : 0.0;\n" + " color = vec4(0.0, 0.0, 0.0, max(alpha, border));\n" + "}\n"; + shadowProgram = compile_program(vertexSource, fragmentSource); + GLint linked = 0; + glGetProgramiv(shadowProgram, GL_LINK_STATUS, &linked); + if (shadowProgram == 0 || linked == 0) { + char log[1024] = {}; + glGetProgramInfoLog(shadowProgram, sizeof(log), nullptr, log); + for (char* c = log; *c != '\0'; c++) { + if (*c == '\n') { + *c = ' '; + } + } + waylandLogger.error() << "failed to build the shadow shader: " << log; + shadowEnabled = false; + return; + } + const char* names[] { + "uSurface", "uRect", "uBlur", "uStrength", "uOffset", "uSpread", + "uBorder", "uRadius", nullptr + }; + for (int i = 0; names[i] != nullptr; i++) { + shadowUniforms[i] = glGetUniformLocation(shadowProgram, names[i]); + } + +} + +void WaylandWindow::drawShadow() { + const int margin = marginSize(); + if (margin <= 0 || shadowProgram == 0) { + return; + } + const auto surface = surfaceSize(); + glViewport(0, 0, surface.x, surface.y); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + glUseProgram(shadowProgram); + glUniform2f( + shadowUniforms[0], + static_cast(surface.x), + static_cast(surface.y) + ); + glUniform4f( + shadowUniforms[1], + static_cast(margin), + static_cast(margin), + static_cast(size.x), + static_cast(size.y) + ); + glUniform1f(shadowUniforms[2], 7.0f); + glUniform1f(shadowUniforms[3], activated ? 0.5f : 0.3f); + glUniform1f(shadowUniforms[4], 0.0f); + glUniform1f(shadowUniforms[5], 1.0f); + glUniform1f(shadowUniforms[6], activated ? 0.1f : 0.05f); + glUniform1f(shadowUniforms[7], 0.0f); + glBindVertexArray(stretchVao); + glDrawArrays(GL_TRIANGLES, 0, 3); + glBindVertexArray(0); + glUseProgram(0); +} + +void WaylandWindow::makeContentOpaque(int x, int y, int width, int height) { + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); + glEnable(GL_SCISSOR_TEST); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glScissor(x, y, width, height); + glClear(GL_COLOR_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); +} + +void WaylandWindow::composeFrame() { + const int margin = marginSize(); + GlStateGuard state; + glBindFramebuffer(GL_FRAMEBUFFER, 0); + if (margin <= 0) { + makeContentOpaque(0, 0, size.x, size.y); + return; + } + const auto surface = surfaceSize(); + glViewport(0, 0, surface.x, surface.y); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_BLEND); + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); + drawShadow(); + if (stretchProgram == 0 || cacheWidth == 0) { + glEnable(GL_SCISSOR_TEST); + glScissor(margin, margin, size.x, size.y); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + return; + } + glViewport(margin, margin, size.x, size.y); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + glUseProgram(stretchProgram); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, cacheTexture); + glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glBindVertexArray(stretchVao); + glDrawArrays(GL_TRIANGLES, 0, 3); + glBindVertexArray(0); + glUseProgram(0); + makeContentOpaque(margin, margin, size.x, size.y); +} + void WaylandWindow::resizeCache(int width, int height) { if (cacheWidth == width && cacheHeight == height) { return; diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 6186b9433..38a822992 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -55,6 +55,9 @@ double barPressX = 0.0; double barPressY = 0.0; uint32_t barPressSerial = 0; bool barPressed = false; +bool initialSizeApplied = false; +mutable bool frameRendered = false; +bool sizeChanged = false; bool barDragging = false; int barPressedButton = -1; int initialWidth = 0; @@ -113,9 +116,40 @@ glm::vec4 scissorArea {}; - static constexpr int BAR_HEIGHT = 30; - static constexpr int BAR_BUTTON = 30; + static constexpr int BAR_HEIGHT = 48; + static constexpr int BAR_BUTTON = 24; + static constexpr int BAR_PADDING = 12; + static constexpr int BAR_GAP = 12; static constexpr int BAR_EDGE = 8; + static constexpr int SHADOW_MARGIN = 10; + static constexpr int RESIZE_GRAB_EXTRA = 2; + bool shadowEnabled = false; + GLuint shadowProgram = 0; + + GLint shadowUniforms[7] {}; + + int marginSize() const; + + double contentX(double x) const { + return x - marginSize(); + } + + double contentY(double y) const { + return y - marginSize(); + } + + glm::ivec2 surfaceSize() const; + + void updateWindowGeometry(); + + void initShadowRenderer(); + + void drawShadow(); + + void composeFrame(); + + void makeContentOpaque(int x, int y, int width, int height); + int decorationOffset() const { return barVisible() ? BAR_HEIGHT : 0; @@ -152,6 +186,7 @@ glm::vec4 scissorArea {}; int barButtonAt(double x, double y) const; uint32_t barEdgeAt(double x, double y) const; static CursorShape edgeCursor(uint32_t edges); + uint32_t pointerEdges() const; bool handleBarMotion(double x, double y); bool handleBarButton(uint32_t serial, int button, bool pressed); bool handleBarScroll() const; From b5416d1219ea1ae0c3a49425cd222496f1a175e5 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 23:07:58 +0300 Subject: [PATCH 13/35] Fix the issues found while reviewing the Wayland frame work A review of the branch turned up a number of defects, gaps and leftovers; this commit addresses all of them. Defects: - the shadow uniform array held seven entries while eight locations were written, so the last one landed outside the object; - CursorShape::LAST stayed in the middle of the enum after the new corner shapes were appended, which made the GLFW cursor table read out of bounds; the extra shapes are now mapped onto the ones GLFW knows, and the table is only filled for those; - GlStateGuard asked glIsEnabled for an attribute pname, so it always got GL_INVALID_ENUM and never restored the vertex attribute arrays; - the early returns in wayland_window_initialize left the global window and input pointers dangling when falling back to GLFW; - the icon textures were listed nowhere, so none of them ever loaded; - a shader failure disabled the shadow after the surface had already been sized for it, and VOXEL_DECORATIONS outlived the switch cleanup. Behavior: - the keyboard now releases every pressed key when it loses focus, and a repeat rate of zero means no repeat; - the fourth UTF-8 lead byte is decoded with the right mask, control characters no longer reach text fields, and a vanished clipboard offer clears the cached text; - compositor side decorations disable ours again instead of leaving two titles, the window destructor releases the rest of the state, and the content inset is computed before the GUI acts so the HUD and the container never disagree for a frame; the HUD clamps it; - the window controls fall back to minimize, maximize and close, and the icons are drawn from textures only. Cleanups: one monotonic timer instead of three, one vertex shader shared by both renderers with a link check, one button layout parser, the inset rule moved into Screen, the scissor stack moved into the base Window (about 110 duplicated lines), named shadow and evdev constants, trimmed includes, a README note about the Wayland dependencies, and the long lines introduced by this branch wrapped. --- README.md | 7 + res/preload.json | 3 + src/CMakeLists.txt | 4 +- src/engine/Engine.cpp | 13 +- src/engine/WindowBar.cpp | 43 ++---- src/frontend/hud.cpp | 9 +- src/frontend/screens/MenuScreen.hpp | 4 + src/frontend/screens/Screen.cpp | 5 + src/frontend/screens/Screen.hpp | 4 + src/graphics/core/commons.hpp | 2 +- src/graphics/ui/GUI.hpp | 7 + src/window/Window.cpp | 65 ++++++++ src/window/Window.hpp | 9 +- src/window/detail/GLFWWindow.cpp | 91 ++++-------- src/window/wayland/WaylandCommon.cpp | 34 ++++- src/window/wayland/WaylandCommon.hpp | 13 +- src/window/wayland/WaylandDecorations.cpp | 85 ++++++----- src/window/wayland/WaylandInit.cpp | 67 +++++++-- src/window/wayland/WaylandInput.hpp | 49 ++++-- src/window/wayland/WaylandListeners.cpp | 52 ++++--- src/window/wayland/WaylandListeners.hpp | 13 +- src/window/wayland/WaylandSettings.cpp | 5 +- src/window/wayland/WaylandSettings.hpp | 1 - src/window/wayland/WaylandWindow.cpp | 172 +++++++++------------- src/window/wayland/WaylandWindow.hpp | 168 +++++++++++---------- 25 files changed, 523 insertions(+), 402 deletions(-) diff --git a/README.md b/README.md index d040e7707..4443ca07f 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,13 @@ apt-get install entt-devel libglfw3-devel libGLEW-devel libglm-devel libpng-deve ```sh sudo apt install libglfw3 libglfw3-dev libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libcurl4-openssl-dev libssl-dev libfreetype6-dev + +#### Wayland (optional, enabled by default on Linux) + +The native Wayland backend needs `wayland-client`, `wayland-egl`, +`wayland-scanner`, `wayland-protocols`, `libxkbcommon` and EGL. Build with +`-DVOXELENGINE_WAYLAND=OFF` to fall back to GLFW; `libsystemd` (sd-bus) is +picked up automatically for the desktop button layout. ``` > [!TIP] diff --git a/res/preload.json b/res/preload.json index 51acb129c..b20c3602b 100644 --- a/res/preload.json +++ b/res/preload.json @@ -30,6 +30,9 @@ "gui/warning", "gui/error", "gui/cross", + "gui/minimize_w", + "gui/maximize_w", + "gui/restore_w", "gui/refresh", "gui/folder_icon", "gui/settings_icon", diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3ee250a4d..7cee11a0a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -127,8 +127,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) target_sources( VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) - target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) - target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) + target_include_directories(VoxelCoreSrc PRIVATE ${WAYLAND_GENERATED}) + target_compile_definitions(VoxelCoreSrc PRIVATE VOXELENGINE_WAYLAND=1) if(libsystemd_FOUND) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_SDBUS=1) target_link_libraries(VoxelCoreSrc PRIVATE PkgConfig::libsystemd) diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index 3e5edb371..a9ddccbc1 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,15 +1,12 @@ -#include - -#include - #include "Engine.hpp" -#include "frontend/screens/MenuScreen.hpp" #include "WindowBar.hpp" #ifndef GLEW_STATIC #define GLEW_STATIC #endif +#include + #include "AssetsManagement.hpp" #include "audio/audio.hpp" #include "coders/commons.hpp" @@ -276,6 +273,7 @@ void Engine::updateFrontend() { assets->update(); updateHotkeys(); audio::update(delta); + gui->setContentInset(screen->getContentInset(*window)); gui->act(delta, window->getSize()); screen->update(delta); gui->postAct(); @@ -324,11 +322,6 @@ void Engine::renderFrame() { screen->draw(time.getDelta()); DrawContext ctx(nullptr, *window, nullptr); - gui->setContentInset( - dynamic_cast(screen.get()) != nullptr - ? 0 - : window->getDecorationHeight() - ); gui->draw(ctx, *assets->getStorage()); draw_window_bar(*this); } diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp index 618df3a1e..0c28c0f7c 100644 --- a/src/engine/WindowBar.cpp +++ b/src/engine/WindowBar.cpp @@ -1,11 +1,11 @@ #include "WindowBar.hpp" #include "Engine.hpp" -#include "debug/Logger.hpp" #include "graphics/core/Batch2D.hpp" #include #include #include "graphics/core/Shader.hpp" +#include "constants.hpp" #include "graphics/core/Font.hpp" #include "graphics/core/Texture.hpp" #include "graphics/ui/GUI.hpp" @@ -23,9 +23,15 @@ namespace { return converter.from_bytes(text); } - constexpr const char* BAR_FONT = "normal"; + const std::string BAR_FONT = FONT_DEFAULT; } +/// @brief Draws the window bar the backend cannot draw itself. +/// +/// The bar lives in window coordinates while the GUI container is shifted +/// down by its height in game, so the GUI camera cannot be reused here: the +/// bar sets its own viewport and projection. It borrows the GUI batch only +/// because the ui shader it needs is the one the GUI already loads. void draw_window_bar(Engine& engine) { auto& window = engine.getWindow(); const int height = window.getDecorationHeight(); @@ -34,14 +40,17 @@ void draw_window_bar(Engine& engine) { } auto* batch = engine.getGUI().getBatch2D(); auto font = engine.requireAssets().getShared(BAR_FONT); - if (batch == nullptr || font == nullptr) { + if (font == nullptr) { return; } const auto size = window.getSize(); const float barHeight = static_cast(height); - glViewport(0, 0, static_cast(size.x), static_cast(size.y)); - if (auto shader = engine.requireAssets().get("ui"); shader != nullptr) { + glViewport( + 0, 0, static_cast(size.x), static_cast(size.y) + ); + auto shader = engine.requireAssets().get("ui"); + if (shader != nullptr) { shader->use(); shader->uniformMatrix( "u_projview", @@ -98,7 +107,6 @@ void draw_window_bar(Engine& engine) { batch->untexture(); } - const float thickness = 2.0f; for (size_t i = 0; i < buttons.size(); i++) { const auto& item = buttons[i]; const float x = item.x; @@ -132,29 +140,8 @@ void draw_window_bar(Engine& engine) { iconSize, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, ink ); batch->untexture(); - continue; - } - if (item.button == DecorationButton::CLOSE) { - for (int step = 0; step < 8; step++) { - batch->rect(cx - 5.0f + step, cy - 5.0f + step, thickness, thickness); - batch->rect(cx + 3.0f - step, cy - 5.0f + step, thickness, thickness); - } - } else if (item.button == DecorationButton::MINIMIZE) { - batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness); - } else if (!window.isMaximized()) { - batch->rect(cx - 6.0f, cy - 6.0f, 12.0f, thickness); - batch->rect(cx - 6.0f, cy + 4.0f, 12.0f, thickness); - batch->rect(cx - 6.0f, cy - 6.0f, thickness, 12.0f); - batch->rect(cx + 4.0f, cy - 6.0f, thickness, 12.0f); - } else { - batch->rect(cx - 7.0f, cy + 1.0f, 11.0f, thickness); - batch->rect(cx - 7.0f, cy + 1.0f, thickness, 6.0f); - batch->rect(cx + 2.0f, cy + 1.0f, thickness, 6.0f); - batch->rect(cx - 7.0f, cy + 5.0f, 11.0f, thickness); - batch->rect(cx - 2.0f, cy - 5.0f, 9.0f, thickness); - batch->rect(cx - 2.0f, cy - 5.0f, thickness, 6.0f); - batch->rect(cx + 5.0f, cy - 5.0f, thickness, 6.0f); } + } batch->flush(); } diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index 50748323e..cf5fdb303 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -625,9 +625,14 @@ void Hud::setDebug(bool flag) { void Hud::draw(const DrawContext& ctx){ const auto& viewport = ctx.getViewport(); - uint inset = static_cast(ctx.getWindow().getDecorationHeight()); + const int inset = gui.getContentInset(); + const int contentHeight = std::max( + 1, static_cast(viewport.y) - inset + ); - updateElementsPosition(glm::uvec2(viewport.x, viewport.y - inset)); + updateElementsPosition( + glm::uvec2(viewport.x, static_cast(contentHeight)) + ); uicamera->setFov(viewport.y); uicamera->setAspectRatio(viewport.x / static_cast(viewport.y)); diff --git a/src/frontend/screens/MenuScreen.hpp b/src/frontend/screens/MenuScreen.hpp index a8caf0fef..7f8f02ad5 100644 --- a/src/frontend/screens/MenuScreen.hpp +++ b/src/frontend/screens/MenuScreen.hpp @@ -15,6 +15,10 @@ public: void onOpen() override; + int getContentInset(const Window&) const override { + return 0; + } + void update(float delta) override; void draw(float delta) override; diff --git a/src/frontend/screens/Screen.cpp b/src/frontend/screens/Screen.cpp index 3fd648258..16e84e716 100644 --- a/src/frontend/screens/Screen.cpp +++ b/src/frontend/screens/Screen.cpp @@ -1,4 +1,5 @@ #include "Screen.hpp" +#include "window/Window.hpp" #include "graphics/core/Batch2D.hpp" #include "engine/Engine.hpp" @@ -10,3 +11,7 @@ Screen::Screen(Engine& engine) Screen::~Screen() { } + +int Screen::getContentInset(const Window& window) const { + return window.getDecorationHeight(); +} diff --git a/src/frontend/screens/Screen.hpp b/src/frontend/screens/Screen.hpp index c24dc8b38..44039b968 100644 --- a/src/frontend/screens/Screen.hpp +++ b/src/frontend/screens/Screen.hpp @@ -4,6 +4,7 @@ class Engine; class Batch2D; +class Window; /// @brief Screen is a mainloop state class Screen : public util::ObjectsKeeper { @@ -18,4 +19,7 @@ public: virtual void draw(float delta) = 0; virtual void onEngineShutdown() {}; virtual const char* getName() const = 0; + + /// @brief Inset of the GUI content from the top of the window + virtual int getContentInset(const Window& window) const; }; diff --git a/src/graphics/core/commons.hpp b/src/graphics/core/commons.hpp index 6c09d5b43..230c9b0db 100644 --- a/src/graphics/core/commons.hpp +++ b/src/graphics/core/commons.hpp @@ -56,7 +56,7 @@ enum class CursorShape { SE_RESIZE, SW_RESIZE, - LAST=NOT_ALLOWED + LAST=SW_RESIZE }; namespace advanced_pipeline { diff --git a/src/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index 4ccc51147..6cf84b919 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -123,6 +123,8 @@ namespace gui { /// @param assets active assets storage void draw(const DrawContext& pctx, Assets& assets); + /// @brief Offset of the main container from the top of the window, + /// e.g. the height of the engine drawn window bar int viewportOffset = 0; /// @brief Get the cursor position in the main container coordinates @@ -133,6 +135,11 @@ namespace gui { viewportOffset = inset; } + int getContentInset() const { + return viewportOffset; + } + + /// @brief Batch used to draw the window bar on top of the GUI Batch2D* getBatch2D() { return batch2D.get(); } diff --git a/src/window/Window.cpp b/src/window/Window.cpp index 48ba76076..e57535dec 100644 --- a/src/window/Window.cpp +++ b/src/window/Window.cpp @@ -6,6 +6,14 @@ #include +#ifndef GLEW_STATIC +#define GLEW_STATIC +#endif + +#include + +#include + static debug::Logger logger("window"); #ifdef VOXELENGINE_WAYLAND @@ -34,3 +42,60 @@ std::tuple< #endif return glfw_window_initialize(settings, std::move(title)); } + +void Window::pushScissor(glm::vec4 area) { + if (scissorStack.empty()) { + glEnable(GL_SCISSOR_TEST); + } + scissorStack.push(scissorArea); + + area.z += glm::ceil(area.x); + area.w += glm::ceil(area.y); + + area.x = glm::max(area.x, scissorArea.x); + area.y = glm::max(area.y, scissorArea.y); + + area.z = glm::min(area.z, scissorArea.z); + area.w = glm::min(area.w, scissorArea.w); + + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(glm::ceil(area.z - area.x))), + std::max(0, static_cast(glm::ceil(area.w - area.y))) + ); + } + scissorArea = area; +} + +void Window::popScissor() { + if (scissorStack.empty()) { + logger.warning() << "extra Window::popScissor call"; + return; + } + glm::vec4 area = scissorStack.top(); + scissorStack.pop(); + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(area.z - area.x)), + std::max(0, static_cast(area.w - area.y)) + ); + } + if (scissorStack.empty()) { + glDisable(GL_SCISSOR_TEST); + } + scissorArea = area; +} + +void Window::resetScissor() { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); + scissorStack = std::stack(); + glDisable(GL_SCISSOR_TEST); +} diff --git a/src/window/Window.hpp b/src/window/Window.hpp index 020e36c0a..d0a62394a 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -80,9 +81,9 @@ public: virtual void setIcon(const ImageData* image) = 0; - virtual void pushScissor(glm::vec4 area) = 0; - virtual void popScissor() = 0; - virtual void resetScissor() = 0; + virtual void pushScissor(glm::vec4 area); + virtual void popScissor(); + virtual void resetScissor(); virtual void setShouldRefresh() = 0; virtual bool checkShouldRefresh() = 0; @@ -104,6 +105,8 @@ public: > initialize(DisplaySettings* settings, std::string title); protected: glm::ivec2 size; + std::stack scissorStack; + glm::vec4 scissorArea {}; WindowMode mode = WindowMode::WINDOWED; }; diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 88161de93..ee772c3cd 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -185,6 +185,26 @@ static void glfw_error_callback(int error, const char* description) { static GLFWcursor* standard_cursors[static_cast(CursorShape::LAST) + 1] = {}; +/// @brief Map extra cursor shapes onto the ones GLFW knows about +static int cursor_index(CursorShape shape) { + switch (shape) { + case CursorShape::N_RESIZE: + case CursorShape::S_RESIZE: + return static_cast(CursorShape::NS_RESIZE); + case CursorShape::E_RESIZE: + case CursorShape::W_RESIZE: + return static_cast(CursorShape::EW_RESIZE); + case CursorShape::NE_RESIZE: + case CursorShape::SW_RESIZE: + return static_cast(CursorShape::NESW_RESIZE); + case CursorShape::NW_RESIZE: + case CursorShape::SE_RESIZE: + return static_cast(CursorShape::NWSE_RESIZE); + default: + return static_cast(shape); + } +} + class GLFWInput : public BaseInput { public: GLFWInput(GLFWwindow* window) @@ -245,7 +265,9 @@ public: ~GLFWWindow() { for (int i = 0; i <= static_cast(CursorShape::LAST); i++) { - glfwDestroyCursor(standard_cursors[i]); + if (standard_cursors[i] != nullptr) { + glfwDestroyCursor(standard_cursors[i]); + } } glfwTerminate(); } @@ -307,7 +329,7 @@ public: } cursor = shape; // nullptr cursor is valid for GLFW - glfwSetCursor(window, standard_cursors[static_cast(shape)]); + glfwSetCursor(window, standard_cursors[cursor_index(shape)]); } void setMode(WindowMode mode) override { @@ -397,64 +419,7 @@ public: } } - void pushScissor(glm::vec4 area) override { - if (scissorStack.empty()) { - glEnable(GL_SCISSOR_TEST); - } - scissorStack.push(scissorArea); - - area.z += glm::ceil(area.x); - area.w += glm::ceil(area.y); - - area.x = glm::max(area.x, scissorArea.x); - area.y = glm::max(area.y, scissorArea.y); - - area.z = glm::min(area.z, scissorArea.z); - area.w = glm::min(area.w, scissorArea.w); - - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(glm::ceil(area.z - area.x))), - std::max(0, static_cast(glm::ceil(area.w - area.y))) - ); - } - scissorArea = area; - } - - void resetScissor() override { - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - scissorStack = std::stack(); - glDisable(GL_SCISSOR_TEST); - } - - void popScissor() override { - if (scissorStack.empty()) { - logger.warning() << "extra Window::popScissor call"; - return; - } - glm::vec4 area = scissorStack.top(); - scissorStack.pop(); - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(area.z - area.x)), - std::max(0, static_cast(area.w - area.y)) - ); - } - if (scissorStack.empty()) { - glDisable(GL_SCISSOR_TEST); - } - scissorArea = area; - } - - std::unique_ptr takeScreenshot() override { + std::unique_ptr takeScreenshot() override { glBindFramebuffer(GL_FRAMEBUFFER, 0); auto data = std::make_unique(size.x * size.y * 3); glPixelStorei(GL_PACK_ALIGNMENT, 1); @@ -475,8 +440,6 @@ private: GLFWwindow* window; CursorShape cursor = CursorShape::ARROW; int framerate = -1; - std::stack scissorStack; - glm::vec4 scissorArea {}; double prevSwap = 0.0; int posX = 0; int posY = 0; @@ -547,7 +510,9 @@ static void iconify_callback(GLFWwindow* window, int iconified) { } static void create_standard_cursors() { - for (int i = 0; i <= static_cast(CursorShape::LAST); i++) { + // GLFW knows only the shapes up to NOT_ALLOWED, the rest are mapped + // onto them by cursor_index() + for (int i = 0; i <= static_cast(CursorShape::NOT_ALLOWED); i++) { int cursor = GLFW_ARROW_CURSOR + i; // GLFW 3.3 does not support some cursors if (GLFW_VERSION_MAJOR <= 3 && GLFW_VERSION_MINOR <= 3 && diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp index 5ea51bbae..be4afff39 100644 --- a/src/window/wayland/WaylandCommon.cpp +++ b/src/window/wayland/WaylandCommon.cpp @@ -5,6 +5,21 @@ debug::Logger waylandLogger("window"); +const char* WAYLAND_VERTEX_SHADER = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "out vec2 vUV;\n" + "void main() {\n" + " vUV = aPos * 0.5 + 0.5;\n" + " gl_Position = vec4(aPos, 0.0, 1.0);\n" + "}\n"; + +double waylandNow() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); +} + GlStateGuard::GlStateGuard() { glGetIntegerv(GL_CURRENT_PROGRAM, &values[0]); @@ -25,12 +40,20 @@ GlStateGuard::GlStateGuard() { glGetIntegerv(GL_VIEWPORT, viewport); glGetIntegerv(GL_COLOR_WRITEMASK, colorMask); for (int i = 0; i < 3; i++) { - attribFlags[i] = glIsEnabled(GL_VERTEX_ATTRIB_ARRAY_ENABLED + i); + GLint attribEnabled = 0; + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &attribEnabled + ); + attribFlags[i] = attribEnabled != 0; glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &attribs[i][0]); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &attribs[i][1]); - glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &attribs[i][2]); + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &attribs[i][2] + ); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &attribs[i][3]); - glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][5]); + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][5] + ); void* pointer = nullptr; glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer); attribs[i][6] = static_cast(reinterpret_cast(pointer)); @@ -102,11 +125,6 @@ class WaylandWindow; WaylandInput* input = nullptr; WaylandWindow* window = nullptr; -bool decorations_enabled() { - const char* value = getenv("VOXEL_DECORATIONS"); - return value == nullptr || strcmp(value, "none") != 0; -} - bool serverDecorations = false; int keycode_from_keysym(xkb_keysym_t sym) { diff --git a/src/window/wayland/WaylandCommon.hpp b/src/window/wayland/WaylandCommon.hpp index 3407a0ef1..f1378a2ec 100644 --- a/src/window/wayland/WaylandCommon.hpp +++ b/src/window/wayland/WaylandCommon.hpp @@ -28,15 +28,9 @@ #include #include #include -#include #include #include -const wl_registry_listener& registry_listener(); -const wl_data_device_listener& data_device_listener(); -const xdg_surface_listener& surface_listener(); -const xdg_toplevel_listener& toplevel_listener(); - struct GlStateGuard { GLint values[16] {}; GLint attribs[3][7] {}; @@ -52,6 +46,12 @@ GLuint compile_program(const char* vertexSource, const char* fragmentSource); extern debug::Logger waylandLogger; +/// @brief Monotonic time in seconds, shared by the whole backend +double waylandNow(); + +/// @brief Fullscreen triangle vertex shader used by the backend renderers +extern const char* WAYLAND_VERTEX_SHADER; + struct WaylandState { wl_display* display = nullptr; wl_registry* registry = nullptr; @@ -97,7 +97,6 @@ template void ignore_event(Args...) { } -bool decorations_enabled(); void dispatch_events(int timeoutMs); int keycode_from_keysym(xkb_keysym_t sym); diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp index ead71b136..e9f0b1341 100644 --- a/src/window/wayland/WaylandDecorations.cpp +++ b/src/window/wayland/WaylandDecorations.cpp @@ -4,10 +4,7 @@ #include #include -#include #include -#include -#include namespace { constexpr const char* LAYOUT_SCHEMA = "org.gnome.desktop.wm.preferences"; @@ -19,7 +16,8 @@ namespace { while (start <= text.size()) { const size_t end = text.find(',', start); const std::string name = text.substr( - start, end == std::string::npos ? std::string::npos : end - start + start, + end == std::string::npos ? std::string::npos : end - start ); if (name == "close") { buttons.push_back(DecorationButton::CLOSE); @@ -36,8 +34,30 @@ namespace { return buttons; } + void split_layout( + const std::string& value, std::vector& left, + std::vector& right + ) { + std::string text = value; + text.erase( + std::remove_if(text.begin(), text.end(), [] (char c) { + return c == '\'' || c == '"' || c == '\n' || c == '\r'; + }), + text.end() + ); + const size_t separator = text.find(':'); + if (separator == std::string::npos) { + left.clear(); + right = parse_buttons(text); + } else { + left = parse_buttons(text.substr(0, separator)); + right = parse_buttons(text.substr(separator + 1)); + } + } + bool read_button_layout( - std::vector& left, std::vector& right + std::vector& left, + std::vector& right ) { FILE* pipe = popen( "gsettings get org.gnome.desktop.wm.preferences button-layout" @@ -53,46 +73,20 @@ namespace { if (line == nullptr || status != 0) { return false; } - std::string value(buffer); - value.erase( - std::remove_if(value.begin(), value.end(), [] (char c) { - return c == '\'' || c == '"' || c == '\n' || c == '\r'; - }), - value.end() - ); - const size_t separator = value.find(':'); - if (separator == std::string::npos) { - left.clear(); - right = parse_buttons(value); - } else { - left = parse_buttons(value.substr(0, separator)); - right = parse_buttons(value.substr(separator + 1)); - } + split_layout(std::string(buffer), left, right); return true; } constexpr double DRAG_THRESHOLD = 5.0; + constexpr double LAYOUT_CHECK_INTERVAL = 2.0; constexpr double DOUBLE_CLICK_TIME = 0.4; constexpr double DOUBLE_CLICK_DISTANCE = 8.0; } void WaylandWindow::applyLayoutValue(const std::string& rawValue) { - std::string value = rawValue; - value.erase( - std::remove_if(value.begin(), value.end(), [] (char c) { - return c == '\'' || c == '"' || c == '\n' || c == '\r'; - }), - value.end() - ); - const size_t separator = value.find(':'); std::vector left; std::vector right; - if (separator == std::string::npos) { - right = parse_buttons(value); - } else { - left = parse_buttons(value.substr(0, separator)); - right = parse_buttons(value.substr(separator + 1)); - } + split_layout(rawValue, left, right); if (left == leftButtons && right == rightButtons) { return; } @@ -127,7 +121,7 @@ void WaylandWindow::updateButtonLayout() { return; } const double current = now(); - if (current - lastLayoutCheck < 2.0) { + if (current - lastLayoutCheck < LAYOUT_CHECK_INTERVAL) { return; } lastLayoutCheck = current; @@ -145,6 +139,14 @@ void WaylandWindow::updateButtonLayout() { } void WaylandWindow::updateBarGeometry() { + if (leftButtons.empty() && rightButtons.empty()) { + // desktop layout is unavailable, fall back to the usual three controls + rightButtons = { + DecorationButton::MINIMIZE, + DecorationButton::MAXIMIZE, + DecorationButton::CLOSE, + }; + } barButtons.clear(); const float width = static_cast(size.x); constexpr float pitch = BAR_BUTTON + BAR_GAP; @@ -166,7 +168,8 @@ void WaylandWindow::updateBarGeometry() { } } -const std::vector& WaylandWindow::getDecorationButtons() const { +const std::vector& +WaylandWindow::getDecorationButtons() const { return barButtons; } @@ -183,10 +186,16 @@ int WaylandWindow::getDecorationHoveredButton() const { } void WaylandWindow::enableOwnDecorations() { - if (!decorations_enabled()) { + barEnabled = true; + setShouldRefresh(); +} + +void WaylandWindow::disableOwnDecorations() { + if (!barEnabled) { return; } - barEnabled = true; + barEnabled = false; + resize(size.x, size.y); setShouldRefresh(); } diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp index d8904a487..25823cd9e 100644 --- a/src/window/wayland/WaylandInit.cpp +++ b/src/window/wayland/WaylandInit.cpp @@ -11,6 +11,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { state.display = wl_display_connect(nullptr); if (state.display == nullptr) { waylandLogger.error() << "could not connect to the Wayland display"; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } state.registry = wl_display_get_registry(state.display); @@ -27,6 +33,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { waylandLogger.error() << "the compositor does not provide xdg-shell"; wl_display_disconnect(state.display); state.display = nullptr; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } @@ -44,15 +56,15 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { state.dataDeviceManager, state.seat ); static const wl_data_device_listener deviceListener = [] { - wl_data_device_listener value {}; - value.data_offer = data_device_data_offer; - value.enter = ignore_event<>; - value.leave = ignore_event<>; - value.motion = ignore_event<>; - value.drop = ignore_event<>; - value.selection = data_device_selection; - return value; - }(); + wl_data_device_listener value {}; + value.data_offer = data_device_data_offer; + value.enter = ignore_event<>; + value.leave = ignore_event<>; + value.motion = ignore_event<>; + value.drop = ignore_event<>; + value.selection = data_device_selection; + return value; + }(); wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); } @@ -105,7 +117,13 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { while (!window->configured) { if (wl_display_dispatch(state.display) == -1) { waylandLogger.error() << "the Wayland connection was lost"; - return {nullptr, nullptr}; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } + return {nullptr, nullptr}; } } @@ -115,6 +133,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { if (window->eglDisplay == EGL_NO_DISPLAY || eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { waylandLogger.error() << "could not initialize EGL"; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } eglBindAPI(EGL_OPENGL_API); @@ -156,7 +180,13 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { << "no EGL config with alpha, the drop shadow is off"; if (!chooseConfig(0, requestedSamples) && !chooseConfig(0, 0)) { waylandLogger.error() << "no suitable EGL config"; - return {nullptr, nullptr}; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } + return {nullptr, nullptr}; } window->shadowEnabled = false; } @@ -185,6 +215,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { window->eglContext ) == EGL_FALSE) { waylandLogger.error() << "could not create the OpenGL context"; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } eglSwapInterval(window->eglDisplay, 0); @@ -194,6 +230,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { waylandLogger.error() << "failed to initialize GLEW:\n" << glewGetErrorString(glewError); + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } @@ -208,7 +250,8 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); if (maxTextureSize[0] > 0) { Texture::MAX_RESOLUTION = maxTextureSize[0]; - waylandLogger.info() << "max texture size is " << Texture::MAX_RESOLUTION; + waylandLogger.info() + << "max texture size is " << Texture::MAX_RESOLUTION; } waylandLogger.info() << "GL Vendor: " << reinterpret_cast(glGetString(GL_VENDOR)); diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp index a83e52d84..bf9071a30 100644 --- a/src/window/wayland/WaylandInput.hpp +++ b/src/window/wayland/WaylandInput.hpp @@ -16,6 +16,9 @@ #include #include +/// @brief Offset between the evdev keycode and the xkb one +static constexpr uint32_t XKB_KEYCODE_OFFSET = 8; + class WaylandInput : public BaseInput { public: void pollEvents(bool waitForRefresh) override; @@ -83,7 +86,9 @@ public: close(clipboardFd); clipboardFd = -1; } - wl_data_device_set_selection(state.dataDevice, source, state.inputSerial); + wl_data_device_set_selection( + state.dataDevice, source, state.inputSerial + ); wl_display_flush(state.display); } @@ -154,6 +159,20 @@ public: applyCursor(); } + /// @brief Release every pressed key, e.g. when the keyboard focus is lost + void releasePressedKeys() { + const auto keys = pressedKeys; + for (auto key : keys) { + onKeyCallback(static_cast(key), false); + } + repeatKeycode = 0; + } + + /// @brief Forget the cached clipboard text + void clearClipboardText() { + clipboard.clear(); + } + void onRelativeMotion(double dx, double dy) { delta.x += dx; delta.y += dy; @@ -163,7 +182,7 @@ public: if (state.xkbState == nullptr || state.xkbKeymap == nullptr) { return; } - xkb_keycode_t code = key + 8; + xkb_keycode_t code = key + XKB_KEYCODE_OFFSET; const xkb_keysym_t* syms = nullptr; if (xkb_keymap_key_get_syms_by_level( state.xkbKeymap, code, 0, 0, &syms @@ -244,9 +263,7 @@ private: } static double now() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); + return waylandNow(); } void appendCodepoints(xkb_keycode_t code) { @@ -264,18 +281,26 @@ private: codepoint = (codepoint << 6) | (bytes[i] & 0x3F); continue; } - if (codepoint != 0) { + if (codepoint >= 0x20 && codepoint != 0x7F) { codepoints.push_back(codepoint); } - codepoint = (bytes[i] & 0x80) ? (bytes[i] & 0x1F) : bytes[i]; + if ((bytes[i] & 0x80) == 0) { + codepoint = bytes[i]; + } else if ((bytes[i] & 0xE0) == 0xC0) { + codepoint = bytes[i] & 0x1F; + } else if ((bytes[i] & 0xF0) == 0xE0) { + codepoint = bytes[i] & 0x0F; + } else { + codepoint = bytes[i] & 0x07; + } } - if (codepoint != 0) { + if (codepoint >= 0x20 && codepoint != 0x7F) { codepoints.push_back(codepoint); } } void updateRepeat() { - if (repeatKeycode == 0 || !state.xkbState) { + if (repeatKeycode == 0 || state.repeatRate == 0 || !state.xkbState) { return; } int keycode = 0; @@ -321,8 +346,10 @@ private: ) { if (input) { const std::string& text = input->sourceText; - if (!text.empty() && write(fd, text.data(), text.size()) < 0) { - waylandLogger.warning() << "could not write to the clipboard"; + if (!text.empty() && + write(fd, text.data(), text.size()) < 0) { + waylandLogger.warning() + << "could not write to the clipboard"; } } close(fd); diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index ed2efe249..10e4ed0e3 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -53,19 +53,15 @@ static void pointer_button( uint32_t buttonState ) { state.inputSerial = serial; - int index = -1; - switch (button) { - case 0x110: index = 0; break; - case 0x111: index = 1; break; - case 0x112: index = 2; break; - case 0x113: index = 3; break; - case 0x114: index = 4; break; - case 0x115: index = 5; break; - case 0x116: index = 6; break; - case 0x117: index = 7; break; - } + // BTN_LEFT .. BTN_TASK from linux/input-event-codes.h + constexpr uint32_t EVDEV_BUTTON_FIRST = 0x110; + constexpr uint32_t EVDEV_BUTTON_LAST = 0x117; + int index = button >= EVDEV_BUTTON_FIRST && button <= EVDEV_BUTTON_LAST + ? static_cast(button - EVDEV_BUTTON_FIRST) + : -1; const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; - if (index >= 0 && window && window->handleBarButton(serial, index, pressed)) { + if (index >= 0 && window && + window->handleBarButton(serial, index, pressed)) { return; } if (index >= 0 && input) { @@ -129,6 +125,9 @@ static void keyboard_enter( } static void keyboard_leave(void*, wl_keyboard*, uint32_t, wl_surface*) { + if (input) { + input->releasePressedKeys(); + } } static void keyboard_key( @@ -154,8 +153,10 @@ static void keyboard_modifiers( } } -static void keyboard_repeat_info(void*, wl_keyboard*, int32_t rate, int32_t delay) { - state.repeatRate = rate > 0 ? rate : 25; +static void keyboard_repeat_info( + void*, wl_keyboard*, int32_t rate, int32_t delay +) { + state.repeatRate = rate > 0 ? static_cast(rate) : 0; state.repeatDelay = delay > 0 ? delay : 400; } @@ -273,8 +274,13 @@ void data_device_selection(void*, wl_data_device*, wl_data_offer* offer) { wl_data_offer_destroy(input->selection); } input->selection = offer; - input->selectionMimes = std::move(input->pendingMimes); input->pendingMimes.clear(); + if (offer == nullptr) { + input->selectionMimes.clear(); + input->clearClipboardText(); + return; + } + input->selectionMimes = std::move(input->pendingMimes); input->requestClipboardText(); } @@ -314,14 +320,18 @@ void registry_global( std::min(version, 3u) ) ); - } else if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) { + } else if ( + strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0 + ) { state.cursorShapeManager = static_cast( wl_registry_bind( registry, name, &wp_cursor_shape_manager_v1_interface, std::min(version, 2u) ) ); - } else if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) { + } else if ( + strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0 + ) { state.pointerConstraints = static_cast( wl_registry_bind( registry, name, &zwp_pointer_constraints_v1_interface, 1 @@ -360,8 +370,12 @@ void zxdg_decoration_configure( void*, zxdg_toplevel_decoration_v1*, uint32_t mode ) { serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; - if (!serverDecorations && window != nullptr) { - window->enableOwnDecorations(); + if (window != nullptr) { + if (serverDecorations) { + window->disableOwnDecorations(); + } else { + window->enableOwnDecorations(); + } } } diff --git a/src/window/wayland/WaylandListeners.hpp b/src/window/wayland/WaylandListeners.hpp index a8ea8bf28..c78e9dd5e 100644 --- a/src/window/wayland/WaylandListeners.hpp +++ b/src/window/wayland/WaylandListeners.hpp @@ -2,13 +2,20 @@ #include "window/wayland/WaylandCommon.hpp" -void toplevel_configure(void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states); +void toplevel_configure( + void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states +); void toplevel_close(void*, xdg_toplevel*); void toplevel_configure_bounds(void*, xdg_toplevel*, int32_t, int32_t); void toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*); void xdg_surface_configure(void*, xdg_surface* surface, uint32_t serial); void data_device_data_offer(void*, wl_data_device*, wl_data_offer* offer); void data_device_selection(void*, wl_data_device*, wl_data_offer* offer); -void registry_global(void*, wl_registry* registry, uint32_t name, const char* interface, uint32_t version); +void registry_global( + void*, wl_registry* registry, uint32_t name, const char* interface, + uint32_t version +); void registry_global_remove(void*, wl_registry*, uint32_t); -void zxdg_decoration_configure(void*, zxdg_toplevel_decoration_v1*, uint32_t mode); +void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +); diff --git a/src/window/wayland/WaylandSettings.cpp b/src/window/wayland/WaylandSettings.cpp index 58817b16f..aeb2360b3 100644 --- a/src/window/wayland/WaylandSettings.cpp +++ b/src/window/wayland/WaylandSettings.cpp @@ -30,7 +30,8 @@ namespace { } if (type == 's') { const char* text = nullptr; - if (sd_bus_message_read(message, "s", &text) < 0 || text == nullptr) { + if (sd_bus_message_read(message, "s", &text) < 0 || + text == nullptr) { return {}; } return text; @@ -167,8 +168,6 @@ bool SettingsWatcher::poll( } impl->changed = false; value = impl->changedValue; - (void)schema; - (void)key; return true; #else return false; diff --git a/src/window/wayland/WaylandSettings.hpp b/src/window/wayland/WaylandSettings.hpp index 30012e9e3..878b379f5 100644 --- a/src/window/wayland/WaylandSettings.hpp +++ b/src/window/wayland/WaylandSettings.hpp @@ -16,7 +16,6 @@ public: private: bool open(); void close(); - bool handleMessage(const char* schema, const char* key, std::string& value); struct Impl; Impl* impl = nullptr; diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index aa4eb1474..8467dadd4 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -1,9 +1,5 @@ #include "window/wayland/WaylandWindow.hpp" -#include -#include -#include - #include "settings.hpp" #include "graphics/core/Texture.hpp" #include "util/platform.hpp" @@ -20,6 +16,9 @@ WaylandWindow::WaylandWindow( } WaylandWindow::~WaylandWindow() { + if (window == this) { + window = nullptr; + } if (state.idleInhibitor) { zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); } @@ -81,12 +80,30 @@ WaylandWindow::~WaylandWindow() { if (eglDisplay != EGL_NO_DISPLAY) { eglTerminate(eglDisplay); } + if (state.pointer) { + wl_pointer_destroy(state.pointer); + state.pointer = nullptr; + } + if (state.keyboard) { + wl_keyboard_destroy(state.keyboard); + state.keyboard = nullptr; + } + if (state.seat) { + wl_seat_destroy(state.seat); + state.seat = nullptr; + } + if (state.xkbState) { + xkb_state_unref(state.xkbState); + state.xkbState = nullptr; + } + if (state.xkbKeymap) { + xkb_keymap_unref(state.xkbKeymap); + state.xkbKeymap = nullptr; + } } double WaylandWindow::time() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); + return now(); } void WaylandWindow::swapBuffers() { @@ -297,7 +314,9 @@ void WaylandWindow::resize(int width, int height) { scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); } -void WaylandWindow::onConfigure(int32_t width, int32_t height, wl_array* states) { +void WaylandWindow::onConfigure( + int32_t width, int32_t height, wl_array* states +) { pendingWidth = width; pendingHeight = height; stateMaximized = false; @@ -339,63 +358,6 @@ void WaylandWindow::applyConfigure() { setShouldRefresh(); } -void WaylandWindow::pushScissor(glm::vec4 area) { - if (scissorStack.empty()) { - glEnable(GL_SCISSOR_TEST); - } - scissorStack.push(scissorArea); - - area.z += glm::ceil(area.x); - area.w += glm::ceil(area.y); - - area.x = glm::max(area.x, scissorArea.x); - area.y = glm::max(area.y, scissorArea.y); - - area.z = glm::min(area.z, scissorArea.z); - area.w = glm::min(area.w, scissorArea.w); - - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(glm::ceil(area.z - area.x))), - std::max(0, static_cast(glm::ceil(area.w - area.y))) - ); - } - scissorArea = area; -} - -void WaylandWindow::popScissor() { - if (scissorStack.empty()) { - waylandLogger.warning() << "extra Window::popScissor call"; - return; - } - glm::vec4 area = scissorStack.top(); - scissorStack.pop(); - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(area.z - area.x)), - std::max(0, static_cast(area.w - area.y)) - ); - } - if (scissorStack.empty()) { - glDisable(GL_SCISSOR_TEST); - } - scissorArea = area; -} - -void WaylandWindow::resetScissor() { - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - scissorStack = std::stack(); - glDisable(GL_SCISSOR_TEST); -} - std::unique_ptr WaylandWindow::takeScreenshot() { glBindFramebuffer(GL_FRAMEBUFFER, 0); GLint readBuffer = 0; @@ -424,14 +386,6 @@ void WaylandWindow::setFramerate(int framerate) { } void WaylandWindow::initStretchRenderer() { - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "out vec2 vUV;\n" - "void main() {\n" - " vUV = aPos * 0.5 + 0.5;\n" - " gl_Position = vec4(aPos, 0.0, 1.0);\n" - "}\n"; static const char* fragmentSource = "#version 330 core\n" "in vec2 vUV;\n" @@ -440,18 +394,15 @@ void WaylandWindow::initStretchRenderer() { "void main() {\n" " color = texture(uTexture, vUV);\n" "}\n"; - GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexSource, nullptr); - glCompileShader(vertexShader); - GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); - glCompileShader(fragmentShader); - stretchProgram = glCreateProgram(); - glAttachShader(stretchProgram, vertexShader); - glAttachShader(stretchProgram, fragmentShader); - glLinkProgram(stretchProgram); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); + stretchProgram = compile_program(WAYLAND_VERTEX_SHADER, fragmentSource); + GLint stretchLinked = 0; + glGetProgramiv(stretchProgram, GL_LINK_STATUS, &stretchLinked); + if (stretchProgram == 0 || stretchLinked == 0) { + waylandLogger.error() << "failed to build the stretch shader"; + stretchProgram = 0; + return; + } + stretchTextureUniform = glGetUniformLocation(stretchProgram, "uTexture"); const float vertices[] {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f}; glGenVertexArrays(1, &stretchVao); @@ -472,14 +423,6 @@ void WaylandWindow::initShadowRenderer() { if (!shadowEnabled) { return; } - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "out vec2 vUV;\n" - "void main() {\n" - " vUV = aPos * 0.5 + 0.5;\n" - " gl_Position = vec4(aPos, 0.0, 1.0);\n" - "}\n"; static const char* fragmentSource = "#version 330 core\n" "in vec2 vUV;\n" @@ -506,7 +449,8 @@ void WaylandWindow::initShadowRenderer() { " t * 0.17087277)))))))));\n" " return x >= 0.0 ? tau : 2.0 - tau;\n" "}\n" - "float boxDistance(vec2 p, vec2 center, vec2 halfSize, float radius) {\n" + "float boxDistance(vec2 p, vec2 center, vec2 halfSize, float radius)" + " {\n" " vec2 q = abs(p - center) - (halfSize - vec2(radius));\n" " return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;\n" "}\n" @@ -519,12 +463,13 @@ void WaylandWindow::initShadowRenderer() { " uRadius + uSpread\n" " );\n" " float sigma = max(uBlur * 0.5, 0.001);\n" - " float alpha = uStrength * 0.5 * erfcApprox(shadow / (sigma * 1.41421356));\n" + " float alpha = uStrength * 0.5 * " + "erfcApprox(shadow / (sigma * 1.41421356));\n" " float side = boxDistance(p, center, halfSize, uRadius);\n" " float border = side > 0.0 && side <= 1.0 ? uBorder : 0.0;\n" " color = vec4(0.0, 0.0, 0.0, max(alpha, border));\n" "}\n"; - shadowProgram = compile_program(vertexSource, fragmentSource); + shadowProgram = compile_program(WAYLAND_VERTEX_SHADER, fragmentSource); GLint linked = 0; glGetProgramiv(shadowProgram, GL_LINK_STATUS, &linked); if (shadowProgram == 0 || linked == 0) { @@ -537,6 +482,7 @@ void WaylandWindow::initShadowRenderer() { } waylandLogger.error() << "failed to build the shadow shader: " << log; shadowEnabled = false; + resize(size.x, size.y); return; } const char* names[] { @@ -549,6 +495,15 @@ void WaylandWindow::initShadowRenderer() { } +namespace { + constexpr float SHADOW_BLUR = 7.0f; + constexpr float SHADOW_SPREAD = 1.0f; + constexpr float SHADOW_STRENGTH = 0.5f; + constexpr float SHADOW_STRENGTH_BACKDROP = 0.3f; + constexpr float SHADOW_BORDER = 0.1f; + constexpr float SHADOW_BORDER_BACKDROP = 0.05f; +} + void WaylandWindow::drawShadow() { const int margin = marginSize(); if (margin <= 0 || shadowProgram == 0) { @@ -574,11 +529,17 @@ void WaylandWindow::drawShadow() { static_cast(size.x), static_cast(size.y) ); - glUniform1f(shadowUniforms[2], 7.0f); - glUniform1f(shadowUniforms[3], activated ? 0.5f : 0.3f); + glUniform1f(shadowUniforms[2], SHADOW_BLUR); + glUniform1f( + shadowUniforms[3], + activated ? SHADOW_STRENGTH : SHADOW_STRENGTH_BACKDROP + ); glUniform1f(shadowUniforms[4], 0.0f); - glUniform1f(shadowUniforms[5], 1.0f); - glUniform1f(shadowUniforms[6], activated ? 0.1f : 0.05f); + glUniform1f(shadowUniforms[5], SHADOW_SPREAD); + glUniform1f( + shadowUniforms[6], + activated ? SHADOW_BORDER : SHADOW_BORDER_BACKDROP + ); glUniform1f(shadowUniforms[7], 0.0f); glBindVertexArray(stretchVao); glDrawArrays(GL_TRIANGLES, 0, 3); @@ -628,7 +589,7 @@ void WaylandWindow::composeFrame() { glUseProgram(stretchProgram); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cacheTexture); - glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glUniform1i(stretchTextureUniform, 0); glBindVertexArray(stretchVao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); @@ -660,6 +621,9 @@ void WaylandWindow::resizeCache(int width, int height) { glBindTexture(GL_TEXTURE_2D, 0); } +/// @brief Copies the frame the engine just drew into a texture. +/// Runs every frame: composeFrame() rebuilds the window from this texture, +/// which keeps the engine itself unaware of the shadow margins. void WaylandWindow::cacheContent() { GlStateGuard state; if (stretchProgram == 0) { @@ -692,7 +656,7 @@ void WaylandWindow::drawStretched() { glUseProgram(stretchProgram); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cacheTexture); - glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glUniform1i(stretchTextureUniform, 0); glBindVertexArray(stretchVao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); @@ -790,7 +754,5 @@ const wl_callback_listener& WaylandWindow::frameListener() { } double WaylandWindow::now() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); + return waylandNow(); } diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 38a822992..a50c81313 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -15,84 +15,85 @@ #include class WaylandWindow : public Window { -public: -WaylandInput& input; -DisplaySettings* settings; -EGLDisplay eglDisplay = EGL_NO_DISPLAY; -EGLContext eglContext = EGL_NO_CONTEXT; -EGLSurface eglSurface = EGL_NO_SURFACE; -wl_egl_window* eglWindow = nullptr; -int32_t pendingWidth = 0; -int32_t pendingHeight = 0; -bool stateMaximized = false; -bool stateSuspended = false; -bool stateActivated = true; -bool configured = false; -static constexpr double RESIZE_TIMEOUT = 0.4; -static constexpr double FRAME_TIMEOUT = 0.025; -static constexpr double RESIZE_PAUSE = 0.12; -static constexpr double MIN_CACHE_TIMEOUT = 0.3; -static constexpr double MAX_CACHE_TIMEOUT = 3.0; -int framerate = -1; -double prevSwap = 0.0; -double lastResize = 0.0; -bool barEnabled = false; -bool fullscreen = false; -std::string title = "VoxelCore"; -int hoveredButton = -1; -bool pointerInBar = false; -SettingsWatcher settingsWatcher; -bool layoutRead = false; -void applyLayoutValue(const std::string& value); + public: + WaylandInput& input; + DisplaySettings* settings; + EGLDisplay eglDisplay = EGL_NO_DISPLAY; + EGLContext eglContext = EGL_NO_CONTEXT; + EGLSurface eglSurface = EGL_NO_SURFACE; + wl_egl_window* eglWindow = nullptr; + int32_t pendingWidth = 0; + int32_t pendingHeight = 0; + bool stateMaximized = false; + bool stateSuspended = false; + bool stateActivated = true; + bool configured = false; + static constexpr double RESIZE_TIMEOUT = 0.4; + static constexpr double FRAME_TIMEOUT = 0.025; + static constexpr double RESIZE_PAUSE = 0.12; + static constexpr double MIN_CACHE_TIMEOUT = 0.3; + static constexpr double MAX_CACHE_TIMEOUT = 3.0; + int framerate = -1; + double prevSwap = 0.0; + double lastResize = 0.0; + bool barEnabled = false; + bool fullscreen = false; + std::string title = "VoxelCore"; + int hoveredButton = -1; + bool pointerInBar = false; + SettingsWatcher settingsWatcher; + bool layoutRead = false; + void applyLayoutValue(const std::string& value); std::vector leftButtons; std::vector rightButtons; std::vector barButtons; double lastLayoutCheck = 0.0; -double lastBarPress = 0.0; -double lastBarPressX = 0.0; -double lastBarPressY = 0.0; -double barPressX = 0.0; -double barPressY = 0.0; -uint32_t barPressSerial = 0; -bool barPressed = false; -bool initialSizeApplied = false; -mutable bool frameRendered = false; -bool sizeChanged = false; -bool barDragging = false; -int barPressedButton = -1; -int initialWidth = 0; -int initialHeight = 0; -double pointerX = 0.0; -double pointerY = 0.0; -bool frameOnCallback = false; -double frameInterval = 0.0; -double nextFrameTime = 0.0; -double frameCost = 0.0; -double cacheTimeout = 0.5; -bool resizing = false; -bool renderPending = true; -bool presentPending = true; -double lastPresent = 0.0; -wl_callback* frameCallback = nullptr; -bool frameDone = false; -GLuint stretchProgram = 0; -GLuint stretchVao = 0; -GLuint stretchVbo = 0; -GLuint cacheFbo = 0; -GLuint cacheTexture = 0; -int cacheWidth = 0; -int cacheHeight = 0; -double lastCacheTime = 0.0; -double lastSwapEnd = 0.0; -bool shouldRefresh = true; -bool shouldClose = false; -bool maximized = false; -bool suspended = false; -bool activated = true; -bool focusWarning = false; -std::stack scissorStack; -glm::vec4 scissorArea {}; - WaylandWindow( WaylandInput& input, DisplaySettings* settings, int width, int height ); + double lastBarPress = 0.0; + double lastBarPressX = 0.0; + double lastBarPressY = 0.0; + double barPressX = 0.0; + double barPressY = 0.0; + uint32_t barPressSerial = 0; + bool barPressed = false; + bool initialSizeApplied = false; + mutable bool frameRendered = false; + bool sizeChanged = false; + bool barDragging = false; + int barPressedButton = -1; + int initialWidth = 0; + int initialHeight = 0; + double pointerX = 0.0; + double pointerY = 0.0; + bool frameOnCallback = false; + double frameInterval = 0.0; + double nextFrameTime = 0.0; + double frameCost = 0.0; + double cacheTimeout = 0.5; + bool resizing = false; + bool renderPending = true; + bool presentPending = true; + double lastPresent = 0.0; + wl_callback* frameCallback = nullptr; + bool frameDone = false; + GLuint stretchProgram = 0; + GLint stretchTextureUniform = -1; + GLuint stretchVao = 0; + GLuint stretchVbo = 0; + GLuint cacheFbo = 0; + GLuint cacheTexture = 0; + int cacheWidth = 0; + int cacheHeight = 0; + double lastCacheTime = 0.0; + double lastSwapEnd = 0.0; + bool shouldRefresh = true; + bool shouldClose = false; + bool maximized = false; + bool suspended = false; + bool activated = true; + bool focusWarning = false; + WaylandWindow( + WaylandInput& input, DisplaySettings* settings, int width, int height + ); ~WaylandWindow() override; double time() override; void swapBuffers() override; @@ -101,6 +102,9 @@ glm::vec4 scissorArea {}; bool isMaximized() const override; bool isFocused() const override; bool isIconified() const override; + /// @brief Whether the engine is going to draw a frame now. + /// The answer is remembered, so swapBuffers() can tell a freshly drawn + /// frame from a buffer the engine skipped (it would be undefined). bool isFrameRequired() const override; bool isShouldClose() const override; void setShouldClose(bool flag) override; @@ -113,9 +117,6 @@ glm::vec4 scissorArea {}; int getDecorationHeight() const override; int getDecorationHoveredButton() const override; - - - static constexpr int BAR_HEIGHT = 48; static constexpr int BAR_BUTTON = 24; static constexpr int BAR_PADDING = 12; @@ -126,7 +127,7 @@ glm::vec4 scissorArea {}; bool shadowEnabled = false; GLuint shadowProgram = 0; - GLint shadowUniforms[7] {}; + GLint shadowUniforms[8] {}; int marginSize() const; @@ -151,11 +152,8 @@ glm::vec4 scissorArea {}; void makeContentOpaque(int x, int y, int width, int height); - int decorationOffset() const { - return barVisible() ? BAR_HEIGHT : 0; - } - - const std::vector& getDecorationButtons() const override; + const std::vector& getDecorationButtons() const + override; void updateButtonLayout(); @@ -172,9 +170,6 @@ glm::vec4 scissorArea {}; void resize(int width, int height); void onConfigure(int32_t width, int32_t height, wl_array* states); void applyConfigure(); - void pushScissor(glm::vec4 area) override; - void popScissor() override; - void resetScissor() override; std::unique_ptr takeScreenshot() override; void setFramerate(int framerate) override; void initStretchRenderer(); @@ -182,6 +177,7 @@ glm::vec4 scissorArea {}; void cacheContent(); void drawStretched(); void enableOwnDecorations(); + void disableOwnDecorations(); bool barVisible() const; int barButtonAt(double x, double y) const; uint32_t barEdgeAt(double x, double y) const; From 543cab957965a1434b2e54366a0e3d89a5e1f259 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 23:09:38 +0300 Subject: [PATCH 14/35] Drop the manual trigger from the Windows workflow --- .github/workflows/windows.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index bcd9ff18e..ec5322bc0 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -5,7 +5,6 @@ on: branches: [ "main", "release-**"] pull_request: branches: [ "main", "dev" ] - workflow_dispatch: jobs: build-windows: From 01ed8b7dc5c073b5dbac667c1b9eb8333f9224ab Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 23:50:30 +0300 Subject: [PATCH 15/35] Fix 2D batch drawing with a stale texture binding Batch2D cached the bound texture and skipped the bind when the cache matched, but the render pipeline binds textures of its own and leaves a non-zero texture unit active. A rectangle drawn without a texture (the hud hotbar background and slot tiles) was then modulated by whatever texture was left bound, which made the hotbar darken for a single frame on every window resize. The batch now draws from texture unit 0 and compares the cached texture with the actual binding instead of trusting the cache. --- src/graphics/core/Batch2D.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/graphics/core/Batch2D.cpp b/src/graphics/core/Batch2D.cpp index 33265b49f..7d6a7c8fe 100644 --- a/src/graphics/core/Batch2D.cpp +++ b/src/graphics/core/Batch2D.cpp @@ -33,6 +33,7 @@ void Batch2D::setPrimitive(DrawPrimitive primitive) { void Batch2D::begin(){ currentTexture = nullptr; + glActiveTexture(GL_TEXTURE0); blank->bind(); region = blank->getUVRegion(); color = glm::vec4(1.0f); @@ -61,7 +62,16 @@ void Batch2D::vertex( } void Batch2D::texture(const Texture* newTexture){ - if (currentTexture == newTexture) { + // The batch is not the only owner of the texture unit: the render pipeline + // binds textures of its own, so the cached value is only a hint. Compare it + // with the actual binding, otherwise a rectangle without a texture is + // modulated by whatever texture is left bound. + glActiveTexture(GL_TEXTURE0); + const uint expected = + newTexture != nullptr ? newTexture->getId() : blank->getId(); + GLint bound = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound); + if (currentTexture == newTexture && static_cast(bound) == expected) { return; } flush(); From ab7f542d619aedbb3546d9ca67b81d0f5e3a4edb Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 00:12:37 +0300 Subject: [PATCH 16/35] Add display settings for the wayland window frame The frame the native wayland backend draws gets three switches in the display tab: a narrow 24px bar instead of the 48px one, the shadow with the outer resize area, and redrawing the content while the window is resized (off keeps the previous behaviour of stretching the last frame). The settings are applied at runtime: the bar geometry is rebuilt and the surface is resized together with the toplevel geometry, no restart needed. The narrow bar drops the insets and the gap of its controls, so that they sit flush against the window edge. The switches are hidden outside of the wayland backend, which reports its name through Window::getBackendName(). --- res/layouts/pages/settings_display.xml.lua | 16 ++++++ res/texts/ru_RU.txt | 6 +++ src/io/settings_io.cpp | 3 ++ src/logic/scripting/lua/libs/libapp.cpp | 6 +++ src/settings.hpp | 6 +++ src/window/Window.hpp | 2 + src/window/detail/GLFWWindow.cpp | 4 ++ src/window/wayland/WaylandDecorations.cpp | 26 +++++---- src/window/wayland/WaylandWindow.cpp | 62 +++++++++++++++++++--- src/window/wayland/WaylandWindow.hpp | 19 +++++++ 10 files changed, 133 insertions(+), 17 deletions(-) diff --git a/res/layouts/pages/settings_display.xml.lua b/res/layouts/pages/settings_display.xml.lua index a3941bf2a..b82bd0966 100644 --- a/res/layouts/pages/settings_display.xml.lua +++ b/res/layouts/pages/settings_display.xml.lua @@ -66,6 +66,22 @@ function on_open() "", app.get_setting("display.window-mode")) ) + -- these only affect the window frame the native wayland backend draws + if app.get_window_backend() == "wayland" then + create_checkbox( + "display.compact-window-bar", "Narrow Window Bar", + "display.compact-window-bar.tooltip" + ) + create_checkbox( + "display.window-shadow", "Window Shadow", + "display.window-shadow.tooltip" + ) + create_checkbox( + "display.live-resize", "Live Window Resize", + "display.live-resize.tooltip" + ) + end + create_checkbox("camera.shaking", "Camera Shaking") create_checkbox("camera.inertia", "Camera Inertia") create_checkbox("camera.fov-effects", "Camera FOV Effects") diff --git a/res/texts/ru_RU.txt b/res/texts/ru_RU.txt index 295d467af..6a95f8454 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -118,6 +118,12 @@ settings.microphone.None=Нет settings.Clouds quality=Качество облаков settings.Acoustic effects=Акустические эффекты settings.Microphone access=Доступ к микрофону +settings.Narrow Window Bar=Узкая шапка окна +settings.Window Shadow=Тень окна +settings.Live Window Resize=Живой ресайз окна +settings.display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px +settings.display.window-shadow.tooltip=Тень вокруг окна и внешняя область для изменения размера (без неё окно рисуется упрощённо) +settings.display.live-resize.tooltip=Перерисовывать содержимое окна при изменении размера (выключено — последний кадр растягивается) # Управление chunks.reload=Перезагрузить Чанки diff --git a/src/io/settings_io.cpp b/src/io/settings_io.cpp index e72cb009d..772b5ccd8 100644 --- a/src/io/settings_io.cpp +++ b/src/io/settings_io.cpp @@ -55,6 +55,9 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) { builder.add("limit-fps-iconified", &settings.display.limitFpsIconified); builder.add("window-mode", &settings.display.windowMode); builder.add("adaptive-menu-fps", &settings.display.adaptiveFpsInMenu); + builder.add("compact-window-bar", &settings.display.compactWindowBar); + builder.add("window-shadow", &settings.display.windowShadow); + builder.add("live-resize", &settings.display.liveResize); builder.addSection("camera"); builder.add("sensitivity", &settings.camera.sensitivity); diff --git a/src/logic/scripting/lua/libs/libapp.cpp b/src/logic/scripting/lua/libs/libapp.cpp index 0058fcada..b69908624 100644 --- a/src/logic/scripting/lua/libs/libapp.cpp +++ b/src/logic/scripting/lua/libs/libapp.cpp @@ -229,6 +229,11 @@ static int l_open_url(lua::State* L) { } +/// @brief Name of the windowing backend ("glfw" or "wayland") +static int l_get_window_backend(lua::State* L) { + return lua::pushstring(L, engine->getWindow().getBackendName()); +} + /// @brief Bring application window to focus static int l_focus(lua::State* L) { engine->getWindow().focus(); @@ -502,6 +507,7 @@ const luaL_Reg applib[] = { {"open_folder", lua::wrap}, {"open_url", lua::wrap}, /// window + {"get_window_backend", lua::wrap}, {"focus", lua::wrap}, {"set_title", lua::wrap}, {"quit", lua::wrap}, diff --git a/src/settings.hpp b/src/settings.hpp index 320d0fc8d..7d84d6786 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -38,6 +38,12 @@ struct DisplaySettings { FlagSetting limitFpsIconified {false}; /// @brief Adaptive framerate in menu (experimental) FlagSetting adaptiveFpsInMenu {false}; + /// @brief Draw the narrow (24px) window bar instead of the 48px one + FlagSetting compactWindowBar {false}; + /// @brief Draw the window shadow and keep the outer area for resizing + FlagSetting windowShadow {true}; + /// @brief Render the window content every frame while it is resized + FlagSetting liveResize {true}; }; struct ChunksSettings { diff --git a/src/window/Window.hpp b/src/window/Window.hpp index d0a62394a..b1840175c 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -64,6 +64,8 @@ public: return empty; } + virtual const char* getBackendName() const = 0; + virtual int getDecorationHeight() const { return 0; } diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index ee772c3cd..c1fa8e482 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -384,6 +384,10 @@ public: std::string title; + const char* getBackendName() const override { + return "glfw"; + } + const std::string& getTitle() const override { return title; } diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp index e9f0b1341..90a44d74b 100644 --- a/src/window/wayland/WaylandDecorations.cpp +++ b/src/window/wayland/WaylandDecorations.cpp @@ -149,18 +149,22 @@ void WaylandWindow::updateBarGeometry() { } barButtons.clear(); const float width = static_cast(size.x); - constexpr float pitch = BAR_BUTTON + BAR_GAP; + // The narrow bar has no room for the insets of the wide one, so its + // controls sit flush against the window edge and each other. + const float padding = compactBar() ? 0.0f : BAR_PADDING; + const float gap = compactBar() ? 0.0f : BAR_GAP; + const float pitch = BAR_BUTTON + gap; for (size_t i = 0; i < leftButtons.size(); i++) { - const float x = BAR_PADDING + static_cast(i) * pitch; + const float x = padding + static_cast(i) * pitch; if (x + BAR_BUTTON > width) { break; } barButtons.push_back({leftButtons[i], x, BAR_BUTTON}); } for (size_t i = 0; i < rightButtons.size(); i++) { - const float x = width - BAR_PADDING - + const float x = width - padding - static_cast(rightButtons.size() - i) * pitch + - BAR_GAP; + gap; if (x < 0.0f) { break; } @@ -178,7 +182,7 @@ const std::string& WaylandWindow::getTitle() const { } int WaylandWindow::getDecorationHeight() const { - return barVisible() ? BAR_HEIGHT : 0; + return barVisible() ? barHeight() : 0; } int WaylandWindow::getDecorationHoveredButton() const { @@ -204,7 +208,7 @@ bool WaylandWindow::barVisible() const { } int WaylandWindow::barButtonAt(double x, double y) const { - constexpr int top = (BAR_HEIGHT - BAR_BUTTON) / 2; + const int top = (barHeight() - BAR_BUTTON) / 2; if (!barVisible() || y < top || y >= top + BAR_BUTTON) { return -1; } @@ -221,7 +225,7 @@ uint32_t WaylandWindow::barEdgeAt(double x, double y) const { if (barButtonAt(x, y) >= 0) { return 0; } - const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; + const bool inBar = barVisible() && y >= 0.0 && y < barHeight(); uint32_t edges = 0; if (y < BAR_EDGE) { edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; @@ -312,7 +316,8 @@ bool WaylandWindow::handleBarMotion(double x, double y) { return true; } const double contentY = this->contentY(y); - const bool inBar = barVisible() && contentY >= 0.0 && contentY < BAR_HEIGHT; + const bool inBar = + barVisible() && contentY >= 0.0 && contentY < barHeight(); if (inBar && !pointerInBar) { lastLayoutCheck = 0.0; } @@ -334,7 +339,7 @@ bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) { const double x = contentX(pointerX); const double y = contentY(pointerY); const uint32_t edges = pointerEdges(); - const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT; + const bool inBar = barVisible() && y >= 0.0 && y < barHeight(); if (button != 0) { return inBar || edges != 0; } @@ -395,7 +400,8 @@ bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) { bool WaylandWindow::handleBarScroll() const { const double y = contentY(pointerY); - return (barVisible() && y >= 0.0 && y < BAR_HEIGHT) || pointerEdges() != 0; + return (barVisible() && y >= 0.0 && y < barHeight()) || + pointerEdges() != 0; } void WaylandWindow::onPointerLeave() { diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index 8467dadd4..9724d82a8 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -107,15 +107,22 @@ double WaylandWindow::time() { } void WaylandWindow::swapBuffers() { + updateSettings(); updateResizing(); if (resizing && !presentPending && !frameDone) { resetScissor(); return; } - if (resizing) { + if (liveResizeEnabled()) { + if (frameRendered) { + cacheContent(); + } + } else if (resizing) { + // While the pointer drags the window border the content is only + // redrawn when the engine asked for it, otherwise the last frame is + // stretched into the new size. if (renderPending) { cacheContent(); - renderPending = false; } else if (marginSize() == 0) { drawStretched(); } @@ -123,6 +130,7 @@ void WaylandWindow::swapBuffers() { cacheContent(); } frameRendered = false; + renderPending = false; composeFrame(); requestFrame(); eglSwapBuffers(eglDisplay, eglSurface); @@ -187,11 +195,18 @@ bool WaylandWindow::isIconified() const { } bool WaylandWindow::isFrameRequired() const { - const bool required = !resizing || renderPending; - if (required) { - frameRendered = true; + if (!liveResizeEnabled()) { + const bool required = !resizing || renderPending; + if (required) { + frameRendered = true; + } + return required; } - return required; + // The engine draws every frame, also while the window is being resized: + // resizing only paces the presentation now, it no longer freezes the + // content into a stretched copy of the last frame. + frameRendered = true; + return true; } bool WaylandWindow::isShouldClose() const { @@ -266,7 +281,8 @@ void WaylandWindow::setMaximized(bool enabled) { } int WaylandWindow::marginSize() const { - if (!barEnabled || !shadowEnabled) { + if (!barEnabled || !shadowEnabled || + (settings != nullptr && !settings->windowShadow.get())) { return 0; } if (fullscreen || maximized || Window::mode != WindowMode::WINDOWED) { @@ -275,6 +291,38 @@ int WaylandWindow::marginSize() const { return SHADOW_MARGIN; } +bool WaylandWindow::compactBar() const { + return settings != nullptr && settings->compactWindowBar.get(); +} + +int WaylandWindow::barHeight() const { + return compactBar() ? BAR_HEIGHT_COMPACT : BAR_HEIGHT; +} + +bool WaylandWindow::liveResizeEnabled() const { + return settings == nullptr || settings->liveResize.get(); +} + +void WaylandWindow::updateSettings() { + if (settings == nullptr) { + return; + } + const bool shadow = settings->windowShadow.get(); + if (shadow != shadowSetting) { + shadowSetting = shadow; + // The surface size depends on whether the frame around the content is + // drawn at all, so the egl window and the toplevel geometry change. + resize(size.x, size.y); + setShouldRefresh(); + } + const bool compactBar = settings->compactWindowBar.get(); + if (compactBar != compactBarSetting) { + compactBarSetting = compactBar; + updateBarGeometry(); + setShouldRefresh(); + } +} + glm::ivec2 WaylandWindow::surfaceSize() const { const int margin = marginSize() * 2; return {size.x + margin, size.y + margin}; diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index a50c81313..77bdd8543 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -114,10 +114,18 @@ class WaylandWindow : public Window { void focus() override; void setTitle(const std::string& title) override; const std::string& getTitle() const override; + const char* getBackendName() const override { + return "wayland"; + } + + /// @brief Whether the narrow window bar is selected + bool compactBar() const; + int getDecorationHeight() const override; int getDecorationHoveredButton() const override; static constexpr int BAR_HEIGHT = 48; + static constexpr int BAR_HEIGHT_COMPACT = 24; static constexpr int BAR_BUTTON = 24; static constexpr int BAR_PADDING = 12; static constexpr int BAR_GAP = 12; @@ -125,12 +133,23 @@ class WaylandWindow : public Window { static constexpr int SHADOW_MARGIN = 10; static constexpr int RESIZE_GRAB_EXTRA = 2; bool shadowEnabled = false; + bool shadowSetting = true; + bool compactBarSetting = false; GLuint shadowProgram = 0; GLint shadowUniforms[8] {}; int marginSize() const; + /// @brief Window bar height, which the display settings may reduce + int barHeight() const; + + /// @brief Whether the content is redrawn every frame during a resize + bool liveResizeEnabled() const; + + /// @brief Applies the display settings that affect the window frame + void updateSettings(); + double contentX(double x) const { return x - marginSize(); } From 27a58b584e994853b3a459d1305384c65ec94f9f Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 00:38:06 +0300 Subject: [PATCH 17/35] Fix black frames of the simple window and rename its setting Without the shadow and the resize border composeFrame() only forced the alpha channel, so the buffer the driver reallocated after a size change was presented as it is, which showed up as a black frame on every resize step. The content is now always painted from the cache and only the shadow itself is skipped when there are no margins. The setting is named simple-window and means the opposite of the previous shadow-and-border: it is off by default, so the window keeps its shadow and the outer border for resizing. --- res/layouts/pages/settings_display.xml.lua | 4 ++-- res/texts/ru_RU.txt | 4 ++-- src/io/settings_io.cpp | 2 +- src/settings.hpp | 4 ++-- src/window/wayland/WaylandWindow.cpp | 21 +++++++++++---------- src/window/wayland/WaylandWindow.hpp | 2 +- 6 files changed, 19 insertions(+), 18 deletions(-) diff --git a/res/layouts/pages/settings_display.xml.lua b/res/layouts/pages/settings_display.xml.lua index b82bd0966..8c7986989 100644 --- a/res/layouts/pages/settings_display.xml.lua +++ b/res/layouts/pages/settings_display.xml.lua @@ -73,8 +73,8 @@ function on_open() "display.compact-window-bar.tooltip" ) create_checkbox( - "display.window-shadow", "Window Shadow", - "display.window-shadow.tooltip" + "display.simple-window", "Simple Window", + "display.simple-window.tooltip" ) create_checkbox( "display.live-resize", "Live Window Resize", diff --git a/res/texts/ru_RU.txt b/res/texts/ru_RU.txt index 6a95f8454..97372af89 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -119,10 +119,10 @@ settings.Clouds quality=Качество облаков settings.Acoustic effects=Акустические эффекты settings.Microphone access=Доступ к микрофону settings.Narrow Window Bar=Узкая шапка окна -settings.Window Shadow=Тень окна +settings.Simple Window=Простое окно settings.Live Window Resize=Живой ресайз окна settings.display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px -settings.display.window-shadow.tooltip=Тень вокруг окна и внешняя область для изменения размера (без неё окно рисуется упрощённо) +settings.display.simple-window.tooltip=Без тени и внешней рамки ресайза settings.display.live-resize.tooltip=Перерисовывать содержимое окна при изменении размера (выключено — последний кадр растягивается) # Управление diff --git a/src/io/settings_io.cpp b/src/io/settings_io.cpp index 772b5ccd8..4c2b3c218 100644 --- a/src/io/settings_io.cpp +++ b/src/io/settings_io.cpp @@ -56,7 +56,7 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) { builder.add("window-mode", &settings.display.windowMode); builder.add("adaptive-menu-fps", &settings.display.adaptiveFpsInMenu); builder.add("compact-window-bar", &settings.display.compactWindowBar); - builder.add("window-shadow", &settings.display.windowShadow); + builder.add("simple-window", &settings.display.simpleWindow); builder.add("live-resize", &settings.display.liveResize); builder.addSection("camera"); diff --git a/src/settings.hpp b/src/settings.hpp index 7d84d6786..9d9b3c80a 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -40,8 +40,8 @@ struct DisplaySettings { FlagSetting adaptiveFpsInMenu {false}; /// @brief Draw the narrow (24px) window bar instead of the 48px one FlagSetting compactWindowBar {false}; - /// @brief Draw the window shadow and keep the outer area for resizing - FlagSetting windowShadow {true}; + /// @brief Draw the window without the shadow and the resize border + FlagSetting simpleWindow {false}; /// @brief Render the window content every frame while it is resized FlagSetting liveResize {true}; }; diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index 9724d82a8..c7cbb37ef 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -282,7 +282,7 @@ void WaylandWindow::setMaximized(bool enabled) { int WaylandWindow::marginSize() const { if (!barEnabled || !shadowEnabled || - (settings != nullptr && !settings->windowShadow.get())) { + (settings != nullptr && settings->simpleWindow.get())) { return 0; } if (fullscreen || maximized || Window::mode != WindowMode::WINDOWED) { @@ -307,9 +307,9 @@ void WaylandWindow::updateSettings() { if (settings == nullptr) { return; } - const bool shadow = settings->windowShadow.get(); - if (shadow != shadowSetting) { - shadowSetting = shadow; + const bool simple = settings->simpleWindow.get(); + if (simple != simpleWindowSetting) { + simpleWindowSetting = simple; // The surface size depends on whether the frame around the content is // drawn at all, so the egl window and the toplevel geometry change. resize(size.x, size.y); @@ -610,18 +610,19 @@ void WaylandWindow::composeFrame() { const int margin = marginSize(); GlStateGuard state; glBindFramebuffer(GL_FRAMEBUFFER, 0); - if (margin <= 0) { - makeContentOpaque(0, 0, size.x, size.y); - return; - } const auto surface = surfaceSize(); glViewport(0, 0, surface.x, surface.y); glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + // Without the shadow the surface is exactly the content, but it still has + // to be painted from the cache: a buffer the driver reallocated after a + // resize holds nothing until something is drawn into it. + glClearColor(0.0f, 0.0f, 0.0f, margin > 0 ? 0.0f : 1.0f); glClear(GL_COLOR_BUFFER_BIT); - drawShadow(); + if (margin > 0) { + drawShadow(); + } if (stretchProgram == 0 || cacheWidth == 0) { glEnable(GL_SCISSOR_TEST); glScissor(margin, margin, size.x, size.y); diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 77bdd8543..9754126cd 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -133,7 +133,7 @@ class WaylandWindow : public Window { static constexpr int SHADOW_MARGIN = 10; static constexpr int RESIZE_GRAB_EXTRA = 2; bool shadowEnabled = false; - bool shadowSetting = true; + bool simpleWindowSetting = false; bool compactBarSetting = false; GLuint shadowProgram = 0; From aac67ac93a7aaf856e1a955c6ea1514ab038b841 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 01:03:56 +0300 Subject: [PATCH 18/35] fix README.md --- README.md | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4443ca07f..e13db2f44 100644 --- a/README.md +++ b/README.md @@ -23,27 +23,17 @@ cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=ON .. sudo make install ``` -> [!WARNING] -> If you are using ALT Linux, do **not** use this EnTT installation method. - #### ALT Linux based distros ```sh su - -apt-get install entt-devel libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel +apt-get install libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel ``` #### Debian based distros ```sh sudo apt install libglfw3 libglfw3-dev libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libcurl4-openssl-dev libssl-dev libfreetype6-dev - -#### Wayland (optional, enabled by default on Linux) - -The native Wayland backend needs `wayland-client`, `wayland-egl`, -`wayland-scanner`, `wayland-protocols`, `libxkbcommon` and EGL. Build with -`-DVOXELENGINE_WAYLAND=OFF` to fall back to GLFW; `libsystemd` (sd-bus) is -picked up automatically for the desktop button layout. ``` > [!TIP] @@ -66,6 +56,12 @@ sudo dnf install glfw-devel glew-devel glm-devel libpng-devel libvorbis-devel op sudo pacman -S glfw glew glm libpng libvorbis openal luajit curl freetype2 openssl ``` +#### Wayland + +On Linux the engine draws the window frame itself and needs `wayland-client`, +`wayland-egl`, `wayland-scanner`, `wayland-protocols`, `libxkbcommon` and EGL. +Build with `-DVOXELENGINE_WAYLAND=OFF` to fall back to GLFW. + ### Building engine with CMake ```sh From 714567a06ea8dbba5c6d240821dde190136a44a6 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 12:34:52 +0300 Subject: [PATCH 19/35] fix names --- README.md | 2 +- src/CMakeLists.txt | 8 ++++---- src/window/Window.cpp | 4 ++-- src/window/detail/WindowBackends.hpp | 2 +- src/window/wayland/WaylandSettings.cpp | 16 ++++++++-------- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index e13db2f44..41fcad58e 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ sudo pacman -S glfw glew glm libpng libvorbis openal luajit curl freetype2 opens On Linux the engine draws the window frame itself and needs `wayland-client`, `wayland-egl`, `wayland-scanner`, `wayland-protocols`, `libxkbcommon` and EGL. -Build with `-DVOXELENGINE_WAYLAND=OFF` to fall back to GLFW. +Build with `-DVOXELCORE_WAYLAND=OFF` to fall back to GLFW. ### Building engine with CMake diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7cee11a0a..a50c63b82 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -76,8 +76,8 @@ endif() target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -option(VOXELENGINE_WAYLAND "Build the native Wayland window backend" ON) -if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) +option(VOXELCORE_WAYLAND "Build the native Wayland window backend" ON) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELCORE_WAYLAND) find_package(PkgConfig REQUIRED) pkg_check_modules(wayland-client IMPORTED_TARGET wayland-client) pkg_check_modules(xkbcommon IMPORTED_TARGET xkbcommon) @@ -128,9 +128,9 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) target_sources( VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) target_include_directories(VoxelCoreSrc PRIVATE ${WAYLAND_GENERATED}) - target_compile_definitions(VoxelCoreSrc PRIVATE VOXELENGINE_WAYLAND=1) + target_compile_definitions(VoxelCoreSrc PRIVATE VOXELCORE_WAYLAND=1) if(libsystemd_FOUND) - target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_SDBUS=1) + target_compile_definitions(VoxelCoreSrc PUBLIC VOXELCORE_SDBUS=1) target_link_libraries(VoxelCoreSrc PRIVATE PkgConfig::libsystemd) message(STATUS "Wayland backend: sd-bus settings are on") else() diff --git a/src/window/Window.cpp b/src/window/Window.cpp index e57535dec..9b9a39180 100644 --- a/src/window/Window.cpp +++ b/src/window/Window.cpp @@ -16,7 +16,7 @@ static debug::Logger logger("window"); -#ifdef VOXELENGINE_WAYLAND +#ifdef VOXELCORE_WAYLAND static bool prefer_wayland() { const char* display = getenv("WAYLAND_DISPLAY"); if (display != nullptr && *display) { @@ -31,7 +31,7 @@ std::tuple< std::unique_ptr > Window::initialize(DisplaySettings* settings, std::string title) { input_util::initialize(); -#ifdef VOXELENGINE_WAYLAND +#ifdef VOXELCORE_WAYLAND if (prefer_wayland()) { auto result = wayland_window_initialize(settings, title); if (std::get<0>(result) && std::get<1>(result)) { diff --git a/src/window/detail/WindowBackends.hpp b/src/window/detail/WindowBackends.hpp index 0d546c14c..873173040 100644 --- a/src/window/detail/WindowBackends.hpp +++ b/src/window/detail/WindowBackends.hpp @@ -11,7 +11,7 @@ struct DisplaySettings; std::tuple, std::unique_ptr> glfw_window_initialize(DisplaySettings* settings, std::string title); -#ifdef VOXELENGINE_WAYLAND +#ifdef VOXELCORE_WAYLAND std::tuple, std::unique_ptr> wayland_window_initialize(DisplaySettings* settings, std::string title); #endif diff --git a/src/window/wayland/WaylandSettings.cpp b/src/window/wayland/WaylandSettings.cpp index aeb2360b3..a36070220 100644 --- a/src/window/wayland/WaylandSettings.cpp +++ b/src/window/wayland/WaylandSettings.cpp @@ -4,7 +4,7 @@ #include -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS #include #endif @@ -13,7 +13,7 @@ namespace { constexpr const char* PORTAL_PATH = "/org/freedesktop/portal/desktop"; constexpr const char* PORTAL_INTERFACE = "org.freedesktop.portal.Settings"; -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS std::string readVariant(sd_bus_message* message) { const char* contents = nullptr; char type = 0; @@ -42,7 +42,7 @@ namespace { } struct SettingsWatcher::Impl { -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS sd_bus* bus = nullptr; std::string changedKey; std::string changedValue; @@ -78,7 +78,7 @@ SettingsWatcher::~SettingsWatcher() { } bool SettingsWatcher::open() { -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS if (impl->bus != nullptr) { return true; } @@ -97,7 +97,7 @@ bool SettingsWatcher::open() { } void SettingsWatcher::close() { -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS if (impl->bus != nullptr) { sd_bus_flush_close_unref(impl->bus); impl->bus = nullptr; @@ -106,7 +106,7 @@ void SettingsWatcher::close() { } bool SettingsWatcher::isAvailable() const { -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS return impl->bus != nullptr; #else return false; @@ -116,7 +116,7 @@ bool SettingsWatcher::isAvailable() const { bool SettingsWatcher::read( const char* schema, const char* key, std::string& value ) { -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS if (impl->bus == nullptr) { return false; } @@ -150,7 +150,7 @@ bool SettingsWatcher::read( bool SettingsWatcher::poll( const char* schema, const char* key, std::string& value ) { -#ifdef VOXELENGINE_SDBUS +#ifdef VOXELCORE_SDBUS if (impl->bus == nullptr) { open(); return false; From b558beeea3c33ca62745892af53babc6b14c2036 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 14:15:40 +0300 Subject: [PATCH 20/35] Fix the build with the wayland 1.20 headers axis_value120 (wl_pointer version 8) and axis_relative_direction (version 9) do not exist in the headers older distributions ship, which broke the build on ubuntu 22.04. They are not needed anyway: a pointer inherits the version of its seat, which is bound at version 7 here, so the compositor cannot send those events at all. The version cap now documents that the listener covers it and that raising it requires handling the newer events too. --- src/window/wayland/WaylandListeners.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index 10e4ed0e3..c30a9e0a2 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -172,8 +172,6 @@ static void seat_capabilities(void*, wl_seat* seat, uint32_t capabilities) { listener.axis_source = ignore_event<>; listener.axis_stop = ignore_event<>; listener.axis_discrete = ignore_event<>; - listener.axis_value120 = ignore_event<>; - listener.axis_relative_direction = ignore_event<>; return listener; }(); @@ -303,6 +301,10 @@ void registry_global( }(); xdg_wm_base_add_listener(state.wmBase, &listener, nullptr); } else if (strcmp(interface, wl_seat_interface.name) == 0) { + // A pointer inherits the seat version, so the pointer listener only + // has to cover the events of version 7 and below. Version 8 adds + // axis_value120 and version 9 axis_relative_direction, whose members + // do not exist in the wayland 1.20 headers either. state.seat = static_cast(wl_registry_bind( registry, name, &wl_seat_interface, std::min(version, 7u) )); From aac0bfa44a569a97a4c0248f68e6471baef6689b Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 14:15:40 +0300 Subject: [PATCH 21/35] Build the window backends as separate libraries VoxelGLFW, VoxelWindowBase (the input state both backends share) and VoxelWayland own their sources, dependencies and protocol generation, while VoxelCoreSrc only sees the Window/Input interfaces and the factories declared in detail/WindowBackends.hpp. VOXELCORE_WAYLAND now only selects the subdirectory to add and the library to link, and the wayland library defines the macro for whoever links it, so linking the backend is what enables it. The protocol sources are generated inside build/src/window/wayland, and missing dependencies only turn the backend off instead of breaking the configuration. --- src/CMakeLists.txt | 132 +++++++++--------------------- src/window/detail/CMakeLists.txt | 22 +++++ src/window/wayland/CMakeLists.txt | 94 +++++++++++++++++++++ 3 files changed, 155 insertions(+), 93 deletions(-) create mode 100644 src/window/detail/CMakeLists.txt create mode 100644 src/window/wayland/CMakeLists.txt diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a50c63b82..2e02155fd 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,9 +4,12 @@ file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp) file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) -file(GLOB_RECURSE wayland_sources +# The window backends are separate libraries: the engine only talks to the +# Window/Input interfaces and to the factories in detail/WindowBackends.hpp +file(GLOB_RECURSE backend_sources + ${CMAKE_CURRENT_SOURCE_DIR}/window/detail/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/window/wayland/*.cpp) -list(REMOVE_ITEM sources ${wayland_sources}) +list(REMOVE_ITEM sources ${backend_sources}) add_library(VoxelCoreSrc STATIC ${sources} ${headers}) @@ -76,97 +79,8 @@ endif() target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -option(VOXELCORE_WAYLAND "Build the native Wayland window backend" ON) -if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELCORE_WAYLAND) - find_package(PkgConfig REQUIRED) - pkg_check_modules(wayland-client IMPORTED_TARGET wayland-client) - pkg_check_modules(xkbcommon IMPORTED_TARGET xkbcommon) - pkg_check_modules(egl IMPORTED_TARGET egl) - find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1) - find_program(WAYLAND_SCANNER wayland-scanner) - pkg_check_modules(libsystemd IMPORTED_TARGET libsystemd) - - if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND - OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER) - message(STATUS "Wayland backend is off: dependencies are not found") - else() - set(WAYLAND_PROTOCOLS ${CMAKE_CURRENT_SOURCE_DIR}/window/wayland/protocols) - set(WAYLAND_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/wayland-protocols) - file(MAKE_DIRECTORY ${WAYLAND_GENERATED}) - set(WAYLAND_SOURCES) - - function(voxel_wayland_protocol XML NAME) - add_custom_command( - OUTPUT ${WAYLAND_GENERATED}/${NAME}-client-protocol.h - ${WAYLAND_GENERATED}/${NAME}-protocol.c - COMMAND ${WAYLAND_SCANNER} client-header - ${WAYLAND_PROTOCOLS}/${XML} - ${WAYLAND_GENERATED}/${NAME}-client-protocol.h - COMMAND ${WAYLAND_SCANNER} private-code - ${WAYLAND_PROTOCOLS}/${XML} - ${WAYLAND_GENERATED}/${NAME}-protocol.c - DEPENDS ${WAYLAND_PROTOCOLS}/${XML} - VERBATIM) - set(WAYLAND_SOURCES ${WAYLAND_SOURCES} - ${WAYLAND_GENERATED}/${NAME}-protocol.c - PARENT_SCOPE) - endfunction() - - voxel_wayland_protocol(xdg-shell.xml xdg-shell) - voxel_wayland_protocol(cursor-shape-v1.xml cursor-shape-v1) - voxel_wayland_protocol(idle-inhibit-unstable-v1.xml - idle-inhibit-unstable-v1) - voxel_wayland_protocol(pointer-constraints-unstable-v1.xml - pointer-constraints-unstable-v1) - voxel_wayland_protocol(relative-pointer-unstable-v1.xml - relative-pointer-unstable-v1) - voxel_wayland_protocol(xdg-decoration-unstable-v1.xml - xdg-decoration-unstable-v1) - # tablet is referenced by cursor-shape-v1 - voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) - - target_sources( - VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) - target_include_directories(VoxelCoreSrc PRIVATE ${WAYLAND_GENERATED}) - target_compile_definitions(VoxelCoreSrc PRIVATE VOXELCORE_WAYLAND=1) - if(libsystemd_FOUND) - target_compile_definitions(VoxelCoreSrc PUBLIC VOXELCORE_SDBUS=1) - target_link_libraries(VoxelCoreSrc PRIVATE PkgConfig::libsystemd) - message(STATUS "Wayland backend: sd-bus settings are on") - else() - message(STATUS "Wayland backend: sd-bus settings are off") - endif() - target_link_libraries( - VoxelCoreSrc - PRIVATE PkgConfig::wayland-client - PkgConfig::xkbcommon - PkgConfig::egl - ${WAYLAND_EGL_LIBRARY}) - message(STATUS "Wayland backend is on") - endif() -endif() - -target_link_libraries( - VoxelCoreSrc - PRIVATE glfw - OpenGL::GL - GLEW::GLEW - ZLIB::ZLIB - PNG::PNG - CURL::libcurl - OpenSSL::Crypto - OpenAL::OpenAL - Vorbis::vorbis - Vorbis::vorbisfile - Freetype::Freetype - PUBLIC luajit::luajit - glm::glm # Need public for src/delegates.hpp, which including to - # main.cpp -) - -target_compile_options( - VoxelCoreSrc - PUBLIC $<$: +set(VOXEL_COMPILE_OPTIONS + $<$: /utf-8 /MP /D_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR @@ -202,6 +116,38 @@ target_compile_options( -Wduplicated-cond >) +option(VOXELCORE_WAYLAND "Build the native Wayland window backend" ON) + +add_subdirectory(window/detail) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELCORE_WAYLAND) + add_subdirectory(window/wayland) +endif() + +target_link_libraries( + VoxelCoreSrc + PRIVATE VoxelGLFW + glfw + OpenGL::GL + GLEW::GLEW + ZLIB::ZLIB + PNG::PNG + CURL::libcurl + OpenSSL::Crypto + OpenAL::OpenAL + Vorbis::vorbis + Vorbis::vorbisfile + Freetype::Freetype + PUBLIC luajit::luajit + glm::glm # Need public for src/delegates.hpp, which including to + # main.cpp +) + +if(TARGET VoxelWayland) + target_link_libraries(VoxelCoreSrc PRIVATE VoxelWayland) +endif() + +target_compile_options(VoxelCoreSrc PUBLIC ${VOXEL_COMPILE_OPTIONS}) + target_link_options( VoxelCoreSrc PUBLIC diff --git a/src/window/detail/CMakeLists.txt b/src/window/detail/CMakeLists.txt new file mode 100644 index 000000000..7939d486a --- /dev/null +++ b/src/window/detail/CMakeLists.txt @@ -0,0 +1,22 @@ +project(VoxelWindowBackends) + +# Input state shared by the window backends. +add_library(VoxelWindowBase STATIC BaseInput.cpp) + +target_include_directories(VoxelWindowBase PRIVATE ${CMAKE_SOURCE_DIR}/src) + +target_compile_options(VoxelWindowBase PRIVATE ${VOXEL_COMPILE_OPTIONS}) + +add_library(VoxelGLFW STATIC GLFWWindow.cpp) + +target_include_directories(VoxelGLFW PRIVATE ${CMAKE_SOURCE_DIR}/src) + +target_compile_options(VoxelGLFW PRIVATE ${VOXEL_COMPILE_OPTIONS}) + +target_link_libraries( + VoxelGLFW + PRIVATE VoxelWindowBase + glfw + OpenGL::GL + GLEW::GLEW + glm::glm) diff --git a/src/window/wayland/CMakeLists.txt b/src/window/wayland/CMakeLists.txt new file mode 100644 index 000000000..667fd1174 --- /dev/null +++ b/src/window/wayland/CMakeLists.txt @@ -0,0 +1,94 @@ +project(VoxelWayland) + +# The library is linked from the parent directory, so the imported targets of +# its dependencies have to be visible outside of this directory too. +function(voxel_wayland_pkg_config MODULE) + pkg_check_modules(${MODULE} IMPORTED_TARGET ${ARGN}) + if(TARGET PkgConfig::${MODULE}) + set_target_properties( + PkgConfig::${MODULE} PROPERTIES IMPORTED_GLOBAL TRUE) + endif() +endfunction() + +macro(voxel_wayland_protocol XML NAME) + add_custom_command( + OUTPUT ${WAYLAND_GENERATED}/${NAME}-client-protocol.h + ${WAYLAND_GENERATED}/${NAME}-protocol.c + COMMAND ${WAYLAND_SCANNER} client-header ${WAYLAND_PROTOCOLS}/${XML} + ${WAYLAND_GENERATED}/${NAME}-client-protocol.h + COMMAND ${WAYLAND_SCANNER} private-code ${WAYLAND_PROTOCOLS}/${XML} + ${WAYLAND_GENERATED}/${NAME}-protocol.c + DEPENDS ${WAYLAND_PROTOCOLS}/${XML} + VERBATIM) + list(APPEND WAYLAND_SOURCES ${WAYLAND_GENERATED}/${NAME}-protocol.c) +endmacro() + +function(voxel_add_wayland_backend) + find_package(PkgConfig REQUIRED) + voxel_wayland_pkg_config(wayland-client wayland-client) + voxel_wayland_pkg_config(xkbcommon xkbcommon) + voxel_wayland_pkg_config(egl egl) + voxel_wayland_pkg_config(libsystemd libsystemd) + find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1) + find_program(WAYLAND_SCANNER wayland-scanner) + + if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND + OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER) + message(STATUS "Wayland backend is off: dependencies are not found") + return() + endif() + + set(WAYLAND_PROTOCOLS ${CMAKE_CURRENT_SOURCE_DIR}/protocols) + set(WAYLAND_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/protocols) + file(MAKE_DIRECTORY ${WAYLAND_GENERATED}) + set(WAYLAND_SOURCES) + + voxel_wayland_protocol(xdg-shell.xml xdg-shell) + voxel_wayland_protocol(cursor-shape-v1.xml cursor-shape-v1) + voxel_wayland_protocol(idle-inhibit-unstable-v1.xml + idle-inhibit-unstable-v1) + voxel_wayland_protocol(pointer-constraints-unstable-v1.xml + pointer-constraints-unstable-v1) + voxel_wayland_protocol(relative-pointer-unstable-v1.xml + relative-pointer-unstable-v1) + voxel_wayland_protocol(xdg-decoration-unstable-v1.xml + xdg-decoration-unstable-v1) + # tablet is referenced by cursor-shape-v1 + voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) + + file(GLOB wayland_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) + + add_library(VoxelWayland STATIC ${wayland_sources} ${WAYLAND_SOURCES}) + + target_include_directories(VoxelWayland + PRIVATE ${CMAKE_SOURCE_DIR}/src ${WAYLAND_GENERATED}) + + target_compile_options(VoxelWayland PRIVATE ${VOXEL_COMPILE_OPTIONS}) + + # Linking this library is what enables the backend in the engine code. + target_compile_definitions(VoxelWayland PUBLIC VOXELCORE_WAYLAND=1) + + target_link_libraries( + VoxelWayland + PRIVATE VoxelWindowBase + PkgConfig::wayland-client + PkgConfig::xkbcommon + PkgConfig::egl + ${WAYLAND_EGL_LIBRARY} + glfw + OpenGL::GL + GLEW::GLEW + glm::glm) + + if(libsystemd_FOUND) + target_compile_definitions(VoxelWayland PRIVATE VOXELCORE_SDBUS=1) + target_link_libraries(VoxelWayland PRIVATE PkgConfig::libsystemd) + message(STATUS "Wayland backend: sd-bus settings are on") + else() + message(STATUS "Wayland backend: sd-bus settings are off") + endif() + + message(STATUS "Wayland backend is on") +endfunction() + +voxel_add_wayland_backend() From b9a13c853dfa29bb82c95224b01c4c2cbbdbbb76 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 14:20:33 +0300 Subject: [PATCH 22/35] Give the window backends the engine include surface VoxelWindowBase only got the src include directory, so BaseInput.cpp could not find glm/vec2.hpp through window/input.hpp on macOS, where glm lives in a prefix outside the default include path. VoxelGLFW had glm linked, which hid the problem on Linux, where glm sits in /usr/include anyway. The backends now link a single interface target carrying the engine sources and the third-party headers their public headers pull in, instead of each backend keeping its own list. --- src/CMakeLists.txt | 15 +++++++++++++++ src/window/detail/CMakeLists.txt | 14 +++----------- src/window/wayland/CMakeLists.txt | 10 +++------- 3 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2e02155fd..02a974cc1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -116,6 +116,21 @@ set(VOXEL_COMPILE_OPTIONS -Wduplicated-cond >) +# Everything the engine sources and their public headers include: the backends +# compile against the same surface, and a missing include directory shows up as +# a build failure only on the platforms that keep the library outside the +# default include path. +add_library(VoxelCoreInterface INTERFACE) + +target_include_directories(VoxelCoreInterface INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR}) + +target_link_libraries(VoxelCoreInterface INTERFACE + glfw + GLEW::GLEW + OpenGL::GL + glm::glm) + option(VOXELCORE_WAYLAND "Build the native Wayland window backend" ON) add_subdirectory(window/detail) diff --git a/src/window/detail/CMakeLists.txt b/src/window/detail/CMakeLists.txt index 7939d486a..9537eefe8 100644 --- a/src/window/detail/CMakeLists.txt +++ b/src/window/detail/CMakeLists.txt @@ -3,20 +3,12 @@ project(VoxelWindowBackends) # Input state shared by the window backends. add_library(VoxelWindowBase STATIC BaseInput.cpp) -target_include_directories(VoxelWindowBase PRIVATE ${CMAKE_SOURCE_DIR}/src) - target_compile_options(VoxelWindowBase PRIVATE ${VOXEL_COMPILE_OPTIONS}) +target_link_libraries(VoxelWindowBase PRIVATE VoxelCoreInterface) + add_library(VoxelGLFW STATIC GLFWWindow.cpp) -target_include_directories(VoxelGLFW PRIVATE ${CMAKE_SOURCE_DIR}/src) - target_compile_options(VoxelGLFW PRIVATE ${VOXEL_COMPILE_OPTIONS}) -target_link_libraries( - VoxelGLFW - PRIVATE VoxelWindowBase - glfw - OpenGL::GL - GLEW::GLEW - glm::glm) +target_link_libraries(VoxelGLFW PRIVATE VoxelWindowBase VoxelCoreInterface) diff --git a/src/window/wayland/CMakeLists.txt b/src/window/wayland/CMakeLists.txt index 667fd1174..fe8a7b810 100644 --- a/src/window/wayland/CMakeLists.txt +++ b/src/window/wayland/CMakeLists.txt @@ -60,8 +60,7 @@ function(voxel_add_wayland_backend) add_library(VoxelWayland STATIC ${wayland_sources} ${WAYLAND_SOURCES}) - target_include_directories(VoxelWayland - PRIVATE ${CMAKE_SOURCE_DIR}/src ${WAYLAND_GENERATED}) + target_include_directories(VoxelWayland PRIVATE ${WAYLAND_GENERATED}) target_compile_options(VoxelWayland PRIVATE ${VOXEL_COMPILE_OPTIONS}) @@ -71,14 +70,11 @@ function(voxel_add_wayland_backend) target_link_libraries( VoxelWayland PRIVATE VoxelWindowBase + VoxelCoreInterface PkgConfig::wayland-client PkgConfig::xkbcommon PkgConfig::egl - ${WAYLAND_EGL_LIBRARY} - glfw - OpenGL::GL - GLEW::GLEW - glm::glm) + ${WAYLAND_EGL_LIBRARY}) if(libsystemd_FOUND) target_compile_definitions(VoxelWayland PRIVATE VOXELCORE_SDBUS=1) From 56a225fe15e1a6daca89a9bc67e3673149eecaa0 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 15:30:55 +0300 Subject: [PATCH 23/35] Draw the window frame on windows and on x11 The engine already draws the bar on wayland; the GLFW backend now does the same where the client may move its own window, and keeps the native frame elsewhere: wayland forbids client side positioning, and macOS has its own frame. On windows the native frame is kept and only its caption is hidden, so the thick frame, the shadow, the animations and the snap layouts keep working. A window procedure returns HTCAPTION for the bar, HTCLIENT for the controls and HT* for the edges. On x11 the window manager runs the interactive move or resize (_NET_WM_MOVERESIZE), which keeps window snapping and tiling native too. Where neither is available the frame moves and resizes the window itself, as before. The X11 accessors of GLFW are resolved with dlsym, so a wayland-only build still links, and the window manager operations are only compiled in when X11 is found. The title of the window is stored on creation now: the bar draws it, and the GLFW backend used to leave it empty. --- src/window/detail/CMakeLists.txt | 20 +- src/window/detail/FrameLayout.hpp | 97 +++++++ src/window/detail/FrameOperations.cpp | 248 +++++++++++++++++ src/window/detail/FrameOperations.hpp | 28 ++ src/window/detail/GLFWWindow.cpp | 378 +++++++++++++++++++++++++- 5 files changed, 765 insertions(+), 6 deletions(-) create mode 100644 src/window/detail/FrameLayout.hpp create mode 100644 src/window/detail/FrameOperations.cpp create mode 100644 src/window/detail/FrameOperations.hpp diff --git a/src/window/detail/CMakeLists.txt b/src/window/detail/CMakeLists.txt index 9537eefe8..a309ad51a 100644 --- a/src/window/detail/CMakeLists.txt +++ b/src/window/detail/CMakeLists.txt @@ -7,8 +7,24 @@ target_compile_options(VoxelWindowBase PRIVATE ${VOXEL_COMPILE_OPTIONS}) target_link_libraries(VoxelWindowBase PRIVATE VoxelCoreInterface) -add_library(VoxelGLFW STATIC GLFWWindow.cpp) +add_library(VoxelGLFW STATIC GLFWWindow.cpp FrameOperations.cpp) target_compile_options(VoxelGLFW PRIVATE ${VOXEL_COMPILE_OPTIONS}) -target_link_libraries(VoxelGLFW PRIVATE VoxelWindowBase VoxelCoreInterface) +target_link_libraries( + VoxelGLFW PRIVATE VoxelWindowBase VoxelCoreInterface ${CMAKE_DL_LIBS}) + +# On X11 the window manager moves and resizes the window when the engine draws +# the frame. A wayland-only build of GLFW does not answer, and the frame then +# falls back to moving the window itself. +if(UNIX AND NOT APPLE) + find_package(X11) + if(X11_FOUND) + target_compile_definitions(VoxelGLFW PRIVATE VOXEL_X11_FRAME=1) + target_include_directories(VoxelGLFW PRIVATE ${X11_INCLUDE_DIR}) + target_link_libraries(VoxelGLFW PRIVATE ${X11_LIBRARIES}) + message(STATUS "window frame: window manager operations are on") + else() + message(STATUS "window frame: window manager operations are off") + endif() +endif() diff --git a/src/window/detail/FrameLayout.hpp b/src/window/detail/FrameLayout.hpp new file mode 100644 index 000000000..ae3394457 --- /dev/null +++ b/src/window/detail/FrameLayout.hpp @@ -0,0 +1,97 @@ +#pragma once + +/// @brief Geometry of the window frame the engine draws itself. +/// +/// Wayland has its own implementation because it also talks to the compositor, +/// this one is used by the backends that decorate their window by themselves. +/// It deliberately depends on nothing but the standard library, so the layout +/// and the hit testing can be checked without a window. +namespace frame { + constexpr int BAR_HEIGHT = 48; + constexpr int BAR_HEIGHT_COMPACT = 24; + constexpr int BUTTON = 24; + constexpr int PADDING = 12; + constexpr int GAP = 12; + constexpr int EDGE = 8; + constexpr int MAX_BUTTONS = 4; + + constexpr int EDGE_TOP = 1; + constexpr int EDGE_BOTTOM = 2; + constexpr int EDGE_LEFT = 4; + constexpr int EDGE_RIGHT = 8; + + struct Rect { + float x = 0.0f; + float width = 0.0f; + }; + + /// @brief Places the controls of the bar flush against the right edge. + /// @param count number of controls, ordered from left to right + /// @return number of placed controls, which is 0 for a window too narrow + inline int layoutButtons( + float windowWidth, int count, bool compact, Rect* out + ) { + if (count > MAX_BUTTONS) { + count = MAX_BUTTONS; + } + const float padding = compact ? 0.0f : PADDING; + const float gap = compact ? 0.0f : GAP; + const float pitch = BUTTON + gap; + int placed = 0; + for (int i = 0; i < count; i++) { + const float x = windowWidth - padding - (count - i) * pitch + gap; + if (x < 0.0f) { + break; + } + out[placed++] = {x, static_cast(BUTTON)}; + } + return placed; + } + + /// @brief Control under the pointer, or -1 + inline int buttonAt( + const Rect* buttons, int count, int barHeight, float x, float y + ) { + const int top = (barHeight - BUTTON) / 2; + if (y < top || y >= top + BUTTON) { + return -1; + } + for (int i = 0; i < count; i++) { + if (x >= buttons[i].x && x < buttons[i].x + buttons[i].width) { + return i; + } + } + return -1; + } + + /// @brief What the pointer is over, in client coordinates + struct Hit { + /// the bar drags the window, which on win32 is the OS caption + bool caption = false; + /// resize edges, 0 when the pointer is not near any of them + int edges = 0; + }; + + /// @brief Resize edges grab-able at the given position, 0 when none + inline int edgesAt( + int width, int height, int barHeight, float x, float y + ) { + int edges = 0; + if (y < EDGE) { + edges |= EDGE_TOP; + } else if (y >= height - EDGE) { + edges |= EDGE_BOTTOM; + } + // Inside the bar only its top strip resizes the window, the rest + // belongs to the controls and to dragging. + if (y < barHeight && y >= EDGE) { + return edges; + } + if (x < EDGE) { + edges |= EDGE_LEFT; + } else if (x >= width - EDGE) { + edges |= EDGE_RIGHT; + } + return edges; + } +} diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp new file mode 100644 index 000000000..294428789 --- /dev/null +++ b/src/window/detail/FrameOperations.cpp @@ -0,0 +1,248 @@ +#include "window/detail/FrameOperations.hpp" + +#if defined(VOXEL_X11_FRAME) +#include +#include + +#include + +namespace { + /// @brief X11 accessors of GLFW, resolved when they are really there + /// + /// A wayland-only build of GLFW does not export them, and then the frame + /// moves the window itself instead of asking the window manager. + struct X11Api { + Display* (*display)() = nullptr; + Window (*window)(GLFWwindow*) = nullptr; + + X11Api() { + display = reinterpret_cast( + dlsym(RTLD_DEFAULT, "glfwGetX11Display") + ); + window = reinterpret_cast( + dlsym(RTLD_DEFAULT, "glfwGetX11Window") + ); + if (display == nullptr || window == nullptr) { + display = nullptr; + window = nullptr; + } + } + + bool available() const { + return display != nullptr && window != nullptr; + } + }; + + X11Api& x11_api() { + static X11Api api; + return api; + } + + /// @brief Edge mask to the _NET_WM_MOVERESIZE direction + int x11_direction(int edges) { + switch (edges) { + case frame::EDGE_TOP | frame::EDGE_LEFT: + return 0; + case frame::EDGE_TOP: + return 1; + case frame::EDGE_TOP | frame::EDGE_RIGHT: + return 2; + case frame::EDGE_RIGHT: + return 3; + case frame::EDGE_BOTTOM | frame::EDGE_RIGHT: + return 4; + case frame::EDGE_BOTTOM: + return 5; + case frame::EDGE_BOTTOM | frame::EDGE_LEFT: + return 6; + default: + return 7; + } + } + + constexpr int MOVERESIZE_MOVE = 8; + constexpr int SOURCE_APPLICATION = 1; + + bool x11_request(GLFWwindow* glfwWindow, int direction) { + X11Api& api = x11_api(); + if (!api.available()) { + return false; + } + Display* display = api.display(); + const Window window = api.window(glfwWindow); + if (display == nullptr || window == 0) { + return false; + } + const Window root = DefaultRootWindow(display); + int rootX = 0, rootY = 0, windowX = 0, windowY = 0; + Window child = 0, rootReturn = 0; + unsigned int mask = 0; + XQueryPointer( + display, + root, + &rootReturn, + &child, + &rootX, + &rootY, + &windowX, + &windowY, + &mask + ); + XEvent event {}; + event.xclient.type = ClientMessage; + event.xclient.message_type = + XInternAtom(display, "_NET_WM_MOVERESIZE", False); + event.xclient.display = display; + event.xclient.window = window; + event.xclient.format = 32; + event.xclient.data.l[0] = rootX; + event.xclient.data.l[1] = rootY; + event.xclient.data.l[2] = direction; + event.xclient.data.l[3] = Button1; + event.xclient.data.l[4] = SOURCE_APPLICATION; + XUngrabPointer(display, CurrentTime); + XSendEvent( + display, + root, + False, + SubstructureRedirectMask | SubstructureNotifyMask, + &event + ); + XFlush(display); + return true; + } +} + +#elif defined(_WIN32) +#define NOMINMAX +#include +#include + +#define GLFW_EXPOSE_NATIVE_WIN32 +#include + +namespace { + WNDPROC original_window_proc = nullptr; + frame::Hit (*hit_test_callback)(void*, int, int) = nullptr; + void* hit_test_userdata = nullptr; + + LRESULT CALLBACK frame_window_proc( + HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam + ) { + switch (message) { + case WM_NCCALCSIZE: + // the caption is gone, the whole window is the client area + if (wparam == TRUE) { + return 0; + } + break; + case WM_NCPAINT: + // the frame is not drawn by us + return 0; + case WM_NCACTIVATE: + // and it is not repainted when the window is activated + return TRUE; + case WM_NCHITTEST: { + if (hit_test_callback == nullptr) { + break; + } + POINT point {GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}; + ScreenToClient(hwnd, &point); + const frame::Hit hit = + hit_test_callback(hit_test_userdata, point.x, point.y); + if (hit.caption) { + return HTCAPTION; + } + switch (hit.edges) { + case frame::EDGE_TOP | frame::EDGE_LEFT: + return HTTOPLEFT; + case frame::EDGE_TOP: + return HTTOP; + case frame::EDGE_TOP | frame::EDGE_RIGHT: + return HTTOPRIGHT; + case frame::EDGE_RIGHT: + return HTRIGHT; + case frame::EDGE_BOTTOM | frame::EDGE_RIGHT: + return HTBOTTOMRIGHT; + case frame::EDGE_BOTTOM: + return HTBOTTOM; + case frame::EDGE_BOTTOM | frame::EDGE_LEFT: + return HTBOTTOMLEFT; + case frame::EDGE_LEFT: + return HTLEFT; + default: + return HTCLIENT; + } + } + } + return CallWindowProc( + original_window_proc, hwnd, message, wparam, lparam + ); + } +} +#endif + +bool frame_has_native_operations() { +#if defined(VOXEL_X11_FRAME) + return x11_api().available(); +#else + return false; +#endif +} + +bool frame_start_move(GLFWwindow* window) { +#if defined(VOXEL_X11_FRAME) + return x11_request(window, MOVERESIZE_MOVE); +#else + (void)window; + return false; +#endif +} + +bool frame_start_resize(GLFWwindow* window, int edges) { +#if defined(VOXEL_X11_FRAME) + return edges != 0 && x11_request(window, x11_direction(edges)); +#else + (void)window; + (void)edges; + return false; +#endif +} + +void frame_setup_native( + GLFWwindow* window, + frame::Hit (*hitTest)(void*, int, int), + void* userdata +) { +#if defined(_WIN32) + HWND hwnd = glfwGetWin32Window(window); + if (hwnd == nullptr) { + return; + } + hit_test_callback = hitTest; + hit_test_userdata = userdata; + // The native frame stays: its thick frame is what gives the window the + // resize border, the shadow, the animations and the snap layouts. Only + // the caption is hidden, and the client area covers the whole window. + LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); + style |= WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU; + style &= ~WS_CAPTION; + SetWindowLongPtr(hwnd, GWL_STYLE, style); + original_window_proc = reinterpret_cast(SetWindowLongPtr( + hwnd, GWLP_WNDPROC, reinterpret_cast(frame_window_proc) + )); + SetWindowPos( + hwnd, + nullptr, + 0, + 0, + 0, + 0, + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER + ); +#else + (void)window; + (void)hitTest; + (void)userdata; +#endif +} diff --git a/src/window/detail/FrameOperations.hpp b/src/window/detail/FrameOperations.hpp new file mode 100644 index 000000000..5871b0982 --- /dev/null +++ b/src/window/detail/FrameOperations.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include "window/detail/FrameLayout.hpp" + +struct GLFWwindow; + +/// @name Window operations the window manager performs itself +/// +/// The frame is drawn by the engine, but moving and resizing are better left +/// to the window manager: it keeps window snapping, tiling and the resize +/// feedback native. Every function returns false when that is not available +/// and the caller has to move or resize the window on its own. +/// @{ + +/// @brief Whether the window manager can be asked to do it +bool frame_has_native_operations(); + +/// @brief Ask the window manager to start moving the window +bool frame_start_move(GLFWwindow* window); + +/// @brief Ask the window manager to start resizing the window +bool frame_start_resize(GLFWwindow* window, int edges); + +/// @brief Hide the caption of the native frame, keeping the rest of it +/// @param hitTest tells what the pointer is over +void frame_setup_native(GLFWwindow* window, frame::Hit (*hitTest)(void*, int, int), void* userdata); + +/// @} diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index c1fa8e482..3038f8f24 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -1,5 +1,7 @@ #include "window/Window.hpp" #include "window/detail/BaseInput.hpp" +#include "window/detail/FrameLayout.hpp" +#include "window/detail/FrameOperations.hpp" #include "window/detail/WindowBackends.hpp" #include @@ -7,6 +9,7 @@ #include #include +#include #include #include @@ -33,6 +36,26 @@ static const char* get_platform_name() { return "unknown"; } +/// @brief Whether the engine draws the window frame itself. +/// +/// Only where the client is allowed to move and resize its own window: +/// wayland forbids that, and on macOS the system frame is the expected one. +static bool use_engine_frame() { +#if defined(_WIN32) + return true; +#elif defined(__linux__) +#if GLFW_VERSION_MAJOR > 3 || \ + (GLFW_VERSION_MAJOR == 3 && GLFW_VERSION_MINOR >= 4) + return glfwGetPlatform() == GLFW_PLATFORM_X11; +#else + // GLFW 3.3 has no wayland backend at all + return true; +#endif +#else + return false; +#endif +} + static std::unordered_set supported_gl_extensions; static void window_size_callback(GLFWwindow* window, int width, int height); @@ -255,12 +278,17 @@ public: GLFWwindow* window, DisplaySettings* settings, int width, - int height + int height, + bool engineFrame ) : Window({width, height}), input(glfwInput), settings(settings), - window(window) { + window(window), + engineFrame(engineFrame) { + if (engineFrame) { + frame_setup_native(window, &frame_hit_test, this); + } } ~GLFWWindow() { @@ -303,6 +331,148 @@ public: return false; } + int barHeight() const { + if (!engineFrame || mode != WindowMode::WINDOWED) { + return 0; + } + return settings->compactWindowBar.get() ? frame::BAR_HEIGHT_COMPACT + : frame::BAR_HEIGHT; + } + + int getDecorationHeight() const override { + return barHeight(); + } + + const std::vector& getDecorationButtons() const + override { + buttonRects.clear(); + if (barHeight() <= 0) { + return buttonRects; + } + frame::Rect rects[frame::MAX_BUTTONS]; + const int count = layoutFrameButtons(rects); + for (int i = 0; i < count; i++) { + buttonRects.push_back({frameButtons[i], rects[i].x, rects[i].width}); + } + return buttonRects; + } + + int getDecorationHoveredButton() const override { + return hoveredButton; + } + + /// @brief What the pointer is over, in client coordinates + frame::Hit hitTestFrame(int x, int y) const { + const int height = barHeight(); + if (height <= 0) { + return frame::Hit {}; + } + frame::Rect rects[frame::MAX_BUTTONS]; + const int count = layoutFrameButtons(rects); + if (frame::buttonAt( + rects, + count, + height, + static_cast(x), + static_cast(y) + ) >= 0) { + return frame::Hit {}; + } + if (y < height) { + return frame::Hit {true, 0}; + } + return frame::Hit { + false, + frame::edgesAt( + getSize().x, + getSize().y, + height, + static_cast(x), + static_cast(y) + )}; + } + + /// @brief Turns a pointer move into hovering, dragging or resizing + void handleFrameMotion(double x, double y) { + if (input.isCursorLocked() || barHeight() <= 0) { + hoveredButton = -1; + return; + } + if (dragging || resizeEdges != 0) { + updateFrameDrag(); + } + updateFrameHover(x, y); + } + + /// @brief Turns a pointer button into a frame action + /// @return whether the frame handled the event + bool handleFrameButton(int button, bool pressed, double x, double y) { + if (button != GLFW_MOUSE_BUTTON_LEFT || input.isCursorLocked() || + barHeight() <= 0) { + return false; + } + if (!pressed) { + if (pressedButton >= 0) { + const int index = pressedButton; + pressedButton = -1; + if (index == hoveredButton) { + activateFrameButton(index); + } + return true; + } + if (dragging) { + dragging = false; + if (frameMoved) { + lastBarClick = 0.0; + } + return true; + } + if (resizeEdges != 0) { + resizeEdges = 0; + return true; + } + return false; + } + updateFrameHover(x, y); + if (hoveredButton >= 0) { + pressedButton = hoveredButton; + return true; + } + const frame::Hit hit = hitTestFrame( + static_cast(x), static_cast(y) + ); + if (hit.caption) { + const double now = glfwGetTime(); + if (lastBarClick > 0.0 && now - lastBarClick < DOUBLE_CLICK_TIME) { + lastBarClick = 0.0; + toggleMaximize(); + return true; + } + lastBarClick = now; + if (frame_start_move(window)) { + return true; + } + dragging = true; + frameMoved = false; + grabX = x; + grabY = y; + return true; + } + if (hit.edges == 0) { + return false; + } + if (frame_start_resize(window, hit.edges)) { + return true; + } + resizeEdges = hit.edges; + resizeStartW = getSize().x; + resizeStartH = getSize().y; + glfwGetWindowPos(window, &resizeStartX, &resizeStartY); + grabScreenX = resizeStartX + x; + grabScreenY = resizeStartY + y; + return true; + } + bool isMaximized() const override { return glfwGetWindowAttrib(window, GLFW_MAXIMIZED); } @@ -364,7 +534,7 @@ public: settings->height.get(), GLFW_DONT_CARE ); - glfwSetWindowAttrib(window, GLFW_DECORATED, GLFW_TRUE); + applyDecoration(); glfwSetWindowAttrib(window, GLFW_RESIZABLE, GLFW_TRUE); window_size_callback(window, settings->width.get(), settings->height.get()); } @@ -441,7 +611,191 @@ public: } private: + int layoutFrameButtons(frame::Rect* rects) const { + return frame::layoutButtons( + static_cast(getSize().x), + static_cast(frameButtons.size()), + settings->compactWindowBar.get(), + rects + ); + } + + void updateFrameHover(double x, double y) { + const int height = barHeight(); + frame::Rect rects[frame::MAX_BUTTONS]; + const int count = layoutFrameButtons(rects); + hoveredButton = frame::buttonAt( + rects, count, height, static_cast(x), static_cast(y) + ); + if (dragging || resizeEdges != 0) { + return; + } + // inside the bar the controls win over the resize edges + const int edges = hoveredButton < 0 + ? frame::edgesAt( + getSize().x, + getSize().y, + height, + static_cast(x), + static_cast(y) + ) + : 0; + if (edges != 0) { + setCursor(edgeCursor(edges)); + } else if (y < height) { + setCursor(CursorShape::ARROW); + } + } + + void updateFrameDrag() { + double x = 0.0, y = 0.0; + glfwGetCursorPos(window, &x, &y); + int windowX = 0, windowY = 0; + glfwGetWindowPos(window, &windowX, &windowY); + if (dragging) { + const double dx = x - grabX; + const double dy = y - grabY; + if (std::abs(dx) > MOVE_THRESHOLD || std::abs(dy) > MOVE_THRESHOLD) { + frameMoved = true; + } + glfwSetWindowPos( + window, + windowX + static_cast(std::lround(dx)), + windowY + static_cast(std::lround(dy)) + ); + return; + } + const double dx = (windowX + x) - grabScreenX; + const double dy = (windowY + y) - grabScreenY; + int width = resizeStartW; + int height = resizeStartH; + int newX = resizeStartX; + int newY = resizeStartY; + if (resizeEdges & frame::EDGE_LEFT) { + width = resizeStartW - static_cast(std::lround(dx)); + newX = resizeStartX + static_cast(std::lround(dx)); + } else if (resizeEdges & frame::EDGE_RIGHT) { + width = resizeStartW + static_cast(std::lround(dx)); + } + if (resizeEdges & frame::EDGE_TOP) { + height = resizeStartH - static_cast(std::lround(dy)); + newY = resizeStartY + static_cast(std::lround(dy)); + } else if (resizeEdges & frame::EDGE_BOTTOM) { + height = resizeStartH + static_cast(std::lround(dy)); + } + if (width < MIN_WIDTH) { + if (resizeEdges & frame::EDGE_LEFT) { + newX = resizeStartX + (resizeStartW - MIN_WIDTH); + } + width = MIN_WIDTH; + } + if (height < MIN_HEIGHT) { + if (resizeEdges & frame::EDGE_TOP) { + newY = resizeStartY + (resizeStartH - MIN_HEIGHT); + } + height = MIN_HEIGHT; + } + glfwSetWindowSize(window, width, height); + glfwSetWindowPos(window, newX, newY); + } + + void activateFrameButton(int index) { + if (index < 0 || index >= static_cast(frameButtons.size())) { + return; + } + switch (frameButtons[index]) { + case DecorationButton::MINIMIZE: + glfwIconifyWindow(window); + break; + case DecorationButton::MAXIMIZE: + toggleMaximize(); + break; + case DecorationButton::CLOSE: + glfwSetWindowShouldClose(window, true); + break; + } + } + + void toggleMaximize() { + if (glfwGetWindowAttrib(window, GLFW_MAXIMIZED)) { + glfwRestoreWindow(window); + } else { + glfwMaximizeWindow(window); + } + setShouldRefresh(); + } + + void applyDecoration() { + if (engineFrame) { + // frame_setup_native() owns the window style, GLFW would drop the + // thick frame the native resize border and snapping need + return; + } + glfwSetWindowAttrib(window, GLFW_DECORATED, GLFW_TRUE); + } + + static frame::Hit frame_hit_test(void* userdata, int x, int y) { + return static_cast(userdata)->hitTestFrame(x, y); + } + + static CursorShape edgeCursor(int edges) { + const bool left = edges & frame::EDGE_LEFT; + const bool right = edges & frame::EDGE_RIGHT; + const bool top = edges & frame::EDGE_TOP; + const bool bottom = edges & frame::EDGE_BOTTOM; + if (left && top) { + return CursorShape::NW_RESIZE; + } + if (right && top) { + return CursorShape::NE_RESIZE; + } + if (left && bottom) { + return CursorShape::SW_RESIZE; + } + if (right && bottom) { + return CursorShape::SE_RESIZE; + } + if (left) { + return CursorShape::W_RESIZE; + } + if (right) { + return CursorShape::E_RESIZE; + } + if (top) { + return CursorShape::N_RESIZE; + } + if (bottom) { + return CursorShape::S_RESIZE; + } + return CursorShape::ARROW; + } + GLFWwindow* window; + bool engineFrame = false; + std::vector frameButtons { + DecorationButton::MINIMIZE, + DecorationButton::MAXIMIZE, + DecorationButton::CLOSE, + }; + mutable std::vector buttonRects; + int hoveredButton = -1; + int pressedButton = -1; + bool dragging = false; + bool frameMoved = false; + double grabX = 0.0; + double grabY = 0.0; + int resizeEdges = 0; + int resizeStartX = 0; + int resizeStartY = 0; + int resizeStartW = 0; + int resizeStartH = 0; + double grabScreenX = 0.0; + double grabScreenY = 0.0; + double lastBarClick = 0.0; + static constexpr double DOUBLE_CLICK_TIME = 0.4; + static constexpr double MOVE_THRESHOLD = 4.0; + static constexpr int MIN_WIDTH = 320; + static constexpr int MIN_HEIGHT = 200; CursorShape cursor = CursorShape::ARROW; int framerate = -1; double prevSwap = 0.0; @@ -453,6 +807,12 @@ static_assert(!std::is_abstract()); static void mouse_button_callback(GLFWwindow* window, int button, int action, int) { auto handler = static_cast(glfwGetWindowUserPointer(window)); + double x = 0.0, y = 0.0; + glfwGetCursorPos(window, &x, &y); + if (handler->handleFrameButton(button, action == GLFW_PRESS, x, y)) { + handler->setShouldRefresh(); + return; + } handler->input.onMouseCallback(button, action == GLFW_PRESS); handler->setShouldRefresh(); } @@ -499,6 +859,7 @@ static void scroll_callback(GLFWwindow* window, double, double yoffset) { static void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos) { auto handler = static_cast(glfwGetWindowUserPointer(window)); handler->input.setCursorPosition(xpos, ypos); + handler->handleFrameMotion(xpos, ypos); handler->setShouldRefresh(); } @@ -557,6 +918,12 @@ std::tuple< } logger.info() << "windowing platform: " << get_platform_name(); + const bool engineFrame = use_engine_frame(); + if (engineFrame) { + // the engine draws the window bar, the system frame must be gone + glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); + } + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); #if GLFW_VERSION_MAJOR >= 3 && GLFW_VERSION_MINOR >= 4 @@ -636,8 +1003,11 @@ std::tuple< auto inputPtr = std::make_unique(window); auto windowPtr = std::make_unique( - *inputPtr, window, settings, width, height + *inputPtr, window, settings, width, height, engineFrame ); + // the engine draws the window bar from the title, and this is the only + // place the initial one is known + windowPtr->setTitle(title); glfwSetWindowUserPointer(window, windowPtr.get()); return {std::move(windowPtr), std::move(inputPtr)}; } From 7126158d68d4853eac01c3c3999fd07308aea456 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 15:51:32 +0300 Subject: [PATCH 24/35] Keep the window frame usable without a window manager frame_has_native_operations() trusted the X11 accessors of GLFW alone, but a window manager that does not advertise _NET_WM_MOVERESIZE drops the request silently: on a plain X11 session the frame asked it to move and resize the window and nothing happened at all. The root window is checked for the atom now, and the frame falls back to moving and resizing the window itself. The resize edges also win over the bar instead of the bar swallowing its top strip, which made the top edge and the top corners impossible to grab. Both backends log the active path as "engine window frame: on, window manager operations are on|off". --- src/window/detail/FrameOperations.cpp | 51 +++++++++++++++++++++++++-- src/window/detail/GLFWWindow.cpp | 26 ++++++++------ 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp index 294428789..6f9009888 100644 --- a/src/window/detail/FrameOperations.cpp +++ b/src/window/detail/FrameOperations.cpp @@ -1,6 +1,7 @@ #include "window/detail/FrameOperations.hpp" #if defined(VOXEL_X11_FRAME) +#include #include #include @@ -38,6 +39,50 @@ namespace { return api; } + /// @brief Whether the window manager advertises _NET_WM_MOVERESIZE + /// + /// Without it the request would be silently dropped, and the frame has to + /// move and resize the window itself. The answer is cached. + bool x11_supports_moveresize(Display* display) { + static int cached = -1; + if (cached >= 0) { + return cached == 1; + } + cached = 0; + const Atom supported = XInternAtom(display, "_NET_SUPPORTED", False); + const Atom moveresize = + XInternAtom(display, "_NET_WM_MOVERESIZE", False); + Atom type = 0; + int format = 0; + unsigned long count = 0, after = 0; + unsigned char* data = nullptr; + if (XGetWindowProperty( + display, + DefaultRootWindow(display), + supported, + 0, + 8192, + False, + XA_ATOM, + &type, + &format, + &count, + &after, + &data + ) == Success && + data != nullptr) { + const Atom* atoms = reinterpret_cast(data); + for (unsigned long i = 0; i < count; i++) { + if (atoms[i] == moveresize) { + cached = 1; + break; + } + } + XFree(data); + } + return cached == 1; + } + /// @brief Edge mask to the _NET_WM_MOVERESIZE direction int x11_direction(int edges) { switch (edges) { @@ -70,7 +115,8 @@ namespace { } Display* display = api.display(); const Window window = api.window(glfwWindow); - if (display == nullptr || window == 0) { + if (display == nullptr || window == 0 || + !x11_supports_moveresize(display)) { return false; } const Window root = DefaultRootWindow(display); @@ -184,7 +230,8 @@ namespace { bool frame_has_native_operations() { #if defined(VOXEL_X11_FRAME) - return x11_api().available(); + X11Api& api = x11_api(); + return api.available() && x11_supports_moveresize(api.display()); #else return false; #endif diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 3038f8f24..737c1f736 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -378,18 +378,18 @@ public: ) >= 0) { return frame::Hit {}; } - if (y < height) { - return frame::Hit {true, 0}; + // the resize edges win over the bar, its top strip resizes too + const int edges = frame::edgesAt( + getSize().x, + getSize().y, + height, + static_cast(x), + static_cast(y) + ); + if (edges != 0) { + return frame::Hit {false, edges}; } - return frame::Hit { - false, - frame::edgesAt( - getSize().x, - getSize().y, - height, - static_cast(x), - static_cast(y) - )}; + return frame::Hit {y < height, 0}; } /// @brief Turns a pointer move into hovering, dragging or resizing @@ -919,6 +919,10 @@ std::tuple< logger.info() << "windowing platform: " << get_platform_name(); const bool engineFrame = use_engine_frame(); + logger.info() << "engine window frame: " << (engineFrame ? "on" : "off") + << (engineFrame && frame_has_native_operations() + ? ", window manager operations are on" + : ""); if (engineFrame) { // the engine draws the window bar, the system frame must be gone glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); From f13b75475f5d3861f142407769868c4bb67287f4 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 16:04:39 +0300 Subject: [PATCH 25/35] Let the window frame keep its cursor The GUI sets the cursor of the hovered widget every frame, and over the window that widget is usually the background with a plain arrow. The frame sets its resize cursors on pointer motion, so the GUI replaced them on the next frame: hovering a window edge did not show a resize cursor, it flickered and stayed an arrow. The window now reports whether the frame owns the cursor, and the GUI only sets the hovered cursor when it does not. The GLFW backend claims it inside the frame and gives it back in the client area together with the arrow, since the GUI sets a cursor only while a widget is hovered. Wayland keeps returning false, so the GUI behaves exactly as before there. --- src/graphics/ui/GUI.cpp | 2 +- src/window/Window.hpp | 8 ++++++++ src/window/detail/GLFWWindow.cpp | 13 +++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/graphics/ui/GUI.cpp b/src/graphics/ui/GUI.cpp index d80c03d71..2786590cb 100644 --- a/src/graphics/ui/GUI.cpp +++ b/src/graphics/ui/GUI.cpp @@ -310,7 +310,7 @@ void GUI::draw(const DrawContext& pctx, Assets& assets) { frame->draw(ctx, assets); } - if (hover) { + if (hover && !engine.getWindow().ownsCursor()) { engine.getWindow().setCursor(hover->getCursor()); } if (hover && debug) { diff --git a/src/window/Window.hpp b/src/window/Window.hpp index b1840175c..db837eade 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -52,6 +52,14 @@ public: } virtual void setCursor(CursorShape shape) = 0; + + /// @brief Whether the engine drawn window frame owns the cursor now + /// + /// The frame puts the resize cursors of its edges and of the bar, and the + /// GUI must not override them with the cursor of the hovered widget. + virtual bool ownsCursor() const { + return false; + } virtual void setMode(WindowMode mode) = 0; virtual WindowMode getMode() const = 0; diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 737c1f736..c6ec88758 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -361,6 +361,10 @@ public: return hoveredButton; } + bool ownsCursor() const override { + return frameCursorActive; + } + /// @brief What the pointer is over, in client coordinates frame::Hit hitTestFrame(int x, int y) const { const int height = barHeight(); @@ -396,6 +400,7 @@ public: void handleFrameMotion(double x, double y) { if (input.isCursorLocked() || barHeight() <= 0) { hoveredButton = -1; + frameCursorActive = false; return; } if (dragging || resizeEdges != 0) { @@ -641,8 +646,15 @@ private: ) : 0; if (edges != 0) { + frameCursorActive = true; setCursor(edgeCursor(edges)); } else if (y < height) { + frameCursorActive = true; + setCursor(CursorShape::ARROW); + } else if (frameCursorActive) { + // the client area below the bar belongs to the GUI, which only + // sets a cursor when a widget is hovered + frameCursorActive = false; setCursor(CursorShape::ARROW); } } @@ -779,6 +791,7 @@ private: }; mutable std::vector buttonRects; int hoveredButton = -1; + bool frameCursorActive = false; int pressedButton = -1; bool dragging = false; bool frameMoved = false; From 4bc81af7267672023a415ac6140a050de8d7784c Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 16:10:04 +0300 Subject: [PATCH 26/35] Include glfw3.h before glfw3native.h glfw3native.h needs the GLFWmonitor, GLFWwindow and GLFWAPI declarations of glfw3.h, so the windows build failed on the win32 branch. Only that branch is affected: x11 resolves the GLFW accessors with dlsym and does not include the native header at all. --- src/window/detail/FrameOperations.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp index 6f9009888..530869769 100644 --- a/src/window/detail/FrameOperations.cpp +++ b/src/window/detail/FrameOperations.cpp @@ -164,6 +164,8 @@ namespace { #include #include +#include + #define GLFW_EXPOSE_NATIVE_WIN32 #include From 68d4214627711be994ff7e5be0575a2f34cc850a Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 22:02:33 +0300 Subject: [PATCH 27/35] Fix the engine window frame on windows Four things came out of testing on windows. The window settings were hidden outside of wayland because the check used the backend name, while the bar height matters wherever the engine draws the frame. The window now reports that (hasEngineFrame: barEnabled on wayland, engineFrame on glfw) and the display page asks for it. Only the live resize switch stays wayland specific, since the glfw backend always draws a fresh frame. The simplified mode is gone: when the frame is active and the surface has alpha, the shadow and the outer resize border are always there. The bar and its controls are drawn even when the font is missing: the early return used to make the whole bar invisible while its hit zones kept working. GLFW rewrites the window style on every mode change and dropped the thick frame the native resize border and snapping need, so the frame is set up again after such a change. Windows runs a modal loop while a window border is dragged and the main loop is blocked inside it, which froze the content during a resize. The backend draws and presents a frame from the refresh callback now, and skips the framerate limit there. --- res/layouts/pages/settings_display.xml.lua | 12 ++--- res/texts/ru_RU.txt | 2 - src/engine/WindowBar.cpp | 56 +++++++++++----------- src/engine/WindowControl.cpp | 8 ++++ src/io/settings_io.cpp | 1 - src/logic/scripting/lua/libs/libapp.cpp | 6 +++ src/settings.hpp | 2 - src/window/Window.hpp | 25 ++++++++++ src/window/detail/GLFWWindow.cpp | 20 ++++++-- src/window/wayland/WaylandWindow.cpp | 11 +---- src/window/wayland/WaylandWindow.hpp | 5 +- 11 files changed, 96 insertions(+), 52 deletions(-) diff --git a/res/layouts/pages/settings_display.xml.lua b/res/layouts/pages/settings_display.xml.lua index 8c7986989..4525b92ed 100644 --- a/res/layouts/pages/settings_display.xml.lua +++ b/res/layouts/pages/settings_display.xml.lua @@ -66,16 +66,16 @@ function on_open() "", app.get_setting("display.window-mode")) ) - -- these only affect the window frame the native wayland backend draws - if app.get_window_backend() == "wayland" then + -- the bar height matters wherever the engine draws the window frame + if app.has_engine_window_frame() then create_checkbox( "display.compact-window-bar", "Narrow Window Bar", "display.compact-window-bar.tooltip" ) - create_checkbox( - "display.simple-window", "Simple Window", - "display.simple-window.tooltip" - ) + end + -- live rendering only has the cached frame as its alternative, which is + -- what the native wayland backend does + if app.get_window_backend() == "wayland" then create_checkbox( "display.live-resize", "Live Window Resize", "display.live-resize.tooltip" diff --git a/res/texts/ru_RU.txt b/res/texts/ru_RU.txt index 97372af89..38d4048c8 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -119,10 +119,8 @@ settings.Clouds quality=Качество облаков settings.Acoustic effects=Акустические эффекты settings.Microphone access=Доступ к микрофону settings.Narrow Window Bar=Узкая шапка окна -settings.Simple Window=Простое окно settings.Live Window Resize=Живой ресайз окна settings.display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px -settings.display.simple-window.tooltip=Без тени и внешней рамки ресайза settings.display.live-resize.tooltip=Перерисовывать содержимое окна при изменении размера (выключено — последний кадр растягивается) # Управление diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp index 0c28c0f7c..68fdeabd8 100644 --- a/src/engine/WindowBar.cpp +++ b/src/engine/WindowBar.cpp @@ -40,9 +40,6 @@ void draw_window_bar(Engine& engine) { } auto* batch = engine.getGUI().getBatch2D(); auto font = engine.requireAssets().getShared(BAR_FONT); - if (font == nullptr) { - return; - } const auto size = window.getSize(); const float barHeight = static_cast(height); @@ -81,30 +78,35 @@ void draw_window_bar(Engine& engine) { titleRight = std::min(titleRight, item.x - 8.0f); } } - const std::wstring title = to_wide(window.getTitle()); - const float available = std::max(0.0f, titleRight - titleLeft); - size_t titleLength = title.size(); - while (titleLength > 0 && font->calcWidth(title, titleLength) > available) { - titleLength--; - } - if (titleLength > 0) { - const float textWidth = static_cast( - font->calcWidth(title, titleLength) - ); - const float centered = (static_cast(size.x) - textWidth) * 0.5f; - const float titleX = std::clamp( - centered, - titleLeft, - std::max(titleLeft, titleRight - textWidth) - ); - batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f)); - font->draw( - *batch, std::wstring_view(title).substr(0, titleLength), - static_cast(titleX), - (height - font->getLineHeight()) / 2, - nullptr, 0 - ); - batch->untexture(); + // the bar and its controls do not need the font, only the title does + if (font != nullptr) { + const std::wstring title = to_wide(window.getTitle()); + const float available = std::max(0.0f, titleRight - titleLeft); + size_t titleLength = title.size(); + while (titleLength > 0 && + font->calcWidth(title, titleLength) > available) { + titleLength--; + } + if (titleLength > 0) { + const float textWidth = static_cast( + font->calcWidth(title, titleLength) + ); + const float centered = + (static_cast(size.x) - textWidth) * 0.5f; + const float titleX = std::clamp( + centered, + titleLeft, + std::max(titleLeft, titleRight - textWidth) + ); + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f)); + font->draw( + *batch, std::wstring_view(title).substr(0, titleLength), + static_cast(titleX), + (height - font->getLineHeight()) / 2, + nullptr, 0 + ); + batch->untexture(); + } } for (size_t i = 0; i < buttons.size(); i++) { diff --git a/src/engine/WindowControl.cpp b/src/engine/WindowControl.cpp index 19119fb12..add00ba1a 100644 --- a/src/engine/WindowControl.cpp +++ b/src/engine/WindowControl.cpp @@ -66,6 +66,14 @@ WindowControl::Result WindowControl::initialize() { } } + // Windows blocks the main loop inside its own modal loop while the user + // drags a window border, and asks for a repaint instead: drawing a frame + // from there is what keeps the content alive during such a resize. + window->setRefreshHandler([this] { + engine.renderFrame(); + engine.getWindow().swapBuffers(); + }); + return Result {std::move(window), std::move(input)}; } diff --git a/src/io/settings_io.cpp b/src/io/settings_io.cpp index 4c2b3c218..8ccb24839 100644 --- a/src/io/settings_io.cpp +++ b/src/io/settings_io.cpp @@ -56,7 +56,6 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) { builder.add("window-mode", &settings.display.windowMode); builder.add("adaptive-menu-fps", &settings.display.adaptiveFpsInMenu); builder.add("compact-window-bar", &settings.display.compactWindowBar); - builder.add("simple-window", &settings.display.simpleWindow); builder.add("live-resize", &settings.display.liveResize); builder.addSection("camera"); diff --git a/src/logic/scripting/lua/libs/libapp.cpp b/src/logic/scripting/lua/libs/libapp.cpp index b69908624..13146979d 100644 --- a/src/logic/scripting/lua/libs/libapp.cpp +++ b/src/logic/scripting/lua/libs/libapp.cpp @@ -229,6 +229,11 @@ static int l_open_url(lua::State* L) { } +/// @brief Whether the engine draws the window frame itself +static int l_has_engine_window_frame(lua::State* L) { + return lua::pushboolean(L, engine->getWindow().hasEngineFrame()); +} + /// @brief Name of the windowing backend ("glfw" or "wayland") static int l_get_window_backend(lua::State* L) { return lua::pushstring(L, engine->getWindow().getBackendName()); @@ -508,6 +513,7 @@ const luaL_Reg applib[] = { {"open_url", lua::wrap}, /// window {"get_window_backend", lua::wrap}, + {"has_engine_window_frame", lua::wrap}, {"focus", lua::wrap}, {"set_title", lua::wrap}, {"quit", lua::wrap}, diff --git a/src/settings.hpp b/src/settings.hpp index 9d9b3c80a..88a6ec133 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -40,8 +40,6 @@ struct DisplaySettings { FlagSetting adaptiveFpsInMenu {false}; /// @brief Draw the narrow (24px) window bar instead of the 48px one FlagSetting compactWindowBar {false}; - /// @brief Draw the window without the shadow and the resize border - FlagSetting simpleWindow {false}; /// @brief Render the window content every frame while it is resized FlagSetting liveResize {true}; }; diff --git a/src/window/Window.hpp b/src/window/Window.hpp index db837eade..7fac8dff3 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -72,6 +73,29 @@ public: return empty; } + /// @brief Whether the engine draws the window frame itself here + /// + /// The bar height and its buttons only mean something when it does, and + /// the window settings are only shown where that is the case. + /// @brief Handler the windowing system calls when it wants a repaint + /// + /// Windows runs a modal loop while the user drags a window border and the + /// main loop is blocked inside it, so the only way to keep the content + /// alive during such a resize is to draw a frame from the message loop. + using RefreshHandler = std::function; + + void setRefreshHandler(RefreshHandler handler) { + refreshHandler = std::move(handler); + } + + const RefreshHandler& getRefreshHandler() const { + return refreshHandler; + } + + virtual bool hasEngineFrame() const { + return false; + } + virtual const char* getBackendName() const = 0; virtual int getDecorationHeight() const { @@ -118,6 +142,7 @@ protected: std::stack scissorStack; glm::vec4 scissorArea {}; WindowMode mode = WindowMode::WINDOWED; + RefreshHandler refreshHandler; }; namespace display { diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index c6ec88758..28a753269 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -307,7 +307,7 @@ public: void swapBuffers() override { glfwSwapBuffers(window); resetScissor(); - if (framerate > 0) { + if (framerate > 0 && !inRefreshCallback) { auto elapsedTime = time() - prevSwap; auto frameTime = 1.0 / framerate; if (elapsedTime < frameTime) { @@ -361,6 +361,13 @@ public: return hoveredButton; } + bool hasEngineFrame() const override { + return engineFrame; + } + + /// @brief Set while a frame is drawn from the refresh callback + bool inRefreshCallback = false; + bool ownsCursor() const override { return frameCursorActive; } @@ -739,8 +746,9 @@ private: void applyDecoration() { if (engineFrame) { - // frame_setup_native() owns the window style, GLFW would drop the - // thick frame the native resize border and snapping need + // GLFW rewrites the window style on every mode change and drops + // the thick frame the native resize border and snapping need + frame_setup_native(window, &frame_hit_test, this); return; } glfwSetWindowAttrib(window, GLFW_DECORATED, GLFW_TRUE); @@ -904,6 +912,12 @@ static void create_standard_cursors() { static void refresh_callback(GLFWwindow* window) { auto handler = static_cast(glfwGetWindowUserPointer(window)); handler->setShouldRefresh(); + const auto& refresh = handler->getRefreshHandler(); + if (refresh) { + handler->inRefreshCallback = true; + refresh(); + handler->inRefreshCallback = false; + } } static void setup_callbacks(GLFWwindow* window) { diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index c7cbb37ef..5f38dabc6 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -281,8 +281,7 @@ void WaylandWindow::setMaximized(bool enabled) { } int WaylandWindow::marginSize() const { - if (!barEnabled || !shadowEnabled || - (settings != nullptr && settings->simpleWindow.get())) { + if (!barEnabled || !shadowEnabled) { return 0; } if (fullscreen || maximized || Window::mode != WindowMode::WINDOWED) { @@ -307,14 +306,6 @@ void WaylandWindow::updateSettings() { if (settings == nullptr) { return; } - const bool simple = settings->simpleWindow.get(); - if (simple != simpleWindowSetting) { - simpleWindowSetting = simple; - // The surface size depends on whether the frame around the content is - // drawn at all, so the egl window and the toplevel geometry change. - resize(size.x, size.y); - setShouldRefresh(); - } const bool compactBar = settings->compactWindowBar.get(); if (compactBar != compactBarSetting) { compactBarSetting = compactBar; diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 9754126cd..495236a0c 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -114,6 +114,10 @@ class WaylandWindow : public Window { void focus() override; void setTitle(const std::string& title) override; const std::string& getTitle() const override; + bool hasEngineFrame() const override { + return barEnabled; + } + const char* getBackendName() const override { return "wayland"; } @@ -133,7 +137,6 @@ class WaylandWindow : public Window { static constexpr int SHADOW_MARGIN = 10; static constexpr int RESIZE_GRAB_EXTRA = 2; bool shadowEnabled = false; - bool simpleWindowSetting = false; bool compactBarSetting = false; GLuint shadowProgram = 0; From 74a28cebe57da0f1b527ee453284604671768f22 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 23:04:27 +0300 Subject: [PATCH 28/35] Fix the windows frame hang and center new windows The frame is set up again after every window mode change, but it subclassed the window procedure each time and stored our own procedure as the original one. Every message we do not handle then went through CallWindowProc straight back into ourselves: the window hung, and repaint messages were lost with it, which is what broke the live rendering during a resize. The subclass is installed once now, while the window style is still re-applied on every mode change. New windows are also placed at the center of the monitor work area instead of the top left corner. This only happens where the platform lets the client place its window, which wayland does not. --- src/window/detail/FrameOperations.cpp | 12 +++++++++--- src/window/detail/GLFWWindow.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp index 530869769..76effe5f8 100644 --- a/src/window/detail/FrameOperations.cpp +++ b/src/window/detail/FrameOperations.cpp @@ -277,9 +277,15 @@ void frame_setup_native( style |= WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU; style &= ~WS_CAPTION; SetWindowLongPtr(hwnd, GWL_STYLE, style); - original_window_proc = reinterpret_cast(SetWindowLongPtr( - hwnd, GWLP_WNDPROC, reinterpret_cast(frame_window_proc) - )); + // Only subclass once: storing our own procedure as the original one + // would send every unhandled message back into it, forever. + const LONG_PTR current = GetWindowLongPtr(hwnd, GWLP_WNDPROC); + if (current != reinterpret_cast(frame_window_proc)) { + original_window_proc = reinterpret_cast(current); + SetWindowLongPtr( + hwnd, GWLP_WNDPROC, reinterpret_cast(frame_window_proc) + ); + } SetWindowPos( hwnd, nullptr, diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 28a753269..633af93b1 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -56,6 +56,16 @@ static bool use_engine_frame() { #endif } +/// @brief Whether the platform lets the client place its own window +static bool can_place_window() { +#if GLFW_VERSION_MAJOR > 3 || \ + (GLFW_VERSION_MAJOR == 3 && GLFW_VERSION_MINOR >= 4) + return glfwGetPlatform() != GLFW_PLATFORM_WAYLAND; +#else + return true; +#endif +} + static std::unordered_set supported_gl_extensions; static void window_size_callback(GLFWwindow* window, int width, int height); @@ -980,6 +990,22 @@ std::tuple< glfwTerminate(); return {nullptr, nullptr}; } + if (can_place_window()) { + int areaX = 0, areaY = 0, areaWidth = 0, areaHeight = 0; + glfwGetMonitorWorkarea( + glfwGetPrimaryMonitor(), + &areaX, + &areaY, + &areaWidth, + &areaHeight + ); + glfwSetWindowPos( + window, + areaX + (areaWidth - width) / 2, + areaY + (areaHeight - height) / 2 + ); + } + glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; From 4f9b125e17a92061f1f78e384c39a86d0aa62789 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sat, 10 Oct 2026 23:04:27 +0300 Subject: [PATCH 29/35] Record where the wayland protocol descriptions come from They are vendored on purpose: they come from wayland-protocols rather than libwayland, they are newer than the 1.25 of older distributions, and the build has to work offline and from a source archive. --- src/window/wayland/protocols/SOURCES.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/window/wayland/protocols/SOURCES.txt diff --git a/src/window/wayland/protocols/SOURCES.txt b/src/window/wayland/protocols/SOURCES.txt new file mode 100644 index 000000000..1fb6d3d0c --- /dev/null +++ b/src/window/wayland/protocols/SOURCES.txt @@ -0,0 +1,10 @@ +From wayland-protocols (not libwayland), newer than 1.25 (xdg-shell v7, cursor-shape-v1 v2). +sha256 of the revision in use, keep the copyright headers when updating: + +bb57d91e53a79dadab7c612dab87c233393cee73673feefa7442cfbfdd9aed2f cursor-shape-v1.xml +c2ac9f002c6669ca6c02eb9b587b8e9108e3ce6deab4a2de58b576f4f864ca38 idle-inhibit-unstable-v1.xml +f980fac900ba1dcfbbe97f588fc17b893926bd2b57624563653a1bfe4d035948 pointer-constraints-unstable-v1.xml +ab4930dd3084f732b6fdd12ee6dbd0a112a758ed8a57b170366391dbeb1a22ff relative-pointer-unstable-v1.xml +db291b574adb2d42d27f3d01a77723bb3350a7a32e6d33de16513521b42294a9 tablet-unstable-v2.xml +68753c4a85a28659e3aa1fe0f138329a8bf3dff0b4789f4663a2c7fedbfecf2f xdg-decoration-unstable-v1.xml +7ba7f9c8473deee674cb1f154a18abd0bb0cc072604fc055b0c15e459fc4c7df xdg-shell.xml From 4d1b4a16387e9a3e4e348546b7eec95c57f5993d Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sun, 11 Oct 2026 01:05:47 +0300 Subject: [PATCH 30/35] Redraw the windows frame from WM_SIZE and keep its style The refresh callback is triggered by WM_PAINT, but windows does not send it while a border is dragged: the window class has neither CS_HREDRAW nor CS_VREDRAW and nothing invalidates the client area. Only WM_SIZE arrives, so nothing was drawn during such a resize. The frame is drawn from WM_SIZE now, after forwarding the message to GLFW so that the new size is already in. WM_NCHITTEST re-applies the style bits the engine frame needs and which GLFW drops on every window mode change, taking the drag area with them. Every frame setup logs whether the subclass had to be installed again, so a lost window procedure is visible in the log. The live resize switch is honoured by the GLFW backend as well: with it off the frame from the message loop is skipped and the window keeps showing what the system stretches. --- res/layouts/pages/settings_display.xml.lua | 14 +++--- res/texts/ru_RU.txt | 2 +- src/window/detail/FrameOperations.cpp | 55 +++++++++++++++++++--- src/window/detail/FrameOperations.hpp | 12 ++++- src/window/detail/GLFWWindow.cpp | 42 +++++++++++++---- 5 files changed, 100 insertions(+), 25 deletions(-) diff --git a/res/layouts/pages/settings_display.xml.lua b/res/layouts/pages/settings_display.xml.lua index 4525b92ed..b6eaa6fa4 100644 --- a/res/layouts/pages/settings_display.xml.lua +++ b/res/layouts/pages/settings_display.xml.lua @@ -73,14 +73,12 @@ function on_open() "display.compact-window-bar.tooltip" ) end - -- live rendering only has the cached frame as its alternative, which is - -- what the native wayland backend does - if app.get_window_backend() == "wayland" then - create_checkbox( - "display.live-resize", "Live Window Resize", - "display.live-resize.tooltip" - ) - end + -- every backend has an alternative to redrawing during a resize: the + -- cached frame on wayland, the frame the system stretches elsewhere + create_checkbox( + "display.live-resize", "Live Window Resize", + "display.live-resize.tooltip" + ) create_checkbox("camera.shaking", "Camera Shaking") create_checkbox("camera.inertia", "Camera Inertia") diff --git a/res/texts/ru_RU.txt b/res/texts/ru_RU.txt index 38d4048c8..efcd0ab96 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -121,7 +121,7 @@ settings.Microphone access=Доступ к микрофону settings.Narrow Window Bar=Узкая шапка окна settings.Live Window Resize=Живой ресайз окна settings.display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px -settings.display.live-resize.tooltip=Перерисовывать содержимое окна при изменении размера (выключено — последний кадр растягивается) +settings.display.live-resize.tooltip=Перерисовывать окно при изменении размера (выключено — показывать последний кадр) # Управление chunks.reload=Перезагрузить Чанки diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp index 76effe5f8..6c5ebff46 100644 --- a/src/window/detail/FrameOperations.cpp +++ b/src/window/detail/FrameOperations.cpp @@ -169,10 +169,31 @@ namespace { #define GLFW_EXPOSE_NATIVE_WIN32 #include +#include "debug/Logger.hpp" + +static debug::Logger frame_logger("window-frame"); + namespace { WNDPROC original_window_proc = nullptr; frame::Hit (*hit_test_callback)(void*, int, int) = nullptr; void* hit_test_userdata = nullptr; + FrameRefresh refresh_callback = nullptr; + void* refresh_userdata = nullptr; + + /// @brief Keeps the window style the engine frame relies on + /// + /// GLFW rewrites the style on every window mode change, and a lost thick + /// frame takes the native resize border and the window snapping with it. + void apply_engine_style(HWND hwnd) { + const LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); + const LONG_PTR wanted = + (style | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | + WS_SYSMENU) & + ~WS_CAPTION; + if (wanted != style) { + SetWindowLongPtr(hwnd, GWL_STYLE, wanted); + } + } LRESULT CALLBACK frame_window_proc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam @@ -190,7 +211,21 @@ namespace { case WM_NCACTIVATE: // and it is not repainted when the window is activated return TRUE; + case WM_SIZE: { + // Windows runs its own modal loop while a border is dragged + // and never sends WM_PAINT there, so WM_SIZE is the only + // place to draw a frame from during such a resize. + const LRESULT result = CallWindowProc( + original_window_proc, hwnd, message, wparam, lparam + ); + if (refresh_callback != nullptr) { + refresh_callback(refresh_userdata); + } + return result; + } case WM_NCHITTEST: { + // the style may have been rewritten since the last setup + apply_engine_style(hwnd); if (hit_test_callback == nullptr) { break; } @@ -261,7 +296,9 @@ bool frame_start_resize(GLFWwindow* window, int edges) { void frame_setup_native( GLFWwindow* window, frame::Hit (*hitTest)(void*, int, int), - void* userdata + void* hitTestData, + FrameRefresh refresh, + void* refreshData ) { #if defined(_WIN32) HWND hwnd = glfwGetWin32Window(window); @@ -269,14 +306,13 @@ void frame_setup_native( return; } hit_test_callback = hitTest; - hit_test_userdata = userdata; + hit_test_userdata = hitTestData; + refresh_callback = refresh; + refresh_userdata = refreshData; // The native frame stays: its thick frame is what gives the window the // resize border, the shadow, the animations and the snap layouts. Only // the caption is hidden, and the client area covers the whole window. - LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); - style |= WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU; - style &= ~WS_CAPTION; - SetWindowLongPtr(hwnd, GWL_STYLE, style); + apply_engine_style(hwnd); // Only subclass once: storing our own procedure as the original one // would send every unhandled message back into it, forever. const LONG_PTR current = GetWindowLongPtr(hwnd, GWLP_WNDPROC); @@ -285,6 +321,9 @@ void frame_setup_native( SetWindowLongPtr( hwnd, GWLP_WNDPROC, reinterpret_cast(frame_window_proc) ); + frame_logger.info() << "window frame: subclass installed"; + } else { + frame_logger.info() << "window frame: subclass was ours"; } SetWindowPos( hwnd, @@ -298,6 +337,8 @@ void frame_setup_native( #else (void)window; (void)hitTest; - (void)userdata; + (void)hitTestData; + (void)refresh; + (void)refreshData; #endif } diff --git a/src/window/detail/FrameOperations.hpp b/src/window/detail/FrameOperations.hpp index 5871b0982..9cb8ecc0b 100644 --- a/src/window/detail/FrameOperations.hpp +++ b/src/window/detail/FrameOperations.hpp @@ -21,8 +21,18 @@ bool frame_start_move(GLFWwindow* window); /// @brief Ask the window manager to start resizing the window bool frame_start_resize(GLFWwindow* window, int edges); +/// @brief Called when the windowing system wants the content redrawn +using FrameRefresh = void (*)(void*); + /// @brief Hide the caption of the native frame, keeping the rest of it /// @param hitTest tells what the pointer is over -void frame_setup_native(GLFWwindow* window, frame::Hit (*hitTest)(void*, int, int), void* userdata); +/// @param refresh draws a frame when the system blocks the main loop +void frame_setup_native( + GLFWwindow* window, + frame::Hit (*hitTest)(void*, int, int), + void* hitTestData, + FrameRefresh refresh, + void* refreshData +); /// @} diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 633af93b1..91e684dd6 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -297,7 +297,9 @@ public: window(window), engineFrame(engineFrame) { if (engineFrame) { - frame_setup_native(window, &frame_hit_test, this); + frame_setup_native( + window, &frame_hit_test, this, &frame_refresh_thunk, this + ); } } @@ -375,6 +377,33 @@ public: return engineFrame; } + /// @brief Whether the window is redrawn while it is being resized + bool isLiveResizeEnabled() const { + return settings == nullptr || settings->liveResize.get(); + } + + /// @brief Draws a frame for the windowing system + /// + /// Windows runs a modal loop while a border is dragged and blocks the main + /// loop inside it, so the only frames drawn during such a resize are the + /// ones asked for from the message loop. + void drawRefreshFrame() { + if (!isLiveResizeEnabled()) { + return; + } + const auto& refresh = getRefreshHandler(); + if (!refresh) { + return; + } + inRefreshCallback = true; + refresh(); + inRefreshCallback = false; + } + + static void frame_refresh_thunk(void* userdata) { + static_cast(userdata)->drawRefreshFrame(); + } + /// @brief Set while a frame is drawn from the refresh callback bool inRefreshCallback = false; @@ -758,7 +787,9 @@ private: if (engineFrame) { // GLFW rewrites the window style on every mode change and drops // the thick frame the native resize border and snapping need - frame_setup_native(window, &frame_hit_test, this); + frame_setup_native( + window, &frame_hit_test, this, &frame_refresh_thunk, this + ); return; } glfwSetWindowAttrib(window, GLFW_DECORATED, GLFW_TRUE); @@ -922,12 +953,7 @@ static void create_standard_cursors() { static void refresh_callback(GLFWwindow* window) { auto handler = static_cast(glfwGetWindowUserPointer(window)); handler->setShouldRefresh(); - const auto& refresh = handler->getRefreshHandler(); - if (refresh) { - handler->inRefreshCallback = true; - refresh(); - handler->inRefreshCallback = false; - } + handler->drawRefreshFrame(); } static void setup_callbacks(GLFWwindow* window) { From c635549892453d0eb942674cf85dc66f3b79cb69 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sun, 11 Oct 2026 20:06:03 +0300 Subject: [PATCH 31/35] Fix the issues found while reviewing the Wayland backend Report the errors the display read loop can fail with instead of dispatching events on a dead connection, and release exactly the keys the user really holds: BaseInput::pressedKeys is never erased, so the previous list sent key releases for keys that were never pressed. The bar is the only owner of the pointer edges now, the fullscreen state comes from the compositor, and the decorations are enabled once, with the window geometry published again. The initialization failure paths destroy their resources exactly once, the screen state is reset on teardown, the clipboard write does not block the frame loop on a slow reader, and the gsettings fallback is not retried after it failed. The stretch blit of the last frame is gone: composeFrame() already paints the cached content. --- src/window/wayland/WaylandCommon.cpp | 50 ++++++++--- src/window/wayland/WaylandCommon.hpp | 7 +- src/window/wayland/WaylandDecorations.cpp | 33 +++++-- src/window/wayland/WaylandInit.cpp | 100 ++++++++++------------ src/window/wayland/WaylandInput.hpp | 58 +++++++++++-- src/window/wayland/WaylandListeners.cpp | 4 +- src/window/wayland/WaylandSettings.cpp | 25 ++++-- src/window/wayland/WaylandWindow.cpp | 55 ++++-------- src/window/wayland/WaylandWindow.hpp | 11 ++- 9 files changed, 206 insertions(+), 137 deletions(-) diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp index be4afff39..bf998a272 100644 --- a/src/window/wayland/WaylandCommon.cpp +++ b/src/window/wayland/WaylandCommon.cpp @@ -1,5 +1,6 @@ #include "window/wayland/WaylandCommon.hpp" +#include #include #include @@ -20,7 +21,6 @@ double waylandNow() { ).count(); } - GlStateGuard::GlStateGuard() { glGetIntegerv(GL_CURRENT_PROGRAM, &values[0]); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &values[1]); @@ -37,6 +37,7 @@ GlStateGuard::GlStateGuard() { glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &values[12]); glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &values[13]); glGetIntegerv(GL_DEPTH_WRITEMASK, &values[14]); + glGetIntegerv(GL_PACK_ALIGNMENT, &values[15]); glGetIntegerv(GL_VIEWPORT, viewport); glGetIntegerv(GL_COLOR_WRITEMASK, colorMask); for (int i = 0; i < 3; i++) { @@ -52,11 +53,13 @@ GlStateGuard::GlStateGuard() { ); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &attribs[i][3]); glGetVertexAttribiv( - i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][5] + i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][4] ); void* pointer = nullptr; glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer); - attribs[i][6] = static_cast(reinterpret_cast(pointer)); + attribs[i][5] = static_cast( + reinterpret_cast(pointer) + ); } flags[0] = glIsEnabled(GL_BLEND); flags[1] = glIsEnabled(GL_DEPTH_TEST); @@ -70,6 +73,7 @@ GlStateGuard::~GlStateGuard() { glActiveTexture(values[2]); glBindTexture(GL_TEXTURE_2D, values[3]); glPixelStorei(GL_UNPACK_ALIGNMENT, values[4]); + glPixelStorei(GL_PACK_ALIGNMENT, values[15]); glBlendFuncSeparate(values[5], values[6], values[7], values[8]); glBlendEquationSeparate(values[9], values[10]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, values[12]); @@ -86,11 +90,11 @@ GlStateGuard::~GlStateGuard() { } } for (int i = 0; i < 3; i++) { - glBindBuffer(GL_ARRAY_BUFFER, static_cast(attribs[i][5])); + glBindBuffer(GL_ARRAY_BUFFER, static_cast(attribs[i][4])); glVertexAttribPointer( i, attribs[i][0], static_cast(attribs[i][1]), attribs[i][2], attribs[i][3], - reinterpret_cast(static_cast(attribs[i][6])) + reinterpret_cast(static_cast(attribs[i][5])) ); if (attribFlags[i]) { glEnableVertexAttribArray(i); @@ -125,8 +129,6 @@ class WaylandWindow; WaylandInput* input = nullptr; WaylandWindow* window = nullptr; -bool serverDecorations = false; - int keycode_from_keysym(xkb_keysym_t sym) { switch (sym) { case XKB_KEY_Escape: return GLFW_KEY_ESCAPE; @@ -203,21 +205,43 @@ int keycode_from_keysym(xkb_keysym_t sym) { } void dispatch_events(int timeoutMs) { - wl_display_flush(state.display); + if (state.display == nullptr) { + return; + } + if (wl_display_get_error(state.display) != 0) { + on_display_error(); + return; + } + if (wl_display_flush(state.display) == -1 && errno != EAGAIN) { + on_display_error(); + return; + } while (wl_display_prepare_read(state.display) != 0) { - wl_display_dispatch_pending(state.display); - wl_display_flush(state.display); + if (wl_display_get_error(state.display) != 0) { + on_display_error(); + return; + } + if (wl_display_dispatch_pending(state.display) == -1 || + wl_display_get_error(state.display) != 0) { + on_display_error(); + return; + } + if (wl_display_flush(state.display) == -1 && errno != EAGAIN) { + on_display_error(); + return; + } } pollfd descriptor {wl_display_get_fd(state.display), POLLIN, 0}; if (poll(&descriptor, 1, timeoutMs) > 0) { if (wl_display_read_events(state.display) == -1) { - wl_display_cancel_read(state.display); + on_display_error(); + return; } } else { wl_display_cancel_read(state.display); } - wl_display_dispatch_pending(state.display); - if (wl_display_get_error(state.display) != 0) { + if (wl_display_dispatch_pending(state.display) == -1 || + wl_display_get_error(state.display) != 0) { on_display_error(); } } diff --git a/src/window/wayland/WaylandCommon.hpp b/src/window/wayland/WaylandCommon.hpp index f1378a2ec..e49beeee7 100644 --- a/src/window/wayland/WaylandCommon.hpp +++ b/src/window/wayland/WaylandCommon.hpp @@ -26,17 +26,16 @@ #include #include #include -#include #include #include #include struct GlStateGuard { GLint values[16] {}; - GLint attribs[3][7] {}; + GLint attribs[3][6] {}; GLint viewport[4] {}; GLint colorMask[4] {}; - GLboolean flags[6] {}; + GLboolean flags[4] {}; GLboolean attribFlags[3] {}; GlStateGuard(); ~GlStateGuard(); @@ -100,8 +99,6 @@ void ignore_event(Args...) { void dispatch_events(int timeoutMs); int keycode_from_keysym(xkb_keysym_t sym); -extern bool serverDecorations; - void zxdg_decoration_configure( void*, zxdg_toplevel_decoration_v1*, uint32_t mode ); diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp index 90a44d74b..2321fdfe5 100644 --- a/src/window/wayland/WaylandDecorations.cpp +++ b/src/window/wayland/WaylandDecorations.cpp @@ -55,22 +55,27 @@ namespace { } } + bool layoutUnavailable = false; + bool read_button_layout( std::vector& left, std::vector& right ) { - FILE* pipe = popen( - "gsettings get org.gnome.desktop.wm.preferences button-layout" - " 2>/dev/null", - "r" - ); + if (layoutUnavailable) { + return false; + } + const std::string command = std::string("gsettings get ") + + LAYOUT_SCHEMA + " " + LAYOUT_KEY + " 2>/dev/null"; + FILE* pipe = popen(command.c_str(), "r"); if (pipe == nullptr) { + layoutUnavailable = true; return false; } char buffer[256] {}; const char* line = fgets(buffer, sizeof(buffer), pipe); const int status = pclose(pipe); if (line == nullptr || status != 0) { + layoutUnavailable = true; return false; } split_layout(std::string(buffer), left, right); @@ -190,7 +195,11 @@ int WaylandWindow::getDecorationHoveredButton() const { } void WaylandWindow::enableOwnDecorations() { + if (barEnabled) { + return; + } barEnabled = true; + resize(size.x, size.y); setShouldRefresh(); } @@ -222,10 +231,13 @@ int WaylandWindow::barButtonAt(double x, double y) const { } uint32_t WaylandWindow::barEdgeAt(double x, double y) const { + if (!barVisible()) { + return 0; + } if (barButtonAt(x, y) >= 0) { return 0; } - const bool inBar = barVisible() && y >= 0.0 && y < barHeight(); + const bool inBar = y >= 0.0 && y < barHeight(); uint32_t edges = 0; if (y < BAR_EDGE) { edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP; @@ -276,6 +288,9 @@ CursorShape WaylandWindow::edgeCursor(uint32_t edges) { } uint32_t WaylandWindow::pointerEdges() const { + if (!barVisible()) { + return 0; + } const int margin = marginSize(); uint32_t edges = 0; if (margin > 0) { @@ -399,9 +414,11 @@ bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) { } bool WaylandWindow::handleBarScroll() const { + if (!barVisible()) { + return false; + } const double y = contentY(pointerY); - return (barVisible() && y >= 0.0 && y < barHeight()) || - pointerEdges() != 0; + return (y >= 0.0 && y < barHeight()) || pointerEdges() != 0; } void WaylandWindow::onPointerLeave() { diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp index 25823cd9e..a5d76ca1d 100644 --- a/src/window/wayland/WaylandInit.cpp +++ b/src/window/wayland/WaylandInit.cpp @@ -6,18 +6,42 @@ #include "graphics/core/Texture.hpp" #include +WaylandInput::~WaylandInput() { + if (clipboardFd >= 0) { + close(clipboardFd); + clipboardFd = -1; + } + if (state.xkbContext) { + xkb_context_unref(state.xkbContext); + state.xkbContext = nullptr; + } + if (input == this) { + input = nullptr; + } +} + std::tuple, std::unique_ptr> wayland_window_initialize(DisplaySettings* settings, std::string title) { - state.display = wl_display_connect(nullptr); - if (state.display == nullptr) { - waylandLogger.error() << "could not connect to the Wayland display"; + std::unique_ptr inputPtr; + std::unique_ptr windowPtr; + const auto fail = [&] ( + const std::string& message + ) -> std::tuple, std::unique_ptr> { + waylandLogger.error() << message; window = nullptr; input = nullptr; + windowPtr.reset(); + inputPtr.reset(); if (state.display != nullptr) { wl_display_disconnect(state.display); state.display = nullptr; } return {nullptr, nullptr}; + }; + + state.display = wl_display_connect(nullptr); + if (state.display == nullptr) { + return fail("could not connect to the Wayland display"); } state.registry = wl_display_get_registry(state.display); static const wl_registry_listener registryListener = [] { @@ -30,23 +54,14 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { wl_registry_add_listener(state.registry, ®istryListener, nullptr); wl_display_roundtrip(state.display); if (state.compositor == nullptr || state.wmBase == nullptr) { - waylandLogger.error() << "the compositor does not provide xdg-shell"; - wl_display_disconnect(state.display); - state.display = nullptr; - window = nullptr; - input = nullptr; - if (state.display != nullptr) { - wl_display_disconnect(state.display); - state.display = nullptr; - } - return {nullptr, nullptr}; + return fail("the compositor does not provide xdg-shell"); } state.surface = wl_compositor_create_surface(state.compositor); - auto inputPtr = std::make_unique(); + inputPtr = std::make_unique(); input = inputPtr.get(); - auto windowPtr = std::make_unique( + windowPtr = std::make_unique( *inputPtr, settings, settings->width.get(), settings->height.get() ); window = windowPtr.get(); @@ -66,7 +81,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { return value; }(); - wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); + wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); } { @@ -116,14 +131,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { while (!window->configured) { if (wl_display_dispatch(state.display) == -1) { - waylandLogger.error() << "the Wayland connection was lost"; - window = nullptr; - input = nullptr; - if (state.display != nullptr) { - wl_display_disconnect(state.display); - state.display = nullptr; - } - return {nullptr, nullptr}; + return fail("the Wayland connection was lost"); } } @@ -132,14 +140,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { ); if (window->eglDisplay == EGL_NO_DISPLAY || eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { - waylandLogger.error() << "could not initialize EGL"; - window = nullptr; - input = nullptr; - if (state.display != nullptr) { - wl_display_disconnect(state.display); - state.display = nullptr; - } - return {nullptr, nullptr}; + return fail("could not initialize EGL"); } eglBindAPI(EGL_OPENGL_API); @@ -179,14 +180,7 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { waylandLogger.warning() << "no EGL config with alpha, the drop shadow is off"; if (!chooseConfig(0, requestedSamples) && !chooseConfig(0, 0)) { - waylandLogger.error() << "no suitable EGL config"; - window = nullptr; - input = nullptr; - if (state.display != nullptr) { - wl_display_disconnect(state.display); - state.display = nullptr; - } - return {nullptr, nullptr}; + return fail("no suitable EGL config"); } window->shadowEnabled = false; } @@ -214,29 +208,17 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { window->eglDisplay, window->eglSurface, window->eglSurface, window->eglContext ) == EGL_FALSE) { - waylandLogger.error() << "could not create the OpenGL context"; - window = nullptr; - input = nullptr; - if (state.display != nullptr) { - wl_display_disconnect(state.display); - state.display = nullptr; - } - return {nullptr, nullptr}; + return fail("could not create the OpenGL context"); } eglSwapInterval(window->eglDisplay, 0); glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { - waylandLogger.error() << "failed to initialize GLEW:\n" - << glewGetErrorString(glewError); - window = nullptr; - input = nullptr; - if (state.display != nullptr) { - wl_display_disconnect(state.display); - state.display = nullptr; - } - return {nullptr, nullptr}; + return fail( + std::string("failed to initialize GLEW:\n") + + reinterpret_cast(glewGetErrorString(glewError)) + ); } window->initStretchRenderer(); @@ -259,6 +241,10 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { << reinterpret_cast(glGetString(GL_RENDERER)); waylandLogger.info() << "windowing platform: Wayland (native)"; + // The first configure may arrive with a zero size, so the geometry is + // published once the surface exists. + window->updateWindowGeometry(); + return {std::move(windowPtr), std::move(inputPtr)}; } diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp index bf9071a30..d3a832838 100644 --- a/src/window/wayland/WaylandInput.hpp +++ b/src/window/wayland/WaylandInput.hpp @@ -10,10 +10,12 @@ #include #include +#include #include #include #include #include +#include #include /// @brief Offset between the evdev keycode and the xkb one @@ -21,6 +23,8 @@ static constexpr uint32_t XKB_KEYCODE_OFFSET = 8; class WaylandInput : public BaseInput { public: + ~WaylandInput() override; + void pollEvents(bool waitForRefresh) override; const char* getClipboardText() const override { @@ -161,7 +165,8 @@ public: /// @brief Release every pressed key, e.g. when the keyboard focus is lost void releasePressedKeys() { - const auto keys = pressedKeys; + const auto keys = heldKeys; + heldKeys.clear(); for (auto key : keys) { onKeyCallback(static_cast(key), false); } @@ -190,6 +195,11 @@ public: int keycode = keycode_from_keysym(syms[0]); if (keycode != 0) { onKeyCallback(keycode, pressed); + if (pressed) { + heldKeys.insert(static_cast(keycode)); + } else { + heldKeys.erase(static_cast(keycode)); + } } if (pressed) { repeatKeycode = code; @@ -344,13 +354,45 @@ private: listener.send = [] ( void*, wl_data_source*, const char*, int32_t fd ) { - if (input) { - const std::string& text = input->sourceText; - if (!text.empty() && - write(fd, text.data(), text.size()) < 0) { - waylandLogger.warning() - << "could not write to the clipboard"; + if (input == nullptr) { + close(fd); + return; + } + const std::string& text = input->sourceText; + const int flags = fcntl(fd, F_GETFL, 0); + if (flags != -1) { + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + // The reader may be slow, so the frame loop is not allowed to + // block on the pipe: partial writes and EAGAIN are retried + // only for a bounded time. + const double deadline = waylandNow() + 0.1; + size_t offset = 0; + while (offset < text.size()) { + const ssize_t written = write( + fd, text.data() + offset, text.size() - offset + ); + if (written > 0) { + offset += static_cast(written); + continue; } + if (written < 0 && errno == EINTR) { + continue; + } + if (written < 0 && + (errno == EAGAIN || errno == EWOULDBLOCK)) { + if (waylandNow() < deadline) { + pollfd descriptor {fd, POLLOUT, 0}; + if (poll(&descriptor, 1, 10) > 0) { + continue; + } + } + } + break; + } + if (offset < text.size()) { + waylandLogger.warning() + << "could not write to the clipboard"; } close(fd); }; @@ -386,6 +428,8 @@ private: CursorShape cursor = CursorShape::ARROW; std::optional overrideCursor; + // the keys really held: BaseInput::pressedKeys is never erased + std::unordered_set heldKeys; xkb_keycode_t repeatKeycode = 0; double repeatTime = 0.0; double lastRepeat = 0.0; diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index c30a9e0a2..2e204b34c 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -38,6 +38,7 @@ static void pointer_motion( const double x = wl_fixed_to_double(sx); const double y = wl_fixed_to_double(sy); if (window && window->handleBarMotion(x, y)) { + window->setShouldRefresh(); return; } if (input) { @@ -371,7 +372,8 @@ void registry_global_remove(void*, wl_registry*, uint32_t) { void zxdg_decoration_configure( void*, zxdg_toplevel_decoration_v1*, uint32_t mode ) { - serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; + const bool serverDecorations = + mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; if (window != nullptr) { if (serverDecorations) { window->disableOwnDecorations(); diff --git a/src/window/wayland/WaylandSettings.cpp b/src/window/wayland/WaylandSettings.cpp index a36070220..201b4aab9 100644 --- a/src/window/wayland/WaylandSettings.cpp +++ b/src/window/wayland/WaylandSettings.cpp @@ -44,6 +44,7 @@ namespace { struct SettingsWatcher::Impl { #ifdef VOXELCORE_SDBUS sd_bus* bus = nullptr; + std::string changedSchema; std::string changedKey; std::string changedValue; bool changed = false; @@ -58,7 +59,8 @@ struct SettingsWatcher::Impl { return 0; } const std::string value = readVariant(message); - if (key != nullptr && !value.empty()) { + if (schema != nullptr && key != nullptr && !value.empty()) { + self->changedSchema = schema; self->changedKey = key; self->changedValue = value; self->changed = true; @@ -86,10 +88,14 @@ bool SettingsWatcher::open() { impl->bus = nullptr; return false; } - sd_bus_match_signal( - impl->bus, nullptr, nullptr, PORTAL_PATH, PORTAL_INTERFACE, - "SettingChanged", &Impl::onSettingChanged, impl - ); + if (sd_bus_match_signal( + impl->bus, nullptr, nullptr, PORTAL_PATH, PORTAL_INTERFACE, + "SettingChanged", &Impl::onSettingChanged, impl + ) < 0) { + sd_bus_flush_close_unref(impl->bus); + impl->bus = nullptr; + return false; + } return true; #else return false; @@ -163,10 +169,17 @@ bool SettingsWatcher::poll( message = nullptr; } } - if (!impl->changed || impl->changedKey != key) { + if (result < 0) { + close(); + return false; + } + if (!impl->changed) { return false; } impl->changed = false; + if (impl->changedSchema != schema || impl->changedKey != key) { + return false; + } value = impl->changedValue; return true; #else diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index 5f38dabc6..17c46a8ee 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -1,7 +1,6 @@ #include "window/wayland/WaylandWindow.hpp" #include "settings.hpp" -#include "graphics/core/Texture.hpp" #include "util/platform.hpp" WaylandWindow::WaylandWindow( @@ -100,6 +99,14 @@ WaylandWindow::~WaylandWindow() { xkb_keymap_unref(state.xkbKeymap); state.xkbKeymap = nullptr; } + if (state.xkbContext) { + xkb_context_unref(state.xkbContext); + state.xkbContext = nullptr; + } + if (state.display) { + wl_display_disconnect(state.display); + } + state = WaylandState {}; } double WaylandWindow::time() { @@ -118,13 +125,11 @@ void WaylandWindow::swapBuffers() { cacheContent(); } } else if (resizing) { - // While the pointer drags the window border the content is only - // redrawn when the engine asked for it, otherwise the last frame is - // stretched into the new size. + // While the pointer drags the window border the content is redrawn + // only when the engine asked for it, otherwise composeFrame() reuses + // the cached frame. if (renderPending) { cacheContent(); - } else if (marginSize() == 0) { - drawStretched(); } } else if (frameRendered) { cacheContent(); @@ -291,7 +296,7 @@ int WaylandWindow::marginSize() const { } bool WaylandWindow::compactBar() const { - return settings != nullptr && settings->compactWindowBar.get(); + return settings->compactWindowBar.get(); } int WaylandWindow::barHeight() const { @@ -299,13 +304,10 @@ int WaylandWindow::barHeight() const { } bool WaylandWindow::liveResizeEnabled() const { - return settings == nullptr || settings->liveResize.get(); + return settings->liveResize.get(); } void WaylandWindow::updateSettings() { - if (settings == nullptr) { - return; - } const bool compactBar = settings->compactWindowBar.get(); if (compactBar != compactBarSetting) { compactBarSetting = compactBar; @@ -342,8 +344,8 @@ void WaylandWindow::resize(int width, int height) { if (eglWindow) { const auto surface = surfaceSize(); wl_egl_window_resize(eglWindow, surface.x, surface.y, 0, 0); + glViewport(0, 0, width, height); } - glViewport(0, 0, width, height); updateWindowGeometry(); if (Window::mode == WindowMode::WINDOWED && !maximized) { settings->width.set(width); @@ -359,6 +361,7 @@ void WaylandWindow::onConfigure( pendingWidth = width; pendingHeight = height; stateMaximized = false; + stateFullscreen = false; stateSuspended = false; stateActivated = false; const auto* values = static_cast(states->data); @@ -367,6 +370,9 @@ void WaylandWindow::onConfigure( case XDG_TOPLEVEL_STATE_MAXIMIZED: stateMaximized = true; break; + case XDG_TOPLEVEL_STATE_FULLSCREEN: + stateFullscreen = true; + break; case XDG_TOPLEVEL_STATE_SUSPENDED: stateSuspended = true; break; @@ -379,6 +385,7 @@ void WaylandWindow::onConfigure( void WaylandWindow::applyConfigure() { maximized = stateMaximized; + fullscreen = stateFullscreen; suspended = stateSuspended; if (pendingWidth > 0 && pendingHeight > 0) { if (!initialSizeApplied && Window::mode == WindowMode::WINDOWED && @@ -531,7 +538,6 @@ void WaylandWindow::initShadowRenderer() { for (int i = 0; names[i] != nullptr; i++) { shadowUniforms[i] = glGetUniformLocation(shadowProgram, names[i]); } - } namespace { @@ -680,29 +686,6 @@ void WaylandWindow::cacheContent() { lastCacheTime = now(); } -void WaylandWindow::drawStretched() { - GlStateGuard state; - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glViewport(0, 0, size.x, size.y); - glDisable(GL_DEPTH_TEST); - glDisable(GL_BLEND); - glDisable(GL_CULL_FACE); - glDisable(GL_SCISSOR_TEST); - if (stretchProgram == 0 || cacheWidth == 0) { - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - return; - } - glUseProgram(stretchProgram); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, cacheTexture); - glUniform1i(stretchTextureUniform, 0); - glBindVertexArray(stretchVao); - glDrawArrays(GL_TRIANGLES, 0, 3); - glBindVertexArray(0); - glUseProgram(0); -} - void WaylandWindow::onFrameDone() { frameCallback = nullptr; frameDone = true; diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 495236a0c..5b4fb86c2 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -15,7 +15,7 @@ #include class WaylandWindow : public Window { - public: +public: WaylandInput& input; DisplaySettings* settings; EGLDisplay eglDisplay = EGL_NO_DISPLAY; @@ -25,6 +25,7 @@ class WaylandWindow : public Window { int32_t pendingWidth = 0; int32_t pendingHeight = 0; bool stateMaximized = false; + bool stateFullscreen = false; bool stateSuspended = false; bool stateActivated = true; bool configured = false; @@ -70,6 +71,10 @@ class WaylandWindow : public Window { double frameCost = 0.0; double cacheTimeout = 0.5; bool resizing = false; + // renderPending asks the engine for a new frame after a resize pause, + // presentPending marks a buffer the compositor has not taken yet and + // frameDone a frame callback that already fired. frameOnCallback says + // that pacing follows those callbacks rather than the wall clock. bool renderPending = true; bool presentPending = true; double lastPresent = 0.0; @@ -173,7 +178,6 @@ class WaylandWindow : public Window { void makeContentOpaque(int x, int y, int width, int height); - const std::vector& getDecorationButtons() const override; @@ -197,11 +201,10 @@ class WaylandWindow : public Window { void initStretchRenderer(); void resizeCache(int width, int height); void cacheContent(); - void drawStretched(); void enableOwnDecorations(); void disableOwnDecorations(); bool barVisible() const; - int barButtonAt(double x, double y) const; + int barButtonAt(double x, double y) const; uint32_t barEdgeAt(double x, double y) const; static CursorShape edgeCursor(uint32_t edges); uint32_t pointerEdges() const; From fbedfad478d89ed8f6a0ef76f39cea1d11692e14 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sun, 11 Oct 2026 20:06:11 +0300 Subject: [PATCH 32/35] Fix the issues found while reviewing the engine frame Use util::str2wstr_utf8 for the window title instead of the deprecated codecvt conversion, choose the bar control icon with a switch, and keep the frontend layout in sync when a frame is drawn from the refresh callback the platform calls while it blocks the main loop. The frame forgets its interaction state when the window mode changes or the cursor gets locked, a bar click that only moved the window is no longer a double click, and one frame per size is drawn per resize. The tooltips of the two window settings were only present in the Russian locale and under a key the settings page never asks for: they are named display..tooltip now and translated in both locales. The version label of the debug build moves below the bar that covers the menu screen. --- res/texts/en_US.txt | 2 + res/texts/ru_RU.txt | 4 +- src/engine/WindowBar.cpp | 43 +++--- src/engine/WindowControl.cpp | 6 +- src/frontend/menu.cpp | 6 +- src/frontend/screens/MenuScreen.hpp | 1 + src/window/Window.hpp | 13 +- src/window/detail/FrameLayout.hpp | 8 +- src/window/detail/FrameOperations.cpp | 211 +++++++++++++------------- src/window/detail/GLFWWindow.cpp | 32 +++- 10 files changed, 173 insertions(+), 153 deletions(-) diff --git a/res/texts/en_US.txt b/res/texts/en_US.txt index 294758a7e..4a566ba6b 100644 --- a/res/texts/en_US.txt +++ b/res/texts/en_US.txt @@ -25,6 +25,8 @@ graphics.backlight.tooltip=Backlight to prevent total darkness graphics.dense-render.tooltip=Enables transparency in blocks like leaves graphics.soft-lighting.tooltip=Enables blocks soft lighting graphics.advanced-render.tooltip=Use graphics pipeline supporting advanced effects like shadows, SSAO +display.compact-window-bar.tooltip=Window bar 24 px high instead of 48 px +display.live-resize.tooltip=Redraw the window while it is resized (off: show the last frame) # settings settings.Controls Search Mode=Search by attached button name diff --git a/res/texts/ru_RU.txt b/res/texts/ru_RU.txt index efcd0ab96..f1cc9fc41 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -120,8 +120,8 @@ settings.Acoustic effects=Акустические эффекты settings.Microphone access=Доступ к микрофону settings.Narrow Window Bar=Узкая шапка окна settings.Live Window Resize=Живой ресайз окна -settings.display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px -settings.display.live-resize.tooltip=Перерисовывать окно при изменении размера (выключено — показывать последний кадр) +display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px +display.live-resize.tooltip=Перерисовывать окно при изменении размера (выключено — показывать последний кадр) # Управление chunks.reload=Перезагрузить Чанки diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp index 68fdeabd8..b6097a60c 100644 --- a/src/engine/WindowBar.cpp +++ b/src/engine/WindowBar.cpp @@ -11,27 +11,15 @@ #include "graphics/ui/GUI.hpp" #include "window/Window.hpp" #include "assets/Assets.hpp" +#include "util/stringutil.hpp" #include #include -#include -#include - -namespace { - std::wstring to_wide(const std::string& text) { - std::wstring_convert> converter; - return converter.from_bytes(text); - } - - const std::string BAR_FONT = FONT_DEFAULT; -} /// @brief Draws the window bar the backend cannot draw itself. /// -/// The bar lives in window coordinates while the GUI container is shifted -/// down by its height in game, so the GUI camera cannot be reused here: the -/// bar sets its own viewport and projection. It borrows the GUI batch only -/// because the ui shader it needs is the one the GUI already loads. +/// The bar lives in window coordinates, so it sets the shader and projection +/// itself instead of depending on the state the GUI left behind. void draw_window_bar(Engine& engine) { auto& window = engine.getWindow(); const int height = window.getDecorationHeight(); @@ -39,7 +27,7 @@ void draw_window_bar(Engine& engine) { return; } auto* batch = engine.getGUI().getBatch2D(); - auto font = engine.requireAssets().getShared(BAR_FONT); + auto font = engine.requireAssets().getShared(FONT_DEFAULT); const auto size = window.getSize(); const float barHeight = static_cast(height); @@ -80,7 +68,7 @@ void draw_window_bar(Engine& engine) { } // the bar and its controls do not need the font, only the title does if (font != nullptr) { - const std::wstring title = to_wide(window.getTitle()); + const std::wstring title = util::str2wstr_utf8(window.getTitle()); const float available = std::max(0.0f, titleRight - titleLeft); size_t titleLength = title.size(); while (titleLength > 0 && @@ -124,13 +112,20 @@ void draw_window_bar(Engine& engine) { } const float ink = isHovered ? 1.0f : 0.8f; batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink)); - const char* iconName = - item.button == DecorationButton::CLOSE - ? "gui/cross" - : item.button == DecorationButton::MINIMIZE - ? "gui/minimize_w" - : window.isMaximized() ? "gui/restore_w" - : "gui/maximize_w"; + const char* iconName = nullptr; + switch (item.button) { + case DecorationButton::CLOSE: + iconName = "gui/cross"; + break; + case DecorationButton::MINIMIZE: + iconName = "gui/minimize_w"; + break; + case DecorationButton::MAXIMIZE: + default: + iconName = window.isMaximized() ? "gui/restore_w" + : "gui/maximize_w"; + break; + } auto icon = engine.requireAssets().getShared(iconName); if (icon != nullptr) { const float iconSize = std::min( diff --git a/src/engine/WindowControl.cpp b/src/engine/WindowControl.cpp index add00ba1a..eb70b777b 100644 --- a/src/engine/WindowControl.cpp +++ b/src/engine/WindowControl.cpp @@ -66,10 +66,10 @@ WindowControl::Result WindowControl::initialize() { } } - // Windows blocks the main loop inside its own modal loop while the user - // drags a window border, and asks for a repaint instead: drawing a frame - // from there is what keeps the content alive during such a resize. + // The platform blocks the main loop while it resizes the window, so the + // frame is drawn from here, with the frontend layout updated first. window->setRefreshHandler([this] { + engine.updateFrontend(); engine.renderFrame(); engine.getWindow().swapBuffers(); }); diff --git a/src/frontend/menu.cpp b/src/frontend/menu.cpp index ab06b42dc..3e91551e0 100644 --- a/src/frontend/menu.cpp +++ b/src/frontend/menu.cpp @@ -17,6 +17,7 @@ #include "screens/MenuScreen.hpp" #include "settings.hpp" #include "util/stringutil.hpp" +#include "window/Window.hpp" #include "assets/assetload_funcs.hpp" #include "content/ContentPack.hpp" @@ -24,11 +25,12 @@ using namespace gui; void menus::create_version_label(gui::GUI& gui) { auto text = ENGINE_VERSION_STRING + " debug build"; + // the menu screen keeps no inset, the bar covers the top of it + const int top = gui.getEngine().getWindow().getDecorationHeight() + 4; gui.add(guiutil::create( gui, "" + "margin='4," + std::to_string(top) + ",4,4'>" + text + "" )); } diff --git a/src/frontend/screens/MenuScreen.hpp b/src/frontend/screens/MenuScreen.hpp index 7f8f02ad5..ba91f5b22 100644 --- a/src/frontend/screens/MenuScreen.hpp +++ b/src/frontend/screens/MenuScreen.hpp @@ -15,6 +15,7 @@ public: void onOpen() override; + // the bar covers the top getDecorationHeight() pixels, no widgets there int getContentInset(const Window&) const override { return 0; } diff --git a/src/window/Window.hpp b/src/window/Window.hpp index 7fac8dff3..3e8b61e0a 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -17,7 +17,7 @@ struct DisplaySettings; enum class DecorationButton { CLOSE, MINIMIZE, - MAXIMIZE, + MAXIMIZE }; struct DecorationButtonLayout { @@ -73,10 +73,6 @@ public: return empty; } - /// @brief Whether the engine draws the window frame itself here - /// - /// The bar height and its buttons only mean something when it does, and - /// the window settings are only shown where that is the case. /// @brief Handler the windowing system calls when it wants a repaint /// /// Windows runs a modal loop while the user drags a window border and the @@ -92,6 +88,10 @@ public: return refreshHandler; } + /// @brief Whether the engine draws the window frame itself here + /// + /// The bar height and its buttons only mean something when it does, and + /// the window settings are only shown where that is the case. virtual bool hasEngineFrame() const { return false; } @@ -106,7 +106,8 @@ public: return -1; } - virtual const std::vector& getDecorationButtons() const { + virtual const std::vector& getDecorationButtons() + const { static const std::vector empty; return empty; } diff --git a/src/window/detail/FrameLayout.hpp b/src/window/detail/FrameLayout.hpp index ae3394457..42542eac3 100644 --- a/src/window/detail/FrameLayout.hpp +++ b/src/window/detail/FrameLayout.hpp @@ -2,10 +2,10 @@ /// @brief Geometry of the window frame the engine draws itself. /// -/// Wayland has its own implementation because it also talks to the compositor, -/// this one is used by the backends that decorate their window by themselves. -/// It deliberately depends on nothing but the standard library, so the layout -/// and the hit testing can be checked without a window. +/// Wayland has its own implementation because it also talks to the compositor. +/// This one is used by the GLFW backends, on an undecorated window, and +/// depends on nothing but the standard library, so the layout and the hit +/// testing can be checked without a window. namespace frame { constexpr int BAR_HEIGHT = 48; constexpr int BAR_HEIGHT_COMPACT = 24; diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp index 6c5ebff46..6eed04f7f 100644 --- a/src/window/detail/FrameOperations.cpp +++ b/src/window/detail/FrameOperations.cpp @@ -1,6 +1,107 @@ #include "window/detail/FrameOperations.hpp" -#if defined(VOXEL_X11_FRAME) +#if defined(_WIN32) +#define NOMINMAX +#include +#include + +#include + +#define GLFW_EXPOSE_NATIVE_WIN32 +#include + +namespace { + WNDPROC original_window_proc = nullptr; + frame::Hit (*hit_test_callback)(void*, int, int) = nullptr; + void* hit_test_userdata = nullptr; + FrameRefresh refresh_callback = nullptr; + void* refresh_userdata = nullptr; + + /// @brief Keeps the window style the engine frame relies on + /// + /// GLFW rewrites the style on every window mode change, and a lost thick + /// frame takes the native resize border and the window snapping with it. + void apply_engine_style(HWND hwnd) { + const LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); + const LONG_PTR wanted = + (style | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | + WS_SYSMENU) & + ~WS_CAPTION; + if (wanted != style) { + SetWindowLongPtr(hwnd, GWL_STYLE, wanted); + } + } + + LRESULT CALLBACK frame_window_proc( + HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam + ) { + switch (message) { + case WM_NCCALCSIZE: + // the caption is gone, the whole window is the client area + if (wparam == TRUE) { + return 0; + } + break; + case WM_NCPAINT: + // the frame is not drawn by us + return 0; + case WM_NCACTIVATE: + // and it is not repainted when the window is activated + return TRUE; + case WM_SIZE: { + // Windows runs its own modal loop while a border is dragged + // and never sends WM_PAINT there, so WM_SIZE is the only + // place to draw a frame from during such a resize. + const LRESULT result = CallWindowProc( + original_window_proc, hwnd, message, wparam, lparam + ); + if (refresh_callback != nullptr) { + refresh_callback(refresh_userdata); + } + return result; + } + case WM_NCHITTEST: { + // the style may have been rewritten since the last setup + apply_engine_style(hwnd); + if (hit_test_callback == nullptr) { + break; + } + POINT point {GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}; + ScreenToClient(hwnd, &point); + const frame::Hit hit = + hit_test_callback(hit_test_userdata, point.x, point.y); + if (hit.caption) { + return HTCAPTION; + } + switch (hit.edges) { + case frame::EDGE_TOP | frame::EDGE_LEFT: + return HTTOPLEFT; + case frame::EDGE_TOP: + return HTTOP; + case frame::EDGE_TOP | frame::EDGE_RIGHT: + return HTTOPRIGHT; + case frame::EDGE_RIGHT: + return HTRIGHT; + case frame::EDGE_BOTTOM | frame::EDGE_RIGHT: + return HTBOTTOMRIGHT; + case frame::EDGE_BOTTOM: + return HTBOTTOM; + case frame::EDGE_BOTTOM | frame::EDGE_LEFT: + return HTBOTTOMLEFT; + case frame::EDGE_LEFT: + return HTLEFT; + default: + return HTCLIENT; + } + } + } + return CallWindowProc( + original_window_proc, hwnd, message, wparam, lparam + ); + } +} + +#elif defined(VOXEL_X11_FRAME) #include #include #include @@ -158,111 +259,6 @@ namespace { return true; } } - -#elif defined(_WIN32) -#define NOMINMAX -#include -#include - -#include - -#define GLFW_EXPOSE_NATIVE_WIN32 -#include - -#include "debug/Logger.hpp" - -static debug::Logger frame_logger("window-frame"); - -namespace { - WNDPROC original_window_proc = nullptr; - frame::Hit (*hit_test_callback)(void*, int, int) = nullptr; - void* hit_test_userdata = nullptr; - FrameRefresh refresh_callback = nullptr; - void* refresh_userdata = nullptr; - - /// @brief Keeps the window style the engine frame relies on - /// - /// GLFW rewrites the style on every window mode change, and a lost thick - /// frame takes the native resize border and the window snapping with it. - void apply_engine_style(HWND hwnd) { - const LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); - const LONG_PTR wanted = - (style | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | - WS_SYSMENU) & - ~WS_CAPTION; - if (wanted != style) { - SetWindowLongPtr(hwnd, GWL_STYLE, wanted); - } - } - - LRESULT CALLBACK frame_window_proc( - HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam - ) { - switch (message) { - case WM_NCCALCSIZE: - // the caption is gone, the whole window is the client area - if (wparam == TRUE) { - return 0; - } - break; - case WM_NCPAINT: - // the frame is not drawn by us - return 0; - case WM_NCACTIVATE: - // and it is not repainted when the window is activated - return TRUE; - case WM_SIZE: { - // Windows runs its own modal loop while a border is dragged - // and never sends WM_PAINT there, so WM_SIZE is the only - // place to draw a frame from during such a resize. - const LRESULT result = CallWindowProc( - original_window_proc, hwnd, message, wparam, lparam - ); - if (refresh_callback != nullptr) { - refresh_callback(refresh_userdata); - } - return result; - } - case WM_NCHITTEST: { - // the style may have been rewritten since the last setup - apply_engine_style(hwnd); - if (hit_test_callback == nullptr) { - break; - } - POINT point {GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}; - ScreenToClient(hwnd, &point); - const frame::Hit hit = - hit_test_callback(hit_test_userdata, point.x, point.y); - if (hit.caption) { - return HTCAPTION; - } - switch (hit.edges) { - case frame::EDGE_TOP | frame::EDGE_LEFT: - return HTTOPLEFT; - case frame::EDGE_TOP: - return HTTOP; - case frame::EDGE_TOP | frame::EDGE_RIGHT: - return HTTOPRIGHT; - case frame::EDGE_RIGHT: - return HTRIGHT; - case frame::EDGE_BOTTOM | frame::EDGE_RIGHT: - return HTBOTTOMRIGHT; - case frame::EDGE_BOTTOM: - return HTBOTTOM; - case frame::EDGE_BOTTOM | frame::EDGE_LEFT: - return HTBOTTOMLEFT; - case frame::EDGE_LEFT: - return HTLEFT; - default: - return HTCLIENT; - } - } - } - return CallWindowProc( - original_window_proc, hwnd, message, wparam, lparam - ); - } -} #endif bool frame_has_native_operations() { @@ -321,9 +317,6 @@ void frame_setup_native( SetWindowLongPtr( hwnd, GWLP_WNDPROC, reinterpret_cast(frame_window_proc) ); - frame_logger.info() << "window frame: subclass installed"; - } else { - frame_logger.info() << "window frame: subclass was ours"; } SetWindowPos( hwnd, diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 91e684dd6..db735d7b1 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -379,7 +379,7 @@ public: /// @brief Whether the window is redrawn while it is being resized bool isLiveResizeEnabled() const { - return settings == nullptr || settings->liveResize.get(); + return settings->liveResize.get(); } /// @brief Draws a frame for the windowing system @@ -388,14 +388,19 @@ public: /// loop inside it, so the only frames drawn during such a resize are the /// ones asked for from the message loop. void drawRefreshFrame() { - if (!isLiveResizeEnabled()) { + if (inRefreshCallback || !isLiveResizeEnabled()) { return; } const auto& refresh = getRefreshHandler(); if (!refresh) { return; } + // the system may ask twice for one resize + if (size == lastRefreshSize) { + return; + } inRefreshCallback = true; + lastRefreshSize = size; refresh(); inRefreshCallback = false; } @@ -445,6 +450,7 @@ public: /// @brief Turns a pointer move into hovering, dragging or resizing void handleFrameMotion(double x, double y) { if (input.isCursorLocked() || barHeight() <= 0) { + resetFrameInteraction(); hoveredButton = -1; frameCursorActive = false; return; @@ -494,12 +500,19 @@ public: ); if (hit.caption) { const double now = glfwGetTime(); - if (lastBarClick > 0.0 && now - lastBarClick < DOUBLE_CLICK_TIME) { + int windowX = 0, windowY = 0; + glfwGetWindowPos(window, &windowX, &windowY); + // a window manager drag moves the window, and it must not leave + // the previous click able to turn the next one into a double one + if (lastBarClick > 0.0 && now - lastBarClick < DOUBLE_CLICK_TIME && + windowX == lastBarClickX && windowY == lastBarClickY) { lastBarClick = 0.0; toggleMaximize(); return true; } lastBarClick = now; + lastBarClickX = windowX; + lastBarClickY = windowY; if (frame_start_move(window)) { return true; } @@ -555,6 +568,7 @@ public: void setMode(WindowMode mode) override { Window::mode = mode; + resetFrameInteraction(); GLFWmonitor* monitor = get_window_monitor(window); const GLFWvidmode* glfwMode = glfwGetVideoMode(monitor); @@ -671,6 +685,14 @@ private: ); } + /// @brief Drops the interaction the frame can no longer keep + void resetFrameInteraction() { + dragging = false; + resizeEdges = 0; + pressedButton = -1; + frameMoved = false; + } + void updateFrameHover(double x, double y) { const int height = barHeight(); frame::Rect rects[frame::MAX_BUTTONS]; @@ -854,6 +876,8 @@ private: double grabScreenX = 0.0; double grabScreenY = 0.0; double lastBarClick = 0.0; + int lastBarClickX = 0; + int lastBarClickY = 0; static constexpr double DOUBLE_CLICK_TIME = 0.4; static constexpr double MOVE_THRESHOLD = 4.0; static constexpr int MIN_WIDTH = 320; @@ -864,6 +888,8 @@ private: int posX = 0; int posY = 0; bool shouldRefresh = true; + /// @brief Size of the last frame drawn from the refresh callback + glm::ivec2 lastRefreshSize {0, 0}; }; static_assert(!std::is_abstract()); From 3a574ade8cac814be8289516e8dea1e0d05506d1 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sun, 11 Oct 2026 20:06:15 +0300 Subject: [PATCH 33/35] Keep the frames of the GUI inside the content area The engine draws the window bar on top of the GUI, so a frame as high as the window lost its top to the bar. GUI::act() limits such a frame to the content area and places it right below the bar; frames that are smaller than the window are not touched. --- src/graphics/ui/GUI.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/graphics/ui/GUI.cpp b/src/graphics/ui/GUI.cpp index 2786590cb..812eec4d4 100644 --- a/src/graphics/ui/GUI.cpp +++ b/src/graphics/ui/GUI.cpp @@ -243,10 +243,20 @@ void GUI::actFocused() { void GUI::act(float delta, const glm::uvec2& vp) { const uint inset = static_cast(viewportOffset); + const uint contentHeight = vp.y > inset ? vp.y - inset : vp.y; container->setPos({0.0f, static_cast(inset)}); - container->setSize({vp.x, vp.y > inset ? vp.y - inset : vp.y}); + container->setSize({vp.x, contentHeight}); for (auto& pair : frames) { - pair.second->act(delta); + auto& frame = *pair.second; + auto size = frame.getSize(); + // the bar covers the top of the window, so a frame as high as the + // window is limited to the content area + if (size.y > static_cast(contentHeight)) { + size.y = static_cast(contentHeight); + frame.setSize(size); + frame.setPos({0.0f, static_cast(inset)}); + } + frame.act(delta); } auto prevfocus = focus; From b6f6235249d92beed3d11c31a1d0184aec8775cf Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sun, 11 Oct 2026 20:06:19 +0300 Subject: [PATCH 34/35] Fix the issues found while reviewing the build files Install the Wayland development packages in both workflows and bundle the runtime libraries in the AppImage: the release build had no native Wayland backend at all, and the engine silently fell back to GLFW there. Build the window backends on every platform that is not Windows and not Apple, glob the wayland sources with CONFIGURE_DEPENDS, and report a missing Wayland dependency with the list of what is missing. Also drop the dead nested project() calls and the duplicate -no-pie option, make .dirIcon the file appimagetool expects, and describe the real Linux dependencies in the README. --- .github/workflows/appimage.yml | 3 ++- .github/workflows/cmake.yml | 3 ++- .gitignore | 3 +-- CMakeLists.txt | 4 ---- README.md | 11 +++++++---- dev/AppImageBuilder.yml | 4 ++++ dev/cmake/BuildAppdir.cmake | 5 ++++- src/CMakeLists.txt | 8 ++++---- src/window/detail/CMakeLists.txt | 4 +--- src/window/wayland/CMakeLists.txt | 27 +++++++++++++++++++++------ 10 files changed, 46 insertions(+), 26 deletions(-) diff --git a/.github/workflows/appimage.yml b/.github/workflows/appimage.yml index 7b53b3fbf..4955f1bdc 100644 --- a/.github/workflows/appimage.yml +++ b/.github/workflows/appimage.yml @@ -31,7 +31,8 @@ jobs: sudo apt-get update sudo apt-get install -y build-essential libglfw3-dev libglfw3 libglew-dev libglew2.2 \ libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev \ - libcurl4-openssl-dev libssl-dev libgtest-dev libfreetype6-dev cmake squashfs-tools valgrind + libcurl4-openssl-dev libssl-dev libgtest-dev libfreetype6-dev cmake squashfs-tools valgrind \ + libwayland-dev libxkbcommon-dev libegl1-mesa-dev libsystemd-dev # fix luajit paths sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a sudo ln -s /usr/include/luajit-2.1 /usr/include/lua diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 6956a1f3d..f9a55c816 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -39,7 +39,8 @@ jobs: # make && make install INSTALL_INC=/usr/include/lua run: | sudo apt-get update - sudo apt-get install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libgtest-dev libcurl4-openssl-dev libssl-dev libfreetype6-dev + # the Wayland backend is on by default on Linux (VOXELCORE_WAYLAND) + sudo apt-get install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libgtest-dev libcurl4-openssl-dev libssl-dev libfreetype6-dev libwayland-dev libxkbcommon-dev libegl1-mesa-dev libsystemd-dev # fix luajit paths sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua-5.1.a sudo ln -s /usr/include/luajit-2.1 /usr/include/lua diff --git a/.gitignore b/.gitignore index 4d0155832..0fc04afdb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,6 @@ Debug/src/**/*.d Debug/src/**/*.o -Debug/voxel_engine - /build /cmake-build-** /screenshots @@ -36,6 +34,7 @@ Debug/voxel_engine /Default/ AppDir appimage-build/ +*.AppImage* # macOS folder attributes *.DS_Store diff --git a/CMakeLists.txt b/CMakeLists.txt index a9ac24a1d..a91c908cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,8 +5,6 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -execute_process(COMMAND ${CMAKE_COMMAND} --version) - option(VOXELENGINE_BUILD_APPDIR "Pack linux build" OFF) option(VOXELENGINE_BUILD_TESTS "Build tests" OFF) @@ -36,8 +34,6 @@ endif() target_link_libraries(VoxelCore PRIVATE VoxelCoreSrc $<$:winmm>) -target_link_options(VoxelCore PRIVATE $<$:-no-pie>) - # Deploy res to build dir add_custom_command( TARGET VoxelCore diff --git a/README.md b/README.md index 41fcad58e..d45cdaef2 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ sudo make install ```sh su - -apt-get install libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel +apt-get install entt-devel libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel ``` #### Debian based distros @@ -58,9 +58,12 @@ sudo pacman -S glfw glew glm libpng libvorbis openal luajit curl freetype2 opens #### Wayland -On Linux the engine draws the window frame itself and needs `wayland-client`, -`wayland-egl`, `wayland-scanner`, `wayland-protocols`, `libxkbcommon` and EGL. -Build with `-DVOXELCORE_WAYLAND=OFF` to fall back to GLFW. +On Linux the engine draws the window frame itself and needs `libwayland-dev` +(with `libwayland-bin` for `wayland-scanner`), `libxkbcommon-dev` and +`libegl-dev`. The protocol XML descriptions are vendored in +`src/window/wayland/protocols`, so the `wayland-protocols` package is not used. +`libsystemd-dev` is optional and adds the window button layout read through +sd-bus. Build with `-DVOXELCORE_WAYLAND=OFF` to fall back to GLFW. ### Building engine with CMake diff --git a/dev/AppImageBuilder.yml b/dev/AppImageBuilder.yml index bed1dde47..79d2d29dc 100644 --- a/dev/AppImageBuilder.yml +++ b/dev/AppImageBuilder.yml @@ -32,6 +32,10 @@ AppDir: - libvorbisfile3 - libluajit-5.1-2 - libfreetype6 + - libwayland-client0 + - libwayland-cursor0 + - libwayland-egl1 + - libxkbcommon0 exclude: - hicolor-icon-theme - sound-theme-freedesktop diff --git a/dev/cmake/BuildAppdir.cmake b/dev/cmake/BuildAppdir.cmake index 7445d1016..b1016252a 100644 --- a/dev/cmake/BuildAppdir.cmake +++ b/dev/cmake/BuildAppdir.cmake @@ -6,7 +6,10 @@ file(MAKE_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/share/VoxelCore) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/res DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/share/VoxelCore) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.png DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/share/icons/hicolor/256x256) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.png DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir) -file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.png DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/.dirIcon) +# .dirIcon is the icon of the AppDir itself and has to be a file, not a directory +file(REMOVE_RECURSE ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/.dirIcon) +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.png + ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/.dirIcon COPYONLY) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.desktop DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/share/applications) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/dev/VoxelCore.desktop DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/AppDir/usr/lib) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 02a974cc1..4a3317b8d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -116,10 +116,10 @@ set(VOXEL_COMPILE_OPTIONS -Wduplicated-cond >) -# Everything the engine sources and their public headers include: the backends -# compile against the same surface, and a missing include directory shows up as -# a build failure only on the platforms that keep the library outside the -# default include path. +# The include directory and the window/render dependencies shared by the engine +# and the window backends: glfw, GLEW, OpenGL and glm. The remaining engine +# dependencies (luajit, EnTT, OpenAL, zlib and others) are linked to VoxelCoreSrc +# only, even though the public headers pull them in. add_library(VoxelCoreInterface INTERFACE) target_include_directories(VoxelCoreInterface INTERFACE diff --git a/src/window/detail/CMakeLists.txt b/src/window/detail/CMakeLists.txt index a309ad51a..de716ca02 100644 --- a/src/window/detail/CMakeLists.txt +++ b/src/window/detail/CMakeLists.txt @@ -1,5 +1,3 @@ -project(VoxelWindowBackends) - # Input state shared by the window backends. add_library(VoxelWindowBase STATIC BaseInput.cpp) @@ -17,7 +15,7 @@ target_link_libraries( # On X11 the window manager moves and resizes the window when the engine draws # the frame. A wayland-only build of GLFW does not answer, and the frame then # falls back to moving the window itself. -if(UNIX AND NOT APPLE) +if(NOT WIN32 AND NOT APPLE) find_package(X11) if(X11_FOUND) target_compile_definitions(VoxelGLFW PRIVATE VOXEL_X11_FRAME=1) diff --git a/src/window/wayland/CMakeLists.txt b/src/window/wayland/CMakeLists.txt index fe8a7b810..1ebbb7933 100644 --- a/src/window/wayland/CMakeLists.txt +++ b/src/window/wayland/CMakeLists.txt @@ -1,5 +1,3 @@ -project(VoxelWayland) - # The library is linked from the parent directory, so the imported targets of # its dependencies have to be visible outside of this directory too. function(voxel_wayland_pkg_config MODULE) @@ -32,9 +30,25 @@ function(voxel_add_wayland_backend) find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1) find_program(WAYLAND_SCANNER wayland-scanner) - if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND - OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER) - message(STATUS "Wayland backend is off: dependencies are not found") + set(wayland_missing) + if(NOT wayland-client_FOUND) + list(APPEND wayland_missing wayland-client) + endif() + if(NOT xkbcommon_FOUND) + list(APPEND wayland_missing xkbcommon) + endif() + if(NOT egl_FOUND) + list(APPEND wayland_missing egl) + endif() + if(NOT WAYLAND_EGL_LIBRARY) + list(APPEND wayland_missing wayland-egl) + endif() + if(NOT WAYLAND_SCANNER) + list(APPEND wayland_missing wayland-scanner) + endif() + if(wayland_missing) + list(JOIN wayland_missing ", " wayland_missing) + message(WARNING "Wayland backend is off: not found: ${wayland_missing}") return() endif() @@ -56,7 +70,8 @@ function(voxel_add_wayland_backend) # tablet is referenced by cursor-shape-v1 voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) - file(GLOB wayland_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) + file(GLOB wayland_sources CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) add_library(VoxelWayland STATIC ${wayland_sources} ${WAYLAND_SOURCES}) From 2c8fd6087012156108b4a60b7369e74aaf6b03e6 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Sun, 11 Oct 2026 22:04:20 +0300 Subject: [PATCH 35/35] Keep the windows frame free of the native frame leftovers Windows leaves a strip of the native frame behind when WM_NCCALCSIZE returns without correcting the rectangle it proposes, and that strip stays black because nothing paints it. The client area is now set to the window rectangle explicitly, the resize borders still come from WS_THICKFRAME and from the frame hit test. WM_SIZE also carries the new client size, which the platform may not have reported to the engine yet. The frame used to be drawn for the previous size and was then skipped by the one frame per size check, so the window seemed to change its size only after the drag was over. The size is passed to the refresh callback and applied before the frame is drawn. --- src/window/detail/FrameOperations.cpp | 29 ++++++++++++++++++++------- src/window/detail/FrameOperations.hpp | 4 +++- src/window/detail/GLFWWindow.cpp | 13 ++++++++++-- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/window/detail/FrameOperations.cpp b/src/window/detail/FrameOperations.cpp index 6eed04f7f..25755c7dd 100644 --- a/src/window/detail/FrameOperations.cpp +++ b/src/window/detail/FrameOperations.cpp @@ -36,12 +36,21 @@ namespace { HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam ) { switch (message) { - case WM_NCCALCSIZE: - // the caption is gone, the whole window is the client area - if (wparam == TRUE) { - return 0; + case WM_NCCALCSIZE: { + // The caption is gone and the engine draws the whole frame, + // so the client area has to be the window itself. The + // rectangle Windows proposes here keeps a strip of the native + // frame, and that strip stays black because nothing paints it. + if (lparam == 0) { + break; } - break; + RECT window {}; + if (!GetWindowRect(hwnd, &window)) { + break; + } + reinterpret_cast(lparam)->rgrc[0] = window; + return 0; + } case WM_NCPAINT: // the frame is not drawn by us return 0; @@ -51,12 +60,18 @@ namespace { case WM_SIZE: { // Windows runs its own modal loop while a border is dragged // and never sends WM_PAINT there, so WM_SIZE is the only - // place to draw a frame from during such a resize. + // place to draw a frame from during such a resize. It also + // carries the new client size, which the platform may not + // have reported to the engine yet. const LRESULT result = CallWindowProc( original_window_proc, hwnd, message, wparam, lparam ); if (refresh_callback != nullptr) { - refresh_callback(refresh_userdata); + refresh_callback( + refresh_userdata, + static_cast(LOWORD(lparam)), + static_cast(HIWORD(lparam)) + ); } return result; } diff --git a/src/window/detail/FrameOperations.hpp b/src/window/detail/FrameOperations.hpp index 9cb8ecc0b..625b665ed 100644 --- a/src/window/detail/FrameOperations.hpp +++ b/src/window/detail/FrameOperations.hpp @@ -22,7 +22,9 @@ bool frame_start_move(GLFWwindow* window); bool frame_start_resize(GLFWwindow* window, int edges); /// @brief Called when the windowing system wants the content redrawn -using FrameRefresh = void (*)(void*); +/// @param width new client width, 0 when the system does not know it +/// @param height new client height, 0 when the system does not know it +using FrameRefresh = void (*)(void*, int width, int height); /// @brief Hide the caption of the native frame, keeping the rest of it /// @param hitTest tells what the pointer is over diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index db735d7b1..f8b28fe41 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -405,8 +405,17 @@ public: inRefreshCallback = false; } - static void frame_refresh_thunk(void* userdata) { - static_cast(userdata)->drawRefreshFrame(); + static void frame_refresh_thunk(void* userdata, int width, int height) { + auto* self = static_cast(userdata); + // The platform reports the new size from its own message loop, where + // GLFW has not updated the window yet: without this the frame is + // drawn for the previous size and leaves an unpainted strip behind. + if (width > 0 && height > 0 && + self->getSize() != glm::ivec2(width, height)) { + self->setSize(width, height); + self->resetScissor(); + } + self->drawRefreshFrame(); } /// @brief Set while a frame is drawn from the refresh callback