WIP: RynthChat: pin channels to the top bar #16

Draft
AwfulWaffle wants to merge 12 commits from AwfulWaffle/RynthCore:chat/pins into main
13 changed files with 1726 additions and 69 deletions

View file

@ -29,6 +29,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
@ -73,6 +74,11 @@ internal sealed class ChatFace : IImGuiPanel
private float _inputScroll;
private bool _openSettings;
// Pinned tabs in the header (2026-11-15): the ones that did not fit (the overflow button's list),
// and the pin whose right-click menu is open.
private string[] _pinOverflow = Array.Empty<string>();
private bool _openPinMore, _openPinMenu;
private string _pinMenuTab = "";
/// <summary>A line colour changed and isn't saved yet (saved once the picker is let go).</summary>
private bool _coloursDirty;
/// <summary>The Chat history slider's value while it's held (0: not held).</summary>
@ -181,12 +187,99 @@ internal sealed class ChatFace : IImGuiPanel
}
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(ChatModel.CurrentTab());
// Search fills the rest.
float sx = start.X + _view.LastTabButtonWidth + 4, sw = buttonsX - 4 - sx;
// The pinned tabs, then search fills the rest (at least 120 px: pins that do not fit go into the overflow button).
float sx = start.X + _view.LastTabButtonWidth + 4;
sx = DrawPinnedButtons(sx, start.Y, h, buttonsX - 4 - sx - 120 - 2);
float sw = buttonsX - 4 - sx;
if (sw > 40) _view.DrawSearch(new Vector2(sx, start.Y), sw);
return start.Y + h + 4;
}
/// <summary>
/// The pinned tabs as buttons after the channel button (drawer mode, main window only): the
/// tab's name, unread badge, highlighted when current; click selects, right-click offers
/// Unpin. Those that do not fit in <paramref name="avail"/> go into one overflow button.
/// A pin on a hidden tab (its server is not active) is not drawn and not lost.
/// Returns the x after them (+4), or <paramref name="x"/> when nothing was drawn.
/// </summary>
private float DrawPinnedButtons(float x, float y, float h, float avail)
{
_pinOverflow = Array.Empty<string>();
string[] pins = ChatPins.Visible(ChatModel.PinnedTabs, ChatModel.AllTabs());
if (pins.Length == 0) return x;
const float gap = 2, overflowW = 22;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
string current = ChatModel.CurrentTab();
var unreadAll = _view.Unread;
var badges = new string?[pins.Length];
var widths = new float[pins.Length];
float total = 0;
for (int i = 0; i < pins.Length; i++)
{
unreadAll.TryGetValue(pins[i], out var unread);
bool active = string.Equals(pins[i], current, StringComparison.OrdinalIgnoreCase);
badges[i] = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null;
widths[i] = ImGuiNET.ImGui.CalcTextSize(pins[i]).X + 12 + (badges[i] != null ? ChatView.BadgeWidth(badges[i]!) + 3 : 0);
total += widths[i] + gap;
}
// Not all fit: the overflow button is always drawn, and its width comes out of the room
// before search's 120 px. Only when even that leaves search under its floor does search go.
(int fit, bool overflow) = ChatPins.Layout(widths, avail, overflowW, gap);
float start = x;
for (int i = 0; i < fit; i++)
{
string tab = pins[i];
bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase);
unreadAll.TryGetValue(tab, out var unread);
ImGuiNET.ImGui.PushID("pin_" + tab);
if (Button("##pin", "", new Vector2(x, y), new Vector2(widths[i], h), Text, active ? TabActive : BtnFill))
ChatModel.SelectTab(tab);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _pinMenuTab = tab; _openPinMenu = true; }
if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here");
else ImGuiNET.ImGui.SetItemTooltip("Right-click to unpin");
float textW = ImGuiNET.ImGui.CalcTextSize(tab).X;
dl.AddText(new Vector2(x + 6, y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, tab);
if (badges[i] != null)
ChatView.DrawBadge(dl, new Vector2(x + 6 + textW + 3, y + 4), ChatView.BadgeWidth(badges[i]!), h - 8, badges[i]!, unread.Mention);
ImGuiNET.ImGui.PopID();
x += widths[i] + gap;
}
if (overflow)
{
_pinOverflow = pins.Skip(fit).ToArray();
if (IconButton("##chat_pinmore", PhosphorIcons.CaretRight, new Vector2(x, y), new Vector2(overflowW, h), Text, BtnFill, font: UiFont.Ui11))
_openPinMore = true;
ImGuiNET.ImGui.SetItemTooltip("More pinned tabs");
x += overflowW + gap;
}
return x > start ? x + 2 : x; // the 4 px after the channel button, 2 here and 2 left from the last gap
}
/// <summary>The overflow list and the Unpin menu of the pinned buttons (drawn in DrawPopups).</summary>
private void DrawPinPopups()
{
if (_openPinMore) { _openPinMore = false; ImGuiNET.ImGui.OpenPopup("##chat_pinmore"); }
if (_openPinMenu) { _openPinMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_pinmenu"); }
if (ImGuiNET.ImGui.BeginPopup("##chat_pinmore"))
{
string current = ChatModel.CurrentTab();
foreach (string tab in _pinOverflow)
{
_view.Unread.TryGetValue(tab, out var unread);
bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase);
string label = !active && unread.Count > 0 ? $"{tab} ({unread.Count})" : tab;
if (ImGuiNET.ImGui.Selectable(label + "##pinsel_" + tab, active)) ChatModel.SelectTab(tab);
}
ImGuiNET.ImGui.EndPopup();
}
if (ImGuiNET.ImGui.BeginPopup("##chat_pinmenu"))
{
if (ImGuiNET.ImGui.Selectable("Unpin")) ChatModel.Unpin(_pinMenuTab);
ImGuiNET.ImGui.EndPopup();
}
}
/// <summary>
/// "Tabs across the top" (ChatModel.TabsAcross): every tab in a row that wraps left of
/// the buttons, as before the drawer; right-click a tab to rename, delete or open it in a
@ -240,6 +333,7 @@ internal sealed class ChatFace : IImGuiPanel
var dl = ImGuiNET.ImGui.GetWindowDrawList();
string current = ChatModel.CurrentTab();
var unreadAll = _view.Unread;
string[] pinnedNow = ChatModel.PinnedTabs;
float y = start.Y;
foreach (string tab in ChatModel.AllTabs())
{
@ -248,19 +342,35 @@ internal sealed class ChatFace : IImGuiPanel
string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null;
ImGuiNET.ImGui.PushID(tab);
var p = new Vector2(start.X, y);
// The pin, at the row's right edge, submitted after the row so it takes the click
// (the row allows the overlap, as NavFace and MetaFace.List do).
const float pinW = 18;
var pinPos = new Vector2(p.X + w - pinW - 1, y + 1);
var pinSize = new Vector2(pinW, rowH - 2);
bool overPin = ImGuiNET.ImGui.IsMouseHoveringRect(pinPos, pinPos + pinSize); // the row's own menu and tooltip stay off the pin
ImGuiNET.ImGui.SetNextItemAllowOverlap();
if (Button("##row", "", p, new Vector2(w, rowH), Text, active ? TabActive : BtnFill))
ChatModel.SelectTab(tab);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab);
if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here");
else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab)
if (!overPin && ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) _view.OpenTabMenu(tab);
if (!overPin) // the pin has its own tooltip
if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here");
else ImGuiNET.ImGui.SetItemTooltip(ChatModel.IsBaseTab(tab)
? "Right-click: open in a new window"
: "Right-click to rename, delete or open this tab in a new window");
bool pinned = pinnedNow.Contains(tab, StringComparer.OrdinalIgnoreCase);
ImGuiNET.ImGui.SetCursorScreenPos(pinPos);
if (ImGuiNET.ImGui.InvisibleButton("##pin", pinSize)) ChatModel.TogglePin(tab);
bool pinHot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.SetItemTooltip(pinned ? "Unpin from the top bar" : "Pin to the top bar");
// A lighter fill than the row's own, or the chip vanishes on the current row.
if (pinned) dl.AddRectFilled(pinPos, pinPos + pinSize, active ? Lighten(TabActive) : TabActive, 3);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.PushPin, pinPos, pinSize, pinned || pinHot ? Text : Mute);
float badgeW = badge != null ? ChatView.BadgeWidth(badge) : 0;
float ty = y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(p, p + new Vector2(w - (badge != null ? badgeW + 8 : 0), rowH), true);
dl.PushClipRect(p, p + new Vector2(w - pinW - 2 - (badge != null ? badgeW + 4 : 0), rowH), true);
dl.AddText(new Vector2(p.X + 6, ty), active ? Teal : Text, tab);
dl.PopClipRect();
if (badge != null) ChatView.DrawBadge(dl, new Vector2(p.X + w - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention);
if (badge != null) ChatView.DrawBadge(dl, new Vector2(p.X + w - pinW - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention);
ImGuiNET.ImGui.PopID();
y += rowH + 2;
}
@ -362,6 +472,7 @@ internal sealed class ChatFace : IImGuiPanel
ChatView.PushPopupStyle();
DrawSettingsPopup();
_view.DrawPopups();
DrawPinPopups();
ChatView.PopPopupStyle();
}

