diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 115de74..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)"); } @@ -428,9 +433,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..e773554 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,30 @@ 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 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; + + /// 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 +512,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 +643,31 @@ 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) => 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); + /// The tabs a Move/Copy rule can send lines to: every tab but All. public static string[] TargetTabs() => AllTabs().Where(t => t != "All").ToArray(); @@ -648,11 +695,13 @@ internal static class ChatModel { name = name.Trim(); if (name.Length == 0) return null; - string? existing = AllTabs().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) @@ -675,17 +724,23 @@ 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. + (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; @@ -701,18 +756,235 @@ 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. + (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) + 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. + // + // 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. 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, 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, + IReadOnlyDictionary? serverNames = null) + { + 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); + } + 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); + 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 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 + 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) + { + 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; + 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) + 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; + }); + } + + /// 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) + { + 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; + } + + /// + /// 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 + 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(); + } + } + + 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) + { + 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 +1018,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 +1045,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 +1056,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) @@ -818,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); } @@ -854,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) @@ -883,6 +1158,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 +1171,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 +1199,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 +1639,10 @@ internal static class ChatModel public const int SettingsVersion = 2; private static readonly object SaveLock = new(); private static int _settingsLoaded; + // 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 => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_settings.json"); @@ -1357,9 +1651,13 @@ internal static class ChatModel public static void EnsureSettingsLoaded() { if (Interlocked.Exchange(ref _settingsLoaded, 1) != 0) return; - LoadSettings(); + // 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 @@ -1376,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."); @@ -1384,31 +1695,41 @@ 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(); + // 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; } } /// 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) { @@ -1449,6 +1770,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,19 +1794,40 @@ 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 + 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; } } @@ -1528,6 +1873,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 new file mode 100644 index 0000000..817a2a1 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -0,0 +1,360 @@ +// ============================================================================ +// 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 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, 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; +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 +{ + /// 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 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 + // 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); + + 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; + + /// 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 + "] "; + + /// 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 = Has(s.Seeded, key); + string clashBase = ClashName(d, s.ServerName); + + 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); + + // 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]; + var want = 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, + // 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)); + } + 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; + 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, 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); + } + + /// + /// 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. 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) + && 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 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). 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, 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) && !Has(tabs, r.Tab!)) tabs.Add(r.Tab!); + foreach (string tab in tabs) + { + 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; + } + + 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); + } + + // -- 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/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/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 08f5de2..c37841e 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -61,6 +61,20 @@ // 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; "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 +// 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 +159,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 +177,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 +201,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 +304,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 +327,67 @@ 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 ? "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")) + { + 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; } + // 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 ───────────────────────────────────────────────────── /// A lower-case id of letters, digits, '-' and '_' (at most MaxIdLength), else "". diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs index a677357..4ffa693 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,22 @@ 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(); + var names = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (ServerState s in servers) + { + if (s.Active) active.Add(s.Id); + 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}"); } } /// The built-in servers, then every server a manifest declares with a new id. 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 20cb2dd..043014f 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; @@ -53,6 +54,9 @@ internal static class Program RetailRules(); RetailSetting(); TabsAcrossSetting(); + ServerTabSettingsRoundTrip(); + ServerTabDiscovery(); + ServerTabPlans(); SharedFileReload(); LineColorTags(); LineColorKinds(); @@ -1108,6 +1112,361 @@ 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"); + } + + // -- Server default tabs (2026-11-15) -- + + 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) + { + 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; + } + + + /// 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() + { + 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("Apply_SeedsFresh"); + Check(key == "dreamweave/dereth-network", "owner key"); + 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("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("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"); + 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"); + 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_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"); + 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" }; + 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("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) + { + 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"); diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs index bfdeb98..81a7ffd 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,79 @@ 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"); + 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 = + { + """{ "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": [] }""", + """{ "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", + "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); + 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)");