Draw the window title bar by the engine

The native Wayland backend had no window controls: no title, no close
button, no way to move or resize the window, and the fullscreen toggle
could throw the window to another monitor. GNOME does not implement
zxdg_decoration_manager_v1, so there is nobody to draw a frame for us:
the backend now falls back to its own decorations when the compositor
offers no server side ones, and the engine draws the visible part.

The bar itself is drawn by the engine (WindowBar.cpp) through the usual
batch and font, so it uses the same assets as the rest of the UI and the
backend only owns the behaviour: hit zones, cursor shapes, click
interception and the xdg-shell requests. Its geometry follows the
desktop's button layout, read and subscribed through
xdg-desktop-portal over sd-bus (libsystemd is an optional dependency,
gsettings is only a startup fallback).

Controls behave like they do elsewhere:
- pressing anywhere on the bar starts a move once the pointer leaves a
  5 px radius, so dragging works from the buttons as well;
- a button acts on release, only if the pointer stayed on it;
- a double click on the bar toggles maximize;
- the top edge and the top corners resize, the top 8 px of the sides,
  the sides and the bottom are 8 px wide resize strips;
- right and middle clicks and the scroll wheel over the bar never reach
  the game.

The in-game user interface is offset below the bar while menus keep the
whole window, so the translucent bar shows the menu background through
itself and never covers the HUD. The HUD lays its elements out against
the content height and the cursor is translated once, which fixes items
following the mouse one row above the pointer in game.

The window size is now written to the settings when the window is
resized in windowed mode and applied on the first configure, so the
window opens with the size it was left with, and leaving fullscreen or
borderless mode restores it instead of overwriting the settings with the
fullscreen size (an unconditional unmaximize made the compositor restore
the maximized geometry).

Measured: menu layout unchanged (706 bright pixels in the same place),
gui viewport 1123x751 in menus against 1123x721 in game, 1123x751 ->
2560x1080 -> 1123x751 round trip keeps the settings, a saved 1000x640
opens as 1000x640, no errors in the log.
This commit is contained in:
alexei-zebra 2026-10-09 20:56:55 +03:00
parent 4731ac0706
commit 6c2192b5d8
No known key found for this signature in database
GPG key ID: D19D450AC3D9A80E
14 changed files with 685 additions and 94 deletions

View file

@ -84,6 +84,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND)
pkg_check_modules(egl IMPORTED_TARGET egl) pkg_check_modules(egl IMPORTED_TARGET egl)
find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1) find_library(WAYLAND_EGL_LIBRARY NAMES wayland-egl libwayland-egl.so.1)
find_program(WAYLAND_SCANNER wayland-scanner) find_program(WAYLAND_SCANNER wayland-scanner)
pkg_check_modules(libsystemd IMPORTED_TARGET libsystemd)
if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND if(NOT wayland-client_FOUND OR NOT xkbcommon_FOUND OR NOT egl_FOUND
OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER) OR NOT WAYLAND_EGL_LIBRARY OR NOT WAYLAND_SCANNER)
@ -128,6 +129,13 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND)
VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources})
target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED})
target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1)
if(libsystemd_FOUND)
target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_SDBUS=1)
target_link_libraries(VoxelCoreSrc PRIVATE PkgConfig::libsystemd)
message(STATUS "Wayland backend: sd-bus settings are on")
else()
message(STATUS "Wayland backend: sd-bus settings are off")
endif()
target_link_libraries( target_link_libraries(
VoxelCoreSrc VoxelCoreSrc
PRIVATE PkgConfig::wayland-client PRIVATE PkgConfig::wayland-client

View file

@ -1,4 +1,9 @@
#include <algorithm>
#include <GL/glew.h>
#include "Engine.hpp" #include "Engine.hpp"
#include "frontend/screens/MenuScreen.hpp"
#include "WindowBar.hpp" #include "WindowBar.hpp"
#ifndef GLEW_STATIC #ifndef GLEW_STATIC
@ -310,9 +315,20 @@ void Engine::renderFrame() {
if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) {
input->toggleCursor(); input->toggleCursor();
} }
glViewport(
0,
0,
static_cast<GLsizei>(window->getSize().x),
static_cast<GLsizei>(window->getSize().y)
);
screen->draw(time.getDelta()); screen->draw(time.getDelta());
DrawContext ctx(nullptr, *window, nullptr); DrawContext ctx(nullptr, *window, nullptr);
gui->setContentInset(
dynamic_cast<const MenuScreen*>(screen.get()) != nullptr
? 0
: window->getDecorationHeight()
);
gui->draw(ctx, *assets->getStorage()); gui->draw(ctx, *assets->getStorage());
draw_window_bar(*this); draw_window_bar(*this);
} }

