Web panel host: STA thread, WebView2 lifetime, allowlist, focus, visibility; offline harness

WebPanelHost (CoreCLR engine only): one unowned WS_POPUP over the game client area on its own STA thread and GetMessage loop, lifted from the 2026-11-07 spike's popup-free path. Open/Navigate/Close/GetState never block: they validate, update the caller-visible state under a lock, queue work and post WM_APP+1 to the host window. WebView2Loader.dll is loaded by full path from the shim's Runtime folder; the runtime probe on the panel thread decides RuntimeMissing, any later creation failure is CreateFailed. Navigation guard (NavigationStarting incl. redirects, NewWindowRequested, LaunchingExternalUriScheme): off-list http/https goes to the system browser, anything else is dropped; logs carry only Redact()ed URLs or hosts. Escape via AcceleratorKeyPressed unless PageKeepsEscape. Visibility by the PID rule on a 50 ms timer plus a foreground WinEvent; raises only when below the game; layout remembered in layout.json. Shutdown unhooks, closes the controller, destroys the window and unregisters the class before the collectible context unloads.

WebPanelNativeArgs copies every string out of the caller's (stack or pooled) buffers before anything is queued. WebPanelApi is the ABI glue (AOT keeps the Unavailable stub). engine.json "WebPanel" (default true) is the kill switch. EngineLifecycle shuts the panel down after EndSceneHook.Uninstall. The WebView2 package's WinForms/WPF references are dropped before reference resolution.

Deviations from the brief: IWebPanelEnvironment gains BrowserExecutableFolderForTests (the harness forces a creation failure with it) and is excluded from the AOT build with the host; Show only takes the foreground when it is already in this process (or none).

tools\WebPanelHarness (x86 exe) + tools\WebPanelHarness.Payload: fake game thread, fake 16 ms pump, collectible context mirroring EngineLoadContext, local virtual hosts, posted input only. 17 ok, 0 FAIL, 4 UNVERIFIED offline (Escape via posted input never raises AcceleratorKeyPressed; visibility needs the foreground): owner in-game checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-11-07 15:04:01 -08:00
commit f130be3d2b
14 changed files with 2682 additions and 9 deletions

View file

@ -172,6 +172,11 @@ internal static class EngineLifecycle
// we tear down anything else.
Thread.Sleep(80);
// The web panel after the plugins' own Shutdowns (EndSceneHook.Uninstall above runs them, and they
// may still Close it): its STA thread, window class, WinEvent hook and WebView2 objects go before
// the collectible engine context unloads.
Step("WebPanelApi.Shutdown", () => WebPanel.WebPanelApi.Shutdown());
Step("AvaloniaOverlay.Stop", () => AvaloniaOverlay.Stop());
// Restore AC's original window WndProc. EngineFrameController.Shutdown

View file

@ -70,6 +70,8 @@ internal static class EngineSettings
private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode;
// "TransitionGate": default true. False = queued game actions are never held for a death / portal.
private static bool _transitionGate = true;
// "WebPanel": default true. False = the v93 web panel calls answer Unavailable (plugins open the system browser).
private static bool _webPanel = true;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -714,6 +716,26 @@ internal static class EngineSettings
}
}
/// <summary>"WebPanel" in engine.json (default true): the v93 web panel (WebPanel\WebPanelHost.cs, a
/// WebView2 window over the game for DreamWeave's market and tools; CoreCLR engine only). False is the
/// kill switch: WebPanelOpen answers Unavailable and plugins open the page in the system browser
/// instead. A panel already open stays until it is closed.</summary>
public static bool WebPanel
{
get
{
EnsureLoaded();
return _webPanel;
}
set
{
EnsureLoaded();
if (_webPanel == value) return;
_webPanel = value;
Save("WebPanel");
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
@ -919,6 +941,10 @@ internal static class EngineSettings
(tgEl.ValueKind == JsonValueKind.True || tgEl.ValueKind == JsonValueKind.False))
_transitionGate = tgEl.GetBoolean();
if (doc.RootElement.TryGetProperty("WebPanel", out var wpEl) &&
(wpEl.ValueKind == JsonValueKind.True || wpEl.ValueKind == JsonValueKind.False))
_webPanel = wpEl.GetBoolean();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
@ -989,7 +1015,7 @@ internal static class EngineSettings
"FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "RememberWindowLayout",
"RememberAcWindowPosition", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel",
"LoadAllServerPlugins", "TransitionGate",
"LoadAllServerPlugins", "TransitionGate", "WebPanel",
"HoldReloadInWorld", "HoldReloadInWorldMaxMinutes",
"PanelLayoutPerCharacter",
"UiCostLog", "UiCostThresholdMs",
@ -1070,6 +1096,8 @@ internal static class EngineSettings
w.WriteBoolean("CloseOnServerDisconnect", false);
if (!_transitionGate) // default true: only a hand-set false is written
w.WriteBoolean("TransitionGate", false);
if (!_webPanel) // default true: only a hand-set false is written
w.WriteBoolean("WebPanel", false);
if (_loadAllServerPlugins) // default false: only a hand-set true is written
w.WriteBoolean("LoadAllServerPlugins", true);
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written

View file

@ -43,8 +43,35 @@
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles>
<DebugType>portable</DebugType>
<!-- The web panel (WebPanel\WebPanelHost.cs) uses only the WebView2 Core wrapper: no WinRT projection. -->
<WebView2UseWinRT>false</WebView2UseWinRT>
<WebView2LoaderPreference>Dynamic</WebView2LoaderPreference>
</PropertyGroup>
<!--
v93 web panel: WebView2 on the CoreCLR engine only. NativeAOT cannot host the Core wrapper's COM
interop, so that build drops the host and its Win32/WebView2 glue (WebPanelApi.cs answers Unavailable
there and PluginManager leaves the table slots zero).
-->
<ItemGroup Condition="'$(EngineHost)' == 'coreclr'">
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
</ItemGroup>
<ItemGroup Condition="'$(EngineHost)' != 'coreclr'">
<Compile Remove="WebPanel\WebPanelHost.cs;WebPanel\WebPanelNative.cs;WebPanel\EngineWebPanelEnvironment.cs;WebPanel\IWebPanelEnvironment.cs" />
</ItemGroup>
<!-- The package references its WinForms and WPF controls unconditionally; the engine uses neither. Dropped
before reference resolution, so they are neither compiled against nor copied to the output. -->
<Target Name="DropWebView2UiAssemblies" BeforeTargets="ResolveAssemblyReferences" Condition="'$(EngineHost)' == 'coreclr'">
<ItemGroup>
<Reference Remove="@(Reference)" Condition="'%(Filename)' == 'Microsoft.Web.WebView2.WinForms' Or '%(Filename)' == 'Microsoft.Web.WebView2.Wpf'" />
</ItemGroup>
</Target>
<Target Name="DropWebView2UiCopies" AfterTargets="ResolveAssemblyReferences" Condition="'$(EngineHost)' == 'coreclr'">
<ItemGroup>
<ReferenceCopyLocalPaths Remove="@(ReferenceCopyLocalPaths)" Condition="'%(Filename)' == 'Microsoft.Web.WebView2.WinForms' Or '%(Filename)' == 'Microsoft.Web.WebView2.Wpf'" />
</ItemGroup>
</Target>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<StackTraceSupport>true</StackTraceSupport>
<DebugType>full</DebugType>

View file

@ -0,0 +1,63 @@
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using Microsoft.Web.WebView2.Core;
namespace RynthCore.Engine.WebPanel;
/// <summary>The web panel host's surroundings inside acclient.exe (CoreCLR engine only).</summary>
internal sealed class EngineWebPanelEnvironment : IWebPanelEnvironment
{
private readonly string _runtimeDir = FindRuntimeDir();
public IntPtr GameHwnd
{
get
{
IntPtr h = ImGuiBackend.Win32Backend.GameHwnd;
return h != IntPtr.Zero ? h : EntryPoint.GameHwnd;
}
}
/// <summary>
/// Runtime\: the folder of the loaded RynthCore.Shim assembly, as ManagedPlugins.FindSharedDir finds it.
/// Never this assembly's Location: the engine is stream-loaded, so that is empty.
/// </summary>
public string RuntimeDir => _runtimeDir;
public string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
public string WorldName => Compatibility.AccountHooks.TryGetWorldName(out string name) ? name : "";
public void Log(string line) => RynthLog.Info("WebPanel: " + line);
public void Chat(string line) => Compatibility.ClientHelperHooks.WriteToChat(line, 1);
public bool OpenInBrowser(string url)
{
if (!WebPanelUrlPolicy.IsBrowserSafe(url)) return false;
IntPtr r = WebPanelNative.ShellExecuteW(IntPtr.Zero, "open", url, null, null, WebPanelNative.SW_SHOWNORMAL);
return r.ToInt64() > 32;
}
public Thread StartStaThread(string name, ThreadStart body) => EngineThreads.Start(name, body, ApartmentState.STA);
public Action<CoreWebView2>? ConfigureForTests => null;
public int EnvironmentDelayMsForTests => 0;
public string? BrowserExecutableFolderForTests => null;
private static string FindRuntimeDir()
{
try
{
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
if (a.GetName().Name != "RynthCore.Shim" || string.IsNullOrEmpty(a.Location)) continue;
return Path.GetDirectoryName(a.Location) ?? "";
}
}
catch { }
return "";
}
}

