From 9709a39e63b8b7dd7463e256e8b8566e01482000 Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Mon, 5 Oct 2026 16:42:54 -0400 Subject: [PATCH] feat(engine): install-aware paths, logging levels and item drag bridge - RynthInstallPaths: logs, AcClient, RynthSuite data and imgui.ini resolve from the installer-chosen folders instead of hard-coded C:\Games paths (engine, injector, loader, launcher, StatusAgent). - Logging levels: engine.json "LoggingLevel" plus per-category levels (LogSettings), edited live from the launcher's Logging tab; RynthLog category methods write through them. Errors are always written. - RynthCore.DesktopLog: shared rolling log + .NET desktop prerequisite check for the launcher and agents. - Item drag bridge: an AC inventory item dragged onto an ImGui window is handed to the window instead of dropping on the ground (DragDropHooks, ItemDragBridge, Win32Backend input routing); ImGui gets the mouse over Avalonia panels while it wants it. No plugin API changes. Co-authored-by: Cursor --- RynthCore.sln | 15 ++ src/RynthCore.App.Avalonia/App.axaml.cs | 14 + src/RynthCore.App.Avalonia/EngineJsonStore.cs | 15 ++ src/RynthCore.App.Avalonia/LauncherDiag.cs | 4 +- .../LauncherHostDiagnostics.cs | 110 ++++++++ .../LoggingSettingsStore.cs | 192 ++++++++++++++ .../MainWindow.Logging.cs | 153 +++++++++++ src/RynthCore.App.Avalonia/MainWindow.axaml | 50 +++- .../MainWindow.axaml.cs | 152 ++++++++++- .../RynthCore.App.Avalonia.csproj | 19 ++ src/RynthCore.App/AppSettings.cs | 10 + src/RynthCore.App/RynthInstallPaths.cs | 128 +++++++++ src/RynthCore.DesktopLog/DesktopRollingLog.cs | 130 +++++++++ .../NetDesktopX64Prerequisite.cs | 105 ++++++++ .../RynthCore.DesktopLog.csproj | 10 + .../Compatibility/DragDropHooks.cs | 110 ++++++++ src/RynthCore.Engine/EntryPoint.cs | 112 ++++++-- src/RynthCore.Engine/ImGui/ItemDragBridge.cs | 251 ++++++++++++++++++ src/RynthCore.Engine/ImGui/Win32Backend.cs | 25 +- src/RynthCore.Engine/LogPaths.cs | 4 +- src/RynthCore.Engine/LogSettings.cs | 245 +++++++++++++++++ .../Plugins/EngineSettings.cs | 76 ++++++ src/RynthCore.Engine/RynthCore.Engine.csproj | 10 + src/RynthCore.Engine/RynthLog.cs | 88 +++--- src/RynthCore.Engine/UI/Data/MetaData.cs | 3 +- src/RynthCore.Injector/LaunchCommand.cs | 3 +- src/RynthCore.Injector/Program.cs | 4 +- .../RynthCore.Injector.csproj | 2 + src/RynthCore.Loader/EntryPoint.cs | 4 +- src/RynthCore.Loader/RynthCore.Loader.csproj | 5 + src/RynthCore.StatusAgent/AgentConfig.cs | 9 +- .../RynthCore.StatusAgent.csproj | 5 + 32 files changed, 1977 insertions(+), 86 deletions(-) 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.App/RynthInstallPaths.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/ImGui/ItemDragBridge.cs create mode 100644 src/RynthCore.Engine/LogSettings.cs 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/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/LauncherDiag.cs b/src/RynthCore.App.Avalonia/LauncherDiag.cs index a73faf0..494e6d3 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; @@ -18,7 +19,8 @@ namespace RynthCore.App.Avalonia; /// internal static class LauncherDiag { - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore). + private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir; private const string UnifiedLogFileName = "RynthCore.log"; private static readonly object LogLock = new(); 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 4176226..31ba128 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -366,7 +366,17 @@ - + + + + + + + + + + @@ -409,6 +419,42 @@ + + + + + +