View file

@ -1,12 +1,18 @@
#include "WindowBar.hpp" #include "WindowBar.hpp"
#include "Engine.hpp" #include "Engine.hpp"
#include "debug/Logger.hpp"
#include "graphics/core/Batch2D.hpp" #include "graphics/core/Batch2D.hpp"
#include <GL/glew.h>
#include <glm/gtc/matrix_transform.hpp>
#include "graphics/core/Shader.hpp"
#include "graphics/core/Font.hpp" #include "graphics/core/Font.hpp"
#include "graphics/ui/GUI.hpp" #include "graphics/ui/GUI.hpp"
#include "window/Window.hpp" #include "window/Window.hpp"
#include "assets/Assets.hpp" #include "assets/Assets.hpp"
#include <algorithm>
#include <string_view>
#include <codecvt> #include <codecvt>
#include <locale> #include <locale>
@ -33,46 +39,85 @@ void draw_window_bar(Engine& engine) {
const auto size = window.getSize(); const auto size = window.getSize();
const float barHeight = static_cast<float>(height); const float barHeight = static_cast<float>(height);
glViewport(0, 0, static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y));
if (auto shader = engine.requireAssets().get<Shader>("ui"); 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->begin();
batch->setColor(glm::vec4(0.0f, 0.0f, 0.0f, 0.82f)); batch->setColor(glm::vec4(0.0f, 0.0f, 0.0f, 0.82f));
batch->rect(0.0f, 0.0f, size.x, barHeight); batch->rect(0.0f, 0.0f, size.x, barHeight);
batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.10f));
batch->rect(0.0f, barHeight - 1.0f, size.x, 1.0f);
const std::wstring title = to_wide(window.getTitle()); const auto& buttons = window.getDecorationButtons();
const int textX = static_cast<int>(barHeight * 0.4f);
const int textY = (height - font->getLineHeight()) / 2;
batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f));
font->draw(*batch, title, textX, textY, nullptr, 0);
batch->untexture();
const float button = barHeight;
const int hovered = window.getDecorationHoveredButton(); const int hovered = window.getDecorationHoveredButton();
for (int i = 0; i < 3; i++) {
const float x = size.x - button * (i + 1); float titleLeft = static_cast<float>(barHeight * 0.4f);
const float cx = x + button * 0.5f; float titleRight = size.x - 8.0f;
const float cy = barHeight * 0.5f; for (const auto& item : buttons) {
if (hovered == i) { if (item.x + item.width * 0.5f < size.x * 0.5f) {
batch->setColor( titleLeft = std::max(titleLeft, item.x + item.width + 8.0f);
i == 0 ? glm::vec4(0.62f, 0.13f, 0.09f, 0.9f) } else {
: glm::vec4(1.0f, 1.0f, 1.0f, 0.16f) titleRight = std::min(titleRight, item.x - 8.0f);
);
batch->rect(x, 0.0f, button, barHeight - 1.0f);
} }
const float ink = hovered == i ? 1.0f : 0.8f; }
const float thickness = 2.0f; const std::wstring title = to_wide(window.getTitle());
const float available = std::max(0.0f, titleRight - titleLeft);
size_t titleLength = title.size();
while (titleLength > 0 && font->calcWidth(title, titleLength) > available) {
titleLength--;
}
if (titleLength > 0) {
batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.85f));
font->draw(
*batch, std::wstring_view(title).substr(0, titleLength),
static_cast<int>(titleLeft),
(height - font->getLineHeight()) / 2,
nullptr, 0
);
batch->untexture();
}
const float thickness = 2.0f;
for (size_t i = 0; i < buttons.size(); i++) {
const auto& item = buttons[i];
const float x = item.x;
const float cx = x + item.width * 0.5f;
const float cy = barHeight * 0.5f;
const bool isHovered = hovered == static_cast<int>(i);
if (isHovered) {
batch->setColor(
item.button == DecorationButton::CLOSE
? glm::vec4(0.62f, 0.13f, 0.09f, 0.9f)
: glm::vec4(1.0f, 1.0f, 1.0f, 0.16f)
);
batch->rect(x, 0.0f, item.width, barHeight);
}
const float ink = isHovered ? 1.0f : 0.8f;
batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink)); batch->setColor(glm::vec4(1.0f, 1.0f, 1.0f, ink));
if (i == 0) { if (item.button == DecorationButton::CLOSE) {
for (int s = 0; s < 8; s++) { for (int step = 0; step < 8; step++) {
batch->rect(cx - 5.0f + s, cy - 5.0f + s, thickness, thickness); batch->rect(cx - 5.0f + step, cy - 5.0f + step, thickness, thickness);
batch->rect(cx + 3.0f - s, cy - 5.0f + s, thickness, thickness); batch->rect(cx + 3.0f - step, cy - 5.0f + step, thickness, thickness);
} }
} else if (i == 1 && !window.isMaximized()) { } else if (item.button == DecorationButton::MINIMIZE) {
batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness);
} else if (!window.isMaximized()) {
batch->rect(cx - 6.0f, cy - 6.0f, 12.0f, thickness); batch->rect(cx - 6.0f, cy - 6.0f, 12.0f, thickness);
batch->rect(cx - 6.0f, cy + 4.0f, 12.0f, thickness); batch->rect(cx - 6.0f, cy + 4.0f, 12.0f, thickness);
batch->rect(cx - 6.0f, cy - 6.0f, thickness, 12.0f); batch->rect(cx - 6.0f, cy - 6.0f, thickness, 12.0f);
batch->rect(cx + 4.0f, cy - 6.0f, thickness, 12.0f); batch->rect(cx + 4.0f, cy - 6.0f, thickness, 12.0f);
} else if (i == 1) { } else {
batch->rect(cx - 7.0f, cy + 1.0f, 11.0f, thickness); batch->rect(cx - 7.0f, cy + 1.0f, 11.0f, thickness);
batch->rect(cx - 7.0f, cy + 1.0f, thickness, 6.0f); batch->rect(cx - 7.0f, cy + 1.0f, thickness, 6.0f);
batch->rect(cx + 2.0f, cy + 1.0f, thickness, 6.0f); batch->rect(cx + 2.0f, cy + 1.0f, thickness, 6.0f);
@ -80,8 +125,6 @@ void draw_window_bar(Engine& engine) {
batch->rect(cx - 2.0f, cy - 5.0f, 9.0f, thickness); batch->rect(cx - 2.0f, cy - 5.0f, 9.0f, thickness);
batch->rect(cx - 2.0f, cy - 5.0f, thickness, 6.0f); batch->rect(cx - 2.0f, cy - 5.0f, thickness, 6.0f);
batch->rect(cx + 5.0f, cy - 5.0f, thickness, 6.0f); batch->rect(cx + 5.0f, cy - 5.0f, thickness, 6.0f);
} else {
batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness);
} }
} }
batch->flush(); batch->flush();

