diff --git a/apps/evo-client/controls_flow.hpp b/apps/evo-client/controls_flow.hpp new file mode 100644 index 0000000..31344b0 --- /dev/null +++ b/apps/evo-client/controls_flow.hpp @@ -0,0 +1,114 @@ +#pragma once +// M9.8d host side of the Controls panel (ADR-0085): startup loading, draft editing, +// binding capture and Apply/save. Kept out of main() so the real adapter and panels +// can rehearse Apply -> save -> restart -> load in tests. +#include "evo/client/application.hpp" +#include "evo/client/bindings.hpp" +#include "evo/client/ui_state.hpp" +#include "panels.hpp" +#include +#include +#include +#include +#include + +namespace evo::client_app { +class ControlsFlow { + public: + // `file` empty: nothing is loaded or saved (bindings still apply for the session). + explicit ControlsFlow(std::filesystem::path file) : file_{std::move(file)} {} + // Installs saved bindings. An invalid file is reported and left untouched; defaults + // stay in force until the user applies new bindings. + void load(client::Application& app, client::UiState& ui) const { + std::error_code missing; + if (file_.empty() || !std::filesystem::exists(file_, missing)) + return; + if (const auto loaded = client::load_bindings(file_)) + app.set_bindings(*loaded); + else + notify(ui, + "Saved controls rejected: " + client::describe(loaded.error()) + + " Default controls are in use; the file was not changed.", + client::NoticeLevel::warning, 15000); + } + [[nodiscard]] bool open() const noexcept { + return editor_.has_value(); + } + void show(const client::Application& app) { + if (!editor_) { + editor_.emplace(app.bindings()); + problem_.reset(); + } + } + void fill(PanelView& view) const { + view.controls = editor_ ? &*editor_ : nullptr; + view.capturing = capturing_; + view.controls_problem = problem_; + } + // One frame: panel actions, then a finished capture (key, Escape or focus loss), + // which only changes the draft. + void step(const PanelActions& a, client::Application& app, client::UiState& ui) { + if (a.open_controls) + show(app); + if (editor_) { + if (a.capture_key && !capturing_) { + capturing_ = a.capture_key; + problem_.reset(); + app.begin_key_capture(); + } + if (a.cancel_capture && capturing_) { + app.cancel_key_capture(); + capturing_.reset(); + } + if (a.clear_secondary) + editor_->clear_secondary(*a.clear_secondary); + if (a.reset_controls) { + editor_->reset_defaults(); + problem_.reset(); + } + if (a.apply_controls) + apply(app, ui); + if (a.close_controls) { + editor_.reset(); + problem_.reset(); + } + if (!editor_ && capturing_) { + app.cancel_key_capture(); + capturing_.reset(); + } + } + if (capturing_ && editor_ && !app.key_capture_active()) { + if (const auto key = app.take_captured_key(); key && *key != client::escape_key) { + if (auto assigned = + editor_->assign(capturing_->action, capturing_->secondary, *key); + !assigned) + problem_ = assigned.error(); + } + capturing_.reset(); + } + } + + private: + static void notify(client::UiState& ui, const std::string& text, client::NoticeLevel level, + std::uint64_t lifetime_ms = 5000) { + static_cast(ui.notify(text, level, lifetime_ms).has_value()); // Bounded. + } + void apply(client::Application& app, client::UiState& ui) { + const auto applied = editor_->apply(); + if (!applied) { + problem_ = applied.error(); + return; + } + app.set_bindings(*applied); // Releases held actions. + const bool saved = !file_.empty() && client::save_bindings(*applied, file_); + notify(ui, + saved ? "Controls saved." : "Controls apply to this session but could not be saved.", + saved ? client::NoticeLevel::info : client::NoticeLevel::warning); + editor_.reset(); + } + std::filesystem::path file_; + std::optional editor_; + std::optional capturing_; + std::optional problem_; +}; +} // namespace evo::client_app diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index 207e1e1..521a5bc 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -1,3 +1,4 @@ +#include "controls_flow.hpp" #include "evo/client/application.hpp" #include "evo/client/launcher.hpp" #include "evo/client/selection.hpp" @@ -335,31 +336,18 @@ int main(int argc, char** argv) try { std::fprintf(stderr, "client initialization error=%d\n", static_cast(app.error())); return 1; } - // 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. + // Controls (ADR-0085): per-user file unless --controls names one. 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; + // Notices expire on the same monotonic clock the loop uses. + static_cast(ui.advance(milliseconds(std::chrono::steady_clock::now())).has_value()); + evo::client_app::ControlsFlow controls{controls_path}; + controls.load(**app, ui); if (show_controls) - editor.emplace((*app)->bindings()); + controls.show(**app); + // A minimized native window may start with no drawable area. Adopt the + // native viewport before projecting; until then use the requested size. auto camera = evo::client::Camera::create( {config.width, config.height, config.width, config.height}, {}, 0.05); if (!camera) @@ -405,9 +393,7 @@ int main(int argc, char** argv) try { } view.visible_organisms = drawn_organisms; view.bindings = &(*app)->bindings(); - view.controls = editor ? &*editor : nullptr; - view.capturing = capturing; - view.controls_problem = controls_problem; + controls.fill(view); actions = evo::client_app::draw_panels(view, buffers, display); }); std::vector boxes; @@ -451,65 +437,11 @@ 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(); - } + controls.step(actions, **app, ui); actions = {}; // The launcher and modal dialogs own input: no world movement or selection. (*app)->set_ui_capture(mode() == Mode::launcher || ui.dialog().has_value() || - editor.has_value()); + controls.open()); 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/docs/adr/0085-rebindable-engineering-controls.md b/docs/adr/0085-rebindable-engineering-controls.md index a6d2ae0..a83111d 100644 --- a/docs/adr/0085-rebindable-engineering-controls.md +++ b/docs/adr/0085-rebindable-engineering-controls.md @@ -62,3 +62,13 @@ 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. + +## M9.8d review corrections +Binding capture now also balances the toolkit: arming capture drops the toolkit's +keyboard state and queued keyboard/text input (keys and modifiers whose releases +capture will consume), and the chosen physical key stays owned until its release or +focus loss, so its repeats, text and release reach neither toolkit nor world (text +is suppressed while it is held). The adapter runs an idle toolkit frame when nothing +is drawn and bounds the toolkit input queue at 512 events (dropped with every +toolkit key/button released). The Controls host logic lives in +`apps/evo-client/controls_flow.hpp` and is rehearsed with the real adapter. diff --git a/docs/engineering/CLIENT_UI_STATE.md b/docs/engineering/CLIENT_UI_STATE.md index 966d775..b78472a 100644 --- a/docs/engineering/CLIENT_UI_STATE.md +++ b/docs/engineering/CLIENT_UI_STATE.md @@ -83,3 +83,9 @@ saves; Reset defaults and Cancel only change the draft/close. A save failure lea 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. + +Capture and toolkit (M9.8d review): arming binding capture clears the toolkit's held +keys/modifiers and its queued keyboard/text input; the chosen key is consumed until +released (repeats, text, release), and focus loss frees it. With no overlay or a +paused window the adapter still runs idle toolkit frames; more than 512 queued +toolkit events are dropped with all toolkit keys/buttons released. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index a009fff..4bde568 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -3797,3 +3797,37 @@ 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. + + +## 2026-10-02 — M9.8d review corrections (.cache/reviews/m98d-review.md) + +1. Toolkit keys held before capture: `begin_key_capture` drops the toolkit's key and + modifier state plus queued keyboard/text events. 2. Chosen key ownership: the key + stays owned across polls until release or focus loss; repeats, text and release + are consumed. Also fixed (found while writing the regression): without an overlay + or while paused the toolkit queue was never consumed; idle toolkit frames run and + the queue is bounded at 512 events (lossy for the toolkit, never a stuck press). + +Tests now use realistic key events (scancode, keycode from the US fixture, down, +modifiers) in lifecycle and panel suites. New lifecycle `capture_balances_toolkit`: +positive controls (Q and Left Shift press and release in the toolkit), Shift+Q+W held +then released during capture under external capture for choose, cancel and focus +loss (all up in toolkit and world), chosen J held over three polls with repeats and +text (no queued toolkit input, J never down), fresh J afterwards reaches the toolkit, +owned key freed by focus loss, a 2000-event flood while hidden stays within the bound +and ends released. New panel `apply_save_restart`: real adapter, production panels +and `ControlsFlow` host logic; slot click arms capture, Up is refused as Pan up's key +(draft keeps A), J chosen, Apply via a click writes the file and shows "Controls +saved."; a restarted application loads it and J moves left. + +Negative checks (Windows MSVC): removing the toolkit reset fails the held-key check; +removing key ownership fails the repeat/text check. + +Executed: Windows MSVC client 9/9, client-network 10/10 (final, after formatting). +Linux: clang-19 client-probe with clang-tidy (keep-going, no owned diagnostics) +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; +repository format check. + +Limits: physical keyboards, non-US layouts and IME remain unqualified; the Apply +rehearsal is automated with synthetic events, not a manual session. diff --git a/src/client/platform/application.cpp b/src/client/platform/application.cpp index 39928fa..cb68cf6 100644 --- a/src/client/platform/application.cpp +++ b/src/client/platform/application.cpp @@ -55,6 +55,39 @@ struct Toolkit { renderer = false; } }; +// Drops the toolkit's keyboard state and any keyboard/text input it has queued but not +// yet processed. Used when binding capture starts: releases of keys the toolkit already +// saw pressed will be consumed by capture, so they must not stay down there. +void reset_toolkit_keys() { + auto& queue = ImGui::GetCurrentContext()->InputEventsQueue; + for (int i = 0; i < queue.Size;) { + if (queue[i].Type == ImGuiInputEventType_Key || queue[i].Type == ImGuiInputEventType_Text) + queue.erase(queue.Data + i); + else + ++i; + } + ImGui::GetIO().ClearInputKeys(); // Keys, modifiers and pending characters. +} +// Consumes the toolkit's queued input when nothing is drawn (no overlay, or a paused +// window), so its event queue stays bounded and its key state follows the events. +void idle_toolkit_frame() { + ImGui_ImplSDLRenderer3_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + ImGui::EndFrame(); +} +// The toolkit trickles queued input (one transition per key per frame), so a flood can +// outpace frames. Past this bound its queue is dropped and every toolkit key/button is +// released: lossy for the toolkit, never a stuck or replayed press. +constexpr int max_toolkit_events = 512; +void bound_toolkit_queue() { + auto& io = ImGui::GetIO(); + if (ImGui::GetCurrentContext()->InputEventsQueue.Size <= max_toolkit_events) + return; + io.ClearEventsQueue(); + io.ClearInputKeys(); + io.ClearInputMouse(); +} constexpr float click_slop = 4; // Logical units between press and release. // True when `at` lies on a toolkit window drawn in the last frame or any popup is open. // Resolved per event from the toolkit's retained window rectangles, so a move onto a @@ -93,6 +126,9 @@ struct Application::Impl { bool backlogged{false}; bool key_capture{false}; // Binding capture armed. std::optional captured_key; // Taken once by the host. + // The chosen physical key stays owned by capture until its release (or focus loss): + // its repeats, text and release reach neither the toolkit nor the world. + std::optional owned_key; // 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}; @@ -157,6 +193,7 @@ const Bindings& Application::bindings() const noexcept { return impl_->bindings; } void Application::begin_key_capture() noexcept { + reset_toolkit_keys(); impl_->captured_key.reset(); impl_->key_capture = true; impl_->update_capture(); @@ -256,24 +293,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 + // Binding capture consumes keyboard events before the toolkit and world. While + // the chosen key is still held, its repeats and release are consumed, and so is + // all text input (it cannot be attributed to a key). + const bool key_event = event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP; + const bool keyboard = key_event ? 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)))) { + const bool owned = + keyboard && p.owned_key && (!key_event || event.key.scancode == *p.owned_key); + if (keyboard && (p.key_capture || owned)) { if (p.key_capture && event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) { p.captured_key = static_cast(event.key.scancode); + p.owned_key = event.key.scancode; p.key_capture = false; - key_chosen = true; p.update_capture(); // Drains the rest of this batch before world input. + } else if (owned && event.type == SDL_EVENT_KEY_UP) { + p.owned_key.reset(); } continue; } @@ -315,6 +355,7 @@ 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; + p.owned_key.reset(); // The toolkit clears its own keys on focus loss. if (p.key_capture) { // Focus loss cancels binding capture without a key. p.key_capture = false; p.update_capture(); @@ -375,6 +416,7 @@ std::expected Application::poll_events() { reset = true; } } + bound_toolkit_queue(); if (p.failure) { p.input.admit(false); return std::unexpected(*p.failure); @@ -414,8 +456,10 @@ std::expected Application::present(const render::Frame& frame) { if (p.state.closed) return Step::closed; if (p.state.hidden || p.state.minimized || p.state.logical_width == 0 || - p.state.logical_height == 0 || p.state.pixel_width == 0 || p.state.pixel_height == 0) + p.state.logical_height == 0 || p.state.pixel_width == 0 || p.state.pixel_height == 0) { + idle_toolkit_frame(); return Step::paused; + } if (auto result = detail::draw(p.renderer.get(), frame, p.state); !result) { p.failure = result.error(); p.input.admit(false); @@ -429,6 +473,8 @@ std::expected Application::present(const render::Frame& frame) { p.overlay(); ImGui::Render(); ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), p.renderer.get()); + } else { + idle_toolkit_frame(); } if (!p.screenshot.empty()) { // Engineering visual review only: the composed frame as an uncompressed BMP. diff --git a/tests/client_lifecycle.cpp b/tests/client_lifecycle.cpp index 65fc197..df014b6 100644 --- a/tests/client_lifecycle.cpp +++ b/tests/client_lifecycle.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -167,6 +168,8 @@ void native_input() { event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; event.key.windowID = id; event.key.scancode = scancode; + event.key.key = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); // US fixture. + event.key.down = down; event.key.repeat = repeat; CHECK(SDL_PushEvent(&event)); }; @@ -356,6 +359,8 @@ void toolkit_capture() { event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; event.key.windowID = id; event.key.scancode = scancode; + event.key.key = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); // US fixture. + event.key.down = down; event.key.repeat = repeat; CHECK(SDL_PushEvent(&event)); }; @@ -452,6 +457,8 @@ void rebinding() { event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; event.key.windowID = id; event.key.scancode = scancode; + event.key.key = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); // US fixture. + event.key.down = down; event.key.repeat = repeat; CHECK(SDL_PushEvent(&event)); }; @@ -536,6 +543,143 @@ void rebinding() { CHECK(app->poll_events() && move_y() == 1000); CHECK(app->present(frame) == Step::rendered); } +// M9.8d review: realistic key events (keycode, scancode, modifiers). Keys the toolkit +// saw pressed before binding capture are up there after choose, cancel or focus loss; +// the chosen key is owned until released (no repeats, text or press reach the toolkit). +int queued_keyboard_events() { + const auto& queue = ImGui::GetCurrentContext()->InputEventsQueue; + int n = 0; + for (const auto& e : queue) + n += e.Type == ImGuiInputEventType_Key || e.Type == ImGuiInputEventType_Text ? 1 : 0; + return n; +} +void capture_balances_toolkit() { + 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); + auto push = [id](SDL_Scancode scancode, bool down, bool repeat = false, + SDL_Keymod mod = SDL_KMOD_NONE) { + SDL_Event event{}; + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.windowID = id; + event.key.scancode = scancode; + event.key.key = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); + event.key.mod = mod; + event.key.down = down; + event.key.repeat = repeat; + CHECK(SDL_PushEvent(&event)); + }; + auto text = [id](const char* utf8) { + SDL_Event event{}; + event.type = SDL_EVENT_TEXT_INPUT; + event.text.windowID = id; + event.text.text = utf8; + CHECK(SDL_PushEvent(&event)); + }; + const auto frame_once = [&] { + CHECK(app->poll_events() && app->present(frame) == Step::rendered); + }; + const auto& io = ImGui::GetIO(); + // No overlay: the adapter still runs idle toolkit frames, so its key state follows. + std::uint64_t tick = 300; + const auto move_y = [&] { return required(app->sample_intention(++tick)).move_y; }; + CHECK(app->present(frame) == Step::rendered); + // Positive controls: complete events press and release toolkit keys and modifiers. + push(SDL_SCANCODE_Q, true); + frame_once(); + CHECK(ImGui::IsKeyDown(ImGuiKey_Q)); + push(SDL_SCANCODE_Q, false); + frame_once(); + CHECK(!ImGui::IsKeyDown(ImGuiKey_Q)); + push(SDL_SCANCODE_LSHIFT, true, false, SDL_KMOD_LSHIFT); + frame_once(); + CHECK(ImGui::IsKeyDown(ImGuiKey_LeftShift) && io.KeyShift); + push(SDL_SCANCODE_LSHIFT, false); + frame_once(); + CHECK(!ImGui::IsKeyDown(ImGuiKey_LeftShift) && !io.KeyShift); + + // Shift+Q and W held, capture armed (the host holds external capture for the + // Controls panel), all three released while capture consumes keyboard input. + const auto held_then_released = [&](const auto& finish) { + app->set_ui_capture(true); + push(SDL_SCANCODE_LSHIFT, true, false, SDL_KMOD_LSHIFT); + push(SDL_SCANCODE_Q, true, false, SDL_KMOD_LSHIFT); + push(SDL_SCANCODE_W, true, false, SDL_KMOD_LSHIFT); + frame_once(); + CHECK(ImGui::IsKeyDown(ImGuiKey_Q) && ImGui::IsKeyDown(ImGuiKey_LeftShift) && io.KeyShift); + app->begin_key_capture(); + push(SDL_SCANCODE_Q, false, false, SDL_KMOD_LSHIFT); + push(SDL_SCANCODE_LSHIFT, false); + push(SDL_SCANCODE_W, false); + frame_once(); + finish(); + frame_once(); + CHECK(!ImGui::IsKeyDown(ImGuiKey_Q) && !ImGui::IsKeyDown(ImGuiKey_LeftShift) && + !ImGui::IsKeyDown(ImGuiKey_W) && !io.KeyShift); + app->set_ui_capture(false); + CHECK(app->poll_events() && move_y() == 0); + }; + // 1. Choose J, then hold it across polls: repeats and text stay away from the toolkit. + held_then_released([&] { + push(SDL_SCANCODE_J, true); + CHECK(app->poll_events() && app->take_captured_key() == KeyCode{SDL_SCANCODE_J}); + for (int i = 0; i < 3; ++i) { + push(SDL_SCANCODE_J, true, true); + text("j"); + CHECK(app->poll_events() && queued_keyboard_events() == 0); + CHECK(app->present(frame) == Step::rendered && !ImGui::IsKeyDown(ImGuiKey_J)); + } + push(SDL_SCANCODE_J, false); // Release ends ownership; it is consumed too. + CHECK(app->poll_events() && queued_keyboard_events() == 0); + }); + // After release a fresh press reaches the toolkit normally (positive control). + push(SDL_SCANCODE_J, true); + CHECK(app->poll_events() && queued_keyboard_events() > 0); + CHECK(app->present(frame) == Step::rendered && ImGui::IsKeyDown(ImGuiKey_J)); + push(SDL_SCANCODE_J, false); + frame_once(); + CHECK(!ImGui::IsKeyDown(ImGuiKey_J)); + // 2. Explicit cancel. + held_then_released([&] { + app->cancel_key_capture(); + CHECK(!app->key_capture_active() && !app->take_captured_key()); + }); + // 3. Focus loss cancels capture; also drops an owned key held at that moment. + held_then_released([&] { + send(SDL_EVENT_WINDOW_FOCUS_LOST, id); + 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(); + push(SDL_SCANCODE_K, true); + CHECK(app->poll_events() && app->take_captured_key() == KeyCode{SDL_SCANCODE_K}); + send(SDL_EVENT_WINDOW_FOCUS_LOST, id); + send(SDL_EVENT_WINDOW_FOCUS_GAINED, id); + CHECK(app->poll_events()); + push(SDL_SCANCODE_K, true); // K's release never arrived; after focus loss it is free. + CHECK(app->poll_events() && queued_keyboard_events() > 0); + CHECK(app->present(frame) == Step::rendered && ImGui::IsKeyDown(ImGuiKey_K)); + // World input still works with fresh presses. + push(SDL_SCANCODE_W, true); + CHECK(app->poll_events() && move_y() == 1000); + // While paused (hidden) nothing is drawn, yet the toolkit queue stays bounded. + send(SDL_EVENT_WINDOW_HIDDEN, id); + for (int round = 0; round < 20; ++round) { + for (int i = 0; i < 100; ++i) + push(SDL_SCANCODE_Q, i % 2 == 0); + CHECK(app->poll_events() && app->present(frame) == Step::paused); + CHECK(ImGui::GetCurrentContext()->InputEventsQueue.Size <= 512); // Adapter bound. + } + send(SDL_EVENT_WINDOW_SHOWN, id); + for (int i = 0; i < 2; ++i) + CHECK(app->poll_events() && app->present(frame) == Step::rendered); + CHECK(!ImGui::IsKeyDown(ImGuiKey_Q)); // The flood ended with a release; never stuck. +} } // namespace int main() try { client_controls_tests(); @@ -544,6 +688,7 @@ int main() try { native_input(); toolkit_capture(); rebinding(); + capture_balances_toolkit(); 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 3f83ab5..8c91123 100644 --- a/tests/client_panels.cpp +++ b/tests/client_panels.cpp @@ -2,11 +2,13 @@ // software renderer, pinned toolkit). Notices fit their fixed-width window with a // visible close button; clicking it (move + press + release in one batch, no settling // frame) dismisses exactly that notice and never reaches the world. +#include "controls_flow.hpp" #include "evo/client/application.hpp" #include "panels.hpp" #include #include #include +#include #include #include #include @@ -206,6 +208,8 @@ void controls_panel() { key.type = SDL_EVENT_KEY_DOWN; key.key.windowID = id; key.key.scancode = SDL_SCANCODE_J; + key.key.key = SDL_GetKeyFromScancode(SDL_SCANCODE_J, SDL_KMOD_NONE, false); + key.key.down = true; 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)); @@ -214,11 +218,143 @@ void controls_panel() { CHECK(editor.apply() && editor.apply()->action(SDL_SCANCODE_J) == Action::move_left); CHECK(!app->take_navigation().click); } + +// M9.8d review: host rehearsal through the real adapter, production panels and the +// host's ControlsFlow: click a slot, a conflicting key is refused, choose J, Apply +// writes the file; a restarted application loads it and J moves left. +SDL_Event key_event(SDL_WindowID id, SDL_Scancode scancode, bool down) { + SDL_Event event{}; + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.windowID = id; + event.key.scancode = scancode; + event.key.key = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); + event.key.down = down; + return event; +} +void apply_save_restart() { + const auto dir = std::filesystem::temp_directory_path() / "evo-controls-rehearsal"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + const auto file = dir / "controls-v1.txt"; + 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; + ControlsFlow flow{file}; + flow.load(*app, ui); // No file yet: defaults. + CHECK(app->bindings() == Bindings::defaults()); + flow.show(*app); + PanelActions pending; + app->set_overlay([&] { + 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(); + flow.fill(view); + pending = draw_panels(view, form, display); + }); + // The host's frame order: poll, panel actions of the last frame, capture, draw. + const auto host_frame = [&] { + CHECK(app->poll_events()); + flow.step(pending, *app, ui); + pending = {}; + app->set_ui_capture(flow.open()); + CHECK(!app->take_navigation().click && app->present(*frame) == Step::rendered); + }; + for (int i = 0; i < 2; ++i) + host_frame(); + const auto* w = ImGui::FindWindowByName("Controls"); + CHECK(w != nullptr && w->Active); + const auto& style = ImGui::GetStyle(); + // Probe one-batch clicks until `done` reports the intended widget answered. + const auto probe = [&](float x, float y0, float y1, float dy, const auto& done) { + for (float y = y0; (dy > 0 ? y < y1 : y > y1); y += dy) { + 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); + for (int i = 0; i < 3; ++i) { + host_frame(); + if (done()) + return true; + } + } + return false; + }; + const float primary_x = + w->Pos.x + w->Size.x - style.WindowPadding.x - 150 - (2 * style.CellPadding.x) - 50; + CHECK(probe(primary_x, w->Pos.y + 20, w->Pos.y + w->Size.y, 4, + [&] { return app->key_capture_active(); })); + // Up is Pan up's key: refused, the draft keeps A. Then arm again and choose J. + auto up = key_event(id, SDL_SCANCODE_UP, true); + CHECK(SDL_PushEvent(&up)); + host_frame(); + CHECK(!app->key_capture_active()); + PanelView shown; + flow.fill(shown); + CHECK(shown.controls != nullptr && shown.controls->draft()[0].primary == SDL_SCANCODE_A); + CHECK(shown.controls_problem && shown.controls_problem->error == BindingError::conflict && + shown.controls_problem->other == Action::pan_up); + auto up_release = key_event(id, SDL_SCANCODE_UP, false); + CHECK(SDL_PushEvent(&up_release)); + host_frame(); + CHECK(probe(primary_x, w->Pos.y + 20, w->Pos.y + w->Size.y, 4, + [&] { return app->key_capture_active(); })); + auto j = key_event(id, SDL_SCANCODE_J, true); + auto j_release = key_event(id, SDL_SCANCODE_J, false); + CHECK(SDL_PushEvent(&j) && SDL_PushEvent(&j_release)); + host_frame(); + CHECK(!app->key_capture_active() && flow.open() && !std::filesystem::exists(file)); + // Apply sits at the bottom left of the panel. + CHECK(probe(w->Pos.x + style.WindowPadding.x + 40, w->Pos.y + w->Size.y - 6, w->Pos.y, -4, + [&] { return !flow.open(); })); + CHECK(app->bindings().action(SDL_SCANCODE_J) == Action::move_left); + CHECK(!app->bindings().action(SDL_SCANCODE_A)); + CHECK(std::filesystem::exists(file) && !ui.notices().empty() && + ui.notices().back().text == "Controls saved."); + } + // Restart: a new application loads the saved file; J moves left after a press. + auto opened = Application::open({320, 240, false, "software"}); + CHECK(opened); + auto app = std::move(*opened); + const auto id = SDL_GetWindowID(window()); + UiState ui; + ControlsFlow{file}.load(*app, ui); + CHECK(ui.notices().empty() && app->bindings().action(SDL_SCANCODE_J) == Action::move_left); + SDL_Event focus{}; + focus.type = SDL_EVENT_WINDOW_FOCUS_GAINED; + focus.window.windowID = id; + CHECK(SDL_PushEvent(&focus) && app->poll_events() && app->poll_events()); + auto j = key_event(id, SDL_SCANCODE_J, true); + CHECK(SDL_PushEvent(&j) && app->poll_events()); + const auto intention = app->sample_intention(1); + CHECK(intention && intention->move_x == -1000); + std::filesystem::remove_all(dir); +} } // namespace int main() try { notices(); controls_panel(); + apply_save_restart(); std::puts("client panel tests passed"); return 0; } catch (const std::exception& e) {