// Exercise the real private Win32 controls and modal handlers in their own // executable, without adding test hooks to the shipping UI or wire protocol. #include "../app/viewer_win32.cpp" #include #include #include namespace production_controls { using namespace settlement; using Void::Testing::Test; using namespace std::chrono_literals; void require(bool condition, const char* message = "production controls invariant failed") { if (!condition) throw std::runtime_error(message); } constexpr UINT_PTR drive_timer = 904; struct MenuStep { UINT command; std::function before_select; }; std::vector steps; std::vector> observed_menus; HMENU active_menu = nullptr; std::string driver_error; unsigned timer_attempts = 0; void key(std::vector& input, WORD code) { INPUT down{}; down.type = INPUT_KEYBOARD; down.ki.wVk = code; input.push_back(down); down.ki.dwFlags = KEYEVENTF_KEYUP; input.push_back(down); } LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_INITMENUPOPUP) { active_menu = reinterpret_cast(wparam); std::vector labels; for (int index = 0; index < GetMenuItemCount(active_menu); ++index) { wchar_t label[512]{}; GetMenuStringW(active_menu, static_cast(index), label, 512, MF_BYPOSITION); labels.emplace_back(label); } observed_menus.push_back(std::move(labels)); } if (message == WM_TIMER && wparam == drive_timer) { if (++timer_attempts > 100) { 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); EndMenu(); return 0; } if (!active_menu || steps.empty()) return 0; const auto menu = std::exchange(active_menu, nullptr); auto step = std::move(steps.front()); steps.erase(steps.begin()); int target = -1; for (int index = 0; index < GetMenuItemCount(menu); ++index) { if (GetMenuItemID(menu, index) == step.command) { target = index; break; } } if (target < 0) { driver_error = "expected action absent from actual popup"; EndMenu(); return 0; } try { if (step.before_select) step.before_select(); } catch (const std::exception& error) { driver_error = error.what(); EndMenu(); return 0; } std::vector input; key(input, VK_HOME); for (int index = 0; index < target; ++index) { if ((GetMenuState(menu, static_cast(index), MF_BYPOSITION) & MF_SEPARATOR) == 0) key(input, VK_DOWN); } key(input, VK_RETURN); if (SendInput(static_cast(input.size()), input.data(), sizeof(INPUT)) != input.size()) { driver_error = "SendInput failed for actual popup"; EndMenu(); } return 0; } return window_proc(window, message, wparam, lparam); } struct Window { HWND handle = nullptr; std::filesystem::path user_data; std::wstring old_user_data; explicit Window(std::unique_ptr initial) { const auto uuid = Void::Uuid::try_v4(); require(uuid.has_value()); user_data = std::filesystem::temp_directory_path() / ("settlement-order-controls-" + uuid->to_string()); require(std::filesystem::create_directory(user_data)); wchar_t old[32768]{}; const auto size = GetEnvironmentVariableW(L"LOCALAPPDATA", old, 32768); old_user_data.assign(old, size < 32768 ? size : 0); require(SetEnvironmentVariableW(L"LOCALAPPDATA", user_data.c_str())); auto rules = default_rules_manifest(); require(rules.has_value()); session = std::make_unique( WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 2); world = session->world(); showing_title = true; has_session = true; lan = std::make_unique(); displayed_lan_state = LanState::Offline; placement_mode = PlacementMode::None; camera = {}; placement_message.clear(); steps.clear(); observed_menus.clear(); active_menu = nullptr; driver_error.clear(); timer_attempts = 0; INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; require(InitCommonControlsEx(&controls)); WNDCLASSW type{}; type.lpfnWndProc = test_window_proc; type.hInstance = GetModuleHandleW(nullptr); type.lpszClassName = L"SettlementProductionControlsTest"; type.hCursor = LoadCursorW(nullptr, IDC_ARROW); require(RegisterClassW(&type) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS); handle = CreateWindowExW(0, type.lpszClassName, L"Production controls test", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 32, 32, 1120, 752, nullptr, nullptr, type.hInstance, nullptr); require(handle != nullptr); show_title_screen(handle, false); file_dialog_active = true; // Freeze ticks while exercising UI receipt delivery. KillTimer(handle, timer_id); session->set_ticking(false); ShowWindow(handle, SW_SHOW); UpdateWindow(handle); SetForegroundWindow(handle); } ~Window() { if (handle) DestroyWindow(handle); session.reset(); world.reset(); file_dialog_active = false; MSG message{}; while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {} SetEnvironmentVariableW(L"LOCALAPPDATA", old_user_data.empty() ? nullptr : old_user_data.c_str()); std::error_code error; std::filesystem::remove_all(user_data, error); } void menu(std::vector actions, const std::function& open) { steps = std::move(actions); require(SetTimer(handle, drive_timer, 50, nullptr) != 0); open(); KillTimer(handle, drive_timer); require(driver_error.empty(), driver_error.c_str()); require(steps.empty(), "not all popup pages were reachable"); } void pump_until(const std::function& done) { const auto deadline = std::chrono::steady_clock::now() + 5s; while (!done()) { SendMessageW(handle, WM_TIMER, timer_id, 0); require(std::chrono::steady_clock::now() < deadline, "UI receipt/replacement did not finish"); std::this_thread::yield(); } } void activate_tool() { menu({{manage_orders_id, {}}}, [&] { SendMessageW(work_list_button, BM_CLICK, 0, 0); }); // The normal work menu posts WM_COMMAND after closing its popup. MSG message{}; while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessageW(&message); } 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((client.right / 2.0 + (cell.x - cell.y) * tile_width / 2.0) * scale + offset.x), static_cast((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 orders(unsigned count = 2) { auto result = std::make_unique(43, 32, 32, 1, ExecutionMode::SerialReference); for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::SawPlank); return result; } struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests : Void::Testing::Suite { [[= 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 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 returning_resident_explains_wait_for_storage(); }; Test ProductionControlsTests::real_work_menu_selects_exact_id_and_waits_for_receipt() { Window fixture(orders()); const auto first = world->production_orders().front().id; const auto second = world->production_orders().back().id; fixture.activate_tool(); fixture.menu({{2, {}}}, [&] { fixture.click_cell({8, 8}); }); require(world->find_production(second) && world->find_production(first) && placement_message.find(L"ожидает подтверждения") != std::wstring::npos, "UI forged success before a committed receipt"); 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, "actual popup lost the order name, durable id or user-facing position"); fixture.pump_until([&] { return !world->find_production(second); }); require(world->find_production(first) && placement_message.find(L"Заказ отменён") != std::wstring::npos && session->runtime().latest()->next_requests[0] == 2 && world->next_command_sequence(1) == 1); } Test ProductionControlsTests::every_order_remains_accessible_across_popup_pages() { Window fixture(orders(35)); const auto last = world->production_orders().back().id; fixture.activate_tool(); fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { fixture.click_cell({8, 8}); }); fixture.pump_until([&] { return !world->find_production(last); }); 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"); } 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() { for (const bool complete_replacement : {false, true}) { Window fixture(orders()); const auto opening = session->runtime().latest(); fixture.activate_tool(); fixture.menu({{1, [&] { session->new_colony(); if (complete_replacement) { const auto deadline = std::chrono::steady_clock::now() + 5s; while (session->changing_world()) { static_cast(session->poll()); require(std::chrono::steady_clock::now() < deadline); std::this_thread::yield(); } world = session->world(); } }}}, [&] { fixture.click_cell({8, 8}); }); fixture.pump_until([&] { return !session->changing_world(); }); const auto current = session->runtime().latest(); require(current->identity != opening->identity && current->next_requests[0] == 1 && current->world->next_command_sequence(1) == 1, "stale popup enqueued a production command into the new session"); require(opening->world->production_orders().size() == 2, "modal selection invalidated pinned snapshot"); } } Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() { 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(); 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()); const auto before = session->runtime().latest(); const auto menu = create_work_menu(); require(menu != nullptr && GetMenuState(menu, manage_orders_id, MF_BYCOMMAND) == static_cast(-1), "legacy guest saw the modern management action"); DestroyMenu(menu); SendMessageW(fixture.handle, WM_COMMAND, manage_orders_id, 0); require(placement_mode != PlacementMode::ManageOrders && !can_manage_orders()); placement_mode = PlacementMode::ManageOrders; edit_at_cell(fixture.handle, {8, 8}); require(!enqueue_command(CancelProductionPayload{1}) && !enqueue_command(ResumeProductionPayload{1}) && session->runtime().latest() == before && guest_intents.empty(), "legacy guest admitted a modern order payload"); } Test ProductionControlsTests::returning_resident_explains_wait_for_storage() { auto initial = orders(0); initial->queue_production({8, 8}, RecipeId::BuildCabin); const auto storage = initial->add_storage({3, 3}, 5); initial->stock_storage(storage, ItemType::Plank, 3); initial->stock_storage(storage, ItemType::StoneBlock, 2); const auto resident = initial->spawn_agent({1, 3}); for (int tick = 0; tick < 100 && initial->agents().front().inventory.empty(); ++tick) initial->step(); require(!initial->agents().front().inventory.empty()); initial->stock_storage(storage, ItemType::Wood, 5); require(initial->cancel_production(initial->production_orders().front().id) == CommandStatus::Accepted); for (int tick = 0; tick < 5; ++tick) initial->step(); Window fixture(std::move(initial)); selected_resident = resident; const auto details = resident_details(); require(details.find(L"Возвращает материалы") != std::wstring::npos && (details.find(L"нет доступного склада с местом") != std::wstring::npos || details.find(L"на складе недостаточно места") != std::wstring::npos) && details.find(L"доски ×3") != std::wstring::npos && details.find(L"блоки ×2") != std::wstring::npos, "real returning resident did not expose actual cargo and waiting reason"); } } // namespace production_controls