From c9743a2612ffa3678edffd4382cdc7d7afd69ac8 Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Mon, 12 Oct 2026 01:06:53 -0400 Subject: [PATCH] feat(engine): SK engine and UI work through 2026-10-10 on 2026.10.12.1 See Changelog/2026-10-11-sk-engine-work-through-10-10.md. Co-authored-by: Cursor --- ...2026-10-11-sk-engine-work-through-10-10.md | 90 +++ RynthCore.sln | 15 + native/SehTrampoline/SehTrampoline.c | 557 +++++++++++--- src/RynthCore.App.Avalonia/App.axaml.cs | 14 + src/RynthCore.App.Avalonia/EngineJsonStore.cs | 15 + .../InstallerHandoff.cs | 29 + src/RynthCore.App.Avalonia/LauncherDiag.cs | 1 + .../LauncherHostDiagnostics.cs | 110 +++ .../LoggingSettingsStore.cs | 192 +++++ .../MainWindow.Logging.cs | 153 ++++ src/RynthCore.App.Avalonia/MainWindow.axaml | 50 +- .../MainWindow.axaml.cs | 150 +++- .../RynthCore.App.Avalonia.csproj | 14 +- src/RynthCore.App/AppSettings.cs | 10 + src/RynthCore.DesktopLog/DesktopRollingLog.cs | 130 ++++ .../NetDesktopX64Prerequisite.cs | 105 +++ .../RynthCore.DesktopLog.csproj | 10 + .../Compatibility/ClientHelperHooks.cs | 27 +- .../Compatibility/ClientObjectHooks.cs | 180 ++++- .../Compatibility/CreateObjectHooks.cs | 3 + .../Compatibility/DeleteObjectHooks.cs | 1 + .../Compatibility/DragDropHooks.cs | 110 +++ .../Compatibility/HeartbeatLogger.cs | 3 +- .../Compatibility/MergeStackResults.cs | 77 ++ .../Compatibility/SehTrampoline.cs | 22 +- src/RynthCore.Engine/D3D9/EndSceneHook.cs | 5 + src/RynthCore.Engine/EngineLifecycle.cs | 1 + src/RynthCore.Engine/EntryPoint.cs | 112 ++- .../ImGui/EngineFrameController.cs | 178 ++++- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 106 +++ src/RynthCore.Engine/ImGui/ItemDragBridge.cs | 251 +++++++ .../ImGui/Panels/ChatFiltersFace.cs | 60 +- .../ImGui/Panels/DashboardDrawers.cs | 4 +- .../ImGui/Panels/DungeonMapFace.cs | 2 +- .../ImGui/Panels/InventoryFace.Classic.cs | 2 +- .../ImGui/Panels/InventoryFace.cs | 78 +- src/RynthCore.Engine/ImGui/Panels/NavFace.cs | 317 +++++++- .../ImGui/Panels/RynthAiFace.Drawers.cs | 93 ++- .../ImGui/Panels/RynthAiFace.cs | 107 ++- .../ImGui/Panels/SettingsFace.cs | 281 ++++++- .../ImGui/Panels/SkillsFace.Progression.cs | 693 ++++++++++++++++++ .../ImGui/Panels/SkillsFace.cs | 27 +- src/RynthCore.Engine/ImGui/Win32Backend.cs | 42 +- src/RynthCore.Engine/LogPaths.cs | 1 + src/RynthCore.Engine/LogSettings.cs | 245 +++++++ .../Plugins/EngineSettings.cs | 46 +- src/RynthCore.Engine/Plugins/LoadedPlugin.cs | 53 ++ .../Plugins/PluginContract.cs | 26 +- .../Plugins/PluginContractVersion.cs | 3 +- src/RynthCore.Engine/Plugins/PluginLoader.cs | 10 + src/RynthCore.Engine/Plugins/PluginManager.cs | 197 +++++ src/RynthCore.Engine/RynthCore.Engine.csproj | 7 +- src/RynthCore.Engine/RynthLog.cs | 97 +-- src/RynthCore.Engine/UI/Data/CharmsData.cs | 78 ++ src/RynthCore.Engine/UI/Data/ChatData.cs | 23 + src/RynthCore.Engine/UI/Data/ChatRouting.cs | 27 +- .../UI/Data/ChatSettingsDto.cs | 10 + src/RynthCore.Engine/UI/Data/ItemsData.cs | 19 +- src/RynthCore.Engine/UI/Data/NavData.cs | 30 + .../UI/Data/ProgressionData.cs | 206 ++++++ src/RynthCore.Engine/UI/Data/RynthAiData.cs | 33 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 137 +++- src/RynthCore.Engine/UI/Data/UiSources.cs | 4 + src/RynthCore.Engine/UI/LayeredWindow.cs | 78 +- src/RynthCore.Engine/UI/OverlayFrameBuffer.cs | 72 ++ src/RynthCore.Engine/UI/Panels/ItemsPanel.cs | 158 +++- src/RynthCore.Engine/UI/Panels/NavPanel.cs | 38 +- .../UI/Panels/RynthAiPanel.cs | 48 +- .../UI/Panels/RynthChatFiltersPanel.cs | 117 ++- .../UI/Panels/RynthChatPresets.cs | 250 +++++++ .../UI/Panels/SettingsPanel.cs | 156 ++++ .../UI/RynthAiDashboardState.cs | 21 +- src/RynthCore.Injector/LaunchCommand.cs | 3 +- src/RynthCore.Injector/Program.cs | 1 + src/RynthCore.Loader/EntryPoint.cs | 1 + src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 2 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 33 + .../build/RynthCore.PluginSdk.targets | 2 +- src/RynthCore.StatusAgent/AgentConfig.cs | 1 + tools/PluginManifestTests/Program.cs | 16 +- 80 files changed, 6311 insertions(+), 365 deletions(-) create mode 100644 Changelog/2026-10-11-sk-engine-work-through-10-10.md create mode 100644 src/RynthCore.App.Avalonia/InstallerHandoff.cs create mode 100644 src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs create mode 100644 src/RynthCore.App.Avalonia/LoggingSettingsStore.cs create mode 100644 src/RynthCore.App.Avalonia/MainWindow.Logging.cs create mode 100644 src/RynthCore.DesktopLog/DesktopRollingLog.cs create mode 100644 src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs create mode 100644 src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj create mode 100644 src/RynthCore.Engine/Compatibility/DragDropHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/MergeStackResults.cs create mode 100644 src/RynthCore.Engine/ImGui/ItemDragBridge.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs create mode 100644 src/RynthCore.Engine/LogSettings.cs create mode 100644 src/RynthCore.Engine/UI/Data/CharmsData.cs create mode 100644 src/RynthCore.Engine/UI/Data/ProgressionData.cs create mode 100644 src/RynthCore.Engine/UI/OverlayFrameBuffer.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs diff --git a/Changelog/2026-10-11-sk-engine-work-through-10-10.md b/Changelog/2026-10-11-sk-engine-work-through-10-10.md new file mode 100644 index 0000000..363ab23 --- /dev/null +++ b/Changelog/2026-10-11-sk-engine-work-through-10-10.md @@ -0,0 +1,90 @@ +# SK engine and UI work through 2026-10-10, rebased on 2026.10.12.1 + +Replaces the closed per-feature PRs RynthCore #1-#5 and the earlier `sk` commits. This commit +carries everything from those PRs that main doesn't already have, merged onto release 2026.10.12.1 +with the conflicts resolved. Work from 2026-10-11 follows in separate commits. + +Nothing here changes what 2026.10.12.1 already does unless a setting below says so. + +## Merge notes for 2026.10.12.1 + +- **API v81:** 2026.10.12.1 took v80 for `GetContainerOrder` and `PutItemInContainer`, so + `GetMergeStackResult` moves to v81, after them (engine table, SDK table, + `RynthCoreSdkApiVersion`, `HasGetMergeStackResult`, and the manifest test's slot order). + Plugins built against the earlier SK SDK must be rebuilt. +- **Chat routing:** `ChatRouter` now lives in `UI/Data/ChatRouting.cs`. The standard-filter step + (`RynthChatPresets`) is added there instead of in `ChatData.cs`. +- **Settings:** `LoggingLevel` and `EnablePluginOverlayWindows` sit next to the new + `CloseOnServerDisconnect`; the Items payload keeps both `missingIds` and `autoEquipShield`. + +## Launcher and logging + +- **Logging level** in the launcher (Error, Warning, Info, Debug, Trace), saved as `LoggingLevel` + in `engine.json`. The engine reads it at start and watches it while running + (`LogSettings`, `LoggingSettingsStore`, `MainWindow.Logging`). Per-category trace switches are + shown with a warning when a category is hidden by the level. +- The heartbeat line is always written, whatever the level, because the launcher uses it to tell + a client is alive (`RynthLog.Heartbeat`). +- `RynthCore.DesktopLog` (new project): rolling launcher log and the .NET desktop x64 prerequisite + check, with host diagnostics in the launcher (`LauncherHostDiagnostics`). +- Install-aware paths: the launcher, injector, loader and status agent find the install folder the + installer recorded (`InstallerHandoff`, `LogPaths`) instead of assuming `C:\Games\RynthCore`. + +## Plugin windows and ImGui + +- **Plugin overlay windows** while the ImGui shell is off: a plugin that exports + `RynthPluginRenderOverlay` draws its extra ImGui windows over the Avalonia UI. + `engine.json` `"EnablePluginOverlayWindows": false` turns this off. Plugins get the engine's + ImGui context for these windows. +- ImGui draw data is submitted after the Avalonia blit, so ImGui windows stay on top. +- Panel windows are destroyed on the thread that owns them, and a login pop-out waits until the + game window is hooked. +- Docked panels open clear of popped-out windows (`LayeredWindow`). +- `CS0162` (unreachable code) is an error in the engine project: a misplaced statement after a + `return` once left the plugin render snapshot unpublished. + +## Items, drag and drop, object data + +- **Item drag bridge** (`ItemDragBridge`, `DragDropHooks`): items dragged from the game or from a + popped-out Inventory can be dropped on Mini Remote slots. Game-inventory drags carry the dragged + item, not the previous selection. +- Object name and type are seeded when the object is created, so panels show them before the + first update (`CreateObjectHooks`, `DeleteObjectHooks`). +- Off-thread int property reads are snapshotted from the PWD and kept current with server + updates (`ClientObjectHooks`); IconOverlay and IconUnderlay DIDs are served from the PWD. +- **Merge-stack results** (API v81, `GetMergeStackResult`, after rynth's v80 slots): plugins can see whether a stack merge + went through (`MergeStackResults`). The thunk is cdecl; stdcall corrupted plugin stacks. + +## Native crash logging + +- `SehTrampoline.c`: the native crash logger records only fatal faults by default, and logs + access violations in the CoreCLR-hosted engine immediately rather than at exit. + +## Panels + +- **Nav:** route editing in the Nav panel, Breadcrumbs and Route overlay toggles, + and the waypoint list no longer jumps back to the top on every poll. +- **Skills > Progression tab:** XP and augmentation planning laid out like UB's ILT Tools XP and + Augs tabs, an attribute raiser, and per-server augmentation cost settings + (`ProgressionData`). The Char launcher has a menu that opens it. +- **Chat filters:** UB-IT-style standard filters, plain-text custom rule modes, a line tester, and + presets (`RynthChatPresets`). +- **RynthAi dashboard:** Char and Hub launcher buttons, Map and Lua buttons, a Mini Remote drawer, + a Buffs picker in Loaded Files and a Spells window button. +- **Items panel (Avalonia):** Shields section and Add Selected Shield. +- **Inventory:** a menu item that adds an item to RynthAi's item count HUD. +- **Settings:** Charms Tracking tab, an Inventory HUDs button, the Server Features text row, and + one "Describe Items When Selected" toggle (the duplicate "Item Info On Select" row is removed). +- **Loot:** "Include T11 attributes" in the Add to loot profile popup, with a tooltip that covers + the stamped tier and gear grade. + +## Build + +- `RynthCore.sln` includes `RynthCore.DesktopLog`. +- One `Tmds.DBus.Protocol` 0.21.3 pin in the engine project (GHSA-xrw6-gwf8-vvr9). + +## Testing + +- Engine (CoreCLR host) and launcher build in Release. +- `tools/PluginManifestTests` pass. +- Each feature was run in game on the SK builds of 2026-10-04 to 2026-10-10. diff --git a/RynthCore.sln b/RynthCore.sln index 971bb41..e450961 100644 --- a/RynthCore.sln +++ b/RynthCore.sln @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Engine", "src\Ryn EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DesktopLog", "src\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj", "{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" @@ -63,6 +65,18 @@ Global {A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.ActiveCfg = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.Build.0 = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.ActiveCfg = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.Build.0 = Debug|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.ActiveCfg = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.Build.0 = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.Build.0 = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.ActiveCfg = Release|Any CPU + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.Build.0 = Release|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86 {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86 {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -179,6 +193,7 @@ Global {2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {D1E2F3A4-5678-4ABC-8DEF-1234567890AB} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} {C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index a458eeb..5b4bba8 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -26,12 +26,36 @@ #define WIN32_LEAN_AND_MEAN #include +/* File version of this native module (bump with every behavioural change). */ +#define RC_SEH_TRAMPOLINE_VERSION 3 /* v3: CoreCLR-hosted engine AVs logged immediately */ + +/* Crash-logger state that the SEH_* wrappers and DllMain also touch (defined below). */ +static __declspec(thread) int t_sehDepth; /* >0 while inside an SEH_* wrapper call */ +static void CrashLoggerFlushOnExit(void); + +/* Every SEH_* wrapper brackets its guarded call with these so the crash logger knows an + * access violation on this thread is about to be caught by our own __except. */ +#define RC_SEH_ENTER() (++t_sehDepth) +#define RC_SEH_LEAVE() (--t_sehDepth) + BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved) { - (void)hModule; (void)ul_reason; (void)lpReserved; + (void)hModule; + /* lpReserved != NULL on DLL_PROCESS_DETACH means the process is exiting (ExitProcess), + * which is how AC's own crash handling ends the process: write out any recent + * first-chance AVs so a crash AC swallowed still leaves a trace. */ + if (ul_reason == DLL_PROCESS_DETACH && lpReserved != NULL) { + CrashLoggerFlushOnExit(); + } return TRUE; } +/* Diagnostic: native module version so the engine log can confirm which build is loaded. */ +__declspec(dllexport) unsigned int __cdecl RC_SehTrampolineVersion(void) +{ + return RC_SEH_TRAMPOLINE_VERSION; +} + /* ── Cdecl helpers ─────────────────────────────────────────────────────── */ /* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */ @@ -40,14 +64,17 @@ __declspec(dllexport) int __cdecl SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result) { *out_result = NULL; + RC_SEH_ENTER(); __try { *out_result = fn(arg); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = NULL; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -57,14 +84,17 @@ __declspec(dllexport) int __cdecl SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result) { *out_result = NULL; + RC_SEH_ENTER(); __try { *out_result = fn(); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = NULL; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -73,13 +103,16 @@ typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char); __declspec(dllexport) int __cdecl SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2) { + RC_SEH_ENTER(); __try { fn(arg1, arg2); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); return 0; } + RC_SEH_LEAVE(); return 1; } @@ -95,13 +128,16 @@ typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int s __declspec(dllexport) int __cdecl SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId) { + RC_SEH_ENTER(); __try { ((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); return 0; } + RC_SEH_LEAVE(); return 1; } @@ -152,14 +188,17 @@ SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg, unsigned char* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -171,14 +210,17 @@ __declspec(dllexport) int __cdecl SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_uint_noarg(fn, this_ptr); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -209,179 +251,480 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, int* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } -/* ── Process-wide native crash logger (VEH) ─────────────────────────────── - * Logs the faulting 32-bit context + a module-resolved stack sweep to a - * dedicated file BEFORE the process dies, for the fatal exceptions that bypass - * NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and - * 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled - * managed exception or a stack-walk fail-fast in the plugin/engine). +/* ── Process-wide native crash logger (fatal-only, v2) ──────────────────── + * Goal: native-crash.log holds FATAL crashes only. v1 logged every first-chance AV + * (including ones AC or our own SEH_* wrappers handle) plus its own stack-sweep faults, + * so its 24-entry cap filled with noise before a real crash could be recorded. * - * This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so - * unlike the removed managed CrashLogger VEH it cannot itself re-trigger a - * NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns - * EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly - * as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio / - * user32) so the build link line stays unchanged. Hardened: stack sweep in - * __try/__except, capped log count, dedicated file (no contention with the - * managed log). x86 (32-bit) context fields only — matches the WOW64 target. + * All paths are PURE NATIVE (no managed callback / reverse-P/Invoke — that could itself + * trigger a NativeAOT fail-fast on an AC-owned thread) and observe-only: they always + * return EXCEPTION_CONTINUE_SEARCH or chain, so AC's SEH and the runtime proceed exactly + * as before. Only kernel32 APIs + hand-rolled, bounds-checked formatting (no CRT stdio). + * + * 1. Unhandled-exception filter (SetUnhandledExceptionFilter, chained to the previous + * filter): an exception nobody handled is written immediately as FATAL. + * 2. First-chance VEH, immediate: AVs whose faulting address is inside a NativeAOT + * module (engine / plugins). The runtime fail-fasts on those via + * RaiseFailFastException, which bypasses every handler including the filter in (1), + * so first chance is the only chance to record them. 0xC0000602 / 0xC0000409 too. + * 2b. (v3) Same for the CoreCLR-hosted engine (RynthCore.Shim): non-null AVs in JIT'd + * code (private executable memory, no module), coreclr.dll / clrjit.dll, or the + * framework's precompiled System.* / Microsoft.* images. CoreCLR treats a non-null + * AV in managed code as uncatchable and fail-fasts with HandleFatalError (the WER + * signature coreclr.dll+0x2c1c6e c0000005 is that fail-fast site, not the bug), so + * the deferred ring below was never flushed and native-crash.log stayed empty. AVs + * with a data address under 64K are skipped there: CoreCLR turns those into a + * catchable NullReferenceException. + * 3. First-chance VEH, deferred: every other AV (acclient.exe, drivers, DINPUT8, …) is + * formatted into an in-memory ring and written ONLY if the process then dies — via + * the filter in (1), or at ExitProcess (DllMain detach) when it happened within the + * last CL_EXIT_FLUSH_WINDOW_MS (AC's own crash handling ends with ExitProcess). + * AVs that AC handles and survives never reach the file. + * + * Skipped entirely: AVs raised inside our own SEH_* wrappers (t_sehDepth > 0 — our + * __except catches them) and any fault raised while the logger itself is running on + * that thread (t_inLogger — v1 logged its own sweep faults as SehTrampoline.dll+0x13E8). + * + * The stack sweep is bounded to [Esp, NtCurrentTeb()->NtTib.StackBase); v1 read 4096 + * slots past ESP unconditionally and ran off the top of the stack. + * x86 (32-bit) context fields only — matches the WOW64 target. */ +#define CL_SLOT_BYTES 8192 /* one formatted record */ +#define CL_RING_SLOTS 8 /* deferred first-chance records kept in memory */ +#define CL_MAX_IMMEDIATE 16 /* NativeAOT-module / fail-fast records per run */ +#define CL_MAX_FATAL 8 /* unhandled-exception records per run */ +#define CL_MAX_SWEEP_SLOTS 4096 /* stack slots scanned (also capped by StackBase) */ +#define CL_MAX_SWEEP_LINES 96 /* code pointers emitted per record */ +#define CL_EXIT_FLUSH_WINDOW_MS 30000 /* deferred AVs this recent are flushed at exit */ + +#define CL_SLOT_EMPTY 0 +#define CL_SLOT_WRITING 1 +#define CL_SLOT_PENDING 2 /* deferred first-chance AV, not in the file (yet) */ +#define CL_SLOT_DONE 3 /* written to the file, or discarded */ + +typedef struct { + volatile LONG state; + DWORD tid; + DWORD tick; + unsigned int exAddr; + int len; + char text[CL_SLOT_BYTES]; +} CL_SLOT; + static wchar_t g_crashLogPath[MAX_PATH]; -static volatile LONG g_crashCount = 0; -static PVOID g_vehHandle = NULL; +static PVOID g_vehHandle = NULL; +static CL_SLOT g_ring[CL_RING_SLOTS]; +static volatile LONG g_ringNext = 0; +static volatile LONG g_immediateCount = 0; +static volatile LONG g_fatalCount = 0; +static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL; +static __declspec(thread) int t_inLogger; /* logger running on this thread */ +static __declspec(thread) int t_inUef; /* filter running (guards chain cycles) */ -static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; } +/* ── Bounds-checked text writer ── */ +typedef struct { char* p; char* end; } CL_W; -static char* cl_hex(char* p, unsigned int v) +static void cl_str(CL_W* w, const char* s) +{ + while (*s && w->p < w->end) { *w->p++ = *s++; } +} + +static void cl_hex(CL_W* w, unsigned int v) { const char* H = "0123456789ABCDEF"; int i; - *p++ = '0'; *p++ = 'x'; - for (i = 28; i >= 0; i -= 4) { *p++ = H[(v >> i) & 0xF]; } - return p; + cl_str(w, "0x"); + for (i = 28; i >= 0 && w->p < w->end; i -= 4) { *w->p++ = H[(v >> i) & 0xF]; } } -static char* cl_u(char* p, unsigned int v) +static void cl_u(CL_W* w, unsigned int v) { char tmp[12]; int n = 0; - if (v == 0) { *p++ = '0'; return p; } + if (v == 0) { cl_str(w, "0"); return; } while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; } - while (n) { *p++ = tmp[--n]; } - return p; + while (n && w->p < w->end) { *w->p++ = tmp[--n]; } +} + +/* Leaf file name of a loaded module, as narrow ASCII (lower-cased when lower != 0). */ +static int cl_module_leaf(HMODULE hm, char* out, int cap, int lower) +{ + wchar_t wpath[MAX_PATH]; + DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); + DWORD i, leaf = 0; + int k = 0; + for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') { leaf = i + 1; } } + for (i = leaf; i < n && k < cap - 1; i++) { + char ch = (char)wpath[i]; + if (lower && ch >= 'A' && ch <= 'Z') { ch = (char)(ch - 'A' + 'a'); } + out[k++] = ch; + } + out[k] = 0; + return k; } /* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ -static char* cl_sym(char* p, unsigned int addr) +static void cl_sym(CL_W* w, unsigned int addr) { HMODULE hm = NULL; /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) { - wchar_t wpath[MAX_PATH]; - DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); - DWORD i, leaf = 0; - for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; } - for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; } - p = cl_str(p, "+"); - p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm); + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 0); + cl_str(w, leaf); + cl_str(w, "+"); + cl_hex(w, addr - (unsigned int)(UINT_PTR)hm); } else { - p = cl_hex(p, addr); + cl_hex(w, addr); } - return p; } -static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +static int cl_starts_with(const char* s, const char* prefix) { + while (*prefix) { if (*s++ != *prefix++) { return 0; } } + return 1; +} + +/* ── NativeAOT module detection (cached per module base) ── */ +#define CL_MOD_CACHE 16 +static volatile UINT_PTR g_modBase[CL_MOD_CACHE]; +static volatile LONG g_modManaged[CL_MOD_CACHE]; +static volatile LONG g_modNext = 0; + +/* True when addr lies in a NativeAOT image (engine / plugin). NativeAOT images export + * DotNetRuntimeDebugHeader; RynthCore.* names are a fallback (minus our native DLLs). */ +static int cl_is_nativeaot_address(unsigned int addr) +{ + HMODULE hm = NULL; + int i, managed; + if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) { return 0; } + + for (i = 0; i < CL_MOD_CACHE; i++) { + if (g_modBase[i] == (UINT_PTR)hm) { return (int)g_modManaged[i]; } + } + + managed = GetProcAddress(hm, "DotNetRuntimeDebugHeader") != NULL; + if (!managed) { + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 1); + managed = cl_starts_with(leaf, "rynthcore.") + && !cl_starts_with(leaf, "rynthcore.sehtrampoline") + && !cl_starts_with(leaf, "rynthcore.cimgui"); + } + + /* Benign race: base is cleared first and published last, so a concurrent reader + * either misses the entry (and recomputes) or sees a matching flag. */ + i = (int)((unsigned int)InterlockedIncrement(&g_modNext) % CL_MOD_CACHE); + g_modBase[i] = 0; + g_modManaged[i] = managed; + g_modBase[i] = (UINT_PTR)hm; + return managed; +} + +/* True when addr is code of the CoreCLR-hosted engine: JIT'd code (committed private + * executable memory outside any module), the runtime itself (coreclr.dll, clrjit.dll), + * or a precompiled framework image (System.* / Microsoft.*, e.g. Marshal.ReadIntPtr in + * System.Private.CoreLib.dll). Not cached: the JIT path has no module base to key on, + * and VirtualQuery is cheap next to formatting a record. */ +static int cl_is_coreclr_address(unsigned int addr) +{ + HMODULE hm = NULL; + if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) { + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPCVOID)(UINT_PTR)addr, &mbi, sizeof(mbi)) == 0) { return 0; } + return mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE + && (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE + | PAGE_EXECUTE_WRITECOPY)) != 0; + } + { + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 1); + return cl_starts_with(leaf, "coreclr.dll") + || cl_starts_with(leaf, "clrjit.dll") + || cl_starts_with(leaf, "system.") + || cl_starts_with(leaf, "microsoft."); + } +} + +/* ── Record formatting ── */ + +/* Formats one crash record (header, registers, bounded stack sweep) into buf. + * Returns the byte count. Reads of stack memory are guarded by __try. */ +static int cl_format(char* buf, int cap, PEXCEPTION_POINTERS ep, const char* banner) +{ + CL_W w; + CONTEXT* c = ep->ContextRecord; DWORD code = ep->ExceptionRecord->ExceptionCode; - if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { - return EXCEPTION_CONTINUE_SEARCH; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + + w.p = buf; + w.end = buf + cap - 64; /* reserve room for the END line */ + + cl_str(&w, "\r\n==== NATIVE CRASH LOGGER: "); + cl_str(&w, banner); + cl_str(&w, " ====\r\n code="); + cl_hex(&w, code); + cl_str(&w, " exAddr="); + cl_sym(&w, exAddr); + cl_str(&w, " tid="); + cl_u(&w, GetCurrentThreadId()); + { + SYSTEMTIME st; GetLocalTime(&st); + cl_str(&w, " time="); + cl_u(&w, st.wHour); cl_str(&w, ":"); + if (st.wMinute < 10) { cl_str(&w, "0"); } cl_u(&w, st.wMinute); cl_str(&w, ":"); + if (st.wSecond < 10) { cl_str(&w, "0"); } cl_u(&w, st.wSecond); } - if (InterlockedIncrement(&g_crashCount) > 24) { - return EXCEPTION_CONTINUE_SEARCH; + if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { + unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; + unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; + cl_str(&w, " access="); + cl_str(&w, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); + cl_str(&w, " dataAddr="); + cl_hex(&w, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ } + cl_str(&w, "\r\n eip="); cl_sym(&w, c->Eip); + cl_str(&w, " esp="); cl_hex(&w, c->Esp); + cl_str(&w, " ebp="); cl_hex(&w, c->Ebp); + cl_str(&w, "\r\n eax="); cl_hex(&w, c->Eax); + cl_str(&w, " ebx="); cl_hex(&w, c->Ebx); + cl_str(&w, " ecx="); cl_hex(&w, c->Ecx); + cl_str(&w, " edx="); cl_hex(&w, c->Edx); + cl_str(&w, " esi="); cl_hex(&w, c->Esi); + cl_str(&w, " edi="); cl_hex(&w, c->Edi); + cl_str(&w, "\r\n stack code pointers (esp -> StackBase):\r\n"); { - HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); - if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; } - SetFilePointer(h, 0, NULL, FILE_END); - - { - char buf[4096]; - char* p = buf; - CONTEXT* c = ep->ContextRecord; - unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; - DWORD wr; - - p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code="); - p = cl_hex(p, code); - p = cl_str(p, " exAddr="); - p = cl_sym(p, exAddr); - p = cl_str(p, " tid="); - p = cl_u(p, GetCurrentThreadId()); - { - SYSTEMTIME st; GetLocalTime(&st); - p = cl_str(p, " time="); - p = cl_u(p, st.wHour); p = cl_str(p, ":"); - if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":"); - if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond); - } - if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { - unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; - unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; - p = cl_str(p, " access="); - p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); - p = cl_str(p, " dataAddr="); - p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ - } - p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip); - p = cl_str(p, " esp="); p = cl_hex(p, c->Esp); - p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp); - p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax); - p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx); - p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx); - p = cl_str(p, " edx="); p = cl_hex(p, c->Edx); - p = cl_str(p, " esi="); p = cl_hex(p, c->Esi); - p = cl_str(p, " edi="); p = cl_hex(p, c->Edi); - p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n"); - WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL); + /* The handler runs on the faulting thread, so this TEB's stack bounds apply to + * the faulting ESP. Never read at or past StackBase (top of the stack). */ + NT_TIB* tib = (NT_TIB*)NtCurrentTeb(); + UINT_PTR base = (UINT_PTR)tib->StackBase; + UINT_PTR limit = (UINT_PTR)tib->StackLimit; + UINT_PTR esp = (UINT_PTR)c->Esp; + if (esp < limit || esp >= base) { + cl_str(&w, " \r\n"); + } else { + unsigned int slots = (unsigned int)((base - esp) / sizeof(unsigned int)); + if (slots > CL_MAX_SWEEP_SLOTS) { slots = CL_MAX_SWEEP_SLOTS; } __try { - unsigned int* sp = (unsigned int*)c->Esp; - int i, emitted = 0; - for (i = 0; i < 4096 && emitted < 96; i++) { + const unsigned int* sp = (const unsigned int*)esp; + unsigned int i; + int emitted = 0; + /* 320 bytes of headroom = one full "+0xOFF module+0xRVA" line. */ + for (i = 0; i < slots && emitted < CL_MAX_SWEEP_LINES && (w.end - w.p) > 320; i++) { unsigned int v = sp[i]; if (v > 0x00401000u && v < 0x7FFF0000u) { HMODULE hm = NULL; if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) { - char* q = buf; - q = cl_str(q, " +"); - q = cl_hex(q, (unsigned int)(i * 4)); - q = cl_str(q, " "); - q = cl_sym(q, v); - q = cl_str(q, "\r\n"); - WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL); + cl_str(&w, " +"); + cl_hex(&w, i * 4u); + cl_str(&w, " "); + cl_sym(&w, v); + cl_str(&w, "\r\n"); emitted++; } } } } __except (EXCEPTION_EXECUTE_HANDLER) { - const char* m = " \r\n"; - WriteFile(h, m, (DWORD)lstrlenA(m), &wr, NULL); - } - - { - const char* e = "==== END NATIVE CRASH ====\r\n"; - WriteFile(h, e, (DWORD)lstrlenA(e), &wr, NULL); + cl_str(&w, " \r\n"); } } - CloseHandle(h); } + + w.end = buf + cap; + cl_str(&w, "==== END NATIVE CRASH ====\r\n"); + return (int)(w.p - buf); +} + +/* ── Output ── */ + +static void cl_append_file(const char* data, int len) +{ + HANDLE h; + DWORD wr; + if (len <= 0 || g_crashLogPath[0] == 0) { return; } + h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); + if (h == INVALID_HANDLE_VALUE) { return; } + SetFilePointer(h, 0, NULL, FILE_END); + WriteFile(h, data, (DWORD)len, &wr, NULL); + CloseHandle(h); +} + +/* Claims a ring slot for writing. Rotates through the ring, overwriting the oldest + * PENDING/DONE record; never steals a slot another thread is mid-write on. */ +static CL_SLOT* cl_claim_slot(void) +{ + int tries; + for (tries = 0; tries < CL_RING_SLOTS * 2; tries++) { + CL_SLOT* s = &g_ring[(unsigned int)InterlockedIncrement(&g_ringNext) % CL_RING_SLOTS]; + LONG st = s->state; + if (st != CL_SLOT_WRITING && + InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, st) == st) { + return s; + } + } + return NULL; +} + +/* Writes PENDING deferred records to the file. Skips the record matching skipTid/skipAddr + * (the same fault the caller is about to log) and, when maxAgeMs != 0, records older + * than maxAgeMs (handled AVs from long before the exit). */ +static void cl_flush_pending(DWORD skipTid, unsigned int skipAddr, DWORD maxAgeMs) +{ + DWORD now = GetTickCount(); + int i; + for (i = 0; i < CL_RING_SLOTS; i++) { + CL_SLOT* s = &g_ring[i]; + if (InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, CL_SLOT_PENDING) != CL_SLOT_PENDING) { + continue; + } + if ((skipTid != 0 && s->tid == skipTid && s->exAddr == skipAddr) || + (maxAgeMs != 0 && now - s->tick > maxAgeMs)) { + InterlockedExchange(&s->state, CL_SLOT_DONE); + continue; + } + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } +} + +/* ── Handlers ── */ + +static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +{ + DWORD code = ep->ExceptionRecord->ExceptionCode; + unsigned int exAddr; + int immediate; + int coreclr = 0; + CL_SLOT* s; + + if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { + return EXCEPTION_CONTINUE_SEARCH; + } + if (t_inLogger) { + return EXCEPTION_CONTINUE_SEARCH; /* our own fault — the logger's __try handles it */ + } + if (code == 0xC0000005 && t_sehDepth > 0) { + return EXCEPTION_CONTINUE_SEARCH; /* an SEH_* wrapper's __except will catch it */ + } + + t_inLogger = 1; + exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + immediate = (code != 0xC0000005) || cl_is_nativeaot_address(exAddr); + if (!immediate) { + /* v3: CoreCLR-hosted engine. A data address under 64K is a null-ref that CoreCLR + * hands to managed code as NullReferenceException, so it stays deferred. */ + unsigned int dataAddr = ep->ExceptionRecord->NumberParameters >= 2 + ? (unsigned int)ep->ExceptionRecord->ExceptionInformation[1] : 0; + coreclr = dataAddr >= 0x10000 && cl_is_coreclr_address(exAddr); + immediate = coreclr; + } + + if (!immediate || InterlockedIncrement(&g_immediateCount) <= CL_MAX_IMMEDIATE) { + s = cl_claim_slot(); + if (s) { + s->tid = GetCurrentThreadId(); + s->tick = GetTickCount(); + s->exAddr = exAddr; + s->len = cl_format(s->text, CL_SLOT_BYTES, ep, + code != 0xC0000005 + ? "FAIL-FAST / STACK CHECK (always fatal)" + : (coreclr + ? "AV IN CORECLR-HOSTED CODE (JIT / runtime; fail-fast, non-null address)" + : immediate + ? "AV IN NATIVEAOT CODE (runtime fail-fasts unless it is a null-ref)" + : "FIRST-CHANCE AV (deferred; written because the process died or exited soon after)")); + if (immediate) { + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } else { + InterlockedExchange(&s->state, CL_SLOT_PENDING); + } + } + } + + t_inLogger = 0; return EXCEPTION_CONTINUE_SEARCH; } -/* Install the VEH once. logPath = wide path to the dedicated crash log. */ +/* Unhandled-exception filter: nobody caught this exception, so it is fatal. */ +static LONG WINAPI CrashUef(PEXCEPTION_POINTERS ep) +{ + LONG verdict = EXCEPTION_CONTINUE_SEARCH; + + /* A replaced-then-reasserted filter chain can loop back here; bail out of the cycle. */ + if (t_inUef) { + return EXCEPTION_CONTINUE_SEARCH; + } + t_inUef = 1; + + if (!t_inLogger && InterlockedIncrement(&g_fatalCount) <= CL_MAX_FATAL) { + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + CL_SLOT* s; + t_inLogger = 1; + /* Earlier first-chance AVs (other threads, earlier faults) are context for this + * crash; the first-chance record of THIS fault is skipped as a duplicate. Flushed + * before claiming a slot so the claim can't overwrite one of them. */ + cl_flush_pending(GetCurrentThreadId(), exAddr, 0); + s = cl_claim_slot(); + if (s) { + s->len = cl_format(s->text, CL_SLOT_BYTES, ep, "UNHANDLED EXCEPTION (fatal)"); + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } + t_inLogger = 0; + } + + if (g_prevFilter) { + verdict = g_prevFilter(ep); + } + t_inUef = 0; + return verdict; +} + +/* DllMain (process exit): write deferred AVs from the last CL_EXIT_FLUSH_WINDOW_MS. */ +static void CrashLoggerFlushOnExit(void) +{ + if (g_crashLogPath[0] == 0) { return; } + cl_flush_pending(0, 0, CL_EXIT_FLUSH_WINDOW_MS); +} + +/* Installs the VEH once and (re-)asserts the unhandled-exception filter. + * logPath = wide path to the dedicated crash log. Safe to call more than once: + * a later call re-installs the filter if AC or a runtime replaced it. */ __declspec(dllexport) void __cdecl RC_InstallCrashLogger(const wchar_t* logPath) { - if (g_vehHandle) { return; } + LPTOP_LEVEL_EXCEPTION_FILTER prev; if (logPath) { int i = 0; for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } g_crashLogPath[i] = 0; } - g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + if (!g_vehHandle) { + g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + } + prev = SetUnhandledExceptionFilter(CrashUef); + if (prev != CrashUef) { + g_prevFilter = prev; + } } /* ── Tagged-text parser guard (native MinHook detour body) ──────────────── diff --git a/src/RynthCore.App.Avalonia/App.axaml.cs b/src/RynthCore.App.Avalonia/App.axaml.cs index 150a5b9..d0fa2db 100644 --- a/src/RynthCore.App.Avalonia/App.axaml.cs +++ b/src/RynthCore.App.Avalonia/App.axaml.cs @@ -1,6 +1,8 @@ +using System; using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; +using RynthCore; namespace RynthCore.App.Avalonia; @@ -13,6 +15,18 @@ public partial class App : Application public override void OnFrameworkInitializationCompleted() { + try + { + string t = DateTime.Now.ToString("O"); + DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, + $"[{t}] [pid:{Environment.ProcessId}] RynthCore.App.Avalonia started (launcher)."); + // Detailed host + sidecar file layout (see LauncherHostDiagnostics) for runtime mis-detection triage. + LauncherHostDiagnostics.AppendDesktopLogBlock(t); + } + catch + { + } + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.MainWindow = new MainWindow(); diff --git a/src/RynthCore.App.Avalonia/EngineJsonStore.cs b/src/RynthCore.App.Avalonia/EngineJsonStore.cs index 69c07d2..2254a4e 100644 --- a/src/RynthCore.App.Avalonia/EngineJsonStore.cs +++ b/src/RynthCore.App.Avalonia/EngineJsonStore.cs @@ -120,4 +120,19 @@ internal static class EngineJsonStore fields[field] = doc.RootElement.Clone(); Write(fields); } + + /// + /// Sets a single string field (e.g. "LoggingLevel"), preserving every other field. + /// + public static void SetString(string field, string value) + { + Dictionary fields = Read(); + + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + w.WriteStringValue(value); + using var doc = JsonDocument.Parse(ms.ToArray()); + fields[field] = doc.RootElement.Clone(); + Write(fields); + } } diff --git a/src/RynthCore.App.Avalonia/InstallerHandoff.cs b/src/RynthCore.App.Avalonia/InstallerHandoff.cs new file mode 100644 index 0000000..01f64c9 --- /dev/null +++ b/src/RynthCore.App.Avalonia/InstallerHandoff.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.InteropServices; +using RynthCore.Install; + +namespace RynthCore.App.Avalonia; + +/// +/// One-shot values the installer leaves under Software\Rynth for the launcher +/// (e.g. PendingPluginRegistration). Kept out of the shared, read-only +/// , which must stay byte-identical with RynthSuite's copy. +/// +internal static class InstallerHandoff +{ + /// A string value from Software\Rynth: HKCU first, then HKLM (32-bit view); null when absent. + public static string? ReadSetting(string valueName) + => SystemInstallSettings.Instance.CurrentUser(valueName) + ?? SystemInstallSettings.Instance.LocalMachine(valueName); + + /// Deletes a value from HKCU Software\Rynth once it has been acted on. Best effort. + public static void DeleteUserSetting(string valueName) + { + try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RynthInstallPaths.RegistryKey, valueName); } catch { } + } + + private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001)); + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName); +} diff --git a/src/RynthCore.App.Avalonia/LauncherDiag.cs b/src/RynthCore.App.Avalonia/LauncherDiag.cs index 22c3070..4056c79 100644 --- a/src/RynthCore.App.Avalonia/LauncherDiag.cs +++ b/src/RynthCore.App.Avalonia/LauncherDiag.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Text; using System.Threading; +using RynthCore.Install; namespace RynthCore.App.Avalonia; diff --git a/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs b/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs new file mode 100644 index 0000000..4b1eed3 --- /dev/null +++ b/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs @@ -0,0 +1,110 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore; + +namespace RynthCore.App.Avalonia; + +/// +/// One-shot host metadata for the Avalonia launcher: helps confirm the renamed apphost +/// (RynthCore.exe) sits next to matching .runtimeconfig.json / .deps.json after installer staging. +/// +internal static class LauncherHostDiagnostics +{ + /// Single line for the in-window activity feed (short). + internal static string BuildActivitySummaryLine() + { + string exe = TryGetHostExePath(); + string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory; + HostSidecars side = DescribeSidecars(dir); + // x64 FDD tool prereq: same registry keys as installer/RynthCore.iss (see NetDesktopX64Prerequisite). + string suiteTools = NetDesktopX64Prerequisite.IsSatisfied() + ? "x64 suite tools: .NET 10+ OK (registry, same as setup)" + : "x64 suite tools: .NET 10+ not found — install x64 runtime from " + NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl; + if (!Environment.Is64BitOperatingSystem) + suiteTools = "x64 suite tools: n/a on 32-bit OS (same as setup)"; + + return + $"Host: {RuntimeInformation.FrameworkDescription}, arch={RuntimeInformation.ProcessArchitecture}, " + + $"runtimeconfig={(side.RenamedRuntimeConfig ? "RynthCore" : side.LegacyRuntimeConfig ? "App.Avalonia (mismatch?)" : "missing")}, " + + $"deps={(side.RenamedDeps ? "RynthCore" : side.LegacyDeps ? "App.Avalonia (mismatch?)" : "missing")}; {suiteTools}"; + } + + /// Writes a detailed block to the desktop rolling launcher log. + internal static void AppendDesktopLogBlock(string timestampIso) + { + try + { + string exe = TryGetHostExePath(); + string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory; + HostSidecars side = DescribeSidecars(dir); + + var sb = new StringBuilder(512); + sb.Append('[').Append(timestampIso).Append("] [pid:").Append(Environment.ProcessId).AppendLine("] Launcher host resolution:"); + sb.Append(" ProcessPath: ").AppendLine(exe); + sb.Append(" BaseDirectory: ").AppendLine(AppContext.BaseDirectory); + sb.Append(" Framework: ").AppendLine(RuntimeInformation.FrameworkDescription); + sb.Append(" OSDescription: ").AppendLine(RuntimeInformation.OSDescription); + sb.Append(" ProcessArchitecture: ").AppendLine(RuntimeInformation.ProcessArchitecture.ToString()); + sb.Append(" CLR: ").AppendLine(Environment.Version.ToString()); + sb.Append(" RynthCore.runtimeconfig.json: ").AppendLine(side.RenamedRuntimeConfig ? "present" : "absent"); + sb.Append(" RynthCore.App.Avalonia.runtimeconfig.json: ").AppendLine(side.LegacyRuntimeConfig ? "present (unexpected if exe is RynthCore.exe)" : "absent"); + sb.Append(" RynthCore.deps.json: ").AppendLine(side.RenamedDeps ? "present" : "absent"); + sb.Append(" RynthCore.App.Avalonia.deps.json: ").AppendLine(side.LegacyDeps ? "present (unexpected if exe is RynthCore.exe)" : "absent"); + // Loot/Monster editors are x64 FDD: probe matches RynthCore.iss prerequisite page (64-bit registry view). + sb.Append(" x64 FDD tool runtime (Loot/Monster, same checks as installer): ") + .AppendLine(NetDesktopX64Prerequisite.IsSatisfied() ? "present" : "not detected") + .Append(" .NET 10+ x64 download hub: ") + .AppendLine(NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl); + + DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, sb.ToString()); + } + catch + { + // Logging must never prevent startup. + } + } + + private static string TryGetHostExePath() + { + try + { + // Prefer the actual apphost path (works for published rename to RynthCore.exe). + string? p = Environment.ProcessPath; + if (!string.IsNullOrWhiteSpace(p)) + return p; + } + catch + { + // ignore + } + + try + { + return typeof(App).Assembly.Location; + } + catch + { + return string.Empty; + } + } + + private static HostSidecars DescribeSidecars(string directory) + { + if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) + return new HostSidecars(false, false, false, false); + + bool renamedRc = File.Exists(Path.Combine(directory, "RynthCore.runtimeconfig.json")); + bool legacyRc = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.runtimeconfig.json")); + bool renamedDeps = File.Exists(Path.Combine(directory, "RynthCore.deps.json")); + bool legacyDeps = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.deps.json")); + return new HostSidecars(renamedRc, legacyRc, renamedDeps, legacyDeps); + } + + private readonly record struct HostSidecars( + bool RenamedRuntimeConfig, + bool LegacyRuntimeConfig, + bool RenamedDeps, + bool LegacyDeps); +} diff --git a/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs b/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs new file mode 100644 index 0000000..eb3b801 --- /dev/null +++ b/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; +using RynthCore.Install; + +namespace RynthCore.App.Avalonia; + +/// +/// Launcher-side access to every live logging switch: +/// +/// Engine: engine.json "LoggingLevel" (global threshold) and "LogCategories" (per-category emit +/// level). The engine polls engine.json once a second, so edits apply to running clients. +/// RynthAi: Logs\Diagnostics\diagnostics.json "Categories" and "Events" (Off / Trace / Info). +/// RynthAi polls it every couple of seconds and rewrites it with the full catalog on load. +/// +/// +internal static class LoggingSettingsStore +{ + /// One engine log category as shown in the launcher. + internal readonly record struct EngineCategory(string Name, string DefaultLevel, string Description); + + /// One RynthAi category / event row read from diagnostics.json. + internal sealed record DiagnosticsRow(string Key, string Level, string Description); + + /// Global level choices (engine.json "LoggingLevel"), most to least quiet. + internal static readonly string[] GlobalLevels = { "Off", "Error", "Warning", "Info", "Debug", "Trace" }; + + /// Engine category emit levels. Info = normal log; Debug/Trace show only at that global level. + internal static readonly string[] EngineCategoryLevels = { "Off", "Trace", "Debug", "Info" }; + + /// RynthAi category / event levels: Off, Trace (trace file only), Info (also the normal log). + internal static readonly string[] RynthAiLevels = { "Off", "Trace", "Info" }; + + /// Must match RynthCore.Engine.LogCategory names and LogSettings defaults. + internal static readonly EngineCategory[] EngineCategories = + { + new("General", "Info", "Uncategorised engine lines."), + new("D3D9", "Info", "D3D9 hook, EndScene, bootstrapper, matrix capture, nav markers."), + new("Compat", "Info", "Client hooks: objects, combat, movement, vitals, chat."), + new("Render", "Off", "ImGui rendering and Win32 input (very chatty)."), + new("Plugin", "Info", "Plugin loader/manager and every plugin host Log line."), + new("UI", "Info", "Avalonia overlay and panels."), + new("Verbose", "Debug", "Detail lines across all subsystems (Info = always in the normal log)."), + }; + + private const string EngineCategoriesProperty = "LogCategories"; + + /// RynthAi's diagnostics.json (created by RynthAi on its first load). + internal static string DiagnosticsPath => + Path.Combine(RynthInstallPaths.RynthAiDir, "Logs", "Diagnostics", "diagnostics.json"); + + // ── Engine ────────────────────────────────────────────────────────── + + /// Current engine category levels; categories missing from engine.json get their defaults. + internal static Dictionary ReadEngineCategoryLevels() + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (EngineCategory c in EngineCategories) result[c.Name] = c.DefaultLevel; + + Dictionary fields = EngineJsonStore.Read(); + if (fields.TryGetValue(EngineCategoriesProperty, out JsonElement cats) && cats.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty p in cats.EnumerateObject()) + { + if (p.Value.ValueKind == JsonValueKind.String && result.ContainsKey(p.Name)) + result[p.Name] = p.Value.GetString() ?? result[p.Name]; + } + } + return result; + } + + /// Sets one engine category level in engine.json, preserving every other field. + internal static void SetEngineCategoryLevel(string category, string level) + { + Dictionary levels = ReadEngineCategoryLevels(); + levels[category] = level; + + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + foreach (EngineCategory c in EngineCategories) + w.WriteString(c.Name, levels[c.Name]); + w.WriteEndObject(); + } + + Dictionary fields = EngineJsonStore.Read(); + using var doc = JsonDocument.Parse(ms.ToArray()); + fields[EngineCategoriesProperty] = doc.RootElement.Clone(); + EngineJsonStore.Write(fields); + } + + // ── RynthAi ───────────────────────────────────────────────────────── + + /// + /// Reads RynthAi's category and event rows. Returns false (with empty lists) when diagnostics.json + /// does not exist yet or cannot be parsed (e.g. RynthAi is mid-write; retry later). + /// + internal static bool TryReadRynthAi(out List categories, out List events, out string? error) + { + categories = new List(); + events = new List(); + error = null; + try + { + if (!File.Exists(DiagnosticsPath)) + { + error = "diagnostics.json not found - start RynthAi once to create it."; + return false; + } + if (JsonNode.Parse(File.ReadAllText(DiagnosticsPath)) is not JsonObject root) + { + error = "diagnostics.json is not a JSON object."; + return false; + } + ReadRows(root["Categories"] as JsonArray, "Name", categories); + ReadRows(root["Events"] as JsonArray, "Key", events); + if (categories.Count == 0) + error = "diagnostics.json has no category list - update RynthAi to 0.6.18 or later."; + return true; + } + catch (Exception ex) + { + error = $"diagnostics.json unreadable ({ex.GetType().Name}: {ex.Message})."; + return false; + } + } + + /// Sets a RynthAi category level ("Off", "Trace", "Info") and keeps "Traces" in sync. + internal static void SetRynthAiCategoryLevel(string category, string level) + => UpdateDiagnostics("Categories", "Name", category, level); + + /// Sets a RynthAi key-event level ("Off", "Trace", "Info"). + internal static void SetRynthAiEventLevel(string eventKey, string level) + => UpdateDiagnostics("Events", "Key", eventKey, level); + + private static void ReadRows(JsonArray? array, string keyField, List into) + { + if (array == null) return; + foreach (JsonNode? node in array) + { + if (node is not JsonObject o) continue; + string key = o[keyField]?.GetValue() ?? string.Empty; + if (key.Length == 0) continue; + into.Add(new DiagnosticsRow( + key, + o["Level"]?.GetValue() ?? "Off", + o["Description"]?.GetValue() ?? string.Empty)); + } + } + + /// Read-modify-write of one row's Level; every other field in the file is preserved. + private static void UpdateDiagnostics(string section, string keyField, string key, string level) + { + string path = DiagnosticsPath; + if (JsonNode.Parse(File.ReadAllText(path)) is not JsonObject root) + throw new InvalidDataException("diagnostics.json is not a JSON object."); + if (root[section] is not JsonArray rows) + throw new InvalidDataException($"diagnostics.json has no \"{section}\" list."); + + bool found = false; + foreach (JsonNode? node in rows) + { + if (node is JsonObject o && string.Equals(o[keyField]?.GetValue(), key, StringComparison.OrdinalIgnoreCase)) + { + o["Level"] = level; + found = true; + } + } + if (!found) + throw new KeyNotFoundException($"\"{key}\" is not in diagnostics.json {section}."); + + // RynthAi reads Categories when present, but older readers (and /ra trace status) use Traces. + if (section == "Categories") + { + var traces = new JsonArray(); + foreach (JsonNode? node in rows) + { + if (node is JsonObject o && !string.Equals(o["Level"]?.GetValue(), "Off", StringComparison.OrdinalIgnoreCase)) + traces.Add(o["Name"]?.GetValue()); + } + root["Traces"] = traces; + } + + // Atomic swap so RynthAi's poll never reads a half-written file. + string tmp = path + ".tmp"; + File.WriteAllText(tmp, root.ToJsonString(new JsonSerializerOptions { WriteIndented = false })); + File.Move(tmp, path, overwrite: true); + } +} diff --git a/src/RynthCore.App.Avalonia/MainWindow.Logging.cs b/src/RynthCore.App.Avalonia/MainWindow.Logging.cs new file mode 100644 index 0000000..90abc2c --- /dev/null +++ b/src/RynthCore.App.Avalonia/MainWindow.Logging.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; + +namespace RynthCore.App.Avalonia; + +/// +/// Runtime tab → Logging card and the live global Logging level box. Every change is written +/// straight to engine.json / diagnostics.json (see ); running +/// clients poll those files, so nothing needs a restart or the Save button. +/// +internal partial class MainWindow +{ + private static readonly IBrush LogNameBrush = new SolidColorBrush(Color.Parse("#EAF0F4")); + private static readonly IBrush LogMutedBrush = new SolidColorBrush(Color.Parse("#9AA8B3")); + + // Set while the rows are being (re)built so programmatic selections don't write files. + private bool _suppressLoggingEvents; + + /// Wires the Logging card and the live global level box. Called once after LoadRuntimeControls. + private void InitLoggingControls() + { + LoggingLevelComboBox.SelectionChanged += (_, _) => OnGlobalLoggingLevelChanged(); + ReloadLoggingButton.Click += (_, _) => BuildLoggingRows(); + BuildLoggingRows(); + } + + /// Global level changed: persist to the launcher settings and push to engine.json now. + private void OnGlobalLoggingLevelChanged() + { + if (_suppressLoggingEvents) return; + string level = GetSelectedLoggingLevel(); + if (string.Equals(level, _settings.LoggingLevel, StringComparison.OrdinalIgnoreCase)) return; + try + { + _settings.LoggingLevel = level; + SaveSettings(); + EngineJsonStore.SetString("LoggingLevel", level); + AppendActivity($"Logging level set to {level} (applied live to running clients)."); + } + catch (Exception ex) + { + AppendActivity($"Failed to save logging level: {ex.Message}"); + } + } + + /// (Re)builds the engine category, RynthAi category and RynthAi event rows from disk. + private void BuildLoggingRows() + { + _suppressLoggingEvents = true; + try + { + EngineLogCategoriesPanel.Children.Clear(); + Dictionary engineLevels = LoggingSettingsStore.ReadEngineCategoryLevels(); + foreach (LoggingSettingsStore.EngineCategory cat in LoggingSettingsStore.EngineCategories) + { + string name = cat.Name; + EngineLogCategoriesPanel.Children.Add(BuildLoggingRow( + name, cat.Description, LoggingSettingsStore.EngineCategoryLevels, engineLevels[name], + level => + { + LoggingSettingsStore.SetEngineCategoryLevel(name, level); + AppendActivity($"Engine log category {name} set to {level} (applied live)."); + })); + } + + RynthAiLogCategoriesPanel.Children.Clear(); + RynthAiLogEventsPanel.Children.Clear(); + bool ok = LoggingSettingsStore.TryReadRynthAi( + out List categories, + out List events, + out string? error); + + foreach (LoggingSettingsStore.DiagnosticsRow row in categories) + { + string key = row.Key; + RynthAiLogCategoriesPanel.Children.Add(BuildLoggingRow( + key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level, + level => + { + LoggingSettingsStore.SetRynthAiCategoryLevel(key, level); + AppendActivity($"RynthAi log category {key} set to {level} (applied live)."); + })); + } + foreach (LoggingSettingsStore.DiagnosticsRow row in events) + { + string key = row.Key; + RynthAiLogEventsPanel.Children.Add(BuildLoggingRow( + key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level, + level => + { + LoggingSettingsStore.SetRynthAiEventLevel(key, level); + AppendActivity($"RynthAi log event {key} set to {level} (applied live)."); + })); + } + + LoggingStatusText.Text = ok && error == null + ? $"engine.json: {EngineJsonStore.Path}\ndiagnostics.json: {LoggingSettingsStore.DiagnosticsPath}" + : $"RynthAi: {error}"; + } + catch (Exception ex) + { + LoggingStatusText.Text = $"Failed to load logging settings: {ex.Message}"; + } + finally + { + _suppressLoggingEvents = false; + } + } + + /// One "Name | level box | description" row. runs on user changes only. + private Control BuildLoggingRow(string name, string description, string[] levels, string current, Action apply) + { + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("170,110,*") }; + + grid.Children.Add(new TextBlock + { + Text = name, + Foreground = LogNameBrush, + VerticalAlignment = VerticalAlignment.Center, + }); + + var combo = new ComboBox { ItemsSource = levels, MinWidth = 100, Margin = new global::Avalonia.Thickness(0, 0, 8, 0) }; + int index = Array.FindIndex(levels, l => string.Equals(l, current, StringComparison.OrdinalIgnoreCase)); + combo.SelectedIndex = index >= 0 ? index : 0; + combo.SelectionChanged += (_, _) => + { + if (_suppressLoggingEvents || combo.SelectedItem is not string level) return; + try { apply(level); } + catch (Exception ex) + { + AppendActivity($"Failed to set {name} to {level}: {ex.Message}"); + // Show what is actually on disk; posted so the combo raising this event isn't torn down mid-handler. + global::Avalonia.Threading.Dispatcher.UIThread.Post(BuildLoggingRows); + } + }; + Grid.SetColumn(combo, 1); + grid.Children.Add(combo); + + var desc = new TextBlock + { + Text = description, + Foreground = LogMutedBrush, + TextWrapping = TextWrapping.Wrap, + VerticalAlignment = VerticalAlignment.Center, + }; + Grid.SetColumn(desc, 2); + grid.Children.Add(desc); + return grid; + } +} diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index ce8c9d1..6c67966 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -366,7 +366,17 @@ - + + + + + + + + + + @@ -409,6 +419,42 @@ + + + + + +