From 5cf8709912df9b198fae571cd237ca5de8392864 Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 2 Oct 2026 11:30:17 -0400 Subject: [PATCH] Add M9.8d rebindable engineering controls SDL-free action/HID-key bindings with conflict validation, a staging editor and a versioned all-or-nothing controls file (ADR-0085). The adapter maps keys through the bindings, releases and drains on rebinding, and captures the chosen key ahead of the toolkit and world. The client adds a Controls panel, key hints, startup loading with a bounded rejection notice, and --controls/--show-controls. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 7 +- CMakePresets.json | 4 +- apps/evo-client/main.cpp | 95 ++++- apps/evo-client/panels.cpp | 92 ++++- apps/evo-client/panels.hpp | 17 +- deploy/docker/Dockerfile | 4 +- docs/ROADMAP.md | 3 +- docs/STATUS.md | 5 +- .../0085-rebindable-engineering-controls.md | 64 +++ docs/adr/README.md | 3 +- docs/architecture/CLIENT_ARCHITECTURE.md | 4 + docs/engineering/CAMERA_INPUT.md | 11 +- docs/engineering/CLIENT.md | 11 +- docs/engineering/CLIENT_UI_STATE.md | 13 + docs/engineering/M9_8_DELIVERY_PLAN.md | 6 +- docs/engineering/VALIDATION.md | 41 ++ include/evo/client/application.hpp | 19 +- include/evo/client/bindings.hpp | 112 ++++++ src/client/input/bindings.cpp | 369 ++++++++++++++++++ src/client/platform/application.cpp | 93 +++-- tests/client_bindings.cpp | 186 +++++++++ tests/client_lifecycle.cpp | 101 +++++ tests/client_panels.cpp | 77 ++++ 23 files changed, 1292 insertions(+), 45 deletions(-) create mode 100644 docs/adr/0085-rebindable-engineering-controls.md create mode 100644 include/evo/client/bindings.hpp create mode 100644 src/client/input/bindings.cpp create mode 100644 tests/client_bindings.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d908216..3faab06 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -97,7 +97,7 @@ include(CTest) if(EVO_BUILD_CLIENT OR EVO_BUILD_NETWORK) # SDL-free client value contracts (M9.3-M9.5), shared by the client and the dev # session codec. They copy read-only world/biology views, never the reverse. - add_library(evo_client_controls STATIC src/client/camera/camera.cpp src/client/input/input.cpp src/client/ui/ui_state.cpp src/client/ui/outcome_log.cpp) + add_library(evo_client_controls STATIC src/client/camera/camera.cpp src/client/input/input.cpp src/client/input/bindings.cpp src/client/ui/ui_state.cpp src/client/ui/outcome_log.cpp) target_include_directories(evo_client_controls PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") evo_owned_target(evo_client_controls) if(BUILD_TESTING) @@ -106,6 +106,11 @@ if(EVO_BUILD_CLIENT OR EVO_BUILD_NETWORK) evo_owned_target(evo-client-state-tests) add_test(NAME client-ui-state COMMAND evo-client-state-tests) set_tests_properties(client-ui-state PROPERTIES TIMEOUT 30 LABELS "client") + add_executable(evo-client-bindings-tests tests/client_bindings.cpp) + target_link_libraries(evo-client-bindings-tests PRIVATE evo_client_controls) + evo_owned_target(evo-client-bindings-tests) + add_test(NAME client-bindings COMMAND evo-client-bindings-tests) + set_tests_properties(client-bindings PROPERTIES TIMEOUT 30 LABELS "client") endif() add_library(evo_client_views STATIC src/client/views/environment_view.cpp src/client/views/organism_view.cpp) target_link_libraries(evo_client_views PUBLIC evo::world evo::biology) diff --git a/CMakePresets.json b/CMakePresets.json index e998106..9b008f8 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -19,10 +19,10 @@ {"name": "analysis", "configurePreset": "analysis"}, {"name": "asan", "configurePreset": "asan"}, {"name": "tsan", "configurePreset": "tsan"}, - {"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests"]}, + {"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests"]}, {"name": "client-probe", "configurePreset": "client-probe", "targets": ["evo-client-probe"]}, {"name": "network", "configurePreset": "network", "targets": ["evo-client-state-tests", "evo-network-tests", "evo-dev-session"]}, - {"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-network-tests", "evo-dev-session"]} + {"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-dev-session"]} ], "testPresets": [ {"name": "debug", "configurePreset": "debug", "output": {"outputOnFailure": true}}, diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index 73e2d4b..207e1e1 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -214,6 +215,8 @@ int main(int argc, char** argv) try { bool start_fixture = false; std::optional scripted_pick; std::string screenshot; + std::filesystem::path controls_path; // Empty: per-user settings directory. + bool show_controls = false; evo::render::EnvironmentDisplay display; evo::client::ConnectForm form; bool connect_now = false; @@ -251,6 +254,12 @@ int main(int argc, char** argv) try { return 2; } else if (arg == "--screenshot" && i + 1 < argc) { // Last frame, as BMP. screenshot = argv[++i]; + } else if (arg == "--controls" && i + 1 < argc) { + controls_path = argv[++i]; + if (controls_path.empty()) + return 2; + } else if (arg == "--show-controls") { // Engineering review: open the panel. + show_controls = true; } else { std::fputs("usage: evo-client [--renderer NAME] [--hidden] [--frames 1..100000]\n" " [--fixture | --connect HOST:PORT --server-name NAME " @@ -258,6 +267,7 @@ int main(int argc, char** argv) try { " [--layer water|nitrogen|...|heat|moisture]\n" " [--refresh-every 1..1000] [--pick X,Y] " "[--screenshot FILE.bmp --frames N]\n" + " [--controls FILE] [--show-controls]\n" "Without --fixture or --connect the launcher opens.\n", stderr); return 2; @@ -327,6 +337,29 @@ int main(int argc, char** argv) try { } // A minimized native window may start with no drawable area. Adopt the // native viewport before projecting; until then use the requested size. + // Controls (ADR-0085): an invalid file is reported and left untouched; defaults + // apply until the user saves new bindings. + if (controls_path.empty()) + if (const auto dir = evo::client::Application::settings_directory()) + controls_path = *dir / "controls-v1.txt"; + if (std::error_code missing; + !controls_path.empty() && std::filesystem::exists(controls_path, missing)) { + // Notices expire on the same monotonic clock the loop uses. + static_cast(ui.advance(milliseconds(std::chrono::steady_clock::now())).has_value()); + if (const auto loaded = evo::client::load_bindings(controls_path)) + (*app)->set_bindings(*loaded); + else + static_cast( + ui.notify("Saved controls rejected: " + evo::client::describe(loaded.error()) + + " Default controls are in use; the file was not changed.", + evo::client::NoticeLevel::warning, 15000) + .has_value()); + } + std::optional editor; + std::optional capturing; + std::optional controls_problem; + if (show_controls) + editor.emplace((*app)->bindings()); auto camera = evo::client::Camera::create( {config.width, config.height, config.width, config.height}, {}, 0.05); if (!camera) @@ -371,6 +404,10 @@ int main(int argc, char** argv) try { view.outcomes = &remote->outcomes(); } view.visible_organisms = drawn_organisms; + view.bindings = &(*app)->bindings(); + view.controls = editor ? &*editor : nullptr; + view.capturing = capturing; + view.controls_problem = controls_problem; actions = evo::client_app::draw_panels(view, buffers, display); }); std::vector boxes; @@ -414,9 +451,65 @@ int main(int argc, char** argv) try { disconnect_dialog.reset(); if (actions.dismiss_notice) static_cast(ui.dismiss(*actions.dismiss_notice)); + if (actions.open_controls && !editor) { + editor.emplace((*app)->bindings()); + controls_problem.reset(); + } + if (editor) { + if (actions.capture_key && !capturing) { + capturing = actions.capture_key; + controls_problem.reset(); + (*app)->begin_key_capture(); + } + if (actions.cancel_capture && capturing) { + (*app)->cancel_key_capture(); + capturing.reset(); + } + if (actions.clear_secondary) + editor->clear_secondary(*actions.clear_secondary); + if (actions.reset_controls) { + editor->reset_defaults(); + controls_problem.reset(); + } + if (actions.apply_controls) { + if (const auto applied = editor->apply(); !applied) { + controls_problem = applied.error(); + } else { + (*app)->set_bindings(*applied); // Releases held actions. + const bool saved = !controls_path.empty() && + evo::client::save_bindings(*applied, controls_path); + static_cast( + ui.notify(saved ? "Controls saved." + : "Controls apply to this session but could not be saved.", + saved ? evo::client::NoticeLevel::info + : evo::client::NoticeLevel::warning) + .has_value()); + editor.reset(); + } + } + if (actions.close_controls) { + editor.reset(); + controls_problem.reset(); + } + if (!editor && capturing) { + (*app)->cancel_key_capture(); + capturing.reset(); + } + } + // A finished capture (key, Escape or focus loss) updates the draft only. + if (capturing && editor && !(*app)->key_capture_active()) { + if (const auto key = (*app)->take_captured_key(); + key && *key != evo::client::escape_key) { + if (auto assigned = editor->assign(capturing->action, capturing->secondary, *key); + !assigned) + controls_problem = assigned.error(); + } + capturing.reset(); + } actions = {}; // The launcher and modal dialogs own input: no world movement or selection. - (*app)->set_ui_capture(mode() == Mode::launcher || ui.dialog().has_value()); + (*app)->set_ui_capture(mode() == Mode::launcher || ui.dialog().has_value() || + editor.has_value()); const auto navigation = (*app)->take_navigation(); // Local input counter; in remote mode the session sets the server tick. const auto intention = (*app)->sample_intention(count); diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index bc42865..aa47a00 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -61,6 +61,17 @@ void disabled_wrapped(const char* text) { ImGui::TextWrapped("%s", text); ImGui::PopStyleColor(); } +std::string key_label(client::KeyCode key) { + return key == client::no_key ? std::string{"-"} : std::string{client::key_name(key)}; +} +std::string controls_hint(const client::Bindings& b) { + using client::Action; + const auto k = [&](Action action) { return key_label(b.slot(action).primary); }; + return "Click selects, wheel zooms. Move " + k(Action::move_up) + " " + k(Action::move_left) + + " " + k(Action::move_down) + " " + k(Action::move_right) + "; pan " + k(Action::pan_up) + + " " + k(Action::pan_left) + " " + k(Action::pan_down) + " " + k(Action::pan_right) + + "; UI capture " + k(Action::toggle_capture) + "."; +} // Fixed wording only (never echoes paths or file bytes); wraps inside the launcher. void error_text(client::LaunchError error) { ImGui::PushStyleColor(ImGuiCol_Text, red); @@ -83,6 +94,8 @@ void launcher(const PanelView& v, FormBuffers& form, PanelActions& a) { ImGui::Begin("Aeternalis Evolution - engineering client", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); ImGui::TextWrapped("Choose a data source. Nothing here is a game or a player account."); + if (ImGui::SmallButton("Controls...")) + a.open_controls = true; ImGui::Separator(); if (ImGui::Button("Local fixture", {160, 0})) a.fixture = true; @@ -132,12 +145,18 @@ void banner(const PanelView& v, PanelActions& a) { ImGui::SameLine(); if (ImGui::SmallButton("Launcher")) a.back = true; + ImGui::SameLine(); + if (ImGui::SmallButton("Controls")) + a.open_controls = true; } else { ImGui::TextColored(v.remote && v.remote->phase == "connected" ? green : amber, "DEV REGION - %s", v.remote ? v.remote->phase.c_str() : "?"); ImGui::SameLine(); if (ImGui::SmallButton("Disconnect")) a.ask_disconnect = true; + ImGui::SameLine(); + if (ImGui::SmallButton("Controls")) + a.open_controls = true; } ImGui::End(); } @@ -183,7 +202,8 @@ void legend(const PanelView& v, render::EnvironmentDisplay& display) { ImGui::TextWrapped("Fixture organisms are static presentation data built from genomes."); if (v.visible_organisms >= 0) ImGui::Text("Organisms drawn: %d", v.visible_organisms); - disabled_wrapped("Click to select. Arrows pan, wheel zooms, WASD moves."); + if (v.bindings != nullptr) + disabled_wrapped(controls_hint(*v.bindings).c_str()); ImGui::End(); } @@ -242,6 +262,75 @@ void inspector(const PanelView& v) { ImGui::End(); } +// Rebinding: each slot button arms key capture for that slot; the panel holds UI +// capture, so no key or click reaches the world while it is open (ADR-0085). +void controls(const PanelView& v, PanelActions& a) { + if (v.controls == nullptr) + return; + const auto& io = ImGui::GetIO(); + ImGui::SetNextWindowPos({io.DisplaySize.x * 0.5F, io.DisplaySize.y * 0.5F}, ImGuiCond_Always, + {0.5F, 0.5F}); + ImGui::SetNextWindowSize({std::min(460.0F, io.DisplaySize.x - 16), 0}, ImGuiCond_Always); + ImGui::Begin("Controls", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoSavedSettings); + disabled_wrapped("Keys are named by their US-layout position. Mouse click (select) and " + "wheel (zoom) are fixed. Escape cancels a key capture."); + if (ImGui::BeginTable("bindings", 3, ImGuiTableFlags_RowBg)) { + ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Primary", ImGuiTableColumnFlags_WidthFixed, 120); + ImGui::TableSetupColumn("Secondary", ImGuiTableColumnFlags_WidthFixed, 150); + ImGui::TableHeadersRow(); + for (std::size_t k = 0; k < client::action_count; ++k) { + const auto action = static_cast(k); + const auto& slot = v.controls->draft()[k]; + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(std::string{client::action_name(action)}.c_str()); + for (const bool secondary : {false, true}) { + ImGui::TableNextColumn(); + const ControlSlot here{action, secondary}; + const auto key = secondary ? slot.secondary : slot.primary; + const std::string label = + (v.capturing == here ? std::string{"Press a key"} : key_label(key)) + "##" + + std::to_string(k) + (secondary ? "s" : "p"); + ImGui::BeginDisabled(v.capturing.has_value()); + if (ImGui::Button(label.c_str(), {100, 0})) + a.capture_key = here; + if (secondary && key != client::no_key) { + ImGui::SameLine(); + if (ImGui::SmallButton(("x##clear" + std::to_string(k)).c_str())) + a.clear_secondary = action; + } + ImGui::EndDisabled(); + } + } + ImGui::EndTable(); + } + if (v.capturing) { + ImGui::TextColored(amber, "Press a key for %s (Escape cancels).", + std::string{client::action_name(v.capturing->action)}.c_str()); + if (ImGui::Button("Cancel capture", {140, 0})) + a.cancel_capture = true; + } + if (v.controls_problem) { + ImGui::PushStyleColor(ImGuiCol_Text, red); + ImGui::TextWrapped("%s", client::describe(*v.controls_problem).c_str()); + ImGui::PopStyleColor(); + } + ImGui::BeginDisabled(v.capturing.has_value()); + if (ImGui::Button("Apply", {100, 0})) + a.apply_controls = true; + ImGui::SameLine(); + if (ImGui::Button("Reset defaults", {130, 0})) + a.reset_controls = true; + ImGui::SameLine(); + if (ImGui::Button("Cancel", {100, 0})) + a.close_controls = true; + ImGui::EndDisabled(); + ImGui::End(); +} + void session(const PanelView& v) { if (!v.remote) return; @@ -376,6 +465,7 @@ PanelActions draw_panels(const PanelView& view, FormBuffers& form, inspector(view); session(view); } + controls(view, actions); notices(view, actions); dialog(view, actions); return actions; diff --git a/apps/evo-client/panels.hpp b/apps/evo-client/panels.hpp index 4cac061..b14c4d2 100644 --- a/apps/evo-client/panels.hpp +++ b/apps/evo-client/panels.hpp @@ -2,6 +2,7 @@ // M9.8c engineering panels (ADR-0084). Drawn inside Application's overlay callback; // they read presentation copies and report what the user asked for. Only this file // pair and the platform adapter use the toolkit. +#include "evo/client/bindings.hpp" #include "evo/client/environment_view.hpp" #include "evo/client/launcher.hpp" #include "evo/client/organism_view.hpp" @@ -25,6 +26,12 @@ struct FormBuffers { void load(const client::ConnectForm& form); [[nodiscard]] client::ConnectForm form() const; }; +// One key slot of one action in the controls panel. +struct ControlSlot { + client::Action action{}; + bool secondary{}; + friend bool operator==(const ControlSlot&, const ControlSlot&) = default; +}; struct PanelView { Mode mode{Mode::launcher}; const client::Launcher* launcher{}; @@ -36,11 +43,19 @@ struct PanelView { const client::UiState* ui{}; std::optional remote; const client::OutcomeLog* outcomes{}; - int visible_organisms{-1}; // -1 when unknown. + int visible_organisms{-1}; // -1 when unknown. + const client::Bindings* bindings{}; // In force (hints). + // Controls panel, drawn while `controls` is set. Edits stay in the draft until Apply. + const client::BindingEditor* controls{}; + std::optional capturing; // Waiting for the next key press. + std::optional controls_problem; }; struct PanelActions { bool fixture{}, connect{}, cancel{}, retry{}, back{}, ask_disconnect{}; std::optional dismiss_notice, confirm_dialog, cancel_dialog; + bool open_controls{}, apply_controls{}, reset_controls{}, close_controls{}, cancel_capture{}; + std::optional capture_key; + std::optional clear_secondary; }; // Draws every panel for this frame. `display` may be changed by the layer selector. [[nodiscard]] PanelActions draw_panels(const PanelView& view, FormBuffers& form, diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 4fb143c..e5de8a5 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -43,13 +43,13 @@ RUN cmake -P tools/prepare-sdl3.cmake \ && cmake -P tools/prepare-imgui.cmake \ && cmake --preset client-probe -DCMAKE_CXX_COMPILER=clang++-19 -DCMAKE_C_COMPILER=clang-19 \ -DEVO_BUILD_CLIENT=ON -DEVO_BUILD_UI_PROBE=ON -DEVO_ENABLE_TIDY=ON -DSDL_X11=ON -DSDL_WAYLAND=OFF \ - && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests --parallel 2 \ + && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests --parallel 2 \ && ctest --preset client-probe --no-tests=error \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-probe --renderer software \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests \ && cmake --preset client-probe -DEVO_BUILD_CLIENT=ON -DEVO_SANITIZER=address -DEVO_ENABLE_TIDY=OFF \ - && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests --parallel 2 \ + && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests --parallel 2 \ && ctest --preset client-probe --no-tests=error \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 141c9da..cea052f 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -457,7 +457,8 @@ terrain meshing or procedural creature animation is required. **M9.8a (2026-10-02):** isolated Dear ImGui 1.92.9b probe qualified on Windows/Linux; M9.8b adds bounded UI state, protected external input capture and bounded session event delivery. M9.8c integrates the launcher, legend, labelled inspector, click -selection and session panel. ADR-0084 records each scope. +selection and session panel. M9.8d adds rebindable controls (ADR-0085). ADR-0084 +records the toolkit scopes. **M9.8 planning (2026-10-02):** user-confirmed Windows ZIP, temporary Gitea Actions artifacts, labelled engineering UI/launcher and control rebinding. See the diff --git a/docs/STATUS.md b/docs/STATUS.md index e619017..f4e41d3 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,10 +7,11 @@ SDL3 probe (ADR-0084). M9.8b adds bounded notification/dialog state, protected external input capture and bounded session events with disconnect/drain/reconnect backpressure. M9.8c adds the launcher (labelled local fixture vs dev region, bounded errors, Retry/Cancel), legend, labelled inspector, click selection, session -panel with the intention outcome record, and visible notifications/dialog. Tests, +panel with the intention outcome record, and visible notifications/dialog. M9.8d +adds rebindable controls (ADR-0085) with conflict checks and a validated file. Tests, visual review and limits are recorded in engineering/VALIDATION.md. -Next: M9.8d rebindable controls, then packaging and qualification (9.8e-g). +Next: M9.8e reproducible Windows ZIP, then route design and qualification (9.8f-g). Windows packages will be built locally until a Windows runner exists. Testing is internal; 172.10.1.160 is the RKE2 control-plane address. VM qualification and the cluster restart drill remain outstanding, as agreed. See engineering/M9_8_DELIVERY_PLAN.md. diff --git a/docs/adr/0085-rebindable-engineering-controls.md b/docs/adr/0085-rebindable-engineering-controls.md new file mode 100644 index 0000000..a6d2ae0 --- /dev/null +++ b/docs/adr/0085-rebindable-engineering-controls.md @@ -0,0 +1,64 @@ +# ADR-0085: Rebindable engineering controls + +## Status +Accepted for M9.8d engineering client. Extends ADR-0079 (input intentions) and +ADR-0084 (toolkit). Bindings are engineering controls, not final player UI. + +## Context +ADR-0079 fixed WASD/arrows/Tab in the platform adapter. M9.8 requires rebindable +controls with conflict validation, reset to defaults and rejection of malformed +configuration, without stuck actions or click-through while the binding UI is open. + +## Decision +`include/evo/client/bindings.hpp` (SDL-free, `evo_client_controls`) defines nine +actions: four movement directions, four pan directions and toggle UI capture. +Physical keys are USB HID keyboard usages (SDL scancodes share the numbering), +named by US-layout position, so a key keeps its position across layouts. Only a +fixed table of 92 keys is bindable: letters, digits, punctuation, F1-F12, +navigation, arrows and keypad. Modifiers, locks, system/media keys are excluded; +Escape is reserved to cancel a capture. Mouse click selection and wheel zoom are +fixed. + +`Bindings` is always valid: every action has a primary key, at most one secondary, +and no key is used twice. `BindingEditor` stages changes; a conflicting assignment +is refused with the other action named and leaves the draft unchanged; Apply +validates the whole set. Releasing either key of an action releases the action +(no counting of held keys, so nothing can stay stuck). + +The adapter maps keys through the current bindings. `set_bindings` releases every +held action and drains already queued input; fresh presses are then required. +Binding capture (`begin_key_capture`) consumes keyboard and text events before the +toolkit and world; the first non-repeat press is returned once, the rest of that +batch is drained, focus loss cancels, and world input is captured while armed. The +host keeps UI capture on while the Controls panel is open. + +Configuration is a versioned text file (`evo-controls 1`, then `action key [key]` +per action, comments allowed), at most 4096 bytes of printable ASCII. Any error +rejects the whole file; the client then uses defaults, shows a notice and leaves +the file unchanged. Apply writes a sibling temporary file and renames it over the +target. The default location is SDL's per-user preference directory +(`Aeternalis Games/Evolution Engineering Client/controls-v1.txt`); `--controls FILE` +overrides it. The file contains key names only: no credentials, paths or grants. + +## Alternatives considered +- ImGui key enums: toolkit types would enter the contract and the file. +- SDL key names/keycodes: layout-dependent and SDL-specific text in a persisted file. +- JSON/TOML: needs a parser dependency for nine lines. +- Allowing modifiers or chords: interacts with toolkit shortcuts and focus; deferred. +- Counting held keys per action: correct for two held keys but risks stuck actions + when admission clears; rejected for engineering controls. + +## Benefits +Testable without SDL, bounded parsing, no partial configuration, no stuck actions. + +## Costs +US-position names may surprise non-US layouts (documented in the panel). Only one +secondary key per action; no gamepad or mouse-button bindings. + +## Risks +Physical keyboard layouts, IME and OS shortcuts are not qualified by synthetic +events. A file edited by hand can still choose awkward but valid keys. + +## Consequences +`Application` gains binding and capture APIs; host, panels, docs and tests change +together. Future player controls need a separate product ADR. diff --git a/docs/adr/README.md b/docs/adr/README.md index c79019d..39e0f1f 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -96,4 +96,5 @@ design. No unadopted candidate is a link dependency of the proof. - [ADR-0082: Dev session transport](0082-dev-session-transport.md) - TLS 1.3-only Mbed TLS 4.1.1 LTS (pinned, compiled-down), dev-only HMAC grants, versioned bounded protocol v1 and session admission for M9. - [ADR-0083: Dev region sessions](0083-dev-region-sessions.md) - session server in evo-server, durable no-effect intentions on synthetic carriers, empty organism presentation, reconnect with fresh baselines, loopback-only drill-time dev deployment. -- [ADR-0084: Engineering UI toolkit](0084-engineering-ui-toolkit.md) - accepted for the isolated M9.8a Dear ImGui 1.92.9b compatibility probe; application UI follows. +- [ADR-0084: Engineering UI toolkit](0084-engineering-ui-toolkit.md) - Dear ImGui 1.92.9b pinned (M9.8a) and integrated as the engineering client overlay with toolkit-first input routing (M9.8c). +- [ADR-0085: Rebindable engineering controls](0085-rebindable-engineering-controls.md) - SDL-free action/HID-key bindings, conflict validation, versioned all-or-nothing controls file, binding capture before toolkit/world. diff --git a/docs/architecture/CLIENT_ARCHITECTURE.md b/docs/architecture/CLIENT_ARCHITECTURE.md index a0919b2..af30d6c 100644 --- a/docs/architecture/CLIENT_ARCHITECTURE.md +++ b/docs/architecture/CLIENT_ARCHITECTURE.md @@ -92,3 +92,7 @@ models in `src/client/ui`. Dear ImGui is confined to the platform adapter (overl callback, event routing first, capture flags) and `apps/evo-client/panels.cpp`; library headers expose no toolkit type. Panels read presentation copies only and return requested actions; the app owns sessions, fixture and selection. + +M9.8d (ADR-0085) adds SDL-free bindings (actions vs HID key usages, validation, +versioned controls file) to `evo_client_controls`; the adapter maps keys through +them and offers binding capture ahead of toolkit and world input. diff --git a/docs/engineering/CAMERA_INPUT.md b/docs/engineering/CAMERA_INPUT.md index cfdcc18..d26f4cf 100644 --- a/docs/engineering/CAMERA_INPUT.md +++ b/docs/engineering/CAMERA_INPUT.md @@ -55,9 +55,14 @@ Use `poll_events()` -> read current window/navigation -> update camera -> `step(frame)` retains the combined poll/present convenience for lifecycle tests. Focus loss, hidden/minimized/closed/failed/zero-area state, or UI capture clears held state. A fresh non-repeat keydown is needed to re-arm; releases always -clear keys. UI code calls `set_ui_capture` before world polling. Tab toggles an -engineering capture mode in the adapter; repeats do not retoggle it. Window -close remains available while captured. +clear keys. UI code calls `set_ui_capture` before world polling. The +toggle-capture action (default Tab) toggles an engineering capture mode in the +adapter; repeats do not retoggle it. Window close remains available while captured. + +M9.8d (ADR-0085): keys reach `InputState` only through the current `Bindings` +(defaults: WASD move, arrows pan, Tab toggles capture). `set_bindings` releases +held actions and drains queued input; binding capture consumes the chosen key +before the toolkit and world. Releasing either key of an action releases it. A 256-event saturated batch clears admission. Remaining queued keydowns are ignored until a later poll drains the backlog; the drained state remains neutral diff --git a/docs/engineering/CLIENT.md b/docs/engineering/CLIENT.md index ad1755f..16cb958 100644 --- a/docs/engineering/CLIENT.md +++ b/docs/engineering/CLIENT.md @@ -1,4 +1,4 @@ -# Native engineering client (M9.2–M9.8c) +# Native engineering client (M9.2–M9.8d) This opens a resizable native window showing camera-controlled environment habitats and organisms either from a local in-memory fixture authority or from one dev @@ -47,13 +47,18 @@ one explicit backend, without fallback. `--frames N` exits after N bounded steps window and pauses drawing. These options permit unattended smoke checks. `--layer NAME` selects the displayed field or `moisture`; `--refresh-every N` (1..1000 fixture authority ticks) delays view refresh so the stale state is visible. +Controls are saved to `controls-v1.txt` in the per-user settings directory +(Windows: `%APPDATA%\Aeternalis Games\Evolution Engineering Client`); `--controls +FILE` uses another file and `--show-controls` opens the Controls panel at start. +An invalid file is reported, left unchanged, and defaults apply. `--pick X,Y` performs one scripted world click at window coordinates and `--screenshot FILE.bmp` (requires `--frames`) saves the last frame; both exist for unattended visual review. Usage errors exit 2, lifecycle/fixture failures exit 1, orderly exit returns 0. -Engineering controls: arrow keys pan, mouse wheel zooms around the pointer, WASD -updates the small intention indicator (sent as intentions in remote mode). A left +Engineering controls (defaults; rebindable, ADR-0085): arrow keys pan, mouse wheel +zooms around the pointer, WASD updates the small intention indicator (sent as +intentions in remote mode). A left click without dragging selects the topmost organism, else the habitat cell, for the Inspector; a click that lands on a panel or dismisses a notification never selects through it. Toolkit events are processed first: while a text field is focused or diff --git a/docs/engineering/CLIENT_UI_STATE.md b/docs/engineering/CLIENT_UI_STATE.md index 030e1ef..966d775 100644 --- a/docs/engineering/CLIENT_UI_STATE.md +++ b/docs/engineering/CLIENT_UI_STATE.md @@ -70,3 +70,16 @@ Notices (app panels): newest at the bottom right, at most 320 logical pixels wid stack stops at 60 % of the viewport height and shows how many notices are not drawn and how many were discarded. `client-panels` renders the production panels through the adapter and checks notice geometry and close-button dismissal. + +## M9.8d controls panel + +Opened from the launcher ("Controls...") or the mode banner. While open the host +keeps UI capture on, so neither keys nor clicks reach the world. Each slot button +arms adapter key capture for that slot (other buttons disabled); Escape or "Cancel +capture" ends it without a change, focus loss cancels it. A conflicting or +unbindable key is refused with fixed text naming the other action; the draft is +unchanged. Apply validates the whole set, installs it (held actions released) and +saves; Reset defaults and Cancel only change the draft/close. A save failure leaves +the bindings active for the session with a warning notice. The Legend hint lists +the keys in force. `client-panels` checks the panel geometry and that a slot click +requests capture without a world click. diff --git a/docs/engineering/M9_8_DELIVERY_PLAN.md b/docs/engineering/M9_8_DELIVERY_PLAN.md index 6e8bd91..147c264 100644 --- a/docs/engineering/M9_8_DELIVERY_PLAN.md +++ b/docs/engineering/M9_8_DELIVERY_PLAN.md @@ -1,8 +1,8 @@ # M9.8 delivery plan -Status: M9.8a probe, M9.8b owned state/capture/event bounds and M9.8c launcher, -legend, labelled inspector and click selection complete, 2026-10-02; remaining -segments planned. +Status: M9.8a probe, M9.8b owned state/capture/event bounds, M9.8c launcher, +legend, labelled inspector and click selection, and M9.8d rebindable controls +complete, 2026-10-02; remaining segments planned. No application UI or deployment completion is claimed. See ADR-0084 for the toolkit boundary. ## Confirmed scope diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index c313cd2..a009fff 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -3756,3 +3756,44 @@ live WSL dev region showing the wrapped connection notice with its close button. Limits unchanged: no physical mouse/keyboard session, DPI or accessibility review; the live screenshot sent no intentions. No Docker/Gitea, packaging or deployment. + + +## 2026-10-02 — M9.8d rebindable controls (ADR-0085) + +Implemented SDL-free bindings (nine actions, 92 named HID key positions, Escape +reserved, modifiers/locks/system keys excluded), a staging editor with conflict +refusal, and a versioned all-or-nothing controls file (4096 bytes, printable ASCII, +temp-file replace). The adapter maps keys through the bindings, releases and drains +on `set_bindings`, and offers binding capture ahead of the toolkit and world. The +app adds a Controls panel (launcher and banner), Legend key hints, startup loading +with a fixed-text notice on rejection, and `--controls FILE` / `--show-controls`. + +Tests: `client-bindings` (names, defaults, conflicts incl. own secondary, missing +primary, reserved/modifier keys, editor refusal leaves draft unchanged, reset, +serialize/parse round trip, comments/CRLF/tabs/order, unknown/duplicate/missing +actions, bad names, extra tokens, non-ASCII/NUL, size bound, unsupported version, +file load/save/replace, unreadable/too large/invalid/missing directory). Lifecycle +`rebinding`: rebinding while held releases and drains (new key queued before the +change does not act), unbound old key ignored, two keys per action never stick, +rebound toggle, capture consumes the key (repeat ignored, toolkit never sees it, +rest of batch drained), Escape returned, focus loss and cancel give no key. +`client-panels` controls panel: fits viewport, a slot click requests capture for +Move left without a world click, chosen key consumed before the toolkit. + +Executed: Windows MSVC client 9/9 and client-network 10/10 (final). Linux: clang-19 +client-probe with clang-tidy enabled (keep-going; one test finding fixed) CTest +13/13; Xvfb/X11 lifecycle and panels; Clang ASan/UBSan CTest 13/13 plus Xvfb +lifecycle/panels; GCC 14 client-network CTest 10/10; clang-tidy app main/panels +(client-network); repository format check. + +Visual review (dummy driver, software renderer): Controls panel with a custom file +(J/L/I/K, F1 + Keypad0) and matching Legend hint; invalid file (missing actions) +showing "Saved controls rejected: Move left needs a primary key..." with defaults in +use and the file byte-identical afterwards. Review found the startup notice expired +immediately (UI clock not yet advanced); fixed. A CRLF parsing defect was found by +the new test and fixed. CTest smoke runs create the empty per-user settings +directory (SDL creates it on lookup); no controls file is written by tests. + +Not run: interactive rebinding with a physical keyboard, non-US layouts, IME, the +Apply/save path end-to-end through the GUI (covered by file and editor tests), DPI, +accessibility, Docker/Gitea, packaging or deployment. diff --git a/include/evo/client/application.hpp b/include/evo/client/application.hpp index b056477..8b805ce 100644 --- a/include/evo/client/application.hpp +++ b/include/evo/client/application.hpp @@ -1,10 +1,13 @@ #pragma once +#include "evo/client/bindings.hpp" #include "evo/client/input.hpp" #include "evo/render/frame.hpp" #include #include +#include #include #include +#include #include namespace evo::client { @@ -48,8 +51,22 @@ class Application { [[nodiscard]] WindowState state() const noexcept; [[nodiscard]] std::expected poll_events(); [[nodiscard]] std::expected present(const render::Frame& frame); - // External modal/widget capture cannot be disabled by the legacy Tab toggle. + // External modal/widget capture cannot be disabled by the toggle-capture action. void set_ui_capture(bool captured) noexcept; + // Replaces the key-to-action map (ADR-0085). Every held world action is released; + // input queued before the change is drained, then fresh presses are required. + void set_bindings(const Bindings& bindings) noexcept; + [[nodiscard]] const Bindings& bindings() const noexcept; + // Binding capture: the next non-repeat key press (any key, including Escape) is + // consumed for take_captured_key() and reaches neither the toolkit nor the world. + // World input stays captured while armed; focus loss cancels it without a key. + void begin_key_capture() noexcept; + void cancel_key_capture() noexcept; + [[nodiscard]] bool key_capture_active() const noexcept; + [[nodiscard]] std::optional take_captured_key() noexcept; + // Per-user settings directory, created when needed; nullopt when unavailable. + // Callable without an open Application. + [[nodiscard]] static std::optional settings_directory(); [[nodiscard]] bool ui_captured() const noexcept; void set_overlay(Overlay overlay); // The toolkit held the pointer during the last poll (no world click, pan or zoom). diff --git a/include/evo/client/bindings.hpp b/include/evo/client/bindings.hpp new file mode 100644 index 0000000..4ba2d9b --- /dev/null +++ b/include/evo/client/bindings.hpp @@ -0,0 +1,112 @@ +#pragma once +// M9.8d rebindable engineering controls (ADR-0085). Actions are separate from +// physical keys; keys are USB HID keyboard usages (page 7), the numbering SDL +// scancodes also use, so this contract stays SDL-free. Mouse selection/zoom are not +// rebindable. The file stores key names only: never credentials, paths or grants. +#include +#include +#include +#include +#include +#include +#include +#include + +namespace evo::client { +enum class Action : std::uint8_t { + move_left, + move_right, + move_up, + move_down, + pan_left, + pan_right, + pan_up, + pan_down, + toggle_capture +}; +inline constexpr std::size_t action_count = 9; +using KeyCode = std::uint16_t; // HID usage; 0 means unbound. +inline constexpr KeyCode no_key = 0; +inline constexpr KeyCode escape_key = 41; // Reserved: cancels binding capture. +struct KeySlot { + KeyCode primary{no_key}, secondary{no_key}; + friend bool operator==(const KeySlot&, const KeySlot&) = default; +}; +using KeySlots = std::array; + +enum class BindingError : std::uint8_t { + unbindable_key, // Not in the supported key table, or reserved (Escape). + conflict, // One physical key bound to two actions or both slots. + missing_primary, // Every action needs a primary key. + malformed, // File syntax, unknown action/key name, duplicate action line. + unsupported_version, + too_large, + unreadable, + write_failed +}; +// Why a set of bindings was refused, for fixed-wording display. +struct BindingProblem { + BindingError error{BindingError::malformed}; + std::optional action, other; + KeyCode key{no_key}; +}; + +[[nodiscard]] std::string_view action_id(Action action) noexcept; // "move_up" (file token) +[[nodiscard]] std::string_view action_name(Action action) noexcept; // "Move up" (label) +[[nodiscard]] std::optional action_from_id(std::string_view id) noexcept; +// Display/file name of a supported key ("W", "Up", "F5"); empty when unsupported. +[[nodiscard]] std::string_view key_name(KeyCode key) noexcept; +[[nodiscard]] std::optional key_from_name(std::string_view name) noexcept; +[[nodiscard]] bool bindable(KeyCode key) noexcept; +[[nodiscard]] std::string describe(const BindingProblem& problem); + +// An always-valid binding set: every action has a bindable primary, at most one +// bindable secondary, and no key appears twice. +class Bindings { + public: + [[nodiscard]] static Bindings defaults() noexcept; + [[nodiscard]] static std::expected make(const KeySlots& slots); + [[nodiscard]] std::optional action(KeyCode key) const noexcept; + [[nodiscard]] const KeySlot& slot(Action action) const noexcept { + return slots_[static_cast(action)]; + } + [[nodiscard]] const KeySlots& slots() const noexcept { + return slots_; + } + friend bool operator==(const Bindings&, const Bindings&) = default; + + private: + explicit Bindings(const KeySlots& slots) noexcept : slots_{slots} {} + KeySlots slots_; +}; + +// Staged edits for a controls panel. Nothing applies until apply() validates the +// whole set; an assignment that would conflict is refused and leaves the draft as is. +class BindingEditor { + public: + explicit BindingEditor(const Bindings& current) noexcept : draft_{current.slots()} {} + [[nodiscard]] std::expected assign(Action action, bool secondary, + KeyCode key); + void clear_secondary(Action action) noexcept; + void reset_defaults() noexcept; + [[nodiscard]] const KeySlots& draft() const noexcept { + return draft_; + } + [[nodiscard]] std::expected apply() const; + + private: + KeySlots draft_; +}; + +// Versioned text: "evo-controls 1", then one "action key [key]" line per action. +// All actions must appear exactly once; '#' starts a comment. Rejected as a whole +// on any error (never partially applied). +inline constexpr std::size_t max_bindings_bytes = 4096; +[[nodiscard]] std::string serialize(const Bindings& bindings); +[[nodiscard]] std::expected parse_bindings(std::string_view text); +[[nodiscard]] std::expected +load_bindings(const std::filesystem::path& file); +// Writes a sibling temporary file, then replaces `file`. +[[nodiscard]] std::expected save_bindings(const Bindings& bindings, + const std::filesystem::path& file); +} // namespace evo::client diff --git a/src/client/input/bindings.cpp b/src/client/input/bindings.cpp new file mode 100644 index 0000000..47289b5 --- /dev/null +++ b/src/client/input/bindings.cpp @@ -0,0 +1,369 @@ +#include "evo/client/bindings.hpp" +#include +#include +#include +#include + +namespace evo::client { +namespace { +// HID keyboard usages named by their US-layout position. Usages are positional, so +// "W" is the key in that position whatever a layout prints on it. Modifiers, locks, +// system and media keys are deliberately absent (OS shortcuts, toggled state). +struct NamedKey { + KeyCode code; + std::string_view name; +}; +constexpr auto keys = std::to_array({ + {4, "A"}, + {5, "B"}, + {6, "C"}, + {7, "D"}, + {8, "E"}, + {9, "F"}, + {10, "G"}, + {11, "H"}, + {12, "I"}, + {13, "J"}, + {14, "K"}, + {15, "L"}, + {16, "M"}, + {17, "N"}, + {18, "O"}, + {19, "P"}, + {20, "Q"}, + {21, "R"}, + {22, "S"}, + {23, "T"}, + {24, "U"}, + {25, "V"}, + {26, "W"}, + {27, "X"}, + {28, "Y"}, + {29, "Z"}, + {30, "1"}, + {31, "2"}, + {32, "3"}, + {33, "4"}, + {34, "5"}, + {35, "6"}, + {36, "7"}, + {37, "8"}, + {38, "9"}, + {39, "0"}, + {40, "Enter"}, + {41, "Escape"}, + {42, "Backspace"}, + {43, "Tab"}, + {44, "Space"}, + {45, "Minus"}, + {46, "Equals"}, + {47, "LeftBracket"}, + {48, "RightBracket"}, + {49, "Backslash"}, + {51, "Semicolon"}, + {52, "Apostrophe"}, + {53, "Grave"}, + {54, "Comma"}, + {55, "Period"}, + {56, "Slash"}, + {58, "F1"}, + {59, "F2"}, + {60, "F3"}, + {61, "F4"}, + {62, "F5"}, + {63, "F6"}, + {64, "F7"}, + {65, "F8"}, + {66, "F9"}, + {67, "F10"}, + {68, "F11"}, + {69, "F12"}, + {73, "Insert"}, + {74, "Home"}, + {75, "PageUp"}, + {76, "Delete"}, + {77, "End"}, + {78, "PageDown"}, + {79, "Right"}, + {80, "Left"}, + {81, "Down"}, + {82, "Up"}, + {84, "KeypadDivide"}, + {85, "KeypadMultiply"}, + {86, "KeypadMinus"}, + {87, "KeypadPlus"}, + {88, "KeypadEnter"}, + {89, "Keypad1"}, + {90, "Keypad2"}, + {91, "Keypad3"}, + {92, "Keypad4"}, + {93, "Keypad5"}, + {94, "Keypad6"}, + {95, "Keypad7"}, + {96, "Keypad8"}, + {97, "Keypad9"}, + {98, "Keypad0"}, + {99, "KeypadPeriod"}, + {100, "NonUsBackslash"}, + {50, "NonUsHash"}, +}); +static_assert(keys.size() == 92); +struct NamedAction { + std::string_view id, name; +}; +constexpr std::array actions{{ + {"move_left", "Move left"}, + {"move_right", "Move right"}, + {"move_up", "Move up"}, + {"move_down", "Move down"}, + {"pan_left", "Pan left"}, + {"pan_right", "Pan right"}, + {"pan_up", "Pan up"}, + {"pan_down", "Pan down"}, + {"toggle_capture", "Toggle UI capture"}, +}}; +constexpr KeySlots default_slots{{ + {4, no_key}, // A + {7, no_key}, // D + {26, no_key}, // W + {22, no_key}, // S + {80, no_key}, // Left + {79, no_key}, // Right + {82, no_key}, // Up + {81, no_key}, // Down + {43, no_key}, // Tab +}}; +constexpr std::string_view header = "evo-controls"; + +constexpr std::string_view blank = " \t\r"; // CRLF files are accepted. +std::string_view trim(std::string_view text) noexcept { + const auto first = text.find_first_not_of(blank); + if (first == std::string_view::npos) + return {}; + const auto last = text.find_last_not_of(blank); + return text.substr(first, last - first + 1); +} +std::vector tokens(std::string_view line) { + std::vector out; + while (!(line = trim(line)).empty()) { + const auto end = line.find_first_of(blank); + out.push_back(line.substr(0, end)); + line = end == std::string_view::npos ? std::string_view{} : line.substr(end); + } + return out; +} +BindingProblem problem(BindingError error, std::optional action = std::nullopt, + KeyCode key = no_key, std::optional other = std::nullopt) { + return {error, action, other, key}; +} +std::string key_text(KeyCode key) { + const auto name = key_name(key); + return name.empty() ? std::string{"That key"} : std::string{name}; +} +} // namespace + +std::string_view action_id(Action action) noexcept { + return actions.at(static_cast(action)).id; +} +std::string_view action_name(Action action) noexcept { + return actions.at(static_cast(action)).name; +} +std::optional action_from_id(std::string_view id) noexcept { + for (std::size_t k = 0; k < actions.size(); ++k) + if (actions[k].id == id) + return static_cast(k); + return std::nullopt; +} +std::string_view key_name(KeyCode key) noexcept { + for (const auto& k : keys) + if (k.code == key) + return k.name; + return {}; +} +std::optional key_from_name(std::string_view name) noexcept { + for (const auto& k : keys) + if (k.name == name) + return k.code; + return std::nullopt; +} +bool bindable(KeyCode key) noexcept { + return key != escape_key && !key_name(key).empty(); +} +std::string describe(const BindingProblem& p) { + const std::string action = p.action ? std::string{action_name(*p.action)} : "An action"; + switch (p.error) { + case BindingError::unbindable_key: + return p.key == escape_key + ? "Escape is reserved for cancelling." + : key_text(p.key) + " cannot be bound (modifier, system or unsupported key)."; + case BindingError::conflict: + return key_text(p.key) + " is already bound to " + + (p.other ? std::string{action_name(*p.other)} : std::string{"another action"}) + "."; + case BindingError::missing_primary: + return action + " needs a primary key."; + case BindingError::malformed: + return "The controls file is not valid."; + case BindingError::unsupported_version: + return "The controls file is from an unsupported version."; + case BindingError::too_large: + return "The controls file is too large."; + case BindingError::unreadable: + return "The controls file could not be read."; + case BindingError::write_failed: + return "The controls could not be saved."; + } + return "Invalid controls."; +} + +Bindings Bindings::defaults() noexcept { + return Bindings{default_slots}; +} +std::expected Bindings::make(const KeySlots& slots) { + for (std::size_t k = 0; k < slots.size(); ++k) { + const auto action = static_cast(k); + const auto& s = slots[k]; + if (s.primary == no_key) + return std::unexpected(problem(BindingError::missing_primary, action)); + for (const auto key : {s.primary, s.secondary}) + if (key != no_key && !bindable(key)) + return std::unexpected(problem(BindingError::unbindable_key, action, key)); + if (s.secondary == s.primary) + return std::unexpected(problem(BindingError::conflict, action, s.primary, action)); + for (std::size_t j = 0; j < k; ++j) + for (const auto key : {s.primary, s.secondary}) + if (key != no_key && (slots[j].primary == key || slots[j].secondary == key)) + return std::unexpected( + problem(BindingError::conflict, action, key, static_cast(j))); + } + return Bindings{slots}; +} +std::optional Bindings::action(KeyCode key) const noexcept { + if (key == no_key) + return std::nullopt; + for (std::size_t k = 0; k < slots_.size(); ++k) + if (slots_[k].primary == key || slots_[k].secondary == key) + return static_cast(k); + return std::nullopt; +} + +std::expected BindingEditor::assign(Action action, bool secondary, + KeyCode key) { + if (!bindable(key)) + return std::unexpected(problem(BindingError::unbindable_key, action, key)); + for (std::size_t k = 0; k < draft_.size(); ++k) { + const auto other = static_cast(k); + const auto& s = draft_[k]; + const bool same_slot = other == action && ((secondary && s.secondary == key) || + (!secondary && s.primary == key)); + if (!same_slot && (s.primary == key || s.secondary == key)) + return std::unexpected(problem(BindingError::conflict, action, key, other)); + } + auto& slot = draft_[static_cast(action)]; + (secondary ? slot.secondary : slot.primary) = key; + return {}; +} +void BindingEditor::clear_secondary(Action action) noexcept { + draft_[static_cast(action)].secondary = no_key; +} +void BindingEditor::reset_defaults() noexcept { + draft_ = default_slots; +} +std::expected BindingEditor::apply() const { + return Bindings::make(draft_); +} + +std::string serialize(const Bindings& bindings) { + std::string out{header}; + out += " 1\n# Aeternalis Evolution engineering client controls (key names only).\n"; + for (std::size_t k = 0; k < action_count; ++k) { + const auto& s = bindings.slots()[k]; + out += action_id(static_cast(k)); + out += ' '; + out += key_name(s.primary); + if (s.secondary != no_key) { + out += ' '; + out += key_name(s.secondary); + } + out += '\n'; + } + return out; +} +std::expected parse_bindings(std::string_view text) { + if (text.size() > max_bindings_bytes) + return std::unexpected(problem(BindingError::too_large)); + if (std::ranges::any_of(text, [](char c) { + const auto u = static_cast(c); + return u >= 0x7F || (u < 0x20 && c != '\n' && c != '\r' && c != '\t'); + })) + return std::unexpected(problem(BindingError::malformed)); + KeySlots slots{}; + std::array seen{}; + bool versioned = false; + while (!text.empty()) { + const auto end = text.find('\n'); + auto line = text.substr(0, end); + text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1); + if (const auto hash = line.find('#'); hash != std::string_view::npos) + line = line.substr(0, hash); + const auto t = tokens(line); + if (t.empty()) + continue; + if (!versioned) { + if (t.size() != 2 || t[0] != header) + return std::unexpected(problem(BindingError::malformed)); + if (t[1] != "1") + return std::unexpected(problem(BindingError::unsupported_version)); + versioned = true; + continue; + } + const auto action = action_from_id(t[0]); + if (!action || t.size() < 2 || t.size() > 3 || seen[static_cast(*action)]) + return std::unexpected(problem(BindingError::malformed, action)); + seen[static_cast(*action)] = true; + auto& slot = slots[static_cast(*action)]; + const auto primary = key_from_name(t[1]); + const auto secondary = t.size() == 3 ? key_from_name(t[2]) : std::optional{no_key}; + if (!primary || !secondary) + return std::unexpected(problem(BindingError::malformed, action)); + slot = {*primary, *secondary}; + } + if (!versioned) + return std::unexpected(problem(BindingError::malformed)); + return Bindings::make(slots); // Missing actions have no primary. +} +std::expected load_bindings(const std::filesystem::path& file) { + std::error_code error; + const auto size = std::filesystem::file_size(file, error); + if (error || !std::filesystem::is_regular_file(file, error)) + return std::unexpected(problem(BindingError::unreadable)); + if (size > max_bindings_bytes) + return std::unexpected(problem(BindingError::too_large)); + std::ifstream in{file, std::ios::binary}; + std::string text(max_bindings_bytes + 1, '\0'); + in.read(text.data(), static_cast(text.size())); + if (in.bad()) + return std::unexpected(problem(BindingError::unreadable)); + text.resize(static_cast(in.gcount())); + return parse_bindings(text); // Re-checks size if the file grew meanwhile. +} +std::expected save_bindings(const Bindings& bindings, + const std::filesystem::path& file) { + auto temporary = file; + temporary += ".tmp"; + const auto text = serialize(bindings); + { + std::ofstream out{temporary, std::ios::binary | std::ios::trunc}; + out.write(text.data(), static_cast(text.size())); + out.flush(); + if (!out) + return std::unexpected(problem(BindingError::write_failed)); + } + std::error_code error; + std::filesystem::rename(temporary, file, error); + if (error) { + std::filesystem::remove(temporary, error); + return std::unexpected(problem(BindingError::write_failed)); + } + return {}; +} +} // namespace evo::client diff --git a/src/client/platform/application.cpp b/src/client/platform/application.cpp index 39dc561..39928fa 100644 --- a/src/client/platform/application.cpp +++ b/src/client/platform/application.cpp @@ -13,28 +13,13 @@ namespace evo::client { namespace { bool runtime_owned = false; // Process main-thread-only contract; no hidden threads. -std::optional input_key(SDL_Scancode code) { - switch (code) { - case SDL_SCANCODE_A: - return Key::left; - case SDL_SCANCODE_D: - return Key::right; - case SDL_SCANCODE_W: - return Key::up; - case SDL_SCANCODE_S: - return Key::down; - case SDL_SCANCODE_LEFT: - return Key::pan_left; - case SDL_SCANCODE_RIGHT: - return Key::pan_right; - case SDL_SCANCODE_UP: - return Key::pan_up; - case SDL_SCANCODE_DOWN: - return Key::pan_down; - default: +// World actions map onto the input contract's held-key slots in declaration order. +std::optional held_key(Action action) noexcept { + if (action == Action::toggle_capture) return std::nullopt; - } + return static_cast(static_cast(action)); } +static_assert(static_cast(Action::pan_down) == static_cast(Key::pan_down)); // Private toolkit state (ADR-0084): created after the renderer, destroyed before it. struct Toolkit { bool context{}, platform{}, renderer{}; @@ -104,7 +89,10 @@ struct Application::Impl { Toolkit toolkit; // After window/renderer: destroyed first. Overlay overlay; InputState input; + Bindings bindings{Bindings::defaults()}; bool backlogged{false}; + bool key_capture{false}; // Binding capture armed. + std::optional captured_key; // Taken once by the host. // Capture sources: an external modal/launcher, the legacy Tab toggle and the // toolkit's own keyboard focus. World actions run only when none applies. bool external_capture{false}, tab_capture{false}, toolkit_capture{false}; @@ -117,7 +105,7 @@ struct Application::Impl { // that batch is discarded first. The Tab toggle is ordered within its own batch // (CAMERA_INPUT.md): presses after it belong to the new state, no drain. void update_capture(bool drain = true) { - const bool wanted = external_capture || tab_capture || toolkit_capture; + const bool wanted = external_capture || tab_capture || toolkit_capture || key_capture; if (wanted == input.captured()) return; if (!wanted && drain) { @@ -156,6 +144,41 @@ void Application::set_ui_capture(bool captured) noexcept { impl_->external_capture = captured; impl_->update_capture(); } +void Application::set_bindings(const Bindings& bindings) noexcept { + auto& p = *impl_; + p.bindings = bindings; + // Held actions may belong to keys that changed meaning: release them all and drain + // whatever is already queued, exactly like a capture release. + p.backlogged = true; + p.input.admit(false); + p.press.reset(); +} +const Bindings& Application::bindings() const noexcept { + return impl_->bindings; +} +void Application::begin_key_capture() noexcept { + impl_->captured_key.reset(); + impl_->key_capture = true; + impl_->update_capture(); +} +void Application::cancel_key_capture() noexcept { + impl_->key_capture = false; + impl_->update_capture(); +} +bool Application::key_capture_active() const noexcept { + return impl_->key_capture; +} +std::optional Application::take_captured_key() noexcept { + return std::exchange(impl_->captured_key, std::nullopt); +} +std::optional Application::settings_directory() { + char* path = SDL_GetPrefPath("Aeternalis Games", "Evolution Engineering Client"); + if (path == nullptr) + return std::nullopt; + std::filesystem::path result{reinterpret_cast(path)}; + SDL_free(path); + return result; +} void Application::set_overlay(Overlay overlay) { impl_->overlay = std::move(overlay); } @@ -233,9 +256,27 @@ std::expected Application::poll_events() { // A press on a panel in this batch may focus a text field before the toolkit's next // frame can report it: world key-downs after it wait for that frame (releases pass). bool ui_pressed = false; + bool key_chosen = false; // Binding capture completed in this batch. SDL_Event event{}; int count = 0; for (; count < 256 && SDL_PollEvent(&event); ++count) { + // Binding capture consumes keyboard events before the toolkit and world; text + // produced by the chosen key (later in this batch) is swallowed as well. + const bool keyboard = (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) + ? event.key.windowID == id + : event.type == SDL_EVENT_TEXT_INPUT ? event.text.windowID == id + : event.type == SDL_EVENT_TEXT_EDITING ? event.edit.windowID == id + : false; + if (keyboard && (p.key_capture || (key_chosen && (event.type == SDL_EVENT_TEXT_INPUT || + event.type == SDL_EVENT_TEXT_EDITING)))) { + if (p.key_capture && event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) { + p.captured_key = static_cast(event.key.scancode); + p.key_capture = false; + key_chosen = true; + p.update_capture(); // Drains the rest of this batch before world input. + } + continue; + } // Toolkit first: widgets see every event before world input is derived. ImGui_ImplSDL3_ProcessEvent(&event); if (event.type == SDL_EVENT_QUIT) @@ -274,17 +315,23 @@ std::expected Application::poll_events() { if (!p.state.accepts_input()) { p.press.reset(); // A release may never arrive for this window. p.ui_press = false; + if (p.key_capture) { // Focus loss cancels binding capture without a key. + p.key_capture = false; + p.update_capture(); + } } if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) && event.key.windowID == id) { const bool down = event.type == SDL_EVENT_KEY_DOWN; - if (event.key.scancode == SDL_SCANCODE_TAB && down && !event.key.repeat && + const auto action = p.bindings.action(static_cast(event.key.scancode)); + if (action == Action::toggle_capture && down && !event.key.repeat && p.state.accepts_input() && !p.backlogged && !p.external_capture && !p.toolkit_capture && !ui_pressed) { p.tab_capture = !p.tab_capture; p.update_capture(false); } - if (const auto key = input_key(event.key.scancode); key && (!down || !ui_pressed)) { + if (const auto key = action ? held_key(*action) : std::nullopt; + key && (!down || !ui_pressed)) { if (auto result = p.input.key(*key, down, event.key.repeat); !result) p.input.admit(false); } diff --git a/tests/client_bindings.cpp b/tests/client_bindings.cpp new file mode 100644 index 0000000..8dc7d2b --- /dev/null +++ b/tests/client_bindings.cpp @@ -0,0 +1,186 @@ +// M9.8d rebindable controls (ADR-0085): SDL-free binding contract, editor and file. +#include "evo/client/bindings.hpp" +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::client; +void check(bool ok, std::source_location at = std::source_location::current()) { + if (!ok) + throw std::runtime_error("client bindings line " + std::to_string(at.line())); +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) +KeyCode key(std::string_view name) { + const auto k = key_from_name(name); + if (!k) + throw std::runtime_error("client bindings: unknown key name"); + return *k; +} +bool refused(const auto& result, BindingError error) { + return !result && result.error().error == error; +} + +void names_and_defaults() { + const auto d = Bindings::defaults(); + CHECK(d.action(key("W")) == Action::move_up && d.action(key("A")) == Action::move_left); + CHECK(d.action(key("Up")) == Action::pan_up && d.action(key("Tab")) == Action::toggle_capture); + CHECK(!d.action(key("Q")) && !d.action(no_key)); + CHECK(key_name(26) == "W" && key_name(82) == "Up" && key_name(0).empty() && + key_name(224).empty()); + CHECK(!bindable(escape_key) && !bindable(no_key) && !bindable(224) && !bindable(57)); + CHECK(bindable(key("Keypad5")) && bindable(key("F12"))); + CHECK(!key_from_name("w") && !key_from_name("") && !key_from_name("LeftShift")); + for (std::size_t k = 0; k < action_count; ++k) { + const auto a = static_cast(k); + CHECK(action_from_id(action_id(a)) == a && !action_name(a).empty()); + } + CHECK(!action_from_id("jump")); + // Defaults are themselves valid and round-trip through make(). + const auto again = Bindings::make(d.slots()); + CHECK(again && *again == d); +} + +void validation() { + auto slots = Bindings::defaults().slots(); + slots[2].secondary = key("I"); + CHECK(Bindings::make(slots)); + auto conflict = slots; + conflict[0].secondary = key("W"); // Move up's key. + const auto c = Bindings::make(conflict); + CHECK(refused(c, BindingError::conflict) && c.error().other == Action::move_left && + c.error().action == Action::move_up && c.error().key == key("W")); + CHECK(describe(c.error()) == "W is already bound to Move left."); + auto same = slots; + same[3].secondary = same[3].primary; + CHECK(refused(Bindings::make(same), BindingError::conflict)); + auto missing = slots; + missing[8].primary = no_key; + const auto m = Bindings::make(missing); + CHECK(refused(m, BindingError::missing_primary) && m.error().action == Action::toggle_capture); + auto reserved = slots; + reserved[1].primary = escape_key; + CHECK(refused(Bindings::make(reserved), BindingError::unbindable_key)); + auto modifier = slots; + modifier[1].secondary = 225; // Left Shift. + CHECK(refused(Bindings::make(modifier), BindingError::unbindable_key)); +} + +void editor() { + BindingEditor e{Bindings::defaults()}; + // A conflicting assignment is refused and leaves the draft unchanged. + const auto before = e.draft(); + const auto refused_assign = e.assign(Action::move_up, false, key("Left")); + CHECK(!refused_assign && refused_assign.error().other == Action::pan_left); + CHECK(e.draft() == before); + CHECK(!e.assign(Action::move_up, true, escape_key)); + CHECK(!e.assign(Action::move_up, true, key("W"))); // Its own primary. + // Reassigning a slot to its current key is allowed (no-op). + CHECK(e.assign(Action::move_up, false, key("W"))); + CHECK(e.assign(Action::move_up, false, key("I")) && e.assign(Action::move_up, true, key("W"))); + auto applied = e.apply(); + CHECK(applied && applied->action(key("I")) == Action::move_up && + applied->action(key("W")) == Action::move_up); + e.clear_secondary(Action::move_up); + CHECK(e.draft()[2].secondary == no_key); + e.reset_defaults(); + CHECK(e.apply() == Bindings::defaults()); +} + +void file_format() { + auto slots = Bindings::defaults().slots(); + slots[8] = {key("F1"), key("Keypad0")}; + const auto custom = Bindings::make(slots); + CHECK(custom); + const auto text = serialize(*custom); + CHECK(text.starts_with("evo-controls 1\n") && + text.find("toggle_capture F1 Keypad0\n") != std::string::npos); + CHECK(parse_bindings(text) == *custom); + // Comments, blank lines, CRLF and tabs are tolerated; order is free. + std::string loose = "# mine\r\nevo-controls 1\r\n\r\n"; + for (std::size_t k = action_count; k-- > 0;) { + const auto a = static_cast(k); + loose += " " + std::string{action_id(a)} + "\t" + std::string{key_name(slots[k].primary)}; + if (slots[k].secondary != no_key) + loose += " " + std::string{key_name(slots[k].secondary)}; + loose += " # note\r\n"; + } + CHECK(parse_bindings(loose) == *custom); + // Malformed inputs are rejected as a whole. + const auto without = [&](std::string_view action) { + std::string out; + std::size_t at = 0; + while (at < text.size()) { + const auto end = text.find('\n', at); + const auto line = text.substr(at, end - at + 1); + if (!line.starts_with(std::string{action} + " ")) + out += line; + at = end + 1; + } + return out; + }; + CHECK(refused(parse_bindings(""), BindingError::malformed)); + CHECK(refused(parse_bindings("move_up W\n"), BindingError::malformed)); + CHECK(refused(parse_bindings("evo-controls 2\n"), BindingError::unsupported_version)); + CHECK(refused(parse_bindings("evo-controls 1 extra\n"), BindingError::malformed)); + CHECK(refused(parse_bindings(without("pan_down")), BindingError::missing_primary)); + CHECK(refused(parse_bindings(text + "move_up W\n"), BindingError::malformed)); + CHECK(refused(parse_bindings(text + "jump Space\n"), BindingError::malformed)); + CHECK(refused(parse_bindings(without("move_up") + "move_up w\n"), BindingError::malformed)); + CHECK(refused(parse_bindings(without("move_up") + "move_up W I O\n"), BindingError::malformed)); + CHECK(refused(parse_bindings(without("move_up") + "move_up\n"), BindingError::malformed)); + CHECK(refused(parse_bindings(without("move_up") + "move_up A\n"), BindingError::conflict)); + CHECK(refused(parse_bindings(without("move_up") + "move_up Escape\n"), + BindingError::unbindable_key)); + CHECK(refused(parse_bindings(text + std::string{"\0", 1}), BindingError::malformed)); + CHECK(refused(parse_bindings(text + "# \xC3\xA9\n"), BindingError::malformed)); + CHECK( + refused(parse_bindings(std::string(max_bindings_bytes + 1, ' ')), BindingError::too_large)); + CHECK(parse_bindings(text + std::string(max_bindings_bytes - text.size(), '\n'))); +} + +void files() { + const auto dir = std::filesystem::temp_directory_path() / "evo-bindings-test"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + const auto file = dir / "controls-v1.txt"; + CHECK(refused(load_bindings(file), BindingError::unreadable)); + CHECK(refused(load_bindings(dir), BindingError::unreadable)); + auto slots = Bindings::defaults().slots(); + slots[0].secondary = key("J"); + const auto custom = Bindings::make(slots); + CHECK(custom && save_bindings(*custom, file)); + CHECK(load_bindings(file) == *custom && !std::filesystem::exists(dir / "controls-v1.txt.tmp")); + // Saving again replaces the file. + CHECK(save_bindings(Bindings::defaults(), file) && load_bindings(file) == Bindings::defaults()); + { + std::ofstream big{file, std::ios::binary | std::ios::trunc}; + big << std::string(max_bindings_bytes + 1, '#'); + } + CHECK(refused(load_bindings(file), BindingError::too_large)); + { + std::ofstream bad{file, std::ios::binary | std::ios::trunc}; + bad << "evo-controls 1\nmove_up W\n"; + } + CHECK(refused(load_bindings(file), BindingError::missing_primary)); + CHECK(refused(save_bindings(Bindings::defaults(), dir / "missing" / "controls-v1.txt"), + BindingError::write_failed)); + std::filesystem::remove_all(dir); +} +} // namespace + +int main() try { + names_and_defaults(); + validation(); + editor(); + file_format(); + files(); + std::puts("client binding tests passed"); + return 0; +} catch (const std::exception& e) { + std::fprintf(stderr, "%s\n", e.what()); + return 1; +} diff --git a/tests/client_lifecycle.cpp b/tests/client_lifecycle.cpp index 894fcea..65fc197 100644 --- a/tests/client_lifecycle.cpp +++ b/tests/client_lifecycle.cpp @@ -436,6 +436,106 @@ void toolkit_capture() { std::filesystem::remove(shot); CHECK(!app->request_screenshot("")); } +// M9.8d: actions come from the binding map; rebinding releases held actions; binding +// capture consumes the key before the toolkit and world; focus loss cancels it. +void rebinding() { + const auto frame = fixture(); + auto result = Application::open({320, 240, false, "software"}); + CHECK(result); + auto app = std::move(result.value()); + CHECK(app->poll_events()); + const auto id = SDL_GetWindowID(window()); + send(SDL_EVENT_WINDOW_FOCUS_GAINED, id); + CHECK(app->poll_events() && app->bindings() == Bindings::defaults()); + auto key = [id](SDL_Scancode scancode, bool down, bool repeat = false) { + SDL_Event event{}; + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.windowID = id; + event.key.scancode = scancode; + event.key.repeat = repeat; + CHECK(SDL_PushEvent(&event)); + }; + std::uint64_t tick = 200; + const auto move_y = [&] { return required(app->sample_intention(++tick)).move_y; }; + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events() && move_y() == 1000); + // Rebind while W is held: the action is released at once and nothing queued before + // the change (including a press of the new key) replays. + auto slots = Bindings::defaults().slots(); + slots[static_cast(Action::move_up)] = {SDL_SCANCODE_I, SDL_SCANCODE_KP_8}; + slots[static_cast(Action::toggle_capture)] = {SDL_SCANCODE_F1, no_key}; + const auto custom = Bindings::make(slots); + CHECK(custom); + key(SDL_SCANCODE_I, true); // Queued before the change. + app->set_bindings(*custom); + CHECK(move_y() == 0 && app->bindings() == *custom); + CHECK(app->poll_events() && move_y() == 0); // Drained batch. + key(SDL_SCANCODE_W, true); // No longer bound. + CHECK(app->poll_events() && move_y() == 0); + key(SDL_SCANCODE_I, true); + CHECK(app->poll_events() && move_y() == 1000); + // Two keys for one action: releasing either releases the action (never stuck). + key(SDL_SCANCODE_KP_8, true); + key(SDL_SCANCODE_KP_8, false); + CHECK(app->poll_events() && move_y() == 0); + key(SDL_SCANCODE_KP_8, true); + CHECK(app->poll_events() && move_y() == 1000); + key(SDL_SCANCODE_KP_8, false); + key(SDL_SCANCODE_I, false); + CHECK(app->poll_events() && move_y() == 0); + // Tab is unbound now; F1 toggles capture. + key(SDL_SCANCODE_TAB, true); + CHECK(app->poll_events() && !app->ui_captured()); + key(SDL_SCANCODE_F1, true); + key(SDL_SCANCODE_I, true); + CHECK(app->poll_events() && app->ui_captured() && move_y() == 0); + key(SDL_SCANCODE_F1, true); + CHECK(app->poll_events() && !app->ui_captured() && move_y() == 0); + key(SDL_SCANCODE_I, true); + CHECK(app->poll_events() && move_y() == 1000); + + // Binding capture: world input is released and captured while armed. + app->begin_key_capture(); + CHECK(app->key_capture_active() && app->ui_captured() && move_y() == 0); + key(SDL_SCANCODE_K, true, true); // A repeat is not a choice. + CHECK(app->poll_events() && app->key_capture_active()); + SDL_Event text{}; + text.type = SDL_EVENT_TEXT_INPUT; + text.text.windowID = id; + text.text.text = "k"; + key(SDL_SCANCODE_K, true); + CHECK(SDL_PushEvent(&text)); + key(SDL_SCANCODE_I, true); // Same batch after the choice: drained, no movement. + CHECK(app->poll_events() && !app->key_capture_active()); + CHECK(app->take_captured_key() == KeyCode{SDL_SCANCODE_K} && !app->take_captured_key()); + CHECK(!app->ui_captured() && move_y() == 0); + CHECK(app->present(frame) == Step::rendered); + CHECK(!ImGui::IsKeyDown(ImGuiKey_K)); // The toolkit never saw the chosen key. + key(SDL_SCANCODE_K, false); + key(SDL_SCANCODE_I, true); + CHECK(app->poll_events() && move_y() == 1000); + // Escape is captured too (the host treats it as cancel); bound keys do not act. + app->begin_key_capture(); + key(SDL_SCANCODE_ESCAPE, true); + CHECK(app->poll_events() && app->take_captured_key() == escape_key && move_y() == 0); + // Focus loss cancels capture without a key; explicit cancel likewise. + app->begin_key_capture(); + send(SDL_EVENT_WINDOW_FOCUS_LOST, id); + key(SDL_SCANCODE_J, true); + CHECK(app->poll_events() && !app->key_capture_active() && !app->take_captured_key()); + send(SDL_EVENT_WINDOW_FOCUS_GAINED, id); + CHECK(app->poll_events()); + app->begin_key_capture(); + app->cancel_key_capture(); + key(SDL_SCANCODE_J, true); + CHECK(app->poll_events() && !app->key_capture_active() && !app->take_captured_key()); + // Restoring defaults restores W after a fresh press. + app->set_bindings(Bindings::defaults()); + CHECK(app->poll_events()); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events() && move_y() == 1000); + CHECK(app->present(frame) == Step::rendered); +} } // namespace int main() try { client_controls_tests(); @@ -443,6 +543,7 @@ int main() try { lifecycle(); native_input(); toolkit_capture(); + rebinding(); return 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s: %s\n", e.what(), SDL_GetError()); diff --git a/tests/client_panels.cpp b/tests/client_panels.cpp index 07b5f14..3f83ab5 100644 --- a/tests/client_panels.cpp +++ b/tests/client_panels.cpp @@ -138,10 +138,87 @@ void notices() { const auto* more = ImGui::FindWindowByName("##evicted"); CHECK(more != nullptr && more->Active && more->Pos.y >= 0); } + +// M9.8d controls panel: fits the viewport, a slot button requests key capture for that +// slot without a world click, and the chosen key reaches neither toolkit nor world. +void controls_panel() { + const std::array boxes{{{0, 0, 32, 32, {40, 40, 40, 255}}}}; + auto frame = render::Frame::create(boxes); + CHECK(frame); + auto opened = Application::open({960, 640, false, "software"}); + CHECK(opened); + auto app = std::move(*opened); + const auto id = SDL_GetWindowID(window()); + SDL_Event focus{}; + focus.type = SDL_EVENT_WINDOW_FOCUS_GAINED; + focus.window.windowID = id; + CHECK(SDL_PushEvent(&focus) && app->poll_events()); + UiState ui; + EnvironmentLayer environment; + OrganismLayer organisms; + Selection selection; + Launcher launcher; + FormBuffers form; + render::EnvironmentDisplay display; + BindingEditor editor{app->bindings()}; + PanelView view; + view.mode = Mode::fixture; + view.launcher = &launcher; + view.environment = &environment; + view.organisms = &organisms; + view.selection = &selection; + view.ui = &ui; + view.bindings = &app->bindings(); + view.controls = &editor; + PanelActions last; + app->set_overlay([&] { + const auto a = draw_panels(view, form, display); + if (a.capture_key) + last.capture_key = a.capture_key; + last.apply_controls = last.apply_controls || a.apply_controls; + }); + app->set_ui_capture(true); // As the host does while the panel is open. + for (int i = 0; i < 2; ++i) + CHECK(app->poll_events() && app->present(*frame) == Step::rendered); + const auto* w = ImGui::FindWindowByName("Controls"); + CHECK(w != nullptr && w->Active); + const auto& style = ImGui::GetStyle(); + CHECK(w->ContentSize.x <= w->Size.x - (2 * style.WindowPadding.x) + 0.5F); + CHECK(w->Pos.x >= 0 && w->Pos.y >= 0 && w->Pos.x + w->Size.x <= 960 && + w->Pos.y + w->Size.y <= 640); + // Probe down the primary column until a slot button answers: the first row is + // Move left. Every probe is one batch (move, press, release). + const float x = + w->Pos.x + w->Size.x - style.WindowPadding.x - 150 - (2 * style.CellPadding.x) - 50; + for (float y = w->Pos.y + 20; y < w->Pos.y + w->Size.y && !last.capture_key; y += 4) { + mouse(id, SDL_EVENT_MOUSE_MOTION, x, y); + mouse(id, SDL_EVENT_MOUSE_BUTTON_DOWN, x, y); + mouse(id, SDL_EVENT_MOUSE_BUTTON_UP, x, y); + CHECK(app->poll_events() && !app->take_navigation().click); + for (int i = 0; i < 3 && !last.capture_key; ++i) + CHECK(app->present(*frame) == Step::rendered && app->poll_events()); + } + CHECK(last.capture_key == ControlSlot{Action::move_left, false} && !last.apply_controls); + // The host arms capture; the chosen key is consumed before the toolkit. + view.capturing = last.capture_key; + app->begin_key_capture(); + SDL_Event key{}; + key.type = SDL_EVENT_KEY_DOWN; + key.key.windowID = id; + key.key.scancode = SDL_SCANCODE_J; + CHECK(SDL_PushEvent(&key) && app->poll_events()); + CHECK(app->take_captured_key() == KeyCode{SDL_SCANCODE_J}); + CHECK(editor.assign(Action::move_left, false, SDL_SCANCODE_J)); + view.capturing.reset(); + CHECK(app->present(*frame) == Step::rendered && !ImGui::IsKeyDown(ImGuiKey_J)); + CHECK(editor.apply() && editor.apply()->action(SDL_SCANCODE_J) == Action::move_left); + CHECK(!app->take_navigation().click); +} } // namespace int main() try { notices(); + controls_panel(); std::puts("client panel tests passed"); return 0; } catch (const std::exception& e) {