View file

@ -625,8 +625,9 @@ void Hud::setDebug(bool flag) {
void Hud::draw(const DrawContext& ctx){ void Hud::draw(const DrawContext& ctx){
const auto& viewport = ctx.getViewport(); const auto& viewport = ctx.getViewport();
uint inset = static_cast<uint>(ctx.getWindow().getDecorationHeight());
updateElementsPosition(viewport); updateElementsPosition(glm::uvec2(viewport.x, viewport.y - inset));
uicamera->setFov(viewport.y); uicamera->setFov(viewport.y);
uicamera->setAspectRatio(viewport.x / static_cast<float>(viewport.y)); uicamera->setAspectRatio(viewport.x / static_cast<float>(viewport.y));
@ -698,7 +699,7 @@ void Hud::updateElementsPosition(const glm::uvec2& viewport) {
} }
} }
if (exchangeSlot != nullptr) { if (exchangeSlot != nullptr) {
exchangeSlot->setPos(input.getCursor().pos); exchangeSlot->setPos(gui.getCursorPosition());
} }
hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65));
hotbarView->setSelected(player.getChosenSlot()); hotbarView->setSelected(player.getChosenSlot());

View file

@ -36,6 +36,10 @@ public:
Batch2D* getBatch2D() const; Batch2D* getBatch2D() const;
const glm::uvec2& getViewport() const; const glm::uvec2& getViewport() const;
Window& getWindow() const {
return window;
}
[[nodiscard]] DrawContext sub(Flushable* flushable=nullptr) const; [[nodiscard]] DrawContext sub(Flushable* flushable=nullptr) const;
void setViewport(const glm::uvec2& viewport); void setViewport(const glm::uvec2& viewport);

View file