View file

@ -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));
}
/// <summary>Left-to-right placement that wraps to a new row when the next item doesn't fit.</summary>

View file

@ -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<ChatLine[]>
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,46 @@ internal static class ChatModel
private static string[] _customTabs = Array.Empty<string>();
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<string>(); // owner keys
private static Dictionary<string, string> _tabServers = NewMap(); // tab -> server id
private static Dictionary<string, string> _globalRooms = NewMap(); // server id -> room
private static string[] _pinnedTabs = ChatPins.FromSettings(null); // pin order (All until a file says otherwise)
// Published by ApplyServerTabs (render thread), read lock-free by the pump and the faces.
private static volatile string[] _activeServers = Array.Empty<string>();
private static volatile SectionChatTabDecl[] _tabDecls = Array.Empty<SectionChatTabDecl>();
private static volatile IReadOnlyDictionary<string, string> _serverNames = ChatServerTabs.NewMap(); // id -> display name
private static Dictionary<string, string> NewMap(IEnumerable<KeyValuePair<string, string>>? from = null) => ChatServerTabs.NewMap(from);
/// <summary>The ids of the servers active now (SectionRegistry's verdicts). Any thread; never changed in place.</summary>
public static string[] ActiveServers => _activeServers;
/// <summary>Does a rule or tab for <paramref name="server"/> apply now ("" = every server)? Any thread.</summary>
public static bool ServerActive(string server) => ChatRouter.ServerIn(_activeServers, server);
/// <summary>The tabs pinned to the main window's top bar, in pin order. Any thread.</summary>
public static string[] PinnedTabs => Volatile.Read(ref _pinnedTabs);
/// <summary>Pins <paramref name="tab"/> to the top bar, or unpins it. Saved with the settings. Any thread.</summary>
public static void TogglePin(string tab)
{
lock (EditLock)
Volatile.Write(ref _pinnedTabs, ChatPins.Toggle(_pinnedTabs, tab));
SaveSettings();
}
/// <summary>Unpins <paramref name="tab"/> (one way: a stale menu cannot pin it again). Saved. Any thread.</summary>
public static void Unpin(string tab)
{
lock (EditLock)
Volatile.Write(ref _pinnedTabs, ChatPins.Remove(_pinnedTabs, tab));
SaveSettings();
}
public static ChatFilterRule[] Filters => Volatile.Read(ref _filters);
@ -484,15 +528,25 @@ internal static class ChatModel
/// <summary>A rule just made from a chat line: the rule editor scrolls to it and flashes it.</summary>
public static volatile ChatFilterRule? FocusRule;
public static void EditFilters(Action<List<ChatFilterRule>> edit)
public static void EditFilters(Action<List<ChatFilterRule>> edit) => EditFiltersIfChanged(list => { edit(list); return true; });
/// <summary>
/// An edit that may turn out to change nothing: <paramref name="edit"/> 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 <c>list => list.Remove(r)</c> would bind to the bool overload.)
/// </summary>
public static bool EditFiltersIfChanged(Func<List<ChatFilterRule>, bool> edit)
{
bool changed;
lock (EditLock)
{
var list = new List<ChatFilterRule>(_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;
}
/// <summary>Moves a rule one place up (-1) or down (+1). Order matters (see the header).</summary>
@ -605,22 +659,31 @@ internal static class ChatModel
/// </summary>
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<string>(StringComparer.OrdinalIgnoreCase);
var tabs = new List<string>();
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;
}
/// <summary>
/// AllTabs, or with <paramref name="active"/> null every tab including those of inactive
/// servers (a tab named by "tabServers" shows only while its server is active).
/// </summary>
private static string[] BuildTabs(string[]? active) => BuildTabs(active, Filters);
private static string[] BuildTabs(string[]? active, IEnumerable<ChatFilterRule> rules) =>
ChatServerTabs.ListTabs(BaseTabs, Volatile.Read(ref _customTabs), rules,
RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs(), Volatile.Read(ref _tabServers), active);
/// <summary>Is <paramref name="tab"/> a tab at all, shown or not (its server may be inactive)?</summary>
private static bool TabExists(string tab) => BuildTabs(null).Contains(tab, StringComparer.OrdinalIgnoreCase);
/// <summary>The tabs a Move/Copy rule can send lines to: every tab but All.</summary>
public static string[] TargetTabs() => AllTabs().Where(t => t != "All").ToArray();
@ -648,11 +711,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 +740,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<string, string> 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 +772,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<string, string> 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.
/// <summary>
/// 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.
/// </summary>
public static void ApplyServerTabs(IReadOnlyList<SectionChatTabDecl> decls, IReadOnlyCollection<string> activeServers,
IReadOnlyDictionary<string, string>? 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<SectionChatTabDecl>(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;
});
}
/// <summary>
/// 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.
/// </summary>
internal static void PumpDiscoverGlobalRoom(IReadOnlyList<ChatLine> 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<string, string> 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;
});
}
/// <summary>Does an active entry with a Global-room rule store another room than <paramref name="room"/> (null: any entry at all)?</summary>
private static bool WantsRoom(SectionChatTabDecl[] decls, string[] active, Dictionary<string, string> 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;
}
/// <summary>
/// One entry, under EditLock: ChatServerTabs.Apply decides, this only carries out its edits.
/// True when it wrote anything.
/// </summary>
private static bool ApplyServerTab(List<ChatFilterRule> 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, ChatPins.Add(_pinnedTabs, e.Pin));
if (e.Seed != null) Volatile.Write(ref _seededTabs, _seededTabs.Append(e.Seed).ToArray());
if (e.TabServer != null && !IsBaseTab(e.TabServer))
{
Dictionary<string, string> 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;
}
/// <summary>Makes <paramref name="rule"/> what Apply wants, field by field; its colour is the player's and stays.</summary>
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<string, string> a, IReadOnlyDictionary<string, string> 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<SectionChatTabDecl> 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<string, string>? NullIfEmpty(Dictionary<string, string> m) => m.Count > 0 ? m : null;
/// <summary>Is the line shown under <paramref name="tab"/> (rules applied, no search)?</summary>
public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel);
@ -746,7 +1034,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 +1061,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 +1072,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 +1106,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 +1143,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<string>())
if (!string.IsNullOrWhiteSpace(t)) EnsureCustomTab(t.Trim());
foreach (ChatFilterRule r in imported)
@ -883,6 +1174,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,
};
/// <summary>
@ -892,6 +1187,14 @@ internal static class ChatModel
/// it out of All too).
/// </summary>
private static ChatFilterRule FromDto(RynthChatFilterDto f)
{
ChatFilterRule rule = BuildRule(f);
rule.Recompile();
return rule;
}
/// <summary>FromDto without compiling the pattern (ApplyServerTabs compares canonical forms every second).</summary>
private static ChatFilterRule BuildRule(RynthChatFilterDto f)
{
string tab = (f.Tab ?? "").Trim();
var rule = new ChatFilterRule
@ -912,8 +1215,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 +1655,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 +1667,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 +1690,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 +1711,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;
/// <summary>True when there is no file, or it was read; false when it couldn't be read.</summary>
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;
}
}
/// <param name="reload">Another client changed the file: presets it doesn't list go off, and
/// this client's selected tab is kept.</param>
private static void LoadSettings(string json, bool reload)
/// <returns>True when the file was read (a reload's unreadable file is skipped, false).</returns>
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 +1786,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 +1810,38 @@ 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<string>())
.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
string[] pinned = ChatPins.FromSettings(dto.PinnedTabs); // absent = All; [] stays empty
// Under EditLock, as ApplyServerTabs (render thread) edits the same lists.
lock (EditLock)
{
_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 +1887,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: seeded tabs, tab servers, global rooms. Pins are always written (see below).
SeededTabs = NullIfEmpty(Volatile.Read(ref _seededTabs)),
TabServers = NullIfEmpty(Volatile.Read(ref _tabServers)),
GlobalRooms = NullIfEmpty(Volatile.Read(ref _globalRooms)),
PinnedTabs = Volatile.Read(ref _pinnedTabs), // always written, empty included: [] = nothing pinned, absent = All
Filters = Filters.Select(ToDto).ToArray(),
// Only presets the user touched: new presets in later builds start off.
Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All

View file

@ -0,0 +1,105 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ChatPins.cs
// Pinned chat tabs (2026-11-15): which tabs sit in the main chat window's top
// bar. Pure list bookkeeping (no ChatModel or ImGui) so tools/ChatFilterTests
// compiles it as is. Names compare OrdinalIgnoreCase, every function returns a
// new array, and the order of the array is the order of the buttons.
//
// A pin on a tab that is not there (a server tab while its server is not
// active) is kept but not drawn: Visible filters, nothing removes.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.Engine.UI.Data;
internal static class ChatPins
{
private static bool Same(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
/// <summary>Pins <paramref name="tab"/> at the end, or unpins it when it is pinned. A blank name changes nothing.</summary>
internal static string[] Toggle(string[] pins, string tab)
{
if (string.IsNullOrWhiteSpace(tab)) return pins.ToArray();
tab = tab.Trim();
if (pins.Any(p => Same(p, tab))) return Remove(pins, tab);
return pins.Append(tab).ToArray();
}
/// <summary>The tab pinned when nothing was ever saved.</summary>
internal const string DefaultPin = "All";
/// <summary>
/// The pins a settings file means: absent (never set, or a file from before pins) = All
/// pinned; a saved array, empty included, is exactly what the player left. Blank names are
/// dropped and repeats (any case) kept once.
/// </summary>
internal static string[] FromSettings(string[]? saved)
{
if (saved == null) return new[] { DefaultPin };
var result = new List<string>(saved.Length);
foreach (string s in saved)
{
if (string.IsNullOrWhiteSpace(s)) continue;
string name = s.Trim();
if (!result.Any(r => Same(r, name))) result.Add(name);
}
return result.ToArray();
}
/// <summary>Pins <paramref name="tab"/> at the end unless it is pinned already (idempotent, unlike Toggle). A blank name changes nothing.</summary>
internal static string[] Add(string[] pins, string tab)
{
if (string.IsNullOrWhiteSpace(tab)) return pins.ToArray();
tab = tab.Trim();
return pins.Any(p => Same(p, tab)) ? pins.ToArray() : pins.Append(tab).ToArray();
}
/// <summary>The pin follows a renamed tab and keeps its place. If <paramref name="to"/> is already pinned, one pin remains.</summary>
internal static string[] Rename(string[] pins, string from, string to)
{
var result = new List<string>(pins.Length);
foreach (string p in pins)
{
string name = Same(p, from) ? to : p;
if (!result.Any(r => Same(r, name))) result.Add(name);
}
return result.ToArray();
}
/// <summary>Drops the pin of a deleted tab.</summary>
internal static string[] Remove(string[] pins, string tab) => pins.Where(p => !Same(p, tab)).ToArray();
/// <summary>
/// How many of the pin buttons (button widths in <paramref name="widths"/>, each followed by
/// <paramref name="gap"/>) fit in <paramref name="avail"/>, and whether an overflow button is
/// needed. When not all fit the overflow button (width <paramref name="overflowW"/> + gap) is
/// paid for first, so the buttons that fit are a prefix of the pins. Nothing fits in a
/// negative room: Fit 0 with the overflow button still wanted.
/// </summary>
internal static (int Fit, bool Overflow) Layout(float[] widths, float avail, float overflowW, float gap)
{
if (widths.Length == 0) return (0, false);
float total = 0;
foreach (float wd in widths) total += wd + gap;
if (total <= avail) return (widths.Length, false);
float room = avail - overflowW - gap, used = 0;
int fit = 0;
while (fit < widths.Length && used + widths[fit] + gap <= room) used += widths[fit++] + gap;
return (fit, true);
}
/// <summary>The pins that have a tab now, in pin order, spelled as the tab is.</summary>
internal static string[] Visible(string[] pins, string[] allTabs)
{
var result = new List<string>(pins.Length);
foreach (string p in pins)
{
string? tab = allTabs.FirstOrDefault(t => Same(t, p));
if (tab != null && !result.Any(r => Same(r, tab))) result.Add(tab);
}
return result.ToArray();
}
}

View file

@ -202,6 +202,13 @@ internal sealed class ChatFilterRule
public const uint DefaultColor = 0xFFFFD27A;
/// <summary>0xAARRGGBB.</summary>
public volatile uint ColorArgb = DefaultColor;
/// <summary>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.</summary>
public volatile string Server = "";
/// <summary>"server/entry id" of the plugin entry that owns it, "" for the player's own rule.</summary>
public volatile string Owner = "";
/// <summary>Its pattern follows the Global room discovered from chat (ChatModel.ApplyServerTabs).</summary>
public volatile bool GlobalRoom;
private volatile WhenSpec _when = WhenSpec.Any;
/// <summary>"" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions).</summary>
@ -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;
/// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param>
/// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param>
public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits)
/// <param name="activeServers">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.</param>
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<string>();
_passTicks = new long[rules.Length];
}
/// <summary>Does a rule for <paramref name="server"/> run ("" = every server)?</summary>
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;
}
/// <summary>
/// Before routing the <paramref name="lines"/> 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;

