This commit is contained in:
Alex Zebra 2026-11-03 20:25:14 +03:00 • committed by GitHub
commit e78b0f0367
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
64 changed files with 8634 additions and 387 deletions

View file

@ -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

View file

@ -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

3
.gitignore vendored
View file

@ -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

View file

@ -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
$<$<PLATFORM_ID:Windows>:winmm>)
target_link_options(VoxelCore PRIVATE $<$<CXX_COMPILER_ID:GNU>:-no-pie>)
# Deploy res to build dir
add_custom_command(
TARGET VoxelCore

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -66,6 +66,20 @@ function on_open()
"</select>", 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")

View file

@ -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",

View file

@ -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

View file

@ -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=Перезагрузить Чанки

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 B

View file

@ -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 $<$<CXX_COMPILER_ID:MSVC>:
set(VOXEL_COMPILE_OPTIONS
$<$<CXX_COMPILER_ID:MSVC>:
/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

View file

@ -1,9 +1,12 @@
#include "Engine.hpp"
#include "WindowBar.hpp"
#ifndef GLEW_STATIC
#define GLEW_STATIC
#endif
#include <GL/glew.h>
#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<GLsizei>(window->getSize().x),
static_cast<GLsizei>(window->getSize().y)
);
screen->draw(time.getDelta());
DrawContext ctx(nullptr, *window, nullptr);
gui->draw(ctx, *assets->getStorage());
draw_window_bar(*this);
}
void Engine::saveSettings() {

View file

@ -48,7 +48,7 @@ void Mainloop::run() {
engine.applicationTick();
engine.updateFrontend();
if (!window.isIconified()) {
if (!window.isIconified() && window.isFrameRequired()) {
engine.renderFrame();
}
engine.postUpdate();

144
src/engine/WindowBar.cpp Normal file
View file

@ -0,0 +1,144 @@
#include "WindowBar.hpp"
#include "Engine.hpp"
#include "graphics/core/Batch2D.hpp"
#include <GL/glew.h>
#include <glm/gtc/matrix_transform.hpp>
#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 <algorithm>
#include <string_view>
/// @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>(FONT_DEFAULT);
const auto size = window.getSize();
const float barHeight = static_cast<float>(height);
glViewport(
0, 0, static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y)
);
auto shader = engine.requireAssets().get<Shader>("ui");
if (shader != nullptr) {
shader->use();
shader->uniformMatrix(
"u_projview",
glm::ortho(
0.0f,
static_cast<float>(size.x),
static_cast<float>(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<float>(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<float>(
font->calcWidth(title, titleLength)
);
const float centered =
(static_cast<float>(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<int>(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<int>(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<Texture>(iconName);
if (icon != nullptr) {
const float iconSize = std::min(
16.0f, static_cast<float>(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();
}

5
src/engine/WindowBar.hpp Normal file
View file

@ -0,0 +1,5 @@
#pragma once
class Engine;
void draw_window_bar(Engine& engine);

View file

@ -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)};
}

View file

@ -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<int>(viewport.y) - inset
);
updateElementsPosition(viewport);
updateElementsPosition(
glm::uvec2(viewport.x, static_cast<uint>(contentHeight))
);
uicamera->setFov(viewport.y);
uicamera->setAspectRatio(viewport.x / static_cast<float>(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());

View file

@ -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,
"<label z-index='1000' color='#FFFFFF30' gravity='top-right' "
"margin='4'>" +
text + "</label>"
"margin='4," + std::to_string(top) + ",4,4'>" + text + "</label>"
));
}

View file

@ -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;

View file

@ -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();
}

View file

@ -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;
};

View file

@ -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<uint>(bound) == expected) {
return;
}
flush();

View file

@ -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);

View file

@ -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 {

View file

@ -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<uint>(viewportOffset);
const uint contentHeight = vp.y > inset ? vp.y - inset : vp.y;
container->setPos({0.0f, static_cast<float>(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<float>(contentHeight)) {
size.y = static_cast<float>(contentHeight);
frame.setSize(size);
frame.setPos({0.0f, static_cast<float>(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<float>(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) {

View file

@ -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

View file

@ -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);

View file

@ -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<l_open_folder>},
{"open_url", lua::wrap<l_open_url>},
/// window
{"get_window_backend", lua::wrap<l_get_window_backend>},
{"has_engine_window_frame", lua::wrap<l_has_engine_window_frame>},
{"focus", lua::wrap<l_focus>},
{"set_title", lua::wrap<l_set_title>},
{"quit", lua::wrap<l_quit>},

View file

@ -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 {

101
src/window/Window.cpp Normal file
View file

@ -0,0 +1,101 @@
#include "Window.hpp"
#include "debug/Logger.hpp"
#include "detail/WindowBackends.hpp"
#include "window/input.hpp"
#include <cstdlib>
#ifndef GLEW_STATIC
#define GLEW_STATIC
#endif
#include <GL/glew.h>
#include <algorithm>
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<Window>,
std::unique_ptr<Input>
> 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<int>(glm::ceil(area.z - area.x))),
std::max(0, static_cast<int>(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<int>(area.z - area.x)),
std::max(0, static_cast<int>(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<glm::vec4>();
glDisable(GL_SCISSOR_TEST);
}

View file

@ -2,6 +2,10 @@
#include <glm/glm.hpp>
#include <memory>
#include <stack>
#include <functional>
#include <string>
#include <vector>
#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()>;
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<DecorationButtonLayout>& getDecorationButtons()
const {
static const std::vector<DecorationButtonLayout> 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<glm::vec4> scissorStack;
glm::vec4 scissorArea {};
WindowMode mode = WindowMode::WINDOWED;
RefreshHandler refreshHandler;
};
namespace display {

View file

@ -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<Keycode>(key));
if (callbacks != keyCallbacks.end()) {
callbacks->second.notify();
}
}
if (pressed && key < MOUSE_KEYS_OFFSET) {
pressedKeys.push_back(static_cast<Keycode>(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<Keycode>(MOUSE_KEYS_OFFSET + static_cast<int>(button)),
std::move(callback)
);
}
const std::vector<Keycode>& BaseInput::getPressedKeys() const {
return pressedKeys;
}
const std::vector<uint>& 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<int>(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<int>(keycode)] == currentFrame;
}
bool BaseInput::clicked(Mousecode code) const {
return pressed(
static_cast<Keycode>(MOUSE_KEYS_OFFSET + static_cast<int>(code))
);
}
bool BaseInput::jclicked(Mousecode code) const {
return clicked(code) &&
frames[static_cast<int>(code) + MOUSE_KEYS_OFFSET] == currentFrame;
}
void BaseInput::simulateKey(Keycode key, bool pressed) {
onKeyCallback(static_cast<int>(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<Keycode>(binding.code));
break;
case InputType::MOUSE:
newstate = clicked(static_cast<Mousecode>(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;
}
}
}
}

View file

@ -0,0 +1,58 @@
#pragma once
#include "window/input.hpp"
#include <glm/vec2.hpp>
#include <unordered_map>
#include <vector>
inline constexpr short KEYS_BUFFER_SIZE = 1036;
inline constexpr short MOUSE_KEYS_OFFSET = 1024;
class BaseInput : public Input {
public:
std::vector<uint> 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<Keycode>& getPressedKeys() const override;
const std::vector<uint>& 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<Keycode> pressedKeys;
Bindings bindings;
bool keys[KEYS_BUFFER_SIZE] {};
std::unordered_map<Keycode, util::HandlersList<>> keyCallbacks;
bool cursorLocked = false;
bool cursorDrag = false;
glm::vec2 delta {};
glm::vec2 cursor {};
};

View file

@ -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()

View file

@ -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<float>(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;
}
}

View file

@ -0,0 +1,352 @@
#include "window/detail/FrameOperations.hpp"
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#include <windowsx.h>
#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
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<NCCALCSIZE_PARAMS*>(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<int>(LOWORD(lparam)),
static_cast<int>(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 <X11/Xatom.h>
#include <X11/Xlib.h>
#include <dlfcn.h>
#include <GLFW/glfw3.h>
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<Display* (*)()>(
dlsym(RTLD_DEFAULT, "glfwGetX11Display")
);
window = reinterpret_cast<Window (*)(GLFWwindow*)>(
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<const Atom*>(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<LONG_PTR>(frame_window_proc)) {
original_window_proc = reinterpret_cast<WNDPROC>(current);
SetWindowLongPtr(
hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(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
}

View file

@ -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
);
/// @}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
#pragma once
#include <memory>
#include <string>
#include <tuple>
class Window;
class Input;
struct DisplaySettings;
std::tuple<std::unique_ptr<Window>, std::unique_ptr<Input>>
glfw_window_initialize(DisplaySettings* settings, std::string title);
#ifdef VOXELCORE_WAYLAND
std::tuple<std::unique_ptr<Window>, std::unique_ptr<Input>>
wayland_window_initialize(DisplaySettings* settings, std::string title);
#endif

View file

@ -6,6 +6,7 @@
#include <GLFW/glfw3.h>
#include <cctype>
#include <unordered_map>
#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<char>(std::toupper(c)) : c;
capitalize = false;
}
return result;
}
std::string input_util::to_string(Mousecode code) {

View file

@ -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()

View file

@ -0,0 +1,248 @@
#include "window/wayland/WaylandCommon.hpp"
#include <cerrno>
#include <cstring>
#include <poll.h>
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<double>(
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<GLint>(
reinterpret_cast<intptr_t>(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<GLuint>(attribs[i][4]));
glVertexAttribPointer(
i, attribs[i][0], static_cast<GLenum>(attribs[i][1]),
attribs[i][2], attribs[i][3],
reinterpret_cast<void*>(static_cast<intptr_t>(attribs[i][5]))
);
if (attribFlags[i]) {
glEnableVertexAttribArray(i);
} else {
glDisableVertexAttribArray(i);
}
}
glBindBuffer(GL_ARRAY_BUFFER, static_cast<GLuint>(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();
}
}

View file

@ -0,0 +1,105 @@
#pragma once
#include <GL/glew.h>
#include "debug/Logger.hpp"
#include <GLFW/glfw3.h>
#include <wayland-client.h>
#include <xkbcommon/xkbcommon.h>
#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 <EGL/egl.h>
#include <EGL/eglext.h>
#include <wayland-egl.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <memory>
#include <optional>
#include <poll.h>
#include <string>
#include <tuple>
#include <vector>
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 <typename... Args>
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();

View file

@ -0,0 +1,431 @@
#include "window/wayland/WaylandWindow.hpp"
#include "settings.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
namespace {
constexpr const char* LAYOUT_SCHEMA = "org.gnome.desktop.wm.preferences";
constexpr const char* LAYOUT_KEY = "button-layout";
std::vector<DecorationButton> parse_buttons(const std::string& text) {
std::vector<DecorationButton> 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<DecorationButton>& left,
std::vector<DecorationButton>& 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<DecorationButton>& left,
std::vector<DecorationButton>& 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<DecorationButton> left;
std::vector<DecorationButton> 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<DecorationButton> left;
std::vector<DecorationButton> 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<DecorationButton> left;
std::vector<DecorationButton> 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<float>(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<float>(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<float>(rightButtons.size() - i) * pitch +
gap;
if (x < 0.0f) {
break;
}
barButtons.push_back({rightButtons[i], x, BAR_BUTTON});
}
}
const std::vector<DecorationButtonLayout>&
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<int>(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<int>(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);
}

View file

@ -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 <EGL/eglext.h>
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<Window>, std::unique_ptr<Input>>
wayland_window_initialize(DisplaySettings* settings, std::string title) {
std::unique_ptr<WaylandInput> inputPtr;
std::unique_ptr<WaylandWindow> windowPtr;
const auto fail = [&] (
const std::string& message
) -> std::tuple<std::unique_ptr<Window>, std::unique_ptr<Input>> {
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, &registryListener, 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<WaylandInput>();
input = inputPtr.get();
windowPtr = std::make_unique<WaylandWindow>(
*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<EGLNativeWindowType>(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<const char*>(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<GLint>(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<const char*>(glGetString(GL_VENDOR));
waylandLogger.info() << "GL Renderer: "
<< reinterpret_cast<const char*>(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();
}
}

View file

@ -0,0 +1,436 @@
#pragma once
#include "window/wayland/WaylandCommon.hpp"
#include "window/detail/BaseInput.hpp"
#include "window/Window.hpp"
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <optional>
#include <string>
#include <thread>
#include <unordered_set>
#include <vector>
/// @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<CursorShape> 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<int>(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<uint32_t>(keycode));
} else {
heldKeys.erase(static_cast<uint32_t>(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<std::string> selectionMimes;
std::vector<std::string> 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<const ubyte*>(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>(keycode))) {
return;
}
double time = now();
if (time - repeatTime < state.repeatDelay / 1000.0) {
return;
}
double interval = 1.0 / std::max<uint32_t>(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<size_t>(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<CursorShape> overrideCursor;
// the keys really held: BaseInput::pressedKeys is never erased
std::unordered_set<uint32_t> heldKeys;
xkb_keycode_t repeatKeycode = 0;
double repeatTime = 0.0;
double lastRepeat = 0.0;
};

View file

@ -0,0 +1,385 @@
#include "window/wayland/WaylandWindow.hpp"
#include "window/wayland/WaylandInput.hpp"
#include <sys/mman.h>
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<int>(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<char*>(
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<uint32_t>(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_compositor*>(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<xdg_wm_base*>(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_seat*>(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_data_device_manager*>(
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<wp_cursor_shape_manager_v1*>(
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<zwp_pointer_constraints_v1*>(
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<zwp_relative_pointer_manager_v1*>(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<zwp_idle_inhibit_manager_v1*>(
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<zxdg_decoration_manager_v1*>(
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();
}
}
}

View file

@ -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
);

View file

@ -0,0 +1,188 @@
#include "window/wayland/WaylandSettings.hpp"
#include "window/wayland/WaylandCommon.hpp"
#include <cstring>
#ifdef VOXELCORE_SDBUS
#include <systemd/sd-bus.h>
#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<Impl*>(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
}

View file

@ -0,0 +1,22 @@
#pragma once
#include <string>
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;
};

View file

@ -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<size_t>((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<const uint32_t*>(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<ImageData> 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<ubyte[]>(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<GLenum>(readBuffer));
return std::make_unique<ImageData>(
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<float>(surface.x),
static_cast<float>(surface.y)
);
glUniform4f(
shadowUniforms[1],
static_cast<float>(margin),
static_cast<float>(margin),
static_cast<float>(size.x),
static_cast<float>(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<WaylandWindow*>(data)->onFrameDone();
};
return value;
}();
return listener;
}
double WaylandWindow::now() {
return waylandNow();
}

View file

@ -0,0 +1,223 @@
#pragma once
#include "window/wayland/WaylandCommon.hpp"
#include <algorithm>
#include "window/wayland/WaylandSettings.hpp"
#include "window/wayland/WaylandInput.hpp"
#include "graphics/core/ImageData.hpp"
#include "window/Window.hpp"
#include <EGL/egl.h>
#include <string>
#include <vector>
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<DecorationButton> leftButtons;
std::vector<DecorationButton> rightButtons;
std::vector<DecorationButtonLayout> 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<DecorationButtonLayout>& 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<ImageData> 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();
};

View file

@ -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

View file

@ -0,0 +1,162 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="cursor_shape_v1">
<copyright>
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.
</copyright>
<interface name="wp_cursor_shape_manager_v1" version="2">
<description summary="cursor shape manager">
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.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the manager">
Destroy the cursor shape manager.
</description>
</request>
<request name="get_pointer">
<description summary="manage the cursor shape of a pointer device">
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.
</description>
<arg name="cursor_shape_device" type="new_id" interface="wp_cursor_shape_device_v1"/>
<arg name="pointer" type="object" interface="wl_pointer"/>
</request>
<request name="get_tablet_tool_v2">
<description summary="manage the cursor shape of a tablet tool device">
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.
</description>
<arg name="cursor_shape_device" type="new_id" interface="wp_cursor_shape_device_v1"/>
<arg name="tablet_tool" type="object" interface="zwp_tablet_tool_v2"/>
</request>
</interface>
<interface name="wp_cursor_shape_device_v1" version="2">
<description summary="cursor shape for a device">
This interface allows clients to set the cursor shape.
</description>
<enum name="shape">
<description summary="cursor shapes">
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.
</description>
<entry name="default" value="1" summary="default cursor"/>
<entry name="context_menu" value="2" summary="a context menu is available for the object under the cursor"/>
<entry name="help" value="3" summary="help is available for the object under the cursor"/>
<entry name="pointer" value="4" summary="pointer that indicates a link or another interactive element"/>
<entry name="progress" value="5" summary="progress indicator"/>
<entry name="wait" value="6" summary="program is busy, user should wait"/>
<entry name="cell" value="7" summary="a cell or set of cells may be selected"/>
<entry name="crosshair" value="8" summary="simple crosshair"/>
<entry name="text" value="9" summary="text may be selected"/>
<entry name="vertical_text" value="10" summary="vertical text may be selected"/>
<entry name="alias" value="11" summary="drag-and-drop: alias of/shortcut to something is to be created"/>
<entry name="copy" value="12" summary="drag-and-drop: something is to be copied"/>
<entry name="move" value="13" summary="drag-and-drop: something is to be moved"/>
<entry name="no_drop" value="14" summary="drag-and-drop: the dragged item cannot be dropped at the current cursor location"/>
<entry name="not_allowed" value="15" summary="drag-and-drop: the requested action will not be carried out"/>
<entry name="grab" value="16" summary="drag-and-drop: something can be grabbed"/>
<entry name="grabbing" value="17" summary="drag-and-drop: something is being grabbed"/>
<entry name="e_resize" value="18" summary="resizing: the east border is to be moved"/>
<entry name="n_resize" value="19" summary="resizing: the north border is to be moved"/>
<entry name="ne_resize" value="20" summary="resizing: the north-east corner is to be moved"/>
<entry name="nw_resize" value="21" summary="resizing: the north-west corner is to be moved"/>
<entry name="s_resize" value="22" summary="resizing: the south border is to be moved"/>
<entry name="se_resize" value="23" summary="resizing: the south-east corner is to be moved"/>
<entry name="sw_resize" value="24" summary="resizing: the south-west corner is to be moved"/>
<entry name="w_resize" value="25" summary="resizing: the west border is to be moved"/>
<entry name="ew_resize" value="26" summary="resizing: the east and west borders are to be moved"/>
<entry name="ns_resize" value="27" summary="resizing: the north and south borders are to be moved"/>
<entry name="nesw_resize" value="28" summary="resizing: the north-east and south-west corners are to be moved"/>
<entry name="nwse_resize" value="29" summary="resizing: the north-west and south-east corners are to be moved"/>
<entry name="col_resize" value="30" summary="resizing: that the item/column can be resized horizontally"/>
<entry name="row_resize" value="31" summary="resizing: that the item/row can be resized vertically"/>
<entry name="all_scroll" value="32" summary="something can be scrolled in any direction"/>
<entry name="zoom_in" value="33" summary="something can be zoomed in"/>
<entry name="zoom_out" value="34" summary="something can be zoomed out"/>
<entry name="dnd_ask" value="35" summary="drag-and-drop: the user will select which action will be carried out (non-css value)" since="2"/>
<entry name="all_resize" value="36" summary="resizing: something can be moved or resized in any direction (non-css value)" since="2"/>
</enum>
<enum name="error">
<entry name="invalid_shape" value="1"
summary="the specified shape value is invalid"/>
</enum>
<request name="destroy" type="destructor">
<description summary="destroy the cursor shape device">
Destroy the cursor shape device.
The device cursor shape remains unchanged.
</description>
</request>
<request name="set_shape">
<description summary="set device cursor to the shape">
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.
</description>
<arg name="serial" type="uint" summary="serial number of the enter event"/>
<arg name="shape" type="uint" enum="shape"/>
</request>
</interface>
</protocol>

View file

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="idle_inhibit_unstable_v1">
<copyright>
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.
</copyright>
<interface name="zwp_idle_inhibit_manager_v1" version="1">
<description summary="control behavior when display idles">
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.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the idle inhibitor object">
Destroy the inhibit manager.
</description>
</request>
<request name="create_inhibitor">
<description summary="create a new inhibitor object">
Create a new inhibitor object associated with the given surface.
</description>
<arg name="id" type="new_id" interface="zwp_idle_inhibitor_v1"/>
<arg name="surface" type="object" interface="wl_surface"
summary="the surface that inhibits the idle behavior"/>
</request>
</interface>
<interface name="zwp_idle_inhibitor_v1" version="1">
<description summary="context object for inhibiting idle behavior">
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.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the idle inhibitor object">
Remove the inhibitor effect from the associated wl_surface.
</description>
</request>
</interface>
</protocol>

View file

@ -0,0 +1,334 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="pointer_constraints_unstable_v1">
<copyright>
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.
</copyright>
<description summary="protocol for constraining pointer motions">
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.
</description>
<interface name="zwp_pointer_constraints_v1" version="1">
<description summary="constrain the movement of a pointer">
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.
</description>
<enum name="error">
<description summary="wp_pointer_constraints error values">
These errors can be emitted in response to wp_pointer_constraints
requests.
</description>
<entry name="already_constrained" value="1"
summary="pointer constraint already requested on that surface"/>
</enum>
<enum name="lifetime">
<description summary="constraint lifetime">
These values represent different lifetime semantics. They are passed
as arguments to the factory requests to specify how the constraint
lifetimes should be managed.
</description>
<entry name="oneshot" value="1">
<description summary="the pointer constraint is defunct once deactivated">
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.
</description>
</entry>
<entry name="persistent" value="2">
<description summary="the pointer constraint may reactivate">
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.
</description>
</entry>
</enum>
<request name="destroy" type="destructor">
<description summary="destroy the pointer constraints manager object">
Used by the client to notify the server that it will no longer use this
pointer constraints object.
</description>
</request>
<request name="lock_pointer">
<description summary="lock pointer to a position">
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.
</description>
<arg name="id" type="new_id" interface="zwp_locked_pointer_v1"/>
<arg name="surface" type="object" interface="wl_surface"
summary="surface to lock pointer to"/>
<arg name="pointer" type="object" interface="wl_pointer"
summary="the pointer that should be locked"/>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
<arg name="lifetime" type="uint" enum="lifetime" summary="lock lifetime"/>
</request>
<request name="confine_pointer">
<description summary="confine pointer to a region">
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.
</description>
<arg name="id" type="new_id" interface="zwp_confined_pointer_v1"/>
<arg name="surface" type="object" interface="wl_surface"
summary="surface to lock pointer to"/>
<arg name="pointer" type="object" interface="wl_pointer"
summary="the pointer that should be confined"/>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
<arg name="lifetime" type="uint" enum="lifetime" summary="confinement lifetime"/>
</request>
</interface>
<interface name="zwp_locked_pointer_v1" version="1">
<description summary="receive relative pointer motion events">
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.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the locked pointer object">
Destroy the locked pointer object. If applicable, the compositor will
unlock the pointer.
</description>
</request>
<request name="set_cursor_position_hint">
<description summary="set the pointer cursor position hint">
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.
</description>
<arg name="surface_x" type="fixed"
summary="surface-local x coordinate"/>
<arg name="surface_y" type="fixed"
summary="surface-local y coordinate"/>
</request>
<request name="set_region">
<description summary="set a new lock region">
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.
</description>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
</request>
<event name="locked">
<description summary="lock activation event">
Notification that the pointer lock of the seat's pointer is activated.
</description>
</event>
<event name="unlocked">
<description summary="lock deactivation event">
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.
</description>
</event>
</interface>
<interface name="zwp_confined_pointer_v1" version="1">
<description summary="confined pointer object">
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.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the confined pointer object">
Destroy the confined pointer object. If applicable, the compositor will
unconfine the pointer.
</description>
</request>
<request name="set_region">
<description summary="set a new confine region">
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.
</description>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
</request>
<event name="confined">
<description summary="pointer confined">
Notification that the pointer confinement of the seat's pointer is
activated.
</description>
</event>
<event name="unconfined">
<description summary="pointer unconfined">
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.
</description>
</event>
</interface>
</protocol>

View file

@ -0,0 +1,136 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="relative_pointer_unstable_v1">
<copyright>
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.
</copyright>
<description summary="protocol for relative pointer motion events">
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.
</description>
<interface name="zwp_relative_pointer_manager_v1" version="1">
<description summary="get relative pointer objects">
A global interface used for getting the relative pointer object for a
given pointer.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the relative pointer manager object">
Used by the client to notify the server that it will no longer use this
relative pointer manager object.
</description>
</request>
<request name="get_relative_pointer">
<description summary="get a relative pointer object">
Create a relative pointer interface given a wl_pointer object. See the
wp_relative_pointer interface for more details.
</description>
<arg name="id" type="new_id" interface="zwp_relative_pointer_v1"/>
<arg name="pointer" type="object" interface="wl_pointer"/>
</request>
</interface>
<interface name="zwp_relative_pointer_v1" version="1">
<description summary="relative pointer object">
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.
</description>
<request name="destroy" type="destructor">
<description summary="release the relative pointer object"/>
</request>
<event name="relative_motion">
<description summary="relative pointer motion">
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.
</description>
<arg name="utime_hi" type="uint"
summary="high 32 bits of a 64 bit timestamp with microsecond granularity"/>
<arg name="utime_lo" type="uint"
summary="low 32 bits of a 64 bit timestamp with microsecond granularity"/>
<arg name="dx" type="fixed"
summary="the x component of the motion vector"/>
<arg name="dy" type="fixed"
summary="the y component of the motion vector"/>
<arg name="dx_unaccel" type="fixed"
summary="the x component of the unaccelerated motion vector"/>
<arg name="dy_unaccel" type="fixed"
summary="the y component of the unaccelerated motion vector"/>
</event>
</interface>
</protocol>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,176 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="xdg_decoration_unstable_v1">
<copyright>
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.
</copyright>
<interface name="zxdg_decoration_manager_v1" version="2">
<description summary="window decoration manager">
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.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the decoration manager object">
Destroy the decoration manager. This doesn't destroy objects created
with the manager.
</description>
</request>
<request name="get_toplevel_decoration">
<description summary="create a new toplevel decoration object">
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.
</description>
<arg name="id" type="new_id" interface="zxdg_toplevel_decoration_v1"/>
<arg name="toplevel" type="object" interface="xdg_toplevel"/>
</request>
</interface>
<interface name="zxdg_toplevel_decoration_v1" version="2">
<description summary="decoration object for a toplevel surface">
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.
</description>
<enum name="error">
<entry name="unconfigured_buffer" value="0"
summary="xdg_toplevel has a buffer attached before configure"/>
<entry name="already_constructed" value="1"
summary="xdg_toplevel already has a decoration object"/>
<entry name="orphaned" value="2"
summary="xdg_toplevel destroyed before the decoration object"/>
<entry name="invalid_mode" value="3" summary="invalid mode"/>
</enum>
<request name="destroy" type="destructor">
<description summary="destroy the decoration object">
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.
</description>
</request>
<enum name="mode">
<description summary="window decoration modes">
These values describe window decoration modes.
</description>
<entry name="client_side" value="1"
summary="no server-side window decoration"/>
<entry name="server_side" value="2"
summary="server-side window decoration"/>
</enum>
<request name="set_mode">
<description summary="set the decoration mode">
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.
</description>
<arg name="mode" type="uint" enum="mode" summary="the decoration mode"/>
</request>
<request name="unset_mode">
<description summary="unset the decoration mode">
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.
</description>
</request>
<event name="configure">
<description summary="notify a decoration mode change">
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.
</description>
<arg name="mode" type="uint" enum="mode" summary="the decoration mode"/>
</event>
</interface>
</protocol>

File diff suppressed because it is too large Load diff