From f2d7f0464ccdf0dd1284f7b31ef1768f36ebd4bc Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:22:56 -0800 Subject: [PATCH 01/12] Sections manifest: parse chatTabs (server default chat tabs) Co-Authored-By: Claude Opus 5.5 --- .../UI/Sections/SectionManifest.cs | 67 +++++++++++++++++++ tools/SectionsTests/Program.cs | 53 +++++++++++++++ 2 files changed, 120 insertions(+) diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs index 08f5de2..95942d5 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -61,6 +61,17 @@ // command, or with a duplicate id, is dropped; at most MaxBarMenuItems (6) // are kept, and a "barMenu" that is not an array is ignored (the window is // kept). Engines before v95 ignore the key. +// chatTabs (2026-11-15) default RynthChat tabs a server's plugin declares: +// [ { "server": "dreamweave", "id": "dereth-network", "name": "Network", +// "pinned": true, "globalRoomFallback": "Roleplay", +// "rules": [ { "action": "copy", "when": "type:3", "mode": "", +// "pattern": "...", "globalRoom": false } ] } ]. +// "server" and "id" are ids (the owner key is "server/id"); "action" is copy +// or move; "globalRoomFallback" is General, Trade, LFG or Roleplay (the +// room a "globalRoom": true rule matches until chat shows another). An +// entry with a bad field is dropped and reported in the parse error (the +// other keys still parse); at most MaxChatTabs entries of MaxChatRules +// rules each. Engines before this ignore the key. // // Everything from a plugin is checked here: ids are short lower-case words, // text is capped, a command must be a single "/..." chat command, and the lists @@ -145,6 +156,12 @@ internal sealed record SectionWindowDecl( public SectionBarMenuItem[] Menu => BarMenu ?? System.Array.Empty(); } +/// One rule of a plugin-declared chat tab ("chatTabs"); a GlobalRoom rule's pattern follows the room discovered from chat. +internal sealed record SectionChatRuleDecl(string Action, string When, string Mode, string Pattern, bool GlobalRoom); + +/// A default chat tab a server's plugin declares ("chatTabs", 2026-11-15); owner key = Server + "/" + Id. +internal sealed record SectionChatTabDecl(string Server, string Id, string Name, bool Pinned, string GlobalRoomFallback, SectionChatRuleDecl[] Rules); + /// One plugin's parsed manifest. internal sealed record SectionManifest( string Plugin, @@ -157,6 +174,9 @@ internal sealed record SectionManifest( /// The windows the plugin draws (plugin API v89 engines host them; older ones ignore the key). public SectionWindowDecl[] Windows { get; init; } = Array.Empty(); + + /// The default chat tabs the plugin declares for its server (2026-11-15; older engines ignore the key). + public SectionChatTabDecl[] ChatTabs { get; init; } = Array.Empty(); } internal static class SectionManifestParser @@ -178,6 +198,9 @@ internal static class SectionManifestParser public const int MaxWindowTitleLength = 32; /// Most items kept in one window's bar-icon dropdown (v95). public const int MaxBarMenuItems = 6; + /// Most chat tab entries kept per manifest, and rules per entry (2026-11-15). + public const int MaxChatTabs = 8; + public const int MaxChatRules = 16; public const float DefaultWindowWidth = 420f, DefaultWindowHeight = 300f, MinWindowSize = 120f, MaxWindowSize = 2000f; /// @@ -278,9 +301,20 @@ internal static class SectionManifestParser BarMenu: barMenu.Count > 0 ? barMenu.ToArray() : null)); } + var chatTabs = new List(); + foreach (JsonElement e in Array(root, "chatTabs")) + { + if (chatTabs.Count >= MaxChatTabs) { Note(ref error, $"chatTabs: more than {MaxChatTabs} entries, the rest dropped"); break; } + SectionChatTabDecl? decl = ChatTab(e, out string why); + if (decl == null) { Note(ref error, "chatTabs: entry dropped, " + why); continue; } + if (chatTabs.Exists(c => c.Server == decl.Server && c.Id == decl.Id)) { Note(ref error, "chatTabs: duplicate " + decl.Server + "/" + decl.Id); continue; } + chatTabs.Add(decl); + } + return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray()) { Windows = windows.ToArray(), + ChatTabs = chatTabs.ToArray(), }; } catch (JsonException ex) @@ -290,6 +324,39 @@ internal static class SectionManifestParser } } + /// Keeps the first note; a dropped chatTabs entry is reported without discarding the rest of the manifest. + private static void Note(ref string error, string note) + { + if (error.Length == 0) error = note; + } + + /// One chatTabs entry, or null (with the reason) when a field is bad. + private static SectionChatTabDecl? ChatTab(JsonElement e, out string why) + { + why = string.Empty; + string server = Id(Str(e, "server")); + if (server.Length == 0) { why = "missing or bad server"; return null; } + string id = Id(Str(e, "id")); + if (id.Length == 0) { why = "missing or bad id"; return null; } + string name = Text(Str(e, "name"), MaxLabelLength); + if (name.Length == 0) { why = "missing name"; return null; } + string fallback = Str(e, "globalRoomFallback").Trim(); + string room = fallback.Length == 0 ? "General" : GlobalRooms.FirstOrDefault(r => r.Equals(fallback, StringComparison.OrdinalIgnoreCase)) ?? string.Empty; + if (room.Length == 0) { why = "globalRoomFallback is not General, Trade, LFG or Roleplay"; return null; } + var rules = new List(); + foreach (JsonElement r in Array(e, "rules")) + { + if (rules.Count >= MaxChatRules) { why = $"more than {MaxChatRules} rules"; return null; } + string action = Str(r, "action").Trim().ToLowerInvariant(); + if (action is not ("copy" or "move")) { why = "rule action is not copy or move"; return null; } + rules.Add(new SectionChatRuleDecl(action, Text(Str(r, "when"), MaxLabelLength), Text(Str(r, "mode"), MaxLabelLength), + Text(Str(r, "pattern"), MaxTextLength), Bool(r, "globalRoom", false))); + } + return new SectionChatTabDecl(server, id, name, Bool(e, "pinned", false), room, rules.ToArray()); + } + + private static readonly string[] GlobalRooms = { "General", "Trade", "LFG", "Roleplay" }; + // ── Field rules ───────────────────────────────────────────────────── /// A lower-case id of letters, digits, '-' and '_' (at most MaxIdLength), else "". diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index bfdeb98..0d66f61 100644 --- a/tools/SectionsTests/Program.cs +++ b/tools/SectionsTests/Program.cs @@ -34,6 +34,7 @@ internal static class Program WindowTakeOver(); WindowFrameless(); ManifestBarMenu(); + ManifestChatTabs(); BarMenuHoverTiming(); BarMenuReload(); StackCheckAfterPluginDraw(); @@ -594,6 +595,58 @@ internal static class Program "{ \"version\": 1, \"windows\": [ { \"id\": \"server\", \"title\": \"DreamWeave\", \"surface\": \"window:server\", \"bar\": true" + windowExtra + " } ] }"; + private static void ManifestChatTabs() + { + Case("manifest: chatTabs (2026-11-15)"); + const string good = """ + { "chatTabs": [ { "server": "dreamweave", "id": "dereth-network", "name": "Network", "pinned": true, + "globalRoomFallback": "Roleplay", + "rules": [ { "action": "copy", "when": "type:3", "mode": "", "pattern": "^x", "globalRoom": false }, + { "action": "copy", "when": "", "mode": "startswith", "pattern": "", "globalRoom": true } ] } ] } + """; + SectionManifest m = SectionManifestParser.Parse("DW", good, out string err); + Check(err.Length == 0 && m.ChatTabs.Length == 1, "one entry parses: " + err); + SectionChatTabDecl t = m.ChatTabs[0]; + Check(t.Server == "dreamweave" && t.Id == "dereth-network" && t.Name == "Network" && t.Pinned && t.GlobalRoomFallback == "Roleplay", + "entry fields"); + Check(t.Rules.Length == 2 && t.Rules[1].GlobalRoom && t.Rules[1].Pattern == "", "rules: global-room rule with an empty pattern"); + Check(t.Rules[0].Action == "copy" && t.Rules[0].When == "type:3" && t.Rules[0].Pattern == "^x" && !t.Rules[0].GlobalRoom, "rule 0 fields"); + + Check(SectionManifestParser.Parse("DW", """{ "contributions": [] }""", out _).ChatTabs.Length == 0, "no chatTabs key = empty array"); + + // Each reject drops the entry, reports it in error, and still parses the other keys. + string section = """ "sections": [ { "id": "quests", "label": "Quests", "order": 150 } ] """; + string[] bad = + { + """{ "id": "a", "name": "A", "globalRoomFallback": "General", "rules": [] }""", + """{ "server": "dw", "name": "A", "globalRoomFallback": "General", "rules": [] }""", + """{ "server": "dw", "id": "Bad Id", "name": "A", "globalRoomFallback": "General", "rules": [] }""", + """{ "server": "dw", "id": "a", "name": "A", "globalRoomFallback": "General", "rules": [ { "action": "delete", "when": "", "mode": "", "pattern": "x" } ] }""", + """{ "server": "dw", "id": "a", "name": "A", "globalRoomFallback": "Sports", "rules": [] }""", + }; + string[] why = { "missing server", "missing id", "bad id", "bad action", "bad fallback" }; + for (int i = 0; i < bad.Length; i++) + { + m = SectionManifestParser.Parse("DW", "{ " + section + ", \"chatTabs\": [" + bad[i] + "] }", out err); + Check(m.ChatTabs.Length == 0 && err.Length > 0 && m.Sections.Length == 1, "dropped, error set, other keys kept: " + why[i]); + } + + var entries = new System.Text.StringBuilder(); + for (int i = 0; i < 9; i++) + entries.Append(i > 0 ? "," : "").Append($"{{ \"server\": \"dw\", \"id\": \"t{i}\", \"name\": \"T{i}\", \"globalRoomFallback\": \"General\", \"rules\": [] }}"); + m = SectionManifestParser.Parse("DW", "{ \"chatTabs\": [" + entries + "] }", out err); + Check(m.ChatTabs.Length == SectionManifestParser.MaxChatTabs && SectionManifestParser.MaxChatTabs == 8 && err.Length > 0, + "more than 8 entries: the cap holds and error is set: " + m.ChatTabs.Length); + + var rules = new System.Text.StringBuilder(); + for (int i = 0; i < 17; i++) + rules.Append(i > 0 ? "," : "").Append($"{{ \"action\": \"copy\", \"when\": \"\", \"mode\": \"\", \"pattern\": \"r{i}\" }}"); + m = SectionManifestParser.Parse("DW", "{ " + section + ", \"chatTabs\": [ { \"server\": \"dw\", \"id\": \"a\", \"name\": \"A\", \"globalRoomFallback\": \"General\", \"rules\": [" + + rules + "] } ] }", out err); + Check(SectionManifestParser.MaxChatRules == 16 && m.ChatTabs.Length == 0 && err.Length > 0 && m.Sections.Length == 1, + "17 rules: entry dropped, error set"); + } + private static void ManifestBarMenu() { Case("plugin windows: barMenu (v95)"); -- 2.43.0 From 626cc9dfc33215f83608b394b292a5baf55daf61 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:23:24 -0800 Subject: [PATCH 02/12] RynthChat settings: server tab, owner, pinned fields Co-Authored-By: Claude Opus 5.5 --- .../UI/Data/ChatSettingsDto.cs | 16 +++++++++ tools/ChatFilterTests/Program.cs | 35 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs index d3dfbf9..49d42d8 100644 --- a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs @@ -41,6 +41,13 @@ internal sealed class RynthChatFilterDto // 2026-10-05: /// "contains" | "startswith" | "endswith"; absent: a regex (ChatRuleMatching). [JsonPropertyName("mode")] public string? Mode { get; set; } + // 2026-11-15 (server default tabs, ChatServerTabs); each is absent on a player's own rule: + /// The server id whose plugin tab this rule belongs to; absent = every server. + [JsonPropertyName("server")] public string? Server { get; set; } + /// "<server>/<entry id>" of the plugin entry that owns this rule; absent = the player's rule. + [JsonPropertyName("owner")] public string? Owner { get; set; } + /// True on the rule whose pattern follows the room discovered from chat; absent = false. + [JsonPropertyName("globalRoom")] public bool? GlobalRoom { get; set; } } internal sealed class RynthChatSettingsDto @@ -71,6 +78,15 @@ internal sealed class RynthChatSettingsDto // 2026-10-20: the tabs in a row across the top instead of the channels drawer; absent while off. [JsonPropertyName("tabsAcross")] public bool? TabsAcross { get; set; } [JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; } + // 2026-11-15: server default tabs (ChatServerTabs) and pinned channels (ChatPins); each absent while unused. + /// Owner keys ("server/id") of the plugin tabs already seeded, so a deleted tab is not re-created. + [JsonPropertyName("seededTabs")] public string[]? SeededTabs { get; set; } + /// Tab name -> the server id whose plugin declared it; the tab shows only while that server is active. + [JsonPropertyName("tabServers")] public Dictionary? TabServers { get; set; } + /// Server id -> the Global room (General, Trade, LFG, Roleplay) last discovered from chat. + [JsonPropertyName("globalRooms")] public Dictionary? GlobalRooms { get; set; } + /// Tabs pinned to the main chat window's top bar, in pin order. + [JsonPropertyName("pinnedTabs")] public string[]? PinnedTabs { get; set; } [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } /// Standard filters' user state (RynthChatPresets); absent while none was changed. [JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; } diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 20cb2dd..12407ea 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -53,6 +53,7 @@ internal static class Program RetailRules(); RetailSetting(); TabsAcrossSetting(); + ServerTabSettingsRoundTrip(); SharedFileReload(); LineColorTags(); LineColorKinds(); @@ -1108,6 +1109,40 @@ internal static class Program Check(JsonSerializer.Deserialize(off, opts)!.Filters!.Length == 3, "the other fields are untouched"); } + private static void ServerTabSettingsRoundTrip() + { + Case("server tab settings: server, owner, globalRoom, seededTabs, tabServers, globalRooms, pinnedTabs (2026-11-15)"); + var opts = RynthChatJsonContext.Default.RynthChatSettingsDto; + var full = new RynthChatSettingsDto + { + SeededTabs = new[] { "dreamweave/dereth-network" }, + TabServers = new Dictionary { ["Network"] = "dreamweave" }, + GlobalRooms = new Dictionary { ["dreamweave"] = "Trade" }, + PinnedTabs = new[] { "Chat", "Network" }, + Filters = new[] + { + new RynthChatFilterDto { Pattern = "x", Tab = "Network", Server = "dreamweave", Owner = "dreamweave/dereth-network", GlobalRoom = true }, + }, + }; + RynthChatSettingsDto back = JsonSerializer.Deserialize(JsonSerializer.Serialize(full, opts), opts)!; + Check(back.SeededTabs != null && back.SeededTabs.Length == 1 && back.SeededTabs[0] == "dreamweave/dereth-network", "seededTabs round-trips"); + Check(back.TabServers != null && back.TabServers["Network"] == "dreamweave", "tabServers round-trips"); + Check(back.GlobalRooms != null && back.GlobalRooms["dreamweave"] == "Trade", "globalRooms round-trips"); + Check(back.PinnedTabs != null && back.PinnedTabs.SequenceEqual(new[] { "Chat", "Network" }), "pinnedTabs round-trips in order"); + RynthChatFilterDto r = back.Filters![0]; + Check(r.Server == "dreamweave" && r.Owner == "dreamweave/dereth-network" && r.GlobalRoom == true, "rule server, owner and globalRoom round-trip"); + + string plain = JsonSerializer.Serialize(new RynthChatSettingsDto { Filters = new[] { new RynthChatFilterDto { Pattern = "x", Tab = "Chat" } } }, opts); + Check(!plain.Contains("seededTabs", StringComparison.Ordinal) && !plain.Contains("pinnedTabs", StringComparison.Ordinal) + && !plain.Contains("\"owner\"", StringComparison.Ordinal), "a default DTO writes none of the new keys: " + plain); + Check(!plain.Contains("tabServers", StringComparison.Ordinal) && !plain.Contains("globalRooms", StringComparison.Ordinal) + && !plain.Contains("\"server\"", StringComparison.Ordinal) && !plain.Contains("globalRoom", StringComparison.Ordinal), "nor the rest"); + + RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!; + Check(old.SeededTabs == null && old.TabServers == null && old.GlobalRooms == null && old.PinnedTabs == null, "an old file has none of the settings fields"); + Check(old.Filters!.All(f => f.Server == null && f.Owner == null && f.GlobalRoom == null), "an old file's rules have none of the rule fields"); + } + private static void TabsAcrossSetting() { Case("tabs across the top: off (the drawer) unless a file says true"); -- 2.43.0 From 620e6b15072c280d60e72d4535b3456219336df5 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:25:02 -0800 Subject: [PATCH 03/12] RynthChat: server default tab planning and Global room discovery Co-Authored-By: Claude Opus 5.5 --- .../UI/Data/ChatServerTabs.cs | 96 +++++++++++++++++++ tools/ChatFilterTests/ChatFilterTests.csproj | 3 + tools/ChatFilterTests/Program.cs | 80 ++++++++++++++++ 3 files changed, 179 insertions(+) create mode 100644 src/RynthCore.Engine/UI/Data/ChatServerTabs.cs diff --git a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs new file mode 100644 index 0000000..b3b02b1 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -0,0 +1,96 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatServerTabs.cs +// Server default chat tabs (2026-11-15): what a server plugin's "chatTabs" +// manifest entry turns into in RynthChat's settings. Pure decisions only (no +// ChatModel, ImGui or SectionRegistry): ChatModel.ApplyServerTabs gathers the +// state, calls Plan, and applies the result; tools/ChatFilterTests compiles +// this file as is. +// +// An entry's rules are owned by it ("owner" = "/"), so a +// refresh rewrites only those rules and a renamed tab keeps them. A tab is +// seeded once (seededTabs); a tab the player deleted stays deleted, because +// deleting disables its rules and the seed mark remains. An older engine that +// rewrites the shared settings file strips the new fields: the seed then +// recognises its own rules by owner, or an existing tab of the same name, and +// adopts it instead of creating a second one. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using RynthCore.Engine.UI.Sections; + +namespace RynthCore.Engine.UI.Data; + +internal static class ChatServerTabs +{ + /// What Plan needs to know about the current settings. + internal sealed record SeedState(IReadOnlyCollection Seeded, IReadOnlyCollection ExistingTabs, IReadOnlyList OwnedRules); + + /// What to do: create/pin the tab, mark it seeded, and the full replacement set of this owner's rules. + internal sealed record SeedPlan(bool CreateTab, string TabName, bool Pin, bool MarkSeeded, RynthChatFilterDto[] Rules); + + // A remote speaker's room line: [Trade] Ann@coldeve says, "..." (optionally Ann@coldeve (Discord)). + // Anchored at the line start and the speaker may not contain a quote, so a tell or a say that merely + // quotes such a line does not match. + private static readonly Regex RoomLine = new( + "^\\[(General|Trade|LFG|Roleplay)\\] [^\"]+@[a-z0-9-]+( \\(discord\\))? says, \"", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.NonBacktracking); + + /// The owner key of an entry: "server/id". + internal static string OwnerKey(SectionChatTabDecl d) => d.Server + "/" + d.Id; + + /// The Global room a remote speaker's line names (canonical capitalisation), or null. + internal static string? DiscoverRoom(string text) + { + if (string.IsNullOrEmpty(text)) return null; + Match m = RoomLine.Match(text); + if (!m.Success) return null; + return m.Groups[1].Value.ToLowerInvariant() switch + { + "general" => "General", + "trade" => "Trade", + "lfg" => "LFG", + "roleplay" => "Roleplay", + _ => null, + }; + } + + /// The "startswith" pattern a Global-room rule uses for . + internal static string GlobalPattern(string room) => "[" + room + "] "; + + internal static SeedPlan Plan(SectionChatTabDecl d, SeedState s, string? discoveredRoom) + { + string key = OwnerKey(d); + bool seeded = s.Seeded.Contains(key, StringComparer.OrdinalIgnoreCase); + bool hasOwned = s.OwnedRules.Count > 0; + bool tabNamed = s.ExistingTabs.Contains(d.Name, StringComparer.OrdinalIgnoreCase); + + // Follow a rename: the owned rules carry the tab's current name. + string tabName = d.Name; + foreach (RynthChatFilterDto owned in s.OwnedRules) + if (!string.IsNullOrEmpty(owned.Tab)) { tabName = owned.Tab!; break; } + + bool create = !seeded && !hasOwned && !tabNamed; + string room = discoveredRoom ?? d.GlobalRoomFallback; + var rules = new RynthChatFilterDto[d.Rules.Length]; + for (int i = 0; i < rules.Length; i++) + { + SectionChatRuleDecl r = d.Rules[i]; + rules[i] = new RynthChatFilterDto + { + Owner = key, + Server = d.Server, + Tab = tabName, + Action = r.Action, + When = r.When, + Mode = r.GlobalRoom ? "startswith" : r.Mode, + Pattern = r.GlobalRoom ? GlobalPattern(room) : r.Pattern, + GlobalRoom = r.GlobalRoom ? true : null, + Enabled = i < s.OwnedRules.Count ? s.OwnedRules[i].Enabled : true, + }; + } + return new SeedPlan(create, tabName, create && d.Pinned, !seeded, rules); + } +} diff --git a/tools/ChatFilterTests/ChatFilterTests.csproj b/tools/ChatFilterTests/ChatFilterTests.csproj index e870212..9b050bb 100644 --- a/tools/ChatFilterTests/ChatFilterTests.csproj +++ b/tools/ChatFilterTests/ChatFilterTests.csproj @@ -36,6 +36,9 @@ + + + diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 12407ea..b1fb8ae 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.RegularExpressions; using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Sections; namespace ChatFilterTests; @@ -54,6 +55,8 @@ internal static class Program RetailSetting(); TabsAcrossSetting(); ServerTabSettingsRoundTrip(); + ServerTabDiscovery(); + ServerTabPlans(); SharedFileReload(); LineColorTags(); LineColorKinds(); @@ -1143,6 +1146,83 @@ internal static class Program Check(old.Filters!.All(f => f.Server == null && f.Owner == null && f.GlobalRoom == null), "an old file's rules have none of the rule fields"); } + // ── Server default tabs (2026-11-15) ── + + private static SectionChatTabDecl NetworkDecl() => new( + "dreamweave", "dereth-network", "Network", true, "Roleplay", + new[] + { + new SectionChatRuleDecl("copy", "type:3", "", "^[^\"]+@[a-z0-9-]+( \\(discord\\))? tells you, \"", false), + new SectionChatRuleDecl("copy", "type:4", "", "^You tell [^\"]+@[a-z0-9-]+( \\(discord\\))?, \"", false), + new SectionChatRuleDecl("copy", "", "startswith", "", true), + }); + + private static ChatServerTabs.SeedState State(string[]? seeded = null, string[]? tabs = null, RynthChatFilterDto[]? owned = null) + => new(seeded ?? Array.Empty(), tabs ?? new[] { "All", "Chat" }, owned ?? Array.Empty()); + + private static void ServerTabDiscovery() + { + Case("Discover_FindsRemoteSpeaker"); + Check(ChatServerTabs.DiscoverRoom("[Roleplay] Bob@coldeve says, \"hi\"") == "Roleplay", "Roleplay, remote speaker"); + Check(ChatServerTabs.DiscoverRoom("[trade] Ann Smith@leaf-tide (Discord) says, \"x\"") == "Trade", "lower-case tag, Discord speaker, canonical Trade"); + Check(ChatServerTabs.DiscoverRoom("[LFG] Zed@dw says, \"x\"") == "LFG" && ChatServerTabs.DiscoverRoom("[general] Zed@dw says, \"x\"") == "General", "LFG and General"); + Case("Discover_IgnoresLocalSpeaker"); + Check(ChatServerTabs.DiscoverRoom("[Roleplay] Ann says, \"hi\"") == null, "a local speaker"); + Check(ChatServerTabs.DiscoverRoom("[Roleplay] Ann (Discord) says, \"hi\"") == null, "a Discord speaker with no @world"); + Case("Discover_IgnoresQuotedRoomText"); + Check(ChatServerTabs.DiscoverRoom("Bob says, \"[Trade] Ann@coldeve says, \\\"x\\\"\"") == null, "a say quoting a room line"); + Check(ChatServerTabs.DiscoverRoom("Bob@coldeve tells you, \"[Trade] Ann@coldeve says, \\\"x\\\"\"") == null, "a tell carrying a room line"); + Check(ChatServerTabs.DiscoverRoom("") == null && ChatServerTabs.DiscoverRoom("[Sports] Bob@coldeve says, \"x\"") == null, "empty and an unknown room"); + } + + private static void ServerTabPlans() + { + SectionChatTabDecl d = NetworkDecl(); + string key = ChatServerTabs.OwnerKey(d); + Case("Plan_SeedsFresh"); + Check(key == "dreamweave/dereth-network", "owner key"); + ChatServerTabs.SeedPlan p = ChatServerTabs.Plan(d, State(), null); + Check(p.CreateTab && p.TabName == "Network" && p.Pin && p.MarkSeeded, "creates, names, pins and marks the tab"); + Check(p.Rules.Length == 3 && p.Rules.All(r => r.Owner == key && r.Server == "dreamweave" && r.Tab == "Network" && r.Enabled), "3 owned rules for the tab"); + RynthChatFilterDto g = p.Rules[2]; + Check(g.GlobalRoom == true && g.Mode == "startswith" && g.Pattern == "[Roleplay] ", "the Global rule uses the fallback room"); + Check(p.Rules[0].GlobalRoom == null && p.Rules[0].Pattern == d.Rules[0].Pattern && p.Rules[0].When == "type:3", "other rules copy the declaration"); + + Case("Plan_UsesDiscoveredRoom"); + Check(ChatServerTabs.Plan(d, State(), "General").Rules[2].Pattern == "[General] ", "the discovered room wins over the fallback"); + + Case("Plan_AdoptsExistingTabByName"); + p = ChatServerTabs.Plan(d, State(tabs: new[] { "All", "Chat", "Network" }), null); + Check(!p.CreateTab && !p.Pin && p.MarkSeeded && p.TabName == "Network", "an existing Network tab is adopted, not duplicated or re-pinned"); + p = ChatServerTabs.Plan(d, State(tabs: new[] { "network" }), null); + Check(!p.CreateTab, "the name match ignores case"); + var strayRule = new RynthChatFilterDto { Owner = key, Tab = "DN" }; + p = ChatServerTabs.Plan(d, State(owned: new[] { strayRule }), null); + Check(!p.CreateTab && !p.Pin && p.MarkSeeded && p.TabName == "DN", "owned rules without a seed mark (older engine) are adopted too"); + + Case("Refresh_FollowsRenamedTab"); + RynthChatFilterDto[] owned = ChatServerTabs.Plan(d, State(), null).Rules; + foreach (RynthChatFilterDto r in owned) r.Tab = "DN"; + p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Chat", "DN" }, owned: owned), "Trade"); + Check(p.TabName == "DN" && !p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: no create, no pin, no new mark"); + Check(p.Rules.All(r => r.Tab == "DN"), "every rule follows the rename"); + Check(p.Rules[2].Pattern == "[Trade] ", "a refresh rewrites the Global pattern"); + + Case("Refresh_KeepsDeletedTabDeleted"); + owned = ChatServerTabs.Plan(d, State(), null).Rules; + foreach (RynthChatFilterDto r in owned) r.Enabled = false; + p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, owned: owned), null); + Check(!p.CreateTab && !p.Pin, "a seeded tab that is gone is not re-created"); + Check(p.Rules.All(r => !r.Enabled), "its rules stay disabled"); + + Case("Plan rules compile"); + foreach (RynthChatFilterDto r in ChatServerTabs.Plan(d, State(), "LFG").Rules) + { + System.Text.RegularExpressions.Regex? rx = ChatRuleMatching.Compile(ChatRuleMatching.Parse(r.Mode), r.Pattern, 5000, out string? err); + Check(err == null && rx != null, $"rule '{r.Pattern}' compiles: {err}"); + } + } + private static void TabsAcrossSetting() { Case("tabs across the top: off (the drawer) unless a file says true"); -- 2.43.0 From a92b282fd6fa46520dee4c2994a01f85c2b8f0a9 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:38:04 -0800 Subject: [PATCH 04/12] RynthChat: server-scoped default tabs from plugin manifests SectionRegistry.Rebuild hands every manifest's chatTabs and the active server ids to ChatModel.ApplyServerTabs, which seeds each entry's tab once (seededTabs), rewrites its owned rules from the manifest, and gates the tab (tabServers) and its rules (ChatFilterRule.Server, ChatRouter) on the server being active. The pump records the Global room from network room lines (globalRooms) and rewrites the Global-room rule. - Apply is a no-op when nothing changed (EditFiltersIfChanged; rules compared as canonical forms with ChatServerTabs.SameRule), since Rebuild runs every second, and waits for the settings file to load first. - Rules an older engine stripped of "owner" are reclaimed by content (ChatServerTabs.Reclaim) instead of a second set being added. - A deleted server tab stays deleted across a reload: its disabled owned rules no longer re-create it in LoadSettings. - AllTabs caches per filter version and active-server set. - The rule editor marks server rules; a manifest with a dropped chatTabs entry is logged as partly read, not as unread. Co-Authored-By: Claude Opus 5.5 --- .../ImGui/Panels/ChatFiltersFace.cs | 8 +- src/RynthCore.Engine/UI/Data/ChatData.cs | 413 ++++++++++++++++-- src/RynthCore.Engine/UI/Data/ChatRouting.cs | 25 +- .../UI/Data/ChatServerTabs.cs | 68 +++ .../UI/Sections/SectionRegistry.cs | 18 +- tools/ChatFilterTests/Program.cs | 46 ++ 6 files changed, 544 insertions(+), 34 deletions(-) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 115de74..ce4a8e5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -428,9 +428,13 @@ internal sealed class ChatFiltersFace : IImGuiPanel if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber); if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0) return ("Pick a tab: until then it only colours.", Amber); - if (!r.Enabled) return ("Off.", Faded(Mute)); + // A server plugin's tab rule (ChatModel.ApplyServerTabs): kept in step with its manifest, so + // only on/off and the colour stay as the player sets them. + string from = r.Owner.Length > 0 ? $"Server rule ({r.Server}, kept up to date by its plugin). " : ""; + if (from.Length > 0 && !ChatModel.ServerActive(r.Server)) return (from + "Not running: that server is not active.", Faded(Mute)); + if (!r.Enabled) return (from + "Off.", Faded(Mute)); int hits = System.Threading.Volatile.Read(ref r.Hits); - return (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}.", Faded(Mute)); + return (from + (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}."), Faded(Mute)); } /// Left-to-right placement that wraps to a new row when the next item doesn't fit. diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 69b7adf..3874098 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -64,6 +64,7 @@ using System.Threading; using RynthCore.Engine.Compatibility; using RynthCore.Engine.ImGuiBackend; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Sections; namespace RynthCore.Engine.UI.Data; @@ -179,6 +180,10 @@ internal sealed unsafe class ChatSource : UiSource if (line.Route.Mention) ChatModel.PumpMentionSound(); added.Add(line); } + // A server tab's Global room, seen in chat (ChatModel.ApplyServerTabs). A new room bumps the + // filter version, so the next poll routes the kept lines, these included, with the new rule. + try { ChatModel.PumpDiscoverGlobalRoom(added); } + catch (Exception ex) { RynthLog.UI($"ChatSource: Global room check failed ({ex.GetType().Name}: {ex.Message})."); } if (added.Count == 0) { RelayRead(added); @@ -464,7 +469,35 @@ internal static class ChatModel private static string[] _customTabs = Array.Empty(); private static long _filtersVersion = 1; private static long _routesVersion = 1; - private static (long Version, string[] Tabs) _allTabs; + private static (long Version, string[] Active, string[] Tabs) _allTabs; + + // Server default tabs (2026-11-15, ChatServerTabs). Written only under EditLock and replaced, + // never changed in place, like _filters, so any thread can read them; saved with the settings. + private static string[] _seededTabs = Array.Empty(); // owner keys + private static Dictionary _tabServers = NewMap(); // tab -> server id + private static Dictionary _globalRooms = NewMap(); // server id -> room + private static string[] _pinnedTabs = Array.Empty(); // pin order + // Published by ApplyServerTabs (render thread), read lock-free by the pump and the faces. + private static volatile string[] _activeServers = Array.Empty(); + private static volatile SectionChatTabDecl[] _tabDecls = Array.Empty(); + + private static Dictionary NewMap(IDictionary? from = null) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (from != null) + foreach (var kv in from) + if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value)) map[kv.Key.Trim()] = kv.Value.Trim(); + return map; + } + + /// The ids of the servers active now (SectionRegistry's verdicts). Any thread; never changed in place. + public static string[] ActiveServers => _activeServers; + + /// Does a rule or tab for apply now ("" = every server)? Any thread. + public static bool ServerActive(string server) => ChatRouter.ServerIn(_activeServers, server); + + /// The tabs pinned to the main window's top bar, in pin order. Any thread. + public static string[] PinnedTabs => Volatile.Read(ref _pinnedTabs); public static ChatFilterRule[] Filters => Volatile.Read(ref _filters); @@ -484,15 +517,25 @@ internal static class ChatModel /// A rule just made from a chat line: the rule editor scrolls to it and flashes it. public static volatile ChatFilterRule? FocusRule; - public static void EditFilters(Action> edit) + public static void EditFilters(Action> edit) => EditFiltersIfChanged(list => { edit(list); return true; }); + + /// + /// An edit that may turn out to change nothing: returns whether it + /// changed anything, and only then is the list published, the version bumped and the + /// settings saved. Runs under EditLock, like every edit. (Its own name, not an EditFilters + /// overload: a lambda such as list => list.Remove(r) would bind to the bool overload.) + /// + public static bool EditFiltersIfChanged(Func, bool> edit) { + bool changed; lock (EditLock) { var list = new List(_filters); - edit(list); - Volatile.Write(ref _filters, list.ToArray()); + changed = edit(list); + if (changed) Volatile.Write(ref _filters, list.ToArray()); } - FiltersChanged(); + if (changed) FiltersChanged(); + return changed; } /// Moves a rule one place up (-1) or down (+1). Order matters (see the header). @@ -605,22 +648,44 @@ internal static class ChatModel /// public static string[] AllTabs() { + // Read the version before the active set: ApplyServerTabs publishes the set and only then + // bumps the version, so a list cached under the new version was built from the new set. + // The set is part of the key as well, so a list built from an older set is never reused. long version = FiltersVersion; + string[] active = ActiveServers; var cached = _allTabs; - if (cached.Tabs != null && cached.Version == version) return cached.Tabs; - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var tabs = new List(); - foreach (string t in BaseTabs) if (seen.Add(t)) tabs.Add(t); - foreach (string t in Volatile.Read(ref _customTabs)) if (seen.Add(t)) tabs.Add(t); - foreach (ChatFilterRule rule in Filters) - if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 && seen.Add(rule.Tab)) tabs.Add(rule.Tab); - foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs()) - if (seen.Add(t)) tabs.Add(t); - string[] result = tabs.ToArray(); - _allTabs = (version, result); + if (cached.Tabs != null && cached.Version == version && ReferenceEquals(cached.Active, active)) return cached.Tabs; + string[] result = BuildTabs(active); + _allTabs = (version, active, result); return result; } + /// + /// AllTabs, or with null every tab including those of inactive + /// servers (a tab named by "tabServers" shows only while its server is active). + /// + private static string[] BuildTabs(string[]? active) + { + Dictionary tabServers = Volatile.Read(ref _tabServers); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var tabs = new List(); + void Add(string t) + { + if (active != null && !IsBaseTab(t) && tabServers.TryGetValue(t, out string? server) + && !ChatRouter.ServerIn(active, server)) return; + if (seen.Add(t)) tabs.Add(t); + } + foreach (string t in BaseTabs) Add(t); + foreach (string t in Volatile.Read(ref _customTabs)) Add(t); + foreach (ChatFilterRule rule in Filters) + if (rule.Enabled && rule.Routes && rule.Tab.Length > 0) Add(rule.Tab); + foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs()) Add(t); + return tabs.ToArray(); + } + + /// Is a tab at all, shown or not (its server may be inactive)? + private static bool TabExists(string tab) => BuildTabs(null).Contains(tab, StringComparer.OrdinalIgnoreCase); + /// The tabs a Move/Copy rule can send lines to: every tab but All. public static string[] TargetTabs() => AllTabs().Where(t => t != "All").ToArray(); @@ -675,13 +740,24 @@ internal static class ChatModel { newName = newName.Trim(); if (newName.Length == 0 || IsBaseTab(tab)) return false; + // Every tab counts, also one hidden because its server is not active, or the two would merge. if (!string.Equals(tab, newName, StringComparison.OrdinalIgnoreCase) - && AllTabs().Contains(newName, StringComparer.OrdinalIgnoreCase)) return false; + && TabExists(newName)) return false; lock (EditLock) { string[] tabs = _customTabs.Select(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase) ? newName : t).ToArray(); if (!tabs.Contains(newName)) tabs = tabs.Append(newName).ToArray(); Volatile.Write(ref _customTabs, tabs); + // A server's tab stays that server's, and a pinned tab stays pinned in its place. + if (_tabServers.TryGetValue(tab, out string? server)) + { + Dictionary map = NewMap(_tabServers); + map.Remove(tab); + map[newName] = server; + Volatile.Write(ref _tabServers, map); + } + Volatile.Write(ref _pinnedTabs, + _pinnedTabs.Select(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase) ? newName : t).ToArray()); } foreach (ChatFilterRule rule in Filters) if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) @@ -701,18 +777,249 @@ internal static class ChatModel public static void DeleteCustomTab(string tab) { lock (EditLock) + { Volatile.Write(ref _customTabs, _customTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); - foreach (ChatFilterRule rule in Filters) - if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy - && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) - rule.Enabled = false; + // A server's tab: its seed mark stays (seededTabs), so ApplyServerTabs never re-creates it. + if (_tabServers.ContainsKey(tab)) + { + Dictionary map = NewMap(_tabServers); + map.Remove(tab); + Volatile.Write(ref _tabServers, map); + } + Volatile.Write(ref _pinnedTabs, + _pinnedTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); + // Inside the lock with the tab's removal, so ApplyServerTabs never sees the tab gone + // while its rules are still on (it would take the tab for an existing one). + foreach (ChatFilterRule rule in _filters) + if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy + && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) + rule.Enabled = false; + } foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All) if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase)) preset.Enabled = false; FiltersChanged(); } + // -- Server default tabs (2026-11-15) --------------------------------- + // + // A server plugin's sections manifest can declare chat tabs ("chatTabs", SectionManifest.cs). + // What they become is decided by ChatServerTabs (pure; tools/ChatFilterTests) and applied here: + // the tab is created and pinned once (seededTabs), its rules ("owner" = "server/id") are + // rewritten from the manifest on every read, the tab shows and its rules run only while its + // server is active (tabServers, ChatFilterRule.Server), and the Global-room rule follows the + // room chat last showed (globalRooms). + // + // Threads. Two callers: SectionRegistry.Rebuild on AC's render thread (every second, with every + // manifest's entries and the active servers), and ChatSource.PollLines on the pump (a line + // showed this server's Global room). Both apply through EditFiltersIfChanged, under EditLock, + // the lock every rule and tab edit and a settings reload take, so the two are serialized with + // each other, with the editors and with LoadSettings. Nothing done while holding EditLock takes + // another lock or calls out (no SectionRegistry, no plugin export, no file I/O; the save is + // queued to the background writer after the lock is released), so no thread can hold EditLock + // while waiting on one that wants it: no deadlock. The pump never calls into SectionRegistry; it + // reads what Rebuild last published (_tabDecls, _activeServers: volatile references to arrays + // never changed in place). The active set is read once per router (ChatRouter keeps the + // reference) and once per AllTabs build, never per line, and it is published BEFORE the version + // bump that announces it, so a reader that sees the new version also sees the new set. + // + // No-op. Rebuild calls ApplyServerTabs every second, so in the steady state it must neither save + // nor bump the version. Every write is guarded by a comparison with what is already there: the + // active set (as a sorted set), each owned rule (ChatServerTabs.SameRule on canonical forms, + // both sides through BuildRule and ToDto), the tab, the pin, the seed mark and the tab's server + // (each added only when missing, never overwritten). Only a write sets "changed", and only + // "changed" publishes, bumps and saves (EditFiltersIfChanged). + + /// + /// Render thread (SectionRegistry.Rebuild): every manifest's chat tab entries and the ids of the + /// active servers. Publishes the active set (re-routing and re-listing tabs when it moved) and + /// applies the entries of active servers. Cheap and silent when nothing changed. + /// + public static void ApplyServerTabs(IReadOnlyList decls, IReadOnlyCollection activeServers) + { + string[] active = activeServers.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(s => s, StringComparer.OrdinalIgnoreCase).ToArray(); + if (!SameServers(active, _activeServers)) + { + _activeServers = active; // before the bump: see the threading note above + Interlocked.Increment(ref _filtersVersion); + } + + // One entry per owner key (two plugins declaring the same one would rewrite each other's rules every second). + var unique = new List(decls.Count); + foreach (SectionChatTabDecl d in decls) + if (!unique.Exists(u => string.Equals(ChatServerTabs.OwnerKey(u), ChatServerTabs.OwnerKey(d), StringComparison.OrdinalIgnoreCase))) + unique.Add(d); + if (!SameDecls(unique, _tabDecls)) _tabDecls = unique.ToArray(); + + // Not before the settings file is read: seeding the empty defaults would save them over it. + if (!_settingsReady) return; + string[] now = _activeServers; + if (!unique.Exists(d => ChatRouter.ServerIn(now, d.Server))) return; // nothing to apply: no lock + EditFiltersIfChanged(list => + { + bool changed = false; + foreach (SectionChatTabDecl d in unique) + if (ChatRouter.ServerIn(now, d.Server)) changed |= ApplyServerTab(list, d); + return changed; + }); + } + + /// + /// Pump thread (ChatSource.PollLines): a new line from a network speaker in a room is that + /// server's Global room; when it differs from the stored one, store it and rewrite the + /// Global-room rule. Lines from no active server's entry cost nothing. + /// + internal static void PumpDiscoverGlobalRoom(IReadOnlyList added) + { + SectionChatTabDecl[] decls = _tabDecls; + if (decls.Length == 0 || added.Count == 0 || !_settingsReady) return; + string[] active = _activeServers; + bool any = false; + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(r => r.GlobalRoom)) { any = true; break; } + if (!any) return; + + string? room = null; + foreach (ChatLine line in added) + if (line.Text.Length > 0 && line.Text[0] == '[' && ChatServerTabs.DiscoverRoom(line.Text) is { } r) room = r; + if (room == null) return; + string seen = room; + Dictionary rooms = Volatile.Read(ref _globalRooms); + bool news = false; + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(x => x.GlobalRoom) + && !(rooms.TryGetValue(d.Server, out string? have) && have == seen)) { news = true; break; } + if (!news) return; // the usual case on a room line: the room is already known, no lock + + EditFiltersIfChanged(list => + { + bool changed = false; + Dictionary map = NewMap(_globalRooms); + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(x => x.GlobalRoom) + && !(map.TryGetValue(d.Server, out string? have) && have == seen)) + { + map[d.Server] = seen; + changed = true; + } + if (!changed) return false; + Volatile.Write(ref _globalRooms, map); + RynthLog.UI($"ChatModel: the Global room is now [{seen}] (seen in chat)."); + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server)) ApplyServerTab(list, d); + return true; + }); + } + + /// One entry, under EditLock: plans it (ChatServerTabs.Plan) and writes only what differs. True when it wrote. + private static bool ApplyServerTab(List list, SectionChatTabDecl d) + { + string key = ChatServerTabs.OwnerKey(d); + var ownedAt = new List(); + for (int i = 0; i < list.Count; i++) + if (string.Equals(list[i].Owner, key, StringComparison.OrdinalIgnoreCase)) ownedAt.Add(i); + if (ownedAt.Count == 0 && d.Rules.Length > 0 && ChatServerTabs.Reclaim(d, list.Select(ToDto).ToArray()) is { } found) + ownedAt.AddRange(found); // an older engine dropped "owner": these are ours, not a second set + + // The tabs there are: created ones, and those an enabled Move/Copy rule fills (AllTabs, unfiltered). + var existing = new List(BaseTabs); + existing.AddRange(_customTabs); + foreach (ChatFilterRule rule in list) + if (rule.Enabled && rule.Routes && rule.Tab.Length > 0) existing.Add(rule.Tab); + string? room = _globalRooms.TryGetValue(d.Server, out string? r) ? r : null; + var state = new ChatServerTabs.SeedState(_seededTabs, existing, ownedAt.Select(i => ToDto(list[i])).ToArray()); + ChatServerTabs.SeedPlan plan = ChatServerTabs.Plan(d, state, room); + + bool changed = false; + int both = Math.Min(ownedAt.Count, plan.Rules.Length); + for (int i = 0; i < both; i++) changed |= RefreshRule(list[ownedAt[i]], plan.Rules[i]); + if (plan.Rules.Length > both) + { + // New rules go after the entry's last rule, or at the end (as a rule the player adds). + int at = ownedAt.Count > 0 ? ownedAt.Max() + 1 : list.Count; + for (int i = both; i < plan.Rules.Length; i++) list.Insert(at++, FromDto(plan.Rules[i])); + changed = true; + } + else if (ownedAt.Count > both) + { + foreach (int i in ownedAt.Skip(both).OrderByDescending(i => i)) list.RemoveAt(i); + changed = true; + } + + string tab = plan.TabName; + bool baseTab = IsBaseTab(tab); + if (plan.CreateTab && !baseTab && !_customTabs.Contains(tab, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _customTabs, _customTabs.Append(tab).ToArray()); + changed = true; + } + if (plan.Pin && !_pinnedTabs.Contains(tab, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _pinnedTabs, _pinnedTabs.Append(tab).ToArray()); + changed = true; + } + if (plan.MarkSeeded && !_seededTabs.Contains(key, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _seededTabs, _seededTabs.Append(key).ToArray()); + changed = true; + } + // The tab is the server's while it exists (a deleted one gets no entry back). Added when + // missing, never overwritten, so two entries naming one tab can't take turns. + bool tabThere = plan.CreateTab || existing.Contains(tab, StringComparer.OrdinalIgnoreCase); + if (tabThere && !baseTab && !_tabServers.ContainsKey(tab)) + { + Dictionary map = NewMap(_tabServers); + map[tab] = d.Server; + Volatile.Write(ref _tabServers, map); + changed = true; + } + if (changed) RynthLog.UI($"ChatModel: server tab \"{tab}\" ({key}) updated from the {d.Server} manifest{(plan.CreateTab ? " (created)" : "")}."); + return changed; + } + + /// Makes what Plan wants, field by field; false (nothing written) when it already is. + private static bool RefreshRule(ChatFilterRule rule, RynthChatFilterDto want) + { + ChatFilterRule w = BuildRule(want); // the canonical form, not compiled + if (ChatServerTabs.SameRule(ToDto(w), ToDto(rule))) return false; + rule.Owner = w.Owner; + rule.Server = w.Server; + rule.Tab = w.Tab; + rule.Action = w.Action; + rule.When = w.When; + rule.GlobalRoom = w.GlobalRoom; + rule.Enabled = w.Enabled; + if (rule.Mode != w.Mode || !string.Equals(rule.Pattern, w.Pattern, StringComparison.Ordinal)) + { + rule.Mode = w.Mode; + rule.Pattern = w.Pattern; + rule.Recompile(); + } + return true; // its colour is the player's and stays + } + + private static bool SameServers(string[] a, string[] b) + { + if (ReferenceEquals(a, b)) return true; + if (a.Length != b.Length) return false; + for (int i = 0; i < a.Length; i++) + if (!string.Equals(a[i], b[i], StringComparison.OrdinalIgnoreCase)) return false; + return true; + } + + private static bool SameDecls(List a, SectionChatTabDecl[] b) + { + if (a.Count != b.Length) return false; + for (int i = 0; i < b.Length; i++) + if (!ReferenceEquals(a[i], b[i])) return false; + return true; + } + + private static string[]? NullIfEmpty(string[] a) => a.Length > 0 ? a : null; + private static Dictionary? NullIfEmpty(Dictionary m) => m.Count > 0 ? m : null; + /// Is the line shown under (rules applied, no search)? public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel); @@ -746,7 +1053,7 @@ internal static class ChatModel long version = FiltersVersion; var cached = _pumpRouter; if (cached is { } c && c.Version == version && c.Name == name) return c.Router; - var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true); + var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true, ActiveServers); _pumpRouter = (version, name, router); return router; } @@ -773,7 +1080,7 @@ internal static class ChatModel if (cached is { } c && c.Version == version && c.Name == name) router = c.Router; else { - router = new ChatRouter(Filters, mention: null, name, countHits: false); + router = new ChatRouter(Filters, mention: null, name, countHits: false, ActiveServers); _retailRouter = (version, name, router); } return ChatRetailVerdict.IsHidden(router, line, chatType); @@ -784,7 +1091,7 @@ internal static class ChatModel { string name = SessionStateRegistry.LastCharacterName; if (string.IsNullOrWhiteSpace(name)) name = _pumpName ?? ""; - return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false); + return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false, ActiveServers); } private static Regex? BuildMentionRegex(string name) @@ -883,6 +1190,10 @@ internal static class ChatModel Color = f.ColorMode != ChatColorMode.None || f.ColorArgb != ChatFilterRule.DefaultColor ? FormatColor(f.ColorArgb) : null, // Absent for a Regex rule, so a file without plain-text rules is written as before. Mode = ChatRuleMatching.ToJson(f.Mode), + // Absent on the player's own rules (2026-11-15, server default tabs). + Server = f.Server.Length > 0 ? f.Server : null, + Owner = f.Owner.Length > 0 ? f.Owner : null, + GlobalRoom = f.GlobalRoom ? true : null, }; /// @@ -892,6 +1203,14 @@ internal static class ChatModel /// it out of All too). /// private static ChatFilterRule FromDto(RynthChatFilterDto f) + { + ChatFilterRule rule = BuildRule(f); + rule.Recompile(); + return rule; + } + + /// FromDto without compiling the pattern (ApplyServerTabs compares canonical forms every second). + private static ChatFilterRule BuildRule(RynthChatFilterDto f) { string tab = (f.Tab ?? "").Trim(); var rule = new ChatFilterRule @@ -912,8 +1231,11 @@ internal static class ChatModel ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, // Absent (every file before 2026-10-05): Regex, as those rules always were. Mode = ChatRuleMatching.Parse(f.Mode), + // Absent (the player's own rules, and every file before 2026-11-15): every server, no owner. + Server = (f.Server ?? "").Trim(), + Owner = (f.Owner ?? "").Trim(), + GlobalRoom = f.GlobalRoom ?? false, }; - rule.Recompile(); return rule; } @@ -1349,6 +1671,9 @@ internal static class ChatModel public const int SettingsVersion = 2; private static readonly object SaveLock = new(); private static int _settingsLoaded; + // Set once the first load has finished (_settingsLoaded is set as it starts). ApplyServerTabs + // waits for it: seeding into the empty defaults would save them over the shared file. + private static volatile bool _settingsReady; private static string SettingsPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_settings.json"); @@ -1357,7 +1682,8 @@ internal static class ChatModel public static void EnsureSettingsLoaded() { if (Interlocked.Exchange(ref _settingsLoaded, 1) != 0) return; - LoadSettings(); + try { LoadSettings(); } + finally { _settingsReady = true; } } // Every client shares rynthchat_settings.json and saves its whole state, so a client that @@ -1449,6 +1775,9 @@ internal static class ChatModel rules.Add(rule); // A tab typed into a rule used to exist only while the rule was on: // make it a real tab, so turning the rule off doesn't drop the tab. + // Not for a server plugin's rule that is off: deleting its tab turned it off, + // and the deleted tab must stay deleted (ApplyServerTabs keeps the rule). + if (rule.Owner.Length > 0 && !rule.Enabled) continue; if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy && rule.Tab.Length > 0 && !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase)) tabs.Add(rule.Tab); @@ -1470,13 +1799,32 @@ internal static class ChatModel && !tabs.Contains(preset.Tab, StringComparer.OrdinalIgnoreCase)) tabs.Add(preset.Tab); } - _customTabs = tabs.ToArray(); - _filters = rules.ToArray(); + // Server default tabs (2026-11-15): absent in every older file, and in a file an older + // engine saved over (it drops what it doesn't know). ApplyServerTabs then finds its + // rules and tab again instead of adding new ones (ChatServerTabs.Plan / Reclaim). + string[] seeded = (dto.SeededTabs ?? Array.Empty()) + .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + string[] pinned = (dto.PinnedTabs ?? Array.Empty()) + .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + // Under EditLock, as ApplyServerTabs (render thread) edits the same lists. + lock (EditLock) + { + _customTabs = tabs.ToArray(); + _filters = rules.ToArray(); + _seededTabs = seeded; + _tabServers = NewMap(dto.TabServers); + _globalRooms = NewMap(dto.GlobalRooms); + _pinnedTabs = pinned; + } Interlocked.Increment(ref _filtersVersion); - if (!reload && !string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) + // Every tab, also one whose server isn't active (yet: at startup no server is known). + string[] everyTab = BuildTabs(null); + if (!reload && !string.IsNullOrEmpty(dto.ActiveChannel) && everyTab.Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = dto.ActiveChannel; - else if (reload && !AllTabs().Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) + else if (reload && !everyTab.Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = "All"; // the tab this client was on was removed elsewhere } catch (Exception ex) when (reload) @@ -1528,6 +1876,11 @@ internal static class ChatModel LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set RetailColors = ChatLineColors.RetailColors ? null : false, // left out while on (the default) CustomTabs = Volatile.Read(ref _customTabs), + // Left out while empty (2026-11-15), so a file without server tabs or pins is as before. + SeededTabs = NullIfEmpty(Volatile.Read(ref _seededTabs)), + TabServers = NullIfEmpty(Volatile.Read(ref _tabServers)), + GlobalRooms = NullIfEmpty(Volatile.Read(ref _globalRooms)), + PinnedTabs = NullIfEmpty(Volatile.Read(ref _pinnedTabs)), Filters = Filters.Select(ToDto).ToArray(), // Only presets the user touched: new presets in later builds start off. Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs index 8decf42..6c9dd51 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRouting.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -202,6 +202,13 @@ internal sealed class ChatFilterRule public const uint DefaultColor = 0xFFFFD27A; /// 0xAARRGGBB. public volatile uint ColorArgb = DefaultColor; + /// A server plugin's tab rule (2026-11-15, ChatServerTabs): the server id it runs on, "" + /// = every server. The router skips it while that server is not active. + public volatile string Server = ""; + /// "server/entry id" of the plugin entry that owns it, "" for the player's own rule. + public volatile string Owner = ""; + /// Its pattern follows the Global room discovered from chat (ChatModel.ApplyServerTabs). + public volatile bool GlobalRoom; private volatile WhenSpec _when = WhenSpec.Any; /// "" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions). @@ -311,21 +318,34 @@ internal sealed class ChatRouter private readonly Regex? _mention; private readonly string _self; private readonly bool _countHits; + private readonly string[] _activeServers; private readonly long[] _passTicks; private long _passBudgetTicks = PassBudgetTicks; private bool _inPass; /// Your character's name ("" unknown): your own emotes don't mention you. /// Count matches into ChatFilterRule.Hits (the pump's router; not the test box's). - public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits) + /// The active server ids (ChatModel.ActiveServers, read once here): a rule + /// with a Server outside them is skipped. Null: none, so only rules for every server run. + public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits, string[]? activeServers = null) { _rules = rules; _mention = mention; _self = self.Trim(); _countHits = countHits; + _activeServers = activeServers ?? Array.Empty(); _passTicks = new long[rules.Length]; } + /// Does a rule for run ("" = every server)? + internal static bool ServerIn(string[] active, string server) + { + if (server.Length == 0) return true; + foreach (string s in active) + if (string.Equals(s, server, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + /// /// Before routing the kept lines again: hit counts restart, and /// each rule's time is watched (PassBudgetMs per PassBudgetLines lines, never less than @@ -381,6 +401,9 @@ internal sealed class ChatRouter { ChatFilterRule rule = _rules[i]; if (!rule.Enabled || rule.Slow) continue; + // A server plugin's rule runs only on its server (the snapshot this router was built with; + // a change of active servers bumps the filter version, so the pump builds a new router). + if (!ServerIn(_activeServers, rule.Server)) continue; Regex? rx = rule.Compiled; if (rx == null) continue; ChatRuleAction action = rule.Action; diff --git a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs index b3b02b1..490115a 100644 --- a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -93,4 +93,72 @@ internal static class ChatServerTabs } return new SeedPlan(create, tabName, create && d.Pinned, !seeded, rules); } + + /// + /// True when a stored rule already is what Plan wants, on every field Plan sets (owner, + /// server, tab, action, when, mode, pattern, globalRoom, enabled); colours are the player's + /// and are not compared. Both sides must come through the same rule-to-JSON conversion + /// (ChatModel compares canonical forms), so absent and empty mean the same here as well. + /// This is what keeps ChatModel.ApplyServerTabs, which runs every second, from saving + /// when nothing changed. + /// + internal static bool SameRule(RynthChatFilterDto want, RynthChatFilterDto have) => + Same(want.Owner, have.Owner) && Same(want.Server, have.Server) && Same(want.Tab, have.Tab) + && string.Equals(want.Action ?? "", have.Action ?? "", StringComparison.OrdinalIgnoreCase) + && Same(want.When, have.When) + && ChatRuleMatching.Parse(want.Mode) == ChatRuleMatching.Parse(have.Mode) + && Same(want.Pattern, have.Pattern) + && (want.GlobalRoom ?? false) == (have.GlobalRoom ?? false) + && want.Enabled == have.Enabled; + + private static bool Same(string? a, string? b) => string.Equals(a ?? "", b ?? "", StringComparison.Ordinal); + + private static readonly string[] Rooms = { "General", "Trade", "LFG", "Roleplay" }; + + /// + /// An older engine rewrote the shared settings file and dropped "owner" from this entry's + /// rules: finds them again among the ownerless rules, so a refresh rewrites them instead of + /// adding a second set (which would grow by one set per old-engine save). A rule matches a + /// declared one on action, when, mode and pattern; a GlobalRoom rule matches "[room] " + /// (Starts with) for any room. Every declared rule must be found, all in one tab (the + /// entry's name is tried first). Returns their indexes in , in + /// declaration order, or null. + /// + internal static int[]? Reclaim(SectionChatTabDecl d, IReadOnlyList rules) + { + if (d.Rules.Length == 0) return null; + var tabs = new List { d.Name }; + foreach (RynthChatFilterDto r in rules) + if (string.IsNullOrEmpty(r.Owner) && !string.IsNullOrEmpty(r.Tab) + && !tabs.Contains(r.Tab!, StringComparer.Ordinal)) tabs.Add(r.Tab!); + foreach (string tab in tabs) + { + var found = new int[d.Rules.Length]; + bool all = true; + for (int i = 0; i < d.Rules.Length && all; i++) + { + found[i] = -1; + for (int j = 0; j < rules.Count; j++) + { + RynthChatFilterDto r = rules[j]; + if (!string.IsNullOrEmpty(r.Owner) || !string.Equals(r.Tab, tab, StringComparison.Ordinal)) continue; + if (Array.IndexOf(found, j, 0, i) >= 0 || !Matches(d.Rules[i], r)) continue; + found[i] = j; + break; + } + all = found[i] >= 0; + } + if (all) return found; + } + return null; + } + + private static bool Matches(SectionChatRuleDecl decl, RynthChatFilterDto r) + { + if (!string.Equals(decl.Action, r.Action ?? "", StringComparison.OrdinalIgnoreCase) || !Same(decl.When, r.When)) return false; + if (decl.GlobalRoom) + return ChatRuleMatching.Parse(r.Mode) == ChatMatchMode.StartsWith + && Rooms.Any(room => Same(GlobalPattern(room), r.Pattern)); + return ChatRuleMatching.Parse(decl.Mode) == ChatRuleMatching.Parse(r.Mode) && Same(decl.Pattern, r.Pattern); + } } diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs index a677357..788df25 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs @@ -173,7 +173,11 @@ internal static class SectionRegistry seen.Add(plugin); if (PluginManifests.TryGetValue(plugin, out var old) && old.Json == json) continue; SectionManifest m = SectionManifestParser.Parse(plugin, json, out string error); - if (error.Length > 0) RynthLog.UI($"Sections: {plugin}'s manifest was not read - {error}."); + // A dropped "chatTabs" entry is reported in the error too, while the rest of the + // manifest is kept (SectionManifestParser.Note): don't call that "not read". + if (error.StartsWith("chatTabs:", StringComparison.Ordinal)) + RynthLog.UI($"Sections: {plugin}'s manifest was read, but part of it was left out - {error}."); + else if (error.Length > 0) RynthLog.UI($"Sections: {plugin}'s manifest was not read - {error}."); PluginManifests[plugin] = (json, m); changed = true; } @@ -217,6 +221,18 @@ internal static class SectionRegistry // The windows plugins draw (their manifests' "windows"): hosted as panels while wanted. try { PluginWindows.Sync(manifests, servers); } catch (Exception ex) { RynthLog.UI($"PluginWindows: sync failed - {ex.GetType().Name}: {ex.Message}"); } + // The chat tabs servers' plugins declare ("chatTabs"): RynthChat seeds them and runs their + // rules only while their server is active. No lock is held here (ChatModel takes its own). + try + { + var chatTabs = new List(); + foreach (SectionManifest m in manifests) chatTabs.AddRange(m.ChatTabs); + var active = new List(); + foreach (ServerState s in servers) + if (s.Active) active.Add(s.Id); + UI.Data.ChatModel.ApplyServerTabs(chatTabs, active); + } + catch (Exception ex) { RynthLog.UI($"Sections: chat tabs not applied - {ex.GetType().Name}: {ex.Message}"); } } /// The built-in servers, then every server a manifest declares with a new id. diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index b1fb8ae..426e343 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1215,6 +1215,52 @@ internal static class Program Check(!p.CreateTab && !p.Pin, "a seeded tab that is gone is not re-created"); Check(p.Rules.All(r => !r.Enabled), "its rules stay disabled"); + Case("Refresh_IsANoOpWhenNothingChanged"); + // ChatModel.ApplyServerTabs runs every second: a plan made from its own output must match it + // rule for rule (SameRule), and want no create, pin or seed mark, or every Rebuild would save. + owned = ChatServerTabs.Plan(d, State(), "Trade").Rules; + p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Network" }, owned: owned), "Trade"); + Check(!p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: nothing to create, pin or mark"); + Check(p.Rules.Length == owned.Length && p.Rules.Zip(owned).All(z => ChatServerTabs.SameRule(z.First, z.Second)), "every rule is the same as before"); + var absent = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = null, Mode = null, Pattern = "x", GlobalRoom = null, Enabled = true }; + var empty = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = "", Mode = "", Pattern = "x", GlobalRoom = false, Enabled = true }; + Check(ChatServerTabs.SameRule(absent, empty), "absent and empty When / Mode / GlobalRoom are the same"); + Check(ChatServerTabs.SameRule(empty, new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", Pattern = "x", Color = "#FF0000", ColorMode = "line" }), + "a colour the player gave the rule is not a difference"); + Check(!ChatServerTabs.SameRule(owned[2], ChatServerTabs.Plan(d, State(), "General").Rules[2]), "a new Global room is a difference"); + var off = ChatServerTabs.Plan(d, State(), "Trade").Rules; + off[0].Enabled = false; + Check(!ChatServerTabs.SameRule(owned[0], off[0]), "on / off is a difference"); + + Case("Reclaim_FindsRulesAnOlderEngineStripped"); + // An older engine rewrote the file: its copy of the rules has no owner, server or globalRoom. + RynthChatFilterDto Strip(RynthChatFilterDto r) => new() { Tab = r.Tab, Action = r.Action, When = r.When, Mode = r.Mode, Pattern = r.Pattern, Enabled = r.Enabled }; + RynthChatFilterDto[] ours = ChatServerTabs.Plan(d, State(), "Trade").Rules; + var player = new RynthChatFilterDto { Tab = "RP", Action = "copy", Mode = "startswith", Pattern = "[Roleplay] " }; + var file = new List { player, Strip(ours[1]), new() { Tab = "Junk", Action = "hide", Pattern = "spam" }, Strip(ours[0]), Strip(ours[2]) }; + int[]? found = ChatServerTabs.Reclaim(d, file); + Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), $"found in declaration order, not the player's look-alike Global rule: {(found == null ? "null" : string.Join(",", found))}"); + foreach (RynthChatFilterDto r in file) if (r.Tab == "Network") r.Tab = "DN"; + found = ChatServerTabs.Reclaim(d, file); + Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), "a renamed tab's stripped rules are found too"); + Check(ChatServerTabs.Reclaim(d, new[] { player, Strip(ours[0]) }) == null, "an incomplete set is not reclaimed"); + file[3].Owner = key; + Check(ChatServerTabs.Reclaim(d, file) == null, "a rule that still has an owner is not reclaimed"); + Check(ChatServerTabs.Reclaim(d, new[] { Strip(ours[0]), Strip(ours[1]), new RynthChatFilterDto { Tab = "Other", Action = "copy", Mode = "startswith", Pattern = "[Trade] " } }) == null, + "the set must be in one tab"); + + Case("Router_SkipsRulesOfInactiveServers"); + var serverRule = new ChatFilterRule { Pattern = "^x", Tab = "Network", Action = ChatRuleAction.Copy, Server = "dreamweave" }; + serverRule.Recompile(); + var anyRule = new ChatFilterRule { Pattern = "^x", Tab = "Every", Action = ChatRuleAction.Copy }; + anyRule.Recompile(); + ChatRoute on = new ChatRouter(new[] { serverRule, anyRule }, null, "", countHits: false, new[] { "DreamWeave" }).Evaluate("x", "Chat", 2, null); + ChatRoute offRoute = new ChatRouter(new[] { serverRule, anyRule }, null, "", countHits: false, new[] { "aelrynth" }).Evaluate("x", "Chat", 2, null); + ChatRoute none = new ChatRouter(new[] { serverRule, anyRule }, null, "", countHits: false).Evaluate("x", "Chat", 2, null); + Check(on.ShowsIn("Network", "Chat") && on.ShowsIn("Every", "Chat"), "its server active (any case): both rules run"); + Check(!offRoute.ShowsIn("Network", "Chat") && offRoute.ShowsIn("Every", "Chat"), "another server: only the every-server rule runs"); + Check(!none.ShowsIn("Network", "Chat") && none.ShowsIn("Every", "Chat"), "no servers known: only the every-server rule runs"); + Case("Plan rules compile"); foreach (RynthChatFilterDto r in ChatServerTabs.Plan(d, State(), "LFG").Rules) { -- 2.43.0 From 01f432d7452f9a8b4568c65aac3d9f3fa4ddb4e7 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:39:27 -0800 Subject: [PATCH 05/12] Sections manifest: an absent globalRoomFallback means Roleplay The Dereth Network README names Roleplay as the room a world usually borrows for the Global room, so an entry that leaves the fallback out matches Roleplay until chat shows another room. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/UI/Sections/SectionManifest.cs | 5 +++-- tools/SectionsTests/Program.cs | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs index 95942d5..86a4f55 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -68,7 +68,8 @@ // "pattern": "...", "globalRoom": false } ] } ]. // "server" and "id" are ids (the owner key is "server/id"); "action" is copy // or move; "globalRoomFallback" is General, Trade, LFG or Roleplay (the -// room a "globalRoom": true rule matches until chat shows another). An +// room a "globalRoom": true rule matches until chat shows another; absent: +// Roleplay, the room the Dereth Network README names as usual). An // entry with a bad field is dropped and reported in the parse error (the // other keys still parse); at most MaxChatTabs entries of MaxChatRules // rules each. Engines before this ignore the key. @@ -341,7 +342,7 @@ internal static class SectionManifestParser string name = Text(Str(e, "name"), MaxLabelLength); if (name.Length == 0) { why = "missing name"; return null; } string fallback = Str(e, "globalRoomFallback").Trim(); - string room = fallback.Length == 0 ? "General" : GlobalRooms.FirstOrDefault(r => r.Equals(fallback, StringComparison.OrdinalIgnoreCase)) ?? string.Empty; + string room = fallback.Length == 0 ? "Roleplay" : GlobalRooms.FirstOrDefault(r => r.Equals(fallback, StringComparison.OrdinalIgnoreCase)) ?? string.Empty; if (room.Length == 0) { why = "globalRoomFallback is not General, Trade, LFG or Roleplay"; return null; } var rules = new List(); foreach (JsonElement r in Array(e, "rules")) diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index 0d66f61..aa3a9d2 100644 --- a/tools/SectionsTests/Program.cs +++ b/tools/SectionsTests/Program.cs @@ -613,6 +613,8 @@ internal static class Program Check(t.Rules[0].Action == "copy" && t.Rules[0].When == "type:3" && t.Rules[0].Pattern == "^x" && !t.Rules[0].GlobalRoom, "rule 0 fields"); Check(SectionManifestParser.Parse("DW", """{ "contributions": [] }""", out _).ChatTabs.Length == 0, "no chatTabs key = empty array"); + var noFallback = SectionManifestParser.Parse("DW", """{ "chatTabs": [ { "server": "dw", "id": "a", "name": "A", "rules": [] } ] }""", out _); + Check(noFallback.ChatTabs.Length == 1 && noFallback.ChatTabs[0].GlobalRoomFallback == "Roleplay", "absent globalRoomFallback = Roleplay"); // Each reject drops the entry, reports it in error, and still parses the other keys. string section = """ "sections": [ { "id": "quests", "label": "Quests", "order": 150 } ] """; -- 2.43.0 From 05a6d7d088f46c5311f81553c44f7ffe905af27f Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:59:53 -0800 Subject: [PATCH 06/12] RynthChat server tabs: review fixes (pure apply core, pairing, clashes) The decision core of ChatModel.ApplyServerTab moves into ChatServerTabs.Apply, a pure function returning edits (rule updates, inserts, removals, tab create, pin, seed mark, tab server); ChatModel only carries them out. ChatFilterTests drives it through a small settings model. - A seeded entry whose tab was deleted never gets a rule turned on: a rule the manifest gains, or one re-added after the player deleted the rules, is added off. Tab listing skips a tab only an inactive server's rule fills. - Owned rules pair with declared ones by content (Global-room flag, then when/action/mode/pattern, then leftovers), never by position, so a reorder or delete no longer moves on/off or colour to another rule. Reclaim uses the same pairing. - Settings count as ready only after a successful read (or no file); a failed read is retried every 2 s, the unreadable copy kept once. - Export leaves out server rules and server tabs; Import makes every imported rule the player's (no owner, server or globalRoom). - Both rule editors lock pattern, mode, when, action, tab, move and delete on a server rule; on/off and colour stay live, with a note. - No adopt-by-name: a taken name seeds " ()" instead, and tabServers is written only for a tab the plugin made. Reclaim requires the entry's name, its clash name, or a tab holding only the matched rules. AddCustomTab checks hidden tabs. - Global-room discovery re-reads the entries and active servers under the lock. The manifest parser rejects a bad when or mode, and keeps a pattern's spaces. Co-Authored-By: Claude Opus 5.5 --- .../ImGui/Panels/ChatFiltersFace.cs | 23 +- src/RynthCore.Engine/UI/Data/ChatData.cs | 293 ++++++++-------- .../UI/Data/ChatServerTabs.cs | 290 +++++++++++++--- .../UI/Panels/RynthChatFiltersPanel.cs | 23 +- .../UI/Sections/SectionManifest.cs | 36 +- .../UI/Sections/SectionRegistry.cs | 6 +- tools/ChatFilterTests/Program.cs | 324 ++++++++++++++---- tools/SectionsTests/Program.cs | 21 +- 8 files changed, 726 insertions(+), 290 deletions(-) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index ce4a8e5..79069d7 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -282,11 +282,14 @@ internal sealed class ChatFiltersFace : IImGuiPanel const float btn = 22; float x = p.X + 42; + // A server plugin's rule (ChatModel.ApplyServerTabs rewrites it from the manifest every + // second): only on/off and the colour are the player's, so everything else is locked. + bool locked = r.Owner.Length > 0; int modeIdx = (int)r.Mode; string modeText = ChatRuleMatching.Labels[modeIdx] + Caret; float modeW = ButtonWidth(ChatRuleMatching.Labels[2] + Caret); // the widest, so patterns line up ChatFilterRule moded = r; - if (Button("##mode", modeText, new Vector2(x, p.Y), new Vector2(modeW, rowH), Text, BtnFill, leftAlign: true)) + if (Button("##mode", modeText, new Vector2(x, p.Y), new Vector2(modeW, rowH), Text, BtnFill, enabled: !locked, leftAlign: true)) _picker.Open(new Vector2(x, p.Y + rowH + 2), ChatRuleMatching.Labels, modeIdx, k => { moded.Mode = (ChatMatchMode)k; @@ -296,12 +299,14 @@ internal sealed class ChatFiltersFace : IImGuiPanel SafeImGui.SetItemTooltip(ModeHelp[modeIdx]); x += modeW + 4; float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x); - if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, ModeHints[modeIdx], out bool patActive)) + if (locked) ImGuiNET.ImGui.BeginDisabled(); + if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, ModeHints[modeIdx], out bool patActive) && !locked) { r.Pattern = Utf8(b.Pattern); r.Recompile(); ChatModel.FiltersChanged(); } + if (locked) ImGuiNET.ImGui.EndDisabled(); b.Active = patActive; if (r.Invalid && r.Pattern.Length > 0) dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Red, 3); @@ -309,17 +314,17 @@ internal sealed class ChatFiltersFace : IImGuiPanel dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Amber, 3); x += patW + 4; ChatFilterRule rule = r; - if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i > 0)) + if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i > 0 && !locked)) edit = () => ChatModel.MoveFilter(rule, -1); ImGuiNET.ImGui.SetItemTooltip("Move up (runs earlier)"); x += btn + 2; - if (IconButton("##down", PhosphorIcons.ArrowDown, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i < rules.Length - 1)) + if (IconButton("##down", PhosphorIcons.ArrowDown, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i < rules.Length - 1 && !locked)) edit = () => ChatModel.MoveFilter(rule, +1); ImGuiNET.ImGui.SetItemTooltip("Move down (runs later)"); x += btn + 2; - if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x, p.Y), new Vector2(btn, rowH), Red, BtnFill)) + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x, p.Y), new Vector2(btn, rowH), Red, BtnFill, !locked)) edit = () => ChatModel.EditFilters(list => list.Remove(rule)); - ImGuiNET.ImGui.SetItemTooltip("Delete this rule"); + ImGuiNET.ImGui.SetItemTooltip(locked ? "A server rule: turn it off instead (its plugin keeps it)" : "Delete this rule"); // Row 2 (wraps when narrow): When, action, tab, colour mode, swatch. float left = p.X + 42, right = card.X + rowW - 4; @@ -327,14 +332,14 @@ internal sealed class ChatFiltersFace : IImGuiPanel string whenText = "When: " + ChatModel.ConditionLabel(r.When) + Caret; Vector2 wp = flow.Place(Math.Min(ButtonWidth(whenText), 240)); - if (Button("##when", whenText, wp, new Vector2(Math.Min(ButtonWidth(whenText), 240), rowH), Text, BtnFill, leftAlign: true)) + if (Button("##when", whenText, wp, new Vector2(Math.Min(ButtonWidth(whenText), 240), rowH), Text, BtnFill, enabled: !locked, leftAlign: true)) OpenWhenPicker(rule, wp); ImGuiNET.ImGui.SetItemTooltip("Only lines from this channel or chat type (Any line: every line)"); int action = (int)r.Action; string actText = ActionLabels[action] + Caret; Vector2 aPos = flow.Place(ButtonWidth(actText)); - if (Button("##act", actText, aPos, new Vector2(ButtonWidth(actText), rowH), Text, BtnFill)) + if (Button("##act", actText, aPos, new Vector2(ButtonWidth(actText), rowH), Text, BtnFill, enabled: !locked)) _picker.Open(aPos + new Vector2(0, rowH + 2), ActionLabels, action, k => { rule.Action = (ChatRuleAction)k; @@ -348,7 +353,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel bool noTab = r.Tab.Length == 0; string tabText = (noTab ? "pick a tab" : r.Tab) + Caret; Vector2 tPos = flow.Place(ButtonWidth(tabText)); - if (Button("##tab", tabText, tPos, new Vector2(ButtonWidth(tabText), rowH), noTab ? Amber : Teal, BtnFill)) + if (Button("##tab", tabText, tPos, new Vector2(ButtonWidth(tabText), rowH), noTab ? Amber : Teal, BtnFill, enabled: !locked)) OpenTabPicker(rule, tPos); ImGuiNET.ImGui.SetItemTooltip("The tab it goes to (pick \"New tab…\" to make one)"); } diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 3874098..b84d41c 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -481,14 +481,9 @@ internal static class ChatModel private static volatile string[] _activeServers = Array.Empty(); private static volatile SectionChatTabDecl[] _tabDecls = Array.Empty(); - private static Dictionary NewMap(IDictionary? from = null) - { - var map = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (from != null) - foreach (var kv in from) - if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value)) map[kv.Key.Trim()] = kv.Value.Trim(); - return map; - } + private static volatile IReadOnlyDictionary _serverNames = ChatServerTabs.NewMap(); // id -> display name + + private static Dictionary NewMap(IEnumerable>? from = null) => ChatServerTabs.NewMap(from); /// The ids of the servers active now (SectionRegistry's verdicts). Any thread; never changed in place. public static string[] ActiveServers => _activeServers; @@ -664,24 +659,11 @@ internal static class ChatModel /// AllTabs, or with null every tab including those of inactive /// servers (a tab named by "tabServers" shows only while its server is active). /// - private static string[] BuildTabs(string[]? active) - { - Dictionary tabServers = Volatile.Read(ref _tabServers); - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var tabs = new List(); - void Add(string t) - { - if (active != null && !IsBaseTab(t) && tabServers.TryGetValue(t, out string? server) - && !ChatRouter.ServerIn(active, server)) return; - if (seen.Add(t)) tabs.Add(t); - } - foreach (string t in BaseTabs) Add(t); - foreach (string t in Volatile.Read(ref _customTabs)) Add(t); - foreach (ChatFilterRule rule in Filters) - if (rule.Enabled && rule.Routes && rule.Tab.Length > 0) Add(rule.Tab); - foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs()) Add(t); - return tabs.ToArray(); - } + private static string[] BuildTabs(string[]? active) => BuildTabs(active, Filters); + + private static string[] BuildTabs(string[]? active, IEnumerable rules) => + ChatServerTabs.ListTabs(BaseTabs, Volatile.Read(ref _customTabs), rules, + RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs(), Volatile.Read(ref _tabServers), active); /// Is a tab at all, shown or not (its server may be inactive)? private static bool TabExists(string tab) => BuildTabs(null).Contains(tab, StringComparer.OrdinalIgnoreCase); @@ -713,7 +695,9 @@ internal static class ChatModel { name = name.Trim(); if (name.Length == 0) return null; - string? existing = AllTabs().FirstOrDefault(t => string.Equals(t, name, StringComparison.OrdinalIgnoreCase)); + // Every tab, also one hidden because its server is not active (as RenameCustomTab), or a + // second tab of the same name would be made beside it. + string? existing = BuildTabs(null).FirstOrDefault(t => string.Equals(t, name, StringComparison.OrdinalIgnoreCase)); if (existing == null || !IsBaseTab(existing)) EnsureCustomTab(existing ?? name); if (select) ActiveChannel = existing ?? name; SaveSettings(); @@ -749,19 +733,14 @@ internal static class ChatModel if (!tabs.Contains(newName)) tabs = tabs.Append(newName).ToArray(); Volatile.Write(ref _customTabs, tabs); // A server's tab stays that server's, and a pinned tab stays pinned in its place. - if (_tabServers.TryGetValue(tab, out string? server)) - { - Dictionary map = NewMap(_tabServers); - map.Remove(tab); - map[newName] = server; - Volatile.Write(ref _tabServers, map); - } - Volatile.Write(ref _pinnedTabs, - _pinnedTabs.Select(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase) ? newName : t).ToArray()); + (Dictionary servers, string[] pins) = ChatServerTabs.RenameTab(_tabServers, _pinnedTabs, tab, newName); + Volatile.Write(ref _tabServers, servers); + Volatile.Write(ref _pinnedTabs, pins); + // Inside the lock with the tab, so ApplyServerTabs sees the rename whole (its rules follow the tab). + foreach (ChatFilterRule rule in _filters) + if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) + rule.Tab = newName; } - foreach (ChatFilterRule rule in Filters) - if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) - rule.Tab = newName; foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All) if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase)) preset.Tab = newName; @@ -781,14 +760,9 @@ internal static class ChatModel Volatile.Write(ref _customTabs, _customTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); // A server's tab: its seed mark stays (seededTabs), so ApplyServerTabs never re-creates it. - if (_tabServers.ContainsKey(tab)) - { - Dictionary map = NewMap(_tabServers); - map.Remove(tab); - Volatile.Write(ref _tabServers, map); - } - Volatile.Write(ref _pinnedTabs, - _pinnedTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); + (Dictionary servers, string[] pins) = ChatServerTabs.DeleteTab(_tabServers, _pinnedTabs, tab); + Volatile.Write(ref _tabServers, servers); + Volatile.Write(ref _pinnedTabs, pins); // Inside the lock with the tab's removal, so ApplyServerTabs never sees the tab gone // while its rules are still on (it would take the tab for an existing one). foreach (ChatFilterRule rule in _filters) @@ -824,19 +798,26 @@ internal static class ChatModel // reference) and once per AllTabs build, never per line, and it is published BEFORE the version // bump that announces it, so a reader that sees the new version also sees the new set. // + // The pump re-reads the entries and the active set inside the lock, so it never applies a + // snapshot older than one Rebuild already applied. + // // No-op. Rebuild calls ApplyServerTabs every second, so in the steady state it must neither save - // nor bump the version. Every write is guarded by a comparison with what is already there: the - // active set (as a sorted set), each owned rule (ChatServerTabs.SameRule on canonical forms, - // both sides through BuildRule and ToDto), the tab, the pin, the seed mark and the tab's server - // (each added only when missing, never overwritten). Only a write sets "changed", and only - // "changed" publishes, bumps and saves (EditFiltersIfChanged). + // nor bump the version. The active set is replaced only when it differs as a sorted set. For an + // entry, ChatServerTabs.Apply returns edits only for what differs: a paired rule only when + // SameRule fails on canonical forms (both sides through BuildRule and ToDto), a rule added or + // removed only when pairing leaves one over, and the tab, pin, seed mark and tab server only + // when missing (never overwritten), all of which the first apply fills. No edits: "changed" + // stays false, and only "changed" publishes, bumps and saves (EditFiltersIfChanged). + // tools/ChatFilterTests: Apply_SecondApplyIsANoOp. /// - /// Render thread (SectionRegistry.Rebuild): every manifest's chat tab entries and the ids of the - /// active servers. Publishes the active set (re-routing and re-listing tabs when it moved) and - /// applies the entries of active servers. Cheap and silent when nothing changed. + /// Render thread (SectionRegistry.Rebuild): every manifest's chat tab entries, the ids of the + /// active servers, and the servers' display names (id -> name; a clash-named tab uses it). + /// Publishes the active set (re-routing and re-listing tabs when it moved) and applies the + /// entries of active servers. Cheap and silent when nothing changed. /// - public static void ApplyServerTabs(IReadOnlyList decls, IReadOnlyCollection activeServers) + public static void ApplyServerTabs(IReadOnlyList decls, IReadOnlyCollection activeServers, + IReadOnlyDictionary? serverNames = null) { string[] active = activeServers.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) .Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(s => s, StringComparer.OrdinalIgnoreCase).ToArray(); @@ -845,6 +826,7 @@ internal static class ChatModel _activeServers = active; // before the bump: see the threading note above Interlocked.Increment(ref _filtersVersion); } + if (serverNames != null && !SameMap(serverNames, _serverNames)) _serverNames = NewMap(serverNames); // One entry per owner key (two plugins declaring the same one would rewrite each other's rules every second). var unique = new List(decls.Count); @@ -853,7 +835,8 @@ internal static class ChatModel unique.Add(d); if (!SameDecls(unique, _tabDecls)) _tabDecls = unique.ToArray(); - // Not before the settings file is read: seeding the empty defaults would save them over it. + // Not before the settings file was read successfully: seeding the empty defaults (or what + // survived a half-written file) would save them over the player's rules. if (!_settingsReady) return; string[] now = _activeServers; if (!unique.Exists(d => ChatRouter.ServerIn(now, d.Server))) return; // nothing to apply: no lock @@ -873,28 +856,21 @@ internal static class ChatModel /// internal static void PumpDiscoverGlobalRoom(IReadOnlyList added) { - SectionChatTabDecl[] decls = _tabDecls; - if (decls.Length == 0 || added.Count == 0 || !_settingsReady) return; - string[] active = _activeServers; - bool any = false; - foreach (SectionChatTabDecl d in decls) - if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(r => r.GlobalRoom)) { any = true; break; } - if (!any) return; + if (added.Count == 0 || !_settingsReady) return; + if (!WantsRoom(_tabDecls, _activeServers, Volatile.Read(ref _globalRooms), null)) return; // no lock, no regex string? room = null; foreach (ChatLine line in added) if (line.Text.Length > 0 && line.Text[0] == '[' && ChatServerTabs.DiscoverRoom(line.Text) is { } r) room = r; if (room == null) return; string seen = room; - Dictionary rooms = Volatile.Read(ref _globalRooms); - bool news = false; - foreach (SectionChatTabDecl d in decls) - if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(x => x.GlobalRoom) - && !(rooms.TryGetValue(d.Server, out string? have) && have == seen)) { news = true; break; } - if (!news) return; // the usual case on a room line: the room is already known, no lock + if (!WantsRoom(_tabDecls, _activeServers, Volatile.Read(ref _globalRooms), seen)) return; // the usual case: known EditFiltersIfChanged(list => { + // Read again under the lock: Rebuild may have published new entries or servers meanwhile. + SectionChatTabDecl[] decls = _tabDecls; + string[] active = _activeServers; bool changed = false; Dictionary map = NewMap(_globalRooms); foreach (SectionChatTabDecl d in decls) @@ -913,77 +889,59 @@ internal static class ChatModel }); } - /// One entry, under EditLock: plans it (ChatServerTabs.Plan) and writes only what differs. True when it wrote. - private static bool ApplyServerTab(List list, SectionChatTabDecl d) + /// Does an active entry with a Global-room rule store another room than (null: any entry at all)? + private static bool WantsRoom(SectionChatTabDecl[] decls, string[] active, Dictionary rooms, string? room) { - string key = ChatServerTabs.OwnerKey(d); - var ownedAt = new List(); - for (int i = 0; i < list.Count; i++) - if (string.Equals(list[i].Owner, key, StringComparison.OrdinalIgnoreCase)) ownedAt.Add(i); - if (ownedAt.Count == 0 && d.Rules.Length > 0 && ChatServerTabs.Reclaim(d, list.Select(ToDto).ToArray()) is { } found) - ownedAt.AddRange(found); // an older engine dropped "owner": these are ours, not a second set - - // The tabs there are: created ones, and those an enabled Move/Copy rule fills (AllTabs, unfiltered). - var existing = new List(BaseTabs); - existing.AddRange(_customTabs); - foreach (ChatFilterRule rule in list) - if (rule.Enabled && rule.Routes && rule.Tab.Length > 0) existing.Add(rule.Tab); - string? room = _globalRooms.TryGetValue(d.Server, out string? r) ? r : null; - var state = new ChatServerTabs.SeedState(_seededTabs, existing, ownedAt.Select(i => ToDto(list[i])).ToArray()); - ChatServerTabs.SeedPlan plan = ChatServerTabs.Plan(d, state, room); - - bool changed = false; - int both = Math.Min(ownedAt.Count, plan.Rules.Length); - for (int i = 0; i < both; i++) changed |= RefreshRule(list[ownedAt[i]], plan.Rules[i]); - if (plan.Rules.Length > both) - { - // New rules go after the entry's last rule, or at the end (as a rule the player adds). - int at = ownedAt.Count > 0 ? ownedAt.Max() + 1 : list.Count; - for (int i = both; i < plan.Rules.Length; i++) list.Insert(at++, FromDto(plan.Rules[i])); - changed = true; - } - else if (ownedAt.Count > both) - { - foreach (int i in ownedAt.Skip(both).OrderByDescending(i => i)) list.RemoveAt(i); - changed = true; - } - - string tab = plan.TabName; - bool baseTab = IsBaseTab(tab); - if (plan.CreateTab && !baseTab && !_customTabs.Contains(tab, StringComparer.OrdinalIgnoreCase)) - { - Volatile.Write(ref _customTabs, _customTabs.Append(tab).ToArray()); - changed = true; - } - if (plan.Pin && !_pinnedTabs.Contains(tab, StringComparer.OrdinalIgnoreCase)) - { - Volatile.Write(ref _pinnedTabs, _pinnedTabs.Append(tab).ToArray()); - changed = true; - } - if (plan.MarkSeeded && !_seededTabs.Contains(key, StringComparer.OrdinalIgnoreCase)) - { - Volatile.Write(ref _seededTabs, _seededTabs.Append(key).ToArray()); - changed = true; - } - // The tab is the server's while it exists (a deleted one gets no entry back). Added when - // missing, never overwritten, so two entries naming one tab can't take turns. - bool tabThere = plan.CreateTab || existing.Contains(tab, StringComparer.OrdinalIgnoreCase); - if (tabThere && !baseTab && !_tabServers.ContainsKey(tab)) - { - Dictionary map = NewMap(_tabServers); - map[tab] = d.Server; - Volatile.Write(ref _tabServers, map); - changed = true; - } - if (changed) RynthLog.UI($"ChatModel: server tab \"{tab}\" ({key}) updated from the {d.Server} manifest{(plan.CreateTab ? " (created)" : "")}."); - return changed; + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(x => x.GlobalRoom) + && (room == null || !(rooms.TryGetValue(d.Server, out string? have) && have == room))) return true; + return false; } - /// Makes what Plan wants, field by field; false (nothing written) when it already is. - private static bool RefreshRule(ChatFilterRule rule, RynthChatFilterDto want) + /// + /// One entry, under EditLock: ChatServerTabs.Apply decides, this only carries out its edits. + /// True when it wrote anything. + /// + private static bool ApplyServerTab(List list, SectionChatTabDecl d) + { + RynthChatFilterDto[] rules = list.Select(ToDto).ToArray(); + string? room = _globalRooms.TryGetValue(d.Server, out string? r) ? r : null; + string name = _serverNames.TryGetValue(d.Server, out string? n) ? n : d.Server; + var state = new ChatServerTabs.TabState(_seededTabs, _customTabs, BuildTabs(null, list), _tabServers, + _pinnedTabs, rules, room, name); + ChatServerTabs.TabEdits e = ChatServerTabs.Apply(d, state, w => ToDto(BuildRule(w))); + if (!e.Changed) return false; + + // Updates first (by object, so the indexes stay right), then removals (highest first), then + // the new rules after the entry's last one, or at the end (as a rule the player adds). + ChatFilterRule[] before = list.ToArray(); + foreach ((int index, RynthChatFilterDto want) in e.Updates) WriteRule(before[index], want); + int at = e.InsertAt; + foreach (int index in e.Removes) + { + list.Remove(before[index]); + if (index < e.InsertAt) at--; + } + foreach (RynthChatFilterDto want in e.Inserts) list.Insert(Math.Min(at++, list.Count), FromDto(want)); + + if (e.CreateTab != null && !IsBaseTab(e.CreateTab)) Volatile.Write(ref _customTabs, _customTabs.Append(e.CreateTab).ToArray()); + if (e.Pin != null) Volatile.Write(ref _pinnedTabs, _pinnedTabs.Append(e.Pin).ToArray()); + if (e.Seed != null) Volatile.Write(ref _seededTabs, _seededTabs.Append(e.Seed).ToArray()); + if (e.TabServer != null && !IsBaseTab(e.TabServer)) + { + Dictionary map = NewMap(_tabServers); + map[e.TabServer] = d.Server; + Volatile.Write(ref _tabServers, map); + } + RynthLog.UI($"ChatModel: server tab \"{e.TabName}\" ({ChatServerTabs.OwnerKey(d)}) updated from the {d.Server} manifest" + + $"{(e.CreateTab != null ? " (created)" : "")}: {e.Updates.Count} changed, {e.Inserts.Length} added, {e.Removes.Length} removed."); + return true; + } + + /// Makes what Apply wants, field by field; its colour is the player's and stays. + private static void WriteRule(ChatFilterRule rule, RynthChatFilterDto want) { ChatFilterRule w = BuildRule(want); // the canonical form, not compiled - if (ChatServerTabs.SameRule(ToDto(w), ToDto(rule))) return false; rule.Owner = w.Owner; rule.Server = w.Server; rule.Tab = w.Tab; @@ -997,7 +955,14 @@ internal static class ChatModel rule.Pattern = w.Pattern; rule.Recompile(); } - return true; // its colour is the player's and stays + } + + private static bool SameMap(IReadOnlyDictionary a, IReadOnlyDictionary b) + { + if (a.Count != b.Count) return false; + foreach (var kv in a) + if (!b.TryGetValue(kv.Key, out string? v) || !string.Equals(v, kv.Value, StringComparison.Ordinal)) return false; + return true; } private static bool SameServers(string[] a, string[] b) @@ -1125,8 +1090,9 @@ internal static class ChatModel var dto = new RynthChatRuleSetDto { Format = RynthChatRuleSetDto.FormatName, - Tabs = Volatile.Read(ref _customTabs), - Rules = Filters.Select(ToDto).ToArray(), + // The player's own: a server's tab and rules come from its manifest (ChatServerTabs.ExportRules). + Tabs = ChatServerTabs.ExportTabs(Volatile.Read(ref _customTabs), Volatile.Read(ref _tabServers)), + Rules = ChatServerTabs.ExportRules(Filters.Select(ToDto)), }; return JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatRuleSetDto); } @@ -1161,7 +1127,9 @@ internal static class ChatModel } catch (JsonException ex) { return "Not a rule set: " + ex.Message; } if (rules == null || rules.Length == 0) return "No rules found in the clipboard."; - var imported = rules.Select(FromDto).ToList(); + // Imported rules are the player's, whatever the file says (a whole settings file carries + // server rules): no owner, every server, a fixed pattern. + var imported = rules.Select(ChatServerTabs.AsPlayerRule).Select(FromDto).ToList(); foreach (string t in tabs ?? Array.Empty()) if (!string.IsNullOrWhiteSpace(t)) EnsureCustomTab(t.Trim()); foreach (ChatFilterRule r in imported) @@ -1671,8 +1639,9 @@ internal static class ChatModel public const int SettingsVersion = 2; private static readonly object SaveLock = new(); private static int _settingsLoaded; - // Set once the first load has finished (_settingsLoaded is set as it starts). ApplyServerTabs - // waits for it: seeding into the empty defaults would save them over the shared file. + // Set once the file was read successfully, or found absent (_settingsLoaded is set as the first + // read starts, whatever its outcome). ApplyServerTabs waits for it: seeding into the defaults + // left by a failed read would save them over the player's rules in the shared file. private static volatile bool _settingsReady; private static string SettingsPath => @@ -1682,10 +1651,13 @@ internal static class ChatModel public static void EnsureSettingsLoaded() { if (Interlocked.Exchange(ref _settingsLoaded, 1) != 0) return; - try { LoadSettings(); } - finally { _settingsReady = true; } + // Ready only when the file was read (or there is none): after a failed read the defaults in + // memory are not the player's settings. PollSettingsFile tries again every 2 s. + _settingsReady = LoadSettings(); } + private static long _nextLoadRetryMs; + // Every client shares rynthchat_settings.json and saves its whole state, so a client that // never re-read the file wrote back stale presets/rules over another client's change (last // writer won; a ticked standard filter came back off). Each client now re-reads the file @@ -1702,6 +1674,19 @@ internal static class ChatModel if (Volatile.Read(ref _settingsLoaded) == 0) return; try { + if (!_settingsReady) + { + // The first read failed (a half-written or broken file): try it again every 2 s. + long now = Environment.TickCount64; + if (now < _nextLoadRetryMs) return; + _nextLoadRetryMs = now + 2000; + if (LoadSettings()) + { + _settingsReady = true; + RynthLog.UI("ChatModel: rynthchat_settings.json read on a retry."); + } + return; + } string? json = SettingsWatch.Changed(Environment.TickCount64, SettingsPath); // null: nobody else saved if (json == null) return; RynthLog.UI("ChatModel: rynthchat_settings.json changed (another client saved it); reloading the rules and filters."); @@ -1710,31 +1695,37 @@ internal static class ChatModel catch (Exception ex) { RynthLog.UI($"ChatModel: settings re-read failed ({ex.GetType().Name}: {ex.Message})."); } } - private static void LoadSettings() + private static bool _keptUnreadable; + + /// True when there is no file, or it was read; false when it couldn't be read. + private static bool LoadSettings() { try { string path = SettingsPath; - if (!File.Exists(path)) return; + if (!File.Exists(path)) return true; SettingsWatch.Seen(File.GetLastWriteTimeUtc(path)); - LoadSettings(File.ReadAllText(path), reload: false); + return LoadSettings(File.ReadAllText(path), reload: false); } catch (Exception ex) { RynthLog.UI($"ChatModel: settings load failed: {ex.Message}"); - KeepUnreadable(); + // One copy per run: the retry every 2 s must not leave a copy each time. + if (!_keptUnreadable) { _keptUnreadable = true; KeepUnreadable(); } + return false; } } /// Another client changed the file: presets it doesn't list go off, and /// this client's selected tab is kept. - private static void LoadSettings(string json, bool reload) + /// True when the file was read (a reload's unreadable file is skipped, false). + private static bool LoadSettings(string json, bool reload) { try { string path = SettingsPath; var dto = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatSettingsDto); - if (dto == null) return; + if (dto == null) return false; if (dto.Version < SettingsVersion) { @@ -1826,11 +1817,13 @@ internal static class ChatModel ActiveChannel = dto.ActiveChannel; else if (reload && !everyTab.Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = "All"; // the tab this client was on was removed elsewhere + return true; } catch (Exception ex) when (reload) { // A half-written or broken file from another client: keep what this client has. RynthLog.UI($"ChatModel: settings re-read skipped (unreadable: {ex.Message})."); + return false; } } diff --git a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs index 490115a..470d2d6 100644 --- a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -3,16 +3,18 @@ // Server default chat tabs (2026-11-15): what a server plugin's "chatTabs" // manifest entry turns into in RynthChat's settings. Pure decisions only (no // ChatModel, ImGui or SectionRegistry): ChatModel.ApplyServerTabs gathers the -// state, calls Plan, and applies the result; tools/ChatFilterTests compiles -// this file as is. +// state, calls Apply, and carries out the edits it returns; tools/ChatFilterTests +// compiles this file as is. // // An entry's rules are owned by it ("owner" = "/"), so a -// refresh rewrites only those rules and a renamed tab keeps them. A tab is -// seeded once (seededTabs); a tab the player deleted stays deleted, because -// deleting disables its rules and the seed mark remains. An older engine that -// rewrites the shared settings file strips the new fields: the seed then -// recognises its own rules by owner, or an existing tab of the same name, and -// adopts it instead of creating a second one. +// refresh rewrites only those rules, paired with the declared ones by content +// (never by position), and a renamed tab keeps them. A tab is seeded once +// (seededTabs); a tab the player deleted stays deleted: deleting turns its rules +// off, the seed mark remains, and no rule of a deleted tab is ever turned on +// again. A tab of the declared name that is the player's is never taken over: +// the entry seeds " ()" instead. An older engine that rewrites the +// shared settings file strips "owner": Reclaim finds those rules again by +// content, so no second set is added. // ============================================================================ using System; @@ -25,11 +27,36 @@ namespace RynthCore.Engine.UI.Data; internal static class ChatServerTabs { - /// What Plan needs to know about the current settings. - internal sealed record SeedState(IReadOnlyCollection Seeded, IReadOnlyCollection ExistingTabs, IReadOnlyList OwnedRules); + /// The settings Apply decides from. Rules are every rule in list order, as their JSON form. + internal sealed record TabState( + IReadOnlyCollection Seeded, + IReadOnlyCollection CustomTabs, + IReadOnlyCollection AllTabs, + IReadOnlyDictionary TabServers, + IReadOnlyCollection Pinned, + IReadOnlyList Rules, + string? Room, + string ServerName); - /// What to do: create/pin the tab, mark it seeded, and the full replacement set of this owner's rules. - internal sealed record SeedPlan(bool CreateTab, string TabName, bool Pin, bool MarkSeeded, RynthChatFilterDto[] Rules); + /// + /// What to change for one entry. Updates and Removes index TabState.Rules; Inserts go in at + /// InsertAt (an index into TabState.Rules, before any removal). The string fields are null + /// when there is nothing to do: CreateTab / Pin / TabServer name the tab, Seed the owner key. + /// + internal sealed record TabEdits( + string TabName, + IReadOnlyList<(int Index, RynthChatFilterDto Rule)> Updates, + int InsertAt, + RynthChatFilterDto[] Inserts, + int[] Removes, + string? CreateTab, + string? Pin, + string? Seed, + string? TabServer) + { + public bool Changed => Updates.Count > 0 || Inserts.Length > 0 || Removes.Length > 0 + || CreateTab != null || Pin != null || Seed != null || TabServer != null; + } // A remote speaker's room line: [Trade] Ann@coldeve says, "..." (optionally Ann@coldeve (Discord)). // Anchored at the line start and the speaker may not contain a quote, so a tell or a say that merely @@ -38,6 +65,8 @@ internal static class ChatServerTabs "^\\[(General|Trade|LFG|Roleplay)\\] [^\"]+@[a-z0-9-]+( \\(discord\\))? says, \"", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.NonBacktracking); + private static readonly string[] Rooms = { "General", "Trade", "LFG", "Roleplay" }; + /// The owner key of an entry: "server/id". internal static string OwnerKey(SectionChatTabDecl d) => d.Server + "/" + d.Id; @@ -60,25 +89,52 @@ internal static class ChatServerTabs /// The "startswith" pattern a Global-room rule uses for . internal static string GlobalPattern(string room) => "[" + room + "] "; - internal static SeedPlan Plan(SectionChatTabDecl d, SeedState s, string? discoveredRoom) + /// The name an entry seeds under when its own name is taken: "Network (DreamWeave)". + internal static string ClashName(SectionChatTabDecl d, string serverName) => + d.Name + " (" + (string.IsNullOrWhiteSpace(serverName) ? d.Server : serverName.Trim()) + ")"; + + /// + /// Everything to change for entry . turns a + /// rule into the form the settings hold (ChatModel: through its rule and back), so that a + /// rule already as wanted compares equal; identity when omitted. + /// + internal static TabEdits Apply(SectionChatTabDecl d, TabState s, Func? canonical = null) { + canonical ??= r => r; string key = OwnerKey(d); - bool seeded = s.Seeded.Contains(key, StringComparer.OrdinalIgnoreCase); - bool hasOwned = s.OwnedRules.Count > 0; - bool tabNamed = s.ExistingTabs.Contains(d.Name, StringComparer.OrdinalIgnoreCase); + bool seeded = Has(s.Seeded, key); + string clashBase = ClashName(d, s.ServerName); - // Follow a rename: the owned rules carry the tab's current name. - string tabName = d.Name; - foreach (RynthChatFilterDto owned in s.OwnedRules) - if (!string.IsNullOrEmpty(owned.Tab)) { tabName = owned.Tab!; break; } + var owned = new List(); + for (int i = 0; i < s.Rules.Count; i++) + if (string.Equals(s.Rules[i].Owner, key, StringComparison.OrdinalIgnoreCase)) owned.Add(i); + bool reclaimed = false; + if (owned.Count == 0 && Reclaim(d, s.Rules, s.ServerName) is { } found) + { + owned.AddRange(found); + reclaimed = true; + } + int[] pair = Pair(d, s.Rules, owned, leftovers: !reclaimed); - bool create = !seeded && !hasOwned && !tabNamed; - string room = discoveredRoom ?? d.GlobalRoomFallback; - var rules = new RynthChatFilterDto[d.Rules.Length]; - for (int i = 0; i < rules.Length; i++) + // The tab: the one the entry's rules fill (follows a rename), else the declared name; a + // fresh seed never takes over a tab that is already there (a player's, or a base tab). + string? ownTab = null; + foreach (int c in pair) if (c >= 0 && !string.IsNullOrEmpty(s.Rules[c].Tab)) { ownTab = s.Rules[c].Tab; break; } + if (ownTab == null) + foreach (int c in owned) if (!string.IsNullOrEmpty(s.Rules[c].Tab)) { ownTab = s.Rules[c].Tab; break; } + bool fresh = !seeded && owned.Count == 0; + string tabName = ownTab ?? (fresh ? FreeName(d.Name, clashBase, s.AllTabs) : d.Name); + bool tabThere = Has(s.AllTabs, tabName); + // Seeded (or adopted) but its tab is gone: the player deleted it. Nothing turns on again. + bool deleted = !fresh && !tabThere; + + string room = s.Room ?? d.GlobalRoomFallback; + var updates = new List<(int, RynthChatFilterDto)>(); + var inserts = new List(); + for (int i = 0; i < d.Rules.Length; i++) { SectionChatRuleDecl r = d.Rules[i]; - rules[i] = new RynthChatFilterDto + var want = new RynthChatFilterDto { Owner = key, Server = d.Server, @@ -88,19 +144,70 @@ internal static class ChatServerTabs Mode = r.GlobalRoom ? "startswith" : r.Mode, Pattern = r.GlobalRoom ? GlobalPattern(room) : r.Pattern, GlobalRoom = r.GlobalRoom ? true : null, - Enabled = i < s.OwnedRules.Count ? s.OwnedRules[i].Enabled : true, + // A rule paired with one already there keeps its on/off; a new one is on, unless + // the tab was deleted (a manifest that gains a rule, or the player deleted the rules). + Enabled = pair[i] >= 0 ? s.Rules[pair[i]].Enabled : !deleted, }; + if (pair[i] < 0) inserts.Add(want); + else if (!SameRule(canonical(want), s.Rules[pair[i]])) updates.Add((pair[i], want)); } - return new SeedPlan(create, tabName, create && d.Pinned, !seeded, rules); + int[] removes = owned.Where(c => Array.IndexOf(pair, c) < 0).OrderByDescending(c => c).ToArray(); + int insertAt = owned.Count > 0 ? owned.Max() + 1 : s.Rules.Count; + + // The tab is the server's only when the plugin made it: created now, or found again by + // Reclaim (which accepts a tab only when it is the entry's name or holds only its rules). + bool ours = fresh || (reclaimed && tabThere); + return new TabEdits( + tabName, updates, insertAt, inserts.ToArray(), removes, + CreateTab: fresh && !Has(s.CustomTabs, tabName) ? tabName : null, + Pin: fresh && d.Pinned && !Has(s.Pinned, tabName) ? tabName : null, + Seed: seeded ? null : key, + TabServer: ours && !s.TabServers.ContainsKey(tabName) ? tabName : null); + } + + private static string FreeName(string name, string clashBase, IReadOnlyCollection tabs) + { + if (!Has(tabs, name)) return name; + if (!Has(tabs, clashBase)) return clashBase; + for (int n = 2; ; n++) + if (!Has(tabs, clashBase + " " + n)) return clashBase + " " + n; } /// - /// True when a stored rule already is what Plan wants, on every field Plan sets (owner, + /// Pairs each declared rule with one of (indexes into + /// ) by content, never by position: a Global-room rule with the rule + /// marked globalRoom (or, stripped of the mark, one that starts with "[room] "), then each + /// other rule with one of the same when, action, mode and pattern, then (with + /// ) what is left in order, so a rule the manifest changed keeps + /// its on/off. Returns a candidate index per declared rule, or -1. + /// + internal static int[] Pair(SectionChatTabDecl d, IReadOnlyList rules, IReadOnlyList candidates, bool leftovers) + { + var result = Enumerable.Repeat(-1, d.Rules.Length).ToArray(); + var used = new HashSet(); + int Take(Func fits) + { + foreach (int c in candidates.OrderBy(c => c)) + if (!used.Contains(c) && fits(rules[c])) { used.Add(c); return c; } + return -1; + } + for (int i = 0; i < d.Rules.Length; i++) + if (d.Rules[i].GlobalRoom) result[i] = Take(r => r.GlobalRoom == true); + for (int i = 0; i < d.Rules.Length; i++) + if (d.Rules[i].GlobalRoom && result[i] < 0) { SectionChatRuleDecl decl = d.Rules[i]; result[i] = Take(r => r.GlobalRoom != true && Matches(decl, r)); } + for (int i = 0; i < d.Rules.Length; i++) + if (!d.Rules[i].GlobalRoom) { SectionChatRuleDecl decl = d.Rules[i]; result[i] = Take(r => r.GlobalRoom != true && Matches(decl, r)); } + if (leftovers) + for (int i = 0; i < d.Rules.Length; i++) + if (result[i] < 0) result[i] = Take(_ => true); + return result; + } + + /// + /// True when a stored rule already is what Apply wants, on every field it sets (owner, /// server, tab, action, when, mode, pattern, globalRoom, enabled); colours are the player's - /// and are not compared. Both sides must come through the same rule-to-JSON conversion - /// (ChatModel compares canonical forms), so absent and empty mean the same here as well. - /// This is what keeps ChatModel.ApplyServerTabs, which runs every second, from saving - /// when nothing changed. + /// and are not compared. Absent and empty are the same. This is what keeps + /// ChatModel.ApplyServerTabs, which runs every second, from saving when nothing changed. /// internal static bool SameRule(RynthChatFilterDto want, RynthChatFilterDto have) => Same(want.Owner, have.Owner) && Same(want.Server, have.Server) && Same(want.Tab, have.Tab) @@ -113,42 +220,36 @@ internal static class ChatServerTabs private static bool Same(string? a, string? b) => string.Equals(a ?? "", b ?? "", StringComparison.Ordinal); - private static readonly string[] Rooms = { "General", "Trade", "LFG", "Roleplay" }; + private static bool Has(IEnumerable list, string item) => list.Contains(item, StringComparer.OrdinalIgnoreCase); /// /// An older engine rewrote the shared settings file and dropped "owner" from this entry's /// rules: finds them again among the ownerless rules, so a refresh rewrites them instead of - /// adding a second set (which would grow by one set per old-engine save). A rule matches a - /// declared one on action, when, mode and pattern; a GlobalRoom rule matches "[room] " - /// (Starts with) for any room. Every declared rule must be found, all in one tab (the - /// entry's name is tried first). Returns their indexes in , in + /// adding a second set (which would grow by one set per old-engine save). Every declared + /// rule must pair by content (Pair, no leftovers) with a rule of one tab, and that tab must + /// be one the entry would have made (its name, or its clash name) or hold no other rule, so + /// a player's own tab with look-alike rules is never taken. Returns the rules' indexes in /// declaration order, or null. /// - internal static int[]? Reclaim(SectionChatTabDecl d, IReadOnlyList rules) + internal static int[]? Reclaim(SectionChatTabDecl d, IReadOnlyList rules, string serverName = "") { if (d.Rules.Length == 0) return null; + string clashBase = ClashName(d, serverName); var tabs = new List { d.Name }; foreach (RynthChatFilterDto r in rules) - if (string.IsNullOrEmpty(r.Owner) && !string.IsNullOrEmpty(r.Tab) - && !tabs.Contains(r.Tab!, StringComparer.Ordinal)) tabs.Add(r.Tab!); + if (string.IsNullOrEmpty(r.Owner) && !string.IsNullOrEmpty(r.Tab) && !Has(tabs, r.Tab!)) tabs.Add(r.Tab!); foreach (string tab in tabs) { - var found = new int[d.Rules.Length]; - bool all = true; - for (int i = 0; i < d.Rules.Length && all; i++) - { - found[i] = -1; - for (int j = 0; j < rules.Count; j++) - { - RynthChatFilterDto r = rules[j]; - if (!string.IsNullOrEmpty(r.Owner) || !string.Equals(r.Tab, tab, StringComparison.Ordinal)) continue; - if (Array.IndexOf(found, j, 0, i) >= 0 || !Matches(d.Rules[i], r)) continue; - found[i] = j; - break; - } - all = found[i] >= 0; - } - if (all) return found; + var candidates = new List(); + for (int j = 0; j < rules.Count; j++) + if (string.IsNullOrEmpty(rules[j].Owner) && string.Equals(rules[j].Tab, tab, StringComparison.OrdinalIgnoreCase)) candidates.Add(j); + int[] found = Pair(d, rules, candidates, leftovers: false); + if (found.Any(c => c < 0)) continue; + bool entryName = string.Equals(tab, d.Name, StringComparison.OrdinalIgnoreCase) + || string.Equals(tab, clashBase, StringComparison.OrdinalIgnoreCase) + || tab.StartsWith(clashBase + " ", StringComparison.OrdinalIgnoreCase); + int inTab = rules.Count(r => string.Equals(r.Tab, tab, StringComparison.OrdinalIgnoreCase)); + if (entryName || inTab == found.Length) return found; } return null; } @@ -161,4 +262,81 @@ internal static class ChatServerTabs && Rooms.Any(room => Same(GlobalPattern(room), r.Pattern)); return ChatRuleMatching.Parse(decl.Mode) == ChatRuleMatching.Parse(r.Mode) && Same(decl.Pattern, r.Pattern); } + + // -- Tab bookkeeping shared by ChatModel and the tests -------------------------- + + /// A tab -> server (or server -> room) map that ignores case, from any map (blank entries dropped). + internal static Dictionary NewMap(IEnumerable>? from = null) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (from != null) + foreach (var kv in from) + if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value)) map[kv.Key.Trim()] = kv.Value.Trim(); + return map; + } + + /// + /// The tabs to list (AllTabs): base tabs, created tabs, tabs an enabled Move/Copy rule fills, + /// then . With set, a tab whose server + /// (tabServers) is not active is left out, and so is a tab only a server rule of an inactive + /// server fills; with it null, every tab. + /// + internal static string[] ListTabs(IReadOnlyList baseTabs, IEnumerable customTabs, IEnumerable rules, + IEnumerable presetTabs, IReadOnlyDictionary tabServers, string[]? active) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var tabs = new List(); + void Add(string t) + { + if (active != null && !Has(baseTabs, t) && tabServers.TryGetValue(t, out string? server) + && !ChatRouter.ServerIn(active, server)) return; + if (seen.Add(t)) tabs.Add(t); + } + foreach (string t in baseTabs) Add(t); + foreach (string t in customTabs) Add(t); + foreach (ChatFilterRule rule in rules) + if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 + && (active == null || ChatRouter.ServerIn(active, rule.Server))) Add(rule.Tab); + foreach (string t in presetTabs) Add(t); + return tabs.ToArray(); + } + + /// A tab renamed: its server entry and its pin (in its place) follow. + internal static (Dictionary TabServers, string[] Pins) RenameTab( + IReadOnlyDictionary tabServers, IEnumerable pins, string from, string to) + { + Dictionary map = NewMap(tabServers); + if (map.Remove(from, out string? server)) map[to] = server; + string[] pinned = pins.Select(t => string.Equals(t, from, StringComparison.OrdinalIgnoreCase) ? to : t) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + return (map, pinned); + } + + /// A tab deleted: its server entry and its pin go (the seed mark stays, elsewhere). + internal static (Dictionary TabServers, string[] Pins) DeleteTab( + IReadOnlyDictionary tabServers, IEnumerable pins, string tab) + { + Dictionary map = NewMap(tabServers); + map.Remove(tab); + return (map, pins.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); + } + + // -- Export / Import ------------------------------------------------------------- + + /// The player's rules only: a server's rules come from its manifest, not from a clipboard. + internal static RynthChatFilterDto[] ExportRules(IEnumerable rules) => + rules.Where(r => string.IsNullOrEmpty(r.Owner)).ToArray(); + + /// The created tabs without the servers' ones. + internal static string[] ExportTabs(IEnumerable tabs, IReadOnlyDictionary tabServers) => + tabs.Where(t => !tabServers.ContainsKey(t)).ToArray(); + + /// An imported rule is the player's: no owner, every server, a fixed pattern. + internal static RynthChatFilterDto AsPlayerRule(RynthChatFilterDto r) + { + r.Owner = null; + r.Server = null; + r.GlobalRoom = null; + return r; + } } diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs index 4588fba..1aff2e6 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs @@ -202,12 +202,31 @@ internal static class RynthChatFiltersPanel RebuildRows(); }; - rows.Children.Add(new StackPanel + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn }, - }); + }; + // A server plugin's rule (ChatModel.ApplyServerTabs rewrites it from the manifest every + // second): only on/off is the player's here, the rest is locked and says why. + if (r.Owner.Length > 0) + { + modeBtn.IsEnabled = patternBox.IsEnabled = tabBox.IsEnabled = false; + upBtn.IsEnabled = downBtn.IsEnabled = delBtn.IsEnabled = false; + string note = $"Server rule ({r.Server}, kept up to date by its plugin)." + + (ChatModel.ServerActive(r.Server) ? "" : " Not running: that server is not active."); + ToolTip.SetTip(row, note); + rows.Children.Add(new StackPanel + { + Children = + { + row, + new TextBlock { Text = note, FontSize = 9, Foreground = Brushes.Gray, Margin = new Thickness(24, 0, 0, 2) }, + }, + }); + } + else rows.Children.Add(row); } if (filters.Length == 0) diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs index 86a4f55..c37841e 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -67,7 +67,9 @@ // "rules": [ { "action": "copy", "when": "type:3", "mode": "", // "pattern": "...", "globalRoom": false } ] } ]. // "server" and "id" are ids (the owner key is "server/id"); "action" is copy -// or move; "globalRoomFallback" is General, Trade, LFG or Roleplay (the +// or move; "when" is "", chan: or type:; "mode" is "", regex, +// contains, startswith or endswith; "pattern" keeps its spaces (a +// "globalRoom" rule's is ignored); "globalRoomFallback" is General, Trade, LFG or Roleplay (the // room a "globalRoom": true rule matches until chat shows another; absent: // Roleplay, the room the Dereth Network README names as usual). An // entry with a bad field is dropped and reported in the parse error (the @@ -350,12 +352,40 @@ internal static class SectionManifestParser if (rules.Count >= MaxChatRules) { why = $"more than {MaxChatRules} rules"; return null; } string action = Str(r, "action").Trim().ToLowerInvariant(); if (action is not ("copy" or "move")) { why = "rule action is not copy or move"; return null; } - rules.Add(new SectionChatRuleDecl(action, Text(Str(r, "when"), MaxLabelLength), Text(Str(r, "mode"), MaxLabelLength), - Text(Str(r, "pattern"), MaxTextLength), Bool(r, "globalRoom", false))); + // A mistyped when or mode must not quietly become "any line" or a regex (the chat + // reads anything it doesn't know that way, ChatRuleMatching.ParseWhen / Parse). + string when = Str(r, "when").Trim(); + if (!ChatWhenValid(when)) { why = "rule when is not empty, chan: or type:"; return null; } + string mode = Str(r, "mode").Trim().ToLowerInvariant(); + if (mode is not ("" or "regex" or "contains" or "startswith" or "endswith")) { why = "rule mode is not regex, contains, startswith or endswith"; return null; } + bool globalRoom = Bool(r, "globalRoom", false); + // A pattern keeps its spaces ("[Trade] " ends in one); only control characters go. + string pattern = globalRoom ? string.Empty : Pattern(Str(r, "pattern"), MaxTextLength); + rules.Add(new SectionChatRuleDecl(action, when, mode, pattern, globalRoom)); } return new SectionChatTabDecl(server, id, name, Bool(e, "pinned", false), room, rules.ToArray()); } + /// A chat rule's when, as RynthChat reads it: "", "chan:<tab>" or "type:<number >= 0>". + private static bool ChatWhenValid(string when) + { + if (when.Length == 0) return true; + if (when.StartsWith("chan:", StringComparison.OrdinalIgnoreCase)) return when.Length > 5 && Text(when, MaxLabelLength) == when; + return when.StartsWith("type:", StringComparison.OrdinalIgnoreCase) + && int.TryParse(when[5..], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int t) && t >= 0; + } + + /// A rule pattern: control characters become spaces, capped, NOT trimmed. + private static string Pattern(string? text, int max) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var chars = text.ToCharArray(); + for (int i = 0; i < chars.Length; i++) + if (char.IsControl(chars[i])) chars[i] = ' '; + string t = new string(chars); + return t.Length <= max ? t : t[..max]; + } + private static readonly string[] GlobalRooms = { "General", "Trade", "LFG", "Roleplay" }; // ── Field rules ───────────────────────────────────────────────────── diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs index 788df25..4ffa693 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs @@ -228,9 +228,13 @@ internal static class SectionRegistry var chatTabs = new List(); foreach (SectionManifest m in manifests) chatTabs.AddRange(m.ChatTabs); var active = new List(); + var names = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (ServerState s in servers) + { if (s.Active) active.Add(s.Id); - UI.Data.ChatModel.ApplyServerTabs(chatTabs, active); + if (s.Name.Length > 0) names[s.Id] = s.Name; + } + UI.Data.ChatModel.ApplyServerTabs(chatTabs, active, names); } catch (Exception ex) { RynthLog.UI($"Sections: chat tabs not applied - {ex.GetType().Name}: {ex.Message}"); } } diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 426e343..f1b5c79 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1146,19 +1146,82 @@ internal static class Program Check(old.Filters!.All(f => f.Server == null && f.Owner == null && f.GlobalRoom == null), "an old file's rules have none of the rule fields"); } - // ── Server default tabs (2026-11-15) ── + // -- Server default tabs (2026-11-15) -- - private static SectionChatTabDecl NetworkDecl() => new( - "dreamweave", "dereth-network", "Network", true, "Roleplay", - new[] + private static readonly SectionChatRuleDecl TellRule = new("copy", "type:3", "", "^[^\"]+@[a-z0-9-]+( \\(discord\\))? tells you, \"", false); + private static readonly SectionChatRuleDecl SentRule = new("copy", "type:4", "", "^You tell [^\"]+@[a-z0-9-]+( \\(discord\\))?, \"", false); + private static readonly SectionChatRuleDecl GlobalRule = new("copy", "", "startswith", "", true); + + private static SectionChatTabDecl NetworkDecl(params SectionChatRuleDecl[] extra) => new( + "dreamweave", "dereth-network", "Network", true, "Roleplay", new[] { TellRule, SentRule, GlobalRule }.Concat(extra).ToArray()); + + private static RynthChatFilterDto CloneRule(RynthChatFilterDto r) => new() + { + Enabled = r.Enabled, Pattern = r.Pattern, Tab = r.Tab, Action = r.Action, When = r.When, ColorMode = r.ColorMode, + Color = r.Color, Mode = r.Mode, Server = r.Server, Owner = r.Owner, GlobalRoom = r.GlobalRoom, + }; + + /// The chat settings in miniature: carries out ChatServerTabs.Apply's edits the way ChatModel.ApplyServerTab does. + private sealed class TabSim + { + public static readonly string[] BaseTabs = { "All", "Chat", "Channels" }; + public List Rules = new(); + public List Custom = new(); + public List Seeded = new(); + public string[] Pins = Array.Empty(); + public Dictionary TabServers = ChatServerTabs.NewMap(); + public string? Room; + public string ServerName = "DreamWeave"; + + public string[] AllTabs() => BaseTabs.Concat(Custom) + .Concat(Rules.Where(r => r.Enabled && r.Action is "copy" or "move" && !string.IsNullOrEmpty(r.Tab)).Select(r => r.Tab!)) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + + public ChatServerTabs.TabEdits Apply(SectionChatTabDecl d) { - new SectionChatRuleDecl("copy", "type:3", "", "^[^\"]+@[a-z0-9-]+( \\(discord\\))? tells you, \"", false), - new SectionChatRuleDecl("copy", "type:4", "", "^You tell [^\"]+@[a-z0-9-]+( \\(discord\\))?, \"", false), - new SectionChatRuleDecl("copy", "", "startswith", "", true), - }); + var state = new ChatServerTabs.TabState(Seeded.ToArray(), Custom.ToArray(), AllTabs(), ChatServerTabs.NewMap(TabServers), + Pins.ToArray(), Rules.Select(CloneRule).ToArray(), Room, ServerName); + ChatServerTabs.TabEdits e = ChatServerTabs.Apply(d, state); + RynthChatFilterDto[] before = Rules.ToArray(); + foreach ((int index, RynthChatFilterDto want) in e.Updates) + { + RynthChatFilterDto w = CloneRule(want); + w.Color = before[index].Color; // the colour is the player's + w.ColorMode = before[index].ColorMode; + Rules[Rules.IndexOf(before[index])] = w; + } + int at = e.InsertAt; + foreach (int index in e.Removes) + { + Rules.Remove(before[index]); + if (index < e.InsertAt) at--; + } + foreach (RynthChatFilterDto want in e.Inserts) Rules.Insert(Math.Min(at++, Rules.Count), CloneRule(want)); + if (e.CreateTab != null) Custom.Add(e.CreateTab); + if (e.Pin != null) Pins = Pins.Append(e.Pin).ToArray(); + if (e.Seed != null) Seeded.Add(e.Seed); + if (e.TabServer != null) TabServers[e.TabServer] = d.Server; + return e; + } - private static ChatServerTabs.SeedState State(string[]? seeded = null, string[]? tabs = null, RynthChatFilterDto[]? owned = null) - => new(seeded ?? Array.Empty(), tabs ?? new[] { "All", "Chat" }, owned ?? Array.Empty()); + + /// RenameCustomTab: the tab, its rules, its server entry and its pin. + public void Rename(string from, string to) + { + Custom = Custom.Select(t => string.Equals(t, from, StringComparison.OrdinalIgnoreCase) ? to : t).ToList(); + foreach (RynthChatFilterDto r in Rules) if (string.Equals(r.Tab, from, StringComparison.OrdinalIgnoreCase)) r.Tab = to; + (TabServers, Pins) = ChatServerTabs.RenameTab(TabServers, Pins, from, to); + } + + /// DeleteCustomTab: the tab goes, its Move/Copy rules turn off, its server entry and pin go, the seed mark stays. + public void Delete(string tab) + { + Custom.RemoveAll(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)); + foreach (RynthChatFilterDto r in Rules) + if (r.Action is "copy" or "move" && string.Equals(r.Tab, tab, StringComparison.OrdinalIgnoreCase)) r.Enabled = false; + (TabServers, Pins) = ChatServerTabs.DeleteTab(TabServers, Pins, tab); + } + } private static void ServerTabDiscovery() { @@ -1179,75 +1242,200 @@ internal static class Program { SectionChatTabDecl d = NetworkDecl(); string key = ChatServerTabs.OwnerKey(d); - Case("Plan_SeedsFresh"); + + Case("Apply_SeedsFresh"); Check(key == "dreamweave/dereth-network", "owner key"); - ChatServerTabs.SeedPlan p = ChatServerTabs.Plan(d, State(), null); - Check(p.CreateTab && p.TabName == "Network" && p.Pin && p.MarkSeeded, "creates, names, pins and marks the tab"); - Check(p.Rules.Length == 3 && p.Rules.All(r => r.Owner == key && r.Server == "dreamweave" && r.Tab == "Network" && r.Enabled), "3 owned rules for the tab"); - RynthChatFilterDto g = p.Rules[2]; - Check(g.GlobalRoom == true && g.Mode == "startswith" && g.Pattern == "[Roleplay] ", "the Global rule uses the fallback room"); - Check(p.Rules[0].GlobalRoom == null && p.Rules[0].Pattern == d.Rules[0].Pattern && p.Rules[0].When == "type:3", "other rules copy the declaration"); + var sim = new TabSim(); + ChatServerTabs.TabEdits e = sim.Apply(d); + Check(e.CreateTab == "Network" && e.Pin == "Network" && e.Seed == key && e.TabServer == "Network", "creates, pins, marks and claims the tab"); + Check(e.Inserts.Length == 3 && e.Inserts.All(r => r.Owner == key && r.Server == "dreamweave" && r.Tab == "Network" && r.Enabled), "3 owned rules, on"); + Check(e.Inserts[2].GlobalRoom == true && e.Inserts[2].Mode == "startswith" && e.Inserts[2].Pattern == "[Roleplay] ", "the Global rule uses the fallback room"); + Check(e.Inserts[0].GlobalRoom == null && e.Inserts[0].Pattern == TellRule.Pattern && e.Inserts[0].When == "type:3", "other rules copy the declaration"); - Case("Plan_UsesDiscoveredRoom"); - Check(ChatServerTabs.Plan(d, State(), "General").Rules[2].Pattern == "[General] ", "the discovered room wins over the fallback"); + Case("Apply_SecondApplyIsANoOp"); + // ChatModel.ApplyServerTabs runs every second: once applied, nothing may be left to change. + Check(!sim.Apply(d).Changed, "a second apply changes nothing"); + sim.Rules.Add(new RynthChatFilterDto { Tab = "Network", Action = "copy", Pattern = "^Bob", Enabled = true }); + Check(!sim.Apply(d).Changed, "a rule the player added to the tab is left alone"); + sim.Room = "Trade"; + e = sim.Apply(d); + Check(e.Updates.Count == 1 && e.Updates[0].Rule.Pattern == "[Trade] " && e.Inserts.Length == 0 && e.Removes.Length == 0, "a new room rewrites the Global rule only"); + Check(!sim.Apply(d).Changed, "and then nothing again"); - Case("Plan_AdoptsExistingTabByName"); - p = ChatServerTabs.Plan(d, State(tabs: new[] { "All", "Chat", "Network" }), null); - Check(!p.CreateTab && !p.Pin && p.MarkSeeded && p.TabName == "Network", "an existing Network tab is adopted, not duplicated or re-pinned"); - p = ChatServerTabs.Plan(d, State(tabs: new[] { "network" }), null); - Check(!p.CreateTab, "the name match ignores case"); - var strayRule = new RynthChatFilterDto { Owner = key, Tab = "DN" }; - p = ChatServerTabs.Plan(d, State(owned: new[] { strayRule }), null); - Check(!p.CreateTab && !p.Pin && p.MarkSeeded && p.TabName == "DN", "owned rules without a seed mark (older engine) are adopted too"); + Case("Apply_UsesDiscoveredRoom"); + Check(new TabSim { Room = "General" }.Apply(d).Inserts[2].Pattern == "[General] ", "the discovered room wins over the fallback"); + + Case("Apply_ClashSeedsUnderServerName"); + sim = new TabSim { Custom = { "Network" } }; + sim.Rules.Add(new RynthChatFilterDto { Tab = "Network", Action = "move", Pattern = "^guild", Enabled = true }); + e = sim.Apply(d); + Check(e.CreateTab == "Network (DreamWeave)" && e.Inserts.All(r => r.Tab == "Network (DreamWeave)"), "a player's Network tab is not taken: seeds under the server's name"); + Check(e.TabServer == "Network (DreamWeave)" && !sim.TabServers.ContainsKey("Network"), "the player's tab gets no server entry"); + Check(sim.Rules[0].Owner == null && sim.Rules[0].Tab == "Network", "the player's rule is untouched"); + Check(!sim.Apply(d).Changed, "and the clash-named tab is stable"); + sim = new TabSim { Custom = { "Network", "Network (DreamWeave)" } }; + Check(sim.Apply(d).CreateTab == "Network (DreamWeave) 2", "both names taken: numbered"); + var chatDecl = d with { Name = "Chat" }; + Check(new TabSim { ServerName = "" }.Apply(chatDecl).CreateTab == "Chat (dreamweave)", "a base tab's name: the server id when no display name"); Case("Refresh_FollowsRenamedTab"); - RynthChatFilterDto[] owned = ChatServerTabs.Plan(d, State(), null).Rules; - foreach (RynthChatFilterDto r in owned) r.Tab = "DN"; - p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Chat", "DN" }, owned: owned), "Trade"); - Check(p.TabName == "DN" && !p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: no create, no pin, no new mark"); - Check(p.Rules.All(r => r.Tab == "DN"), "every rule follows the rename"); - Check(p.Rules[2].Pattern == "[Trade] ", "a refresh rewrites the Global pattern"); + sim = new TabSim(); + sim.Apply(d); + sim.Rename("Network", "DN"); + Check(sim.TabServers.ContainsKey("DN") && !sim.TabServers.ContainsKey("Network") && sim.Pins.SequenceEqual(new[] { "DN" }), "rename moves the server entry and the pin"); + sim.Room = "Trade"; + e = sim.Apply(d); + Check(e.TabName == "DN" && e.CreateTab == null && e.Pin == null && e.Seed == null && e.TabServer == null, "seeded: no create, pin, mark or claim"); + Check(sim.Rules.All(r => r.Tab == "DN") && sim.Rules[2].Pattern == "[Trade] ", "every rule follows the rename; the Global pattern refreshes"); + Check(!sim.Apply(d).Changed, "stable after the rename"); Case("Refresh_KeepsDeletedTabDeleted"); - owned = ChatServerTabs.Plan(d, State(), null).Rules; - foreach (RynthChatFilterDto r in owned) r.Enabled = false; - p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, owned: owned), null); - Check(!p.CreateTab && !p.Pin, "a seeded tab that is gone is not re-created"); - Check(p.Rules.All(r => !r.Enabled), "its rules stay disabled"); + sim = new TabSim(); + sim.Apply(d); + sim.Delete("Network"); + Check(sim.TabServers.Count == 0 && sim.Pins.Length == 0 && sim.Seeded.Contains(key), "delete drops the server entry and pin, keeps the seed mark"); + e = sim.Apply(d); + Check(!e.Changed, "a deleted tab: nothing to do: " + e); + Check(!sim.AllTabs().Contains("Network") && sim.Rules.All(r => !r.Enabled), "the tab stays gone, its rules off"); - Case("Refresh_IsANoOpWhenNothingChanged"); - // ChatModel.ApplyServerTabs runs every second: a plan made from its own output must match it - // rule for rule (SameRule), and want no create, pin or seed mark, or every Rebuild would save. - owned = ChatServerTabs.Plan(d, State(), "Trade").Rules; - p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Network" }, owned: owned), "Trade"); - Check(!p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: nothing to create, pin or mark"); - Check(p.Rules.Length == owned.Length && p.Rules.Zip(owned).All(z => ChatServerTabs.SameRule(z.First, z.Second)), "every rule is the same as before"); + Case("Refresh_NewRuleStaysOffForDeletedTab"); + var bigger = NetworkDecl(new SectionChatRuleDecl("copy", "type:18", "", "^\\[Network\\]", false)); + e = sim.Apply(bigger); + Check(e.Inserts.Length == 1 && !e.Inserts[0].Enabled && e.CreateTab == null && e.TabServer == null, "a rule the manifest gained is added off, the tab not re-created"); + Check(!sim.AllTabs().Contains("Network"), "the tab is still gone"); + + Case("Refresh_AllRulesDeletedStaysOff"); + sim = new TabSim(); + sim.Apply(d); + sim.Delete("Network"); + sim.Rules.Clear(); // the player also deleted the rules + e = sim.Apply(d); + Check(e.Inserts.Length == 3 && e.Inserts.All(r => !r.Enabled) && e.CreateTab == null && e.Pin == null && e.TabServer == null, "re-added, all off, no tab"); + Check(!sim.AllTabs().Contains("Network") && !sim.Apply(d).Changed, "the tab stays gone, and it is stable"); + + Case("Pair_ByContentNotPosition"); + sim = new TabSim(); + sim.Apply(d); + sim.Rules[1].Enabled = false; // the player turned off "tells you send" + sim.Rules[0].Color = "#FF0000"; // and coloured "tells to you" + sim.Rules[0].ColorMode = "line"; + // Reordered by the player (and an older editor): Global first, a player rule between. + sim.Rules = new List + { + sim.Rules[2], new() { Tab = "Junk", Action = "hide", Pattern = "spam", Enabled = true }, sim.Rules[1], sim.Rules[0], + }; + string[] order = sim.Rules.Select(r => r.Pattern ?? "").ToArray(); + Check(!sim.Apply(d).Changed, "a permuted list pairs by content: nothing to change"); + Check(sim.Rules.Select(r => r.Pattern ?? "").SequenceEqual(order), "the player's order is kept"); + Check(!sim.Rules.Single(r => r.When == "type:4").Enabled && sim.Rules.Single(r => r.When == "type:3").Enabled, "the off switch stays on the rule it was set on"); + var changed = new SectionChatTabDecl(d.Server, d.Id, d.Name, d.Pinned, d.GlobalRoomFallback, + new[] { TellRule with { Pattern = "^[^\"]+@[a-z0-9-]+ tells you, \"" }, SentRule, GlobalRule }); + e = sim.Apply(changed); + RynthChatFilterDto tell = sim.Rules.Single(r => r.When == "type:3"); + Check(e.Updates.Count == 1 && e.Inserts.Length == 0 && e.Removes.Length == 0 && tell.Pattern == changed.Rules[0].Pattern, "a pattern the manifest changed is rewritten in place"); + Check(tell.Color == "#FF0000" && !sim.Rules.Single(r => r.When == "type:4").Enabled, "the colour and the other rule's off switch stay put"); + + Case("Reclaim_FindsRulesAnOlderEngineStripped"); + // An older engine rewrote the file: its copy of the rules has no owner, server or globalRoom. + RynthChatFilterDto Strip(RynthChatFilterDto r) => new() { Tab = r.Tab, Action = r.Action, When = r.When, Mode = r.Mode, Pattern = r.Pattern, Enabled = r.Enabled }; + RynthChatFilterDto[] ours = new TabSim { Room = "Trade" }.Apply(d).Inserts; + var player = new RynthChatFilterDto { Tab = "RP", Action = "copy", Mode = "startswith", Pattern = "[Roleplay] " }; + var file = new List { player, Strip(ours[1]), new() { Tab = "Junk", Action = "hide", Pattern = "spam" }, Strip(ours[0]), Strip(ours[2]) }; + int[]? found = ChatServerTabs.Reclaim(d, file, "DreamWeave"); + Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), $"found in declaration order, not the player's look-alike Global rule: {(found == null ? "null" : string.Join(",", found))}"); + foreach (RynthChatFilterDto r in file) if (r.Tab == "Network") r.Tab = "DN"; + found = ChatServerTabs.Reclaim(d, file, "DreamWeave"); + Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), "a renamed tab holding only those rules is found too"); + Check(ChatServerTabs.Reclaim(d, new[] { player, Strip(ours[0]) }) == null, "an incomplete set is not reclaimed"); + Check(ChatServerTabs.Reclaim(d, new[] { Strip(ours[0]), Strip(ours[1]), new RynthChatFilterDto { Tab = "Other", Action = "copy", Mode = "startswith", Pattern = "[Trade] " } }) == null, + "the set must be in one tab"); + file[3].Owner = key; + Check(ChatServerTabs.Reclaim(d, file, "DreamWeave") == null, "a rule that still has an owner is not reclaimed"); + + Case("Reclaim_RefusesAPlayersLookAlikeTab"); + var mine = new List { Strip(ours[0]), Strip(ours[1]), Strip(ours[2]) }; + foreach (RynthChatFilterDto r in mine) r.Tab = "Mine"; + Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") != null, "a tab holding only those rules is reclaimed (renamed)"); + mine.Add(new RynthChatFilterDto { Tab = "Mine", Action = "copy", Pattern = "^Bob" }); + Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") == null, "a tab with another rule of the player's, not named for the entry, is not"); + foreach (RynthChatFilterDto r in mine) r.Tab = "Network (DreamWeave)"; + Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") != null, "the entry's clash name is reclaimed with the player's rule in it"); + foreach (RynthChatFilterDto r in mine) r.Tab = "Network"; + Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") != null, "so is the entry's own name"); + + Case("Apply_StrippedByOlderEngineAddsNoSecondSet"); + sim = new TabSim(); + sim.Apply(d); + sim.Rules[1].Enabled = false; + sim.Rules = sim.Rules.Select(Strip).ToList(); // an older engine saved: owner, server, globalRoom gone + sim.Seeded.Clear(); + sim.TabServers.Clear(); + sim.Pins = Array.Empty(); + e = sim.Apply(d); + Check(e.Inserts.Length == 0 && e.Removes.Length == 0 && e.Updates.Count == 3 && e.CreateTab == null, "the stripped rules are rewritten, not doubled: " + e.Inserts.Length); + Check(e.Seed == key && e.TabServer == "Network" && e.Pin == null, "seed mark and server entry restored, pin not forced back"); + Check(sim.Rules.Count == 3 && sim.Rules.All(r => r.Owner == key) && !sim.Rules[1].Enabled, "owned again, the off switch kept"); + Check(!sim.Apply(d).Changed, "and stable"); + + Case("TabBookkeeping_RenameAndDelete"); + var servers = ChatServerTabs.NewMap(new Dictionary { ["Network"] = "dreamweave", ["Other"] = "aelrynth" }); + (Dictionary s1, string[] p1) = ChatServerTabs.RenameTab(servers, new[] { "Chat", "network", "All" }, "Network", "DN"); + Check(s1["DN"] == "dreamweave" && !s1.ContainsKey("Network") && s1["Other"] == "aelrynth", "rename: the server entry moves, others stay"); + Check(p1.SequenceEqual(new[] { "Chat", "DN", "All" }), "rename: the pin keeps its place (any case)"); + (Dictionary s2, string[] p2) = ChatServerTabs.DeleteTab(s1, p1, "dn"); + Check(!s2.ContainsKey("DN") && s2.Count == 1 && p2.SequenceEqual(new[] { "Chat", "All" }), "delete: the server entry and the pin go"); + (Dictionary s3, string[] p3) = ChatServerTabs.RenameTab(s2, p2, "Mine", "Ours"); + Check(s3.Count == 1 && p3.SequenceEqual(p2), "renaming an unpinned player tab touches neither"); + + Case("ListTabs_HidesInactiveServerTabs"); + ChatFilterRule Rule(string tab, string server = "", bool on = true) + { + var r = new ChatFilterRule { Pattern = "^x", Tab = tab, Action = ChatRuleAction.Copy, Server = server, Enabled = on }; + r.Recompile(); + return r; + } + string[] baseTabs = { "All", "Chat" }; + var rules = new[] { Rule("Network", "dreamweave"), Rule("Extra", "dreamweave"), Rule("Mine"), Rule("Off", "", on: false) }; + var tabServers = ChatServerTabs.NewMap(new Dictionary { ["Network"] = "dreamweave" }); + string[] custom = { "Network", "Kept" }; + string[] onDw = ChatServerTabs.ListTabs(baseTabs, custom, rules, new[] { "Preset" }, tabServers, new[] { "DreamWeave" }); + string[] onOther = ChatServerTabs.ListTabs(baseTabs, custom, rules, new[] { "Preset" }, tabServers, new[] { "aelrynth" }); + string[] every = ChatServerTabs.ListTabs(baseTabs, custom, rules, new[] { "Preset" }, tabServers, null); + Check(onDw.SequenceEqual(new[] { "All", "Chat", "Network", "Kept", "Extra", "Mine", "Preset" }), "its server active: every tab: " + string.Join(",", onDw)); + Check(onOther.SequenceEqual(new[] { "All", "Chat", "Kept", "Mine", "Preset" }), "another server: the server's tab and the tab only its rule fills are hidden: " + string.Join(",", onOther)); + Check(every.SequenceEqual(onDw), "no filter: every tab"); + Check(ChatServerTabs.ListTabs(baseTabs, custom, rules, Array.Empty(), ChatServerTabs.NewMap(new Dictionary { ["Chat"] = "dreamweave" }), Array.Empty()).Contains("Chat"), + "a base tab is never hidden"); + + Case("Export_SkipsServerRules_ImportClearsOwnership"); + sim = new TabSim(); + sim.Apply(d); + sim.Custom.Add("Mine"); + sim.Rules.Add(new RynthChatFilterDto { Tab = "Mine", Action = "copy", Pattern = "^Bob", Enabled = true }); + var set = new RynthChatRuleSetDto + { + Format = RynthChatRuleSetDto.FormatName, + Tabs = ChatServerTabs.ExportTabs(sim.Custom, sim.TabServers), + Rules = ChatServerTabs.ExportRules(sim.Rules), + }; + string json = JsonSerializer.Serialize(set, RynthChatJsonContext.Default.RynthChatRuleSetDto); + RynthChatRuleSetDto? back = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatRuleSetDto); + Check(back?.Rules?.Length == 1 && back.Rules[0].Pattern == "^Bob" && back.Tabs!.SequenceEqual(new[] { "Mine" }), "export: the player's rule and tab only"); + Check(!json.Contains("\"owner\"") && !json.Contains("Network"), "export: no server rule, no server tab"); + // A whole settings file pasted into Import carries the server's rules: they become the player's. + RynthChatFilterDto[] imported = sim.Rules.Select(CloneRule).Select(ChatServerTabs.AsPlayerRule).ToArray(); + Check(imported.All(r => r.Owner == null && r.Server == null && r.GlobalRoom == null), "import: no owner, every server, a fixed pattern"); + Check(imported[2].Pattern == "[Roleplay] " && imported[2].Mode == "startswith" && imported[0].When == "type:3", "import keeps what the rule does"); + + Case("Refresh_IsANoOpWhenNothingChanged (SameRule)"); var absent = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = null, Mode = null, Pattern = "x", GlobalRoom = null, Enabled = true }; var empty = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = "", Mode = "", Pattern = "x", GlobalRoom = false, Enabled = true }; Check(ChatServerTabs.SameRule(absent, empty), "absent and empty When / Mode / GlobalRoom are the same"); Check(ChatServerTabs.SameRule(empty, new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", Pattern = "x", Color = "#FF0000", ColorMode = "line" }), "a colour the player gave the rule is not a difference"); - Check(!ChatServerTabs.SameRule(owned[2], ChatServerTabs.Plan(d, State(), "General").Rules[2]), "a new Global room is a difference"); - var off = ChatServerTabs.Plan(d, State(), "Trade").Rules; - off[0].Enabled = false; - Check(!ChatServerTabs.SameRule(owned[0], off[0]), "on / off is a difference"); - - Case("Reclaim_FindsRulesAnOlderEngineStripped"); - // An older engine rewrote the file: its copy of the rules has no owner, server or globalRoom. - RynthChatFilterDto Strip(RynthChatFilterDto r) => new() { Tab = r.Tab, Action = r.Action, When = r.When, Mode = r.Mode, Pattern = r.Pattern, Enabled = r.Enabled }; - RynthChatFilterDto[] ours = ChatServerTabs.Plan(d, State(), "Trade").Rules; - var player = new RynthChatFilterDto { Tab = "RP", Action = "copy", Mode = "startswith", Pattern = "[Roleplay] " }; - var file = new List { player, Strip(ours[1]), new() { Tab = "Junk", Action = "hide", Pattern = "spam" }, Strip(ours[0]), Strip(ours[2]) }; - int[]? found = ChatServerTabs.Reclaim(d, file); - Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), $"found in declaration order, not the player's look-alike Global rule: {(found == null ? "null" : string.Join(",", found))}"); - foreach (RynthChatFilterDto r in file) if (r.Tab == "Network") r.Tab = "DN"; - found = ChatServerTabs.Reclaim(d, file); - Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), "a renamed tab's stripped rules are found too"); - Check(ChatServerTabs.Reclaim(d, new[] { player, Strip(ours[0]) }) == null, "an incomplete set is not reclaimed"); - file[3].Owner = key; - Check(ChatServerTabs.Reclaim(d, file) == null, "a rule that still has an owner is not reclaimed"); - Check(ChatServerTabs.Reclaim(d, new[] { Strip(ours[0]), Strip(ours[1]), new RynthChatFilterDto { Tab = "Other", Action = "copy", Mode = "startswith", Pattern = "[Trade] " } }) == null, - "the set must be in one tab"); + var off = CloneRule(empty); + off.Enabled = false; + Check(!ChatServerTabs.SameRule(empty, off), "on / off is a difference"); Case("Router_SkipsRulesOfInactiveServers"); var serverRule = new ChatFilterRule { Pattern = "^x", Tab = "Network", Action = ChatRuleAction.Copy, Server = "dreamweave" }; @@ -1261,8 +1449,8 @@ internal static class Program Check(!offRoute.ShowsIn("Network", "Chat") && offRoute.ShowsIn("Every", "Chat"), "another server: only the every-server rule runs"); Check(!none.ShowsIn("Network", "Chat") && none.ShowsIn("Every", "Chat"), "no servers known: only the every-server rule runs"); - Case("Plan rules compile"); - foreach (RynthChatFilterDto r in ChatServerTabs.Plan(d, State(), "LFG").Rules) + Case("Apply rules compile"); + foreach (RynthChatFilterDto r in new TabSim { Room = "LFG" }.Apply(d).Inserts) { System.Text.RegularExpressions.Regex? rx = ChatRuleMatching.Compile(ChatRuleMatching.Parse(r.Mode), r.Pattern, 5000, out string? err); Check(err == null && rx != null, $"rule '{r.Pattern}' compiles: {err}"); diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index aa3a9d2..81a7ffd 100644 --- a/tools/SectionsTests/Program.cs +++ b/tools/SectionsTests/Program.cs @@ -616,6 +616,19 @@ internal static class Program var noFallback = SectionManifestParser.Parse("DW", """{ "chatTabs": [ { "server": "dw", "id": "a", "name": "A", "rules": [] } ] }""", out _); Check(noFallback.ChatTabs.Length == 1 && noFallback.ChatTabs[0].GlobalRoomFallback == "Roleplay", "absent globalRoomFallback = Roleplay"); + Case("manifest: chatTabs rule when, mode and pattern are kept as written"); + m = SectionManifestParser.Parse("DW", """ + { "chatTabs": [ { "server": "dw", "id": "a", "name": "A", "rules": [ + { "action": "copy", "when": "chan:Combat", "mode": "StartsWith", "pattern": "[Trade] " }, + { "action": "copy", "when": "TYPE:4", "mode": "contains", "pattern": " two " }, + { "action": "copy", "when": "", "mode": "startswith", "pattern": "ignored", "globalRoom": true } ] } ] } + """, out err); + Check(err.Length == 0 && m.ChatTabs.Length == 1 && m.ChatTabs[0].Rules.Length == 3, "three valid rules parse: " + err); + SectionChatRuleDecl[] kept = m.ChatTabs.Length == 1 ? m.ChatTabs[0].Rules : System.Array.Empty(); + Check(kept.Length == 3 && kept[0].Pattern == "[Trade] " && kept[1].Pattern == " two ", "a pattern's spaces are kept"); + Check(kept.Length == 3 && kept[0].When == "chan:Combat" && kept[1].When == "TYPE:4" && kept[0].Mode == "startswith", "chan:/type: when accepted, mode lower-cased"); + Check(kept.Length == 3 && kept[2].Pattern == "", "a globalRoom rule's pattern is ignored (the engine supplies it)"); + // Each reject drops the entry, reports it in error, and still parses the other keys. string section = """ "sections": [ { "id": "quests", "label": "Quests", "order": 150 } ] """; string[] bad = @@ -625,8 +638,14 @@ internal static class Program """{ "server": "dw", "id": "Bad Id", "name": "A", "globalRoomFallback": "General", "rules": [] }""", """{ "server": "dw", "id": "a", "name": "A", "globalRoomFallback": "General", "rules": [ { "action": "delete", "when": "", "mode": "", "pattern": "x" } ] }""", """{ "server": "dw", "id": "a", "name": "A", "globalRoomFallback": "Sports", "rules": [] }""", + """{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "typo:3", "mode": "", "pattern": "x" } ] }""", + """{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "type:x", "mode": "", "pattern": "x" } ] }""", + """{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "type:-1", "mode": "", "pattern": "x" } ] }""", + """{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "chan:", "mode": "", "pattern": "x" } ] }""", + """{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "", "mode": "startwith", "pattern": "x" } ] }""", }; - string[] why = { "missing server", "missing id", "bad id", "bad action", "bad fallback" }; + string[] why = { "missing server", "missing id", "bad id", "bad action", "bad fallback", + "when typo:3", "when type:x", "when type:-1", "when chan: with no tab", "mode startwith" }; for (int i = 0; i < bad.Length; i++) { m = SectionManifestParser.Parse("DW", "{ " + section + ", \"chatTabs\": [" + bad[i] + "] }", out err); -- 2.43.0 From 0eec23f6fdd00754ca52b68c4fb2a1fbdc8a1a07 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 09:05:29 -0800 Subject: [PATCH 07/12] RynthChat: a new tab never lands in a hidden server tab "New tab: Network" on a server where the DreamWeave Network tab is hidden returned that hidden tab, so the player's new rule filled the server's tab. ChatServerTabs.ResolveNewTab now keeps "returns the existing one" for a visible tab only; a hidden match gets a free numbered name ("Network 2"). An unreadable settings file is logged once per run instead of on every 2 s retry. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/UI/Data/ChatData.cs | 22 +++++++++++-------- .../UI/Data/ChatServerTabs.cs | 22 +++++++++++++++++-- tools/ChatFilterTests/Program.cs | 10 +++++++++ 3 files changed, 43 insertions(+), 11 deletions(-) diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index b84d41c..e773554 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -695,13 +695,13 @@ internal static class ChatModel { name = name.Trim(); if (name.Length == 0) return null; - // Every tab, also one hidden because its server is not active (as RenameCustomTab), or a - // second tab of the same name would be made beside it. - string? existing = BuildTabs(null).FirstOrDefault(t => string.Equals(t, name, StringComparison.OrdinalIgnoreCase)); - if (existing == null || !IsBaseTab(existing)) EnsureCustomTab(existing ?? name); - if (select) ActiveChannel = existing ?? name; + // A tab the player sees by that name is that tab; one hidden because its server is not + // active is that server's, so the new tab gets a free name beside it ("Network 2"). + (string tab, bool existing) = ChatServerTabs.ResolveNewTab(name, AllTabs(), BuildTabs(null)); + if (!existing || !IsBaseTab(tab)) EnsureCustomTab(tab); + if (select) ActiveChannel = tab; SaveSettings(); - return existing ?? name; + return tab; } private static void EnsureCustomTab(string name) @@ -1709,9 +1709,13 @@ internal static class ChatModel } catch (Exception ex) { - RynthLog.UI($"ChatModel: settings load failed: {ex.Message}"); - // One copy per run: the retry every 2 s must not leave a copy each time. - if (!_keptUnreadable) { _keptUnreadable = true; KeepUnreadable(); } + // Logged and copied once per run: the retry every 2 s must not repeat either. + if (!_keptUnreadable) + { + _keptUnreadable = true; + RynthLog.UI($"ChatModel: settings load failed (retrying every 2 s, logged once): {ex.Message}"); + KeepUnreadable(); + } return false; } } diff --git a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs index 470d2d6..817a2a1 100644 --- a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -168,9 +168,27 @@ internal static class ChatServerTabs private static string FreeName(string name, string clashBase, IReadOnlyCollection tabs) { if (!Has(tabs, name)) return name; - if (!Has(tabs, clashBase)) return clashBase; + return Numbered(clashBase, tabs); + } + + /// if no tab has it, else "name 2", "name 3"... + private static string Numbered(string name, IReadOnlyCollection tabs) + { + if (!Has(tabs, name)) return name; for (int n = 2; ; n++) - if (!Has(tabs, clashBase + " " + n)) return clashBase + " " + n; + if (!Has(tabs, name + " " + n)) return name + " " + n; + } + + /// + /// The tab "New tab: " means (ChatModel.AddCustomTab): a tab the player + /// can see by that name is that tab (Existing); one that exists but is hidden (an inactive + /// server's) is not theirs to fill, so a free "name 2" is made instead; else the name itself. + /// + internal static (string Tab, bool Existing) ResolveNewTab(string name, IReadOnlyCollection visibleTabs, IReadOnlyCollection everyTab) + { + string? shown = visibleTabs.FirstOrDefault(t => string.Equals(t, name, StringComparison.OrdinalIgnoreCase)); + if (shown != null) return (shown, true); + return (Numbered(name, everyTab), false); } /// diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index f1b5c79..043014f 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1449,6 +1449,16 @@ internal static class Program Check(!offRoute.ShowsIn("Network", "Chat") && offRoute.ShowsIn("Every", "Chat"), "another server: only the every-server rule runs"); Check(!none.ShowsIn("Network", "Chat") && none.ShowsIn("Every", "Chat"), "no servers known: only the every-server rule runs"); + Case("ResolveNewTab_HiddenServerTabIsAClash"); + // "New tab: Network" on another server, where the DreamWeave Network tab is hidden. + string[] visible = { "All", "Chat", "Mine" }; + string[] everyTab = { "All", "Chat", "Mine", "Network", "Network 2" }; + Check(ChatServerTabs.ResolveNewTab("mine", visible, everyTab) == ("Mine", true), "a visible tab of that name is that tab (its own case)"); + Check(ChatServerTabs.ResolveNewTab("chat", visible, everyTab) == ("Chat", true), "a base tab too"); + Check(ChatServerTabs.ResolveNewTab("Network", visible, everyTab) == ("Network 3", false), "a hidden server tab: a free numbered name, not the server's tab"); + Check(ChatServerTabs.ResolveNewTab("Network", visible, new[] { "All", "Network" }) == ("Network 2", false), "the first free number"); + Check(ChatServerTabs.ResolveNewTab("Fresh", visible, everyTab) == ("Fresh", false), "no match: the name itself, new"); + Case("Apply rules compile"); foreach (RynthChatFilterDto r in new TabSim { Room = "LFG" }.Apply(d).Inserts) { -- 2.43.0 From 6f26d3f80bcbcdf1222c9cc1588e1e76228c8e8f Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:43:48 -0800 Subject: [PATCH 08/12] RynthChat: pinned tab bookkeeping ChatPins: pure Toggle/Rename/Remove/Visible over the pinned-tab list (OrdinalIgnoreCase, order = button order). A pin on a hidden tab is kept but not returned by Visible. Tests in tools/ChatFilterTests. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/UI/Data/ChatPins.cs | 57 ++++++++++++++++++++ tools/ChatFilterTests/ChatFilterTests.csproj | 2 + tools/ChatFilterTests/Program.cs | 37 +++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 src/RynthCore.Engine/UI/Data/ChatPins.cs diff --git a/src/RynthCore.Engine/UI/Data/ChatPins.cs b/src/RynthCore.Engine/UI/Data/ChatPins.cs new file mode 100644 index 0000000..76854cc --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatPins.cs @@ -0,0 +1,57 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatPins.cs +// Pinned chat tabs (2026-11-15): which tabs sit in the main chat window's top +// bar. Pure list bookkeeping (no ChatModel or ImGui) so tools/ChatFilterTests +// compiles it as is. Names compare OrdinalIgnoreCase, every function returns a +// new array, and the order of the array is the order of the buttons. +// +// A pin on a tab that is not there (a server tab while its server is not +// active) is kept but not drawn: Visible filters, nothing removes. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RynthCore.Engine.UI.Data; + +internal static class ChatPins +{ + private static bool Same(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + + /// Pins at the end, or unpins it when it is pinned. A blank name changes nothing. + internal static string[] Toggle(string[] pins, string tab) + { + if (string.IsNullOrWhiteSpace(tab)) return pins.ToArray(); + tab = tab.Trim(); + if (pins.Any(p => Same(p, tab))) return Remove(pins, tab); + return pins.Append(tab).ToArray(); + } + + /// The pin follows a renamed tab and keeps its place. If is already pinned, one pin remains. + internal static string[] Rename(string[] pins, string from, string to) + { + var result = new List(pins.Length); + foreach (string p in pins) + { + string name = Same(p, from) ? to : p; + if (!result.Any(r => Same(r, name))) result.Add(name); + } + return result.ToArray(); + } + + /// Drops the pin of a deleted tab. + internal static string[] Remove(string[] pins, string tab) => pins.Where(p => !Same(p, tab)).ToArray(); + + /// The pins that have a tab now, in pin order, spelled as the tab is. + internal static string[] Visible(string[] pins, string[] allTabs) + { + var result = new List(pins.Length); + foreach (string p in pins) + { + string? tab = allTabs.FirstOrDefault(t => Same(t, p)); + if (tab != null && !result.Any(r => Same(r, tab))) result.Add(tab); + } + return result.ToArray(); + } +} \ No newline at end of file diff --git a/tools/ChatFilterTests/ChatFilterTests.csproj b/tools/ChatFilterTests/ChatFilterTests.csproj index 9b050bb..353492c 100644 --- a/tools/ChatFilterTests/ChatFilterTests.csproj +++ b/tools/ChatFilterTests/ChatFilterTests.csproj @@ -39,6 +39,8 @@ + + diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 043014f..7764e41 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -57,6 +57,7 @@ internal static class Program ServerTabSettingsRoundTrip(); ServerTabDiscovery(); ServerTabPlans(); + PinBookkeeping(); SharedFileReload(); LineColorTags(); LineColorKinds(); @@ -1603,4 +1604,40 @@ internal static class Program Check(ChatFilterPresets.Get("no.such") == null, "an unknown id is null"); Check(ChatFilterPresets.All.Length >= 10, "a useful set"); } + + // 2026-11-15: pinned tab bookkeeping (ChatPins), pure. + private static void PinBookkeeping() + { + Case("Toggle_AddsAtEndAndRemoves"); + string[] p = ChatPins.Toggle(Array.Empty(), "Chat"); + p = ChatPins.Toggle(p, "Network"); + Check(p.SequenceEqual(new[] { "Chat", "Network" }), "added in pin order"); + string[] q = ChatPins.Toggle(p, "chat"); + Check(q.SequenceEqual(new[] { "Network" }), "a differently cased name unpins"); + Check(p.SequenceEqual(new[] { "Chat", "Network" }), "the input array is not changed"); + Check(ChatPins.Toggle(q, " ").Length == 1, "a blank name pins nothing"); + + Case("Rename_KeepsPosition"); + string[] r = ChatPins.Rename(new[] { "Chat", "Network", "Trade" }, "network", "DN"); + Check(r.SequenceEqual(new[] { "Chat", "DN", "Trade" }), "renamed in place"); + Check(ChatPins.Rename(r, "Nope", "X").SequenceEqual(r), "an unpinned tab changes nothing"); + string[] merged = ChatPins.Rename(new[] { "A", "B" }, "A", "b"); + Check(merged.Length == 1 && merged[0] == "b", "a rename onto a pinned name leaves one pin"); + + Case("Remove_DropsOnlyThatPin"); + Check(ChatPins.Remove(new[] { "Chat", "Network" }, "NETWORK").SequenceEqual(new[] { "Chat" }), "removed"); + Check(ChatPins.Remove(new[] { "Chat" }, "Nope").SequenceEqual(new[] { "Chat" }), "absent = unchanged"); + + Case("Visible_SkipsHiddenTabsKeepsPin"); + string[] pins = { "Network", "Chat" }; + string[] vis = ChatPins.Visible(pins, new[] { "All", "Chat" }); + Check(vis.SequenceEqual(new[] { "Chat" }), "the hidden tab is not drawn"); + Check(pins.SequenceEqual(new[] { "Network", "Chat" }), "the pin is still held"); + Check(ChatPins.Visible(pins, new[] { "All", "Chat", "network" }).SequenceEqual(new[] { "network", "Chat" }), + "back when the server is back, in pin order, as the tab is spelled now"); + + Case("Visible_BaseTabsPinnable"); + Check(ChatPins.Visible(ChatPins.Toggle(Array.Empty(), "All"), new[] { "All", "Chat" }).SequenceEqual(new[] { "All" }), "All"); + Check(ChatPins.Visible(ChatPins.Toggle(Array.Empty(), "Chat"), new[] { "All", "Chat" }).SequenceEqual(new[] { "Chat" }), "Chat"); + } } -- 2.43.0 From ff7c9119d86ee987886b4418d01ae4bd18207944 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:44:58 -0800 Subject: [PATCH 09/12] RynthChat: pin channels to the top bar A push-pin button on each drawer row pins the tab to the main window's header: one button per pin after the channel button (unread badge, right-click to unpin), the ones that do not fit in an overflow button, search keeps 120 px. ChatModel.TogglePin saves; rename, delete and the server-tab seed now go through ChatPins. Extra windows and "Tabs across the top" draw no pins. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 120 +++++++++++++++++- src/RynthCore.Engine/UI/Data/ChatData.cs | 10 +- .../UI/Data/ChatServerTabs.cs | 6 +- 3 files changed, 127 insertions(+), 9 deletions(-) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index f0529b5..43206c8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Numerics; using ImGuiNET; using RynthCore.Engine.Compatibility; @@ -73,6 +74,11 @@ internal sealed class ChatFace : IImGuiPanel private float _inputScroll; private bool _openSettings; + // Pinned tabs in the header (2026-11-15): the ones that did not fit (the overflow button's list), + // and the pin whose right-click menu is open. + private string[] _pinOverflow = Array.Empty(); + private bool _openPinMore, _openPinMenu; + private string _pinMenuTab = ""; /// A line colour changed and isn't saved yet (saved once the picker is let go). private bool _coloursDirty; /// The Chat history slider's value while it's held (0: not held). @@ -181,12 +187,105 @@ internal sealed class ChatFace : IImGuiPanel } if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(ChatModel.CurrentTab()); - // Search fills the rest. - float sx = start.X + _view.LastTabButtonWidth + 4, sw = buttonsX - 4 - sx; + // The pinned tabs, then search fills the rest (at least 120 px: pins that do not fit go into the overflow button). + float sx = start.X + _view.LastTabButtonWidth + 4; + sx = DrawPinnedButtons(sx, start.Y, h, buttonsX - 4 - sx - 120); + float sw = buttonsX - 4 - sx; if (sw > 40) _view.DrawSearch(new Vector2(sx, start.Y), sw); return start.Y + h + 4; } + /// + /// The pinned tabs as buttons after the channel button (drawer mode, main window only): the + /// tab's name, unread badge, highlighted when current; click selects, right-click offers + /// Unpin. Those that do not fit in go into one overflow button. + /// A pin on a hidden tab (its server is not active) is not drawn and not lost. + /// Returns the x after them (+4), or when nothing was drawn. + /// + private float DrawPinnedButtons(float x, float y, float h, float avail) + { + _pinOverflow = Array.Empty(); + if (avail <= 0) return x; + string[] pins = ChatPins.Visible(ChatModel.PinnedTabs, ChatModel.AllTabs()); + if (pins.Length == 0) return x; + + const float gap = 2, overflowW = 22; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + string current = ChatModel.CurrentTab(); + var unreadAll = _view.Unread; + var badges = new string?[pins.Length]; + var widths = new float[pins.Length]; + float total = 0; + for (int i = 0; i < pins.Length; i++) + { + unreadAll.TryGetValue(pins[i], out var unread); + bool active = string.Equals(pins[i], current, StringComparison.OrdinalIgnoreCase); + badges[i] = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null; + widths[i] = ImGuiNET.ImGui.CalcTextSize(pins[i]).X + 12 + (badges[i] != null ? ChatView.BadgeWidth(badges[i]!) + 3 : 0); + total += widths[i] + gap; + } + int fit = pins.Length; + if (total > avail) + { + float room = avail - overflowW - gap, used = 0; + fit = 0; + while (fit < pins.Length && used + widths[fit] + gap <= room) used += widths[fit++] + gap; + if (room < 0) fit = 0; + } + + float start = x; + for (int i = 0; i < fit; i++) + { + string tab = pins[i]; + bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); + unreadAll.TryGetValue(tab, out var unread); + ImGuiNET.ImGui.PushID("pin_" + tab); + if (Button("##pin", "", new Vector2(x, y), new Vector2(widths[i], h), Text, active ? TabActive : BtnFill)) + ChatModel.SelectTab(tab); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _pinMenuTab = tab; _openPinMenu = true; } + if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); + else ImGuiNET.ImGui.SetItemTooltip("Right-click to unpin"); + float textW = ImGuiNET.ImGui.CalcTextSize(tab).X; + dl.AddText(new Vector2(x + 6, y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, tab); + if (badges[i] != null) + ChatView.DrawBadge(dl, new Vector2(x + 6 + textW + 3, y + 4), ChatView.BadgeWidth(badges[i]!), h - 8, badges[i]!, unread.Mention); + ImGuiNET.ImGui.PopID(); + x += widths[i] + gap; + } + if (fit < pins.Length) + { + _pinOverflow = pins.Skip(fit).ToArray(); + if (IconButton("##chat_pinmore", PhosphorIcons.CaretRight, new Vector2(x, y), new Vector2(overflowW, h), Text, BtnFill, font: UiFont.Ui11)) + _openPinMore = true; + ImGuiNET.ImGui.SetItemTooltip("More pinned tabs"); + x += overflowW + gap; + } + return x > start ? x + 2 : x; // the 4 px after the channel button, 2 here and 2 left from the last gap + } + + /// The overflow list and the Unpin menu of the pinned buttons (drawn in DrawPopups). + private void DrawPinPopups() + { + if (_openPinMore) { _openPinMore = false; ImGuiNET.ImGui.OpenPopup("##chat_pinmore"); } + if (_openPinMenu) { _openPinMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_pinmenu"); } + if (ImGuiNET.ImGui.BeginPopup("##chat_pinmore")) + { + string current = ChatModel.CurrentTab(); + foreach (string tab in _pinOverflow) + { + _view.Unread.TryGetValue(tab, out var unread); + bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); + string label = !active && unread.Count > 0 ? $"{tab} ({unread.Count})" : tab; + if (ImGuiNET.ImGui.Selectable(label + "##pinsel_" + tab, active)) ChatModel.SelectTab(tab); + } + ImGuiNET.ImGui.EndPopup(); + } + if (ImGuiNET.ImGui.BeginPopup("##chat_pinmenu")) + { + if (ImGuiNET.ImGui.Selectable("Unpin")) ChatModel.TogglePin(_pinMenuTab); + ImGuiNET.ImGui.EndPopup(); + } + } /// /// "Tabs across the top" (ChatModel.TabsAcross): every tab in a row that wraps left of /// the buttons, as before the drawer; right-click a tab to rename, delete or open it in a @@ -240,6 +339,7 @@ internal sealed class ChatFace : IImGuiPanel var dl = ImGuiNET.ImGui.GetWindowDrawList(); string current = ChatModel.CurrentTab(); var unreadAll = _view.Unread; + string[] pinnedNow = ChatModel.PinnedTabs; float y = start.Y; foreach (string tab in ChatModel.AllTabs()) { @@ -255,12 +355,23 @@ internal sealed class ChatFace : IImGuiPanel else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab) ? "Right-click: open in a new window" : "Right-click to rename, delete or open this tab in a new window"); + // The pin, at the row's right edge, submitted after the row so it takes the click. + const float pinW = 18; + bool pinned = pinnedNow.Contains(tab, StringComparer.OrdinalIgnoreCase); + var pinPos = new Vector2(p.X + w - pinW - 1, y + 1); + var pinSize = new Vector2(pinW, rowH - 2); + ImGuiNET.ImGui.SetCursorScreenPos(pinPos); + if (ImGuiNET.ImGui.InvisibleButton("##pin", pinSize)) ChatModel.TogglePin(tab); + bool pinHot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(pinned ? "Unpin from the top bar" : "Pin to the top bar"); + if (pinned) dl.AddRectFilled(pinPos, pinPos + pinSize, TabActive, 3); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.PushPin, pinPos, pinSize, pinned || pinHot ? Text : Mute); float badgeW = badge != null ? ChatView.BadgeWidth(badge) : 0; float ty = y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; - dl.PushClipRect(p, p + new Vector2(w - (badge != null ? badgeW + 8 : 0), rowH), true); + dl.PushClipRect(p, p + new Vector2(w - pinW - 2 - (badge != null ? badgeW + 4 : 0), rowH), true); dl.AddText(new Vector2(p.X + 6, ty), active ? Teal : Text, tab); dl.PopClipRect(); - if (badge != null) ChatView.DrawBadge(dl, new Vector2(p.X + w - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention); + if (badge != null) ChatView.DrawBadge(dl, new Vector2(p.X + w - pinW - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention); ImGuiNET.ImGui.PopID(); y += rowH + 2; } @@ -362,6 +473,7 @@ internal sealed class ChatFace : IImGuiPanel ChatView.PushPopupStyle(); DrawSettingsPopup(); _view.DrawPopups(); + DrawPinPopups(); ChatView.PopPopupStyle(); } diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index e773554..5d7644c 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -494,6 +494,14 @@ internal static class ChatModel /// The tabs pinned to the main window's top bar, in pin order. Any thread. public static string[] PinnedTabs => Volatile.Read(ref _pinnedTabs); + /// Pins to the top bar, or unpins it. Saved with the settings. Any thread. + public static void TogglePin(string tab) + { + lock (EditLock) + Volatile.Write(ref _pinnedTabs, ChatPins.Toggle(_pinnedTabs, tab)); + SaveSettings(); + } + public static ChatFilterRule[] Filters => Volatile.Read(ref _filters); /// Bumped on every rule / tab / mention-setting change. The pump re-routes when it moves. @@ -925,7 +933,7 @@ internal static class ChatModel foreach (RynthChatFilterDto want in e.Inserts) list.Insert(Math.Min(at++, list.Count), FromDto(want)); if (e.CreateTab != null && !IsBaseTab(e.CreateTab)) Volatile.Write(ref _customTabs, _customTabs.Append(e.CreateTab).ToArray()); - if (e.Pin != null) Volatile.Write(ref _pinnedTabs, _pinnedTabs.Append(e.Pin).ToArray()); + if (e.Pin != null) Volatile.Write(ref _pinnedTabs, ChatPins.Add(_pinnedTabs, e.Pin)); if (e.Seed != null) Volatile.Write(ref _seededTabs, _seededTabs.Append(e.Seed).ToArray()); if (e.TabServer != null && !IsBaseTab(e.TabServer)) { diff --git a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs index 817a2a1..cb32417 100644 --- a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -325,9 +325,7 @@ internal static class ChatServerTabs { Dictionary map = NewMap(tabServers); if (map.Remove(from, out string? server)) map[to] = server; - string[] pinned = pins.Select(t => string.Equals(t, from, StringComparison.OrdinalIgnoreCase) ? to : t) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - return (map, pinned); + return (map, ChatPins.Rename(pins.ToArray(), from, to)); } /// A tab deleted: its server entry and its pin go (the seed mark stays, elsewhere). @@ -336,7 +334,7 @@ internal static class ChatServerTabs { Dictionary map = NewMap(tabServers); map.Remove(tab); - return (map, pins.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); + return (map, ChatPins.Remove(pins.ToArray(), tab)); } // -- Export / Import ------------------------------------------------------------- -- 2.43.0 From 6e271c0955ea8c7ca34515e41fb6e21763670e40 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:49:20 -0800 Subject: [PATCH 10/12] RynthChat pins: review fixes Drawer pin was unclickable: the row now allows overlap and the pin takes the click (and the row menu/tooltip stay off the pin). Header layout is a pure ChatPins.Layout: the overflow button is always drawn when pins do not all fit and its width is reserved before search's 120 px. The pinned chip uses a lighter fill on the current row. ChatPins.Add (idempotent) seeds the server pin; ChatModel.Unpin (one way) backs the header Unpin menu. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 43 +++++++++---------- src/RynthCore.Engine/UI/Data/ChatData.cs | 8 ++++ src/RynthCore.Engine/UI/Data/ChatPins.cs | 27 ++++++++++++ tools/ChatFilterTests/Program.cs | 26 ++++++++++- 4 files changed, 81 insertions(+), 23 deletions(-) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 43206c8..ca483cd 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -189,7 +189,7 @@ internal sealed class ChatFace : IImGuiPanel // The pinned tabs, then search fills the rest (at least 120 px: pins that do not fit go into the overflow button). float sx = start.X + _view.LastTabButtonWidth + 4; - sx = DrawPinnedButtons(sx, start.Y, h, buttonsX - 4 - sx - 120); + sx = DrawPinnedButtons(sx, start.Y, h, buttonsX - 4 - sx - 120 - 2); float sw = buttonsX - 4 - sx; if (sw > 40) _view.DrawSearch(new Vector2(sx, start.Y), sw); return start.Y + h + 4; @@ -205,7 +205,6 @@ internal sealed class ChatFace : IImGuiPanel private float DrawPinnedButtons(float x, float y, float h, float avail) { _pinOverflow = Array.Empty(); - if (avail <= 0) return x; string[] pins = ChatPins.Visible(ChatModel.PinnedTabs, ChatModel.AllTabs()); if (pins.Length == 0) return x; @@ -224,14 +223,9 @@ internal sealed class ChatFace : IImGuiPanel widths[i] = ImGuiNET.ImGui.CalcTextSize(pins[i]).X + 12 + (badges[i] != null ? ChatView.BadgeWidth(badges[i]!) + 3 : 0); total += widths[i] + gap; } - int fit = pins.Length; - if (total > avail) - { - float room = avail - overflowW - gap, used = 0; - fit = 0; - while (fit < pins.Length && used + widths[fit] + gap <= room) used += widths[fit++] + gap; - if (room < 0) fit = 0; - } + // Not all fit: the overflow button is always drawn, and its width comes out of the room + // before search's 120 px. Only when even that leaves search under its floor does search go. + (int fit, bool overflow) = ChatPins.Layout(widths, avail, overflowW, gap); float start = x; for (int i = 0; i < fit; i++) @@ -252,7 +246,7 @@ internal sealed class ChatFace : IImGuiPanel ImGuiNET.ImGui.PopID(); x += widths[i] + gap; } - if (fit < pins.Length) + if (overflow) { _pinOverflow = pins.Skip(fit).ToArray(); if (IconButton("##chat_pinmore", PhosphorIcons.CaretRight, new Vector2(x, y), new Vector2(overflowW, h), Text, BtnFill, font: UiFont.Ui11)) @@ -282,7 +276,7 @@ internal sealed class ChatFace : IImGuiPanel } if (ImGuiNET.ImGui.BeginPopup("##chat_pinmenu")) { - if (ImGuiNET.ImGui.Selectable("Unpin")) ChatModel.TogglePin(_pinMenuTab); + if (ImGuiNET.ImGui.Selectable("Unpin")) ChatModel.Unpin(_pinMenuTab); ImGuiNET.ImGui.EndPopup(); } } @@ -348,23 +342,28 @@ internal sealed class ChatFace : IImGuiPanel string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null; ImGuiNET.ImGui.PushID(tab); var p = new Vector2(start.X, y); - if (Button("##row", "", p, new Vector2(w, rowH), Text, active ? TabActive : BtnFill)) - ChatModel.SelectTab(tab); - if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab); - if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); - else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab) - ? "Right-click: open in a new window" - : "Right-click to rename, delete or open this tab in a new window"); - // The pin, at the row's right edge, submitted after the row so it takes the click. + // The pin, at the row's right edge, submitted after the row so it takes the click + // (the row allows the overlap, as NavFace and MetaFace.List do). const float pinW = 18; - bool pinned = pinnedNow.Contains(tab, StringComparer.OrdinalIgnoreCase); var pinPos = new Vector2(p.X + w - pinW - 1, y + 1); var pinSize = new Vector2(pinW, rowH - 2); + bool overPin = ImGuiNET.ImGui.IsMouseHoveringRect(pinPos, pinPos + pinSize); // the row's own menu and tooltip stay off the pin + ImGuiNET.ImGui.SetNextItemAllowOverlap(); + if (Button("##row", "", p, new Vector2(w, rowH), Text, active ? TabActive : BtnFill)) + ChatModel.SelectTab(tab); + if (!overPin && ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab); + if (!overPin) // the pin has its own tooltip + if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); + else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab) + ? "Right-click: open in a new window" + : "Right-click to rename, delete or open this tab in a new window"); + bool pinned = pinnedNow.Contains(tab, StringComparer.OrdinalIgnoreCase); ImGuiNET.ImGui.SetCursorScreenPos(pinPos); if (ImGuiNET.ImGui.InvisibleButton("##pin", pinSize)) ChatModel.TogglePin(tab); bool pinHot = ImGuiNET.ImGui.IsItemHovered(); ImGuiNET.ImGui.SetItemTooltip(pinned ? "Unpin from the top bar" : "Pin to the top bar"); - if (pinned) dl.AddRectFilled(pinPos, pinPos + pinSize, TabActive, 3); + // A lighter fill than the row's own, or the chip vanishes on the current row. + if (pinned) dl.AddRectFilled(pinPos, pinPos + pinSize, active ? Lighten(TabActive) : TabActive, 3); PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.PushPin, pinPos, pinSize, pinned || pinHot ? Text : Mute); float badgeW = badge != null ? ChatView.BadgeWidth(badge) : 0; float ty = y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 5d7644c..6899ca2 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -502,6 +502,14 @@ internal static class ChatModel SaveSettings(); } + /// Unpins (one way: a stale menu cannot pin it again). Saved. Any thread. + public static void Unpin(string tab) + { + lock (EditLock) + Volatile.Write(ref _pinnedTabs, ChatPins.Remove(_pinnedTabs, tab)); + SaveSettings(); + } + public static ChatFilterRule[] Filters => Volatile.Read(ref _filters); /// Bumped on every rule / tab / mention-setting change. The pump re-routes when it moves. diff --git a/src/RynthCore.Engine/UI/Data/ChatPins.cs b/src/RynthCore.Engine/UI/Data/ChatPins.cs index 76854cc..a81b9cd 100644 --- a/src/RynthCore.Engine/UI/Data/ChatPins.cs +++ b/src/RynthCore.Engine/UI/Data/ChatPins.cs @@ -28,6 +28,14 @@ internal static class ChatPins return pins.Append(tab).ToArray(); } + /// Pins at the end unless it is pinned already (idempotent, unlike Toggle). A blank name changes nothing. + internal static string[] Add(string[] pins, string tab) + { + if (string.IsNullOrWhiteSpace(tab)) return pins.ToArray(); + tab = tab.Trim(); + return pins.Any(p => Same(p, tab)) ? pins.ToArray() : pins.Append(tab).ToArray(); + } + /// The pin follows a renamed tab and keeps its place. If is already pinned, one pin remains. internal static string[] Rename(string[] pins, string from, string to) { @@ -43,6 +51,25 @@ internal static class ChatPins /// Drops the pin of a deleted tab. internal static string[] Remove(string[] pins, string tab) => pins.Where(p => !Same(p, tab)).ToArray(); + /// + /// How many of the pin buttons (button widths in , each followed by + /// ) fit in , and whether an overflow button is + /// needed. When not all fit the overflow button (width + gap) is + /// paid for first, so the buttons that fit are a prefix of the pins. Nothing fits in a + /// negative room: Fit 0 with the overflow button still wanted. + /// + internal static (int Fit, bool Overflow) Layout(float[] widths, float avail, float overflowW, float gap) + { + if (widths.Length == 0) return (0, false); + float total = 0; + foreach (float wd in widths) total += wd + gap; + if (total <= avail) return (widths.Length, false); + float room = avail - overflowW - gap, used = 0; + int fit = 0; + while (fit < widths.Length && used + widths[fit] + gap <= room) used += widths[fit++] + gap; + return (fit, true); + } + /// The pins that have a tab now, in pin order, spelled as the tab is. internal static string[] Visible(string[] pins, string[] allTabs) { diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 7764e41..a96fdf9 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1639,5 +1639,29 @@ internal static class Program Case("Visible_BaseTabsPinnable"); Check(ChatPins.Visible(ChatPins.Toggle(Array.Empty(), "All"), new[] { "All", "Chat" }).SequenceEqual(new[] { "All" }), "All"); Check(ChatPins.Visible(ChatPins.Toggle(Array.Empty(), "Chat"), new[] { "All", "Chat" }).SequenceEqual(new[] { "Chat" }), "Chat"); - } + + Case("Add_IsIdempotent"); + string[] added = ChatPins.Add(new[] { "Chat" }, "Network"); + Check(added.SequenceEqual(new[] { "Chat", "Network" }), "appended"); + Check(ChatPins.Add(added, "network").SequenceEqual(added), "a pinned name (any case) adds nothing"); + Check(ChatPins.Add(added, "").Length == 2 && ChatPins.Add(added, " ").Length == 2, "a blank name adds nothing"); + Check(ChatPins.Add(Array.Empty(), " Net ").SequenceEqual(new[] { "Net" }), "trimmed"); + + Case("Layout_ZeroPins"); + Check(ChatPins.Layout(Array.Empty(), 500, 22, 2) == (0, false), "nothing to draw, no overflow button"); + Check(ChatPins.Layout(Array.Empty(), -50, 22, 2) == (0, false), "also in no room"); + + Case("Layout_AllFit"); + Check(ChatPins.Layout(new[] { 50f, 60f }, 114, 22, 2) == (2, false), "exactly full (50+2+60+2)"); + Check(ChatPins.Layout(new[] { 50f, 60f }, 300, 22, 2) == (2, false), "room to spare"); + + Case("Layout_SomeFit"); + // 50+2 fits in 114-22-2=90, then 52+60+2=114 > 90: one pin, the rest in overflow. + Check(ChatPins.Layout(new[] { 50f, 60f }, 113, 22, 2) == (1, true), "one fits, overflow button"); + Check(ChatPins.Layout(new[] { 50f, 60f, 10f }, 113, 22, 2) == (1, true), "a later small pin does not jump the queue"); + + Case("Layout_NoneFit"); + Check(ChatPins.Layout(new[] { 50f, 60f }, 60, 22, 2) == (0, true), "room for the overflow button only"); + Check(ChatPins.Layout(new[] { 50f }, 10, 22, 2) == (0, true), "less than the overflow button: still wanted"); + Check(ChatPins.Layout(new[] { 50f }, -30, 22, 2) == (0, true), "negative room: still wanted"); } } -- 2.43.0 From ef61144592ba80661e6bbe54224979eb28d758e1 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 10:19:08 -0800 Subject: [PATCH 11/12] RynthChat: All is pinned by default pinnedTabs absent (never set, or a file from before pins) means All is pinned (ChatPins.FromSettings); saving always writes the array, so unpinning everything persists as [] and is not mistaken for "never set". Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/UI/Data/ChatData.cs | 8 +++----- src/RynthCore.Engine/UI/Data/ChatPins.cs | 21 +++++++++++++++++++++ tools/ChatFilterTests/Program.cs | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 6899ca2..10247de 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -476,7 +476,7 @@ internal static class ChatModel private static string[] _seededTabs = Array.Empty(); // owner keys private static Dictionary _tabServers = NewMap(); // tab -> server id private static Dictionary _globalRooms = NewMap(); // server id -> room - private static string[] _pinnedTabs = Array.Empty(); // pin order + private static string[] _pinnedTabs = ChatPins.FromSettings(null); // pin order (All until a file says otherwise) // Published by ApplyServerTabs (render thread), read lock-free by the pump and the faces. private static volatile string[] _activeServers = Array.Empty(); private static volatile SectionChatTabDecl[] _tabDecls = Array.Empty(); @@ -1816,9 +1816,7 @@ internal static class ChatModel string[] seeded = (dto.SeededTabs ?? Array.Empty()) .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - string[] pinned = (dto.PinnedTabs ?? Array.Empty()) - .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + string[] pinned = ChatPins.FromSettings(dto.PinnedTabs); // absent = All; [] stays empty // Under EditLock, as ApplyServerTabs (render thread) edits the same lists. lock (EditLock) { @@ -1893,7 +1891,7 @@ internal static class ChatModel SeededTabs = NullIfEmpty(Volatile.Read(ref _seededTabs)), TabServers = NullIfEmpty(Volatile.Read(ref _tabServers)), GlobalRooms = NullIfEmpty(Volatile.Read(ref _globalRooms)), - PinnedTabs = NullIfEmpty(Volatile.Read(ref _pinnedTabs)), + PinnedTabs = Volatile.Read(ref _pinnedTabs), // always written, empty included: [] = nothing pinned, absent = All Filters = Filters.Select(ToDto).ToArray(), // Only presets the user touched: new presets in later builds start off. Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All diff --git a/src/RynthCore.Engine/UI/Data/ChatPins.cs b/src/RynthCore.Engine/UI/Data/ChatPins.cs index a81b9cd..fafffd8 100644 --- a/src/RynthCore.Engine/UI/Data/ChatPins.cs +++ b/src/RynthCore.Engine/UI/Data/ChatPins.cs @@ -28,6 +28,27 @@ internal static class ChatPins return pins.Append(tab).ToArray(); } + /// The tab pinned when nothing was ever saved. + internal const string DefaultPin = "All"; + + /// + /// The pins a settings file means: absent (never set, or a file from before pins) = All + /// pinned; a saved array, empty included, is exactly what the player left. Blank names are + /// dropped and repeats (any case) kept once. + /// + internal static string[] FromSettings(string[]? saved) + { + if (saved == null) return new[] { DefaultPin }; + var result = new List(saved.Length); + foreach (string s in saved) + { + if (string.IsNullOrWhiteSpace(s)) continue; + string name = s.Trim(); + if (!result.Any(r => Same(r, name))) result.Add(name); + } + return result.ToArray(); + } + /// Pins at the end unless it is pinned already (idempotent, unlike Toggle). A blank name changes nothing. internal static string[] Add(string[] pins, string tab) { diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index a96fdf9..06a1b06 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1647,6 +1647,23 @@ internal static class Program Check(ChatPins.Add(added, "").Length == 2 && ChatPins.Add(added, " ").Length == 2, "a blank name adds nothing"); Check(ChatPins.Add(Array.Empty(), " Net ").SequenceEqual(new[] { "Net" }), "trimmed"); + Case("PinsDefault_AbsentMeansAll"); + Check(ChatPins.FromSettings(null).SequenceEqual(new[] { "All" }), "never set = All pinned"); + RynthChatSettingsDto oldFile = JsonSerializer.Deserialize( + "{\"version\":1,\"customTabs\":[\"Mine\"]}", RynthChatJsonContext.Default.RynthChatSettingsDto)!; + Check(oldFile.PinnedTabs == null && ChatPins.FromSettings(oldFile.PinnedTabs).SequenceEqual(new[] { "All" }), + "a file from before pins = All pinned"); + + Case("PinsDefault_EmptyRoundTrips"); + var noPins = new RynthChatSettingsDto { PinnedTabs = ChatPins.Remove(ChatPins.FromSettings(null), "All") }; + string noPinsJson = JsonSerializer.Serialize(noPins, RynthChatJsonContext.Default.RynthChatSettingsDto); + Check(noPinsJson.Contains("\"pinnedTabs\":[]", StringComparison.Ordinal), "unpinning everything is written as []: " + noPinsJson); + RynthChatSettingsDto noPinsBack = JsonSerializer.Deserialize(noPinsJson, RynthChatJsonContext.Default.RynthChatSettingsDto)!; + Check(noPinsBack.PinnedTabs != null && ChatPins.FromSettings(noPinsBack.PinnedTabs).Length == 0, "and loads as nothing pinned, not All"); + string nullJson = JsonSerializer.Serialize(new RynthChatSettingsDto(), RynthChatJsonContext.Default.RynthChatSettingsDto); + Check(!nullJson.Contains("pinnedTabs", StringComparison.Ordinal), "WhenWritingNull still drops only null"); + string[] kept = ChatPins.FromSettings(new[] { "Chat", " ", "chat", "Network" }); + Check(kept.SequenceEqual(new[] { "Chat", "Network" }), "a saved list is cleaned, order kept"); Case("Layout_ZeroPins"); Check(ChatPins.Layout(Array.Empty(), 500, 22, 2) == (0, false), "nothing to draw, no overflow button"); Check(ChatPins.Layout(Array.Empty(), -50, 22, 2) == (0, false), "also in no room"); -- 2.43.0 From 4d4788ac7afc7617c631a33d1499b7e6629abc90 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 10:21:48 -0800 Subject: [PATCH 12/12] RynthChat pins: source-scan the always-written pin array ChatFilterTests now scans ChatData.cs for the pin save and load lines so a refactor back to NullIfEmpty cannot silently turn "nothing pinned" into "All pinned". Also fixes the save comment that still said pins are left out while empty. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/UI/Data/ChatData.cs | 2 +- tools/ChatFilterTests/Program.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 10247de..52576a4 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -1887,7 +1887,7 @@ internal static class ChatModel LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set RetailColors = ChatLineColors.RetailColors ? null : false, // left out while on (the default) CustomTabs = Volatile.Read(ref _customTabs), - // Left out while empty (2026-11-15), so a file without server tabs or pins is as before. + // Left out while empty: seeded tabs, tab servers, global rooms. Pins are always written (see below). SeededTabs = NullIfEmpty(Volatile.Read(ref _seededTabs)), TabServers = NullIfEmpty(Volatile.Read(ref _tabServers)), GlobalRooms = NullIfEmpty(Volatile.Read(ref _globalRooms)), diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 06a1b06..179af1b 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1664,6 +1664,24 @@ internal static class Program Check(!nullJson.Contains("pinnedTabs", StringComparison.Ordinal), "WhenWritingNull still drops only null"); string[] kept = ChatPins.FromSettings(new[] { "Chat", " ", "chat", "Network" }); Check(kept.SequenceEqual(new[] { "Chat", "Network" }), "a saved list is cleaned, order kept"); + // Source scan (the model is not compiled into this tool): the pin save and load lines are + // what make [] persist, and a refactor back to NullIfEmpty would silently turn "nothing + // pinned" into "All pinned" on the next load. + Case("PinsDefault_SourceScan"); + string? chatData = null; + for (string? dir = AppContext.BaseDirectory; dir != null && chatData == null; dir = Path.GetDirectoryName(dir)) + { + string candidate = Path.Combine(dir, "src", "RynthCore.Engine", "UI", "Data", "ChatData.cs"); + if (File.Exists(candidate)) chatData = candidate; + } + Check(chatData != null, "found src/RynthCore.Engine/UI/Data/ChatData.cs by walking up from " + AppContext.BaseDirectory); + if (chatData != null) + { + string src = File.ReadAllText(chatData); + Check(src.Contains("PinnedTabs = Volatile.Read(ref _pinnedTabs)", StringComparison.Ordinal), "save writes the pin array as is"); + Check(src.Contains("ChatPins.FromSettings(dto.PinnedTabs)", StringComparison.Ordinal), "load goes through FromSettings (absent = All)"); + Check(!src.Contains("NullIfEmpty(Volatile.Read(ref _pinnedTabs))", StringComparison.Ordinal), "save does not drop an empty pin array"); + } Case("Layout_ZeroPins"); Check(ChatPins.Layout(Array.Empty(), 500, 22, 2) == (0, false), "nothing to draw, no overflow button"); Check(ChatPins.Layout(Array.Empty(), -50, 22, 2) == (0, false), "also in no room"); -- 2.43.0