From 6908c64807c384d9cba884913a20b243e2d330c4 Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Sun, 4 Oct 2026 19:56:52 -0400 Subject: [PATCH] fix(engine): destroy panel windows on their owner thread; hold login pop-out until game window is hooked LayeredWindow.Dispose now destroys inline when the caller owns the HWND, else posts WM_RYNTH_SELF_DESTROY to the panel itself. Floating-panel restore at login waits for Win32Backend.CanRunOnGameThread so the HWND is created on AC's game thread. Co-authored-by: Cursor --- ...6-10-04-panel-window-owner-thread-fixes.md | 42 ++++++++ src/RynthCore.Engine/ImGui/Win32Backend.cs | 66 +++---------- src/RynthCore.Engine/UI/AvaloniaOverlay.cs | 48 +++++++++- src/RynthCore.Engine/UI/LayeredWindow.cs | 96 ++++++++++++------- 4 files changed, 165 insertions(+), 87 deletions(-) create mode 100644 Changelog/2026-10-04-panel-window-owner-thread-fixes.md diff --git a/Changelog/2026-10-04-panel-window-owner-thread-fixes.md b/Changelog/2026-10-04-panel-window-owner-thread-fixes.md new file mode 100644 index 0000000..be2f448 --- /dev/null +++ b/Changelog/2026-10-04-panel-window-owner-thread-fixes.md @@ -0,0 +1,42 @@ +# Floating panel windows: destroy on the owner thread, create on the game thread (2026-10-04) + +Ships in the next installer after 2026.10.4.15. + +## Destroy each panel window on the thread that owns it + +`LayeredWindow.Dispose` used to call `Win32Backend.PostDestroyWindow`, which always +posted the destroy to the game window. That was wrong for any panel not created on +the game thread (for example the login-time pop-out, created on the Avalonia UI +thread). The game thread's `DestroyWindow` then failed because it didn't own the +window, and the panel stayed on screen, frozen. The post was also dropped if the +game WndProc had already been unhooked at shutdown. + +- New `LayeredWindow.DestroyOnOwnerThread`: it looks up the window's owning thread with + `GetWindowThreadProcessId`. + - If the window no longer exists, it logs and returns. + - If the caller owns the window, it calls `DestroyWindow` inline. + - Otherwise it posts the new `WM_RYNTH_SELF_DESTROY` (0x8005) to the panel window itself. + The panel's own `StaticWndProc` then destroys it on its owner thread. This never + blocks the caller, and it works after the game WndProc is unhooked. +- `PostMessage` in `LayeredWindow` now sets the last error, so a failed post is logged + with the real error code. +- Removed `Win32Backend.PostDestroyWindow` and its `WM_RYNTH_DESTROY_HWND` (0x8003) + handler; 0x8003 is reserved and not reused. The shutdown sweep + (`WM_RYNTH_SWEEP_PANELS`) remains as a backstop for panels that were never disposed. + +## Hold the login-time pop-out until panels can be created on the game thread + +Floating panels saved as popped out are restored when `LoginComplete` fires. That can +happen before the engine has found and subclassed the game window, so +`FloatingPanelHost` took its legacy path and created the window on the Avalonia UI +thread. That path brings back the Win11 `WS_EX_NOACTIVATE` click-drop race and the +cross-thread destroy problem above. + +- New `Win32Backend.CanRunOnGameThread`: true once the game window is known and its + WndProc is subclassed, which is what `RunOnGameThread` needs. The window handle + alone isn't enough. +- `AvaloniaOverlay.RestoreFloatingPanels` now polls every 200 ms on the UI thread until + `CanRunOnGameThread` is true, then restores. It logs once when it starts holding and + again when it releases. +- After 60 s it restores anyway on the legacy path and logs a warning line, so the panels + are not lost on a client that is never hooked. diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index b7c6de8..cd199bf 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -70,13 +70,9 @@ internal static unsafe class Win32Backend /// HWNDs drop WM_LBUTTONDOWN on Win11 in some focus states). public const uint WM_RYNTH_RUN_ACTION = 0x8002; - /// UI deep-dive finding P0-1 belt-and-braces (2026-07-02): - /// posted (not sent) by LayeredWindow.Dispose to destroy an HWND on the - /// game thread without blocking the calling thread — DestroyWindow must - /// run on the owning thread, but the caller (often the Avalonia UI - /// thread, e.g. redocking a panel) doesn't need to wait for it to - /// finish. wParam carries the HWND to destroy. - public const uint WM_RYNTH_DESTROY_HWND = 0x8003; + // 0x8003 was WM_RYNTH_DESTROY_HWND (destroy a panel via the game window). + // Retired: LayeredWindow now posts WM_RYNTH_SELF_DESTROY (0x8005) to the + // panel itself so it is destroyed on its real owner thread. Don't reuse 0x8003. /// Destroys floating-panel HWNDs on the game thread (their owner). /// wParam != 0 includes this engine load's own panels (sent synchronously by @@ -364,36 +360,12 @@ internal static unsafe class Win32Backend } /// - /// UI deep-dive finding P0-1 (2026-07-02): posts (does not block on) a - /// DestroyWindow for onto the game thread. - /// DestroyWindow must run on the HWND's owning thread, but unlike - /// RunOnGameThread this never needs the caller to observe a result — so - /// it uses a dedicated PostMessage instead of the shared - /// RunOnGameThread action slot, avoiding any risk of blocking the - /// caller (e.g. LayeredWindow.Dispose called from the Avalonia UI - /// thread while redocking a panel) on the game thread's WndProc. + /// True once the game window is known AND its WndProc is subclassed, i.e. + /// can actually deliver work to AC's main + /// thread. Knowing the HWND alone is not enough: without the subclass, + /// WM_RYNTH_RUN_ACTION reaches AC's own WndProc, which ignores it. /// - public static void PostDestroyWindow(IntPtr hwnd) - { - if (hwnd == IntPtr.Zero) return; - if (_gameHwnd == IntPtr.Zero) - { - // No game thread to marshal to (e.g. very early/late in - // lifecycle) — best-effort inline as LayeredWindow.Dispose's own - // fallback already does for the RunOnGameThread-unavailable case. - DestroyWindow(hwnd); - return; - } - - GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId); - if (gameThreadId == GetCurrentThreadId()) - { - DestroyWindow(hwnd); - return; - } - - PostMessage(_gameHwnd, WM_RYNTH_DESTROY_HWND, hwnd, IntPtr.Zero); - } + public static bool CanRunOnGameThread => _initialized && _gameHwnd != IntPtr.Zero; /// Deactivates chat capture. The game HWND retains focus throughout so no /// Win32 focus transfer is needed. @@ -532,10 +504,11 @@ internal static unsafe class Win32Backend if (!_initialized) return; // Destroy floating panels while our hook can still run on the game - // thread. LayeredWindow.Dispose only POSTS its destroy, and the game - // thread usually hasn't reached that post by the time we unhook below — - // AC's own WndProc then drops it and the panel outlives this engine - // load, frozen and unclickable (duplicate RynthAi dashboard after RL). + // thread. LayeredWindow.Dispose posts its destroy to the panel itself + // (handled by the panel's own WndProc, which survives this unhook), but + // any panel never disposed would outlive this engine load, frozen and + // unclickable (duplicate RynthAi dashboard after RL) — this sweep is the + // synchronous backstop for those. IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero, SMTO_NORMAL, 2000, out _); if (swept == IntPtr.Zero) @@ -706,19 +679,6 @@ internal static unsafe class Win32Backend return IntPtr.Zero; } - if (msg == WM_RYNTH_DESTROY_HWND) - { - IntPtr target = wParam; - try - { - bool destroyed = DestroyWindow(target); - int err = destroyed ? 0 : Marshal.GetLastWin32Error(); - RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}."); - } - catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); } - return IntPtr.Zero; - } - if (msg == WM_RYNTH_SWEEP_PANELS) { try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); } diff --git a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs index c5636ad..75c1a83 100644 --- a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs +++ b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs @@ -1487,7 +1487,53 @@ internal class RynthOverlayWindow : Window } } - private void RestoreFloatingPanels(List titles) + // How often, and for how long, the login-time floating-panel restore waits + // for Win32Backend to be able to create windows on AC's game thread. + private const int FloatingRestorePollMs = 200; + private const long FloatingRestoreMaxWaitMs = 60_000; + + /// + /// Restores saved floating panels, but only once + /// is true, so + /// each panel's LayeredWindow is created on AC's game thread like every + /// other pop-out. LoginComplete can fire before the engine has found and + /// hooked the game window; popping out then makes FloatingPanelHost take + /// its legacy path and create the HWND on the Avalonia UI thread instead + /// (Win11 WS_EX_NOACTIVATE focus race, cross-thread destroy on redock). + /// Polls on the UI thread; after it + /// restores anyway (logged) so a never-hooked client doesn't lose the panels. + /// + private void RestoreFloatingPanels(List titles) => + RestoreFloatingPanelsWhenGameThreadReady(titles, Environment.TickCount64 + FloatingRestoreMaxWaitMs, loggedWait: false); + + private void RestoreFloatingPanelsWhenGameThreadReady(List titles, long deadline, bool loggedWait) + { + if (!ImGuiBackend.Win32Backend.CanRunOnGameThread) + { + if (Environment.TickCount64 < deadline) + { + if (!loggedWait) + { + try { RynthLog.UI($"AvaloniaOverlay: holding {titles.Count} floating panel(s) until the game window is hooked (GameHwnd=0x{ImGuiBackend.Win32Backend.GameHwnd.ToInt64():X}): [{string.Join(", ", titles)}]"); } catch { } + } + DispatcherTimer.RunOnce( + () => RestoreFloatingPanelsWhenGameThreadReady(titles, deadline, loggedWait: true), + TimeSpan.FromMilliseconds(FloatingRestorePollMs), + DispatcherPriority.Background); + return; + } + + try { RynthLog.UI($"AvaloniaOverlay: game window still not hooked after {FloatingRestoreMaxWaitMs / 1000}s — restoring floating panels on the legacy (UI-thread) path."); } catch { } + } + else if (loggedWait) + { + try { RynthLog.UI("AvaloniaOverlay: game window hooked — restoring held floating panels on the game thread."); } catch { } + } + + RestoreFloatingPanelsNow(titles); + } + + private void RestoreFloatingPanelsNow(List titles) { try { diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index cf45708..9ba8939 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -67,6 +67,10 @@ internal sealed unsafe class LayeredWindow : IDisposable // because LayeredWindow lives in UI/ and avoids depending on the ImGui // subsystem. private const uint WM_RYNTH_RESTORE_FOCUS = 0x8001; + // Posted by DestroyOnOwnerThread to the panel HWND itself, so DestroyWindow + // runs in StaticWndProc on whichever thread owns it. Must not collide with + // Win32Backend's game-window messages (0x8001-0x8004). + private const uint WM_RYNTH_SELF_DESTROY = 0x8005; private const uint WM_ENTERSIZEMOVE = 0x0231; private const uint WM_EXITSIZEMOVE = 0x0232; private const uint WM_NCHITTEST = 0x0084; @@ -199,7 +203,7 @@ internal sealed unsafe class LayeredWindow : IDisposable [DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd); private const uint GW_OWNER = 4; [DllImport("user32.dll")] private static extern bool ReleaseCapture(); - [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll", SetLastError = true)] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint); @@ -264,6 +268,16 @@ internal sealed unsafe class LayeredWindow : IDisposable [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam) { + // Handled before the instance lookup: Dispose has already removed the + // instance by the time this posted message is dispatched. + if (msg == WM_RYNTH_SELF_DESTROY) + { + bool destroyed = DestroyWindow(hwnd); + int err = destroyed ? 0 : Marshal.GetLastWin32Error(); + RynthCore.Engine.RynthLog.Info($"LayeredWindow: self-destroy DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed} err={err} on thread=0x{GetCurrentThreadId():X}."); + return IntPtr.Zero; + } + LayeredWindow? self; lock (_instancesLock) _instances.TryGetValue(hwnd, out self); @@ -294,12 +308,11 @@ internal sealed unsafe class LayeredWindow : IDisposable /// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on /// the owning thread. /// - /// Dispose only posts the destroy, and Win32Backend.Shutdown unhooks the - /// game WndProc ~1 ms after the overlay stops — usually before the game - /// thread gets to the post. AC's own WndProc then drops it, and because - /// the engine module is never unloaded the panel lives on: frozen on its - /// last frame, deaf to input, and hidden under the next generation's copy - /// of it until that one is moved ("two RynthAi windows"). + /// Synchronous backstop for panels that were never disposed: because the + /// engine module is never unloaded, such a panel lives on after shutdown, + /// frozen on its last frame, deaf to input, and hidden under the next + /// generation's copy of it until that one is moved ("two RynthAi windows"). + /// (Disposed panels destroy themselves via WM_RYNTH_SELF_DESTROY.) /// /// =false spares this engine /// load's own windows (class names carry a per-load Guid) and removes only @@ -1180,34 +1193,51 @@ internal sealed unsafe class LayeredWindow : IDisposable lock (_instancesLock) _instances.Remove(hwnd); - // DestroyWindow MUST run on the thread that owns the HWND — Win32 - // silently no-ops it otherwise. The HWND was created on the game - // thread (see FloatingPanelHost ctor's RunOnGameThread wrap), so - // marshal the teardown there too. Without this, redocking left - // the original floating window visible but orphaned ("frozen - // duplicate"). - // - // UI deep-dive finding P0-1 (2026-07-02): this used to block via - // RunOnGameThread (a synchronous SendMessage) — Dispose is often - // called from the Avalonia UI thread (e.g. redocking a panel), - // and blocking it on the game thread's WndProc is part of the - // same AB-BA deadlock class the OnInput fix closes. Dispose - // doesn't need to observe the destroy completing, so post it - // instead — fire-and-forget, never blocks the caller. - try - { - RynthCore.Engine.ImGuiBackend.Win32Backend.PostDestroyWindow(hwnd); - } - catch (Exception ex) - { - RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: PostDestroyWindow threw {ex.GetType().Name}: {ex.Message}. Falling back to inline call on thread=0x{GetCurrentThreadId():X}."); - // Best-effort fallback if Win32Backend isn't available - // (e.g. early shutdown after it's already torn down). - bool destroyed = DestroyWindow(hwnd); - RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: fallback DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed}."); - } + // DestroyWindow MUST run on the thread that owns the HWND (Win32 + // fails it with ERROR_ACCESS_DENIED otherwise); a missed destroy + // leaves the floating window visible but orphaned ("frozen duplicate"). + DestroyOnOwnerThread(hwnd); } DisposeDib(); } + + /// + /// Destroys on the thread that actually owns it, never + /// blocking the caller. Inline when the caller is the owner; otherwise posts + /// WM_RYNTH_SELF_DESTROY to the window itself so its own WndProc destroys it. + /// Posting to the panel (not the game window) works for panels created on + /// any thread, and still works after Win32Backend has unhooked the game + /// WndProc at shutdown — a post to the game window would be dropped by AC. + /// + private static void DestroyOnOwnerThread(IntPtr hwnd) + { + uint ownerThread = GetWindowThreadProcessId(hwnd, out _); + uint currentThread = GetCurrentThreadId(); + + if (ownerThread == 0) + { + // Window already gone (e.g. its owning thread exited, which destroys it). + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: HWND=0x{hwnd.ToInt64():X} no longer exists — nothing to destroy."); + return; + } + + if (ownerThread == currentThread) + { + bool destroyed = DestroyWindow(hwnd); + int err = destroyed ? 0 : Marshal.GetLastWin32Error(); + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: DestroyWindow(0x{hwnd.ToInt64():X}) inline on owner thread=0x{currentThread:X} = {destroyed} err={err}."); + return; + } + + if (PostMessage(hwnd, WM_RYNTH_SELF_DESTROY, IntPtr.Zero, IntPtr.Zero)) + { + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: posted self-destroy to HWND=0x{hwnd.ToInt64():X} (owner thread=0x{ownerThread:X}, caller thread=0x{currentThread:X})."); + return; + } + + // Post failed (queue full or HWND destroyed in the meantime); a cross-thread + // DestroyWindow would only fail, so report it rather than attempt it. + RynthCore.Engine.RynthLog.Error($"LayeredWindow.Dispose: PostMessage(self-destroy) to HWND=0x{hwnd.ToInt64():X} failed err={Marshal.GetLastWin32Error()} (owner thread=0x{ownerThread:X})."); + } }