Verify order selection through real window controls and modal replacement

This commit is contained in:
faumaray committed 2026-12-02 23:23:51 +03:00
1 parent a1c65119a2
commit 13b4665ed2
4 files changed
+89 -14

No files matched your search

+1 -1
View File
@@ -1878,7 +1878,7 @@ void manage_orders_at_cell(HWND window, settlement::GridPosition cell) {
if (offset != 0 || more) AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); if (offset != 0 || more) AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
if (offset != 0) AppendMenuW(menu, MF_STRING, previous_page, L"← Предыдущие заказы"); if (offset != 0) AppendMenuW(menu, MF_STRING, previous_page, L"← Предыдущие заказы");
if (more) AppendMenuW(menu, MF_STRING, next_page, L"Следующие заказы →"); if (more) AppendMenuW(menu, MF_STRING, next_page, L"Следующие заказы →");
const auto selected = static_cast<UINT>(TrackPopupMenu(menu, TPM_RETURNCMD | TPM_NONOTIFY | const auto selected = static_cast<UINT>(TrackPopupMenu(menu, TPM_RETURNCMD |
TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, window, nullptr)); TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, window, nullptr));
DestroyMenu(menu); DestroyMenu(menu);
if (!current_context()) { if (!current_context()) {
+14
View File
@@ -20,6 +20,20 @@
Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06. Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06.
## Реализованный срез S04-02: отмена и возобновление
Современная сессия принимает отдельные `CancelProductionPayload{ProductionId}` и `ResumeProductionPayload{ProductionId}`. Диспетчер проверяет доверенного игрока, мир, инкарнацию, город и номер запроса, затем передаёт действие в `World::cancel_production` / `resume_production`. Их физические эффекты принадлежат [S06](S06.md): адаптер команд не перемещает имущество самостоятельно. Современные действия доступны хозяину; гостю возвращается сохраняемый `Unauthorized`. Они не расширяют `CommandKind`, LAN 11 и прежнюю нумерацию `PlayerCommand`.
Принятый результат и отказ сохраняются в существующем журнале с исходными тактом и ревизией. Точный повтор возвращает прежнюю квитанцию даже после удаления заказа. Другой ID или замена отмены на возобновление под тем же номером возвращает `Conflict`; новый успешный эффект увеличивает ревизию ровно один раз. Используется существующий контракт [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6) для журнала и [#8](https://git.faumaray.com/Void/Library/issues/8) для физического перехода. У закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792` нет готового игрового жизненного цикла заказа; условия замены журнала и передачи имущества сохраняются в этих задачах.
В обычном окне игры команда находится в **Работы → Управление заказами…**. После выбора клетки меню показывает явные «Отменить» / «Возобновить», название работы, постоянный ID и координаты. Несколько заказов одной клетки остаются отдельными действиями; страницы содержат до 16 заказов с переходами вперёд и назад. Отмена предлагается для незавершённых активных работ, возобновление — для приостановленных. Завершённые итоговые объекты сохраняют прежний отказ `Busy` от ядра. Перед отправкой повторно проверяются актуальный заказ, полная идентичность сессии, поколение представления, начавшаяся смена мира, сетевое соединение и выбранный режим. Открытый снимок удерживается до закрытия меню. Диалог из прежней колонии не может отправить действие в новую; гость LAN 11 не видит инструмент и не может вызвать его синтетической командой окна.
До квитанции интерфейс показывает ожидание подтверждения. Подтверждённая отмена сообщает о сохранении установленных частей и последующем возврате груза; возобновление сообщает о продолжении работы. У возвращающего материалы жителя видны действительный состав сумки и причина ожидания: отсутствие доступного склада, недостаток места, занятый склад либо предел учёта. Прежние `DemolishObject` / `MoveObject` сохраняют отказы при занятом источнике, складе и объекте.
Проверки с реальным ядром: [production_commands_tests.cpp](../../../tests/production_commands_tests.cpp) — повтор принятых/отклонённых результатов, конфликты вариантов и ID, границы контекста и прав, отмена до получения/в пути/на площадке, ожидание полного склада и возврат всех материалов, продолжение частичной кровати и установленного станка, публикация runtime. [production_controls_tests.cpp](../../../tests/production_controls_tests.cpp) создаёт настоящее Win32-окно с Direct3D, выбирает клетку обычными сообщениями мыши, проходит меню клавиатурным вводом через `WM_TIMER`, проверяет квитанции обоих действий, выбор точного ID и доступ ко всем 35 заказам на одной клетке, смену мира во время меню, подключённого гостя LAN 11 и причину ожидания возвращающегося жителя. Каждый запуск окна использует отдельный временный каталог пользовательских данных.
На объединённом ядре S06 и кодеке S15 выполнена сборка Windows x64 GCC 16.2; полный `ctest -V` под Wine 11 прошёл 4 исполняемых набора: 160 core, 4 LAN, 14 viewer-session и 6 Win32 controls. В предыдущем полном прогоне один существовавший тест восстановления после сбоя (`viewer_session_tests.cpp:363`) однократно не получил ожидаемый допуск синхронизации; отдельный повтор и итоговый полный прогон прошли. Нативные Windows и MSVC не проверялись.
## Данные и владение ## Данные и владение
| Новый объект | Ответственность | | Новый объект | Ответственность |
+9 -3
View File
@@ -74,8 +74,8 @@ struct [[= Void::Testing::name("ProductionCommandsTests")]] ProductionCommandsTe
Test ProductionCommandsTests::exact_results_and_conflicts_use_durable_ids() { Test ProductionCommandsTests::exact_results_and_conflicts_use_durable_ids() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference); World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.queue_production({8, 8}, RecipeId::BuildCabin); world.queue_production({8, 8}, RecipeId::SawPlank);
world.queue_production({8, 8}, RecipeId::BuildCabin); world.queue_production({8, 8}, RecipeId::SawPlank);
const auto first = world.production_orders().front().id; const auto first = world.production_orders().front().id;
const auto second = world.production_orders().back().id; const auto second = world.production_orders().back().id;
CommandDispatcher dispatcher(identity()); CommandDispatcher dispatcher(identity());
@@ -219,6 +219,10 @@ Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identi
require(world.find_production(id) && world.find_production(id)->suspended && require(world.find_production(id) && world.find_production(id)->suspended &&
world.find_production(id)->bed_stage == stage && !world.can_place_storage({9, 3}), world.find_production(id)->bed_stage == stage && !world.can_place_storage({9, 3}),
"cancel removed installed progress or its occupied site"); "cancel removed installed progress or its occupied site");
const auto suspended_cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id});
const auto busy = dispatcher.dispatch(world, host, suspended_cancel);
require(busy.status == DispatchStatus::Completed && busy.command_status == CommandStatus::Busy &&
dispatcher.dispatch(world, host, suspended_cancel) == busy);
for (int tick = 0; tick < 5; ++tick) world.step(); for (int tick = 0; tick < 5; ++tick) world.step();
const auto resume = envelope(dispatcher.next_request(host), ResumeProductionPayload{id}); const auto resume = envelope(dispatcher.next_request(host), ResumeProductionPayload{id});
const auto resumed = dispatcher.dispatch(world, host, resume); const auto resumed = dispatcher.dispatch(world, host, resume);
@@ -226,6 +230,8 @@ Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identi
require(world.find_production(id) && !world.find_production(id)->suspended && require(world.find_production(id) && !world.find_production(id)->suspended &&
world.find_production(id)->bed_stage == stage && dispatcher.dispatch(world, host, resume) == resumed && world.find_production(id)->bed_stage == stage && dispatcher.dispatch(world, host, resume) == resumed &&
world.next_command_sequence(1) == sequence && !before_cancel->find_production(id)->suspended); world.next_command_sequence(1) == sequence && !before_cancel->find_production(id)->suspended);
require(dispatcher.dispatch(world, host, suspended_cancel) == busy && !world.find_production(id)->suspended,
"old refused cancellation changed after the same durable order was resumed");
world.stock_storage(storage, bed ? ItemType::Cloth : ItemType::Flax, 2); world.stock_storage(storage, bed ? ItemType::Cloth : ItemType::Flax, 2);
step_until(world, [&] { return bed ? world.find_production(id)->state == JobState::Completed : step_until(world, [&] { return bed ? world.find_production(id)->state == JobState::Completed :
world.find_storage(storage)->item_count(ItemType::Cloth) > 0; }); world.find_storage(storage)->item_count(ItemType::Cloth) > 0; });
@@ -233,7 +239,7 @@ Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identi
"resume charged for an already installed stage twice"); "resume charged for an already installed stage twice");
if (bed) { if (bed) {
const auto refused = send(world, dispatcher, CancelProductionPayload{id}); const auto refused = send(world, dispatcher, CancelProductionPayload{id});
require(refused.command_status == CommandStatus::InvalidTarget, require(refused.command_status == CommandStatus::Busy,
"completed final bed accepted cancel"); "completed final bed accepted cancel");
} }
} }
+65 -10
View File
@@ -44,7 +44,8 @@ LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPAR
} }
if (message == WM_TIMER && wparam == drive_timer) { if (message == WM_TIMER && wparam == drive_timer) {
if (++timer_attempts > 100) { if (++timer_attempts > 100) {
driver_error = "real popup did not accept the scripted input"; driver_error = "real popup did not accept input: menus=" + std::to_string(observed_menus.size()) +
" remaining=" + std::to_string(steps.size()) + " active=" + std::to_string(active_menu != nullptr);
KillTimer(window, drive_timer); KillTimer(window, drive_timer);
EndMenu(); EndMenu();
return 0; return 0;
@@ -62,7 +63,13 @@ LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPAR
EndMenu(); EndMenu();
return 0; return 0;
} }
if (step.before_select) step.before_select(); try {
if (step.before_select) step.before_select();
} catch (const std::exception& error) {
driver_error = error.what();
EndMenu();
return 0;
}
std::vector<INPUT> input; std::vector<INPUT> input;
key(input, VK_HOME); key(input, VK_HOME);
for (int index = 0; index < target; ++index) { for (int index = 0; index < target; ++index) {
@@ -94,13 +101,14 @@ struct Window {
auto rules = default_rules_manifest(); auto rules = default_rules_manifest();
require(rules.has_value()); require(rules.has_value());
session = std::make_unique<settlement::viewer::ViewerSession>( session = std::make_unique<settlement::viewer::ViewerSession>(
WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 1); WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 2);
world = session->world(); world = session->world();
showing_title = true; showing_title = true;
has_session = true; has_session = true;
lan = std::make_unique<settlement::viewer::LanSession>(); lan = std::make_unique<settlement::viewer::LanSession>();
displayed_lan_state = LanState::Offline; displayed_lan_state = LanState::Offline;
placement_mode = PlacementMode::None; placement_mode = PlacementMode::None;
camera = {};
placement_message.clear(); placement_message.clear();
steps.clear(); steps.clear();
observed_menus.clear(); observed_menus.clear();
@@ -163,17 +171,33 @@ struct Window {
} }
require(placement_mode == PlacementMode::ManageOrders, "Работы menu did not activate order management"); require(placement_mode == PlacementMode::ManageOrders, "Работы menu did not activate order management");
} }
void click_cell(GridPosition cell) {
RECT client{};
GetClientRect(handle, &client);
const auto scale = camera.scale();
const auto offset = camera.offset();
POINT point{static_cast<LONG>((client.right / 2.0 + (cell.x - cell.y) * tile_width / 2.0) * scale + offset.x),
static_cast<LONG>((map_origin_y + (cell.x + cell.y) * tile_height / 2.0) * scale + offset.y)};
require(map_cell(client, point) == cell, "normal map hit test did not select the target cell");
auto screen = point;
ClientToScreen(handle, &screen);
SetCursorPos(screen.x, screen.y);
const auto coordinates = MAKELPARAM(point.x, point.y);
SendMessageW(handle, WM_LBUTTONDOWN, MK_LBUTTON, coordinates);
SendMessageW(handle, WM_LBUTTONUP, 0, coordinates);
}
}; };
std::unique_ptr<World> orders(unsigned count = 2) { std::unique_ptr<World> orders(unsigned count = 2) {
auto result = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference); auto result = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::BuildCabin); for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::SawPlank);
return result; return result;
} }
struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests
: Void::Testing::Suite<ProductionControlsTests> { : Void::Testing::Suite<ProductionControlsTests> {
[[= Void::Testing::tag("production-controls")]] Test real_work_menu_selects_exact_id_and_waits_for_receipt(); [[= Void::Testing::tag("production-controls")]] Test real_work_menu_selects_exact_id_and_waits_for_receipt();
[[= Void::Testing::tag("production-controls")]] Test real_resume_choice_keeps_installed_loom_and_waits_for_receipt();
[[= Void::Testing::tag("production-controls")]] Test every_order_remains_accessible_across_popup_pages(); [[= Void::Testing::tag("production-controls")]] Test every_order_remains_accessible_across_popup_pages();
[[= Void::Testing::tag("production-controls")]] Test replacement_during_popup_cannot_cancel_in_new_world(); [[= Void::Testing::tag("production-controls")]] Test replacement_during_popup_cannot_cancel_in_new_world();
[[= Void::Testing::tag("production-controls")]] Test legacy_guest_has_no_action_or_modern_submission(); [[= Void::Testing::tag("production-controls")]] Test legacy_guest_has_no_action_or_modern_submission();
@@ -185,11 +209,11 @@ Test ProductionControlsTests::real_work_menu_selects_exact_id_and_waits_for_rece
const auto first = world->production_orders().front().id; const auto first = world->production_orders().front().id;
const auto second = world->production_orders().back().id; const auto second = world->production_orders().back().id;
fixture.activate_tool(); fixture.activate_tool();
fixture.menu({{2, {}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); fixture.menu({{2, {}}}, [&] { fixture.click_cell({8, 8}); });
require(world->find_production(second) && world->find_production(first) && require(world->find_production(second) && world->find_production(first) &&
placement_message.find(L"ожидает подтверждения") != std::wstring::npos, placement_message.find(L"ожидает подтверждения") != std::wstring::npos,
"UI forged success before a committed receipt"); "UI forged success before a committed receipt");
require(observed_menus.back().at(1).find(L"Отменить: Построить домик №" + std::to_wstring(second)) != std::wstring::npos && require(observed_menus.back().at(1).find(L"Отменить: Распилить доску №" + std::to_wstring(second)) != std::wstring::npos &&
observed_menus.back().at(1).find(L"[9, 9]") != std::wstring::npos, observed_menus.back().at(1).find(L"[9, 9]") != std::wstring::npos,
"actual popup lost the order name, durable id or user-facing position"); "actual popup lost the order name, durable id or user-facing position");
fixture.pump_until([&] { return !world->find_production(second); }); fixture.pump_until([&] { return !world->find_production(second); });
@@ -201,12 +225,28 @@ Test ProductionControlsTests::every_order_remains_accessible_across_popup_pages(
Window fixture(orders(35)); Window fixture(orders(35));
const auto last = world->production_orders().back().id; const auto last = world->production_orders().back().id;
fixture.activate_tool(); fixture.activate_tool();
fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { fixture.click_cell({8, 8}); });
fixture.pump_until([&] { return !world->find_production(last); }); fixture.pump_until([&] { return !world->find_production(last); });
require(world->production_orders().size() == 34 && world->production_orders().front().id == 1); require(world->production_orders().size() == 34 && world->production_orders().front().id == 1);
for (const auto& page : observed_menus) require(page.size() <= 19, "popup page exceeded its bounded display size"); for (const auto& page : observed_menus) require(page.size() <= 19, "popup page exceeded its bounded display size");
} }
Test ProductionControlsTests::real_resume_choice_keeps_installed_loom_and_waits_for_receipt() {
auto initial = orders(0);
initial->queue_production({8, 8}, RecipeId::WeaveCloth);
const auto id = initial->production_orders().front().id;
require(initial->cancel_production(id) == CommandStatus::Accepted && initial->find_production(id)->suspended);
Window fixture(std::move(initial));
fixture.activate_tool();
fixture.menu({{1, {}}}, [&] { fixture.click_cell({8, 8}); });
require(world->find_production(id)->suspended &&
placement_message.find(L"ожидает подтверждения") != std::wstring::npos);
require(observed_menus.back().at(0).find(L"Возобновить: Ткать ткань №" + std::to_wstring(id)) != std::wstring::npos);
fixture.pump_until([&] { return !world->find_production(id)->suspended; });
require(world->find_production(id)->recipe == RecipeId::WeaveCloth &&
placement_message.find(L"возобновлена") != std::wstring::npos && world->next_command_sequence(1) == 1);
}
Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_world() { Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_world() {
for (const bool complete_replacement : {false, true}) { for (const bool complete_replacement : {false, true}) {
Window fixture(orders()); Window fixture(orders());
@@ -223,7 +263,7 @@ Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_worl
} }
world = session->world(); world = session->world();
} }
}}}, [&] { edit_at_cell(fixture.handle, {8, 8}); }); }}}, [&] { fixture.click_cell({8, 8}); });
fixture.pump_until([&] { return !session->changing_world(); }); fixture.pump_until([&] { return !session->changing_world(); });
const auto current = session->runtime().latest(); const auto current = session->runtime().latest();
require(current->identity != opening->identity && current->next_requests[0] == 1 && require(current->identity != opening->identity && current->next_requests[0] == 1 &&
@@ -235,8 +275,22 @@ Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_worl
Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() { Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() {
Window fixture(orders()); Window fixture(orders());
const auto host_id = Void::Uuid::try_v4();
const auto rules = default_rules_manifest();
require(host_id.has_value() && rules.has_value());
SimulationRuntime host_runtime(WorldCheckpoint{make_first_colony(2), *host_id, 1, *rules}, {.ticking = false});
settlement::viewer::LanSession host_peer;
host_peer.host(0, true);
session->enter_guest(); session->enter_guest();
lan->join("127.0.0.1", "000000", 1); lan->join("127.0.0.1", host_peer.join_code(), host_peer.port());
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (lan->state() != LanState::GuestConnected) {
host_peer.poll_host(host_runtime);
if (auto incoming = lan->poll_guest()) session->receive_guest(std::move(incoming));
require(std::chrono::steady_clock::now() < deadline, "real legacy guest did not connect");
std::this_thread::yield();
}
world = session->world();
require(lan->is_guest() && session->guest()); require(lan->is_guest() && session->guest());
const auto before = session->runtime().latest(); const auto before = session->runtime().latest();
const auto menu = create_work_menu(); const auto menu = create_work_menu();
@@ -253,7 +307,8 @@ Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission()
} }
Test ProductionControlsTests::returning_resident_explains_wait_for_storage() { Test ProductionControlsTests::returning_resident_explains_wait_for_storage() {
auto initial = orders(1); auto initial = orders(0);
initial->queue_production({8, 8}, RecipeId::BuildCabin);
const auto storage = initial->add_storage({3, 3}, 5); const auto storage = initial->add_storage({3, 3}, 5);
initial->stock_storage(storage, ItemType::Plank, 3); initial->stock_storage(storage, ItemType::Plank, 3);
initial->stock_storage(storage, ItemType::StoneBlock, 2); initial->stock_storage(storage, ItemType::StoneBlock, 2);