Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): allow Hyprland foreground typing with Num Lock and keymap options (#3970)

Osamah Beig7954a1c089b3
diff --git a/libs/cua-driver/hyprland-plugin/CMakeLists.txt b/libs/cua-driver/hyprland-plugin/CMakeLists.txt
index 8a80de28a2..36df36b2ea 100644
--- a/libs/cua-driver/hyprland-plugin/CMakeLists.txt
+++ b/libs/cua-driver/hyprland-plugin/CMakeLists.txt
@@ -53,6 +53,34 @@ if(BUILD_TESTING)
target_compile_options(cua_hyprland_foreground_route_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_test(NAME cua_hyprland_foreground_route_test COMMAND cua_hyprland_foreground_route_test)
+ # Keyboard layout and foreground modifier tests compile real XKB keymaps.
+ # Set CUA_HYPRLAND_REQUIRE_XKBCOMMON in the environment to fail instead of
+ # skipping them when the xkbcommon development files are missing.
+ find_package(PkgConfig QUIET)
+ if(PkgConfig_FOUND)
+ pkg_check_modules(CUA_XKBCOMMON QUIET IMPORTED_TARGET xkbcommon)
+ endif()
+ if(NOT CUA_XKBCOMMON_FOUND AND DEFINED ENV{CUA_HYPRLAND_REQUIRE_XKBCOMMON})
+ message(FATAL_ERROR "xkbcommon development files are required for the keyboard tests")
+ endif()
+ if(CUA_XKBCOMMON_FOUND)
+ foreach(xkb_test IN ITEMS keymap_equivalence keyboard_layout)
+ add_executable(cua_hyprland_${xkb_test}_test tests/${xkb_test}_test.cpp)
+ target_compile_features(cua_hyprland_${xkb_test}_test PRIVATE cxx_std_26)
+ target_include_directories(cua_hyprland_${xkb_test}_test PRIVATE src)
+ target_compile_options(cua_hyprland_${xkb_test}_test PRIVATE -Wall -Wextra -Wpedantic -Werror)
+ target_link_libraries(cua_hyprland_${xkb_test}_test PRIVATE PkgConfig::CUA_XKBCOMMON)
+ add_test(NAME cua_hyprland_${xkb_test}_test COMMAND cua_hyprland_${xkb_test}_test)
+ set_tests_properties(cua_hyprland_${xkb_test}_test PROPERTIES SKIP_RETURN_CODE 77)
+ endforeach()
+ else()
+ message(STATUS "xkbcommon not found; keyboard layout tests are not built")
+ endif()
+ add_test(NAME cua_hyprland_foreground_modifiers_test
+ COMMAND ${Python3_EXECUTABLE} -B ${CMAKE_CURRENT_SOURCE_DIR}/tests/foreground_modifiers_test.py)
+ set_tests_properties(cua_hyprland_foreground_modifiers_test PROPERTIES
+ ENVIRONMENT "CXX=${CMAKE_CXX_COMPILER}")
+
add_executable(cua_hyprland_passive_pointer_target_test tests/passive_pointer_target_test.cpp)
target_compile_features(cua_hyprland_passive_pointer_target_test PRIVATE cxx_std_26)
target_include_directories(cua_hyprland_passive_pointer_target_test PRIVATE src)
diff --git a/libs/cua-driver/hyprland-plugin/README.md b/libs/cua-driver/hyprland-plugin/README.md
index 4a40f8b921..3ed42fd71f 100644
--- a/libs/cua-driver/hyprland-plugin/README.md
+++ b/libs/cua-driver/hyprland-plugin/README.md
@@ -146,6 +146,20 @@ must check its compositor epoch, protocol version, advertised capabilities,
socket path, discovery-only state, and ABI identity before connecting. A loaded
module alone is not evidence that target discovery or mutation is available.
+The opt-in v3 build also reports two keyboard fields, whether or not input is
+enabled, so an installer can tell an updated module from an older one still
+loaded in the running compositor before it enables input:
+
+- `keyboard_layout_independent: true`: the agent seats use their own canonical
+ keymap, and foreground pointer-only actions do not depend on the physical
+ keyboard layout.
+- `foreground_numlock_compatible: true`: foreground keyboard actions keep the
+ human keyboard's Num Lock and admit a key only when it means the same thing
+ under it. Caps Lock, and keypad keys that Num Lock changes, refuse explicitly.
+
+Neither field says that the current physical keymap qualifies for foreground
+typing; each foreground key is still checked when it is sent.
+
The local transport is also disabled by default. To exercise negotiation in a
disposable session, set the following and reload the configuration after the
plugin loads. For Omarchy's Lua configuration, add:
diff --git a/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md b/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md
index f9cbfbf0d9..e057a489c3 100644
--- a/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md
+++ b/libs/cua-driver/hyprland-plugin/protocol/cua-input-v3.md
@@ -172,11 +172,36 @@ makes no promise to restore focus or cursor position after delivery.
Before taking over primary input, the plugin must refuse held physical keys or
buttons, active grabs, pointer constraints, and drag-and-drop. It requires a
single primary seat binding, excluding its own agent seats by resource identity,
-and refuses binding or input-resource changes during dispatch. Keyboard delivery
-requires the physical keymap to match canonical `evdev`/`pc105`/`us`, with
-neutral primary modifiers and layout group zero; remaps, latched or locked
-modifiers refuse before activation. Foreground pointer-only actions do not
-depend on the physical keyboard layout. Foreground drag
+and refuses binding or input-resource changes during dispatch. Foreground
+keyboard delivery never changes the human keyboard's modifiers or locks, so the
+focused client sees no modifier change around the action. It requires layout
+group zero and no held or latched modifiers. Num Lock may stay on; Caps Lock and
+any other lock refuse. The physical keymap qualifies when every key the KEY
+command can press (evdev 1-247 except the lock keys) produces the same keysym as
+canonical `evdev`/`pc105`/`us`, at the base level and, for non-modifier keys,
+with Shift held. Options that only change Caps Lock or modifier chords, such as
+`compose:caps` and `shift:both_capslock_cancel`, qualify; a different layout or
+a remapped typing key refuses before activation with `unsupported_layout`.
+Before consuming the grant or changing focus, the plugin also simulates the
+whole KEY chord under the live keymap and lock state and admits it only when it
+means what the wire chord means on a neutral canonical US keyboard: the same
+symbols, consumed modifiers, and resulting modifier state. These refusals use
+`primary_target_busy` before activation, with these details:
+
+- `foreground_keyboard_caps_lock`: Caps Lock is on.
+- `foreground_keyboard_numlock_keypad`: Num Lock is on and changes what a
+ keypad key in the chord means, such as `KP_End` becoming `KP_1`. Text,
+ digits, navigation keys, and keypad operators are unaffected.
+- `foreground_unsupported_layout`: the chord, such as a remapped Ctrl, Alt, or
+ Super shortcut, means something else under the live keymap.
+- `foreground_keyboard_locked`, `foreground_keyboard_depressed`,
+ `foreground_keyboard_latched`, `foreground_keyboard_group`: another lock
+ modifier, a held or latched modifier, or a nonzero layout group.
+
+A modifier, lock, or group change during the action refuses the rest of it
+with `foreground_partial_unknown` and detail `foreground_keyboard_state`; the
+unwind restores the human keyboard's current state. Foreground pointer-only
+actions do not depend on the physical keyboard layout. Foreground drag
cancellation on primary-input and focus transitions remains subject to review
and native verification; do not infer background isolation from this route.
Foreground results use foreground delivery metadata. A drag cancellation after
diff --git a/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp b/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp
index c499a05afe..159132e367 100644
--- a/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp
+++ b/libs/cua-driver/hyprland-plugin/src/foreground_route.hpp
@@ -25,6 +25,7 @@ enum class ForegroundFailureReason {
session_unavailable, unsupported_layout, lease_expired, physical_keyboard,
keyboard_state, physical_pointer, pointer_target, seat_resource, pointer_resources,
keyboard_resources, keyboard_depressed, keyboard_latched, keyboard_locked, keyboard_group,
+ keyboard_caps_lock, keyboard_numlock_keypad,
};
struct ForegroundFailure {
@@ -59,6 +60,8 @@ struct ForegroundFailure {
case ForegroundFailureReason::keyboard_latched: return "foreground_keyboard_latched";
case ForegroundFailureReason::keyboard_locked: return "foreground_keyboard_locked";
case ForegroundFailureReason::keyboard_group: return "foreground_keyboard_group";
+ case ForegroundFailureReason::keyboard_caps_lock: return "foreground_keyboard_caps_lock";
+ case ForegroundFailureReason::keyboard_numlock_keypad: return "foreground_keyboard_numlock_keypad";
}
return "foreground_unknown";
}
@@ -78,11 +81,17 @@ struct ForegroundSeatBindings {
bool unique() const { return primary_candidates == 1; }
};
-inline ForegroundFailureReason foreground_key_modifier_failure(const std::array<std::uint32_t, 4>& modifiers) {
- // The KEY mapping assumes a neutral US state, including layout group zero.
+// Foreground delivery never changes the human keyboard's modifiers or locks.
+// The KEY mapping assumes a neutral US state with layout group zero, except for
+// a Num Lock mask the caller resolved through the live keymap. Caps Lock and
+// every other lock refuse; the chord check decides what Num Lock may change.
+inline ForegroundFailureReason foreground_key_modifier_failure(const std::array<std::uint32_t, 4>& modifiers,
+ std::uint32_t allowed_locked = 0,
+ std::uint32_t caps_locked = 0) {
if (modifiers[0]) return ForegroundFailureReason::keyboard_depressed;
if (modifiers[1]) return ForegroundFailureReason::keyboard_latched;
- if (modifiers[2]) return ForegroundFailureReason::keyboard_locked;
+ if (modifiers[2] & caps_locked) return ForegroundFailureReason::keyboard_caps_lock;
+ if (modifiers[2] & ~allowed_locked) return ForegroundFailureReason::keyboard_locked;
if (modifiers[3]) return ForegroundFailureReason::keyboard_group;
return ForegroundFailureReason::none;
}
diff --git a/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp b/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp
index bdd1437b7d..2d8cd94904 100644
--- a/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp
+++ b/libs/cua-driver/hyprland-plugin/src/input_experiment.cpp
@@ -9,6 +9,7 @@
#include "seat_lifetime.hpp"
#include "owned_socket_path.hpp"
#include "foreground_route.hpp"
+#include "keymap_equivalence.hpp"
#include <src/Compositor.hpp>
#include <src/devices/IKeyboard.hpp>
@@ -218,7 +219,7 @@ struct InputExperiment::Impl {
xkb_keymap* physical_keymap = nullptr;
xkb_state* physical_keyboard_state = nullptr;
int keymap_fd = -1;
- bool retired = false, suspended = true, us_keymap = false, physical_keymap_present = false;
+ bool retired = false, suspended = true, typing_keymap = false, physical_keymap_present = false;
WP<IKeyboard> physical_keyboard;
CHyprSignalListener keymap_listener;
unsigned lane;
@@ -248,19 +249,6 @@ struct InputExperiment::Impl {
// No private key or input-enabled default exists in this component.
}
- static bool canonical_us_keymap(xkb_context* context, xkb_keymap* map) {
- // Compare canonical compiled content, not a layout display name. This
- // deliberately excludes variants, options, remaps, and multiple groups.
- const xkb_rule_names names{kAgentKeymap.rules.data(), kAgentKeymap.model.data(),
- kAgentKeymap.layout.data(), kAgentKeymap.variant.data(), kAgentKeymap.options.data()};
- auto* reference = xkb_keymap_new_from_names(context, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
- if (!reference) return false;
- char* actual = xkb_keymap_get_as_string(map, XKB_KEYMAP_FORMAT_TEXT_V1);
- char* expected = xkb_keymap_get_as_string(reference, XKB_KEYMAP_FORMAT_TEXT_V1);
- const bool matches = actual && expected && std::strcmp(actual, expected) == 0;
- std::free(actual); std::free(expected); xkb_keymap_unref(reference);
- return matches;
- }
static int create_keymap_file(std::string_view text) {
const auto fd = memfd_create("cua-agent-keymap", MFD_CLOEXEC);
std::string payload(text);
@@ -313,7 +301,7 @@ struct InputExperiment::Impl {
bool layout_qualified() const {
if (!kProduction) return true;
const auto keyboard = g_pSeatManager->m_keyboard.lock();
- return physical_keymap_present && us_keymap && physical_keyboard_state && keyboard &&
+ return physical_keymap_present && typing_keymap && physical_keyboard_state && keyboard &&
keyboard->m_xkbKeymapV1FD.get() >= 0 && keyboard->m_xkbKeymapV1String == physical_keymap_text;
}
void sync_keymap() {
@@ -352,7 +340,10 @@ struct InputExperiment::Impl {
if (physical_keymap) xkb_keymap_unref(physical_keymap);
if (physical_xkb_context) xkb_context_unref(physical_xkb_context);
physical_keyboard_state = state; physical_keymap = map; physical_xkb_context = context;
- us_keymap = !kProduction || canonical_us_keymap(context, map);
+ // Keyboard qualification: every key the KEY command can press must type the
+ // same keysym as the canonical agent keymap. Checked once per keymap, so a
+ // different layout refuses before activation rather than mid-string.
+ typing_keymap = !kProduction || typing_keymap_equivalent(map, keymap);
physical_keymap_text = keyboard->m_xkbKeymapV1String;
}
void start() {
@@ -833,6 +824,37 @@ struct InputExperiment::Impl {
.exact_pointer_focus = root && g_pSeatManager->m_state.pointerFocus == root,
};
}
+ // Hyprland reports each keyboard's raw masks in that keyboard's own keymap
+ // encoding and merges shared keyboards into the primary state. Refuse a
+ // keyboard action under any state other than neutral or an unambiguous
+ // Num Lock, and name Caps Lock explicitly.
+ std::array<std::uint32_t, 4> capture_foreground_modifiers(bool needs_keyboard) const {
+ const auto physical = g_pSeatManager->m_keyboard.lock();
+ if (!physical) throw ForegroundFailure{ForegroundFailureReason::physical_keyboard};
+ std::array<std::uint32_t, 4> result{};
+ const auto observe = [&](const auto& kb, bool primary) {
+ const std::array<std::uint32_t, 4> state{kb->m_modifiersState.depressed, kb->m_modifiersState.latched,
+ kb->m_modifiersState.locked, kb->m_modifiersState.group};
+ if (needs_keyboard) {
+ const auto failure = foreground_key_modifier_failure(state, foreground_numlock_mask(kb->m_xkbKeymap),
+ foreground_caps_mask(kb->m_xkbKeymap));
+ if (failure != ForegroundFailureReason::none) throw ForegroundFailure{failure};
+ // A lock from a different encoding must not be reinterpreted
+ // as the primary keymap's Num Lock.
+ if (state[2] && state[2] != foreground_numlock_mask(physical_keymap))
+ throw ForegroundFailure{ForegroundFailureReason::keyboard_locked};
+ }
+ for (unsigned i = 0; i < 3; ++i) result[i] |= state[i];
+ if (primary) result[3] = state[3];
+ };
+ observe(physical, true);
+ for (const auto& kb : g_pInputManager->m_keyboards) {
+ if (kb == physical || !kb->m_enabled || !kb->shareStates() ||
+ (kb->isVirtual() && g_pInputManager->shouldIgnoreVirtualKeyboard(kb))) continue;
+ observe(kb, false);
+ }
+ return result;
+ }
void require_foreground(Client& c) {
if (lease != &c) throw ForegroundFailure{ForegroundFailureReason::lease};
if (c.dead) throw ForegroundFailure{ForegroundFailureReason::client_dead};
@@ -840,6 +862,11 @@ struct InputExperiment::Impl {
if (!input_layout_qualified(c.route, foreground_needs_keyboard, layout_qualified()))
throw ForegroundFailure{ForegroundFailureReason::unsupported_layout};
if (Clock::now() >= expires) throw ForegroundFailure{ForegroundFailureReason::lease_expired};
+ // The chord was admitted under the human keyboard's state. A lock or
+ // modifier change during the action, including one caused by
+ // activation, changes what the remaining events mean.
+ if (foreground_needs_keyboard && capture_foreground_modifiers(true) != foreground_modifiers)
+ throw ForegroundFailure{ForegroundFailureReason::keyboard_state};
const auto failure = foreground_guard(c).dispatch_failure(foreground_needs_pointer);
if (failure != ForegroundFailureReason::none) throw ForegroundFailure{failure};
}
@@ -855,19 +882,26 @@ struct InputExperiment::Impl {
p->sendButton(event_ms(), held_button, WL_POINTER_BUTTON_STATE_RELEASED);
p->sendFrame();
}
- if (foreground_keyboard_used && root && root->good() && g_pSeatManager->m_state.keyboardFocus == root)
+ if (foreground_keyboard_used && root && root->good() && g_pSeatManager->m_state.keyboardFocus == root) {
+ // Synthetic keys change only private state. If human input cancelled
+ // the action, restore the human keyboard's current state, not the
+ // state captured at admission.
+ const auto restore = g_pSeatManager->m_keyboard.lock() ?
+ capture_foreground_modifiers(false) : foreground_modifiers;
for (const auto& weak : foreground_keyboards)
if (const auto k = weak.lock(); k && k->good()) {
for (auto code : held_keys) k->sendKey(event_ms(), code, WL_KEYBOARD_KEY_STATE_RELEASED);
- k->sendMods(foreground_modifiers[0], foreground_modifiers[1], foreground_modifiers[2], foreground_modifiers[3]);
+ k->sendMods(restore[0], restore[1], restore[2], restore[3]);
}
+ }
held_button = 0; held_keys.clear();
foreground_pointers.clear(); foreground_keyboards.clear(); foreground_surface.reset(); foreground_seat.reset();
foreground_started = false;
foreground_keyboard_used = false;
foreground_needs_keyboard = false;
}
- void start_foreground(Client& c, double x, double y, bool needs_pointer, bool needs_keyboard) {
+ void start_foreground(Client& c, double x, double y, bool needs_pointer, bool needs_keyboard,
+ const std::array<std::uint32_t, 4>& modifiers) {
const auto root = c.surface.lock();
const auto physical = g_pSeatManager->m_keyboard.lock();
const auto failure = foreground_guard(c).activation_failure();
@@ -887,17 +921,9 @@ struct InputExperiment::Impl {
throw ForegroundFailure{ForegroundFailureReason::keyboard_resources};
foreground_modifiers = {};
if (needs_keyboard) {
- foreground_modifiers = {physical->m_modifiersState.depressed, physical->m_modifiersState.latched,
- physical->m_modifiersState.locked, physical->m_modifiersState.group};
- for (const auto& kb : g_pInputManager->m_keyboards) {
- if (!kb->m_enabled || !kb->shareStates() ||
- (kb->isVirtual() && g_pInputManager->shouldIgnoreVirtualKeyboard(kb))) continue;
- foreground_modifiers[0] |= kb->m_modifiersState.depressed;
- foreground_modifiers[1] |= kb->m_modifiersState.latched;
- foreground_modifiers[2] |= kb->m_modifiersState.locked;
- }
- const auto modifier_failure = foreground_key_modifier_failure(foreground_modifiers);
- if (modifier_failure != ForegroundFailureReason::none) throw ForegroundFailure{modifier_failure};
+ // Keep the human keyboard's modifiers and locks. The caller admitted
+ // this chord under exactly this state before consuming the grant.
+ foreground_modifiers = modifiers;
xkb_state_update_mask(physical_keyboard_state, foreground_modifiers[0], foreground_modifiers[1],
foreground_modifiers[2], 0, 0, foreground_modifiers[3]);
}
@@ -1242,8 +1268,19 @@ struct InputExperiment::Impl {
if (Clock::now() + std::chrono::milliseconds(duration + 50) >= expires) { send(c, refusal("lease_expired")); return; }
}
}
+ std::array<std::uint32_t, 4> modifiers{};
+ if (command == "KEY") {
+ // Simulate the whole chord under the human keyboard's live state
+ // before consuming the grant or changing focus. Num Lock and Caps
+ // Lock stay as they are; a chord whose meaning they or the layout
+ // would change refuses with its specific reason.
+ modifiers = capture_foreground_modifiers(true);
+ const auto failure = foreground_chord_failure(physical_keymap, keymap, static_cast<std::uint32_t>(code),
+ static_cast<std::uint32_t>(mods), modifiers);
+ if (failure != ForegroundFailureReason::none) throw ForegroundFailure{failure};
+ }
if (!consume_grant(c, cap)) return;
- start_foreground(c, x, y, command != "KEY" && command != "ACTIVATE", command == "KEY");
+ start_foreground(c, x, y, command != "KEY" && command != "ACTIVATE", command == "KEY", modifiers);
if (command == "KEY") {
const std::array<std::uint32_t, 4> keys{42, 29, 56, 125};
for (unsigned i = 0; i < 4; ++i) if ((mods & (1u << i)) && keys[i] != code) foreground_key(c, keys[i], true);
diff --git a/libs/cua-driver/hyprland-plugin/src/keymap_equivalence.hpp b/libs/cua-driver/hyprland-plugin/src/keymap_equivalence.hpp
new file mode 100644
index 0000000000..ba73ec6bbb
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/src/keymap_equivalence.hpp
@@ -0,0 +1,204 @@
+#pragma once
+
+// The chord comparison below (foreground_numlock_mask through
+// foreground_chord_failure) is adapted from omacom/omarchy-pkgs#473,
+// pkgbuilds/cua-hyprland-plugin/independent-keymaps.patch, by Spencer Bull.
+// Copyright (c) David Heinemeier Hansson. Used under the MIT License, whose
+// permission notice is the same as this repository's LICENSE.md.
+
+#include "foreground_route.hpp"
+
+#include <xkbcommon/xkbcommon.h>
+#include <xkbcommon/xkbcommon-names.h>
+
+#include <array>
+#include <cstdint>
+#include <memory>
+
+namespace cua::hyprland {
+
+// Lock keys are refused by the KEY command itself, so they never need to match.
+inline constexpr bool foreground_lock_key(std::uint32_t code) {
+ return code == 58 || code == 69 || code == 70;
+}
+
+inline constexpr bool foreground_modifier_key(std::uint32_t code) {
+ switch (code) {
+ case 29: case 42: case 54: case 56: case 97: case 100: case 125: case 126:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// True when typing through `physical` produces the same keysyms as `canonical`
+// for every key the foreground KEY command can press (evdev 1-247, minus the
+// lock keys): at the base level, and with Shift held for non-modifier keys.
+// Options that only change Caps Lock or modifier chords, such as compose:caps
+// and shift:both_capslock_cancel, qualify. A different layout, or a remap of a
+// letter, digit, punctuation, or modifier key, does not. This compares fresh
+// states, so the human keyboard's current locks do not affect it.
+inline bool typing_keymap_equivalent(xkb_keymap* physical, xkb_keymap* canonical) {
+ if (!physical || !canonical) return false;
+ auto* actual = xkb_state_new(physical);
+ auto* expected = xkb_state_new(canonical);
+ bool equal = actual && expected;
+ constexpr xkb_keycode_t left_shift = 42 + 8;
+ for (int shifted = 0; equal && shifted < 2; ++shifted) {
+ if (shifted) {
+ xkb_state_update_key(actual, left_shift, XKB_KEY_DOWN);
+ xkb_state_update_key(expected, left_shift, XKB_KEY_DOWN);
+ }
+ for (std::uint32_t code = 1; equal && code <= 247; ++code) {
+ if (foreground_lock_key(code) || (shifted && foreground_modifier_key(code))) continue;
+ equal = xkb_state_key_get_one_sym(actual, code + 8) == xkb_state_key_get_one_sym(expected, code + 8);
+ }
+ }
+ if (actual) xkb_state_unref(actual);
+ if (expected) xkb_state_unref(expected);
+ return equal;
+}
+
+using ForegroundXkbState = std::unique_ptr<xkb_state, decltype(&xkb_state_unref)>;
+
+inline ForegroundXkbState foreground_xkb_state(xkb_keymap* map) {
+ return {map ? xkb_state_new(map) : nullptr, xkb_state_unref};
+}
+
+inline std::uint32_t foreground_caps_mask(xkb_keymap* map) {
+ const auto index = map ? xkb_keymap_mod_get_index(map, XKB_MOD_NAME_CAPS) : XKB_MOD_INVALID;
+ return index < 32 ? std::uint32_t{1} << index : 0;
+}
+
+// Resolve Num Lock through this map's own Num Lock key rather than assuming
+// Mod2. An encoding that is not a single modifier, or that overlaps Caps Lock,
+// is not admitted.
+inline std::uint32_t foreground_numlock_mask(xkb_keymap* map) {
+ auto state = foreground_xkb_state(map);
+ if (!state) return 0;
+ constexpr xkb_keycode_t num_lock = 69 + 8;
+ xkb_state_update_key(state.get(), num_lock, XKB_KEY_DOWN);
+ xkb_state_update_key(state.get(), num_lock, XKB_KEY_UP);
+ const auto mask = xkb_state_serialize_mods(state.get(), XKB_STATE_MODS_LOCKED);
+ return mask && !(mask & (mask - 1)) && !(mask & foreground_caps_mask(map)) ? mask : 0;
+}
+
+inline bool foreground_same_key_symbols(xkb_state* actual, xkb_state* expected, xkb_keycode_t key) {
+ const xkb_keysym_t *a = nullptr, *b = nullptr;
+ const int na = xkb_state_key_get_syms(actual, key, &a);
+ const int nb = xkb_state_key_get_syms(expected, key, &b);
+ if (na != nb) return false;
+ for (int i = 0; i < na; ++i) if (a[i] != b[i]) return false;
+ return true;
+}
+
+// Toolkits subtract consumed modifiers when matching shortcuts, so equal
+// symbols and modifier state alone do not preserve a shortcut's meaning.
+inline bool foreground_same_consumed_modifiers(xkb_state* actual, xkb_state* expected, xkb_keycode_t key) {
+ for (auto* state : {actual, expected}) {
+ auto* map = xkb_state_get_keymap(state);
+ for (xkb_mod_index_t i = 0; i < xkb_keymap_num_mods(map); ++i) {
+ const char* name = xkb_keymap_mod_get_name(map, i);
+ if (!name || xkb_state_mod_name_is_active(state, name, XKB_STATE_MODS_EFFECTIVE) <= 0) continue;
+ const auto ai = xkb_keymap_mod_get_index(xkb_state_get_keymap(actual), name);
+ const auto bi = xkb_keymap_mod_get_index(xkb_state_get_keymap(expected), name);
+ for (auto mode : {XKB_CONSUMED_MODE_XKB, XKB_CONSUMED_MODE_GTK})
+ if ((xkb_state_mod_index_is_consumed2(actual, key, ai, mode) > 0) !=
+ (xkb_state_mod_index_is_consumed2(expected, key, bi, mode) > 0)) return false;
+ }
+ }
+ return true;
+}
+
+// Modifier indices can differ between maps. Compare names in both directions,
+// including nonstandard modifiers and lock or latch changes on key release.
+inline bool foreground_same_modifier_state(xkb_state* actual, xkb_state* expected) {
+ for (auto* state : {actual, expected}) {
+ auto* map = xkb_state_get_keymap(state);
+ for (xkb_mod_index_t i = 0; i < xkb_keymap_num_mods(map); ++i) {
+ const char* name = xkb_keymap_mod_get_name(map, i);
+ if (!name) continue;
+ for (auto component : {XKB_STATE_MODS_DEPRESSED, XKB_STATE_MODS_LATCHED,
+ XKB_STATE_MODS_LOCKED, XKB_STATE_MODS_EFFECTIVE}) {
+ const bool a = xkb_state_mod_name_is_active(actual, name, component) > 0;
+ const bool b = xkb_state_mod_name_is_active(expected, name, component) > 0;
+ if (a != b) return false;
+ }
+ }
+ }
+ for (auto component : {XKB_STATE_LAYOUT_DEPRESSED, XKB_STATE_LAYOUT_LATCHED,
+ XKB_STATE_LAYOUT_LOCKED, XKB_STATE_LAYOUT_EFFECTIVE})
+ if (xkb_state_serialize_layout(actual, component) != xkb_state_serialize_layout(expected, component))
+ return false;
+ return true;
+}
+
+// Simulate a complete KEY chord (modifiers, key press and release, modifier
+// release) before any event is delivered or focus changes. The human keyboard's
+// modifiers and locks stay as they are; the chord is admitted only when it means
+// under the live keymap and lock state what the wire chord means on a neutral
+// canonical US keyboard. This compares meaning; it never translates key
+// positions. Three states are compared:
+// actual: the live physical keymap with the human keyboard's locks;
+// expected: the canonical keymap with the same (Num Lock) lock;
+// intended: the canonical keymap in the neutral state the wire assumes.
+// actual differing from expected is a layout difference. expected differing
+// from intended can only come from the admitted Num Lock, which on the
+// canonical keymap changes only keypad keys.
+inline ForegroundFailureReason foreground_chord_failure(xkb_keymap* physical, xkb_keymap* canonical,
+ std::uint32_t code, std::uint32_t mods,
+ const std::array<std::uint32_t, 4>& modifiers) {
+ if (!physical || !canonical) return ForegroundFailureReason::keyboard_state;
+ const auto state_failure = foreground_key_modifier_failure(modifiers, foreground_numlock_mask(physical),
+ foreground_caps_mask(physical));
+ if (state_failure != ForegroundFailureReason::none) return state_failure;
+ auto actual = foreground_xkb_state(physical);
+ auto expected = foreground_xkb_state(canonical);
+ auto intended = foreground_xkb_state(canonical);
+ if (!actual || !expected || !intended) return ForegroundFailureReason::keyboard_state;
+ if (modifiers[2]) {
+ const auto canonical_lock = foreground_numlock_mask(canonical);
+ if (!canonical_lock) return ForegroundFailureReason::keyboard_locked;
+ xkb_state_update_mask(actual.get(), 0, 0, modifiers[2], 0, 0, 0);
+ xkb_state_update_mask(expected.get(), 0, 0, canonical_lock, 0, 0, 0);
+ if (!foreground_same_modifier_state(actual.get(), expected.get()))
+ return ForegroundFailureReason::unsupported_layout;
+ }
+ auto failure = ForegroundFailureReason::none;
+ const auto event = [&](std::uint32_t key, xkb_key_direction direction) {
+ const xkb_keycode_t keycode = key + 8;
+ // A client interprets a press using the preceding modifiers event.
+ // Stock shift:both_capslock_cancel gives Shift a Caps_Lock symbol at
+ // its shifted level; that level is not another press. Releases pair
+ // by keycode, but their lock, latch, and group effects must agree.
+ if (direction == XKB_KEY_DOWN) {
+ if (!foreground_same_key_symbols(actual.get(), expected.get(), keycode) ||
+ !foreground_same_consumed_modifiers(actual.get(), expected.get(), keycode)) {
+ failure = ForegroundFailureReason::unsupported_layout;
+ return false;
+ }
+ if (!foreground_same_key_symbols(expected.get(), intended.get(), keycode) ||
+ !foreground_same_consumed_modifiers(expected.get(), intended.get(), keycode)) {
+ failure = ForegroundFailureReason::keyboard_numlock_keypad;
+ return false;
+ }
+ }
+ xkb_state_update_key(actual.get(), keycode, direction);
+ xkb_state_update_key(expected.get(), keycode, direction);
+ xkb_state_update_key(intended.get(), keycode, direction);
+ if (!foreground_same_modifier_state(actual.get(), expected.get())) {
+ failure = ForegroundFailureReason::unsupported_layout;
+ return false;
+ }
+ return true;
+ };
+ constexpr std::array<std::uint32_t, 4> keys{42, 29, 56, 125};
+ for (unsigned i = 0; i < keys.size(); ++i)
+ if ((mods & (1u << i)) && keys[i] != code && !event(keys[i], XKB_KEY_DOWN)) return failure;
+ if (!event(code, XKB_KEY_DOWN) || !event(code, XKB_KEY_UP)) return failure;
+ for (int i = 3; i >= 0; --i)
+ if ((mods & (1u << i)) && keys[i] != code && !event(keys[i], XKB_KEY_UP)) return failure;
+ return ForegroundFailureReason::none;
+}
+
+} // namespace cua::hyprland
diff --git a/libs/cua-driver/hyprland-plugin/src/plugin.cpp b/libs/cua-driver/hyprland-plugin/src/plugin.cpp
index 88b99002e8..4e92a2a03d 100644
--- a/libs/cua-driver/hyprland-plugin/src/plugin.cpp
+++ b/libs/cua-driver/hyprland-plugin/src/plugin.cpp
@@ -218,6 +218,18 @@ std::string status_output(bool json) {
if (json) {
auto result = cua::hyprland::render_status_json(report);
+#ifdef CUA_HYPRLAND_INPUT
+ // Compiled keyboard behavior of this loaded module, reported whether or
+ // not input is enabled, so an installer can tell it from an older module
+ // still loaded in the running compositor. keyboard_layout_independent:
+ // agent seats use a private canonical keymap, and foreground
+ // pointer-only actions do not depend on the physical layout.
+ // foreground_numlock_compatible: foreground keys keep the human
+ // keyboard's Num Lock and are admitted only when they mean the same
+ // thing under it.
+ result.pop_back();
+ result += R"(,"keyboard_layout_independent":true,"foreground_numlock_compatible":true})";
+#endif
#if defined(CUA_HYPRLAND_TEST_INPUT) || defined(CUA_HYPRLAND_INPUT)
if (g_experiment) {
#ifdef CUA_HYPRLAND_INPUT
diff --git a/libs/cua-driver/hyprland-plugin/tests/foreground_modifiers_test.py b/libs/cua-driver/hyprland-plugin/tests/foreground_modifiers_test.py
new file mode 100644
index 0000000000..3b80d16b11
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/foreground_modifiers_test.py
@@ -0,0 +1,339 @@
+"""Exercise production foreground keyboard admission, dispatch and unwind with XKB.
+
+The method bodies come from input_experiment.cpp, so a changed production call
+site changes the behavior under test. The compositor, seat and client objects
+are fakes: this is policy coverage, not evidence of Wayland delivery.
+
+Adapted from tests/foreground_modifiers_test.py in omacom/omarchy-pkgs#473
+(pkgbuilds/cua-hyprland-plugin/independent-keymaps.patch), by Spencer Bull.
+Copyright (c) David Heinemeier Hansson. Used under the MIT License, whose
+permission notice is the same as this repository's LICENSE.md.
+"""
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+REQUIRED = bool(os.environ.get('CUA_HYPRLAND_REQUIRE_XKBCOMMON'))
+
+FIXTURE = r'''
+#include "keymap_equivalence.hpp"
+#include <algorithm>
+#include <chrono>
+#include <cstdlib>
+#include <iostream>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+using namespace cua::hyprland;
+using Clock = std::chrono::steady_clock;
+void check(bool ok, const char* why) { if (!ok) { std::cerr << why << '\n'; std::exit(1); } }
+struct Vector2D { double x, y; };
+constexpr int WL_KEYBOARD_KEY_STATE_PRESSED = 1, WL_KEYBOARD_KEY_STATE_RELEASED = 0;
+constexpr int WL_POINTER_BUTTON_STATE_RELEASED = 0;
+struct Root : std::enable_shared_from_this<Root> {
+ bool good() const { return true; }
+ int client() const { return 0; }
+ auto at(Vector2D, bool) { return std::pair{shared_from_this(), 0}; }
+};
+struct Resource {
+ xkb_state* client = nullptr;
+ std::vector<xkb_keysym_t> symbols;
+ std::vector<std::array<unsigned, 4>> history;
+ bool good() const { return true; }
+ void sendKey(unsigned, unsigned code, unsigned down) {
+ if (down) symbols.push_back(xkb_state_key_get_one_sym(client, code + 8));
+ }
+ void sendMods(unsigned d, unsigned l, unsigned k, unsigned g) {
+ history.push_back({d, l, k, g});
+ xkb_state_update_mask(client, d, l, k, 0, 0, g);
+ }
+ void sendButton(unsigned, unsigned, unsigned) {}
+ void sendFrame() {}
+};
+struct Keyboard {
+ struct { unsigned depressed = 0, latched = 0, locked = 0, group = 0; } m_modifiersState;
+ xkb_keymap* m_xkbKeymap = nullptr;
+ bool m_enabled = true, shared = true, virt = false;
+ bool shareStates() const { return shared; }
+ bool isVirtual() const { return virt; }
+};
+struct Seat {
+ std::vector<std::shared_ptr<Resource>> m_keyboards, m_pointers;
+ bool good() const { return true; }
+};
+struct SeatManager {
+ std::weak_ptr<Keyboard> m_keyboard;
+ bool m_mouse = true;
+ struct { std::shared_ptr<Root> keyboardFocus, pointerFocus; } m_state;
+ std::shared_ptr<Seat> seat;
+ auto seatResourceForClient(int) { return seat; }
+ void setPointerFocus(std::shared_ptr<Root> root, Vector2D) { m_state.pointerFocus = root; }
+} manager, *g_pSeatManager = &manager;
+struct InputManager {
+ std::vector<std::shared_ptr<Keyboard>> m_keyboards;
+ bool shouldIgnoreVirtualKeyboard(const std::shared_ptr<Keyboard>&) { return false; }
+} input, *g_pInputManager = &input;
+namespace Desktop {
+constexpr int FOCUS_REASON_OTHER = 0;
+struct Focus {
+ std::shared_ptr<Root> root;
+ std::shared_ptr<Keyboard> change_on_focus;
+ auto window() { return root; }
+ auto surface() { return root; }
+ void fullWindowFocus(std::shared_ptr<Root>, int, std::shared_ptr<Root> r) {
+ root = r; manager.m_state.keyboardFocus = r;
+ if (change_on_focus) change_on_focus->m_modifiersState.locked = 0;
+ }
+} focus;
+auto focusState() { return &focus; }
+}
+namespace Pointer { struct Manager { void warpTo(Vector2D) {} } pointer; auto mgr() { return &pointer; } }
+struct Client {
+ InputRoute route = InputRoute::primary_foreground;
+ bool dead = false, foreground_attempted = false;
+ std::weak_ptr<Root> surface, window;
+ std::array<double, 6> geometry{100, 100, 400, 300, 100, 100};
+};
+struct Lane {
+ xkb_keymap* physical_keymap = nullptr;
+ xkb_keymap* keymap = nullptr;
+ xkb_state* physical_keyboard_state = nullptr;
+ std::array<std::uint32_t, 4> foreground_modifiers{};
+ std::vector<std::weak_ptr<Resource>> foreground_keyboards, foreground_pointers;
+ std::weak_ptr<Root> foreground_surface;
+ std::weak_ptr<Seat> foreground_seat;
+ std::vector<std::uint32_t> held_keys;
+ std::uint32_t held_button = 0;
+ bool foreground_started = false, foreground_activating = false, foreground_keyboard_used = false;
+ bool foreground_needs_keyboard = false, foreground_needs_pointer = false;
+ bool layout_ready = true, physical_held = false;
+ Client* lease = nullptr;
+ Clock::time_point expires = Clock::now() + std::chrono::hours(1);
+ unsigned consumed = 0, motions = 0;
+ bool available() const { return true; }
+ bool layout_qualified() const { return layout_ready; }
+ bool point(Client&, double, double) { return true; }
+ std::uint32_t event_ms() { return 0; }
+ void foreground_motion(Client&, double, double) { ++motions; }
+ ForegroundGuard foreground_guard(const Client&) const {
+ return {.exact_root = true, .physical_keys = physical_held, .exact_keyboard_focus = true,
+ .exact_pointer_focus = true};
+ }
+ bool consume_grant(Client&, std::uint64_t) { ++consumed; return true; }
+ // METHODS
+ void preflight(Client& c, const std::string& command, std::uint64_t code, std::uint64_t mods) {
+ const std::uint64_t cap = command == "KEY" ? 2 : 1;
+ const double x = 10, y = 10;
+ // PREFLIGHT
+ }
+ void key(Client& c, std::uint32_t code, std::uint32_t mods) {
+ preflight(c, "KEY", code, mods);
+ const std::array<std::uint32_t, 4> keys{42, 29, 56, 125};
+ for (unsigned i = 0; i < 4; ++i) if ((mods & (1u << i)) && keys[i] != code) foreground_key(c, keys[i], true);
+ foreground_key(c, code, true); foreground_key(c, code, false);
+ for (int i = 3; i >= 0; --i) if ((mods & (1u << i)) && keys[i] != code) foreground_key(c, keys[i], false);
+ finish();
+ }
+ void finish() {
+ finish_foreground();
+ if (physical_keyboard_state) xkb_state_unref(physical_keyboard_state);
+ physical_keyboard_state = xkb_state_new(physical_keymap);
+ }
+ ~Lane() { if (physical_keyboard_state) xkb_state_unref(physical_keyboard_state); }
+};
+ForegroundFailureReason refused(Lane& lane, Client& client, const std::string& command, unsigned code, unsigned mods) {
+ client.foreground_attempted = false; // TARGET admission resets this in production.
+ try { lane.preflight(client, command, code, mods); }
+ catch (const ForegroundFailure& failure) { lane.finish(); return failure.reason; }
+ lane.finish();
+ return ForegroundFailureReason::none;
+}
+int main() {
+ auto context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
+ const xkb_rule_names names{"evdev", "pc105", "us", "", "compose:caps,shift:both_capslock_cancel"};
+ auto physical = xkb_keymap_new_from_names(context, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
+ const xkb_rule_names agent{"evdev", "pc105", "us", "", ""};
+ auto canonical = xkb_keymap_new_from_names(context, &agent, XKB_KEYMAP_COMPILE_NO_FLAGS);
+ if (!physical || !canonical) { std::cout << "SKIP: XKB data unavailable\n"; return 77; }
+ auto keyboard = std::make_shared<Keyboard>(); keyboard->m_xkbKeymap = physical;
+ manager.m_keyboard = keyboard; input.m_keyboards = {keyboard};
+ auto root = std::make_shared<Root>();
+ manager.m_state.keyboardFocus = root; manager.m_state.pointerFocus = root; Desktop::focus.root = root;
+ manager.seat = std::make_shared<Seat>();
+ auto resource = std::make_shared<Resource>();
+ auto pointer = std::make_shared<Resource>();
+ resource->client = xkb_state_new(physical);
+ manager.seat->m_keyboards = {resource}; manager.seat->m_pointers = {pointer};
+ Client client; client.surface = root; client.window = root;
+ Lane lane; lane.physical_keymap = physical; lane.keymap = canonical;
+ lane.physical_keyboard_state = xkb_state_new(physical); lane.lease = &client;
+ const auto num = foreground_numlock_mask(physical);
+ const auto caps = foreground_caps_mask(physical);
+ check(num != 0 && caps != 0, "lock encodings unresolved");
+ using Reason = ForegroundFailureReason;
+
+ // Omarchy default: Num Lock on. Text types, and the client never sees
+ // Num Lock cleared: no modifier change around the action.
+ keyboard->m_modifiersState.locked = num;
+ xkb_state_update_mask(resource->client, 0, 0, num, 0, 0, 0);
+ lane.preflight(client, "KEY", 30, 1);
+ check(lane.foreground_started && lane.foreground_modifiers[2] == num,
+ "actual Num Lock state was not captured for delivery");
+ check(resource->history.empty(), "a modifier event was sent before the first key");
+ lane.foreground_key(client, 42, true); lane.foreground_key(client, 30, true);
+ lane.foreground_key(client, 30, false); lane.foreground_key(client, 42, false);
+ check(resource->symbols.back() == XKB_KEY_A, "client did not receive intended shifted text");
+ for (const auto& state : resource->history)
+ check(state[2] == num, "dispatch transiently cleared Num Lock");
+ lane.finish();
+ check(resource->history.back() == std::array<unsigned, 4>{0, 0, num, 0} &&
+ keyboard->m_modifiersState.locked == num,
+ "completion changed real or client Num Lock state");
+ lane.key(client, 2, 0);
+ check(resource->symbols.back() == XKB_KEY_1, "digit changed under Num Lock");
+
+ // Keypad keys whose meaning Num Lock changes refuse before the grant is used.
+ auto consumed = lane.consumed;
+ const auto sent = resource->history.size();
+ check(refused(lane, client, "KEY", 79, 0) == Reason::keyboard_numlock_keypad,
+ "Num Lock keypad semantics admitted");
+ check(lane.consumed == consumed && !client.foreground_attempted && resource->history.size() == sent,
+ "keypad refusal consumed the grant, activated, or sent input");
+ keyboard->m_modifiersState.locked = 0;
+ xkb_state_update_mask(resource->client, 0, 0, 0, 0, 0, 0);
+ lane.key(client, 79, 0);
+ check(resource->symbols.back() == XKB_KEY_KP_End, "neutral keypad contract changed");
+
+ // Caps Lock refuses keyboard actions by name, but never pointer actions.
+ keyboard->m_modifiersState.locked = caps;
+ consumed = lane.consumed;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::keyboard_caps_lock, "Caps Lock admitted text");
+ check(refused(lane, client, "KEY", 2, 0) == Reason::keyboard_caps_lock, "Caps Lock admitted a digit");
+ check(lane.consumed == consumed, "Caps Lock refusal consumed the grant");
+ keyboard->m_modifiersState.locked = caps | num;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::keyboard_caps_lock, "Caps and Num Lock admitted");
+ const auto motions = lane.motions;
+ check(refused(lane, client, "CLICK", 272, 0) == Reason::none && lane.motions == motions + 1,
+ "Caps Lock gated a pointer-only action");
+ keyboard->m_modifiersState.locked = 0x80;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::keyboard_locked, "unknown lock admitted");
+
+ // A human lock change during the action refuses the rest of it, and the
+ // unwind restores the current human state rather than a stale one.
+ keyboard->m_modifiersState.locked = num;
+ lane.preflight(client, "KEY", 30, 1); lane.foreground_key(client, 42, true);
+ keyboard->m_modifiersState.locked = 0;
+ try { lane.foreground_key(client, 30, true); check(false, "ambient state change accepted"); }
+ catch (const ForegroundFailure& f) { check(f.reason == Reason::keyboard_state, "wrong state change refusal"); }
+ lane.finish();
+ check(resource->history.back() == std::array<unsigned, 4>{}, "cancellation restored stale Num Lock");
+ keyboard->m_modifiersState.locked = num; lane.preflight(client, "KEY", 30, 1); lane.foreground_key(client, 42, true);
+ keyboard->m_modifiersState.locked = caps;
+ keyboard->m_modifiersState.depressed = xkb_keymap_mod_get_index(physical, XKB_MOD_NAME_CTRL) < 32 ?
+ 1u << xkb_keymap_mod_get_index(physical, XKB_MOD_NAME_CTRL) : 0;
+ lane.finish();
+ check(resource->history.back()[0] == keyboard->m_modifiersState.depressed &&
+ resource->history.back()[2] == keyboard->m_modifiersState.locked,
+ "cancellation failed to restore current human Caps Lock and held Control");
+ keyboard->m_modifiersState.depressed = 0; keyboard->m_modifiersState.locked = num;
+
+ // Held physical keys still refuse before activation.
+ lane.physical_held = true;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::physical_keys, "held physical key admitted");
+ lane.physical_held = false;
+
+ // Shared keyboards merge into the state the client sees.
+ auto shared = std::make_shared<Keyboard>(); shared->m_xkbKeymap = physical;
+ shared->m_modifiersState.locked = num;
+ keyboard->m_modifiersState.locked = 0;
+ input.m_keyboards.push_back(shared);
+ lane.preflight(client, "KEY", 30, 0);
+ check(lane.foreground_modifiers[2] == num, "shared Num Lock was ignored");
+ lane.foreground_key(client, 30, true); lane.foreground_key(client, 30, false); lane.finish();
+ check(resource->history.back()[2] == num, "shared Num Lock not restored");
+ shared->m_modifiersState.locked = caps;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::keyboard_caps_lock, "shared Caps Lock admitted");
+ shared->shared = false;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::none, "unshared keyboard state gated input");
+
+ // A differently encoded lock on another keyboard is not Num Lock.
+ const xkb_rule_names other{"evdev", "pc105", "us", "", ""};
+ auto other_map = xkb_keymap_new_from_names(context, &other, XKB_KEYMAP_COMPILE_NO_FLAGS);
+ shared->shared = true; shared->m_xkbKeymap = other_map; shared->m_modifiersState.locked = 0x40;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::keyboard_locked, "foreign lock encoding admitted");
+ input.m_keyboards.pop_back();
+
+ // Focus callbacks can change real state between admission and the first event.
+ keyboard->m_modifiersState.locked = num;
+ Desktop::focus.root.reset(); Desktop::focus.change_on_focus = keyboard;
+ const auto before_focus = resource->history.size();
+ check(refused(lane, client, "KEY", 30, 0) == Reason::keyboard_state, "focus-time state change accepted");
+ check(resource->history.size() == before_focus, "unused keyboard sent a modifier restore");
+ Desktop::focus.change_on_focus.reset();
+
+ // The up-front layout gate still applies to foreground keys.
+ lane.layout_ready = false; keyboard->m_modifiersState.locked = 0;
+ check(refused(lane, client, "KEY", 30, 0) == Reason::unsupported_layout, "unqualified layout admitted");
+ lane.layout_ready = true;
+
+ xkb_state_unref(resource->client); xkb_keymap_unref(other_map);
+ xkb_keymap_unref(physical); xkb_keymap_unref(canonical); xkb_context_unref(context);
+ std::cout << "foreground modifier tests passed\n";
+}
+'''
+
+
+def production_fixture(source):
+ methods = []
+ for name in ('capture_foreground_modifiers', 'require_foreground', 'finish_foreground',
+ 'start_foreground', 'foreground_key'):
+ body = re.search(r'^ \S[^\n]*\b' + name + r'\(.*?^ }', source, re.M | re.S)
+ if not body:
+ raise AssertionError(f'production method not found: {name}')
+ methods.append(body.group())
+ preflight = re.search(r' std::array<std::uint32_t, 4> modifiers\{\};\n if \(command == "KEY"\) \{.*?'
+ r' start_foreground\([^\n]*;', source, re.S)
+ if not preflight:
+ raise AssertionError('production foreground KEY preflight not found')
+ return FIXTURE.replace('// METHODS', '\n'.join(methods)).replace('// PREFLIGHT', preflight.group())
+
+
+def xkbcommon_flags():
+ if shutil.which('pkg-config') is None:
+ return None
+ result = subprocess.run(['pkg-config', '--cflags', '--libs', 'xkbcommon'], capture_output=True, text=True)
+ return shlex.split(result.stdout) if result.returncode == 0 else None
+
+
+class ForegroundModifiersTest(unittest.TestCase):
+ def test_production_modifiers(self):
+ fixture = production_fixture((ROOT / 'src/input_experiment.cpp').read_text())
+ flags = xkbcommon_flags()
+ if flags is None:
+ if REQUIRED:
+ self.fail('xkbcommon development files are required')
+ self.skipTest('xkbcommon development files unavailable')
+ compiler = shlex.split(os.environ.get('CXX', '')) or [
+ shutil.which('clang++-18') or shutil.which('clang++') or 'c++']
+ with tempfile.TemporaryDirectory(prefix='cua-foreground-modifiers-') as directory:
+ cpp, binary = Path(directory) / 'fixture.cpp', Path(directory) / 'fixture'
+ cpp.write_text(fixture)
+ build = subprocess.run([*compiler, '-std=c++20', '-Wall', '-Wextra', '-Wpedantic', '-Werror',
+ '-I', str(ROOT / 'src'), str(cpp), '-o', str(binary), *flags],
+ capture_output=True, text=True, timeout=120)
+ self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
+ result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=30)
+ if result.returncode == 77 and not REQUIRED:
+ self.skipTest('XKB data unavailable')
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp b/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp
index d3351362d9..9ae38a9b39 100644
--- a/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp
+++ b/libs/cua-driver/hyprland-plugin/tests/foreground_route_test.cpp
@@ -16,12 +16,29 @@ int main() {
"foreground_physical_pointer", "foreground_pointer_target", "foreground_seat_resource",
"foreground_pointer_resources", "foreground_keyboard_resources", "foreground_keyboard_depressed",
"foreground_keyboard_latched", "foreground_keyboard_locked", "foreground_keyboard_group",
+ "foreground_keyboard_caps_lock", "foreground_keyboard_numlock_keypad",
};
- static_assert(labels.size() == static_cast<unsigned>(ForegroundFailureReason::keyboard_group) + 1);
+ static_assert(labels.size() == static_cast<unsigned>(ForegroundFailureReason::keyboard_numlock_keypad) + 1);
for (unsigned i = 0; i < labels.size(); ++i)
check(ForegroundFailure{static_cast<ForegroundFailureReason>(i)}.detail() == labels[i]);
check(ForegroundFailure::code(false) == "primary_target_busy");
check(ForegroundFailure::code(true) == "foreground_partial_unknown");
+ // Locks stay on. Only a Num Lock mask resolved through the live keymap is
+ // admitted to the chord check; Caps Lock and any other lock refuse with
+ // their own reasons. Omarchy turns Num Lock on by default.
+ constexpr std::uint32_t num = 0x10, caps = 0x2;
+ const std::array<std::uint32_t, 4> num_lock{0, 0, num, 0};
+ check(foreground_key_modifier_failure(num_lock) == ForegroundFailureReason::keyboard_locked);
+ check(foreground_key_modifier_failure(num_lock, num, caps) == ForegroundFailureReason::none);
+ check(foreground_key_modifier_failure({0, 0, caps, 0}, num, caps) == ForegroundFailureReason::keyboard_caps_lock);
+ check(foreground_key_modifier_failure({0, 0, caps | num, 0}, num, caps) ==
+ ForegroundFailureReason::keyboard_caps_lock);
+ check(foreground_key_modifier_failure({0, 0, 0x80 | num, 0}, num, caps) == ForegroundFailureReason::keyboard_locked);
+ check(foreground_key_modifier_failure({0, 0, 0x80, 0}, 0, caps) == ForegroundFailureReason::keyboard_locked);
+ check(foreground_key_modifier_failure({1, 0, num, 0}, num, caps) == ForegroundFailureReason::keyboard_depressed);
+ check(foreground_key_modifier_failure({0, 1, num, 0}, num, caps) == ForegroundFailureReason::keyboard_latched);
+ check(foreground_key_modifier_failure({0, 0, num, 1}, num, caps) == ForegroundFailureReason::keyboard_group);
+ check(foreground_key_modifier_failure({0, 0, 0, 0}, num, caps) == ForegroundFailureReason::none);
// Exhaust every guard combination against the original admission predicates.
for (unsigned bits = 0; bits < 1024; ++bits) {
diff --git a/libs/cua-driver/hyprland-plugin/tests/keyboard_layout_test.cpp b/libs/cua-driver/hyprland-plugin/tests/keyboard_layout_test.cpp
new file mode 100644
index 0000000000..ae960decc1
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/keyboard_layout_test.cpp
@@ -0,0 +1,179 @@
+// Adapted from tests/keyboard_layout_test.cpp in omacom/omarchy-pkgs#473
+// (pkgbuilds/cua-hyprland-plugin/independent-keymaps.patch), by Spencer Bull.
+// Copyright (c) David Heinemeier Hansson. Used under the MIT License, whose
+// permission notice is the same as this repository's LICENSE.md.
+#include "keymap_equivalence.hpp"
+
+#include <cstdio>
+#include <cstdlib>
+#include <iostream>
+#include <memory>
+#include <string>
+
+using namespace cua::hyprland;
+namespace {
+void check(bool condition, const char* message) {
+ if (!condition) { std::cerr << "FAILED: " << message << '\n'; std::exit(1); }
+}
+using Reason = ForegroundFailureReason;
+using Mods = std::array<std::uint32_t, 4>;
+}
+
+int main() {
+ using Context = std::unique_ptr<xkb_context, decltype(&xkb_context_unref)>;
+ using Map = std::unique_ptr<xkb_keymap, decltype(&xkb_keymap_unref)>;
+ Context context{xkb_context_new(XKB_CONTEXT_NO_FLAGS), xkb_context_unref};
+ const auto map = [&](const char* layout, const char* variant, const char* options) {
+ const xkb_rule_names names{"evdev", "pc105", layout, variant, options};
+ return Map{context ? xkb_keymap_new_from_names(context.get(), &names, XKB_KEYMAP_COMPILE_NO_FLAGS) : nullptr,
+ xkb_keymap_unref};
+ };
+ const xkb_rule_names agent_names{kAgentKeymap.rules.data(), kAgentKeymap.model.data(),
+ kAgentKeymap.layout.data(), kAgentKeymap.variant.data(), kAgentKeymap.options.data()};
+ Map agent{context ? xkb_keymap_new_from_names(context.get(), &agent_names, XKB_KEYMAP_COMPILE_NO_FLAGS) : nullptr,
+ xkb_keymap_unref};
+ if (!agent) {
+ if (std::getenv("CUA_HYPRLAND_REQUIRE_XKBCOMMON")) check(false, "XKB data unavailable");
+ std::puts("SKIP: XKB data unavailable");
+ return 77;
+ }
+ const auto chord = [&](xkb_keymap* physical, std::uint32_t code, std::uint32_t mods, const Mods& state) {
+ return foreground_chord_failure(physical, agent.get(), code, mods, state);
+ };
+ auto stock = map("us", "", "compose:caps,shift:both_capslock_cancel");
+ auto nocaps = map("us", "", "ctrl:nocaps");
+ auto swapctrl = map("us", "", "ctrl:swapcaps");
+ auto swapalt = map("us", "", "altwin:swap_alt_win");
+ auto german = map("de", "", "");
+ check(stock && nocaps && swapctrl && swapalt && german, "test keymaps unavailable");
+
+ // Hyprland's numlock_by_default locks Mod2; the resolved mask must agree.
+ for (auto* physical : {agent.get(), stock.get(), nocaps.get(), german.get()}) {
+ check(foreground_numlock_mask(physical) == 0x10, "Num Lock does not resolve to Mod2");
+ check(foreground_caps_mask(physical) == 0x2, "Caps Lock does not resolve to Lock");
+ }
+ check(foreground_numlock_mask(nullptr) == 0 && foreground_caps_mask(nullptr) == 0, "missing map resolved a lock");
+
+ // Omarchy's default options pass the up-front typing qualification.
+ check(typing_keymap_equivalent(stock.get(), agent.get()), "Omarchy default options refused");
+ check(typing_keymap_equivalent(nocaps.get(), agent.get()), "Caps to Ctrl refused");
+
+ // The chord check compares meaning only: unrelated remaps are harmless,
+ // requested remaps fail closed.
+ for (auto* physical : {stock.get(), nocaps.get(), swapctrl.get(), swapalt.get(), german.get()}) {
+ check(chord(physical, 30, 0, {}) == Reason::none, "unrelated remap blocked A");
+ check(chord(physical, 30, 1, {}) == Reason::none, "unrelated remap blocked Shift+A");
+ check(chord(physical, 28, 0, {}) == Reason::none, "unrelated remap blocked Return");
+ }
+ check(chord(stock.get(), 30, 2, {}) == Reason::none, "stock Omarchy blocked Ctrl+A");
+ check(chord(nocaps.get(), 30, 2, {}) == Reason::none, "Caps to Ctrl blocked Ctrl+A");
+ check(chord(swapctrl.get(), 30, 2, {}) == Reason::unsupported_layout, "Ctrl/Caps swap sent wrong Ctrl+A");
+ check(chord(swapctrl.get(), 29, 0, {}) == Reason::unsupported_layout, "remapped modifier key accepted");
+ check(chord(swapalt.get(), 30, 4, {}) == Reason::unsupported_layout, "Alt/Super swap sent wrong Alt+A");
+ check(chord(swapalt.get(), 30, 8, {}) == Reason::unsupported_layout, "Alt/Super swap sent wrong Super+A");
+ check(chord(german.get(), 21, 0, {}) == Reason::unsupported_layout, "German Z accepted as US Y");
+ check(chord(german.get(), 3, 1, {}) == Reason::unsupported_layout, "German shifted punctuation accepted");
+ check(chord(nullptr, 30, 0, {}) == Reason::keyboard_state, "missing physical map accepted");
+
+ for (auto* physical : {agent.get(), stock.get(), nocaps.get()}) {
+ const auto numlock = foreground_numlock_mask(physical);
+ for (const auto locked : {0u, numlock}) {
+ const Mods ambient{0, 0, locked, 0};
+ // Driver text and shortcuts keep working with Num Lock on.
+ for (const auto key : {30u, 48u, 44u, 2u, 11u, 12u, 28u, 57u, 14u, 15u, 1u, 103u, 105u, 111u})
+ for (const auto mods : {0u, 1u, 2u, 3u})
+ check(chord(physical, key, mods, ambient) == Reason::none,
+ "Num Lock blocked ordinary text, navigation, or shortcut");
+ // Keypad keys whose meaning Num Lock changes refuse with their own reason.
+ for (const auto key : {71u, 72u, 73u, 75u, 76u, 77u, 79u, 80u, 81u, 82u, 83u})
+ check(chord(physical, key, 0, ambient) == (locked ? Reason::keyboard_numlock_keypad : Reason::none),
+ "Num Lock keypad semantic change was ignored");
+ // Keypad operators mean the same thing either way.
+ for (const auto key : {55u, 74u, 78u, 96u, 98u})
+ check(chord(physical, key, 0, ambient) == Reason::none, "Num Lock blocked a keypad operator");
+ }
+ const auto caps = foreground_caps_mask(physical);
+ check(chord(physical, 30, 0, {0, 0, caps, 0}) == Reason::keyboard_caps_lock, "Caps Lock accepted");
+ check(chord(physical, 2, 0, {0, 0, caps, 0}) == Reason::keyboard_caps_lock, "Caps Lock accepted for a digit");
+ check(chord(physical, 30, 0, {0, 0, caps | numlock, 0}) == Reason::keyboard_caps_lock,
+ "Caps Lock with Num Lock accepted");
+ check(chord(physical, 30, 0, {0, 0, 0x80000000u, 0}) == Reason::keyboard_locked, "unknown lock accepted");
+ check(chord(physical, 30, 0, {0, 0, 0x80000000u | numlock, 0}) == Reason::keyboard_locked,
+ "unknown lock with Num Lock accepted");
+ check(chord(physical, 30, 0, {numlock, 0, numlock, 0}) == Reason::keyboard_depressed,
+ "held modifier accepted with Num Lock");
+ check(chord(physical, 30, 0, {0, numlock, numlock, 0}) == Reason::keyboard_latched,
+ "latched modifier accepted with Num Lock");
+ check(chord(physical, 30, 0, {0, 0, numlock, 1}) == Reason::keyboard_group,
+ "nonzero group accepted with Num Lock");
+ }
+ const auto numlock = foreground_numlock_mask(agent.get());
+ check(chord(swapctrl.get(), 30, 2, {0, 0, numlock, 0}) == Reason::unsupported_layout, "Num Lock hid Ctrl remap");
+ check(chord(german.get(), 21, 0, {0, 0, numlock, 0}) == Reason::unsupported_layout, "Num Lock hid layout mismatch");
+
+ // Every supported wire chord stays compatible on the canonical map.
+ for (unsigned code = 1; code <= 247; ++code)
+ if (!foreground_lock_key(code))
+ for (unsigned mods = 0; mods < 16; ++mods)
+ check(chord(agent.get(), code, mods, {}) == Reason::none, "canonical chord rejected");
+
+ // Equal symbols can hide a changed XKB action. Simulate an A that locks Mod3.
+ char* serialized = xkb_keymap_get_as_string(agent.get(), XKB_KEYMAP_FORMAT_TEXT_V1);
+ check(serialized != nullptr, "canonical keymap cannot serialize");
+ const std::string canonical_text = serialized;
+ std::free(serialized);
+ const auto compile = [&](const std::string& text) {
+ return Map{xkb_keymap_new_from_string(context.get(), text.c_str(), XKB_KEYMAP_FORMAT_TEXT_V1,
+ XKB_KEYMAP_COMPILE_NO_FLAGS), xkb_keymap_unref};
+ };
+ std::string changed = canonical_text;
+ const auto at = changed.find("key <AC01>");
+ const auto end = changed.find(';', at);
+ check(at != std::string::npos && end != std::string::npos, "test action fixture unavailable");
+ changed.replace(at, end - at + 1,
+ "key <AC01> { type=\"ALPHABETIC\", symbols[Group1]=[a,A], "
+ "actions[Group1]=[LockMods(modifiers=Mod3),LockMods(modifiers=Mod3)] };");
+ auto lock = compile(changed);
+ check(bool(lock), "action fixture failed to compile");
+ check(chord(lock.get(), 30, 0, {}) == Reason::unsupported_layout, "hidden lock action accepted");
+ check(chord(lock.get(), 30, 0, {0, 0, numlock, 0}) == Reason::unsupported_layout,
+ "Num Lock hid an unexpected lock action");
+
+ // Equal symbols and modifier state can still alter toolkit shortcut matching.
+ changed = canonical_text;
+ const auto type_at = changed.find("type \"ALPHABETIC\"");
+ const auto type_end = changed.find("};", type_at);
+ check(type_at != std::string::npos && type_end != std::string::npos, "key type fixture unavailable");
+ changed.insert(type_end, "preserve[Shift] = Shift;\n");
+ auto preserved = compile(changed);
+ check(bool(preserved), "preserved modifier fixture failed to compile");
+ check(chord(preserved.get(), 30, 1, {}) == Reason::unsupported_layout, "consumed modifier mismatch accepted");
+ check(chord(preserved.get(), 30, 1, {0, 0, numlock, 0}) == Reason::unsupported_layout,
+ "Num Lock hid changed shortcut consumption");
+
+ // A modifier that sets Shift but emits another symbol must fail.
+ changed = canonical_text;
+ const auto shift_at = changed.find("key <LFSH>");
+ const auto shift_end = changed.find(';', shift_at);
+ check(shift_at != std::string::npos && shift_end != std::string::npos, "shift fixture unavailable");
+ changed.replace(shift_at, shift_end - shift_at + 1,
+ "key <LFSH> { symbols[Group1]=[Delete], actions[Group1]=[SetMods(modifiers=Shift)] };");
+ auto badshift = compile(changed);
+ check(bool(badshift), "shift fixture failed to compile");
+ check(chord(badshift.get(), 30, 1, {}) == Reason::unsupported_layout, "modifier press symbols not checked");
+
+ // A keymap whose Num Lock key locks something other than one modifier
+ // resolves no Num Lock, so an ambient lock refuses instead of guessing.
+ changed = canonical_text;
+ const auto nmlk_at = changed.find("key <NMLK>");
+ const auto nmlk_end = changed.find(';', nmlk_at);
+ check(nmlk_at != std::string::npos && nmlk_end != std::string::npos, "Num Lock fixture unavailable");
+ changed.replace(nmlk_at, nmlk_end - nmlk_at + 1,
+ "key <NMLK> { symbols[Group1]=[Num_Lock], actions[Group1]=[LockMods(modifiers=Mod2+Mod3)] };");
+ auto ambiguous = compile(changed);
+ check(bool(ambiguous), "ambiguous Num Lock fixture failed to compile");
+ check(foreground_numlock_mask(ambiguous.get()) == 0, "ambiguous Num Lock encoding admitted");
+ check(chord(ambiguous.get(), 30, 0, {0, 0, 0x10, 0}) == Reason::keyboard_locked,
+ "lock accepted without a resolved Num Lock");
+ std::cout << "keyboard layout tests passed\n";
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/keymap_equivalence_test.cpp b/libs/cua-driver/hyprland-plugin/tests/keymap_equivalence_test.cpp
new file mode 100644
index 0000000000..e90c3bf175
--- /dev/null
+++ b/libs/cua-driver/hyprland-plugin/tests/keymap_equivalence_test.cpp
@@ -0,0 +1,79 @@
+#include "keymap_equivalence.hpp"
+
+#include <cstdio>
+#include <cstdlib>
+#include <fstream>
+#include <iterator>
+#include <string>
+
+using namespace cua::hyprland;
+
+namespace {
+
+void check(bool value, const char* what) {
+ if (!value) {
+ std::fprintf(stderr, "FAILED: %s\n", what);
+ std::abort();
+ }
+}
+
+xkb_keymap* compile(xkb_context* context, const char* layout, const char* variant, const char* options) {
+ const xkb_rule_names names{"evdev", "pc105", layout, variant, options};
+ return xkb_keymap_new_from_names(context, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
+}
+
+struct Case {
+ const char* layout;
+ const char* variant;
+ const char* options;
+ bool equivalent;
+ const char* what;
+};
+
+}
+
+// With a path argument, reports whether that keymap (for example the output of
+// `xkbcli dump-keymap-wayland`) qualifies for foreground typing.
+int main(int argc, char** argv) {
+ check(foreground_lock_key(58) && foreground_lock_key(69) && foreground_lock_key(70), "lock keys");
+ check(foreground_modifier_key(42) && !foreground_modifier_key(30), "modifier keys");
+ auto* context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
+ auto* us = context ? compile(context, "us", "", "") : nullptr;
+ if (!us) {
+ check(!std::getenv("CUA_HYPRLAND_REQUIRE_XKBCOMMON"), "XKB data unavailable");
+ std::puts("SKIP: XKB data unavailable");
+ return 77;
+ }
+ if (argc > 1) {
+ std::ifstream file(argv[1]);
+ const std::string text{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
+ auto* map = xkb_keymap_new_from_string(context, text.c_str(), XKB_KEYMAP_FORMAT_TEXT_V1,
+ XKB_KEYMAP_COMPILE_NO_FLAGS);
+ check(map != nullptr, "keymap file compiles");
+ const bool equivalent = typing_keymap_equivalent(map, us);
+ std::puts(equivalent ? "equivalent" : "different");
+ xkb_keymap_unref(map);
+ xkb_keymap_unref(us);
+ xkb_context_unref(context);
+ return equivalent ? 0 : 1;
+ }
+ const Case cases[] = {
+ {"us", "", "", true, "canonical us"},
+ {"us", "", "compose:caps,shift:both_capslock_cancel", true, "Omarchy default options"},
+ {"us", "", "caps:escape", true, "Caps Lock remap"},
+ {"de", "", "", false, "German layout"},
+ {"us", "dvorak", "", false, "Dvorak variant"},
+ {"us", "", "altwin:swap_alt_win", false, "Alt/Super swap"},
+ {"us", "", "ctrl:swapcaps", false, "Ctrl/Caps swap"},
+ };
+ for (const auto& test : cases) {
+ auto* map = compile(context, test.layout, test.variant, test.options);
+ check(map != nullptr, test.what);
+ check(typing_keymap_equivalent(map, us) == test.equivalent, test.what);
+ xkb_keymap_unref(map);
+ }
+ check(!typing_keymap_equivalent(nullptr, us), "missing keymap");
+ xkb_keymap_unref(us);
+ xkb_context_unref(context);
+ return 0;
+}
diff --git a/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cpp b/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cpp
index d0edfa54e2..ccfcfd0b35 100644
--- a/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cpp
+++ b/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cpp
@@ -114,6 +114,9 @@ int main() {
std::string::npos &&
json_text.find(R"("enabled":[])") != std::string::npos,
"disabled plugin status cannot advertise mutation or transport readiness");
+ check(json_text.find("keyboard_layout_independent") == std::string::npos &&
+ json_text.find("foreground_numlock_compatible") == std::string::npos,
+ "discovery-only status cannot advertise input keyboard behavior");
check(Event::bus()->m_events.config.reloaded.active_count() == 1,
"plugin owns one config-reload listener while loaded");
pluginExit();
diff --git a/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp b/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp
index ff09451d63..135f07e4df 100644
--- a/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp
+++ b/libs/cua-driver/hyprland-plugin/tests/plugin_input_lifetime_test.cpp
@@ -4,6 +4,7 @@
#include <array>
#include <cstdlib>
#include <iostream>
+#include <string>
#include <sys/stat.h>
#include <unistd.h>
@@ -19,6 +20,16 @@ void check(bool value, const char* message) {
std::exit(1);
}
}
+// Omarchy's Cua Input toggle checks both fields before enabling input, to tell
+// this module from an older one still loaded. Keep these exact names.
+[[maybe_unused]] bool advertises_keyboard_behavior(const std::string& status) {
+ return status.find(R"("keyboard_layout_independent":true)") != std::string::npos &&
+ status.find(R"("foreground_numlock_compatible":true)") != std::string::npos;
+}
+[[maybe_unused]] bool mentions_keyboard_behavior(const std::string& status) {
+ return status.find("keyboard_layout_independent") != std::string::npos ||
+ status.find("foreground_numlock_compatible") != std::string::npos;
+}
}
// This mock tests the entry point's ownership decisions, not native wl_seat
@@ -51,8 +62,17 @@ int main() {
check(setenv("XDG_RUNTIME_DIR", directory, 1) == 0 &&
setenv("HYPRLAND_INSTANCE_SIGNATURE", "mock", 1) == 0,
"select runtime");
- Config::Values::configured_bool_override = true;
+ Config::Values::configured_bool_override = false;
static_cast<void>(pluginInit(nullptr));
+ const auto initial_status = HyprlandAPI::registered_legacy_command->fn(FORMAT_JSON, {});
+ check(created == 0 && initial_status.find(R"("configured":false)") != std::string::npos,
+ "plugin starts with input disabled");
+#ifdef CUA_HYPRLAND_INPUT
+ check(advertises_keyboard_behavior(initial_status),
+ "disabled v3 module advertises its compiled keyboard behavior before enable");
+#else
+ check(!mentions_keyboard_behavior(initial_status), "experiment advertises v3 keyboard behavior");
+#endif
const auto toggle = [](bool enabled) {
HyprlandAPI::registered_bool->set_mock_value(enabled);
Event::bus()->m_events.config.reloaded.emit();
@@ -66,6 +86,12 @@ int main() {
status.find("\"input\":{}") != std::string::npos &&
status.find("operator") == std::string::npos,
"v3 status advertises its actual admission mode");
+ check(advertises_keyboard_behavior(status) && status.back() == '}' &&
+ status.find(R"("foreground_numlock_compatible":true,"input":{}})") != std::string::npos,
+ "enabled v3 status keeps both keyboard fields in one JSON object");
+#else
+ check(!mentions_keyboard_behavior(HyprlandAPI::registered_legacy_command->fn(FORMAT_JSON, {})),
+ "experiment advertises v3 keyboard behavior");
#endif
check(created == 1 && destroyed == 0 && resumed == i + 1,
"enable reuses the session's seat owner");
@@ -74,6 +100,10 @@ int main() {
toggle(false);
check(destroyed == 0 && access(socket.c_str(), F_OK) != 0,
"disable stops transport but retains seat owner");
+#ifdef CUA_HYPRLAND_INPUT
+ check(advertises_keyboard_behavior(HyprlandAPI::registered_legacy_command->fn(FORMAT_JSON, {})),
+ "disabled v3 module keeps advertising its keyboard behavior");
+#endif
}
fail_resume = true;
toggle(true);
diff --git a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
index 4def10ac17..585a2ab743 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
@@ -314,8 +314,14 @@ held physical input, grabs, constraints, drag-and-drop, ambiguous primary seat
bindings, and non-neutral keyboard modifiers. Background refusal never selects
this route automatically. Driver expands bounded ASCII text under the exact
US keymap; Unicode and IME remain outside its raw-input scope. Foreground
-pointer-only actions are layout-independent, but foreground keyboard actions
-still require the canonical physical US map.
+pointer-only actions are layout-independent. Foreground keyboard actions leave
+the user's Num Lock and Caps Lock untouched. They work with Num Lock on and with
+keymap options that leave every typing and modifier key unchanged, such as
+`compose:caps`. They refuse before any input under Caps Lock
+(`foreground_keyboard_caps_lock`), for a keypad key that Num Lock changes
+(`foreground_keyboard_numlock_keypad`), and for a different layout or remapped
+key (`foreground_unsupported_layout`). Ask the user to turn Caps Lock off, or
+use the equivalent non-keypad key, instead of retrying the same call.
The retained bounded app evidence at source
`f180e8828b8f31cc153e3c44eaa89a9c13c5bc68` includes instrumented Calc/Inkscape