diff --git a/Changelog/2026-11-07-bar-menu.md b/Changelog/2026-11-07-bar-menu.md new file mode 100644 index 0000000..7fc6211 --- /dev/null +++ b/Changelog/2026-11-07-bar-menu.md @@ -0,0 +1,46 @@ +# Bar icon dropdown: plugin API v95 + +Branch `pr/bar-menu`, from `pr/web-panel` (web panel, v94). Not deployed. The API number 95 is provisional, as +94 is (unmerged upstream branches also use these numbers; whichever merges second renumbers). The manifest is parsed here; the bar draws it (below). + +## What changed + +- A plugin window in the sections manifest (`windows`, with `"bar": true`) may declare `"barMenu"`: up to 6 items of + `{ "id", "tooltip", "icon", "command" }`. `SectionManifest.cs` parses it into `SectionWindowDecl.BarMenu` + (`SectionBarMenuItem` records; `Menu` is the never-null view). +- Validation, with the window always kept: the id is a short lower-case word and unique in the menu, the tooltip is + non-empty and capped at 48 characters, the command is a single `/...` chat command (the same rule as a contribution's), + the icon is one Phosphor glyph or empty (an icon that is not a glyph is kept as an empty icon, and the bar draws the tooltip's first letter). An item with a bad id, tooltip or command is dropped; items past + `MaxBarMenuItems` (6) are ignored; a `barMenu` that is not an array is ignored. +- `PluginContractVersion.Current` and the SDK's `RynthCoreSdkApiVersion` (`RynthCore.PluginSdk.targets`) go to 95. + No function table change. Engines before v95 ignore the key, so a plugin can declare it unconditionally. + +## Tests + +`tools/SectionsTests`: + +- `ManifestBarMenu`: valid items in order with exact fields, rejected commands (no slash, a line break, over-long), + empty id, duplicate id, empty tooltip, empty icon kept, 20 items capped to 6, a non-array `barMenu`, no key, and the + 48-character tooltip cap. +- `BarMenuHoverTiming`: the 0.15 s open delay, a quick sweep never opening, the 0.30 s close delay covering the gap + from icon to dropdown, switching to another icon at once, no reopen while still hovering after a click, and a + clock jump or a gap over 0.5 s resetting. +- `BarMenuReload`: a change to only `barMenu` leaves the panel signature alone (no re-registration) and changes the + menu signature (so the bar rebuilds). + +`tools/PluginManifestTests` pins the SDK and engine numbers together, and that `PluginContractVersion.BarMenu` is at or +below `Current`. + +Not yet tested in game. + +## The dropdown + +- Hovering a plugin window's bar icon for 0.15 s drops a column of icon buttons flush below it (flush above when it would + cross the bottom of the screen; clamped sideways). It stays while the mouse is over the icon or the column, and for + 0.30 s after it leaves both. Another icon's dropdown replaces it at once. Clicking an item runs its command as a player + chat command (the hotkey path) and closes the dropdown. The icon's own click still toggles the window. +- A plugin reload that changes only `barMenu` reaches the bar: `PluginWindows.Sync` refreshes the hosted declaration + (`WindowPlan.MenuSignature`) without re-registering the panel, and bumps the version so the bar rebuilds its buttons. +- The dropdown is brought to the display front every frame (cimgui `igBringWindowToDisplayFront`, no focus change), so a + panel focused since does not cover it; without those exports it keeps its normal order and logs once. +- Timing is `ImGui/BarMenuHover.cs` (pure; `SectionsTests` `BarMenuHoverTiming`). Drawing is in-game only. diff --git a/Changelog/2026-11-07-web-panel.md b/Changelog/2026-11-07-web-panel.md new file mode 100644 index 0000000..8f1ba86 --- /dev/null +++ b/Changelog/2026-11-07-web-panel.md @@ -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. \ No newline at end of file diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index fa14668..91ad778 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -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. +``` diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 8cc0b84..b982d4d 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -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) { diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index 2a0e746..f52a0fd 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -199,7 +199,11 @@ internal static class ChatCommandReplies V("unlockactions", "Usage: /rc unlockactions (opens the client's item-action gates now)", NoArgs, "unlock"), 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), + // The extra chat windows (ImGui/Panels/ChatWindowFace); its handler checks the arguments + // (UI/Data/ChatWindows.Parse, whose Usage is this same line). + V("chatwindow", "Usage: /rc chatwindow [list] | open [tab] | close <2-7|all> | tab <2-7> ", null, "chatwin", "chatwindows"), 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")), }; /// /rc uicost: the UI frame cost breakdown (ImGui/UiCost.cs). diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 3330ce1..0e5dbc1 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -108,6 +108,9 @@ namespace RynthCore.Engine.Compatibility; /// /rc uicost [on|off|<ms>|now|status] - the UI frame cost breakdown /// (): 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. +/// /rc webpanel [status|close] - the in-game web panel (): +/// status is one redacted line (state, handle, visible/focused, browser pid, free address space); +/// close closes the panel. It never opens a URL. /// /// internal static class RynthCoreChatCommands @@ -650,12 +653,26 @@ 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)) { HandleLayoutCommand(layoutArgs); return; } + // /rc chatwindow [list] | open [tab] | close | tab : the extra chat windows. + if (IsVerb(sub, "chatwindow", out string chatWinArgs) || IsVerb(sub, "chatwin", out chatWinArgs) + || IsVerb(sub, "chatwindows", out chatWinArgs)) + { + HandleChatWindowCommand(chatWinArgs); + return; + } if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs)) { // The parser's own errors (an unknown verb, a bad key) are the failures; the rest is what changed. @@ -1216,6 +1233,32 @@ internal static class RynthCoreChatCommands Reply(ChatCommandReplies.PanelReply(label, null, wasOpen)); } + /// + /// /rc chatwindow: the extra chat windows (ImGui/Panels/ChatWindowFace). Alone or list: which + /// are open and what they show; open [tab] (alone: the main chat's tab); close <n|all>; + /// tab <n> <tab>. Every form answers with what happened, or why not and the usage. + /// + private static void HandleChatWindowCommand(string args) + { + UI.Data.ChatWindowCommand c = UI.Data.ChatWindows.Parse(args); + (bool Ok, string Message) r; + switch (c.Verb) + { + case UI.Data.ChatWindowVerb.List: + ReplyLines(ImGuiBackend.Panels.ChatWindowFace.Describe(), + ImGuiBackend.Panels.ChatWindowFace.Available ? ChatReplyKind.Ok : ChatReplyKind.Fail); + return; + case UI.Data.ChatWindowVerb.Open: r = ImGuiBackend.Panels.ChatWindowFace.OpenNew(c.Tab); break; + case UI.Data.ChatWindowVerb.Close: r = ImGuiBackend.Panels.ChatWindowFace.Close(c.Number); break; + case UI.Data.ChatWindowVerb.CloseAll: r = ImGuiBackend.Panels.ChatWindowFace.CloseAll(); break; + case UI.Data.ChatWindowVerb.Tab: r = ImGuiBackend.Panels.ChatWindowFace.ShowTab(c.Number, c.Tab); break; + default: + Fail(c.Error); + return; + } + Answer(r.Ok, r.Message, r.Message); + } + /// /// "/rc sense compact on|off | collapse on|off | view full|compact|collapsed": the Sense panel's /// look (saved in sense.txt), and the look now; alone, compact / collapse / view say the look now. @@ -1716,6 +1759,27 @@ internal static class RynthCoreChatCommands ReplyLines(UI.Data.Discord.ChatDiscord.HandleCommand(verb)); } + /// + /// /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. + /// + 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()); + } + /// /// /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; diff --git a/src/RynthCore.Engine/Compatibility/UiElementHooks.cs b/src/RynthCore.Engine/Compatibility/UiElementHooks.cs index 9bc389b..b50c847 100644 --- a/src/RynthCore.Engine/Compatibility/UiElementHooks.cs +++ b/src/RynthCore.Engine/Compatibility/UiElementHooks.cs @@ -383,9 +383,8 @@ internal static unsafe class UiElementHooks [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] private static byte CatchDroppedItemDetour(IntPtr catcher, IntPtr dragDropInfo) { - var original = (delegate* unmanaged[Thiscall])_origCatchDrop; if (!CatchDropSlot.Enabled || _dead || dragDropInfo == IntPtr.Zero) - return original(catcher, dragDropInfo); + return CallOriginalCatchDrop(catcher, dragDropInfo); uint obj = 0, spell = 0; try @@ -411,7 +410,7 @@ internal static unsafe class UiElementHooks LogOnce("CatchDroppedItem", ex); } - byte result = original(catcher, dragDropInfo); + byte result = CallOriginalCatchDrop(catcher, dragDropInfo); try { _dragObject = _dragSpell = 0; @@ -475,6 +474,29 @@ internal static unsafe class UiElementHooks return false; } + private static int _catchDropFaults; + + /// + /// AC's CatchDroppedItem, called through the SEH trampoline. AC's own drop handlers can fault + /// (seen 11-09: a null read inside the item-list drop code at a vault). Without our detour the + /// game-tick guard survives that; with a managed frame in between, the CLR would end the + /// process. So the fault is caught here, the drop counts as not caught, and the client goes on. + /// + private static byte CallOriginalCatchDrop(IntPtr catcher, IntPtr dragDropInfo) + { + if (!SehTrampoline.IsAvailable) + return ((delegate* unmanaged[Thiscall])_origCatchDrop)(catcher, dragDropInfo); + + byte result = SehTrampoline.ThiscallByteUint(_origCatchDrop, catcher, (uint)dragDropInfo, out bool faulted); + if (!faulted) + return result; + + int n = Interlocked.Increment(ref _catchDropFaults); + if (n <= 5) + try { RynthLog.Compat($"UiElementHooks: AC's CatchDroppedItem faulted (access violation) on element 0x{(catcher != IntPtr.Zero ? *(uint*)(catcher + ElementId) : 0):X8}; drop treated as not caught, client kept running ({n} so far)."); } catch { } + return 0; + } + private static int _loggedErrors; private static void LogOnce(string where, Exception ex) diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index f10593d..b45b966 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -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 diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 8d6486b..1f58e84 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -1236,6 +1236,7 @@ public static class EntryPoint if (HasPluginDll("RynthCore.Plugin.RynthChat.dll")) { ImGuiBackend.Panels.ChatFace.Register(); + ImGuiBackend.Panels.ChatWindowFace.RegisterAll(); // "Chat 2".."Chat 7", the extra chat windows ImGuiBackend.Panels.ChatFiltersFace.Register(); ImGuiBackend.Panels.ChatDiscordFace.Register(); } diff --git a/src/RynthCore.Engine/ImGui/BarMenuHover.cs b/src/RynthCore.Engine/ImGui/BarMenuHover.cs new file mode 100644 index 0000000..3a2e6b2 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/BarMenuHover.cs @@ -0,0 +1,79 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/BarMenuHover.cs +// The timing of the bar icon dropdown (a plugin window's "barMenu", plugin API +// v95): pure, so tools/SectionsTests compiles it as is. ImGuiBar feeds it once +// a frame. +// +// An icon must be hovered OpenDelay before its dropdown opens (a sweep of the +// mouse across the bar opens nothing). Once open, the dropdown stays while the +// mouse is over the icon or the dropdown, and for CloseDelay after it leaves +// both (the gap between them is crossed within that). Hovering another icon +// while one is open switches at once. After a click (Close) the same icon does +// not reopen until the mouse has left it and hovered it again. +// ============================================================================ + +namespace RynthCore.Engine.ImGuiBackend; + +internal sealed class BarMenuHover +{ + public const double OpenDelay = 0.15, CloseDelay = 0.30; + /// Frames further apart than this (or a clock that runs backwards) reset the state. + public const double ResetGap = 0.5; + + private string? _hovered; // the icon being hovered, and since when (_hoverStart) + private double _hoverStart; + private double? _leftAt; // when the mouse left both the icon and the dropdown (open only) + private string? _closedByClick; // the icon hovered when Close() ran: ignored until it is left + private double _lastNow = double.NegativeInfinity; + + /// The bar button id whose dropdown is open, else null. + public string? OpenFor { get; private set; } + + /// + /// Once per frame. : id of the menu-bearing bar button under the mouse, else null. + /// : the mouse is over the open dropdown. : seconds. + /// + public void Update(string? hoveredButton, bool overMenu, double now) + { + // The clock is one ImGui context's (the popped-out bar has its own, starting near 0), and a bar that + // wasn't drawn for a while sends no frames: either way, start from a closed dropdown. + if (now < _lastNow || now - _lastNow > ResetGap) + { + OpenFor = null; + _hovered = null; + _hoverStart = now; + _leftAt = null; + _closedByClick = null; + } + _lastNow = now; + + if (_closedByClick != null && hoveredButton != _closedByClick) _closedByClick = null; + string? hovered = hoveredButton != null && hoveredButton == _closedByClick ? null : hoveredButton; + + if (hovered != _hovered) { _hovered = hovered; _hoverStart = now; } + + if (OpenFor != null) + { + if (hovered != null) { OpenFor = hovered; _leftAt = null; } + else if (overMenu) _leftAt = null; + else + { + _leftAt ??= now; + if (now - _leftAt.Value >= CloseDelay) { OpenFor = null; _leftAt = null; } + } + } + else if (hovered != null && now - _hoverStart >= OpenDelay) + { + OpenFor = hovered; + _leftAt = null; + } + } + + /// An item was clicked, or the bar went away. + public void Close() + { + OpenFor = null; + _leftAt = null; + _closedByClick = _hovered; + } +} diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 89ba804..5f8fca0 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -894,6 +894,7 @@ internal static class EngineFrameController ImGuiNET.ImGui.NewFrame(); UiCost.Stop(UiCost.ImGuiNewFrame, cNew); frameStarted = true; + ImGuiPopOuts.NoteMainFrame(); // _context is current: the frame number pop-out frames share // Before any window: a drag from a popped-out Inventory or AC's inventory becomes // a payload the client's drop targets (Mini Remote slots) see this frame. ItemDragBridge.SubmitMainFrame(io); diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index 3d1815a..beab7f9 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -11,6 +11,9 @@ // draws that asked for one (its manifest's "windows" with "bar", UI/Sections/ // PluginWindows.cs; an engine panel such a window has taken over loses its own // button), reload (RL) and pop out. +// A plugin window with a "barMenu" (plugin API v95) drops a column of icon buttons below its +// bar icon after the mouse rests on it (BarMenuHover: open and close delays); a click runs that +// item's chat command. The icon's own click still toggles the window. // A button whose window is open, docked or popped out, draws highlighted in the // theme's accent (RynthTheme.BarButtonOpen*); the ILT and Scripts buttons while // any window in their menu is (UI/BarOpenState.cs; one IsOpen lookup a key). @@ -71,7 +74,17 @@ internal static class ImGuiBar // the button toggles it through ScriptWindowRegistry, like the Scripts menu does. // OpenKey: the panel whose open state lights the button (BarOpenState.KeyFor). private sealed record ButtonInfo(string Title, string Id, string Icon, bool Letter, string Tooltip, - string OpenKey, ScriptWindow? Window = null); + string OpenKey, ScriptWindow? Window = null, UI.Sections.SectionBarMenuItem[]? Menu = null); + + // The bar icon dropdown (a plugin window's "barMenu"): the timer, last frame's "mouse is over the + // dropdown", the menu-bearing buttons' rects this frame, and when the timer was last fed (a gap + // means the bar wasn't drawn: start from a closed dropdown). + private static readonly BarMenuHover _menuHover = new(); + private static bool _overMenu; + private static readonly List<(ButtonInfo Button, Vector2 Min, Vector2 Max)> _menuRects = new(); + private const ImGuiWindowFlags MenuFlags = ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.AlwaysAutoResize + | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoDocking + | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav; // The open check every highlight uses (one set lookup a key), as one delegate: no allocation a frame. private static readonly Func IsOpenCheck = ImGuiPanelHost.IsOpen; @@ -133,7 +146,13 @@ internal static class ImGuiBar { letter = !PanelIcons.TryGetValue(title, out string? icon); if (!letter) return icon!; - foreach (char c in title) + return FirstLetter(title); + } + + /// The bar's letter fallback: the first letter or digit of , upper-cased, else "?". + private static string FirstLetter(string text) + { + foreach (char c in text) if (char.IsLetterOrDigit(c)) return char.ToUpperInvariant(c).ToString(); return "?"; } @@ -468,7 +487,9 @@ internal static class ImGuiBar SafeImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button"); PhosphorIcons.DrawCentered(dl, iconFont, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretLeft, cPos, caretSize, caretHot ? RynthTheme.RcLabel : 0xFF9A9A9Au); - if (collapsed) return; + double menuNow = ImGuiNET.ImGui.GetTime(); + _menuRects.Clear(); + if (collapsed) { _menuHover.Update(null, false, menuNow); _overMenu = false; return; } // Rows (header): perRow icons a row, each row from iconsX (under the first icon); // RL and pop out go at the end of the first row (NextSlot, or after the icons when @@ -487,6 +508,7 @@ internal static class ImGuiBar ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11); // A button whose window is open (docked or popped out) draws in the theme's accent // (BarOpenState); a menu button (ILT, Scripts) while any window it lists is open. + string? menuHovered = null; foreach (ButtonInfo b in _buttons!) { NextSlot(ref slot, perRow, iconsX, s, iconFont, popped); @@ -496,7 +518,12 @@ internal static class ImGuiBar if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !open); else PanelRouter.Toggle(b.Title); } - SafeImGui.SetItemTooltip(b.Tooltip); + if (b.Menu != null) + { + if (ImGuiNET.ImGui.IsItemHovered()) menuHovered = b.Id; + _menuRects.Add((b, ImGuiNET.ImGui.GetItemRectMin(), ImGuiNET.ImGui.GetItemRectMax())); + } + if (_menuHover.OpenFor != b.Id) SafeImGui.SetItemTooltip(b.Tooltip); // the dropdown sits where it would show } // The ILT section: one button, only on Infinite Leaftide with ILT panels registered @@ -533,6 +560,109 @@ internal static class ImGuiBar // Drawn after the bar buttons' style is popped, so the menu has the normal look. ScriptsMenu(scripts); IltMenu(); + _menuHover.Update(menuHovered, _overMenu, menuNow); + DrawBarMenu(s, square, iconFont, letterFont); + } + + /// + /// The bar icon dropdown of the button names: a column of square icon + /// buttons flush under the icon (flush above it when that would cross the bottom of the screen), clamped + /// to the screen sideways. Its own window, not a popup, so the bar keeps its hover. A click runs the + /// item's chat command as the player's. AC thread, inside the bar window. + /// + private static void DrawBarMenu(float s, Vector2 square, ImFontPtr iconFont, ImFontPtr letterFont) + { + _overMenu = false; + string? openFor = _menuHover.OpenFor; + if (openFor == null) return; + ButtonInfo? owner = null; + Vector2 min = default, max = default; + foreach (var r in _menuRects) + if (r.Button.Id == openFor) { owner = r.Button; min = r.Min; max = r.Max; break; } + if (owner?.Menu == null || owner.Menu.Length == 0) { _menuHover.Close(); return; } + + UI.Sections.SectionBarMenuItem[] items = owner.Menu; + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + float inset = 4f * s; // WindowPadding (4, 3) + float width = square.X + 2f * inset; + float height = items.Length * square.Y + (items.Length - 1) * ButtonGap * s + 6f * s; + float x = min.X - inset, y = max.Y; // icons straight under the parent + if (display.X > 1 && display.Y > 1) + { + if (y + height > display.Y && min.Y - height >= 0f) y = min.Y - height; // flush above instead + x = Math.Max(0f, Math.Min(x, display.X - width)); + } + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(x, y), ImGuiCond.Always); + + PushBarWindowStyle(s); + PushBarButtonStyle(s); + bool begun = ImGuiNET.ImGui.Begin("##rc_bar_menu", MenuFlags); + bool clicked = false; + try + { + if (begun) + { + // NoFocusOnAppearing leaves a re-shown menu behind a panel focused since: lift it + // every frame (no focus change, so another window's text edit stays active). + MenuToFront(); + _overMenu = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); + // ImGui truncates the window's position, which can leave the icons up to a pixel left of + // the parent; put each one exactly where the placement meant (the parent's left edge + // unless the viewport clamp moved the window). Each new line starts back at the window's + // own content edge, so this is set per icon. + float iconX = x + inset; + foreach (UI.Sections.SectionBarMenuItem item in items) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(iconX, ImGuiNET.ImGui.GetCursorScreenPos().Y)); + bool letter = item.Icon.Length == 0; + string glyph = letter ? FirstLetter(item.Tooltip) : item.Icon; + if (IconButton(owner.Id + "_m_" + item.Id, letter ? letterFont : iconFont, glyph, square, RynthTheme.BarText)) + { + if (!AcMainThreadQueue.EnqueueChatCommand(item.Command, ChatCommandOrigin.Player)) + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Bar menu: the chat command queue is full; try again.", 1); + clicked = true; + } + SafeImGui.SetItemTooltip(item.Tooltip); + } + } + } + finally + { + ImGuiNET.ImGui.End(); + PopBarButtonStyle(); + PopBarWindowStyle(); + } + if (clicked) { _menuHover.Close(); _overMenu = false; } + } + + private static IntPtr _getCurrentWindow, _bringToFront; + private static int _frontState; // 0 = not resolved, 1 = available, -1 = off + + /// + /// Brings the current window (the bar menu) to the display front without focusing it, through + /// cimgui's igGetCurrentWindow and igBringWindowToDisplayFront (resolved once, as ImGuiStackGuard + /// does). Missing exports: logged once, and the menu keeps its normal order. Inside the menu's Begin. + /// + private static unsafe void MenuToFront() + { + if (_frontState == 0) + { + _frontState = -1; + IntPtr module = EntryPoint.ImGuiNativeHandle; + if (module != IntPtr.Zero + && System.Runtime.InteropServices.NativeLibrary.TryGetExport(module, "igGetCurrentWindow", out IntPtr get) + && System.Runtime.InteropServices.NativeLibrary.TryGetExport(module, "igBringWindowToDisplayFront", out IntPtr bring)) + { + _getCurrentWindow = get; + _bringToFront = bring; + _frontState = 1; + } + else + RynthLog.UI("ImGuiBar: this cimgui.dll has no igGetCurrentWindow / igBringWindowToDisplayFront exports; the bar menu can draw behind a panel focused since."); + } + if (_frontState < 0) return; + void* window = ((delegate* unmanaged[Cdecl])_getCurrentWindow)(); + if (window != null) ((delegate* unmanaged[Cdecl])_bringToFront)(window); } /// @@ -836,7 +966,7 @@ internal static class ImGuiBar bool letter = false; string icon = w.Icon.Length > 0 ? w.Icon : IconFor(w.Title, out letter); list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title, - BarOpenState.KeyFor(w.Title, null))); + BarOpenState.KeyFor(w.Title, null), Menu: w.Menu.Length > 0 ? w.Menu : null)); } // Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the // engine's own. Only while the plugin is loaded and has submitted the window. diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index 2236b4b..2cd29f6 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -256,11 +256,14 @@ internal static class ImGuiPanelHost } } - /// Changes a dynamic face's header text. Any thread. + /// + /// Changes a face's header text: a dynamic face's, or an engine panel's that names what it + /// shows (an extra chat window's tab). Not while a plugin window has the panel's place. Any thread. + /// public static void SetDisplayTitle(string key, string displayTitle) { lock (Sync) - if (Entries.TryGetValue(key, out Entry? e) && e.Dynamic) e.DisplayTitle = displayTitle; + if (Entries.TryGetValue(key, out Entry? e) && !e.TakenOver) e.DisplayTitle = displayTitle; } /// diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index 868feab..01188e0 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -109,6 +109,23 @@ internal static unsafe class ImGuiPopOuts /// True while a pop-out's ImGui frame is being built (inside a face's Draw). AC thread. public static bool InPopOutFrame => _current != null; + private static int _mainFrame; + + /// + /// The main context's ImGui frame number, the same inside a pop-out's frame (whose own + /// context counts its frames from 0): for frame-numbered state shared across contexts + /// (a script window's local values and its replay budget, ScriptWindowReplay). AC thread. + /// + public static int FrameNumber => + _current != null || ImGuiNET.ImGui.GetCurrentContext() == IntPtr.Zero ? _mainFrame : ImGuiNET.ImGui.GetFrameCount(); + + /// + /// Records the main context's frame number for . Call right after + /// the main context's NewFrame, with it current (EngineFrameController.BuildImGuiFrame): + /// the main context is not current when the pop-outs render. AC thread. + /// + public static void NoteMainFrame() => _mainFrame = ImGuiNET.ImGui.GetFrameCount(); + /// /// Where a popped-out face puts its window (its top-left in the pop-out's ImGui /// coordinates): the panel's place on the work area. (0,0) outside a pop-out frame. @@ -422,6 +439,10 @@ internal static unsafe class ImGuiPopOuts return; } + // No ImGui call before a pop-out's own context is current: the main context is NOT current + // here (EngineFrameController restores the previous one, normally none, after each frame), and + // igGetFrameCount with no context is an access violation that ends the client (11-10). The main + // frame number comes from NoteMainFrame instead. IntPtr previous = ImGuiNET.ImGui.GetCurrentContext(); long now = Stopwatch.GetTimestamp(); try @@ -720,7 +741,10 @@ internal static unsafe class ImGuiPopOuts public static string? RequestSnapshot(string title) { if (!Pops.TryGetValue(title, out PopOut? pop)) return null; - string path = System.IO.Path.Combine(LogPaths.LogDirectory, $"popout_{title.Replace(' ', '_')}.bmp"); + // A script window's key ("script:RynthLua/loot-inbox/Loot") isn't a file name as it is. + var name = new System.Text.StringBuilder(title.Length); + foreach (char c in title) name.Append(c == ' ' || Array.IndexOf(System.IO.Path.GetInvalidFileNameChars(), c) >= 0 ? '_' : c); + string path = System.IO.Path.Combine(LogPaths.LogDirectory, $"popout_{name}.bmp"); pop.Surface.SnapshotPath = path; pop.HotFrames = Math.Max(pop.HotFrames, 2); return path; diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 3d28325..f0529b5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -1,36 +1,26 @@ // ============================================================================ // RynthCore.Engine - ImGui/Panels/ChatFace.cs -// ImGui face of RynthChat (docked or popped out; the old Avalonia face is -// UI/Panels/RynthChatPanel.cs): channel and custom tabs with unread counts -// (right-click a tab: mark read, rename, delete), Filters (the ChatFilters -// rule editor), the settings gear (with a colour per kind of line under -// "Line colours", ChatLineColors), search, the coloured scrollback, and the -// input line with Tell and the panel's resize grip beside it. +// ImGui face of RynthChat's main window (docked or popped out; the old +// Avalonia face is UI/Panels/RynthChatPanel.cs): channel and custom tabs with +// unread counts (right-click a tab: mark read, rename, delete, open in a new +// window), Filters (the ChatFilters rule editor), the settings gear (with a +// colour per kind of line under "Line colours", ChatLineColors), the New chat +// window button, search, the coloured scrollback, and the input line with +// Tell and the panel's resize grip beside it. // -// Scrollback: wrapped lines, heights cached per wrap width and font; only -// the lines in view are drawn. The timestamp is dimmed and the text wraps -// under itself. Lines keep the colour and highlights the rules gave them -// (ChatLine.Route, worked out on the pump - no regex runs here); a line with -// highlights is laid out by hand (LayoutSpans) so each run can take its own -// colour. Drag across lines to copy them (the keyboard stays with the game, -// so copy is mouse-driven). Right-click a line to copy it or to make a rule -// from it: move / copy lines like it to a tab, hide them, colour or highlight -// them (a "Highlight line" rule: a band behind the whole line). A line -// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go -// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The -// coordinates are also drawn as underlined links: click points RynthNav's -// arrow there (its overlay opens), Ctrl+click walks there. -// Follows the newest line until you scroll up; the scroll for new lines is set -// in the same frame they're drawn (DrawLines; until 2026-10-11 it landed a frame -// late and the text bounced). Scrolled up, the view holds still. The history is -// as long as the "Chat history" setting (ChatHistory, up to 10,000 lines): no -// per-frame work walks all of it, and re-measuring after a resize is time-sliced. +// The scrollback, its menus and the unread counts are a ChatView (ChatView.cs, +// 2026-11-09), shared with the extra chat windows (ChatWindowFace.cs, "Chat 2" +// to "Chat 7"), each of which has its own view and tab. This window shows +// ChatModel's current tab, as before; the settings and the input line are +// this window's only. // // The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend // turns the chat keys into ChatModel edits on AC's thread, which is also // this face's thread. Clicking the box starts typing, like Enter. While // typing, Ctrl+V pastes and Ctrl+C / Ctrl+X copy / cut the whole line; -// /r and /rt reply and retell (TellMemory). +// /r and /rt reply and retell (TellMemory). The extra windows have no input +// line: there is one chat entry (Enter, the typed line, the Tell button), and +// it stays here. // // The panel has no strip under the body for the resize grip (PanelSpec. // GripInBody): the input row stops short of the bottom-right corner by @@ -57,7 +47,7 @@ internal sealed class ChatFace : IImGuiPanel // top" (ChatModel.TabsAcross, 2026-10-20) puts the row back for those who want it. private readonly ChannelsDrawer _channels; private readonly DashboardDrawers _drawers; - private bool _openTabsPopup; + private readonly ChatView _view; /// /rc ui channels: the channels drawer opens or closes on the next draw, as its button does. public static volatile bool ToggleChannelsRequested; @@ -66,81 +56,27 @@ internal sealed class ChatFace : IImGuiPanel { _channels = new ChannelsDrawer(this); _drawers = new DashboardDrawers("##chat_drawers", _channels); + _view = new ChatView(Title, isMain: true, ChatModel.CurrentTab, ChatModel.SelectTab); } - public static void Register() => ImGuiPanelHost.Register(Title, - new PanelSpec(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true), - () => new ChatFace()); + /// The window spec, shared with the extra chat windows (ChatWindowFace). + internal static PanelSpec Spec => new(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true); - private static readonly uint TabAdd = RynthTheme.Argb(0xFF7AE09A), InputActive = RynthTheme.Argb(0xFFFFD700), - SelBg = RynthTheme.Argb(0x663A6EA5), TellBg = RynthTheme.Argb(0xFF0E2E3A), - TsColor = RynthTheme.Argb(0xFF6F8397), MentionBg = RynthTheme.Argb(0x33FFC857), - BadgeBg = RynthTheme.Argb(0xFF1F6F7A), BadgeMention = RynthTheme.Argb(0xFFB8860B); + public static void Register() => ImGuiPanelHost.Register(Title, Spec, () => new ChatFace()); + + private static readonly uint InputActive = RynthTheme.Argb(0xFFFFD700), TellBg = RynthTheme.Argb(0xFF0E2E3A); private static uint TabActive => RynthTheme.AccentFill; private static uint InputBg => RynthTheme.BoxBg; private static uint InputBorder => RynthTheme.AccentFill; - private static uint FlashBg => RynthTheme.WithAlpha(RynthTheme.AccentFill, 0xE0); - private const float StickThreshold = 24f; - // Visible lines for the current tab + search, with wrapped heights; _lay - // holds the hand layout of lines with highlights (null for plain lines). - private readonly List _vis = new(512); - private readonly List _h = new(512); - private readonly List _lay = new(512); - private float[] _tops = new float[1]; - private int _heightsFrom; // first new line: not measured at all yet - // Lines below this index were measured for another width or font, or not at all (a - // rebuild gives them one row each until then): MeasureLines catches up a few ms a frame. - private int _measuredFrom; - private float _rowH = 13f; // one row of the chat font: an unmeasured line's height - private bool _topsDirty = true; - private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId; - private string _seenTab = "", _seenSearch = ""; - private float _seenWrap = -1, _seenFont = -1; - private bool _seenTs; - - private readonly byte[] _search = new byte[128], _newTab = new byte[64], _mentionWords = new byte[256]; - private bool _stick = true; - private float _lastScrollY; - // Height of lines dropped off the top (the buffer is full) while not following the - // tail: the view is moved up by as much, so the lines being read stay put instead of - // sliding away. - private float _droppedAbove; - // The part of a dropped-lines move ImGui's whole-pixel scroll couldn't take, carried - // into the next one (heights can be fractional at some DPI scales). - private float _scrollCarry; - // The list's scrollbar width (always shown), and a correction to the list width - // DrawLines works out before its BeginChild, should the child ever report another. - private const float ListScrollbarW = 10f; - private float _wrapFix; + private readonly byte[] _mentionWords = new byte[256]; private float _inputScroll; - // Selection: indices into _vis. - private int _selAnchor = -1, _selEnd = -1; - private bool _selDragging, _selMoved; - private Vector2 _selDown; - private string? _flash; - private double _flashUntil; - - // Unread lines per tab since it was last on screen (Id of the newest line seen there). - private readonly Dictionary _seenId = new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary _unread = new(StringComparer.OrdinalIgnoreCase); - private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1, _unreadCountedTo; - private string _unreadTab = ""; - - private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename; + private bool _openSettings; /// A line colour changed and isn't saved yet (saved once the picker is let go). private bool _coloursDirty; /// The Chat history slider's value while it's held (0: not held). private int _historyEdit; - private string? _ctxTab, _renameFrom; - private ChatLine? _ctxLine; - private string _ctxPattern = ""; - // Map coordinates in the right-clicked line (ChatCoords, found when the menu opens): - // its menu offers "Arrow to" / "Go to" them, through RynthNav. - private List _ctxCoords = new(); - /// A Move/Copy rule waiting for the New tab popup to name its tab. - private ChatFilterRule? _pendingRule; public bool ClickThrough => ChatModel.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl; @@ -153,16 +89,14 @@ internal sealed class ChatFace : IImGuiPanel UiSources.Chat.Subscribe(); UiSources.Chat.RequestRefresh(); ChatModel.SetShown(true); - _stick = true; - _seenRoutes = -1; // full rebuild on the first frame - _seenId.Clear(); // every tab starts read - _unreadLines = _unreadRoutes = -1; // a full recount + _view.OnShown(); } public void OnHidden() { ChatModel.SetShown(false); UiSources.Chat.Unsubscribe(); + _view.OnHidden(); } public void Draw() @@ -178,20 +112,19 @@ internal sealed class ChatFace : IImGuiPanel var snap = UiSources.Chat.Current; ChatLine[] lines = snap?.Value ?? Array.Empty(); - string tab = ChatModel.CurrentTab(); - UpdateUnread(lines, snap?.Version ?? -1, tab); + string tab = _view.BeginFrame(lines, snap?.Version ?? -1); bool across = ChatModel.TabsAcross; float y; if (across) { y = DrawTabStrip(new Vector2(x0, origin.Y + 4), w); - DrawSearch(new Vector2(x0, y), w); + _view.DrawSearch(new Vector2(x0, y), w); y += 26; } else y = DrawHeader(new Vector2(x0, origin.Y + 4), w); - SyncLines(snap, lines, tab); + _view.SyncLines(snap, lines, tab); // Scrollback, then the input row along the bottom; the grip takes its // bottom-right corner (ImGuiPanelHost.BodyGripReserve). @@ -200,7 +133,7 @@ internal sealed class ChatFace : IImGuiPanel float inputY = origin.Y + size.Y - bottomPad - inputH; float listH = Math.Max(20, inputY - 4 - y); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y)); - DrawLines(new Vector2(w, listH)); + _view.DrawLines(new Vector2(w, listH)); float inputRight = reserve > 0 ? origin.X + size.X - reserve - 3 : x0 + w; DrawInput(new Vector2(x0, inputY), inputRight - x0, inputH); @@ -212,93 +145,67 @@ internal sealed class ChatFace : IImGuiPanel // ── Tabs ───────────────────────────────────────────────────────────── - private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search…"; - /// - /// One row: the channel button (current tab, unread elsewhere; it opens the channels - /// drawer, or a list when popped out), search, Filters and the gear. Returns the y below it. + /// The buttons at the right of the top row: the gear, Filters and New chat window, right to + /// left. Returns the x left of them. /// - private float DrawHeader(Vector2 start, float w) + private float DrawRightButtons(Vector2 start, float w, float h) { - const float h = 22; - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - float gearW = 22, filtW = 22, right = start.X + w; + float gearW = 22, filtW = 22, winW = 22, right = start.X + w; if (IconButton("##chat_gear", PhosphorIcons.Gear, new Vector2(right - gearW, start.Y), new Vector2(gearW, h), Text, BtnFill)) _openSettings = true; ImGuiNET.ImGui.SetItemTooltip("Chat settings"); if (IconButton("##chat_filters", PhosphorIcons.Funnel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill)) PanelRouter.Toggle("ChatFilters"); ImGuiNET.ImGui.SetItemTooltip("Filters: move, copy or hide lines by regex, and colour them"); + float winX = right - gearW - filtW - 6 - winW; + _view.DrawNewWindowButton("##chat_newwin_btn", new Vector2(winX, start.Y), new Vector2(winW, h)); + return winX; + } + + /// + /// One row: the channel button (current tab, unread elsewhere; it opens the channels + /// drawer, or a list when popped out), search, New chat window, Filters and the gear. + /// Returns the y below it. + /// + private float DrawHeader(Vector2 start, float w) + { + const float h = 22; + float buttonsX = DrawRightButtons(start, w, h); - // The channel button: icon, current tab, and the unread count of every other tab. - string current = ChatModel.CurrentTab(); - int others = 0; - bool mention = false; - foreach (var kv in _unread) - { - if (string.Equals(kv.Key, current, StringComparison.OrdinalIgnoreCase)) continue; - others += kv.Value.Count; - mention |= kv.Value.Mention && kv.Value.Count > 0; - } - string? badge = others > 0 ? (others > 99 ? "99+" : others.ToString()) : null; - float badgeW = badge != null ? BadgeWidth(badge) : 0; - string label = PhosphorIcons.ChatCircleText + " " + current; - float labelW = ImGuiNET.ImGui.CalcTextSize(label).X; - float caretW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.CaretDown).X; - float bw = MathF.Min(labelW + 16 + caretW + (badge != null ? badgeW + 4 : 0), w * 0.45f); bool drawerOpen = _drawers.IsOpen(_channels); - if (Button("##chat_channel", "", start, new Vector2(bw, h), Text, drawerOpen ? TabActive : BtnFill)) + if (_view.DrawTabButton("##chat_channel", start, w * 0.45f, h, drawerOpen)) { - if (ImGuiPopOuts.InPopOutFrame) _openTabsPopup = true; // no drawer beside a popped-out window + if (ImGuiPopOuts.InPopOutFrame) _view.OpenTabsPopup(); // no drawer beside a popped-out window else _drawers.Toggle(_channels); } - if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) - SafeImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); - float ty = start.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; - dl.PushClipRect(start, start + new Vector2(bw - caretW - 6 - (badge != null ? badgeW + 4 : 0), h), true); - dl.AddText(new Vector2(start.X + 6, ty), Text, label); - dl.PopClipRect(); - float bx = start.X + bw - caretW - 6; - if (badge != null) - { - bx -= badgeW + 4; - DrawBadge(dl, new Vector2(bx, start.Y + 4), badgeW, h - 8, badge, mention); - bx += badgeW + 4; - } - dl.AddText(new Vector2(start.X + bw - caretW - 5, ty), Mute, PhosphorIcons.CaretDown); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(ChatModel.CurrentTab()); // Search fills the rest. - float sx = start.X + bw + 4, sw = right - gearW - filtW - 7 - sx; - if (sw > 40) DrawSearch(new Vector2(sx, start.Y), sw); + float sx = start.X + _view.LastTabButtonWidth + 4, sw = buttonsX - 4 - sx; + if (sw > 40) _view.DrawSearch(new Vector2(sx, start.Y), sw); return start.Y + h + 4; } /// /// "Tabs across the top" (ChatModel.TabsAcross): every tab in a row that wraps left of - /// Filters and the gear, as before the drawer; right-click a tab to rename or delete it, - /// + adds one. Returns the y below the strip. + /// the buttons, as before the drawer; right-click a tab to rename, delete or open it in a + /// new window, + adds one. Returns the y below the strip. /// private float DrawTabStrip(Vector2 start, float w) { const float h = 20; var dl = ImGuiNET.ImGui.GetWindowDrawList(); - float gearW = 22, filtW = 22, right = start.X + w; - if (IconButton("##chat_gear", PhosphorIcons.Gear, new Vector2(right - gearW, start.Y), new Vector2(gearW, h), Text, BtnFill)) - _openSettings = true; - ImGuiNET.ImGui.SetItemTooltip("Chat settings"); - if (IconButton("##chat_filters", PhosphorIcons.Funnel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill)) - PanelRouter.Toggle("ChatFilters"); - ImGuiNET.ImGui.SetItemTooltip("Filters: move, copy or hide lines by regex, and colour them"); - - float stripRight = right - gearW - filtW - 8; + float stripRight = DrawRightButtons(start, w, h) - 5; float x = start.X, y = start.Y; string current = ChatModel.CurrentTab(); + var unreadAll = _view.Unread; foreach (string tab in ChatModel.AllTabs()) { bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); - _unread.TryGetValue(tab, out var unread); + unreadAll.TryGetValue(tab, out var unread); string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null; - float badgeW = badge != null ? BadgeWidth(badge) : 0; + float badgeW = badge != null ? ChatView.BadgeWidth(badge) : 0; float textW = ImGuiNET.ImGui.CalcTextSize(tab).X; float bw = textW + 12 + (badge != null ? badgeW + 3 : 0); if (x > start.X && x + bw > stripRight) { x = start.X; y += h + 2; } @@ -306,103 +213,62 @@ internal sealed class ChatFace : IImGuiPanel var p = new Vector2(x, y); if (Button("##tab", "", p, new Vector2(bw, h), Text, active ? TabActive : BtnFill)) ChatModel.SelectTab(tab); - if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _ctxTab = tab; _openTabMenu = true; } + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab); if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); - else if (!ChatModel.IsBaseTab(tab)) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab"); + else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab) + ? "Right-click: open in a new window" + : "Right-click to rename, delete or open this tab in a new window"); dl.AddText(new Vector2(x + 6, y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, tab); - if (badge != null) DrawBadge(dl, new Vector2(x + 6 + textW + 3, y + 4), badgeW, h - 8, badge, unread.Mention); + if (badge != null) ChatView.DrawBadge(dl, new Vector2(x + 6 + textW + 3, y + 4), badgeW, h - 8, badge, unread.Mention); ImGuiNET.ImGui.PopID(); x += bw + 2; } if (x > start.X && x + 18 > stripRight) { x = start.X; y += h + 2; } - if (IconButton("##chat_addtab", PhosphorIcons.Plus, new Vector2(x, y), new Vector2(18, h), TabAdd, BtnFill, font: UiFont.Ui11)) - { - _pendingRule = null; - WriteUtf8(_newTab, ""); - _openNewTab = _focusNewTab = true; - } + if (IconButton("##chat_addtab", PhosphorIcons.Plus, new Vector2(x, y), new Vector2(18, h), ChatView.TabAdd, BtnFill, font: UiFont.Ui11)) + _view.OpenNewTab(); ImGuiNET.ImGui.SetItemTooltip("New tab (fill it with a rule: right-click a line, or Filters)"); return y + h + 4; } - private static float BadgeWidth(string badge) - { - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - float w = ImGuiNET.ImGui.CalcTextSize(badge).X + 8; - ImGuiNET.ImGui.PopFont(); - return w; - } - - private static void DrawBadge(ImDrawListPtr dl, Vector2 p, float w, float h, string badge, bool mention) - { - dl.AddRectFilled(p, p + new Vector2(w, h), mention ? BadgeMention : BadgeBg, h * 0.5f); - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - dl.AddText(p + new Vector2(4, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge); - ImGuiNET.ImGui.PopFont(); - } - /// /// The channel rows (the drawer's panel; the popped-out list draws its own): each tab with - /// its unread count, the current one highlighted; click picks it, right-click renames or - /// deletes a created tab; "+ New tab" at the end. + /// its unread count, the current one highlighted; click picks it, right-click its menu + /// (open in a new window; rename or delete a created tab); "+ New tab" at the end. /// private void DrawChannelRows(Vector2 start, float w, float rowH) { var dl = ImGuiNET.ImGui.GetWindowDrawList(); string current = ChatModel.CurrentTab(); + var unreadAll = _view.Unread; float y = start.Y; foreach (string tab in ChatModel.AllTabs()) { bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); - _unread.TryGetValue(tab, out var unread); + unreadAll.TryGetValue(tab, out var unread); string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null; ImGuiNET.ImGui.PushID(tab); var p = new Vector2(start.X, y); if (Button("##row", "", p, new Vector2(w, rowH), Text, active ? TabActive : BtnFill)) ChatModel.SelectTab(tab); - if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _ctxTab = tab; _openTabMenu = true; } + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab); if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); - else if (!ChatModel.IsBaseTab(tab)) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab"); - float badgeW = badge != null ? BadgeWidth(badge) : 0; + else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab) + ? "Right-click: open in a new window" + : "Right-click to rename, delete or open this tab in a new window"); + float badgeW = badge != null ? ChatView.BadgeWidth(badge) : 0; float ty = y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; dl.PushClipRect(p, p + new Vector2(w - (badge != null ? badgeW + 8 : 0), rowH), true); dl.AddText(new Vector2(p.X + 6, ty), active ? Teal : Text, tab); dl.PopClipRect(); - if (badge != null) DrawBadge(dl, new Vector2(p.X + w - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention); + if (badge != null) ChatView.DrawBadge(dl, new Vector2(p.X + w - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention); ImGuiNET.ImGui.PopID(); y += rowH + 2; } - if (Button("##chat_addtab", PhosphorIcons.Plus + " New tab", new Vector2(start.X, y), new Vector2(w, rowH), TabAdd, BtnFill)) - { - _pendingRule = null; - WriteUtf8(_newTab, ""); - _openNewTab = _focusNewTab = true; - } + if (Button("##chat_addtab", PhosphorIcons.Plus + " New tab", new Vector2(start.X, y), new Vector2(w, rowH), ChatView.TabAdd, BtnFill)) + _view.OpenNewTab(); ImGuiNET.ImGui.SetItemTooltip("New tab (fill it with a rule: right-click a line, or Filters)"); } - /// Popped out (no drawer beside the window): the channels as a list under the button. - private void DrawTabsPopup() - { - if (!ImGuiNET.ImGui.BeginPopup("##chat_tabs")) return; - string current = ChatModel.CurrentTab(); - foreach (string tab in ChatModel.AllTabs()) - { - _unread.TryGetValue(tab, out var unread); - bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); - string label = !active && unread.Count > 0 ? $"{tab} ({unread.Count})" : tab; - if (ImGuiNET.ImGui.Selectable(label + "##tabsel_" + tab, active)) ChatModel.SelectTab(tab); - } - ImGuiNET.ImGui.Separator(); - if (ImGuiNET.ImGui.Selectable(PhosphorIcons.Plus + " New tab")) - { - _pendingRule = null; - WriteUtf8(_newTab, ""); - _openNewTab = _focusNewTab = true; - } - ImGuiNET.ImGui.EndPopup(); - } - /// The channels drawer on the chat window's left edge (DashboardDrawers' mechanics). private sealed class ChannelsDrawer : DashboardDrawer { @@ -432,598 +298,6 @@ internal sealed class ChatFace : IImGuiPanel } } - /// - /// Unread counts per tab: lines shown there that arrived after it was last on - /// screen. Recounted only when the lines, the routes or the tabs change. - /// - private void UpdateUnread(ChatLine[] lines, long linesVersion, string current) - { - long newest = lines.Length > 0 ? lines[^1].Id : 0; - _seenId[current] = newest; - long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion; - bool recount = routes != _unreadRoutes || tabsVersion != _unreadTabsVersion - || !string.Equals(current, _unreadTab, StringComparison.Ordinal); - if (!recount && linesVersion == _unreadLines) return; - _unreadLines = linesVersion; - _unreadRoutes = routes; - _unreadTabsVersion = tabsVersion; - _unreadTab = current; - // Only new lines arrived: count just those (lines past _unreadCountedTo). A full recount - // walks every unread line of every tab - up to the whole history per tab (3.7 ms at - // 10,000 lines, tools/ChatHistoryBench), which used to run on every new batch. - if (recount) _unread.Clear(); - foreach (string tab in ChatModel.AllTabs()) - { - if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read - long from = recount ? seen : Math.Max(seen, _unreadCountedTo); - int count = 0; - bool mention = false; - for (int i = lines.Length - 1; i >= 0 && lines[i].Id > from; i--) - if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; } - if (count == 0) continue; - _unread.TryGetValue(tab, out var had); - _unread[tab] = (had.Count + count, had.Mention || mention); - } - _unreadCountedTo = newest; - } - - private void DrawSearch(Vector2 p, float w) - { - bool hasText = _search[0] != 0; - TextBox("##chat_search", _search, p, hasText ? w - 24 : w, SearchHint, out _); - if (hasText) - { - if (IconButton("##chat_search_x", PhosphorIcons.X, new Vector2(p.X + w - 22, p.Y), new Vector2(22, 22), Mute, BtnFill, font: UiFont.Ui10)) - WriteUtf8(_search, ""); - ImGuiNET.ImGui.SetItemTooltip("Clear the search"); - } - } - - // ── Lines ──────────────────────────────────────────────────────────── - - /// Brings _vis up to date with the snapshot, tab, search and routes. - private void SyncLines(UiSnapshot? snap, ChatLine[] lines, string tab) - { - string search = Utf8(_search); - long routes = ChatModel.RoutesVersion; - - if (routes != _seenRoutes || tab != _seenTab || search != _seenSearch) - { - _seenRoutes = routes; - _seenTab = tab; - _seenSearch = search; - _seenLinesVersion = snap?.Version ?? -1; - _vis.Clear(); - _h.Clear(); - _lay.Clear(); - foreach (ChatLine line in lines) - if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(_rowH); _lay.Add(null); } - _lastId = lines.Length > 0 ? lines[^1].Id : _lastId; - _heightsFrom = _measuredFrom = _vis.Count; // all unmeasured: MeasureLines, newest first - _topsDirty = true; - ClearSelection(); - _stick = true; // a rebuild re-pins to the newest line - _droppedAbove = 0f; - return; - } - if (snap == null || snap.Version == _seenLinesVersion) return; - _seenLinesVersion = snap.Version; - - // Drop lines the source no longer keeps, then add the new ones. - long oldest = lines.Length > 0 ? lines[0].Id : long.MaxValue; - int drop = 0; - while (drop < _vis.Count && _vis[drop].Id < oldest) drop++; - if (drop > 0 && !_selDragging) - { - if (!Following) - for (int i = 0; i < drop; i++) _droppedAbove += _h[i]; - _vis.RemoveRange(0, drop); - _h.RemoveRange(0, drop); - _lay.RemoveRange(0, drop); - _heightsFrom = Math.Max(0, _heightsFrom - drop); - _measuredFrom = Math.Max(0, _measuredFrom - drop); - if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); } - _topsDirty = true; - } - foreach (ChatLine line in lines) - { - if (line.Id <= _lastId) continue; - _lastId = line.Id; - if (!ChatModel.LineVisible(line, tab, search)) continue; - if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count; - _vis.Add(line); - _h.Add(_rowH); - _lay.Add(null); - _topsDirty = true; - } - } - - /// The view follows the newest line (auto-scroll on and not scrolled away). - private bool Following => ChatModel.AutoScroll && _stick; - - private void DrawLines(Vector2 size) - { - float fontSize = ChatModel.FontSize; - ImFontPtr font = ImGuiFonts.Chat(fontSize); - ImGuiNET.ImGui.PushFont(font); - bool showTs = ChatModel.ShowTimestamps; - - // The lines are measured BEFORE the list's BeginChild, so this frame's scroll can be - // set for this frame's lines (see "Where the view goes" below). The width they wrap - // to is the child's: its width less its scrollbar (always shown) and a margin; - // _wrapFix corrects that guess if the child ever reports otherwise. - float wrapW = Math.Max(20, MathF.Floor(size.X) - ListScrollbarW - 6 + _wrapFix); - float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0; - MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y)); - float total = _tops[_vis.Count]; - - // Where the view goes this frame. (2026-10-11, the chat "bouncing": until now the - // view followed the newest line with SetScrollHereY at the end of the frame, which - // only lands in the NEXT frame's Begin. So every batch of new lines was first drawn - // at the old scroll: with the buffer full, lines leave the top as others arrive, - // and the text jumped by the difference - up and back down when a long line left - // and a short one came - then snapped into place a frame later. A popped-out chat - // redraws at 5 Hz while idle, so the wrong frame stayed up for 200 ms.) Now the - // content height and the scroll are both handed to this frame's BeginChild: - // • the content size, so ImGui's scroll limit is this frame's and not last frame's - // (it clamps any scroll set before Begin to the limit it knows); - // • following: the bottom (the limit clamps 'total' to exactly the bottom); - // • not following: only the lines dropped off a full buffer's top, so what is - // being read stays put (fractions carried, so rounding can't creep the view). - // A frame with wheel input over the list leaves the scroll to the wheel (this would - // override it); a drag-select scrolls the list itself. - Vector2 listPos = ImGuiNET.ImGui.GetCursorScreenPos(); - bool wheelHere = ImGuiNET.ImGui.GetIO().MouseWheel != 0f - && ImGuiNET.ImGui.IsMouseHoveringRect(listPos, listPos + size, false); - ImGuiNET.ImGui.SetNextWindowContentSize(new Vector2(0f, total)); - bool compensated = false; - if (Following) - { - _droppedAbove = 0f; - _scrollCarry = 0f; - // Not counted as "our move": a scrollbar drag in this Begin overrides it, and the - // check below must see that to stop following. - if (!wheelHere && !_selDragging) - ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, total)); - } - else if (_droppedAbove != 0f && !wheelHere) - { - float target = _lastScrollY + _scrollCarry - _droppedAbove; - float applied = MathF.Round(Math.Max(0f, target)); // ImGui rounds scroll to whole pixels - _scrollCarry = target > 0f ? target - applied : 0f; - ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, applied)); - _droppedAbove = 0f; - compensated = true; - } - - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0)); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, ListScrollbarW); - bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar); - ImGuiNET.ImGui.PopStyleVar(2); - ImGuiNET.ImGui.PopStyleColor(2); - if (!open) { ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopFont(); return; } - - // The child's real width, should the guess above ever be off (a style change): - // measured again now, and the guess corrected from the next frame on. - float realWrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6); - if (Math.Abs(realWrapW - wrapW) > 0.5f) - { - _wrapFix += realWrapW - wrapW; - wrapW = realWrapW; - MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y)); - total = _tops[_vis.Count]; - } - float textW = Math.Max(20, wrapW - tsW); - int n = _vis.Count; - - // Following the tail until the user scrolls away from it. - float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY(); - if (compensated) _lastScrollY = scrollY; // our move, not the user's - else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) _scrollCarry = 0f; // the user's: start afresh - // Wheel up over the chat stops following at once; reaching the bottom again resumes it. - // Not while it has nothing to scroll: no scroll change would ever turn following back on. - if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f) - _stick = false; - else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) - _stick = scrollY >= maxY - StickThreshold; - - Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos(); - float viewH = ImGuiNET.ImGui.GetWindowHeight(); - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - int first = FirstAtOrBelow(scrollY, n); - int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); - for (int i = first; i < n && _tops[i] < scrollY + viewH; i++) - { - Vector2 p = basePos + new Vector2(0, _tops[i]); - ChatLine line = _vis[i]; - ChatRoute route = line.Route; - // A "Highlight line" rule: a band behind all of the line's rows, under the mention - // tint and the selection. One rect, no allocation; _h[i] already spans every row. - if (route.HighlightArgb is uint band) - dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), RynthTheme.Argb(ChatColorModes.BandArgb(band))); - if (route.Mention) - dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg); - if (lo >= 0 && i >= lo && i <= hi) - dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg); - uint col = RynthTheme.Argb(ChatModel.LineArgb(line)); - if (showTs) dl.AddText(font, font.FontSize, p + new Vector2(3, 0), TsColor, line.Timestamp); - Vector2 tp = p + new Vector2(3 + tsW, 0); - SpanLayout? lay = _lay[i]; - if (lay == null) - dl.AddText(font, font.FontSize, tp, col, line.Text, textW); - else - foreach (Seg seg in lay.Segs) - { - dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text); - if (seg.Link >= 0) // a map coordinate: underlined, it's clickable - { - Vector2 u = tp + seg.Offset + new Vector2(0, font.FontSize - 1); - dl.AddLine(u, u + new Vector2(seg.W, 0), RynthTheme.Argb(LinkCol), 1f); - } - } - } - ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total))); - HoverLink(basePos, tsW, n, out ChatCoord? hoveredLink); - HandleSelection(basePos, wrapW, scrollY, viewH, n, hoveredLink); - HandleLineMenu(basePos, wrapW, n); - - _lastScrollY = scrollY; - - // "Copied N lines" / "Rule added", top-right, for a moment. - if (_flash != null) - { - if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null; - else - { - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_flash); - Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); - Vector2 fp = new(Math.Max(wp.X + 2, wp.X + wrapW - ts.X - 12), wp.Y + 4); - dl.AddRectFilled(fp, fp + ts + new Vector2(12, 4), FlashBg, 3); - dl.AddText(fp + new Vector2(6, 2), Text, _flash); - ImGuiNET.ImGui.PopFont(); - } - } - - ImGuiNET.ImGui.EndChild(); - ImGuiNET.ImGui.PopFont(); // pushed before the child, for MeasureLines - } - - /// Time MeasureLines may spend a frame catching up on lines measured for another width. - private const double MeasureBudgetMs = 2.0; - private static readonly long MeasureBudgetTicks = (long)(System.Diagnostics.Stopwatch.Frequency * MeasureBudgetMs / 1000); - - /// - /// Brings the line heights and tops up to date for this wrap width, font and timestamp - /// setting. Chat font pushed. New lines are measured at once. When the width, font or - /// timestamps change (or after a rebuild) every line needs measuring again: 16 ms at - /// 10,000 lines (tools/ChatHistoryBench), every frame of a resize drag. So that is done - /// a slice at a time: the lines in view first, then from the newest line up, for - /// MeasureBudgetMs a frame; the others keep their old height meanwhile. Scrolled up, - /// the view is moved by however much the lines above it grew or shrank, so what's being - /// read stays put (the same way as lines dropping off the top). - /// - private void MeasureLines(ImFontPtr font, float wrapW, float tsW, float fontSize, bool showTs, float viewH) - { - // The text starts after the timestamp and wraps under itself. - float textW = Math.Max(20, wrapW - tsW); - _rowH = font.FontSize; - if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs) - { - _seenWrap = wrapW; - _seenFont = fontSize; - _seenTs = showTs; - _measuredFrom = Math.Min(_heightsFrom, _vis.Count); // all measured so far is stale - } - bool changed = false; - for (int i = _heightsFrom; i < _vis.Count; i++) { MeasureLine(font, i, textW); changed = true; } - _heightsFrom = _vis.Count; - - if (_measuredFrom > 0) - { - UpdateTops(); - int n = _vis.Count; - bool following = Following; - // Where the view will be (last frame's scroll, less any move still to come). - float viewTop = _lastScrollY + _scrollCarry - _droppedAbove; - int firstVisible = following || n == 0 ? int.MaxValue : FirstAtOrBelow(Math.Max(0f, viewTop), n); - if (!following) - for (int i = firstVisible; i < Math.Min(n, _measuredFrom) && _tops[i] < viewTop + viewH; i++) - MeasureLine(font, i, textW); - float grewAbove = 0f; - long t0 = System.Diagnostics.Stopwatch.GetTimestamp(); - int count = 0; - while (_measuredFrom > 0) - { - int i = --_measuredFrom; - float old = _h[i]; - MeasureLine(font, i, textW); - if (i < firstVisible) grewAbove += _h[i] - old; - if ((++count & 15) == 0 && System.Diagnostics.Stopwatch.GetTimestamp() - t0 > MeasureBudgetTicks) break; - } - if (!following) _droppedAbove -= grewAbove; - changed = true; - } - if (changed) _topsDirty = true; - UpdateTops(); - } - - private void MeasureLine(ImFontPtr font, int i, float textW) - { - ChatLine line = _vis[i]; - ChatSpan[]? spans = line.Route.Spans; - // Map coordinates ("82.3N, 34.2E") become links. Found here, when the line is measured, - // never per frame; a line without any keeps the plain (or highlighted) path. - List coords = ChatCoords.MayHaveCoords(line.Text) ? ChatCoords.Find(line.Text) : NoCoords; - if (coords.Count > 0) - { - ChatSpan[] withLinks = ChatCoords.LinkSpans(spans, coords, LinkCol); - SpanLayout lay = LayoutSpans(font, line.Text, withLinks, textW, coords); - _lay[i] = lay; - _h[i] = lay.Height; - } - else if (spans != null) - { - SpanLayout lay = LayoutSpans(font, line.Text, spans, textW); - _lay[i] = lay; - _h[i] = lay.Height; - } - else - { - _lay[i] = null; - _h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y; - } - } - - private void UpdateTops() - { - if (!_topsDirty && _tops.Length > _vis.Count) return; - if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)]; - _tops[0] = 0; - for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i]; - _topsDirty = false; - } - - private void Flash(string message, double seconds = 2.0) - { - _flash = message; - _flashUntil = ImGuiNET.ImGui.GetTime() + seconds; - } - - // ── Highlighted lines: hand layout ─────────────────────────────────── - - // Argb 0 = the line's colour. W: the run's width. Link: index into SpanLayout.Links (a map - // coordinate drawn as a link: click = RynthNav arrow, Ctrl+click = go), -1 for plain text. - private readonly record struct Seg(string Text, Vector2 Offset, uint Argb, float W = 0f, int Link = -1); - - private sealed class SpanLayout - { - public required float Height; - public required Seg[] Segs; - /// The line's map coordinates (ChatCoords), when any are drawn as links. - public ChatCoord[]? Links; - } - - /// Coordinate links in chat lines: soft teal, underlined (0xAARRGGBB, like ChatSpan.Argb). - private const uint LinkCol = 0xFF5ECFE0; - - private static readonly List NoCoords = new(); - - /// - /// Word-wraps to and cuts each - /// row where a highlight starts or ends, so every run is drawn in its own - /// colour. Called when a line is measured, never per frame. - /// : the line's map coordinates, whose runs get a link index. - /// - private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW, List? links = null) - { - // Which coordinate link a run [s0, s1) belongs to (-1 none). - int LinkOf(int s0, int s1) - { - if (links == null) return -1; - for (int k = 0; k < links.Count; k++) - if (s0 >= links[k].Start && s1 <= links[k].Start + links[k].Length) return k; - return -1; - } - - float size = font.FontSize; - float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X; - - // Rows as [start, end) character ranges. - var rows = new List<(int Start, int End)>(); - int rowStart = 0; - float x = 0; - int i = 0; - while (i < text.Length) - { - if (text[i] == '\n') { rows.Add((rowStart, i)); rowStart = i + 1; x = 0; i++; continue; } - // A word and the spaces after it. - int j = i; - while (j < text.Length && text[j] != ' ' && text[j] != '\n') j++; - while (j < text.Length && text[j] == ' ') j++; - float ww = Width(i, j); - int wordEnd = j; - while (wordEnd > i && text[wordEnd - 1] == ' ') wordEnd--; - float inkW = Width(i, wordEnd); - if (x > 0 && x + inkW > wrapW) - { - rows.Add((rowStart, i)); - rowStart = i; - x = 0; - } - if (x == 0 && inkW > wrapW) - { - // A word wider than the row: break it by characters. - int k = i; - while (k < wordEnd) - { - int m = k + 1; - while (m < wordEnd && Width(k, m + 1) <= wrapW) m++; - if (m < wordEnd) { rows.Add((rowStart, m)); rowStart = m; } - else x = Width(k, j); - k = m; - } - i = j; - continue; - } - x += ww; - i = j; - } - rows.Add((rowStart, text.Length)); - - var segs = new List(); - for (int r = 0; r < rows.Count; r++) - { - (int a, int b) = rows[r]; - float y = r * size, sx = 0; - int c = a; - foreach (ChatSpan span in spans) - { - int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b); - if (s1 <= s0) continue; - if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); } - float spanW = Width(s0, s1); - segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb, spanW, LinkOf(s0, s1))); - sx += spanW; - c = s1; - } - if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0)); - } - return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray(), Links = links?.ToArray() }; - } - - /// Index of the line containing content y (clamped to the list). - private int FirstAtOrBelow(float y, int n) - { - int lo = 0, hi = n; // first i with _tops[i + 1] > y - while (lo < hi) - { - int mid = (lo + hi) >> 1; - if (_tops[mid + 1] > y) hi = mid; else lo = mid + 1; - } - return Math.Min(lo, Math.Max(0, n - 1)); - } - - /// - /// The map coordinate link under the mouse, if any (hand cursor and a tooltip). Only the - /// hovered line's runs are looked at. - /// - private void HoverLink(Vector2 basePos, float tsW, int n, out ChatCoord? link) - { - link = null; - if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsWindowHovered()) return; - Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); - float contentY = mouse.Y - basePos.Y; - if (contentY < 0 || contentY >= _tops[n]) return; - int i = FirstAtOrBelow(contentY, n); - if (_lay[i] is not { Links: { Length: > 0 } links } lay) return; - Vector2 tp = basePos + new Vector2(3 + tsW, _tops[i]); - float h = ImGuiNET.ImGui.GetFontSize(); - foreach (Seg seg in lay.Segs) - { - if (seg.Link < 0 || seg.Link >= links.Length) continue; - Vector2 a = tp + seg.Offset, b = a + new Vector2(seg.W, h); - if (mouse.X < a.X || mouse.X >= b.X || mouse.Y < a.Y || mouse.Y >= b.Y) continue; - link = links[seg.Link]; - ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - bool nav = ImGuiPanelHost.HasFace(RynthNavFace.Title); - SafeImGui.SetTooltip(nav - ? $"Click: point the arrow at {link.Value.Text}\nCtrl+click: RynthNav walks there\nRight-click: more" - : $"{link.Value.Text}\n(RynthNav isn't loaded: no arrow)"); - return; - } - } - - /// A click on a coordinate link: RynthNav's arrow there, or (Ctrl) walk there. - private void ClickLink(ChatCoord c) - { - if (!ImGuiPanelHost.HasFace(RynthNavFace.Title)) { Flash("RynthNav isn't loaded", 1.5); return; } - if (ImGuiNET.ImGui.GetIO().KeyCtrl) - { - RynthNavCommands.Go(c.Text, c.Ns, c.Ew); - Flash("Going to " + c.Text, 1.5); - } - else - { - RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew); - Flash("Arrow: " + c.Text, 1.5); - } - } - - private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n, ChatCoord? hoveredLink = null) - { - if (n == 0) { ClearSelection(); return; } - Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); - float contentY = mouse.Y - basePos.Y; - if (!_selDragging) - { - if (!ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) - || !ImGuiNET.ImGui.IsWindowHovered() - || mouse.X > basePos.X + wrapW + 6) // the scrollbar - return; - ClearSelection(); - if (contentY < 0 || contentY >= _tops[n]) return; - _selAnchor = _selEnd = FirstAtOrBelow(contentY, n); - _selDragging = true; - _selMoved = false; - _selDown = mouse; - _downLink = hoveredLink; // a click (no drag) on it acts on release - return; - } - - if (Math.Abs(mouse.X - _selDown.X) > 3 || Math.Abs(mouse.Y - _selDown.Y) > 3) _selMoved = true; - _selEnd = FirstAtOrBelow(Math.Clamp(contentY, 0, _tops[n] - 1), n); - - // Dragging past the edges scrolls. - Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); - if (mouse.Y < wp.Y) ImGuiNET.ImGui.SetScrollY(Math.Max(0, scrollY - 12)); - else if (mouse.Y > wp.Y + viewH) ImGuiNET.ImGui.SetScrollY(scrollY + 12); - - if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return; - _selDragging = false; - // A drag (even within one line) copies; a plain click just clears, or follows a - // coordinate link it was pressed on. - if (!_selMoved && _selEnd == _selAnchor) - { - ChatCoord? link = _downLink; - ClearSelection(); - if (link is { } c) ClickLink(c); - return; - } - int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); - var parts = new List(hi - lo + 1); - for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i])); - Flash(ChatModel.CopyLines(parts), 1.5); - } - - private static string CopyText(ChatLine line) => ChatModel.ShowTimestamps ? line.FormattedText : line.Text; - - /// Right-click on a line: its menu (drawn in DrawPopups). - private void HandleLineMenu(Vector2 basePos, float wrapW, int n) - { - if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right) || !ImGuiNET.ImGui.IsWindowHovered()) - return; - Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); - float contentY = mouse.Y - basePos.Y; - if (mouse.X > basePos.X + wrapW + 6 || contentY < 0 || contentY >= _tops[n]) return; - _ctxLine = _vis[FirstAtOrBelow(contentY, n)]; - _ctxPattern = ChatModel.PatternFor(_ctxLine); - _ctxCoords = ImGuiPanelHost.HasFace(RynthNavFace.Title) ? ChatCoords.Find(_ctxLine.Text) : new List(); - _openLineMenu = true; - } - - private void ClearSelection() - { - _selAnchor = _selEnd = -1; - _selDragging = _selMoved = false; - _downLink = null; - } - - /// The coordinate link the left button went down on (acted on if it comes up without a drag). - private ChatCoord? _downLink; - // ── Input ──────────────────────────────────────────────────────────── private void DrawInput(Vector2 p, float w, float h) @@ -1068,45 +342,6 @@ internal sealed class ChatFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("Select an NPC or player in the game, then click to start /tell , — or type /tell and press Enter."); } - // ── Rules from a line ──────────────────────────────────────────────── - - private void RuleFromLine(ChatRuleAction action, string? tab, ChatColorMode colour = ChatColorMode.Line) - { - var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" }; - if (action == ChatRuleAction.Color) - { - rule.ColorMode = colour; - ChatModel.AddRule(rule); - if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters"); - Flash(colour == ChatColorMode.Highlight - ? "Rule added: lines like this are highlighted - pick its colour in Filters" - : "Rule added - pick its colour in Filters"); - return; - } - ChatModel.AddRule(rule); - Flash(action switch - { - ChatRuleAction.Move => $"Rule added: lines like this move to {tab}", - ChatRuleAction.Copy => $"Rule added: lines like this also show in {tab}", - _ => "Rule added: lines like this are hidden (undo in Filters)", - }, 3); - } - - private void TabMenu(string id, ChatRuleAction action) - { - if (!ImGuiNET.ImGui.BeginMenu(id)) return; - foreach (string t in ChatModel.TargetTabs()) - if (ImGuiNET.ImGui.MenuItem(t)) RuleFromLine(action, t); - ImGuiNET.ImGui.Separator(); - if (ImGuiNET.ImGui.MenuItem("New tab…")) - { - _pendingRule = new ChatFilterRule { Pattern = _ctxPattern, Action = action }; - WriteUtf8(_newTab, ""); - _openNewTab = _focusNewTab = true; - } - ImGuiNET.ImGui.EndMenu(); - } - // ── Popups ─────────────────────────────────────────────────────────── private void DrawPopups() @@ -1114,7 +349,7 @@ internal sealed class ChatFace : IImGuiPanel if (ToggleChannelsRequested) { ToggleChannelsRequested = false; - if (ImGuiPopOuts.InPopOutFrame) _openTabsPopup = true; + if (ImGuiPopOuts.InPopOutFrame) _view.OpenTabsPopup(); else _drawers.Toggle(_channels); } if (_openSettings) @@ -1123,31 +358,11 @@ internal sealed class ChatFace : IImGuiPanel WriteUtf8(_mentionWords, ChatModel.MentionWords); ImGuiNET.ImGui.OpenPopup("##chat_settings"); } - if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chat_newtab"); } - if (_openTabMenu) { _openTabMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_tabmenu"); } - if (_openLineMenu) { _openLineMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_linemenu"); } - if (_openRename) { _openRename = false; ImGuiNET.ImGui.OpenPopup("##chat_rename"); } - if (_openTabsPopup) { _openTabsPopup = false; ImGuiNET.ImGui.OpenPopup("##chat_tabs"); } - - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Argb(0xF2060C14)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, TabActive); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, TabActive); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + ChatView.PushPopupStyle(); DrawSettingsPopup(); - DrawTabsPopup(); - DrawNewTabPopup(); - DrawTabMenu(); - DrawRenamePopup(); - DrawLineMenu(); - - ImGuiNET.ImGui.PopStyleVar(); - ImGuiNET.ImGui.PopStyleColor(8); + _view.DrawPopups(); + ChatView.PopPopupStyle(); } private void DrawSettingsPopup() @@ -1198,7 +413,7 @@ internal sealed class ChatFace : IImGuiPanel if (ImGuiNET.ImGui.Checkbox("Auto-scroll", ref auto)) { ChatModel.AutoScroll = auto; - if (auto) _stick = true; + if (auto) _view.Restick(); ChatModel.SaveSettings(); } bool hide = ChatHooks.SuppressOriginalChat; @@ -1370,133 +585,4 @@ internal sealed class ChatFace : IImGuiPanel "keywords, how often, and the send log."); Label(UI.Data.Discord.ChatDiscord.SwitchLine() + " " + UI.Data.Discord.ChatDiscord.StatusLine(), Mute); } - - private void DrawNewTabPopup() - { - if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab")) - { - _pendingRule = null; - return; - } - if (_pendingRule != null) - Label(_pendingRule.Action == ChatRuleAction.Copy ? "New tab for a copy of lines like this:" : "New tab for lines like this:", Mute); - if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - bool enter = TextBox("##newtab_name", _newTab, p, 120, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); - bool add = Button("##newtab_add", "Add", new Vector2(p.X + 124, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, TabActive); - bool cancel = Button("##newtab_cancel", "Cancel", new Vector2(p.X + 128 + ButtonWidth("Add"), p.Y), new Vector2(ButtonWidth("Cancel"), 20), Text, BtnFill); - NextLine(p, 20); - if (enter || add) - { - ChatFilterRule? pending = _pendingRule; - string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: pending == null); - if (name != null && pending != null) - { - pending.Tab = name; - ChatModel.AddRule(pending); - Flash(pending.Action == ChatRuleAction.Copy - ? $"Rule added: lines like this also show in {name}" - : $"Rule added: lines like this move to {name}", 3); - } - _pendingRule = null; - ImGuiNET.ImGui.CloseCurrentPopup(); - } - else if (cancel || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) - { - _pendingRule = null; - ImGuiNET.ImGui.CloseCurrentPopup(); - } - ImGuiNET.ImGui.EndPopup(); - } - - private void DrawTabMenu() - { - if (!ImGuiNET.ImGui.BeginPopup("##chat_tabmenu")) return; - string tab = _ctxTab ?? ""; - Label(tab, Teal); - ImGuiNET.ImGui.Separator(); - if (ImGuiNET.ImGui.MenuItem("Mark as read")) - { - var lines = UiSources.Chat.Current?.Value; - _seenId[tab] = lines is { Length: > 0 } ? lines[^1].Id : 0; - _unread.Remove(tab); - } - if (ImGuiNET.ImGui.MenuItem("Mark all tabs read")) - { - var lines = UiSources.Chat.Current?.Value; - long newest = lines is { Length: > 0 } ? lines[^1].Id : 0; - foreach (string t in ChatModel.AllTabs()) _seenId[t] = newest; - _unread.Clear(); - } - if (!ChatModel.IsBaseTab(tab)) - { - if (ImGuiNET.ImGui.MenuItem("Rename…")) - { - _renameFrom = tab; - WriteUtf8(_newTab, tab); - _openRename = _focusNewTab = true; - } - if (ImGuiNET.ImGui.MenuItem("Delete tab")) ChatModel.DeleteCustomTab(tab); - } - if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) - PanelRouter.Toggle("ChatFilters"); - ImGuiNET.ImGui.EndPopup(); - } - - private void DrawRenamePopup() - { - if (!ImGuiNET.ImGui.BeginPopup("##chat_rename")) return; - Label($"Rename \"{_renameFrom}\" (its rules follow):", Mute); - if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - bool enter = TextBox("##rename_name", _newTab, p, 140, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); - bool ok = Button("##rename_ok", "Rename", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Rename"), 20), Text, TabActive); - NextLine(p, 20); - if (enter || ok) - { - if (_renameFrom != null && !ChatModel.RenameCustomTab(_renameFrom, Utf8(_newTab))) - Flash("That name is taken (or blank)"); - ImGuiNET.ImGui.CloseCurrentPopup(); - } - else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) - ImGuiNET.ImGui.CloseCurrentPopup(); - ImGuiNET.ImGui.EndPopup(); - } - - private void DrawLineMenu() - { - ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(200, 0), new Vector2(420, float.MaxValue)); - if (!ImGuiNET.ImGui.BeginPopup("##chat_linemenu")) return; - ChatLine? line = _ctxLine; - if (line == null) { ImGuiNET.ImGui.EndPopup(); return; } - // Coordinates in the line: point RynthNav's arrow there, or walk there (left-click - // selects lines, so this lives in the right-click menu). - for (int i = 0; i < _ctxCoords.Count && i < 3; i++) - { - ChatCoord c = _ctxCoords[i]; - ImGuiNET.ImGui.PushID(i); - if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.NavigationArrow + " Arrow to " + c.Text)) - RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew); - if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Go to " + c.Text)) - RynthNavCommands.Go(c.Text, c.Ns, c.Ew); - ImGuiNET.ImGui.PopID(); - } - if (_ctxCoords.Count > 0) ImGuiNET.ImGui.Separator(); - if (ImGuiNET.ImGui.MenuItem("Copy line")) Flash(ChatModel.CopyLines(new[] { CopyText(line) }), 1.5); - ImGuiNET.ImGui.Separator(); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); - ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 400); - ImGuiNET.ImGui.TextUnformatted("Lines like this: " + _ctxPattern); - ImGuiNET.ImGui.PopTextWrapPos(); - ImGuiNET.ImGui.PopStyleColor(); - TabMenu("Move them to", ChatRuleAction.Move); - TabMenu("Also show them in", ChatRuleAction.Copy); - if (ImGuiNET.ImGui.MenuItem("Hide them")) RuleFromLine(ChatRuleAction.Hide, null); - if (ImGuiNET.ImGui.MenuItem("Colour them…")) RuleFromLine(ChatRuleAction.Color, null); - if (ImGuiNET.ImGui.MenuItem("Highlight them…")) RuleFromLine(ChatRuleAction.Color, null, ChatColorMode.Highlight); - ImGuiNET.ImGui.Separator(); - if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) - PanelRouter.Toggle("ChatFilters"); - ImGuiNET.ImGui.EndPopup(); - } } diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatView.cs b/src/RynthCore.Engine/ImGui/Panels/ChatView.cs new file mode 100644 index 0000000..651e67d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ChatView.cs @@ -0,0 +1,1125 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ChatView.cs +// One view of RynthChat's scrollback (2026-11-09, split out of ChatFace.cs +// for the extra chat windows): the main chat panel (ChatFace) has one, each +// extra window (ChatWindowFace, "Chat 2".."Chat 7") has its own. A view keeps +// what belongs to one window: its lines for its tab and search, their wrapped +// heights, the scroll (following the newest line until you scroll up), the +// drag selection, the unread counts per tab, the right-click menus (a line: +// copy, coordinates, make a rule; a tab: mark read, rename, delete, open in a +// new window) and the New tab / Rename popups. Which tab it shows is its +// owner's (Tab / SelectTab): the main chat's is ChatModel's current tab, an +// extra window's its own. +// +// Scrollback: wrapped lines, heights cached per wrap width and font; only +// the lines in view are drawn. The timestamp is dimmed and the text wraps +// under itself. Lines keep the colour and highlights the rules gave them +// (ChatLine.Route, worked out on the pump - no regex runs here); a line with +// highlights is laid out by hand (LayoutSpans) so each run can take its own +// colour. Drag across lines to copy them (the keyboard stays with the game, +// so copy is mouse-driven). Right-click a line to copy it or to make a rule +// from it: move / copy lines like it to a tab, hide them, colour or highlight +// them (a "Highlight line" rule: a band behind the whole line). A line +// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go +// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The +// coordinates are also drawn as underlined links: click points RynthNav's +// arrow there (its overlay opens), Ctrl+click walks there. +// Follows the newest line until you scroll up; the scroll for new lines is set +// in the same frame they're drawn (DrawLines; until 2026-10-11 it landed a frame +// late and the text bounced). Scrolled up, the view holds still. The history is +// as long as the "Chat history" setting (ChatHistory, up to 10,000 lines): no +// per-frame work walks all of it, and re-measuring after a resize is time-sliced. +// +// A tab on screen in any open view counts as read in the others (OnScreen): +// with Combat in its own window, the main chat doesn't count Combat unread. +// AC's thread only (every chat face draws there, docked or popped out). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ChatView +{ + private readonly Func _tabOf; + private readonly Action _selectTab; + private readonly string _viewKey; + /// The main chat's view (ChatModel's current tab), not an extra window's. + public bool IsMain { get; } + + /// The owner's panel key ("Chat", "Chat 2", ...): names this view in . + public ChatView(string viewKey, bool isMain, Func tab, Action selectTab) + { + _viewKey = viewKey; + IsMain = isMain; + _tabOf = tab; + _selectTab = selectTab; + } + + /// The tab this view shows. + public string Tab => _tabOf(); + + internal static readonly uint TabAdd = RynthTheme.Argb(0xFF7AE09A), + SelBg = RynthTheme.Argb(0x663A6EA5), + TsColor = RynthTheme.Argb(0xFF6F8397), MentionBg = RynthTheme.Argb(0x33FFC857), + BadgeBg = RynthTheme.Argb(0xFF1F6F7A), BadgeMention = RynthTheme.Argb(0xFFB8860B); + internal static uint TabActive => RynthTheme.AccentFill; + private static uint FlashBg => RynthTheme.WithAlpha(RynthTheme.AccentFill, 0xE0); + private const float StickThreshold = 24f; + + // ── Tabs on screen in any view (AC thread) ────────────────────────────── + + /// The tab each shown chat view shows, by its owner's key. + private static readonly Dictionary OnScreen = new(StringComparer.OrdinalIgnoreCase); + + /// True when is on screen in another chat view than this one. + private bool OnScreenElsewhere(string tab) + { + foreach (var kv in OnScreen) + if (!string.Equals(kv.Key, _viewKey, StringComparison.OrdinalIgnoreCase) + && string.Equals(kv.Value, tab, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + // Visible lines for the current tab + search, with wrapped heights; _lay + // holds the hand layout of lines with highlights (null for plain lines). + private readonly List _vis = new(512); + private readonly List _h = new(512); + private readonly List _lay = new(512); + private float[] _tops = new float[1]; + private int _heightsFrom; // first new line: not measured at all yet + // Lines below this index were measured for another width or font, or not at all (a + // rebuild gives them one row each until then): MeasureLines catches up a few ms a frame. + private int _measuredFrom; + private float _rowH = 13f; // one row of the chat font: an unmeasured line's height + private bool _topsDirty = true; + private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId; + private string _seenTab = "", _seenSearch = ""; + private float _seenWrap = -1, _seenFont = -1; + private bool _seenTs; + + private readonly byte[] _search = new byte[128], _newTab = new byte[64]; + private bool _stick = true; + private float _lastScrollY; + // Height of lines dropped off the top (the buffer is full) while not following the + // tail: the view is moved up by as much, so the lines being read stay put instead of + // sliding away. + private float _droppedAbove; + // The part of a dropped-lines move ImGui's whole-pixel scroll couldn't take, carried + // into the next one (heights can be fractional at some DPI scales). + private float _scrollCarry; + // The list's scrollbar width (always shown), and a correction to the list width + // DrawLines works out before its BeginChild, should the child ever report another. + private const float ListScrollbarW = 10f; + private float _wrapFix; + + // Selection: indices into _vis. + private int _selAnchor = -1, _selEnd = -1; + private bool _selDragging, _selMoved; + private Vector2 _selDown; + private string? _flash; + private double _flashUntil; + + // Unread lines per tab since it was last on screen (Id of the newest line seen there). + private readonly Dictionary _seenId = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _unread = new(StringComparer.OrdinalIgnoreCase); + private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1, _unreadCountedTo; + private string _unreadTab = ""; + + private bool _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename, _openTabsPopup, _openNewWindow; + private string? _ctxTab, _renameFrom; + private ChatLine? _ctxLine; + private string _ctxPattern = ""; + // Map coordinates in the right-clicked line (ChatCoords, found when the menu opens): + // its menu offers "Arrow to" / "Go to" them, through RynthNav. + private List _ctxCoords = new(); + /// A Move/Copy rule waiting for the New tab popup to name its tab. + private ChatFilterRule? _pendingRule; + + /// Unread lines per tab (not the one on screen). + public IReadOnlyDictionary Unread => _unread; + + /// The face opened: follow the newest line, every tab starts read. + public void OnShown() + { + _stick = true; + _seenRoutes = -1; // full rebuild on the first frame + _seenId.Clear(); // every tab starts read + _unreadLines = _unreadRoutes = -1; // a full recount + } + + public void OnHidden() => OnScreen.Remove(_viewKey); + + /// Follow the newest line again (Auto-scroll turned on). + public void Restick() => _stick = true; + + /// + /// Start of the face's frame: this view's tab is on screen, and the unread counts are + /// brought up to date. Returns the tab shown this frame. + /// + public string BeginFrame(ChatLine[] lines, long linesVersion) + { + string tab = Tab; + OnScreen[_viewKey] = tab; + UpdateUnread(lines, linesVersion, tab); + return tab; + } + + // ── Opening the menus and popups (drawn in DrawPopups) ────────────────── + + /// Right-click on a tab (strip, drawer row, list): its menu. + public void OpenTabMenu(string tab) + { + _ctxTab = tab; + _openTabMenu = true; + } + + /// "+ New tab": the name popup (the new tab is shown in this view). + public void OpenNewTab() + { + _pendingRule = null; + WriteUtf8(_newTab, ""); + _openNewTab = _focusNewTab = true; + } + + /// The tabs as a list under the button (popped out, or an extra window). + public void OpenTabsPopup() => _openTabsPopup = true; + + /// The "New chat window" button: a list of tabs to open in their own window. + public void OpenNewWindowMenu() => _openNewWindow = true; + + // ── Tabs ───────────────────────────────────────────────────────────── + + internal static float BadgeWidth(string badge) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + float w = ImGuiNET.ImGui.CalcTextSize(badge).X + 8; + ImGuiNET.ImGui.PopFont(); + return w; + } + + internal static void DrawBadge(ImDrawListPtr dl, Vector2 p, float w, float h, string badge, bool mention) + { + dl.AddRectFilled(p, p + new Vector2(w, h), mention ? BadgeMention : BadgeBg, h * 0.5f); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + dl.AddText(p + new Vector2(4, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge); + ImGuiNET.ImGui.PopFont(); + } + + /// + /// The channel button (the view's tab, with the unread count of every other tab), as the + /// main chat's header has it. Returns true when clicked. : drawn as active. + /// + public bool DrawTabButton(string id, Vector2 start, float maxW, float h, bool highlight) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + string current = Tab; + int others = 0; + bool mention = false; + foreach (var kv in _unread) + { + if (string.Equals(kv.Key, current, StringComparison.OrdinalIgnoreCase)) continue; + others += kv.Value.Count; + mention |= kv.Value.Mention && kv.Value.Count > 0; + } + string? badge = others > 0 ? (others > 99 ? "99+" : others.ToString()) : null; + float badgeW = badge != null ? BadgeWidth(badge) : 0; + string label = PhosphorIcons.ChatCircleText + " " + current; + float labelW = ImGuiNET.ImGui.CalcTextSize(label).X; + float caretW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.CaretDown).X; + float bw = MathF.Min(labelW + 16 + caretW + (badge != null ? badgeW + 4 : 0), maxW); + bool clicked = Button(id, "", start, new Vector2(bw, h), Text, highlight ? TabActive : BtnFill); + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) + SafeImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); + float ty = start.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.PushClipRect(start, start + new Vector2(bw - caretW - 6 - (badge != null ? badgeW + 4 : 0), h), true); + dl.AddText(new Vector2(start.X + 6, ty), Text, label); + dl.PopClipRect(); + float bx = start.X + bw - caretW - 6; + if (badge != null) + { + bx -= badgeW + 4; + DrawBadge(dl, new Vector2(bx, start.Y + 4), badgeW, h - 8, badge, mention); + } + dl.AddText(new Vector2(start.X + bw - caretW - 5, ty), Mute, PhosphorIcons.CaretDown); + LastTabButtonWidth = bw; + return clicked; + } + + /// The width took this frame. + public float LastTabButtonWidth { get; private set; } + + /// The "New chat window" icon button (a list of tabs to open in their own window). + public void DrawNewWindowButton(string id, Vector2 p, Vector2 size) + { + if (IconButton(id, PhosphorIcons.AppWindow, p, size, Text, BtnFill)) + OpenNewWindowMenu(); + ImGuiNET.ImGui.SetItemTooltip("New chat window: show a tab in a window of its own\n" + + "(or right-click a tab: Open in new window)"); + } + + /// The tabs as a list under the button: click shows one here, right-click its menu. + private void DrawTabsPopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_tabs")) return; + string current = Tab; + foreach (string tab in ChatModel.AllTabs()) + { + _unread.TryGetValue(tab, out var unread); + bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); + string label = !active && unread.Count > 0 ? $"{tab} ({unread.Count})" : tab; + if (ImGuiNET.ImGui.Selectable(label + "##tabsel_" + tab, active)) _selectTab(tab); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + OpenTabMenu(tab); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + } + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.Selectable(PhosphorIcons.Plus + " New tab")) OpenNewTab(); + ImGuiNET.ImGui.EndPopup(); + } + + /// The "New chat window" list: pick a tab, it opens in the first free window. + private void DrawNewWindowPopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_newwin")) return; + Label("Open in a new window:", Mute); + foreach (string tab in ChatModel.AllTabs()) + { + _unread.TryGetValue(tab, out var unread); + string label = unread.Count > 0 ? $"{tab} ({unread.Count})" : tab; + if (ImGuiNET.ImGui.Selectable(label + "##newwin_" + tab)) OpenInNewWindow(tab); + } + ImGuiNET.ImGui.EndPopup(); + } + + private void OpenInNewWindow(string tab) + { + var (ok, message) = ChatWindowFace.OpenNew(tab); + Flash(message, ok ? 2.0 : 3.0); + } + + /// + /// Unread counts per tab: lines shown there that arrived after it was last on + /// screen. Recounted only when the lines, the routes or the tabs change. + /// + private void UpdateUnread(ChatLine[] lines, long linesVersion, string current) + { + long newest = lines.Length > 0 ? lines[^1].Id : 0; + _seenId[current] = newest; + // Tabs another chat window has on screen are read here too. + foreach (var kv in OnScreen) + { + if (string.Equals(kv.Key, _viewKey, StringComparison.OrdinalIgnoreCase)) continue; + _seenId[kv.Value] = newest; + _unread.Remove(kv.Value); + } + long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion; + bool recount = routes != _unreadRoutes || tabsVersion != _unreadTabsVersion + || !string.Equals(current, _unreadTab, StringComparison.Ordinal); + if (!recount && linesVersion == _unreadLines) return; + _unreadLines = linesVersion; + _unreadRoutes = routes; + _unreadTabsVersion = tabsVersion; + _unreadTab = current; + // Only new lines arrived: count just those (lines past _unreadCountedTo). A full recount + // walks every unread line of every tab - up to the whole history per tab (3.7 ms at + // 10,000 lines, tools/ChatHistoryBench), which used to run on every new batch. + if (recount) _unread.Clear(); + foreach (string tab in ChatModel.AllTabs()) + { + if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read + long from = recount ? seen : Math.Max(seen, _unreadCountedTo); + int count = 0; + bool mention = false; + for (int i = lines.Length - 1; i >= 0 && lines[i].Id > from; i--) + if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; } + if (count == 0) continue; + _unread.TryGetValue(tab, out var had); + _unread[tab] = (had.Count + count, had.Mention || mention); + } + _unreadCountedTo = newest; + } + + private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search…"; + + public void DrawSearch(Vector2 p, float w) + { + bool hasText = _search[0] != 0; + TextBox("##chat_search", _search, p, hasText ? w - 24 : w, SearchHint, out _); + if (hasText) + { + if (IconButton("##chat_search_x", PhosphorIcons.X, new Vector2(p.X + w - 22, p.Y), new Vector2(22, 22), Mute, BtnFill, font: UiFont.Ui10)) + WriteUtf8(_search, ""); + ImGuiNET.ImGui.SetItemTooltip("Clear the search"); + } + } + + // ── Lines ──────────────────────────────────────────────────────────── + + /// Brings _vis up to date with the snapshot, tab, search and routes. + public void SyncLines(UiSnapshot? snap, ChatLine[] lines, string tab) + { + string search = Utf8(_search); + long routes = ChatModel.RoutesVersion; + + if (routes != _seenRoutes || tab != _seenTab || search != _seenSearch) + { + _seenRoutes = routes; + _seenTab = tab; + _seenSearch = search; + _seenLinesVersion = snap?.Version ?? -1; + _vis.Clear(); + _h.Clear(); + _lay.Clear(); + foreach (ChatLine line in lines) + if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(_rowH); _lay.Add(null); } + _lastId = lines.Length > 0 ? lines[^1].Id : _lastId; + _heightsFrom = _measuredFrom = _vis.Count; // all unmeasured: MeasureLines, newest first + _topsDirty = true; + ClearSelection(); + _stick = true; // a rebuild re-pins to the newest line + _droppedAbove = 0f; + return; + } + if (snap == null || snap.Version == _seenLinesVersion) return; + _seenLinesVersion = snap.Version; + + // Drop lines the source no longer keeps, then add the new ones. + long oldest = lines.Length > 0 ? lines[0].Id : long.MaxValue; + int drop = 0; + while (drop < _vis.Count && _vis[drop].Id < oldest) drop++; + if (drop > 0 && !_selDragging) + { + if (!Following) + for (int i = 0; i < drop; i++) _droppedAbove += _h[i]; + _vis.RemoveRange(0, drop); + _h.RemoveRange(0, drop); + _lay.RemoveRange(0, drop); + _heightsFrom = Math.Max(0, _heightsFrom - drop); + _measuredFrom = Math.Max(0, _measuredFrom - drop); + if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); } + _topsDirty = true; + } + foreach (ChatLine line in lines) + { + if (line.Id <= _lastId) continue; + _lastId = line.Id; + if (!ChatModel.LineVisible(line, tab, search)) continue; + if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count; + _vis.Add(line); + _h.Add(_rowH); + _lay.Add(null); + _topsDirty = true; + } + } + + /// The view follows the newest line (auto-scroll on and not scrolled away). + private bool Following => ChatModel.AutoScroll && _stick; + + public void DrawLines(Vector2 size) + { + float fontSize = ChatModel.FontSize; + ImFontPtr font = ImGuiFonts.Chat(fontSize); + ImGuiNET.ImGui.PushFont(font); + bool showTs = ChatModel.ShowTimestamps; + + // The lines are measured BEFORE the list's BeginChild, so this frame's scroll can be + // set for this frame's lines (see "Where the view goes" below). The width they wrap + // to is the child's: its width less its scrollbar (always shown) and a margin; + // _wrapFix corrects that guess if the child ever reports otherwise. + float wrapW = Math.Max(20, MathF.Floor(size.X) - ListScrollbarW - 6 + _wrapFix); + float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0; + MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y)); + float total = _tops[_vis.Count]; + + // Where the view goes this frame. (2026-10-11, the chat "bouncing": until now the + // view followed the newest line with SetScrollHereY at the end of the frame, which + // only lands in the NEXT frame's Begin. So every batch of new lines was first drawn + // at the old scroll: with the buffer full, lines leave the top as others arrive, + // and the text jumped by the difference - up and back down when a long line left + // and a short one came - then snapped into place a frame later. A popped-out chat + // redraws at 5 Hz while idle, so the wrong frame stayed up for 200 ms.) Now the + // content height and the scroll are both handed to this frame's BeginChild: + // • the content size, so ImGui's scroll limit is this frame's and not last frame's + // (it clamps any scroll set before Begin to the limit it knows); + // • following: the bottom (the limit clamps 'total' to exactly the bottom); + // • not following: only the lines dropped off a full buffer's top, so what is + // being read stays put (fractions carried, so rounding can't creep the view). + // A frame with wheel input over the list leaves the scroll to the wheel (this would + // override it); a drag-select scrolls the list itself. + Vector2 listPos = ImGuiNET.ImGui.GetCursorScreenPos(); + bool wheelHere = ImGuiNET.ImGui.GetIO().MouseWheel != 0f + && ImGuiNET.ImGui.IsMouseHoveringRect(listPos, listPos + size, false); + ImGuiNET.ImGui.SetNextWindowContentSize(new Vector2(0f, total)); + bool compensated = false; + if (Following) + { + _droppedAbove = 0f; + _scrollCarry = 0f; + // Not counted as "our move": a scrollbar drag in this Begin overrides it, and the + // check below must see that to stop following. + if (!wheelHere && !_selDragging) + ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, total)); + } + else if (_droppedAbove != 0f && !wheelHere) + { + float target = _lastScrollY + _scrollCarry - _droppedAbove; + float applied = MathF.Round(Math.Max(0f, target)); // ImGui rounds scroll to whole pixels + _scrollCarry = target > 0f ? target - applied : 0f; + ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, applied)); + _droppedAbove = 0f; + compensated = true; + } + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, ListScrollbarW); + bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) { ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopFont(); return; } + + // The child's real width, should the guess above ever be off (a style change): + // measured again now, and the guess corrected from the next frame on. + float realWrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6); + if (Math.Abs(realWrapW - wrapW) > 0.5f) + { + _wrapFix += realWrapW - wrapW; + wrapW = realWrapW; + MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y)); + total = _tops[_vis.Count]; + } + float textW = Math.Max(20, wrapW - tsW); + int n = _vis.Count; + + // Following the tail until the user scrolls away from it. + float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY(); + if (compensated) _lastScrollY = scrollY; // our move, not the user's + else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) _scrollCarry = 0f; // the user's: start afresh + // Wheel up over the chat stops following at once; reaching the bottom again resumes it. + // Not while it has nothing to scroll: no scroll change would ever turn following back on. + if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f) + _stick = false; + else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) + _stick = scrollY >= maxY - StickThreshold; + + Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos(); + float viewH = ImGuiNET.ImGui.GetWindowHeight(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + int first = FirstAtOrBelow(scrollY, n); + int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); + for (int i = first; i < n && _tops[i] < scrollY + viewH; i++) + { + Vector2 p = basePos + new Vector2(0, _tops[i]); + ChatLine line = _vis[i]; + ChatRoute route = line.Route; + // A "Highlight line" rule: a band behind all of the line's rows, under the mention + // tint and the selection. One rect, no allocation; _h[i] already spans every row. + if (route.HighlightArgb is uint band) + dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), RynthTheme.Argb(ChatColorModes.BandArgb(band))); + if (route.Mention) + dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg); + if (lo >= 0 && i >= lo && i <= hi) + dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg); + uint col = RynthTheme.Argb(ChatModel.LineArgb(line)); + if (showTs) dl.AddText(font, font.FontSize, p + new Vector2(3, 0), TsColor, line.Timestamp); + Vector2 tp = p + new Vector2(3 + tsW, 0); + SpanLayout? lay = _lay[i]; + if (lay == null) + dl.AddText(font, font.FontSize, tp, col, line.Text, textW); + else + foreach (Seg seg in lay.Segs) + { + dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text); + if (seg.Link >= 0) // a map coordinate: underlined, it's clickable + { + Vector2 u = tp + seg.Offset + new Vector2(0, font.FontSize - 1); + dl.AddLine(u, u + new Vector2(seg.W, 0), RynthTheme.Argb(LinkCol), 1f); + } + } + } + ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total))); + HoverLink(basePos, tsW, n, out ChatCoord? hoveredLink); + HandleSelection(basePos, wrapW, scrollY, viewH, n, hoveredLink); + HandleLineMenu(basePos, wrapW, n); + + _lastScrollY = scrollY; + + // "Copied N lines" / "Rule added", top-right, for a moment. + if (_flash != null) + { + if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null; + else + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_flash); + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); + Vector2 fp = new(Math.Max(wp.X + 2, wp.X + wrapW - ts.X - 12), wp.Y + 4); + dl.AddRectFilled(fp, fp + ts + new Vector2(12, 4), FlashBg, 3); + dl.AddText(fp + new Vector2(6, 2), Text, _flash); + ImGuiNET.ImGui.PopFont(); + } + } + + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopFont(); // pushed before the child, for MeasureLines + } + + /// Time MeasureLines may spend a frame catching up on lines measured for another width. + private const double MeasureBudgetMs = 2.0; + private static readonly long MeasureBudgetTicks = (long)(System.Diagnostics.Stopwatch.Frequency * MeasureBudgetMs / 1000); + + /// + /// Brings the line heights and tops up to date for this wrap width, font and timestamp + /// setting. Chat font pushed. New lines are measured at once. When the width, font or + /// timestamps change (or after a rebuild) every line needs measuring again: 16 ms at + /// 10,000 lines (tools/ChatHistoryBench), every frame of a resize drag. So that is done + /// a slice at a time: the lines in view first, then from the newest line up, for + /// MeasureBudgetMs a frame; the others keep their old height meanwhile. Scrolled up, + /// the view is moved by however much the lines above it grew or shrank, so what's being + /// read stays put (the same way as lines dropping off the top). + /// + private void MeasureLines(ImFontPtr font, float wrapW, float tsW, float fontSize, bool showTs, float viewH) + { + // The text starts after the timestamp and wraps under itself. + float textW = Math.Max(20, wrapW - tsW); + _rowH = font.FontSize; + if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs) + { + _seenWrap = wrapW; + _seenFont = fontSize; + _seenTs = showTs; + _measuredFrom = Math.Min(_heightsFrom, _vis.Count); // all measured so far is stale + } + bool changed = false; + for (int i = _heightsFrom; i < _vis.Count; i++) { MeasureLine(font, i, textW); changed = true; } + _heightsFrom = _vis.Count; + + if (_measuredFrom > 0) + { + UpdateTops(); + int n = _vis.Count; + bool following = Following; + // Where the view will be (last frame's scroll, less any move still to come). + float viewTop = _lastScrollY + _scrollCarry - _droppedAbove; + int firstVisible = following || n == 0 ? int.MaxValue : FirstAtOrBelow(Math.Max(0f, viewTop), n); + if (!following) + for (int i = firstVisible; i < Math.Min(n, _measuredFrom) && _tops[i] < viewTop + viewH; i++) + MeasureLine(font, i, textW); + float grewAbove = 0f; + long t0 = System.Diagnostics.Stopwatch.GetTimestamp(); + int count = 0; + while (_measuredFrom > 0) + { + int i = --_measuredFrom; + float old = _h[i]; + MeasureLine(font, i, textW); + if (i < firstVisible) grewAbove += _h[i] - old; + if ((++count & 15) == 0 && System.Diagnostics.Stopwatch.GetTimestamp() - t0 > MeasureBudgetTicks) break; + } + if (!following) _droppedAbove -= grewAbove; + changed = true; + } + if (changed) _topsDirty = true; + UpdateTops(); + } + + private void MeasureLine(ImFontPtr font, int i, float textW) + { + ChatLine line = _vis[i]; + ChatSpan[]? spans = line.Route.Spans; + // Map coordinates ("82.3N, 34.2E") become links. Found here, when the line is measured, + // never per frame; a line without any keeps the plain (or highlighted) path. + List coords = ChatCoords.MayHaveCoords(line.Text) ? ChatCoords.Find(line.Text) : NoCoords; + if (coords.Count > 0) + { + ChatSpan[] withLinks = ChatCoords.LinkSpans(spans, coords, LinkCol); + SpanLayout lay = LayoutSpans(font, line.Text, withLinks, textW, coords); + _lay[i] = lay; + _h[i] = lay.Height; + } + else if (spans != null) + { + SpanLayout lay = LayoutSpans(font, line.Text, spans, textW); + _lay[i] = lay; + _h[i] = lay.Height; + } + else + { + _lay[i] = null; + _h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y; + } + } + + private void UpdateTops() + { + if (!_topsDirty && _tops.Length > _vis.Count) return; + if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)]; + _tops[0] = 0; + for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i]; + _topsDirty = false; + } + + public void Flash(string message, double seconds = 2.0) + { + _flash = message; + _flashUntil = ImGuiNET.ImGui.GetTime() + seconds; + } + + // ── Highlighted lines: hand layout ─────────────────────────────────── + + // Argb 0 = the line's colour. W: the run's width. Link: index into SpanLayout.Links (a map + // coordinate drawn as a link: click = RynthNav arrow, Ctrl+click = go), -1 for plain text. + private readonly record struct Seg(string Text, Vector2 Offset, uint Argb, float W = 0f, int Link = -1); + + private sealed class SpanLayout + { + public required float Height; + public required Seg[] Segs; + /// The line's map coordinates (ChatCoords), when any are drawn as links. + public ChatCoord[]? Links; + } + + /// Coordinate links in chat lines: soft teal, underlined (0xAARRGGBB, like ChatSpan.Argb). + private const uint LinkCol = 0xFF5ECFE0; + + private static readonly List NoCoords = new(); + + /// + /// Word-wraps to and cuts each + /// row where a highlight starts or ends, so every run is drawn in its own + /// colour. Called when a line is measured, never per frame. + /// : the line's map coordinates, whose runs get a link index. + /// + private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW, List? links = null) + { + // Which coordinate link a run [s0, s1) belongs to (-1 none). + int LinkOf(int s0, int s1) + { + if (links == null) return -1; + for (int k = 0; k < links.Count; k++) + if (s0 >= links[k].Start && s1 <= links[k].Start + links[k].Length) return k; + return -1; + } + + float size = font.FontSize; + float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X; + + // Rows as [start, end) character ranges. + var rows = new List<(int Start, int End)>(); + int rowStart = 0; + float x = 0; + int i = 0; + while (i < text.Length) + { + if (text[i] == '\n') { rows.Add((rowStart, i)); rowStart = i + 1; x = 0; i++; continue; } + // A word and the spaces after it. + int j = i; + while (j < text.Length && text[j] != ' ' && text[j] != '\n') j++; + while (j < text.Length && text[j] == ' ') j++; + float ww = Width(i, j); + int wordEnd = j; + while (wordEnd > i && text[wordEnd - 1] == ' ') wordEnd--; + float inkW = Width(i, wordEnd); + if (x > 0 && x + inkW > wrapW) + { + rows.Add((rowStart, i)); + rowStart = i; + x = 0; + } + if (x == 0 && inkW > wrapW) + { + // A word wider than the row: break it by characters. + int k = i; + while (k < wordEnd) + { + int m = k + 1; + while (m < wordEnd && Width(k, m + 1) <= wrapW) m++; + if (m < wordEnd) { rows.Add((rowStart, m)); rowStart = m; } + else x = Width(k, j); + k = m; + } + i = j; + continue; + } + x += ww; + i = j; + } + rows.Add((rowStart, text.Length)); + + var segs = new List(); + for (int r = 0; r < rows.Count; r++) + { + (int a, int b) = rows[r]; + float y = r * size, sx = 0; + int c = a; + foreach (ChatSpan span in spans) + { + int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b); + if (s1 <= s0) continue; + if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); } + float spanW = Width(s0, s1); + segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb, spanW, LinkOf(s0, s1))); + sx += spanW; + c = s1; + } + if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0)); + } + return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray(), Links = links?.ToArray() }; + } + + /// Index of the line containing content y (clamped to the list). + private int FirstAtOrBelow(float y, int n) + { + int lo = 0, hi = n; // first i with _tops[i + 1] > y + while (lo < hi) + { + int mid = (lo + hi) >> 1; + if (_tops[mid + 1] > y) hi = mid; else lo = mid + 1; + } + return Math.Min(lo, Math.Max(0, n - 1)); + } + + /// + /// The map coordinate link under the mouse, if any (hand cursor and a tooltip). Only the + /// hovered line's runs are looked at. + /// + private void HoverLink(Vector2 basePos, float tsW, int n, out ChatCoord? link) + { + link = null; + if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsWindowHovered()) return; + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + float contentY = mouse.Y - basePos.Y; + if (contentY < 0 || contentY >= _tops[n]) return; + int i = FirstAtOrBelow(contentY, n); + if (_lay[i] is not { Links: { Length: > 0 } links } lay) return; + Vector2 tp = basePos + new Vector2(3 + tsW, _tops[i]); + float h = ImGuiNET.ImGui.GetFontSize(); + foreach (Seg seg in lay.Segs) + { + if (seg.Link < 0 || seg.Link >= links.Length) continue; + Vector2 a = tp + seg.Offset, b = a + new Vector2(seg.W, h); + if (mouse.X < a.X || mouse.X >= b.X || mouse.Y < a.Y || mouse.Y >= b.Y) continue; + link = links[seg.Link]; + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + bool nav = ImGuiPanelHost.HasFace(RynthNavFace.Title); + SafeImGui.SetTooltip(nav + ? $"Click: point the arrow at {link.Value.Text}\nCtrl+click: RynthNav walks there\nRight-click: more" + : $"{link.Value.Text}\n(RynthNav isn't loaded: no arrow)"); + return; + } + } + + /// A click on a coordinate link: RynthNav's arrow there, or (Ctrl) walk there. + private void ClickLink(ChatCoord c) + { + if (!ImGuiPanelHost.HasFace(RynthNavFace.Title)) { Flash("RynthNav isn't loaded", 1.5); return; } + if (ImGuiNET.ImGui.GetIO().KeyCtrl) + { + RynthNavCommands.Go(c.Text, c.Ns, c.Ew); + Flash("Going to " + c.Text, 1.5); + } + else + { + RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew); + Flash("Arrow: " + c.Text, 1.5); + } + } + + private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n, ChatCoord? hoveredLink = null) + { + if (n == 0) { ClearSelection(); return; } + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + float contentY = mouse.Y - basePos.Y; + if (!_selDragging) + { + if (!ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) + || !ImGuiNET.ImGui.IsWindowHovered() + || mouse.X > basePos.X + wrapW + 6) // the scrollbar + return; + ClearSelection(); + if (contentY < 0 || contentY >= _tops[n]) return; + _selAnchor = _selEnd = FirstAtOrBelow(contentY, n); + _selDragging = true; + _selMoved = false; + _selDown = mouse; + _downLink = hoveredLink; // a click (no drag) on it acts on release + return; + } + + if (Math.Abs(mouse.X - _selDown.X) > 3 || Math.Abs(mouse.Y - _selDown.Y) > 3) _selMoved = true; + _selEnd = FirstAtOrBelow(Math.Clamp(contentY, 0, _tops[n] - 1), n); + + // Dragging past the edges scrolls. + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); + if (mouse.Y < wp.Y) ImGuiNET.ImGui.SetScrollY(Math.Max(0, scrollY - 12)); + else if (mouse.Y > wp.Y + viewH) ImGuiNET.ImGui.SetScrollY(scrollY + 12); + + if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return; + _selDragging = false; + // A drag (even within one line) copies; a plain click just clears, or follows a + // coordinate link it was pressed on. + if (!_selMoved && _selEnd == _selAnchor) + { + ChatCoord? link = _downLink; + ClearSelection(); + if (link is { } c) ClickLink(c); + return; + } + int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); + var parts = new List(hi - lo + 1); + for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i])); + Flash(ChatModel.CopyLines(parts), 1.5); + } + + private static string CopyText(ChatLine line) => ChatModel.ShowTimestamps ? line.FormattedText : line.Text; + + /// Right-click on a line: its menu (drawn in DrawPopups). + private void HandleLineMenu(Vector2 basePos, float wrapW, int n) + { + if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right) || !ImGuiNET.ImGui.IsWindowHovered()) + return; + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + float contentY = mouse.Y - basePos.Y; + if (mouse.X > basePos.X + wrapW + 6 || contentY < 0 || contentY >= _tops[n]) return; + _ctxLine = _vis[FirstAtOrBelow(contentY, n)]; + _ctxPattern = ChatModel.PatternFor(_ctxLine); + _ctxCoords = ImGuiPanelHost.HasFace(RynthNavFace.Title) ? ChatCoords.Find(_ctxLine.Text) : new List(); + _openLineMenu = true; + } + + private void ClearSelection() + { + _selAnchor = _selEnd = -1; + _selDragging = _selMoved = false; + _downLink = null; + } + + /// The coordinate link the left button went down on (acted on if it comes up without a drag). + private ChatCoord? _downLink; + + // ── Rules from a line ──────────────────────────────────────────────── + + private void RuleFromLine(ChatRuleAction action, string? tab, ChatColorMode colour = ChatColorMode.Line) + { + var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" }; + if (action == ChatRuleAction.Color) + { + rule.ColorMode = colour; + ChatModel.AddRule(rule); + if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters"); + Flash(colour == ChatColorMode.Highlight + ? "Rule added: lines like this are highlighted - pick its colour in Filters" + : "Rule added - pick its colour in Filters"); + return; + } + ChatModel.AddRule(rule); + Flash(action switch + { + ChatRuleAction.Move => $"Rule added: lines like this move to {tab}", + ChatRuleAction.Copy => $"Rule added: lines like this also show in {tab}", + _ => "Rule added: lines like this are hidden (undo in Filters)", + }, 3); + } + + private void TabMenu(string id, ChatRuleAction action) + { + if (!ImGuiNET.ImGui.BeginMenu(id)) return; + foreach (string t in ChatModel.TargetTabs()) + if (ImGuiNET.ImGui.MenuItem(t)) RuleFromLine(action, t); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("New tab…")) + { + _pendingRule = new ChatFilterRule { Pattern = _ctxPattern, Action = action }; + WriteUtf8(_newTab, ""); + _openNewTab = _focusNewTab = true; + } + ImGuiNET.ImGui.EndMenu(); + } + + // ── Popups ─────────────────────────────────────────────────────────── + + /// The chat popups' colours and padding (pair with ). + internal static void PushPopupStyle() + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Argb(0xF2060C14)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, TabActive); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, TabActive); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + } + + internal static void PopPopupStyle() + { + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(8); + } + + /// + /// Opens what was asked for this frame and draws this view's popups: the tab list, New tab, + /// a tab's menu, Rename, a line's menu and the New chat window list. Inside the popup style. + /// + public void DrawPopups() + { + if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chat_newtab"); } + if (_openTabMenu) { _openTabMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_tabmenu"); } + if (_openLineMenu) { _openLineMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_linemenu"); } + if (_openRename) { _openRename = false; ImGuiNET.ImGui.OpenPopup("##chat_rename"); } + if (_openTabsPopup) { _openTabsPopup = false; ImGuiNET.ImGui.OpenPopup("##chat_tabs"); } + if (_openNewWindow) { _openNewWindow = false; ImGuiNET.ImGui.OpenPopup("##chat_newwin"); } + + DrawTabsPopup(); + DrawNewTabPopup(); + DrawTabMenu(); + DrawRenamePopup(); + DrawLineMenu(); + DrawNewWindowPopup(); + } + + private void DrawNewTabPopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab")) + { + _pendingRule = null; + return; + } + if (_pendingRule != null) + Label(_pendingRule.Action == ChatRuleAction.Copy ? "New tab for a copy of lines like this:" : "New tab for lines like this:", Mute); + if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool enter = TextBox("##newtab_name", _newTab, p, 120, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); + bool add = Button("##newtab_add", "Add", new Vector2(p.X + 124, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, TabActive); + bool cancel = Button("##newtab_cancel", "Cancel", new Vector2(p.X + 128 + ButtonWidth("Add"), p.Y), new Vector2(ButtonWidth("Cancel"), 20), Text, BtnFill); + NextLine(p, 20); + if (enter || add) + { + ChatFilterRule? pending = _pendingRule; + // The main chat selects the new tab as it always has; an extra window shows it itself. + string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: IsMain && pending == null); + if (name != null && pending == null && !IsMain) _selectTab(name); + if (name != null && pending != null) + { + pending.Tab = name; + ChatModel.AddRule(pending); + Flash(pending.Action == ChatRuleAction.Copy + ? $"Rule added: lines like this also show in {name}" + : $"Rule added: lines like this move to {name}", 3); + } + _pendingRule = null; + ImGuiNET.ImGui.CloseCurrentPopup(); + } + else if (cancel || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) + { + _pendingRule = null; + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawTabMenu() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_tabmenu")) return; + string tab = _ctxTab ?? ""; + Label(tab, Teal); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Mark as read")) + { + var lines = UiSources.Chat.Current?.Value; + _seenId[tab] = lines is { Length: > 0 } ? lines[^1].Id : 0; + _unread.Remove(tab); + } + if (ImGuiNET.ImGui.MenuItem("Mark all tabs read")) + { + var lines = UiSources.Chat.Current?.Value; + long newest = lines is { Length: > 0 } ? lines[^1].Id : 0; + foreach (string t in ChatModel.AllTabs()) _seenId[t] = newest; + _unread.Clear(); + } + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.AppWindow + " Open in new window")) + OpenInNewWindow(tab); + ImGuiNET.ImGui.SetItemTooltip("Show this tab in a chat window of its own (up to " + ChatWindows.MaxWindows + " extra windows)"); + if (!ChatModel.IsBaseTab(tab)) + { + if (ImGuiNET.ImGui.MenuItem("Rename…")) + { + _renameFrom = tab; + WriteUtf8(_newTab, tab); + _openRename = _focusNewTab = true; + } + if (ImGuiNET.ImGui.MenuItem("Delete tab")) ChatModel.DeleteCustomTab(tab); + } + if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) + PanelRouter.Toggle("ChatFilters"); + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawRenamePopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_rename")) return; + Label($"Rename \"{_renameFrom}\" (its rules follow):", Mute); + if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; } + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool enter = TextBox("##rename_name", _newTab, p, 140, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20); + bool ok = Button("##rename_ok", "Rename", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Rename"), 20), Text, TabActive); + NextLine(p, 20); + if (enter || ok) + { + if (_renameFrom != null && !ChatModel.RenameCustomTab(_renameFrom, Utf8(_newTab))) + Flash("That name is taken (or blank)"); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape)) + ImGuiNET.ImGui.CloseCurrentPopup(); + ImGuiNET.ImGui.EndPopup(); + } + + private void DrawLineMenu() + { + ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(200, 0), new Vector2(420, float.MaxValue)); + if (!ImGuiNET.ImGui.BeginPopup("##chat_linemenu")) return; + ChatLine? line = _ctxLine; + if (line == null) { ImGuiNET.ImGui.EndPopup(); return; } + // Coordinates in the line: point RynthNav's arrow there, or walk there (left-click + // selects lines, so this lives in the right-click menu). + for (int i = 0; i < _ctxCoords.Count && i < 3; i++) + { + ChatCoord c = _ctxCoords[i]; + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.NavigationArrow + " Arrow to " + c.Text)) + RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Go to " + c.Text)) + RynthNavCommands.Go(c.Text, c.Ns, c.Ew); + ImGuiNET.ImGui.PopID(); + } + if (_ctxCoords.Count > 0) ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Copy line")) Flash(ChatModel.CopyLines(new[] { CopyText(line) }), 1.5); + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 400); + ImGuiNET.ImGui.TextUnformatted("Lines like this: " + _ctxPattern); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + TabMenu("Move them to", ChatRuleAction.Move); + TabMenu("Also show them in", ChatRuleAction.Copy); + if (ImGuiNET.ImGui.MenuItem("Hide them")) RuleFromLine(ChatRuleAction.Hide, null); + if (ImGuiNET.ImGui.MenuItem("Colour them…")) RuleFromLine(ChatRuleAction.Color, null); + if (ImGuiNET.ImGui.MenuItem("Highlight them…")) RuleFromLine(ChatRuleAction.Color, null, ChatColorMode.Highlight); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) + PanelRouter.Toggle("ChatFilters"); + ImGuiNET.ImGui.EndPopup(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatWindowFace.cs new file mode 100644 index 0000000..77e6380 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ChatWindowFace.cs @@ -0,0 +1,265 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ChatWindowFace.cs +// Extra chat windows (2026-11-09; retail AC has them): "Chat 2" to "Chat 7" +// (UI/Data/ChatWindows.cs), each showing one tab of RynthChat beside the main +// chat, with its own scroll (following the newest line until you scroll up), +// search, unread counts and right-click menus - a ChatView of its own, drawn +// by the same code as the main chat's. +// +// Opening: the main chat's New chat window button (a list of tabs), "Open in +// new window" in any tab's right-click menu (main chat or an extra window), or +// /rc chatwindow open [tab]. Each window opens in the first free slot. Its +// header row: the tab button (click: the tabs, to switch this window's tab; +// right-click: the tab's menu), search, New chat window and Filters. The +// window's own header has pop-out and close, as every panel's. +// +// Each window is an ordinary engine panel to the host (registered once, by +// key), so it opens, closes, moves, resizes, pops out of the client into its +// own window and docks back like the main chat, independently of the others, +// and where it is, its size, docked or popped out and whether it is open are +// saved in the panel layout (panel_state.txt, per character) and come back +// after a hot reload or a restart (ImGuiPanelHost.RestoreOnce). The tab it +// shows is saved in that layout too (PanelStateStore value chatwin..tab), +// written only when the player opens a window on a tab, picks another tab +// for it, or renames that tab; a tab that is deleted shows as All without +// changing what is saved. +// +// No input line: there is one chat entry (Enter, the typed line, Tell), the +// main chat's. These windows don't count as the chat being shown +// (ChatModel.SetShown), so Enter never types into a window without a box. +// AC's thread (the panel host), except the static Open/Close/Describe calls +// (any thread: they only queue panel requests and read the store). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ChatWindowFace : IImGuiPanel +{ + private readonly int _number; + private readonly string _key; + private readonly ChatView _view; + /// The tab saved for this window ("" when none). + private string _savedTab = ""; + private int _readGeneration = -1, _readVersion = -1; + private string _shownHeader = ""; + + /// Goes up when any window's saved tab changes: the open ones read theirs again. + private static int s_tabsVersion; + + private ChatWindowFace(int number) + { + _number = number; + _key = ChatWindows.Key(number); + _view = new ChatView(_key, isMain: false, () => CurrentTab, tab => SaveTab(_number, tab)); + } + + /// The extra windows' panels: once, at engine init, beside the main chat. + public static void RegisterAll() + { + for (int n = ChatWindows.FirstNumber; n <= ChatWindows.LastNumber; n++) + { + int number = n; + ImGuiPanelHost.Register(ChatWindows.Key(number), ChatFace.Spec, () => new ChatWindowFace(number)); + } + } + + private string CurrentTab => ChatWindows.EffectiveTab(_savedTab, ChatModel.AllTabs()); + + public bool ClickThrough => ChatModel.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl; + + public int PopOutIdleHz => 5; + + public void OnShown() + { + ChatModel.EnsureSettingsLoaded(); + UiSources.Chat.Subscribe(); + UiSources.Chat.RequestRefresh(); + ReadTab(); + UpdateHeader(); + _view.OnShown(); + } + + public void OnHidden() + { + UiSources.Chat.Unsubscribe(); + _view.OnHidden(); + } + + /// Reads this window's saved tab (on open, after a layout switch, after a tab was saved). + private void ReadTab() + { + _readGeneration = PanelStateStore.Generation; + _readVersion = Volatile.Read(ref s_tabsVersion); + _savedTab = PanelStateStore.TryGetValue(ChatWindows.TabValueKey(_number), out string t) ? t : ""; + } + + private void UpdateHeader() + { + string header = ChatWindows.HeaderText(_number, CurrentTab); + if (string.Equals(header, _shownHeader, StringComparison.Ordinal)) return; + _shownHeader = header; + ImGuiPanelHost.SetDisplayTitle(_key, header); + } + + public void Draw() + { + if (PanelStateStore.Generation != _readGeneration || Volatile.Read(ref s_tabsVersion) != _readVersion) + ReadTab(); + UpdateHeader(); + + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + uint bg = RynthTheme.Argb(((uint)Math.Clamp(ChatModel.BackgroundAlpha, 0, 255) << 24) | 0x0A121A); + dl.AddRectFilled(origin, origin + size, bg, 4); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4)); + float x0 = origin.X + 4, w = size.X - 8; + + var snap = UiSources.Chat.Current; + ChatLine[] lines = snap?.Value ?? Array.Empty(); + string tab = _view.BeginFrame(lines, snap?.Version ?? -1); + + // Top row: the tab button, search, New chat window, Filters. + const float h = 22; + var start = new Vector2(x0, origin.Y + 4); + float right = x0 + w, btnW = 22; + if (IconButton("##chatwin_filters", PhosphorIcons.Funnel, new Vector2(right - btnW, start.Y), new Vector2(btnW, h), Text, BtnFill)) + PanelRouter.Toggle("ChatFilters"); + ImGuiNET.ImGui.SetItemTooltip("Filters: move, copy or hide lines by regex, and colour them"); + float winX = right - btnW - 3 - btnW; + _view.DrawNewWindowButton("##chatwin_newwin", new Vector2(winX, start.Y), new Vector2(btnW, h)); + if (_view.DrawTabButton("##chatwin_tab", start, w * 0.45f, h, highlight: false)) + _view.OpenTabsPopup(); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab); + float sx = start.X + _view.LastTabButtonWidth + 4, sw = winX - 4 - sx; + if (sw > 40) _view.DrawSearch(new Vector2(sx, start.Y), sw); + float y = start.Y + h + 4; + + _view.SyncLines(snap, lines, tab); + + // The scrollback fills the rest, ending above the resize grip in the bottom-right corner. + float reserve = ImGuiPanelHost.BodyGripReserve; + float bottom = origin.Y + size.Y - Math.Max(2f, reserve); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y)); + _view.DrawLines(new Vector2(w, Math.Max(20, bottom - y))); + + ImGuiNET.ImGui.PopStyleVar(); + ChatView.PushPopupStyle(); + _view.DrawPopups(); + ChatView.PopPopupStyle(); + ImGuiNET.ImGui.PopFont(); + } + + // ── Opening, closing and the saved tabs (any thread) ──────────────────── + + private static string SavedTab(int number) => + PanelStateStore.TryGetValue(ChatWindows.TabValueKey(number), out string t) ? t : ""; + + /// Saves the tab window shows: the player picked it. + private static void SaveTab(int number, string tab) + { + PanelStateStore.SetValue(ChatWindows.TabValueKey(number), tab); + Interlocked.Increment(ref s_tabsVersion); + } + + /// The extra windows are registered (RynthChat is installed and the ImGui layer is on). Any thread. + internal static bool Available =>ImGuiPanelHost.HasFace(ChatWindows.Key(ChatWindows.FirstNumber)); + + private const string NotAvailable = "Chat windows aren't available (the ImGui layer is off?)."; + + /// + /// Opens (null or blank: the main chat's tab) in the first free extra + /// window; one that already shows it stays the only one. The player asked for it (a button, + /// a menu or a command). Returns whether a window shows it now, and what to tell the player. + /// + public static (bool Ok, string Message) OpenNew(string? tab) + { + if (!Available) return (false, NotAvailable); + string[] all = ChatModel.AllTabs(); + string? resolved = string.IsNullOrWhiteSpace(tab) ? ChatModel.CurrentTab() : ChatWindows.Resolve(tab, all); + if (resolved == null) return (false, $"No tab called '{tab!.Trim()}'. Tabs: {string.Join(", ", all)}."); + for (int n = ChatWindows.FirstNumber; n <= ChatWindows.LastNumber; n++) + if (ImGuiPanelHost.IsOpen(ChatWindows.Key(n)) + && string.Equals(ChatWindows.EffectiveTab(SavedTab(n), all), resolved, StringComparison.OrdinalIgnoreCase)) + return (true, $"Chat {n} already shows {resolved}."); + int free = ChatWindows.FirstFree(ImGuiPanelHost.IsOpen); + if (free == 0) return (false, $"All {ChatWindows.MaxWindows} extra chat windows are open: close one first."); + SaveTab(free, resolved); + ImGuiPanelHost.Open(ChatWindows.Key(free)); + return (true, $"Chat {free} opened on {resolved}."); + } + + /// Shows in window (opening it if closed). + public static (bool Ok, string Message) ShowTab(int number, string tab) + { + if (!Available) return (false, NotAvailable); + string[] all = ChatModel.AllTabs(); + string? resolved = ChatWindows.Resolve(tab, all); + if (resolved == null) return (false, $"No tab called '{tab.Trim()}'. Tabs: {string.Join(", ", all)}."); + SaveTab(number, resolved); + bool wasOpen = ImGuiPanelHost.IsOpen(ChatWindows.Key(number)); + if (!wasOpen) ImGuiPanelHost.Open(ChatWindows.Key(number)); + return (true, wasOpen ? $"Chat {number} now shows {resolved}." : $"Chat {number} opened on {resolved}."); + } + + public static (bool Ok, string Message) Close(int number) + { + if (!Available) return (false, NotAvailable); + string key = ChatWindows.Key(number); + if (!ImGuiPanelHost.IsOpen(key)) return (false, $"Chat {number} isn't open."); + ImGuiPanelHost.Close(key); + return (true, $"Chat {number} closed."); + } + + public static (bool Ok, string Message) CloseAll() + { + if (!Available) return (false, NotAvailable); + int closed = 0; + foreach (string key in ChatWindows.Keys()) + if (ImGuiPanelHost.IsOpen(key)) { ImGuiPanelHost.Close(key); closed++; } + return (true, closed == 0 ? "No extra chat window is open." : $"Closed {closed} chat window{(closed == 1 ? "" : "s")}."); + } + + /// One line per extra window: open or closed, its tab, docked or popped out. + public static List Describe() + { + var lines = new List(); + if (!Available) { lines.Add(NotAvailable); return lines; } + string[] all = ChatModel.AllTabs(); + int open = 0; + for (int n = ChatWindows.FirstNumber; n <= ChatWindows.LastNumber; n++) + { + string key = ChatWindows.Key(n); + if (!ImGuiPanelHost.IsOpen(key)) continue; + open++; + string saved = SavedTab(n); + string tab = ChatWindows.EffectiveTab(saved, all); + string gone = saved.Length > 0 && !string.Equals(saved, tab, StringComparison.OrdinalIgnoreCase) ? $" ({saved} is gone)" : ""; + lines.Add($"Chat {n}: {tab}{gone}, {(ImGuiPanelHost.IsPopped(key) ? "popped out" : "in the client")}."); + } + lines.Insert(0, open == 0 + ? "No extra chat window is open (the main chat's window button, or right-click a tab: Open in new window). " + ChatWindows.Usage + : $"{open} of {ChatWindows.MaxWindows} extra chat windows open:"); + return lines; + } + + /// + /// The player renamed a tab (ChatModel.RenameCustomTab): the windows that show it follow. Any thread. + /// + public static void OnTabRenamed(string from, string to) + { + for (int n = ChatWindows.FirstNumber; n <= ChatWindows.LastNumber; n++) + if (ChatWindows.FollowRename(SavedTab(n), from, to) is string next) + SaveTab(n, next); + } +} diff --git a/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs b/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs index 6a22324..491ee2f 100644 --- a/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs +++ b/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs @@ -70,7 +70,9 @@ internal static unsafe class ScriptWindowReplay /// Draws 's latest list into the current window. AC thread. public static void Draw(ScriptWindow w) { - int frame = ImGuiNative.igGetFrameCount(); + // The main context's frame number, also in a pop-out (whose context counts from 0): + // the locals' ages, the budget and the latency stay in one count when a window moves. + int frame = ImGuiPopOuts.FrameNumber; if (frame != _frame) { _frame = frame; @@ -466,6 +468,10 @@ internal static unsafe class ScriptWindowReplay } case ScriptOp.TreeNode: { + // Open state lives in the ImGui context: a window drawn in a new one (popped + // out, or back in) starts as the script recorded it, not closed. Once = only + // where this context has no state for the node; elsewhere the player's wins. + ImGuiNative.igSetNextItemOpen(op.Flag != 0 ? (byte)1 : (byte)0, ImGuiCond.Once); byte live = ImGuiNative.igTreeNodeEx_Str(str, (ImGuiTreeNodeFlags)op.Flags); ReportOpen(w, ref op, live, frame); if (live != 0 && op.Flag != 0 && open < Scopes.Length) @@ -480,6 +486,7 @@ internal static unsafe class ScriptWindowReplay } case ScriptOp.CollapsingHeader: { + ImGuiNative.igSetNextItemOpen(op.Flag != 0 ? (byte)1 : (byte)0, ImGuiCond.Once); // as TreeNode byte live = ImGuiNative.igCollapsingHeader_TreeNodeFlags(str, (ImGuiTreeNodeFlags)op.Flags); ReportOpen(w, ref op, live, frame); // Just closed by the player: the recorded contents follow; hide them until the diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 1e707e0..f0d9f60 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -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 PluginPaths @@ -714,6 +716,26 @@ internal static class EngineSettings } } + /// "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. + 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 diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 8ad0b04..bb69de1 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -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+. 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). + + /// v94: int WebPanelOpen(WebPanelOpenNative* open): opens (or replaces) the web panel. + /// Returns a handle > 0, or BadArgs / UrlNotAllowed / NoGameWindow / Unavailable / ShuttingDown + /// (WebPanelCode). Requires API v94+ (provisional number). + public IntPtr WebPanelOpenFn; + /// v94: int WebPanelNavigate(int handle, byte* url): 1 queued; -2 off the allowlist + /// (opened in the system browser when it is browser-safe); -6 stale handle. + public IntPtr WebPanelNavigateFn; + /// v94: int WebPanelClose(int handle): 1 queued, 0 already closed, -6 stale handle. + public IntPtr WebPanelCloseFn; + /// v94: int WebPanelGetState(int handle, WebPanelStateNative* state): the WebPanelStatusCode + /// (a handle that is not the live one reads 6 Superseded), -1 bad args. + public IntPtr WebPanelGetStateFn; +} + +/// v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct WebPanelOpenNative +{ + /// sizeof the caller's struct; the engine accepts Size >= OffsetOf(Reserved) (32 on x86). + public uint Size; + /// WebPanelFlags; unknown bits ignored. + public uint Flags; + /// UTF-8 NUL-terminated, at most 4096 bytes, must pass the URL policy's IsAllowed. + public byte* Url; + /// UTF-8, '\n'-separated allowlist (WebPanelUrlPolicy.TryParseAllowlist). + public byte* Allowlist; + /// UTF-8, may be null; at most 256 bytes. + public byte* ProfileKey; + /// UTF-8, may be null; at most 128 bytes. + public byte* Title; + /// 0 = 88, else 30..100 (only when no remembered layout). + public int WidthPercent; + public int HeightPercent; + public fixed uint Reserved[4]; +} + +/// v94 WebPanelGetState result (Pack 4; 48 bytes). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct WebPanelStateNative +{ + public uint Size; + public int Handle; + /// WebPanelStatusCode. + public int Status; + /// 1 Visible, 2 Focused, 4 OpenedInBrowser. + public uint Flags; + /// 0 or a negative WebPanelCode (RuntimeMissing / CreateFailed / ProcessFailed). + public int Error; + public int LastHttpStatus; + public uint NavigationCount; + public fixed uint Reserved[5]; +} + +/// v94 return codes of the web panel calls. Append only. +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, +} + +/// v94 WebPanelStateNative.Status values. Append only. +internal enum WebPanelStatusCode +{ + None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6, } /// v89 GetUiColor tokens. Append only: plugins compiled against these numbers keep them. @@ -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); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 627dcad..d13120b 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -47,5 +47,16 @@ 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. + // v95: no table change. SectionManifest.cs reads a plugin window's "barMenu" (a hover dropdown on its + // bar icon: up to 6 items of id, tooltip, icon and a /command the engine runs on click). Engines + // before v95 ignore the key (was v94 on up/bar-menu; renumbered after upstream's v93). The number + // is PROVISIONAL, as 94 is: whichever merges second renumbers. + /// The API version that added the "barMenu" manifest key; a plugin declaring it pins its own copy against this. + public const uint BarMenu = 95; + + public const uint Current = 95; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index d939a73..9bd837d 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -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(); } diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index df21097..71a4a3a 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -43,8 +43,37 @@ true false portable + + false + Dynamic + + + + + + + + + + + + + + + + + + + + + true full diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index b173fdc..a8fc7c3 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -687,6 +687,8 @@ internal static class ChatModel if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase)) preset.Tab = newName; if (string.Equals(ActiveChannel, tab, StringComparison.OrdinalIgnoreCase)) ActiveChannel = newName; + // The extra chat windows showing it follow (their tabs are saved in the panel layout). + RynthCore.Engine.ImGuiBackend.Panels.ChatWindowFace.OnTabRenamed(tab, newName); FiltersChanged(); return true; } @@ -949,9 +951,8 @@ internal static class ChatModel ChatHooks.ChatPanelShown = n > 0; if (n == 0 && Win32Backend.ChatCaptureActive) { - // Abandon a half-typed line rather than keep swallowing keys for a closed panel. + // Stop swallowing keys for a closed panel; the half-typed line stays, as after Escape. Win32Backend.ChatCaptureActive = false; - SetInput("", 0, null); } } @@ -1056,17 +1057,25 @@ internal static class ChatModel SetInput("", 0, null); }; Win32Backend.OnChatSend = OnSend; + // Escape leaves the line, as retail's chat does: the half-typed text stays in the box + // (it used to be erased), and Enter or a click on the box carries on typing it. Win32Backend.OnChatCancel = () => { _historyIndex = -1; - SetInput("", 0, null); + InputState s = _input; + SetInput(s.Text, s.Cursor, null); }; } + /// + /// Typing starts again (Enter, or a click on the box): the text left there by Escape is + /// kept, with the caret at its end. A sent line was already cleared by OnSend. + /// private static void OnActivated() { _historyIndex = -1; - SetInput("", 0, null); + string text = _input.Text; + SetInput(text, text.Length, null); } /// diff --git a/src/RynthCore.Engine/UI/Data/ChatWindows.cs b/src/RynthCore.Engine/UI/Data/ChatWindows.cs new file mode 100644 index 0000000..e09fe1c --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatWindows.cs @@ -0,0 +1,152 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatWindows.cs +// Extra chat windows (2026-11-09), the pure part: retail AC opens more chat +// windows beside the main one, each showing its own tab. The engine has a +// fixed set of them, "Chat 2" to "Chat 7" (MaxWindows), registered as panels +// like the main "Chat" (ImGui/Panels/ChatWindowFace.cs): each is opened, +// closed, placed, sized and popped out by the panel host, so which ones are +// open, where, docked or popped out lives in the panel layout (panel_state.txt, +// per character) with every other window. The tab each one shows is saved in +// that layout too (PanelStateStore value "chatwin..tab"), written only when +// the player picks a tab for that window, opens one, or renames the tab. +// +// No ImGui and no engine state here: tools/ChatWindowTests compiles this file. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Data; + +/// What "/rc chatwindow ..." asks for. +internal enum ChatWindowVerb { List, Open, Close, CloseAll, Tab, Error } + +/// A parsed "/rc chatwindow" line. Number: the window (2..); Tab: as typed. +internal readonly record struct ChatWindowCommand(ChatWindowVerb Verb, int Number = 0, string Tab = "", string Error = ""); + +internal static class ChatWindows +{ + /// How many extra chat windows there are (the main chat is window 1). + public const int MaxWindows = 6; + + /// The first extra window's number ("Chat 2"). + public const int FirstNumber = 2; + + /// The last extra window's number. + public const int LastNumber = FirstNumber + MaxWindows - 1; + + /// The tab a window shows when its own is gone (as the main chat does). + public const string FallbackTab = "All"; + + public const string Usage = + "Usage: /rc chatwindow [list] | open [tab] | close <2-7|all> | tab <2-7> "; + + /// The panel key of window : "Chat 2". + public static string Key(int number) => "Chat " + number.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// Every extra window's key, in order. + public static IEnumerable Keys() + { + for (int n = FirstNumber; n <= LastNumber; n++) yield return Key(n); + } + + /// The window number in a key ("Chat 3" is 3); false for any other key. + public static bool TryNumber(string? key, out int number) + { + number = 0; + if (key == null || !key.StartsWith("Chat ", StringComparison.OrdinalIgnoreCase)) return false; + return int.TryParse(key.AsSpan(5), System.Globalization.NumberStyles.None, + System.Globalization.CultureInfo.InvariantCulture, out number) + && number >= FirstNumber && number <= LastNumber; + } + + /// The layout value that holds window 's tab. + public static string TabValueKey(int number) => + "chatwin." + number.ToString(System.Globalization.CultureInfo.InvariantCulture) + ".tab"; + + /// The first window that isn't open, or 0 when all are. + public static int FirstFree(Func isOpen) + { + for (int n = FirstNumber; n <= LastNumber; n++) + if (!isOpen(Key(n))) return n; + return 0; + } + + /// + /// The tab a window shows: its saved one, spelled as the tab is now, or All when it was + /// deleted (or nothing is saved). The saved value is left alone: a tab that comes back + /// (another client's settings, an undo) shows again. + /// + public static string EffectiveTab(string? saved, IReadOnlyList allTabs) => + Resolve(saved, allTabs) ?? FallbackTab; + + /// The tab called (any case), as it is spelled; null when there is none. + public static string? Resolve(string? typed, IReadOnlyList allTabs) + { + string t = (typed ?? "").Trim(); + if (t.Length == 0) return null; + foreach (string tab in allTabs) + if (string.Equals(tab, t, StringComparison.OrdinalIgnoreCase)) return tab; + return null; + } + + /// A window's saved tab after the player renamed : the new name, or null for no change. + public static string? FollowRename(string? saved, string from, string to) => + saved != null && to.Trim().Length > 0 && string.Equals(saved.Trim(), from.Trim(), StringComparison.OrdinalIgnoreCase) + ? to.Trim() : null; + + /// The header text of a window showing . + public static string HeaderText(int number, string tab) => + "Chat " + number.ToString(System.Globalization.CultureInfo.InvariantCulture) + " · " + tab; + + /// + /// "/rc chatwindow" arguments: "" or list; open [tab]; close <n|all>; tab <n> <tab>. + /// A tab name may have spaces. The number may be written "2" or "chat 2". + /// + public static ChatWindowCommand Parse(string? args) + { + string a = (args ?? "").Trim(); + if (a.Length == 0 || a.Equals("list", StringComparison.OrdinalIgnoreCase) || a.Equals("status", StringComparison.OrdinalIgnoreCase)) + return new ChatWindowCommand(ChatWindowVerb.List); + int sp = a.IndexOf(' '); + string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant(); + string rest = sp < 0 ? "" : a[(sp + 1)..].Trim(); + switch (verb) + { + case "open": + case "new": + return new ChatWindowCommand(ChatWindowVerb.Open, Tab: rest); + case "close": + if (rest.Equals("all", StringComparison.OrdinalIgnoreCase)) return new ChatWindowCommand(ChatWindowVerb.CloseAll); + if (TryWindowNumber(rest, out int n, out string after) && after.Length == 0) + return new ChatWindowCommand(ChatWindowVerb.Close, n); + return Bad(rest.Length == 0 ? "Which window? " : $"No chat window '{rest}'. "); + case "tab": + if (!TryWindowNumber(rest, out int w, out string tab)) + return Bad(rest.Length == 0 ? "Which window? " : $"No chat window '{rest}'. "); + if (tab.Length == 0) return Bad("Which tab? "); + return new ChatWindowCommand(ChatWindowVerb.Tab, w, tab); + default: + return Bad($"Unknown '{verb}'. "); + } + } + + private static ChatWindowCommand Bad(string why) => + new(ChatWindowVerb.Error, Error: why + Usage); + + /// "3 Combat" or "chat 3 Combat": the window number, and what follows it. + private static bool TryWindowNumber(string s, out int number, out string rest) + { + number = 0; + rest = ""; + s = s.Trim(); + if (s.StartsWith("chat ", StringComparison.OrdinalIgnoreCase)) s = s[5..].TrimStart(); + int sp = s.IndexOf(' '); + string word = sp < 0 ? s : s[..sp]; + if (!int.TryParse(word, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out number) + || number < FirstNumber || number > LastNumber) + return false; + rest = sp < 0 ? "" : s[(sp + 1)..].Trim(); + return true; + } +} diff --git a/src/RynthCore.Engine/UI/PanelStateStore.cs b/src/RynthCore.Engine/UI/PanelStateStore.cs index dc2f5ef..ec615f5 100644 --- a/src/RynthCore.Engine/UI/PanelStateStore.cs +++ b/src/RynthCore.Engine/UI/PanelStateStore.cs @@ -10,6 +10,9 @@ // barlayout=, (BarLayout; only when not 1,0) // panel.=<open|closed>,<left>,<top>,<width>,<height> // [,<docked|floating>,<screenLeft>,<screenTop>] +// value.<key>=<text> (SetValue: a window's own choice +// that belongs to the layout, e.g. +// an extra chat window's tab) // // The trailing three columns on each row were added when panels (and later // the bar itself) gained the ability to detach into their own top-level @@ -52,6 +55,8 @@ internal static class PanelStateStore private static readonly object Sync = new(); private static readonly Dictionary<string, PanelEntry> Panels = new(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary<string, string> Values = new(StringComparer.OrdinalIgnoreCase); + private static int _generation; private static (double Left, double Top)? _barPosition; private static bool _barFloating; private static (double Left, double Top)? _barFloatingPosition; @@ -107,6 +112,8 @@ internal static class PanelStateStore { if (flushCurrent && _loaded) Save(); Panels.Clear(); + Values.Clear(); + System.Threading.Interlocked.Increment(ref _generation); _barPosition = null; _barFloating = false; _barFloatingPosition = null; @@ -229,6 +236,50 @@ internal static class PanelStateStore } } + /// <summary> + /// Goes up each time the store switches to another file (<see cref="SwitchTo"/>): a window that + /// read a <see cref="TryGetValue"/> value reads it again when this changes. Any thread. + /// </summary> + public static int Generation => System.Threading.Volatile.Read(ref _generation); + + /// <summary>A value saved with <see cref="SetValue"/> in the layout in use. Any thread.</summary> + public static bool TryGetValue(string key, out string value) + { + lock (Sync) + { + Load(); + if (Values.TryGetValue(key, out string? v)) { value = v; return true; } + value = string.Empty; + return false; + } + } + + /// <summary> + /// Saves a one-line value in the layout in use (null or empty removes it): a window's own + /// choice that belongs with its place, such as which tab an extra chat window shows. Only + /// what the player does may call this. Line breaks are dropped. Any thread. + /// </summary> + public static void SetValue(string key, string? value) + { + key = key.Replace('\r', ' ').Replace('\n', ' ').Replace('=', ' ').Trim(); + if (key.Length == 0) return; + value = value?.Replace('\r', ' ').Replace('\n', ' ').Trim(); + lock (Sync) + { + Load(); + if (string.IsNullOrEmpty(value)) + { + if (!Values.Remove(key)) return; + } + else + { + if (Values.TryGetValue(key, out string? had) && string.Equals(had, value, StringComparison.Ordinal)) return; + Values[key] = value; + } + Save(); + } + } + public static void MarkPanelClosed(string title) { lock (Sync) @@ -298,6 +349,11 @@ internal static class PanelStateStore // An unreadable row leaves the defaults (TryParse sets them). BarLayout.TryParse(value, out _barRows, out _barMaxPerRow); } + else if (key.StartsWith("value.", StringComparison.OrdinalIgnoreCase)) + { + string name = key["value.".Length..].Trim(); + if (name.Length > 0 && value.Length > 0) Values[name] = value; + } else if (key.StartsWith("panel.", StringComparison.OrdinalIgnoreCase)) { string title = key["panel.".Length..]; @@ -398,6 +454,9 @@ internal static class PanelStateStore sw.AppendLine(FormattableString.Invariant( $"panel.{kv.Key}={(e.Open ? "open" : "closed")},{e.Left:0.##},{e.Top:0.##},{e.Width:0.##},{e.Height:0.##},{(e.Floating ? "floating" : "docked")},{e.FloatingLeft:0.##},{e.FloatingTop:0.##}")); } + // Only rows that were set: a file without values reads back the same. + foreach (var kv in Values) + sw.AppendLine("value." + kv.Key + "=" + kv.Value); return sw.ToString(); } diff --git a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs index e33b07c..d2fba8a 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs @@ -570,7 +570,8 @@ internal static class ScriptWindowRegistry UiInfoNative full = default; full.Size = (uint)sizeof(UiInfoNative); bool imgui = EngineSettings.EnableImGuiBackend; - full.Flags = (imgui ? 1u : 0u) | (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete ? 2u : 0u); + full.Flags = (imgui ? 1u : 0u) | (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete ? 2u : 0u) + | (PanelRouter.CanPopOut ? 4u : 0u); full.MaxFormatVersion = DisplayListParser.FormatVersion; full.OpLevel = DisplayListParser.OpLevel; full.MaxOpsPerWindow = MaxOpsPerWindow; @@ -691,7 +692,14 @@ internal static class ScriptWindowRegistry /// <summary>The flag bits that shape the panel spec (a change re-registers the entry).</summary> private const uint SpecFlags = WindowFlags.ChromeNone | WindowFlags.NoBackground - | WindowFlags.NoScrollbar | WindowFlags.NoScrollWithMouse; + | WindowFlags.NoScrollbar | WindowFlags.NoScrollWithMouse | WindowFlags.NoPopOut; + + /// <summary> + /// Whether a window with these flags may pop out (↗, Phase 2): a framed window unless the hud + /// set NoPopOut. A bare window (ChromeNone) has no header for the ↗ and is drawn over the game + /// (an overlay, usually click-through), which an OS window of its own can't be: it stays docked. + /// </summary> + public static bool CanPopOut(uint flags) => (flags & (WindowFlags.ChromeNone | WindowFlags.NoPopOut)) == 0; private static void Apply(ScriptWindow w, ParsedWindow pw, uint ackSeq, bool isNew) { @@ -714,7 +722,13 @@ internal static class ScriptWindowRegistry // DrawPanel reads the entry's spec every frame, so a new spec applies at once. if (specChanged) + { ImGuiPanelHost.RegisterDynamic(w.PanelKey, w.Title, SpecFor(w), () => new ScriptWindowFace(w)); + // Popped out and no longer allowed to be (NoPopOut set, or the hud went bare): it + // comes back into the client, where it was docked. Saved as docked, so it stays there. + if (!isNew && !CanPopOut(w.Flags) && ImGuiPanelHost.IsPopped(w.PanelKey)) + ImGuiPanelHost.Redock(w.PanelKey); + } else if (titleChanged) ImGuiPanelHost.SetDisplayTitle(w.PanelKey, w.Title); @@ -870,11 +884,12 @@ internal static class ScriptWindowRegistry ImGuiNET.ImGuiWindowFlags body = ImGuiNET.ImGuiWindowFlags.None; if ((f & WindowFlags.NoScrollbar) != 0) body |= ImGuiNET.ImGuiWindowFlags.NoScrollbar; if ((f & WindowFlags.NoScrollWithMouse) != 0) body |= ImGuiNET.ImGuiWindowFlags.NoScrollWithMouse; - // ClickThrough stays on the face (IImGuiPanel.ClickThrough), read every frame. - // Pop-outs aren't in the MVP (decision 8): no ↗. + // ClickThrough stays on the face (IImGuiPanel.ClickThrough), read every frame; popped + // out, the host makes the window interactive like any panel. + // Pop-outs (Phase 2, decision 8): the ↗ like any panel, unless CanPopOut says no. return new PanelSpec(size, min, none ? PanelChrome.None : PanelChrome.Standard, Background: (f & WindowFlags.NoBackground) != 0 ? 0u : null, - NoPopOut: true, + NoPopOut: !CanPopOut(f), BodyFlags: body, DefaultPos: w.DefaultPos); } @@ -974,6 +989,9 @@ internal static unsafe class ScriptWindowMetrics { long now = Stopwatch.GetTimestamp(); if (_current != null && now - _takenAt < Stopwatch.Frequency) return; + // A popped-out window's context has the monitor's work area for its display, not AC's + // window: the snapshot is taken from a docked one (the font metrics are the same). + if (_current != null && ImGuiPopOuts.InPopOutFrame) return; _takenAt = now; var io = ImGuiNET.ImGui.GetIO(); var style = ImGuiNET.ImGui.GetStyle(); @@ -988,7 +1006,7 @@ internal static unsafe class ScriptWindowMetrics SpacingY = style.ItemSpacing.Y, PadX = style.FramePadding.X, PadY = style.FramePadding.Y, - Frame = (uint)ImGuiNET.ImGui.GetFrameCount(), + Frame = (uint)ImGuiPopOuts.FrameNumber, // the main frame number, also when popped out }; byte* one = stackalloc byte[2]; for (int i = 0; i < 95; i++) diff --git a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs index 651c82c..c18fb90 100644 --- a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs +++ b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs @@ -104,7 +104,17 @@ internal static class PluginWindows foreach ((string title, SectionWindowDecl w) in want) { string sig = WindowPlan.Signature(w); - if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue; + if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) + { + // Same panel, but the bar's dropdown may differ (a plugin reload with a new "barMenu"): + // refresh the declaration without re-registering the panel, and let the bar rebuild. + if (WindowPlan.MenuSignature(h.Decl) != WindowPlan.MenuSignature(w)) + { + Live[title] = h with { Decl = w }; + changed = true; + } + continue; + } SectionWindowDecl decl = w; Func<IImGuiPanel> face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title, decl.FitHeight, decl.MinWidth, decl.DrawScale); if (takeOvers.Contains(title)) diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs index 20b8c27..08f5de2 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -51,6 +51,16 @@ // opens when nothing is saved for it (v90, 2026-10-22). "scale": "draw" = // the window draws its content at any size (PanelScale): Ctrl+wheel over // it steps that size, 30-250%, not its text size (v90, 2026-10-23). +// "barMenu" (v95, 2026-11-07): a hover dropdown on the window's bar icon, for a +// window with "bar": true. An array of { "id": "market", "tooltip": "Market", +// "icon": "<Phosphor glyph, may be empty>", "command": "/rserver market" }: +// "id" a short lower-case word (unique in the menu), "tooltip" the item's +// label (capped like any label), "icon" as the window's icon (one glyph or +// ""), "command" a single "/..." chat command the engine runs as a player +// chat command when the item is clicked. An item missing its id, tooltip or +// command, or with a duplicate id, is dropped; at most MaxBarMenuItems (6) +// are kept, and a "barMenu" that is not an array is ignored (the window is +// kept). Engines before v95 ignore the key. // // Everything from a plugin is checked here: ids are short lower-case words, // text is capped, a command must be a single "/..." chat command, and the lists @@ -92,6 +102,9 @@ internal sealed record SectionContribution( public bool IsUniversal => Server.Length == 0; } +/// <summary>One entry of a window's bar-icon dropdown ("barMenu", v95): a click runs <see cref="Command"/> as a player chat command.</summary> +internal sealed record SectionBarMenuItem(string Id, string Tooltip, string Icon, string Command); + /// <summary> /// A window a plugin draws, hosted by the engine (docs/PLUGIN_WINDOWS.md): its panel key and header /// are <see cref="Title"/>, its body the plugin's <see cref="Surface"/> through RynthPluginRenderEmbed. @@ -121,10 +134,15 @@ internal sealed record SectionWindowDecl( bool DrawScale = false, // 2026-11-07 (no version bump: older engines ignore the key): drawn under AC's own UI, like a native // AC window ("layer": "underUi"; frameless windows only). AC's windows cover it and take the clicks there. - bool UnderUi = false) + bool UnderUi = false, + // v95: the bar icon's hover dropdown ("barMenu"); null when the window declares none. + SectionBarMenuItem[]? BarMenu = null) { /// <summary>For every world, not one server.</summary> public bool IsUniversal => Server.Length == 0; + + /// <summary>The bar icon's dropdown items (empty when none).</summary> + public SectionBarMenuItem[] Menu => BarMenu ?? System.Array.Empty<SectionBarMenuItem>(); } /// <summary>One plugin's parsed manifest.</summary> @@ -158,6 +176,8 @@ internal static class SectionManifestParser public const int MaxJsonLength = 256 * 1024; public const int MaxWindows = 8; public const int MaxWindowTitleLength = 32; + /// <summary>Most items kept in one window's bar-icon dropdown (v95).</summary> + public const int MaxBarMenuItems = 6; public const float DefaultWindowWidth = 420f, DefaultWindowHeight = 300f, MinWindowSize = 120f, MaxWindowSize = 2000f; /// <summary> @@ -237,6 +257,16 @@ internal static class SectionManifestParser float height = WindowSize(Size(e, "height"), DefaultWindowHeight); float minWidth = Math.Min(WindowSize(Size(e, "minWidth"), MinWindowSize), width); float minHeight = Math.Min(WindowSize(Size(e, "minHeight"), MinWindowSize), height); + var barMenu = new List<SectionBarMenuItem>(); + foreach (JsonElement item in Array(e, "barMenu")) + { + if (barMenu.Count >= MaxBarMenuItems) break; + string itemId = Id(Str(item, "id")); + string tooltip = Text(Str(item, "tooltip"), MaxLabelLength); + string itemCommand = Command(Str(item, "command")); + if (itemId.Length == 0 || tooltip.Length == 0 || itemCommand.Length == 0 || barMenu.Exists(b => b.Id == itemId)) continue; + barMenu.Add(new SectionBarMenuItem(itemId, tooltip, Icon(Str(item, "icon")), itemCommand)); + } windows.Add(new SectionWindowDecl(plugin, id, title, surface, Icon(Str(e, "icon")), width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server, Bool(e, "takeOver", false), @@ -244,7 +274,8 @@ internal static class SectionManifestParser FitHeight: Bool(e, "fitHeight", false), Corner: Str(e, "corner").Trim() is "topLeft" or "topRight" or "bottomLeft" or "bottomRight" or "top" or "bottom" ? Str(e, "corner").Trim() : "", DrawScale: Str(e, "scale").Trim().Equals("draw", StringComparison.OrdinalIgnoreCase), - UnderUi: Str(e, "layer").Trim().Equals("underUi", StringComparison.OrdinalIgnoreCase))); + UnderUi: Str(e, "layer").Trim().Equals("underUi", StringComparison.OrdinalIgnoreCase), + BarMenu: barMenu.Count > 0 ? barMenu.ToArray() : null)); } return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray()) diff --git a/src/RynthCore.Engine/UI/Sections/WindowPlan.cs b/src/RynthCore.Engine/UI/Sections/WindowPlan.cs index e11fb52..8eacec3 100644 --- a/src/RynthCore.Engine/UI/Sections/WindowPlan.cs +++ b/src/RynthCore.Engine/UI/Sections/WindowPlan.cs @@ -67,4 +67,11 @@ internal static class WindowPlan public static string Signature(SectionWindowDecl w) => string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge, w.TakeOver, w.Frameless, w.FitHeight); + + /// <summary> + /// What the bar's dropdown shows for a window (its "barMenu"): kept apart from <see cref="Signature"/> because + /// a menu change must reach the bar without re-registering the panel (that would reset the window's state). + /// </summary> + public static string MenuSignature(SectionWindowDecl w) => + string.Join("\n", System.Linq.Enumerable.Select(w.Menu, i => string.Join("\t", i.Id, i.Tooltip, i.Icon, i.Command))); } diff --git a/src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs b/src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs new file mode 100644 index 0000000..49b42ac --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs @@ -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 ""; + } +} diff --git a/src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs b/src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs new file mode 100644 index 0000000..e939b33 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs @@ -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; } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs new file mode 100644 index 0000000..d9cae83 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs @@ -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 diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs new file mode 100644 index 0000000..db98fca --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs @@ -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; + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelBrowserGate.cs b/src/RynthCore.Engine/WebPanel/WebPanelBrowserGate.cs new file mode 100644 index 0000000..32b1899 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelBrowserGate.cs @@ -0,0 +1,50 @@ +// WebPanelBrowserGate.cs - when an off-allowlist page may go to the system browser (2026-11-09, Tom OK'd +// the port review's finding: a page, or an ad iframe in it, could open browser tabs on its own). Pure: no +// Win32, no WebView2; WebPanelHost asks it before ShellExecute. +using System; + +namespace RynthCore.Engine.WebPanel; + +internal enum BrowserOpenVerdict +{ + /// <summary>Open it in the system browser.</summary> + Open, + /// <summary>The page asked without a click (script, redirect, timer): dropped.</summary> + NotUserInitiated, + /// <summary>Too soon after the last one, or too many this minute: dropped.</summary> + TooSoon, +} + +/// <summary> +/// One gate per panel thread. A page's own request needs the user's click behind it (WebView2's +/// IsUserInitiated); a plugin's Navigate to an off-list URL counts as asked for (a button or a command). +/// Either way at most one open per <see cref="MinGapMs"/> and <see cref="MaxPerMinute"/> a minute. +/// </summary> +internal sealed class WebPanelBrowserGate +{ + public const long MinGapMs = 2000; + public const int MaxPerMinute = 5; + + private readonly long[] _recent = new long[MaxPerMinute]; + private int _count; + private int _next; + private long _last = long.MinValue; + + /// <param name="userInitiated">The page's request came from a click (or a plugin asked).</param> + /// <param name="nowMs">Environment.TickCount64.</param> + public BrowserOpenVerdict Decide(bool userInitiated, long nowMs) + { + if (!userInitiated) return BrowserOpenVerdict.NotUserInitiated; + if (_last != long.MinValue && nowMs - _last < MinGapMs) return BrowserOpenVerdict.TooSoon; + int inLastMinute = 0; + for (int i = 0; i < _count; i++) + if (nowMs - _recent[i] < 60_000) inLastMinute++; + if (inLastMinute >= MaxPerMinute) return BrowserOpenVerdict.TooSoon; + + _recent[_next] = nowMs; + _next = (_next + 1) % MaxPerMinute; + if (_count < MaxPerMinute) _count++; + _last = nowMs; + return BrowserOpenVerdict.Open; + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs new file mode 100644 index 0000000..9f872b3 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -0,0 +1,1131 @@ +// ============================================================================ +// RynthCore.Engine - WebPanel/WebPanelHost.cs (CoreCLR engine only) +// +// One WebView2 panel over the game's client area, on a dedicated STA thread with its own +// GetMessage loop and an UNOWNED WS_POPUP host window (an owned popup would attach the game's +// input queue). Lifted from the 2026-11-07 spike (spikes\webview2\RynthWebSpike\WebPanel.cs, +// popup-free path), which ran it inside a live acclient. +// +// Threads: Open/Navigate/Close/GetState run on any thread (AC's main thread, the plugin pump, +// ImGui draws) and never block: they validate, update the caller-visible state under _sync, +// queue work and post WM_RUN to the host window. Everything that touches Win32 windows or +// WebView2 runs on the panel thread. Shutdown posts the teardown and joins within a budget. +// +// Lifetime: everything started or registered here (thread, window class, WinEvent hook, timer, +// WebView2 controller/environment) is torn down by Shutdown, before the collectible engine +// context unloads. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Web.WebView2.Core; +using RynthCore.Engine.Plugins; +using static RynthCore.Engine.WebPanel.WebPanelNative; + +namespace RynthCore.Engine.WebPanel; + +internal sealed unsafe class WebPanelHost +{ + private const uint WM_RUN = WM_APP + 1; + private const int CaptionPx = 28, CloseBoxPx = 34; + private const uint FlagFallback = 1, FlagPageKeepsEscape = 2; + private const uint StateVisible = 1, StateFocused = 2, StateOpenedInBrowser = 4; + private const uint VK_ESCAPE = 0x1B; + private static readonly IntPtr TimerId = (IntPtr)1; + private static readonly uint Background = Rgb(32, 32, 36), CaptionColor = Rgb(44, 44, 50), TextColor = Rgb(222, 222, 228); + + // The WndProc and WinEvent target. One live host per engine generation (WebPanelApi holds it). + private static WebPanelHost? s_active; + private static int s_classSeq; + + private readonly IWebPanelEnvironment _env; + private readonly uint _ourPid = GetCurrentProcessId(); + + // ---- caller-visible state: under _sync ---- + private readonly object _sync = new(); + private readonly ConcurrentQueue<Action> _queue = new(); + private int _nextHandle; + private int _live; + private int _status; + private uint _flags; + private int _error, _http; + private uint _navCount; + private string _liveUrl = ""; + private bool _shuttingDown; + private Thread? _thread; + private bool _threadDone; + private IntPtr _hwnd; // published once the window exists; WM_RUN goes here + + // ---- panel thread only ---- + private IntPtr _staHwnd, _hook, _bgBrush, _captionBrush; + private string _className = ""; + private bool _windowFailed, _tornDown, _timerOn, _inSizeMove; + private volatile bool _open; + private int _serving; // the handle whose request the panel shows + private WebPanelRequest? _req; + private string _title = "RynthCore"; + private PanelFractions _fractions = WebPanelWindowPolicy.Default(0, 0); + private string _pendingUrl = ""; + private bool _loaderLoaded; + private CoreWebView2Environment? _wvEnv; + private CoreWebView2Controller? _ctl; + private CoreWebView2? _web; + private string? _profileFolder; + private bool _creating, _needsRecreate; + private int _createSeq; + // Off-list pages to the system browser: only after a click, and rate-limited (panel thread only). + private readonly WebPanelBrowserGate _browserGate = new(); + + // ---- diagnostics (Describe and the offline harness) ---- + private volatile int _environmentCount, _acceleratorEvents; + private volatile uint _browserPid; + private volatile string _source = ""; + + public WebPanelHost(IWebPanelEnvironment env) => _env = env; + + // ============================ any thread ============================ + + public int Open(WebPanelRequest request) + { + if (request == null) return (int)WebPanelCode.BadArgs; + lock (_sync) if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (!WebPanelUrlPolicy.IsAllowed(request.Url, request.Allowlist)) return (int)WebPanelCode.UrlNotAllowed; + IntPtr game = _env.GameHwnd; + if (game == IntPtr.Zero || !IsWindow(game)) return (int)WebPanelCode.NoGameWindow; + + lock (_sync) + { + if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (_nextHandle <= 0) _nextHandle = (Environment.TickCount & 0x3FFFFFFF) | 1; + int handle = _nextHandle++; + // Kept to undo below if the thread cannot start: the caller then sees a failure, and the state must agree. + int prevLive = _live, prevStatus = _status, prevError = _error, prevHttp = _http; + uint prevFlags = _flags, prevNav = _navCount; + string prevUrl = _liveUrl; + string[] prevAllow = _currentAllowlist; + _live = handle; + _status = (int)WebPanelStatusCode.Starting; + _flags = 0; + _error = 0; + _http = 0; + _navCount = 0; + _liveUrl = request.Url; + _currentAllowlist = request.Allowlist; + _queue.Enqueue(() => ProcessOpen(handle, request)); + if (_thread == null || _threadDone) + { + // First call (or the thread died): start it and return at once. The thread creates its + // window first, then drains the queue. + try + { + StartThreadLocked(); + } + catch + { + // The queued ProcessOpen stays behind but is skipped: its handle is no longer live. + _live = prevLive; _status = prevStatus; _flags = prevFlags; _error = prevError; + _http = prevHttp; _navCount = prevNav; _liveUrl = prevUrl; _currentAllowlist = prevAllow; + _threadDone = true; + throw; // WebPanelApi reports Unavailable + } + } + else if (_hwnd != IntPtr.Zero) + { + PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero); + } + return handle; + } + } + + public int Navigate(int handle, string url) + { + lock (_sync) + { + if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (handle <= 0 || handle != _live) return (int)WebPanelCode.StaleHandle; + if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return (int)WebPanelCode.StaleHandle; + } + if (string.IsNullOrEmpty(url)) return (int)WebPanelCode.BadArgs; + string[] allow; + lock (_sync) allow = _currentAllowlist; + if (!WebPanelUrlPolicy.IsAllowed(url, allow)) + { + // Off the list: the system browser when that is safe (on the panel thread: ShellExecute can be slow). + Post(() => RouteOffList(url, userInitiated: true)); // a plugin asked: a button or a command + return (int)WebPanelCode.UrlNotAllowed; + } + return Post(() => NavigateNow(handle, url)) ? (int)WebPanelCode.Queued : (int)WebPanelCode.ShuttingDown; + } + + public int Close(int handle) + { + lock (_sync) + { + if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (handle <= 0 || handle != _live) return (int)WebPanelCode.StaleHandle; + if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return (int)WebPanelCode.AlreadyClosed; + } + return Post(() => CloseNow(handle)) ? (int)WebPanelCode.Queued : (int)WebPanelCode.ShuttingDown; + } + + public int GetState(int handle, out WebPanelSnapshot s) + { + lock (_sync) + { + if (_shuttingDown) + { + s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.None, 0, (int)WebPanelCode.ShuttingDown, 0, 0); + return (int)WebPanelCode.ShuttingDown; + } + if (handle <= 0 || handle != _live) + { + s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0); + return (int)WebPanelStatusCode.Superseded; + } + s = new WebPanelSnapshot(_live, _status, _flags, _error, _http, _navCount); + return _status; + } + } + + /// <summary>Idempotent. Posts the teardown (which ends with WM_QUIT) and joins the thread within the budget.</summary> + public void Shutdown(int budgetMs) + { + Thread? t; + lock (_sync) + { + t = _thread; + if (!_shuttingDown) + { + _shuttingDown = true; + if (t != null && !_threadDone) + { + _queue.Enqueue(TeardownOnPanelThread); + if (_hwnd != IntPtr.Zero) PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero); + } + } + } + if (t == null || t == Thread.CurrentThread) return; + if (!t.Join(Math.Max(0, budgetMs))) + SafeLog($"shutdown: the panel thread did not finish within {budgetMs} ms"); + } + + /// <summary>The live handle (0 before the first Open), for engine-side callers such as a close-on-command.</summary> + public int LiveHandle { get { lock (_sync) return _live; } } + + public string Describe() + { + lock (_sync) + { + string thread = _thread == null ? "not started" : _threadDone ? "stopped" : "running"; + string status = ((WebPanelStatusCode)_status).ToString(); + return $"web panel: thread {thread}{(_shuttingDown ? " (shut down)" : "")}, handle {_live}, {status}, error {_error}, " + + $"http {_http}, navigations {_navCount}, environments {_environmentCount}, visible {((_flags & StateVisible) != 0 ? "yes" : "no")}, focused {((_flags & StateFocused) != 0 ? "yes" : "no")}, in browser {((_flags & StateOpenedInBrowser) != 0 ? "yes" : "no")}, browser pid {_browserPid}, url {WebPanelUrlPolicy.Redact(_liveUrl)}"; + } + } + + /// <summary>Under _sync. _threadDone goes false only once the thread exists, so a failed start leaves it true.</summary> + private void StartThreadLocked() + { + _hwnd = IntPtr.Zero; + _thread = _env.StartStaThread("RynthCore.WebPanel", ThreadMain); + _threadDone = false; + } + + // The live request's allowlist, for Navigate's caller-side check (set on Open, under _sync). + private string[] _currentAllowlist = Array.Empty<string>(); + + private bool Post(Action a) + { + lock (_sync) + { + if (_thread == null || _threadDone) return false; + _queue.Enqueue(a); + if (_hwnd != IntPtr.Zero) PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero); + return true; + } + } + + /// <summary>Applies <paramref name="apply"/> to the caller-visible state only while <paramref name="handle"/> is the live one.</summary> + private void SetState(int handle, Action apply) + { + lock (_sync) if (handle == _live) apply(); + } + + private void SafeLog(string line) { try { _env.Log(line); } catch { } } + private void SafeChat(string line) { try { _env.Chat(line); } catch { } } + + // ---- test and diagnostic views (no secrets: Source is never logged) ---- + internal IntPtr HostHwndForTests { get { lock (_sync) return _hwnd; } } + internal int EnvironmentCountForTests => _environmentCount; + internal uint BrowserProcessIdForTests => _browserPid; + internal int AcceleratorKeyEventsForTests => _acceleratorEvents; + internal string SourceForTests => _source; + internal bool ThreadRunningForTests { get { lock (_sync) return _thread != null && !_threadDone && _thread.IsAlive; } } + internal bool PostForTests(Action<CoreWebView2?> a) => Post(() => a(_web)); + internal bool PanelOpenForTests => _open; + /// <summary>A renderer-unresponsive report, as WebView2 would raise it (counting against UnresponsiveLimit).</summary> + internal bool UnresponsiveForTests() => Post(() => HandleProcessFailed(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)); + /// <summary>A failure arriving late for <paramref name="handle"/> (the harness passes a superseded one).</summary> + internal bool FailForTests(int handle) => Post(() => Fail(handle, WebPanelCode.ProcessFailed, "synthetic (harness)", allowFallback: false)); + + // ============================ panel thread ============================ + + private void ThreadMain() + { + // A thread restarted after a failed one (no window) starts clean. + _tornDown = false; + _windowFailed = false; + try + { + try { CreateHostWindow(); } + catch (Exception ex) + { + _windowFailed = true; + SafeLog("could not create the panel window: " + ex.GetType().Name + " " + ex.Message); + } + lock (_sync) _hwnd = _staHwnd; + Drain(); + if (_staHwnd != IntPtr.Zero) + { + while (GetMessageW(out MSG msg, IntPtr.Zero, 0, 0) > 0) + { + TranslateMessage(ref msg); + DispatchMessageW(ref msg); + } + } + else + { + TeardownOnPanelThread(); + } + } + catch (Exception ex) + { + SafeLog("panel thread failed: " + ex.GetType().Name + " " + ex.Message); + } + finally + { + // However the loop ended (WM_QUIT from the teardown, a GetMessage error, an exception), nothing + // this thread registered (window class, WinEvent hook, WebView2) may outlive it: the class's WndProc + // points into the collectible engine context. + if (!_tornDown) { try { TeardownOnPanelThread(); } catch { } } + lock (_sync) + { + _threadDone = true; + _hwnd = IntPtr.Zero; + // An Open queued after this thread's last drain (e.g. while a failed window creation was being + // torn down) would otherwise wait for the next Open: start a fresh thread for it now. The new + // thread cannot finish (its finally takes this lock) before _threadDone is set back. + if (!_shuttingDown && !_queue.IsEmpty) + { + try { StartThreadLocked(); } + catch (Exception ex) { SafeLog("could not restart the panel thread: " + ex.GetType().Name); } + } + } + } + } + + private void CreateHostWindow() + { + _className = $"RynthCoreWebPanel_{Environment.TickCount64:X}_{Interlocked.Increment(ref s_classSeq):X}"; + _bgBrush = CreateSolidBrush(Background); + _captionBrush = CreateSolidBrush(CaptionColor); + IntPtr inst = GetModuleHandleW(IntPtr.Zero); + fixed (char* pName = _className) + { + var wc = new WNDCLASSEXW + { + cbSize = (uint)sizeof(WNDCLASSEXW), + style = CS_HREDRAW | CS_VREDRAW, + lpfnWndProc = (IntPtr)(delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, IntPtr, IntPtr>)&WndProc, + hInstance = inst, + hCursor = LoadCursorW(IntPtr.Zero, (IntPtr)IDC_ARROW), + hbrBackground = _bgBrush, + lpszClassName = (IntPtr)pName, + }; + if (RegisterClassExW(ref wc) == 0) + { + int err = Marshal.GetLastWin32Error(); + _className = ""; + throw new InvalidOperationException("RegisterClassExW failed " + err); + } + } + s_active = this; + IntPtr h = CreateWindowExW(WS_EX_TOOLWINDOW, _className, "RynthCore", WS_POPUP | WS_CLIPCHILDREN | WS_THICKFRAME, + 0, 0, 640, 480, IntPtr.Zero, IntPtr.Zero, inst, IntPtr.Zero); + if (h == IntPtr.Zero) throw new InvalidOperationException("CreateWindowExW failed " + Marshal.GetLastWin32Error()); + _staHwnd = h; + _hook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, &WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l) + { + WebPanelHost? p = s_active; + if (p != null) + { + try + { + if (p.HandleMessage(h, m, w, l, out IntPtr r)) return r; + } + catch (Exception ex) + { + p.SafeLog("WndProc threw " + ex.GetType().Name + " " + ex.Message); + } + } + return DefWindowProcW(h, m, w, l); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int idObject, int idChild, uint thread, uint time) + { + WebPanelHost? p = s_active; + if (p == null || hook != p._hook) return; + try { p.Track(); } + catch (Exception ex) { p.SafeLog("foreground tracking threw " + ex.GetType().Name + " " + ex.Message); } + } + + private bool HandleMessage(IntPtr h, uint m, IntPtr w, IntPtr l, out IntPtr result) + { + result = IntPtr.Zero; + if (_staHwnd == IntPtr.Zero || h != _staHwnd) return false; // during CreateWindowExW: default handling + switch (m) + { + case WM_RUN: + Drain(); + return true; + case WM_TIMER: + if (w != TimerId) return false; + Track(); + return true; + case WM_SIZE: + ResizeController(); + return false; + case WM_SETFOCUS: + try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { } + return false; + case WM_CLOSE: // Alt+F4 on the panel: close it, keep the window + CloseNow(_serving); + return true; + case WM_NCHITTEST: + { + result = DefWindowProcW(h, m, w, l); + if (result == (IntPtr)HTCLIENT) + { + var pt = new POINT { X = (short)((long)l & 0xFFFF), Y = (short)(((long)l >> 16) & 0xFFFF) }; + ScreenToClient(h, ref pt); + if (pt.Y >= 0 && pt.Y < CaptionPx && !InCloseBox(pt)) result = (IntPtr)HTCAPTION; + } + return true; + } + case WM_LBUTTONDOWN: + { + var pt = new POINT { X = (short)((long)l & 0xFFFF), Y = (short)(((long)l >> 16) & 0xFFFF) }; + if (InCloseBox(pt)) CloseNow(_serving); + return true; + } + case WM_PAINT: + Paint(h); + return true; + case WM_ENTERSIZEMOVE: + _inSizeMove = true; + return false; + case WM_EXITSIZEMOVE: + _inSizeMove = false; + RememberUserLayout(); + return false; + } + return false; + } + + private bool InCloseBox(POINT pt) + { + GetClientRect(_staHwnd, out RECT rc); + return pt.Y >= 0 && pt.Y < CaptionPx && pt.X >= rc.Right - CloseBoxPx && pt.X < rc.Right; + } + + private void Paint(IntPtr h) + { + IntPtr dc = BeginPaint(h, out PAINTSTRUCT ps); + try + { + GetClientRect(h, out RECT rc); + var strip = new RECT { Left = 0, Top = 0, Right = rc.Right, Bottom = Math.Min(CaptionPx, rc.Bottom) }; + FillRect(dc, ref strip, _captionBrush); + SetBkMode(dc, TRANSPARENT); + SetTextColor(dc, TextColor); + IntPtr old = SelectObject(dc, GetStockObject(DEFAULT_GUI_FONT)); + var title = new RECT { Left = 10, Top = 0, Right = Math.Max(10, rc.Right - CloseBoxPx - 6), Bottom = strip.Bottom }; + DrawTextW(dc, _title, -1, ref title, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX); + var x = new RECT { Left = rc.Right - CloseBoxPx, Top = 0, Right = rc.Right, Bottom = strip.Bottom }; + DrawTextW(dc, "X", -1, ref x, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX); + SelectObject(dc, old); + } + finally { EndPaint(h, ref ps); } + } + + private void Drain() + { + while (_queue.TryDequeue(out Action? a)) + { + try { a(); } + catch (Exception ex) { SafeLog("panel action threw " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); } // no Message: it could carry a URL + } + } + + private bool IsLive(int handle) { lock (_sync) return handle == _live && !_shuttingDown; } + + private void ProcessOpen(int handle, WebPanelRequest r) + { + if (_tornDown || !IsLive(handle)) return; // a newer Open is queued behind this one + _serving = handle; + _unresponsiveCount = 0; // a new panel starts its own count + _req = r; + _title = string.IsNullOrWhiteSpace(r.Title) ? "RynthCore" : r.Title.Trim(); + _fractions = WebPanelLayoutStore.TryLoad(_env.LocalAppData, out PanelFractions stored) + ? stored + : WebPanelWindowPolicy.Default(r.WidthPercent, r.HeightPercent); + _pendingUrl = r.Url; + if (_windowFailed) { Fail(handle, WebPanelCode.CreateFailed, "no panel window", allowFallback: true); return; } + + if (_needsRecreate || (_profileFolder != null && !string.Equals(_profileFolder, r.ProfileFolder, StringComparison.OrdinalIgnoreCase))) + TearDownWebView(); + + _open = true; + InvalidateRect(_staHwnd, IntPtr.Zero, true); + Show(); + if (_ctl != null) { NavigatePending(handle); return; } + if (!_creating) StartCreate(handle, r.ProfileFolder); + } + + private void StartCreate(int handle, string folder) + { + _creating = true; + int seq = ++_createSeq; + _profileFolder = folder; + if (!EnsureLoader(out string why)) { CreationFailed(seq, WebPanelCode.CreateFailed, why); return; } + try + { + string version = CoreWebView2Environment.GetAvailableBrowserVersionString(); + if (string.IsNullOrEmpty(version)) { CreationFailed(seq, WebPanelCode.RuntimeMissing, "no WebView2 runtime"); return; } + } + catch (Exception ex) + { + CreationFailed(seq, Classify(ex), "runtime probe: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); + return; + } + int delay = _env.EnvironmentDelayMsForTests; + if (delay > 0) Task.Delay(delay).ContinueWith(_ => Post(() => CreateEnvironment(seq, folder))); + else CreateEnvironment(seq, folder); + } + + private bool EnsureLoader(out string why) + { + why = ""; + if (_loaderLoaded) return true; + string path = Path.Combine(_env.RuntimeDir ?? "", "WebView2Loader.dll"); + try + { + // By full path first, so the Core wrapper's DllImport("WebView2Loader.dll") finds the loaded module. + NativeLibrary.Load(path); + _loaderLoaded = true; + return true; + } + catch (Exception ex) + { + why = "WebView2Loader.dll did not load from the runtime folder: " + ex.GetType().Name; + return false; + } + } + + private void CreateEnvironment(int seq, string folder) + { + if (seq != _createSeq || _tornDown) return; + Task<CoreWebView2Environment> t; + try + { + Directory.CreateDirectory(folder); + t = CoreWebView2Environment.CreateAsync(_env.BrowserExecutableFolderForTests, folder, new CoreWebView2EnvironmentOptions()); + } + catch (Exception ex) + { + CreationFailed(seq, WebPanelCode.CreateFailed, "environment: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); + return; + } + t.ContinueWith(done => Post(() => OnEnvironment(seq, done)), TaskContinuationOptions.ExecuteSynchronously); + } + + private void OnEnvironment(int seq, Task<CoreWebView2Environment> t) + { + if (seq != _createSeq || _tornDown) return; + if (!t.IsCompletedSuccessfully) + { + Exception? ex = t.Exception?.GetBaseException(); + CreationFailed(seq, WebPanelCode.CreateFailed, "environment: " + (ex?.GetType().Name ?? "cancelled") + " 0x" + (ex?.HResult ?? 0).ToString("X8")); + return; + } + _wvEnv = t.Result; + _environmentCount++; + Task<CoreWebView2Controller> c; + try { c = _wvEnv.CreateCoreWebView2ControllerAsync(_staHwnd); } + catch (Exception ex) + { + CreationFailed(seq, WebPanelCode.CreateFailed, "controller: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); + return; + } + c.ContinueWith(done => Post(() => OnController(seq, done)), TaskContinuationOptions.ExecuteSynchronously); + } + + private void OnController(int seq, Task<CoreWebView2Controller> t) + { + if (seq != _createSeq || _tornDown) + { + if (t.IsCompletedSuccessfully) { try { t.Result.Close(); } catch { } } + return; + } + if (!t.IsCompletedSuccessfully) + { + Exception? ex = t.Exception?.GetBaseException(); + CreationFailed(seq, WebPanelCode.CreateFailed, "controller: " + (ex?.GetType().Name ?? "cancelled") + " 0x" + (ex?.HResult ?? 0).ToString("X8")); + return; + } + _creating = false; + _ctl = t.Result; + _web = _ctl.CoreWebView2; + _ctl.DefaultBackgroundColor = System.Drawing.Color.FromArgb(255, 32, 32, 36); + + CoreWebView2Settings s = _web.Settings; + s.AreDevToolsEnabled = false; + s.AreBrowserAcceleratorKeysEnabled = false; + s.IsStatusBarEnabled = false; + s.AreHostObjectsAllowed = false; + s.IsWebMessageEnabled = false; // phase 2 turns it on per open + s.IsPasswordAutosaveEnabled = false; + + _web.NavigationStarting += OnNavigationStarting; + _web.NavigationCompleted += OnNavigationCompleted; + _web.NewWindowRequested += OnNewWindowRequested; + _web.PermissionRequested += OnPermissionRequested; + _web.ProcessFailed += OnProcessFailed; + _web.LaunchingExternalUriScheme += OnLaunchingExternalUriScheme; + _ctl.AcceleratorKeyPressed += OnAcceleratorKeyPressed; + _browserPid = _web.BrowserProcessId; + + _env.ConfigureForTests?.Invoke(_web); + ResizeController(); + if (_open) + { + _ctl.IsVisible = true; + NavigatePending(_serving); + if (ForegroundIsThisProcess()) FocusPage(); // the rule Show uses: never focus from another program + } + else + { + _ctl.IsVisible = false; + } + } + + private void CreationFailed(int seq, WebPanelCode code, string reason) + { + if (seq != _createSeq) return; + _creating = false; + _wvEnv = null; + _profileFolder = null; // the next Open tries again + Fail(_serving, code, reason, allowFallback: true); + } + + /// <summary>Only the runtime probe can say RuntimeMissing; a failure after it is CreateFailed.</summary> + private static WebPanelCode Classify(Exception? ex) => + ex is WebView2RuntimeNotFoundException ? WebPanelCode.RuntimeMissing : WebPanelCode.CreateFailed; + + private void NavigatePending(int handle) + { + if (_web == null || !IsLive(handle)) return; + string url = _pendingUrl; + SetState(handle, () => _status = (int)WebPanelStatusCode.Loading); + try { _web.Navigate(url); } + catch (Exception ex) { SafeLog("navigate threw " + ex.GetType().Name + " for " + WebPanelUrlPolicy.Redact(url)); } + } + + private void NavigateNow(int handle, string url) + { + if (!IsLive(handle) || _serving != handle) return; + _pendingUrl = url; + if (_web == null) return; // still creating: the controller navigates to _pendingUrl when it is ready + NavigatePending(handle); + } + + // ---- navigation guard ---- + + private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e) + { + try + { + string url = e.Uri; + if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return; // our own close, or the page's + string[] allow = _req?.Allowlist ?? Array.Empty<string>(); + if (!WebPanelUrlPolicy.IsAllowed(url, allow)) + { + e.Cancel = true; + RouteOffList(url, e.IsUserInitiated); + return; + } + int handle = _serving; + SetState(handle, () => + { + _navCount++; + if (_status != (int)WebPanelStatusCode.Closed && _status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Loading; + }); + } + catch + { + // Fail closed: a guard that threw must not let the navigation through. + try { e.Cancel = true; } catch { } + } + } + + private void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e) + { + _unresponsiveCount = 0; // a completed navigation means the renderer answered + string source = _web?.Source ?? ""; + if (string.Equals(source, "about:blank", StringComparison.OrdinalIgnoreCase) || !_open) return; + _source = source; + int http = e.HttpStatusCode; + int handle = _serving; + SetState(handle, () => + { + if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return; + _status = (int)WebPanelStatusCode.Ready; + if (http != 0) _http = http; + }); + } + + private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e) + { + try + { + e.Handled = true; // never a second window + string url = e.Uri; + string[] allow = _req?.Allowlist ?? Array.Empty<string>(); + if (WebPanelUrlPolicy.IsAllowed(url, allow)) + { + try { _web?.Navigate(url); } catch { } + } + else + { + RouteOffList(url, e.IsUserInitiated); + } + } + catch + { + // Fail closed: still no second window. + try { e.Handled = true; } catch { } + } + } + + /// <summary> + /// An off-list URL: the system browser when it is browser-safe, came from a click (or a plugin) and + /// isn't too soon after the last (WebPanelBrowserGate); else dropped (logged redacted). + /// </summary> + private void RouteOffList(string url, bool userInitiated) + { + if (WebPanelUrlPolicy.IsBrowserSafe(url)) + { + BrowserOpenVerdict verdict = _browserGate.Decide(userInitiated, Environment.TickCount64); + if (verdict != BrowserOpenVerdict.Open) + { + SafeLog((verdict == BrowserOpenVerdict.NotUserInitiated + ? "kept an off-list page out of the system browser (not from a click): " + : "kept an off-list page out of the system browser (too many, too fast): ") + WebPanelUrlPolicy.Redact(url)); + return; + } + bool ok = false; + try { ok = _env.OpenInBrowser(url); } catch { } + string host = Uri.TryCreate(url, UriKind.Absolute, out Uri? u) ? u.Host : "the page"; + SafeLog((ok ? "opened in the system browser: " : "the system browser did not open: ") + WebPanelUrlPolicy.Redact(url)); + if (ok) SafeChat("[RynthCore] Opened " + host + " in your web browser."); + } + else + { + SafeLog("blocked a navigation (" + SchemeOf(url) + "): " + WebPanelUrlPolicy.Redact(url)); + } + } + + private static string SchemeOf(string url) + { + int colon = url.IndexOf(':'); + if (colon <= 0 || colon > 32) return "no scheme"; + foreach (char c in url.AsSpan(0, colon)) + if (!char.IsAsciiLetterOrDigit(c) && c != '+' && c != '-' && c != '.') return "no scheme"; + return url.Substring(0, colon).ToLowerInvariant(); + } + + private void OnLaunchingExternalUriScheme(object? sender, CoreWebView2LaunchingExternalUriSchemeEventArgs e) + { + e.Cancel = true; // never hand a custom scheme to the shell, and never show WebView2's prompt for one + SafeLog("blocked an external scheme launch (" + SchemeOf(e.Uri) + ")"); + } + + private void OnPermissionRequested(object? sender, CoreWebView2PermissionRequestedEventArgs e) + { + // ClipboardRead only for a frame on the allowlist (iframes are unrestricted otherwise); everything else denied. + CoreWebView2PermissionState state = CoreWebView2PermissionState.Deny; + try + { + // IsAllowed accepts about:blank (for our own close); a blank frame gets no clipboard. + if (e.PermissionKind == CoreWebView2PermissionKind.ClipboardRead + && !string.Equals(e.Uri, "about:blank", StringComparison.OrdinalIgnoreCase) + && WebPanelUrlPolicy.IsAllowed(e.Uri, _req?.Allowlist ?? Array.Empty<string>())) + state = CoreWebView2PermissionState.Allow; + } + catch { state = CoreWebView2PermissionState.Deny; } + // Never remember a decision in the profile: an Allow must not outlive an allowlist change. + try { e.SavesInProfile = false; } catch { } + e.State = state; + } + + private void OnAcceleratorKeyPressed(object? sender, CoreWebView2AcceleratorKeyPressedEventArgs e) + { + _acceleratorEvents++; + if (e.KeyEventKind != CoreWebView2KeyEventKind.KeyDown || e.VirtualKey != VK_ESCAPE) return; + if (((_req?.Flags ?? 0) & FlagPageKeepsEscape) != 0) return; // the page gets it + e.Handled = true; + int handle = _serving; + Post(() => CloseNow(handle)); // not inside WebView2's own callback + } + + private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e) + { + CoreWebView2ProcessFailedKind kind = e.ProcessFailedKind; + Post(() => HandleProcessFailed(kind)); // act outside WebView2's own callback + } + + // RenderProcessUnresponsive: WebView2 raises it repeatedly while the main frame's renderer stays hung. One + // report can be a long script; this many within the window fails the panel like a renderer exit. + private const int UnresponsiveLimit = 3; + private const long UnresponsiveWindowMs = 30000; + private int _unresponsiveCount; + private long _unresponsiveSinceMs; + + /// <summary> + /// Only two kinds end the panel (WebView2's own docs, Microsoft.Web.WebView2.Core.xml, + /// CoreWebView2ProcessFailedKind): BrowserProcessExited (everything is gone: full teardown) and + /// RenderProcessExited (the main frame's renderer: about:blank, recreate on the next Open). GPU, utility, + /// sandbox helper and PPAPI processes are recreated by WebView2 and are not fatal; a frame-only renderer exit + /// does not touch the top-level document; those are logged only. Acts on the panel being served now, not on + /// the handle when the event fired, so a late event never hides a newer panel (Fail ignores a non-live handle). + /// </summary> + private void HandleProcessFailed(CoreWebView2ProcessFailedKind kind) + { + if (_tornDown) return; + int handle = _serving; + switch (kind) + { + case CoreWebView2ProcessFailedKind.BrowserProcessExited: + SafeLog("WebView2 process failed: " + kind); + TearDownWebView(); + break; + case CoreWebView2ProcessFailedKind.RenderProcessExited: + SafeLog("WebView2 process failed: " + kind); + try { _web?.Navigate("about:blank"); } catch { } + _needsRecreate = true; // the next Open recreates the controller and environment + break; + case CoreWebView2ProcessFailedKind.RenderProcessUnresponsive: + { + long now = Environment.TickCount64; + if (_unresponsiveCount == 0 || now - _unresponsiveSinceMs > UnresponsiveWindowMs) { _unresponsiveCount = 0; _unresponsiveSinceMs = now; } + _unresponsiveCount++; + SafeLog($"WebView2 renderer unresponsive ({_unresponsiveCount} of {UnresponsiveLimit} within {UnresponsiveWindowMs / 1000} s)"); + if (_unresponsiveCount < UnresponsiveLimit) return; + _unresponsiveCount = 0; + try { _web?.Navigate("about:blank"); } catch { } + _needsRecreate = true; + break; + } + default: + SafeLog("WebView2 process failed (not fatal, panel kept): " + kind); + return; + } + // Never a browser fallback here: a navigation already ran, so the launch code is spent. + Fail(handle, WebPanelCode.ProcessFailed, kind.ToString(), allowFallback: false); + } + + // ---- open, close, fail ---- + + private void Fail(int handle, WebPanelCode code, string reason, bool allowFallback) + { + bool fallback = false, ignored = false; + string url = ""; + lock (_sync) + { + if (handle != _live || _status == (int)WebPanelStatusCode.Closed) + { + ignored = true; + } + else + { + WebPanelRequest? r = _req; + if (allowFallback && r != null && (code == WebPanelCode.RuntimeMissing || code == WebPanelCode.CreateFailed) + && (r.Flags & FlagFallback) != 0 && _navCount == 0 && WebPanelUrlPolicy.IsBrowserSafe(r.Url)) + { + // Failed is published only together with the fallback's outcome (below): a plugin polling in + // between must never see Failed without OpenedInBrowser and open the page a second time. + fallback = true; + url = r.Url; + } + else + { + _status = (int)WebPanelStatusCode.Failed; + _error = (int)code; + } + } + } + if (ignored) { SafeLog($"panel failure after close or supersede, panel left as it is: {code} ({reason})"); return; } + HidePanel(); + SafeLog($"panel failed: {code} ({reason})"); + if (!fallback) return; + bool ok = false; + try { ok = _env.OpenInBrowser(url); } catch { } + // One lock: Failed, the error and (only when the browser opened) the flag become visible together, and only + // for the panel that failed; a Close or a newer Open in the meantime wins. + lock (_sync) + { + if (handle == _live && _status != (int)WebPanelStatusCode.Closed) + { + _status = (int)WebPanelStatusCode.Failed; + _error = (int)code; + if (ok) _flags |= StateOpenedInBrowser; + } + } + SafeLog((ok ? "fallback: opened in the system browser: " : "fallback: the system browser did not open: ") + WebPanelUrlPolicy.Redact(url)); + string why = code == WebPanelCode.RuntimeMissing ? "WebView2 runtime not installed" : "it failed to start"; + SafeChat(ok + ? "[RynthCore] The in-game browser could not start (" + why + "); opened the page in your web browser." + : "[RynthCore] The in-game browser could not start (" + why + "), and your web browser did not open."); + } + + private void Show() + { + PlaceNow(force: true); + ShowWindow(_staHwnd, SW_SHOWNA); + // Focus the panel only from within this process (the game, or a pop-out): a plugin opening it while the + // player is in another program must not pull the foreground away (the PID rule keeps it hidden meanwhile). + // Never while the foreground is null (mid alt-tab): that would grab focus on the way to another program. + // Only this process, defensively: a foreground in the WebView2 browser process is assumed (not observed) to + // be the page's own dialog, which should keep it (IsOurPid, which includes the browser, is for the + // visibility rule only). + bool inProcess = ForegroundIsThisProcess(); + if (inProcess) SetForegroundWindow(_staHwnd); + if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } } + if (inProcess) FocusPage(); // same rule, defensively: moving WebView2 focus might activate the host window (not observed) + if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; } + UpdateStateFlags(); + } + + /// <summary>The foreground is a window of this process (not null, not another program, not the browser process).</summary> + private bool ForegroundIsThisProcess() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return false; + GetWindowThreadProcessId(fg, out uint fgPid); + return fgPid == _ourPid; + } + + private void FocusPage() + { + try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { } + } + + private void CloseNow(int handle) + { + if (!IsLive(handle) || handle != _serving) return; + if (_open) + { + HidePanel(); + if (_ctl != null) { try { _web?.Navigate("about:blank"); } catch { } } + } + SetState(handle, () => + { + if (_status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Closed; + _flags &= ~(StateVisible | StateFocused); + }); + } + + /// <summary>Hides the panel (controller, window, timer); hands the foreground back to the game when the panel held it.</summary> + private void HidePanel() + { + bool hadForeground = HoldsForeground(); + _open = false; + if (_timerOn) { KillTimer(_staHwnd, TimerId); _timerOn = false; } + if (_ctl != null) { try { _ctl.IsVisible = false; } catch { } } + if (_staHwnd != IntPtr.Zero) ShowWindow(_staHwnd, SW_HIDE); + lock (_sync) if (_serving == _live) _flags &= ~(StateVisible | StateFocused); + if (hadForeground) + { + IntPtr game = _env.GameHwnd; + if (game != IntPtr.Zero && IsWindow(game)) SetForegroundWindow(game); + } + } + + private bool HoldsForeground() + { + if (_staHwnd == IntPtr.Zero) return false; + IntPtr fg = GetForegroundWindow(); + return fg != IntPtr.Zero && (fg == _staHwnd || GetAncestor(fg, GA_ROOT) == _staHwnd); + } + + // ---- tracking: 50 ms timer and the foreground WinEvent ---- + + private void Track() + { + if (!_open || _staHwnd == IntPtr.Zero) return; + IntPtr game = _env.GameHwnd; + if (game == IntPtr.Zero || !IsWindow(game)) { CloseNow(_serving); return; } + IntPtr fg = GetForegroundWindow(); + uint fgPid = 0; + if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); + // The page's own dialogs (alert, file picker, sign-in) are windows of the WebView2 browser process: count + // that process as ours so they do not hide the panel they belong to. + if (IsOurPid(fgPid)) fgPid = _ourPid; + bool? visible = WebPanelWindowPolicy.Visible(true, true, IsIconic(game), IsWindowVisible(game), fg == IntPtr.Zero, fgPid, _ourPid); + bool shown = IsWindowVisible(_staHwnd); + if (visible == false) + { + if (shown) ShowWindow(_staHwnd, SW_HIDE); + } + else + { + if (visible == true && !shown) { ShowWindow(_staHwnd, SW_SHOWNA); shown = true; } + if (shown) + { + if (!_inSizeMove) PlaceNow(force: false); + RaiseAboveGame(game); + } + } + UpdateStateFlags(); + } + + /// <summary> + /// This process, or this panel's WebView2 browser process. The browser PID is CoreWebView2.BrowserProcessId, + /// read when the controller is created (OnController) and cleared by TearDownWebView; 0 while there is none. + /// </summary> + private bool IsOurPid(uint pid) + { + if (pid == 0) return false; + uint browser = _browserPid; + return pid == _ourPid || (browser != 0 && pid == browser); + } + + private bool GameClientScreen(out PanelRect rect) + { + rect = default; + IntPtr game = _env.GameHwnd; + if (game == IntPtr.Zero || !GetClientRect(game, out RECT c)) return false; + var p = new POINT(); + if (!ClientToScreen(game, ref p)) return false; + rect = new PanelRect(p.X, p.Y, p.X + c.W, p.Y + c.H); + return rect.Width > 0 && rect.Height > 0; + } + + private void PlaceNow(bool force) + { + if (!GameClientScreen(out PanelRect client)) return; + PanelRect want = WebPanelWindowPolicy.Place(client, _fractions); + GetWindowRect(_staHwnd, out RECT have); + if (!force && have.Left == want.Left && have.Top == want.Top && have.Right == want.Right && have.Bottom == want.Bottom) return; + SetWindowPos(_staHwnd, IntPtr.Zero, want.Left, want.Top, want.Width, want.Height, SWP_NOZORDER | SWP_NOACTIVATE); + } + + /// <summary>Raises the panel only when it is below the game window, so it never covers a window the user brought forward.</summary> + private void RaiseAboveGame(IntPtr game) + { + int guard = 0; + for (IntPtr h = GetWindow(game, GW_HWNDPREV); h != IntPtr.Zero && guard < 4096; h = GetWindow(h, GW_HWNDPREV), guard++) + if (h == _staHwnd) return; + SetWindowPos(_staHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + } + + private void UpdateStateFlags() + { + bool visible = _staHwnd != IntPtr.Zero && IsWindowVisible(_staHwnd); + bool focused = HoldsForeground(); + lock (_sync) + { + if (_serving != _live) return; + _flags = (_flags & StateOpenedInBrowser) | (visible && _open ? StateVisible : 0) | (focused && _open ? StateFocused : 0); + } + } + + private void RememberUserLayout() + { + if (!GameClientScreen(out PanelRect client)) return; + GetWindowRect(_staHwnd, out RECT r); + _fractions = WebPanelWindowPolicy.FromUserRect(client, new PanelRect(r.Left, r.Top, r.Right, r.Bottom)); + if (!WebPanelLayoutStore.Save(_env.LocalAppData, _fractions)) SafeLog("could not save the panel layout"); + } + + private void ResizeController() + { + if (_ctl == null || _staHwnd == IntPtr.Zero) return; + GetClientRect(_staHwnd, out RECT rc); + try { _ctl.Bounds = new System.Drawing.Rectangle(0, CaptionPx, Math.Max(0, rc.W), Math.Max(0, rc.H - CaptionPx)); } catch { } + } + + // ---- teardown ---- + + /// <summary>Drops the controller and environment (profile switch, browser exit, shutdown). Pending creations become stale.</summary> + private void TearDownWebView() + { + _createSeq++; + _creating = false; + _needsRecreate = false; + _unresponsiveCount = 0; + CoreWebView2? web = _web; + CoreWebView2Controller? ctl = _ctl; + _web = null; + _ctl = null; + _wvEnv = null; + _profileFolder = null; + _browserPid = 0; + if (web != null) + { + try + { + web.NavigationStarting -= OnNavigationStarting; + web.NavigationCompleted -= OnNavigationCompleted; + web.NewWindowRequested -= OnNewWindowRequested; + web.PermissionRequested -= OnPermissionRequested; + web.ProcessFailed -= OnProcessFailed; + web.LaunchingExternalUriScheme -= OnLaunchingExternalUriScheme; + } + catch { } + } + if (ctl != null) + { + try { ctl.AcceleratorKeyPressed -= OnAcceleratorKeyPressed; } catch { } + try { ctl.Close(); } catch { } + } + } + + private void TeardownOnPanelThread() + { + if (_tornDown) return; + _tornDown = true; + _open = false; + if (_hook != IntPtr.Zero) { UnhookWinEvent(_hook); _hook = IntPtr.Zero; } + if (_timerOn && _staHwnd != IntPtr.Zero) { KillTimer(_staHwnd, TimerId); _timerOn = false; } + TearDownWebView(); + if (_staHwnd != IntPtr.Zero) { DestroyWindow(_staHwnd); _staHwnd = IntPtr.Zero; } + lock (_sync) _hwnd = IntPtr.Zero; + if (_className.Length != 0) { UnregisterClassW(_className, GetModuleHandleW(IntPtr.Zero)); _className = ""; } + if (_bgBrush != IntPtr.Zero) { DeleteObject(_bgBrush); _bgBrush = IntPtr.Zero; } + if (_captionBrush != IntPtr.Zero) { DeleteObject(_captionBrush); _captionBrush = IntPtr.Zero; } + if (s_active == this) s_active = null; + _req = null; + PostQuitMessage(0); + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs b/src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs new file mode 100644 index 0000000..284eb0c --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs @@ -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); + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelNative.cs b/src/RynthCore.Engine/WebPanel/WebPanelNative.cs new file mode 100644 index 0000000..383801c --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelNative.cs @@ -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); +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs b/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs new file mode 100644 index 0000000..e319d28 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs @@ -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; + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs b/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs new file mode 100644 index 0000000..b09ca79 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs @@ -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(); + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs new file mode 100644 index 0000000..230bd9b --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs @@ -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; + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs new file mode 100644 index 0000000..405eaac --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs @@ -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); +} diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 7a81114..6d713ad 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -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> diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 00fc926..5e5da89 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -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; diff --git a/src/RynthCore.PluginSdk/WebPanelTypes.cs b/src/RynthCore.PluginSdk/WebPanelTypes.cs new file mode 100644 index 0000000..3c8117c --- /dev/null +++ b/src/RynthCore.PluginSdk/WebPanelTypes.cs @@ -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; +} diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index ecae5c1..8434353 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ <PropertyGroup> <!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. --> - <RynthCoreSdkApiVersion>93</RynthCoreSdkApiVersion> + <RynthCoreSdkApiVersion>95</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> diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index d2efaca..b0f2d29 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -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() @@ -167,6 +170,8 @@ internal static class Program ("flight", "flight mark here", "flight frob", "FlightRecorder.HandleCommand: its usage"), ("autoid", "autoid limited", "autoid frob", "AutoIdService.HandleCommand: its usage"), ("uicost", "uicost 80", "uicost frob", "UiCost.HandleCommand: its usage"), + ("chatwindow", "chatwindow open Combat", "chatwindow frob", "ChatWindows.Parse: unknown verb + usage"), + ("chatwindow", "chatwin close all", "chatwin close 9", "ChatWindows.Parse: no such window + usage"), ("netmsg", "netmsg log on", "netmsg frob", "ServerMessageStream.HandleCommand: its usage"), ("hotkeys", "hotkeys", "hotkeys frob", "HotkeyCommandParser: unknown verb + usage"), ("settings", "settings Hotkeys", "settings frob", "SettingsCommand: no tab called 'frob' (tabs: ...)"), @@ -341,6 +346,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) diff --git a/tools/ChatWindowTests/ChatWindowTests.csproj b/tools/ChatWindowTests/ChatWindowTests.csproj new file mode 100644 index 0000000..e8e0831 --- /dev/null +++ b/tools/ChatWindowTests/ChatWindowTests.csproj @@ -0,0 +1,30 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the extra chat windows (2026-11-09): src\RynthCore.Engine\UI\Data\ChatWindows.cs + (window keys and numbers, the first free window, which tab a window shows when its own is gone, a + rename followed, /rc chatwindow's parsing) and UI\PanelStateStore.cs's values (where a window's tab + is saved: per layout, switched with it, written only when set, kept by an unknown reader), with + BarLayout.cs and EngineSettingsFile.cs, compiled in with a stub RynthLog and EngineSettings. Also + reads ChatCommandReplies.cs and ChatView.cs / ChatFace.cs as text (the catalog's usage line is + ChatWindows.Usage; no face's code saves a tab on its own). Writes only to a temp folder (deleted + at the end); never touches %LOCALAPPDATA% or C:\Games. + 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>ChatWindowTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatWindows.cs" Link="Engine\ChatWindows.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\PanelStateStore.cs" Link="Engine\PanelStateStore.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\BarLayout.cs" Link="Engine\BarLayout.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/ChatWindowTests/Program.cs b/tools/ChatWindowTests/Program.cs new file mode 100644 index 0000000..cab11fb --- /dev/null +++ b/tools/ChatWindowTests/Program.cs @@ -0,0 +1,257 @@ +using System.Text.RegularExpressions; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine +{ + /// <summary>Stub of the engine's log (PanelStateStore writes load/save problems to it).</summary> + internal static class RynthLog + { + internal static readonly List<string> Lines = new(); + internal static void UI(string msg) { lock (Lines) Lines.Add(msg); } + } +} + +namespace RynthCore.Engine.Plugins +{ + /// <summary>Stub of the one engine.json setting PanelStateStore reads.</summary> + internal static class EngineSettings + { + public static bool RememberWindowLayout { get; set; } = true; + } +} + +namespace ChatWindowTests +{ + /// <summary> + /// The extra chat windows without AC: their keys, the first free one, the tab each shows, the + /// /rc chatwindow parser, and the panel layout values that keep each window's tab. + /// </summary> + internal static class Program + { + private static int _fails, _checks; + private static string _case = ""; + + private static int Main() + { + Keys(); + FirstFree(); + Tabs(); + Parser(); + StoreValues(); + Sources(); + Console.WriteLine(_fails == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_fails} of {_checks} checks"); + return _fails == 0 ? 0 : 1; + } + + private static void Case(string name) { _case = name; Console.WriteLine("-- " + name); } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _fails++; + 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 readonly string[] AllTabs = + { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Items", "Other", "Loot Log" }; + + private static void Keys() + { + Case("window keys and numbers"); + Eq(ChatWindows.MaxWindows, 6, "six extra windows"); + Eq(ChatWindows.Key(2), "Chat 2", "the first extra window is Chat 2 (the main chat is Chat)"); + Eq(string.Join("|", ChatWindows.Keys()), "Chat 2|Chat 3|Chat 4|Chat 5|Chat 6|Chat 7", "every key, in order"); + Check(ChatWindows.TryNumber("Chat 4", out int n) && n == 4, "Chat 4 is window 4"); + Check(ChatWindows.TryNumber("chat 7", out n) && n == 7, "any case"); + Check(!ChatWindows.TryNumber("Chat", out _), "the main chat isn't an extra window"); + Check(!ChatWindows.TryNumber("Chat 1", out _), "nor window 1"); + Check(!ChatWindows.TryNumber("Chat 8", out _), "nor past the last"); + Check(!ChatWindows.TryNumber("Chat 2x", out _), "nor a longer word"); + Check(!ChatWindows.TryNumber("ChatFilters", out _), "nor the Filters panel"); + Check(!ChatWindows.TryNumber(null, out _), "nor nothing"); + Eq(ChatWindows.TabValueKey(3), "chatwin.3.tab", "where window 3's tab is saved"); + Eq(ChatWindows.HeaderText(3, "Combat"), "Chat 3 · Combat", "its header"); + } + + private static void FirstFree() + { + Case("the first free window"); + Eq(ChatWindows.FirstFree(_ => false), 2, "none open: Chat 2"); + var open = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Chat 2", "Chat 4" }; + Eq(ChatWindows.FirstFree(open.Contains), 3, "a gap is filled first"); + Eq(ChatWindows.FirstFree(k => k != "Chat 7"), 7, "the last one"); + Eq(ChatWindows.FirstFree(_ => true), 0, "all open: none (0)"); + } + + private static void Tabs() + { + Case("the tab a window shows"); + Eq(ChatWindows.EffectiveTab("Combat", AllTabs), "Combat", "its own"); + Eq(ChatWindows.EffectiveTab("combat", AllTabs), "Combat", "spelled as the tab is now"); + Eq(ChatWindows.EffectiveTab("loot log", AllTabs), "Loot Log", "a created tab, with a space"); + Eq(ChatWindows.EffectiveTab("Gone", AllTabs), "All", "a deleted tab: All (like the main chat)"); + Eq(ChatWindows.EffectiveTab("", AllTabs), "All", "nothing saved: All"); + Eq(ChatWindows.EffectiveTab(null, AllTabs), "All", "nothing saved (null): All"); + Eq(ChatWindows.Resolve(" Items ", AllTabs), "Items", "typed with spaces around it"); + Eq(ChatWindows.Resolve("Itemz", AllTabs), null, "no such tab: null"); + + Case("a rename followed"); + Eq(ChatWindows.FollowRename("Loot Log", "loot log", "Drops"), "Drops", "the window showing it follows"); + Eq(ChatWindows.FollowRename("Combat", "Loot Log", "Drops"), null, "another window: no change"); + Eq(ChatWindows.FollowRename(null, "Loot Log", "Drops"), null, "nothing saved: no change"); + Eq(ChatWindows.FollowRename("Loot Log", "Loot Log", " "), null, "a blank new name: no change"); + } + + private static void Parser() + { + Case("/rc chatwindow parsing"); + Eq(ChatWindows.Parse("").Verb, ChatWindowVerb.List, "alone: the list"); + Eq(ChatWindows.Parse(" list ").Verb, ChatWindowVerb.List, "list"); + Eq(ChatWindows.Parse("status").Verb, ChatWindowVerb.List, "status"); + var open = ChatWindows.Parse("open Loot Log"); + Check(open.Verb == ChatWindowVerb.Open && open.Tab == "Loot Log", "open <tab with a space>"); + var bare = ChatWindows.Parse("open"); + Check(bare.Verb == ChatWindowVerb.Open && bare.Tab == "", "open alone: the main chat's tab"); + Eq(ChatWindows.Parse("new Combat").Verb, ChatWindowVerb.Open, "new = open"); + var close = ChatWindows.Parse("close 3"); + Check(close.Verb == ChatWindowVerb.Close && close.Number == 3, "close 3"); + close = ChatWindows.Parse("close chat 3"); + Check(close.Verb == ChatWindowVerb.Close && close.Number == 3, "close chat 3"); + Eq(ChatWindows.Parse("CLOSE ALL").Verb, ChatWindowVerb.CloseAll, "close all, any case"); + var tab = ChatWindows.Parse("tab 5 Loot Log"); + Check(tab.Verb == ChatWindowVerb.Tab && tab.Number == 5 && tab.Tab == "Loot Log", "tab 5 <tab>"); + tab = ChatWindows.Parse("tab chat 5 Combat"); + Check(tab.Verb == ChatWindowVerb.Tab && tab.Number == 5 && tab.Tab == "Combat", "tab chat 5 <tab>"); + + foreach (string bad in new[] { "frob", "close", "close 9", "close 1", "close 3 x", "close x", "tab", "tab 3", "tab 9 Combat", "tab Combat" }) + { + var c = ChatWindows.Parse(bad); + Check(c.Verb == ChatWindowVerb.Error && c.Error.EndsWith(ChatWindows.Usage, StringComparison.Ordinal), + $"'/rc chatwindow {bad}': why, then the usage (got {c.Verb}: {c.Error})"); + Check(!c.Error.StartsWith("Usage", StringComparison.Ordinal) || c.Error == ChatWindows.Usage, $"'{bad}': one usage line"); + } + Check(ChatWindows.Parse("frob").Error.StartsWith("Unknown", StringComparison.Ordinal), "an unknown verb starts 'Unknown' (a failure in red)"); + Check(ChatWindows.Usage.StartsWith("Usage: /rc chatwindow", StringComparison.Ordinal), "the usage names the command"); + } + + private static string NewDir(string name) + { + string d = Path.Combine(Path.GetTempPath(), "rynth-chatwindowtests-" + Environment.ProcessId, name); + Directory.CreateDirectory(d); + return d; + } + + private static void StoreValues() + { + Case("a window's tab in the panel layout (PanelStateStore values)"); + string root = NewDir("store"); + try + { + string a = Path.Combine(root, "a", "panel_state.txt"); + string b = Path.Combine(root, "b", "panel_state.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(a)!); + const string aText = "# A\r\npanel.Chat=open,10,20,300,200,docked,0,0\r\npanel.Chat 2=open,400,20,300,200,floating,900,100\r\n"; + File.WriteAllText(a, aText); + PanelStateStore.SwitchTo(a, flushCurrent: false); + int gen = PanelStateStore.Generation; + Check(!PanelStateStore.TryGetValue("chatwin.2.tab", out string v) && v == "", "nothing saved: no value"); + Check(PanelStateStore.TryGetPanel("Chat 2", out var w2) && w2.Open && w2.Floating && w2.FloatingLeft == 900, + "an extra window's place, open and popped-out state are an ordinary panel row"); + Eq(File.ReadAllText(a), aText, "reading writes nothing"); + + PanelStateStore.SetValue("chatwin.2.tab", "Loot Log"); + Check(PanelStateStore.TryGetValue("chatwin.2.tab", out v) && v == "Loot Log", "set, then read back"); + Check(File.ReadAllText(a).Contains("value.chatwin.2.tab=Loot Log", StringComparison.Ordinal), "saved in the layout's file"); + Check(File.ReadAllText(a).Contains("panel.Chat 2=open,400,20,300,200,floating,900,100", StringComparison.Ordinal), "the panel rows are kept"); + string before = File.ReadAllText(a); + PanelStateStore.SetValue("chatwin.2.tab", "Loot Log"); + Eq(File.ReadAllText(a), before, "the same value again writes nothing new"); + + PanelStateStore.SetValue("chatwin.3.tab", "Tab = with, commas"); + Check(PanelStateStore.TryGetValue("chatwin.3.tab", out v) && v == "Tab = with, commas", "'=' and ',' in a value survive in memory"); + + PanelStateStore.SwitchTo(b, flushCurrent: true); + Check(PanelStateStore.Generation != gen, "a switch moves the generation (open windows read their tab again)"); + Check(!PanelStateStore.TryGetValue("chatwin.2.tab", out _), "another layout: its own values (none)"); + Check(!File.Exists(b), "reading a layout without a file makes none"); + + PanelStateStore.SwitchTo(a, flushCurrent: false); + Check(PanelStateStore.TryGetValue("chatwin.2.tab", out v) && v == "Loot Log", "back: the value is read from the file"); + Check(PanelStateStore.TryGetValue("chatwin.3.tab", out v) && v == "Tab = with, commas", "'=' and ',' survive the file"); + + PanelStateStore.SetValue("chatwin.3.tab", "line\r\nbreak"); + Check(PanelStateStore.TryGetValue("chatwin.3.tab", out v) && !v.Contains('\n') && !v.Contains('\r'), "line breaks are dropped (one row per value)"); + PanelStateStore.SetValue("chatwin.3.tab", null); + Check(!PanelStateStore.TryGetValue("chatwin.3.tab", out _), "null removes it"); + Check(!File.ReadAllText(a).Contains("chatwin.3", StringComparison.Ordinal), "and its row"); + + Case("PanelStateStore values: a file from an older build, and Remember Open Windows off"); + string old = Path.Combine(root, "old", "panel_state.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(old)!); + File.WriteAllText(old, "panel.Chat=open,1,2,3,4\r\n"); + PanelStateStore.SwitchTo(old, flushCurrent: false); + Check(PanelStateStore.TryGetPanel("Chat", out _) && !PanelStateStore.TryGetValue("chatwin.2.tab", out _), "no value rows: loads as before"); + RynthCore.Engine.Plugins.EngineSettings.RememberWindowLayout = false; + try + { + string oldText = File.ReadAllText(old); + PanelStateStore.SetValue("chatwin.2.tab", "Combat"); + Check(PanelStateStore.TryGetValue("chatwin.2.tab", out v) && v == "Combat", "off: kept in memory"); + Eq(File.ReadAllText(old), oldText, "off: the file isn't written (as panel places)"); + } + finally { RynthCore.Engine.Plugins.EngineSettings.RememberWindowLayout = true; } + } + finally + { + try { Directory.Delete(Path.GetDirectoryName(root)!, recursive: true); } catch { } + } + } + + private static string? FindRepoFile(string relative) + { + string? dir = AppContext.BaseDirectory; + while (dir != null) + { + string p = Path.Combine(dir, relative); + if (File.Exists(p)) return p; + dir = Path.GetDirectoryName(dir); + } + return null; + } + + private static void Sources() + { + Case("sources: the catalog's usage, and nothing saves a tab by itself"); + string? replies = FindRepoFile(Path.Combine("src", "RynthCore.Engine", "Compatibility", "ChatCommandReplies.cs")); + Check(replies != null && File.ReadAllText(replies).Contains("\"" + ChatWindows.Usage + "\"", StringComparison.Ordinal), + "ChatCommandReplies' chatwindow row has ChatWindows.Usage"); + + string? face = FindRepoFile(Path.Combine("src", "RynthCore.Engine", "ImGui", "Panels", "ChatWindowFace.cs")); + Check(face != null, "found ChatWindowFace.cs"); + if (face != null) + { + string src = File.ReadAllText(face); + int from = src.IndexOf("public void OnShown()", StringComparison.Ordinal); + int to = src.IndexOf("// ── Opening, closing", StringComparison.Ordinal); + Check(from > 0 && to > from, "found the face's open/draw code"); + if (from > 0 && to > from) + { + string body = src.Substring(from, to - from); + Check(!body.Contains("SaveTab(", StringComparison.Ordinal) && !body.Contains("SetValue(", StringComparison.Ordinal), + "opening, reading and drawing a window never saves its tab (only a player's pick, open or rename does)"); + } + } + + string? view = FindRepoFile(Path.Combine("src", "RynthCore.Engine", "ImGui", "Panels", "ChatView.cs")); + Check(view != null, "found ChatView.cs"); + if (view != null) + Eq(Regex.Matches(File.ReadAllText(view), @"_selectTab\(").Count, 2, + "a view picks a tab in two places only: a click in the tab list, and a tab it created"); + } + } +} diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index c72eebc..78e80a6 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -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. diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 93b6dc3..9180535 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -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); @@ -565,6 +569,7 @@ internal static class Program { Eq(RynthCoreHost.CurrentApiVersion, PluginContractVersion.Current, "RynthCoreHost.CurrentApiVersion"); Check(RynthCoreHost.BaselineApiVersion <= RynthCoreHost.CurrentApiVersion, "baseline at or below current"); + Check(PluginContractVersion.BarMenu <= PluginContractVersion.Current, "BarMenu (the barMenu manifest key's version) is at or below current"); // The SDK's copy of the table must reach as far as the engine's (same field count, same size). int sdkFields = typeof(RynthCoreApiNative).GetFields().Length; @@ -589,6 +594,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 +704,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 +719,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()); diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index 13807e4..bfdeb98 100644 --- a/tools/SectionsTests/Program.cs +++ b/tools/SectionsTests/Program.cs @@ -33,6 +33,9 @@ internal static class Program WindowPlanChoices(); WindowTakeOver(); WindowFrameless(); + ManifestBarMenu(); + BarMenuHoverTiming(); + BarMenuReload(); StackCheckAfterPluginDraw(); Console.WriteLine(); @@ -585,6 +588,167 @@ internal static class Program "chrome and fitHeight are in the signature (a change re-registers)"); } + // -- Bar icon dropdown (v95) -- + + private static string BarMenuManifest(string windowExtra) => + "{ \"version\": 1, \"windows\": [ { \"id\": \"server\", \"title\": \"DreamWeave\", \"surface\": \"window:server\", \"bar\": true" + + windowExtra + " } ] }"; + + private static void ManifestBarMenu() + { + Case("plugin windows: barMenu (v95)"); + string storefront = ((char)0xE470).ToString(), shield = ((char)0xE40A).ToString(), sparkle = ((char)0xE6A2).ToString(); + string longTip = new string('T', 60); + string longCommand = "/" + new string('c', 250); + string items = """ + [ + { "id": "market", "tooltip": "Market", "icon": "@STORE@", "command": "/rserver market" }, + { "id": "nocmdslash", "tooltip": "No slash", "icon": "@STORE@", "command": "rserver x" }, + { "id": "multiline", "tooltip": "Two lines", "icon": "@STORE@", "command": "/rserver a\n/rserver b" }, + { "id": "toolong", "tooltip": "Too long", "icon": "@STORE@", "command": "@LONGCMD@" }, + { "id": "", "tooltip": "No id", "icon": "@STORE@", "command": "/rserver x" }, + { "id": "market", "tooltip": "Duplicate", "icon": "@STORE@", "command": "/rserver market" }, + { "id": "notip", "tooltip": "", "icon": "@STORE@", "command": "/rserver x" }, + { "id": "suit", "tooltip": "Suit Builder", "icon": "@SHIELD@", "command": "/rserver suit" }, + { "id": "noicon", "tooltip": "No icon", "icon": "", "command": "/rserver x" }, + { "id": "abilities", "tooltip": "Ability Planner", "icon": "@SPARKLE@", "command": "/rserver abilities" }, + { "id": "longtip", "tooltip": "@LONGTIP@", "icon": "@STORE@", "command": "/rserver x" } + ] + """ + .Replace("@STORE@", storefront).Replace("@SHIELD@", shield).Replace("@SPARKLE@", sparkle) + .Replace("@LONGCMD@", longCommand).Replace("@LONGTIP@", longTip); + + SectionManifest m = SectionManifestParser.Parse("DW", BarMenuManifest(", \"barMenu\": " + items), out string err); + Check(err.Length == 0 && m.Windows.Length == 1, "parses and the window is kept: " + err); + SectionBarMenuItem[] menu = m.Windows[0].Menu; + string[] ids = menu.Select(i => i.Id).ToArray(); + Check(ids.SequenceEqual(new[] { "market", "suit", "noicon", "abilities", "longtip" }), + "bad items dropped, order kept: " + string.Join(",", ids)); + Check(menu[0] == new SectionBarMenuItem("market", "Market", storefront, "/rserver market"), "market: fields exactly equal"); + Check(menu[1] == new SectionBarMenuItem("suit", "Suit Builder", shield, "/rserver suit"), "suit: fields exactly equal"); + Check(menu[3] == new SectionBarMenuItem("abilities", "Ability Planner", sparkle, "/rserver abilities"), "abilities: fields exactly equal"); + Check(menu[2].Icon == "" && menu[2].Tooltip == "No icon", "an empty icon is kept as \"\""); + Check(menu[4].Tooltip.Length == SectionManifestParser.MaxLabelLength && menu[4].Tooltip == longTip[..48], + "an over-long tooltip is cut to 48: " + menu[4].Tooltip.Length); + Check(SectionManifestParser.Command("/rserver a\n/rserver b").Length == 0 && SectionManifestParser.Command("rserver x").Length == 0 + && SectionManifestParser.Command(longCommand).Length == 0, "(the rejected commands are ones Command() rejects)"); + + var many = new System.Text.StringBuilder("["); + for (int i = 0; i < 20; i++) + many.Append(i > 0 ? "," : "").Append($"{{ \"id\": \"item{i}\", \"tooltip\": \"Item {i}\", \"icon\": \"\", \"command\": \"/rserver x{i}\" }}"); + many.Append(']'); + m = SectionManifestParser.Parse("DW", BarMenuManifest(", \"barMenu\": " + many), out err); + Check(SectionManifestParser.MaxBarMenuItems == 6 && m.Windows[0].Menu.Length == SectionManifestParser.MaxBarMenuItems, + "twenty valid items give exactly MaxBarMenuItems: " + m.Windows[0].Menu.Length); + Check(m.Windows[0].Menu[0].Id == "item0" && m.Windows[0].Menu[5].Id == "item5", "the first six are the ones kept"); + + m = SectionManifestParser.Parse("DW", BarMenuManifest(", \"barMenu\": \"nope\""), out err); + Check(err.Length == 0 && m.Windows.Length == 1 && m.Windows[0].Menu.Length == 0, "barMenu not an array: window kept, no menu"); + m = SectionManifestParser.Parse("DW", BarMenuManifest(""), out err); + Check(err.Length == 0 && m.Windows.Length == 1 && m.Windows[0].Menu.Length == 0, "no barMenu key: no menu"); + m = SectionManifestParser.Parse("DW", BarMenuManifest(", \"barMenu\": [ { \"id\": \"x\", \"tooltip\": \"X\", \"icon\": \"x\", \"command\": \"/rserver x\" } ]"), out err); + Check(err.Length == 0 && m.Windows[0].Menu.Length == 1 && m.Windows[0].Menu[0].Icon == "" && m.Windows[0].Menu[0].Command == "/rserver x", + "a non-glyph icon keeps the item with Icon \"\""); + } + + private static void BarMenuHoverTiming() + { + Case("bar dropdown: hover timer"); + var h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.10); + Check(h.OpenFor == null, "hovering for 0.10 s: not open yet"); + h.Update("a", false, 0.16); + Check(h.OpenFor == "a", "hovering for 0.16 s: open"); + + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.10); + h.Update(null, false, 0.11); + h.Update(null, false, 0.20); + h.Update(null, false, 0.30); + Check(h.OpenFor == null, "a sweep across the icon (0.10 s) never opens it"); + + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.20); + Check(h.OpenFor == "a", "(setup) open on a"); + Feed(h, "a", 0.30, 0.90); + h.Update(null, false, 1.0); + h.Update(null, false, 1.10); + h.Update(null, true, 1.20); + h.Update(null, true, 1.25); + Check(h.OpenFor == "a", "leaving the icon and reaching the dropdown 0.20 s later: still open (the gap is covered)"); + + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.20); + Feed(h, "a", 0.30, 0.90); + h.Update(null, false, 1.0); + h.Update(null, false, 1.29); + Check(h.OpenFor == "a", "gone for 0.29 s: still open"); + h.Update(null, false, 1.31); + Check(h.OpenFor == null, "gone for 0.31 s: closed"); + + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.20); + Feed(h, "a", 0.30, 1.90); + h.Update("b", false, 2.0); + Check(h.OpenFor == "b", "an open dropdown switches to another icon at once"); + + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.20); + h.Close(); + Check(h.OpenFor == null, "Close() closes"); + Feed(h, "a", 0.30, 4.90); + h.Update("a", false, 5.0); + Check(h.OpenFor == null, "still hovering the same icon: not reopened"); + h.Update(null, false, 5.10); + Feed(h, null, 5.20, 5.90); + h.Update("a", false, 6.0); + Check(h.OpenFor == null, "hovered again but not for OpenDelay yet"); + h.Update("a", false, 6.16); + Check(h.OpenFor == "a", "left and hovered again for OpenDelay: reopens"); + Check(BarMenuHover.OpenDelay == 0.15 && BarMenuHover.CloseDelay == 0.30, "delays are 0.15 s and 0.30 s"); + + // The popped-out bar draws in another ImGui context whose clock starts near 0. + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.20); + h.Update(null, false, 1000.0); + h.Update(null, false, 0.05); + Check(h.OpenFor == null, "the clock jumping back (a pop-out's own context): reset, closed"); + + // A bar that wasn't drawn for a while sends no frames. + h = new BarMenuHover(); + h.Update("a", false, 0.0); + h.Update("a", false, 0.20); + h.Update("a", false, 0.20 + BarMenuHover.ResetGap + 0.01); + Check(h.OpenFor == null, "a forward gap of more than 0.5 s: reset, closed"); + } + + // Frames from..to every 0.1 s (a real run draws every frame; the timer resets on a gap over 0.5 s). + private static void Feed(BarMenuHover h, string? hovered, double from, double to) + { + for (double t = from; t <= to + 1e-9; t += 0.1) h.Update(hovered, false, t); + } + + private static void BarMenuReload() + { + Case("bar dropdown: a barMenu-only change is seen by the host"); + string one = BarMenuManifest(", \"barMenu\": [ { \"id\": \"a\", \"tooltip\": \"A\", \"icon\": \"\", \"command\": \"/rserver a\" } ]"); + SectionWindowDecl w1 = SectionManifestParser.Parse("DW", one, out _).Windows[0]; + SectionWindowDecl w1Again = SectionManifestParser.Parse("DW", one, out _).Windows[0]; + SectionWindowDecl w2 = SectionManifestParser.Parse("DW", one.Replace("/rserver a", "/rserver b"), out _).Windows[0]; + SectionWindowDecl w3 = SectionManifestParser.Parse("DW", BarMenuManifest(""), out _).Windows[0]; + Check(WindowPlan.Signature(w1) == WindowPlan.Signature(w2), "(the panel signature ignores the menu: no re-registration)"); + Check(WindowPlan.MenuSignature(w1) == WindowPlan.MenuSignature(w1Again), "the same menu parsed twice: same menu signature"); + Check(WindowPlan.MenuSignature(w1) != WindowPlan.MenuSignature(w2), "a changed command: new menu signature"); + Check(WindowPlan.MenuSignature(w1) != WindowPlan.MenuSignature(w3), "menu removed: new menu signature"); + Check(WindowPlan.MenuSignature(w3) == WindowPlan.MenuSignature(w3 with { BarMenu = null }), "no menu is always the same signature"); + } // ImGui 1.91.6's ImGuiErrorRecoveryState, in field order: windows, IDs, tree nodes, colours, // style vars, fonts, focus scopes, groups, item flags, popups, disabled. The base values are // the ones a 32-bit probe of our cimgui.dll read inside a panel's body child (2026-10-21). diff --git a/tools/SectionsTests/SectionsTests.csproj b/tools/SectionsTests/SectionsTests.csproj index 7ed4da3..25730bd 100644 --- a/tools/SectionsTests/SectionsTests.csproj +++ b/tools/SectionsTests/SectionsTests.csproj @@ -26,6 +26,8 @@ <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" /> <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" /> <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\WindowPlan.cs" Link="Engine\WindowPlan.cs" /> + <!-- The bar icon dropdown's hover timer (pure). --> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\BarMenuHover.cs" Link="Engine\BarMenuHover.cs" /> <!-- What a plugin window's draw left on ImGui's stacks (the record ImGuiStackGuard takes). --> <Compile Include="..\..\src\RynthCore.Engine\ImGui\ImGuiStackState.cs" Link="Engine\ImGuiStackState.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" /> diff --git a/tools/WebPanelHarness.Payload/PayloadEntry.cs b/tools/WebPanelHarness.Payload/PayloadEntry.cs new file mode 100644 index 0000000..bf24cf9 --- /dev/null +++ b/tools/WebPanelHarness.Payload/PayloadEntry.cs @@ -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"); + }; + }; + } +} diff --git a/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj b/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj new file mode 100644 index 0000000..b23a566 --- /dev/null +++ b/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj @@ -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> diff --git a/tools/WebPanelHarness/Program.cs b/tools/WebPanelHarness/Program.cs new file mode 100644 index 0000000..a50be4f --- /dev/null +++ b/tools/WebPanelHarness/Program.cs @@ -0,0 +1,1148 @@ +// Offline harness for the web panel host: see WebPanelHarness.csproj. Port of the 2026-11-07 spike's +// WebSpikeHost (spikes\webview2\WebSpikeHost), popup-free path only. +using System.Collections.Concurrent; +using System.Diagnostics; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +using System.Text; + +namespace WebPanelHarness; + +internal static unsafe class Program +{ + private const string Secret = "SECRET123"; + private const string Allow = "panel.test\n*.panel.test"; + private const int StatusStarting = 1, StatusLoading = 2, StatusReady = 3, StatusClosed = 4, StatusFailed = 5, StatusSuperseded = 6; + private const int CodeQueued = 1, CodeUrlNotAllowed = -2, CodeShuttingDown = -5, CodeStale = -6, CodeCreateFailed = -8, CodeProcessFailed = -9; + private const uint FlagFallback = 1, FlagPageKeepsEscape = 2; + private const int StateOpenedInBrowser = 4; + + private static readonly StringBuilder Out = new(); + private static readonly List<string> Results = new(); + private static int _fails, _unverified; + + private static readonly ConcurrentQueue<string> LogLines = new(); + private static readonly ConcurrentQueue<string> ChatLines = new(); + private static readonly ConcurrentQueue<string> BrowserCalls = new(); + + private static readonly ConcurrentQueue<(Func<string> Fn, ManualResetEventSlim Done, string[] Result)> GameQ = new(); + private static IntPtr _game, _popOut; + private static uint _gameTid; + private static volatile int _gameKeyMsgs; + private static bool _haveForeground, _allowForeground; + + private static volatile Session? _pumpSession; + private static volatile int _pumpHandle; + private static volatile bool _pumpStop; + private static long _pumpCalls; + + private static string _root = ""; + + private static void W(string s) + { + string line = $"[{DateTime.Now:HH:mm:ss.fff}] {s}"; + Console.WriteLine(line); + lock (Out) Out.AppendLine(line); + } + + private static void Ok(string name) { Results.Add("ok " + name); W("ok " + name); } + private static void Fail(string name, string detail) { _fails++; Results.Add($"FAIL {name}: {detail}"); W($"FAIL {name}: {detail}"); } + private static void Unverified(string name, string detail) { _unverified++; Results.Add($"UNVERIFIED {name}: {detail}"); W($"UNVERIFIED {name}: {detail}"); } + + private static int Main(string[] args) + { + W($"harness pid={Environment.ProcessId} IntPtr.Size={IntPtr.Size} is64={Environment.Is64BitProcess} runtime={RuntimeInformation.FrameworkDescription} " + + $"invariantGlobalization={AppContext.TryGetSwitch("System.Globalization.Invariant", out bool inv) && inv}"); + if (IntPtr.Size != 4) { Fail("Bitness", $"IntPtr.Size={IntPtr.Size}; the harness must run 32-bit like acclient"); return Finish(); } + + string payloadDir = Path.Combine(AppContext.BaseDirectory, "payload"); + foreach (string a in args) + { + if (a.StartsWith("--payload=", StringComparison.Ordinal)) payloadDir = a.Substring(10); + // Opt in: the harness itself asks for the foreground (a plain SetForegroundWindow; Windows refuses it while + // the user is active elsewhere). Without it the foreground-dependent checks report UNVERIFIED. + if (a == "--foreground") _allowForeground = true; + } + if (Environment.GetEnvironmentVariable("WEBPANEL_HARNESS_FOREGROUND") == "1") _allowForeground = true; + _root = Path.Combine(Path.GetTempPath(), "rynth-webpanel-harness", DateTime.Now.ToString("yyyyMMdd-HHmmss")); + string lad = Path.Combine(_root, "LocalAppData"), panelDir = Path.Combine(_root, "panel"), otherDir = Path.Combine(_root, "other"); + WriteSite(panelDir, otherDir); + W($"payload {payloadDir}; temp root {_root}"); + + var up = new ManualResetEventSlim(); + var gt = new Thread(() => GameThread(up)) { IsBackground = true, Name = "FakeAcMain" }; + gt.SetApartmentState(ApartmentState.STA); + gt.Start(); + up.Wait(); + new Thread(PumpLoop) { IsBackground = true, Name = "FakeNormalPluginPump" }.Start(); + + // Foreground: only taken if this process may (it never forces it; no SendInput, no AttachThreadInput). + _haveForeground = EnsureForeground(_game); + W($"game window 0x{_game.ToInt64():X} tid={_gameTid}; harness may ask for the foreground (--foreground): {_allowForeground}; holds it: {_haveForeground} ({FgDesc()})"); + + // ---------------- session 1: the behaviour checks ---------------- + var s = new Session(payloadDir); + s.Call("Init", _game, payloadDir, lad, panelDir, otherDir, + (Action<string>)(l => { LogLines.Enqueue(l); W(" engine log: " + l); }), + (Action<string>)(c => { ChatLines.Enqueue(c); W(" chat: " + c); }), + (Action<string>)(u => { BrowserCalls.Enqueue(u); W(" browser call recorded"); })); + _pumpSession = s; + + int handle = 0; + Guard("OpenIsNonBlocking", () => handle = CheckOpenIsNonBlocking(s)); + Guard("CyclesReuseEnvironment", () => handle = CheckCycles(s, handle)); + Guard("KeysStayInPage", () => handle = CheckKeys(s)); + Guard("EscapeClosesAndRefocusesGame", () => CheckEscape(s, handle)); + Guard("PageKeepsEscapeFlag", () => handle = CheckPageKeepsEscape(s)); + Guard("OffListRedirectGoesToBrowser", () => CheckRedirect(s, handle)); + Guard("WindowOpenNeverMakesAWindow", () => CheckWindowOpen(s, handle)); + Guard("CustomSchemeNeverLaunched", () => CheckCustomScheme(s, handle)); + Guard("StaleHandles", () => handle = CheckStaleHandles(s, handle)); + Guard("ProfileSwitchRecreates", () => handle = CheckProfileSwitch(s)); + Guard("NoBrowserFallbackAfterNavigation", () => CheckNoFallbackAfterNavigation(s, handle)); + Guard("GpuProcessCrashKeepsPanel", () => handle = CheckGpuCrash(s)); + Guard("LateFailureForSupersededHandle", () => handle = CheckLateFailure(s)); + Guard("UnresponsiveCountResetsPerOpen", () => handle = CheckUnresponsiveReset(s)); + Guard("CreateFailureFallsBack", () => CheckCreateFailure(s)); + Guard("CreateFailureBrowserFails", () => CheckCreateFailureBrowserFails(s)); + Guard("NoFocusFromAnotherProcess", () => { int r = CheckNoFocusFromAnotherProcess(s); if (r > 0) handle = r; }); + Guard("VisibilitySameProcess", () => handle = CheckVisibilitySameProcess(s)); + Unverified("VisibilityOtherProcess", "needs another process to take the foreground (alt-tab); the harness never forces it. Owner in-game check."); + Guard("LayoutRemembered", () => handle = CheckLayout(s, lad)); + Guard("UnloadAfterCloseCollected", () => CheckUnloadAfterClose(ref s, handle)); + + // ---------------- session 2: unload with the panel up ---------------- + Guard("UnloadWhileVisibleCollected", () => CheckUnloadWhileVisible(payloadDir, lad, panelDir, otherDir)); + + Guard("NoSecretInLog", () => + { + int hits = LogLines.Count(l => l.Contains(Secret)) + ChatLines.Count(l => l.Contains(Secret)); + if (hits != 0) Fail("NoSecretInLog", $"{hits} log/chat line(s) contain {Secret}"); + else if (LogLines.IsEmpty) Fail("NoSecretInLog", "no engine log captured at all (the check would prove nothing)"); + else Ok("NoSecretInLog"); + }); + + _pumpStop = true; + W($"pump GetState calls from the fake pump thread: {Interlocked.Read(ref _pumpCalls)}"); + W($"fake game key messages total: {_gameKeyMsgs}"); + return Finish(); + } + + private static int Finish() + { + W("===== summary ====="); + foreach (string r in Results) W(r); + int exit = _fails > 0 ? 1 : _unverified > 0 ? 2 : 0; + W($"{Results.Count} checks: {Results.Count - _fails - _unverified} ok, {_fails} FAIL, {_unverified} UNVERIFIED -> exit {exit}"); + try { File.WriteAllText(Path.Combine(_root, "harness-output.txt"), Out.ToString()); } catch { } + return exit; + } + + private static void Guard(string name, Action check) + { + W($"----- {name} -----"); + try { check(); } + catch (Exception ex) { Fail(name, "threw " + (ex is TargetInvocationException t ? t.InnerException : ex)); } + } + + // ============================== checks ============================== + + private static int CheckOpenIsNonBlocking(Session s) + { + s.Call("SetEnvironmentDelay", 2000); + // Warm the argument reader and the host's validation once (an off-list URL never starts the thread). + var (warm, warmMs) = Open(s, "https://elsewhere.invalid/", Allow); + W($"warm-up open (off-list url) -> {warm} in {warmMs:F2} ms"); + bool threadBefore = (bool)s.Call("get_ThreadRunning")!; + string url = "https://panel.test/launch.html?code=" + Secret; + var (h, ms) = Open(s, url, Allow, title: "Harness launch"); + int[] st = State(s, h); + W($"first open -> handle {h} in {ms:F2} ms (thread running before: {threadBefore}); status right after: {st[2]}"); + bool ready = WaitStatus(s, h, StatusReady, 60000, out int[] fin); + string src = (string)s.Call("get_Source")!; + s.Call("SetEnvironmentDelay", 0); + if (h <= 0) { Fail("OpenIsNonBlocking", "open returned " + h); return h; } + if (threadBefore) { Fail("OpenIsNonBlocking", "the panel thread ran before the first open"); return h; } + if (ms >= 20) { Fail("OpenIsNonBlocking", $"open took {ms:F2} ms (>= 20)"); return h; } + if (st[2] != StatusStarting) { Fail("OpenIsNonBlocking", $"status right after open {st[2]}, want Starting"); return h; } + if (!ready) { Fail("OpenIsNonBlocking", $"never Ready: state [{string.Join(",", fin)}]"); return h; } + Ok("OpenIsNonBlocking"); + // The caller's buffers were overwritten with junk and freed right after Open returned (every Open does). + if (src != url) Fail("OpenCopiesCallerStrings", "page source is not the url passed in (redacted): " + Redact(src)); + else Ok("OpenCopiesCallerStrings"); + return h; + } + + private static int CheckCycles(Session s, int handle) + { + int envsBefore = (int)s.Call("get_EnvironmentCount")!; + int closeRc = (int)s.Call("Close", handle)!; + if (closeRc != CodeQueued || !WaitStatus(s, handle, StatusClosed, 5000, out _)) { Fail("CyclesReuseEnvironment", $"first close rc={closeRc} never Closed"); return handle; } + int modsAfter1 = -1, modsNow = -1; + var seq = new List<string>(); + int h = handle; + for (int c = 1; c <= 5; c++) + { + (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Cycle " + c); + bool r = WaitStatus(s, h, StatusReady, 30000, out int[] a); + int rc = (int)s.Call("Close", h)!; + bool cl = WaitStatus(s, h, StatusClosed, 5000, out int[] b); + seq.Add($"{c}:{(r ? "Ready" : "st" + a[2])}/{(cl ? "Closed" : "st" + b[2])}(rc {rc})"); + modsNow = WebViewModuleCount(); + if (c == 1) modsAfter1 = modsNow; + } + int envs = (int)s.Call("get_EnvironmentCount")!; + W($"cycles {string.Join(" ", seq)}; environments {envsBefore} -> {envs}; webview modules after cycle 1 = {modsAfter1}, after cycle 5 = {modsNow}"); + if (seq.Any(x => !x.Contains("Ready/Closed"))) Fail("CyclesReuseEnvironment", "a cycle missed Ready or Closed: " + string.Join(" ", seq)); + else if (envs != 1 || envsBefore != 1) Fail("CyclesReuseEnvironment", $"environments created {envs} (want exactly 1)"); + else if (modsNow != modsAfter1) Fail("CyclesReuseEnvironment", $"webview module count changed {modsAfter1} -> {modsNow}"); + else Ok("CyclesReuseEnvironment"); + return h; + } + + /// <summary> + /// The host moves keyboard focus into the page only while this process holds the foreground (never from + /// another program), so the posted-key checks are meaningful only then. + /// </summary> + private static bool ThisProcessHoldsForeground() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return false; + GetWindowThreadProcessId(fg, out uint pid); + return pid == Environment.ProcessId; + } + + private static int CheckKeys(Session s) + { + bool inProcess = ThisProcessHoldsForeground(); + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Keys"); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("KeysStayInPage", $"not Ready [{string.Join(",", a)}]"); return h; } + Thread.Sleep(500); + W("focus -> " + s.Call("Eval", "document.getElementById('t').focus(); JSON.stringify({active: document.activeElement && document.activeElement.id, hasFocus: document.hasFocus()})", 5000)); + IntPtr widget = RenderWidget(s, out string tree); + W("panel window tree: " + tree); + if (widget == IntPtr.Zero) { Fail("KeysStayInPage", "no Chrome_RenderWidgetHostHWND under the panel window"); return h; } + int g0 = _gameKeyMsgs, k0 = (int)s.Call("get_AcceleratorKeyEvents")!; + foreach (char ch in "x1q") PostKey(widget, char.ToUpperInvariant(ch), ch); + Thread.Sleep(1200); + string value = (string)s.Call("Eval", "document.getElementById('t').value", 5000)!; + int g = _gameKeyMsgs - g0; + W($"page input value {value}; fake game key messages during the test: {g}; AcceleratorKeyPressed events {(int)s.Call("get_AcceleratorKeyEvents")! - k0}; panel visible={IsWindowVisible((IntPtr)s.Call("get_HostHwnd")!)}; {FgDesc()}"); + Snap((IntPtr)s.Call("get_HostHwnd")!, Path.Combine(_root, "panel-keys.png")); + // The game-side count is informational only: the keys are posted straight to the Chromium window, so the + // game could not see them here whatever the host did. Input isolation (unowned popup, separate queue) is an + // owner in-game check: type in the panel, nothing reaches AC's chat. + W($"(informational, cannot fail: game key messages {g})"); + if (value.Contains("x1q")) Ok("KeysStayInPage"); + else if (!inProcess) Unverified("KeysStayInPage", $"page input is {value}: another process held the foreground at Open ({FgDesc()}), so by design the panel did not focus the page; owner in-game check (type in the panel)"); + else Fail("KeysStayInPage", $"page input is {value}, want x1q"); + return h; + } + + private static void CheckEscape(Session s, int handle) + { + IntPtr widget = RenderWidget(s, out _); + if (widget == IntPtr.Zero) { Fail("EscapeClosesAndRefocusesGame", "no render widget to post to"); return; } + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + bool panelFg = EnsureForeground(host); + s.Call("Eval", "document.getElementById('t').focus(); 1", 5000); + W($"before Escape: panel holds the foreground {panelFg} ({FgDesc()}), panel visible {IsWindowVisible(host)}"); + int acc0 = (int)s.Call("get_AcceleratorKeyEvents")!; + int g0 = _gameKeyMsgs; + PostKey(widget, 0x1B, '\x1b'); + bool closed = WaitStatus(s, handle, StatusClosed, 3000, out int[] st); + int acc = (int)s.Call("get_AcceleratorKeyEvents")! - acc0; + int g = _gameKeyMsgs - g0; + Thread.Sleep(200); + IntPtr fg = GetForegroundWindow(); + W($"after posted Escape: status {st[2]}, AcceleratorKeyPressed events {acc}, game key messages {g}, foreground {FgDesc()} (game 0x{_game.ToInt64():X})"); + if (acc == 0) + { + Unverified("EscapeClosesAndRefocusesGame", $"AcceleratorKeyPressed did not fire for a POSTED Escape (status {st[2]}, panel held the foreground: {panelFg}; the page itself gets posted keys, see KeysStayInPage); Escape-to-close needs the owner's in-game check"); + if (!closed) { s.Call("Close", handle); WaitStatus(s, handle, StatusClosed, 3000, out _); } + return; + } + if (!closed) { Fail("EscapeClosesAndRefocusesGame", $"AcceleratorKeyPressed fired but the panel is {st[2]}, not Closed"); return; } + if (!panelFg) { Unverified("EscapeClosesAndRefocusesGame", $"closed (game key messages {g}, informational only); the foreground hand-back could not be checked (the panel did not hold the foreground)"); return; } + if (fg != _game) { Fail("EscapeClosesAndRefocusesGame", "closed, but the foreground is not the game"); return; } + Ok("EscapeClosesAndRefocusesGame"); + } + + private static int CheckPageKeepsEscape(Session s) + { + bool inProcess = ThisProcessHoldsForeground(); + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Keeps Escape", flags: FlagFallback | FlagPageKeepsEscape); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("PageKeepsEscapeFlag", $"not Ready [{string.Join(",", a)}]"); return h; } + Thread.Sleep(400); + s.Call("Eval", "window.keys = []; document.getElementById('t').focus(); 1", 5000); + IntPtr widget = RenderWidget(s, out _); + int acc0 = (int)s.Call("get_AcceleratorKeyEvents")!; + PostKey(widget, 0x1B, '\x1b'); + Thread.Sleep(1200); + int acc = (int)s.Call("get_AcceleratorKeyEvents")! - acc0; + string keys = (string)s.Call("Eval", "JSON.stringify(window.keys)", 5000)!; + int[] st = State(s, h); + W($"flag 2: page keys {keys}, status {st[2]}, AcceleratorKeyPressed events {acc}"); + if (st[2] != StatusReady) Fail("PageKeepsEscapeFlag", $"panel status {st[2]}, want Ready (open)"); + else if (!keys.Contains("Escape") && !inProcess) Unverified("PageKeepsEscapeFlag", $"the page did not see Escape ({keys}): another process held the foreground at Open ({FgDesc()}), so by design the panel did not focus the page; owner in-game check"); + else if (!keys.Contains("Escape")) Fail("PageKeepsEscapeFlag", "the page keydown listener did not see Escape: " + keys); + else if (acc == 0) Unverified("PageKeepsEscapeFlag", "page saw Escape and stayed open, but AcceleratorKeyPressed never fired for posted input, so the flag path itself was not exercised"); + else Ok("PageKeepsEscapeFlag"); + return h; + } + + private static void CheckRedirect(Session s, int h) + { + Drain(BrowserCalls); + string before = (string)s.Call("get_Source")!; + int rc = (int)s.Call("Navigate", h, "https://go.panel.test/redirect?code=" + Secret)!; + Thread.Sleep(2500); + string after = (string)s.Call("get_Source")!; + string[] calls = BrowserCalls.ToArray(); + string want = "https://other.test/landing.html"; + W($"navigate rc {rc}; source {Redact(before)} -> {Redact(after)}; browser calls {calls.Length}: {string.Join(" | ", calls.Select(Redact))}"); + if (rc != CodeQueued) Fail("OffListRedirectGoesToBrowser", "navigate rc " + rc); + else if (calls.Length != 1) Fail("OffListRedirectGoesToBrowser", $"{calls.Length} browser call(s), want 1 (served-302 log lines: {LogLines.Count(l => l.Contains("served the 302"))})"); + else if (Redact(calls[0]) != want) Fail("OffListRedirectGoesToBrowser", "browser got " + Redact(calls[0])); + else if (!after.StartsWith("https://panel.test/", StringComparison.Ordinal)) Fail("OffListRedirectGoesToBrowser", "panel left panel.test: " + Redact(after)); + else Ok("OffListRedirectGoesToBrowser"); + } + + private static void CheckWindowOpen(Session s, int h) + { + Drain(BrowserCalls); + uint bpid = (uint)(int)s.Call("get_BrowserProcessId")!; + HashSet<IntPtr> before = TopLevelWindows(); + string r = (string)s.Call("Eval", "String(window.open('https://other.test/x.html?code=" + Secret + "'))", 5000)!; + Thread.Sleep(1500); + var fresh = TopLevelWindows().Where(w => !before.Contains(w) && IsWindowVisible(w)).Where(w => OwnedByUsOrWebView(w)).ToList(); + int calls = BrowserCalls.Count; + W($"window.open(other.test) -> {r}; new visible top-level windows of this process or msedgewebview2: {fresh.Count}; browser calls {calls}"); + string r2 = (string)s.Call("Eval", "String(window.open('https://panel.test/b.html'))", 5000)!; + bool onB = WaitFor(() => ((string)s.Call("get_Source")!).EndsWith("/b.html", StringComparison.Ordinal), 5000); + W($"window.open(panel.test/b.html) -> {r2}; panel on b.html: {onB}"); + if (fresh.Count != 0) Fail("WindowOpenNeverMakesAWindow", $"{fresh.Count} new top-level window(s)"); + else if (calls != 1) Fail("WindowOpenNeverMakesAWindow", $"{calls} browser call(s) for the off-list window.open, want 1"); + else if (!onB) Fail("WindowOpenNeverMakesAWindow", "window.open to an allowed url did not navigate the panel"); + else Ok("WindowOpenNeverMakesAWindow"); + WaitStatus(s, h, StatusReady, 5000, out _); + } + + private static void CheckCustomScheme(Session s, int h) + { + Drain(BrowserCalls); + string src0 = (string)s.Call("get_Source")!; + int[] st0 = State(s, h); + int logs0 = LogLines.Count; + s.Call("Eval", "location = 'ms-settings:'; 1", 5000); + Thread.Sleep(1500); + s.Call("Eval", "location = 'file:///C:/'; 1", 5000); + Thread.Sleep(1500); + string src = (string)s.Call("get_Source")!; + int[] st = State(s, h); + var newLogs = LogLines.Skip(logs0).ToList(); + W($"after ms-settings: and file:///C:/ -> source {Redact(src0)} -> {Redact(src)}; navigations {st0[6]} -> {st[6]}; browser calls {BrowserCalls.Count}; new log lines: {string.Join(" | ", newLogs)}"); + if (BrowserCalls.Count != 0) Fail("CustomSchemeNeverLaunched", "a browser call was made"); + else if (src != src0) Fail("CustomSchemeNeverLaunched", "the panel navigated away"); + else if (st[6] != st0[6]) Fail("CustomSchemeNeverLaunched", "the navigation count moved"); + else if (!newLogs.Any(l => l.Contains("(ms-settings)"))) Fail("CustomSchemeNeverLaunched", "no blocked-navigation log line for ms-settings:"); + else Ok("CustomSchemeNeverLaunched"); + } + + private static int CheckStaleHandles(Session s, int h) + { + var (h2, _) = Open(s, "https://panel.test/index.html", Allow, title: "Supersede"); + int[] old = State(s, h); + int nav = (int)s.Call("Navigate", h, "https://panel.test/b.html")!; + int close = (int)s.Call("Close", h)!; + bool ready = WaitStatus(s, h2, StatusReady, 30000, out _); + int offList = (int)s.Call("Navigate", h2, "https://other.test/x.html?code=" + Secret)!; + W($"old handle {h}: GetState {old[0]} status {old[2]}, Navigate {nav}, Close {close}; new handle {h2} = old + 1: {h2 == h + 1}; new Ready {ready}; off-list Navigate {offList}"); + Thread.Sleep(300); + if (old[0] != StatusSuperseded || old[2] != StatusSuperseded) Fail("StaleHandles", "old handle does not read Superseded"); + else if (nav != CodeStale || close != CodeStale) Fail("StaleHandles", $"old handle Navigate {nav} / Close {close}, want {CodeStale}"); + else if (h2 != h + 1) Fail("StaleHandles", "handles do not count up by one"); + else if (!ready) Fail("StaleHandles", "new handle never Ready"); + else if (offList != CodeUrlNotAllowed) Fail("StaleHandles", "off-list Navigate returned " + offList); + else Ok("StaleHandles"); + return h2; + } + + private static int CheckProfileSwitch(Session s) + { + int e0 = (int)s.Call("get_EnvironmentCount")!; + var (h1, _) = Open(s, "https://panel.test/index.html", Allow, key: "Alpha"); + bool r1 = WaitStatus(s, h1, StatusReady, 30000, out _); + int e1 = (int)s.Call("get_EnvironmentCount")!; + var (h2, _) = Open(s, "https://panel.test/b.html", Allow, key: "alpha "); + bool r2 = WaitStatus(s, h2, StatusReady, 30000, out _); + int e2 = (int)s.Call("get_EnvironmentCount")!; + string fDefault = (string)s.Call("ProfileFolder", "Harness World", "")!, fAlpha = (string)s.Call("ProfileFolder", "Harness World", "Alpha")!; + W($"environments {e0} -> {e1} (key Alpha) -> {e2} (key 'alpha ', same profile); folders default {Directory.Exists(fDefault)}, alpha {Directory.Exists(fAlpha)} ({fAlpha})"); + if (!r1 || !r2) Fail("ProfileSwitchRecreates", $"not Ready ({r1}, {r2})"); + else if (e1 != e0 + 1) Fail("ProfileSwitchRecreates", $"a new key did not create a new environment ({e0} -> {e1})"); + else if (e2 != e1) Fail("ProfileSwitchRecreates", $"the same key made another environment ({e1} -> {e2})"); + else if (fDefault == fAlpha || !Directory.Exists(fAlpha)) Fail("ProfileSwitchRecreates", "the alpha profile folder is missing or not separate"); + else Ok("ProfileSwitchRecreates"); + return h2; + } + + private static void CheckNoFallbackAfterNavigation(Session s, int h) + { + Drain(BrowserCalls); + int pid = (int)s.Call("get_BrowserProcessId")!; + if (pid == 0) { Fail("NoBrowserFallbackAfterNavigation", "no browser process id"); return; } + string name; + try { using var p = Process.GetProcessById(pid); name = p.ProcessName; if (!name.StartsWith("msedgewebview2", StringComparison.OrdinalIgnoreCase)) { Fail("NoBrowserFallbackAfterNavigation", "browser pid is " + name); return; } p.Kill(); } + catch (Exception ex) { Fail("NoBrowserFallbackAfterNavigation", "could not kill the panel's browser process: " + ex.Message); return; } + bool failed = WaitStatus(s, h, StatusFailed, 10000, out int[] st); + Thread.Sleep(500); + W($"killed browser pid {pid} ({name}); state [{string.Join(",", st)}]; browser calls {BrowserCalls.Count}"); + if (!failed) Fail("NoBrowserFallbackAfterNavigation", "status " + st[2] + ", want Failed"); + else if (st[4] != CodeProcessFailed) Fail("NoBrowserFallbackAfterNavigation", "error " + st[4] + ", want ProcessFailed"); + else if (BrowserCalls.Count != 0 || (st[3] & StateOpenedInBrowser) != 0) Fail("NoBrowserFallbackAfterNavigation", "fell back to the browser after a navigation"); + else Ok("NoBrowserFallbackAfterNavigation"); + // The next open recreates. + var (h2, _) = Open(s, "https://panel.test/index.html", Allow); + if (WaitStatus(s, h2, StatusReady, 30000, out int[] st2)) Ok("OpenAfterProcessFailedRecreates"); + else Fail("OpenAfterProcessFailedRecreates", $"[{string.Join(",", st2)}]"); + } + + private static int CheckGpuCrash(Session s) + { + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "GPU crash"); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("GpuProcessCrashKeepsPanel", $"not Ready [{string.Join(",", a)}]"); return h; } + uint browser = (uint)(int)s.Call("get_BrowserProcessId")!; + int children = 0, readable = 0, gpu = 0; + foreach (Process p in Process.GetProcessesByName("msedgewebview2")) + { + using (p) + { + if (ParentPid(p.Id) != browser) continue; + children++; + string? cmd = CommandLine(p.Id); + if (cmd == null) continue; + readable++; + if (gpu == 0 && cmd.Contains("--type=gpu-process", StringComparison.Ordinal)) gpu = p.Id; + } + } + W($"browser pid {browser}: {children} child process(es), {readable} command line(s) readable, gpu-process pid {gpu}"); + if (gpu == 0) { Unverified("GpuProcessCrashKeepsPanel", $"no msedgewebview2 child of browser pid {browser} with --type=gpu-process ({children} children, {readable} command lines read)"); return h; } + int logs0 = LogLines.Count; + try { using var p = Process.GetProcessById(gpu); p.Kill(); } + catch (Exception ex) { Unverified("GpuProcessCrashKeepsPanel", "could not kill the gpu process: " + ex.Message); return h; } + Thread.Sleep(3000); + int[] st = State(s, h); + string alive = (string)s.Call("Eval", "document.title", 5000)!; + bool open = (bool)s.Call("get_PanelOpen")!; + var newLogs = LogLines.Skip(logs0).ToList(); + W($"killed gpu pid {gpu}: state [{string.Join(",", st)}], panel open {open}, page title {alive}; log: {string.Join(" | ", newLogs)}"); + if (st[2] != StatusReady || st[4] != 0) Fail("GpuProcessCrashKeepsPanel", $"status {st[2]} error {st[4]}, want Ready with no error"); + else if (!open) Fail("GpuProcessCrashKeepsPanel", "the panel closed"); + else if (!newLogs.Any(l => l.Contains("GpuProcessExited"))) Unverified("GpuProcessCrashKeepsPanel", "panel stayed Ready, but no GpuProcessExited ProcessFailed event arrived within 3 s, so the handler path was not shown"); + else Ok("GpuProcessCrashKeepsPanel"); + return h; + } + + private static int CheckLateFailure(Session s) + { + var (a, _) = Open(s, "https://panel.test/index.html", Allow, title: "Old"); + bool ra = WaitStatus(s, a, StatusReady, 30000, out _); + var (b, _) = Open(s, "https://panel.test/b.html", Allow, title: "New"); + bool rb = WaitStatus(s, b, StatusReady, 30000, out _); + bool open0 = (bool)s.Call("get_PanelOpen")!; + bool posted = (bool)s.Call("FailHandle", a)!; + Thread.Sleep(600); + int[] st = State(s, b); + bool open = (bool)s.Call("get_PanelOpen")!; + W($"late synthetic failure for superseded handle {a} (posted {posted}): newer handle {b} state [{string.Join(",", st)}], panel open before {open0} after {open}"); + if (!ra || !rb || !open0) Fail("LateFailureForSupersededHandle", "setup: panels not Ready/open"); + else if (st[2] != StatusReady) Fail("LateFailureForSupersededHandle", $"newer panel status {st[2]}, want Ready"); + else if (!open) Fail("LateFailureForSupersededHandle", "the late failure hid the newer panel"); + else Ok("LateFailureForSupersededHandle"); + return b; + } + + // Two unresponsive reports, a new Open, one more report: the count starts again per panel, so the new one + // stays Ready (the limit is 3 within 30 s). Reports are injected through the host's own handler. + private static int CheckUnresponsiveReset(Session s) + { + var (a, _) = Open(s, "https://panel.test/index.html", Allow, title: "Hung A"); + bool ra = WaitStatus(s, a, StatusReady, 30000, out _); + s.Call("ReportUnresponsive"); s.Call("ReportUnresponsive"); + Thread.Sleep(300); + int[] sa = State(s, a); + var (b, _) = Open(s, "https://panel.test/b.html", Allow, title: "Hung B"); + bool rb = WaitStatus(s, b, StatusReady, 30000, out _); + s.Call("ReportUnresponsive"); + Thread.Sleep(500); + int[] sb = State(s, b); + W($"two reports on {a}: state [{string.Join(",", sa)}]; then Open {b} Ready {rb}, one more report: state [{string.Join(",", sb)}]"); + if (!ra || !rb) Fail("UnresponsiveCountResetsPerOpen", "setup: not Ready"); + else if (sa[2] != StatusReady) Fail("UnresponsiveCountResetsPerOpen", "two reports already failed the panel (limit is 3)"); + else if (sb[2] != StatusReady) Fail("UnresponsiveCountResetsPerOpen", $"the third report overall failed the new panel: status {sb[2]} error {sb[4]}"); + else Ok("UnresponsiveCountResetsPerOpen"); + return b; + } + + private static uint ParentPid(int pid) + { + IntPtr h = OpenProcess(0x1000 /* PROCESS_QUERY_LIMITED_INFORMATION */, false, pid); + if (h == IntPtr.Zero) return 0; + try + { + PROCESS_BASIC_INFORMATION pbi; + return NtQueryInformationProcess(h, 0, &pbi, sizeof(PROCESS_BASIC_INFORMATION), out _) == 0 ? (uint)pbi.InheritedFromUniqueProcessId.ToInt64() : 0; + } + finally { CloseHandle(h); } + } + + /// <summary>ProcessCommandLineInformation (60): a UNICODE_STRING followed by its text, in our buffer.</summary> + private static string? CommandLine(int pid) + { + IntPtr h = OpenProcess(0x1000, false, pid); + if (h == IntPtr.Zero) return null; + try + { + byte[] buf = new byte[65536]; + fixed (byte* b = buf) + { + if (NtQueryInformationProcess(h, 60, b, buf.Length, out _) != 0) return null; + int len = *(ushort*)b; + char* text = *(char**)(b + IntPtr.Size); + return text == null ? null : new string(text, 0, len / 2); + } + } + finally { CloseHandle(h); } + } + + private static void CheckCreateFailure(Session s) + { + Drain(BrowserCalls); + Drain(ChatLines); + s.Call("SetBrowserFolder", Path.Combine(_root, "no-such-browser")); + s.Call("SetBrowserDelay", 300); // a slow browser launch widens any Failed-before-flag window + int samples = 0, failedNoFlag = 0; + bool failed = false; + int[] st; + try + { + var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow, key: "beta"); + // Poll continuously: a plugin that sees Failed without OpenedInBrowser would open the page a second time. + var sw = Stopwatch.StartNew(); + st = State(s, h); + while (sw.ElapsedMilliseconds < 20000) + { + st = State(s, h); + samples++; + if (st[2] == StatusFailed && (st[3] & StateOpenedInBrowser) == 0) failedNoFlag++; + if (st[2] == StatusFailed && (st[3] & StateOpenedInBrowser) != 0) { failed = true; break; } + if (st[2] == StatusFailed && failedNoFlag > 400) break; // the flag is not coming + Thread.Sleep(1); + } + if (!failed) failed = st[2] == StatusFailed; + } + finally { s.Call("SetBrowserDelay", 0); s.Call("SetBrowserFolder", (string?)null); } + string[] calls = BrowserCalls.ToArray(); + W($"forced create failure: state [{string.Join(",", st)}]; {samples} samples, {failedNoFlag} showed Failed without OpenedInBrowser; browser calls {calls.Length}; chat: {string.Join(" | ", ChatLines)}"); + if (!failed) Fail("CreateFailureFallsBack", "status " + st[2]); + else if (failedNoFlag > 0) Fail("CreateFailureFallsBack", $"{failedNoFlag} of {samples} samples showed Failed without OpenedInBrowser (a polling plugin would open the page twice)"); + else if (st[4] != CodeCreateFailed) Fail("CreateFailureFallsBack", "error " + st[4] + ", want CreateFailed"); + else if ((st[3] & StateOpenedInBrowser) == 0) Fail("CreateFailureFallsBack", "OpenedInBrowser flag not set"); + else if (calls.Length != 1 || Redact(calls[0]) != "https://panel.test/launch.html") Fail("CreateFailureFallsBack", $"{calls.Length} browser call(s)"); + else if (!ChatLines.Any(c => c.Contains("could not start (it failed to start)"))) Fail("CreateFailureFallsBack", "no fallback chat line"); + else Ok("CreateFailureFallsBack"); + } + + private static void CheckCreateFailureBrowserFails(Session s) + { + Drain(BrowserCalls); + Drain(ChatLines); + s.Call("SetBrowserFolder", Path.Combine(_root, "no-such-browser")); + s.Call("SetBrowserFails", true); + int[] st; + bool failed; + try + { + var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow, key: "beta"); + failed = WaitStatus(s, h, StatusFailed, 20000, out st); + WaitFor(() => ChatLines.Any(c => c.Contains("could not start")), 3000); + } + finally { s.Call("SetBrowserFails", false); s.Call("SetBrowserFolder", (string?)null); } + string[] chat = ChatLines.ToArray(); + W($"create failure, browser fails: state [{string.Join(",", st)}]; browser calls {BrowserCalls.Count}; chat: {string.Join(" | ", chat)}"); + if (!failed) Fail("CreateFailureBrowserFails", "status " + st[2]); + else if (st[4] != CodeCreateFailed) Fail("CreateFailureBrowserFails", "error " + st[4] + ", want CreateFailed"); + else if ((st[3] & StateOpenedInBrowser) != 0) Fail("CreateFailureBrowserFails", "OpenedInBrowser flag set although the browser did not open"); + else if (chat.Any(c => c.Contains("opened the page"))) Fail("CreateFailureBrowserFails", "chat claims the page opened"); + else if (!chat.Any(c => c.Contains("could not start (it failed to start), and your web browser did not open"))) Fail("CreateFailureBrowserFails", "no browser-did-not-open chat line"); + else Ok("CreateFailureBrowserFails"); + } + + /// <summary> + /// Only when the foreground already belongs to another process (the harness never arranges it): opening a + /// panel must leave that process in front. When this harness holds the foreground the check is UNVERIFIED. + /// </summary> + private static int CheckNoFocusFromAnotherProcess(Session s) + { + IntPtr fg0 = GetForegroundWindow(); + uint pid0 = 0; + if (fg0 != IntPtr.Zero) GetWindowThreadProcessId(fg0, out pid0); + int bpid = (int)s.Call("get_BrowserProcessId")!; + if (fg0 == IntPtr.Zero || pid0 == Environment.ProcessId || (bpid != 0 && pid0 == bpid)) + { + Unverified("NoFocusFromAnotherProcess", $"the foreground is not another process ({FgDesc()}); the harness never forces it there. Owner in-game check (alt-tab away, open the panel from a plugin)"); + return 0; + } + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "No focus"); + bool ready = WaitStatus(s, h, StatusReady, 30000, out int[] st); + Thread.Sleep(500); + IntPtr fg1 = GetForegroundWindow(); + uint pid1 = 0; + if (fg1 != IntPtr.Zero) GetWindowThreadProcessId(fg1, out pid1); + W($"foreground before pid {pid0}, after open pid {pid1} ({FgDesc()}); state [{string.Join(",", st)}]"); + if (!ready) Fail("NoFocusFromAnotherProcess", "not Ready"); + else if (pid1 == Environment.ProcessId || (bpid != 0 && pid1 == bpid)) Fail("NoFocusFromAnotherProcess", "the panel took the foreground from another process"); + else Ok("NoFocusFromAnotherProcess"); + return h; + } + + private static int CheckVisibilitySameProcess(Session s) + { + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Visibility"); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("VisibilitySameProcess", $"not Ready [{string.Join(",", a)}]"); return h; } + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + if (!EnsureForeground(host)) + { + Unverified("VisibilitySameProcess", $"the harness does not hold the foreground (--foreground {_allowForeground}; {FgDesc()}), so no in-process window can take it; owner in-game check (pop out a RynthCore window, panel stays)"); + return h; + } + Thread.Sleep(300); + bool visBefore = IsWindowVisible(host); + Game(() => { _popOut = CreateWindowExW(0, "FakeAcClient", "Fake pop-out", 0x00CF0000, 300, 300, 400, 300, IntPtr.Zero, IntPtr.Zero, GetModuleHandleW(IntPtr.Zero), IntPtr.Zero); ShowWindow(_popOut, 5); SetForegroundWindow(_popOut); return ""; }); + Thread.Sleep(600); + bool fgIsPop = GetForegroundWindow() == _popOut; + bool vis = IsWindowVisible(host); + Game(() => { DestroyWindow(_popOut); SetForegroundWindow(_game); return ""; }); + Thread.Sleep(300); + W($"panel visible before {visBefore}; pop-out foreground {fgIsPop}; panel visible with the pop-out in front {vis}; now {FgDesc()}"); + if (!visBefore) Fail("VisibilitySameProcess", "panel not visible before the pop-out"); + else if (!fgIsPop) Unverified("VisibilitySameProcess", "the pop-out could not take the foreground"); + else if (!vis) Fail("VisibilitySameProcess", "panel hid when another window of this process took the foreground"); + else Ok("VisibilitySameProcess"); + return h; + } + + private static int CheckLayout(Session s, string lad) + { + string path = Path.Combine(lad, "RynthCore", "WebPanel", "layout.json"); + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + // A drag is a modal loop inside DefWindowProc; WM_EXITSIZEMOVE is what the host saves on. Post the + // pair around a move made with SetWindowPos (no input involved). + GetClientRect(_game, out RECT gc); + var p = new POINT(); + ClientToScreen(_game, ref p); + PostMessageW(host, 0x0231 /* WM_ENTERSIZEMOVE */, IntPtr.Zero, IntPtr.Zero); + Thread.Sleep(150); + SetWindowPos(host, IntPtr.Zero, p.X + 20, p.Y + 30, gc.Right / 2, gc.Bottom / 2, 0x0004 | 0x0010); + PostMessageW(host, 0x0232 /* WM_EXITSIZEMOVE */, IntPtr.Zero, IntPtr.Zero); + bool saved = WaitFor(() => File.Exists(path), 3000); + string json = saved ? File.ReadAllText(path) : ""; + var (h, _) = Open(s, "https://panel.test/index.html", Allow, w: 40, hgt: 40); + WaitStatus(s, h, StatusReady, 30000, out _); + Thread.Sleep(300); + GetWindowRect(host, out RECT r); + W($"layout.json saved {saved}: {json}; panel after reopen at 40% request: [{r.Left - p.X},{r.Top - p.Y},{r.Right - r.Left}x{r.Bottom - r.Top}] client {gc.Right}x{gc.Bottom}"); + bool remembered = Math.Abs(r.Left - p.X - 20) <= 2 && Math.Abs(r.Top - p.Y - 30) <= 2 && Math.Abs((r.Right - r.Left) - gc.Right / 2) <= 2; + if (!saved) Fail("LayoutRemembered", "no layout.json after WM_EXITSIZEMOVE"); + else if (!json.Contains("\"x\"") || !json.Contains("\"h\"")) Fail("LayoutRemembered", "layout.json has no x/y/w/h: " + json); + else if (!remembered) Fail("LayoutRemembered", "the reopened panel did not take the stored layout over the 40% request"); + else Ok("LayoutRemembered"); + try { File.Delete(path); } catch { } + return h; + } + + private static void CheckUnloadAfterClose(ref Session s, int handle) + { + int[] st = State(s, handle); + int live = st[1]; + s.Call("Close", live); + WaitStatus(s, live, StatusClosed, 5000, out _); + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + var sd = Stopwatch.StartNew(); + s.Call("Shutdown", 2000); + W($"Shutdown(2000) returned in {sd.ElapsedMilliseconds} ms (panel closed)"); + bool stopped = !(bool)s.Call("get_ThreadRunning")!; + var (afterOpen, _) = Open(s, "https://panel.test/index.html", Allow); + int afterState = State(s, live)[0]; + int afterClose = (int)s.Call("Close", live)!; + W($"after Shutdown: thread stopped {stopped}, host window alive {IsWindow(host)}, Open {afterOpen}, GetState {afterState}, Close {afterClose}"); + if (!stopped || IsWindow(host) || afterOpen != CodeShuttingDown || afterState != CodeShuttingDown || afterClose != CodeShuttingDown) + Fail("ShutdownRefusesCalls", "thread or window survived, or a call did not return ShuttingDown"); + else Ok("ShutdownRefusesCalls"); + UnloadAndJudge("UnloadAfterCloseCollected", ref s); + } + + private static void CheckUnloadWhileVisible(string payloadDir, string lad, string panelDir, string otherDir) + { + var s = new Session(payloadDir); + s.Call("Init", _game, payloadDir, lad, panelDir, otherDir, + (Action<string>)(l => { LogLines.Enqueue(l); W(" engine log (2): " + l); }), + (Action<string>)(c => ChatLines.Enqueue(c)), + (Action<string>)(u => BrowserCalls.Enqueue(u))); + _pumpSession = s; + var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] st)) { Fail("UnloadWhileVisibleCollected", $"not Ready [{string.Join(",", st)}]"); } + bool visible = IsWindowVisible((IntPtr)s.Call("get_HostHwnd")!); + W($"session 2 open: state [{string.Join(",", State(s, h))}] host visible {visible}"); + var sd = Stopwatch.StartNew(); + s.Call("Shutdown", 2000); + W($"Shutdown(2000) returned in {sd.ElapsedMilliseconds} ms (panel open; window shown only if the harness held the foreground)"); + UnloadAndJudge("UnloadWhileVisibleCollected", ref s, visible ? null : "collected, but the panel window was not visible (the PID rule hid it: the harness did not hold the foreground), so the visible-teardown path was not shown"); + } + + private static void UnloadAndJudge(string name, ref Session s, string? unverifiedIfCollected = null) + { + _pumpSession = null; + _pumpHandle = 0; + Thread.Sleep(100); + s.Call("Release"); + WeakReference weak = s.Unload(); + s = null!; + var sw = Stopwatch.StartNew(); + while (weak.IsAlive && sw.ElapsedMilliseconds < 3000) { GC.Collect(); GC.WaitForPendingFinalizers(); if (weak.IsAlive) Thread.Sleep(20); } + W($"{name}: context {(weak.IsAlive ? "STILL HELD" : "collected")} after {sw.ElapsedMilliseconds} ms"); + if (weak.IsAlive) Fail(name, "the payload context was not collected within 3000 ms"); + else if (unverifiedIfCollected != null) Unverified(name, unverifiedIfCollected); + else Ok(name); + } + + // ============================== helpers ============================== + + private static (int Rc, double Ms) Open(Session s, string url, string allow, string key = "", string title = "", + uint flags = FlagFallback, int w = 0, int hgt = 0) + { + IntPtr pUrl = Utf8(url), pAllow = Utf8(allow), pKey = key.Length == 0 ? IntPtr.Zero : Utf8(key), pTitle = title.Length == 0 ? IntPtr.Zero : Utf8(title); + IntPtr pArgs = Marshal.AllocHGlobal(sizeof(OpenArgs)); + var a = (OpenArgs*)pArgs; + *a = default; + a->Size = (uint)sizeof(OpenArgs); + a->Flags = flags; + a->Url = (byte*)pUrl; a->Allowlist = (byte*)pAllow; a->ProfileKey = (byte*)pKey; a->Title = (byte*)pTitle; + a->WidthPercent = w; a->HeightPercent = hgt; + double ms = 0; + string r = Game(() => + { + long t0 = Stopwatch.GetTimestamp(); + int rc = (int)s.Call("Open", pArgs)!; + ms = Stopwatch.GetElapsedTime(t0).TotalMilliseconds; + // The SDK's buffers are stack or pooled: gone the moment the call returns. Junk them, then free. + Junk(pUrl); Junk(pAllow); Junk(pKey); Junk(pTitle); + new Span<byte>((void*)pArgs, sizeof(OpenArgs)).Fill(0xCD); + return rc.ToString(); + }); + foreach (IntPtr p in new[] { pUrl, pAllow, pKey, pTitle, pArgs }) if (p != IntPtr.Zero) Marshal.FreeHGlobal(p); + int code = int.TryParse(r, out int v) ? v : int.MinValue; + if (code > 0) _pumpHandle = code; + return (code, ms); + } + + private static readonly Dictionary<IntPtr, int> Sizes = new(); + private static IntPtr Utf8(string s) + { + byte[] b = Encoding.UTF8.GetBytes(s + "\0"); + IntPtr p = Marshal.AllocHGlobal(b.Length); + Marshal.Copy(b, 0, p, b.Length); + lock (Sizes) Sizes[p] = b.Length; + return p; + } + private static void Junk(IntPtr p) + { + if (p == IntPtr.Zero) return; + int n; lock (Sizes) n = Sizes[p]; + new Span<byte>((void*)p, n - 1).Fill((byte)'Z'); + } + + private static int[] State(Session s, int h) => (int[])s.Call("GetState", h)!; + + private static bool WaitStatus(Session s, int h, int want, int ms, out int[] last) + { + var sw = Stopwatch.StartNew(); + last = State(s, h); + while (sw.ElapsedMilliseconds < ms) + { + last = State(s, h); + if (last[2] == want) return true; + if (want != StatusFailed && last[2] == StatusFailed) return false; + Thread.Sleep(25); + } + return false; + } + + private static bool WaitFor(Func<bool> f, int ms) + { + var sw = Stopwatch.StartNew(); + while (sw.ElapsedMilliseconds < ms) { if (f()) return true; Thread.Sleep(25); } + return f(); + } + + /// <summary>A plain SetForegroundWindow from the game thread (no input, no AttachThreadInput): Windows grants it or not.</summary> + private static bool EnsureForeground(IntPtr target) + { + if (IsOurs(GetForegroundWindow(), target)) return true; + if (!_allowForeground) return false; + Game(() => SetForegroundWindow(target) ? "1" : "0"); + Thread.Sleep(200); + return IsOurs(GetForegroundWindow(), target); + } + + private static bool IsOurs(IntPtr fg, IntPtr target) => fg != IntPtr.Zero && (fg == target || GetAncestor(fg, 2 /* GA_ROOT */) == target); + + private static string FgDesc() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return "foreground none"; + GetWindowThreadProcessId(fg, out uint pid); + return $"foreground 0x{fg.ToInt64():X} {Cls(fg)} pid {pid}{(pid == Environment.ProcessId ? " (this harness)" : "")}"; + } + + private static void Drain<T>(ConcurrentQueue<T> q) { while (q.TryDequeue(out _)) { } } + + private static string Redact(string? url) + { + if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.Absolute, out Uri? u) || u.Host.Length == 0) return "<invalid url>"; + return u.Scheme + "://" + u.Host + (u.IsDefaultPort ? "" : ":" + u.Port) + u.AbsolutePath; + } + + private static void PostKey(IntPtr h, int vk, char ch) + { + uint scan = MapVirtualKeyW((uint)vk, 0); + IntPtr down = (IntPtr)(int)(1 | (scan << 16)), up = unchecked((IntPtr)(int)(1 | (scan << 16) | 0xC0000000)); + // Down and up only: the browser's own TranslateMessage makes the WM_CHAR (posting one too typed every key twice). + PostMessageW(h, 0x0100, (IntPtr)vk, down); + PostMessageW(h, 0x0101, (IntPtr)vk, up); + Thread.Sleep(60); + } + + private static IntPtr RenderWidget(Session s, out string tree) + { + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + var all = new List<IntPtr>(); + Collect(host, all); + var sb = new StringBuilder(); + IntPtr widget = IntPtr.Zero; + foreach (IntPtr c in all) + { + string cls = Cls(c); + GetWindowThreadProcessId(c, out uint pid); + sb.Append($"[0x{c.ToInt64():X} {cls} pid {pid}] "); + if (widget == IntPtr.Zero && cls == "Chrome_RenderWidgetHostHWND") widget = c; + } + tree = sb.ToString(); + return widget; + } + + private static void Collect(IntPtr h, List<IntPtr> into) + { + for (IntPtr c = GetWindow(h, 5 /* GW_CHILD */); c != IntPtr.Zero; c = GetWindow(c, 2 /* GW_HWNDNEXT */)) + { + into.Add(c); + Collect(c, into); + } + } + + private static List<IntPtr>? _enumInto; + private static HashSet<IntPtr> TopLevelWindows() + { + _enumInto = new List<IntPtr>(); + EnumWindows(&EnumProc, IntPtr.Zero); + var set = new HashSet<IntPtr>(_enumInto); + _enumInto = null; + return set; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int EnumProc(IntPtr h, IntPtr l) { _enumInto?.Add(h); return 1; } + + private static bool OwnedByUsOrWebView(IntPtr w) + { + GetWindowThreadProcessId(w, out uint pid); + if (pid == Environment.ProcessId) return true; + try { using var p = Process.GetProcessById((int)pid); return p.ProcessName.StartsWith("msedgewebview2", StringComparison.OrdinalIgnoreCase); } + catch { return false; } + } + + private static int WebViewModuleCount() + { + using var p = Process.GetCurrentProcess(); + p.Refresh(); + int n = 0; + foreach (ProcessModule m in p.Modules) + if (m.ModuleName.Contains("WebView", StringComparison.OrdinalIgnoreCase) || m.ModuleName.Contains("EmbeddedBrowser", StringComparison.OrdinalIgnoreCase)) n++; + return n; + } + + // ---- screenshot (PrintWindow PW_RENDERFULLCONTENT -> PNG), from the spike ---- + private static void Snap(IntPtr h, string path) + { + try + { + GetWindowRect(h, out RECT r); + int w = r.Right - r.Left, ht = r.Bottom - r.Top; + if (w <= 0 || ht <= 0) { W("screenshot skipped: empty window rect"); return; } + IntPtr sdc = GetDC(IntPtr.Zero), mdc = CreateCompatibleDC(sdc), bmp = CreateCompatibleBitmap(sdc, w, ht); + IntPtr old = SelectObject(mdc, bmp); + bool ok = PrintWindow(h, mdc, 2); + var bi = new BITMAPINFOHEADER { biSize = 40, biWidth = w, biHeight = -ht, biPlanes = 1, biBitCount = 32 }; + byte[] px = new byte[w * ht * 4]; + fixed (byte* p = px) GetDIBits(mdc, bmp, 0, (uint)ht, p, ref bi, 0); + SelectObject(mdc, old); DeleteObject(bmp); DeleteDC(mdc); ReleaseDC(IntPtr.Zero, sdc); + WritePng(path, w, ht, px); + W($"screenshot {path} ({w}x{ht}, PrintWindow ok={ok}, window visible={IsWindowVisible(h)})"); + } + catch (Exception ex) { W("screenshot failed: " + ex.Message); } + } + + private static void WritePng(string path, int w, int h, byte[] bgra) + { + using var raw = new MemoryStream(); + using (var z = new ZLibStream(raw, CompressionLevel.Fastest, true)) + for (int y = 0; y < h; y++) + { + z.WriteByte(0); + for (int x = 0; x < w; x++) { int i = (y * w + x) * 4; z.WriteByte(bgra[i + 2]); z.WriteByte(bgra[i + 1]); z.WriteByte(bgra[i]); } + } + using var f = File.Create(path); + f.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }); + var ihdr = new byte[13]; + BE(ihdr, 0, w); BE(ihdr, 4, h); ihdr[8] = 8; ihdr[9] = 2; + Chunk(f, "IHDR", ihdr); Chunk(f, "IDAT", raw.ToArray()); Chunk(f, "IEND", Array.Empty<byte>()); + } + + private static void BE(byte[] b, int o, int v) { b[o] = (byte)(v >> 24); b[o + 1] = (byte)(v >> 16); b[o + 2] = (byte)(v >> 8); b[o + 3] = (byte)v; } + + private static uint[]? _crc; + private static void Chunk(Stream s, string type, byte[] data) + { + if (_crc == null) { _crc = new uint[256]; for (uint n = 0; n < 256; n++) { uint c = n; for (int k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1; _crc[n] = c; } } + var len = new byte[4]; BE(len, 0, data.Length); s.Write(len); + var td = new byte[4 + data.Length]; Encoding.ASCII.GetBytes(type).CopyTo(td, 0); data.CopyTo(td, 4); s.Write(td); + uint crc = 0xFFFFFFFF; foreach (byte b in td) crc = _crc[(crc ^ b) & 0xFF] ^ (crc >> 8); crc ^= 0xFFFFFFFF; + var cb = new byte[4]; BE(cb, 0, (int)crc); s.Write(cb); + } + + private static string Cls(IntPtr h) { char* b = stackalloc char[128]; int n = GetClassNameW(h, b, 128); return new string(b, 0, n); } + + private static void WriteSite(string panelDir, string otherDir) + { + Directory.CreateDirectory(panelDir); + Directory.CreateDirectory(otherDir); + string Page(string title) => + "<!doctype html><html><head><meta charset=\"utf-8\"><title>" + title + "" + + "

