diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 115de74..ce4a8e5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -428,9 +428,13 @@ internal sealed class ChatFiltersFace : IImGuiPanel if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber); if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0) return ("Pick a tab: until then it only colours.", Amber); - if (!r.Enabled) return ("Off.", Faded(Mute)); + // A server plugin's tab rule (ChatModel.ApplyServerTabs): kept in step with its manifest, so + // only on/off and the colour stay as the player sets them. + string from = r.Owner.Length > 0 ? $"Server rule ({r.Server}, kept up to date by its plugin). " : ""; + if (from.Length > 0 && !ChatModel.ServerActive(r.Server)) return (from + "Not running: that server is not active.", Faded(Mute)); + if (!r.Enabled) return (from + "Off.", Faded(Mute)); int hits = System.Threading.Volatile.Read(ref r.Hits); - return (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}.", Faded(Mute)); + return (from + (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}."), Faded(Mute)); } /// Left-to-right placement that wraps to a new row when the next item doesn't fit. diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 69b7adf..3874098 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -64,6 +64,7 @@ using System.Threading; using RynthCore.Engine.Compatibility; using RynthCore.Engine.ImGuiBackend; using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI.Sections; namespace RynthCore.Engine.UI.Data; @@ -179,6 +180,10 @@ internal sealed unsafe class ChatSource : UiSource if (line.Route.Mention) ChatModel.PumpMentionSound(); added.Add(line); } + // A server tab's Global room, seen in chat (ChatModel.ApplyServerTabs). A new room bumps the + // filter version, so the next poll routes the kept lines, these included, with the new rule. + try { ChatModel.PumpDiscoverGlobalRoom(added); } + catch (Exception ex) { RynthLog.UI($"ChatSource: Global room check failed ({ex.GetType().Name}: {ex.Message})."); } if (added.Count == 0) { RelayRead(added); @@ -464,7 +469,35 @@ internal static class ChatModel private static string[] _customTabs = Array.Empty(); private static long _filtersVersion = 1; private static long _routesVersion = 1; - private static (long Version, string[] Tabs) _allTabs; + private static (long Version, string[] Active, string[] Tabs) _allTabs; + + // Server default tabs (2026-11-15, ChatServerTabs). Written only under EditLock and replaced, + // never changed in place, like _filters, so any thread can read them; saved with the settings. + private static string[] _seededTabs = Array.Empty(); // owner keys + private static Dictionary _tabServers = NewMap(); // tab -> server id + private static Dictionary _globalRooms = NewMap(); // server id -> room + private static string[] _pinnedTabs = Array.Empty(); // pin order + // Published by ApplyServerTabs (render thread), read lock-free by the pump and the faces. + private static volatile string[] _activeServers = Array.Empty(); + private static volatile SectionChatTabDecl[] _tabDecls = Array.Empty(); + + private static Dictionary NewMap(IDictionary? from = null) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (from != null) + foreach (var kv in from) + if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value)) map[kv.Key.Trim()] = kv.Value.Trim(); + return map; + } + + /// The ids of the servers active now (SectionRegistry's verdicts). Any thread; never changed in place. + public static string[] ActiveServers => _activeServers; + + /// Does a rule or tab for apply now ("" = every server)? Any thread. + public static bool ServerActive(string server) => ChatRouter.ServerIn(_activeServers, server); + + /// The tabs pinned to the main window's top bar, in pin order. Any thread. + public static string[] PinnedTabs => Volatile.Read(ref _pinnedTabs); public static ChatFilterRule[] Filters => Volatile.Read(ref _filters); @@ -484,15 +517,25 @@ internal static class ChatModel /// A rule just made from a chat line: the rule editor scrolls to it and flashes it. public static volatile ChatFilterRule? FocusRule; - public static void EditFilters(Action> edit) + public static void EditFilters(Action> edit) => EditFiltersIfChanged(list => { edit(list); return true; }); + + /// + /// An edit that may turn out to change nothing: returns whether it + /// changed anything, and only then is the list published, the version bumped and the + /// settings saved. Runs under EditLock, like every edit. (Its own name, not an EditFilters + /// overload: a lambda such as list => list.Remove(r) would bind to the bool overload.) + /// + public static bool EditFiltersIfChanged(Func, bool> edit) { + bool changed; lock (EditLock) { var list = new List(_filters); - edit(list); - Volatile.Write(ref _filters, list.ToArray()); + changed = edit(list); + if (changed) Volatile.Write(ref _filters, list.ToArray()); } - FiltersChanged(); + if (changed) FiltersChanged(); + return changed; } /// Moves a rule one place up (-1) or down (+1). Order matters (see the header). @@ -605,22 +648,44 @@ internal static class ChatModel /// public static string[] AllTabs() { + // Read the version before the active set: ApplyServerTabs publishes the set and only then + // bumps the version, so a list cached under the new version was built from the new set. + // The set is part of the key as well, so a list built from an older set is never reused. long version = FiltersVersion; + string[] active = ActiveServers; var cached = _allTabs; - if (cached.Tabs != null && cached.Version == version) return cached.Tabs; - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var tabs = new List(); - foreach (string t in BaseTabs) if (seen.Add(t)) tabs.Add(t); - foreach (string t in Volatile.Read(ref _customTabs)) if (seen.Add(t)) tabs.Add(t); - foreach (ChatFilterRule rule in Filters) - if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 && seen.Add(rule.Tab)) tabs.Add(rule.Tab); - foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs()) - if (seen.Add(t)) tabs.Add(t); - string[] result = tabs.ToArray(); - _allTabs = (version, result); + if (cached.Tabs != null && cached.Version == version && ReferenceEquals(cached.Active, active)) return cached.Tabs; + string[] result = BuildTabs(active); + _allTabs = (version, active, result); return result; } + /// + /// AllTabs, or with null every tab including those of inactive + /// servers (a tab named by "tabServers" shows only while its server is active). + /// + private static string[] BuildTabs(string[]? active) + { + Dictionary tabServers = Volatile.Read(ref _tabServers); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var tabs = new List(); + void Add(string t) + { + if (active != null && !IsBaseTab(t) && tabServers.TryGetValue(t, out string? server) + && !ChatRouter.ServerIn(active, server)) return; + if (seen.Add(t)) tabs.Add(t); + } + foreach (string t in BaseTabs) Add(t); + foreach (string t in Volatile.Read(ref _customTabs)) Add(t); + foreach (ChatFilterRule rule in Filters) + if (rule.Enabled && rule.Routes && rule.Tab.Length > 0) Add(rule.Tab); + foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs()) Add(t); + return tabs.ToArray(); + } + + /// Is a tab at all, shown or not (its server may be inactive)? + private static bool TabExists(string tab) => BuildTabs(null).Contains(tab, StringComparer.OrdinalIgnoreCase); + /// The tabs a Move/Copy rule can send lines to: every tab but All. public static string[] TargetTabs() => AllTabs().Where(t => t != "All").ToArray(); @@ -675,13 +740,24 @@ internal static class ChatModel { newName = newName.Trim(); if (newName.Length == 0 || IsBaseTab(tab)) return false; + // Every tab counts, also one hidden because its server is not active, or the two would merge. if (!string.Equals(tab, newName, StringComparison.OrdinalIgnoreCase) - && AllTabs().Contains(newName, StringComparer.OrdinalIgnoreCase)) return false; + && TabExists(newName)) return false; lock (EditLock) { string[] tabs = _customTabs.Select(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase) ? newName : t).ToArray(); if (!tabs.Contains(newName)) tabs = tabs.Append(newName).ToArray(); Volatile.Write(ref _customTabs, tabs); + // A server's tab stays that server's, and a pinned tab stays pinned in its place. + if (_tabServers.TryGetValue(tab, out string? server)) + { + Dictionary map = NewMap(_tabServers); + map.Remove(tab); + map[newName] = server; + Volatile.Write(ref _tabServers, map); + } + Volatile.Write(ref _pinnedTabs, + _pinnedTabs.Select(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase) ? newName : t).ToArray()); } foreach (ChatFilterRule rule in Filters) if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) @@ -701,18 +777,249 @@ internal static class ChatModel public static void DeleteCustomTab(string tab) { lock (EditLock) + { Volatile.Write(ref _customTabs, _customTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); - foreach (ChatFilterRule rule in Filters) - if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy - && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) - rule.Enabled = false; + // A server's tab: its seed mark stays (seededTabs), so ApplyServerTabs never re-creates it. + if (_tabServers.ContainsKey(tab)) + { + Dictionary map = NewMap(_tabServers); + map.Remove(tab); + Volatile.Write(ref _tabServers, map); + } + Volatile.Write(ref _pinnedTabs, + _pinnedTabs.Where(t => !string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)).ToArray()); + // Inside the lock with the tab's removal, so ApplyServerTabs never sees the tab gone + // while its rules are still on (it would take the tab for an existing one). + foreach (ChatFilterRule rule in _filters) + if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy + && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) + rule.Enabled = false; + } foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All) if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase)) preset.Enabled = false; FiltersChanged(); } + // -- Server default tabs (2026-11-15) --------------------------------- + // + // A server plugin's sections manifest can declare chat tabs ("chatTabs", SectionManifest.cs). + // What they become is decided by ChatServerTabs (pure; tools/ChatFilterTests) and applied here: + // the tab is created and pinned once (seededTabs), its rules ("owner" = "server/id") are + // rewritten from the manifest on every read, the tab shows and its rules run only while its + // server is active (tabServers, ChatFilterRule.Server), and the Global-room rule follows the + // room chat last showed (globalRooms). + // + // Threads. Two callers: SectionRegistry.Rebuild on AC's render thread (every second, with every + // manifest's entries and the active servers), and ChatSource.PollLines on the pump (a line + // showed this server's Global room). Both apply through EditFiltersIfChanged, under EditLock, + // the lock every rule and tab edit and a settings reload take, so the two are serialized with + // each other, with the editors and with LoadSettings. Nothing done while holding EditLock takes + // another lock or calls out (no SectionRegistry, no plugin export, no file I/O; the save is + // queued to the background writer after the lock is released), so no thread can hold EditLock + // while waiting on one that wants it: no deadlock. The pump never calls into SectionRegistry; it + // reads what Rebuild last published (_tabDecls, _activeServers: volatile references to arrays + // never changed in place). The active set is read once per router (ChatRouter keeps the + // reference) and once per AllTabs build, never per line, and it is published BEFORE the version + // bump that announces it, so a reader that sees the new version also sees the new set. + // + // No-op. Rebuild calls ApplyServerTabs every second, so in the steady state it must neither save + // nor bump the version. Every write is guarded by a comparison with what is already there: the + // active set (as a sorted set), each owned rule (ChatServerTabs.SameRule on canonical forms, + // both sides through BuildRule and ToDto), the tab, the pin, the seed mark and the tab's server + // (each added only when missing, never overwritten). Only a write sets "changed", and only + // "changed" publishes, bumps and saves (EditFiltersIfChanged). + + /// + /// Render thread (SectionRegistry.Rebuild): every manifest's chat tab entries and the ids of the + /// active servers. Publishes the active set (re-routing and re-listing tabs when it moved) and + /// applies the entries of active servers. Cheap and silent when nothing changed. + /// + public static void ApplyServerTabs(IReadOnlyList decls, IReadOnlyCollection activeServers) + { + string[] active = activeServers.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(s => s, StringComparer.OrdinalIgnoreCase).ToArray(); + if (!SameServers(active, _activeServers)) + { + _activeServers = active; // before the bump: see the threading note above + Interlocked.Increment(ref _filtersVersion); + } + + // One entry per owner key (two plugins declaring the same one would rewrite each other's rules every second). + var unique = new List(decls.Count); + foreach (SectionChatTabDecl d in decls) + if (!unique.Exists(u => string.Equals(ChatServerTabs.OwnerKey(u), ChatServerTabs.OwnerKey(d), StringComparison.OrdinalIgnoreCase))) + unique.Add(d); + if (!SameDecls(unique, _tabDecls)) _tabDecls = unique.ToArray(); + + // Not before the settings file is read: seeding the empty defaults would save them over it. + if (!_settingsReady) return; + string[] now = _activeServers; + if (!unique.Exists(d => ChatRouter.ServerIn(now, d.Server))) return; // nothing to apply: no lock + EditFiltersIfChanged(list => + { + bool changed = false; + foreach (SectionChatTabDecl d in unique) + if (ChatRouter.ServerIn(now, d.Server)) changed |= ApplyServerTab(list, d); + return changed; + }); + } + + /// + /// Pump thread (ChatSource.PollLines): a new line from a network speaker in a room is that + /// server's Global room; when it differs from the stored one, store it and rewrite the + /// Global-room rule. Lines from no active server's entry cost nothing. + /// + internal static void PumpDiscoverGlobalRoom(IReadOnlyList added) + { + SectionChatTabDecl[] decls = _tabDecls; + if (decls.Length == 0 || added.Count == 0 || !_settingsReady) return; + string[] active = _activeServers; + bool any = false; + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(r => r.GlobalRoom)) { any = true; break; } + if (!any) return; + + string? room = null; + foreach (ChatLine line in added) + if (line.Text.Length > 0 && line.Text[0] == '[' && ChatServerTabs.DiscoverRoom(line.Text) is { } r) room = r; + if (room == null) return; + string seen = room; + Dictionary rooms = Volatile.Read(ref _globalRooms); + bool news = false; + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(x => x.GlobalRoom) + && !(rooms.TryGetValue(d.Server, out string? have) && have == seen)) { news = true; break; } + if (!news) return; // the usual case on a room line: the room is already known, no lock + + EditFiltersIfChanged(list => + { + bool changed = false; + Dictionary map = NewMap(_globalRooms); + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server) && d.Rules.Any(x => x.GlobalRoom) + && !(map.TryGetValue(d.Server, out string? have) && have == seen)) + { + map[d.Server] = seen; + changed = true; + } + if (!changed) return false; + Volatile.Write(ref _globalRooms, map); + RynthLog.UI($"ChatModel: the Global room is now [{seen}] (seen in chat)."); + foreach (SectionChatTabDecl d in decls) + if (ChatRouter.ServerIn(active, d.Server)) ApplyServerTab(list, d); + return true; + }); + } + + /// One entry, under EditLock: plans it (ChatServerTabs.Plan) and writes only what differs. True when it wrote. + private static bool ApplyServerTab(List list, SectionChatTabDecl d) + { + string key = ChatServerTabs.OwnerKey(d); + var ownedAt = new List(); + for (int i = 0; i < list.Count; i++) + if (string.Equals(list[i].Owner, key, StringComparison.OrdinalIgnoreCase)) ownedAt.Add(i); + if (ownedAt.Count == 0 && d.Rules.Length > 0 && ChatServerTabs.Reclaim(d, list.Select(ToDto).ToArray()) is { } found) + ownedAt.AddRange(found); // an older engine dropped "owner": these are ours, not a second set + + // The tabs there are: created ones, and those an enabled Move/Copy rule fills (AllTabs, unfiltered). + var existing = new List(BaseTabs); + existing.AddRange(_customTabs); + foreach (ChatFilterRule rule in list) + if (rule.Enabled && rule.Routes && rule.Tab.Length > 0) existing.Add(rule.Tab); + string? room = _globalRooms.TryGetValue(d.Server, out string? r) ? r : null; + var state = new ChatServerTabs.SeedState(_seededTabs, existing, ownedAt.Select(i => ToDto(list[i])).ToArray()); + ChatServerTabs.SeedPlan plan = ChatServerTabs.Plan(d, state, room); + + bool changed = false; + int both = Math.Min(ownedAt.Count, plan.Rules.Length); + for (int i = 0; i < both; i++) changed |= RefreshRule(list[ownedAt[i]], plan.Rules[i]); + if (plan.Rules.Length > both) + { + // New rules go after the entry's last rule, or at the end (as a rule the player adds). + int at = ownedAt.Count > 0 ? ownedAt.Max() + 1 : list.Count; + for (int i = both; i < plan.Rules.Length; i++) list.Insert(at++, FromDto(plan.Rules[i])); + changed = true; + } + else if (ownedAt.Count > both) + { + foreach (int i in ownedAt.Skip(both).OrderByDescending(i => i)) list.RemoveAt(i); + changed = true; + } + + string tab = plan.TabName; + bool baseTab = IsBaseTab(tab); + if (plan.CreateTab && !baseTab && !_customTabs.Contains(tab, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _customTabs, _customTabs.Append(tab).ToArray()); + changed = true; + } + if (plan.Pin && !_pinnedTabs.Contains(tab, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _pinnedTabs, _pinnedTabs.Append(tab).ToArray()); + changed = true; + } + if (plan.MarkSeeded && !_seededTabs.Contains(key, StringComparer.OrdinalIgnoreCase)) + { + Volatile.Write(ref _seededTabs, _seededTabs.Append(key).ToArray()); + changed = true; + } + // The tab is the server's while it exists (a deleted one gets no entry back). Added when + // missing, never overwritten, so two entries naming one tab can't take turns. + bool tabThere = plan.CreateTab || existing.Contains(tab, StringComparer.OrdinalIgnoreCase); + if (tabThere && !baseTab && !_tabServers.ContainsKey(tab)) + { + Dictionary map = NewMap(_tabServers); + map[tab] = d.Server; + Volatile.Write(ref _tabServers, map); + changed = true; + } + if (changed) RynthLog.UI($"ChatModel: server tab \"{tab}\" ({key}) updated from the {d.Server} manifest{(plan.CreateTab ? " (created)" : "")}."); + return changed; + } + + /// Makes what Plan wants, field by field; false (nothing written) when it already is. + private static bool RefreshRule(ChatFilterRule rule, RynthChatFilterDto want) + { + ChatFilterRule w = BuildRule(want); // the canonical form, not compiled + if (ChatServerTabs.SameRule(ToDto(w), ToDto(rule))) return false; + rule.Owner = w.Owner; + rule.Server = w.Server; + rule.Tab = w.Tab; + rule.Action = w.Action; + rule.When = w.When; + rule.GlobalRoom = w.GlobalRoom; + rule.Enabled = w.Enabled; + if (rule.Mode != w.Mode || !string.Equals(rule.Pattern, w.Pattern, StringComparison.Ordinal)) + { + rule.Mode = w.Mode; + rule.Pattern = w.Pattern; + rule.Recompile(); + } + return true; // its colour is the player's and stays + } + + private static bool SameServers(string[] a, string[] b) + { + if (ReferenceEquals(a, b)) return true; + if (a.Length != b.Length) return false; + for (int i = 0; i < a.Length; i++) + if (!string.Equals(a[i], b[i], StringComparison.OrdinalIgnoreCase)) return false; + return true; + } + + private static bool SameDecls(List a, SectionChatTabDecl[] b) + { + if (a.Count != b.Length) return false; + for (int i = 0; i < b.Length; i++) + if (!ReferenceEquals(a[i], b[i])) return false; + return true; + } + + private static string[]? NullIfEmpty(string[] a) => a.Length > 0 ? a : null; + private static Dictionary? NullIfEmpty(Dictionary m) => m.Count > 0 ? m : null; + /// Is the line shown under (rules applied, no search)? public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel); @@ -746,7 +1053,7 @@ internal static class ChatModel long version = FiltersVersion; var cached = _pumpRouter; if (cached is { } c && c.Version == version && c.Name == name) return c.Router; - var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true); + var router = new ChatRouter(Filters, BuildMentionRegex(name), name, countHits: true, ActiveServers); _pumpRouter = (version, name, router); return router; } @@ -773,7 +1080,7 @@ internal static class ChatModel if (cached is { } c && c.Version == version && c.Name == name) router = c.Router; else { - router = new ChatRouter(Filters, mention: null, name, countHits: false); + router = new ChatRouter(Filters, mention: null, name, countHits: false, ActiveServers); _retailRouter = (version, name, router); } return ChatRetailVerdict.IsHidden(router, line, chatType); @@ -784,7 +1091,7 @@ internal static class ChatModel { string name = SessionStateRegistry.LastCharacterName; if (string.IsNullOrWhiteSpace(name)) name = _pumpName ?? ""; - return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false); + return new ChatRouter(Filters, BuildMentionRegex(name.Trim()), name, countHits: false, ActiveServers); } private static Regex? BuildMentionRegex(string name) @@ -883,6 +1190,10 @@ internal static class ChatModel Color = f.ColorMode != ChatColorMode.None || f.ColorArgb != ChatFilterRule.DefaultColor ? FormatColor(f.ColorArgb) : null, // Absent for a Regex rule, so a file without plain-text rules is written as before. Mode = ChatRuleMatching.ToJson(f.Mode), + // Absent on the player's own rules (2026-11-15, server default tabs). + Server = f.Server.Length > 0 ? f.Server : null, + Owner = f.Owner.Length > 0 ? f.Owner : null, + GlobalRoom = f.GlobalRoom ? true : null, }; /// @@ -892,6 +1203,14 @@ internal static class ChatModel /// it out of All too). /// private static ChatFilterRule FromDto(RynthChatFilterDto f) + { + ChatFilterRule rule = BuildRule(f); + rule.Recompile(); + return rule; + } + + /// FromDto without compiling the pattern (ApplyServerTabs compares canonical forms every second). + private static ChatFilterRule BuildRule(RynthChatFilterDto f) { string tab = (f.Tab ?? "").Trim(); var rule = new ChatFilterRule @@ -912,8 +1231,11 @@ internal static class ChatModel ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, // Absent (every file before 2026-10-05): Regex, as those rules always were. Mode = ChatRuleMatching.Parse(f.Mode), + // Absent (the player's own rules, and every file before 2026-11-15): every server, no owner. + Server = (f.Server ?? "").Trim(), + Owner = (f.Owner ?? "").Trim(), + GlobalRoom = f.GlobalRoom ?? false, }; - rule.Recompile(); return rule; } @@ -1349,6 +1671,9 @@ internal static class ChatModel public const int SettingsVersion = 2; private static readonly object SaveLock = new(); private static int _settingsLoaded; + // Set once the first load has finished (_settingsLoaded is set as it starts). ApplyServerTabs + // waits for it: seeding into the empty defaults would save them over the shared file. + private static volatile bool _settingsReady; private static string SettingsPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_settings.json"); @@ -1357,7 +1682,8 @@ internal static class ChatModel public static void EnsureSettingsLoaded() { if (Interlocked.Exchange(ref _settingsLoaded, 1) != 0) return; - LoadSettings(); + try { LoadSettings(); } + finally { _settingsReady = true; } } // Every client shares rynthchat_settings.json and saves its whole state, so a client that @@ -1449,6 +1775,9 @@ internal static class ChatModel rules.Add(rule); // A tab typed into a rule used to exist only while the rule was on: // make it a real tab, so turning the rule off doesn't drop the tab. + // Not for a server plugin's rule that is off: deleting its tab turned it off, + // and the deleted tab must stay deleted (ApplyServerTabs keeps the rule). + if (rule.Owner.Length > 0 && !rule.Enabled) continue; if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy && rule.Tab.Length > 0 && !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase)) tabs.Add(rule.Tab); @@ -1470,13 +1799,32 @@ internal static class ChatModel && !tabs.Contains(preset.Tab, StringComparer.OrdinalIgnoreCase)) tabs.Add(preset.Tab); } - _customTabs = tabs.ToArray(); - _filters = rules.ToArray(); + // Server default tabs (2026-11-15): absent in every older file, and in a file an older + // engine saved over (it drops what it doesn't know). ApplyServerTabs then finds its + // rules and tab again instead of adding new ones (ChatServerTabs.Plan / Reclaim). + string[] seeded = (dto.SeededTabs ?? Array.Empty()) + .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + string[] pinned = (dto.PinnedTabs ?? Array.Empty()) + .Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + // Under EditLock, as ApplyServerTabs (render thread) edits the same lists. + lock (EditLock) + { + _customTabs = tabs.ToArray(); + _filters = rules.ToArray(); + _seededTabs = seeded; + _tabServers = NewMap(dto.TabServers); + _globalRooms = NewMap(dto.GlobalRooms); + _pinnedTabs = pinned; + } Interlocked.Increment(ref _filtersVersion); - if (!reload && !string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) + // Every tab, also one whose server isn't active (yet: at startup no server is known). + string[] everyTab = BuildTabs(null); + if (!reload && !string.IsNullOrEmpty(dto.ActiveChannel) && everyTab.Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = dto.ActiveChannel; - else if (reload && !AllTabs().Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) + else if (reload && !everyTab.Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = "All"; // the tab this client was on was removed elsewhere } catch (Exception ex) when (reload) @@ -1528,6 +1876,11 @@ internal static class ChatModel LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set RetailColors = ChatLineColors.RetailColors ? null : false, // left out while on (the default) CustomTabs = Volatile.Read(ref _customTabs), + // Left out while empty (2026-11-15), so a file without server tabs or pins is as before. + SeededTabs = NullIfEmpty(Volatile.Read(ref _seededTabs)), + TabServers = NullIfEmpty(Volatile.Read(ref _tabServers)), + GlobalRooms = NullIfEmpty(Volatile.Read(ref _globalRooms)), + PinnedTabs = NullIfEmpty(Volatile.Read(ref _pinnedTabs)), Filters = Filters.Select(ToDto).ToArray(), // Only presets the user touched: new presets in later builds start off. Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs index 8decf42..6c9dd51 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRouting.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -202,6 +202,13 @@ internal sealed class ChatFilterRule public const uint DefaultColor = 0xFFFFD27A; /// 0xAARRGGBB. public volatile uint ColorArgb = DefaultColor; + /// A server plugin's tab rule (2026-11-15, ChatServerTabs): the server id it runs on, "" + /// = every server. The router skips it while that server is not active. + public volatile string Server = ""; + /// "server/entry id" of the plugin entry that owns it, "" for the player's own rule. + public volatile string Owner = ""; + /// Its pattern follows the Global room discovered from chat (ChatModel.ApplyServerTabs). + public volatile bool GlobalRoom; private volatile WhenSpec _when = WhenSpec.Any; /// "" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions). @@ -311,21 +318,34 @@ internal sealed class ChatRouter private readonly Regex? _mention; private readonly string _self; private readonly bool _countHits; + private readonly string[] _activeServers; private readonly long[] _passTicks; private long _passBudgetTicks = PassBudgetTicks; private bool _inPass; /// Your character's name ("" unknown): your own emotes don't mention you. /// Count matches into ChatFilterRule.Hits (the pump's router; not the test box's). - public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits) + /// The active server ids (ChatModel.ActiveServers, read once here): a rule + /// with a Server outside them is skipped. Null: none, so only rules for every server run. + public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits, string[]? activeServers = null) { _rules = rules; _mention = mention; _self = self.Trim(); _countHits = countHits; + _activeServers = activeServers ?? Array.Empty(); _passTicks = new long[rules.Length]; } + /// Does a rule for run ("" = every server)? + internal static bool ServerIn(string[] active, string server) + { + if (server.Length == 0) return true; + foreach (string s in active) + if (string.Equals(s, server, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + /// /// Before routing the kept lines again: hit counts restart, and /// each rule's time is watched (PassBudgetMs per PassBudgetLines lines, never less than @@ -381,6 +401,9 @@ internal sealed class ChatRouter { ChatFilterRule rule = _rules[i]; if (!rule.Enabled || rule.Slow) continue; + // A server plugin's rule runs only on its server (the snapshot this router was built with; + // a change of active servers bumps the filter version, so the pump builds a new router). + if (!ServerIn(_activeServers, rule.Server)) continue; Regex? rx = rule.Compiled; if (rx == null) continue; ChatRuleAction action = rule.Action; diff --git a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs index b3b02b1..490115a 100644 --- a/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs +++ b/src/RynthCore.Engine/UI/Data/ChatServerTabs.cs @@ -93,4 +93,72 @@ internal static class ChatServerTabs } return new SeedPlan(create, tabName, create && d.Pinned, !seeded, rules); } + + /// + /// True when a stored rule already is what Plan wants, on every field Plan sets (owner, + /// server, tab, action, when, mode, pattern, globalRoom, enabled); colours are the player's + /// and are not compared. Both sides must come through the same rule-to-JSON conversion + /// (ChatModel compares canonical forms), so absent and empty mean the same here as well. + /// This is what keeps ChatModel.ApplyServerTabs, which runs every second, from saving + /// when nothing changed. + /// + internal static bool SameRule(RynthChatFilterDto want, RynthChatFilterDto have) => + Same(want.Owner, have.Owner) && Same(want.Server, have.Server) && Same(want.Tab, have.Tab) + && string.Equals(want.Action ?? "", have.Action ?? "", StringComparison.OrdinalIgnoreCase) + && Same(want.When, have.When) + && ChatRuleMatching.Parse(want.Mode) == ChatRuleMatching.Parse(have.Mode) + && Same(want.Pattern, have.Pattern) + && (want.GlobalRoom ?? false) == (have.GlobalRoom ?? false) + && want.Enabled == have.Enabled; + + private static bool Same(string? a, string? b) => string.Equals(a ?? "", b ?? "", StringComparison.Ordinal); + + private static readonly string[] Rooms = { "General", "Trade", "LFG", "Roleplay" }; + + /// + /// An older engine rewrote the shared settings file and dropped "owner" from this entry's + /// rules: finds them again among the ownerless rules, so a refresh rewrites them instead of + /// adding a second set (which would grow by one set per old-engine save). A rule matches a + /// declared one on action, when, mode and pattern; a GlobalRoom rule matches "[room] " + /// (Starts with) for any room. Every declared rule must be found, all in one tab (the + /// entry's name is tried first). Returns their indexes in , in + /// declaration order, or null. + /// + internal static int[]? Reclaim(SectionChatTabDecl d, IReadOnlyList rules) + { + if (d.Rules.Length == 0) return null; + var tabs = new List { d.Name }; + foreach (RynthChatFilterDto r in rules) + if (string.IsNullOrEmpty(r.Owner) && !string.IsNullOrEmpty(r.Tab) + && !tabs.Contains(r.Tab!, StringComparer.Ordinal)) tabs.Add(r.Tab!); + foreach (string tab in tabs) + { + var found = new int[d.Rules.Length]; + bool all = true; + for (int i = 0; i < d.Rules.Length && all; i++) + { + found[i] = -1; + for (int j = 0; j < rules.Count; j++) + { + RynthChatFilterDto r = rules[j]; + if (!string.IsNullOrEmpty(r.Owner) || !string.Equals(r.Tab, tab, StringComparison.Ordinal)) continue; + if (Array.IndexOf(found, j, 0, i) >= 0 || !Matches(d.Rules[i], r)) continue; + found[i] = j; + break; + } + all = found[i] >= 0; + } + if (all) return found; + } + return null; + } + + private static bool Matches(SectionChatRuleDecl decl, RynthChatFilterDto r) + { + if (!string.Equals(decl.Action, r.Action ?? "", StringComparison.OrdinalIgnoreCase) || !Same(decl.When, r.When)) return false; + if (decl.GlobalRoom) + return ChatRuleMatching.Parse(r.Mode) == ChatMatchMode.StartsWith + && Rooms.Any(room => Same(GlobalPattern(room), r.Pattern)); + return ChatRuleMatching.Parse(decl.Mode) == ChatRuleMatching.Parse(r.Mode) && Same(decl.Pattern, r.Pattern); + } } diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs index a677357..788df25 100644 --- a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs +++ b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs @@ -173,7 +173,11 @@ internal static class SectionRegistry seen.Add(plugin); if (PluginManifests.TryGetValue(plugin, out var old) && old.Json == json) continue; SectionManifest m = SectionManifestParser.Parse(plugin, json, out string error); - if (error.Length > 0) RynthLog.UI($"Sections: {plugin}'s manifest was not read - {error}."); + // A dropped "chatTabs" entry is reported in the error too, while the rest of the + // manifest is kept (SectionManifestParser.Note): don't call that "not read". + if (error.StartsWith("chatTabs:", StringComparison.Ordinal)) + RynthLog.UI($"Sections: {plugin}'s manifest was read, but part of it was left out - {error}."); + else if (error.Length > 0) RynthLog.UI($"Sections: {plugin}'s manifest was not read - {error}."); PluginManifests[plugin] = (json, m); changed = true; } @@ -217,6 +221,18 @@ internal static class SectionRegistry // The windows plugins draw (their manifests' "windows"): hosted as panels while wanted. try { PluginWindows.Sync(manifests, servers); } catch (Exception ex) { RynthLog.UI($"PluginWindows: sync failed - {ex.GetType().Name}: {ex.Message}"); } + // The chat tabs servers' plugins declare ("chatTabs"): RynthChat seeds them and runs their + // rules only while their server is active. No lock is held here (ChatModel takes its own). + try + { + var chatTabs = new List(); + foreach (SectionManifest m in manifests) chatTabs.AddRange(m.ChatTabs); + var active = new List(); + foreach (ServerState s in servers) + if (s.Active) active.Add(s.Id); + UI.Data.ChatModel.ApplyServerTabs(chatTabs, active); + } + catch (Exception ex) { RynthLog.UI($"Sections: chat tabs not applied - {ex.GetType().Name}: {ex.Message}"); } } /// The built-in servers, then every server a manifest declares with a new id. diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index b1fb8ae..426e343 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -1215,6 +1215,52 @@ internal static class Program Check(!p.CreateTab && !p.Pin, "a seeded tab that is gone is not re-created"); Check(p.Rules.All(r => !r.Enabled), "its rules stay disabled"); + Case("Refresh_IsANoOpWhenNothingChanged"); + // ChatModel.ApplyServerTabs runs every second: a plan made from its own output must match it + // rule for rule (SameRule), and want no create, pin or seed mark, or every Rebuild would save. + owned = ChatServerTabs.Plan(d, State(), "Trade").Rules; + p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Network" }, owned: owned), "Trade"); + Check(!p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: nothing to create, pin or mark"); + Check(p.Rules.Length == owned.Length && p.Rules.Zip(owned).All(z => ChatServerTabs.SameRule(z.First, z.Second)), "every rule is the same as before"); + var absent = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = null, Mode = null, Pattern = "x", GlobalRoom = null, Enabled = true }; + var empty = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = "", Mode = "", Pattern = "x", GlobalRoom = false, Enabled = true }; + Check(ChatServerTabs.SameRule(absent, empty), "absent and empty When / Mode / GlobalRoom are the same"); + Check(ChatServerTabs.SameRule(empty, new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", Pattern = "x", Color = "#FF0000", ColorMode = "line" }), + "a colour the player gave the rule is not a difference"); + Check(!ChatServerTabs.SameRule(owned[2], ChatServerTabs.Plan(d, State(), "General").Rules[2]), "a new Global room is a difference"); + var off = ChatServerTabs.Plan(d, State(), "Trade").Rules; + off[0].Enabled = false; + Check(!ChatServerTabs.SameRule(owned[0], off[0]), "on / off is a difference"); + + Case("Reclaim_FindsRulesAnOlderEngineStripped"); + // An older engine rewrote the file: its copy of the rules has no owner, server or globalRoom. + RynthChatFilterDto Strip(RynthChatFilterDto r) => new() { Tab = r.Tab, Action = r.Action, When = r.When, Mode = r.Mode, Pattern = r.Pattern, Enabled = r.Enabled }; + RynthChatFilterDto[] ours = ChatServerTabs.Plan(d, State(), "Trade").Rules; + var player = new RynthChatFilterDto { Tab = "RP", Action = "copy", Mode = "startswith", Pattern = "[Roleplay] " }; + var file = new List { player, Strip(ours[1]), new() { Tab = "Junk", Action = "hide", Pattern = "spam" }, Strip(ours[0]), Strip(ours[2]) }; + int[]? found = ChatServerTabs.Reclaim(d, file); + Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), $"found in declaration order, not the player's look-alike Global rule: {(found == null ? "null" : string.Join(",", found))}"); + foreach (RynthChatFilterDto r in file) if (r.Tab == "Network") r.Tab = "DN"; + found = ChatServerTabs.Reclaim(d, file); + Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), "a renamed tab's stripped rules are found too"); + Check(ChatServerTabs.Reclaim(d, new[] { player, Strip(ours[0]) }) == null, "an incomplete set is not reclaimed"); + file[3].Owner = key; + Check(ChatServerTabs.Reclaim(d, file) == null, "a rule that still has an owner is not reclaimed"); + Check(ChatServerTabs.Reclaim(d, new[] { Strip(ours[0]), Strip(ours[1]), new RynthChatFilterDto { Tab = "Other", Action = "copy", Mode = "startswith", Pattern = "[Trade] " } }) == null, + "the set must be in one tab"); + + Case("Router_SkipsRulesOfInactiveServers"); + var serverRule = new ChatFilterRule { Pattern = "^x", Tab = "Network", Action = ChatRuleAction.Copy, Server = "dreamweave" }; + serverRule.Recompile(); + var anyRule = new ChatFilterRule { Pattern = "^x", Tab = "Every", Action = ChatRuleAction.Copy }; + anyRule.Recompile(); + ChatRoute on = new ChatRouter(new[] { serverRule, anyRule }, null, "", countHits: false, new[] { "DreamWeave" }).Evaluate("x", "Chat", 2, null); + ChatRoute offRoute = new ChatRouter(new[] { serverRule, anyRule }, null, "", countHits: false, new[] { "aelrynth" }).Evaluate("x", "Chat", 2, null); + ChatRoute none = new ChatRouter(new[] { serverRule, anyRule }, null, "", countHits: false).Evaluate("x", "Chat", 2, null); + Check(on.ShowsIn("Network", "Chat") && on.ShowsIn("Every", "Chat"), "its server active (any case): both rules run"); + Check(!offRoute.ShowsIn("Network", "Chat") && offRoute.ShowsIn("Every", "Chat"), "another server: only the every-server rule runs"); + Check(!none.ShowsIn("Network", "Chat") && none.ShowsIn("Every", "Chat"), "no servers known: only the every-server rule runs"); + Case("Plan rules compile"); foreach (RynthChatFilterDto r in ChatServerTabs.Plan(d, State(), "LFG").Rules) {