From 05a6d7d088f46c5311f81553c44f7ffe905af27f Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 08:59:53 -0800 Subject: [PATCH] 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);