diff options
| author | andretuta <andreviniciusmerlia@gmail.com> | 2026-11-24 10:33:06 -0300 |
|---|---|---|
| committer | andretuta <andreviniciusmerlia@gmail.com> | 2026-11-24 10:33:06 -0300 |
| commit | b358d9062d10e63fbd90bfbb08c4bac8b9ef0b30 (patch) | |
| tree | ccd04386504ef35462fe27456e7adf3d28fc615c /runtime | |
| parent | 21625bca8c675c62f9dbffc318ce6a59d57faf31 (diff) | |
lifecycle: suspend callbacks on window close and fit the title window (split from #401)
RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification under
api-ms-win-core-psm-appnotify-l1-1-0/-l1-1-1 and kernelbase.dll, and CreateWindowExW/A under
user32.dll and ext-ms-win-rtcore-ntuser-window-l1-1-0/-l1-1-1, plus CreateWindowExA under
ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0, the set the title's import table names. The title's
first top-level window is fitted to the work area and hooked: SC_CLOSE runs the suspend callbacks
(quiesced TRUE) and ends the run through the title's ExitProcess, with a 1 s deadline.
Split from #401 (a02134a9c), as the maintainer asked for one topic per pull request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/CMakeLists.txt | 16 | ||||
| -rw-r--r-- | runtime/shims/lifecycle.cpp | 254 | ||||
| -rw-r--r-- | runtime/shims/lifecycle.h | 21 | ||||
| -rw-r--r-- | runtime/test/lifecycle_test.cpp | 181 |
4 files changed, 472 insertions, 0 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40..65205113b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -125,6 +125,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 125 | shims/xgameruntime_offline.cpp | 125 | shims/xgameruntime_offline.cpp |
| 126 | shims/library_loader.cpp | 126 | shims/library_loader.cpp |
| 127 | shims/process.cpp | 127 | shims/process.cpp |
| 128 | shims/lifecycle.cpp | ||
| 128 | shims/com_shim.cpp | 129 | shims/com_shim.cpp |
| 129 | shims/bcrypt_rng.cpp | 130 | shims/bcrypt_rng.cpp |
| 130 | shims/xapu_chad.cpp | 131 | shims/xapu_chad.cpp |
| @@ -293,6 +294,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 293 | target_link_options(process_cmdline_test PRIVATE /OPT:NOREF) | 294 | target_link_options(process_cmdline_test PRIVATE /OPT:NOREF) |
| 294 | target_link_libraries(process_cmdline_test PRIVATE shell32) | 295 | target_link_libraries(process_cmdline_test PRIVATE shell32) |
| 295 | 296 | ||
| 297 | # Console lifecycle shim: RegisterAppStateChangeNotification, oversized window fitting, and subclass forwarding. | ||
| 298 | add_executable(lifecycle_test | ||
| 299 | test/lifecycle_test.cpp | ||
| 300 | shims/lifecycle.cpp | ||
| 301 | shims/registry.cpp | ||
| 302 | ) | ||
| 303 | target_include_directories(lifecycle_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) | ||
| 304 | target_compile_definitions(lifecycle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 305 | target_compile_options(lifecycle_test PRIVATE /W4 /permissive- /utf-8) | ||
| 306 | target_link_options(lifecycle_test PRIVATE /OPT:NOREF) | ||
| 307 | target_link_libraries(lifecycle_test PRIVATE user32) | ||
| 308 | |||
| 296 | # Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders. | 309 | # Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders. |
| 297 | add_executable(file_system_test | 310 | add_executable(file_system_test |
| 298 | test/file_system_test.cpp | 311 | test/file_system_test.cpp |
| @@ -1172,6 +1185,9 @@ if(BUILD_TESTING) | |||
| 1172 | if(WIN32 AND TARGET process_cmdline_test) | 1185 | if(WIN32 AND TARGET process_cmdline_test) |
| 1173 | add_test(NAME process_cmdline COMMAND process_cmdline_test) | 1186 | add_test(NAME process_cmdline COMMAND process_cmdline_test) |
| 1174 | endif() | 1187 | endif() |
| 1188 | if(WIN32 AND TARGET lifecycle_test) | ||
| 1189 | add_test(NAME lifecycle COMMAND lifecycle_test) | ||
| 1190 | endif() | ||
| 1175 | if(WIN32 AND TARGET file_system_test) | 1191 | if(WIN32 AND TARGET file_system_test) |
| 1176 | add_test(NAME file_system COMMAND file_system_test) | 1192 | add_test(NAME file_system COMMAND file_system_test) |
| 1177 | endif() | 1193 | endif() |
diff --git a/runtime/shims/lifecycle.cpp b/runtime/shims/lifecycle.cpp new file mode 100644 index 000000000..0e28be82e --- /dev/null +++ b/runtime/shims/lifecycle.cpp | |||
| @@ -0,0 +1,254 @@ | |||
| 1 | // lifecycle: console application lifecycle shims for mapped titles. | ||
| 2 | // | ||
| 3 | // Console titles never receive a normal desktop WM_CLOSE; quitting suspends the title (running its | ||
| 4 | // RegisterAppStateChangeNotification callbacks with quiesced = TRUE, giving it ~1 s to flush saves) and then ends the | ||
| 5 | // process. Additionally, console titles often size their top-level window to a 4K render target (3840x2160), which | ||
| 6 | // overflows smaller desktop work areas. | ||
| 7 | // | ||
| 8 | // This shim provides: | ||
| 9 | // - RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification on api-ms-win-core-psm-appnotify-* | ||
| 10 | // and kernelbase.dll; | ||
| 11 | // - CreateWindowExW / CreateWindowExA on user32.dll and ext-ms-win-rtcore-ntuser-window-* (CreateWindowExA also on | ||
| 12 | // the -ansi- set), fitting the title's first top-level window into the primary monitor work area and | ||
| 13 | // subclassing it so SC_CLOSE runs registered suspend callbacks before the run ends. | ||
| 14 | #ifndef WIN32_LEAN_AND_MEAN | ||
| 15 | #define WIN32_LEAN_AND_MEAN | ||
| 16 | #endif | ||
| 17 | #ifndef NOMINMAX | ||
| 18 | #define NOMINMAX | ||
| 19 | #endif | ||
| 20 | |||
| 21 | #include <windows.h> | ||
| 22 | |||
| 23 | #include <algorithm> | ||
| 24 | #include <atomic> | ||
| 25 | #include <chrono> | ||
| 26 | #include <cstdint> | ||
| 27 | #include <cstdio> | ||
| 28 | #include <mutex> | ||
| 29 | #include <thread> | ||
| 30 | #include <utility> | ||
| 31 | #include <vector> | ||
| 32 | |||
| 33 | #include "lifecycle.h" | ||
| 34 | #include "shims.h" | ||
| 35 | |||
| 36 | namespace rt::lifecycle { | ||
| 37 | namespace { | ||
| 38 | |||
| 39 | using AppStateRoutine = void(WINAPI*)(BOOLEAN quiesced, PVOID context); | ||
| 40 | |||
| 41 | struct Registration { | ||
| 42 | std::uintptr_t id; | ||
| 43 | AppStateRoutine routine; | ||
| 44 | void* context; | ||
| 45 | }; | ||
| 46 | |||
| 47 | constexpr wchar_t kTitleProcProp[] = L"leonida.title.wndproc"; | ||
| 48 | constexpr auto kSuspendDeadline = std::chrono::seconds(1); | ||
| 49 | |||
| 50 | // Recursive so a callback can unregister from inside run_suspend_callbacks() on the same thread. | ||
| 51 | std::recursive_mutex& reg_mutex() { | ||
| 52 | // Intentionally immortal so shutdown/WM_SYSCOMMAND cannot race static destruction. | ||
| 53 | static auto* m = new std::recursive_mutex; | ||
| 54 | return *m; | ||
| 55 | } | ||
| 56 | |||
| 57 | std::vector<Registration>& reg_list() { | ||
| 58 | static auto* list = new std::vector<Registration>; | ||
| 59 | return *list; | ||
| 60 | } | ||
| 61 | |||
| 62 | std::atomic<std::uintptr_t> g_next_reg_id{1}; | ||
| 63 | std::atomic<bool> g_ending{false}; | ||
| 64 | std::atomic<HWND> g_title_window{nullptr}; | ||
| 65 | |||
| 66 | // Ends the run through the title's own ExitProcess (process.cpp's game_exit_process -> end_run, which lets the host | ||
| 67 | // finish its cleanup), not TerminateProcess. Falls back to ExitProcess if the shim table has no binding. | ||
| 68 | [[noreturn]] void end_title_run() { | ||
| 69 | using ExitProcessFn = void(__stdcall*)(UINT); | ||
| 70 | if (auto* exit_process = reinterpret_cast<ExitProcessFn>(rt::shims::find("kernel32.dll", "ExitProcess"))) { | ||
| 71 | exit_process(0); | ||
| 72 | } | ||
| 73 | ExitProcess(0); | ||
| 74 | } | ||
| 75 | |||
| 76 | // Runs every registration still in the list, with the registration lock held for the whole loop: an Unregister on | ||
| 77 | // another thread waits for the callback in flight, and one from inside a callback re-enters the recursive lock and | ||
| 78 | // stops the later calls of its id. Ids come from a snapshot and are looked up again, so an entry removed by an | ||
| 79 | // earlier callback is skipped. | ||
| 80 | // ponytail: a callback that blocks on another thread which is itself in Register/Unregister stalls until the 1 s | ||
| 81 | // deadline ends the run. | ||
| 82 | void run_suspend_callbacks() { | ||
| 83 | std::lock_guard lock(reg_mutex()); | ||
| 84 | std::vector<std::uintptr_t> ids; | ||
| 85 | for (const auto& r : reg_list()) ids.push_back(r.id); | ||
| 86 | for (const auto id : ids) { | ||
| 87 | AppStateRoutine routine = nullptr; | ||
| 88 | void* context = nullptr; | ||
| 89 | for (const auto& r : reg_list()) { | ||
| 90 | if (r.id == id) { | ||
| 91 | routine = r.routine; | ||
| 92 | context = r.context; | ||
| 93 | break; | ||
| 94 | } | ||
| 95 | } | ||
| 96 | if (routine) routine(TRUE, context); | ||
| 97 | } | ||
| 98 | } | ||
| 99 | |||
| 100 | void trigger_suspend_and_exit() { | ||
| 101 | if (g_ending.exchange(true, std::memory_order_seq_cst)) return; | ||
| 102 | std::fprintf(stderr, "[rt] lifecycle: window closed; running %zu suspend routine(s)\n", | ||
| 103 | registered_notification_count()); | ||
| 104 | |||
| 105 | // Run suspend callbacks off the UI thread so callbacks that synchronize with the window thread do not deadlock. | ||
| 106 | std::thread([]() { | ||
| 107 | run_suspend_callbacks(); | ||
| 108 | std::fprintf(stderr, "[rt] lifecycle: title suspended; exiting\n"); | ||
| 109 | end_title_run(); | ||
| 110 | }).detach(); | ||
| 111 | |||
| 112 | std::thread([]() { | ||
| 113 | std::this_thread::sleep_for(kSuspendDeadline); | ||
| 114 | std::fprintf(stderr, "[rt] lifecycle: suspend deadline elapsed; exiting\n"); | ||
| 115 | end_title_run(); | ||
| 116 | }).detach(); | ||
| 117 | } | ||
| 118 | |||
| 119 | LRESULT CALLBACK lifecycle_wnd_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { | ||
| 120 | if (message == WM_SYSCOMMAND && (wparam & 0xFFF0u) == SC_CLOSE) { | ||
| 121 | trigger_suspend_and_exit(); | ||
| 122 | return 0; | ||
| 123 | } | ||
| 124 | const HANDLE prop = GetPropW(hwnd, kTitleProcProp); | ||
| 125 | if (message == WM_NCDESTROY) { | ||
| 126 | RemovePropW(hwnd, kTitleProcProp); | ||
| 127 | HWND expected = hwnd; | ||
| 128 | g_title_window.compare_exchange_strong(expected, nullptr); // a later main window may be claimed | ||
| 129 | } | ||
| 130 | auto original = reinterpret_cast<WNDPROC>(prop); | ||
| 131 | if (!original) return DefWindowProcW(hwnd, message, wparam, lparam); | ||
| 132 | return CallWindowProcW(original, hwnd, message, wparam, lparam); | ||
| 133 | } | ||
| 134 | |||
| 135 | void install_window_hook(HWND hwnd) { | ||
| 136 | if (!hwnd) return; | ||
| 137 | const LONG_PTR prev = GetWindowLongPtrW(hwnd, GWLP_WNDPROC); | ||
| 138 | if (!prev || reinterpret_cast<WNDPROC>(prev) == &lifecycle_wnd_proc) return; | ||
| 139 | SetPropW(hwnd, kTitleProcProp, reinterpret_cast<HANDLE>(prev)); | ||
| 140 | SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&lifecycle_wnd_proc)); | ||
| 141 | } | ||
| 142 | |||
| 143 | // Before CreateWindowEx: a candidate is a top-level, non-child, non-tool window. Returns whether it is one, and fits | ||
| 144 | // it only when it is the first candidate (no title window claimed yet). | ||
| 145 | bool prepare_title_window(HWND parent, DWORD style, DWORD ex_style, int& x, int& y, int& width, int& height) { | ||
| 146 | if (parent != nullptr || (style & WS_CHILD) || (ex_style & WS_EX_TOOLWINDOW)) return false; | ||
| 147 | if (g_title_window.load() != nullptr) return true; | ||
| 148 | RECT area{}; | ||
| 149 | if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &area, 0)) return true; | ||
| 150 | const auto [fitted_w, fitted_h] = fit_window_to_area(area, width, height); | ||
| 151 | if (fitted_w == width && fitted_h == height) return true; | ||
| 152 | std::fprintf(stderr, "[rt] lifecycle: fitted oversized title window %dx%d -> %dx%d\n", width, height, fitted_w, | ||
| 153 | fitted_h); | ||
| 154 | width = fitted_w; | ||
| 155 | height = fitted_h; | ||
| 156 | x = area.left + ((area.right - area.left) - width) / 2; | ||
| 157 | y = area.top + ((area.bottom - area.top) - height) / 2; | ||
| 158 | return true; | ||
| 159 | } | ||
| 160 | |||
| 161 | // After CreateWindowEx: the first candidate to succeed claims the title window and gets the SC_CLOSE hook. | ||
| 162 | void adopt_title_window(HWND hwnd, bool candidate) { | ||
| 163 | if (!hwnd || !candidate) return; | ||
| 164 | HWND expected = nullptr; | ||
| 165 | if (g_title_window.compare_exchange_strong(expected, hwnd)) install_window_hook(hwnd); | ||
| 166 | } | ||
| 167 | |||
| 168 | ULONG WINAPI register_app_state_change(AppStateRoutine routine, PVOID context, PVOID* registration) { | ||
| 169 | if (!routine || !registration) return ERROR_INVALID_PARAMETER; | ||
| 170 | const std::uintptr_t id = g_next_reg_id.fetch_add(1, std::memory_order_relaxed); | ||
| 171 | { | ||
| 172 | std::lock_guard lock(reg_mutex()); | ||
| 173 | reg_list().push_back({id, routine, context}); | ||
| 174 | } | ||
| 175 | *registration = reinterpret_cast<PVOID>(id); | ||
| 176 | return ERROR_SUCCESS; | ||
| 177 | } | ||
| 178 | |||
| 179 | void WINAPI unregister_app_state_change(PVOID registration) { | ||
| 180 | const auto id = reinterpret_cast<std::uintptr_t>(registration); | ||
| 181 | std::lock_guard lock(reg_mutex()); | ||
| 182 | auto& list = reg_list(); | ||
| 183 | list.erase(std::remove_if(list.begin(), list.end(), [id](const Registration& r) { return r.id == id; }), | ||
| 184 | list.end()); | ||
| 185 | } | ||
| 186 | |||
| 187 | HWND WINAPI create_window_ex_w_shim(DWORD ex_style, LPCWSTR class_name, LPCWSTR window_name, DWORD style, int x, int y, | ||
| 188 | int width, int height, HWND parent, HMENU menu, HINSTANCE instance, LPVOID param) { | ||
| 189 | const bool candidate = prepare_title_window(parent, style, ex_style, x, y, width, height); | ||
| 190 | const HWND hwnd = | ||
| 191 | ::CreateWindowExW(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, instance, param); | ||
| 192 | adopt_title_window(hwnd, candidate); | ||
| 193 | return hwnd; | ||
| 194 | } | ||
| 195 | |||
| 196 | HWND WINAPI create_window_ex_a_shim(DWORD ex_style, LPCSTR class_name, LPCSTR window_name, DWORD style, int x, int y, | ||
| 197 | int width, int height, HWND parent, HMENU menu, HINSTANCE instance, LPVOID param) { | ||
| 198 | const bool candidate = prepare_title_window(parent, style, ex_style, x, y, width, height); | ||
| 199 | const HWND hwnd = | ||
| 200 | ::CreateWindowExA(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, instance, param); | ||
| 201 | adopt_title_window(hwnd, candidate); | ||
| 202 | return hwnd; | ||
| 203 | } | ||
| 204 | |||
| 205 | } // namespace | ||
| 206 | |||
| 207 | std::pair<int, int> fit_window_to_area(const RECT& area, int width, int height) { | ||
| 208 | const int area_w = area.right - area.left; | ||
| 209 | const int area_h = area.bottom - area.top; | ||
| 210 | if (width <= 0 || height <= 0 || area_w <= 0 || area_h <= 0 || (width <= area_w && height <= area_h)) { | ||
| 211 | return {width, height}; | ||
| 212 | } | ||
| 213 | const double scale = | ||
| 214 | std::min(static_cast<double>(area_w) / static_cast<double>(width), | ||
| 215 | static_cast<double>(area_h) / static_cast<double>(height)); | ||
| 216 | return {static_cast<int>(static_cast<double>(width) * scale), | ||
| 217 | static_cast<int>(static_cast<double>(height) * scale)}; | ||
| 218 | } | ||
| 219 | |||
| 220 | std::size_t registered_notification_count() { | ||
| 221 | std::lock_guard lock(reg_mutex()); | ||
| 222 | return reg_list().size(); | ||
| 223 | } | ||
| 224 | |||
| 225 | void invoke_suspend_callbacks_for_test() { | ||
| 226 | run_suspend_callbacks(); | ||
| 227 | } | ||
| 228 | |||
| 229 | } // namespace rt::lifecycle | ||
| 230 | |||
| 231 | namespace { | ||
| 232 | using namespace rt::lifecycle; | ||
| 233 | |||
| 234 | #define APP_NOTIFY_API(dll) \ | ||
| 235 | {dll, "RegisterAppStateChangeNotification", reinterpret_cast<void*>(®ister_app_state_change)}, \ | ||
| 236 | {dll, "UnregisterAppStateChangeNotification", reinterpret_cast<void*>(&unregister_app_state_change)} | ||
| 237 | |||
| 238 | #define WINDOW_API(dll) \ | ||
| 239 | {dll, "CreateWindowExW", reinterpret_cast<void*>(&create_window_ex_w_shim)}, \ | ||
| 240 | {dll, "CreateWindowExA", reinterpret_cast<void*>(&create_window_ex_a_shim)} | ||
| 241 | |||
| 242 | } // namespace | ||
| 243 | |||
| 244 | SHIM_TABLE(lifecycle, | ||
| 245 | APP_NOTIFY_API("api-ms-win-core-psm-appnotify-l1-1-0.dll"), | ||
| 246 | APP_NOTIFY_API("api-ms-win-core-psm-appnotify-l1-1-1.dll"), | ||
| 247 | APP_NOTIFY_API("kernelbase.dll"), | ||
| 248 | WINDOW_API("user32.dll"), | ||
| 249 | WINDOW_API("ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"), | ||
| 250 | WINDOW_API("ext-ms-win-rtcore-ntuser-window-l1-1-1.dll"), | ||
| 251 | // The title's import table names CreateWindowExA from the ANSI set. | ||
| 252 | {"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA", | ||
| 253 | reinterpret_cast<void*>(&create_window_ex_a_shim)}, | ||
| 254 | ); | ||
diff --git a/runtime/shims/lifecycle.h b/runtime/shims/lifecycle.h new file mode 100644 index 000000000..a3d775738 --- /dev/null +++ b/runtime/shims/lifecycle.h | |||
| @@ -0,0 +1,21 @@ | |||
| 1 | // App lifecycle notifications (RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification) and | ||
| 2 | // oversized top-level console window fitting + suspend-on-close hook (CreateWindowExA/W). | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include <windows.h> | ||
| 6 | |||
| 7 | #include <cstddef> | ||
| 8 | #include <utility> | ||
| 9 | |||
| 10 | namespace rt::lifecycle { | ||
| 11 | |||
| 12 | // Scales down (width, height) proportionally to fit inside `area`, leaving fitting sizes and CW_USEDEFAULT / <= 0 | ||
| 13 | // unchanged. | ||
| 14 | std::pair<int, int> fit_window_to_area(const RECT& area, int width, int height); | ||
| 15 | |||
| 16 | // For tests: number of currently registered app-state change callbacks, and synchronous suspend invocation | ||
| 17 | // (quiesced = TRUE) without terminating the process. | ||
| 18 | std::size_t registered_notification_count(); | ||
| 19 | void invoke_suspend_callbacks_for_test(); | ||
| 20 | |||
| 21 | } // namespace rt::lifecycle | ||
diff --git a/runtime/test/lifecycle_test.cpp b/runtime/test/lifecycle_test.cpp new file mode 100644 index 000000000..8f1f51dd9 --- /dev/null +++ b/runtime/test/lifecycle_test.cpp | |||
| @@ -0,0 +1,181 @@ | |||
| 1 | // Checks the console lifecycle shim (runtime/shims/lifecycle.cpp): app-state change registrations, suspend | ||
| 2 | // callback delivery, oversized window fitting, and window subclass forwarding. | ||
| 3 | #ifndef WIN32_LEAN_AND_MEAN | ||
| 4 | #define WIN32_LEAN_AND_MEAN | ||
| 5 | #endif | ||
| 6 | #ifndef NOMINMAX | ||
| 7 | #define NOMINMAX | ||
| 8 | #endif | ||
| 9 | |||
| 10 | #include <windows.h> | ||
| 11 | |||
| 12 | #include <cstdio> | ||
| 13 | #include <cstring> | ||
| 14 | |||
| 15 | #include "lifecycle.h" | ||
| 16 | #include "shims.h" | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | int g_checks = 0; | ||
| 21 | int g_failures = 0; | ||
| 22 | |||
| 23 | void check(bool condition, const char* what) { | ||
| 24 | ++g_checks; | ||
| 25 | std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); | ||
| 26 | if (!condition) ++g_failures; | ||
| 27 | } | ||
| 28 | |||
| 29 | struct SuspendProbe { | ||
| 30 | int calls = 0; | ||
| 31 | BOOLEAN last_quiesced = FALSE; | ||
| 32 | }; | ||
| 33 | |||
| 34 | void WINAPI on_app_state(BOOLEAN quiesced, PVOID context) { | ||
| 35 | auto* probe = static_cast<SuspendProbe*>(context); | ||
| 36 | if (probe) { | ||
| 37 | ++probe->calls; | ||
| 38 | probe->last_quiesced = quiesced; | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | using UnregFn = void(WINAPI*)(PVOID); | ||
| 43 | UnregFn g_unreg = nullptr; | ||
| 44 | |||
| 45 | // Context for a callback that unregisters `target` (another registration, or its own handle) when it runs. | ||
| 46 | struct UnregProbe { | ||
| 47 | int calls = 0; | ||
| 48 | PVOID target = nullptr; | ||
| 49 | }; | ||
| 50 | |||
| 51 | void WINAPI on_app_state_unregister(BOOLEAN, PVOID context) { | ||
| 52 | auto* probe = static_cast<UnregProbe*>(context); | ||
| 53 | ++probe->calls; | ||
| 54 | if (probe->target) g_unreg(probe->target); | ||
| 55 | } | ||
| 56 | |||
| 57 | } // namespace | ||
| 58 | |||
| 59 | int main() { | ||
| 60 | using RegFn = ULONG(WINAPI*)(void(WINAPI*)(BOOLEAN, PVOID), PVOID, PVOID*); | ||
| 61 | using CreateExWFn = HWND(WINAPI*)(DWORD, LPCWSTR, LPCWSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, | ||
| 62 | LPVOID); | ||
| 63 | |||
| 64 | const auto reg = reinterpret_cast<RegFn>( | ||
| 65 | rt::shims::find("api-ms-win-core-psm-appnotify-l1-1-0.dll", "RegisterAppStateChangeNotification")); | ||
| 66 | const auto unreg = reinterpret_cast<UnregFn>( | ||
| 67 | rt::shims::find("api-ms-win-core-psm-appnotify-l1-1-0.dll", "UnregisterAppStateChangeNotification")); | ||
| 68 | const auto create_w = reinterpret_cast<CreateExWFn>(rt::shims::find("user32.dll", "CreateWindowExW")); | ||
| 69 | const auto create_w_ext = | ||
| 70 | reinterpret_cast<CreateExWFn>(rt::shims::find("ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "CreateWindowExW")); | ||
| 71 | |||
| 72 | check(reg != nullptr && unreg != nullptr, "Register/UnregisterAppStateChangeNotification resolve"); | ||
| 73 | check(create_w != nullptr && create_w == create_w_ext, | ||
| 74 | "CreateWindowExW resolves through user32 and ext-ms-win-rtcore-ntuser-window"); | ||
| 75 | check(!rt::shims::owns_dll("user32.dll"), "user32.dll stays partially overridden"); | ||
| 76 | // The title imports CreateWindowExA from the ANSI window set, not from user32.dll. | ||
| 77 | const void* create_a = rt::shims::find("user32.dll", "CreateWindowExA"); | ||
| 78 | check(create_a != nullptr && | ||
| 79 | rt::shims::find("ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA") == create_a, | ||
| 80 | "CreateWindowExA resolves through ext-ms-win-rtcore-ntuser-window-ansi to the same shim"); | ||
| 81 | if (!reg || !unreg || !create_w) return 1; | ||
| 82 | g_unreg = unreg; | ||
| 83 | |||
| 84 | // 1. Parameter validation and registration / unregistration / suspend dispatch. | ||
| 85 | PVOID handle_a = nullptr, handle_b = nullptr; | ||
| 86 | check(reg(nullptr, nullptr, &handle_a) == ERROR_INVALID_PARAMETER, "null routine returns ERROR_INVALID_PARAMETER"); | ||
| 87 | check(reg(&on_app_state, nullptr, nullptr) == ERROR_INVALID_PARAMETER, | ||
| 88 | "null registration out pointer returns ERROR_INVALID_PARAMETER"); | ||
| 89 | |||
| 90 | SuspendProbe probe_a{}, probe_b{}; | ||
| 91 | check(reg(&on_app_state, &probe_a, &handle_a) == ERROR_SUCCESS && handle_a != nullptr, "register callback A"); | ||
| 92 | check(reg(&on_app_state, &probe_b, &handle_b) == ERROR_SUCCESS && handle_b != nullptr && handle_b != handle_a, | ||
| 93 | "register callback B with distinct handle"); | ||
| 94 | check(rt::lifecycle::registered_notification_count() == 2, "two registrations active"); | ||
| 95 | |||
| 96 | unreg(handle_a); | ||
| 97 | check(rt::lifecycle::registered_notification_count() == 1, "unregister removes callback A"); | ||
| 98 | |||
| 99 | rt::lifecycle::invoke_suspend_callbacks_for_test(); | ||
| 100 | check(probe_a.calls == 0 && probe_b.calls == 1 && probe_b.last_quiesced == TRUE, | ||
| 101 | "suspend dispatch invokes only remaining callback with quiesced=TRUE"); | ||
| 102 | unreg(handle_b); | ||
| 103 | check(rt::lifecycle::registered_notification_count() == 0, "all registrations removed"); | ||
| 104 | |||
| 105 | // 1b. A callback that unregisters a later registration: the later one is skipped during the same dispatch. | ||
| 106 | PVOID handle_later = nullptr, handle_first = nullptr; | ||
| 107 | SuspendProbe later_probe{}; | ||
| 108 | UnregProbe first_probe{}; | ||
| 109 | check(reg(&on_app_state_unregister, &first_probe, &handle_first) == ERROR_SUCCESS, | ||
| 110 | "register unregistering callback"); | ||
| 111 | check(reg(&on_app_state, &later_probe, &handle_later) == ERROR_SUCCESS, "register later callback"); | ||
| 112 | first_probe.target = handle_later; | ||
| 113 | rt::lifecycle::invoke_suspend_callbacks_for_test(); | ||
| 114 | check(first_probe.calls == 1 && later_probe.calls == 0, | ||
| 115 | "unregistered later callback does not run in the same dispatch"); | ||
| 116 | check(rt::lifecycle::registered_notification_count() == 1, "later registration is gone, the first remains"); | ||
| 117 | unreg(handle_first); | ||
| 118 | check(rt::lifecycle::registered_notification_count() == 0, "dispatch test registrations removed"); | ||
| 119 | |||
| 120 | // 1c. A callback that unregisters itself: no deadlock, it runs once, and it is gone afterwards. | ||
| 121 | PVOID handle_self = nullptr; | ||
| 122 | UnregProbe self_probe{}; | ||
| 123 | check(reg(&on_app_state_unregister, &self_probe, &handle_self) == ERROR_SUCCESS, | ||
| 124 | "register self-unregistering callback"); | ||
| 125 | self_probe.target = handle_self; | ||
| 126 | rt::lifecycle::invoke_suspend_callbacks_for_test(); | ||
| 127 | check(self_probe.calls == 1 && rt::lifecycle::registered_notification_count() == 0, | ||
| 128 | "self-unregistering callback runs once and is removed without deadlock"); | ||
| 129 | rt::lifecycle::invoke_suspend_callbacks_for_test(); | ||
| 130 | check(self_probe.calls == 1, "removed self-unregistering callback is not called again"); | ||
| 131 | |||
| 132 | // 2. Oversized window scaling math. | ||
| 133 | const RECT area{0, 0, 1920, 1040}; | ||
| 134 | const auto fitted_4k = rt::lifecycle::fit_window_to_area(area, 3840, 2160); | ||
| 135 | check(fitted_4k.first == 1848 && fitted_4k.second == 1040, | ||
| 136 | "3840x2160 scales proportionally to 1848x1040 inside 1920x1040 work area"); | ||
| 137 | const auto fitted_720 = rt::lifecycle::fit_window_to_area(area, 1280, 720); | ||
| 138 | check(fitted_720.first == 1280 && fitted_720.second == 720, "1280x720 stays unchanged"); | ||
| 139 | const auto fitted_def = rt::lifecycle::fit_window_to_area(area, CW_USEDEFAULT, 0); | ||
| 140 | check(fitted_def.first == CW_USEDEFAULT && fitted_def.second == 0, "CW_USEDEFAULT stays unchanged"); | ||
| 141 | |||
| 142 | // 3. Subclassed window still forwards normal messages to its original window procedure. | ||
| 143 | const HWND hwnd = create_w(0, L"STATIC", L"before", 0, 0, 0, 16, 16, nullptr, nullptr, nullptr, nullptr); | ||
| 144 | check(hwnd != nullptr, "CreateWindowExW shim creates a live window"); | ||
| 145 | if (hwnd) { | ||
| 146 | SetWindowTextW(hwnd, L"after"); | ||
| 147 | wchar_t buf[16] = {}; | ||
| 148 | const int n = GetWindowTextW(hwnd, buf, 16); | ||
| 149 | check(n == 5 && std::wcscmp(buf, L"after") == 0, "subclassed window forwards WM_SETTEXT/WM_GETTEXT"); | ||
| 150 | check(GetPropW(hwnd, L"leonida.title.wndproc") != nullptr, "original WNDPROC property installed"); | ||
| 151 | DestroyWindow(hwnd); | ||
| 152 | } | ||
| 153 | |||
| 154 | // 4. Only the title's first top-level window is hooked; a window is released when it is destroyed. Hidden windows | ||
| 155 | // only: no SC_CLOSE is posted. | ||
| 156 | const wchar_t* kHookProp = L"leonida.title.wndproc"; | ||
| 157 | WNDCLASSEXW wc{}; | ||
| 158 | wc.cbSize = sizeof(wc); | ||
| 159 | wc.lpfnWndProc = DefWindowProcW; | ||
| 160 | wc.hInstance = GetModuleHandleW(nullptr); | ||
| 161 | wc.lpszClassName = L"LeonidaLifecycleTest"; | ||
| 162 | RegisterClassExW(&wc); | ||
| 163 | const DWORD kMain = WS_OVERLAPPEDWINDOW; | ||
| 164 | const wchar_t* kClass = L"LeonidaLifecycleTest"; | ||
| 165 | HWND main_win = create_w(0, kClass, L"main", kMain, 0, 0, 64, 64, nullptr, nullptr, nullptr, nullptr); | ||
| 166 | check(main_win && GetPropW(main_win, kHookProp) != nullptr, "first parentless window is the hooked title window"); | ||
| 167 | HWND second = create_w(0, kClass, L"second", kMain, 0, 0, 64, 64, nullptr, nullptr, nullptr, nullptr); | ||
| 168 | check(second && GetPropW(second, kHookProp) == nullptr, "a second parentless window is not hooked"); | ||
| 169 | HWND tool = create_w(WS_EX_TOOLWINDOW, L"LeonidaLifecycleTest", L"tool", WS_POPUP, 0, 0, 64, 64, nullptr, nullptr, | ||
| 170 | nullptr, nullptr); | ||
| 171 | check(tool && GetPropW(tool, kHookProp) == nullptr, "a WS_EX_TOOLWINDOW window is not hooked"); | ||
| 172 | if (main_win) DestroyWindow(main_win); | ||
| 173 | HWND again = create_w(0, kClass, L"again", kMain, 0, 0, 64, 64, nullptr, nullptr, nullptr, nullptr); | ||
| 174 | check(again && GetPropW(again, kHookProp) != nullptr, "after the title window is destroyed, a new one is hooked"); | ||
| 175 | for (HWND w : {second, tool, again}) { | ||
| 176 | if (w) DestroyWindow(w); | ||
| 177 | } | ||
| 178 | |||
| 179 | std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); | ||
| 180 | return g_failures ? 1 : 0; | ||
| 181 | } | ||