-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebLink.cpp
More file actions
242 lines (203 loc) · 7.95 KB
/
Copy pathWebLink.cpp
File metadata and controls
242 lines (203 loc) · 7.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#include <windows.h>
#include <shellapi.h>
#include "AppQuestionCallbacks.h"
#include "ClientConfig.h"
#include "WebViewBridgeHost.h"
#include "util/FileLogger.h"
#include "util/ProcessLauncher.h"
#include "util/ProfileBootstrap.h"
#include "util/ProcessUtils.h"
#include <memory>
#include <string>
static HWND g_hostHwnd = nullptr;
static std::unique_ptr<FileLogger> g_logger;
static std::unique_ptr<WebViewBridgeHost> g_bridgeHost;
bool ShouldLog(WebViewBridgeLogVerbosity level);
void Log(WebViewBridgeLogVerbosity level, const std::wstring& s);
void Log(const std::wstring& s);
LRESULT CALLBACK HostWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
namespace {
struct LaunchOptions {
bool isRelocated = false;
std::wstring parentName = ClientConfig::ParentProcessName();
};
// Parses the small launcher contract used by the relocation bootstrap.
LaunchOptions ParseLaunchOptions() {
LaunchOptions options;
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (!argv) {
return options;
}
for (int i = 1; i < argc; i++) {
if (_wcsicmp(argv[i], L"-r") == 0) {
options.isRelocated = true;
}
else if (_wcsicmp(argv[i], L"-p") == 0 && i + 1 < argc) {
options.parentName = argv[i + 1];
++i;
}
}
LocalFree(argv);
return options;
}
// Opens the client log sink on first use.
void InitializeLogger() {
if (!g_logger) {
// FileLogger does not own verbosity; it simply writes to the configured path.
g_logger = std::make_unique<FileLogger>(ClientConfig::LogPath());
}
}
// Tries to relaunch under the requested parent process before continuing in-place.
bool RunRelocationBootstrap(const std::wstring& parentName) {
InitializeLogger();
Log(L"Launcher: Target parent is " + parentName);
const DWORD targetPid = GetProcessIdByName(parentName.c_str());
if (targetPid == 0) {
Log(L"Launcher Error: Could not find PID for " + parentName);
return false;
}
if (SpawnRelocatedChildUnderParent(parentName, targetPid, [](const std::wstring& message) {
Log(message);
})) {
return true;
}
Log(L"Launcher: Relocation failed. Running fallback.");
return false;
}
// Initializes COM on the one thread that owns both the host window and WebView callbacks.
bool InitializeCom() {
// WebView2 COM callbacks and the hidden host window both run on this STA thread.
const HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (FAILED(hr)) {
Log(L"App Error: CoInitializeEx failed with HRESULT=" + std::to_wstring(static_cast<unsigned long>(hr)));
return false;
}
return true;
}
// Registers the hidden host window class used for timer dispatch and controller ownership.
bool RegisterHostWindowClass(HINSTANCE hInst) {
WNDCLASSW wc = { 0 };
wc.lpfnWndProc = HostWndProc;
wc.hInstance = hInst;
wc.lpszClassName = L"WV2Host";
const ATOM atom = RegisterClassW(&wc);
if (atom != 0 || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) {
return true;
}
Log(L"App Error: RegisterClassW failed with error=" + std::to_wstring(GetLastError()));
return false;
}
// Creates the message-only window that anchors the native side of the bridge.
bool CreateHostWindow(HINSTANCE hInst) {
// A message-only window is enough for WM_TIMER and WebView2 controller ownership.
g_hostHwnd = CreateWindowExW(0, L"WV2Host", L"Host", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInst, NULL);
if (g_hostHwnd) {
return true;
}
Log(L"App Error: CreateWindowExW failed with error=" + std::to_wstring(GetLastError()));
return false;
}
// Resolves profile policy, builds bridge config, and creates the WebView host object.
bool InitializeBridgeHost() {
const auto profile = ResolveDefaultClientProfile();
Log(FormatResolvedProfileLog(profile));
// The app keeps bootstrap policy here and passes the page contract into WebLinkLib.
WebViewBridgeHostConfig bridgeConfig{
ClientConfig::StartUrl(),
profile.userDataFolder,
profile.resolvedHost == ClientConfig::ProfileHostKind::Direct ? L"" : profile.profileName,
ClientConfig::PollScript(),
ClientConfig::LogVerbosity(),
ClientConfig::kPollTimerId,
ClientConfig::kConnectTimerId,
ClientConfig::kPollMs,
ClientConfig::kConnectRetryMs
};
auto callbacks = CreateAppQuestionCallbackRegistry();
g_bridgeHost = std::make_unique<WebViewBridgeHost>(
g_hostHwnd,
bridgeConfig,
std::move(callbacks),
[](const std::wstring& message) { Log(message); });
const HRESULT hr = g_bridgeHost->Initialize();
if (FAILED(hr)) {
Log(L"App Error: WebViewBridgeHost::Initialize failed with HRESULT=" + std::to_wstring(static_cast<unsigned long>(hr)));
g_bridgeHost.reset();
return false;
}
return true;
}
// Runs the Win32 message pump for the hidden host window and WebView callbacks.
int RunMessageLoop() {
MSG msg{};
while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return 0;
}
// Releases bridge resources and tears down COM for the owning thread.
void ShutdownApp() {
g_bridgeHost.reset();
g_logger.reset();
if (g_hostHwnd) {
g_hostHwnd = nullptr;
}
CoUninitialize();
}
}
// Applies the shared verbosity threshold to one client-side log message severity.
bool ShouldLog(WebViewBridgeLogVerbosity level) {
// ClientConfig owns the shared verbosity gate; FileLogger remains a dumb sink.
switch (ClientConfig::LogVerbosity()) {
case WebViewBridgeLogVerbosity::Silent:
return false;
case WebViewBridgeLogVerbosity::Info:
return level == WebViewBridgeLogVerbosity::Info;
case WebViewBridgeLogVerbosity::Debug:
return true;
default:
return false;
}
}
// Writes one client log line when the shared verbosity threshold allows it.
void Log(WebViewBridgeLogVerbosity level, const std::wstring& s) {
if (g_logger && ShouldLog(level)) {
g_logger->Write(L"[" + CurrentTimestampString() + L"] " + s);
}
}
// Convenience overload for normal informational client log lines.
void Log(const std::wstring& s) {
Log(WebViewBridgeLogVerbosity::Info, s);
}
LRESULT CALLBACK HostWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
// The bridge host owns the timer ids used for reconnect and native-driven polling.
if (msg == WM_TIMER && g_bridgeHost && g_bridgeHost->HandleTimer(static_cast<UINT_PTR>(wp))) { return 0; }
if (msg == WM_DESTROY) { PostQuitMessage(0); return 0; }
return DefWindowProcW(hwnd, msg, wp, lp);
}
// --- MAIN ---
// Bootstraps the hidden native host and then hands control to the Win32 message loop.
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int) {
const LaunchOptions options = ParseLaunchOptions();
if (!options.isRelocated) {
if (RunRelocationBootstrap(options.parentName)) {
g_logger.reset();
return 0;
}
}
InitializeLogger();
Log(L"App: Relocated instance active. Target Parent: " + options.parentName);
if (!InitializeCom()) {
g_logger.reset();
return 1;
}
if (!RegisterHostWindowClass(hInst) || !CreateHostWindow(hInst) || !InitializeBridgeHost()) {
ShutdownApp();
return 1;
}
const int exitCode = RunMessageLoop();
ShutdownApp();
return exitCode;
}