View file

@ -0,0 +1,32 @@
using System;
using System.Threading;
namespace RynthCore.Engine.WebPanel;
/// <summary>
/// What the web panel host needs from its surroundings: the engine (EngineWebPanelEnvironment) or the
/// offline harness (tools\WebPanelHarness.Payload). CoreCLR engine only.
/// </summary>
internal interface IWebPanelEnvironment
{
IntPtr GameHwnd { get; }
/// <summary>Folder holding WebView2Loader.dll and Microsoft.Web.WebView2.Core.dll.</summary>
string RuntimeDir { get; }
/// <summary>Profile and layout root (the harness: a temp folder).</summary>
string LocalAppData { get; }
/// <summary>"" when unknown.</summary>
string WorldName { get; }
/// <summary>Only ever given WebPanelUrlPolicy.Redact()ed URLs or hosts.</summary>
void Log(string line);
/// <summary>Any thread.</summary>
void Chat(string line);
/// <summary>IsBrowserSafe URLs only; the harness records instead of launching.</summary>
bool OpenInBrowser(string url);
Thread StartStaThread(string name, ThreadStart body);
/// <summary>Null in the engine.</summary>
Action<Microsoft.Web.WebView2.Core.CoreWebView2>? ConfigureForTests { get; }
/// <summary>0 in the engine.</summary>
int EnvironmentDelayMsForTests { get; }
/// <summary>Null in the engine (the installed Evergreen runtime); the harness forces a creation failure with it.</summary>
string? BrowserExecutableFolderForTests { get; }
}

View file

@ -2,18 +2,139 @@ using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.WebPanel;
#if ENGINE_CORECLR
/// <summary>
/// The engine side of the v93 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn).
/// Task 2 stub: every call answers Unavailable; the WebView2 host arrives in a later task.
/// No call here may block its caller (AC's main thread, the plugin pump and ImGui draws all call these).
/// The engine side of the v93 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn): reads
/// the native arguments (every string copied before the call returns) and hands them to the one
/// WebPanelHost. No call here blocks its caller (AC's main thread, the plugin pump and ImGui draws all call
/// these). engine.json "WebPanel": false makes Open answer Unavailable (plugins fall back to the browser).
/// </summary>
internal static class WebPanelApi
internal static unsafe class WebPanelApi
{
public static unsafe int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable;
private const int ShutdownBudgetMs = 2000;
private static readonly object Sync = new();
private static WebPanelHost? s_host;
private static EngineWebPanelEnvironment? s_env;
private static volatile bool s_shutdown;
public static unsafe int Navigate(int handle, byte* url) => (int)WebPanelCode.Unavailable;
internal static int Open(WebPanelOpenNative* open)
{
try
{
if (s_shutdown || EngineLifecycle.IsShuttingDown) return (int)WebPanelCode.ShuttingDown;
if (!EngineSettings.WebPanel) return (int)WebPanelCode.Unavailable;
EngineWebPanelEnvironment env;
WebPanelHost host;
lock (Sync)
{
if (s_shutdown) return (int)WebPanelCode.ShuttingDown;
env = s_env ??= new EngineWebPanelEnvironment();
host = s_host ??= new WebPanelHost(env);
}
int rc = WebPanelNativeArgs.TryBuildRequest(open, env.LocalAppData, env.WorldName, out WebPanelRequest? request);
if (rc != 0) return rc;
return host.Open(request!);
}
catch (System.Exception ex)
{
RynthLog.Info("WebPanel: Open failed: " + ex.GetType().Name);
return (int)WebPanelCode.Unavailable;
}
}
public static int Close(int handle) => (int)WebPanelCode.Unavailable;
internal static int Navigate(int handle, byte* urlUtf8)
{
try
{
if (s_shutdown) return (int)WebPanelCode.ShuttingDown;
if (!WebPanelNativeArgs.TryReadUtf8(urlUtf8, WebPanelUrlPolicy.MaxUrlBytes, true, out string url)) return (int)WebPanelCode.BadArgs;
WebPanelHost? host = s_host;
return host == null ? (int)WebPanelCode.StaleHandle : host.Navigate(handle, url);
}
catch (System.Exception ex)
{
RynthLog.Info("WebPanel: Navigate failed: " + ex.GetType().Name);
return (int)WebPanelCode.Unavailable;
}
}
public static unsafe int GetState(int handle, WebPanelStateNative* state) => (int)WebPanelCode.Unavailable;
internal static int Close(int handle)
{
try
{
if (s_shutdown) return (int)WebPanelCode.ShuttingDown;
WebPanelHost? host = s_host;
return host == null ? (int)WebPanelCode.StaleHandle : host.Close(handle);
}
catch (System.Exception ex)
{
RynthLog.Info("WebPanel: Close failed: " + ex.GetType().Name);
return (int)WebPanelCode.Unavailable;
}
}
internal static int GetState(int handle, WebPanelStateNative* state)
{
try
{
if (state == null || state->Size < (uint)((byte*)state->Reserved - (byte*)state)) return (int)WebPanelCode.BadArgs;
if (s_shutdown) return (int)WebPanelCode.ShuttingDown;
WebPanelHost? host = s_host;
WebPanelSnapshot s;
int r;
if (host == null)
{
s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0);
r = (int)WebPanelStatusCode.Superseded;
}
else
{
r = host.GetState(handle, out s);
}
state->Handle = s.Handle;
state->Status = s.Status;
state->Flags = s.Flags;
state->Error = s.Error;
state->LastHttpStatus = s.LastHttpStatus;
state->NavigationCount = s.NavigationCount;
return r;
}
catch (System.Exception ex)
{
RynthLog.Info("WebPanel: GetState failed: " + ex.GetType().Name);
return (int)WebPanelCode.Unavailable;
}
}
/// <summary>EngineLifecycle, after the plugins' own Shutdowns (they may still Close). Idempotent.</summary>
internal static void Shutdown()
{
WebPanelHost? host;
lock (Sync)
{
s_shutdown = true;
host = s_host;
}
host?.Shutdown(ShutdownBudgetMs);
}
/// <summary>Redacted one-liner (no query, fragment or userinfo).</summary>
internal static string Describe()
{
WebPanelHost? host = s_host;
string enabled = EngineSettings.WebPanel ? "on" : "off (engine.json WebPanel)";
return host == null ? "web panel: " + enabled + ", not started" : host.Describe() + "; setting " + enabled;
}
}
#else
/// <summary>The NativeAOT engine has no web panel: PluginManager leaves the v93 slots zero (HasWebPanel false).</summary>
internal static unsafe class WebPanelApi
{
internal static int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable;
internal static int Navigate(int handle, byte* url) => (int)WebPanelCode.Unavailable;
internal static int Close(int handle) => (int)WebPanelCode.Unavailable;
internal static int GetState(int handle, WebPanelStateNative* state) => (int)WebPanelCode.Unavailable;
internal static void Shutdown() { }
internal static string Describe() => "web panel: not available in this engine build";
}
#endif

