RynthCore as of 2026-11-10 (internal b7e3008): release 2026.11.10.1
This commit is contained in:
parent
7cb161cf44
commit
55e15c0ac4
59 changed files with 6963 additions and 1030 deletions
|
|
@ -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> <tab>", 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")),
|
||||
};
|
||||
|
||||
/// <summary>/rc uicost: the UI frame cost breakdown (ImGui/UiCost.cs).</summary>
|
||||
|
|
|
|||
|
|
@ -108,6 +108,9 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// <item><c>/rc uicost [on|off|<ms>|now|status]</c> - the UI frame cost breakdown
|
||||
/// (<see cref="ImGuiBackend.UiCost"/>): timing on or off, the slow-frame threshold, and (now, or
|
||||
/// alone) which parts of the UI frame took the time over the last seconds. Also Settings > Diagnostics.</item>
|
||||
/// <item><c>/rc webpanel [status|close]</c> - the in-game web panel (<see cref="WebPanel.WebPanelApi"/>):
|
||||
/// status is one redacted line (state, handle, visible/focused, browser pid, free address space);
|
||||
/// close closes the panel. It never opens a URL.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class RynthCoreChatCommands
|
||||
|
|
@ -650,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 <n|all> | tab <n> <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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "/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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /rc webpanel [status|close]. Status: one redacted line (WebPanelApi.Describe plus the address
|
||||
/// space). Close: closes the live panel (WebPanelApi.Close does not block). Nothing here opens a URL.
|
||||
/// </summary>
|
||||
private static void HandleWebPanelCommand(string args)
|
||||
{
|
||||
string a = args.Trim().ToLowerInvariant();
|
||||
if (a == "close")
|
||||
{
|
||||
int handle = WebPanel.WebPanelApi.LiveHandle;
|
||||
if (handle <= 0) { Reply("web panel: nothing to close."); return; }
|
||||
int rc = WebPanel.WebPanelApi.Close(handle);
|
||||
// 1 = closing, 0 = already closed (the WebPanelCode values); anything else is a refusal or error.
|
||||
if (rc == 1) Reply("web panel: closing.");
|
||||
else if (rc == 0) Reply("web panel: already closed.");
|
||||
else Fail($"web panel: could not close (code {rc}).");
|
||||
return;
|
||||
}
|
||||
Reply(WebPanel.WebPanelApi.Describe() + "; address space " + AddressSpace.Describe());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /rc layout: which panel layout this client uses and its files (UI/PanelLayout: the character's own,
|
||||
/// or the PC-wide default and why); default makes this character's the default for new characters;
|
||||
|
|
|
|||
|
|
@ -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]<IntPtr, IntPtr, byte>)_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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static byte CallOriginalCatchDrop(IntPtr catcher, IntPtr dragDropInfo)
|
||||
{
|
||||
if (!SehTrampoline.IsAvailable)
|
||||
return ((delegate* unmanaged[Thiscall]<IntPtr, IntPtr, byte>)_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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
|
|
|
|||
79
src/RynthCore.Engine/ImGui/BarMenuHover.cs
Normal file
79
src/RynthCore.Engine/ImGui/BarMenuHover.cs
Normal file
|
|
@ -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;
|
||||
/// <summary>Frames further apart than this (or a clock that runs backwards) reset the state.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The bar button id whose dropdown is open, else null.</summary>
|
||||
public string? OpenFor { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Once per frame. <paramref name="hoveredButton"/>: id of the menu-bearing bar button under the mouse, else null.
|
||||
/// <paramref name="overMenu"/>: the mouse is over the open dropdown. <paramref name="now"/>: seconds.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An item was clicked, or the bar went away.</summary>
|
||||
public void Close()
|
||||
{
|
||||
OpenFor = null;
|
||||
_leftAt = null;
|
||||
_closedByClick = _hovered;
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<string, bool> 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);
|
||||
}
|
||||
|
||||
/// <summary>The bar's letter fallback: the first letter or digit of <paramref name="text"/>, upper-cased, else "?".</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bar icon dropdown of the button <see cref="BarMenuHover.OpenFor"/> 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.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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]<void*>)_getCurrentWindow)();
|
||||
if (window != null) ((delegate* unmanaged[Cdecl]<void*, void>)_bringToFront)(window);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -256,11 +256,14 @@ internal static class ImGuiPanelHost
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Changes a dynamic face's header text. Any thread.</summary>
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -109,6 +109,23 @@ internal static unsafe class ImGuiPopOuts
|
|||
/// <summary>True while a pop-out's ImGui frame is being built (inside a face's Draw). AC thread.</summary>
|
||||
public static bool InPopOutFrame => _current != null;
|
||||
|
||||
private static int _mainFrame;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static int FrameNumber =>
|
||||
_current != null || ImGuiNET.ImGui.GetCurrentContext() == IntPtr.Zero ? _mainFrame : ImGuiNET.ImGui.GetFrameCount();
|
||||
|
||||
/// <summary>
|
||||
/// Records the main context's frame number for <see cref="FrameNumber"/>. 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.
|
||||
/// </summary>
|
||||
public static void NoteMainFrame() => _mainFrame = ImGuiNET.ImGui.GetFrameCount();
|
||||
|
||||
/// <summary>
|
||||
/// 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;
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
1125
src/RynthCore.Engine/ImGui/Panels/ChatView.cs
Normal file
1125
src/RynthCore.Engine/ImGui/Panels/ChatView.cs
Normal file
File diff suppressed because it is too large
Load diff
265
src/RynthCore.Engine/ImGui/Panels/ChatWindowFace.cs
Normal file
265
src/RynthCore.Engine/ImGui/Panels/ChatWindowFace.cs
Normal file
|
|
@ -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.<n>.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;
|
||||
/// <summary>The tab saved for this window ("" when none).</summary>
|
||||
private string _savedTab = "";
|
||||
private int _readGeneration = -1, _readVersion = -1;
|
||||
private string _shownHeader = "";
|
||||
|
||||
/// <summary>Goes up when any window's saved tab changes: the open ones read theirs again.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>The extra windows' panels: once, at engine init, beside the main chat.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Reads this window's saved tab (on open, after a layout switch, after a tab was saved).</summary>
|
||||
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<ChatLine>();
|
||||
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 : "";
|
||||
|
||||
/// <summary>Saves the tab window <paramref name="number"/> shows: the player picked it.</summary>
|
||||
private static void SaveTab(int number, string tab)
|
||||
{
|
||||
PanelStateStore.SetValue(ChatWindows.TabValueKey(number), tab);
|
||||
Interlocked.Increment(ref s_tabsVersion);
|
||||
}
|
||||
|
||||
/// <summary>The extra windows are registered (RynthChat is installed and the ImGui layer is on). Any thread.</summary>
|
||||
internal static bool Available =>ImGuiPanelHost.HasFace(ChatWindows.Key(ChatWindows.FirstNumber));
|
||||
|
||||
private const string NotAvailable = "Chat windows aren't available (the ImGui layer is off?).";
|
||||
|
||||
/// <summary>
|
||||
/// Opens <paramref name="tab"/> (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.
|
||||
/// </summary>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>Shows <paramref name="tab"/> in window <paramref name="number"/> (opening it if closed).</summary>
|
||||
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")}.");
|
||||
}
|
||||
|
||||
/// <summary>One line per extra window: open or closed, its tab, docked or popped out.</summary>
|
||||
public static List<string> Describe()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The player renamed a tab (ChatModel.RenameCustomTab): the windows that show it follow. Any thread.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -70,7 +70,9 @@ internal static unsafe class ScriptWindowReplay
|
|||
/// <summary>Draws <paramref name="w"/>'s latest list into the current window. AC thread.</summary>
|
||||
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
|
||||
|
|
|
|||
|
|
@ -70,6 +70,8 @@ internal static class EngineSettings
|
|||
private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode;
|
||||
// "TransitionGate": default true. False = queued game actions are never held for a death / portal.
|
||||
private static bool _transitionGate = true;
|
||||
// "WebPanel": default true. False = the v94 web panel calls answer Unavailable (plugins open the system browser).
|
||||
private static bool _webPanel = true;
|
||||
private static bool _loaded;
|
||||
|
||||
public static IReadOnlyList<string> PluginPaths
|
||||
|
|
@ -714,6 +716,26 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>"WebPanel" in engine.json (default true): the v94 web panel (WebPanel\WebPanelHost.cs, a
|
||||
/// WebView2 window over the game for DreamWeave's market and tools; CoreCLR engine only). False is the
|
||||
/// kill switch: WebPanelOpen answers Unavailable and plugins open the page in the system browser
|
||||
/// instead. A panel already open stays until it is closed.</summary>
|
||||
public static bool WebPanel
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _webPanel;
|
||||
}
|
||||
set
|
||||
{
|
||||
EnsureLoaded();
|
||||
if (_webPanel == value) return;
|
||||
_webPanel = value;
|
||||
Save("WebPanel");
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddPluginPath(string path)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
|
@ -919,6 +941,10 @@ internal static class EngineSettings
|
|||
(tgEl.ValueKind == JsonValueKind.True || tgEl.ValueKind == JsonValueKind.False))
|
||||
_transitionGate = tgEl.GetBoolean();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("WebPanel", out var wpEl) &&
|
||||
(wpEl.ValueKind == JsonValueKind.True || wpEl.ValueKind == JsonValueKind.False))
|
||||
_webPanel = wpEl.GetBoolean();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
|
||||
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
|
||||
{
|
||||
|
|
@ -989,7 +1015,7 @@ internal static class EngineSettings
|
|||
"FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "RememberWindowLayout",
|
||||
"RememberAcWindowPosition", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
|
||||
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel",
|
||||
"LoadAllServerPlugins", "TransitionGate",
|
||||
"LoadAllServerPlugins", "TransitionGate", "WebPanel",
|
||||
"HoldReloadInWorld", "HoldReloadInWorldMaxMinutes",
|
||||
"PanelLayoutPerCharacter",
|
||||
"UiCostLog", "UiCostThresholdMs",
|
||||
|
|
@ -1070,6 +1096,8 @@ internal static class EngineSettings
|
|||
w.WriteBoolean("CloseOnServerDisconnect", false);
|
||||
if (!_transitionGate) // default true: only a hand-set false is written
|
||||
w.WriteBoolean("TransitionGate", false);
|
||||
if (!_webPanel) // default true: only a hand-set false is written
|
||||
w.WriteBoolean("WebPanel", false);
|
||||
if (_loadAllServerPlugins) // default false: only a hand-set true is written
|
||||
w.WriteBoolean("LoadAllServerPlugins", true);
|
||||
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
|
||||
|
|
|
|||
|
|
@ -1069,6 +1069,74 @@ internal struct RynthCoreAPI
|
|||
/// reading, 0 without (never read; *ratio = -1, *ageMs = 0xFFFFFFFF). Either pointer may be null.
|
||||
/// Read-only, any thread, no game calls. Requires API v93+.</summary>
|
||||
public IntPtr GetMonsterHealthFn;
|
||||
|
||||
// ── v94: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ──
|
||||
// No call blocks its caller (AC's main thread, the plugin pump and ImGui draws all call these).
|
||||
|
||||
/// <summary>v94: <c>int WebPanelOpen(WebPanelOpenNative* open)</c>: opens (or replaces) the web panel.
|
||||
/// Returns a handle > 0, or BadArgs / UrlNotAllowed / NoGameWindow / Unavailable / ShuttingDown
|
||||
/// (WebPanelCode). Requires API v94+ (provisional number).</summary>
|
||||
public IntPtr WebPanelOpenFn;
|
||||
/// <summary>v94: <c>int WebPanelNavigate(int handle, byte* url)</c>: 1 queued; -2 off the allowlist
|
||||
/// (opened in the system browser when it is browser-safe); -6 stale handle.</summary>
|
||||
public IntPtr WebPanelNavigateFn;
|
||||
/// <summary>v94: <c>int WebPanelClose(int handle)</c>: 1 queued, 0 already closed, -6 stale handle.</summary>
|
||||
public IntPtr WebPanelCloseFn;
|
||||
/// <summary>v94: <c>int WebPanelGetState(int handle, WebPanelStateNative* state)</c>: the WebPanelStatusCode
|
||||
/// (a handle that is not the live one reads 6 Superseded), -1 bad args.</summary>
|
||||
public IntPtr WebPanelGetStateFn;
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct WebPanelOpenNative
|
||||
{
|
||||
/// <summary>sizeof the caller's struct; the engine accepts Size >= OffsetOf(Reserved) (32 on x86).</summary>
|
||||
public uint Size;
|
||||
/// <summary>WebPanelFlags; unknown bits ignored.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>UTF-8 NUL-terminated, at most 4096 bytes, must pass the URL policy's IsAllowed.</summary>
|
||||
public byte* Url;
|
||||
/// <summary>UTF-8, '\n'-separated allowlist (WebPanelUrlPolicy.TryParseAllowlist).</summary>
|
||||
public byte* Allowlist;
|
||||
/// <summary>UTF-8, may be null; at most 256 bytes.</summary>
|
||||
public byte* ProfileKey;
|
||||
/// <summary>UTF-8, may be null; at most 128 bytes.</summary>
|
||||
public byte* Title;
|
||||
/// <summary>0 = 88, else 30..100 (only when no remembered layout).</summary>
|
||||
public int WidthPercent;
|
||||
public int HeightPercent;
|
||||
public fixed uint Reserved[4];
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelGetState result (Pack 4; 48 bytes). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct WebPanelStateNative
|
||||
{
|
||||
public uint Size;
|
||||
public int Handle;
|
||||
/// <summary>WebPanelStatusCode.</summary>
|
||||
public int Status;
|
||||
/// <summary>1 Visible, 2 Focused, 4 OpenedInBrowser.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>0 or a negative WebPanelCode (RuntimeMissing / CreateFailed / ProcessFailed).</summary>
|
||||
public int Error;
|
||||
public int LastHttpStatus;
|
||||
public uint NavigationCount;
|
||||
public fixed uint Reserved[5];
|
||||
}
|
||||
|
||||
/// <summary>v94 return codes of the web panel calls. Append only.</summary>
|
||||
internal enum WebPanelCode
|
||||
{
|
||||
Queued = 1, AlreadyClosed = 0, BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3,
|
||||
Unavailable = -4, ShuttingDown = -5, StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9,
|
||||
}
|
||||
|
||||
/// <summary>v94 WebPanelStateNative.Status values. Append only.</summary>
|
||||
internal enum WebPanelStatusCode
|
||||
{
|
||||
None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6,
|
||||
}
|
||||
|
||||
/// <summary>v89 GetUiColor tokens. Append only: plugins compiled against these numbers keep them.</summary>
|
||||
|
|
@ -1930,6 +1998,18 @@ internal unsafe delegate int GetAmbientLightCallbackDelegate(uint* client, uint*
|
|||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetMonsterHealthCallbackDelegate(uint id, float* ratio, uint* ageMs);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WebPanelOpenCallbackDelegate(WebPanelOpenNative* open);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WebPanelNavigateCallbackDelegate(int handle, byte* url);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int WebPanelCloseCallbackDelegate(int handle);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int WebPanelGetStateCallbackDelegate(int handle, WebPanelStateNative* state);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count);
|
||||
|
||||
|
|
|
|||
|
|
@ -47,5 +47,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.
|
||||
/// <summary>The API version that added the "barMenu" manifest key; a plugin declaring it pins its own copy against this.</summary>
|
||||
public const uint BarMenu = 95;
|
||||
|
||||
public const uint Current = 95;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -304,6 +304,12 @@ internal static partial class PluginManager
|
|||
private static SetAmbientLightFloorCallbackDelegate? _setAmbientLightFloorCallback; // v91
|
||||
private static GetAmbientLightCallbackDelegate? _getAmbientLightCallback; // v91
|
||||
private static GetMonsterHealthCallbackDelegate? _getMonsterHealthCallback; // v93
|
||||
#if ENGINE_CORECLR
|
||||
private static WebPanelOpenCallbackDelegate? _webPanelOpenCallback; // v94
|
||||
private static WebPanelNavigateCallbackDelegate? _webPanelNavigateCallback; // v94
|
||||
private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v94
|
||||
private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v94
|
||||
#endif
|
||||
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
|
||||
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
|
||||
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
|
||||
|
|
@ -3254,6 +3260,13 @@ internal static partial class PluginManager
|
|||
_setAmbientLightFloorCallback ??= AmbientLight.SetFloor; // v91
|
||||
unsafe { _getAmbientLightCallback ??= AmbientLight.Get; }
|
||||
unsafe { _getMonsterHealthCallback ??= GetMonsterHealthAction; } // v93
|
||||
#if ENGINE_CORECLR
|
||||
// v94: the AOT engine leaves these slots zero, so HasWebPanel is false there.
|
||||
unsafe { _webPanelOpenCallback ??= WebPanel.WebPanelApi.Open; }
|
||||
unsafe { _webPanelNavigateCallback ??= WebPanel.WebPanelApi.Navigate; }
|
||||
_webPanelCloseCallback ??= WebPanel.WebPanelApi.Close;
|
||||
unsafe { _webPanelGetStateCallback ??= WebPanel.WebPanelApi.GetState; }
|
||||
#endif
|
||||
|
||||
_api.Version = PluginContractVersion.Current;
|
||||
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
|
||||
|
|
@ -3427,6 +3440,12 @@ internal static partial class PluginManager
|
|||
_api.SetAmbientLightFloorFn = Marshal.GetFunctionPointerForDelegate(_setAmbientLightFloorCallback);
|
||||
_api.GetAmbientLightFn = Marshal.GetFunctionPointerForDelegate(_getAmbientLightCallback);
|
||||
_api.GetMonsterHealthFn = Marshal.GetFunctionPointerForDelegate(_getMonsterHealthCallback);
|
||||
#if ENGINE_CORECLR
|
||||
_api.WebPanelOpenFn = Marshal.GetFunctionPointerForDelegate(_webPanelOpenCallback!);
|
||||
_api.WebPanelNavigateFn = Marshal.GetFunctionPointerForDelegate(_webPanelNavigateCallback!);
|
||||
_api.WebPanelCloseFn = Marshal.GetFunctionPointerForDelegate(_webPanelCloseCallback!);
|
||||
_api.WebPanelGetStateFn = Marshal.GetFunctionPointerForDelegate(_webPanelGetStateCallback!);
|
||||
#endif
|
||||
RouteApiThroughLoader();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,8 +43,37 @@
|
|||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles>
|
||||
<DebugType>portable</DebugType>
|
||||
<!-- The web panel (WebPanel\WebPanelHost.cs) uses only the WebView2 Core wrapper: no WinRT projection. -->
|
||||
<WebView2UseWinRT>false</WebView2UseWinRT>
|
||||
<WebView2LoaderPreference>Dynamic</WebView2LoaderPreference>
|
||||
</PropertyGroup>
|
||||
|
||||
<!--
|
||||
v94 web panel: WebView2 on the CoreCLR engine only. NativeAOT cannot host the Core wrapper's COM
|
||||
interop, so that build drops the host and its Win32/WebView2 glue (WebPanelApi.cs answers Unavailable
|
||||
there and PluginManager leaves the table slots zero).
|
||||
-->
|
||||
<ItemGroup Condition="'$(EngineHost)' == 'coreclr'">
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(EngineHost)' != 'coreclr'">
|
||||
<Compile Remove="WebPanel\WebPanelHost.cs;WebPanel\WebPanelNative.cs;WebPanel\EngineWebPanelEnvironment.cs;WebPanel\IWebPanelEnvironment.cs" />
|
||||
</ItemGroup>
|
||||
<!-- The package references its WinForms and WPF controls unconditionally; the engine uses neither. Dropped
|
||||
before reference resolution, so they are neither compiled against nor copied to the output. -->
|
||||
<Target Name="DropWebView2UiAssemblies" BeforeTargets="ResolveAssemblyReferences" Condition="'$(EngineHost)' == 'coreclr'">
|
||||
<ItemGroup>
|
||||
<Reference Remove="@(Reference)" Condition="'%(Filename)' == 'Microsoft.Web.WebView2.WinForms' Or '%(Filename)' == 'Microsoft.Web.WebView2.Wpf'" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
<Target Name="DropWebView2UiCopies" AfterTargets="ResolveAssemblyReferences" Condition="'$(EngineHost)' == 'coreclr'">
|
||||
<ItemGroup>
|
||||
<ReferenceCopyLocalPaths Remove="@(ReferenceCopyLocalPaths)" Condition="'%(Filename)' == 'Microsoft.Web.WebView2.WinForms' Or '%(Filename)' == 'Microsoft.Web.WebView2.Wpf'" />
|
||||
<!-- The Core wrapper's XML doc file is not needed at run time. -->
|
||||
<ReferenceCopyLocalPaths Remove="@(ReferenceCopyLocalPaths)" Condition="'%(Filename)%(Extension)' == 'Microsoft.Web.WebView2.Core.xml'" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<StackTraceSupport>true</StackTraceSupport>
|
||||
<DebugType>full</DebugType>
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static void OnActivated()
|
||||
{
|
||||
_historyIndex = -1;
|
||||
SetInput("", 0, null);
|
||||
string text = _input.Text;
|
||||
SetInput(text, text.Length, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
152
src/RynthCore.Engine/UI/Data/ChatWindows.cs
Normal file
152
src/RynthCore.Engine/UI/Data/ChatWindows.cs
Normal file
|
|
@ -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.<n>.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;
|
||||
|
||||
/// <summary>What "/rc chatwindow ..." asks for.</summary>
|
||||
internal enum ChatWindowVerb { List, Open, Close, CloseAll, Tab, Error }
|
||||
|
||||
/// <summary>A parsed "/rc chatwindow" line. Number: the window (2..); Tab: as typed.</summary>
|
||||
internal readonly record struct ChatWindowCommand(ChatWindowVerb Verb, int Number = 0, string Tab = "", string Error = "");
|
||||
|
||||
internal static class ChatWindows
|
||||
{
|
||||
/// <summary>How many extra chat windows there are (the main chat is window 1).</summary>
|
||||
public const int MaxWindows = 6;
|
||||
|
||||
/// <summary>The first extra window's number ("Chat 2").</summary>
|
||||
public const int FirstNumber = 2;
|
||||
|
||||
/// <summary>The last extra window's number.</summary>
|
||||
public const int LastNumber = FirstNumber + MaxWindows - 1;
|
||||
|
||||
/// <summary>The tab a window shows when its own is gone (as the main chat does).</summary>
|
||||
public const string FallbackTab = "All";
|
||||
|
||||
public const string Usage =
|
||||
"Usage: /rc chatwindow [list] | open [tab] | close <2-7|all> | tab <2-7> <tab>";
|
||||
|
||||
/// <summary>The panel key of window <paramref name="number"/>: "Chat 2".</summary>
|
||||
public static string Key(int number) => "Chat " + number.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Every extra window's key, in order.</summary>
|
||||
public static IEnumerable<string> Keys()
|
||||
{
|
||||
for (int n = FirstNumber; n <= LastNumber; n++) yield return Key(n);
|
||||
}
|
||||
|
||||
/// <summary>The window number in a key ("Chat 3" is 3); false for any other key.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The layout value that holds window <paramref name="number"/>'s tab.</summary>
|
||||
public static string TabValueKey(int number) =>
|
||||
"chatwin." + number.ToString(System.Globalization.CultureInfo.InvariantCulture) + ".tab";
|
||||
|
||||
/// <summary>The first window that isn't open, or 0 when all are.</summary>
|
||||
public static int FirstFree(Func<string, bool> isOpen)
|
||||
{
|
||||
for (int n = FirstNumber; n <= LastNumber; n++)
|
||||
if (!isOpen(Key(n))) return n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static string EffectiveTab(string? saved, IReadOnlyList<string> allTabs) =>
|
||||
Resolve(saved, allTabs) ?? FallbackTab;
|
||||
|
||||
/// <summary>The tab called <paramref name="typed"/> (any case), as it is spelled; null when there is none.</summary>
|
||||
public static string? Resolve(string? typed, IReadOnlyList<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>A window's saved tab after the player renamed <paramref name="from"/>: the new name, or null for no change.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The header text of a window showing <paramref name="tab"/>.</summary>
|
||||
public static string HeaderText(int number, string tab) =>
|
||||
"Chat " + number.ToString(System.Globalization.CultureInfo.InvariantCulture) + " · " + tab;
|
||||
|
||||
/// <summary>
|
||||
/// "/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".
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>"3 Combat" or "chat 3 Combat": the window number, and what follows it.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,9 @@
|
|||
// barlayout=<rows>,<maxIconsPerRow> (BarLayout; only when not 1,0)
|
||||
// panel.<title>=<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();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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++)
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -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)));
|
||||
}
|
||||
|
|
|
|||
63
src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs
Normal file
63
src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>The web panel host's surroundings inside acclient.exe (CoreCLR engine only).</summary>
|
||||
internal sealed class EngineWebPanelEnvironment : IWebPanelEnvironment
|
||||
{
|
||||
private readonly string _runtimeDir = FindRuntimeDir();
|
||||
|
||||
public IntPtr GameHwnd
|
||||
{
|
||||
get
|
||||
{
|
||||
IntPtr h = ImGuiBackend.Win32Backend.GameHwnd;
|
||||
return h != IntPtr.Zero ? h : EntryPoint.GameHwnd;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runtime\: the folder of the loaded RynthCore.Shim assembly, as ManagedPlugins.FindSharedDir finds it.
|
||||
/// Never this assembly's Location: the engine is stream-loaded, so that is empty.
|
||||
/// </summary>
|
||||
public string RuntimeDir => _runtimeDir;
|
||||
|
||||
public string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
|
||||
public string WorldName => Compatibility.AccountHooks.TryGetWorldName(out string name) ? name : "";
|
||||
|
||||
public void Log(string line) => RynthLog.Info("WebPanel: " + line);
|
||||
|
||||
public void Chat(string line) => Compatibility.ClientHelperHooks.WriteToChat(line, 1);
|
||||
|
||||
public bool OpenInBrowser(string url)
|
||||
{
|
||||
if (!WebPanelUrlPolicy.IsBrowserSafe(url)) return false;
|
||||
IntPtr r = WebPanelNative.ShellExecuteW(IntPtr.Zero, "open", url, null, null, WebPanelNative.SW_SHOWNORMAL);
|
||||
return r.ToInt64() > 32;
|
||||
}
|
||||
|
||||
public Thread StartStaThread(string name, ThreadStart body) => EngineThreads.Start(name, body, ApartmentState.STA);
|
||||
|
||||
public Action<CoreWebView2>? ConfigureForTests => null;
|
||||
public int EnvironmentDelayMsForTests => 0;
|
||||
public string? BrowserExecutableFolderForTests => null;
|
||||
|
||||
private static string FindRuntimeDir()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
|
||||
{
|
||||
if (a.GetName().Name != "RynthCore.Shim" || string.IsNullOrEmpty(a.Location)) continue;
|
||||
return Path.GetDirectoryName(a.Location) ?? "";
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return "";
|
||||
}
|
||||
}
|
||||
32
src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs
Normal file
32
src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>
|
||||
/// What the web panel host needs from its surroundings: the engine (EngineWebPanelEnvironment) or the
|
||||
/// offline harness (tools\WebPanelHarness.Payload). CoreCLR engine only.
|
||||
/// </summary>
|
||||
internal interface IWebPanelEnvironment
|
||||
{
|
||||
IntPtr GameHwnd { get; }
|
||||
/// <summary>Folder holding WebView2Loader.dll and Microsoft.Web.WebView2.Core.dll.</summary>
|
||||
string RuntimeDir { get; }
|
||||
/// <summary>Profile and layout root (the harness: a temp folder).</summary>
|
||||
string LocalAppData { get; }
|
||||
/// <summary>"" when unknown.</summary>
|
||||
string WorldName { get; }
|
||||
/// <summary>Only ever given WebPanelUrlPolicy.Redact()ed URLs or hosts.</summary>
|
||||
void Log(string line);
|
||||
/// <summary>Any thread.</summary>
|
||||
void Chat(string line);
|
||||
/// <summary>IsBrowserSafe URLs only; the harness records instead of launching.</summary>
|
||||
bool OpenInBrowser(string url);
|
||||
Thread StartStaThread(string name, ThreadStart body);
|
||||
/// <summary>Null in the engine.</summary>
|
||||
Action<Microsoft.Web.WebView2.Core.CoreWebView2>? ConfigureForTests { get; }
|
||||
/// <summary>0 in the engine.</summary>
|
||||
int EnvironmentDelayMsForTests { get; }
|
||||
/// <summary>Null in the engine (the installed Evergreen runtime); the harness forces a creation failure with it.</summary>
|
||||
string? BrowserExecutableFolderForTests { get; }
|
||||
}
|
||||
142
src/RynthCore.Engine/WebPanel/WebPanelApi.cs
Normal file
142
src/RynthCore.Engine/WebPanel/WebPanelApi.cs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
#if ENGINE_CORECLR
|
||||
/// <summary>
|
||||
/// The engine side of the v94 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn): reads
|
||||
/// the native arguments (every string copied before the call returns) and hands them to the one
|
||||
/// WebPanelHost. No call here blocks its caller (AC's main thread, the plugin pump and ImGui draws all call
|
||||
/// these). engine.json "WebPanel": false makes Open answer Unavailable (plugins fall back to the browser).
|
||||
/// </summary>
|
||||
internal static unsafe class WebPanelApi
|
||||
{
|
||||
private const int ShutdownBudgetMs = 2000;
|
||||
private static readonly object Sync = new();
|
||||
private static WebPanelHost? s_host;
|
||||
private static EngineWebPanelEnvironment? s_env;
|
||||
private static volatile bool s_shutdown;
|
||||
|
||||
internal static int Open(WebPanelOpenNative* open)
|
||||
{
|
||||
try
|
||||
{
|
||||
int refusal = WebPanelApiRules.OpenRefusal(s_shutdown || EngineLifecycle.IsShuttingDown, EngineSettings.WebPanel);
|
||||
if (refusal != 0) return refusal;
|
||||
EngineWebPanelEnvironment env;
|
||||
WebPanelHost host;
|
||||
lock (Sync)
|
||||
{
|
||||
if (s_shutdown) return (int)WebPanelCode.ShuttingDown;
|
||||
env = s_env ??= new EngineWebPanelEnvironment();
|
||||
host = s_host ??= new WebPanelHost(env);
|
||||
}
|
||||
int rc = WebPanelNativeArgs.TryBuildRequest(open, env.LocalAppData, env.WorldName, out WebPanelRequest? request);
|
||||
if (rc != 0) return rc;
|
||||
return host.Open(request!);
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
RynthLog.Info("WebPanel: Open failed: " + ex.GetType().Name);
|
||||
return (int)WebPanelCode.Unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int Navigate(int handle, byte* urlUtf8)
|
||||
{
|
||||
try
|
||||
{
|
||||
int refusal = WebPanelApiRules.CallRefusal(s_shutdown);
|
||||
if (refusal != 0) return refusal;
|
||||
if (!WebPanelNativeArgs.TryReadUtf8(urlUtf8, WebPanelUrlPolicy.MaxUrlBytes, true, out string url)) return (int)WebPanelCode.BadArgs;
|
||||
WebPanelHost? host = s_host;
|
||||
return host == null ? (int)WebPanelCode.StaleHandle : host.Navigate(handle, url);
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
RynthLog.Info("WebPanel: Navigate failed: " + ex.GetType().Name);
|
||||
return (int)WebPanelCode.Unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int Close(int handle)
|
||||
{
|
||||
try
|
||||
{
|
||||
int refusal = WebPanelApiRules.CallRefusal(s_shutdown);
|
||||
if (refusal != 0) return refusal;
|
||||
WebPanelHost? host = s_host;
|
||||
return host == null ? (int)WebPanelCode.StaleHandle : host.Close(handle);
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
RynthLog.Info("WebPanel: Close failed: " + ex.GetType().Name);
|
||||
return (int)WebPanelCode.Unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int GetState(int handle, WebPanelStateNative* state)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!WebPanelApiRules.StateArgsOk(state)) return (int)WebPanelCode.BadArgs;
|
||||
int refusal = WebPanelApiRules.CallRefusal(s_shutdown);
|
||||
if (refusal != 0) return refusal;
|
||||
WebPanelHost? host = s_host;
|
||||
WebPanelSnapshot s;
|
||||
int r;
|
||||
if (host == null)
|
||||
{
|
||||
s = WebPanelApiRules.NoPanel(handle);
|
||||
r = s.Status;
|
||||
}
|
||||
else
|
||||
{
|
||||
r = host.GetState(handle, out s);
|
||||
}
|
||||
WebPanelApiRules.WriteState(state, s);
|
||||
return r;
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
RynthLog.Info("WebPanel: GetState failed: " + ex.GetType().Name);
|
||||
return (int)WebPanelCode.Unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>EngineLifecycle, after the plugins' own Shutdowns (they may still Close). Idempotent.</summary>
|
||||
internal static void Shutdown()
|
||||
{
|
||||
WebPanelHost? host;
|
||||
lock (Sync)
|
||||
{
|
||||
s_shutdown = true;
|
||||
host = s_host;
|
||||
}
|
||||
host?.Shutdown(ShutdownBudgetMs);
|
||||
}
|
||||
|
||||
/// <summary>The live panel handle, 0 when none was opened: lets the engine close it (WebPanelApi.Close(LiveHandle)).</summary>
|
||||
internal static int LiveHandle => s_host?.LiveHandle ?? 0;
|
||||
|
||||
/// <summary>Redacted one-liner (no query, fragment or userinfo); includes the WebView2 browser pid.</summary>
|
||||
internal static string Describe()
|
||||
{
|
||||
WebPanelHost? host = s_host;
|
||||
string enabled = EngineSettings.WebPanel ? "on" : "off (engine.json WebPanel)";
|
||||
return host == null ? "web panel: " + enabled + ", not started" : host.Describe() + "; setting " + enabled;
|
||||
}
|
||||
}
|
||||
#else
|
||||
/// <summary>The NativeAOT engine has no web panel: PluginManager leaves the v94 slots zero (HasWebPanel false).</summary>
|
||||
internal static unsafe class WebPanelApi
|
||||
{
|
||||
internal static int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable;
|
||||
internal static int Navigate(int handle, byte* url) => (int)WebPanelCode.Unavailable;
|
||||
internal static int Close(int handle) => (int)WebPanelCode.Unavailable;
|
||||
internal static int GetState(int handle, WebPanelStateNative* state) => (int)WebPanelCode.Unavailable;
|
||||
internal static void Shutdown() { }
|
||||
internal static int LiveHandle => 0;
|
||||
internal static string Describe() => "web panel: not available in this engine build";
|
||||
}
|
||||
#endif
|
||||
46
src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs
Normal file
46
src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>What WebPanelGetState reports for one handle.</summary>
|
||||
internal readonly record struct WebPanelSnapshot(int Handle, int Status, uint Flags, int Error, int LastHttpStatus, uint NavigationCount);
|
||||
|
||||
/// <summary>
|
||||
/// The pure decisions of the v94 ABI glue (WebPanelApi.cs), kept apart so tools\WebPanelTests can check them
|
||||
/// without the engine: refusals, the GetState argument check, and writing the result struct.
|
||||
/// </summary>
|
||||
internal static unsafe class WebPanelApiRules
|
||||
{
|
||||
/// <summary>0 to go on, else the refusal. Shutting down wins over the engine.json "WebPanel" kill switch.</summary>
|
||||
public static int OpenRefusal(bool shuttingDown, bool enabled) =>
|
||||
shuttingDown ? (int)WebPanelCode.ShuttingDown : enabled ? 0 : (int)WebPanelCode.Unavailable;
|
||||
|
||||
/// <summary>Navigate, Close and GetState: 0 to go on, else ShuttingDown.</summary>
|
||||
public static int CallRefusal(bool shuttingDown) => shuttingDown ? (int)WebPanelCode.ShuttingDown : 0;
|
||||
|
||||
/// <summary>OffsetOf(Reserved): the smallest Size a caller's WebPanelStateNative may declare (28 on x86 and x64: the struct has no pointer fields).</summary>
|
||||
public static uint StateMinSize
|
||||
{
|
||||
get
|
||||
{
|
||||
WebPanelStateNative s = default;
|
||||
return (uint)((byte*)s.Reserved - (byte*)&s);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool StateArgsOk(WebPanelStateNative* state) => state != null && state->Size >= StateMinSize;
|
||||
|
||||
/// <summary>What a handle reads when no panel was ever opened.</summary>
|
||||
public static WebPanelSnapshot NoPanel(int handle) => new(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0);
|
||||
|
||||
/// <summary>Writes the fields before Reserved only (the caller's Size covers at least those).</summary>
|
||||
public static void WriteState(WebPanelStateNative* state, in WebPanelSnapshot s)
|
||||
{
|
||||
state->Handle = s.Handle;
|
||||
state->Status = s.Status;
|
||||
state->Flags = s.Flags;
|
||||
state->Error = s.Error;
|
||||
state->LastHttpStatus = s.LastHttpStatus;
|
||||
state->NavigationCount = s.NavigationCount;
|
||||
}
|
||||
}
|
||||
50
src/RynthCore.Engine/WebPanel/WebPanelBrowserGate.cs
Normal file
50
src/RynthCore.Engine/WebPanel/WebPanelBrowserGate.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
1131
src/RynthCore.Engine/WebPanel/WebPanelHost.cs
Normal file
1131
src/RynthCore.Engine/WebPanel/WebPanelHost.cs
Normal file
File diff suppressed because it is too large
Load diff
80
src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs
Normal file
80
src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>
|
||||
/// The panel's remembered placement: <LocalAppData>\RynthCore\WebPanel\layout.json, {"x","y","w","h"} as
|
||||
/// fractions of the game client rect (WebPanelWindowPolicy.FromUserRect). A valid stored layout beats the
|
||||
/// caller's percentages. Called on the panel thread only.
|
||||
/// </summary>
|
||||
internal static class WebPanelLayoutStore
|
||||
{
|
||||
public static string PathFor(string localAppData) => Path.Combine(localAppData, "RynthCore", "WebPanel", "layout.json");
|
||||
|
||||
public static bool TryLoad(string localAppData, out PanelFractions layout)
|
||||
{
|
||||
layout = default;
|
||||
try
|
||||
{
|
||||
string path = PathFor(localAppData);
|
||||
if (!File.Exists(path)) return false;
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object) return false;
|
||||
if (!Num(r, "x", out double x) || !Num(r, "y", out double y) || !Num(r, "w", out double w) || !Num(r, "h", out double h)) return false;
|
||||
var f = new PanelFractions(x, y, w, h);
|
||||
if (!IsValid(f)) return false;
|
||||
layout = f;
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsValid(PanelFractions f)
|
||||
{
|
||||
const double Slack = 1e-6;
|
||||
if (!double.IsFinite(f.X) || !double.IsFinite(f.Y) || !double.IsFinite(f.W) || !double.IsFinite(f.H)) return false;
|
||||
if (f.W <= 0 || f.H <= 0 || f.W > 1 + Slack || f.H > 1 + Slack) return false;
|
||||
if (f.X < 0 || f.Y < 0) return false;
|
||||
return f.X + f.W <= 1 + Slack && f.Y + f.H <= 1 + Slack;
|
||||
}
|
||||
|
||||
/// <summary>Writes the layout (temp file, then a replace). False (and nothing written) when invalid or on an I/O error.</summary>
|
||||
public static bool Save(string localAppData, PanelFractions f)
|
||||
{
|
||||
if (!IsValid(f)) return false;
|
||||
try
|
||||
{
|
||||
string path = PathFor(localAppData);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string tmp = path + ".tmp";
|
||||
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
using (var w = new Utf8JsonWriter(fs))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("x", f.X);
|
||||
w.WriteNumber("y", f.Y);
|
||||
w.WriteNumber("w", f.W);
|
||||
w.WriteNumber("h", f.H);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Num(JsonElement r, string name, out double v)
|
||||
{
|
||||
v = 0;
|
||||
return r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.Number && e.TryGetDouble(out v);
|
||||
}
|
||||
}
|
||||
95
src/RynthCore.Engine/WebPanel/WebPanelNative.cs
Normal file
95
src/RynthCore.Engine/WebPanel/WebPanelNative.cs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>Win32 for the web panel host (CoreCLR engine only). From the 2026-11-07 WebView2 spike's Native.cs.</summary>
|
||||
internal static unsafe class WebPanelNative
|
||||
{
|
||||
public const uint WS_POPUP = 0x80000000, WS_CLIPCHILDREN = 0x02000000, WS_THICKFRAME = 0x00040000;
|
||||
public const uint WS_EX_TOOLWINDOW = 0x00000080;
|
||||
public const uint CS_VREDRAW = 0x0001, CS_HREDRAW = 0x0002;
|
||||
|
||||
public const uint WM_NCCREATE = 0x0081, WM_SIZE = 0x0005, WM_SETFOCUS = 0x0007, WM_PAINT = 0x000F, WM_CLOSE = 0x0010,
|
||||
WM_NCHITTEST = 0x0084, WM_LBUTTONDOWN = 0x0201, WM_TIMER = 0x0113, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232,
|
||||
WM_APP = 0x8000;
|
||||
public const int HTCLIENT = 1, HTCAPTION = 2;
|
||||
|
||||
public const uint SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOACTIVATE = 0x0010;
|
||||
public const int SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_SHOWNA = 8;
|
||||
public const uint GW_HWNDPREV = 3, GA_ROOT = 2;
|
||||
public static readonly IntPtr HWND_TOP = IntPtr.Zero;
|
||||
|
||||
public const uint EVENT_SYSTEM_FOREGROUND = 0x0003, WINEVENT_OUTOFCONTEXT = 0x0000;
|
||||
public const int TRANSPARENT = 1, DEFAULT_GUI_FONT = 17, IDC_ARROW = 32512;
|
||||
public const uint DT_LEFT = 0x0000, DT_CENTER = 0x0001, DT_VCENTER = 0x0004, DT_SINGLELINE = 0x0020, DT_NOPREFIX = 0x0800, DT_END_ELLIPSIS = 0x8000;
|
||||
|
||||
public static uint Rgb(int r, int g, int b) => (uint)(r | (g << 8) | (b << 16));
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; public int W => Right - Left; public int H => Bottom - Top; }
|
||||
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
|
||||
[StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; }
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct WNDCLASSEXW
|
||||
{
|
||||
public uint cbSize, style; public IntPtr lpfnWndProc; public int cbClsExtra, cbWndExtra;
|
||||
public IntPtr hInstance, hIcon, hCursor, hbrBackground, lpszMenuName, lpszClassName, hIconSm;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct PAINTSTRUCT { public IntPtr hdc; public int fErase; public RECT rcPaint; public int fRestore, fIncUpdate; public fixed byte rgbReserved[32]; }
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)] public static extern ushort RegisterClassExW(ref WNDCLASSEXW wc);
|
||||
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool UnregisterClassW(string cls, IntPtr hInst);
|
||||
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
public static extern IntPtr CreateWindowExW(uint ex, string cls, string name, uint style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr param);
|
||||
[DllImport("user32.dll")] public static extern bool DestroyWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern IntPtr DefWindowProcW(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr h, out RECT r);
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
||||
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p);
|
||||
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr h, ref POINT p);
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
|
||||
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
||||
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll")] public static extern int GetMessageW(out MSG m, IntPtr h, uint min, uint max);
|
||||
[DllImport("user32.dll")] public static extern bool TranslateMessage(ref MSG m);
|
||||
[DllImport("user32.dll")] public static extern IntPtr DispatchMessageW(ref MSG m);
|
||||
[DllImport("user32.dll")] public static extern void PostQuitMessage(int code);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetTimer(IntPtr h, IntPtr id, uint ms, IntPtr proc);
|
||||
[DllImport("user32.dll")] public static extern bool KillTimer(IntPtr h, IntPtr id);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr h, uint cmd);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
|
||||
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr h, IntPtr rect, bool erase);
|
||||
[DllImport("user32.dll")] public static extern IntPtr BeginPaint(IntPtr h, out PAINTSTRUCT ps);
|
||||
[DllImport("user32.dll")] public static extern bool EndPaint(IntPtr h, ref PAINTSTRUCT ps);
|
||||
[DllImport("user32.dll")] public static extern int FillRect(IntPtr dc, ref RECT r, IntPtr brush);
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int DrawTextW(IntPtr dc, string text, int count, ref RECT r, uint format);
|
||||
[DllImport("user32.dll")] public static extern IntPtr LoadCursorW(IntPtr inst, IntPtr name);
|
||||
[DllImport("user32.dll")]
|
||||
public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmod,
|
||||
delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int, int, uint, uint, void> proc, uint pid, uint tid, uint flags);
|
||||
[DllImport("user32.dll")] public static extern bool UnhookWinEvent(IntPtr hook);
|
||||
|
||||
[DllImport("gdi32.dll")] public static extern IntPtr CreateSolidBrush(uint color);
|
||||
[DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr obj);
|
||||
[DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
|
||||
[DllImport("gdi32.dll")] public static extern IntPtr GetStockObject(int obj);
|
||||
[DllImport("gdi32.dll")] public static extern uint SetTextColor(IntPtr dc, uint color);
|
||||
[DllImport("gdi32.dll")] public static extern int SetBkMode(IntPtr dc, int mode);
|
||||
|
||||
[DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
|
||||
[DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId();
|
||||
[DllImport("kernel32.dll")] public static extern IntPtr GetModuleHandleW(IntPtr name);
|
||||
|
||||
/// <summary>ShellExecuteW, not Process.Start (the Process API is an AV hazard inside acclient.exe).</summary>
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern IntPtr ShellExecuteW(IntPtr hwnd, string op, string file, string? parameters, string? dir, int show);
|
||||
}
|
||||
55
src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs
Normal file
55
src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
using System;
|
||||
using System.Text;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>One open request, every string already copied out of the caller's buffers.</summary>
|
||||
internal sealed record WebPanelRequest(string Url, string[] Allowlist, string ProfileFolder, string Title, int WidthPercent, int HeightPercent, uint Flags);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the v94 WebPanelOpen argument. The SDK passes pointers into stack or pooled buffers that are gone
|
||||
/// the moment the call returns, so every string is copied here, synchronously, before anything is queued.
|
||||
/// Pure: no Win32, no WebView2.
|
||||
/// </summary>
|
||||
internal static unsafe class WebPanelNativeArgs
|
||||
{
|
||||
public const int MaxAllowlistBytes = 8192, MaxProfileKeyBytes = 256, MaxTitleBytes = 128;
|
||||
public const uint KnownFlags = 1 | 2; // FallbackToBrowser, PageKeepsEscape
|
||||
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
|
||||
/// <summary>0 and a request, or BadArgs. URL policy (IsAllowed) is the host's to apply.</summary>
|
||||
public static int TryBuildRequest(WebPanelOpenNative* open, string localAppData, string? worldName, out WebPanelRequest? request)
|
||||
{
|
||||
request = null;
|
||||
if (open == null) return (int)WebPanelCode.BadArgs;
|
||||
uint minSize = (uint)((byte*)open->Reserved - (byte*)open);
|
||||
if (open->Size < minSize) return (int)WebPanelCode.BadArgs;
|
||||
if (!TryReadUtf8(open->Url, WebPanelUrlPolicy.MaxUrlBytes, true, out string url)) return (int)WebPanelCode.BadArgs;
|
||||
if (!TryReadUtf8(open->Allowlist, MaxAllowlistBytes, true, out string allowText)) return (int)WebPanelCode.BadArgs;
|
||||
if (!TryReadUtf8(open->ProfileKey, MaxProfileKeyBytes, false, out string key)) return (int)WebPanelCode.BadArgs;
|
||||
if (!TryReadUtf8(open->Title, MaxTitleBytes, false, out string title)) return (int)WebPanelCode.BadArgs;
|
||||
if (!WebPanelUrlPolicy.TryParseAllowlist(allowText, out string[] allowlist)) return (int)WebPanelCode.BadArgs;
|
||||
string folder = WebPanelProfile.Folder(localAppData, worldName, key);
|
||||
request = new WebPanelRequest(url, allowlist, folder, title, open->WidthPercent, open->HeightPercent, open->Flags & KnownFlags);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A NUL-terminated UTF-8 string of at most <paramref name="maxBytes"/> bytes, copied. Null pointer:
|
||||
/// "" (false when required). Required strings must not be empty; invalid UTF-8 is refused.
|
||||
/// </summary>
|
||||
public static bool TryReadUtf8(byte* p, int maxBytes, bool required, out string value)
|
||||
{
|
||||
value = "";
|
||||
if (p == null) return !required;
|
||||
int n = 0;
|
||||
while (n <= maxBytes && p[n] != 0) n++;
|
||||
if (n > maxBytes) return false;
|
||||
if (n == 0) return !required;
|
||||
try { value = StrictUtf8.GetString(p, n); }
|
||||
catch (DecoderFallbackException) { return false; }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
44
src/RynthCore.Engine/WebPanel/WebPanelProfile.cs
Normal file
44
src/RynthCore.Engine/WebPanel/WebPanelProfile.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
using System.IO;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>Pure per-world, per-profile-key WebView2 user data folder naming. No file access.</summary>
|
||||
internal static class WebPanelProfile
|
||||
{
|
||||
/// <summary>
|
||||
/// <localAppData>\RynthCore\WebPanel\<world>\<hex>. World: [A-Za-z0-9 _-] kept, others
|
||||
/// '_', trimmed, max 64, empty -> "_default". Hex: first 16 bytes of
|
||||
/// SHA-256(UTF-8(key.Trim().ToLowerInvariant())) as lowercase hex; empty key -> "default".
|
||||
/// </summary>
|
||||
public static string Folder(string localAppData, string? worldName, string? profileKey)
|
||||
{
|
||||
return Path.Combine(localAppData, "RynthCore", "WebPanel", SanitizeWorld(worldName), KeyHex(profileKey));
|
||||
}
|
||||
|
||||
private static string SanitizeWorld(string? world)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(world)) return "_default";
|
||||
var sb = new StringBuilder();
|
||||
foreach (char c in world.Trim())
|
||||
{
|
||||
bool keep = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|
||||
|| c == ' ' || c == '_' || c == '-';
|
||||
sb.Append(keep ? c : '_');
|
||||
}
|
||||
string s = sb.ToString();
|
||||
if (s.Length > 64) s = s.Substring(0, 64);
|
||||
s = s.Trim(); // a trailing space is not a valid Windows folder name
|
||||
return s.Length == 0 ? "_default" : s;
|
||||
}
|
||||
|
||||
private static string KeyHex(string? key)
|
||||
{
|
||||
string k = (key ?? "").Trim().ToLowerInvariant();
|
||||
if (k.Length == 0) return "default";
|
||||
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(k));
|
||||
return Convert.ToHexString(hash, 0, 16).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
123
src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs
Normal file
123
src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
/// <summary>
|
||||
/// Pure URL rules for the web panel: the navigation allowlist, the "safe to hand to the system
|
||||
/// browser" test, and log redaction. No Win32, no WebView2.
|
||||
/// </summary>
|
||||
internal static class WebPanelUrlPolicy
|
||||
{
|
||||
public const int MaxEntries = 16, MaxEntryLength = 253, MaxUrlBytes = 4096;
|
||||
|
||||
/// <summary>
|
||||
/// Parses a '\n'-separated allowlist (blank lines ignored, '\r' tolerated). An entry is
|
||||
/// "host" (exact) or "*.suffix" (any subdomain depth, not the suffix itself; the suffix must
|
||||
/// contain a dot). No scheme, path, port or other '*'. False on 0 or more than 16 entries or
|
||||
/// any bad entry.
|
||||
/// </summary>
|
||||
public static bool TryParseAllowlist(string? text, out string[] entries)
|
||||
{
|
||||
entries = Array.Empty<string>();
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
|
||||
var list = new List<string>();
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string e = raw.Trim().ToLowerInvariant();
|
||||
if (e.Length == 0) continue;
|
||||
if (list.Count >= MaxEntries) return false;
|
||||
if (!IsValidEntry(e)) return false;
|
||||
list.Add(e);
|
||||
}
|
||||
if (list.Count == 0) return false;
|
||||
entries = list.ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsValidEntry(string e)
|
||||
{
|
||||
if (e.Length > MaxEntryLength) return false;
|
||||
string host = e;
|
||||
if (e.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
host = e.Substring(2);
|
||||
if (host.IndexOf('.') < 0) return false; // "*.com" would allow a whole TLD
|
||||
}
|
||||
return IsValidHostName(host);
|
||||
}
|
||||
|
||||
private static bool IsValidHostName(string host)
|
||||
{
|
||||
if (host.Length == 0) return false;
|
||||
foreach (string label in host.Split('.'))
|
||||
{
|
||||
if (label.Length == 0 || label.Length > 63) return false;
|
||||
if (label[0] == '-' || label[^1] == '-') return false;
|
||||
foreach (char c in label)
|
||||
{
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
|
||||
if (!ok) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// https only, no userinfo, default port; host compared via Uri.IdnHost, case-insensitive,
|
||||
/// one trailing dot stripped. "about:blank" is allowed.
|
||||
/// </summary>
|
||||
public static bool IsAllowed(string? url, IReadOnlyList<string> entries)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url)) return false;
|
||||
if (Encoding.UTF8.GetByteCount(url) > MaxUrlBytes) return false;
|
||||
if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
|
||||
if (uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||
if (uri.UserInfo.Length != 0) return false;
|
||||
if (!uri.IsDefaultPort) return false;
|
||||
|
||||
string host;
|
||||
try { host = uri.IdnHost.ToLowerInvariant(); }
|
||||
catch (UriFormatException) { return false; } // invalid IDN characters: fail closed
|
||||
if (host.EndsWith('.')) host = host.Substring(0, host.Length - 1);
|
||||
if (host.Length == 0) return false;
|
||||
|
||||
foreach (string entry in entries)
|
||||
{
|
||||
if (entry.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
string suffix = entry.Substring(1); // ".example.com"
|
||||
if (host.Length > suffix.Length && host.EndsWith(suffix, StringComparison.Ordinal)) return true;
|
||||
}
|
||||
else if (host == entry)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Absolute http/https without userinfo: the only URLs that may reach ShellExecute.</summary>
|
||||
public static bool IsBrowserSafe(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return false;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
|
||||
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||
if (uri.UserInfo.Length != 0) return false;
|
||||
return uri.Host.Length != 0;
|
||||
}
|
||||
|
||||
/// <summary>"scheme://host[:port]/path" with no userinfo, query or fragment; "<invalid url>" if unparseable.</summary>
|
||||
public static string Redact(string? url)
|
||||
{
|
||||
const string Invalid = "<invalid url>";
|
||||
if (string.IsNullOrEmpty(url)) return Invalid;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return Invalid;
|
||||
if (uri.Host.Length == 0) return Invalid;
|
||||
string port = uri.IsDefaultPort ? "" : ":" + uri.Port;
|
||||
return uri.Scheme + "://" + uri.Host + port + uri.AbsolutePath;
|
||||
}
|
||||
}
|
||||
68
src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs
Normal file
68
src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
using System;
|
||||
namespace RynthCore.Engine.WebPanel;
|
||||
|
||||
internal readonly record struct PanelRect(int Left, int Top, int Right, int Bottom)
|
||||
{
|
||||
public int Width => Right - Left;
|
||||
public int Height => Bottom - Top;
|
||||
}
|
||||
|
||||
/// <summary>Panel placement as fractions (0..1) of the game client rect.</summary>
|
||||
internal readonly record struct PanelFractions(double X, double Y, double W, double H);
|
||||
|
||||
/// <summary>Pure visibility and layout rules for the web panel window. No Win32.</summary>
|
||||
internal static class WebPanelWindowPolicy
|
||||
{
|
||||
public const int DefaultPercent = 88, MinPercent = 30, MaxPercent = 100, MinWidthPx = 480, MinHeightPx = 320;
|
||||
|
||||
/// <summary>
|
||||
/// false when closed, the game is gone, iconic or invisible; null (keep current) when the
|
||||
/// foreground window is null mid alt-tab, so the panel never flickers; otherwise true only
|
||||
/// when the foreground window belongs to the game process.
|
||||
/// </summary>
|
||||
public static bool? Visible(bool open, bool gameAlive, bool gameIconic, bool gameVisible,
|
||||
bool foregroundNull, uint foregroundPid, uint ourPid)
|
||||
{
|
||||
if (!open || !gameAlive || gameIconic || !gameVisible) return false;
|
||||
if (foregroundNull) return null;
|
||||
return foregroundPid == ourPid;
|
||||
}
|
||||
|
||||
/// <summary>Centered fractions for a size in percent of the client; 0 means the default (88).</summary>
|
||||
public static PanelFractions Default(int widthPercent, int heightPercent)
|
||||
{
|
||||
double w = Pct(widthPercent) / 100.0;
|
||||
double h = Pct(heightPercent) / 100.0;
|
||||
return new PanelFractions((1 - w) / 2, (1 - h) / 2, w, h);
|
||||
}
|
||||
|
||||
private static int Pct(int p) => p == 0 ? DefaultPercent : Math.Clamp(p, MinPercent, MaxPercent);
|
||||
|
||||
/// <summary>Screen rect for the fractions: at least 480x320 (or the whole client if smaller), never outside the client.</summary>
|
||||
public static PanelRect Place(PanelRect gameClientScreen, PanelFractions f)
|
||||
{
|
||||
int cw = Math.Max(0, gameClientScreen.Width);
|
||||
int ch = Math.Max(0, gameClientScreen.Height);
|
||||
int w = Math.Clamp((int)Math.Round(Clamp01(f.W) * cw), Math.Min(MinWidthPx, cw), cw);
|
||||
int h = Math.Clamp((int)Math.Round(Clamp01(f.H) * ch), Math.Min(MinHeightPx, ch), ch);
|
||||
int x = Math.Clamp((int)Math.Round(Clamp01(f.X) * cw), 0, cw - w);
|
||||
int y = Math.Clamp((int)Math.Round(Clamp01(f.Y) * ch), 0, ch - h);
|
||||
int left = gameClientScreen.Left + x;
|
||||
int top = gameClientScreen.Top + y;
|
||||
return new PanelRect(left, top, left + w, top + h);
|
||||
}
|
||||
|
||||
/// <summary>Fractions of the client for a panel rect the user dragged or resized, clamped to 0..1.</summary>
|
||||
public static PanelFractions FromUserRect(PanelRect gameClientScreen, PanelRect panelScreen)
|
||||
{
|
||||
int cw = gameClientScreen.Width, ch = gameClientScreen.Height;
|
||||
if (cw <= 0 || ch <= 0) return Default(0, 0);
|
||||
double w = Clamp01((double)panelScreen.Width / cw);
|
||||
double h = Clamp01((double)panelScreen.Height / ch);
|
||||
double x = Math.Clamp((double)(panelScreen.Left - gameClientScreen.Left) / cw, 0, 1 - w);
|
||||
double y = Math.Clamp((double)(panelScreen.Top - gameClientScreen.Top) / ch, 0, 1 - h);
|
||||
return new PanelFractions(x, y, w, h);
|
||||
}
|
||||
|
||||
private static double Clamp01(double v) => double.IsNaN(v) ? 0 : Math.Clamp(v, 0, 1);
|
||||
}
|
||||
Loading…
Reference in a new issue