Web panel: an in-game WebView2 page for plugins (API v94) #12
36 changed files with 4580 additions and 8 deletions
44
Changelog/2026-11-07-web-panel.md
Normal file
44
Changelog/2026-11-07-web-panel.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# In-game web panel: plugin API v94
|
||||
|
||||
Branch `pr/web-panel`, from upstream `main` c68204f (release 2026.11.8.1). Not deployed. The API number 94
|
||||
follows upstream's v93 (GetMonsterHealth) and is provisional (unmerged upstream branches also use 94; whichever
|
||||
merges second renumbers). CoreCLR engine only.
|
||||
|
||||
## What changed
|
||||
|
||||
- Four new function slots at the end of the plugin API table (`WebPanelOpenFn`, `WebPanelNavigateFn`,
|
||||
`WebPanelCloseFn`, `WebPanelGetStateFn`), and SDK wrappers on `RynthCoreHost`: `HasWebPanel`,
|
||||
`OpenWebPanel(WebPanelOptions)`, `NavigateWebPanel`, `CloseWebPanel`, `GetWebPanelState`. Types are in
|
||||
`RynthCore.PluginSdk/WebPanelTypes.cs`. No call blocks its caller.
|
||||
- `WebPanel/WebPanelHost.cs` (engine): one WebView2 panel over the game window, on its own STA thread, with an
|
||||
unowned popup window, a caption bar with a close box, a remembered size and place, and Escape / Alt+F4 / `X` to close.
|
||||
- Navigation allowlist (`WebPanelUrlPolicy`): https only, default port, no user info, exact host or `*.suffix`
|
||||
(`*.x.com` does not match `x.com`: list both). Off-list navigations, pop-ups and custom-scheme launches never
|
||||
load in the panel; an absolute http(s) URL goes to the system browser, anything else is dropped.
|
||||
- Per-world, per-key WebView2 profile (`WebPanelProfile`): the plugin's key is lower-cased and hashed, and the world is added.
|
||||
- `/rc webpanel [status|close]`: a redacted one-line report, and a close.
|
||||
- `engine.json` `"WebPanel": false`: kill switch. `OpenWebPanel` then answers `Unavailable`.
|
||||
- `RynthCore.PluginSdk.targets` already raised a shared-SDK release build's `RynthPluginMinEngineApi` below 88 to the
|
||||
SDK's API; that is now 94 for every such plugin. Plugins that must run on older cores declare 88 or higher.
|
||||
- `tools\WebPanelHarness`: an offline 32-bit harness for the host (see the doc).
|
||||
- Docs: `docs/WEB_PANEL.md` is the plugin contract.
|
||||
|
||||
## How it behaves
|
||||
|
||||
- The panel is designed never to take focus from another program; confirm in game. It takes the foreground (and
|
||||
page focus) only if the foreground window already belongs to the game, and it hides while another program is in front.
|
||||
- Logs and chat never carry a URL's query, fragment or user info (the launch code rides in the query).
|
||||
- Failures: the panel fails only when the WebView2 browser process or the main renderer exits, or the renderer is
|
||||
reported unresponsive 3 times in 30 s. Other process failures are logged. `RuntimeMissing` / `CreateFailed` fall back to
|
||||
the system browser when the plugin asked for it (the default). Page permission `ClipboardRead` is allowed only
|
||||
for allowlisted origins; the rest are denied.
|
||||
- The NativeAOT engine flavour has no web panel: the slots stay zero and `HasWebPanel` is false.
|
||||
|
||||
## Tests
|
||||
|
||||
`tools/WebPanelTests`: URL allowlist and redaction, window visibility and layout, profile folder, the ABI glue.
|
||||
`tools/WebPanelHarness`: the host in a collectible load context against real WebView2 (needs a desktop, the
|
||||
WebView2 runtime and the x86 .NET 10 runtime; not part of `Run-AllTests.ps1`). Checks that need another program in
|
||||
the foreground report UNVERIFIED and are owner in-game checks.
|
||||
|
||||
Not yet tested in game.
|
||||
|
|
@ -76,3 +76,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
|
||||
## Microsoft WebView2 SDK (the in-game web panel)
|
||||
|
||||
- What: `Microsoft.Web.WebView2.Core.dll` (the managed WebView2 Core wrapper) and the x86 `WebView2Loader.dll`, which the engine uses to host the in-game web panel on the CoreCLR build. They find and drive the Evergreen WebView2 Runtime already installed on the machine; the runtime itself is not shipped.
|
||||
- Where: shipped in `Runtime\` of every CoreCLR install, referenced from `src/RynthCore.Engine/RynthCore.Engine.csproj` (NuGet `Microsoft.Web.WebView2` 1.0.2903.40). The package's WinForms and WPF assemblies are not used or shipped.
|
||||
- Source: https://www.nuget.org/packages/Microsoft.Web.WebView2
|
||||
- Licence: Microsoft's BSD-style licence, reproduced below from the package's own LICENSE.txt.
|
||||
|
||||
```
|
||||
Copyright (C) Microsoft Corporation. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* The name of Microsoft Corporation, or the names of its contributors
|
||||
may not be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
```
|
||||
|
|
|
|||
299
docs/WEB_PANEL.md
Normal file
299
docs/WEB_PANEL.md
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
# In-game web panel (plugin API v94)
|
||||
|
||||
A plugin can show a web page in a panel over the Asheron's Call window. The page runs in WebView2.
|
||||
The engine owns the window, the navigation allowlist, focus and the lifetime; the plugin passes a URL,
|
||||
an allowlist and a profile key, then polls for state. This file is the contract plugin authors build against.
|
||||
|
||||
The API number 94 is provisional: unmerged upstream branches also use 94, and whichever merges second
|
||||
renumbers (`PluginContractVersion.cs`). Write `HasWebPanel` checks, not `Version >= 94` checks. That keeps a plugin working
|
||||
across a renumber only for shared-SDK release builds. A NativeAOT plugin build compiles the `Version >= 94` test
|
||||
in, so a plugin built against the provisional SDK must not be distributed, and must be rebuilt after a renumber.
|
||||
|
||||
## Calls
|
||||
|
||||
The SDK wrappers are on `RynthCoreHost` (`RynthCore.PluginSdk`). None of them blocks, and all of them are safe
|
||||
to call from any thread (AC's main thread, the plugin pump, an ImGui draw). Never wait on the panel: call
|
||||
`OpenWebPanel`, return, and poll `GetWebPanelState`.
|
||||
|
||||
| Call | Does |
|
||||
|---|---|
|
||||
| `bool HasWebPanel` | True only on an engine at API 94 or newer that fills all four function slots. Check it before any other call. |
|
||||
| `int OpenWebPanel(WebPanelOptions)` | Opens the panel, or replaces the open one. Returns a handle > 0, or a negative `WebPanelResult`. |
|
||||
| `int NavigateWebPanel(int handle, string url)` | Points the open panel at a URL. `1` queued. |
|
||||
| `int CloseWebPanel(int handle)` | Closes the panel. `1` queued, `0` already closed. |
|
||||
| `WebPanelStatus GetWebPanelState(int handle, out WebPanelState state)` | Where the panel is. |
|
||||
|
||||
On an engine without the feature the wrappers return `Unavailable` (`GetWebPanelState` returns `None`).
|
||||
The NativeAOT engine flavour has no web panel: it leaves the four slots zero, so `HasWebPanel` is false there.
|
||||
Setting `"WebPanel": false` in `engine.json` is a kill switch: `OpenWebPanel` then returns `Unavailable`. A
|
||||
panel that is already open stays until it is closed.
|
||||
|
||||
### WebPanelOptions
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `Url` (required) | At most 4096 UTF-8 bytes. Must pass the same allowlist test as every other URL (below). |
|
||||
| `Allowlist` (required) | 1 to 16 entries; no `\n` inside an entry. |
|
||||
| `ProfileKey` | Opaque string, at most 256 UTF-8 bytes. Default empty. |
|
||||
| `Title` | Caption text, at most 128 UTF-8 bytes. Default empty, which shows "RynthCore". |
|
||||
| `WidthPercent`, `HeightPercent` | 0 means 88; otherwise clamped to 30..100. Used only when no layout has been remembered. |
|
||||
| `Flags` | `WebPanelFlags`. Default `FallbackToBrowser`. |
|
||||
|
||||
`WebPanelFlags`:
|
||||
|
||||
| Flag | Value | Meaning |
|
||||
|---|---|---|
|
||||
| `FallbackToBrowser` | 1 | If the panel cannot start (no WebView2 runtime, creation failed), the engine opens the URL in the system browser. |
|
||||
| `PageKeepsEscape` | 2 | Escape goes to the page instead of closing the panel. |
|
||||
|
||||
Bit 4 is reserved. Unknown bits are ignored.
|
||||
|
||||
### Return codes (`WebPanelResult`)
|
||||
|
||||
| Value | Name | Meaning |
|
||||
|---|---|---|
|
||||
| 1 | `Queued` | Navigate or Close accepted. |
|
||||
| 0 | `AlreadyClosed` | Close: the panel was already Closed or Failed. |
|
||||
| -1 | `BadArgs` | Empty URL or allowlist, more than 16 entries, a bad allowlist entry, a string over its byte limit, invalid UTF-8, or a struct `Size` that is too small. |
|
||||
| -2 | `UrlNotAllowed` | The URL is not allowed by the allowlist. See Navigate below. |
|
||||
| -3 | `NoGameWindow` | There is no game window to cover. |
|
||||
| -4 | `Unavailable` | Older engine, NativeAOT engine, `engine.json` kill switch, or an internal error. |
|
||||
| -5 | `ShuttingDown` | The engine is shutting down. |
|
||||
| -6 | `StaleHandle` | The handle is not the live panel (Navigate, Close). |
|
||||
| -7 | `RuntimeMissing` | State `Error` only: the WebView2 runtime is not installed. |
|
||||
| -8 | `CreateFailed` | State `Error` only: the panel window or WebView2 could not be created. |
|
||||
| -9 | `ProcessFailed` | State `Error` only: the WebView2 browser or renderer process died or hung. |
|
||||
|
||||
`OpenWebPanel` returns a handle (> 0) as soon as the request is queued. The panel loads after that, so a handle
|
||||
does not mean the page loaded. A later failure shows up in the state as `Failed` with `Error` set.
|
||||
|
||||
### State
|
||||
|
||||
`GetWebPanelState` returns the status and fills `WebPanelState(Handle, Status, Flags, Error, LastHttpStatus, NavigationCount)`.
|
||||
|
||||
| `WebPanelStatus` | Value | Meaning |
|
||||
|---|---|---|
|
||||
| `None` | 0 | Returned by the wrapper (not by the engine) on an older engine, bad arguments, or while the engine shuts down. |
|
||||
| `Starting` | 1 | Open accepted; the WebView2 window is being created. |
|
||||
| `Loading` | 2 | A navigation has started. |
|
||||
| `Ready` | 3 | A navigation completed. This means the page answered, not that it succeeded: check `LastHttpStatus`. |
|
||||
| `Closed` | 4 | Closed by the plugin, the player, or the engine. |
|
||||
| `Failed` | 5 | See `Error`. |
|
||||
| `Superseded` | 6 | The handle is not the live panel: a newer Open replaced it, or no panel was ever opened. |
|
||||
|
||||
`WebPanelStateFlags`: `Visible` = 1, `Focused` = 2, `OpenedInBrowser` = 4 (the engine's fallback opened the URL in
|
||||
the system browser). `LastHttpStatus` is the last non-zero HTTP status of a completed navigation. `NavigationCount`
|
||||
counts navigations that started on an allowed URL since Open (the `about:blank` the engine uses to clear the page is
|
||||
not counted).
|
||||
|
||||
## Allowlist
|
||||
|
||||
The allowlist decides what the panel may show. It is checked on Open, on Navigate, on every navigation the page
|
||||
starts itself, and on pop-up requests. Entries are matched against the URL's host:
|
||||
|
||||
- `host`: exactly that host. `example.com` matches `example.com` only.
|
||||
- `*.suffix`: any subdomain, at any depth, but not the suffix itself. `*.example.com` matches `a.example.com`
|
||||
and `a.b.example.com`, and does **not** match `example.com`. To allow both, list both entries.
|
||||
- The suffix after `*.` must contain a dot, so `*.com` is rejected.
|
||||
- No scheme, path, port or other `*`. Entries are lower-cased and trimmed. Through the SDK wrapper an empty entry
|
||||
(or one containing `\n`) is refused with `BadArgs`; at the native level, where the list is one `\n`-separated
|
||||
string, blank lines are ignored.
|
||||
- Entries are ASCII: letters, digits, `-` and `.`; each label 1 to 63 characters, not starting or ending with `-`;
|
||||
at most 253 characters per entry. Write an internationalised host in its punycode form (`xn--...`).
|
||||
- 1 to 16 entries, and the joined list must fit in 8192 bytes.
|
||||
|
||||
A URL is allowed only if it is `https`, has no user info, uses the default port (443), and its host matches an entry
|
||||
(compared in lower case, one trailing dot ignored, IDN hosts in punycode). `about:blank` is also always allowed.
|
||||
That means an `http:` URL and a URL with a port are never allowed, whatever the list says.
|
||||
|
||||
### What the engine does with a URL that is not allowed
|
||||
|
||||
- `OpenWebPanel`: returns `UrlNotAllowed` and opens nothing.
|
||||
- `NavigateWebPanel`: returns `UrlNotAllowed`, and the engine opens the URL in the system browser instead if it
|
||||
is absolute `http` or `https` without user info. Anything else is dropped and logged.
|
||||
- A navigation the page starts: cancelled, then handled the same way as Navigate.
|
||||
- `window.open` and other new-window requests: never a second window. An allowed URL loads in the panel; any
|
||||
other goes to the system browser as above.
|
||||
- Custom-scheme launches (`foo://`): blocked and logged.
|
||||
|
||||
When the engine opens the system browser for an off-list URL it writes `[RynthCore] Opened <host> in your web
|
||||
browser.` to chat. Only the host is shown. Logs and chat never contain a URL's query, fragment or user info (the
|
||||
launch code of a login URL rides in the query), only `scheme://host[:port]/path`.
|
||||
|
||||
### Page permissions
|
||||
|
||||
Everything the page asks permission for is denied, except `ClipboardRead`, which is allowed only for a frame whose
|
||||
URL is on the allowlist (a blank frame gets none). Developer tools, browser accelerator keys, the status bar,
|
||||
host objects, web messages and password autosave are all off.
|
||||
|
||||
## Profile key
|
||||
|
||||
WebView2 keeps cookies and storage in a profile folder. The plugin passes an opaque key; the engine builds the folder:
|
||||
|
||||
```
|
||||
<LocalAppData>\RynthCore\WebPanel\<world>\<hex>
|
||||
```
|
||||
|
||||
- `<hex>`: the key is trimmed and lower-cased, and the first 16 bytes of its SHA-256 (of the UTF-8 text) are written
|
||||
as lower-case hex. An empty key is the folder `default`.
|
||||
- `<world>`: the connected world's name, with every character outside `A-Z a-z 0-9 space _ -` replaced by `_`,
|
||||
at most 64 characters; empty becomes `_default`.
|
||||
|
||||
So the same key on two worlds is two separate profiles, and `Key` and `key` are the same profile. Use a key that
|
||||
names the site or account. Do not put a secret in it.
|
||||
Opening with a different profile than the last Open tears WebView2 down and creates it again; same profile, the
|
||||
WebView2 environment is reused.
|
||||
|
||||
## Window, focus and close
|
||||
|
||||
- The panel is a window over the game's client area, with a 28 px caption bar (the title, and an `X` close box).
|
||||
The caption bar drags it; the frame resizes it. Minimum size is 480 x 320, or the whole client if smaller.
|
||||
- The panel's size and place are remembered as fractions of the game window in
|
||||
`<LocalAppData>\RynthCore\WebPanel\layout.json`, shared by all profiles. A valid stored layout wins over
|
||||
`WidthPercent` / `HeightPercent`.
|
||||
- **The panel is designed never to take focus from another program; confirm in game.** On Open it takes the
|
||||
foreground, and moves keyboard focus into the page, only if the foreground window already belongs to the game's
|
||||
process; if the player is in another program (or mid alt-tab) it does neither.
|
||||
It hides while another program is in the foreground, and comes back when the game is. The panel's own
|
||||
WebView2 dialogs (alert, file picker) are meant not to count as another program: the engine treats the
|
||||
WebView2 browser process as its own. Whether those dialogs belong to that process is not yet confirmed in game.
|
||||
- The panel runs on its own thread, so a slow page never stalls the game's thread or the plugin pump.
|
||||
|
||||
The panel closes (status `Closed`) when:
|
||||
|
||||
- the plugin calls `CloseWebPanel(handle)`;
|
||||
- the player presses Escape (unless `PageKeepsEscape` is set), clicks the `X`, or presses Alt+F4 on the panel;
|
||||
- the game window goes away;
|
||||
- `/rc webpanel close` runs;
|
||||
- a newer `OpenWebPanel` replaces it (the old handle then reads `Superseded`).
|
||||
|
||||
Closing hides the panel and loads `about:blank`; the WebView2 environment stays for the next Open. `CloseWebPanel`
|
||||
returns `1` (queued) for the live panel, `0` if it is already `Closed` or `Failed`, and `-6` for any other handle.
|
||||
After `Closed` or `Failed`, `NavigateWebPanel` returns `StaleHandle`.
|
||||
At engine shutdown the panel is torn down after the plugins' own Shutdown, so a plugin may still call Close there.
|
||||
|
||||
## Failures
|
||||
|
||||
The state is `Failed`, with `Error` set, and the panel is hidden.
|
||||
|
||||
- `RuntimeMissing` / `CreateFailed`: the panel could not start. With `FallbackToBrowser`, and only if no navigation
|
||||
has happened yet and the URL is absolute `http` or `https`, the engine tries to open the URL in the system browser.
|
||||
Only if the browser opens does it set `OpenedInBrowser` and tell the player the page opened there; the plugin
|
||||
must not open it a second time. If the browser does not open, `OpenedInBrowser` stays clear and chat says
|
||||
`[RynthCore] The in-game browser could not start (<why>), and your web browser did not open.`
|
||||
The status stays at its earlier value while the browser launches; `Failed`, the error and `OpenedInBrowser`
|
||||
then appear together, so a poll never sees `Failed` before the engine has decided.
|
||||
- `ProcessFailed`: the engine fails the panel for only these causes: the WebView2 browser process exited
|
||||
(`BrowserProcessExited`), the page's main renderer exited (`RenderProcessExited`), or the renderer is reported
|
||||
unresponsive (`RenderProcessUnresponsive`) 3 times within 30 seconds of the first report (a completed
|
||||
navigation or a new Open resets that count). Every other kind of process failure (GPU, utility, a
|
||||
frame-only renderer, and so on) is logged and the panel is kept. There is never a browser fallback for
|
||||
`ProcessFailed`: a navigation already ran, so the launch code is spent. Open again to retry; WebView2 is
|
||||
recreated.
|
||||
|
||||
## Plugins that must run on older cores
|
||||
|
||||
A plugin built against this SDK runs against the installed core's `Runtime\PluginShared` copy of the SDK. If you want
|
||||
the plugin to keep working on a core without the web panel, with ShellExecute as the fallback:
|
||||
|
||||
1. **Declare `RynthPluginMinEngineApi` at the plugin's true minimum.** In release builds
|
||||
(`-p:RynthPluginSharedSdk=true`, as `Publish-Update.ps1` and `Build-Installer.ps1` pass), a declared minimum
|
||||
*below 88* is raised to the API of the SDK the plugin was built with (94 now), and the launcher then holds the
|
||||
plugin back from older cores, which kills the fallback (`RynthCore.PluginSdk.targets`: `RynthCoreManagedPluginApi`
|
||||
is 88). There is no separate opt-out property: declaring a minimum of **88 or higher** is the opt-out, and a
|
||||
declared 88 or higher is used as it is. Declare the lowest API your plugin really needs at load, and make
|
||||
sure every call newer than that sits behind its `Has*` check. (`RynthPluginManifest=false` drops the manifest
|
||||
altogether, and with it the minimum; do not use it for this.) The build prints a message when it raises a minimum.
|
||||
2. **Put every reference to `HasWebPanel`, `OpenWebPanel`, `WebPanelOptions` and the other WebPanel types in one helper
|
||||
marked `[MethodImpl(MethodImplOptions.NoInlining)]`, taking only strings,** and call it inside
|
||||
`try { } catch (MissingMethodException) { } catch (TypeLoadException) { }`. An older `PluginShared` SDK without
|
||||
these members fails the method (or the type load), not the plugin's load.
|
||||
3. **Fall back to ShellExecute** when the helper throws, when `HasWebPanel` is false, or when `OpenWebPanel` returns
|
||||
`Unavailable`, `NoGameWindow` or `ShuttingDown`. Do nothing more when the state is `Failed` with `OpenedInBrowser`
|
||||
(the engine already opened it). Never fall back on `UrlNotAllowed` (or `BadArgs`): those are plugin bugs, and
|
||||
sending the URL to the browser hides them. Only pass absolute `http` or `https` URLs without user info to ShellExecute.
|
||||
|
||||
```csharp
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
// Returns false when the caller should open the page in the system browser itself.
|
||||
private bool TryShowPanel(string url, string profileKey)
|
||||
{
|
||||
try { return ShowPanelCore(url, profileKey); }
|
||||
catch (MissingMethodException) { return false; }
|
||||
catch (TypeLoadException) { return false; }
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private bool ShowPanelCore(string url, string profileKey)
|
||||
{
|
||||
if (!Host.HasWebPanel) return false;
|
||||
int h = Host.OpenWebPanel(new WebPanelOptions
|
||||
{
|
||||
Url = url,
|
||||
Allowlist = new[] { "example.com", "*.example.com" },
|
||||
ProfileKey = profileKey,
|
||||
Title = "Example",
|
||||
});
|
||||
if (h > 0) { _panelHandle = h; return true; }
|
||||
var r = (WebPanelResult)h;
|
||||
return !(r == WebPanelResult.Unavailable || r == WebPanelResult.NoGameWindow || r == WebPanelResult.ShuttingDown);
|
||||
}
|
||||
```
|
||||
|
||||
Poll the state from a second helper written the same way (`GetWebPanelState` and `WebPanelState` are SDK types too).
|
||||
|
||||
## Native layout (for callers that do not use the SDK wrappers)
|
||||
|
||||
`RynthCoreAPI` gains four function pointers at the end of the table, in this order, all `cdecl`:
|
||||
`int WebPanelOpen(WebPanelOpenNative*)`, `int WebPanelNavigate(int handle, byte* url)`,
|
||||
`int WebPanelClose(int handle)`, `int WebPanelGetState(int handle, WebPanelStateNative*)`.
|
||||
Test `Version >= 94` before reading them: an older engine's table is shorter.
|
||||
|
||||
`WebPanelOpenNative` (pack 4, 48 bytes on x86): `uint Size`, `uint Flags`, `byte* Url`, `byte* Allowlist`
|
||||
(`\n`-separated), `byte* ProfileKey` (may be null), `byte* Title` (may be null), `int WidthPercent`, `int HeightPercent`,
|
||||
`uint Reserved[4]`. All strings are NUL-terminated UTF-8; the engine copies them before the call returns. It accepts
|
||||
`Size` of 32 or more.
|
||||
|
||||
`WebPanelStateNative` (pack 4, 48 bytes): `uint Size`, `int Handle`, `int Status`, `uint Flags`, `int Error`,
|
||||
`int LastHttpStatus`, `uint NavigationCount`, `uint Reserved[5]`. The engine accepts `Size` of 28 or more and writes
|
||||
only the fields before `Reserved`. At the native level `WebPanelGetState` returns the status (a handle that is not the
|
||||
live panel reads 6) or a negative code (`-1` bad arguments, `-4` unavailable: an internal exception, or an engine
|
||||
build without the panel, `-5` shutting down); the wrapper turns a negative into `None`.
|
||||
|
||||
## /rc webpanel
|
||||
|
||||
- `/rc webpanel` or `/rc webpanel status`: one line, redacted (no query, fragment or user info): thread state,
|
||||
handle, status, error, HTTP status, navigation count, WebView2 environments created, visible / focused / in browser,
|
||||
the WebView2 browser process id, the URL as `scheme://host/path`, whether the `engine.json` setting is on, and the
|
||||
free address space. It never opens a URL.
|
||||
- `/rc webpanel close`: closes the live panel. Replies `web panel: closing.`, `web panel: already closed.`, or
|
||||
`web panel: nothing to close.` when no panel was ever opened.
|
||||
|
||||
## Offline harness
|
||||
|
||||
`tools\WebPanelHarness` runs the real panel host in a 32-bit stand-in for the game, with a fake game window, a fake
|
||||
plugin pump and a collectible load context like the engine's. Pages are served from local folders through
|
||||
virtual hosts (`panel.test`, `other.test`), so it needs no network.
|
||||
|
||||
```
|
||||
cd tools\WebPanelHarness
|
||||
dotnet run -c Release
|
||||
```
|
||||
|
||||
Prerequisites:
|
||||
|
||||
- A desktop session (it opens windows) and the Evergreen WebView2 runtime.
|
||||
- A **32-bit dotnet host**: the x86 .NET 10 runtime (the x86 SDK from `BUILD.md` brings it). The harness
|
||||
refuses to run unless the process is 32-bit like acclient (`FAIL Bitness`).
|
||||
- `--foreground` (or `WEBPANEL_HARNESS_FOREGROUND=1`) is an opt-in: the harness then asks Windows to put its fake game
|
||||
window in the foreground, so the foreground-dependent checks (Escape hands focus back, same-process visibility)
|
||||
can run. Without the opt-in, or when Windows refuses the request because you are active in another program,
|
||||
those checks print `UNVERIFIED`. `--payload=<dir>` overrides the payload folder.
|
||||
- It posts input to its own windows only and never uses `SendInput`, so it does not steer a live game client on
|
||||
the same desktop. It is not part of `scripts\Run-AllTests.ps1`.
|
||||
|
||||
Each check prints `ok <name>`, `FAIL <name>: ...` or `UNVERIFIED <name>: ...` (not provable offline, an owner in-game
|
||||
check). Exit code 0 = all ok, 1 = a FAIL, 2 = no FAIL but something UNVERIFIED. The output is also written to
|
||||
`harness-output.txt` under `%TEMP%\rynth-webpanel-harness\<timestamp>\`.
|
||||
|
|
@ -339,6 +339,17 @@ if ($SkipDecalBridge) {
|
|||
# release.txt — which core release this install is ($release, from -Version at the top).
|
||||
Set-Content -Path "$StagingDir\release.txt" -Value @($release, $Version) -Encoding ASCII
|
||||
|
||||
# The PE machine field of a DLL (e_lfanew at 0x3C, then the COFF Machine at PE offset + 4). The game is
|
||||
# 32-bit, so the web panel's native loader must be the x86 one (0x14C): the NuGet package also carries
|
||||
# win-x64 and win-arm64 copies that would load nowhere.
|
||||
function Assert-PeMachine([string]$Path, [int]$Expected) {
|
||||
$bytes = [System.IO.File]::ReadAllBytes($Path)
|
||||
if ($bytes.Length -lt 0x40) { throw "$Path is not a PE file (too short)" }
|
||||
$pe = [System.BitConverter]::ToInt32($bytes, 0x3C)
|
||||
if ($pe -lt 0 -or $pe + 6 -gt $bytes.Length) { throw "$Path is not a PE file (bad e_lfanew)" }
|
||||
$machine = [System.BitConverter]::ToUInt16($bytes, $pe + 4)
|
||||
if ($machine -ne $Expected) { throw ("{0}: PE machine 0x{1:X}, expected 0x{2:X}" -f $Path, $machine, $Expected) }
|
||||
}
|
||||
# Everything a working install needs. The 2026-09-25 public installer went out
|
||||
# without the Loader and the SEH trampoline because nothing checked.
|
||||
$required = @(
|
||||
|
|
@ -359,7 +370,9 @@ if (-not $NativeAot) {
|
|||
$required += @(
|
||||
"$StagingDir\Runtime\RynthCore.Shim.dll",
|
||||
"$StagingDir\Runtime\dotnet\coreclr.dll",
|
||||
"$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll"
|
||||
"$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll",
|
||||
"$StagingDir\Runtime\Microsoft.Web.WebView2.Core.dll",
|
||||
"$StagingDir\Runtime\WebView2Loader.dll"
|
||||
)
|
||||
}
|
||||
if (-not $SkipDecalBridge) {
|
||||
|
|
@ -367,7 +380,9 @@ if (-not $SkipDecalBridge) {
|
|||
}
|
||||
$missing = @($required | Where-Object { -not (Test-Path $_) })
|
||||
if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" }
|
||||
|
||||
if (-not $NativeAot) {
|
||||
Assert-PeMachine "$StagingDir\Runtime\WebView2Loader.dll" 0x14C
|
||||
}
|
||||
# Report staged sizes
|
||||
$engineDll = "$StagingDir\Runtime\RynthCore.Engine.dll"
|
||||
if (Test-Path $engineDll) {
|
||||
|
|
|
|||
|
|
@ -200,6 +200,7 @@ internal static class ChatCommandReplies
|
|||
V("vitals", "Usage: /rc vitals (the old vitals HUD is gone: /rv plates self)", NoArgs, "hud"),
|
||||
V("layout", "Usage: /rc layout [status] | default | reset [confirm]", LayoutArgs),
|
||||
V("uicost", UiCostUsage, null),
|
||||
V("webpanel", "Usage: /rc webpanel [status|close] (status is a redacted one-line report; it never opens a URL)", Words("", "status", "close")),
|
||||
};
|
||||
|
||||
/// <summary>/rc uicost: the UI frame cost breakdown (ImGui/UiCost.cs).</summary>
|
||||
|
|
|
|||
|
|
@ -108,6 +108,9 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// <item><c>/rc uicost [on|off|<ms>|now|status]</c> - the UI frame cost breakdown
|
||||
/// (<see cref="ImGuiBackend.UiCost"/>): timing on or off, the slow-frame threshold, and (now, or
|
||||
/// alone) which parts of the UI frame took the time over the last seconds. Also Settings > Diagnostics.</item>
|
||||
/// <item><c>/rc webpanel [status|close]</c> - the in-game web panel (<see cref="WebPanel.WebPanelApi"/>):
|
||||
/// status is one redacted line (state, handle, visible/focused, browser pid, free address space);
|
||||
/// close closes the panel. It never opens a URL.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class RynthCoreChatCommands
|
||||
|
|
@ -650,6 +653,13 @@ internal static class RynthCoreChatCommands
|
|||
SenseLayoutCommand(senseArgs); // alone, /rc sense opens or closes the panel (the switch below)
|
||||
return;
|
||||
}
|
||||
// /rc webpanel [status|close]: diagnostics for the in-game web panel. It never opens a URL
|
||||
// (an arbitrary-URL command would be a phishing vector); every URL in the line is redacted.
|
||||
if (IsVerb(sub, "webpanel", out string webPanelArgs))
|
||||
{
|
||||
HandleWebPanelCommand(webPanelArgs);
|
||||
return;
|
||||
}
|
||||
// /rc layout [status] | default | reset [confirm]: this client's panel layout (UI/PanelLayout).
|
||||
if (IsVerb(sub, "layout", out string layoutArgs))
|
||||
{
|
||||
|
|
@ -1716,6 +1726,27 @@ internal static class RynthCoreChatCommands
|
|||
ReplyLines(UI.Data.Discord.ChatDiscord.HandleCommand(verb));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /rc webpanel [status|close]. Status: one redacted line (WebPanelApi.Describe plus the address
|
||||
/// space). Close: closes the live panel (WebPanelApi.Close does not block). Nothing here opens a URL.
|
||||
/// </summary>
|
||||
private static void HandleWebPanelCommand(string args)
|
||||
{
|
||||
string a = args.Trim().ToLowerInvariant();
|
||||
if (a == "close")
|
||||
{
|
||||
int handle = WebPanel.WebPanelApi.LiveHandle;
|
||||
if (handle <= 0) { Reply("web panel: nothing to close."); return; }
|
||||
int rc = WebPanel.WebPanelApi.Close(handle);
|
||||
// 1 = closing, 0 = already closed (the WebPanelCode values); anything else is a refusal or error.
|
||||
if (rc == 1) Reply("web panel: closing.");
|
||||
else if (rc == 0) Reply("web panel: already closed.");
|
||||
else Fail($"web panel: could not close (code {rc}).");
|
||||
return;
|
||||
}
|
||||
Reply(WebPanel.WebPanelApi.Describe() + "; address space " + AddressSpace.Describe());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /rc layout: which panel layout this client uses and its files (UI/PanelLayout: the character's own,
|
||||
/// or the PC-wide default and why); default makes this character's the default for new characters;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 v94 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 v94 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
|
||||
|
|
|
|||
|
|
@ -1069,6 +1069,74 @@ internal struct RynthCoreAPI
|
|||
/// reading, 0 without (never read; *ratio = -1, *ageMs = 0xFFFFFFFF). Either pointer may be null.
|
||||
/// Read-only, any thread, no game calls. Requires API v93+.</summary>
|
||||
public IntPtr GetMonsterHealthFn;
|
||||
|
||||
// ── v94: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ──
|
||||
// No call blocks its caller (AC's main thread, the plugin pump and ImGui draws all call these).
|
||||
|
||||
/// <summary>v94: <c>int WebPanelOpen(WebPanelOpenNative* open)</c>: opens (or replaces) the web panel.
|
||||
/// Returns a handle > 0, or BadArgs / UrlNotAllowed / NoGameWindow / Unavailable / ShuttingDown
|
||||
/// (WebPanelCode). Requires API v94+ (provisional number).</summary>
|
||||
public IntPtr WebPanelOpenFn;
|
||||
/// <summary>v94: <c>int WebPanelNavigate(int handle, byte* url)</c>: 1 queued; -2 off the allowlist
|
||||
/// (opened in the system browser when it is browser-safe); -6 stale handle.</summary>
|
||||
public IntPtr WebPanelNavigateFn;
|
||||
/// <summary>v94: <c>int WebPanelClose(int handle)</c>: 1 queued, 0 already closed, -6 stale handle.</summary>
|
||||
public IntPtr WebPanelCloseFn;
|
||||
/// <summary>v94: <c>int WebPanelGetState(int handle, WebPanelStateNative* state)</c>: the WebPanelStatusCode
|
||||
/// (a handle that is not the live one reads 6 Superseded), -1 bad args.</summary>
|
||||
public IntPtr WebPanelGetStateFn;
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct WebPanelOpenNative
|
||||
{
|
||||
/// <summary>sizeof the caller's struct; the engine accepts Size >= OffsetOf(Reserved) (32 on x86).</summary>
|
||||
public uint Size;
|
||||
/// <summary>WebPanelFlags; unknown bits ignored.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>UTF-8 NUL-terminated, at most 4096 bytes, must pass the URL policy's IsAllowed.</summary>
|
||||
public byte* Url;
|
||||
/// <summary>UTF-8, '\n'-separated allowlist (WebPanelUrlPolicy.TryParseAllowlist).</summary>
|
||||
public byte* Allowlist;
|
||||
/// <summary>UTF-8, may be null; at most 256 bytes.</summary>
|
||||
public byte* ProfileKey;
|
||||
/// <summary>UTF-8, may be null; at most 128 bytes.</summary>
|
||||
public byte* Title;
|
||||
/// <summary>0 = 88, else 30..100 (only when no remembered layout).</summary>
|
||||
public int WidthPercent;
|
||||
public int HeightPercent;
|
||||
public fixed uint Reserved[4];
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelGetState result (Pack 4; 48 bytes). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct WebPanelStateNative
|
||||
{
|
||||
public uint Size;
|
||||
public int Handle;
|
||||
/// <summary>WebPanelStatusCode.</summary>
|
||||
public int Status;
|
||||
/// <summary>1 Visible, 2 Focused, 4 OpenedInBrowser.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>0 or a negative WebPanelCode (RuntimeMissing / CreateFailed / ProcessFailed).</summary>
|
||||
public int Error;
|
||||
public int LastHttpStatus;
|
||||
public uint NavigationCount;
|
||||
public fixed uint Reserved[5];
|
||||
}
|
||||
|
||||
/// <summary>v94 return codes of the web panel calls. Append only.</summary>
|
||||
internal enum WebPanelCode
|
||||
{
|
||||
Queued = 1, AlreadyClosed = 0, BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3,
|
||||
Unavailable = -4, ShuttingDown = -5, StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9,
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelStateNative.Status values. Append only.</summary>
|
||||
internal enum WebPanelStatusCode
|
||||
{
|
||||
None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6,
|
||||
}
|
||||
|
||||
/// <summary>v89 GetUiColor tokens. Append only: plugins compiled against these numbers keep them.</summary>
|
||||
|
|
@ -1930,6 +1998,18 @@ internal unsafe delegate int GetAmbientLightCallbackDelegate(uint* client, uint*
|
|||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetMonsterHealthCallbackDelegate(uint id, float* ratio, uint* ageMs);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WebPanelOpenCallbackDelegate(WebPanelOpenNative* open);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WebPanelNavigateCallbackDelegate(int handle, byte* url);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int WebPanelCloseCallbackDelegate(int handle);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WebPanelGetStateCallbackDelegate(int handle, WebPanelStateNative* state);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count);
|
||||
|
||||
|
|
|
|||
|
|
@ -47,5 +47,9 @@ internal static class PluginContractVersion
|
|||
// any thread (feature/hud-health-for-plugins, 2026-11-07). Note: feature/reload-state,
|
||||
// feature/engine-events and the branches built on them (unmerged) also use 93 and 94; whichever
|
||||
// merges second renumbers.
|
||||
public const uint Current = 93;
|
||||
// v94: WebPanelOpen, WebPanelNavigate, WebPanelClose and WebPanelGetState: a WebView2 web panel over the
|
||||
// game window (WebPanel\WebPanelApi.cs; DreamWeave's in-game market and tools), appended after v93's
|
||||
// GetMonsterHealth (was v93 on up/web-panel; renumbered after upstream's v93). The number is
|
||||
// PROVISIONAL: the unmerged branches named under v93 also use 94; whichever merges second renumbers.
|
||||
public const uint Current = 94;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -304,6 +304,12 @@ internal static partial class PluginManager
|
|||
private static SetAmbientLightFloorCallbackDelegate? _setAmbientLightFloorCallback; // v91
|
||||
private static GetAmbientLightCallbackDelegate? _getAmbientLightCallback; // v91
|
||||
private static GetMonsterHealthCallbackDelegate? _getMonsterHealthCallback; // v93
|
||||
#if ENGINE_CORECLR
|
||||
private static WebPanelOpenCallbackDelegate? _webPanelOpenCallback; // v94
|
||||
private static WebPanelNavigateCallbackDelegate? _webPanelNavigateCallback; // v94
|
||||
private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v94
|
||||
private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v94
|
||||
#endif
|
||||
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
|
||||
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
|
||||
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
|
||||
|
|
@ -3254,6 +3260,13 @@ internal static partial class PluginManager
|
|||
_setAmbientLightFloorCallback ??= AmbientLight.SetFloor; // v91
|
||||
unsafe { _getAmbientLightCallback ??= AmbientLight.Get; }
|
||||
unsafe { _getMonsterHealthCallback ??= GetMonsterHealthAction; } // v93
|
||||
#if ENGINE_CORECLR
|
||||
// v94: the AOT engine leaves these slots zero, so HasWebPanel is false there.
|
||||
unsafe { _webPanelOpenCallback ??= WebPanel.WebPanelApi.Open; }
|
||||
unsafe { _webPanelNavigateCallback ??= WebPanel.WebPanelApi.Navigate; }
|
||||
_webPanelCloseCallback ??= WebPanel.WebPanelApi.Close;
|
||||
unsafe { _webPanelGetStateCallback ??= WebPanel.WebPanelApi.GetState; }
|
||||
#endif
|
||||
|
||||
_api.Version = PluginContractVersion.Current;
|
||||
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
|
||||
|
|
@ -3427,6 +3440,12 @@ internal static partial class PluginManager
|
|||
_api.SetAmbientLightFloorFn = Marshal.GetFunctionPointerForDelegate(_setAmbientLightFloorCallback);
|
||||
_api.GetAmbientLightFn = Marshal.GetFunctionPointerForDelegate(_getAmbientLightCallback);
|
||||
_api.GetMonsterHealthFn = Marshal.GetFunctionPointerForDelegate(_getMonsterHealthCallback);
|
||||
#if ENGINE_CORECLR
|
||||
_api.WebPanelOpenFn = Marshal.GetFunctionPointerForDelegate(_webPanelOpenCallback!);
|
||||
_api.WebPanelNavigateFn = Marshal.GetFunctionPointerForDelegate(_webPanelNavigateCallback!);
|
||||
_api.WebPanelCloseFn = Marshal.GetFunctionPointerForDelegate(_webPanelCloseCallback!);
|
||||
_api.WebPanelGetStateFn = Marshal.GetFunctionPointerForDelegate(_webPanelGetStateCallback!);
|
||||
#endif
|
||||
RouteApiThroughLoader();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,8 +43,37 @@
|
|||
<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>
|
||||
|
||||
<!--
|
||||
v94 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'" />
|
||||
<!-- The Core wrapper's XML doc file is not needed at run time. -->
|
||||
<ReferenceCopyLocalPaths Remove="@(ReferenceCopyLocalPaths)" Condition="'%(Filename)%(Extension)' == 'Microsoft.Web.WebView2.Core.xml'" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<StackTraceSupport>true</StackTraceSupport>
|
||||
<DebugType>full</DebugType>
|
||||
|
|
|
|||
63
src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs
Normal file
63
src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs
Normal 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 "";
|
||||
}
|
||||
}
|
||||
32
src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs
Normal file
32
src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs
Normal 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; }
|
||||
}
|
||||
142
src/RynthCore.Engine/WebPanel/WebPanelApi.cs
Normal file
142
src/RynthCore.Engine/WebPanel/WebPanelApi.cs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
#if ENGINE_CORECLR
|
||||
/// <summary>
|
||||
/// The engine side of the v94 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 unsafe class WebPanelApi
|
||||
{
|
||||
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;
|
||||
|
||||
internal static int Open(WebPanelOpenNative* open)
|
||||
{
|
||||
try
|
||||
{
|
||||
int refusal = WebPanelApiRules.OpenRefusal(s_shutdown || EngineLifecycle.IsShuttingDown, EngineSettings.WebPanel);
|
||||
if (refusal != 0) return refusal;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int Navigate(int handle, byte* urlUtf8)
|
||||
{
|
||||
try
|
||||
{
|
||||
int refusal = WebPanelApiRules.CallRefusal(s_shutdown);
|
||||
if (refusal != 0) return refusal;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int Close(int handle)
|
||||
{
|
||||
try
|
||||
{
|
||||
int refusal = WebPanelApiRules.CallRefusal(s_shutdown);
|
||||
if (refusal != 0) return refusal;
|
||||
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 (!WebPanelApiRules.StateArgsOk(state)) return (int)WebPanelCode.BadArgs;
|
||||
int refusal = WebPanelApiRules.CallRefusal(s_shutdown);
|
||||
if (refusal != 0) return refusal;
|
||||
WebPanelHost? host = s_host;
|
||||
WebPanelSnapshot s;
|
||||
int r;
|
||||
if (host == null)
|
||||
{
|
||||
s = WebPanelApiRules.NoPanel(handle);
|
||||
r = s.Status;
|
||||
}
|
||||
else
|
||||
{
|
||||
r = host.GetState(handle, out s);
|
||||
}
|
||||
WebPanelApiRules.WriteState(state, s);
|
||||
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>The live panel handle, 0 when none was opened: lets the engine close it (WebPanelApi.Close(LiveHandle)).</summary>
|
||||
internal static int LiveHandle => s_host?.LiveHandle ?? 0;
|
||||
|
||||
/// <summary>Redacted one-liner (no query, fragment or userinfo); includes the WebView2 browser pid.</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 v94 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 int LiveHandle => 0;
|
||||
internal static string Describe() => "web panel: not available in this engine build";
|
||||
}
|
||||
#endif
|
||||
46
src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs
Normal file
46
src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>What WebPanelGetState reports for one handle.</summary>
|
||||
internal readonly record struct WebPanelSnapshot(int Handle, int Status, uint Flags, int Error, int LastHttpStatus, uint NavigationCount);
|
||||
|
||||
/// <summary>
|
||||
/// The pure decisions of the v94 ABI glue (WebPanelApi.cs), kept apart so tools\WebPanelTests can check them
|
||||
/// without the engine: refusals, the GetState argument check, and writing the result struct.
|
||||
/// </summary>
|
||||
internal static unsafe class WebPanelApiRules
|
||||
{
|
||||
/// <summary>0 to go on, else the refusal. Shutting down wins over the engine.json "WebPanel" kill switch.</summary>
|
||||
public static int OpenRefusal(bool shuttingDown, bool enabled) =>
|
||||
shuttingDown ? (int)WebPanelCode.ShuttingDown : enabled ? 0 : (int)WebPanelCode.Unavailable;
|
||||
|
||||
/// <summary>Navigate, Close and GetState: 0 to go on, else ShuttingDown.</summary>
|
||||
public static int CallRefusal(bool shuttingDown) => shuttingDown ? (int)WebPanelCode.ShuttingDown : 0;
|
||||
|
||||
/// <summary>OffsetOf(Reserved): the smallest Size a caller's WebPanelStateNative may declare (28 on x86 and x64: the struct has no pointer fields).</summary>
|
||||
public static uint StateMinSize
|
||||
{
|
||||
get
|
||||
{
|
||||
WebPanelStateNative s = default;
|
||||
return (uint)((byte*)s.Reserved - (byte*)&s);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool StateArgsOk(WebPanelStateNative* state) => state != null && state->Size >= StateMinSize;
|
||||
|
||||
/// <summary>What a handle reads when no panel was ever opened.</summary>
|
||||
public static WebPanelSnapshot NoPanel(int handle) => new(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0);
|
||||
|
||||
/// <summary>Writes the fields before Reserved only (the caller's Size covers at least those).</summary>
|
||||
public static void WriteState(WebPanelStateNative* state, in WebPanelSnapshot 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;
|
||||
}
|
||||
}
|
||||
1118
src/RynthCore.Engine/WebPanel/WebPanelHost.cs
Normal file
1118
src/RynthCore.Engine/WebPanel/WebPanelHost.cs
Normal file
File diff suppressed because it is too large
Load diff
80
src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs
Normal file
80
src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>
|
||||
/// The panel's remembered placement: <LocalAppData>\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);
|
||||
}
|
||||
}
|
||||
95
src/RynthCore.Engine/WebPanel/WebPanelNative.cs
Normal file
95
src/RynthCore.Engine/WebPanel/WebPanelNative.cs
Normal 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);
|
||||
}
|
||||
55
src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs
Normal file
55
src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs
Normal 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 v94 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;
|
||||
}
|
||||
}
|
||||
44
src/RynthCore.Engine/WebPanel/WebPanelProfile.cs
Normal file
44
src/RynthCore.Engine/WebPanel/WebPanelProfile.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
using System.IO;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>Pure per-world, per-profile-key WebView2 user data folder naming. No file access.</summary>
|
||||
internal static class WebPanelProfile
|
||||
{
|
||||
/// <summary>
|
||||
/// <localAppData>\RynthCore\WebPanel\<world>\<hex>. World: [A-Za-z0-9 _-] kept, others
|
||||
/// '_', trimmed, max 64, empty -> "_default". Hex: first 16 bytes of
|
||||
/// SHA-256(UTF-8(key.Trim().ToLowerInvariant())) as lowercase hex; empty key -> "default".
|
||||
/// </summary>
|
||||
public static string Folder(string localAppData, string? worldName, string? profileKey)
|
||||
{
|
||||
return Path.Combine(localAppData, "RynthCore", "WebPanel", SanitizeWorld(worldName), KeyHex(profileKey));
|
||||
}
|
||||
|
||||
private static string SanitizeWorld(string? world)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(world)) return "_default";
|
||||
var sb = new StringBuilder();
|
||||
foreach (char c in world.Trim())
|
||||
{
|
||||
bool keep = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|
||||
|| c == ' ' || c == '_' || c == '-';
|
||||
sb.Append(keep ? c : '_');
|
||||
}
|
||||
string s = sb.ToString();
|
||||
if (s.Length > 64) s = s.Substring(0, 64);
|
||||
s = s.Trim(); // a trailing space is not a valid Windows folder name
|
||||
return s.Length == 0 ? "_default" : s;
|
||||
}
|
||||
|
||||
private static string KeyHex(string? key)
|
||||
{
|
||||
string k = (key ?? "").Trim().ToLowerInvariant();
|
||||
if (k.Length == 0) return "default";
|
||||
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(k));
|
||||
return Convert.ToHexString(hash, 0, 16).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
123
src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs
Normal file
123
src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>
|
||||
/// Pure URL rules for the web panel: the navigation allowlist, the "safe to hand to the system
|
||||
/// browser" test, and log redaction. No Win32, no WebView2.
|
||||
/// </summary>
|
||||
internal static class WebPanelUrlPolicy
|
||||
{
|
||||
public const int MaxEntries = 16, MaxEntryLength = 253, MaxUrlBytes = 4096;
|
||||
|
||||
/// <summary>
|
||||
/// Parses a '\n'-separated allowlist (blank lines ignored, '\r' tolerated). An entry is
|
||||
/// "host" (exact) or "*.suffix" (any subdomain depth, not the suffix itself; the suffix must
|
||||
/// contain a dot). No scheme, path, port or other '*'. False on 0 or more than 16 entries or
|
||||
/// any bad entry.
|
||||
/// </summary>
|
||||
public static bool TryParseAllowlist(string? text, out string[] entries)
|
||||
{
|
||||
entries = Array.Empty<string>();
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
|
||||
var list = new List<string>();
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string e = raw.Trim().ToLowerInvariant();
|
||||
if (e.Length == 0) continue;
|
||||
if (list.Count >= MaxEntries) return false;
|
||||
if (!IsValidEntry(e)) return false;
|
||||
list.Add(e);
|
||||
}
|
||||
if (list.Count == 0) return false;
|
||||
entries = list.ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsValidEntry(string e)
|
||||
{
|
||||
if (e.Length > MaxEntryLength) return false;
|
||||
string host = e;
|
||||
if (e.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
host = e.Substring(2);
|
||||
if (host.IndexOf('.') < 0) return false; // "*.com" would allow a whole TLD
|
||||
}
|
||||
return IsValidHostName(host);
|
||||
}
|
||||
|
||||
private static bool IsValidHostName(string host)
|
||||
{
|
||||
if (host.Length == 0) return false;
|
||||
foreach (string label in host.Split('.'))
|
||||
{
|
||||
if (label.Length == 0 || label.Length > 63) return false;
|
||||
if (label[0] == '-' || label[^1] == '-') return false;
|
||||
foreach (char c in label)
|
||||
{
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
|
||||
if (!ok) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// https only, no userinfo, default port; host compared via Uri.IdnHost, case-insensitive,
|
||||
/// one trailing dot stripped. "about:blank" is allowed.
|
||||
/// </summary>
|
||||
public static bool IsAllowed(string? url, IReadOnlyList<string> entries)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url)) return false;
|
||||
if (Encoding.UTF8.GetByteCount(url) > MaxUrlBytes) return false;
|
||||
if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
|
||||
if (uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||
if (uri.UserInfo.Length != 0) return false;
|
||||
if (!uri.IsDefaultPort) return false;
|
||||
|
||||
string host;
|
||||
try { host = uri.IdnHost.ToLowerInvariant(); }
|
||||
catch (UriFormatException) { return false; } // invalid IDN characters: fail closed
|
||||
if (host.EndsWith('.')) host = host.Substring(0, host.Length - 1);
|
||||
if (host.Length == 0) return false;
|
||||
|
||||
foreach (string entry in entries)
|
||||
{
|
||||
if (entry.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
string suffix = entry.Substring(1); // ".example.com"
|
||||
if (host.Length > suffix.Length && host.EndsWith(suffix, StringComparison.Ordinal)) return true;
|
||||
}
|
||||
else if (host == entry)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Absolute http/https without userinfo: the only URLs that may reach ShellExecute.</summary>
|
||||
public static bool IsBrowserSafe(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return false;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
|
||||
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||
if (uri.UserInfo.Length != 0) return false;
|
||||
return uri.Host.Length != 0;
|
||||
}
|
||||
|
||||
/// <summary>"scheme://host[:port]/path" with no userinfo, query or fragment; "<invalid url>" if unparseable.</summary>
|
||||
public static string Redact(string? url)
|
||||
{
|
||||
const string Invalid = "<invalid url>";
|
||||
if (string.IsNullOrEmpty(url)) return Invalid;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return Invalid;
|
||||
if (uri.Host.Length == 0) return Invalid;
|
||||
string port = uri.IsDefaultPort ? "" : ":" + uri.Port;
|
||||
return uri.Scheme + "://" + uri.Host + port + uri.AbsolutePath;
|
||||
}
|
||||
}
|
||||
68
src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs
Normal file
68
src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
using System;
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
internal readonly record struct PanelRect(int Left, int Top, int Right, int Bottom)
|
||||
{
|
||||
public int Width => Right - Left;
|
||||
public int Height => Bottom - Top;
|
||||
}
|
||||
|
||||
/// <summary>Panel placement as fractions (0..1) of the game client rect.</summary>
|
||||
internal readonly record struct PanelFractions(double X, double Y, double W, double H);
|
||||
|
||||
/// <summary>Pure visibility and layout rules for the web panel window. No Win32.</summary>
|
||||
internal static class WebPanelWindowPolicy
|
||||
{
|
||||
public const int DefaultPercent = 88, MinPercent = 30, MaxPercent = 100, MinWidthPx = 480, MinHeightPx = 320;
|
||||
|
||||
/// <summary>
|
||||
/// false when closed, the game is gone, iconic or invisible; null (keep current) when the
|
||||
/// foreground window is null mid alt-tab, so the panel never flickers; otherwise true only
|
||||
/// when the foreground window belongs to the game process.
|
||||
/// </summary>
|
||||
public static bool? Visible(bool open, bool gameAlive, bool gameIconic, bool gameVisible,
|
||||
bool foregroundNull, uint foregroundPid, uint ourPid)
|
||||
{
|
||||
if (!open || !gameAlive || gameIconic || !gameVisible) return false;
|
||||
if (foregroundNull) return null;
|
||||
return foregroundPid == ourPid;
|
||||
}
|
||||
|
||||
/// <summary>Centered fractions for a size in percent of the client; 0 means the default (88).</summary>
|
||||
public static PanelFractions Default(int widthPercent, int heightPercent)
|
||||
{
|
||||
double w = Pct(widthPercent) / 100.0;
|
||||
double h = Pct(heightPercent) / 100.0;
|
||||
return new PanelFractions((1 - w) / 2, (1 - h) / 2, w, h);
|
||||
}
|
||||
|
||||
private static int Pct(int p) => p == 0 ? DefaultPercent : Math.Clamp(p, MinPercent, MaxPercent);
|
||||
|
||||
/// <summary>Screen rect for the fractions: at least 480x320 (or the whole client if smaller), never outside the client.</summary>
|
||||
public static PanelRect Place(PanelRect gameClientScreen, PanelFractions f)
|
||||
{
|
||||
int cw = Math.Max(0, gameClientScreen.Width);
|
||||
int ch = Math.Max(0, gameClientScreen.Height);
|
||||
int w = Math.Clamp((int)Math.Round(Clamp01(f.W) * cw), Math.Min(MinWidthPx, cw), cw);
|
||||
int h = Math.Clamp((int)Math.Round(Clamp01(f.H) * ch), Math.Min(MinHeightPx, ch), ch);
|
||||
int x = Math.Clamp((int)Math.Round(Clamp01(f.X) * cw), 0, cw - w);
|
||||
int y = Math.Clamp((int)Math.Round(Clamp01(f.Y) * ch), 0, ch - h);
|
||||
int left = gameClientScreen.Left + x;
|
||||
int top = gameClientScreen.Top + y;
|
||||
return new PanelRect(left, top, left + w, top + h);
|
||||
}
|
||||
|
||||
/// <summary>Fractions of the client for a panel rect the user dragged or resized, clamped to 0..1.</summary>
|
||||
public static PanelFractions FromUserRect(PanelRect gameClientScreen, PanelRect panelScreen)
|
||||
{
|
||||
int cw = gameClientScreen.Width, ch = gameClientScreen.Height;
|
||||
if (cw <= 0 || ch <= 0) return Default(0, 0);
|
||||
double w = Clamp01((double)panelScreen.Width / cw);
|
||||
double h = Clamp01((double)panelScreen.Height / ch);
|
||||
double x = Math.Clamp((double)(panelScreen.Left - gameClientScreen.Left) / cw, 0, 1 - w);
|
||||
double y = Math.Clamp((double)(panelScreen.Top - gameClientScreen.Top) / ch, 0, 1 - h);
|
||||
return new PanelFractions(x, y, w, h);
|
||||
}
|
||||
|
||||
private static double Clamp01(double v) => double.IsNaN(v) ? 0 : Math.Clamp(v, 0, 1);
|
||||
}
|
||||
|
|
@ -204,6 +204,11 @@ public struct RynthCoreApiNative
|
|||
public IntPtr GetAmbientLightFn; // int GetAmbientLight(uint* client, uint* applied) -> 1 hook live, 0 not
|
||||
// v93: the monster plates' last server health reading per object
|
||||
public IntPtr GetMonsterHealthFn; // int GetMonsterHealth(uint id, float* ratio, uint* ageMs) -> 1 reading, 0 none
|
||||
// v94: a WebView2 web panel over the game window (APPEND-AT-END (ABI); number provisional)
|
||||
public IntPtr WebPanelOpenFn; // int WebPanelOpen(WebPanelOpenNative*) -> handle > 0, or BadArgs/UrlNotAllowed/NoGameWindow/Unavailable/ShuttingDown
|
||||
public IntPtr WebPanelNavigateFn; // int WebPanelNavigate(int handle, byte* url) -> 1 queued; -2 off-list; -6 stale
|
||||
public IntPtr WebPanelCloseFn; // int WebPanelClose(int handle) -> 1 queued, 0 already closed, -6 stale
|
||||
public IntPtr WebPanelGetStateFn; // int WebPanelGetState(int handle, WebPanelStateNative*) -> Status (non-live handle -> 6 Superseded), -1 bad args
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -1877,6 +1877,119 @@ public readonly unsafe struct RynthCoreHost
|
|||
return true;
|
||||
}
|
||||
|
||||
// ── v94: a web panel over the game window (number provisional) ───────────
|
||||
|
||||
/// <summary>
|
||||
/// v94: <see cref="OpenWebPanel"/>, <see cref="NavigateWebPanel"/>, <see cref="CloseWebPanel"/> and
|
||||
/// <see cref="GetWebPanelState"/>. True only on an engine at API 94 or newer that fills all four.
|
||||
/// </summary>
|
||||
public bool HasWebPanel => _api.Version >= 94 && _api.WebPanelOpenFn != IntPtr.Zero && _api.WebPanelNavigateFn != IntPtr.Zero
|
||||
&& _api.WebPanelCloseFn != IntPtr.Zero && _api.WebPanelGetStateFn != IntPtr.Zero;
|
||||
|
||||
/// <summary>
|
||||
/// v94: opens the web panel over the game window (a second call replaces the first). Returns a handle
|
||||
/// > 0, or a <see cref="WebPanelResult"/> (BadArgs for an empty URL or allowlist, more than 16
|
||||
/// entries or a newline inside one; Unavailable on an older engine). Never blocks; the panel loads
|
||||
/// after this returns - poll <see cref="GetWebPanelState"/>. Any thread.
|
||||
/// </summary>
|
||||
public int OpenWebPanel(WebPanelOptions options)
|
||||
{
|
||||
if (options == null || string.IsNullOrEmpty(options.Url) || options.Allowlist == null
|
||||
|| options.Allowlist.Count < 1 || options.Allowlist.Count > 16)
|
||||
return (int)WebPanelResult.BadArgs;
|
||||
foreach (string entry in options.Allowlist)
|
||||
if (string.IsNullOrEmpty(entry) || entry.Contains('\n')) return (int)WebPanelResult.BadArgs;
|
||||
if (!HasWebPanel) return (int)WebPanelResult.Unavailable;
|
||||
|
||||
string allowlist = string.Join("\n", options.Allowlist);
|
||||
string profile = options.ProfileKey ?? "";
|
||||
string title = options.Title ?? "";
|
||||
var enc = System.Text.Encoding.UTF8;
|
||||
int nUrl = enc.GetByteCount(options.Url), nAllow = enc.GetByteCount(allowlist);
|
||||
int nProfile = enc.GetByteCount(profile), nTitle = enc.GetByteCount(title);
|
||||
int total = nUrl + nAllow + nProfile + nTitle + 4;
|
||||
|
||||
byte[]? rented = null;
|
||||
Span<byte> buf = total <= 1024 ? stackalloc byte[total] : (rented = System.Buffers.ArrayPool<byte>.Shared.Rent(total)).AsSpan(0, total);
|
||||
try
|
||||
{
|
||||
int o = 0;
|
||||
int oUrl = o; o += enc.GetBytes(options.Url, buf[o..]); buf[o++] = 0;
|
||||
int oAllow = o; o += enc.GetBytes(allowlist, buf[o..]); buf[o++] = 0;
|
||||
int oProfile = o; o += enc.GetBytes(profile, buf[o..]); buf[o++] = 0;
|
||||
int oTitle = o; o += enc.GetBytes(title, buf[o..]); buf[o++] = 0;
|
||||
fixed (byte* b = buf)
|
||||
{
|
||||
var open = new WebPanelOpenNative
|
||||
{
|
||||
Size = (uint)sizeof(WebPanelOpenNative),
|
||||
Flags = (uint)options.Flags,
|
||||
Url = b + oUrl,
|
||||
Allowlist = b + oAllow,
|
||||
ProfileKey = nProfile == 0 ? null : b + oProfile,
|
||||
Title = nTitle == 0 ? null : b + oTitle,
|
||||
WidthPercent = options.WidthPercent,
|
||||
HeightPercent = options.HeightPercent,
|
||||
};
|
||||
return ((delegate* unmanaged[Cdecl]<WebPanelOpenNative*, int>)_api.WebPanelOpenFn)(&open);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rented != null) System.Buffers.ArrayPool<byte>.Shared.Return(rented);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v94: points the panel <paramref name="handle"/> at <paramref name="url"/>. 1 queued; -2
|
||||
/// (UrlNotAllowed) when it is off the allowlist (the engine opens it in the system browser when that is
|
||||
/// safe); -6 (StaleHandle) when the handle is not the live panel. Never blocks. Any thread.
|
||||
/// </summary>
|
||||
public int NavigateWebPanel(int handle, string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url)) return (int)WebPanelResult.BadArgs;
|
||||
if (!HasWebPanel) return (int)WebPanelResult.Unavailable;
|
||||
int n = System.Text.Encoding.UTF8.GetByteCount(url);
|
||||
byte[]? rented = null;
|
||||
Span<byte> buf = n + 1 <= 1024 ? stackalloc byte[n + 1] : (rented = System.Buffers.ArrayPool<byte>.Shared.Rent(n + 1)).AsSpan(0, n + 1);
|
||||
try
|
||||
{
|
||||
System.Text.Encoding.UTF8.GetBytes(url, buf);
|
||||
buf[n] = 0;
|
||||
fixed (byte* p = buf)
|
||||
return ((delegate* unmanaged[Cdecl]<int, byte*, int>)_api.WebPanelNavigateFn)(handle, p);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rented != null) System.Buffers.ArrayPool<byte>.Shared.Return(rented);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v94: closes the panel <paramref name="handle"/>. 1 queued, 0 already closed, -6 stale handle. Never blocks. Any thread.</summary>
|
||||
public int CloseWebPanel(int handle)
|
||||
{
|
||||
if (!HasWebPanel) return (int)WebPanelResult.Unavailable;
|
||||
return ((delegate* unmanaged[Cdecl]<int, int>)_api.WebPanelCloseFn)(handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v94: where the panel <paramref name="handle"/> is. A handle that is not the live panel reads
|
||||
/// Superseded. None (and a default <paramref name="state"/>) on an older engine or bad arguments.
|
||||
/// Any thread.
|
||||
/// </summary>
|
||||
public WebPanelStatus GetWebPanelState(int handle, out WebPanelState state)
|
||||
{
|
||||
state = default;
|
||||
if (!HasWebPanel) return WebPanelStatus.None;
|
||||
WebPanelStateNative native = default;
|
||||
native.Size = (uint)sizeof(WebPanelStateNative);
|
||||
int r = ((delegate* unmanaged[Cdecl]<int, WebPanelStateNative*, int>)_api.WebPanelGetStateFn)(handle, &native);
|
||||
if (r < 0) return WebPanelStatus.None;
|
||||
var status = (WebPanelStatus)native.Status;
|
||||
state = new WebPanelState(native.Handle, status, (WebPanelStateFlags)native.Flags, (WebPanelResult)native.Error, native.LastHttpStatus, native.NavigationCount);
|
||||
return status;
|
||||
}
|
||||
|
||||
private int CallSetActionKey(string action, string key, int op, out string message)
|
||||
{
|
||||
message = string.Empty;
|
||||
|
|
|
|||
95
src/RynthCore.PluginSdk/WebPanelTypes.cs
Normal file
95
src/RynthCore.PluginSdk/WebPanelTypes.cs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.PluginSdk;
|
||||
|
||||
// v94: a WebView2 web panel over the game window. The native structs mirror
|
||||
// RynthCore.Engine/Plugins/PluginContract.cs field for field (tools\PluginManifestTests checks sizes and
|
||||
// offsets). The API number is provisional.
|
||||
|
||||
/// <summary>v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors the engine's WebPanelOpenNative.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public unsafe struct WebPanelOpenNative
|
||||
{
|
||||
/// <summary>sizeof this struct; the engine accepts Size >= OffsetOf(Reserved) (32 on x86).</summary>
|
||||
public uint Size;
|
||||
/// <summary><see cref="WebPanelFlags"/>; unknown bits ignored.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>UTF-8 NUL-terminated, at most 4096 bytes.</summary>
|
||||
public byte* Url;
|
||||
/// <summary>UTF-8, '\n'-separated allowlist.</summary>
|
||||
public byte* Allowlist;
|
||||
/// <summary>UTF-8, may be null; at most 256 bytes.</summary>
|
||||
public byte* ProfileKey;
|
||||
/// <summary>UTF-8, may be null; at most 128 bytes.</summary>
|
||||
public byte* Title;
|
||||
/// <summary>0 = 88, else 30..100 (only when no remembered layout).</summary>
|
||||
public int WidthPercent;
|
||||
public int HeightPercent;
|
||||
public fixed uint Reserved[4];
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelGetState result (Pack 4; 48 bytes). Mirrors the engine's WebPanelStateNative.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public unsafe struct WebPanelStateNative
|
||||
{
|
||||
public uint Size;
|
||||
public int Handle;
|
||||
/// <summary><see cref="WebPanelStatus"/>.</summary>
|
||||
public int Status;
|
||||
/// <summary><see cref="WebPanelStateFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>0 or a negative <see cref="WebPanelResult"/> (RuntimeMissing / CreateFailed / ProcessFailed).</summary>
|
||||
public int Error;
|
||||
public int LastHttpStatus;
|
||||
public uint NavigationCount;
|
||||
public fixed uint Reserved[5];
|
||||
}
|
||||
|
||||
/// <summary>Options for <see cref="RynthCoreHost.OpenWebPanel"/>.</summary>
|
||||
[Flags]
|
||||
public enum WebPanelFlags : uint
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>When the panel cannot open (no WebView2 runtime, creation failed), open the URL in the system browser.</summary>
|
||||
FallbackToBrowser = 1,
|
||||
/// <summary>Escape goes to the page instead of closing the panel.</summary>
|
||||
PageKeepsEscape = 2,
|
||||
// 4 is reserved: phase 2 EnableMessages.
|
||||
}
|
||||
|
||||
/// <summary>Results of the web panel calls; an open that succeeds returns a handle > 0 instead.</summary>
|
||||
public enum WebPanelResult : int
|
||||
{
|
||||
Queued = 1, AlreadyClosed = 0, BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3,
|
||||
Unavailable = -4, ShuttingDown = -5, StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9,
|
||||
}
|
||||
|
||||
/// <summary>Where the web panel is in its life.</summary>
|
||||
public enum WebPanelStatus : int
|
||||
{
|
||||
None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum WebPanelStateFlags : uint
|
||||
{
|
||||
None = 0, Visible = 1, Focused = 2, OpenedInBrowser = 4,
|
||||
}
|
||||
|
||||
/// <summary>A snapshot of the web panel from <see cref="RynthCoreHost.GetWebPanelState"/>.</summary>
|
||||
public readonly record struct WebPanelState(int Handle, WebPanelStatus Status, WebPanelStateFlags Flags, WebPanelResult Error, int LastHttpStatus, uint NavigationCount);
|
||||
|
||||
public sealed class WebPanelOptions
|
||||
{
|
||||
public required string Url { get; init; }
|
||||
/// <summary>1..16 entries, no '\n' inside an entry.</summary>
|
||||
public required IReadOnlyList<string> Allowlist { get; init; }
|
||||
/// <summary>Opaque; the engine lower-cases, hashes and adds the world.</summary>
|
||||
public string ProfileKey { get; init; } = "";
|
||||
public string Title { get; init; } = "";
|
||||
public int WidthPercent { get; init; } = 0;
|
||||
public int HeightPercent { get; init; } = 0;
|
||||
public WebPanelFlags Flags { get; init; } = WebPanelFlags.FallbackToBrowser;
|
||||
}
|
||||
|
|
@ -36,7 +36,7 @@
|
|||
|
||||
<PropertyGroup>
|
||||
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
|
||||
<RynthCoreSdkApiVersion>93</RynthCoreSdkApiVersion>
|
||||
<RynthCoreSdkApiVersion>94</RynthCoreSdkApiVersion>
|
||||
<!-- The first engine API that loads managed plugins and gives them Runtime\PluginShared (2026.10.19.1). -->
|
||||
<RynthCoreManagedPluginApi>88</RynthCoreManagedPluginApi>
|
||||
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
|
||||
|
|
|
|||
|
|
@ -115,6 +115,9 @@ internal static class Program
|
|||
("layout", "layout", "layout frob"),
|
||||
("layout", "layout reset confirm", "layout reset now"),
|
||||
("layout", "layout default", "layout default now"),
|
||||
("webpanel", "webpanel status", "webpanel open"),
|
||||
("webpanel", "webpanel", "webpanel frob"),
|
||||
("webpanel", "webpanel close", "webpanel close now"),
|
||||
};
|
||||
|
||||
private static void EveryVerbValidAndInvalid()
|
||||
|
|
@ -341,6 +344,19 @@ internal static class Program
|
|||
Check(!Regex.IsMatch(src, @"\bReply\(\$?""[Uu]sage"), "no usage line is written as a success (they go through Fail)");
|
||||
Check(!Regex.IsMatch(src, @"\bReply\((usage|ServerUsage)\)"), "nor the usage constants");
|
||||
Check(!Regex.IsMatch(src, @"catch \(Exception ex\) \{ RynthLog\.Compat"), "no command's exception is only logged");
|
||||
|
||||
Case("RynthCoreChatCommands.cs: /rc webpanel never opens or navigates (an arbitrary-URL command would be a phishing vector)");
|
||||
int wpStart = src.IndexOf("private static void HandleWebPanelCommand", StringComparison.Ordinal);
|
||||
int wpEnd = src.IndexOf("private static void HandleLayoutCommand", StringComparison.Ordinal);
|
||||
Check(wpStart > 0 && wpEnd > wpStart, "found HandleWebPanelCommand");
|
||||
if (wpStart > 0 && wpEnd > wpStart)
|
||||
{
|
||||
string wp = src.Substring(wpStart, wpEnd - wpStart);
|
||||
Check(!Regex.IsMatch(wp, @"\bOpen\("), "HandleWebPanelCommand has no Open(");
|
||||
Check(!Regex.IsMatch(wp, @"\bNavigate\("), "HandleWebPanelCommand has no Navigate(");
|
||||
Check(!wp.Contains("ShellExecute", StringComparison.Ordinal), "HandleWebPanelCommand has no ShellExecute");
|
||||
Check(wp.Contains("WebPanelApi.Close(", StringComparison.Ordinal), "the scan reads the real body (it calls WebPanelApi.Close)");
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindRepoFile(string relative)
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ namespace EngineSettingsTests
|
|||
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
|
||||
Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved);
|
||||
Run(nameof(TransitionGateDefaultOnAndSaved), TransitionGateDefaultOnAndSaved);
|
||||
Run(nameof(WebPanelDefaultOnAndSaved), WebPanelDefaultOnAndSaved);
|
||||
Run(nameof(HoldReloadInWorldOptInAndSaved), HoldReloadInWorldOptInAndSaved);
|
||||
Run(nameof(IltServerNamesEdit), IltServerNamesEdit);
|
||||
Run(nameof(DisplaySettingsDefaultsAndSaved), DisplaySettingsDefaultsAndSaved);
|
||||
|
|
@ -118,6 +119,8 @@ namespace EngineSettingsTests
|
|||
case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break;
|
||||
case "tgate-off": EngineSettings.TransitionGate = false; break;
|
||||
case "tgate-on": EngineSettings.TransitionGate = true; break;
|
||||
case "webpanel-off": EngineSettings.WebPanel = false; break;
|
||||
case "webpanel-on": EngineSettings.WebPanel = true; break;
|
||||
case "borderless-on": EngineSettings.BorderlessWindowed = true; break;
|
||||
case "borderless-off": EngineSettings.BorderlessWindowed = false; break;
|
||||
case "layout-on": EngineSettings.RememberWindowLayout = true; break;
|
||||
|
|
@ -148,6 +151,7 @@ namespace EngineSettingsTests
|
|||
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
|
||||
Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect);
|
||||
Console.WriteLine("TransitionGate=" + EngineSettings.TransitionGate);
|
||||
Console.WriteLine("WebPanel=" + EngineSettings.WebPanel);
|
||||
Console.WriteLine("BorderlessWindowed=" + EngineSettings.BorderlessWindowed);
|
||||
Console.WriteLine("RememberWindowLayout=" + EngineSettings.RememberWindowLayout);
|
||||
Console.WriteLine("PanelLayoutPerCharacter=" + EngineSettings.PanelLayoutPerCharacter);
|
||||
|
|
@ -415,6 +419,7 @@ namespace EngineSettingsTests
|
|||
(new[] { "ilt-add", "Frosthaven" }, "IltServerNames", null),
|
||||
(new[] { "autoid", "all" }, "AutoIdMode", "\"All\""),
|
||||
(new[] { "tgate-off" }, "TransitionGate", "false"),
|
||||
(new[] { "webpanel-off" }, "WebPanel", "false"),
|
||||
(new[] { "add-plugin", plugin }, "PluginPaths", null),
|
||||
(new[] { "remove-plugin", "0" }, "PluginPaths", null),
|
||||
};
|
||||
|
|
@ -622,6 +627,36 @@ namespace EngineSettingsTests
|
|||
}
|
||||
}
|
||||
|
||||
// engine.json WebPanel (2026-11-07, the v94 web panel kill switch): default on, only a hand-set false is
|
||||
// written, other saves keep it, a value that is not a boolean is ignored.
|
||||
private static void WebPanelDefaultOnAndSaved()
|
||||
{
|
||||
string dir = NewDir("webpanel");
|
||||
string path = Path.Combine(dir, "engine.json");
|
||||
|
||||
File.WriteAllText(path, LauncherFile);
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "WebPanel"), "True", "missing: on");
|
||||
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default");
|
||||
Check(!ReadJson(path).TryGetProperty("WebPanel", out _), "the default isn't written to the file");
|
||||
|
||||
var (exit, output) = RunChild(path, "webpanel-off");
|
||||
Eq(exit, 0, "turn off (" + output.Trim() + ")");
|
||||
Eq(ReadJson(path).GetProperty("WebPanel").GetRawText(), "false", "off is saved");
|
||||
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept");
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "WebPanel"), "False", "off read back at the next start");
|
||||
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
|
||||
Eq(ReadJson(path).GetProperty("WebPanel").GetRawText(), "false", "off survives other saves");
|
||||
|
||||
Eq(RunChild(path, "webpanel-on").Exit, 0, "turn on");
|
||||
Check(!ReadJson(path).TryGetProperty("WebPanel", out _), "on again: dropped from the file");
|
||||
|
||||
foreach (string bad in new[] { "\"no\"", "0", "null" })
|
||||
{
|
||||
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"WebPanel\": {bad}, \"LoggingLevel\""));
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "WebPanel"), "True", $"{bad}: ignored, on");
|
||||
}
|
||||
}
|
||||
|
||||
// Settings > Display (2026-10-18): BorderlessWindowed off and RememberAcWindowPosition off by default,
|
||||
// RememberWindowLayout on (panels have always been remembered). Only the non-default is written;
|
||||
// other saves keep it; a value that is not a boolean is ignored.
|
||||
|
|
|
|||
|
|
@ -59,6 +59,10 @@ internal static class Program
|
|||
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
|
||||
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
|
||||
Run(nameof(ContainerOrderSlots), ContainerOrderSlots);
|
||||
Run(nameof(WebPanelFieldsAppended), WebPanelFieldsAppended);
|
||||
Run(nameof(WebPanelStructsMatch), WebPanelStructsMatch);
|
||||
Run(nameof(WebPanelCodesMatch), WebPanelCodesMatch);
|
||||
Run(nameof(HasWebPanel_FalseOnOldOrPartialTable), HasWebPanel_FalseOnOldOrPartialTable);
|
||||
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
|
||||
Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice);
|
||||
Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes);
|
||||
|
|
@ -589,6 +593,102 @@ internal static class Program
|
|||
"targets: the manifest and the runtime attribute both use the derived minimum");
|
||||
}
|
||||
|
||||
// v94: the web panel's four slots are appended right after GetMonsterHealthFn, in order, on both sides.
|
||||
private static void WebPanelFieldsAppended()
|
||||
{
|
||||
string[] slots = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" };
|
||||
string prev = "GetMonsterHealthFn";
|
||||
foreach (string slot in slots)
|
||||
{
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>(slot),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>(prev) + IntPtr.Size, "engine " + slot + " right after " + prev);
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>(slot),
|
||||
(int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>(prev) + IntPtr.Size, "SDK " + slot + " right after " + prev);
|
||||
prev = slot;
|
||||
}
|
||||
Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "engine table: GetMonsterHealthFn precedes the four");
|
||||
Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "SDK table: GetMonsterHealthFn precedes the four");
|
||||
}
|
||||
|
||||
private static void StructMirror(Type engine, Type sdk, int size)
|
||||
{
|
||||
Eq(Marshal.SizeOf(engine), size, "engine " + engine.Name + " size");
|
||||
Eq(Marshal.SizeOf(sdk), size, "SDK " + sdk.Name + " size");
|
||||
var ef = engine.GetFields().Select(f => f.Name).ToArray();
|
||||
var sf = sdk.GetFields().Select(f => f.Name).ToArray();
|
||||
Check(ef.SequenceEqual(sf), engine.Name + " field names/order match: " + string.Join(",", ef) + " vs " + string.Join(",", sf));
|
||||
foreach (string f in ef)
|
||||
Eq((int)Marshal.OffsetOf(sdk, f), (int)Marshal.OffsetOf(engine, f), engine.Name + "." + f + " offset");
|
||||
}
|
||||
|
||||
// v94: the SDK's WebPanelOpenNative/WebPanelStateNative are the engine's, byte for byte.
|
||||
private static void WebPanelStructsMatch()
|
||||
{
|
||||
int p = IntPtr.Size;
|
||||
StructMirror(typeof(RynthCore.Engine.Plugins.WebPanelOpenNative), typeof(RynthCore.PluginSdk.WebPanelOpenNative), 8 + 4 * p + 8 + 16);
|
||||
StructMirror(typeof(RynthCore.Engine.Plugins.WebPanelStateNative), typeof(RynthCore.PluginSdk.WebPanelStateNative), 48);
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.WebPanelOpenNative>("Reserved"), 8 + 4 * p + 8, "engine WebPanelOpenNative.Reserved offset (32 on x86)");
|
||||
// The 32-bit AC client's contract: 48 bytes, Reserved at 32 (only checked when this run is x86).
|
||||
if (IntPtr.Size == 4)
|
||||
{
|
||||
Eq(Marshal.SizeOf<RynthCore.Engine.Plugins.WebPanelOpenNative>(), 48, "x86 engine WebPanelOpenNative size");
|
||||
Eq(Marshal.SizeOf<RynthCore.PluginSdk.WebPanelOpenNative>(), 48, "x86 SDK WebPanelOpenNative size");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.WebPanelOpenNative>("Reserved"), 32, "x86 engine WebPanelOpenNative.Reserved offset");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.WebPanelOpenNative>("Reserved"), 32, "x86 SDK WebPanelOpenNative.Reserved offset");
|
||||
Eq(Marshal.SizeOf<RynthCore.Engine.Plugins.WebPanelStateNative>(), 48, "x86 engine WebPanelStateNative size");
|
||||
Eq(Marshal.SizeOf<RynthCore.PluginSdk.WebPanelStateNative>(), 48, "x86 SDK WebPanelStateNative size");
|
||||
}
|
||||
Console.WriteLine($" (WebPanelStructsMatch ran with IntPtr.Size={IntPtr.Size})");
|
||||
}
|
||||
|
||||
// v94: every code value agrees between the engine's enums and the SDK's.
|
||||
private static void WebPanelCodesMatch()
|
||||
{
|
||||
Dictionary<string, long> Vals(Type t) => Enum.GetNames(t).ToDictionary(n => n, n => Convert.ToInt64(Enum.Parse(t, n)));
|
||||
var engine = Vals(typeof(RynthCore.Engine.Plugins.WebPanelCode));
|
||||
var sdk = Vals(typeof(RynthCore.PluginSdk.WebPanelResult));
|
||||
Eq(sdk.Count, engine.Count, "WebPanelCode vs WebPanelResult member count");
|
||||
foreach (var kv in engine)
|
||||
Check(sdk.TryGetValue(kv.Key, out long v) && v == kv.Value, "WebPanelResult." + kv.Key + " = " + kv.Value);
|
||||
var es = Vals(typeof(RynthCore.Engine.Plugins.WebPanelStatusCode));
|
||||
var ss = Vals(typeof(RynthCore.PluginSdk.WebPanelStatus));
|
||||
Eq(ss.Count, es.Count, "WebPanelStatusCode vs WebPanelStatus member count");
|
||||
foreach (var kv in es)
|
||||
Check(ss.TryGetValue(kv.Key, out long v) && v == kv.Value, "WebPanelStatus." + kv.Key + " = " + kv.Value);
|
||||
Eq((uint)RynthCore.PluginSdk.WebPanelStateFlags.Visible, 1u, "state flag Visible");
|
||||
Eq((uint)RynthCore.PluginSdk.WebPanelStateFlags.Focused, 2u, "state flag Focused");
|
||||
Eq((uint)RynthCore.PluginSdk.WebPanelStateFlags.OpenedInBrowser, 4u, "state flag OpenedInBrowser");
|
||||
Eq((uint)RynthCore.PluginSdk.WebPanelFlags.FallbackToBrowser, 1u, "open flag FallbackToBrowser");
|
||||
Eq((uint)RynthCore.PluginSdk.WebPanelFlags.PageKeepsEscape, 2u, "open flag PageKeepsEscape");
|
||||
}
|
||||
|
||||
// v94: HasWebPanel needs Version >= 94 AND all four slots (an old engine's table is shorter and the
|
||||
// runtime copies the full new-size struct, so slots past its end are garbage, not zero).
|
||||
private static void HasWebPanel_FalseOnOldOrPartialTable()
|
||||
{
|
||||
IntPtr x = (IntPtr)0xDEAD;
|
||||
RynthCoreHost Host(uint version, IntPtr a, IntPtr b, IntPtr c, IntPtr d)
|
||||
=> new RynthCoreHost(new RynthCoreApiNative { Version = version, WebPanelOpenFn = a, WebPanelNavigateFn = b, WebPanelCloseFn = c, WebPanelGetStateFn = d });
|
||||
Check(!Host(93, x, x, x, x).HasWebPanel, "Version 93 with garbage slots: false");
|
||||
Check(!Host(94, IntPtr.Zero, x, x, x).HasWebPanel, "Open zero: false");
|
||||
Check(!Host(94, x, IntPtr.Zero, x, x).HasWebPanel, "Navigate zero: false");
|
||||
Check(!Host(94, x, x, IntPtr.Zero, x).HasWebPanel, "Close zero: false");
|
||||
Check(!Host(94, x, x, x, IntPtr.Zero).HasWebPanel, "GetState zero: false");
|
||||
Check(Host(94, x, x, x, x).HasWebPanel, "Version 94, all four: true");
|
||||
var old = Host(93, x, x, x, x);
|
||||
Eq(old.OpenWebPanel(new WebPanelOptions { Url = "https://a.example/", Allowlist = new[] { "a.example" } }), (int)WebPanelResult.Unavailable, "Open without the API: Unavailable");
|
||||
Eq(old.NavigateWebPanel(1, "https://a.example/"), (int)WebPanelResult.Unavailable, "Navigate without the API: Unavailable");
|
||||
Eq(old.CloseWebPanel(1), (int)WebPanelResult.Unavailable, "Close without the API: Unavailable");
|
||||
Eq(old.GetWebPanelState(1, out var st), WebPanelStatus.None, "GetState without the API: None");
|
||||
Eq(st.Handle, 0, "GetState without the API: default state");
|
||||
// Bad arguments are refused before the engine is called (the slots hold garbage, so a call would crash).
|
||||
var live = Host(94, x, x, x, x);
|
||||
Eq(live.OpenWebPanel(new WebPanelOptions { Url = "", Allowlist = new[] { "a" } }), (int)WebPanelResult.BadArgs, "empty URL: BadArgs");
|
||||
Eq(live.OpenWebPanel(new WebPanelOptions { Url = "https://a/", Allowlist = Array.Empty<string>() }), (int)WebPanelResult.BadArgs, "empty allowlist: BadArgs");
|
||||
Eq(live.OpenWebPanel(new WebPanelOptions { Url = "https://a/", Allowlist = new[] { "a\nb" } }), (int)WebPanelResult.BadArgs, "newline in an entry: BadArgs");
|
||||
Eq(live.NavigateWebPanel(1, ""), (int)WebPanelResult.BadArgs, "navigate empty URL: BadArgs");
|
||||
}
|
||||
|
||||
// v79: the SDK's copies of the training structs must be the engine's, byte for byte.
|
||||
private static void TrainingStructsMirror()
|
||||
{
|
||||
|
|
@ -603,11 +703,11 @@ internal static class Program
|
|||
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
|
||||
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
|
||||
// The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v91 follow:
|
||||
// eleven slots to v89, then v90's thirteen, v91's two and v93's one).
|
||||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(27).TakeLast(6).ToArray();
|
||||
// eleven slots to v89, then v90's thirteen, v91's two, v93's one and v94's four).
|
||||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray();
|
||||
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }),
|
||||
"v79, v80 then v81 slots last: " + string.Join(",", names));
|
||||
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(27).TakeLast(6).ToArray();
|
||||
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray();
|
||||
Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order");
|
||||
}
|
||||
|
||||
|
|
@ -618,6 +718,12 @@ internal static class Program
|
|||
{
|
||||
var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray();
|
||||
var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray();
|
||||
// v94: the web panel's four slots end the table; the checks after these are on the table before them.
|
||||
string[] v94 = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" };
|
||||
Check(all.TakeLast(v94.Length).SequenceEqual(v94), "v94 slots last: " + string.Join(",", all.TakeLast(v94.Length)));
|
||||
Check(sdkAll.TakeLast(v94.Length).SequenceEqual(v94), "SDK v94 slots last: " + string.Join(",", sdkAll.TakeLast(v94.Length)));
|
||||
all = all.SkipLast(v94.Length).ToArray();
|
||||
sdkAll = sdkAll.SkipLast(v94.Length).ToArray();
|
||||
// v93: the monster plates' health readings end the table (2026-11-07), right after v91's two.
|
||||
Check(all.Last() == "GetMonsterHealthFn", "v93 slot last: " + all.Last());
|
||||
Check(sdkAll.Last() == "GetMonsterHealthFn", "SDK v93 slot last: " + sdkAll.Last());
|
||||
|
|
|
|||
158
tools/WebPanelHarness.Payload/PayloadEntry.cs
Normal file
158
tools/WebPanelHarness.Payload/PayloadEntry.cs
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
// The harness's way into the web panel host. Everything crossing into the harness is a framework
|
||||
// type (int, string, IntPtr, arrays, Action<string>), so nothing of this collectible context is held
|
||||
// by the default one. The calls mirror WebPanelApi (the engine's ABI glue): Open reads the native
|
||||
// struct with WebPanelNativeArgs exactly as the engine does.
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
public static unsafe class PayloadEntry
|
||||
{
|
||||
private static StubEnvironment? _env;
|
||||
private static WebPanelHost? _host;
|
||||
|
||||
public static void Init(IntPtr gameHwnd, string runtimeDir, string localAppData, string panelDir, string otherDir,
|
||||
Action<string> log, Action<string> chat, Action<string> browser)
|
||||
{
|
||||
_env = new StubEnvironment(gameHwnd, runtimeDir, localAppData, panelDir, otherDir, log, chat, browser);
|
||||
_host = new WebPanelHost(_env);
|
||||
}
|
||||
|
||||
public static void SetEnvironmentDelay(int ms) => _env!.DelayMs = ms;
|
||||
public static void SetBrowserFolder(string? folder) => _env!.BrowserFolder = folder;
|
||||
public static void SetBrowserFails(bool fails) => _env!.BrowserFails = fails;
|
||||
public static void SetBrowserDelay(int ms) => _env!.BrowserDelayMs = ms;
|
||||
public static void SetWorld(string world) => _env!.World = world;
|
||||
|
||||
/// <summary>The engine's WebPanelApi.Open path: read the caller's struct, then the host.</summary>
|
||||
public static int Open(IntPtr nativeArgs)
|
||||
{
|
||||
int rc = WebPanelNativeArgs.TryBuildRequest((WebPanelOpenNative*)nativeArgs, _env!.LocalAppData, _env.WorldName, out WebPanelRequest? req);
|
||||
if (rc != 0) return rc;
|
||||
return _host!.Open(req!);
|
||||
}
|
||||
|
||||
public static int Navigate(int handle, string url) => _host!.Navigate(handle, url);
|
||||
public static int Close(int handle) => _host!.Close(handle);
|
||||
|
||||
/// <summary>[return, handle, status, flags, error, http, navigations].</summary>
|
||||
public static int[] GetState(int handle)
|
||||
{
|
||||
int r = _host!.GetState(handle, out WebPanelSnapshot s);
|
||||
return new[] { r, s.Handle, s.Status, (int)s.Flags, s.Error, s.LastHttpStatus, (int)s.NavigationCount };
|
||||
}
|
||||
|
||||
public static void Shutdown(int budgetMs) => _host!.Shutdown(budgetMs);
|
||||
public static string Describe() => _host!.Describe();
|
||||
|
||||
public static IntPtr HostHwnd => _host!.HostHwndForTests;
|
||||
public static int EnvironmentCount => _host!.EnvironmentCountForTests;
|
||||
public static int BrowserProcessId => (int)_host!.BrowserProcessIdForTests;
|
||||
public static int AcceleratorKeyEvents => _host!.AcceleratorKeyEventsForTests;
|
||||
public static string Source => _host!.SourceForTests;
|
||||
public static bool ThreadRunning => _host!.ThreadRunningForTests;
|
||||
public static bool PanelOpen => _host!.PanelOpenForTests;
|
||||
public static bool FailHandle(int handle) => _host!.FailForTests(handle);
|
||||
public static bool ReportUnresponsive() => _host!.UnresponsiveForTests();
|
||||
|
||||
public static string ProfileFolder(string world, string key) => WebPanelProfile.Folder(_env!.LocalAppData, world, key);
|
||||
|
||||
/// <summary>Runs script in the page on the panel thread; waits here (the harness thread), never there.</summary>
|
||||
public static string Eval(string js, int timeoutMs)
|
||||
{
|
||||
var done = new ManualResetEventSlim();
|
||||
string result = "TIMEOUT";
|
||||
bool posted = _host!.PostForTests(web =>
|
||||
{
|
||||
if (web == null) { result = "no webview"; done.Set(); return; }
|
||||
try
|
||||
{
|
||||
web.ExecuteScriptAsync(js).ContinueWith(t =>
|
||||
{
|
||||
result = t.IsCompletedSuccessfully ? t.Result : "ERR " + t.Exception?.GetBaseException().Message;
|
||||
done.Set();
|
||||
});
|
||||
}
|
||||
catch (Exception ex) { result = "ERR " + ex.Message; done.Set(); }
|
||||
});
|
||||
if (!posted) return "panel thread not running";
|
||||
done.Wait(timeoutMs);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Drops this context's statics so nothing in it is reachable before the unload.</summary>
|
||||
public static void Release()
|
||||
{
|
||||
_host = null;
|
||||
_env = null;
|
||||
}
|
||||
|
||||
private sealed class StubEnvironment : IWebPanelEnvironment
|
||||
{
|
||||
private readonly Action<string> _log, _chat, _browser;
|
||||
private readonly string _panelDir, _otherDir;
|
||||
|
||||
public StubEnvironment(IntPtr game, string runtimeDir, string localAppData, string panelDir, string otherDir,
|
||||
Action<string> log, Action<string> chat, Action<string> browser)
|
||||
{
|
||||
GameHwnd = game;
|
||||
RuntimeDir = runtimeDir;
|
||||
LocalAppData = localAppData;
|
||||
_panelDir = panelDir;
|
||||
_otherDir = otherDir;
|
||||
_log = log;
|
||||
_chat = chat;
|
||||
_browser = browser;
|
||||
}
|
||||
|
||||
public volatile int DelayMs;
|
||||
public volatile string? BrowserFolder;
|
||||
public volatile bool BrowserFails; // OpenInBrowser returns false without recording a call
|
||||
public volatile int BrowserDelayMs; // OpenInBrowser sleeps first (a slow ShellExecute)
|
||||
public volatile string World = "Harness World";
|
||||
|
||||
public IntPtr GameHwnd { get; }
|
||||
public string RuntimeDir { get; }
|
||||
public string LocalAppData { get; }
|
||||
public string WorldName => World;
|
||||
public void Log(string line) => _log(line);
|
||||
public void Chat(string line) => _chat(line);
|
||||
public bool OpenInBrowser(string url)
|
||||
{
|
||||
if (!WebPanelUrlPolicy.IsBrowserSafe(url)) { _log("HARNESS: OpenInBrowser got an unsafe url"); return false; }
|
||||
if (BrowserDelayMs > 0) Thread.Sleep(BrowserDelayMs);
|
||||
if (BrowserFails) { _log("HARNESS: OpenInBrowser set to fail"); return false; }
|
||||
_browser(url);
|
||||
return true;
|
||||
}
|
||||
public Thread StartStaThread(string name, ThreadStart body)
|
||||
{
|
||||
var t = new Thread(body) { Name = name, IsBackground = true };
|
||||
t.SetApartmentState(ApartmentState.STA);
|
||||
t.Start();
|
||||
return t;
|
||||
}
|
||||
public int EnvironmentDelayMsForTests => DelayMs;
|
||||
public string? BrowserExecutableFolderForTests => BrowserFolder;
|
||||
|
||||
public Action<CoreWebView2>? ConfigureForTests => web =>
|
||||
{
|
||||
web.SetVirtualHostNameToFolderMapping("panel.test", _panelDir, CoreWebView2HostResourceAccessKind.Allow);
|
||||
web.SetVirtualHostNameToFolderMapping("other.test", _otherDir, CoreWebView2HostResourceAccessKind.Allow);
|
||||
// https://go.panel.test/redirect answers 302 to other.test. Not folder-mapped: WebResourceRequested
|
||||
// is not raised for a virtual host mapping's own requests (measured: the filter on panel.test/* never fired).
|
||||
web.AddWebResourceRequestedFilter("https://go.panel.test/*", CoreWebView2WebResourceContext.All);
|
||||
web.WebResourceRequested += (s, e) =>
|
||||
{
|
||||
if (!e.Request.Uri.StartsWith("https://go.panel.test/redirect", StringComparison.OrdinalIgnoreCase)) return;
|
||||
e.Response = web.Environment.CreateWebResourceResponse(null, 302, "Found",
|
||||
"Location: https://other.test/landing.html?code=SECRET123\r\nCache-Control: no-store");
|
||||
_log("HARNESS: served the 302 for /redirect");
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
52
tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj
Normal file
52
tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
The web panel host under test, as the CoreCLR engine compiles it: src\RynthCore.Engine\WebPanel\*.cs
|
||||
(host, Win32 interop, policies, layout store, ABI argument reader) and the ABI structs from
|
||||
Plugins\PluginContract.cs, plus a stub environment (PayloadEntry.cs). tools\WebPanelHarness loads this
|
||||
DLL into a collectible AssemblyLoadContext that mirrors the shim's EngineLoadContext, drives it, and
|
||||
checks the context unloads. Not a test project on its own (no "Test" in the name: Run-AllTests skips it).
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>RynthCore.Engine.WebPanel</RootNamespace>
|
||||
<AssemblyName>WebPanelHarness.Payload</AssemblyName>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<WebView2UseWinRT>false</WebView2UseWinRT>
|
||||
<WebView2LoaderPreference>Dynamic</WebView2LoaderPreference>
|
||||
<GenerateDependencyFile>false</GenerateDependencyFile>
|
||||
<NoWarn>$(NoWarn);CS0649;CS0169</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContract.cs" Link="Engine\PluginContract.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelUrlPolicy.cs" Link="Engine\WebPanelUrlPolicy.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelWindowPolicy.cs" Link="Engine\WebPanelWindowPolicy.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelProfile.cs" Link="Engine\WebPanelProfile.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelNativeArgs.cs" Link="Engine\WebPanelNativeArgs.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelApiRules.cs" Link="Engine\WebPanelApiRules.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelLayoutStore.cs" Link="Engine\WebPanelLayoutStore.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\IWebPanelEnvironment.cs" Link="Engine\IWebPanelEnvironment.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelNative.cs" Link="Engine\WebPanelNative.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelHost.cs" Link="Engine\WebPanelHost.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- As the engine: no WinForms/WPF controls (RynthCore.Engine.csproj DropWebView2UiAssemblies). -->
|
||||
<Target Name="DropWebView2UiAssemblies" BeforeTargets="ResolveAssemblyReferences">
|
||||
<ItemGroup>
|
||||
<Reference Remove="@(Reference)" Condition="'%(Filename)' == 'Microsoft.Web.WebView2.WinForms' Or '%(Filename)' == 'Microsoft.Web.WebView2.Wpf'" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
1148
tools/WebPanelHarness/Program.cs
Normal file
1148
tools/WebPanelHarness/Program.cs
Normal file
File diff suppressed because it is too large
Load diff
52
tools/WebPanelHarness/WebPanelHarness.csproj
Normal file
52
tools/WebPanelHarness/WebPanelHarness.csproj
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline harness for the web panel host (src\RynthCore.Engine\WebPanel\WebPanelHost.cs): a 32-bit
|
||||
stand-in for acclient plus the engine. A fake game thread owns a top-level window and runs a
|
||||
PeekMessage loop; a fake 16 ms pump polls the panel state from another thread; the host (built into
|
||||
tools\WebPanelHarness.Payload) loads into a collectible AssemblyLoadContext that mirrors the shim's
|
||||
EngineLoadContext, and must unload after Shutdown. Pages come from local folders through WebView2
|
||||
virtual host mappings (https://panel.test/, https://other.test/): no network. Input is posted to
|
||||
specific windows; never SendInput (live game clients share this desktop).
|
||||
|
||||
Needs a desktop, the Evergreen WebView2 runtime and the x86 .NET 10 runtime; it opens windows.
|
||||
The folder name has no "Test" in it on purpose: scripts\Run-AllTests.ps1 does not run it.
|
||||
Run (foreground): dotnet run -c Release (WEBPANEL_HARNESS_FOREGROUND=1 to opt in, see below)
|
||||
The host's own Show calls SetForegroundWindow (pinned behaviour); with the opt-in the harness also asks for
|
||||
it for the fake game, so the foreground-dependent checks (Escape hand-back, same-process visibility) can run.
|
||||
Windows refuses either request while the user is active in another program: those checks then say UNVERIFIED.
|
||||
Each check prints "ok <name>", "FAIL <name>: ..." or "UNVERIFIED <name>: ..." (could not be shown
|
||||
offline; an owner in-game check). Exit 0 = every check ok, 1 = a FAIL, 2 = no FAIL but UNVERIFIED.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>WebPanelHarness</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Built first, never referenced: the payload must only ever load into the collectible context. -->
|
||||
<ProjectReference Include="..\WebPanelHarness.Payload\WebPanelHarness.Payload.csproj" ReferenceOutputAssembly="false" Private="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyPayload" AfterTargets="Build">
|
||||
<MSBuild Projects="..\WebPanelHarness.Payload\WebPanelHarness.Payload.csproj" Targets="GetTargetPath" Properties="Configuration=$(Configuration)">
|
||||
<Output TaskParameter="TargetOutputs" ItemName="_PayloadTarget" />
|
||||
</MSBuild>
|
||||
<PropertyGroup>
|
||||
<_PayloadDir>@(_PayloadTarget->'%(RootDir)%(Directory)')</_PayloadDir>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<_PayloadFiles Include="$(_PayloadDir)**\*.*" />
|
||||
</ItemGroup>
|
||||
<Copy SourceFiles="@(_PayloadFiles)" DestinationFiles="@(_PayloadFiles->'$(OutDir)payload\%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
304
tools/WebPanelTests/Program.cs
Normal file
304
tools/WebPanelTests/Program.cs
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
using System.Text;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.WebPanel;
|
||||
|
||||
namespace WebPanelTests;
|
||||
|
||||
/// <summary>The web panel's pure policies: URL allowlist, redaction, visibility, layout, profile folder.</summary>
|
||||
internal static unsafe class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static readonly string[] Dw = { "*.acdreamweave.com" };
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
Allowlist_ExactAndWildcard();
|
||||
Allowlist_LookalikesRejected();
|
||||
Allowlist_CaseIdnTrailingDot();
|
||||
Allowlist_BadEntries();
|
||||
Allowlist_ParseGood();
|
||||
BrowserSafe();
|
||||
Redact();
|
||||
Visibility();
|
||||
Layout();
|
||||
Profile();
|
||||
ApiRules();
|
||||
NativeArgs();
|
||||
|
||||
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Case(string name) { _case = name; Console.WriteLine("ok " + name); }
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($"FAIL {_case}: {what}");
|
||||
}
|
||||
|
||||
private static void Eq<T>(T got, T want, string what) =>
|
||||
Check(EqualityComparer<T>.Default.Equals(got, want), $"{what}: got {got}, want {want}");
|
||||
|
||||
private static void Allowlist_ExactAndWildcard()
|
||||
{
|
||||
Case("Allowlist_ExactAndWildcard");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/x", Dw), "www subdomain allowed");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://a.b.acdreamweave.com/", Dw), "deep subdomain allowed");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://acdreamweave.com/", Dw), "wildcard does not match the suffix itself");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://acdreamweave.com/", new[] { "acdreamweave.com" }), "exact entry matches");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/", new[] { "acdreamweave.com" }), "exact entry does not match subdomain");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("about:blank", Dw), "about:blank allowed");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed(null, Dw), "null rejected");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("", Dw), "empty rejected");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/", Array.Empty<string>()), "empty allowlist rejects all");
|
||||
}
|
||||
|
||||
private static void Allowlist_LookalikesRejected()
|
||||
{
|
||||
Case("Allowlist_LookalikesRejected");
|
||||
foreach (string u in new[]
|
||||
{
|
||||
"https://www.acdreamweave.com.evil.com/",
|
||||
"https://evilacdreamweave.com/",
|
||||
"https://www.acdreamweave.com@evil.com/",
|
||||
"https://evil.com/?h=.acdreamweave.com",
|
||||
"http://www.acdreamweave.com/",
|
||||
"https://www.acdreamweave.com:8443/",
|
||||
"https://user:pw@www.acdreamweave.com/",
|
||||
"file:///C:/x",
|
||||
"javascript:alert(1)",
|
||||
})
|
||||
Check(!WebPanelUrlPolicy.IsAllowed(u, Dw), "rejects " + u);
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/" + new string('a', 5000), Dw), "over MaxUrlBytes rejected");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.c\u2100/", Dw), "invalid IDN char fails closed (no throw)");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.c" + "\uD800" + "/", Dw), "lone-surrogate host fails closed (no throw)");
|
||||
}
|
||||
|
||||
private static void Allowlist_CaseIdnTrailingDot()
|
||||
{
|
||||
Case("Allowlist_CaseIdnTrailingDot");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://WWW.AcDreamWeave.com./", Dw), "case and one trailing dot");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com:443/", Dw), "explicit default port");
|
||||
string puny = new System.Globalization.IdnMapping().GetAscii("b\u00fccher.example");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://b\u00fccher.example/", new[] { puny }), "unicode host matches its punycode entry");
|
||||
Check(WebPanelUrlPolicy.IsAllowed("https://" + puny + "/", new[] { puny }), "punycode host matches itself");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://bucher.example/", new[] { puny }), "ascii lookalike does not match punycode entry");
|
||||
Check(!WebPanelUrlPolicy.IsAllowed("https://xn--bcher-kva.example/", new[] { "bucher.example" }), "punycode host does not match other entry");
|
||||
}
|
||||
|
||||
private static void Allowlist_BadEntries()
|
||||
{
|
||||
Case("Allowlist_BadEntries");
|
||||
foreach (string bad in new[] { "*", "*.com", "https://x.com", "x.com/path", "x.com:443", "a.*.com", "", " ", "x.com.", "*.x.*.com", "a b.com", "*x.com" })
|
||||
Check(!WebPanelUrlPolicy.TryParseAllowlist(bad, out _), "rejects entry list '" + bad + "'");
|
||||
Check(!WebPanelUrlPolicy.TryParseAllowlist(null, out _), "null rejected");
|
||||
string seventeen = string.Join("\n", Enumerable.Range(0, 17).Select(i => $"h{i}.example.com"));
|
||||
Check(!WebPanelUrlPolicy.TryParseAllowlist(seventeen, out _), "17 entries rejected");
|
||||
string sixteen = string.Join("\n", Enumerable.Range(0, 16).Select(i => $"h{i}.example.com"));
|
||||
Check(WebPanelUrlPolicy.TryParseAllowlist(sixteen, out var e16) && e16.Length == 16, "16 entries accepted");
|
||||
Check(!WebPanelUrlPolicy.TryParseAllowlist("good.example.com\nbad/entry", out _), "one bad entry fails the list");
|
||||
Check(!WebPanelUrlPolicy.TryParseAllowlist(new string('a', 254) + ".com", out _), "over-long entry rejected");
|
||||
}
|
||||
|
||||
private static void Allowlist_ParseGood()
|
||||
{
|
||||
Case("Allowlist_ParseGood");
|
||||
Check(WebPanelUrlPolicy.TryParseAllowlist("*.AcDreamWeave.com\r\nlocalhost\n", out var e), "parses");
|
||||
Eq(e.Length, 2, "entry count");
|
||||
Eq(e[0], "*.acdreamweave.com", "lower-cased wildcard");
|
||||
Eq(e[1], "localhost", "single-label host ok");
|
||||
}
|
||||
|
||||
private static void BrowserSafe()
|
||||
{
|
||||
Case("BrowserSafe");
|
||||
Check(WebPanelUrlPolicy.IsBrowserSafe("https://example.com/a?b=c"), "https");
|
||||
Check(WebPanelUrlPolicy.IsBrowserSafe("http://example.com/"), "http");
|
||||
foreach (string u in new[] { "file:///C:/Windows/notepad.exe", "javascript:alert(1)", "ms-settings:network", "mailto:a@b.c", "/relative/path", "example.com", "https://u:p@example.com/", "https://u@example.com/", "", " " })
|
||||
Check(!WebPanelUrlPolicy.IsBrowserSafe(u), "not safe: " + u);
|
||||
Check(!WebPanelUrlPolicy.IsBrowserSafe(null), "null not safe");
|
||||
}
|
||||
|
||||
private static void Redact()
|
||||
{
|
||||
Case("Redact");
|
||||
string r = WebPanelUrlPolicy.Redact("https://www.acdreamweave.com/launch?code=SECRET&to=/Browse#f");
|
||||
Eq(r, "https://www.acdreamweave.com/launch", "query and fragment stripped");
|
||||
Check(!r.Contains("SECRET"), "secret absent");
|
||||
Eq(WebPanelUrlPolicy.Redact("https://user:pw@host.example:8443/p/q?x=1"), "https://host.example:8443/p/q", "userinfo dropped, port kept");
|
||||
Check(!WebPanelUrlPolicy.Redact("https://user:pw@host.example/p").Contains("pw"), "password absent");
|
||||
Eq(WebPanelUrlPolicy.Redact("not a url"), "<invalid url>", "garbage");
|
||||
Eq(WebPanelUrlPolicy.Redact(null), "<invalid url>", "null");
|
||||
Eq(WebPanelUrlPolicy.Redact(""), "<invalid url>", "empty");
|
||||
Check(!WebPanelUrlPolicy.Redact("mailto:secret@x.com").Contains("secret"), "non-hierarchical leaks nothing");
|
||||
}
|
||||
|
||||
private static void Visibility()
|
||||
{
|
||||
Case("Visibility");
|
||||
// open, alive, !iconic, visible, !fgNull, fgPid, ourPid
|
||||
Eq(WebPanelWindowPolicy.Visible(true, true, false, true, false, 5, 5), (bool?)true, "same process shows");
|
||||
Eq(WebPanelWindowPolicy.Visible(true, true, false, true, false, 6, 5), (bool?)false, "other process hides");
|
||||
Eq(WebPanelWindowPolicy.Visible(true, true, false, true, true, 0, 5), (bool?)null, "null foreground keeps current");
|
||||
Eq(WebPanelWindowPolicy.Visible(true, true, true, true, false, 5, 5), (bool?)false, "iconic hides");
|
||||
Eq(WebPanelWindowPolicy.Visible(false, true, false, true, false, 5, 5), (bool?)false, "closed hides");
|
||||
Eq(WebPanelWindowPolicy.Visible(true, false, false, true, false, 5, 5), (bool?)false, "dead game hides");
|
||||
Eq(WebPanelWindowPolicy.Visible(true, true, false, false, false, 5, 5), (bool?)false, "invisible game hides");
|
||||
Eq(WebPanelWindowPolicy.Visible(false, true, false, true, true, 0, 5), (bool?)false, "closed beats null foreground");
|
||||
Eq(WebPanelWindowPolicy.Visible(true, true, true, true, true, 0, 5), (bool?)false, "iconic beats null foreground");
|
||||
}
|
||||
|
||||
private static void Layout()
|
||||
{
|
||||
Case("Layout");
|
||||
var client = new PanelRect(100, 50, 1200, 800); // 1100 x 750
|
||||
var f = WebPanelWindowPolicy.Default(0, 0);
|
||||
Check(Math.Abs(f.W - 0.88) < 1e-9 && Math.Abs(f.H - 0.88) < 1e-9, "0 means 88 %");
|
||||
Check(Math.Abs(f.X - 0.06) < 1e-9 && Math.Abs(f.Y - 0.06) < 1e-9, "centered");
|
||||
var r = WebPanelWindowPolicy.Place(client, f);
|
||||
Eq(r.Width, 968, "88 % of 1100");
|
||||
Eq(r.Height, 660, "88 % of 750");
|
||||
Eq(r.Left - client.Left, client.Right - r.Right, "horizontally centered");
|
||||
Eq(r.Top - client.Top, client.Bottom - r.Bottom, "vertically centered");
|
||||
|
||||
var full = WebPanelWindowPolicy.Default(120, 120);
|
||||
Check(full.W == 1.0 && full.H == 1.0 && full.X == 0 && full.Y == 0, "120 clamps to 100");
|
||||
var small = WebPanelWindowPolicy.Default(5, 5);
|
||||
Check(Math.Abs(small.W - 0.30) < 1e-9, "5 clamps to 30");
|
||||
Eq(WebPanelWindowPolicy.Place(client, full), client, "100 % fills the client");
|
||||
|
||||
var tiny = new PanelRect(0, 0, 300, 200);
|
||||
Eq(WebPanelWindowPolicy.Place(tiny, WebPanelWindowPolicy.Default(0, 0)), tiny, "tiny client clamps to client");
|
||||
var mid = new PanelRect(0, 0, 600, 400);
|
||||
var m = WebPanelWindowPolicy.Place(mid, WebPanelWindowPolicy.Default(30, 30));
|
||||
Check(m.Width >= 480 && m.Height >= 320, "minimum size enforced");
|
||||
Check(m.Left >= mid.Left && m.Top >= mid.Top && m.Right <= mid.Right && m.Bottom <= mid.Bottom, "min size stays inside client");
|
||||
|
||||
// Off-screen fractions stay inside.
|
||||
var off = WebPanelWindowPolicy.Place(client, new PanelFractions(0.95, 0.95, 0.5, 0.5));
|
||||
Check(off.Left >= client.Left && off.Top >= client.Top && off.Right <= client.Right && off.Bottom <= client.Bottom, "never outside client");
|
||||
|
||||
// Round trip.
|
||||
var user = new PanelRect(300, 200, 1000, 700);
|
||||
var rt = WebPanelWindowPolicy.Place(client, WebPanelWindowPolicy.FromUserRect(client, user));
|
||||
Check(Math.Abs(rt.Left - user.Left) <= 1 && Math.Abs(rt.Top - user.Top) <= 1 &&
|
||||
Math.Abs(rt.Right - user.Right) <= 1 && Math.Abs(rt.Bottom - user.Bottom) <= 1, $"round trip within 1 px: {rt}");
|
||||
var wild = WebPanelWindowPolicy.FromUserRect(client, new PanelRect(-500, -500, 5000, 5000));
|
||||
Check(wild.X >= 0 && wild.Y >= 0 && wild.W <= 1 && wild.H <= 1 && wild.X + wild.W <= 1.000001, "FromUserRect clamps to 0..1");
|
||||
}
|
||||
|
||||
// WebPanelApi's pure parts (WebPanelApiRules): the kill switch and shutdown refusals, the GetState Size check.
|
||||
private static void ApiRules()
|
||||
{
|
||||
Case("ApiRules");
|
||||
Eq(WebPanelApiRules.OpenRefusal(shuttingDown: false, enabled: true), 0, "enabled, running: go on");
|
||||
Eq(WebPanelApiRules.OpenRefusal(false, false), (int)WebPanelCode.Unavailable, "engine.json WebPanel false: Unavailable");
|
||||
Eq(WebPanelApiRules.OpenRefusal(true, true), (int)WebPanelCode.ShuttingDown, "shutting down: ShuttingDown");
|
||||
Eq(WebPanelApiRules.OpenRefusal(true, false), (int)WebPanelCode.ShuttingDown, "shutting down wins over the kill switch");
|
||||
Eq(WebPanelApiRules.CallRefusal(false), 0, "calls go on while running");
|
||||
Eq(WebPanelApiRules.CallRefusal(true), (int)WebPanelCode.ShuttingDown, "calls refused after shutdown");
|
||||
|
||||
uint min = WebPanelApiRules.StateMinSize;
|
||||
Eq(min, 28u, "OffsetOf(Reserved) of the state struct (no pointer fields: 28 on x86 and x64)");
|
||||
Check(min > 0 && min < (uint)sizeof(WebPanelStateNative), "min size is inside the struct");
|
||||
Check(!WebPanelApiRules.StateArgsOk(null), "null state refused");
|
||||
WebPanelStateNative st = default;
|
||||
st.Size = min - 1;
|
||||
Check(!WebPanelApiRules.StateArgsOk(&st), "Size below OffsetOf(Reserved) refused");
|
||||
st.Size = min;
|
||||
Check(WebPanelApiRules.StateArgsOk(&st), "Size == OffsetOf(Reserved) accepted");
|
||||
st.Size = (uint)sizeof(WebPanelStateNative);
|
||||
Check(WebPanelApiRules.StateArgsOk(&st), "full Size accepted");
|
||||
|
||||
st.Reserved[0] = 0xDEADBEEF;
|
||||
WebPanelApiRules.WriteState(&st, new WebPanelSnapshot(7, 3, 5, -9, 200, 4));
|
||||
Eq(st.Handle, 7, "handle written");
|
||||
Eq(st.Status, 3, "status written");
|
||||
Eq(st.Flags, 5u, "flags written");
|
||||
Eq(st.Error, -9, "error written");
|
||||
Eq(st.LastHttpStatus, 200, "http written");
|
||||
Eq(st.NavigationCount, 4u, "navigations written");
|
||||
Eq(st.Reserved[0], 0xDEADBEEFu, "Reserved untouched");
|
||||
Eq(WebPanelApiRules.NoPanel(9).Status, (int)WebPanelStatusCode.Superseded, "no panel yet: Superseded");
|
||||
}
|
||||
|
||||
// WebPanelNativeArgs: the strings are copied out of the caller's buffers; bad arguments are BadArgs.
|
||||
private static void NativeArgs()
|
||||
{
|
||||
Case("NativeArgs");
|
||||
const string lad = @"C:\lad";
|
||||
Eq(WebPanelNativeArgs.TryBuildRequest(null, lad, "W", out _), (int)WebPanelCode.BadArgs, "null struct");
|
||||
|
||||
int Build(string? url, string? allow, string? key, string? title, uint size, uint flags, out WebPanelRequest? req)
|
||||
{
|
||||
byte[] u = Z(url), a = Z(allow), k = Z(key), ti = Z(title);
|
||||
fixed (byte* pu = u, pa = a, pk = k, pt = ti)
|
||||
{
|
||||
var o = new WebPanelOpenNative
|
||||
{
|
||||
Size = size, Flags = flags,
|
||||
Url = url == null ? null : pu, Allowlist = allow == null ? null : pa,
|
||||
ProfileKey = key == null ? null : pk, Title = title == null ? null : pt,
|
||||
};
|
||||
int rc = WebPanelNativeArgs.TryBuildRequest(&o, lad, "W", out req);
|
||||
Array.Fill(u, (byte)'Z'); Array.Fill(a, (byte)'Z'); // the caller's buffers die right after the call
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
static byte[] Z(string? s) => s == null ? new byte[1] : Encoding.UTF8.GetBytes(s + "\0");
|
||||
uint full = (uint)sizeof(WebPanelOpenNative);
|
||||
|
||||
Eq(Build("https://a.test/x?code=1", "a.test", "k", "T", full, 0xFF, out var r), 0, "good request");
|
||||
Eq(r?.Url, "https://a.test/x?code=1", "url copied before the buffer was overwritten");
|
||||
Eq(r?.Allowlist.Length, 1, "allowlist parsed");
|
||||
Eq(r?.Title, "T", "title copied");
|
||||
Eq(r?.Flags, 3u, "unknown flag bits dropped");
|
||||
Check(r != null && r.ProfileFolder.StartsWith(lad, StringComparison.Ordinal), "profile folder under LocalAppData");
|
||||
Eq(Build("https://a.test/", "a.test", null, null, full, 0, out r), 0, "null key and title");
|
||||
Eq(r?.Title, "", "null title is empty");
|
||||
Eq(Build("https://a.test/", "a.test", null, null, 31, 0, out _), (int)WebPanelCode.BadArgs, "Size below OffsetOf(Reserved)");
|
||||
Eq(Build(null, "a.test", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "no url");
|
||||
Eq(Build("", "a.test", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "empty url");
|
||||
Eq(Build("https://a.test/", null, null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "no allowlist");
|
||||
Eq(Build("https://a.test/", "*.com", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "bad allowlist");
|
||||
Eq(Build("https://a.test/", "a.test", null, new string('t', 129), full, 0, out _), (int)WebPanelCode.BadArgs, "title over 128 bytes");
|
||||
Eq(Build("https://a.test/", "a.test", new string('k', 257), null, full, 0, out _), (int)WebPanelCode.BadArgs, "key over 256 bytes");
|
||||
Eq(Build("https://a.test/" + new string('p', 4096), "a.test", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "url over 4096 bytes");
|
||||
|
||||
byte[] bad = { 0x68, 0xC3, 0x28, 0 }; // invalid UTF-8
|
||||
fixed (byte* pb = bad) Check(!WebPanelNativeArgs.TryReadUtf8(pb, 16, true, out _), "invalid UTF-8 refused");
|
||||
}
|
||||
|
||||
private static void Profile()
|
||||
{
|
||||
Case("Profile");
|
||||
const string root = @"C:\Users\x\AppData\Local";
|
||||
string a = WebPanelProfile.Folder(root, "DreamWeave", "Alice");
|
||||
Eq(a, WebPanelProfile.Folder(root, "DreamWeave", " ALICE "), "case/space-insensitive key");
|
||||
Check(a != WebPanelProfile.Folder(root, "DreamWeave", "Bob"), "different keys differ");
|
||||
Check(a != WebPanelProfile.Folder(root, "Other", "Alice"), "different worlds differ");
|
||||
string leaf = Path.GetFileName(a);
|
||||
Eq(leaf.Length, 32, "hex is 32 chars");
|
||||
Check(leaf.All(c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')), "lowercase hex");
|
||||
// SHA-256("alice") first 16 bytes.
|
||||
Eq(leaf, Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("alice")), 0, 16).ToLowerInvariant(), "hash of lowered key");
|
||||
Eq(Path.GetFileName(WebPanelProfile.Folder(root, "W", "")), "default", "empty key");
|
||||
Eq(Path.GetFileName(WebPanelProfile.Folder(root, "W", null)), "default", "null key");
|
||||
|
||||
string evil = WebPanelProfile.Folder(root, "Dream/Weave..", "k");
|
||||
Check(!evil.Contains(".."), "no dot-dot");
|
||||
Eq(Path.GetFileName(Path.GetDirectoryName(evil)!), "Dream_Weave__", "world sanitized");
|
||||
Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, null, "k"))!), "_default", "null world");
|
||||
Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, " ", "k"))!), "_default", "blank world");
|
||||
Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, new string('w', 100), "k"))!).Length, 64, "world capped at 64");
|
||||
Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, @"..\..\x", "k"))!), "______x", "traversal neutralised");
|
||||
string full = Path.GetFullPath(evil);
|
||||
Check(full.StartsWith(Path.GetFullPath(root), StringComparison.OrdinalIgnoreCase), "under localAppData");
|
||||
Check(evil.Contains(Path.Combine("RynthCore", "WebPanel")), "RynthCore\\WebPanel layout");
|
||||
}
|
||||
}
|
||||
30
tools/WebPanelTests/WebPanelTests.csproj
Normal file
30
tools/WebPanelTests/WebPanelTests.csproj
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the web panel's pure policies (URL allowlist and redaction, window
|
||||
visibility and layout, profile folder): src\RynthCore.Engine\WebPanel\*.cs, compiled in.
|
||||
No AC, no Win32, no WebView2, no files.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>WebPanelTests</RootNamespace>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<NoWarn>$(NoWarn);CS0649;CS0169</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelUrlPolicy.cs" Link="Engine\WebPanelUrlPolicy.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelWindowPolicy.cs" Link="Engine\WebPanelWindowPolicy.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelProfile.cs" Link="Engine\WebPanelProfile.cs" />
|
||||
<!-- The ABI glue's pure parts (WebPanelApi.cs itself needs the engine): argument copy-out and refusals. -->
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContract.cs" Link="Engine\PluginContract.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelNativeArgs.cs" Link="Engine\WebPanelNativeArgs.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\WebPanel\WebPanelApiRules.cs" Link="Engine\WebPanelApiRules.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Loading…
Reference in a new issue