View file

@ -0,0 +1,977 @@
// ============================================================================
// RynthCore.Engine - WebPanel/WebPanelHost.cs (CoreCLR engine only)
//
// One WebView2 panel over the game's client area, on a dedicated STA thread with its own
// GetMessage loop and an UNOWNED WS_POPUP host window (an owned popup would attach the game's
// input queue). Lifted from the 2026-11-07 spike (spikes\webview2\RynthWebSpike\WebPanel.cs,
// popup-free path), which ran it inside a live acclient.
//
// Threads: Open/Navigate/Close/GetState run on any thread (AC's main thread, the plugin pump,
// ImGui draws) and never block: they validate, update the caller-visible state under _sync,
// queue work and post WM_RUN to the host window. Everything that touches Win32 windows or
// WebView2 runs on the panel thread. Shutdown posts the teardown and joins within a budget.
//
// Lifetime: everything started or registered here (thread, window class, WinEvent hook, timer,
// WebView2 controller/environment) is torn down by Shutdown, before the collectible engine
// context unloads.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.Core;
using RynthCore.Engine.Plugins;
using static RynthCore.Engine.WebPanel.WebPanelNative;
namespace RynthCore.Engine.WebPanel;
internal readonly record struct WebPanelSnapshot(int Handle, int Status, uint Flags, int Error, int LastHttpStatus, uint NavigationCount);
internal sealed unsafe class WebPanelHost
{
private const uint WM_RUN = WM_APP + 1;
private const int CaptionPx = 28, CloseBoxPx = 34;
private const uint FlagFallback = 1, FlagPageKeepsEscape = 2;
private const uint StateVisible = 1, StateFocused = 2, StateOpenedInBrowser = 4;
private const uint VK_ESCAPE = 0x1B;
private static readonly IntPtr TimerId = (IntPtr)1;
private static readonly uint Background = Rgb(32, 32, 36), CaptionColor = Rgb(44, 44, 50), TextColor = Rgb(222, 222, 228);
// The WndProc and WinEvent target. One live host per engine generation (WebPanelApi holds it).
private static WebPanelHost? s_active;
private static int s_classSeq;
private readonly IWebPanelEnvironment _env;
private readonly uint _ourPid = GetCurrentProcessId();
// ---- caller-visible state: under _sync ----
private readonly object _sync = new();
private readonly ConcurrentQueue<Action> _queue = new();
private int _nextHandle;
private int _live;
private int _status;
private uint _flags;
private int _error, _http;
private uint _navCount;
private string _liveUrl = "";
private bool _shuttingDown;
private Thread? _thread;
private bool _threadDone;
private IntPtr _hwnd; // published once the window exists; WM_RUN goes here
// ---- panel thread only ----
private IntPtr _staHwnd, _hook, _bgBrush, _captionBrush;
private string _className = "";
private bool _windowFailed, _tornDown, _open, _timerOn, _inSizeMove;
private int _serving; // the handle whose request the panel shows
private WebPanelRequest? _req;
private string _title = "RynthCore";
private PanelFractions _fractions = WebPanelWindowPolicy.Default(0, 0);
private string _pendingUrl = "";
private bool _loaderLoaded;
private CoreWebView2Environment? _wvEnv;
private CoreWebView2Controller? _ctl;
private CoreWebView2? _web;
private string? _profileFolder;
private bool _creating, _needsRecreate;
private int _createSeq;
// ---- diagnostics (Describe and the offline harness) ----
private volatile int _environmentCount, _acceleratorEvents;
private volatile uint _browserPid;
private volatile string _source = "";
public WebPanelHost(IWebPanelEnvironment env) => _env = env;
// ============================ any thread ============================
public int Open(WebPanelRequest request)
{
if (request == null) return (int)WebPanelCode.BadArgs;
lock (_sync) if (_shuttingDown) return (int)WebPanelCode.ShuttingDown;
if (!WebPanelUrlPolicy.IsAllowed(request.Url, request.Allowlist)) return (int)WebPanelCode.UrlNotAllowed;
IntPtr game = _env.GameHwnd;
if (game == IntPtr.Zero || !IsWindow(game)) return (int)WebPanelCode.NoGameWindow;
lock (_sync)
{
if (_shuttingDown) return (int)WebPanelCode.ShuttingDown;
if (_nextHandle <= 0) _nextHandle = (Environment.TickCount & 0x3FFFFFFF) | 1;
int handle = _nextHandle++;
_live = handle;
_status = (int)WebPanelStatusCode.Starting;
_flags = 0;
_error = 0;
_http = 0;
_navCount = 0;
_liveUrl = request.Url;
_currentAllowlist = request.Allowlist;
_queue.Enqueue(() => ProcessOpen(handle, request));
if (_thread == null || _threadDone)
{
// First call (or the thread died): start it and return at once. The thread creates its
// window first, then drains the queue.
_threadDone = false;
_hwnd = IntPtr.Zero;
_thread = _env.StartStaThread("RynthCore.WebPanel", ThreadMain);
}
else if (_hwnd != IntPtr.Zero)
{
PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero);
}
return handle;
}
}
public int Navigate(int handle, string url)
{
lock (_sync)
{
if (_shuttingDown) return (int)WebPanelCode.ShuttingDown;
if (handle <= 0 || handle != _live) return (int)WebPanelCode.StaleHandle;
if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return (int)WebPanelCode.StaleHandle;
}
if (string.IsNullOrEmpty(url)) return (int)WebPanelCode.BadArgs;
string[] allow;
lock (_sync) allow = _currentAllowlist;
if (!WebPanelUrlPolicy.IsAllowed(url, allow))
{
// Off the list: the system browser when that is safe (on the panel thread: ShellExecute can be slow).
Post(() => RouteOffList(url));
return (int)WebPanelCode.UrlNotAllowed;
}
return Post(() => NavigateNow(handle, url)) ? (int)WebPanelCode.Queued : (int)WebPanelCode.ShuttingDown;
}
public int Close(int handle)
{
lock (_sync)
{
if (_shuttingDown) return (int)WebPanelCode.ShuttingDown;
if (handle <= 0 || handle != _live) return (int)WebPanelCode.StaleHandle;
if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return (int)WebPanelCode.AlreadyClosed;
}
return Post(() => CloseNow(handle)) ? (int)WebPanelCode.Queued : (int)WebPanelCode.ShuttingDown;
}
public int GetState(int handle, out WebPanelSnapshot s)
{
lock (_sync)
{
if (_shuttingDown)
{
s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.None, 0, (int)WebPanelCode.ShuttingDown, 0, 0);
return (int)WebPanelCode.ShuttingDown;
}
if (handle <= 0 || handle != _live)
{
s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0);
return (int)WebPanelStatusCode.Superseded;
}
s = new WebPanelSnapshot(_live, _status, _flags, _error, _http, _navCount);
return _status;
}
}
/// <summary>Idempotent. Posts the teardown (which ends with WM_QUIT) and joins the thread within the budget.</summary>
public void Shutdown(int budgetMs)
{
Thread? t;
lock (_sync)
{
t = _thread;
if (!_shuttingDown)
{
_shuttingDown = true;
if (t != null && !_threadDone)
{
_queue.Enqueue(TeardownOnPanelThread);
if (_hwnd != IntPtr.Zero) PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero);
}
}
}
if (t == null || t == Thread.CurrentThread) return;
if (!t.Join(Math.Max(0, budgetMs)))
SafeLog($"shutdown: the panel thread did not finish within {budgetMs} ms");
}
public string Describe()
{
lock (_sync)
{
string thread = _thread == null ? "not started" : _threadDone ? "stopped" : "running";
string status = ((WebPanelStatusCode)_status).ToString();
return $"web panel: thread {thread}{(_shuttingDown ? " (shut down)" : "")}, handle {_live}, {status}, error {_error}, " +
$"http {_http}, navigations {_navCount}, environments {_environmentCount}, flags {_flags}, url {WebPanelUrlPolicy.Redact(_liveUrl)}";
}
}
// The live request's allowlist, for Navigate's caller-side check (set on Open, under _sync).
private string[] _currentAllowlist = Array.Empty<string>();
private bool Post(Action a)
{
lock (_sync)
{
if (_thread == null || _threadDone) return false;
_queue.Enqueue(a);
if (_hwnd != IntPtr.Zero) PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero);
return true;
}
}
/// <summary>Applies <paramref name="apply"/> to the caller-visible state only while <paramref name="handle"/> is the live one.</summary>
private void SetState(int handle, Action apply)
{
lock (_sync) if (handle == _live) apply();
}
private void SafeLog(string line) { try { _env.Log(line); } catch { } }
private void SafeChat(string line) { try { _env.Chat(line); } catch { } }
// ---- test and diagnostic views (no secrets: Source is never logged) ----
internal IntPtr HostHwndForTests { get { lock (_sync) return _hwnd; } }
internal int EnvironmentCountForTests => _environmentCount;
internal uint BrowserProcessIdForTests => _browserPid;
internal int AcceleratorKeyEventsForTests => _acceleratorEvents;
internal string SourceForTests => _source;
internal bool ThreadRunningForTests { get { lock (_sync) return _thread != null && !_threadDone && _thread.IsAlive; } }
internal bool PostForTests(Action<CoreWebView2?> a) => Post(() => a(_web));
// ============================ panel thread ============================
private void ThreadMain()
{
// A thread restarted after a failed one (no window) starts clean.
_tornDown = false;
_windowFailed = false;
try
{
try { CreateHostWindow(); }
catch (Exception ex)
{
_windowFailed = true;
SafeLog("could not create the panel window: " + ex.GetType().Name + " " + ex.Message);
}
lock (_sync) _hwnd = _staHwnd;
Drain();
if (_staHwnd != IntPtr.Zero)
{
while (GetMessageW(out MSG msg, IntPtr.Zero, 0, 0) > 0)
{
TranslateMessage(ref msg);
DispatchMessageW(ref msg);
}
}
else
{
TeardownOnPanelThread();
}
}
catch (Exception ex)
{
SafeLog("panel thread failed: " + ex.GetType().Name + " " + ex.Message);
}
finally
{
// However the loop ended (WM_QUIT from the teardown, a GetMessage error, an exception), nothing
// this thread registered (window class, WinEvent hook, WebView2) may outlive it: the class's WndProc
// points into the collectible engine context.
if (!_tornDown) { try { TeardownOnPanelThread(); } catch { } }
lock (_sync)
{
_threadDone = true;
_hwnd = IntPtr.Zero;
}
}
}
private void CreateHostWindow()
{
_className = $"RynthCoreWebPanel_{Environment.TickCount64:X}_{Interlocked.Increment(ref s_classSeq):X}";
_bgBrush = CreateSolidBrush(Background);
_captionBrush = CreateSolidBrush(CaptionColor);
IntPtr inst = GetModuleHandleW(IntPtr.Zero);
fixed (char* pName = _className)
{
var wc = new WNDCLASSEXW
{
cbSize = (uint)sizeof(WNDCLASSEXW),
style = CS_HREDRAW | CS_VREDRAW,
lpfnWndProc = (IntPtr)(delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, IntPtr, IntPtr>)&WndProc,
hInstance = inst,
hCursor = LoadCursorW(IntPtr.Zero, (IntPtr)IDC_ARROW),
hbrBackground = _bgBrush,
lpszClassName = (IntPtr)pName,
};
if (RegisterClassExW(ref wc) == 0)
{
int err = Marshal.GetLastWin32Error();
_className = "";
throw new InvalidOperationException("RegisterClassExW failed " + err);
}
}
s_active = this;
IntPtr h = CreateWindowExW(WS_EX_TOOLWINDOW, _className, "RynthCore", WS_POPUP | WS_CLIPCHILDREN | WS_THICKFRAME,
0, 0, 640, 480, IntPtr.Zero, IntPtr.Zero, inst, IntPtr.Zero);
if (h == IntPtr.Zero) throw new InvalidOperationException("CreateWindowExW failed " + Marshal.GetLastWin32Error());
_staHwnd = h;
_hook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, &WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l)
{
WebPanelHost? p = s_active;
if (p != null)
{
try
{
if (p.HandleMessage(h, m, w, l, out IntPtr r)) return r;
}
catch (Exception ex)
{
p.SafeLog("WndProc threw " + ex.GetType().Name + " " + ex.Message);
}
}
return DefWindowProcW(h, m, w, l);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int idObject, int idChild, uint thread, uint time)
{
WebPanelHost? p = s_active;
if (p == null || hook != p._hook) return;
try { p.Track(); }
catch (Exception ex) { p.SafeLog("foreground tracking threw " + ex.GetType().Name + " " + ex.Message); }
}
private bool HandleMessage(IntPtr h, uint m, IntPtr w, IntPtr l, out IntPtr result)
{
result = IntPtr.Zero;
if (_staHwnd == IntPtr.Zero || h != _staHwnd) return false; // during CreateWindowExW: default handling
switch (m)
{
case WM_RUN:
Drain();
return true;
case WM_TIMER:
if (w != TimerId) return false;
Track();
return true;
case WM_SIZE:
ResizeController();
return false;
case WM_SETFOCUS:
try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { }
return false;
case WM_CLOSE: // Alt+F4 on the panel: close it, keep the window
CloseNow(_serving);
return true;
case WM_NCHITTEST:
{
result = DefWindowProcW(h, m, w, l);
if (result == (IntPtr)HTCLIENT)
{
var pt = new POINT { X = (short)((long)l & 0xFFFF), Y = (short)(((long)l >> 16) & 0xFFFF) };
ScreenToClient(h, ref pt);
if (pt.Y >= 0 && pt.Y < CaptionPx && !InCloseBox(pt)) result = (IntPtr)HTCAPTION;
}
return true;
}
case WM_LBUTTONDOWN:
{
var pt = new POINT { X = (short)((long)l & 0xFFFF), Y = (short)(((long)l >> 16) & 0xFFFF) };
if (InCloseBox(pt)) CloseNow(_serving);
return true;
}
case WM_PAINT:
Paint(h);
return true;
case WM_ENTERSIZEMOVE:
_inSizeMove = true;
return false;
case WM_EXITSIZEMOVE:
_inSizeMove = false;
RememberUserLayout();
return false;
}
return false;
}
private bool InCloseBox(POINT pt)
{
GetClientRect(_staHwnd, out RECT rc);
return pt.Y >= 0 && pt.Y < CaptionPx && pt.X >= rc.Right - CloseBoxPx && pt.X < rc.Right;
}
private void Paint(IntPtr h)
{
IntPtr dc = BeginPaint(h, out PAINTSTRUCT ps);
try
{
GetClientRect(h, out RECT rc);
var strip = new RECT { Left = 0, Top = 0, Right = rc.Right, Bottom = Math.Min(CaptionPx, rc.Bottom) };
FillRect(dc, ref strip, _captionBrush);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, TextColor);
IntPtr old = SelectObject(dc, GetStockObject(DEFAULT_GUI_FONT));
var title = new RECT { Left = 10, Top = 0, Right = Math.Max(10, rc.Right - CloseBoxPx - 6), Bottom = strip.Bottom };
DrawTextW(dc, _title, -1, ref title, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX);
var x = new RECT { Left = rc.Right - CloseBoxPx, Top = 0, Right = rc.Right, Bottom = strip.Bottom };
DrawTextW(dc, "X", -1, ref x, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
SelectObject(dc, old);
}
finally { EndPaint(h, ref ps); }
}
private void Drain()
{
while (_queue.TryDequeue(out Action? a))
{
try { a(); }
catch (Exception ex) { SafeLog("panel action threw " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); } // no Message: it could carry a URL
}
}
private bool IsLive(int handle) { lock (_sync) return handle == _live && !_shuttingDown; }
private void ProcessOpen(int handle, WebPanelRequest r)
{
if (_tornDown || !IsLive(handle)) return; // a newer Open is queued behind this one
_serving = handle;
_req = r;
_title = string.IsNullOrWhiteSpace(r.Title) ? "RynthCore" : r.Title.Trim();
_fractions = WebPanelLayoutStore.TryLoad(_env.LocalAppData, out PanelFractions stored)
? stored
: WebPanelWindowPolicy.Default(r.WidthPercent, r.HeightPercent);
_pendingUrl = r.Url;
if (_windowFailed) { Fail(handle, WebPanelCode.CreateFailed, "no panel window", allowFallback: true); return; }
if (_needsRecreate || (_profileFolder != null && !string.Equals(_profileFolder, r.ProfileFolder, StringComparison.OrdinalIgnoreCase)))
TearDownWebView();
_open = true;
InvalidateRect(_staHwnd, IntPtr.Zero, true);
Show();
if (_ctl != null) { NavigatePending(handle); return; }
if (!_creating) StartCreate(handle, r.ProfileFolder);
}
private void StartCreate(int handle, string folder)
{
_creating = true;
int seq = ++_createSeq;
_profileFolder = folder;
if (!EnsureLoader(out string why)) { CreationFailed(seq, WebPanelCode.CreateFailed, why); return; }
try
{
string version = CoreWebView2Environment.GetAvailableBrowserVersionString();
if (string.IsNullOrEmpty(version)) { CreationFailed(seq, WebPanelCode.RuntimeMissing, "no WebView2 runtime"); return; }
}
catch (Exception ex)
{
CreationFailed(seq, Classify(ex), "runtime probe: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8"));
return;
}
int delay = _env.EnvironmentDelayMsForTests;
if (delay > 0) Task.Delay(delay).ContinueWith(_ => Post(() => CreateEnvironment(seq, folder)));
else CreateEnvironment(seq, folder);
}
private bool EnsureLoader(out string why)
{
why = "";
if (_loaderLoaded) return true;
string path = Path.Combine(_env.RuntimeDir ?? "", "WebView2Loader.dll");
try
{
// By full path first, so the Core wrapper's DllImport("WebView2Loader.dll") finds the loaded module.
NativeLibrary.Load(path);
_loaderLoaded = true;
return true;
}
catch (Exception ex)
{
why = "WebView2Loader.dll did not load from the runtime folder: " + ex.GetType().Name;
return false;
}
}
private void CreateEnvironment(int seq, string folder)
{
if (seq != _createSeq || _tornDown) return;
Task<CoreWebView2Environment> t;
try
{
Directory.CreateDirectory(folder);
t = CoreWebView2Environment.CreateAsync(_env.BrowserExecutableFolderForTests, folder, new CoreWebView2EnvironmentOptions());
}
catch (Exception ex)
{
CreationFailed(seq, WebPanelCode.CreateFailed, "environment: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8"));
return;
}
t.ContinueWith(done => Post(() => OnEnvironment(seq, done)), TaskContinuationOptions.ExecuteSynchronously);
}
private void OnEnvironment(int seq, Task<CoreWebView2Environment> t)
{
if (seq != _createSeq || _tornDown) return;
if (!t.IsCompletedSuccessfully)
{
Exception? ex = t.Exception?.GetBaseException();
CreationFailed(seq, WebPanelCode.CreateFailed, "environment: " + (ex?.GetType().Name ?? "cancelled") + " 0x" + (ex?.HResult ?? 0).ToString("X8"));
return;
}
_wvEnv = t.Result;
_environmentCount++;
Task<CoreWebView2Controller> c;
try { c = _wvEnv.CreateCoreWebView2ControllerAsync(_staHwnd); }
catch (Exception ex)
{
CreationFailed(seq, WebPanelCode.CreateFailed, "controller: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8"));
return;
}
c.ContinueWith(done => Post(() => OnController(seq, done)), TaskContinuationOptions.ExecuteSynchronously);
}
private void OnController(int seq, Task<CoreWebView2Controller> t)
{
if (seq != _createSeq || _tornDown)
{
if (t.IsCompletedSuccessfully) { try { t.Result.Close(); } catch { } }
return;
}
if (!t.IsCompletedSuccessfully)
{
Exception? ex = t.Exception?.GetBaseException();
CreationFailed(seq, WebPanelCode.CreateFailed, "controller: " + (ex?.GetType().Name ?? "cancelled") + " 0x" + (ex?.HResult ?? 0).ToString("X8"));
return;
}
_creating = false;
_ctl = t.Result;
_web = _ctl.CoreWebView2;
_ctl.DefaultBackgroundColor = System.Drawing.Color.FromArgb(255, 32, 32, 36);
CoreWebView2Settings s = _web.Settings;
s.AreDevToolsEnabled = false;
s.AreBrowserAcceleratorKeysEnabled = false;
s.IsStatusBarEnabled = false;
s.AreHostObjectsAllowed = false;
s.IsWebMessageEnabled = false; // phase 2 turns it on per open
s.IsPasswordAutosaveEnabled = false;
_web.NavigationStarting += OnNavigationStarting;
_web.NavigationCompleted += OnNavigationCompleted;
_web.NewWindowRequested += OnNewWindowRequested;
_web.PermissionRequested += OnPermissionRequested;
_web.ProcessFailed += OnProcessFailed;
_web.LaunchingExternalUriScheme += OnLaunchingExternalUriScheme;
_ctl.AcceleratorKeyPressed += OnAcceleratorKeyPressed;
_browserPid = _web.BrowserProcessId;
_env.ConfigureForTests?.Invoke(_web);
ResizeController();
if (_open)
{
_ctl.IsVisible = true;
NavigatePending(_serving);
FocusPage();
}
else
{
_ctl.IsVisible = false;
}
}
private void CreationFailed(int seq, WebPanelCode code, string reason)
{
if (seq != _createSeq) return;
_creating = false;
_wvEnv = null;
_profileFolder = null; // the next Open tries again
Fail(_serving, code, reason, allowFallback: true);
}
/// <summary>Only the runtime probe can say RuntimeMissing; a failure after it is CreateFailed.</summary>
private static WebPanelCode Classify(Exception? ex) =>
ex is WebView2RuntimeNotFoundException ? WebPanelCode.RuntimeMissing : WebPanelCode.CreateFailed;
private void NavigatePending(int handle)
{
if (_web == null || !IsLive(handle)) return;
string url = _pendingUrl;
SetState(handle, () => _status = (int)WebPanelStatusCode.Loading);
try { _web.Navigate(url); }
catch (Exception ex) { SafeLog("navigate threw " + ex.GetType().Name + " for " + WebPanelUrlPolicy.Redact(url)); }
}
private void NavigateNow(int handle, string url)
{
if (!IsLive(handle) || _serving != handle) return;
_pendingUrl = url;
if (_web == null) return; // still creating: the controller navigates to _pendingUrl when it is ready
NavigatePending(handle);
}
// ---- navigation guard ----
private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e)
{
string url = e.Uri;
if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return; // our own close, or the page's
string[] allow = _req?.Allowlist ?? Array.Empty<string>();
if (!WebPanelUrlPolicy.IsAllowed(url, allow))
{
e.Cancel = true;
RouteOffList(url);
return;
}
int handle = _serving;
SetState(handle, () =>
{
_navCount++;
if (_status != (int)WebPanelStatusCode.Closed && _status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Loading;
});
}
private void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
string source = _web?.Source ?? "";
if (string.Equals(source, "about:blank", StringComparison.OrdinalIgnoreCase) || !_open) return;
_source = source;
int http = e.HttpStatusCode;
int handle = _serving;
SetState(handle, () =>
{
if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return;
_status = (int)WebPanelStatusCode.Ready;
if (http != 0) _http = http;
});
}
private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
{
e.Handled = true; // never a second window
string url = e.Uri;
string[] allow = _req?.Allowlist ?? Array.Empty<string>();
if (WebPanelUrlPolicy.IsAllowed(url, allow))
{
try { _web?.Navigate(url); } catch { }
}
else
{
RouteOffList(url);
}
}
/// <summary>An off-list URL: the system browser when it is browser-safe, else dropped (logged redacted).</summary>
private void RouteOffList(string url)
{
if (WebPanelUrlPolicy.IsBrowserSafe(url))
{
bool ok = false;
try { ok = _env.OpenInBrowser(url); } catch { }
string host = Uri.TryCreate(url, UriKind.Absolute, out Uri? u) ? u.Host : "the page";
SafeLog((ok ? "opened in the system browser: " : "the system browser did not open: ") + WebPanelUrlPolicy.Redact(url));
if (ok) SafeChat("[RynthCore] Opened " + host + " in your web browser.");
}
else
{
SafeLog("blocked a navigation (" + SchemeOf(url) + "): " + WebPanelUrlPolicy.Redact(url));
}
}
private static string SchemeOf(string url)
{
int colon = url.IndexOf(':');
if (colon <= 0 || colon > 32) return "no scheme";
foreach (char c in url.AsSpan(0, colon))
if (!char.IsAsciiLetterOrDigit(c) && c != '+' && c != '-' && c != '.') return "no scheme";
return url.Substring(0, colon).ToLowerInvariant();
}
private void OnLaunchingExternalUriScheme(object? sender, CoreWebView2LaunchingExternalUriSchemeEventArgs e)
{
e.Cancel = true; // never hand a custom scheme to the shell, and never show WebView2's prompt for one
SafeLog("blocked an external scheme launch (" + SchemeOf(e.Uri) + ")");
}
private void OnPermissionRequested(object? sender, CoreWebView2PermissionRequestedEventArgs e)
{
e.State = e.PermissionKind == CoreWebView2PermissionKind.ClipboardRead
? CoreWebView2PermissionState.Allow
: CoreWebView2PermissionState.Deny;
}
private void OnAcceleratorKeyPressed(object? sender, CoreWebView2AcceleratorKeyPressedEventArgs e)
{
_acceleratorEvents++;
if (e.KeyEventKind != CoreWebView2KeyEventKind.KeyDown || e.VirtualKey != VK_ESCAPE) return;
if (((_req?.Flags ?? 0) & FlagPageKeepsEscape) != 0) return; // the page gets it
e.Handled = true;
int handle = _serving;
Post(() => CloseNow(handle)); // not inside WebView2's own callback
}
private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
{
CoreWebView2ProcessFailedKind kind = e.ProcessFailedKind;
int handle = _serving;
Post(() => HandleProcessFailed(handle, kind)); // tear down outside WebView2's own callback
}
private void HandleProcessFailed(int handle, CoreWebView2ProcessFailedKind kind)
{
if (_tornDown) return;
SafeLog("WebView2 process failed: " + kind);
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
{
TearDownWebView();
}
else
{
try { _web?.Navigate("about:blank"); } catch { }
_needsRecreate = true; // the next Open recreates the controller and environment
}
// Never a browser fallback here: a navigation already ran, so the launch code is spent.
Fail(handle, WebPanelCode.ProcessFailed, kind.ToString(), allowFallback: false);
}
// ---- open, close, fail ----
private void Fail(int handle, WebPanelCode code, string reason, bool allowFallback)
{
HidePanel();
bool fallback = false, ignored = false;
string url = "";
lock (_sync)
{
if (handle != _live || _status == (int)WebPanelStatusCode.Closed)
{
ignored = true;
}
else
{
_status = (int)WebPanelStatusCode.Failed;
_error = (int)code;
WebPanelRequest? r = _req;
if (allowFallback && r != null && (code == WebPanelCode.RuntimeMissing || code == WebPanelCode.CreateFailed)
&& (r.Flags & FlagFallback) != 0 && _navCount == 0 && WebPanelUrlPolicy.IsBrowserSafe(r.Url))
{
fallback = true;
url = r.Url;
_flags |= StateOpenedInBrowser;
}
}
}
if (ignored) { SafeLog($"panel failure after close or supersede: {code} ({reason})"); return; }
SafeLog($"panel failed: {code} ({reason})");
if (!fallback) return;
bool ok = false;
try { ok = _env.OpenInBrowser(url); } catch { }
SafeLog((ok ? "fallback: opened in the system browser: " : "fallback: the system browser did not open: ") + WebPanelUrlPolicy.Redact(url));
string why = code == WebPanelCode.RuntimeMissing ? "WebView2 runtime not installed" : "it failed to start";
SafeChat("[RynthCore] The in-game browser could not start (" + why + "); opened the page in your web browser.");
}
private void Show()
{
PlaceNow(force: true);
ShowWindow(_staHwnd, SW_SHOWNA);
// Focus the panel only from within this process (the game, or a pop-out): a plugin opening it while the
// player is in another program must not pull the foreground away (the PID rule keeps it hidden meanwhile).
IntPtr fg = GetForegroundWindow();
uint fgPid = 0;
if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid);
if (fg == IntPtr.Zero || fgPid == _ourPid) SetForegroundWindow(_staHwnd);
if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } }
FocusPage();
if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; }
UpdateStateFlags();
}
private void FocusPage()
{
try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { }
}
private void CloseNow(int handle)
{
if (!IsLive(handle) || handle != _serving) return;
if (_open)
{
HidePanel();
if (_ctl != null) { try { _web?.Navigate("about:blank"); } catch { } }
}
SetState(handle, () =>
{
if (_status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Closed;
_flags &= ~(StateVisible | StateFocused);
});
}
/// <summary>Hides the panel (controller, window, timer); hands the foreground back to the game when the panel held it.</summary>
private void HidePanel()
{
bool hadForeground = HoldsForeground();
_open = false;
if (_timerOn) { KillTimer(_staHwnd, TimerId); _timerOn = false; }
if (_ctl != null) { try { _ctl.IsVisible = false; } catch { } }
if (_staHwnd != IntPtr.Zero) ShowWindow(_staHwnd, SW_HIDE);
lock (_sync) if (_serving == _live) _flags &= ~(StateVisible | StateFocused);
if (hadForeground)
{
IntPtr game = _env.GameHwnd;
if (game != IntPtr.Zero && IsWindow(game)) SetForegroundWindow(game);
}
}
private bool HoldsForeground()
{
if (_staHwnd == IntPtr.Zero) return false;
IntPtr fg = GetForegroundWindow();
return fg != IntPtr.Zero && (fg == _staHwnd || GetAncestor(fg, GA_ROOT) == _staHwnd);
}
// ---- tracking: 50 ms timer and the foreground WinEvent ----
private void Track()
{
if (!_open || _staHwnd == IntPtr.Zero) return;
IntPtr game = _env.GameHwnd;
if (game == IntPtr.Zero || !IsWindow(game)) { CloseNow(_serving); return; }
IntPtr fg = GetForegroundWindow();
uint fgPid = 0;
if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid);
bool? visible = WebPanelWindowPolicy.Visible(true, true, IsIconic(game), IsWindowVisible(game), fg == IntPtr.Zero, fgPid, _ourPid);
bool shown = IsWindowVisible(_staHwnd);
if (visible == false)
{
if (shown) ShowWindow(_staHwnd, SW_HIDE);
}
else
{
if (visible == true && !shown) { ShowWindow(_staHwnd, SW_SHOWNA); shown = true; }
if (shown)
{
if (!_inSizeMove) PlaceNow(force: false);
RaiseAboveGame(game);
}
}
UpdateStateFlags();
}
private bool GameClientScreen(out PanelRect rect)
{
rect = default;
IntPtr game = _env.GameHwnd;
if (game == IntPtr.Zero || !GetClientRect(game, out RECT c)) return false;
var p = new POINT();
if (!ClientToScreen(game, ref p)) return false;
rect = new PanelRect(p.X, p.Y, p.X + c.W, p.Y + c.H);
return rect.Width > 0 && rect.Height > 0;
}
private void PlaceNow(bool force)
{
if (!GameClientScreen(out PanelRect client)) return;
PanelRect want = WebPanelWindowPolicy.Place(client, _fractions);
GetWindowRect(_staHwnd, out RECT have);
if (!force && have.Left == want.Left && have.Top == want.Top && have.Right == want.Right && have.Bottom == want.Bottom) return;
SetWindowPos(_staHwnd, IntPtr.Zero, want.Left, want.Top, want.Width, want.Height, SWP_NOZORDER | SWP_NOACTIVATE);
}
/// <summary>Raises the panel only when it is below the game window, so it never covers a window the user brought forward.</summary>
private void RaiseAboveGame(IntPtr game)
{
int guard = 0;
for (IntPtr h = GetWindow(game, GW_HWNDPREV); h != IntPtr.Zero && guard < 4096; h = GetWindow(h, GW_HWNDPREV), guard++)
if (h == _staHwnd) return;
SetWindowPos(_staHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
private void UpdateStateFlags()
{
bool visible = _staHwnd != IntPtr.Zero && IsWindowVisible(_staHwnd);
bool focused = HoldsForeground();
lock (_sync)
{
if (_serving != _live) return;
_flags = (_flags & StateOpenedInBrowser) | (visible && _open ? StateVisible : 0) | (focused && _open ? StateFocused : 0);
}
}
private void RememberUserLayout()
{
if (!GameClientScreen(out PanelRect client)) return;
GetWindowRect(_staHwnd, out RECT r);
_fractions = WebPanelWindowPolicy.FromUserRect(client, new PanelRect(r.Left, r.Top, r.Right, r.Bottom));
if (!WebPanelLayoutStore.Save(_env.LocalAppData, _fractions)) SafeLog("could not save the panel layout");
}
private void ResizeController()
{
if (_ctl == null || _staHwnd == IntPtr.Zero) return;
GetClientRect(_staHwnd, out RECT rc);
try { _ctl.Bounds = new System.Drawing.Rectangle(0, CaptionPx, Math.Max(0, rc.W), Math.Max(0, rc.H - CaptionPx)); } catch { }
}
// ---- teardown ----
/// <summary>Drops the controller and environment (profile switch, browser exit, shutdown). Pending creations become stale.</summary>
private void TearDownWebView()
{
_createSeq++;
_creating = false;
_needsRecreate = false;
CoreWebView2? web = _web;
CoreWebView2Controller? ctl = _ctl;
_web = null;
_ctl = null;
_wvEnv = null;
_profileFolder = null;
_browserPid = 0;
if (web != null)
{
try
{
web.NavigationStarting -= OnNavigationStarting;
web.NavigationCompleted -= OnNavigationCompleted;
web.NewWindowRequested -= OnNewWindowRequested;
web.PermissionRequested -= OnPermissionRequested;
web.ProcessFailed -= OnProcessFailed;
web.LaunchingExternalUriScheme -= OnLaunchingExternalUriScheme;
}
catch { }
}
if (ctl != null)
{
try { ctl.AcceleratorKeyPressed -= OnAcceleratorKeyPressed; } catch { }
try { ctl.Close(); } catch { }
}
}
private void TeardownOnPanelThread()
{
if (_tornDown) return;
_tornDown = true;
_open = false;
if (_hook != IntPtr.Zero) { UnhookWinEvent(_hook); _hook = IntPtr.Zero; }
if (_timerOn && _staHwnd != IntPtr.Zero) { KillTimer(_staHwnd, TimerId); _timerOn = false; }
TearDownWebView();
if (_staHwnd != IntPtr.Zero) { DestroyWindow(_staHwnd); _staHwnd = IntPtr.Zero; }
lock (_sync) _hwnd = IntPtr.Zero;
if (_className.Length != 0) { UnregisterClassW(_className, GetModuleHandleW(IntPtr.Zero)); _className = ""; }
if (_bgBrush != IntPtr.Zero) { DeleteObject(_bgBrush); _bgBrush = IntPtr.Zero; }
if (_captionBrush != IntPtr.Zero) { DeleteObject(_captionBrush); _captionBrush = IntPtr.Zero; }
if (s_active == this) s_active = null;
_req = null;
PostQuitMessage(0);
}
}

View file

@ -0,0 +1,80 @@
using System;
using System.IO;
using System.Text.Json;
namespace RynthCore.Engine.WebPanel;
/// <summary>
/// The panel's remembered placement: &lt;LocalAppData&gt;\RynthCore\WebPanel\layout.json, {"x","y","w","h"} as
/// fractions of the game client rect (WebPanelWindowPolicy.FromUserRect). A valid stored layout beats the
/// caller's percentages. Called on the panel thread only.
/// </summary>
internal static class WebPanelLayoutStore
{
public static string PathFor(string localAppData) => Path.Combine(localAppData, "RynthCore", "WebPanel", "layout.json");
public static bool TryLoad(string localAppData, out PanelFractions layout)
{
layout = default;
try
{
string path = PathFor(localAppData);
if (!File.Exists(path)) return false;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object) return false;
if (!Num(r, "x", out double x) || !Num(r, "y", out double y) || !Num(r, "w", out double w) || !Num(r, "h", out double h)) return false;
var f = new PanelFractions(x, y, w, h);
if (!IsValid(f)) return false;
layout = f;
return true;
}
catch (Exception)
{
return false;
}
}
public static bool IsValid(PanelFractions f)
{
const double Slack = 1e-6;
if (!double.IsFinite(f.X) || !double.IsFinite(f.Y) || !double.IsFinite(f.W) || !double.IsFinite(f.H)) return false;
if (f.W <= 0 || f.H <= 0 || f.W > 1 + Slack || f.H > 1 + Slack) return false;
if (f.X < 0 || f.Y < 0) return false;
return f.X + f.W <= 1 + Slack && f.Y + f.H <= 1 + Slack;
}
/// <summary>Writes the layout (temp file, then a replace). False (and nothing written) when invalid or on an I/O error.</summary>
public static bool Save(string localAppData, PanelFractions f)
{
if (!IsValid(f)) return false;
try
{
string path = PathFor(localAppData);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var w = new Utf8JsonWriter(fs))
{
w.WriteStartObject();
w.WriteNumber("x", f.X);
w.WriteNumber("y", f.Y);
w.WriteNumber("w", f.W);
w.WriteNumber("h", f.H);
w.WriteEndObject();
}
File.Move(tmp, path, overwrite: true);
return true;
}
catch (Exception)
{
return false;
}
}
private static bool Num(JsonElement r, string name, out double v)
{
v = 0;
return r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.Number && e.TryGetDouble(out v);
}
}

