upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/lifecycle.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/shims/lifecycle.cpp')
-rw-r--r--runtime/shims/lifecycle.cpp254
1 files changed, 254 insertions, 0 deletions
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
36namespace rt::lifecycle {
37namespace {
38
39using AppStateRoutine = void(WINAPI*)(BOOLEAN quiesced, PVOID context);
40
41struct Registration {
42 std::uintptr_t id;
43 AppStateRoutine routine;
44 void* context;
45};
46
47constexpr wchar_t kTitleProcProp[] = L"leonida.title.wndproc";
48constexpr auto kSuspendDeadline = std::chrono::seconds(1);
49
50// Recursive so a callback can unregister from inside run_suspend_callbacks() on the same thread.
51std::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
57std::vector<Registration>& reg_list() {
58 static auto* list = new std::vector<Registration>;
59 return *list;
60}
61
62std::atomic<std::uintptr_t> g_next_reg_id{1};
63std::atomic<bool> g_ending{false};
64std::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.
82void 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
100void 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
119LRESULT 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
135void 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).
145bool 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.
162void 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
168ULONG 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
179void 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
187HWND 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
196HWND 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
207std::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
220std::size_t registered_notification_count() {
221 std::lock_guard lock(reg_mutex());
222 return reg_list().size();
223}
224
225void invoke_suspend_callbacks_for_test() {
226 run_suspend_callbacks();
227}
228
229} // namespace rt::lifecycle
230
231namespace {
232using namespace rt::lifecycle;
233
234#define APP_NOTIFY_API(dll) \
235 {dll, "RegisterAppStateChangeNotification", reinterpret_cast<void*>(&register_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
244SHIM_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);