diff --git a/AGENTS.consumer.md b/AGENTS.consumer.md index 506bb9d..1eef887 100644 --- a/AGENTS.consumer.md +++ b/AGENTS.consumer.md @@ -131,6 +131,7 @@ Heap-only: check `Device::rayTracingSupported`, or expect `std::runtime_error` f - `Window` events, `Event` unless noted: `onMouseMove` (then `currentMousePos`, `lastMousePos`, `mouseDelta`), `onMouseEnter` and `onMouseLeave` with `mouseInside` (native only: the DOM build declares the two events but never fires them, and has no `mouseInside`), `onMouseLeftClick`, `onMouseLeftHold`, `onMouseLeftRelease` and the right-button trio (`mouseLeftHeld`, `mouseRightHeld`), `onMouseScroll` (`Event`: whole detents, reinterpret the payload as `int32`, positive is wheel down, every backend normalised to one per notch), `onRawKeyDown`, `onRawKeyHold`, `onRawKeyUp` (`Event`, raw platform codes; `heldKeys`), `onTextInput` (`Event`, UTF-8; repeats are synthesised on Wayland), `onPreedit` and `onTextInputDelete` (input methods), `onTouchDown`, `onTouchMove`, `onTouchUp` (`Event`; the first finger also drives the pointer events), `onClose`, `onResize`, `onBeforeUpdate`, `onUpdate` (`Event`: `now`, `delta`). On Wayland `lastInputTime` is the compositor's `time` of the pointer, touch or scroll event a listener is being invoked for (milliseconds from an undefined base, wrapping at 2^32, set before the event fires; an event the compositor sends without a time — an enter and the move that follows it, a leave, a touch cancel and its release — keeps the last one's): a consumer that dates gestures — a fling's velocity, a tap against a long press — reads it instead of its own clock at dispatch, since events queued while the loop was busy keep the times they happened at. A listener that dispatches Wayland events itself (it makes a `Window`, or calls `Clipboard::GetText`) has them set it too, for itself from there on and for the listeners of its event that come after it. The other backends have no such member. On Wayland `activated` and `suspended` are what the compositor says of the window's place on the screen (xdg_toplevel's states: it counts as the active window; it is not ordinarily being repainted — covered by another window, say, or its outputs switched off for a screen lock — which a compositor with an xdg_wm_base older than version 6 never says), and `onToplevelState` fires after a configure changed either, with both already set. Which of the two a lock screen or another window in front changes is the compositor's choice, so the test for "the user is looking at this window" — is the message it shows read? — is `activated && !suspended`; by it a window that is visible but not the active one is not looked at. The constructor takes the first configure before a listener can be added: read the two once after it, then follow the event. Both are false until a configure sets them, which that first one need not do. The other backends have neither member. `onFrameOwed`, Wayland's too, is the cue of a resize for a window that draws on demand: see "A program, and what the loop does". - Keys: `Key(CrafterKeys::Space)` is `consteval` and folds to the platform's raw code (a Win32 scancode, a Linux keycode), so bindings stay portable in source and compare against `onRawKeyDown`'s `KeyCode` at runtime. Bindings serialised with `Input::BindingToString` are platform-specific. +- On Wayland a key's `onTextInput` comes from the compositor's keymap. Without one that loaded, keys still fire `onRawKeyDown` and `onRawKeyUp`, without text; a keymap that does not load, such as one of the `no_keymap` format or one the libxkbcommon the application runs with cannot compile, is ignored and leaves the one there was. `Device::xkb_keymap` and `Device::xkb_state` are that keymap and its state, for reading keysyms or modifiers yourself (the XKB keycode is the `KeyCode` plus 8): null until a keymap loads, and freed when the next one loads, so read them at each use and check for null. - `Input::Map`: `auto& jump = map.AddAction("Jump", Input::ActionType::Button);` (`Button`, `Axis1D`, `Vector2`), `jump.bindings = { Input::KeyBind{Key(CrafterKeys::Space)}, Input::GamepadButtonBind{id, Gamepad::Button::South} };` (also `MouseButtonBind`, `MouseScrollBind`, `MouseDeltaBind{scale}`, `GamepadAxisBind`, `GamepadStickBind{id, Gamepad::Stick::Left}`, `WASDBind{up, down, left, right}`), `map.Attach(window);`, and `map.Tick();` once per frame, after `Gamepad::Tick()`, which the loop runs before `onBeforeUpdate`. Every `Tick` recomputes the mouse delta and drains the scroll accumulator, and on Wayland `onBeforeUpdate` fires on every loop wake, so either tick from `onUpdate`, or tick in `onBeforeUpdate` and consume the delta and scroll actions in that same listener, as the Sponza example does. Read `action.pressed`, `value` or `vector2`, or subscribe to `onPerformed`, `onCanceled`, `onValueChanged`, `onVector2Changed`. `StartRebind(action, CaptureMask, callback)` captures the next input. - `Gamepad::connected`, `onConnected`, `onDisconnected`, per-device `buttons[]`, `axes[]` and events, `Rumble(dev, low, high, duration)`, `FindById(id)`; buttons are named by position (`South`, `East`, `West`, `North`). `Clipboard::SetText(text)` and `GetText()` (`std::optional`). diff --git a/AGENTS.template.md b/AGENTS.template.md index dc812ae..627774f 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -72,7 +72,7 @@ Tests are declared in `project.cpp`, not discovered, through the `LibraryTest(na A test is an `int main()`: exit 0 passes, nonzero fails, 77 skips (for a missing capability, never for a failed check). Each runs in its own process, in parallel, with a 60 s default timeout, and the output of a failed, crashed or timed-out test is in `build/test-logs/.log`; a later pass does not delete the log, so check its timestamp. What the tests need, in three groups: -- Pure logic, no GPU: they stage `Device`'s statics or feed synthetic data to the decision functions that were factored out for them (`Device::ResolveFeatures`, `ChooseDevice`, `CheckShaderCapabilities`, `GetMemoryType`, `PreferDirectDeviceWrite`, `PipelineCacheDataCompatible`, `AlignMappedFlushRange`, `BuildMipChainFinalBarriers`, `SwapchainStageUnion`, `BuildTlasWriteBarrier`, `UIRenderer::ClipFlags`, `Window::SwapchainMinImageCount`, `WorkaroundNvidiaAS::Patch`, `DescriptorHeapVulkan::ComputeLayout`, `FontAtlas::Packer`, the font and input-field helpers). `PushConstantRewrite` and `UIFusedShader` compile GLSL with glslang and check the SPIR-V with spirv-val at runtime, and `ExampleShaders` compiles every GLSL shader under `examples/` the way crafter-build would, the descriptor-set build included, so a shader contract change that breaks an example fails here without building the example; `FontAtlasDecode` reads `ui-shared.glsl` and `dom-webgpu.js` and holds their copies of the SDF encoding constants to `FontAtlas`'s; `MouseScroll`, `PointerEnterLeave` and `InputTime` drive the Wayland listener callbacks directly, `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair, `TextInputContent` reads the text input's the same way and feeds its callbacks, and `ToplevelState` does both: it feeds the `xdg_toplevel` and `xdg_surface` configure callbacks of a window whose surfaces are proxies on such a display, and reads the version `xdg_wm_base` is bound at off the wire. `ConfigureResize` does the same for a configure's size: with a made-up swapchain handle it steps the two ends of a frame (`TakeDeferredSize` and `MatchSizesToScale`, `SendFrameSurfaceState`) and reads which commit gets the viewport's destination and the acknowledgement, and what the destination is when the scale changes in between. +- Pure logic, no GPU: they stage `Device`'s statics or feed synthetic data to the decision functions that were factored out for them (`Device::ResolveFeatures`, `ChooseDevice`, `CheckShaderCapabilities`, `GetMemoryType`, `PreferDirectDeviceWrite`, `PipelineCacheDataCompatible`, `AlignMappedFlushRange`, `BuildMipChainFinalBarriers`, `SwapchainStageUnion`, `BuildTlasWriteBarrier`, `UIRenderer::ClipFlags`, `Window::SwapchainMinImageCount`, `WorkaroundNvidiaAS::Patch`, `DescriptorHeapVulkan::ComputeLayout`, `FontAtlas::Packer`, the font and input-field helpers). `PushConstantRewrite` and `UIFusedShader` compile GLSL with glslang and check the SPIR-V with spirv-val at runtime, and `ExampleShaders` compiles every GLSL shader under `examples/` the way crafter-build would, the descriptor-set build included, so a shader contract change that breaks an example fails here without building the example; `FontAtlasDecode` reads `ui-shared.glsl` and `dom-webgpu.js` and holds their copies of the SDF encoding constants to `FontAtlas`'s; `MouseScroll`, `PointerEnterLeave`, `InputTime` and `KeyboardKeymap` drive the Wayland listener callbacks directly (`KeyboardKeymap` with keymaps in memfds, each case in a child process), `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair, `TextInputContent` reads the text input's the same way and feeds its callbacks, and `ToplevelState` does both: it feeds the `xdg_toplevel` and `xdg_surface` configure callbacks of a window whose surfaces are proxies on such a display, and reads the version `xdg_wm_base` is bound at off the wire. `ConfigureResize` does the same for a configure's size: with a made-up swapchain handle it steps the two ends of a frame (`TakeDeferredSize` and `MatchSizesToScale`, `SendFrameSurfaceState`) and reads which commit gets the viewport's destination and the acknowledgement, and what the destination is when the scale changes in between. - A headless device: `Device::Initialize()` and no `Window` (`HeapSlotReuse`, `DeferredDeletion`, `MeshLifetime`, `ImageStagingRelease`, `BLASBuildOptions`, the `TLAS*` tests, ...). Headless still means a Wayland display on Linux. Most of the RT ones check `Device::rayTracingSupported` and return 77 without it; `BLASBuildOptions`, `TLASInstanceDirtyTracking` and `MeshDecompressStagingRelease` do not, and crash on a GPU without ray tracing (`Device::RequireRayTracing` throws out of `main`). `DeviceSelection` skips with one GPU. - A window and a live compositor: `FrameLoopSync`, `SetupCmdBufferReuse`, `UIFallbackParity`, `SwapchainTransferDst`, `WindowUpdateClock`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData`, `WindowOptionalGlobals` (hides xdg-decoration, viewporter and fractional scale from the window in turn), `SwapchainImageCount` (every present mode, and swapchains with more images than frames in flight, in child processes on llvmpipe where the host's GPU never makes one), `TextAntialiasing` (text through `DispatchText` and `DispatchFused` against stb_truetype's own antialiased rasterizer, at 14 and 64 px and stretched, plus a glyph mirrored by its UVs and empty texels shrunk below 4 px), `ResizeViewport` (a `Resize` and a configured size, got by maximizing its window for a moment, against the connection itself: it runs with `WAYLAND_DEBUG` set and stderr in a file and replays the log, which has the driver's attach and commit too), and `FeatureRequests` for its retry case. `UIFallbackParity`, `SwapchainTransferDst`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData` and `TextAntialiasing` read the frame back with `Window::CaptureNextFrame` (a PNG, decoded with a private `STB_IMAGE_STATIC` copy of stb_image), `SwapchainImageCount` with a transfer pass of its own, and check pixels. The others read no frame back: they check what the frame loop, the device and the window report (their counts and members, the validation layer's count, the connection's protocol errors), and `ResizeViewport` the connection's log. diff --git a/implementations/Crafter.Graphics-Device.cpp b/implementations/Crafter.Graphics-Device.cpp index 3b19541..be76687 100644 --- a/implementations/Crafter.Graphics-Device.cpp +++ b/implementations/Crafter.Graphics-Device.cpp @@ -20,6 +20,7 @@ module; #include #include #include +#include #include #include #endif @@ -656,26 +657,67 @@ void Device::PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t time, s } -void Device::keyboard_keymap(void *data, wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) { - if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { +namespace { + // wl_keyboard's active modifiers and group, as the compositor last sent + // them. The protocol keeps them in wl_keyboard's logical state, which + // the keymap is no part of: the modifiers event sets them and a leave + // resets them to zero. So a state made for a new keymap starts from + // them, not from none (#167). + struct KeyboardModifiers { + std::uint32_t depressed = 0; + std::uint32_t latched = 0; + std::uint32_t locked = 0; + std::uint32_t group = 0; + }; + KeyboardModifiers keyboardModifiers; + + void ApplyKeyboardModifiers(xkb_state* state) { + xkb_state_update_mask(state, keyboardModifiers.depressed, keyboardModifiers.latched, + keyboardModifiers.locked, 0, 0, keyboardModifiers.group); + } +} + +// The keymap a key's text comes from. One that loads replaces the keymap and +// state there were, and frees them. One that does not load, such as one of +// another format than xkb_v1 (no_keymap), one that cannot be mapped or one +// this libxkbcommon cannot compile, is ignored and leaves the ones there +// were, or none: keys then still fire onRawKeyDown and onRawKeyUp with the +// kernel's codes, but bring no text (#167). +void Device::keyboard_keymap(void*, wl_keyboard*, uint32_t format, int fd, uint32_t size) { + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { close(fd); - fprintf(stderr, "Unsupported keymap format\n"); + std::println(stderr, "Crafter.Graphics: the compositor's keymap has format {}, not xkb_v1; it is ignored", format); return; } - void *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); - if (map == MAP_FAILED) { - close(fd); - perror("mmap"); - return; - } - - xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); - xkb_keymap = xkb_keymap_new_from_string(xkb_context, (const char *)map, XKB_KEYMAP_FORMAT_TEXT_V1,XKB_KEYMAP_COMPILE_NO_FLAGS); - munmap(map, size); + void* map = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0); + const int mapError = errno; close(fd); + if (map == MAP_FAILED) { + std::println(stderr, "Crafter.Graphics: the compositor's keymap could not be mapped ({}); it is ignored", std::strerror(mapError)); + return; + } - xkb_state = xkb_state_new(xkb_keymap); + // One context for every keymap, made with the first; xkb_context_new + // returns null when it fails. + if (xkb_context == nullptr) xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + ::xkb_keymap* keymap = nullptr; + if (xkb_context != nullptr) { + keymap = xkb_keymap_new_from_string(xkb_context, static_cast(map), XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); + } + munmap(map, size); + ::xkb_state* state = keymap != nullptr ? xkb_state_new(keymap) : nullptr; + if (state == nullptr) { + xkb_keymap_unref(keymap); + std::println(stderr, "Crafter.Graphics: the compositor's keymap did not load; it is ignored"); + return; + } + + ApplyKeyboardModifiers(state); + xkb_state_unref(xkb_state); + xkb_keymap_unref(xkb_keymap); + xkb_state = state; + xkb_keymap = keymap; } void Device::keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys) { @@ -696,6 +738,10 @@ void Device::keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, keyboardWindow = nullptr; keyRepeat.active = false; keyRepeat.utf8.clear(); + // A leave resets wl_keyboard's modifiers and group to zero; the + // compositor sends them again after the next enter. + keyboardModifiers = {}; + if (xkb_state != nullptr) ApplyKeyboardModifiers(xkb_state); } void Device::keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) { @@ -718,9 +764,11 @@ void Device::keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, ui keyboardWindow->onRawKeyDown.Invoke(code); } + // The text comes from the keymap's state; without a keymap that + // loaded, the key brings its code alone. std::string buf; buf.resize(16); - int n = xkb_state_key_get_utf8(xkb_state, xkbKeycode, buf.data(), 16); + int n = xkb_state == nullptr ? 0 : xkb_state_key_get_utf8(xkb_state, xkbKeycode, buf.data(), 16); std::string utf8; if (n > 0 && (unsigned char)buf[0] >= 0x20 && buf[0] != 0x7f) { buf.resize(n); @@ -751,7 +799,10 @@ void Device::keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, ui } void Device::keyboard_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) { - xkb_state_update_mask(xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group); + keyboardModifiers = { mods_depressed, mods_latched, mods_locked, group }; + // Without a keymap there is no state to set; a state made later starts + // from these. + if (xkb_state != nullptr) ApplyKeyboardModifiers(xkb_state); } void Device::keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay) { diff --git a/interfaces/Crafter.Graphics-Device.cppm b/interfaces/Crafter.Graphics-Device.cppm index 1c9a181..a349c81 100644 --- a/interfaces/Crafter.Graphics-Device.cppm +++ b/interfaces/Crafter.Graphics-Device.cppm @@ -98,7 +98,6 @@ export namespace Crafter { // request on a null proxy crashes in libwayland, so check first. inline static wp_fractional_scale_manager_v1* fractionalScaleManager = nullptr; inline static zxdg_decoration_manager_v1* manager = nullptr; - inline static xkb_keymap* xkb_keymap; inline static wl_compositor* compositor = nullptr; inline static Window* focusedWindow = nullptr; // The window with keyboard focus (wl_keyboard.enter/leave), apart from @@ -108,8 +107,18 @@ export namespace Crafter { inline static Window* keyboardWindow = nullptr; inline static wl_shm* shm = nullptr; inline static wp_viewporter* wpViewporter = nullptr; - inline static xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); - inline static xkb_state* xkb_state; + // The keyboard's XKB keymap, from the compositor's wl_keyboard.keymap, + // and the state made from it, for an application that reads keysyms + // or modifiers itself. Null until a keymap loads. One that does not + // load, such as one of another format than xkb_v1, one that cannot be + // mapped or one this libxkbcommon cannot compile, is ignored and + // leaves the ones there were; one that loads frees them, so read these + // at each use rather than keep them. Keys need neither: their codes + // are the kernel's, and only onTextInput's text comes from the state. + inline static xkb_keymap* xkb_keymap = nullptr; + inline static xkb_state* xkb_state = nullptr; + // The one context every keymap is compiled in, made with the first. + inline static xkb_context* xkb_context = nullptr; inline static std::vector windows; inline static wl_pointer* wlPointer; inline static wl_pointer* seatPointer = nullptr; diff --git a/project.cpp b/project.cpp index c2d78b0..164f179 100644 --- a/project.cpp +++ b/project.cpp @@ -445,6 +445,19 @@ extern "C" Configuration CrafterBuildProject(std::span a // an injected clock; no compositor. cfg.tests.push_back(LibraryTest("KeyRepeat")); + // Issue #167: the wl_keyboard handlers with keymaps that do not + // load (one of the no_keymap format, one whose fd cannot be + // mapped, one that does not compile), as the first and after one + // that loaded, and with keymaps one after another: keys without a + // keymap fire their raw events without text, the keymap there was + // stays, the next one that loads frees it (a heap count, on + // glibc), one context compiles them all, and the state is set + // from the modifiers the compositor last sent, which a leave + // resets. + // Drives the callbacks directly with keymaps in memfds, each case + // in a child process. No compositor. + cfg.tests.push_back(LibraryTest("KeyboardKeymap")); + // The pointer's enter, move and leave through the helpers both // native backends report with (Window::PointerEnter and co.). // Drives the wl_pointer callbacks directly, as MouseScroll does. diff --git a/tests/KeyboardKeymap/main.cpp b/tests/KeyboardKeymap/main.cpp new file mode 100644 index 0000000..993a81c --- /dev/null +++ b/tests/KeyboardKeymap/main.cpp @@ -0,0 +1,317 @@ +//SPDX-License-Identifier: LGPL-3.0-only +//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Issue #167: the wl_keyboard handlers with a keymap that does not load, and +// with keymaps that come one after another. keyboard_keymap left +// Device::xkb_state null after a first keymap of another format than xkb_v1 +// or one it could not map, and keyboard_modifiers and keyboard_key then +// passed the null state to libxkbcommon, which crashes on it, at the +// modifiers a compositor sends after a keyboard enter, before any key. For a +// keymap that did not compile, first or later, keyboard_keymap called +// xkb_state_new on the null keymap, which crashed in the handler itself. And +// every keymap that loaded made a context, a keymap and a state, and freed +// none of the ones before. +// +// What the handlers do now: a keymap that does not load is ignored, so keys +// without a keymap fire onRawKeyDown and onRawKeyUp without text, and keys +// after one that loaded keep its text; a keymap that loads frees the one +// before it; every keymap is compiled in one context; and the state is set +// from the modifiers the compositor last sent, also when they came before its +// keymap, and drops them at a leave, as wl_keyboard's logical state has them. +// +// Drives the callbacks directly, with keymaps in memfds, on a +// default-constructed Window (inert without a compositor): no compositor, no +// GPU. Each case runs in a child process, so that a crash fails that case +// alone and each starts with no keymap, as a process does. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__GLIBC__) +#include +#endif + +import Crafter.Graphics; +import Crafter.Event; +import std; +using namespace Crafter; + +namespace { + +int failures = 0; + +// Flushed at once: a case that crashes keeps what it printed before. +void Check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "PASS" : "FAIL", what); + std::fflush(stdout); + if (!ok) ++failures; +} + +// A whole keymap in the xkb_v1 text, as a compositor serialises one: every +// section written out, nothing included. KEY_A (, 30 + 8) types +// `lower`, and `upper` with Shift or Caps Lock. +std::string Keymap(std::string_view lower, std::string_view upper) { + return std::format(R"(xkb_keymap {{ + xkb_keycodes "test" {{ + minimum = 8; + maximum = 255; + = 38; + }}; + xkb_types "test" {{ + type "ALPHABETIC" {{ + modifiers = Shift + Lock; + map[Shift] = Level2; + map[Lock] = Level2; + level_name[Level1] = "Base"; + level_name[Level2] = "Caps"; + }}; + }}; + xkb_compatibility "test" {{ + }}; + xkb_symbols "test" {{ + key {{ type = "ALPHABETIC", [ {}, {} ] }}; + }}; +}}; +)", lower, upper); +} + +constexpr std::string_view kNoKeymap = "xkb_keymap { this is no keymap };"; + +bool Closed(int fd) { + return fcntl(fd, F_GETFD) == -1 && errno == EBADF; +} + +// wl_keyboard.keymap of the xkb_v1 format, `text` in a memfd with the NUL the +// format ends it with. True when the handler closed the fd, as it must on +// every path. +bool SendKeymap(std::string_view text) { + const int fd = memfd_create("crafter-keymap", MFD_CLOEXEC); + if (fd < 0 || write(fd, text.data(), text.size()) != static_cast(text.size()) || write(fd, "", 1) != 1) { + std::println("FAIL could not write a keymap to a memfd: {}", std::strerror(errno)); + std::exit(EXIT_FAILURE); + } + Device::keyboard_keymap(nullptr, nullptr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, fd, static_cast(text.size() + 1)); + return Closed(fd); +} + +// One of the no_keymap format: /dev/null, size 0. +bool SendNoKeymap() { + const int fd = open("/dev/null", O_RDONLY | O_CLOEXEC); + Device::keyboard_keymap(nullptr, nullptr, WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP, fd, 0); + return Closed(fd); +} + +// One of the xkb_v1 format whose fd cannot be mapped: a pipe's. +bool SendUnmappableKeymap() { + int ends[2]; + if (pipe(ends) != 0) { + std::println("FAIL could not make a pipe: {}", std::strerror(errno)); + std::exit(EXIT_FAILURE); + } + close(ends[1]); + Device::keyboard_keymap(nullptr, nullptr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, ends[0], 4096); + return Closed(ends[0]); +} + +void SendModifiers(std::uint32_t depressed, std::uint32_t locked) { + Device::keyboard_modifiers(nullptr, nullptr, 0, depressed, 0, locked, 0); +} + +// The mask of the modifier `name` as a compositor with the test's keymap sends +// it, from that keymap compiled in a context of the test's own. +std::uint32_t Mask(const char* name) { + xkb_context* context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + const std::string text = Keymap("a", "A"); + xkb_keymap* keymap = xkb_keymap_new_from_string(context, text.c_str(), XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); + const xkb_mod_index_t index = xkb_keymap_mod_get_index(keymap, name); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + return 1u << index; +} + +bool CapsLockActive() { + return xkb_state_mod_name_is_active(Device::xkb_state, XKB_MOD_NAME_CAPS, XKB_STATE_MODS_EFFECTIVE) > 0; +} + +#if defined(__GLIBC__) +// The bytes the heap has handed out and not had back, mmapped chunks too. +std::size_t HeapInUse() { + const struct mallinfo2 info = mallinfo2(); + return info.uordblks + info.hblkhd; +} +#endif + +// A window with the keyboard focus, and what its key events brought. +struct Keyboard { + Window window; // default ctor creates no surface — safe without a compositor + int downs = 0; + int ups = 0; + std::string text; + EventListener down { &window.onRawKeyDown, [this](KeyCode) { ++downs; } }; + EventListener up { &window.onRawKeyUp, [this](KeyCode) { ++ups; } }; + EventListener typed { &window.onTextInput, [this](const std::string_view utf8) { text += utf8; } }; + + Keyboard() { Device::keyboardWindow = &window; } + + // KEY_A pressed and released: the text it brought. + std::string TypeA() { + text.clear(); + Device::keyboard_key(nullptr, nullptr, 0, 0, KEY_A, WL_KEYBOARD_KEY_STATE_PRESSED); + Device::keyboard_key(nullptr, nullptr, 0, 0, KEY_A, WL_KEYBOARD_KEY_STATE_RELEASED); + return text; + } +}; + +// Without a keymap: the modifiers a compositor sends after an enter, then a +// key, which still fires its raw events, without text. +void CheckKeysWithoutText(Keyboard& keyboard) { + SendModifiers(Mask(XKB_MOD_NAME_SHIFT), 0); + const std::string text = keyboard.TypeA(); + Check(keyboard.downs == 1 && keyboard.ups == 1, + std::format("a key with modifiers still fires onRawKeyDown and onRawKeyUp ({} and {})", keyboard.downs, keyboard.ups)); + Check(text.empty(), std::format("without text ('{}')", text)); +} + +void FirstKeymapOfAnotherFormat() { + Keyboard keyboard; + Check(SendNoKeymap(), "the fd of a keymap of the no_keymap format is closed"); + Check(Device::xkb_state == nullptr, "and it makes no state"); + CheckKeysWithoutText(keyboard); +} + +void FirstKeymapUnmappable() { + Keyboard keyboard; + Check(SendUnmappableKeymap(), "the fd of a keymap that cannot be mapped is closed"); + Check(Device::xkb_state == nullptr, "and it makes no state"); + CheckKeysWithoutText(keyboard); +} + +void FirstKeymapDoesNotCompile() { + Keyboard keyboard; + Check(SendKeymap(kNoKeymap), "the fd of a keymap that does not compile is closed"); + Check(Device::xkb_keymap == nullptr && Device::xkb_state == nullptr, "and it makes no keymap and no state"); + CheckKeysWithoutText(keyboard); +} + +void KeymapsOneAfterAnother() { + Keyboard keyboard; + const std::string qwerty = Keymap("a", "A"); + const std::string azerty = Keymap("q", "Q"); + Check(SendKeymap(qwerty), "the fd of a keymap that loads is closed"); + Check(keyboard.TypeA() == "a", "and KEY_A types its a"); + SendModifiers(Mask(XKB_MOD_NAME_SHIFT), 0); + Check(keyboard.TypeA() == "A", "with Shift, A"); + SendModifiers(0, 0); + const auto context = Device::xkb_context; + SendKeymap(azerty); + Check(keyboard.TypeA() == "q", "the next keymap replaces it: q"); + Check(Device::xkb_context == context, "and is compiled in the first one's context"); +#if defined(__GLIBC__) + // Both compiled in that context once more first, so that what it keeps of + // a keymap (the names it interns) is there before the count. + SendKeymap(qwerty); + SendKeymap(azerty); + const std::size_t before = HeapInUse(); + for (int i = 0; i < 100; ++i) SendKeymap(i % 2 == 0 ? qwerty : azerty); + const std::ptrdiff_t grown = static_cast(HeapInUse()) - static_cast(before); + Check(grown < 16 * 1024, std::format("100 keymaps more leave {} more bytes on the heap: each frees the one before", grown)); +#else + std::println("SKIP the heap count reads glibc's mallinfo2"); +#endif + Check(Device::xkb_context == context, "every keymap is compiled in that one context"); + Check(keyboard.TypeA() == "q", "and the last one's text is the one typed"); +} + +void KeymapThatDoesNotLoadAfterOne() { + Keyboard keyboard; + SendKeymap(Keymap("a", "A")); + const auto state = Device::xkb_state; + Check(SendKeymap(kNoKeymap), "the fd of a keymap that does not compile is closed"); + Check(Device::xkb_state == state && keyboard.TypeA() == "a", "and it leaves the keymap there was: a"); + Check(SendUnmappableKeymap(), "the fd of one that cannot be mapped is closed"); + Check(Device::xkb_state == state && keyboard.TypeA() == "a", "and it leaves it too"); + Check(SendNoKeymap(), "the fd of one of the no_keymap format is closed"); + Check(Device::xkb_state == state && keyboard.TypeA() == "a", "and so does it"); + SendKeymap(Keymap("q", "Q")); + Check(keyboard.TypeA() == "q", "until one loads: q"); +} + +void ModifiersApartFromTheKeymap() { + Keyboard keyboard; + const std::uint32_t capsLock = Mask(XKB_MOD_NAME_CAPS); + SendKeymap(Keymap("a", "A")); + SendModifiers(0, capsLock); + Check(keyboard.TypeA() == "A", "with Caps Lock, A"); + Device::keyboard_leave(nullptr, nullptr, 0, nullptr); + Check(!CapsLockActive(), "a leave drops the modifiers from the state"); + // An enter, and the modifiers the compositor sends after it. + Device::keyboardWindow = &keyboard.window; + SendModifiers(0, capsLock); + SendKeymap(Keymap("q", "Q")); + Check(keyboard.TypeA() == "Q", "the state of a keymap that comes with no modifiers takes the ones last sent: Q"); + Device::keyboard_leave(nullptr, nullptr, 0, nullptr); + SendKeymap(Keymap("a", "A")); + Check(!CapsLockActive(), "and a state made after a leave, none"); +} + +void ModifiersBeforeTheFirstKeymap() { + Keyboard keyboard; + SendModifiers(Mask(XKB_MOD_NAME_SHIFT), 0); + SendKeymap(Keymap("a", "A")); + Check(keyboard.TypeA() == "A", "modifiers sent before the first keymap are its state's: A"); +} + +// Runs `body` in a child: its checks print there, and its death by a signal, +// which is how these handlers failed, is one more failure. +bool RunCase(std::string_view name, void (*body)()) { + std::println("{}:", name); + std::fflush(stdout); + const pid_t child = fork(); + if (child < 0) { + std::println("FAIL could not fork: {}", std::strerror(errno)); + return false; + } + if (child == 0) { + body(); + std::fflush(stdout); + _exit(failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE); + } + int status = 0; + waitpid(child, &status, 0); + if (WIFSIGNALED(status)) { + std::println("FAIL the case died of signal {}", WTERMSIG(status)); + return false; + } + return WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS; +} + +} // namespace + +int main() { + const std::pair cases[] = { + { "a first keymap of the no_keymap format", FirstKeymapOfAnotherFormat }, + { "a first keymap that cannot be mapped", FirstKeymapUnmappable }, + { "a first keymap that does not compile", FirstKeymapDoesNotCompile }, + { "keymaps one after another", KeymapsOneAfterAnother }, + { "keymaps that do not load, after one that did", KeymapThatDoesNotLoadAfterOne }, + { "the modifiers, apart from the keymap", ModifiersApartFromTheKeymap }, + { "modifiers before the first keymap", ModifiersBeforeTheFirstKeymap }, + }; + std::size_t failed = 0; + for (const auto& [name, body] : cases) { + if (!RunCase(name, body)) ++failed; + } + if (failed == 0) { + std::println("all checks passed"); + } else { + std::println("{} of {} cases failed", failed, std::size(cases)); + } + return failed == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +}