Snapshot for release 2026.10.21.3 (internal 04b831a)
This commit is contained in:
parent
b059db4ca2
commit
c4efe5821d
46 changed files with 2657 additions and 213 deletions
|
|
@ -9,7 +9,11 @@
|
|||
// asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip =
|
||||
// its title; the set is rebuilt as plugins come and go), one per window a plugin
|
||||
// draws that asked for one (its manifest's "windows" with "bar", UI/Sections/
|
||||
// PluginWindows.cs), reload (RL) and pop out.
|
||||
// PluginWindows.cs; an engine panel such a window has taken over loses its own
|
||||
// button), reload (RL) and pop out.
|
||||
// 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).
|
||||
// Dragging the grip moves the bar; the position is the shared bar= row in
|
||||
// panel_state.txt. Right-click the grip for the bar's menu: its size, its rows
|
||||
// and "Report a problem" (panel buttons have no menu). Pop out moves the ImGui
|
||||
|
|
@ -65,8 +69,12 @@ internal static class ImGuiBar
|
|||
|
||||
// Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton);
|
||||
// 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,
|
||||
ScriptWindow? Window = null);
|
||||
string OpenKey, ScriptWindow? Window = null);
|
||||
|
||||
// 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;
|
||||
|
||||
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
|
||||
// Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu.
|
||||
|
|
@ -147,6 +155,9 @@ internal static class ImGuiBar
|
|||
private static ScriptBarItem[]? _builtScriptButtons;
|
||||
private static int _builtImGuiOnlyMask;
|
||||
private static int _builtPluginWindows = -1;
|
||||
// The Scripts menu's panel keys (its button lights while any is open), rebuilt with the snapshot.
|
||||
private static ScriptBarItem[]? _scriptKeysFor;
|
||||
private static string[] _scriptKeys = Array.Empty<string>();
|
||||
private static string _tooltip = "";
|
||||
private static bool _placed;
|
||||
private static Vector2 _pos, _persistedPos;
|
||||
|
|
@ -457,12 +468,15 @@ internal static class ImGuiBar
|
|||
|
||||
PushBarButtonStyle(s);
|
||||
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.
|
||||
foreach (ButtonInfo b in _buttons!)
|
||||
{
|
||||
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
|
||||
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
|
||||
bool open = BarOpenState.IsOpen(b.OpenKey, IsOpenCheck);
|
||||
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText, open))
|
||||
{
|
||||
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey));
|
||||
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !open);
|
||||
else PanelRouter.Toggle(b.Title);
|
||||
}
|
||||
SafeImGui.SetItemTooltip(b.Tooltip);
|
||||
|
|
@ -474,7 +488,8 @@ internal static class ImGuiBar
|
|||
{
|
||||
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
|
||||
string? only = iltCount == 1 ? FirstIltPanel() : null;
|
||||
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText))
|
||||
bool open = BarOpenState.AnyOpen(IltPanels, IsOpenCheck);
|
||||
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText, open))
|
||||
{
|
||||
if (only != null) PanelRouter.Toggle(only);
|
||||
else ImGuiNET.ImGui.OpenPopup("##ilt_menu");
|
||||
|
|
@ -488,7 +503,8 @@ internal static class ImGuiBar
|
|||
if (scripts.Length > 0)
|
||||
{
|
||||
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
|
||||
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText))
|
||||
bool open = BarOpenState.AnyOpen(ScriptKeys(scripts), IsOpenCheck);
|
||||
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText, open))
|
||||
ImGuiNET.ImGui.OpenPopup("##scripts_menu");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Script windows");
|
||||
}
|
||||
|
|
@ -610,11 +626,32 @@ internal static class ImGuiBar
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>A square bar button (the bar's button style) with an icon, or a letter, centred on it.</summary>
|
||||
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color)
|
||||
/// <summary>The Scripts menu's panel keys, rebuilt only when its snapshot changes (a new array then). AC thread.</summary>
|
||||
private static string[] ScriptKeys(ScriptBarItem[] items)
|
||||
{
|
||||
if (ReferenceEquals(items, _scriptKeysFor)) return _scriptKeys;
|
||||
var keys = new string[items.Length];
|
||||
for (int i = 0; i < items.Length; i++) keys[i] = items[i].PanelKey;
|
||||
_scriptKeys = keys;
|
||||
_scriptKeysFor = items;
|
||||
return keys;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A square bar button (the bar's button style) with an icon, or a letter, centred on it.
|
||||
/// <paramref name="open"/>: its window is open, so it draws in the theme's accent.
|
||||
/// </summary>
|
||||
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color, bool open = false)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (open)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButtonOpen);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.BarButtonOpenHover);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonOpenBorder);
|
||||
}
|
||||
bool clicked = ImGuiNET.ImGui.Button(id, size);
|
||||
if (open) ImGuiNET.ImGui.PopStyleColor(3);
|
||||
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), font, icon, at, size, color);
|
||||
return clicked;
|
||||
}
|
||||
|
|
@ -761,17 +798,19 @@ internal static class ImGuiBar
|
|||
_builtImGuiOnlyMask = mask;
|
||||
_builtPluginWindows = pluginWindows;
|
||||
var list = new List<ButtonInfo>();
|
||||
// An engine panel a plugin window has taken over ("takeOver") has no engine button: the
|
||||
// window's own (below) stands in when it asks for one.
|
||||
foreach (var (title, _) in OverlayHost.GetPanels())
|
||||
if (!LauncherOnly.Contains(title))
|
||||
if (!LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
|
||||
{
|
||||
string icon = IconFor(title, out bool letter);
|
||||
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
|
||||
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
|
||||
}
|
||||
foreach (string title in ImGuiOnlyBarPanels)
|
||||
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title))
|
||||
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
|
||||
{
|
||||
string icon = IconFor(title, out bool letter);
|
||||
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
|
||||
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
|
||||
}
|
||||
// Windows plugins draw (their manifests' "windows" with "bar", docs/PLUGIN_WINDOWS.md): the
|
||||
// icon they name (a Phosphor glyph), else the title's letter; the button toggles the panel.
|
||||
|
|
@ -779,7 +818,8 @@ 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));
|
||||
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title,
|
||||
BarOpenState.KeyFor(w.Title, 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.
|
||||
|
|
@ -789,7 +829,7 @@ internal static class ImGuiBar
|
|||
string title = w.Title.Length > 0 ? w.Title : w.Key;
|
||||
string icon = IconFor(title, out bool letter);
|
||||
string id = "##bar_sw" + w.Hash.ToString("X8");
|
||||
list.Add(new ButtonInfo(title, id, icon, letter, title, Window: w));
|
||||
list.Add(new ButtonInfo(title, id, icon, letter, title, BarOpenState.KeyFor(title, w.PanelKey), Window: w));
|
||||
}
|
||||
_buttons = list.ToArray();
|
||||
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar size and rows. Ctrl+wheel over the bar: size.";
|
||||
|
|
|
|||
|
|
@ -9,12 +9,16 @@
|
|||
// and close; 16 px resize grip, all Phosphor icons), placement restore/persistence shared
|
||||
// with the Avalonia face through PanelStateStore, and per-panel error isolation.
|
||||
//
|
||||
// A plugin window can take an engine panel's place (TakeOver, the manifest's
|
||||
// "takeOver"): same key, so the saved place, open state and commands carry
|
||||
// over; the engine's face is kept and comes back on ReleaseTakeOver.
|
||||
//
|
||||
// Threads:
|
||||
// Register engine init.
|
||||
// RegisterDynamic / Unregister / RequestSize / RequestPos
|
||||
// RegisterDynamic / Unregister / RequestSize / RequestPos / TakeOver / ReleaseTakeOver
|
||||
// any thread (script windows, from the plugin pump thread);
|
||||
// DrawOrder is copy-on-write, removal finishes in DrawAll;
|
||||
// requests are applied in DrawPanel.
|
||||
// requests are applied in DrawPanel, face swaps in DrawAll.
|
||||
// Open / Close any thread (router: game thread / Avalonia UI thread).
|
||||
// Applied on AC's render thread at the next DrawAll.
|
||||
// DrawAll AC's render thread, inside the ImGui frame.
|
||||
|
|
@ -146,8 +150,17 @@ internal static class ImGuiPanelHost
|
|||
public volatile bool HasRequest; // RequestedSize or RequestedPos is set
|
||||
public int Failures;
|
||||
public string? Error;
|
||||
/// <summary>True while a plugin window has this engine panel's place (TakeOver).</summary>
|
||||
public bool TakenOver;
|
||||
/// <summary>The engine's own face, kept from the first TakeOver for ReleaseTakeOver.</summary>
|
||||
public FaceSet? EngineOwn;
|
||||
/// <summary>A face change waiting for the render thread (ApplyFaceChanges).</summary>
|
||||
public FaceSet? NextFace;
|
||||
}
|
||||
|
||||
/// <summary>What draws a panel: its spec, its face's factory and its header text.</summary>
|
||||
private sealed record FaceSet(PanelSpec Spec, Func<IImGuiPanel> Factory, string DisplayTitle);
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<string, Entry> Entries = new(StringComparer.OrdinalIgnoreCase);
|
||||
// Copy-on-write under Sync: DrawAll iterates the list it read without holding the lock,
|
||||
|
|
@ -264,6 +277,109 @@ internal static class ImGuiPanelHost
|
|||
lock (Sync) return Entries.ContainsKey(title);
|
||||
}
|
||||
|
||||
// ── Plugin windows taking over an engine panel (docs/PLUGIN_WINDOWS.md, "takeOver") ──
|
||||
|
||||
/// <summary>True when <paramref name="key"/> is an engine panel (Register), taken over or not. Any thread.</summary>
|
||||
public static bool IsEnginePanel(string key)
|
||||
{
|
||||
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && !e.Dynamic;
|
||||
}
|
||||
|
||||
/// <summary>True while a plugin window draws in the engine panel <paramref name="key"/>'s place. Any thread.</summary>
|
||||
public static bool IsTakenOver(string key)
|
||||
{
|
||||
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && e.TakenOver;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plugin window takes the engine panel <paramref name="key"/>'s place: the panel keeps its
|
||||
/// key (its saved place and size, open state, hotkeys, /rc command and router entry) and is
|
||||
/// drawn with <paramref name="spec"/> and <paramref name="factory"/>'s face from the next
|
||||
/// frame; one open now closes and opens again as the new face, where it was (popped out
|
||||
/// stays popped out). The engine's own face is kept for <see cref="ReleaseTakeOver"/>. Also
|
||||
/// updates a window already in place. False when <paramref name="key"/> isn't an engine
|
||||
/// panel. Any thread; applied on AC's render thread.
|
||||
/// </summary>
|
||||
public static bool TakeOver(string key, string displayTitle, PanelSpec spec, Func<IImGuiPanel> factory)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (!Entries.TryGetValue(key, out Entry? e) || e.Dynamic) return false;
|
||||
// The first takeover finds the engine's face in place; later ones may find a plugin's.
|
||||
e.EngineOwn ??= new FaceSet(e.Spec, e.Factory, e.DisplayTitle);
|
||||
e.TakenOver = true;
|
||||
e.NextFace = new FaceSet(spec, factory, displayTitle);
|
||||
}
|
||||
_faceChangePending = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plugin window that took over <paramref name="key"/> went (plugin unloaded, window
|
||||
/// dropped): the engine's own face comes back in its place, open if the window was open.
|
||||
/// Any thread; applied on AC's render thread.
|
||||
/// </summary>
|
||||
public static void ReleaseTakeOver(string key)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (!Entries.TryGetValue(key, out Entry? e) || !e.TakenOver || e.EngineOwn == null) return;
|
||||
e.TakenOver = false;
|
||||
e.NextFace = e.EngineOwn;
|
||||
}
|
||||
_faceChangePending = true;
|
||||
}
|
||||
|
||||
private static volatile bool _faceChangePending;
|
||||
|
||||
/// <summary>
|
||||
/// Swaps in the faces TakeOver / ReleaseTakeOver asked for. A panel shown now closes as its
|
||||
/// old face and opens as the new one (placement saved and read back as usual), and embedded
|
||||
/// copies of it are dropped so their hosts draw the new face. AC thread, before the requests.
|
||||
/// </summary>
|
||||
private static void ApplyFaceChanges(float placeScale)
|
||||
{
|
||||
if (!_faceChangePending) return;
|
||||
_faceChangePending = false;
|
||||
List<Entry>? changed = null;
|
||||
lock (Sync)
|
||||
foreach (Entry e in DrawOrder)
|
||||
{
|
||||
if (e.NextFace is not FaceSet next) continue;
|
||||
e.NextFace = null;
|
||||
bool sameFace = e.Factory == next.Factory;
|
||||
e.Spec = next.Spec;
|
||||
e.Factory = next.Factory;
|
||||
e.DisplayTitle = next.DisplayTitle;
|
||||
if (!sameFace) (changed ??= new List<Entry>()).Add(e);
|
||||
}
|
||||
if (changed == null) return;
|
||||
foreach (Entry e in changed)
|
||||
{
|
||||
RynthLog.UI($"ImGuiPanelHost: {e.Title} is drawn by {(e.TakenOver ? "a plugin's window" : "the engine's face again")}.");
|
||||
DropEmbeddedCopies(e.Title);
|
||||
if (!e.Shown) continue; // the next open uses the new face
|
||||
Apply(e.Title, RequestKind.Close, placeScale);
|
||||
Apply(e.Title, RequestKind.Open, placeScale);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Hides and drops the embedded copies of <paramref name="title"/> (another face takes its place). AC thread.</summary>
|
||||
private static void DropEmbeddedCopies(string title)
|
||||
{
|
||||
List<string>? gone = null;
|
||||
foreach (var kv in EmbeddedFaces)
|
||||
if (kv.Value.Title.Equals(title, StringComparison.OrdinalIgnoreCase)) (gone ??= new List<string>()).Add(kv.Key);
|
||||
if (gone == null) return;
|
||||
foreach (string key in gone)
|
||||
{
|
||||
EmbeddedFace face = EmbeddedFaces[key];
|
||||
EmbeddedFaces.Remove(key);
|
||||
try { face.Instance.OnHidden(); }
|
||||
catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: embedded {face.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
|
||||
public static PanelFace CodeDefault(string title)
|
||||
{
|
||||
lock (Sync) return Entries.TryGetValue(title, out Entry? e) ? e.Spec.CodeDefault : PanelFace.Avalonia;
|
||||
|
|
@ -455,6 +571,7 @@ internal static class ImGuiPanelHost
|
|||
{
|
||||
_frameScale = uiScale;
|
||||
float placeScale = PlacementScale();
|
||||
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
|
||||
while (Requests.TryDequeue(out var req))
|
||||
Apply(req.Title, req.Kind, placeScale);
|
||||
RemoveUnregistered();
|
||||
|
|
|
|||
149
src/RynthCore.Engine/ImGui/ImGuiStackGuard.cs
Normal file
149
src/RynthCore.Engine/ImGui/ImGuiStackGuard.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/ImGuiStackGuard.cs
|
||||
// Puts ImGui's stacks back after plugin drawing code (audit 2026-10-21, 02 F4).
|
||||
// A plugin window's body (PluginWindowFace) is the plugin's own ImGui code; one
|
||||
// unbalanced PushStyleColor, a BeginChild left open, or an exception between a
|
||||
// Begin and its End used to carry over into every panel drawn after it that
|
||||
// frame (soft asserts, so it showed as garbage or a later native fault).
|
||||
//
|
||||
// Take() records the stack depths with ImGui's own ErrorRecoveryStoreState
|
||||
// (exported by our cimgui build); Check() compares a fresh record with it;
|
||||
// RecoverTo() hands a record back to ErrorRecoveryTryToRecoverState, which ends
|
||||
// what was left open (windows and child windows, tables, tab bars, tree nodes,
|
||||
// groups, IDs, disabled blocks, colours, item flags, style vars, fonts, focus
|
||||
// scopes) down to that record. ImGui's own error report (assert, tooltip, debug
|
||||
// log) is switched off around that call: the caller logs once instead, and a
|
||||
// broken plugin can't put an error tooltip on the screen every frame.
|
||||
//
|
||||
// Rule from ImGui: a record to recover to must be taken where the current
|
||||
// window's ID stack is at its base (the start of a window or child body), since
|
||||
// the recovery pops that window's IDs down to its first.
|
||||
//
|
||||
// The record is opaque here (ImGuiStackState reads it for the log). Its size is
|
||||
// checked on first use; on a mismatch, or with a cimgui.dll without the exports,
|
||||
// Available is false and callers do as before. AC's render thread, inside an
|
||||
// ImGui frame and window (StoreState reads the current window).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static unsafe class ImGuiStackGuard
|
||||
{
|
||||
/// <summary>Room for one record (ImGui 1.91.6 writes 22 bytes).</summary>
|
||||
private const int RecordCapacity = 64;
|
||||
|
||||
/// <summary>One stack record. Zeroed before ImGui writes it, so two records compare byte for byte.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Size = RecordCapacity)]
|
||||
internal struct Mark
|
||||
{
|
||||
private fixed byte _bytes[RecordCapacity];
|
||||
}
|
||||
|
||||
/// <summary>A record's fields (ImGuiStackState.Names), read in place: no allocation.</summary>
|
||||
private static ReadOnlySpan<short> FieldsOf(in Mark m) =>
|
||||
MemoryMarshal.Cast<byte, short>(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in m), 1)))
|
||||
[..ImGuiStackState.Fields];
|
||||
|
||||
private static delegate* unmanaged[Cdecl]<void*, void> _store;
|
||||
private static delegate* unmanaged[Cdecl]<void*, void> _recover;
|
||||
private static int _state; // 0 = not resolved, 1 = available, -1 = off
|
||||
|
||||
/// <summary>True when the exports exist and the record size checked out. Render thread, inside a window.</summary>
|
||||
public static bool Available
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_state == 0) Resolve();
|
||||
return _state > 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Resolve()
|
||||
{
|
||||
_state = -1;
|
||||
IntPtr module = EntryPoint.ImGuiNativeHandle;
|
||||
if (module == IntPtr.Zero
|
||||
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryStoreState", out IntPtr store)
|
||||
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryTryToRecoverState", out IntPtr recover))
|
||||
{
|
||||
RynthLog.UI("ImGuiStackGuard: this cimgui.dll has no igErrorRecovery* exports; plugin drawing isn't checked for unbalanced stacks.");
|
||||
return;
|
||||
}
|
||||
_store = (delegate* unmanaged[Cdecl]<void*, void>)store;
|
||||
_recover = (delegate* unmanaged[Cdecl]<void*, void>)recover;
|
||||
|
||||
const byte fill = 0xCC;
|
||||
byte* probe = stackalloc byte[RecordCapacity];
|
||||
new Span<byte>(probe, RecordCapacity).Fill(fill);
|
||||
_store(probe);
|
||||
if (!ImGuiStackState.WroteExpectedSize(new ReadOnlySpan<byte>(probe, RecordCapacity), fill))
|
||||
{
|
||||
RynthLog.UI($"ImGuiStackGuard: ImGui's stack record isn't the {ImGuiStackState.RecordBytes} bytes this engine expects; plugin drawing isn't checked.");
|
||||
return;
|
||||
}
|
||||
_state = 1;
|
||||
}
|
||||
|
||||
/// <summary>The stack depths now. Only when <see cref="Available"/>.</summary>
|
||||
public static Mark Take()
|
||||
{
|
||||
Mark m = default;
|
||||
_store(&m);
|
||||
return m;
|
||||
}
|
||||
|
||||
/// <summary>The stack depths now against <paramref name="before"/>; <paramref name="now"/> for the log.</summary>
|
||||
public static StackCheck Check(in Mark before, out Mark now)
|
||||
{
|
||||
now = Take();
|
||||
return ImGuiStackState.Compare(FieldsOf(before), FieldsOf(now));
|
||||
}
|
||||
|
||||
/// <summary>True when the record was taken with the window's ID stack at its base: one a recovery may go back to.</summary>
|
||||
public static bool AtWindowBase(in Mark mark) => ImGuiStackState.IdsAtBase(FieldsOf(mark));
|
||||
|
||||
/// <summary>What changed between two records, for the log ("colours +2, windows +1").</summary>
|
||||
public static string Describe(in Mark before, in Mark after) => ImGuiStackState.Describe(FieldsOf(before), FieldsOf(after));
|
||||
|
||||
/// <summary>
|
||||
/// Ends and pops everything above <paramref name="mark"/> (taken where the window's ID stack
|
||||
/// was at its base). Windows or pops below the mark can't be put back. When windows below it
|
||||
/// were ended (ImGui's recovery then does nothing), only the colours, style vars and fonts
|
||||
/// above it are popped, which are the context's and safe from any window.
|
||||
/// </summary>
|
||||
public static void RecoverTo(in Mark mark)
|
||||
{
|
||||
Mark now = Take();
|
||||
if (!ImGuiStackState.CanRecover(FieldsOf(mark), FieldsOf(now)))
|
||||
{
|
||||
(int colours, int vars, int fonts) = ImGuiStackState.GlobalPops(FieldsOf(mark), FieldsOf(now));
|
||||
if (colours > 0) ImGuiNET.ImGui.PopStyleColor(colours);
|
||||
if (vars > 0) ImGuiNET.ImGui.PopStyleVar(vars);
|
||||
for (int i = 0; i < fonts; i++) ImGuiNET.ImGui.PopFont();
|
||||
return;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
bool assert = io.ConfigErrorRecoveryEnableAssert, tooltip = io.ConfigErrorRecoveryEnableTooltip;
|
||||
bool debugLog = io.ConfigErrorRecoveryEnableDebugLog, recovery = io.ConfigErrorRecovery;
|
||||
io.ConfigErrorRecoveryEnableAssert = false;
|
||||
io.ConfigErrorRecoveryEnableTooltip = false;
|
||||
io.ConfigErrorRecoveryEnableDebugLog = false;
|
||||
io.ConfigErrorRecovery = true;
|
||||
try
|
||||
{
|
||||
fixed (Mark* m = &Unsafe.AsRef(in mark)) _recover(m);
|
||||
}
|
||||
finally
|
||||
{
|
||||
io.ConfigErrorRecoveryEnableAssert = assert;
|
||||
io.ConfigErrorRecoveryEnableTooltip = tooltip;
|
||||
io.ConfigErrorRecoveryEnableDebugLog = debugLog;
|
||||
io.ConfigErrorRecovery = recovery;
|
||||
}
|
||||
}
|
||||
}
|
||||
121
src/RynthCore.Engine/ImGui/ImGuiStackState.cs
Normal file
121
src/RynthCore.Engine/ImGui/ImGuiStackState.cs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/ImGuiStackState.cs
|
||||
// What a plugin's draw left on ImGui's stacks, from two of Dear ImGui's own
|
||||
// stack records (ImGuiErrorRecoveryState, taken by ImGuiStackGuard before and
|
||||
// after the call). Pure: no ImGui calls, so tools/SectionsTests compiles it.
|
||||
//
|
||||
// The record is ImGui 1.91.6's ImGuiErrorRecoveryState: 11 shorts in the order
|
||||
// of Names below (imgui_internal.h; ImGuiSelfTest pins the version). Checked
|
||||
// against our cimgui.dll in a 32-bit probe on 2026-10-21: 22 bytes written,
|
||||
// and ImGuiStackGuard re-checks the size before its first use.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
/// <summary>How a plugin's draw left ImGui's stacks.</summary>
|
||||
internal enum StackCheck
|
||||
{
|
||||
/// <summary>As it found them.</summary>
|
||||
Balanced,
|
||||
/// <summary>It left things open (pushes, a child window, a group...): ImGui can unwind them.</summary>
|
||||
LeftOpen,
|
||||
/// <summary>It ended or popped something it didn't begin (the host's window, colours): can't be put back.</summary>
|
||||
ClosedTooMuch,
|
||||
}
|
||||
|
||||
internal static class ImGuiStackState
|
||||
{
|
||||
/// <summary>Shorts in ImGuiErrorRecoveryState (1.91.6).</summary>
|
||||
public const int Fields = 11;
|
||||
|
||||
/// <summary>Bytes ImGui writes for one record.</summary>
|
||||
public const int RecordBytes = Fields * sizeof(short);
|
||||
|
||||
/// <summary>Index of the window stack's depth (Begin / BeginChild).</summary>
|
||||
public const int WindowStack = 0;
|
||||
|
||||
/// <summary>What each field counts, in the record's order.</summary>
|
||||
public static readonly string[] Names =
|
||||
{
|
||||
"windows", "IDs", "tree nodes", "colours", "style vars", "fonts",
|
||||
"focus scopes", "groups", "item flags", "popups", "disabled",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Fields that count the current window's own stacks (its IDs, its tree depth): they compare
|
||||
/// only at the same window depth. The rest belong to the context.
|
||||
/// </summary>
|
||||
public static bool PerWindow(int field) => field is 1 or 2;
|
||||
|
||||
/// <summary>The draw's effect: <paramref name="after"/> against <paramref name="before"/>.</summary>
|
||||
public static StackCheck Compare(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
|
||||
{
|
||||
if (after[WindowStack] < before[WindowStack]) return StackCheck.ClosedTooMuch;
|
||||
bool sameWindow = after[WindowStack] == before[WindowStack];
|
||||
bool changed = !sameWindow;
|
||||
for (int i = 0; i < Fields; i++)
|
||||
{
|
||||
if (i == WindowStack || (!sameWindow && PerWindow(i))) continue;
|
||||
if (after[i] < before[i]) return StackCheck.ClosedTooMuch;
|
||||
if (after[i] != before[i]) changed = true;
|
||||
}
|
||||
return changed ? StackCheck.LeftOpen : StackCheck.Balanced;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window's ID stack holds only the window's own ID: a record taken here is one ImGui's
|
||||
/// recovery can go back to (it pops a window's IDs down to that one).
|
||||
/// </summary>
|
||||
public static bool IdsAtBase(ReadOnlySpan<short> record) => record[1] == 1;
|
||||
|
||||
/// <summary>Indexes of the context-wide stacks a pop works on from any window.</summary>
|
||||
public const int Colours = 3, StyleVars = 4, Fonts = 5;
|
||||
|
||||
/// <summary>
|
||||
/// ImGui's recovery can unwind to <paramref name="mark"/> only from the same window depth or
|
||||
/// deeper; when the draw ended windows below the mark (the host's own), it does nothing.
|
||||
/// </summary>
|
||||
public static bool CanRecover(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) => now[WindowStack] >= mark[WindowStack];
|
||||
|
||||
/// <summary>
|
||||
/// When <see cref="CanRecover"/> is false: the colours, style vars and fonts to pop to get back
|
||||
/// to <paramref name="mark"/> (those stacks belong to the context, not a window). 0 where none.
|
||||
/// </summary>
|
||||
public static (int Colours, int StyleVars, int Fonts) GlobalPops(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) =>
|
||||
(Math.Max(0, now[Colours] - mark[Colours]), Math.Max(0, now[StyleVars] - mark[StyleVars]), Math.Max(0, now[Fonts] - mark[Fonts]));
|
||||
|
||||
/// <summary>
|
||||
/// "windows +1, colours +2, style vars +1": the fields that changed, with the change (a
|
||||
/// window's own IDs and tree depth only when the window depth is the same).
|
||||
/// </summary>
|
||||
public static string Describe(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
bool sameWindow = after[WindowStack] == before[WindowStack];
|
||||
for (int i = 0; i < Fields; i++)
|
||||
{
|
||||
int d = after[i] - before[i];
|
||||
if (d == 0 || (!sameWindow && PerWindow(i))) continue;
|
||||
if (sb.Length > 0) sb.Append(", ");
|
||||
sb.Append(Names[i]).Append(' ').Append(d > 0 ? "+" : "").Append(d);
|
||||
}
|
||||
return sb.Length > 0 ? sb.ToString() : "nothing";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The size check on first use: <paramref name="record"/> was filled with
|
||||
/// <paramref name="fill"/> and then written by ImGui. True when exactly the first
|
||||
/// <see cref="RecordBytes"/> bytes were written (the layout this file expects).
|
||||
/// </summary>
|
||||
public static bool WroteExpectedSize(ReadOnlySpan<byte> record, byte fill)
|
||||
{
|
||||
int written = 0;
|
||||
for (int i = 0; i < record.Length; i++)
|
||||
if (record[i] != fill) written = i + 1;
|
||||
// A short that happens to equal fill|fill is a value no stack reaches (0xCCCC = -13108).
|
||||
return written == RecordBytes;
|
||||
}
|
||||
}
|
||||
|
|
@ -4,9 +4,13 @@
|
|||
// the panel host draws the window, this face hands the body to the plugin's
|
||||
// RynthPluginRenderEmbed(surface, width, height) in the default UI font, under
|
||||
// an ID scope of its own. Popped out, PluginManager.RenderEmbed adds ":popout"
|
||||
// to the surface name. An export that throws is switched off (PluginManager
|
||||
// logs it); the body then says so and asks again every 5 s, so a reloaded
|
||||
// plugin draws again without the window being reopened.
|
||||
// to the surface name. An export that throws (or returns -2, "failed") is
|
||||
// switched off (PluginManager logs it); the body then says so and asks again
|
||||
// every 5 s, so a reloaded plugin draws again without the window being reopened.
|
||||
// After every call ImGui's stacks are checked against what they were before it
|
||||
// (ImGuiStackGuard): whatever the plugin left open (colours, style vars, fonts,
|
||||
// IDs, groups, child windows, tables...) is ended and popped there, so the
|
||||
// panels drawn after it start clean; logged once per window, then counted.
|
||||
// docs/PLUGIN_WINDOWS.md. AC's render thread.
|
||||
// ============================================================================
|
||||
|
||||
|
|
@ -44,13 +48,31 @@ internal sealed class PluginWindowFace : IImGuiPanel
|
|||
int result = PluginManager.EmbedFailed;
|
||||
if (_failedAtMs < 0 || now - _failedAtMs >= RetryMs)
|
||||
{
|
||||
// Two stack records: the body's base (where a recovery goes back to: the panel host
|
||||
// calls Draw right after its BeginChild, the ID stack at its base) and the depth the
|
||||
// plugin gets, which it must leave as it found.
|
||||
bool guarded = ImGuiStackGuard.Available;
|
||||
ImGuiStackGuard.Mark bodyBase = guarded ? ImGuiStackGuard.Take() : default;
|
||||
guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before
|
||||
ImGuiNET.ImGui.PushID(_idScope);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default;
|
||||
try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out _); }
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
ImGuiStackGuard.Mark after = default;
|
||||
StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced;
|
||||
if (check == StackCheck.Balanced)
|
||||
{
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Ends and pops what the plugin left, with this face's ID scope and font.
|
||||
ImGuiStackGuard.RecoverTo(bodyBase);
|
||||
NoteUnbalanced(check, ImGuiStackGuard.Describe(given, after));
|
||||
}
|
||||
}
|
||||
if (result == PluginManager.EmbedFailed) _failedAtMs = now;
|
||||
else if (result == PluginManager.EmbedDrawn) _failedAtMs = -1;
|
||||
|
|
@ -66,4 +88,22 @@ internal sealed class PluginWindowFace : IImGuiPanel
|
|||
_ => $"Waiting for {_plugin}…",
|
||||
}, Mute);
|
||||
}
|
||||
|
||||
// Unbalanced draws by plugin + surface: logged the first time, then every RepeatEvery-th.
|
||||
private static readonly System.Collections.Generic.Dictionary<string, int> Unbalanced = new(StringComparer.Ordinal);
|
||||
private const int RepeatEvery = 1000;
|
||||
|
||||
private void NoteUnbalanced(StackCheck check, string what)
|
||||
{
|
||||
string key = _plugin + "/" + _title;
|
||||
Unbalanced.TryGetValue(key, out int n);
|
||||
Unbalanced[key] = ++n;
|
||||
if (n != 1 && n % RepeatEvery != 0) return;
|
||||
string again = n == 1 ? "" : $" ({n} times so far)";
|
||||
RynthLog.Warn(check == StackCheck.ClosedTooMuch
|
||||
? $"PluginWindows: {_plugin} drawing '{_title}' ended or popped what it didn't open ({what}){again}. " +
|
||||
"What it left open was put back; what it took can't be, so the window may draw wrongly."
|
||||
: $"PluginWindows: {_plugin} drawing '{_title}' left ImGui's stacks unbalanced ({what}){again}. " +
|
||||
"Put back after its draw; the panels after it draw as normal.");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,6 +211,11 @@ internal static class RynthTheme
|
|||
public static uint BarBackground => WithAlpha(_t.BarBg, 0xE6);
|
||||
public const float BarRounding = 4f;
|
||||
public static uint BarButton => _t.FrameBg;
|
||||
// A button whose window is open (docked or popped out, BarOpenState): the accent fill
|
||||
// (Chat's active tab), halfway to the accent under the mouse, and an accent border.
|
||||
public static uint BarButtonOpen => _t.AccentFill;
|
||||
public static uint BarButtonOpenHover => _t.WindowBorder;
|
||||
public static uint BarButtonOpenBorder => _t.Accent;
|
||||
public static readonly uint BarText = Argb(0xFFFFFFFF);
|
||||
public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen
|
||||
public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki
|
||||
|
|
|
|||
Loading…
Reference in a new issue