View file

@ -0,0 +1,95 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.WebPanel;
/// <summary>Win32 for the web panel host (CoreCLR engine only). From the 2026-11-07 WebView2 spike's Native.cs.</summary>
internal static unsafe class WebPanelNative
{
public const uint WS_POPUP = 0x80000000, WS_CLIPCHILDREN = 0x02000000, WS_THICKFRAME = 0x00040000;
public const uint WS_EX_TOOLWINDOW = 0x00000080;
public const uint CS_VREDRAW = 0x0001, CS_HREDRAW = 0x0002;
public const uint WM_NCCREATE = 0x0081, WM_SIZE = 0x0005, WM_SETFOCUS = 0x0007, WM_PAINT = 0x000F, WM_CLOSE = 0x0010,
WM_NCHITTEST = 0x0084, WM_LBUTTONDOWN = 0x0201, WM_TIMER = 0x0113, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232,
WM_APP = 0x8000;
public const int HTCLIENT = 1, HTCAPTION = 2;
public const uint SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOACTIVATE = 0x0010;
public const int SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_SHOWNA = 8;
public const uint GW_HWNDPREV = 3, GA_ROOT = 2;
public static readonly IntPtr HWND_TOP = IntPtr.Zero;
public const uint EVENT_SYSTEM_FOREGROUND = 0x0003, WINEVENT_OUTOFCONTEXT = 0x0000;
public const int TRANSPARENT = 1, DEFAULT_GUI_FONT = 17, IDC_ARROW = 32512;
public const uint DT_LEFT = 0x0000, DT_CENTER = 0x0001, DT_VCENTER = 0x0004, DT_SINGLELINE = 0x0020, DT_NOPREFIX = 0x0800, DT_END_ELLIPSIS = 0x8000;
public static uint Rgb(int r, int g, int b) => (uint)(r | (g << 8) | (b << 16));
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; public int W => Right - Left; public int H => Bottom - Top; }
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
[StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; }
[StructLayout(LayoutKind.Sequential)]
public struct WNDCLASSEXW
{
public uint cbSize, style; public IntPtr lpfnWndProc; public int cbClsExtra, cbWndExtra;
public IntPtr hInstance, hIcon, hCursor, hbrBackground, lpszMenuName, lpszClassName, hIconSm;
}
[StructLayout(LayoutKind.Sequential)]
public struct PAINTSTRUCT { public IntPtr hdc; public int fErase; public RECT rcPaint; public int fRestore, fIncUpdate; public fixed byte rgbReserved[32]; }
[DllImport("user32.dll", SetLastError = true)] public static extern ushort RegisterClassExW(ref WNDCLASSEXW wc);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool UnregisterClassW(string cls, IntPtr hInst);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr CreateWindowExW(uint ex, string cls, string name, uint style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr param);
[DllImport("user32.dll")] public static extern bool DestroyWindow(IntPtr h);
[DllImport("user32.dll")] public static extern IntPtr DefWindowProcW(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr h, out RECT r);
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p);
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr h, ref POINT p);
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
[DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] public static extern int GetMessageW(out MSG m, IntPtr h, uint min, uint max);
[DllImport("user32.dll")] public static extern bool TranslateMessage(ref MSG m);
[DllImport("user32.dll")] public static extern IntPtr DispatchMessageW(ref MSG m);
[DllImport("user32.dll")] public static extern void PostQuitMessage(int code);
[DllImport("user32.dll")] public static extern IntPtr SetTimer(IntPtr h, IntPtr id, uint ms, IntPtr proc);
[DllImport("user32.dll")] public static extern bool KillTimer(IntPtr h, IntPtr id);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr h, uint cmd);
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr h, IntPtr rect, bool erase);
[DllImport("user32.dll")] public static extern IntPtr BeginPaint(IntPtr h, out PAINTSTRUCT ps);
[DllImport("user32.dll")] public static extern bool EndPaint(IntPtr h, ref PAINTSTRUCT ps);
[DllImport("user32.dll")] public static extern int FillRect(IntPtr dc, ref RECT r, IntPtr brush);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int DrawTextW(IntPtr dc, string text, int count, ref RECT r, uint format);
[DllImport("user32.dll")] public static extern IntPtr LoadCursorW(IntPtr inst, IntPtr name);
[DllImport("user32.dll")]
public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmod,
delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int, int, uint, uint, void> proc, uint pid, uint tid, uint flags);
[DllImport("user32.dll")] public static extern bool UnhookWinEvent(IntPtr hook);
[DllImport("gdi32.dll")] public static extern IntPtr CreateSolidBrush(uint color);
[DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr obj);
[DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
[DllImport("gdi32.dll")] public static extern IntPtr GetStockObject(int obj);
[DllImport("gdi32.dll")] public static extern uint SetTextColor(IntPtr dc, uint color);
[DllImport("gdi32.dll")] public static extern int SetBkMode(IntPtr dc, int mode);
[DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
[DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId();
[DllImport("kernel32.dll")] public static extern IntPtr GetModuleHandleW(IntPtr name);
/// <summary>ShellExecuteW, not Process.Start (the Process API is an AV hazard inside acclient.exe).</summary>
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr ShellExecuteW(IntPtr hwnd, string op, string file, string? parameters, string? dir, int show);
}

View file

@ -0,0 +1,55 @@
using System;
using System.Text;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.WebPanel;
/// <summary>One open request, every string already copied out of the caller's buffers.</summary>
internal sealed record WebPanelRequest(string Url, string[] Allowlist, string ProfileFolder, string Title, int WidthPercent, int HeightPercent, uint Flags);
/// <summary>
/// Reads the v93 WebPanelOpen argument. The SDK passes pointers into stack or pooled buffers that are gone
/// the moment the call returns, so every string is copied here, synchronously, before anything is queued.
/// Pure: no Win32, no WebView2.
/// </summary>
internal static unsafe class WebPanelNativeArgs
{
public const int MaxAllowlistBytes = 8192, MaxProfileKeyBytes = 256, MaxTitleBytes = 128;
public const uint KnownFlags = 1 | 2; // FallbackToBrowser, PageKeepsEscape
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
/// <summary>0 and a request, or BadArgs. URL policy (IsAllowed) is the host's to apply.</summary>
public static int TryBuildRequest(WebPanelOpenNative* open, string localAppData, string? worldName, out WebPanelRequest? request)
{
request = null;
if (open == null) return (int)WebPanelCode.BadArgs;
uint minSize = (uint)((byte*)open->Reserved - (byte*)open);
if (open->Size < minSize) return (int)WebPanelCode.BadArgs;
if (!TryReadUtf8(open->Url, WebPanelUrlPolicy.MaxUrlBytes, true, out string url)) return (int)WebPanelCode.BadArgs;
if (!TryReadUtf8(open->Allowlist, MaxAllowlistBytes, true, out string allowText)) return (int)WebPanelCode.BadArgs;
if (!TryReadUtf8(open->ProfileKey, MaxProfileKeyBytes, false, out string key)) return (int)WebPanelCode.BadArgs;
if (!TryReadUtf8(open->Title, MaxTitleBytes, false, out string title)) return (int)WebPanelCode.BadArgs;
if (!WebPanelUrlPolicy.TryParseAllowlist(allowText, out string[] allowlist)) return (int)WebPanelCode.BadArgs;
string folder = WebPanelProfile.Folder(localAppData, worldName, key);
request = new WebPanelRequest(url, allowlist, folder, title, open->WidthPercent, open->HeightPercent, open->Flags & KnownFlags);
return 0;
}
/// <summary>
/// A NUL-terminated UTF-8 string of at most <paramref name="maxBytes"/> bytes, copied. Null pointer:
/// "" (false when required). Required strings must not be empty; invalid UTF-8 is refused.
/// </summary>
public static bool TryReadUtf8(byte* p, int maxBytes, bool required, out string value)
{
value = "";
if (p == null) return !required;
int n = 0;
while (n <= maxBytes && p[n] != 0) n++;
if (n > maxBytes) return false;
if (n == 0) return !required;
try { value = StrictUtf8.GetString(p, n); }
catch (DecoderFallbackException) { return false; }
return true;
}
}