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 8d93b56a4..7a093e1c3 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 afd39ca4b..d55f62cd7 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,6 @@ 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 @@ -59,6 +56,15 @@ 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 `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 ```sh 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/res/layouts/pages/settings_display.xml.lua b/res/layouts/pages/settings_display.xml.lua index a3941bf2a..b6eaa6fa4 100644 --- a/res/layouts/pages/settings_display.xml.lua +++ b/res/layouts/pages/settings_display.xml.lua @@ -66,6 +66,20 @@ function on_open() "", app.get_setting("display.window-mode")) ) + -- 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" + ) + 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") create_checkbox("camera.fov-effects", "Camera FOV Effects") 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/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 295d467af..f1cc9fc41 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -118,6 +118,10 @@ settings.microphone.None=Нет settings.Clouds quality=Качество облаков settings.Acoustic effects=Акустические эффекты settings.Microphone access=Доступ к микрофону +settings.Narrow Window Bar=Узкая шапка окна +settings.Live Window Resize=Живой ресайз окна +display.compact-window-bar.tooltip=Шапка окна высотой 24 px вместо 48 px +display.live-resize.tooltip=Перерисовывать окно при изменении размера (выключено — показывать последний кадр) # Управление chunks.reload=Перезагрузить Чанки diff --git a/res/textures/gui/maximize_w.png b/res/textures/gui/maximize_w.png new file mode 100644 index 000000000..c710bf814 Binary files /dev/null and b/res/textures/gui/maximize_w.png differ diff --git a/res/textures/gui/minimize_w.png b/res/textures/gui/minimize_w.png new file mode 100644 index 000000000..1633c39fc Binary files /dev/null and b/res/textures/gui/minimize_w.png differ diff --git a/res/textures/gui/restore_w.png b/res/textures/gui/restore_w.png new file mode 100644 index 000000000..fc245c1a6 Binary files /dev/null and b/res/textures/gui/restore_w.png differ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 398ee274f..0d650771f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,6 +4,13 @@ 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) +# 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 ${backend_sources}) + add_library(VoxelCoreSrc STATIC ${sources} ${headers}) find_package(OpenGL REQUIRED) @@ -79,27 +86,8 @@ endif() target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -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 @@ -135,6 +123,53 @@ target_compile_options( -Wduplicated-cond >) +# 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 + ${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) +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/engine/Engine.cpp b/src/engine/Engine.cpp index 1a4361f9e..c48c36b68 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,9 +1,12 @@ #include "Engine.hpp" +#include "WindowBar.hpp" #ifndef GLEW_STATIC #define GLEW_STATIC #endif +#include + #include "AssetsManagement.hpp" #include "audio/audio.hpp" #include "coders/commons.hpp" @@ -280,6 +283,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(); @@ -319,10 +323,17 @@ 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->draw(ctx, *assets->getStorage()); + draw_window_bar(*this); } void Engine::saveSettings() { 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/WindowBar.cpp b/src/engine/WindowBar.cpp new file mode 100644 index 000000000..b6097a60c --- /dev/null +++ b/src/engine/WindowBar.cpp @@ -0,0 +1,144 @@ +#include "WindowBar.hpp" + +#include "Engine.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" +#include "window/Window.hpp" +#include "assets/Assets.hpp" +#include "util/stringutil.hpp" + +#include +#include + +/// @brief Draws the window bar the backend cannot draw itself. +/// +/// 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(); + if (height <= 0) { + return; + } + auto* batch = engine.getGUI().getBatch2D(); + auto font = engine.requireAssets().getShared(FONT_DEFAULT); + const auto size = window.getSize(); + const float barHeight = static_cast(height); + + 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", + 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); + + const auto& buttons = window.getDecorationButtons(); + const int hovered = window.getDecorationHoveredButton(); + + 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); + } + } + // the bar and its controls do not need the font, only the title does + if (font != nullptr) { + 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 && + 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++) { + 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(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 + ); + } + const float ink = isHovered ? 1.0f : 0.8f; + batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink)); + 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( + 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(); + } + + } + 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/engine/WindowControl.cpp b/src/engine/WindowControl.cpp index 5a14c02ba..eb70b777b 100644 --- a/src/engine/WindowControl.cpp +++ b/src/engine/WindowControl.cpp @@ -59,11 +59,21 @@ 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()); + } } + // 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(); + }); + return Result {std::move(window), std::move(input)}; } diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index 6751b885c..cf5fdb303 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -625,8 +625,14 @@ void Hud::setDebug(bool flag) { void Hud::draw(const DrawContext& ctx){ const auto& viewport = ctx.getViewport(); + const int inset = gui.getContentInset(); + const int contentHeight = std::max( + 1, static_cast(viewport.y) - inset + ); - updateElementsPosition(viewport); + updateElementsPosition( + glm::uvec2(viewport.x, static_cast(contentHeight)) + ); uicamera->setFov(viewport.y); uicamera->setAspectRatio(viewport.x / static_cast(viewport.y)); @@ -698,7 +704,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/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 a8caf0fef..ba91f5b22 100644 --- a/src/frontend/screens/MenuScreen.hpp +++ b/src/frontend/screens/MenuScreen.hpp @@ -15,6 +15,11 @@ public: void onOpen() override; + // the bar covers the top getDecorationHeight() pixels, no widgets there + 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/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(); 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/core/commons.hpp b/src/graphics/core/commons.hpp index 0ca5a6470..230c9b0db 100644 --- a/src/graphics/core/commons.hpp +++ b/src/graphics/core/commons.hpp @@ -46,8 +46,17 @@ 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 + LAST=SW_RESIZE }; namespace advanced_pipeline { @@ -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/graphics/ui/GUI.cpp b/src/graphics/ui/GUI.cpp index 8070d58b0..055a256e0 100644 --- a/src/graphics/ui/GUI.cpp +++ b/src/graphics/ui/GUI.cpp @@ -105,7 +105,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); @@ -238,9 +238,21 @@ void GUI::actFocused() { } void GUI::act(float delta, const glm::uvec2& vp) { - container->setSize(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, 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; @@ -272,6 +284,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()); @@ -299,7 +316,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/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index 997b67bea..6cf84b919 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -123,6 +123,27 @@ 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 + glm::vec2 getCursorPosition() const; + + /// @brief Shift the main container down by the given number of pixels + void setContentInset(int inset) { + 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(); + } + void postAct(); /// @brief Add element to the main container diff --git a/src/io/settings_io.cpp b/src/io/settings_io.cpp index e72cb009d..8ccb24839 100644 --- a/src/io/settings_io.cpp +++ b/src/io/settings_io.cpp @@ -55,6 +55,8 @@ 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("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..13146979d 100644 --- a/src/logic/scripting/lua/libs/libapp.cpp +++ b/src/logic/scripting/lua/libs/libapp.cpp @@ -229,6 +229,16 @@ 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()); +} + /// @brief Bring application window to focus static int l_focus(lua::State* L) { engine->getWindow().focus(); @@ -502,6 +512,8 @@ const luaL_Reg applib[] = { {"open_folder", lua::wrap}, {"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 320d0fc8d..88a6ec133 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -38,6 +38,10 @@ 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 Render the window content every frame while it is resized + FlagSetting liveResize {true}; }; struct ChunksSettings { diff --git a/src/window/Window.cpp b/src/window/Window.cpp new file mode 100644 index 000000000..9b9a39180 --- /dev/null +++ b/src/window/Window.cpp @@ -0,0 +1,101 @@ +#include "Window.hpp" + +#include "debug/Logger.hpp" +#include "detail/WindowBackends.hpp" +#include "window/input.hpp" + +#include + +#ifndef GLEW_STATIC +#define GLEW_STATIC +#endif + +#include + +#include + +static debug::Logger logger("window"); + +#ifdef VOXELCORE_WAYLAND +static bool prefer_wayland() { + 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 VOXELCORE_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)); +} + +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 f5a50a731..3e8b61e0a 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -2,6 +2,10 @@ #include #include +#include +#include +#include +#include #include "graphics/core/commons.hpp" #include "typedefs.hpp" @@ -10,6 +14,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, @@ -32,18 +48,77 @@ public: virtual bool isShouldClose() const = 0; virtual void setShouldClose(bool flag) = 0; + virtual bool isFrameRequired() const { + return true; + } + 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; virtual void focus() = 0; virtual void setTitle(const std::string& title) = 0; + + virtual const std::string& getTitle() const { + static const std::string empty; + return empty; + } + + /// @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; + } + + /// @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; + } + + virtual const char* getBackendName() const = 0; + + virtual int getDecorationHeight() const { + return 0; + } + + virtual int getDecorationHoveredButton() const { + 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; - 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; @@ -65,7 +140,10 @@ public: > initialize(DisplaySettings* settings, std::string title); protected: glm::ivec2 size; + std::stack scissorStack; + glm::vec4 scissorArea {}; WindowMode mode = WindowMode::WINDOWED; + RefreshHandler refreshHandler; }; namespace display { 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/CMakeLists.txt b/src/window/detail/CMakeLists.txt new file mode 100644 index 000000000..de716ca02 --- /dev/null +++ b/src/window/detail/CMakeLists.txt @@ -0,0 +1,28 @@ +# Input state shared by the window backends. +add_library(VoxelWindowBase STATIC BaseInput.cpp) + +target_compile_options(VoxelWindowBase PRIVATE ${VOXEL_COMPILE_OPTIONS}) + +target_link_libraries(VoxelWindowBase PRIVATE VoxelCoreInterface) + +add_library(VoxelGLFW STATIC GLFWWindow.cpp FrameOperations.cpp) + +target_compile_options(VoxelGLFW PRIVATE ${VOXEL_COMPILE_OPTIONS}) + +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(NOT WIN32 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..42542eac3 --- /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 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; + 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..25755c7dd --- /dev/null +++ b/src/window/detail/FrameOperations.cpp @@ -0,0 +1,352 @@ +#include "window/detail/FrameOperations.hpp" + +#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 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; + } + 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; + 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. 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, + static_cast(LOWORD(lparam)), + static_cast(HIWORD(lparam)) + ); + } + 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 + +#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 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) { + 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 || + !x11_supports_moveresize(display)) { + 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; + } +} +#endif + +bool frame_has_native_operations() { +#if defined(VOXEL_X11_FRAME) + X11Api& api = x11_api(); + return api.available() && x11_supports_moveresize(api.display()); +#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* hitTestData, + FrameRefresh refresh, + void* refreshData +) { +#if defined(_WIN32) + HWND hwnd = glfwGetWin32Window(window); + if (hwnd == nullptr) { + return; + } + hit_test_callback = hitTest; + 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. + 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); + 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, + 0, + 0, + 0, + 0, + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER + ); +#else + (void)window; + (void)hitTest; + (void)hitTestData; + (void)refresh; + (void)refreshData; +#endif +} diff --git a/src/window/detail/FrameOperations.hpp b/src/window/detail/FrameOperations.hpp new file mode 100644 index 000000000..625b665ed --- /dev/null +++ b/src/window/detail/FrameOperations.hpp @@ -0,0 +1,40 @@ +#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 Called when the windowing system wants the content redrawn +/// @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 +/// @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 08b39bd07..f8b28fe41 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -1,10 +1,15 @@ #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 #include #include #include +#include #include #include @@ -18,9 +23,72 @@ 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"; +} + +/// @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 +} + +/// @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); +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 +153,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,136 +216,27 @@ 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)); - } +/// @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); } - - 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: @@ -301,48 +245,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 { @@ -378,17 +288,26 @@ 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, &frame_refresh_thunk, this + ); + } } ~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(); } @@ -400,7 +319,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) { @@ -424,6 +343,209 @@ 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; + } + + bool hasEngineFrame() const override { + return engineFrame; + } + + /// @brief Whether the window is redrawn while it is being resized + bool isLiveResizeEnabled() const { + return 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 (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; + } + + 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 + bool inRefreshCallback = false; + + 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(); + 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 {}; + } + // 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 {y < height, 0}; + } + + /// @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; + } + 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(); + 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; + } + 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); } @@ -450,12 +572,13 @@ 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 { Window::mode = mode; - GLFWmonitor* monitor = glfwGetPrimaryMonitor(); + resetFrameInteraction(); + GLFWmonitor* monitor = get_window_monitor(window); const GLFWvidmode* glfwMode = glfwGetVideoMode(monitor); if (input.isCursorLocked()){ @@ -485,7 +608,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()); } @@ -503,10 +626,25 @@ public: glfwFocusWindow(window); } + std::string title; + + const char* getBackendName() const override { + return "glfw"; + } + + const std::string& getTitle() const override { + return title; + } + void setTitle(const std::string& title) override { + this->title = title; glfwSetWindowTitle(window, title.c_str()); } + bool isIconSupported() const override { + return true; + } + void setIcon(const ImageData* image) override { if (image == nullptr) { glfwSetWindowIcon(window, 0, nullptr); @@ -529,64 +667,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); @@ -604,20 +685,231 @@ public: } private: + int layoutFrameButtons(frame::Rect* rects) const { + return frame::layoutButtons( + static_cast(getSize().x), + static_cast(frameButtons.size()), + settings->compactWindowBar.get(), + rects + ); + } + + /// @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]; + 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) { + 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); + } + } + + 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) { + // 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_refresh_thunk, this + ); + 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; + bool frameCursorActive = false; + 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; + 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; + static constexpr int MIN_HEIGHT = 200; CursorShape cursor = CursorShape::ARROW; int framerate = -1; - std::stack scissorStack; - glm::vec4 scissorArea {}; double prevSwap = 0.0; 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()); 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(); } @@ -664,6 +956,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(); } @@ -679,7 +972,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 && @@ -693,6 +988,7 @@ static void create_standard_cursors() { static void refresh_callback(GLFWwindow* window) { auto handler = static_cast(glfwGetWindowUserPointer(window)); handler->setShouldRefresh(); + handler->drawRefreshFrame(); } static void setup_callbacks(GLFWwindow* window) { @@ -709,7 +1005,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 +1014,17 @@ std::tuple< logger.error() << "failed to initialize GLFW"; return {nullptr, nullptr}; } + 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); + } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); @@ -734,6 +1041,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) { @@ -741,6 +1051,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; @@ -782,7 +1108,6 @@ std::tuple< setup_callbacks(window); glfwSwapInterval(1); - input_util::initialize(); create_standard_cursors(); glm::vec2 scale; @@ -796,8 +1121,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)}; } diff --git a/src/window/detail/WindowBackends.hpp b/src/window/detail/WindowBackends.hpp new file mode 100644 index 000000000..873173040 --- /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 VOXELCORE_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 57454020d..15385d8dd 100644 --- a/src/window/input.cpp +++ b/src/window/input.cpp @@ -6,6 +6,7 @@ #include +#include #include #ifdef _WIN32 @@ -169,95 +170,22 @@ std::string input_util::to_string(Keycode code) { 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"; - } + const auto found = keynames.find(icode_repr); + if (found == keynames.end()) { + return "Unknown"; } - return std::string(name); + 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) { diff --git a/src/window/wayland/CMakeLists.txt b/src/window/wayland/CMakeLists.txt new file mode 100644 index 000000000..1ebbb7933 --- /dev/null +++ b/src/window/wayland/CMakeLists.txt @@ -0,0 +1,105 @@ +# 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) + + 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() + + 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 CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) + + add_library(VoxelWayland STATIC ${wayland_sources} ${WAYLAND_SOURCES}) + + target_include_directories(VoxelWayland PRIVATE ${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 + VoxelCoreInterface + PkgConfig::wayland-client + PkgConfig::xkbcommon + PkgConfig::egl + ${WAYLAND_EGL_LIBRARY}) + + 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() diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp new file mode 100644 index 000000000..bf998a272 --- /dev/null +++ b/src/window/wayland/WaylandCommon.cpp @@ -0,0 +1,248 @@ +#include "window/wayland/WaylandCommon.hpp" + +#include +#include +#include + +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]); + 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_PACK_ALIGNMENT, &values[15]); + glGetIntegerv(GL_VIEWPORT, viewport); + glGetIntegerv(GL_COLOR_WRITEMASK, colorMask); + for (int i = 0; i < 3; 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_STRIDE, &attribs[i][3]); + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][4] + ); + void* pointer = nullptr; + glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer); + attribs[i][5] = 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]); + 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]); + 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][4])); + glVertexAttribPointer( + i, attribs[i][0], static_cast(attribs[i][1]), + attribs[i][2], attribs[i][3], + reinterpret_cast(static_cast(attribs[i][5])) + ); + 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); + 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; +class WaylandWindow; + +WaylandInput* input = nullptr; +WaylandWindow* window = nullptr; + +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) { + 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) { + 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) { + on_display_error(); + return; + } + } else { + wl_display_cancel_read(state.display); + } + 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 new file mode 100644 index 000000000..e49beeee7 --- /dev/null +++ b/src/window/wayland/WaylandCommon.hpp @@ -0,0 +1,105 @@ +#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 +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct GlStateGuard { + GLint values[16] {}; + GLint attribs[3][6] {}; + GLint viewport[4] {}; + GLint colorMask[4] {}; + GLboolean flags[4] {}; + GLboolean attribFlags[3] {}; + GlStateGuard(); + ~GlStateGuard(); +}; + +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; + 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...) { +} + +void dispatch_events(int timeoutMs); +int keycode_from_keysym(xkb_keysym_t sym); + +void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +); +void on_display_error(); diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp new file mode 100644 index 000000000..2321fdfe5 --- /dev/null +++ b/src/window/wayland/WaylandDecorations.cpp @@ -0,0 +1,431 @@ +#include "window/wayland/WaylandWindow.hpp" + +#include "settings.hpp" + +#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; + } + + 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 layoutUnavailable = false; + + bool read_button_layout( + std::vector& left, + std::vector& right + ) { + 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); + 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::vector left; + std::vector right; + split_layout(rawValue, left, right); + 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 < LAYOUT_CHECK_INTERVAL) { + 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() { + 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); + // 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 = 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 - padding - + static_cast(rightButtons.size() - i) * pitch + + gap; + 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; +} + +int WaylandWindow::getDecorationHeight() const { + return barVisible() ? barHeight() : 0; +} + +int WaylandWindow::getDecorationHoveredButton() const { + return hoveredButton; +} + +void WaylandWindow::enableOwnDecorations() { + if (barEnabled) { + return; + } + barEnabled = true; + resize(size.x, size.y); + setShouldRefresh(); +} + +void WaylandWindow::disableOwnDecorations() { + if (!barEnabled) { + return; + } + barEnabled = false; + resize(size.x, size.y); + setShouldRefresh(); +} + +bool WaylandWindow::barVisible() const { + return barEnabled && !fullscreen && Window::mode != WindowMode::BORDERLESS; +} + +int WaylandWindow::barButtonAt(double x, double y) const { + const int top = (barHeight() - BAR_BUTTON) / 2; + if (!barVisible() || y < top || y >= top + BAR_BUTTON) { + return -1; + } + 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 (!barVisible()) { + return 0; + } + if (barButtonAt(x, y) >= 0) { + return 0; + } + const bool inBar = y >= 0.0 && y < barHeight(); + 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; + } + 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) { + 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; +} + +uint32_t WaylandWindow::pointerEdges() const { + if (!barVisible()) { + return 0; + } + 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; + 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 = pointerEdges(); + if (edges != 0) { + hoveredButton = -1; + pointerInBar = false; + input.setOverrideCursor(edgeCursor(edges)); + return true; + } + const double contentY = this->contentY(y); + const bool inBar = + barVisible() && contentY >= 0.0 && contentY < barHeight(); + if (inBar && !pointerInBar) { + lastLayoutCheck = 0.0; + } + pointerInBar = inBar; + if (inBar) { + hoveredButton = + barDragging ? -1 : barButtonAt(contentX(x), contentY); + input.setOverrideCursor( + hoveredButton >= 0 ? CursorShape::POINTER : CursorShape::ARROW + ); + return true; + } + hoveredButton = -1; + input.setOverrideCursor(std::nullopt); + return false; +} + +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 < barHeight(); + if (button != 0) { + return inBar || edges != 0; + } + if (edges != 0) { + if (pressed) { + xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); + } + return true; + } + 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 { + if (!barVisible()) { + return false; + } + const double y = contentY(pointerY); + return (y >= 0.0 && y < barHeight()) || pointerEdges() != 0; +} + +void WaylandWindow::onPointerLeave() { + hoveredButton = -1; + pointerInBar = false; + barPressed = false; + barDragging = false; + barPressedButton = -1; + input.setOverrideCursor(std::nullopt); +} diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp new file mode 100644 index 000000000..a5d76ca1d --- /dev/null +++ b/src/window/wayland/WaylandInit.cpp @@ -0,0 +1,273 @@ +#include "window/wayland/WaylandWindow.hpp" +#include "window/wayland/WaylandInput.hpp" +#include "window/wayland/WaylandListeners.hpp" + +#include "settings.hpp" +#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) { + 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 = [] { + 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) { + return fail("the compositor does not provide xdg-shell"); + } + + state.surface = wl_compositor_create_surface(state.compositor); + + inputPtr = std::make_unique(); + input = inputPtr.get(); + 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) { + return fail("the Wayland connection was lost"); + } + } + + window->eglDisplay = eglGetPlatformDisplay( + EGL_PLATFORM_WAYLAND_KHR, state.display, nullptr + ); + if (window->eglDisplay == EGL_NO_DISPLAY || + eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { + return fail("could not initialize EGL"); + } + eglBindAPI(EGL_OPENGL_API); + + EGLint samples = settings->samples.get(); + const EGLint requestedSamples = samples > 0 ? samples : 0; + EGLConfig config = nullptr; + EGLint configCount = 0; + 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, alpha, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_SAMPLES, sampleCount, + EGL_NONE + }; + config = nullptr; + configCount = 0; + eglChooseConfig( + window->eglDisplay, attributes, &config, 1, &configCount + ); + 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)) { + return fail("no suitable EGL config"); + } + window->shadowEnabled = false; + } + } + + 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 + ); + const auto surfaceSize = window->surfaceSize(); + window->eglWindow = wl_egl_window_create( + state.surface, surfaceSize.x, surfaceSize.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) { + 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) { + return fail( + std::string("failed to initialize GLEW:\n") + + reinterpret_cast(glewGetErrorString(glewError)) + ); + } + + window->initStretchRenderer(); + window->initShadowRenderer(); + 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)"; + + // 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)}; +} + +void on_display_error() { + waylandLogger.error() << "the Wayland connection was lost"; + if (window) { + window->setShouldClose(true); + } +} + +void WaylandInput::pollEvents(bool waitForRefresh) { + updateClipboard(); + beginFrame(); + dispatch(waitForRefresh); + if (window) { + window->paceFrame(); + } + updateRepeat(); + updateBindings(); +} + +void WaylandInput::refreshWindow() { + if (window) { + window->setShouldRefresh(); + } +} diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp new file mode 100644 index 000000000..d3a832838 --- /dev/null +++ b/src/window/wayland/WaylandInput.hpp @@ -0,0 +1,436 @@ +#pragma once + +#include "window/wayland/WaylandCommon.hpp" + +#include "window/detail/BaseInput.hpp" + +#include "window/Window.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#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: + ~WaylandInput() override; + + void pollEvents(bool waitForRefresh) override; + + const char* getClipboardText() const override { + return clipboard.c_str(); + } + + void requestClipboardText() { + if (state.dataDevice == nullptr || selection == nullptr) { + return; + } + const char* mime = pickMime(); + if (mime == nullptr) { + clipboard.clear(); + return; + } + int fds[2]; + if (pipe(fds) == -1) { + 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]); + 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; + } + } + + 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 : ""; + clipboard = sourceText; + if (clipboardFd >= 0) { + close(clipboardFd); + clipboardFd = -1; + } + 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(); + } + + /// @brief Release every pressed key, e.g. when the keyboard focus is lost + void releasePressedKeys() { + const auto keys = heldKeys; + heldKeys.clear(); + 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; + } + + void onKey(uint32_t key, bool pressed) { + if (state.xkbState == nullptr || state.xkbKeymap == nullptr) { + return; + } + 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 + ) > 0) { + 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; + 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; + std::string clipboard; + int clipboardFd = -1; + 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::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; + } + return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + } + + static void dispatch(bool block) { + dispatch_events(block ? 500 : 0); + } + + static double now() { + return waylandNow(); + } + + 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 >= 0x20 && codepoint != 0x7F) { + codepoints.push_back(codepoint); + } + 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 >= 0x20 && codepoint != 0x7F) { + codepoints.push_back(codepoint); + } + } + + void updateRepeat() { + if (repeatKeycode == 0 || state.repeatRate == 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 == 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); + }; + 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; + // 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 new file mode 100644 index 000000000..2e204b34c --- /dev/null +++ b/src/window/wayland/WaylandListeners.cpp @@ -0,0 +1,385 @@ +#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( + window ? window->contentX(x) : x, window ? window->contentY(y) : 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)) { + window->setShouldRefresh(); + return; + } + if (input) { + input->setCursorPosition( + window ? window->contentX(x) : x, window ? window->contentY(y) : y + ); + input->refreshWindow(); + } +} + +static void pointer_button( + void*, wl_pointer*, uint32_t serial, uint32_t, uint32_t button, + uint32_t buttonState +) { + state.inputSerial = serial; + // 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)) { + 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) { + if (window && window->handleBarScroll()) { + return; + } + 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*) { + if (input) { + input->releasePressedKeys(); + } +} + +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 ? static_cast(rate) : 0; + 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<>; + 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->pendingMimes.clear(); + if (offer == nullptr) { + input->selectionMimes.clear(); + input->clearClipboardText(); + return; + } + input->selectionMimes = std::move(input->pendingMimes); + input->requestClipboardText(); +} + +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) { + // 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) + )); + 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 +) { + const bool serverDecorations = + mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; + if (window != nullptr) { + if (serverDecorations) { + window->disableOwnDecorations(); + } else { + window->enableOwnDecorations(); + } + } +} + diff --git a/src/window/wayland/WaylandListeners.hpp b/src/window/wayland/WaylandListeners.hpp new file mode 100644 index 000000000..c78e9dd5e --- /dev/null +++ b/src/window/wayland/WaylandListeners.hpp @@ -0,0 +1,21 @@ +#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/WaylandSettings.cpp b/src/window/wayland/WaylandSettings.cpp new file mode 100644 index 000000000..201b4aab9 --- /dev/null +++ b/src/window/wayland/WaylandSettings.cpp @@ -0,0 +1,188 @@ +#include "window/wayland/WaylandSettings.hpp" + +#include "window/wayland/WaylandCommon.hpp" + +#include + +#ifdef VOXELCORE_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 VOXELCORE_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 VOXELCORE_SDBUS + sd_bus* bus = nullptr; + std::string changedSchema; + 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 (schema != nullptr && key != nullptr && !value.empty()) { + self->changedSchema = schema; + 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 VOXELCORE_SDBUS + if (impl->bus != nullptr) { + return true; + } + if (sd_bus_default_user(&impl->bus) < 0) { + impl->bus = nullptr; + return false; + } + 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; +#endif +} + +void SettingsWatcher::close() { +#ifdef VOXELCORE_SDBUS + if (impl->bus != nullptr) { + sd_bus_flush_close_unref(impl->bus); + impl->bus = nullptr; + } +#endif +} + +bool SettingsWatcher::isAvailable() const { +#ifdef VOXELCORE_SDBUS + return impl->bus != nullptr; +#else + return false; +#endif +} + +bool SettingsWatcher::read( + const char* schema, const char* key, std::string& value +) { +#ifdef VOXELCORE_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 VOXELCORE_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 (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 + return false; +#endif +} diff --git a/src/window/wayland/WaylandSettings.hpp b/src/window/wayland/WaylandSettings.hpp new file mode 100644 index 000000000..878b379f5 --- /dev/null +++ b/src/window/wayland/WaylandSettings.hpp @@ -0,0 +1,22 @@ +#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(); + + struct Impl; + Impl* impl = nullptr; +}; diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp new file mode 100644 index 000000000..17c46a8ee --- /dev/null +++ b/src/window/wayland/WaylandWindow.cpp @@ -0,0 +1,781 @@ +#include "window/wayland/WaylandWindow.hpp" + +#include "settings.hpp" +#include "util/platform.hpp" + +WaylandWindow::WaylandWindow( + WaylandInput& input, DisplaySettings* settings, int width, int height +) + : Window({width, height}), + input(input), + settings(settings), + initialWidth(width), + initialHeight(height) { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); +} + +WaylandWindow::~WaylandWindow() { + if (window == this) { + window = nullptr; + } + 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 (shadowProgram) { + glDeleteProgram(shadowProgram); + } + if (stretchVbo) { + glDeleteBuffers(1, &stretchVbo); + } + if (stretchVao) { + glDeleteVertexArrays(1, &stretchVao); + } + 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); + } + 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; + } + if (state.xkbContext) { + xkb_context_unref(state.xkbContext); + state.xkbContext = nullptr; + } + if (state.display) { + wl_display_disconnect(state.display); + } + state = WaylandState {}; +} + +double WaylandWindow::time() { + return now(); +} + +void WaylandWindow::swapBuffers() { + updateSettings(); + updateResizing(); + if (resizing && !presentPending && !frameDone) { + resetScissor(); + return; + } + if (liveResizeEnabled()) { + if (frameRendered) { + cacheContent(); + } + } else if (resizing) { + // 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 (frameRendered) { + cacheContent(); + } + frameRendered = false; + renderPending = false; + composeFrame(); + requestFrame(); + eglSwapBuffers(eglDisplay, eglSurface); + if (sizeChanged) { + sizeChanged = false; + composeFrame(); + 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 + ); + } + } + lastPresent = current; + nextFrameTime = current + frameInterval; + 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 { + if (!liveResizeEnabled()) { + const bool required = !resizing || renderPending; + if (required) { + frameRendered = true; + } + 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 { + 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); + if (maximized) { + setMaximized(false); + } + setIdleInhibit(false); + 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); + } +} + +int WaylandWindow::marginSize() const { + if (!barEnabled || !shadowEnabled) { + return 0; + } + if (fullscreen || maximized || Window::mode != WindowMode::WINDOWED) { + return 0; + } + return SHADOW_MARGIN; +} + +bool WaylandWindow::compactBar() const { + return settings->compactWindowBar.get(); +} + +int WaylandWindow::barHeight() const { + return compactBar() ? BAR_HEIGHT_COMPACT : BAR_HEIGHT; +} + +bool WaylandWindow::liveResizeEnabled() const { + return settings->liveResize.get(); +} + +void WaylandWindow::updateSettings() { + 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}; +} + +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) { + const auto surface = surfaceSize(); + wl_egl_window_resize(eglWindow, surface.x, surface.y, 0, 0); + glViewport(0, 0, width, height); + } + updateWindowGeometry(); + 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); +} + +void WaylandWindow::onConfigure( + int32_t width, int32_t height, wl_array* states +) { + pendingWidth = width; + pendingHeight = height; + stateMaximized = false; + stateFullscreen = 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_FULLSCREEN: + stateFullscreen = true; + break; + case XDG_TOPLEVEL_STATE_SUSPENDED: + stateSuspended = true; + break; + case XDG_TOPLEVEL_STATE_ACTIVATED: + stateActivated = true; + break; + } + } +} + +void WaylandWindow::applyConfigure() { + maximized = stateMaximized; + fullscreen = stateFullscreen; + suspended = stateSuspended; + if (pendingWidth > 0 && pendingHeight > 0) { + if (!initialSizeApplied && Window::mode == WindowMode::WINDOWED && + !maximized && initialWidth > 0 && initialHeight > 0) { + pendingWidth = initialWidth; + pendingHeight = initialHeight; + } + initialSizeApplied = true; + resize(pendingWidth, pendingHeight); + } + if (stateActivated && !activated) { + lastLayoutCheck = 0.0; + } + activated = stateActivated; + configured = true; + setShouldRefresh(); +} + +std::unique_ptr WaylandWindow::takeScreenshot() { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + 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( + 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() + ); +} + +void WaylandWindow::setFramerate(int framerate) { + this->framerate = framerate; +} + +void WaylandWindow::initStretchRenderer() { + 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"; + 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); + 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::initShadowRenderer() { + if (!shadowEnabled) { + return; + } + 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(WAYLAND_VERTEX_SHADER, 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; + resize(size.x, size.y); + 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]); + } +} + +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) { + 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], SHADOW_BLUR); + glUniform1f( + shadowUniforms[3], + activated ? SHADOW_STRENGTH : SHADOW_STRENGTH_BACKDROP + ); + glUniform1f(shadowUniforms[4], 0.0f); + 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); + 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); + 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); + // 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); + if (margin > 0) { + 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(stretchTextureUniform, 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; + } + 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); +} + +/// @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) { + 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::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() { + updateButtonLayout(); + 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(); + 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::markResizing() { + lastResize = now(); + if (!resizing) { + resizing = true; + setShouldRefresh(); + } +} + +void WaylandWindow::updateResizing() { + if (resizing && now() - lastResize > RESIZE_TIMEOUT) { + resizing = false; + renderPending = true; + } +} + +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 waylandNow(); +} diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp new file mode 100644 index 000000000..5b4fb86c2 --- /dev/null +++ b/src/window/wayland/WaylandWindow.hpp @@ -0,0 +1,223 @@ +#pragma once + +#include "window/wayland/WaylandCommon.hpp" + +#include +#include "window/wayland/WaylandSettings.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 stateFullscreen = 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; + // 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; + 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; + void setShouldRefresh() override; + bool checkShouldRefresh() override; + 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; + void setCursor(CursorShape shape) override; + void setMode(WindowMode mode) override; + WindowMode getMode() const override; + 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"; + } + + /// @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; + static constexpr int BAR_EDGE = 8; + static constexpr int SHADOW_MARGIN = 10; + static constexpr int RESIZE_GRAB_EXTRA = 2; + bool shadowEnabled = false; + 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(); + } + + 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); + + const std::vector& getDecorationButtons() const + override; + + void updateButtonLayout(); + + void updateBarGeometry(); + + bool isIconSupported() const override { + return false; + } + + void setIcon(const ImageData*) override { + } + void setFullscreen(bool enabled); + void setMaximized(bool enabled); + void resize(int width, int height); + void onConfigure(int32_t width, int32_t height, wl_array* states); + void applyConfigure(); + std::unique_ptr takeScreenshot() override; + void setFramerate(int framerate) override; + void initStretchRenderer(); + void resizeCache(int width, int height); + void cacheContent(); + void enableOwnDecorations(); + void disableOwnDecorations(); + bool barVisible() 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; + bool handleBarMotion(double x, double y); + bool handleBarButton(uint32_t serial, int button, bool pressed); + bool handleBarScroll() const; + void onPointerLeave(); + void onFrameDone(); + void requestFrame(); + void paceFrame(); + void markResizing(); + void updateResizing(); + void setIdleInhibit(bool enabled); + static const wl_callback_listener& frameListener(); + static double now(); +}; 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 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. + + + + + +