@ -109,7 +109,7 @@ void GUI::updateTooltip(float delta) {
tooltip->setVisible(true); tooltip->setVisible(true);
label->setText(langs::get(text)); label->setText(langs::get(text));
auto size = label->getSize() + glm::vec2(4.0f); 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(); auto rootSize = container->getSize();
pos.x = glm::min(pos.x, rootSize.x - size.x); pos.x = glm::min(pos.x, rootSize.x - size.x);
pos.y = glm::min(pos.y, rootSize.y - size.y); pos.y = glm::min(pos.y, rootSize.y - size.y);
@ -242,7 +242,9 @@ void GUI::actFocused() {
} }
void GUI::act(float delta, const glm::uvec2& vp) { void GUI::act(float delta, const glm::uvec2& vp) {
container->setSize(vp); const uint inset = static_cast<uint>(viewportOffset);
container->setPos({0.0f, static_cast<float>(inset)});
container->setSize({vp.x, vp.y > inset ? vp.y - inset : vp.y});
for (auto& pair : frames) { for (auto& pair : frames) {
pair.second->act(delta); pair.second->act(delta);
} }
@ -276,6 +278,11 @@ void GUI::postAct() {
focusedOnStart = focus.get(); 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) { void GUI::draw(const DrawContext& pctx, Assets& assets) {
auto ctx = pctx.sub(batch2D.get()); auto ctx = pctx.sub(batch2D.get());

View file

@ -123,6 +123,16 @@ namespace gui {
/// @param assets active assets storage /// @param assets active assets storage
void draw(const DrawContext& pctx, Assets& assets); void draw(const DrawContext& pctx, Assets& assets);
int viewportOffset = 0;
/// @brief Get the cursor position in the main container coordinates
glm::vec2 getCursorPosition() const;
/// @brief Shift the main container down by the given number of pixels
void setContentInset(int inset) {
viewportOffset = inset;
}
Batch2D* getBatch2D() { Batch2D* getBatch2D() {
return batch2D.get(); return batch2D.get();
} }

View file

@ -2,6 +2,8 @@
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <memory> #include <memory>
#include <string>
#include <vector>
#include "graphics/core/commons.hpp" #include "graphics/core/commons.hpp"
#include "typedefs.hpp" #include "typedefs.hpp"
@ -10,6 +12,18 @@ class ImageData;
class Input; class Input;
struct DisplaySettings; struct DisplaySettings;
enum class DecorationButton {
CLOSE,
MINIMIZE,
MAXIMIZE,
};
struct DecorationButtonLayout {
DecorationButton button;
float x;
float width;
};
enum class WindowMode { enum class WindowMode {
WINDOWED, WINDOWED,
FULLSCREEN, FULLSCREEN,
@ -57,6 +71,11 @@ public:
return -1; return -1;
} }
virtual const std::vector<DecorationButtonLayout>& getDecorationButtons() const {
static const std::vector<DecorationButtonLayout> empty;
return empty;
}
virtual bool isIconSupported() const = 0; virtual bool isIconSupported() const = 0;
virtual void setIcon(const ImageData* image) = 0; virtual void setIcon(const ImageData* image) = 0;

View file

@ -2,9 +2,172 @@
#include "settings.hpp" #include "settings.hpp"
static constexpr int BAR_HEIGHT = 30; #include <algorithm>
static constexpr int BAR_BUTTON = 30; #include <cmath>
static constexpr int BAR_EDGE = 5; #include <csignal>
#include <cstdio>
#include <sys/wait.h>
#include <unistd.h>
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;
}
bool read_button_layout(
std::vector<DecorationButton>& left, std::vector<DecorationButton>& right
) {
FILE* pipe = popen(
"gsettings get org.gnome.desktop.wm.preferences button-layout"
" 2>/dev/null",
"r"
);
if (pipe == nullptr) {
return false;
}
char buffer[256] {};
const char* line = fgets(buffer, sizeof(buffer), pipe);
const int status = pclose(pipe);
if (line == nullptr || status != 0) {
return false;
}
std::string value(buffer);
value.erase(
std::remove_if(value.begin(), value.end(), [] (char c) {
return c == '\'' || c == '"' || c == '\n' || c == '\r';
}),
value.end()
);
const size_t separator = value.find(':');
if (separator == std::string::npos) {
left.clear();
right = parse_buttons(value);
} else {
left = parse_buttons(value.substr(0, separator));
right = parse_buttons(value.substr(separator + 1));
}
return true;
}
constexpr double DRAG_THRESHOLD = 5.0;
constexpr double DOUBLE_CLICK_TIME = 0.4;
constexpr double DOUBLE_CLICK_DISTANCE = 8.0;
}
void WaylandWindow::applyLayoutValue(const std::string& rawValue) {
std::string value = rawValue;
value.erase(
std::remove_if(value.begin(), value.end(), [] (char c) {
return c == '\'' || c == '"' || c == '\n' || c == '\r';
}),
value.end()
);
const size_t separator = value.find(':');
std::vector<DecorationButton> left;
std::vector<DecorationButton> right;
if (separator == std::string::npos) {
right = parse_buttons(value);
} else {
left = parse_buttons(value.substr(0, separator));
right = parse_buttons(value.substr(separator + 1));
}
if (left == leftButtons && right == rightButtons) {
return;
}
leftButtons = std::move(left);
rightButtons = std::move(right);
updateBarGeometry();
setShouldRefresh();
}
void WaylandWindow::updateButtonLayout() {
if (!layoutRead) {
layoutRead = true;
std::string initial;
if (settingsWatcher.read(LAYOUT_SCHEMA, LAYOUT_KEY, initial)) {
applyLayoutValue(initial);
} else {
std::vector<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 < 2.0) {
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() {
barButtons.clear();
const float width = static_cast<float>(size.x);
for (size_t i = 0; i < leftButtons.size(); i++) {
const float x = static_cast<float>(i) * BAR_BUTTON;
if (x + BAR_BUTTON > width) {
break;
}
barButtons.push_back({leftButtons[i], x, BAR_BUTTON});
}
for (size_t i = 0; i < rightButtons.size(); i++) {
const float x = width -
static_cast<float>(rightButtons.size() - i) * BAR_BUTTON;
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 { const std::string& WaylandWindow::getTitle() const {
return title; return title;
} }
@ -33,27 +196,34 @@ int WaylandWindow::barButtonAt(double x, double y) const {
if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) { if (!barVisible() || y < 0.0 || y >= BAR_HEIGHT) {
return -1; return -1;
} }
for (int i = 0; i < 3; i++) { for (size_t i = 0; i < barButtons.size(); i++) {
const double bx = size.x - BAR_BUTTON * (i + 1); const auto& item = barButtons[i];
if (x >= bx && x < bx + BAR_BUTTON) { if (x >= item.x && x < item.x + item.width) {
return i; return static_cast<int>(i);
} }
} }
return -1; return -1;
} }
uint32_t WaylandWindow::barEdgeAt(double x, double y) const { uint32_t WaylandWindow::barEdgeAt(double x, double y) const {
if (barButtonAt(x, y) >= 0) {
return 0;
}
const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT;
uint32_t edges = 0; 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) { if (x < BAR_EDGE) {
edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT; edges |= XDG_TOPLEVEL_RESIZE_EDGE_LEFT;
} else if (x >= size.x - BAR_EDGE) { } else if (x >= size.x - BAR_EDGE) {
edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT; edges |= XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;
} }
if (barVisible() && y < BAR_EDGE) {
edges |= XDG_TOPLEVEL_RESIZE_EDGE_TOP;
} else if (y >= size.y - BAR_EDGE) {
edges |= XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;
}
return edges; return edges;
} }
@ -80,61 +250,110 @@ CursorShape WaylandWindow::edgeCursor(uint32_t edges) {
bool WaylandWindow::handleBarMotion(double x, double y) { bool WaylandWindow::handleBarMotion(double x, double y) {
pointerX = x; pointerX = x;
pointerY = y; pointerY = y;
const int button = barButtonAt(x, y); if (barPressed && !barDragging &&
if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) { (std::abs(x - barPressX) > DRAG_THRESHOLD ||
hoveredButton = button; std::abs(y - barPressY) > DRAG_THRESHOLD)) {
barDragging = true;
hoveredButton = -1;
xdg_toplevel_move(state.toplevel, state.seat, barPressSerial);
}
const uint32_t edges = barEdgeAt(x, y);
if (edges != 0) {
hoveredButton = -1;
pointerInBar = false;
input.setOverrideCursor(edgeCursor(edges));
return true;
}
const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT;
if (inBar && !pointerInBar) {
lastLayoutCheck = 0.0;
}
pointerInBar = inBar;
if (inBar) {
hoveredButton = barDragging ? -1 : barButtonAt(x, y);
input.setOverrideCursor( input.setOverrideCursor(
button >= 0 ? CursorShape::POINTER : CursorShape::ARROW hoveredButton >= 0 ? CursorShape::POINTER : CursorShape::ARROW
); );
return true; return true;
} }
hoveredButton = -1; hoveredButton = -1;
const uint32_t edges = barEdgeAt(x, y); input.setOverrideCursor(std::nullopt);
input.setOverrideCursor(
edges != 0 ? std::optional<CursorShape>(edgeCursor(edges))
: std::nullopt
);
return false; return false;
} }
bool WaylandWindow::handleBarButton(uint32_t serial, bool pressed) { bool WaylandWindow::handleBarButton(uint32_t serial, int button, bool pressed) {
const double x = pointerX; const double x = pointerX;
const double y = pointerY; const double y = pointerY;
const int button = barButtonAt(x, y);
if (button >= 0) {
if (pressed) {
if (button == 0) {
setShouldClose(true);
} else if (button == 1) {
setMaximized(!maximized);
} else {
xdg_toplevel_set_minimized(state.toplevel);
}
}
return true;
}
if (barVisible() && y >= 0.0 && y < BAR_HEIGHT) {
if (pressed) {
const double current = now();
if (current - lastBarPress < 0.4) {
lastBarPress = 0.0;
setMaximized(!maximized);
} else {
lastBarPress = current;
xdg_toplevel_move(state.toplevel, state.seat, serial);
}
}
return true;
}
const uint32_t edges = barEdgeAt(x, y); const uint32_t edges = barEdgeAt(x, y);
if (pressed && edges != 0) { const bool inBar = barVisible() && y >= 0.0 && y < BAR_HEIGHT;
xdg_toplevel_resize(state.toplevel, state.seat, serial, edges); if (button != 0) {
return inBar || edges != 0;
}
if (edges != 0) {
if (pressed) {
xdg_toplevel_resize(state.toplevel, state.seat, serial, edges);
}
return true; return true;
} }
return false; if (!inBar) {
return false;
}
if (pressed) {
const double current = now();
const bool doubleClick =
current - lastBarPress < DOUBLE_CLICK_TIME &&
std::abs(x - lastBarPressX) < DOUBLE_CLICK_DISTANCE &&
std::abs(y - lastBarPressY) < DOUBLE_CLICK_DISTANCE;
lastBarPress = current;
lastBarPressX = x;
lastBarPressY = y;
if (doubleClick) {
lastBarPress = 0.0;
setMaximized(!maximized);
return true;
}
barPressed = true;
barDragging = false;
barPressedButton = barButtonAt(x, y);
barPressX = x;
barPressY = y;
barPressSerial = serial;
hoveredButton = barPressedButton;
return true;
}
const int releasedButton = barPressedButton;
const bool dragged = barDragging;
barPressed = false;
barDragging = false;
barPressedButton = -1;
if (!dragged && releasedButton >= 0 &&
releasedButton < static_cast<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 {
return (barVisible() && pointerY >= 0.0 && pointerY < BAR_HEIGHT) ||
barEdgeAt(pointerX, pointerY) != 0;
} }
void WaylandWindow::onPointerLeave() { void WaylandWindow::onPointerLeave() {
hoveredButton = -1; hoveredButton = -1;
pointerInBar = false;
barPressed = false;
barDragging = false;
barPressedButton = -1;
input.setOverrideCursor(std::nullopt); input.setOverrideCursor(std::nullopt);
} }

View file

@ -61,7 +61,7 @@ static void pointer_button(
case 0x117: index = 7; break; case 0x117: index = 7; break;
} }
const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED;
if (index == 0 && window && window->handleBarButton(serial, pressed)) { if (index >= 0 && window && window->handleBarButton(serial, index, pressed)) {
return; return;
} }
if (index >= 0 && input) { if (index >= 0 && input) {
@ -74,6 +74,9 @@ static void pointer_axis(
void*, wl_pointer*, uint32_t, uint32_t axis, wl_fixed_t value void*, wl_pointer*, uint32_t, uint32_t axis, wl_fixed_t value
) { ) {
if (input && axis == WL_POINTER_AXIS_VERTICAL_SCROLL) { if (input && axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {
if (window && window->handleBarScroll()) {
return;
}
input->scroll += wl_fixed_to_double(value) > 0 ? -1 : 1; input->scroll += wl_fixed_to_double(value) > 0 ? -1 : 1;
input->refreshWindow(); input->refreshWindow();
} }

View file

@ -0,0 +1,176 @@
#include "window/wayland/WaylandSettings.hpp"
#include "window/wayland/WaylandCommon.hpp"
#include <cstring>
#ifdef VOXELENGINE_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 VOXELENGINE_SDBUS
std::string readVariant(sd_bus_message* message) {
const char* contents = nullptr;
char type = 0;
if (sd_bus_message_peek_type(message, &type, &contents) < 0) {
return {};
}
if (type == 'v') {
if (sd_bus_message_enter_container(message, 'v', nullptr) < 0) {
return {};
}
const std::string result = readVariant(message);
sd_bus_message_exit_container(message);
return result;
}
if (type == 's') {
const char* text = nullptr;
if (sd_bus_message_read(message, "s", &text) < 0 || text == nullptr) {
return {};
}
return text;
}
return {};
}
#endif
}
struct SettingsWatcher::Impl {
#ifdef VOXELENGINE_SDBUS
sd_bus* bus = nullptr;
std::string changedKey;
std::string changedValue;
bool changed = false;
static int onSettingChanged(
sd_bus_message* message, void* userdata, sd_bus_error*
) {
auto* self = static_cast<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 (key != nullptr && !value.empty()) {
self->changedKey = key;
self->changedValue = value;
self->changed = true;
}
return 0;
}
#endif
};
SettingsWatcher::SettingsWatcher() : impl(new Impl()) {
open();
}
SettingsWatcher::~SettingsWatcher() {
close();
delete impl;
}
bool SettingsWatcher::open() {
#ifdef VOXELENGINE_SDBUS
if (impl->bus != nullptr) {
return true;
}
if (sd_bus_default_user(&impl->bus) < 0) {
impl->bus = nullptr;
return false;
}
sd_bus_match_signal(
impl->bus, nullptr, nullptr, PORTAL_PATH, PORTAL_INTERFACE,
"SettingChanged", &Impl::onSettingChanged, impl
);
return true;
#else
return false;
#endif
}
void SettingsWatcher::close() {
#ifdef VOXELENGINE_SDBUS
if (impl->bus != nullptr) {
sd_bus_flush_close_unref(impl->bus);
impl->bus = nullptr;
}
#endif
}
bool SettingsWatcher::isAvailable() const {
#ifdef VOXELENGINE_SDBUS
return impl->bus != nullptr;
#else
return false;
#endif
}
bool SettingsWatcher::read(
const char* schema, const char* key, std::string& value
) {
#ifdef VOXELENGINE_SDBUS
if (impl->bus == nullptr) {
return false;
}
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message* reply = nullptr;
const int result = sd_bus_call_method(
impl->bus, PORTAL_SERVICE, PORTAL_PATH, PORTAL_INTERFACE, "Read",
&error, &reply, "ss", schema, key
);
bool success = false;
if (result >= 0) {
if (sd_bus_message_enter_container(reply, 'v', nullptr) >= 0) {
const std::string text = readVariant(reply);
if (!text.empty()) {
value = text;
success = true;
}
sd_bus_message_exit_container(reply);
}
}
if (reply != nullptr) {
sd_bus_message_unref(reply);
}
sd_bus_error_free(&error);
return success;
#else
return false;
#endif
}
bool SettingsWatcher::poll(
const char* schema, const char* key, std::string& value
) {
#ifdef VOXELENGINE_SDBUS
if (impl->bus == nullptr) {
open();
return false;
}
sd_bus_message* message = nullptr;
int result = 0;
while ((result = sd_bus_process(impl->bus, &message)) > 0) {
if (message != nullptr) {
sd_bus_message_unref(message);
message = nullptr;
}
}
if (!impl->changed || impl->changedKey != key) {
return false;
}
impl->changed = false;
value = impl->changedValue;
(void)schema;
(void)key;
return true;
#else
return false;
#endif
}

View file

@ -0,0 +1,23 @@
#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();
bool handleMessage(const char* schema, const char* key, std::string& value);
struct Impl;
Impl* impl = nullptr;
};

View file

@ -1,5 +1,9 @@
#include "window/wayland/WaylandWindow.hpp" #include "window/wayland/WaylandWindow.hpp"
#include <csignal>
#include <sys/wait.h>
#include <unistd.h>
#include "settings.hpp" #include "settings.hpp"
#include "graphics/core/Texture.hpp" #include "graphics/core/Texture.hpp"
#include "util/platform.hpp" #include "util/platform.hpp"
@ -7,7 +11,11 @@
WaylandWindow::WaylandWindow( WaylandWindow::WaylandWindow(
WaylandInput& input, DisplaySettings* settings, int width, int height WaylandInput& input, DisplaySettings* settings, int width, int height
) )
: Window({width, height}), input(input), settings(settings) { : Window({width, height}),
input(input),
settings(settings),
initialWidth(width),
initialHeight(height) {
scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y);
} }
@ -184,9 +192,10 @@ void WaylandWindow::setMode(WindowMode mode) {
break; break;
case WindowMode::WINDOWED: case WindowMode::WINDOWED:
setFullscreen(false); setFullscreen(false);
setMaximized(false); if (maximized) {
setMaximized(false);
}
setIdleInhibit(false); setIdleInhibit(false);
resize(settings->width.get(), settings->height.get());
break; break;
} }
wl_surface_commit(state.surface); wl_surface_commit(state.surface);
@ -238,6 +247,11 @@ void WaylandWindow::resize(int width, int height) {
} }
glViewport(0, 0, width, height); glViewport(0, 0, width, height);
size = {width, height}; size = {width, height};
if (Window::mode == WindowMode::WINDOWED && !maximized) {
settings->width.set(width);
settings->height.set(height);
}
updateBarGeometry();
scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y);
} }
@ -264,11 +278,19 @@ void WaylandWindow::onConfigure(int32_t width, int32_t height, wl_array* states)
} }
void WaylandWindow::applyConfigure() { void WaylandWindow::applyConfigure() {
if (pendingWidth > 0 && pendingHeight > 0) {
resize(pendingWidth, pendingHeight);
}
maximized = stateMaximized; maximized = stateMaximized;
suspended = stateSuspended; suspended = stateSuspended;
if (pendingWidth > 0 && pendingHeight > 0) {
if (!configured && Window::mode == WindowMode::WINDOWED && !maximized &&
initialWidth > 0 && initialHeight > 0) {
pendingWidth = initialWidth;
pendingHeight = initialHeight;
}
resize(pendingWidth, pendingHeight);
}
if (stateActivated && !activated) {
lastLayoutCheck = 0.0;
}
activated = stateActivated; activated = stateActivated;
configured = true; configured = true;
setShouldRefresh(); setShouldRefresh();
@ -339,10 +361,10 @@ std::unique_ptr<ImageData> WaylandWindow::takeScreenshot() {
auto data = std::make_unique<ubyte[]>(size.x * size.y * 3); auto data = std::make_unique<ubyte[]>(size.x * size.y * 3);
glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get()); glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get());
glReadBuffer(static_cast<GLenum>(readBuffer));
return std::make_unique<ImageData>( return std::make_unique<ImageData>(
ImageFormat::RGB888, size.x, size.y, data.release() ImageFormat::RGB888, size.x, size.y, data.release()
); );
glReadBuffer(static_cast<GLenum>(readBuffer));
} }
void WaylandWindow::setFramerate(int framerate) { void WaylandWindow::setFramerate(int framerate) {
@ -471,6 +493,7 @@ void WaylandWindow::requestFrame() {
} }
void WaylandWindow::paceFrame() { void WaylandWindow::paceFrame() {
updateButtonLayout();
frameOnCallback = frameDone; frameOnCallback = frameDone;
if (lastSwapEnd > 0.0) { if (lastSwapEnd > 0.0) {
const double cost = now() - lastSwapEnd; const double cost = now() - lastSwapEnd;

View file

@ -1,6 +1,9 @@
#pragma once #pragma once
#include "window/wayland/WaylandCommon.hpp" #include "window/wayland/WaylandCommon.hpp"
#include <algorithm>
#include "window/wayland/WaylandSettings.hpp"
#include "window/wayland/WaylandInput.hpp" #include "window/wayland/WaylandInput.hpp"
#include "graphics/core/ImageData.hpp" #include "graphics/core/ImageData.hpp"
@ -37,7 +40,25 @@ bool barEnabled = false;
bool fullscreen = false; bool fullscreen = false;
std::string title = "VoxelCore"; std::string title = "VoxelCore";
int hoveredButton = -1; 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 lastBarPress = 0.0;
double lastBarPressX = 0.0;
double lastBarPressY = 0.0;
double barPressX = 0.0;
double barPressY = 0.0;
uint32_t barPressSerial = 0;
bool barPressed = false;
bool barDragging = false;
int barPressedButton = -1;
int initialWidth = 0;
int initialHeight = 0;
double pointerX = 0.0; double pointerX = 0.0;
double pointerY = 0.0; double pointerY = 0.0;
bool frameOnCallback = false; bool frameOnCallback = false;
@ -89,6 +110,23 @@ glm::vec4 scissorArea {};
int getDecorationHeight() const override; int getDecorationHeight() const override;
int getDecorationHoveredButton() const override; int getDecorationHoveredButton() const override;
static constexpr int BAR_HEIGHT = 30;
static constexpr int BAR_BUTTON = 30;
static constexpr int BAR_EDGE = 8;
int decorationOffset() const {
return barVisible() ? BAR_HEIGHT : 0;
}
const std::vector<DecorationButtonLayout>& getDecorationButtons() const override;
void updateButtonLayout();
void updateBarGeometry();
bool isIconSupported() const override { bool isIconSupported() const override {
return false; return false;
} }
@ -115,7 +153,8 @@ glm::vec4 scissorArea {};
uint32_t barEdgeAt(double x, double y) const; uint32_t barEdgeAt(double x, double y) const;
static CursorShape edgeCursor(uint32_t edges); static CursorShape edgeCursor(uint32_t edges);
bool handleBarMotion(double x, double y); bool handleBarMotion(double x, double y);
bool handleBarButton(uint32_t serial, bool pressed); bool handleBarButton(uint32_t serial, int button, bool pressed);
bool handleBarScroll() const;
void onPointerLeave(); void onPointerLeave();
void onFrameDone(); void onFrameDone();
void requestFrame(); void requestFrame();