" + title + "

" + + ""; + File.WriteAllText(Path.Combine(panelDir, "index.html"), Page("panel index")); + File.WriteAllText(Path.Combine(panelDir, "launch.html"), Page("panel launch")); + File.WriteAllText(Path.Combine(panelDir, "b.html"), Page("panel b")); + File.WriteAllText(Path.Combine(otherDir, "landing.html"), Page("other landing")); + File.WriteAllText(Path.Combine(otherDir, "x.html"), Page("other x")); + } + + // ============================== fake game ============================== + + private static string Game(Func fn) + { + var done = new ManualResetEventSlim(); + var res = new string[1]; + GameQ.Enqueue((fn, done, res)); + PostThreadMessageW(_gameTid, 0x8000 + 7, IntPtr.Zero, IntPtr.Zero); + if (!done.Wait(20000)) return "GAME THREAD TIMEOUT"; + return res[0]; + } + + private static void GameThread(ManualResetEventSlim up) + { + _gameTid = GetCurrentThreadId(); + string cls = "FakeAcClient"; + fixed (char* pc = cls) + { + var wc = new WNDCLASSEXW { cbSize = (uint)sizeof(WNDCLASSEXW), lpfnWndProc = (IntPtr)(delegate* unmanaged[Stdcall])&GameWndProc, hInstance = GetModuleHandleW(IntPtr.Zero), hbrBackground = (IntPtr)(1 + 1), lpszClassName = (IntPtr)pc }; + RegisterClassExW(ref wc); + } + _game = CreateWindowExW(0, cls, "Fake acclient (web panel harness)", 0x00CF0000 /* WS_OVERLAPPEDWINDOW */, 40, 40, 1100, 750, IntPtr.Zero, IntPtr.Zero, GetModuleHandleW(IntPtr.Zero), IntPtr.Zero); + ShowWindow(_game, 4 /* SW_SHOWNOACTIVATE */); + up.Set(); + while (true) + { + while (PeekMessageW(out MSG m, IntPtr.Zero, 0, 0, 1)) + { + if (m.hwnd == IntPtr.Zero && m.message == 0x8000 + 7) continue; + TranslateMessage(ref m); + DispatchMessageW(ref m); + } + while (GameQ.TryDequeue(out var job)) + { + try { job.Result[0] = job.Fn(); } catch (Exception ex) { job.Result[0] = "THREW " + (ex.InnerException ?? ex); } + job.Done.Set(); + } + MsgWaitForMultipleObjects(0, IntPtr.Zero, false, 10, 0x04FF); + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static IntPtr GameWndProc(IntPtr h, uint m, IntPtr w, IntPtr l) + { + if (m is 0x0100 or 0x0101 or 0x0102 or 0x0104 or 0x0105) Interlocked.Increment(ref _gameKeyMsgs); + return DefWindowProcW(h, m, w, l); + } + + private static void PumpLoop() + { + while (!_pumpStop) + { + Thread.Sleep(16); + PumpOnce(); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void PumpOnce() + { + Session? s = _pumpSession; + int h = _pumpHandle; + if (s == null || h == 0) return; + try { s.Call("GetState", h); Interlocked.Increment(ref _pumpCalls); } catch { } + } + + // ============================== payload context ============================== + + /// The payload in a collectible context (the shim's EngineLoadContext, reproduced). + private sealed class Session + { + private PayloadContext? _alc; + private Type? _type; + + public Session(string dir) + { + _alc = new PayloadContext(dir); + Assembly asm = _alc.LoadFromStreamOf(Path.Combine(dir, "WebPanelHarness.Payload.dll")); + _type = asm.GetType("RynthCore.Engine.WebPanel.PayloadEntry", throwOnError: true)!; + W($"payload loaded into a collectible context (IsCollectible={_alc.IsCollectible}, location '{asm.Location}')"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public object? Call(string name, params object?[] args) + { + Type t = _type ?? throw new InvalidOperationException("payload unloaded"); + MethodInfo m = t.GetMethod(name, BindingFlags.Public | BindingFlags.Static) + ?? throw new MissingMethodException(name); + return m.Invoke(null, args); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public WeakReference Unload() + { + PayloadContext alc = _alc!; + _alc = null; + _type = null; + alc.Unload(); + return new WeakReference(alc, trackResurrection: true); + } + } + + private sealed class PayloadContext : AssemblyLoadContext + { + private static readonly HashSet PrivateFramework = new(StringComparer.OrdinalIgnoreCase) { "System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines" }; + private readonly string _dir; + public PayloadContext(string dir) : base("web panel payload", isCollectible: true) => _dir = dir; + + public Assembly LoadFromStreamOf(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + string pdb = Path.ChangeExtension(path, ".pdb"); + if (!File.Exists(pdb)) return LoadFromStream(fs); + using var ps = new FileStream(pdb, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + return LoadFromStream(fs, ps); + } + + protected override Assembly? Load(AssemblyName name) + { + string? simple = name.Name; + if (string.IsNullOrEmpty(simple)) return null; + if (PrivateFramework.Contains(simple)) + { + string fx = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location)!, simple + ".dll"); + return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null; + } + string local = Path.Combine(_dir, simple + ".dll"); + return File.Exists(local) ? LoadFromStreamOf(local) : null; + } + + protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) + { + string candidate = Path.Combine(_dir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? unmanagedDllName : unmanagedDllName + ".dll"); + return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : IntPtr.Zero; + } + } + + // ============================== interop ============================== + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct OpenArgs + { + public uint Size, Flags; + public byte* Url, Allowlist, ProfileKey, Title; + public int WidthPercent, HeightPercent; + public fixed uint Reserved[4]; + } + + [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] private struct BITMAPINFOHEADER { public uint biSize; public int biWidth, biHeight; public ushort biPlanes, biBitCount; public uint biCompression, biSizeImage; public int biXPelsPerMeter, biYPelsPerMeter; public uint biClrUsed, biClrImportant; } + [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] private struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; } + [StructLayout(LayoutKind.Sequential)] private struct WNDCLASSEXW { public uint cbSize, style; public IntPtr lpfnWndProc; public int cbClsExtra, cbWndExtra; public IntPtr hInstance, hIcon, hCursor, hbrBackground, lpszMenuName, lpszClassName, hIconSm; } + + [DllImport("user32.dll")] private static extern ushort RegisterClassExW(ref WNDCLASSEXW wc); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private 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")] private static extern bool DestroyWindow(IntPtr h); + [DllImport("user32.dll")] private static extern IntPtr DefWindowProcW(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr h, int c); + [DllImport("user32.dll")] private static extern bool PeekMessageW(out MSG m, IntPtr h, uint a, uint b, uint r); + [DllImport("user32.dll")] private static extern bool TranslateMessage(ref MSG m); + [DllImport("user32.dll")] private static extern IntPtr DispatchMessageW(ref MSG m); + [DllImport("user32.dll")] private static extern bool PostThreadMessageW(uint t, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] private static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] private static extern uint MsgWaitForMultipleObjects(uint n, IntPtr h, bool all, uint ms, uint mask); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] private static extern bool IsWindow(IntPtr h); + [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr h, uint c); + [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr h, uint f); + [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassNameW(IntPtr h, char* b, int n); + [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr h, IntPtr a, int x, int y, int cx, int cy, uint f); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr h, ref POINT p); + [DllImport("user32.dll")] private static extern uint MapVirtualKeyW(uint code, uint type); + [DllImport("user32.dll")] private static extern bool EnumWindows(delegate* unmanaged[Stdcall] fn, IntPtr l); + [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr h); + [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr h, IntPtr dc); + [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr h, IntPtr dc, uint f); + [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleDC(IntPtr dc); + [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int w, int h); + [DllImport("gdi32.dll")] private static extern IntPtr SelectObject(IntPtr dc, IntPtr o); + [DllImport("gdi32.dll")] private static extern bool DeleteObject(IntPtr o); + [DllImport("gdi32.dll")] private static extern bool DeleteDC(IntPtr dc); + [DllImport("gdi32.dll")] private static extern int GetDIBits(IntPtr dc, IntPtr bmp, uint start, uint lines, byte* bits, ref BITMAPINFOHEADER bi, uint usage); + [StructLayout(LayoutKind.Sequential)] private struct PROCESS_BASIC_INFORMATION { public IntPtr ExitStatus, PebBaseAddress, AffinityMask, BasePriority, UniqueProcessId, InheritedFromUniqueProcessId; } + [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess(IntPtr h, int cls, void* info, int len, out int ret); + [DllImport("kernel32.dll")] private static extern IntPtr OpenProcess(uint access, bool inherit, int pid); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr h); + [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); + [DllImport("kernel32.dll")] private static extern IntPtr GetModuleHandleW(IntPtr n); +} diff --git a/tools/WebPanelHarness/WebPanelHarness.csproj b/tools/WebPanelHarness/WebPanelHarness.csproj new file mode 100644 index 0000000..6f320aa --- /dev/null +++ b/tools/WebPanelHarness/WebPanelHarness.csproj @@ -0,0 +1,52 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + true + enable + enable + true + WebPanelHarness + + + + + + + + + + + + + <_PayloadDir>@(_PayloadTarget->'%(RootDir)%(Directory)') + + + <_PayloadFiles Include="$(_PayloadDir)**\*.*" /> + + + + + diff --git a/tools/WebPanelTests/Program.cs b/tools/WebPanelTests/Program.cs new file mode 100644 index 0000000..9073cc5 --- /dev/null +++ b/tools/WebPanelTests/Program.cs @@ -0,0 +1,326 @@ +using System.Text; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.WebPanel; + +namespace WebPanelTests; + +/// The web panel's pure policies: URL allowlist, redaction, visibility, layout, profile folder. +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(); + BrowserGate(); + 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 got, T want, string what) => + Check(EqualityComparer.Default.Equals(got, want), $"{what}: got {got}, want {want}"); + + private static void BrowserGate() + { + Case("browser gate: off-list pages reach the system browser only after a click, rate-limited"); + var g = new WebPanelBrowserGate(); + Eq(g.Decide(userInitiated: false, 0), BrowserOpenVerdict.NotUserInitiated, "a page's own request (script, ad iframe) is dropped"); + Eq(g.Decide(userInitiated: true, 0), BrowserOpenVerdict.Open, "a click opens it"); + Eq(g.Decide(userInitiated: true, 500), BrowserOpenVerdict.TooSoon, "a second within the gap is dropped"); + Eq(g.Decide(userInitiated: false, 5000), BrowserOpenVerdict.NotUserInitiated, "no click is never opened, even after the gap"); + long t = 0; + int opened = 1; + for (int i = 0; i < 10; i++) + { + t += WebPanelBrowserGate.MinGapMs; + if (g.Decide(true, t) == BrowserOpenVerdict.Open) opened++; + } + Eq(opened, WebPanelBrowserGate.MaxPerMinute, "at most MaxPerMinute a minute, however spaced"); + Eq(g.Decide(true, 61_000 + WebPanelBrowserGate.MinGapMs), BrowserOpenVerdict.Open, "the minute passes: opens again"); + var fresh = new WebPanelBrowserGate(); + Eq(fresh.Decide(true, long.MinValue + 1), BrowserOpenVerdict.Open, "a first open at any clock value opens"); + } + + 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()), "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"), "", "garbage"); + Eq(WebPanelUrlPolicy.Redact(null), "", "null"); + Eq(WebPanelUrlPolicy.Redact(""), "", "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"); + } +} diff --git a/tools/WebPanelTests/WebPanelTests.csproj b/tools/WebPanelTests/WebPanelTests.csproj new file mode 100644 index 0000000..6808076 --- /dev/null +++ b/tools/WebPanelTests/WebPanelTests.csproj @@ -0,0 +1,31 @@ + + + + + Exe + net10.0 + enable + enable + true + WebPanelTests + true + $(NoWarn);CS0649;CS0169 + + + + + + + + + + + + + +