View file

@ -0,0 +1,358 @@
// ============================================================================
// 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" = "<server>/<entry id>"), 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 "<name> (<server>)" 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
{
/// <summary>The settings Apply decides from. Rules are every rule in list order, as their JSON form.</summary>
internal sealed record TabState(
IReadOnlyCollection<string> Seeded,
IReadOnlyCollection<string> CustomTabs,
IReadOnlyCollection<string> AllTabs,
IReadOnlyDictionary<string, string> TabServers,
IReadOnlyCollection<string> Pinned,
IReadOnlyList<RynthChatFilterDto> Rules,
string? Room,
string ServerName);
/// <summary>
/// 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.
/// </summary>
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" };
/// <summary>The owner key of an entry: "server/id".</summary>
internal static string OwnerKey(SectionChatTabDecl d) => d.Server + "/" + d.Id;
/// <summary>The Global room a remote speaker's line names (canonical capitalisation), or null.</summary>
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,
};
}
/// <summary>The "startswith" pattern a Global-room rule uses for <paramref name="room"/>.</summary>
internal static string GlobalPattern(string room) => "[" + room + "] ";
/// <summary>The name an entry seeds under when its own name is taken: "Network (DreamWeave)".</summary>
internal static string ClashName(SectionChatTabDecl d, string serverName) =>
d.Name + " (" + (string.IsNullOrWhiteSpace(serverName) ? d.Server : serverName.Trim()) + ")";
/// <summary>
/// Everything to change for entry <paramref name="d"/>. <paramref name="canonical"/> 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.
/// </summary>
internal static TabEdits Apply(SectionChatTabDecl d, TabState s, Func<RynthChatFilterDto, RynthChatFilterDto>? 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<int>();
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<RynthChatFilterDto>();
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<string> tabs)
{
if (!Has(tabs, name)) return name;
return Numbered(clashBase, tabs);
}
/// <summary><paramref name="name"/> if no tab has it, else "name 2", "name 3"...</summary>
private static string Numbered(string name, IReadOnlyCollection<string> tabs)
{
if (!Has(tabs, name)) return name;
for (int n = 2; ; n++)
if (!Has(tabs, name + " " + n)) return name + " " + n;
}
/// <summary>
/// The tab "New tab: <paramref name="name"/>" 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.
/// </summary>
internal static (string Tab, bool Existing) ResolveNewTab(string name, IReadOnlyCollection<string> visibleTabs, IReadOnlyCollection<string> everyTab)
{
string? shown = visibleTabs.FirstOrDefault(t => string.Equals(t, name, StringComparison.OrdinalIgnoreCase));
if (shown != null) return (shown, true);
return (Numbered(name, everyTab), false);
}
/// <summary>
/// Pairs each declared rule with one of <paramref name="candidates"/> (indexes into
/// <paramref name="rules"/>) 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
/// <paramref name="leftovers"/>) what is left in order, so a rule the manifest changed keeps
/// its on/off. Returns a candidate index per declared rule, or -1.
/// </summary>
internal static int[] Pair(SectionChatTabDecl d, IReadOnlyList<RynthChatFilterDto> rules, IReadOnlyList<int> candidates, bool leftovers)
{
var result = Enumerable.Repeat(-1, d.Rules.Length).ToArray();
var used = new HashSet<int>();
int Take(Func<RynthChatFilterDto, bool> 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;
}
/// <summary>
/// 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.
/// </summary>
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<string> list, string item) => list.Contains(item, StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 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.
/// </summary>
internal static int[]? Reclaim(SectionChatTabDecl d, IReadOnlyList<RynthChatFilterDto> rules, string serverName = "")
{
if (d.Rules.Length == 0) return null;
string clashBase = ClashName(d, serverName);
var tabs = new List<string> { 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<int>();
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 --------------------------
/// <summary>A tab -> server (or server -> room) map that ignores case, from any map (blank entries dropped).</summary>
internal static Dictionary<string, string> NewMap(IEnumerable<KeyValuePair<string, string>>? from = null)
{
var map = new Dictionary<string, string>(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;
}
/// <summary>
/// The tabs to list (AllTabs): base tabs, created tabs, tabs an enabled Move/Copy rule fills,
/// then <paramref name="presetTabs"/>. With <paramref name="active"/> 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.
/// </summary>
internal static string[] ListTabs(IReadOnlyList<string> baseTabs, IEnumerable<string> customTabs, IEnumerable<ChatFilterRule> rules,
IEnumerable<string> presetTabs, IReadOnlyDictionary<string, string> tabServers, string[]? active)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var tabs = new List<string>();
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();
}
/// <summary>A tab renamed: its server entry and its pin (in its place) follow.</summary>
internal static (Dictionary<string, string> TabServers, string[] Pins) RenameTab(
IReadOnlyDictionary<string, string> tabServers, IEnumerable<string> pins, string from, string to)
{
Dictionary<string, string> map = NewMap(tabServers);
if (map.Remove(from, out string? server)) map[to] = server;
return (map, ChatPins.Rename(pins.ToArray(), from, to));
}
/// <summary>A tab deleted: its server entry and its pin go (the seed mark stays, elsewhere).</summary>
internal static (Dictionary<string, string> TabServers, string[] Pins) DeleteTab(
IReadOnlyDictionary<string, string> tabServers, IEnumerable<string> pins, string tab)
{
Dictionary<string, string> map = NewMap(tabServers);
map.Remove(tab);
return (map, ChatPins.Remove(pins.ToArray(), tab));
}
// -- Export / Import -------------------------------------------------------------
/// <summary>The player's rules only: a server's rules come from its manifest, not from a clipboard.</summary>
internal static RynthChatFilterDto[] ExportRules(IEnumerable<RynthChatFilterDto> rules) =>
rules.Where(r => string.IsNullOrEmpty(r.Owner)).ToArray();
/// <summary>The created tabs without the servers' ones.</summary>
internal static string[] ExportTabs(IEnumerable<string> tabs, IReadOnlyDictionary<string, string> tabServers) =>
tabs.Where(t => !tabServers.ContainsKey(t)).ToArray();
/// <summary>An imported rule is the player's: no owner, every server, a fixed pattern.</summary>
internal static RynthChatFilterDto AsPlayerRule(RynthChatFilterDto r)
{
r.Owner = null;
r.Server = null;
r.GlobalRoom = null;
return r;
}
}

View file

@ -41,6 +41,13 @@ internal sealed class RynthChatFilterDto
// 2026-10-05:
/// <summary>"contains" | "startswith" | "endswith"; absent: a regex (ChatRuleMatching).</summary>
[JsonPropertyName("mode")] public string? Mode { get; set; }
// 2026-11-15 (server default tabs, ChatServerTabs); each is absent on a player's own rule:
/// <summary>The server id whose plugin tab this rule belongs to; absent = every server.</summary>
[JsonPropertyName("server")] public string? Server { get; set; }
/// <summary>"&lt;server&gt;/&lt;entry id&gt;" of the plugin entry that owns this rule; absent = the player's rule.</summary>
[JsonPropertyName("owner")] public string? Owner { get; set; }
/// <summary>True on the rule whose pattern follows the room discovered from chat; absent = false.</summary>
[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.
/// <summary>Owner keys ("server/id") of the plugin tabs already seeded, so a deleted tab is not re-created.</summary>
[JsonPropertyName("seededTabs")] public string[]? SeededTabs { get; set; }
/// <summary>Tab name -> the server id whose plugin declared it; the tab shows only while that server is active.</summary>
[JsonPropertyName("tabServers")] public Dictionary<string, string>? TabServers { get; set; }
/// <summary>Server id -> the Global room (General, Trade, LFG, Roleplay) last discovered from chat.</summary>
[JsonPropertyName("globalRooms")] public Dictionary<string, string>? GlobalRooms { get; set; }
/// <summary>Tabs pinned to the main chat window's top bar, in pin order.</summary>
[JsonPropertyName("pinnedTabs")] public string[]? PinnedTabs { get; set; }
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
/// <summary>Standard filters' user state (RynthChatPresets); absent while none was changed.</summary>
[JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; }

View file

@ -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)

View file

@ -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:<tab> or type:<number>; "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<SectionBarMenuItem>();
}
/// <summary>One rule of a plugin-declared chat tab ("chatTabs"); a GlobalRoom rule's pattern follows the room discovered from chat.</summary>
internal sealed record SectionChatRuleDecl(string Action, string When, string Mode, string Pattern, bool GlobalRoom);
/// <summary>A default chat tab a server's plugin declares ("chatTabs", 2026-11-15); owner key = Server + "/" + Id.</summary>
internal sealed record SectionChatTabDecl(string Server, string Id, string Name, bool Pinned, string GlobalRoomFallback, SectionChatRuleDecl[] Rules);
/// <summary>One plugin's parsed manifest.</summary>
internal sealed record SectionManifest(
string Plugin,
@ -157,6 +177,9 @@ internal sealed record SectionManifest(
/// <summary>The windows the plugin draws (plugin API v89 engines host them; older ones ignore the key).</summary>
public SectionWindowDecl[] Windows { get; init; } = Array.Empty<SectionWindowDecl>();
/// <summary>The default chat tabs the plugin declares for its server (2026-11-15; older engines ignore the key).</summary>
public SectionChatTabDecl[] ChatTabs { get; init; } = Array.Empty<SectionChatTabDecl>();
}
internal static class SectionManifestParser
@ -178,6 +201,9 @@ internal static class SectionManifestParser
public const int MaxWindowTitleLength = 32;
/// <summary>Most items kept in one window's bar-icon dropdown (v95).</summary>
public const int MaxBarMenuItems = 6;
/// <summary>Most chat tab entries kept per manifest, and rules per entry (2026-11-15).</summary>
public const int MaxChatTabs = 8;
public const int MaxChatRules = 16;
public const float DefaultWindowWidth = 420f, DefaultWindowHeight = 300f, MinWindowSize = 120f, MaxWindowSize = 2000f;
/// <summary>
@ -278,9 +304,20 @@ internal static class SectionManifestParser
BarMenu: barMenu.Count > 0 ? barMenu.ToArray() : null));
}
var chatTabs = new List<SectionChatTabDecl>();
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
}
}
/// <summary>Keeps the first note; a dropped chatTabs entry is reported without discarding the rest of the manifest.</summary>
private static void Note(ref string error, string note)
{
if (error.Length == 0) error = note;
}
/// <summary>One chatTabs entry, or null (with the reason) when a field is bad.</summary>
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<SectionChatRuleDecl>();
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:<tab> or type:<number>"; 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());
}
/// <summary>A chat rule's when, as RynthChat reads it: "", "chan:&lt;tab&gt;" or "type:&lt;number &gt;= 0&gt;".</summary>
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;
}
/// <summary>A rule pattern: control characters become spaces, capped, NOT trimmed.</summary>
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 ─────────────────────────────────────────────────────
/// <summary>A lower-case id of letters, digits, '-' and '_' (at most MaxIdLength), else "".</summary>

