dsh-gufa-code 1.3.49 → 1.3.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1935 @@
1
+ /**
2
+ * 古法编程 · Windows 桌面悬浮层 helper(C++17 + Win32 + WebView2)
3
+ *
4
+ * 独立小窗口进程:加载 DSH Web GUI 的「古法编程」,做成无边框、永远置顶、
5
+ * 可拖拽/可缩放的悬浮窗。由 host/dev.js 的 float.* 用
6
+ * spawn(gufa-float-win.exe, [payloadJson])
7
+ * 启动;与 Host 只通过 argv 里的一个 JSON + controlPath 控制文件通信。
8
+ * 协议见 desktop/float/PLATFORM-PROTOCOL.md。
9
+ *
10
+ * 本文件刻意写成单文件(少量小文件),方便在无法本地编译的机器上逐行核对;
11
+ * WebView2 SDK 头/静态库由 CMake 的 WEBVIEW2_SDK_DIR 提供。
12
+ *
13
+ * 首版说明:窗口为「不透明」窗口(WebView2 windowed hosting 不支持真正的
14
+ * 逐像素透明;透明需要 DirectComposition + CompositionController +
15
+ * WS_EX_NOREDIRECTIONBITMAP 的 visual hosting,见 README-WIN.md 的 TODO)。
16
+ */
17
+
18
+ #ifndef WIN32_LEAN_AND_MEAN
19
+ #define WIN32_LEAN_AND_MEAN
20
+ #endif
21
+ #ifndef NOMINMAX
22
+ #define NOMINMAX
23
+ #endif
24
+
25
+ #include <windows.h>
26
+ #include <windowsx.h>
27
+ #include <dwmapi.h>
28
+ #include <objbase.h>
29
+ #include <shellapi.h>
30
+ #include <tlhelp32.h>
31
+ #include <wrl.h>
32
+ #include <wrl/client.h>
33
+
34
+ #include <cstdarg>
35
+ #include <cstdio>
36
+ #include <cstdlib>
37
+ #include <ctime>
38
+ #include <cwctype>
39
+ #include <exception>
40
+ #include <string>
41
+ #include <utility>
42
+ #include <vector>
43
+
44
+ #include "json.h"
45
+
46
+ #include "WebView2.h"
47
+ #include "WebView2EnvironmentOptions.h"
48
+
49
+ using Microsoft::WRL::Callback;
50
+ using Microsoft::WRL::ComPtr;
51
+
52
+ namespace {
53
+
54
+ /* ────────────────────────────── 常量 ────────────────────────────── */
55
+
56
+ constexpr wchar_t kMainWindowClass[] = L"GufaFloatWinMain";
57
+ constexpr wchar_t kStripWindowClass[] = L"GufaFloatWinStrip";
58
+ constexpr wchar_t kWindowTitle[] = L"古法编程悬浮层";
59
+ constexpr wchar_t kLogFileName[] = L"gufa-float-debug.log";
60
+
61
+ constexpr UINT kMsgExitGraceful = WM_APP + 1;
62
+ constexpr UINT kMsgStripMenu = WM_APP + 2;
63
+
64
+ constexpr UINT_PTR kTimerFollow = 1;
65
+ constexpr UINT_PTR kTimerControl = 2;
66
+ constexpr UINT_PTR kTimerHideDsh = 3;
67
+ constexpr UINT_PTR kTimerProbeTimeout = 4;
68
+ constexpr UINT_PTR kTimerProbeWatchdog = 5;
69
+ constexpr UINT_PTR kTimerSelftest = 6;
70
+ constexpr UINT_PTR kTimerPageProbe = 7;
71
+ constexpr UINT_PTR kTimerRetry = 8;
72
+
73
+ constexpr int kMenuExit = 1;
74
+ constexpr int kMenuResetFrame = 2;
75
+
76
+ constexpr int kResizeBorderDip = 8; // 左右/底部可缩放边缘宽度(DIP)
77
+ constexpr int kDragStripDip = 22; // 顶部拖动条高度(DIP,与网页 CSS 的 22px 对齐)
78
+ constexpr int kProbeTimeoutMs = 8000;
79
+ constexpr int kProbeWatchdogMs = 20000;
80
+ constexpr int kFollowIntervalMs = 250;
81
+ constexpr int kControlIntervalMs = 300;
82
+
83
+ /* 深色背景(与网页 --gufa-solid-bg 的底色一致) */
84
+ const COLORREF kBackgroundColor = RGB(13, 15, 19);
85
+
86
+ HINSTANCE g_instance = nullptr;
87
+ std::wstring g_logPath;
88
+ /* 崩溃兜底:记录被隐藏的 DSH 窗口,异常退出前尽量恢复(全局变量便于崩溃过滤器访问) */
89
+ std::vector<HWND> g_crashRestoreWindows;
90
+
91
+ /* ────────────────────────────── 基础工具 ────────────────────────────── */
92
+
93
+ std::string WideToUtf8(const std::wstring& text) {
94
+ if (text.empty()) return std::string();
95
+ const int length = WideCharToMultiByte(CP_UTF8, 0, text.c_str(),
96
+ static_cast<int>(text.size()),
97
+ nullptr, 0, nullptr, nullptr);
98
+ if (length <= 0) return std::string();
99
+ std::string result(static_cast<std::size_t>(length), '\0');
100
+ WideCharToMultiByte(CP_UTF8, 0, text.c_str(), static_cast<int>(text.size()),
101
+ result.data(), length, nullptr, nullptr);
102
+ return result;
103
+ }
104
+
105
+ void WriteStdout(const std::wstring& text) {
106
+ const std::string utf8 = WideToUtf8(text);
107
+ HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
108
+ if (handle == nullptr || handle == INVALID_HANDLE_VALUE) return;
109
+ DWORD written = 0;
110
+ WriteFile(handle, utf8.data(), static_cast<DWORD>(utf8.size()), &written, nullptr);
111
+ }
112
+
113
+ std::wstring GetTempDirectory() {
114
+ wchar_t buffer[32768];
115
+ buffer[0] = L'\0';
116
+ const DWORD length = GetTempPathW(static_cast<DWORD>(_countof(buffer)), buffer);
117
+ if (length > 0 && length < _countof(buffer)) return std::wstring(buffer, length);
118
+ return std::wstring(L"C:\\Windows\\Temp\\");
119
+ }
120
+
121
+ std::wstring GetBaseDataDirectory() {
122
+ wchar_t buffer[32768];
123
+ buffer[0] = L'\0';
124
+ const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer,
125
+ static_cast<DWORD>(_countof(buffer)));
126
+ if (length > 0 && length < _countof(buffer)) {
127
+ return std::wstring(buffer, length) + L"\\gufa-float";
128
+ }
129
+ std::wstring temp = GetTempDirectory();
130
+ if (!temp.empty() && temp.back() != L'\\' && temp.back() != L'/') temp.push_back(L'\\');
131
+ return temp + L"gufa-float";
132
+ }
133
+
134
+ void EnsureDirectoryExists(const std::wstring& directory) {
135
+ if (directory.empty()) return;
136
+ std::wstring current;
137
+ current.reserve(directory.size());
138
+ for (std::size_t i = 0; i < directory.size(); ++i) {
139
+ const wchar_t c = directory[i];
140
+ current.push_back(c);
141
+ if (c != L'\\' && c != L'/') continue;
142
+ if (current.size() == 1) continue; // "\"
143
+ if (current.size() == 3 && current[1] == L':') continue; // "C:\"
144
+ CreateDirectoryW(current.c_str(), nullptr);
145
+ }
146
+ CreateDirectoryW(directory.c_str(), nullptr);
147
+ }
148
+
149
+ void AppendLogLine(const std::wstring& message) {
150
+ if (g_logPath.empty()) return;
151
+ SYSTEMTIME now;
152
+ GetLocalTime(&now);
153
+ wchar_t stamp[80];
154
+ _snwprintf_s(stamp, _countof(stamp), _TRUNCATE,
155
+ L"[%04u-%02u-%02u %02u:%02u:%02u] ",
156
+ static_cast<unsigned>(now.wYear), static_cast<unsigned>(now.wMonth),
157
+ static_cast<unsigned>(now.wDay), static_cast<unsigned>(now.wHour),
158
+ static_cast<unsigned>(now.wMinute), static_cast<unsigned>(now.wSecond));
159
+ const std::wstring line = std::wstring(stamp) + message + L"\r\n";
160
+ const std::string utf8 = WideToUtf8(line);
161
+ HANDLE handle = CreateFileW(g_logPath.c_str(), FILE_APPEND_DATA,
162
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
163
+ nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
164
+ if (handle == INVALID_HANDLE_VALUE) return;
165
+ DWORD written = 0;
166
+ WriteFile(handle, utf8.data(), static_cast<DWORD>(utf8.size()), &written, nullptr);
167
+ CloseHandle(handle);
168
+ }
169
+
170
+ void LogFmt(const wchar_t* format, ...) {
171
+ wchar_t buffer[4096];
172
+ buffer[0] = L'\0';
173
+ va_list arguments;
174
+ va_start(arguments, format);
175
+ _vsnwprintf_s(buffer, _countof(buffer), _TRUNCATE, format, arguments);
176
+ va_end(arguments);
177
+ buffer[_countof(buffer) - 1] = L'\0';
178
+ AppendLogLine(buffer);
179
+ }
180
+
181
+ void Log(const std::wstring& message) { AppendLogLine(message); }
182
+
183
+ void Log(const wchar_t* message) { AppendLogLine(std::wstring(message)); }
184
+
185
+ void InitLogging() {
186
+ std::wstring directory = GetTempDirectory();
187
+ if (!directory.empty() && directory.back() != L'\\' && directory.back() != L'/') {
188
+ directory.push_back(L'\\');
189
+ }
190
+ g_logPath = directory + kLogFileName;
191
+ HANDLE handle = CreateFileW(g_logPath.c_str(), GENERIC_READ,
192
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
193
+ nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
194
+ if (handle != INVALID_HANDLE_VALUE) {
195
+ LARGE_INTEGER size;
196
+ size.QuadPart = 0;
197
+ if (GetFileSizeEx(handle, &size) && size.QuadPart > (4LL * 1024 * 1024)) {
198
+ CloseHandle(handle);
199
+ DeleteFileW(g_logPath.c_str());
200
+ } else {
201
+ CloseHandle(handle);
202
+ }
203
+ }
204
+ LogFmt(L"==== gufa-float-win start pid=%lu build=win32 log=%s ====",
205
+ static_cast<unsigned long>(GetCurrentProcessId()), g_logPath.c_str());
206
+ }
207
+
208
+ /* 崩溃 / terminate 兜底:至少把被隐藏的 DSH 主窗口恢复出来,避免「主窗口消失」。 */
209
+ void CrashRestoreWindows() {
210
+ for (HWND hwnd : g_crashRestoreWindows) {
211
+ if (hwnd != nullptr && IsWindow(hwnd)) ShowWindowAsync(hwnd, SW_SHOW);
212
+ }
213
+ g_crashRestoreWindows.clear();
214
+ }
215
+
216
+ LONG WINAPI CrashExceptionFilter(EXCEPTION_POINTERS* exceptionInfo) {
217
+ (void)exceptionInfo;
218
+ CrashRestoreWindows();
219
+ return EXCEPTION_CONTINUE_SEARCH;
220
+ }
221
+
222
+ void CrashTerminateHandler() {
223
+ CrashRestoreWindows();
224
+ std::abort();
225
+ }
226
+
227
+ void InstallCrashHandlers() {
228
+ SetUnhandledExceptionFilter(CrashExceptionFilter);
229
+ std::set_terminate(CrashTerminateHandler);
230
+ }
231
+
232
+ #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
233
+ #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT)-4)
234
+ #endif
235
+
236
+ void EnableDpiAwareness() {
237
+ HMODULE user32 = GetModuleHandleW(L"user32.dll");
238
+ if (user32 != nullptr) {
239
+ using SetProcessDpiAwarenessContextFn = BOOL (WINAPI *)(DPI_AWARENESS_CONTEXT);
240
+ FARPROC address = GetProcAddress(user32, "SetProcessDpiAwarenessContext");
241
+ if (address != nullptr) {
242
+ SetProcessDpiAwarenessContextFn setContext =
243
+ reinterpret_cast<SetProcessDpiAwarenessContextFn>(address);
244
+ if (setContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)) return;
245
+ }
246
+ }
247
+ SetProcessDPIAware();
248
+ }
249
+
250
+ UINT WindowDpi(HWND hwnd) {
251
+ UINT dpi = 0;
252
+ if (hwnd != nullptr) dpi = GetDpiForWindow(hwnd);
253
+ if (dpi == 0) dpi = GetDpiForSystem();
254
+ if (dpi == 0) dpi = 96;
255
+ return dpi;
256
+ }
257
+
258
+ int DpiScale(HWND hwnd, int value) {
259
+ return MulDiv(value, static_cast<int>(WindowDpi(hwnd)), 96);
260
+ }
261
+
262
+ std::wstring GetWindowTitleText(HWND hwnd) {
263
+ const int length = GetWindowTextLengthW(hwnd);
264
+ if (length <= 0) return std::wstring();
265
+ std::wstring text(static_cast<std::size_t>(length) + 1, L'\0');
266
+ const int copied = GetWindowTextW(hwnd, &text[0], static_cast<int>(text.size()));
267
+ if (copied <= 0) return std::wstring();
268
+ text.resize(static_cast<std::size_t>(copied));
269
+ return text;
270
+ }
271
+
272
+ bool ContainsNoCase(const std::wstring& haystack, const std::wstring& needle) {
273
+ if (needle.empty()) return true;
274
+ if (haystack.size() < needle.size()) return false;
275
+ for (std::size_t i = 0; i + needle.size() <= haystack.size(); ++i) {
276
+ bool match = true;
277
+ for (std::size_t j = 0; j < needle.size(); ++j) {
278
+ if (std::towlower(haystack[i + j]) != std::towlower(needle[j])) {
279
+ match = false;
280
+ break;
281
+ }
282
+ }
283
+ if (match) return true;
284
+ }
285
+ return false;
286
+ }
287
+
288
+ DWORD ParentProcessId(DWORD processId) {
289
+ DWORD parent = 0;
290
+ HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
291
+ if (snapshot == INVALID_HANDLE_VALUE) return 0;
292
+ PROCESSENTRY32W entry;
293
+ entry.dwSize = sizeof(PROCESSENTRY32W);
294
+ BOOL more = Process32FirstW(snapshot, &entry);
295
+ while (more) {
296
+ if (entry.th32ProcessID == processId) {
297
+ parent = entry.th32ParentProcessID;
298
+ break;
299
+ }
300
+ entry.dwSize = sizeof(PROCESSENTRY32W);
301
+ more = Process32NextW(snapshot, &entry);
302
+ }
303
+ CloseHandle(snapshot);
304
+ return parent;
305
+ }
306
+
307
+ std::wstring ProcessImagePath(DWORD processId) {
308
+ if (processId == 0) return std::wstring();
309
+ HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
310
+ if (process == nullptr) return std::wstring();
311
+ wchar_t buffer[32768];
312
+ DWORD length = static_cast<DWORD>(_countof(buffer));
313
+ const BOOL ok = QueryFullProcessImageNameW(process, 0, buffer, &length);
314
+ CloseHandle(process);
315
+ if (!ok || length == 0) return std::wstring();
316
+ return std::wstring(buffer, length);
317
+ }
318
+
319
+ std::wstring FileNameOf(const std::wstring& path) {
320
+ const std::size_t slash = path.find_last_of(L"\\/");
321
+ return slash == std::wstring::npos ? path : path.substr(slash + 1);
322
+ }
323
+
324
+ void ForceForeground(HWND hwnd) {
325
+ if (hwnd == nullptr || !IsWindow(hwnd)) return;
326
+ if (IsIconic(hwnd)) {
327
+ ShowWindowAsync(hwnd, SW_RESTORE);
328
+ } else {
329
+ ShowWindowAsync(hwnd, SW_SHOW);
330
+ }
331
+ DWORD foregroundThread = 0;
332
+ HWND foreground = GetForegroundWindow();
333
+ if (foreground != nullptr) foregroundThread = GetWindowThreadProcessId(foreground, nullptr);
334
+ const DWORD currentThread = GetCurrentThreadId();
335
+ bool attached = false;
336
+ if (foregroundThread != 0 && foregroundThread != currentThread) {
337
+ attached = AttachThreadInput(currentThread, foregroundThread, TRUE) != FALSE;
338
+ }
339
+ SetForegroundWindow(hwnd);
340
+ BringWindowToTop(hwnd);
341
+ if (attached) AttachThreadInput(currentThread, foregroundThread, FALSE);
342
+ }
343
+
344
+ /* 目标窗口的「可见」外框:Win10+ 的 GetWindowRect 含 DWM 阴影边距,优先用扩展框。 */
345
+ bool GetVisibleWindowRect(HWND hwnd, RECT* rect) {
346
+ if (hwnd == nullptr || rect == nullptr) return false;
347
+ RECT extended = {};
348
+ const HRESULT hr = DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &extended,
349
+ static_cast<DWORD>(sizeof(extended)));
350
+ if (SUCCEEDED(hr) && extended.right > extended.left && extended.bottom > extended.top) {
351
+ *rect = extended;
352
+ return true;
353
+ }
354
+ RECT basic = {};
355
+ if (!GetWindowRect(hwnd, &basic)) return false;
356
+ if (basic.right <= basic.left || basic.bottom <= basic.top) return false;
357
+ *rect = basic;
358
+ return true;
359
+ }
360
+
361
+ bool RectsEqual(const RECT& left, const RECT& right) {
362
+ return left.left == right.left && left.top == right.top &&
363
+ left.right == right.right && left.bottom == right.bottom;
364
+ }
365
+
366
+ void ClampRectToVirtualScreen(RECT* rect) {
367
+ if (rect == nullptr) return;
368
+ const int virtualX = GetSystemMetrics(SM_XVIRTUALSCREEN);
369
+ const int virtualY = GetSystemMetrics(SM_YVIRTUALSCREEN);
370
+ const int virtualWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
371
+ const int virtualHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
372
+ if (virtualWidth <= 0 || virtualHeight <= 0) return;
373
+ int width = rect->right - rect->left;
374
+ int height = rect->bottom - rect->top;
375
+ if (width <= 0) width = 800;
376
+ if (height <= 0) height = 600;
377
+ if (rect->right <= virtualX) {
378
+ rect->left = virtualX + 40;
379
+ rect->right = rect->left + width;
380
+ } else if (rect->left >= virtualX + virtualWidth) {
381
+ rect->left = virtualX + virtualWidth - width - 40;
382
+ rect->right = rect->left + width;
383
+ }
384
+ if (rect->bottom <= virtualY) {
385
+ rect->top = virtualY + 40;
386
+ rect->bottom = rect->top + height;
387
+ } else if (rect->top >= virtualY + virtualHeight) {
388
+ rect->top = virtualY + virtualHeight - height - 40;
389
+ rect->bottom = rect->top + height;
390
+ }
391
+ }
392
+
393
+ std::wstring AppendFloatQuery(const std::wstring& url) {
394
+ if (url.empty()) return url;
395
+ std::wstring result = url;
396
+ result += (result.find(L'?') == std::wstring::npos) ? L"?gufa-float=1" : L"&gufa-float=1";
397
+ return result;
398
+ }
399
+
400
+ std::wstring ExtractUrlHost(const std::wstring& url) {
401
+ const std::size_t scheme = url.find(L"://");
402
+ const std::size_t start = (scheme == std::wstring::npos) ? 0 : scheme + 3;
403
+ std::size_t end = start;
404
+ while (end < url.size()) {
405
+ const wchar_t c = url[end];
406
+ if (c == L'/' || c == L'?' || c == L'#' || c == L':') break;
407
+ ++end;
408
+ }
409
+ if (end <= start) return std::wstring();
410
+ return url.substr(start, end - start);
411
+ }
412
+
413
+ /* ────────────────────────────── payload ────────────────────────────── */
414
+
415
+ struct FloatPayload {
416
+ std::wstring appUrl;
417
+ std::wstring authUrl;
418
+ std::wstring cookie;
419
+ std::wstring controlPath;
420
+ std::wstring build;
421
+ std::wstring selftest;
422
+ std::wstring followTitle;
423
+ bool hasFollow = false;
424
+ DWORD followPid = 0;
425
+ bool hasState = false;
426
+ gufa::JsonValue state;
427
+ int alpha = 0;
428
+ DWORD ownerPid = 0;
429
+ bool ciProbe = false;
430
+ };
431
+
432
+ DWORD ReadJsonPid(const gufa::JsonValue* value) {
433
+ if (value == nullptr || !value->IsNumber()) return 0;
434
+ const unsigned long long parsed = wcstoull(value->number.c_str(), nullptr, 10);
435
+ if (parsed == 0 || parsed > 0xFFFFFFFFull) return 0;
436
+ return static_cast<DWORD>(parsed);
437
+ }
438
+
439
+ bool ParsePayloadJson(const std::wstring& text, FloatPayload* payload, std::wstring* error) {
440
+ gufa::JsonValue root;
441
+ std::wstring parseError;
442
+ if (!gufa::ParseJson(text, root, &parseError)) {
443
+ *error = L"JSON 解析失败: " + parseError;
444
+ return false;
445
+ }
446
+ if (!root.IsObject()) {
447
+ *error = L"payload 根节点不是 JSON 对象";
448
+ return false;
449
+ }
450
+ auto readString = [&root](const wchar_t* key, std::wstring* out) {
451
+ const gufa::JsonValue* value = root.Find(key);
452
+ if (value != nullptr && value->IsString()) *out = value->text;
453
+ };
454
+ readString(L"appUrl", &payload->appUrl);
455
+ readString(L"authUrl", &payload->authUrl);
456
+ readString(L"cookie", &payload->cookie);
457
+ readString(L"controlPath", &payload->controlPath);
458
+ readString(L"build", &payload->build);
459
+ readString(L"selftest", &payload->selftest);
460
+
461
+ const gufa::JsonValue* follow = root.Find(L"follow");
462
+ if (follow != nullptr && follow->IsObject()) {
463
+ const DWORD pid = ReadJsonPid(follow->Find(L"pid"));
464
+ if (pid != 0) {
465
+ payload->hasFollow = true;
466
+ payload->followPid = pid;
467
+ }
468
+ const gufa::JsonValue* title = follow->Find(L"title");
469
+ if (title != nullptr && title->IsString()) payload->followTitle = title->text;
470
+ }
471
+
472
+ const gufa::JsonValue* state = root.Find(L"state");
473
+ if (state != nullptr && state->IsObject()) {
474
+ payload->hasState = true;
475
+ payload->state = *state;
476
+ }
477
+
478
+ const gufa::JsonValue* alpha = root.Find(L"alpha");
479
+ if (alpha != nullptr && alpha->IsNumber()) {
480
+ const double raw = wcstod(alpha->number.c_str(), nullptr);
481
+ if (raw >= 20.0 && raw <= 100.0) payload->alpha = static_cast<int>(raw);
482
+ }
483
+
484
+ payload->ownerPid = ReadJsonPid(root.Find(L"ownerPid"));
485
+
486
+ const gufa::JsonValue* ciProbe = root.Find(L"ciProbe");
487
+ if (ciProbe != nullptr && ciProbe->IsBool()) payload->ciProbe = ciProbe->boolean;
488
+
489
+ return true;
490
+ }
491
+
492
+ bool ValidatePayload(const FloatPayload& payload, std::wstring* error) {
493
+ if (payload.ciProbe) return true;
494
+ if (payload.appUrl.empty()) {
495
+ *error = L"payload 缺少 appUrl";
496
+ return false;
497
+ }
498
+ if (payload.cookie.empty() && payload.authUrl.empty()) {
499
+ *error = L"payload 既没有 cookie 也没有 authUrl";
500
+ return false;
501
+ }
502
+ return true;
503
+ }
504
+
505
+ /* document-start 注入脚本:悬浮标记 + 主窗口状态(项目/UI/标签页/会话)。 */
506
+ std::wstring BuildBootstrapScript(const FloatPayload& payload) {
507
+ std::wstring script = L"try{localStorage.setItem('gufa-code:float','1');";
508
+ if (payload.hasState) {
509
+ const std::wstring stateJson = gufa::SerializeJson(payload.state);
510
+ if (!stateJson.empty()) {
511
+ script += L"localStorage.setItem('gufa-code:float-state','";
512
+ script += gufa::EscapeJsSingleQuoted(stateJson);
513
+ script += L"');";
514
+ const gufa::JsonValue* projectRoot = payload.state.Find(L"projectRoot");
515
+ if (projectRoot != nullptr && projectRoot->IsString() && !projectRoot->text.empty()) {
516
+ script += L"localStorage.setItem('gufa-code:project',JSON.stringify('";
517
+ script += gufa::EscapeJsSingleQuoted(projectRoot->text);
518
+ script += L"'));";
519
+ }
520
+ const gufa::JsonValue* ui = payload.state.Find(L"ui");
521
+ if (ui != nullptr && ui->IsObject()) {
522
+ script += L"localStorage.setItem('gufa-code:ui:v1','";
523
+ script += gufa::EscapeJsSingleQuoted(gufa::SerializeJson(*ui));
524
+ script += L"');";
525
+ }
526
+ }
527
+ }
528
+ script += L"}catch(e){}";
529
+ return script;
530
+ }
531
+
532
+ /* ───────────────────────── DSH 主窗口查找/隐藏/恢复 ─────────────────────────
533
+ *
534
+ * 注意:payload.ownerPid 由 Host 传的是 process.ppid,可能是 explorer.exe 等
535
+ * 启动器进程。绝不能「无脑隐藏 ownerPid 的所有窗口」(会把任务栏/桌面藏掉)。
536
+ * 因此这里只按以下可信信号识别 DSH 主窗口:
537
+ * 1. 窗口标题包含 "DeepSeek Harness"(协议首选);
538
+ * 2. 进程可执行文件名包含 "deepseek"(Electron 主进程的窗口);
539
+ * 3. 前两者都没找到时,退化为「本 helper 的直接父进程」(即 spawn 它的
540
+ * Host 进程)的可见顶层窗口——仅当父进程不是常见 shell/终端时。
541
+ */
542
+
543
+ struct DshSearch {
544
+ std::vector<HWND> found;
545
+ std::vector<std::pair<DWORD, std::wstring>> processNameCache;
546
+ bool collectByPid = false;
547
+ DWORD pidFilter = 0;
548
+ };
549
+
550
+ std::wstring CachedProcessImageName(DshSearch* search, DWORD processId) {
551
+ for (const auto& item : search->processNameCache) {
552
+ if (item.first == processId) return item.second;
553
+ }
554
+ const std::wstring name = FileNameOf(ProcessImagePath(processId));
555
+ search->processNameCache.emplace_back(processId, name);
556
+ return name;
557
+ }
558
+
559
+ void AppendUniqueWindow(std::vector<HWND>* windows, HWND hwnd) {
560
+ for (HWND existing : *windows) {
561
+ if (existing == hwnd) return;
562
+ }
563
+ windows->push_back(hwnd);
564
+ }
565
+
566
+ bool IsShellLikeProcess(const std::wstring& imageName) {
567
+ static const wchar_t* const kBlocked[] = {
568
+ L"explorer.exe", L"cmd.exe", L"powershell.exe", L"pwsh.exe",
569
+ L"conhost.exe", L"node.exe", L"wsl.exe", L"bash.exe",
570
+ L"mintty.exe", L"windowsterminal.exe", L"wt.exe", L"python.exe",
571
+ L"python3.exe", L"Code.exe", L"devenv.exe",
572
+ };
573
+ for (const wchar_t* blocked : kBlocked) {
574
+ if (ContainsNoCase(imageName, blocked)) return true;
575
+ }
576
+ return false;
577
+ }
578
+
579
+ BOOL CALLBACK DshEnumProc(HWND hwnd, LPARAM lParam) {
580
+ DshSearch* search = reinterpret_cast<DshSearch*>(lParam);
581
+ if (!IsWindowVisible(hwnd)) return TRUE;
582
+ if (GetWindow(hwnd, GW_OWNER) != nullptr) return TRUE;
583
+ const LONG_PTR extendedStyle = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
584
+ if ((extendedStyle & WS_EX_TOOLWINDOW) != 0) return TRUE;
585
+ DWORD processId = 0;
586
+ GetWindowThreadProcessId(hwnd, &processId);
587
+ if (processId == 0 || processId == GetCurrentProcessId()) return TRUE;
588
+ const std::wstring title = GetWindowTitleText(hwnd);
589
+ if (title.empty()) return TRUE;
590
+ if (search->collectByPid) {
591
+ if (processId == search->pidFilter) AppendUniqueWindow(&search->found, hwnd);
592
+ return TRUE;
593
+ }
594
+ if (ContainsNoCase(title, L"deepseek harness")) {
595
+ AppendUniqueWindow(&search->found, hwnd);
596
+ return TRUE;
597
+ }
598
+ const std::wstring processName = CachedProcessImageName(search, processId);
599
+ if (ContainsNoCase(processName, L"deepseek")) AppendUniqueWindow(&search->found, hwnd);
600
+ return TRUE;
601
+ }
602
+
603
+ std::vector<HWND> FindDshWindows(DWORD ownerPid) {
604
+ (void)ownerPid; // ownerPid 仅作 Host 侧信息;见上方注释,不无脑用于隐藏。
605
+ DshSearch search;
606
+ EnumWindows(DshEnumProc, reinterpret_cast<LPARAM>(&search));
607
+ if (search.found.empty()) {
608
+ const DWORD directParent = ParentProcessId(GetCurrentProcessId());
609
+ const std::wstring parentName = FileNameOf(ProcessImagePath(directParent));
610
+ if (directParent != 0 && !IsShellLikeProcess(parentName)) {
611
+ search.collectByPid = true;
612
+ search.pidFilter = directParent;
613
+ EnumWindows(DshEnumProc, reinterpret_cast<LPARAM>(&search));
614
+ }
615
+ }
616
+ return search.found;
617
+ }
618
+
619
+ /* ────────────────────────────── 跟随目标窗口 ────────────────────────────── */
620
+
621
+ struct FollowSearch {
622
+ DWORD processId = 0;
623
+ std::wstring title;
624
+ bool hasTitle = false;
625
+ std::vector<HWND> candidates;
626
+ };
627
+
628
+ BOOL CALLBACK FollowEnumProc(HWND hwnd, LPARAM lParam) {
629
+ FollowSearch* search = reinterpret_cast<FollowSearch*>(lParam);
630
+ if (!IsWindowVisible(hwnd)) return TRUE;
631
+ if (IsIconic(hwnd)) return TRUE;
632
+ if (GetWindow(hwnd, GW_OWNER) != nullptr) return TRUE;
633
+ DWORD processId = 0;
634
+ GetWindowThreadProcessId(hwnd, &processId);
635
+ if (processId != search->processId) return TRUE;
636
+ const LONG_PTR extendedStyle = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
637
+ if ((extendedStyle & WS_EX_TOOLWINDOW) != 0) return TRUE;
638
+ const std::wstring title = GetWindowTitleText(hwnd);
639
+ if (search->hasTitle && !ContainsNoCase(title, search->title)) return TRUE;
640
+ RECT rect = {};
641
+ if (!GetVisibleWindowRect(hwnd, &rect)) return TRUE;
642
+ if (rect.right - rect.left < 120 || rect.bottom - rect.top < 80) return TRUE;
643
+ search->candidates.push_back(hwnd);
644
+ return TRUE;
645
+ }
646
+
647
+ HWND FindFollowWindowForProcess(DWORD processId, const std::wstring& title) {
648
+ if (processId == 0) return nullptr;
649
+ FollowSearch search;
650
+ search.processId = processId;
651
+ search.title = title;
652
+ search.hasTitle = !title.empty();
653
+ HWND foreground = GetForegroundWindow();
654
+ if (foreground != nullptr) {
655
+ DWORD foregroundProcess = 0;
656
+ GetWindowThreadProcessId(foreground, &foregroundProcess);
657
+ if (foregroundProcess == processId && IsWindowVisible(foreground) && !IsIconic(foreground) &&
658
+ GetWindow(foreground, GW_OWNER) == nullptr) {
659
+ RECT foregroundRect = {};
660
+ if (GetVisibleWindowRect(foreground, &foregroundRect) &&
661
+ foregroundRect.right - foregroundRect.left >= 120 &&
662
+ foregroundRect.bottom - foregroundRect.top >= 80 &&
663
+ (!search.hasTitle || ContainsNoCase(GetWindowTitleText(foreground), title))) {
664
+ return foreground;
665
+ }
666
+ }
667
+ }
668
+ EnumWindows(FollowEnumProc, reinterpret_cast<LPARAM>(&search));
669
+ if (search.candidates.empty()) return nullptr;
670
+ HWND best = search.candidates.front();
671
+ long long bestArea = -1;
672
+ for (HWND candidate : search.candidates) {
673
+ RECT rect = {};
674
+ if (!GetVisibleWindowRect(candidate, &rect)) continue;
675
+ const long long area = static_cast<long long>(rect.right - rect.left) *
676
+ static_cast<long long>(rect.bottom - rect.top);
677
+ if (area > bestArea) {
678
+ bestArea = area;
679
+ best = candidate;
680
+ }
681
+ }
682
+ return best;
683
+ }
684
+
685
+ /* ────────────────────────────── 悬浮层窗口 ────────────────────────────── */
686
+
687
+ class FloatApp {
688
+ public:
689
+ FloatApp() = default;
690
+ ~FloatApp();
691
+ FloatApp(const FloatApp&) = delete;
692
+ FloatApp& operator=(const FloatApp&) = delete;
693
+
694
+ bool ParseCommandLine(const std::wstring& jsonText);
695
+ bool CreateMainWindow();
696
+ void Start();
697
+ int RunMessageLoop();
698
+ void RequestExit(int exitCode);
699
+ bool IsCiProbe() const { return payload_.ciProbe; }
700
+
701
+ static LRESULT CALLBACK MainWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
702
+ static LRESULT CALLBACK StripWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
703
+
704
+ private:
705
+ enum class Phase { Idle, Auth, App, Done };
706
+
707
+ static FloatApp* FromWindow(HWND hwnd);
708
+ static FloatApp* FromStripWindow(HWND stripWindow);
709
+ static bool RegisterWindowClasses();
710
+
711
+ LRESULT OnMainMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
712
+ LRESULT HandleNcHitTest(HWND hwnd, LPARAM lparam);
713
+ void HandleMinMaxInfo(MINMAXINFO* info);
714
+
715
+ void LayoutChildren();
716
+ void RaiseStrip();
717
+ void ResetWindowFrame();
718
+ bool LoadSavedFrame(RECT* frame);
719
+ void SaveFrameIfNeeded();
720
+ std::wstring FrameFilePath();
721
+ void ClampInitialRect(RECT* rect);
722
+
723
+ void OnFollowTimer();
724
+ void ApplyFollowFrame();
725
+ void OnHideDshTimer();
726
+ void HideDshWindows();
727
+ void RestoreDshWindows();
728
+
729
+ void OnControlTimer();
730
+ void DeleteControlFile();
731
+ void OnTimer(UINT_PTR timerId);
732
+ void KillAllTimers();
733
+
734
+ void CreateWebViewEnvironment();
735
+ void OnEnvironmentCreated(HRESULT errorCode, ICoreWebView2Environment* environment);
736
+ void OnControllerCreated(HRESULT errorCode, ICoreWebView2Controller* controller);
737
+ void ConfigureWebView();
738
+ void StartScriptInjection();
739
+ void OnScriptRegistered(HRESULT errorCode, LPCWSTR scriptId);
740
+ void BeginNavigation();
741
+ void InjectCookieThenNavigate(const std::wstring& targetUrl);
742
+ void OnNavigationCompleted(bool success);
743
+ void OnNewWindowRequested(ICoreWebView2NewWindowRequestedEventArgs* args);
744
+ void OnProcessFailed(ICoreWebView2ProcessFailedEventArgs* args);
745
+ void OnPageProbeTimer();
746
+ void OnSelftestTimer();
747
+ void HandleWebViewEnvironmentFailure(HRESULT errorCode);
748
+ void FinishProbe(bool loaded);
749
+ void FinishProbeFailure();
750
+
751
+ void DoGracefulExit();
752
+ void OnWindowDestroyed();
753
+ void CleanupWebView();
754
+
755
+ HWND hwnd_ = nullptr;
756
+ HWND strip_ = nullptr;
757
+ FloatPayload payload_;
758
+ bool started_ = false;
759
+ bool exiting_ = false;
760
+ bool controllerReady_ = false;
761
+ bool ciProbeFinished_ = false;
762
+ bool appLoaded_ = false;
763
+ bool followActivated_ = false;
764
+ int appNavAttempt_ = 0;
765
+ int envAttempt_ = 0;
766
+ int exitCode_ = 0;
767
+ int followMissCount_ = 0;
768
+ Phase phase_ = Phase::Idle;
769
+ std::wstring userDataFolder_;
770
+ std::wstring floatUrl_;
771
+ ComPtr<ICoreWebView2Environment> environment_;
772
+ ComPtr<ICoreWebView2Controller> controller_;
773
+ ComPtr<ICoreWebView2> webView_;
774
+ std::vector<HWND> hiddenDshWindows_;
775
+ HWND followWindow_ = nullptr;
776
+ RECT lastFollowRect_ = {};
777
+ bool hasLastFollowRect_ = false;
778
+ HANDLE hostProcess_ = nullptr;
779
+ };
780
+
781
+ FloatApp::~FloatApp() {
782
+ if (hostProcess_ != nullptr) {
783
+ CloseHandle(hostProcess_);
784
+ hostProcess_ = nullptr;
785
+ }
786
+ CleanupWebView();
787
+ }
788
+
789
+ FloatApp* FloatApp::FromWindow(HWND hwnd) {
790
+ if (hwnd == nullptr) return nullptr;
791
+ return reinterpret_cast<FloatApp*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
792
+ }
793
+
794
+ FloatApp* FloatApp::FromStripWindow(HWND stripWindow) {
795
+ if (stripWindow == nullptr) return nullptr;
796
+ return FromWindow(GetParent(stripWindow));
797
+ }
798
+
799
+ LRESULT CALLBACK FloatApp::MainWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
800
+ if (message == WM_NCCREATE) {
801
+ CREATESTRUCTW* createStruct = reinterpret_cast<CREATESTRUCTW*>(lparam);
802
+ if (createStruct != nullptr) {
803
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA,
804
+ reinterpret_cast<LONG_PTR>(createStruct->lpCreateParams));
805
+ }
806
+ }
807
+ FloatApp* app = FromWindow(hwnd);
808
+ if (app == nullptr) return DefWindowProcW(hwnd, message, wparam, lparam);
809
+ return app->OnMainMessage(hwnd, message, wparam, lparam);
810
+ }
811
+
812
+ LRESULT CALLBACK FloatApp::StripWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
813
+ FloatApp* app = FromStripWindow(hwnd);
814
+ switch (message) {
815
+ case WM_ERASEBKGND:
816
+ return 1;
817
+ case WM_PAINT: {
818
+ PAINTSTRUCT paint = {};
819
+ HDC dc = BeginPaint(hwnd, &paint);
820
+ if (dc != nullptr) {
821
+ RECT client = {};
822
+ GetClientRect(hwnd, &client);
823
+ HBRUSH background = CreateSolidBrush(kBackgroundColor);
824
+ if (background != nullptr) {
825
+ FillRect(dc, &client, background);
826
+ DeleteObject(background);
827
+ }
828
+ RECT line = {client.left, client.bottom - 1, client.right, client.bottom};
829
+ HBRUSH lineBrush = CreateSolidBrush(RGB(46, 50, 58));
830
+ if (lineBrush != nullptr) {
831
+ FillRect(dc, &line, lineBrush);
832
+ DeleteObject(lineBrush);
833
+ }
834
+ const UINT dpi = WindowDpi(hwnd);
835
+ HFONT font = CreateFontW(-MulDiv(12, static_cast<int>(dpi), 96), 0, 0, 0, FW_NORMAL,
836
+ FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
837
+ CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
838
+ DEFAULT_PITCH | FF_DONTCARE, L"Microsoft YaHei UI");
839
+ HGDIOBJ oldFont = nullptr;
840
+ if (font != nullptr) oldFont = SelectObject(dc, font);
841
+ SetBkMode(dc, TRANSPARENT);
842
+ SetTextColor(dc, RGB(205, 208, 214));
843
+ const int closeWidth = MulDiv(48, static_cast<int>(dpi), 96);
844
+ RECT textRect = client;
845
+ textRect.left += MulDiv(10, static_cast<int>(dpi), 96);
846
+ textRect.right -= closeWidth;
847
+ DrawTextW(dc, L"古法编程 · 摸鱼中(拖动移动 · 右键菜单)", -1, &textRect,
848
+ DT_SINGLELINE | DT_VCENTER | DT_LEFT | DT_NOPREFIX | DT_END_ELLIPSIS);
849
+ RECT closeRect = {client.right - closeWidth, client.top, client.right, client.bottom};
850
+ SetTextColor(dc, RGB(150, 155, 165));
851
+ DrawTextW(dc, L"✕", -1, &closeRect, DT_SINGLELINE | DT_VCENTER | DT_CENTER | DT_NOPREFIX);
852
+ if (font != nullptr) {
853
+ SelectObject(dc, oldFont);
854
+ DeleteObject(font);
855
+ }
856
+ EndPaint(hwnd, &paint);
857
+ }
858
+ return 0;
859
+ }
860
+ case WM_LBUTTONDOWN: {
861
+ const int x = GET_X_LPARAM(lparam);
862
+ RECT client = {};
863
+ GetClientRect(hwnd, &client);
864
+ const int closeWidth = MulDiv(48, static_cast<int>(WindowDpi(hwnd)), 96);
865
+ if (x >= client.right - closeWidth) {
866
+ if (app != nullptr) app->RequestExit(0);
867
+ } else {
868
+ ReleaseCapture();
869
+ SendMessageW(GetParent(hwnd), WM_NCLBUTTONDOWN, HTCAPTION, 0);
870
+ }
871
+ return 0;
872
+ }
873
+ case WM_RBUTTONUP: {
874
+ HMENU menu = CreatePopupMenu();
875
+ if (menu == nullptr) return 0;
876
+ AppendMenuW(menu, MF_STRING, kMenuExit, L"退出摸鱼(恢复主窗口)");
877
+ AppendMenuW(menu, MF_STRING, kMenuResetFrame, L"重置窗口位置和大小");
878
+ POINT cursor;
879
+ GetCursorPos(&cursor);
880
+ HWND parent = GetParent(hwnd);
881
+ const int command = static_cast<int>(TrackPopupMenu(
882
+ menu, TPM_RETURNCMD | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, parent, nullptr));
883
+ DestroyMenu(menu);
884
+ if (command != 0 && parent != nullptr) {
885
+ PostMessageW(parent, kMsgStripMenu, static_cast<WPARAM>(command), 0);
886
+ }
887
+ return 0;
888
+ }
889
+ case WM_SETCURSOR:
890
+ SetCursor(LoadCursorW(nullptr, IDC_ARROW));
891
+ return TRUE;
892
+ default:
893
+ return DefWindowProcW(hwnd, message, wparam, lparam);
894
+ }
895
+ }
896
+
897
+ bool FloatApp::RegisterWindowClasses() {
898
+ static bool registered = false;
899
+ if (registered) return true;
900
+
901
+ WNDCLASSEXW mainClass = {};
902
+ mainClass.cbSize = sizeof(mainClass);
903
+ mainClass.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
904
+ mainClass.lpfnWndProc = &FloatApp::MainWndProc;
905
+ mainClass.hInstance = g_instance;
906
+ mainClass.hCursor = LoadCursorW(nullptr, IDC_ARROW);
907
+ mainClass.hbrBackground = CreateSolidBrush(kBackgroundColor);
908
+ mainClass.lpszClassName = kMainWindowClass;
909
+ if (RegisterClassExW(&mainClass) == 0) {
910
+ LogFmt(L"register-main-class-failed err=%lu", static_cast<unsigned long>(GetLastError()));
911
+ return false;
912
+ }
913
+
914
+ WNDCLASSEXW stripClass = {};
915
+ stripClass.cbSize = sizeof(stripClass);
916
+ stripClass.style = CS_HREDRAW | CS_VREDRAW;
917
+ stripClass.lpfnWndProc = &FloatApp::StripWndProc;
918
+ stripClass.hInstance = g_instance;
919
+ stripClass.hCursor = LoadCursorW(nullptr, IDC_ARROW);
920
+ stripClass.lpszClassName = kStripWindowClass;
921
+ if (RegisterClassExW(&stripClass) == 0) {
922
+ LogFmt(L"register-strip-class-failed err=%lu", static_cast<unsigned long>(GetLastError()));
923
+ return false;
924
+ }
925
+ registered = true;
926
+ return true;
927
+ }
928
+
929
+ bool FloatApp::ParseCommandLine(const std::wstring& jsonText) {
930
+ std::wstring error;
931
+ if (!ParsePayloadJson(jsonText, &payload_, &error)) {
932
+ LogFmt(L"payload-parse-failed %s", error.c_str());
933
+ return false;
934
+ }
935
+ if (!ValidatePayload(payload_, &error)) {
936
+ LogFmt(L"payload-invalid %s", error.c_str());
937
+ return false;
938
+ }
939
+ LogFmt(L"payload-ok ciProbe=%d follow=%d followPid=%lu ownerPid=%lu cookie=%s authUrl=%s "
940
+ L"controlPath=%s build=%s alpha=%d hasState=%d",
941
+ payload_.ciProbe ? 1 : 0, payload_.hasFollow ? 1 : 0,
942
+ static_cast<unsigned long>(payload_.followPid),
943
+ static_cast<unsigned long>(payload_.ownerPid),
944
+ payload_.cookie.empty() ? L"no" : L"yes",
945
+ payload_.authUrl.empty() ? L"no" : L"yes",
946
+ payload_.controlPath.c_str(), payload_.build.c_str(), payload_.alpha,
947
+ payload_.hasState ? 1 : 0);
948
+ return true;
949
+ }
950
+
951
+ void FloatApp::ClampInitialRect(RECT* rect) {
952
+ if (rect == nullptr) return;
953
+ const int width = rect->right - rect->left;
954
+ const int height = rect->bottom - rect->top;
955
+ const int minimumWidth = DpiScale(nullptr, 320);
956
+ const int minimumHeight = DpiScale(nullptr, 240);
957
+ if (width < minimumWidth) rect->right = rect->left + minimumWidth;
958
+ if (height < minimumHeight) rect->bottom = rect->top + minimumHeight;
959
+ ClampRectToVirtualScreen(rect);
960
+ }
961
+
962
+ bool FloatApp::CreateMainWindow() {
963
+ if (!RegisterWindowClasses()) return false;
964
+
965
+ RECT initial = {};
966
+ bool hasInitial = false;
967
+ if (payload_.ciProbe) {
968
+ initial = {0, 0, 800, 600};
969
+ hasInitial = true;
970
+ } else {
971
+ if (payload_.hasFollow) {
972
+ followWindow_ = FindFollowWindowForProcess(payload_.followPid, payload_.followTitle);
973
+ if (followWindow_ != nullptr) {
974
+ RECT targetRect = {};
975
+ if (GetVisibleWindowRect(followWindow_, &targetRect)) {
976
+ initial = targetRect;
977
+ hasInitial = true;
978
+ }
979
+ }
980
+ }
981
+ if (!hasInitial && !payload_.hasFollow) {
982
+ RECT saved = {};
983
+ if (LoadSavedFrame(&saved)) {
984
+ initial = saved;
985
+ hasInitial = true;
986
+ }
987
+ }
988
+ if (!hasInitial) {
989
+ RECT workArea = {};
990
+ if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &workArea, 0)) {
991
+ workArea.left = 0;
992
+ workArea.top = 0;
993
+ workArea.right = GetSystemMetrics(SM_CXSCREEN);
994
+ workArea.bottom = GetSystemMetrics(SM_CYSCREEN);
995
+ }
996
+ const UINT dpi = WindowDpi(nullptr);
997
+ int width = MulDiv(1180, static_cast<int>(dpi), 96);
998
+ int height = MulDiv(820, static_cast<int>(dpi), 96);
999
+ const int workWidth = workArea.right - workArea.left;
1000
+ const int workHeight = workArea.bottom - workArea.top;
1001
+ if (workWidth > 0 && width > workWidth * 9 / 10) width = workWidth * 9 / 10;
1002
+ if (workHeight > 0 && height > workHeight * 9 / 10) height = workHeight * 9 / 10;
1003
+ initial.left = workArea.left + (workWidth - width) / 2;
1004
+ initial.top = workArea.top + (workHeight - height) / 2;
1005
+ initial.right = initial.left + width;
1006
+ initial.bottom = initial.top + height;
1007
+ hasInitial = true;
1008
+ }
1009
+ ClampInitialRect(&initial);
1010
+ }
1011
+
1012
+ const DWORD extendedStyle = WS_EX_TOPMOST | WS_EX_TOOLWINDOW;
1013
+ const DWORD style = WS_POPUP | WS_THICKFRAME | WS_CLIPCHILDREN;
1014
+ hwnd_ = CreateWindowExW(extendedStyle, kMainWindowClass, kWindowTitle, style, initial.left,
1015
+ initial.top, initial.right - initial.left,
1016
+ initial.bottom - initial.top, nullptr, nullptr, g_instance, this);
1017
+ if (hwnd_ == nullptr) {
1018
+ LogFmt(L"create-main-window-failed err=%lu", static_cast<unsigned long>(GetLastError()));
1019
+ return false;
1020
+ }
1021
+
1022
+ RECT client = {};
1023
+ GetClientRect(hwnd_, &client);
1024
+ const int stripHeight = DpiScale(hwnd_, kDragStripDip);
1025
+ strip_ = CreateWindowExW(0, kStripWindowClass, L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 0,
1026
+ 0, client.right - client.left, stripHeight, hwnd_, nullptr, g_instance,
1027
+ nullptr);
1028
+ if (strip_ == nullptr) {
1029
+ LogFmt(L"create-strip-window-failed err=%lu", static_cast<unsigned long>(GetLastError()));
1030
+ }
1031
+ LayoutChildren();
1032
+
1033
+ if (payload_.ciProbe) {
1034
+ ShowWindow(hwnd_, SW_HIDE);
1035
+ } else {
1036
+ ShowWindow(hwnd_, SW_SHOWNOACTIVATE);
1037
+ UpdateWindow(hwnd_);
1038
+ }
1039
+
1040
+ LogFmt(L"main-window-created rect=(%ld,%ld)-(%ld,%ld) dpi=%u ciProbe=%d",
1041
+ static_cast<long>(initial.left), static_cast<long>(initial.top),
1042
+ static_cast<long>(initial.right), static_cast<long>(initial.bottom),
1043
+ WindowDpi(hwnd_), payload_.ciProbe ? 1 : 0);
1044
+ return true;
1045
+ }
1046
+
1047
+ void FloatApp::Start() {
1048
+ if (started_) return;
1049
+ started_ = true;
1050
+ if (!payload_.ciProbe) {
1051
+ const DWORD directParent = ParentProcessId(GetCurrentProcessId());
1052
+ hostProcess_ = OpenProcess(SYNCHRONIZE, FALSE, directParent);
1053
+ if (hostProcess_ == nullptr) Log(L"host-process-handle-unavailable");
1054
+ if (payload_.hasFollow) {
1055
+ if (followWindow_ == nullptr) {
1056
+ followWindow_ = FindFollowWindowForProcess(payload_.followPid, payload_.followTitle);
1057
+ }
1058
+ if (followWindow_ != nullptr) ForceForeground(followWindow_);
1059
+ SetTimer(hwnd_, kTimerFollow, kFollowIntervalMs, nullptr);
1060
+ }
1061
+ SetTimer(hwnd_, kTimerHideDsh, 450, nullptr);
1062
+ SetTimer(hwnd_, kTimerControl, kControlIntervalMs, nullptr);
1063
+ } else {
1064
+ SetTimer(hwnd_, kTimerProbeWatchdog, kProbeWatchdogMs, nullptr);
1065
+ }
1066
+ CreateWebViewEnvironment();
1067
+ }
1068
+
1069
+ int FloatApp::RunMessageLoop() {
1070
+ MSG message;
1071
+ for (;;) {
1072
+ const int result = GetMessageW(&message, nullptr, 0, 0);
1073
+ if (result == 0) return static_cast<int>(message.wParam);
1074
+ if (result == -1) {
1075
+ LogFmt(L"getmessage-failed err=%lu", static_cast<unsigned long>(GetLastError()));
1076
+ return 0;
1077
+ }
1078
+ TranslateMessage(&message);
1079
+ DispatchMessageW(&message);
1080
+ }
1081
+ }
1082
+
1083
+ void FloatApp::RequestExit(int exitCode) {
1084
+ exitCode_ = exitCode;
1085
+ if (exiting_) return;
1086
+ exiting_ = true;
1087
+ if (hwnd_ != nullptr) {
1088
+ PostMessageW(hwnd_, kMsgExitGraceful, 0, 0);
1089
+ } else {
1090
+ PostQuitMessage(exitCode);
1091
+ }
1092
+ }
1093
+
1094
+ void FloatApp::LayoutChildren() {
1095
+ if (hwnd_ == nullptr) return;
1096
+ RECT client = {};
1097
+ if (!GetClientRect(hwnd_, &client)) return;
1098
+ const int width = client.right - client.left;
1099
+ const int height = client.bottom - client.top;
1100
+ const int border = DpiScale(hwnd_, kResizeBorderDip);
1101
+ const int stripHeight = DpiScale(hwnd_, kDragStripDip);
1102
+ if (strip_ != nullptr) {
1103
+ SetWindowPos(strip_, HWND_TOP, 0, 0, width, stripHeight,
1104
+ SWP_NOACTIVATE | SWP_SHOWWINDOW);
1105
+ }
1106
+ if (controller_.Get() != nullptr) {
1107
+ RECT bounds = {};
1108
+ bounds.left = border;
1109
+ bounds.top = 0;
1110
+ bounds.right = width - border;
1111
+ bounds.bottom = height - border;
1112
+ if (bounds.right - bounds.left < 100) bounds.right = bounds.left + 100;
1113
+ if (bounds.bottom - bounds.top < 100) bounds.bottom = bounds.top + 100;
1114
+ controller_->put_Bounds(bounds);
1115
+ }
1116
+ }
1117
+
1118
+ void FloatApp::RaiseStrip() {
1119
+ if (strip_ == nullptr) return;
1120
+ SetWindowPos(strip_, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
1121
+ }
1122
+
1123
+ LRESULT FloatApp::HandleNcHitTest(HWND hwnd, LPARAM lparam) {
1124
+ POINT point;
1125
+ point.x = GET_X_LPARAM(lparam);
1126
+ point.y = GET_Y_LPARAM(lparam);
1127
+ RECT windowRect = {};
1128
+ if (!GetWindowRect(hwnd, &windowRect)) return HTCLIENT;
1129
+ const int border = DpiScale(hwnd, kResizeBorderDip);
1130
+ const bool left = point.x < windowRect.left + border;
1131
+ const bool right = point.x >= windowRect.right - border;
1132
+ const bool top = point.y < windowRect.top + border;
1133
+ const bool bottom = point.y >= windowRect.bottom - border;
1134
+ if (left && top) return HTTOPLEFT;
1135
+ if (right && top) return HTTOPRIGHT;
1136
+ if (left && bottom) return HTBOTTOMLEFT;
1137
+ if (right && bottom) return HTBOTTOMRIGHT;
1138
+ if (left) return HTLEFT;
1139
+ if (right) return HTRIGHT;
1140
+ if (top) return HTTOP;
1141
+ if (bottom) return HTBOTTOM;
1142
+ return HTCLIENT;
1143
+ }
1144
+
1145
+ void FloatApp::HandleMinMaxInfo(MINMAXINFO* info) {
1146
+ if (info == nullptr) return;
1147
+ const UINT dpi = WindowDpi(hwnd_);
1148
+ info->ptMinTrackSize.x = MulDiv(520, static_cast<int>(dpi), 96);
1149
+ info->ptMinTrackSize.y = MulDiv(360, static_cast<int>(dpi), 96);
1150
+ }
1151
+
1152
+ std::wstring FloatApp::FrameFilePath() {
1153
+ const std::wstring base = GetBaseDataDirectory();
1154
+ if (base.empty()) return std::wstring();
1155
+ EnsureDirectoryExists(base);
1156
+ return base + L"\\frame.ini";
1157
+ }
1158
+
1159
+ bool FloatApp::LoadSavedFrame(RECT* frame) {
1160
+ if (frame == nullptr) return false;
1161
+ const std::wstring path = FrameFilePath();
1162
+ if (path.empty()) return false;
1163
+ HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ,
1164
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1165
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
1166
+ if (handle == INVALID_HANDLE_VALUE) return false;
1167
+ char buffer[256] = {};
1168
+ DWORD read = 0;
1169
+ const BOOL ok = ReadFile(handle, buffer, static_cast<DWORD>(sizeof(buffer) - 1), &read, nullptr);
1170
+ CloseHandle(handle);
1171
+ if (!ok || read == 0) return false;
1172
+ long values[4] = {0, 0, 0, 0};
1173
+ if (sscanf_s(buffer, "%ld %ld %ld %ld", &values[0], &values[1], &values[2], &values[3]) != 4) {
1174
+ return false;
1175
+ }
1176
+ if (values[2] - values[0] < 200 || values[3] - values[1] < 150) return false;
1177
+ frame->left = values[0];
1178
+ frame->top = values[1];
1179
+ frame->right = values[2];
1180
+ frame->bottom = values[3];
1181
+ ClampRectToVirtualScreen(frame);
1182
+ return true;
1183
+ }
1184
+
1185
+ void FloatApp::SaveFrameIfNeeded() {
1186
+ if (payload_.hasFollow || payload_.ciProbe || hwnd_ == nullptr) return;
1187
+ RECT rect = {};
1188
+ if (!GetWindowRect(hwnd_, &rect)) return;
1189
+ const std::wstring path = FrameFilePath();
1190
+ if (path.empty()) return;
1191
+ char buffer[256];
1192
+ const int length = sprintf_s(buffer, sizeof(buffer), "%ld %ld %ld %ld\n",
1193
+ static_cast<long>(rect.left), static_cast<long>(rect.top),
1194
+ static_cast<long>(rect.right), static_cast<long>(rect.bottom));
1195
+ if (length <= 0) return;
1196
+ HANDLE handle = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
1197
+ FILE_ATTRIBUTE_NORMAL, nullptr);
1198
+ if (handle == INVALID_HANDLE_VALUE) return;
1199
+ DWORD written = 0;
1200
+ WriteFile(handle, buffer, static_cast<DWORD>(length), &written, nullptr);
1201
+ CloseHandle(handle);
1202
+ }
1203
+
1204
+ void FloatApp::ResetWindowFrame() {
1205
+ if (hwnd_ == nullptr) return;
1206
+ RECT workArea = {};
1207
+ if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &workArea, 0)) return;
1208
+ const UINT dpi = WindowDpi(hwnd_);
1209
+ int width = MulDiv(1180, static_cast<int>(dpi), 96);
1210
+ int height = MulDiv(820, static_cast<int>(dpi), 96);
1211
+ const int workWidth = workArea.right - workArea.left;
1212
+ const int workHeight = workArea.bottom - workArea.top;
1213
+ if (workWidth > 0 && width > workWidth * 9 / 10) width = workWidth * 9 / 10;
1214
+ if (workHeight > 0 && height > workHeight * 9 / 10) height = workHeight * 9 / 10;
1215
+ const int left = workArea.left + (workWidth - width) / 2;
1216
+ const int top = workArea.top + (workHeight - height) / 2;
1217
+ SetWindowPos(hwnd_, nullptr, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
1218
+ LayoutChildren();
1219
+ Log(L"window-frame-reset");
1220
+ }
1221
+
1222
+ void FloatApp::OnTimer(UINT_PTR timerId) {
1223
+ switch (timerId) {
1224
+ case kTimerFollow:
1225
+ OnFollowTimer();
1226
+ break;
1227
+ case kTimerControl:
1228
+ OnControlTimer();
1229
+ break;
1230
+ case kTimerHideDsh:
1231
+ KillTimer(hwnd_, kTimerHideDsh);
1232
+ OnHideDshTimer();
1233
+ break;
1234
+ case kTimerProbeTimeout:
1235
+ KillTimer(hwnd_, kTimerProbeTimeout);
1236
+ Log(L"ciprobe-timeout");
1237
+ FinishProbe(false);
1238
+ break;
1239
+ case kTimerProbeWatchdog:
1240
+ KillTimer(hwnd_, kTimerProbeWatchdog);
1241
+ Log(L"ciprobe-watchdog-timeout");
1242
+ FinishProbeFailure();
1243
+ break;
1244
+ case kTimerPageProbe:
1245
+ KillTimer(hwnd_, kTimerPageProbe);
1246
+ OnPageProbeTimer();
1247
+ break;
1248
+ case kTimerSelftest:
1249
+ KillTimer(hwnd_, kTimerSelftest);
1250
+ OnSelftestTimer();
1251
+ break;
1252
+ case kTimerRetry:
1253
+ KillTimer(hwnd_, kTimerRetry);
1254
+ if (!exiting_ && webView_.Get() != nullptr && phase_ == Phase::App && !appLoaded_ &&
1255
+ !floatUrl_.empty()) {
1256
+ webView_->Navigate(floatUrl_.c_str());
1257
+ }
1258
+ break;
1259
+ default:
1260
+ break;
1261
+ }
1262
+ }
1263
+
1264
+ void FloatApp::KillAllTimers() {
1265
+ if (hwnd_ == nullptr) return;
1266
+ KillTimer(hwnd_, kTimerFollow);
1267
+ KillTimer(hwnd_, kTimerControl);
1268
+ KillTimer(hwnd_, kTimerHideDsh);
1269
+ KillTimer(hwnd_, kTimerProbeTimeout);
1270
+ KillTimer(hwnd_, kTimerProbeWatchdog);
1271
+ KillTimer(hwnd_, kTimerSelftest);
1272
+ KillTimer(hwnd_, kTimerPageProbe);
1273
+ KillTimer(hwnd_, kTimerRetry);
1274
+ }
1275
+
1276
+ void FloatApp::OnFollowTimer() {
1277
+ if (exiting_) return;
1278
+ ApplyFollowFrame();
1279
+ }
1280
+
1281
+ void FloatApp::ApplyFollowFrame() {
1282
+ if (exiting_ || !payload_.hasFollow) return;
1283
+ HWND target = FindFollowWindowForProcess(payload_.followPid, payload_.followTitle);
1284
+ if (target == nullptr) {
1285
+ followMissCount_ += 1;
1286
+ if (followMissCount_ == 1) Log(L"follow-target-missing keep-last-frame");
1287
+ if (followMissCount_ > 1200) { // 约 5 分钟都找不到目标 → 降级为自由悬浮
1288
+ KillTimer(hwnd_, kTimerFollow);
1289
+ Log(L"follow-stopped-target-gone");
1290
+ }
1291
+ return;
1292
+ }
1293
+ followMissCount_ = 0;
1294
+ RECT targetRect = {};
1295
+ if (!GetVisibleWindowRect(target, &targetRect)) return;
1296
+ const int width = targetRect.right - targetRect.left;
1297
+ const int height = targetRect.bottom - targetRect.top;
1298
+ if (width < 80 || height < 60 || width > 20000 || height > 20000) return;
1299
+ if (!hasLastFollowRect_ || !RectsEqual(lastFollowRect_, targetRect)) {
1300
+ lastFollowRect_ = targetRect;
1301
+ hasLastFollowRect_ = true;
1302
+ SetWindowPos(hwnd_, HWND_TOPMOST, targetRect.left, targetRect.top, width, height,
1303
+ SWP_NOACTIVATE | SWP_SHOWWINDOW);
1304
+ if (controller_.Get() != nullptr) controller_->NotifyParentWindowPositionChanged();
1305
+ RaiseStrip();
1306
+ LogFmt(L"follow-apply rect=(%ld,%ld)-(%ld,%ld)",
1307
+ static_cast<long>(targetRect.left), static_cast<long>(targetRect.top),
1308
+ static_cast<long>(targetRect.right), static_cast<long>(targetRect.bottom));
1309
+ }
1310
+ if (!followActivated_ || target != followWindow_) {
1311
+ followWindow_ = target;
1312
+ followActivated_ = true;
1313
+ ForceForeground(target);
1314
+ Log(L"follow-activated");
1315
+ }
1316
+ }
1317
+
1318
+ void FloatApp::OnHideDshTimer() {
1319
+ HideDshWindows();
1320
+ }
1321
+
1322
+ void FloatApp::HideDshWindows() {
1323
+ if (exiting_ || payload_.ciProbe) return;
1324
+ const std::vector<HWND> windows = FindDshWindows(payload_.ownerPid);
1325
+ std::size_t hiddenCount = 0;
1326
+ for (HWND hwnd : windows) {
1327
+ if (hwnd == nullptr || !IsWindow(hwnd) || !IsWindowVisible(hwnd)) continue;
1328
+ if (IsIconic(hwnd)) continue; // 已经最小化:保持用户原状态,不改成 SW_HIDE
1329
+ ShowWindowAsync(hwnd, SW_HIDE);
1330
+ AppendUniqueWindow(&hiddenDshWindows_, hwnd);
1331
+ hiddenCount += 1;
1332
+ }
1333
+ g_crashRestoreWindows = hiddenDshWindows_;
1334
+ LogFmt(L"dsh-hidden hidden=%zu candidates=%zu", hiddenCount, windows.size());
1335
+ if (followWindow_ != nullptr && IsWindow(followWindow_)) ForceForeground(followWindow_);
1336
+ }
1337
+
1338
+ void FloatApp::RestoreDshWindows() {
1339
+ if (!hiddenDshWindows_.empty()) {
1340
+ LogFmt(L"dsh-restore count=%zu", hiddenDshWindows_.size());
1341
+ for (HWND hwnd : hiddenDshWindows_) {
1342
+ if (hwnd != nullptr && IsWindow(hwnd)) ShowWindowAsync(hwnd, SW_SHOW);
1343
+ }
1344
+ hiddenDshWindows_.clear();
1345
+ }
1346
+ g_crashRestoreWindows.clear();
1347
+ const std::vector<HWND> windows = FindDshWindows(payload_.ownerPid);
1348
+ if (!windows.empty() && windows.front() != nullptr && IsWindow(windows.front())) {
1349
+ HWND target = windows.front();
1350
+ if (IsIconic(target)) ShowWindowAsync(target, SW_RESTORE);
1351
+ ShowWindowAsync(target, SW_SHOW);
1352
+ ForceForeground(target);
1353
+ LogFmt(L"dsh-restored focus=%p", reinterpret_cast<void*>(target));
1354
+ }
1355
+ }
1356
+
1357
+ void FloatApp::DeleteControlFile() {
1358
+ if (payload_.controlPath.empty()) return;
1359
+ DeleteFileW(payload_.controlPath.c_str());
1360
+ }
1361
+
1362
+ void FloatApp::OnControlTimer() {
1363
+ if (exiting_) return;
1364
+ RaiseStrip();
1365
+ if (!payload_.controlPath.empty()) {
1366
+ const DWORD attributes = GetFileAttributesW(payload_.controlPath.c_str());
1367
+ if (attributes != INVALID_FILE_ATTRIBUTES) {
1368
+ Log(L"control-file-detected");
1369
+ DeleteControlFile();
1370
+ RequestExit(0);
1371
+ return;
1372
+ }
1373
+ }
1374
+ if (hostProcess_ != nullptr && WaitForSingleObject(hostProcess_, 0) == WAIT_OBJECT_0) {
1375
+ Log(L"host-process-exited");
1376
+ RequestExit(0);
1377
+ }
1378
+ }
1379
+
1380
+ /* ────────────────────────────── WebView2 ────────────────────────────── */
1381
+
1382
+ void FloatApp::CreateWebViewEnvironment() {
1383
+ if (exiting_) return;
1384
+ const std::wstring baseDirectory = GetBaseDataDirectory();
1385
+ EnsureDirectoryExists(baseDirectory);
1386
+ std::wstring profileName = L"webview2-";
1387
+ if (!payload_.build.empty()) {
1388
+ for (const wchar_t c : payload_.build) {
1389
+ if (std::iswalnum(c) || c == L'.' || c == L'-' || c == L'_') profileName.push_back(c);
1390
+ }
1391
+ }
1392
+ if (profileName.size() <= 10) profileName += L"default";
1393
+ if (envAttempt_ > 0) {
1394
+ profileName = L"webview2-retry-" + std::to_wstring(GetCurrentProcessId()) + L"-" +
1395
+ std::to_wstring(GetTickCount64());
1396
+ }
1397
+ userDataFolder_ = baseDirectory.empty() ? std::wstring() : baseDirectory + L"\\" + profileName;
1398
+ if (!userDataFolder_.empty()) EnsureDirectoryExists(userDataFolder_);
1399
+
1400
+ LogFmt(L"webview2-env-create attempt=%d folder=%s", envAttempt_, userDataFolder_.c_str());
1401
+ ComPtr<CoreWebView2EnvironmentOptions> options =
1402
+ Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
1403
+ if (options.Get() != nullptr) {
1404
+ // 显式把「要求的 Runtime 最低版本」降到 WebView2 GA 版本 86.0.616.0:
1405
+ // 本 helper 只用到 86~94 时代的 API,并且对 CookieManager / Controller2 做了
1406
+ // QueryInterface 降级;这样用户机器上的 Evergreen Runtime 稍旧也能启动,
1407
+ // 而不是直接创建失败(默认值等于 SDK 版本 129.x)。
1408
+ options->put_TargetCompatibleBrowserVersion(L"86.0.616.0");
1409
+ if (payload_.ciProbe) {
1410
+ // CI 的 runner 可能没有可用 GPU:强制软件渲染,避免 ciProbe 卡住。
1411
+ options->put_AdditionalBrowserArguments(L"--disable-gpu");
1412
+ }
1413
+ }
1414
+ const HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(
1415
+ nullptr, userDataFolder_.empty() ? nullptr : userDataFolder_.c_str(),
1416
+ options.Get(),
1417
+ Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
1418
+ [this](HRESULT errorCode, ICoreWebView2Environment* environment) -> HRESULT {
1419
+ OnEnvironmentCreated(errorCode, environment);
1420
+ return S_OK;
1421
+ })
1422
+ .Get());
1423
+ if (FAILED(hr)) {
1424
+ LogFmt(L"webview2-env-call-failed hr=%08lX", static_cast<unsigned long>(hr));
1425
+ HandleWebViewEnvironmentFailure(hr);
1426
+ }
1427
+ }
1428
+
1429
+ void FloatApp::OnEnvironmentCreated(HRESULT errorCode, ICoreWebView2Environment* environment) {
1430
+ if (exiting_) return;
1431
+ if (FAILED(errorCode) || environment == nullptr) {
1432
+ LogFmt(L"webview2-env-failed hr=%08lX", static_cast<unsigned long>(errorCode));
1433
+ if (envAttempt_ == 0) {
1434
+ envAttempt_ = 1;
1435
+ CreateWebViewEnvironment();
1436
+ return;
1437
+ }
1438
+ HandleWebViewEnvironmentFailure(errorCode);
1439
+ return;
1440
+ }
1441
+ // 回调传进来的是「借」的 COM 指针:显式 AddRef 后再由 ComPtr 接管,
1442
+ // 避免依赖 ComPtr 的隐式转换/模板推导(MSVC 下 &ComPtr 是 ComPtrRef)。
1443
+ environment_.Reset();
1444
+ if (environment != nullptr) {
1445
+ environment->AddRef();
1446
+ environment_.Attach(environment);
1447
+ }
1448
+ Log(L"webview2-env-ready");
1449
+ const HRESULT hr = environment_->CreateCoreWebView2Controller(
1450
+ hwnd_,
1451
+ Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
1452
+ [this](HRESULT controllerError, ICoreWebView2Controller* controller) -> HRESULT {
1453
+ OnControllerCreated(controllerError, controller);
1454
+ return S_OK;
1455
+ })
1456
+ .Get());
1457
+ if (FAILED(hr)) {
1458
+ LogFmt(L"create-controller-call-failed hr=%08lX", static_cast<unsigned long>(hr));
1459
+ HandleWebViewEnvironmentFailure(hr);
1460
+ }
1461
+ }
1462
+
1463
+ void FloatApp::OnControllerCreated(HRESULT errorCode, ICoreWebView2Controller* controller) {
1464
+ if (exiting_) return;
1465
+ if (FAILED(errorCode) || controller == nullptr) {
1466
+ LogFmt(L"webview2-controller-failed hr=%08lX", static_cast<unsigned long>(errorCode));
1467
+ HandleWebViewEnvironmentFailure(errorCode);
1468
+ return;
1469
+ }
1470
+ controller_.Reset();
1471
+ if (controller != nullptr) {
1472
+ controller->AddRef();
1473
+ controller_.Attach(controller);
1474
+ }
1475
+ const HRESULT hr = controller_->get_CoreWebView2(webView_.GetAddressOf());
1476
+ if (FAILED(hr) || webView_.Get() == nullptr) {
1477
+ LogFmt(L"get-core-webview-failed hr=%08lX", static_cast<unsigned long>(hr));
1478
+ HandleWebViewEnvironmentFailure(hr);
1479
+ return;
1480
+ }
1481
+ controllerReady_ = true;
1482
+ Log(L"webview2-controller-ready");
1483
+ ConfigureWebView();
1484
+ LayoutChildren();
1485
+ StartScriptInjection();
1486
+ }
1487
+
1488
+ void FloatApp::ConfigureWebView() {
1489
+ if (webView_.Get() == nullptr) return;
1490
+ ComPtr<ICoreWebView2Settings> settings;
1491
+ if (SUCCEEDED(webView_->get_Settings(settings.GetAddressOf())) &&
1492
+ settings.Get() != nullptr) {
1493
+ settings->put_IsStatusBarEnabled(FALSE);
1494
+ settings->put_AreDevToolsEnabled(FALSE);
1495
+ settings->put_IsZoomControlEnabled(FALSE);
1496
+ }
1497
+ ComPtr<ICoreWebView2Controller2> controller2;
1498
+ if (SUCCEEDED(controller_->QueryInterface(IID_PPV_ARGS(controller2.GetAddressOf()))) &&
1499
+ controller2.Get() != nullptr) {
1500
+ COREWEBVIEW2_COLOR background;
1501
+ background.A = 255;
1502
+ background.R = 13;
1503
+ background.G = 15;
1504
+ background.B = 19;
1505
+ controller2->put_DefaultBackgroundColor(background);
1506
+ }
1507
+ controller_->put_IsVisible(TRUE);
1508
+
1509
+ EventRegistrationToken token = {};
1510
+ webView_->add_NavigationCompleted(
1511
+ Callback<ICoreWebView2NavigationCompletedEventHandler>(
1512
+ [this](ICoreWebView2* sender, ICoreWebView2NavigationCompletedEventArgs* args)
1513
+ -> HRESULT {
1514
+ (void)sender;
1515
+ BOOL success = FALSE;
1516
+ if (args != nullptr) args->get_IsSuccess(&success);
1517
+ OnNavigationCompleted(success != FALSE);
1518
+ return S_OK;
1519
+ })
1520
+ .Get(),
1521
+ &token);
1522
+ webView_->add_NewWindowRequested(
1523
+ Callback<ICoreWebView2NewWindowRequestedEventHandler>(
1524
+ [this](ICoreWebView2* sender, ICoreWebView2NewWindowRequestedEventArgs* args)
1525
+ -> HRESULT {
1526
+ (void)sender;
1527
+ OnNewWindowRequested(args);
1528
+ return S_OK;
1529
+ })
1530
+ .Get(),
1531
+ &token);
1532
+ webView_->add_ProcessFailed(
1533
+ Callback<ICoreWebView2ProcessFailedEventHandler>(
1534
+ [this](ICoreWebView2* sender, ICoreWebView2ProcessFailedEventArgs* args) -> HRESULT {
1535
+ (void)sender;
1536
+ OnProcessFailed(args);
1537
+ return S_OK;
1538
+ })
1539
+ .Get(),
1540
+ &token);
1541
+ }
1542
+
1543
+ void FloatApp::StartScriptInjection() {
1544
+ if (webView_.Get() == nullptr) return;
1545
+ const std::wstring script = BuildBootstrapScript(payload_);
1546
+ LogFmt(L"inject-script length=%zu", script.size());
1547
+ const HRESULT hr = webView_->AddScriptToExecuteOnDocumentCreated(
1548
+ script.c_str(),
1549
+ Callback<ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler>(
1550
+ [this](HRESULT errorCode, LPCWSTR scriptId) -> HRESULT {
1551
+ (void)scriptId;
1552
+ OnScriptRegistered(errorCode, scriptId);
1553
+ return S_OK;
1554
+ })
1555
+ .Get());
1556
+ if (FAILED(hr)) {
1557
+ LogFmt(L"inject-script-call-failed hr=%08lX", static_cast<unsigned long>(hr));
1558
+ OnScriptRegistered(hr, nullptr);
1559
+ }
1560
+ }
1561
+
1562
+ void FloatApp::OnScriptRegistered(HRESULT errorCode, LPCWSTR scriptId) {
1563
+ (void)scriptId;
1564
+ if (exiting_) return;
1565
+ if (FAILED(errorCode)) {
1566
+ LogFmt(L"inject-script-failed hr=%08lX", static_cast<unsigned long>(errorCode));
1567
+ } else {
1568
+ Log(L"inject-script-ready");
1569
+ }
1570
+ BeginNavigation();
1571
+ }
1572
+
1573
+ void FloatApp::BeginNavigation() {
1574
+ if (exiting_ || webView_.Get() == nullptr) return;
1575
+ floatUrl_ = AppendFloatQuery(payload_.appUrl);
1576
+ if (payload_.ciProbe) {
1577
+ Log(L"ciprobe-navigate");
1578
+ if (!payload_.appUrl.empty()) {
1579
+ webView_->Navigate(payload_.appUrl.c_str());
1580
+ } else {
1581
+ webView_->NavigateToString(
1582
+ L"<html><head><meta charset=\"utf-8\"><title>gufa-float-ci</title></head>"
1583
+ L"<body>gufa-float ciProbe</body></html>");
1584
+ }
1585
+ SetTimer(hwnd_, kTimerProbeTimeout, kProbeTimeoutMs, nullptr);
1586
+ return;
1587
+ }
1588
+ if (!payload_.cookie.empty()) {
1589
+ InjectCookieThenNavigate(floatUrl_);
1590
+ return;
1591
+ }
1592
+ if (!payload_.authUrl.empty()) {
1593
+ phase_ = Phase::Auth;
1594
+ Log(L"navigate-auth");
1595
+ webView_->Navigate(payload_.authUrl.c_str());
1596
+ return;
1597
+ }
1598
+ Log(L"no-url-configured");
1599
+ RequestExit(2);
1600
+ }
1601
+
1602
+ void FloatApp::InjectCookieThenNavigate(const std::wstring& targetUrl) {
1603
+ bool injected = false;
1604
+ do {
1605
+ const std::size_t separator = payload_.cookie.find(L'=');
1606
+ if (separator == std::wstring::npos) break;
1607
+ const std::wstring name = payload_.cookie.substr(0, separator);
1608
+ const std::wstring value = payload_.cookie.substr(separator + 1);
1609
+ if (name.empty() || value.empty()) break;
1610
+ const std::wstring host = ExtractUrlHost(payload_.appUrl);
1611
+ if (host.empty()) break;
1612
+ ComPtr<ICoreWebView2_2> webView2;
1613
+ if (FAILED(webView_->QueryInterface(IID_PPV_ARGS(webView2.GetAddressOf()))) ||
1614
+ webView2.Get() == nullptr) {
1615
+ break;
1616
+ }
1617
+ ComPtr<ICoreWebView2CookieManager> cookieManager;
1618
+ if (FAILED(webView2->get_CookieManager(cookieManager.GetAddressOf())) ||
1619
+ cookieManager.Get() == nullptr) {
1620
+ break;
1621
+ }
1622
+ ComPtr<ICoreWebView2Cookie> cookie;
1623
+ if (FAILED(cookieManager->CreateCookie(name.c_str(), value.c_str(), host.c_str(), L"/",
1624
+ cookie.GetAddressOf())) ||
1625
+ cookie.Get() == nullptr) {
1626
+ break;
1627
+ }
1628
+ cookie->put_Expires(static_cast<double>(static_cast<long long>(std::time(nullptr)) + 86400));
1629
+ if (FAILED(cookieManager->AddOrUpdateCookie(cookie.Get()))) break;
1630
+ injected = true;
1631
+ } while (false);
1632
+ Log(injected ? L"cookie-injected" : L"cookie-injection-failed");
1633
+ phase_ = Phase::App;
1634
+ appNavAttempt_ = 1;
1635
+ webView_->Navigate(targetUrl.c_str());
1636
+ }
1637
+
1638
+ void FloatApp::OnNavigationCompleted(bool success) {
1639
+ if (exiting_) return;
1640
+ LogFmt(L"navigation-completed success=%d phase=%d", success ? 1 : 0,
1641
+ static_cast<int>(phase_));
1642
+ if (payload_.ciProbe) {
1643
+ KillTimer(hwnd_, kTimerProbeTimeout);
1644
+ FinishProbe(success);
1645
+ return;
1646
+ }
1647
+ if (phase_ == Phase::Auth) {
1648
+ phase_ = Phase::App;
1649
+ appNavAttempt_ = 1;
1650
+ Log(L"navigate-app");
1651
+ webView_->Navigate(floatUrl_.c_str());
1652
+ return;
1653
+ }
1654
+ if (phase_ == Phase::App) {
1655
+ if (success) {
1656
+ phase_ = Phase::Done;
1657
+ appLoaded_ = true;
1658
+ Log(L"app-loaded");
1659
+ SetTimer(hwnd_, kTimerPageProbe, 6000, nullptr);
1660
+ } else if (appNavAttempt_ < 2) {
1661
+ appNavAttempt_ += 1;
1662
+ Log(L"app-load-failed retry");
1663
+ SetTimer(hwnd_, kTimerRetry, 1500, nullptr);
1664
+ } else {
1665
+ Log(L"app-load-failed giving-up");
1666
+ }
1667
+ }
1668
+ }
1669
+
1670
+ void FloatApp::OnNewWindowRequested(ICoreWebView2NewWindowRequestedEventArgs* args) {
1671
+ if (args == nullptr) return;
1672
+ LPWSTR uri = nullptr;
1673
+ if (SUCCEEDED(args->get_Uri(&uri)) && uri != nullptr) {
1674
+ LogFmt(L"new-window-requested uri=%s", uri);
1675
+ ShellExecuteW(nullptr, L"open", uri, nullptr, nullptr, SW_SHOWNORMAL);
1676
+ CoTaskMemFree(uri);
1677
+ }
1678
+ args->put_Handled(TRUE);
1679
+ }
1680
+
1681
+ void FloatApp::OnProcessFailed(ICoreWebView2ProcessFailedEventArgs* args) {
1682
+ if (args == nullptr) return;
1683
+ COREWEBVIEW2_PROCESS_FAILED_KIND kind = COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED;
1684
+ args->get_ProcessFailedKind(&kind);
1685
+ LogFmt(L"webview2-process-failed kind=%d", static_cast<int>(kind));
1686
+ if (kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED) RequestExit(4);
1687
+ }
1688
+
1689
+ void FloatApp::OnPageProbeTimer() {
1690
+ if (webView_.Get() == nullptr) return;
1691
+ static const wchar_t kProbe[] =
1692
+ L"(function(){try{return JSON.stringify({href:location.href,title:document.title,"
1693
+ L"float:localStorage.getItem('gufa-code:float'),"
1694
+ L"root:!!document.querySelector('.gufa-overlay-root'),"
1695
+ L"body:(document.body?document.body.innerText:'').slice(0,160)});}"
1696
+ L"catch(e){return 'probe-error:'+e;}})()";
1697
+ webView_->ExecuteScript(
1698
+ kProbe,
1699
+ Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
1700
+ [](HRESULT errorCode, LPCWSTR result) -> HRESULT {
1701
+ if (SUCCEEDED(errorCode) && result != nullptr) {
1702
+ LogFmt(L"page-probe %s", result);
1703
+ }
1704
+ return S_OK;
1705
+ })
1706
+ .Get());
1707
+ if (!payload_.selftest.empty()) SetTimer(hwnd_, kTimerSelftest, 3000, nullptr);
1708
+ }
1709
+
1710
+ void FloatApp::OnSelftestTimer() {
1711
+ if (webView_.Get() == nullptr || payload_.selftest.empty()) return;
1712
+ webView_->ExecuteScript(
1713
+ payload_.selftest.c_str(),
1714
+ Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
1715
+ [](HRESULT errorCode, LPCWSTR result) -> HRESULT {
1716
+ if (FAILED(errorCode)) {
1717
+ LogFmt(L"selftest-error hr=%08lX", static_cast<unsigned long>(errorCode));
1718
+ } else {
1719
+ LogFmt(L"selftest-result %s", result != nullptr ? result : L"(null)");
1720
+ }
1721
+ return S_OK;
1722
+ })
1723
+ .Get());
1724
+ }
1725
+
1726
+ void FloatApp::FinishProbe(bool loaded) {
1727
+ if (ciProbeFinished_) return;
1728
+ ciProbeFinished_ = true;
1729
+ WriteStdout(loaded ? L"{\"ok\":true,\"platform\":\"win32\",\"urlLoaded\":true}\n"
1730
+ : L"{\"ok\":true,\"platform\":\"win32\",\"urlLoaded\":false}\n");
1731
+ LogFmt(L"ciprobe-finished loaded=%d", loaded ? 1 : 0);
1732
+ RequestExit(0);
1733
+ }
1734
+
1735
+ void FloatApp::FinishProbeFailure() {
1736
+ if (ciProbeFinished_) return;
1737
+ ciProbeFinished_ = true;
1738
+ WriteStdout(L"{\"ok\":false,\"platform\":\"win32\",\"urlLoaded\":false}\n");
1739
+ Log(L"ciprobe-failed");
1740
+ RequestExit(1);
1741
+ }
1742
+
1743
+ void FloatApp::HandleWebViewEnvironmentFailure(HRESULT errorCode) {
1744
+ if (payload_.ciProbe) {
1745
+ FinishProbeFailure();
1746
+ return;
1747
+ }
1748
+ if (exiting_) return;
1749
+ LogFmt(L"webview2-unavailable hr=%08lX", static_cast<unsigned long>(errorCode));
1750
+ MessageBoxW(nullptr,
1751
+ L"无法启动 WebView2。\n\n"
1752
+ L"请确认已安装 Microsoft Edge WebView2 Runtime:\n"
1753
+ L"https://go.microsoft.com/fwlink/p/?LinkId=2124703\n\n"
1754
+ L"(Windows 10/11 通常已自带;安装后重试「摸鱼」。)",
1755
+ L"古法编程悬浮层", MB_ICONERROR | MB_OK);
1756
+ RequestExit(1);
1757
+ }
1758
+
1759
+ void FloatApp::CleanupWebView() {
1760
+ if (webView_.Get() != nullptr) webView_.Reset();
1761
+ if (controller_.Get() != nullptr) {
1762
+ controller_->put_IsVisible(FALSE);
1763
+ controller_->Close();
1764
+ controller_.Reset();
1765
+ }
1766
+ environment_.Reset();
1767
+ }
1768
+
1769
+ void FloatApp::DoGracefulExit() {
1770
+ if (hwnd_ == nullptr) {
1771
+ PostQuitMessage(exitCode_);
1772
+ return;
1773
+ }
1774
+ Log(L"graceful-exit-start");
1775
+ KillAllTimers();
1776
+ RestoreDshWindows();
1777
+ DeleteControlFile();
1778
+ SaveFrameIfNeeded();
1779
+ CleanupWebView();
1780
+ HWND window = hwnd_;
1781
+ hwnd_ = nullptr;
1782
+ if (strip_ != nullptr) {
1783
+ DestroyWindow(strip_);
1784
+ strip_ = nullptr;
1785
+ }
1786
+ DestroyWindow(window);
1787
+ Log(L"graceful-exit-done");
1788
+ }
1789
+
1790
+ void FloatApp::OnWindowDestroyed() {
1791
+ KillAllTimers();
1792
+ CleanupWebView();
1793
+ strip_ = nullptr; // 子窗口随父窗口一起销毁
1794
+ hwnd_ = nullptr;
1795
+ PostQuitMessage(exitCode_);
1796
+ }
1797
+
1798
+ LRESULT FloatApp::OnMainMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
1799
+ switch (message) {
1800
+ case WM_NCCALCSIZE:
1801
+ if (wparam == TRUE) return 0; // 去掉系统边框:客户区 = 整个窗口
1802
+ return DefWindowProcW(hwnd, message, wparam, lparam);
1803
+ case WM_NCHITTEST:
1804
+ return HandleNcHitTest(hwnd, lparam);
1805
+ case WM_GETMINMAXINFO:
1806
+ HandleMinMaxInfo(reinterpret_cast<MINMAXINFO*>(lparam));
1807
+ return 0;
1808
+ case WM_SIZE:
1809
+ LayoutChildren();
1810
+ return 0;
1811
+ case WM_MOVE:
1812
+ if (controller_.Get() != nullptr) controller_->NotifyParentWindowPositionChanged();
1813
+ return 0;
1814
+ case WM_DPICHANGED: {
1815
+ RECT* suggested = reinterpret_cast<RECT*>(lparam);
1816
+ if (suggested != nullptr) {
1817
+ SetWindowPos(hwnd, nullptr, suggested->left, suggested->top,
1818
+ suggested->right - suggested->left, suggested->bottom - suggested->top,
1819
+ SWP_NOZORDER | SWP_NOACTIVATE);
1820
+ }
1821
+ LayoutChildren();
1822
+ if (strip_ != nullptr) InvalidateRect(strip_, nullptr, TRUE);
1823
+ return 0;
1824
+ }
1825
+ case WM_TIMER:
1826
+ OnTimer(static_cast<UINT_PTR>(wparam));
1827
+ return 0;
1828
+ case kMsgExitGraceful:
1829
+ DoGracefulExit();
1830
+ return 0;
1831
+ case kMsgStripMenu:
1832
+ if (wparam == static_cast<WPARAM>(kMenuExit)) {
1833
+ RequestExit(0);
1834
+ } else if (wparam == static_cast<WPARAM>(kMenuResetFrame)) {
1835
+ ResetWindowFrame();
1836
+ }
1837
+ return 0;
1838
+ case WM_SYSKEYDOWN:
1839
+ if (wparam == VK_F4) {
1840
+ RequestExit(0);
1841
+ return 0;
1842
+ }
1843
+ return DefWindowProcW(hwnd, message, wparam, lparam);
1844
+ case WM_CLOSE:
1845
+ RequestExit(0);
1846
+ return 0;
1847
+ case WM_QUERYENDSESSION:
1848
+ return TRUE;
1849
+ case WM_ENDSESSION:
1850
+ if (wparam != 0) RestoreDshWindows();
1851
+ return 0;
1852
+ case WM_DESTROY:
1853
+ OnWindowDestroyed();
1854
+ return 0;
1855
+ default:
1856
+ return DefWindowProcW(hwnd, message, wparam, lparam);
1857
+ }
1858
+ }
1859
+
1860
+ } // namespace
1861
+
1862
+ /* ────────────────────────────── 入口 ────────────────────────────── */
1863
+
1864
+ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE previousInstance, PWSTR commandLine,
1865
+ int showCommand) {
1866
+ (void)previousInstance;
1867
+ (void)commandLine;
1868
+ (void)showCommand;
1869
+
1870
+ g_instance = instance;
1871
+ InitLogging();
1872
+ InstallCrashHandlers();
1873
+
1874
+ int argumentCount = 0;
1875
+ LPWSTR* arguments = CommandLineToArgvW(GetCommandLineW(), &argumentCount);
1876
+ if (arguments == nullptr) {
1877
+ Log(L"commandline-parse-failed");
1878
+ return 2;
1879
+ }
1880
+ const std::wstring firstArgument =
1881
+ argumentCount > 1 ? std::wstring(arguments[1]) : std::wstring();
1882
+ if (firstArgument == L"--version" || firstArgument == L"-v") {
1883
+ WriteStdout(L"gufa-float-win 1.0.0\n");
1884
+ LocalFree(arguments);
1885
+ return 0;
1886
+ }
1887
+ if (firstArgument == L"--help" || firstArgument == L"-h" || firstArgument == L"/?") {
1888
+ WriteStdout(L"gufa-float-win — Windows 悬浮层 helper(由 DSH Host 自动启动)\n"
1889
+ L"用法: gufa-float-win '<payload-json>'\n"
1890
+ L" gufa-float-win --version\n");
1891
+ LocalFree(arguments);
1892
+ return 0;
1893
+ }
1894
+ if (firstArgument.empty()) {
1895
+ Log(L"missing-payload-argument");
1896
+ LocalFree(arguments);
1897
+ return 2;
1898
+ }
1899
+
1900
+ // payload 是 argv[1] 的完整拷贝;CommandLineToArgvW 的内存可以提前释放。
1901
+ std::wstring payloadText = firstArgument;
1902
+ if (firstArgument == L"--ci-probe") payloadText = L"{\"ciProbe\":true}";
1903
+ LocalFree(arguments);
1904
+ arguments = nullptr;
1905
+
1906
+ EnableDpiAwareness();
1907
+
1908
+ const HRESULT comResult = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
1909
+ if (FAILED(comResult)) {
1910
+ LogFmt(L"com-init-failed hr=%08lX", static_cast<unsigned long>(comResult));
1911
+ return 1;
1912
+ }
1913
+
1914
+ int exitCode = 1;
1915
+ {
1916
+ FloatApp app;
1917
+ if (!app.ParseCommandLine(payloadText)) {
1918
+ exitCode = 2;
1919
+ } else if (!app.CreateMainWindow()) {
1920
+ if (app.IsCiProbe()) {
1921
+ WriteStdout(L"{\"ok\":false,\"platform\":\"win32\",\"urlLoaded\":false}\n");
1922
+ exitCode = 1;
1923
+ } else {
1924
+ exitCode = 3;
1925
+ }
1926
+ } else {
1927
+ app.Start();
1928
+ exitCode = app.RunMessageLoop();
1929
+ }
1930
+ }
1931
+
1932
+ CoUninitialize();
1933
+ LogFmt(L"exiting code=%d", exitCode);
1934
+ return exitCode;
1935
+ }