View file

@ -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<SectionChatTabDecl>();
foreach (SectionManifest m in manifests) chatTabs.AddRange(m.ChatTabs);
var active = new List<string>();
var names = new Dictionary<string, string>(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}"); }
}
/// <summary>The built-in servers, then every server a manifest declares with a new id.</summary>

View file

@ -36,6 +36,11 @@
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\SharedFileWatch.cs" Link="Engine\SharedFileWatch.cs" />
<!-- 2026-11-05: a plugin's own colour for a line it writes (RynthAi's Info text colour). -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatOwnColors.cs" Link="Engine\ChatOwnColors.cs" />
<!-- 2026-11-15: server default tabs (a plugin manifest chatTabs) and Global room discovery. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatServerTabs.cs" Link="Engine\ChatServerTabs.cs" />
<!-- 2026-11-15: pinned tab bookkeeping. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatPins.cs" Link="Engine\ChatPins.cs" />
</ItemGroup>
</Project>

View file

@ -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,10 @@ internal static class Program
RetailRules();
RetailSetting();
TabsAcrossSetting();
ServerTabSettingsRoundTrip();
ServerTabDiscovery();
ServerTabPlans();
PinBookkeeping();
SharedFileReload();
LineColorTags();
LineColorKinds();
@ -1108,6 +1113,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<string, string> { ["Network"] = "dreamweave" },
GlobalRooms = new Dictionary<string, string> { ["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,
};
/// <summary>The chat settings in miniature: carries out ChatServerTabs.Apply's edits the way ChatModel.ApplyServerTab does.</summary>
private sealed class TabSim
{
public static readonly string[] BaseTabs = { "All", "Chat", "Channels" };
public List<RynthChatFilterDto> Rules = new();
public List<string> Custom = new();
public List<string> Seeded = new();
public string[] Pins = Array.Empty<string>();
public Dictionary<string, string> 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;
}
/// <summary>RenameCustomTab: the tab, its rules, its server entry and its pin.</summary>
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);
}
/// <summary>DeleteCustomTab: the tab goes, its Move/Copy rules turn off, its server entry and pin go, the seed mark stays.</summary>
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<RynthChatFilterDto>
{
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<RynthChatFilterDto> { 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<RynthChatFilterDto> { 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<string>();
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<string, string> { ["Network"] = "dreamweave", ["Other"] = "aelrynth" });
(Dictionary<string, string> 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<string, string> 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<string, string> 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<string, string> { ["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<string>(), ChatServerTabs.NewMap(new Dictionary<string, string> { ["Chat"] = "dreamweave" }), Array.Empty<string>()).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");
@ -1244,4 +1604,99 @@ internal static class Program
Check(ChatFilterPresets.Get("no.such") == null, "an unknown id is null");
Check(ChatFilterPresets.All.Length >= 10, "a useful set");
}
// 2026-11-15: pinned tab bookkeeping (ChatPins), pure.
private static void PinBookkeeping()
{
Case("Toggle_AddsAtEndAndRemoves");
string[] p = ChatPins.Toggle(Array.Empty<string>(), "Chat");
p = ChatPins.Toggle(p, "Network");
Check(p.SequenceEqual(new[] { "Chat", "Network" }), "added in pin order");
string[] q = ChatPins.Toggle(p, "chat");
Check(q.SequenceEqual(new[] { "Network" }), "a differently cased name unpins");
Check(p.SequenceEqual(new[] { "Chat", "Network" }), "the input array is not changed");
Check(ChatPins.Toggle(q, " ").Length == 1, "a blank name pins nothing");
Case("Rename_KeepsPosition");
string[] r = ChatPins.Rename(new[] { "Chat", "Network", "Trade" }, "network", "DN");
Check(r.SequenceEqual(new[] { "Chat", "DN", "Trade" }), "renamed in place");
Check(ChatPins.Rename(r, "Nope", "X").SequenceEqual(r), "an unpinned tab changes nothing");
string[] merged = ChatPins.Rename(new[] { "A", "B" }, "A", "b");
Check(merged.Length == 1 && merged[0] == "b", "a rename onto a pinned name leaves one pin");
Case("Remove_DropsOnlyThatPin");
Check(ChatPins.Remove(new[] { "Chat", "Network" }, "NETWORK").SequenceEqual(new[] { "Chat" }), "removed");
Check(ChatPins.Remove(new[] { "Chat" }, "Nope").SequenceEqual(new[] { "Chat" }), "absent = unchanged");
Case("Visible_SkipsHiddenTabsKeepsPin");
string[] pins = { "Network", "Chat" };
string[] vis = ChatPins.Visible(pins, new[] { "All", "Chat" });
Check(vis.SequenceEqual(new[] { "Chat" }), "the hidden tab is not drawn");
Check(pins.SequenceEqual(new[] { "Network", "Chat" }), "the pin is still held");
Check(ChatPins.Visible(pins, new[] { "All", "Chat", "network" }).SequenceEqual(new[] { "network", "Chat" }),
"back when the server is back, in pin order, as the tab is spelled now");
Case("Visible_BaseTabsPinnable");
Check(ChatPins.Visible(ChatPins.Toggle(Array.Empty<string>(), "All"), new[] { "All", "Chat" }).SequenceEqual(new[] { "All" }), "All");
Check(ChatPins.Visible(ChatPins.Toggle(Array.Empty<string>(), "Chat"), new[] { "All", "Chat" }).SequenceEqual(new[] { "Chat" }), "Chat");
Case("Add_IsIdempotent");
string[] added = ChatPins.Add(new[] { "Chat" }, "Network");
Check(added.SequenceEqual(new[] { "Chat", "Network" }), "appended");
Check(ChatPins.Add(added, "network").SequenceEqual(added), "a pinned name (any case) adds nothing");
Check(ChatPins.Add(added, "").Length == 2 && ChatPins.Add(added, " ").Length == 2, "a blank name adds nothing");
Check(ChatPins.Add(Array.Empty<string>(), " Net ").SequenceEqual(new[] { "Net" }), "trimmed");
Case("PinsDefault_AbsentMeansAll");
Check(ChatPins.FromSettings(null).SequenceEqual(new[] { "All" }), "never set = All pinned");
RynthChatSettingsDto oldFile = JsonSerializer.Deserialize(
"{\"version\":1,\"customTabs\":[\"Mine\"]}", RynthChatJsonContext.Default.RynthChatSettingsDto)!;
Check(oldFile.PinnedTabs == null && ChatPins.FromSettings(oldFile.PinnedTabs).SequenceEqual(new[] { "All" }),
"a file from before pins = All pinned");
Case("PinsDefault_EmptyRoundTrips");
var noPins = new RynthChatSettingsDto { PinnedTabs = ChatPins.Remove(ChatPins.FromSettings(null), "All") };
string noPinsJson = JsonSerializer.Serialize(noPins, RynthChatJsonContext.Default.RynthChatSettingsDto);
Check(noPinsJson.Contains("\"pinnedTabs\":[]", StringComparison.Ordinal), "unpinning everything is written as []: " + noPinsJson);
RynthChatSettingsDto noPinsBack = JsonSerializer.Deserialize(noPinsJson, RynthChatJsonContext.Default.RynthChatSettingsDto)!;
Check(noPinsBack.PinnedTabs != null && ChatPins.FromSettings(noPinsBack.PinnedTabs).Length == 0, "and loads as nothing pinned, not All");
string nullJson = JsonSerializer.Serialize(new RynthChatSettingsDto(), RynthChatJsonContext.Default.RynthChatSettingsDto);
Check(!nullJson.Contains("pinnedTabs", StringComparison.Ordinal), "WhenWritingNull still drops only null");
string[] kept = ChatPins.FromSettings(new[] { "Chat", " ", "chat", "Network" });
Check(kept.SequenceEqual(new[] { "Chat", "Network" }), "a saved list is cleaned, order kept");
// Source scan (the model is not compiled into this tool): the pin save and load lines are
// what make [] persist, and a refactor back to NullIfEmpty would silently turn "nothing
// pinned" into "All pinned" on the next load.
Case("PinsDefault_SourceScan");
string? chatData = null;
for (string? dir = AppContext.BaseDirectory; dir != null && chatData == null; dir = Path.GetDirectoryName(dir))
{
string candidate = Path.Combine(dir, "src", "RynthCore.Engine", "UI", "Data", "ChatData.cs");
if (File.Exists(candidate)) chatData = candidate;
}
Check(chatData != null, "found src/RynthCore.Engine/UI/Data/ChatData.cs by walking up from " + AppContext.BaseDirectory);
if (chatData != null)
{
string src = File.ReadAllText(chatData);
Check(src.Contains("PinnedTabs = Volatile.Read(ref _pinnedTabs)", StringComparison.Ordinal), "save writes the pin array as is");
Check(src.Contains("ChatPins.FromSettings(dto.PinnedTabs)", StringComparison.Ordinal), "load goes through FromSettings (absent = All)");
Check(!src.Contains("NullIfEmpty(Volatile.Read(ref _pinnedTabs))", StringComparison.Ordinal), "save does not drop an empty pin array");
}
Case("Layout_ZeroPins");
Check(ChatPins.Layout(Array.Empty<float>(), 500, 22, 2) == (0, false), "nothing to draw, no overflow button");
Check(ChatPins.Layout(Array.Empty<float>(), -50, 22, 2) == (0, false), "also in no room");
Case("Layout_AllFit");
Check(ChatPins.Layout(new[] { 50f, 60f }, 114, 22, 2) == (2, false), "exactly full (50+2+60+2)");
Check(ChatPins.Layout(new[] { 50f, 60f }, 300, 22, 2) == (2, false), "room to spare");
Case("Layout_SomeFit");
// 50+2 fits in 114-22-2=90, then 52+60+2=114 > 90: one pin, the rest in overflow.
Check(ChatPins.Layout(new[] { 50f, 60f }, 113, 22, 2) == (1, true), "one fits, overflow button");
Check(ChatPins.Layout(new[] { 50f, 60f, 10f }, 113, 22, 2) == (1, true), "a later small pin does not jump the queue");
Case("Layout_NoneFit");
Check(ChatPins.Layout(new[] { 50f, 60f }, 60, 22, 2) == (0, true), "room for the overflow button only");
Check(ChatPins.Layout(new[] { 50f }, 10, 22, 2) == (0, true), "less than the overflow button: still wanted");
Check(ChatPins.Layout(new[] { 50f }, -30, 22, 2) == (0, true), "negative room: still wanted"); }
}

View file

@ -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<SectionChatRuleDecl>();
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)");