WIP: RynthChat: Network tab Join/Leave bar and Global sends #17

Draft
AwfulWaffle wants to merge 17 commits from AwfulWaffle/RynthCore:chat/network-join into main
19 changed files with 3122 additions and 70 deletions

View file

@ -0,0 +1,251 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AcCharacterOptions.cs
//
// AC's own "Hear <room> Chat" character options (General, Trade, LFG,
// Roleplay), set the way ticking the box in AC's Options panel does: the
// client's own option bit changes, AC's UI is told, and AC itself sends the
// SetSingleCharacterOption game action (0x0005) so the server agrees, no
// relog. Spike for RynthChat's network tab (docs/plans/2026-11-15-rynthchat-
// network-tab-pins.md, Task 10). Probe: /rc chatoption <room> [on|off].
//
// Read off acclient.exe (4,841,472 bytes, SHA256 69AC7517...) 2026-11-15,
// offline with Iced; nothing in the client is written or patched:
// CPlayerSystem ctor 0x005611E0 (stores this to 0x0087119C) builds a member
// at +0x30 (0x0059B760); its PlayerModule part sits at +0x34 (vtable
// 0x007E6404, the same +0x34 AcShortcuts reads). Option bits: +0x8C, +0x90.
// PlayerModule::SetOption(PlayerOption, int) 0x005D4F20, thiscall, ret 8.
// The Options panel's checkbox (0x00487020, its only direct caller) calls
// exactly this on that object: push value, push option id, lea ecx,[edi+4].
// For 0x23..0x26 it goes to a one-option setter (0x005D45C0 for General):
// unchanged -> returns, nothing sent; changed -> flips the bit in +0x90
// (General 0x100, Trade 0x200, LFG 0x400, Roleplay 0x800) and tail-calls
// vtable slot +0x14 with the option id.
// Slot +0x14 = 0x0059B8F0 (the option-changed handler of this class):
// 0x0047A260(po) tells AC's UI listeners (notice 0x004DD21F, each one's
// virtual +0x244(po)); a side-effect switch that has no case for the chat
// options; then, since its table 0x0059B62C says "send now" for 0x23..0x26,
// GetOption(po) and CM_Character's sender 0x006A2330(po, value): opcode 5,
// then the option id, then the value (two uint32s: what ACE's
// GameActionSetSingleCharacterOption reads).
// PlayerModule::GetOption(PlayerOption) 0x005D4AF0, thiscall, ret 4: a pure
// read of the same bits (General: +0x90 bit 8).
// Guards before calling: all three functions found by unique pattern (never by
// a guessed address); the handler's call at +0xCC must reach a function that
// stores opcode 5 at +0x5A; at run time the object's vtable slot +0x14 must be
// that handler (so it is that class, and the send path is the one read here).
// AC's main thread only (the send writes AC's outgoing blob; a /rc command runs
// there).
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class AcCharacterOptions
{
/// <summary>The four rooms whose "Hear ... Chat" option this sets.</summary>
public enum Room { General, Trade, Lfg, Roleplay }
/// <summary>AC's PlayerOption id (ACE CharacterOption): HearGeneralChat 0x23 .. HearRoleplayChat 0x26.</summary>
public static uint OptionId(Room room) => room switch
{
Room.General => 0x23,
Room.Trade => 0x24,
Room.Lfg => 0x25,
_ => 0x26,
};
public static bool TryParseRoom(string word, out Room room)
{
switch (word.Trim().ToLowerInvariant())
{
case "general": room = Room.General; return true;
case "trade": room = Room.Trade; return true;
case "lfg": room = Room.Lfg; return true;
case "roleplay": case "rp": room = Room.Roleplay; return true;
default: room = Room.General; return false;
}
}
public static string Name(Room room) => room switch
{
Room.General => "General",
Room.Trade => "Trade",
Room.Lfg => "LFG",
_ => "Roleplay",
};
private const int PlayerModuleOffset = 0x34; // CPlayerSystem + 0x34 (AcShortcuts uses the same)
private const int ModuleReadSpan = 0x94; // the option words at +0x8C and +0x90
private const int OptionChangedSlot = 0x14; // vtable slot the one-option setters tail-call
private const int HandlerSendCallOffset = 0xCC; // 0x0059B9BC - 0x0059B8F0: call sender
private const int SenderOpcodeStoreOffset = 0x5A; // 0x006A238A - 0x006A2330: mov dword ptr [edx],5
// One per line: tools/pe_pattern.py CHECK reads only the first name of a combined declaration.
private const int SetOptionVa = 0x005D4F20;
private const int GetOptionVa = 0x005D4AF0;
private const int OptionChangedVa = 0x0059B8F0;
// PlayerModule::SetOption(po, value): option 0 is bit 1 of +0x8C, compared byte-wise with the value.
private static readonly byte?[] SetOptionPattern =
[0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x75, 0x47, 0x8B, 0x91, 0x8C, 0x00, 0x00, 0x00, 0x8A, 0x44, 0x24, 0x08];
// PlayerModule::GetOption(po): option 0 is (+0x8C >> 1) & 1, ret 4.
private static readonly byte?[] GetOptionPattern =
[0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x75, 0x0E, 0x8B, 0x81, 0x8C, 0x00, 0x00, 0x00, 0xD1, 0xE8, 0x83, 0xE0, 0x01, 0xC2, 0x04, 0x00];
// The option-changed handler: notify UI (call), then switch on po-2 against 0x2E.
private static readonly byte?[] OptionChangedPattern =
[0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x57, 0x8B, 0xF1, 0xE8, null, null, null, null, 0x8D, 0x47, 0xFE, 0x83, 0xC4, 0x04, 0x83, 0xF8, 0x2E];
private static readonly byte[] OpcodeFiveStore = [0xC7, 0x02, 0x05, 0x00, 0x00, 0x00];
private static IntPtr _setOption, _getOption, _optionChanged;
private static bool _probed;
private static string _status = "not looked for yet";
public static string Status => _status;
private static void Probe()
{
_probed = true;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_status = "acclient.exe not available";
return;
}
// Pattern only, and one match only: a fallback-VA result is never called, nor one of several
// matches (HookResolver picks the one nearest the fallback and says "pattern-multimatch").
// HookResolver also reports "pattern-unique" without looking further when its first match
// sits exactly at the fallback VA, so the count is checked here as well (IsUnique).
// Written out per call so tools/pe_pattern.py CHECK parses and verifies each pattern.
IntPtr PatternOnly(HookResolver.ResolveResult r, byte?[] pattern) =>
r.Success && r.Source == HookResolver.ResolveSource.PatternScan && r.Detail == "pattern-unique"
&& IsUnique(text.Bytes, pattern) ? r.Address : IntPtr.Zero;
IntPtr set = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::SetOption", SetOptionPattern, SetOptionVa), SetOptionPattern);
IntPtr get = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::GetOption", GetOptionPattern, GetOptionVa), GetOptionPattern);
IntPtr changed = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::OptionChanged", OptionChangedPattern, OptionChangedVa), OptionChangedPattern);
if (set == IntPtr.Zero || get == IntPtr.Zero || changed == IntPtr.Zero)
{
_status = $"not found in this client (set {Ok(set)}, get {Ok(get)}, changed {Ok(changed)})";
RynthLog.Compat("AcCharacterOptions: " + _status);
return;
}
// The handler must send through a function that writes game action 5 (SetSingleCharacterOption).
byte[] bytes = text.Bytes;
int call = changed.ToInt32() - text.TextBaseVa + HandlerSendCallOffset;
if (call < 0 || call + 5 > bytes.Length || bytes[call] != 0xE8)
{
_status = "the option handler's send call isn't where it was read";
RynthLog.Compat("AcCharacterOptions: " + _status);
return;
}
int sender = call + 5 + BitConverter.ToInt32(bytes, call + 1);
if (sender < 0 || sender + SenderOpcodeStoreOffset + OpcodeFiveStore.Length > bytes.Length
|| !PatternScanner.VerifyBytes(bytes, sender + SenderOpcodeStoreOffset, OpcodeFiveStore))
{
_status = $"the option handler's call (0x{text.TextBaseVa + sender:X8}) isn't the 0x0005 sender";
RynthLog.Compat("AcCharacterOptions: " + _status);
return;
}
_setOption = set;
_getOption = get;
_optionChanged = changed;
_status = $"SetOption 0x{set.ToInt32():X8}, GetOption 0x{get.ToInt32():X8}, handler 0x{changed.ToInt32():X8} -> sender 0x{text.TextBaseVa + sender:X8}";
RynthLog.Compat("AcCharacterOptions: " + _status);
static string Ok(IntPtr p) => p != IntPtr.Zero ? "ok" : "missing";
}
/// <summary>Does <paramref name="pattern"/> match exactly once in <paramref name="bytes"/>?</summary>
private static bool IsUnique(byte[] bytes, byte?[] pattern)
{
int first = PatternScanner.FindPattern(bytes, pattern);
return first >= 0 && PatternScanner.FindPatternInRegion(bytes, pattern, first + 1, bytes.Length) < 0;
}
/// <summary>The PlayerModule, checked to be the class whose option handler was read; or why not.</summary>
private static IntPtr Module(out string why)
{
why = "";
if (!MainThreadGuard.IsOnMainThread()) { why = "not on AC's thread"; return IntPtr.Zero; }
if (!LoginLifecycleHooks.HasObservedLoginComplete) { why = "not in the world yet"; return IntPtr.Zero; }
if (!_probed) Probe();
if (_setOption == IntPtr.Zero) { why = _status; return IntPtr.Zero; }
IntPtr ps = CharacterManagementHooks.PlayerSystemOnMainThread();
if (ps == IntPtr.Zero) { why = "AC's player system isn't there"; return IntPtr.Zero; }
IntPtr module = ps + PlayerModuleOffset;
if (!ClientObjectHooks.IsReadableSpan(module, ModuleReadSpan)) { why = "AC's player module can't be read"; return IntPtr.Zero; }
IntPtr vtable = Marshal.ReadIntPtr(module);
if (vtable == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(vtable, OptionChangedSlot + 4))
{
why = "AC's player module has no vtable";
return IntPtr.Zero;
}
IntPtr slot = Marshal.ReadIntPtr(vtable, OptionChangedSlot);
if (slot != _optionChanged)
{
why = $"AC's player module isn't the expected class (slot 0x{slot.ToInt32():X8})";
return IntPtr.Zero;
}
return module;
}
/// <summary>The client's current value of the room's option. AC's main thread.</summary>
public static bool TryGet(Room room, out bool on, out string why)
{
on = false;
IntPtr module = Module(out why);
if (module == IntPtr.Zero) return false;
try
{
on = (((delegate* unmanaged[Thiscall]<IntPtr, uint, int>)_getOption)(module, OptionId(room)) & 1) != 0;
return true;
}
catch (Exception ex)
{
why = $"{ex.GetType().Name}: {ex.Message}";
return false;
}
}
/// <summary>
/// Sets "Hear <paramref name="room"/> Chat" as AC's Options panel does. True when the client's
/// value is <paramref name="on"/> afterwards; <paramref name="why"/> says what happened (already
/// so: AC sends nothing, as the panel). AC's main thread.
/// </summary>
public static bool TrySet(Room room, bool on, out string why)
{
IntPtr module = Module(out why);
if (module == IntPtr.Zero) return false;
uint id = OptionId(room);
try
{
var get = (delegate* unmanaged[Thiscall]<IntPtr, uint, int>)_getOption;
bool before = (get(module, id) & 1) != 0;
if (before == on)
{
why = $"Hear {Name(room)} Chat is already {(on ? "on" : "off")}; nothing sent";
return true;
}
((delegate* unmanaged[Thiscall]<IntPtr, uint, int, void>)_setOption)(module, id, on ? 1 : 0);
bool after = (get(module, id) & 1) != 0;
if (after != on)
{
why = $"AC kept Hear {Name(room)} Chat {(after ? "on" : "off")}";
return false;
}
why = $"Hear {Name(room)} Chat {(on ? "on" : "off")} (AC sends option 0x{id:X2} to the server)";
RynthLog.Compat("AcCharacterOptions: " + why);
return true;
}
catch (Exception ex)
{
why = $"{ex.GetType().Name}: {ex.Message}";
return false;
}
}
}

View file

@ -127,6 +127,18 @@ internal static class ChatCommandReplies
public const string ServerUsage =
"Usage: /rc server [<server> auto|on|off] | pick <server>|auto | [aelrynth|other|auto] | names ilt [add|remove <pattern>]";
public const string ChatOptionUsage =
"Usage: /rc chatoption <general|trade|lfg|roleplay> [on|off] (alone: the client's current value)";
/// <summary>"/rc chatoption": a room (rp = roleplay), then nothing, on or off.</summary>
private static bool ChatOptionArgs(string a)
{
string[] w = a.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (w.Length is < 1 or > 2) return false;
if (w[0].ToLowerInvariant() is not ("general" or "trade" or "lfg" or "roleplay" or "rp")) return false;
return w.Length == 1 || w[1].ToLowerInvariant() is "on" or "off";
}
public const string HotkeyUsage =
"Usage: /rc hotkey list | add <combo> <action or /command> | remove <combo> | enable|disable <combo> | actions | status | on|off";
@ -187,6 +199,7 @@ internal static class ChatCommandReplies
V("keymap", "Usage: /rc keymap check|bind|unbind <action> <key> | dump, e.g. /rc keymap bind UseQuickSlot_10 F11", KeymapArgs),
V("panels", "Usage: /rc panels [open|close|toggle <id>] | replace <id> <command|off>", PanelsArgs),
V("title", "Usage: /rc title <title id>", a => uint.TryParse(a.Trim(), out uint t) && t != 0),
V("chatoption", ChatOptionUsage, ChatOptionArgs),
V("hotkey", HotkeyUsage, null),
V("rl", "Usage: /rc rl (reloads RynthCore, as the bar's RL button)", NoArgs, "reload"),
V("inventory", "Usage: /rc inventory (opens or closes the Inventory panel)", NoArgs, "inv"),

View file

@ -647,6 +647,30 @@ internal static class RynthCoreChatCommands
else Fail($"Couldn't set title {titleId}: {why}.");
return;
}
// /rc chatoption <general|trade|lfg|roleplay> [on|off]: AC's own "Hear <room> Chat" option,
// set as its Options panel does (AcCharacterOptions; spike for RynthChat's network tab).
if (IsVerb(sub, "chatoption", out string chatOptionArgs))
{
string[] co = chatOptionArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (co.Length is < 1 or > 2 || !AcCharacterOptions.TryParseRoom(co[0], out var room)
|| (co.Length == 2 && !co[1].Equals("on", StringComparison.OrdinalIgnoreCase)
&& !co[1].Equals("off", StringComparison.OrdinalIgnoreCase)))
{
Fail(ChatCommandReplies.ChatOptionUsage);
return;
}
if (co.Length == 1)
{
if (AcCharacterOptions.TryGet(room, out bool isOn, out string getWhy))
Reply($"Hear {AcCharacterOptions.Name(room)} Chat is {(isOn ? "on" : "off")} in the client.");
else Fail($"Couldn't read Hear {AcCharacterOptions.Name(room)} Chat: {getWhy}.");
return;
}
bool wantOn = co[1].Equals("on", StringComparison.OrdinalIgnoreCase);
if (AcCharacterOptions.TrySet(room, wantOn, out string setWhy)) Reply(setWhy + ".");
else Fail($"Couldn't set Hear {AcCharacterOptions.Name(room)} Chat: {setWhy}.");
return;
}
if (IsVerb(sub, "settings", out string settingsArgs))
{
SettingsCommand(settingsArgs);

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>
@ -123,6 +129,7 @@ internal sealed class ChatFace : IImGuiPanel
y += 26;
}
else y = DrawHeader(new Vector2(x0, origin.Y + 4), w);
y = DrawNetworkBar(x0, y, w);
_view.SyncLines(snap, lines, tab);
@ -181,12 +188,143 @@ 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 network bar (2026-11-15, Task 11) under the header while the current tab is a network
/// tab of an active server (ChatModel.CurrentNetworkEntry): "Join the Dereth Network" until the
/// mod says this character is on it, then "On the network as Name@world" and Leave. Its first
/// view per character session asks the server (ChatModel.NoteNetworkTabViewed). A Join that
/// could not set the room option says why here, once per click. Returns the y below it.
/// </summary>
private float DrawNetworkBar(float x, float y, float w)
{
if (ChatModel.CurrentNetworkEntry() == null) return y;
ChatModel.NoteNetworkTabViewed();
const float h = 22;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float ty = y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
string? problem = ChatNetwork.JoinProblem;
if (ChatNetwork.On == true)
{
const float leaveW = 60;
string label = ChatNetwork.Address is { Length: > 0 } a ? "On the network as " + a : "On the network";
dl.AddText(new Vector2(x + 4, ty), Text, label);
if (Button("##chat_net_leave", "Leave", new Vector2(x + w - leaveW, y), new Vector2(leaveW, h), Text, BtnFill))
ChatModel.RequestNetworkLeave();
ImGuiNET.ImGui.SetItemTooltip("Take this character off the Dereth Network");
}
else
{
// While a Join waits for the mod's answer (ChatNetwork.PendingJoin, 15 s at most) it is not offered again.
bool waiting = ChatNetwork.PendingJoin.IsPending(Environment.TickCount64);
string join = waiting ? "Joining the Dereth Network..." : "Join the Dereth Network";
float joinW = ImGuiNET.ImGui.CalcTextSize(join).X + 16;
if (Button("##chat_net_join", join, new Vector2(x, y), new Vector2(joinW, h), Text, TabActive, enabled: !waiting))
ChatModel.RequestNetworkJoin();
ImGuiNET.ImGui.SetItemTooltip("Put this character on the Dereth Network and listen to its Global room");
}
if (problem != null)
{
y += h + 2;
dl.AddText(new Vector2(x + 4, y), Faded(Text), problem);
y += ImGuiNET.ImGui.GetFontSize();
}
else y += h;
return y + 4;
}
/// <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 +378,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 +387,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;
}
@ -321,7 +476,7 @@ internal sealed class ChatFace : IImGuiPanel
if (text.Length == 0 && !typing)
{
_inputScroll = 0;
dl.AddText(new Vector2(p.X + 5, ty), Faded(Mute), ChatModel.InputHint ?? "Press Enter to chat…");
dl.AddText(new Vector2(p.X + 5, ty), Faded(Mute), ChatModel.InputPlaceholder ?? "Press Enter to chat…");
}
else
{
@ -362,6 +517,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

@ -286,6 +286,17 @@ internal static unsafe class Win32Backend
PostMessage(_gameHwnd, WM_RYNTHCORE_TELL, IntPtr.Zero, IntPtr.Zero);
}
// Chat's network bar (Join / Leave, and the status question on the first view of a network
// tab): its chat lines and AC option go out on a fresh game-thread dispatch, as a typed line does.
internal const uint WM_RYNTHCORE_NETWORK = 0x0400 + 0x5245;
/// <summary>Fired on the game thread to run the chat network bar's queued work (ChatModel).</summary>
public static Action? OnChatNetwork;
/// <summary>Callable from any thread: runs <see cref="OnChatNetwork"/> on AC's main thread. False when nothing was posted.</summary>
public static bool RequestChatNetwork() =>
_gameHwnd != IntPtr.Zero && PostMessage(_gameHwnd, WM_RYNTHCORE_NETWORK, IntPtr.Zero, IntPtr.Zero);
/// <summary>The game's main window handle.</summary>
public static IntPtr GameHwnd => _gameHwnd;
@ -969,6 +980,11 @@ internal static unsafe class Win32Backend
OnChatTellSelected?.Invoke();
return IntPtr.Zero;
}
if (msg == WM_RYNTHCORE_NETWORK)
{
OnChatNetwork?.Invoke();
return IntPtr.Zero;
}
// ── Chat: Enter in-game activates the chat TextBox ───────────
// Numpad Enter (extended key, lParam bit 24) is reserved for AC functions — never capture it.

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;
@ -96,6 +97,7 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
{
// Another client saved the shared settings: pick up its rules / filters (every 2 s at most).
ChatModel.PollSettingsFile();
ChatModel.KickNetworkOps(); // the network bar's next queued op, once its gap has passed
try { PollLines(); }
finally
{
@ -179,6 +181,14 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
if (line.Route.Mention) ChatModel.PumpMentionSound();
added.Add(line);
}
// The network's status lines (ChatNetwork): On follows them, and the answer to the status
// question the first view of a network tab asked is left out of the scrollback.
try { ChatModel.PumpNetworkLines(added); }
catch (Exception ex) { RynthLog.UI($"ChatSource: network status check failed ({ex.GetType().Name}: {ex.Message})."); }
// 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 +474,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 +533,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 +664,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 +716,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 +745,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 +777,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 +1039,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 +1066,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 +1077,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 +1111,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 +1148,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 +1179,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 +1192,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 +1220,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;
}
@ -972,6 +1283,10 @@ internal static class ChatModel
public static int InputCursor => Volatile.Read(ref _input).Cursor;
/// <summary>Shown in the empty input box instead of the usual hint (e.g. "select an NPC first").</summary>
public static string? InputHint => Volatile.Read(ref _input).Hint;
/// <summary>What the empty input box shows: the hint if one is set, else the network tab's line, else null (the face's usual one).</summary>
public static string? InputPlaceholder =>
InputHint ?? (CurrentNetwork() == null ? null
: ChatNetwork.On == false ? "Join the network to chat here" : "Press Enter to chat in Global (Dereth Network)");
public static long InputVersion => Interlocked.Read(ref _inputVersion);
/// <summary>Raised on AC's main thread after the input line changes.</summary>
@ -1060,6 +1375,8 @@ internal static class ChatModel
SetInput("", 0, null);
};
Win32Backend.OnChatSend = OnSend;
Win32Backend.OnChatNetwork = RunNetworkOps; // the network bar's Join / Leave and the status question
HookNetworkSession();
// Escape leaves the line, as retail's chat does: the half-typed text stays in the box
// (it used to be erased), and Enter or a click on the box carries on typing it.
Win32Backend.OnChatCancel = () =>
@ -1149,6 +1466,14 @@ internal static class ChatModel
SetInput("", 0, null);
IntPtr send = SendLinePtr;
if (text.Length == 0 || send == IntPtr.Zero) return;
// On a network tab (CurrentNetwork) a plain line goes through the network's command; off
// the network it is not sent (the placeholder says so, InputHint). Commands go as typed.
if (CurrentNetwork() is { } network)
{
string? rewritten = ChatNetwork.Rewrite(text, network.Command, ChatNetwork.OnOrUnknown);
if (rewritten == null) return;
text = rewritten;
}
IntPtr ptr = Marshal.StringToHGlobalAnsi(text);
// RynthChat sends the line through Host.InvokeChatParser, on this thread: an engine /rc
// command in it is the player's, so it answers in chat (RynthCoreChatCommands.PlayerLine).
@ -1160,6 +1485,282 @@ internal static class ChatModel
finally { Marshal.FreeHGlobal(ptr); }
}
/// <summary>
/// The network declaration of the current tab, or null when the tab is not a network tab: the
/// tab is a server's seeded tab (tabServers), one of that server's active entries owns a rule
/// that fills it, and the entry declares "network". Any thread.
/// </summary>
public static SectionNetworkDecl? CurrentNetwork() => NetworkOfTab(CurrentTab());
/// <summary>The network declaration of <paramref name="tab"/> (see CurrentNetwork), or null.</summary>
public static SectionNetworkDecl? NetworkOfTab(string tab) => NetworkEntryOfTab(tab)?.Network;
/// <summary>The chatTabs entry that makes the current tab a network tab (see CurrentNetwork), or null. Any thread.</summary>
public static SectionChatTabDecl? CurrentNetworkEntry() => NetworkEntryOfTab(CurrentTab());
/// <summary>The chatTabs entry that makes <paramref name="tab"/> a network tab, or null.</summary>
public static SectionChatTabDecl? NetworkEntryOfTab(string tab)
{
if (!Volatile.Read(ref _tabServers).TryGetValue(tab, out string? server)) return null;
string[] active = _activeServers;
if (!ChatRouter.ServerIn(active, server)) return null;
foreach (SectionChatTabDecl d in _tabDecls)
{
if (d.Network == null || !string.Equals(d.Server, server, StringComparison.OrdinalIgnoreCase)) continue;
string key = ChatServerTabs.OwnerKey(d);
foreach (ChatFilterRule rule in Filters)
if (string.Equals(rule.Owner, key, StringComparison.OrdinalIgnoreCase)
&& string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase))
return d;
}
return null;
}
// -- Network join status (Task 11, ChatNetwork) --
/// <summary>Is any active server's entry a network one? Cheap (no lock); the pump checks it per poll.</summary>
private static bool AnyNetworkActive()
{
string[] active = _activeServers;
foreach (SectionChatTabDecl d in _tabDecls)
if (d.Network != null && ChatRouter.ServerIn(active, d.Server)) return true;
return false;
}
/// <summary>
/// Pump thread (ChatSource.PollLines): status lines move ChatNetwork.On; the status question's
/// own answer is taken out of <paramref name="added"/>. Free while no network is active.
/// </summary>
internal static void PumpNetworkLines(List<ChatLine> added)
{
if (added.Count == 0 || !AnyNetworkActive()) return;
long now = Environment.TickCount64;
bool applyJoin = false;
int eaten = added.RemoveAll(l =>
{
bool eat = ChatNetwork.Observe(l.Text, l.ChatType, now, out bool apply);
applyJoin |= apply;
return eat;
});
if (eaten > 0) RynthLog.UI($"ChatModel: the network status answer ({eaten} line{(eaten == 1 ? "" : "s")}) kept out of the scrollback.");
// The mod put the character on after a Join: now its room option (RunNetworkOp, ApplyJoinRoom).
if (applyJoin && Volatile.Read(ref _pendingJoinEntry) is { } entry) RequestNetwork(NetworkOp.ApplyJoinRoom, entry);
}
// The network bar's work, on AC's main thread: one op per WM_RYNTHCORE_NETWORK message, at
// least NetworkOpPacer.GapMs apart (each op sends at most one line through AC's window proc).
// The message is posted only while the gap has passed (KickNetworkOps: the click, and the pump
// every poll), never slept for on AC's thread. Each op carries the entry it was asked for.
private enum NetworkOp { Query, Join, Leave, ApplyJoinRoom }
private readonly record struct NetworkWork(NetworkOp Op, SectionChatTabDecl Entry, long QueuedMs);
private static readonly System.Collections.Concurrent.ConcurrentQueue<NetworkWork> _networkOps = new();
private static readonly NetworkOpPacer _networkPacer = new();
private static int _networkPosted;
private static SectionChatTabDecl? _pendingJoinEntry;
// Settings: JoinKey(server, character) -> the room Join turned on (absent while none).
private static Dictionary<string, string> _networkJoinRooms = NewMap();
/// <summary>
/// The main window shows a network tab (its face, every frame): the first time per character
/// session, once in the world, ask the server whether this character is on the network. The
/// question counts as asked only once it was sent (ChatNetwork.Query).
/// </summary>
public static void NoteNetworkTabViewed()
{
if (!LoginLifecycleHooks.HasObservedLoginComplete || SendLinePtr == IntPtr.Zero) return;
if (CurrentNetworkEntry() is not { } entry || !ChatNetwork.Query.TryQueue()) return;
if (!RequestNetwork(NetworkOp.Query, entry)) ChatNetwork.Query.Dropped();
}
/// <summary>The Join button. Any thread: the work runs on AC's main thread.</summary>
public static void RequestNetworkJoin()
{
if (CurrentNetworkEntry() is { } entry) RequestNetwork(NetworkOp.Join, entry);
}
/// <summary>The Leave button. Any thread: the work runs on AC's main thread.</summary>
public static void RequestNetworkLeave()
{
if (CurrentNetworkEntry() is { } entry) RequestNetwork(NetworkOp.Leave, entry);
}
private static bool RequestNetwork(NetworkOp op, SectionChatTabDecl entry)
{
if (_networkOps.Count >= 8) return false; // clicks while the game thread is busy: a few is plenty
_networkOps.Enqueue(new NetworkWork(op, entry, Environment.TickCount64));
KickNetworkOps();
return true;
}
/// <summary>
/// Posts the message that runs the next op, when one is queued, none is posted, and the gap since
/// the last op has passed. Any thread (PostMessage); the pump calls it every poll.
/// </summary>
internal static void KickNetworkOps()
{
if (_networkOps.IsEmpty || !_networkPacer.IsDue(Environment.TickCount64)) return;
if (Interlocked.CompareExchange(ref _networkPosted, 1, 0) != 0) return;
if (!Win32Backend.RequestChatNetwork()) Volatile.Write(ref _networkPosted, 0); // no window yet: the next kick tries
}
/// <summary>A new character session asks again and knows nothing (login and logout). Once, at init.</summary>
private static void HookNetworkSession()
{
LoginLifecycleHooks.LoginComplete += ChatNetwork.ResetSession;
LogoutLifecycleHooks.LogoutComplete += ChatNetwork.ResetSession;
}
/// <summary>
/// AC's main thread, on a fresh window message (Win32Backend, WM_RYNTHCORE_NETWORK), as a typed
/// line is sent: at most one queued op (the status question, Join, Leave, a Join's room).
/// </summary>
private static void RunNetworkOps()
{
Volatile.Write(ref _networkPosted, 0);
long now = Environment.TickCount64;
if (!_networkPacer.IsDue(now)) return; // the next kick posts again once the gap has passed
while (_networkOps.TryDequeue(out NetworkWork work))
{
if (NetworkOpPacer.IsStale(work.QueuedMs, now))
{
if (work.Op == NetworkOp.Query) ChatNetwork.Query.Dropped();
RynthLog.UI($"ChatModel: network {work.Op} dropped (queued {now - work.QueuedMs} ms ago).");
continue; // nothing sent: the next one may run in this message
}
_networkPacer.TryTake(now);
try { RunNetworkOp(work.Op, work.Entry); }
catch (Exception ex)
{
if (work.Op == NetworkOp.Query) ChatNetwork.Query.Dropped();
RynthLog.UI($"ChatModel: network {work.Op} failed ({ex.GetType().Name}: {ex.Message}).");
}
break; // one op per message
}
KickNetworkOps();
}
private static void RunNetworkOp(NetworkOp op, SectionChatTabDecl entry)
{
// The entry's server stopped being active meanwhile: nothing of its network applies.
if (entry.Network is not { } network || !ChatRouter.ServerIn(_activeServers, entry.Server))
{
if (op == NetworkOp.Query) ChatNetwork.Query.Dropped();
return;
}
string command = network.Command;
string key = ChatNetwork.JoinKey(entry.Server, PumpCharacterName());
switch (op)
{
case NetworkOp.Query:
ChatNetwork.Eater.Query(Environment.TickCount64);
if (SendChatLine("/" + command)) ChatNetwork.Query.MarkSent();
else
{
ChatNetwork.Eater.Clear();
ChatNetwork.Query.Dropped();
}
break;
case NetworkOp.Join:
// The room option waits for the mod's "on" (ChatNetwork.PendingJoin): a refused
// join (a name that cannot be an address, a world off the network) sets nothing.
ChatNetwork.JoinProblem = null;
Volatile.Write(ref _pendingJoinEntry, entry);
ChatNetwork.PendingJoin.Begin(Environment.TickCount64);
if (!SendChatLine("/" + command + " on")) ChatNetwork.PendingJoin.Clear();
break;
case NetworkOp.ApplyJoinRoom:
ApplyJoinRoom(entry, key);
break;
case NetworkOp.Leave:
{
ChatNetwork.JoinProblem = null;
ChatNetwork.PendingJoin.Clear();
SendChatLine("/" + command + " off");
if (!Volatile.Read(ref _networkJoinRooms).TryGetValue(key, out string? joined)) break;
if (AcCharacterOptions.TryParseRoom(joined, out AcCharacterOptions.Room room)
&& !AcCharacterOptions.TrySet(room, false, out string why))
{
ChatNetwork.JoinProblem = $"Hear {AcCharacterOptions.Name(room)} Chat not turned off: {why}";
RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
break; // kept: a later Leave tries again
}
SetJoinRoom(key, null);
break;
}
}
}
/// <summary>
/// A Join was answered "on": the Global room's Hear option, by ChatNetwork.JoinPlan (an earlier
/// Join's room that is no longer the Global one goes off first; the current one goes on only
/// when it is off, and is recorded only then). AC's main thread.
/// </summary>
private static void ApplyJoinRoom(SectionChatTabDecl entry, string key)
{
string roomName = Volatile.Read(ref _globalRooms).TryGetValue(entry.Server, out string? found) ? found : entry.GlobalRoomFallback;
if (!AcCharacterOptions.TryParseRoom(roomName, out AcCharacterOptions.Room room))
{
ChatNetwork.JoinProblem = $"no room \"{roomName}\" to listen to";
return;
}
string current = AcCharacterOptions.Name(room);
if (!AcCharacterOptions.TryGet(room, out bool isOn, out string why))
{
ChatNetwork.JoinProblem = $"Hear {current} Chat not read: {why}";
RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
return;
}
string? recorded = Volatile.Read(ref _networkJoinRooms).TryGetValue(key, out string? r) ? r : null;
JoinPlanResult plan = ChatNetwork.JoinPlan(recorded, current, isOn);
if (plan.TurnOff != null)
{
if (AcCharacterOptions.TryParseRoom(plan.TurnOff, out AcCharacterOptions.Room old)
&& !AcCharacterOptions.TrySet(old, false, out why))
{
ChatNetwork.JoinProblem = $"Hear {AcCharacterOptions.Name(old)} Chat not turned off: {why}";
RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
return; // the record stays: the next Join tries again
}
SetJoinRoom(key, null);
}
if (plan.TurnOn != null && !AcCharacterOptions.TrySet(room, true, out why))
{
ChatNetwork.JoinProblem = $"Hear {current} Chat not set: {why}";
RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
return;
}
SetJoinRoom(key, plan.Record);
}
/// <summary>Records (or with null forgets) the room Join turned on for <paramref name="key"/>. Saved when it changed.</summary>
private static void SetJoinRoom(string key, string? room)
{
lock (EditLock)
{
bool have = _networkJoinRooms.TryGetValue(key, out string? was);
if (room == null ? !have : have && string.Equals(was, room, StringComparison.Ordinal)) return;
Dictionary<string, string> map = NewMap(_networkJoinRooms);
if (room == null) map.Remove(key); else map[key] = room;
Volatile.Write(ref _networkJoinRooms, map);
}
SaveSettings();
}
/// <summary>A line through the chat parser, as a typed one goes; false when RynthChat isn't bound. AC's main thread, on a fresh message.</summary>
private static unsafe bool SendChatLine(string text)
{
IntPtr send = SendLinePtr;
if (send == IntPtr.Zero) return false;
IntPtr ptr = Marshal.StringToHGlobalAnsi(text);
try { ((delegate* unmanaged[Cdecl]<IntPtr, void>)send)(ptr); }
finally { Marshal.FreeHGlobal(ptr); }
return true;
}
/// <summary>The creature selected in the game (an NPC or another player), for /tell.
/// AC's main thread only. Never yourself, never an item.</summary>
private static bool TryGetSelectedTellName(out string name)
@ -1349,6 +1950,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 +1962,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 +1985,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 +2006,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 +2081,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 +2105,39 @@ 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);
_networkJoinRooms = NewMap(dto.NetworkJoinRooms);
_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 +2183,12 @@ 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)),
NetworkJoinRooms = NullIfEmpty(Volatile.Read(ref _networkJoinRooms)),
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,327 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ChatNetwork.cs
// Chat network tabs (2026-11-15): a chatTabs entry with "network" is a tab for a chat
// network (the Dereth Network). While that tab is current, a typed line that is not a
// command is sent through the network's own command ("/<command> global <text>"), and
// only while the player is on the network. Pure and engine-free: ChatModel.OnSend
// calls Rewrite; tools/ChatFilterTests compiles this file as is.
//
// Join status (Task 11): whether this character is on the network is read from the
// mod's own system lines (Classify, the texts of the Dereth.Network ACE mod,
// third_party/dereth/network/ace-mod/Dereth.Network/Core/NetworkWorld.Commands.cs, which
// sends them as ChatMessageType.Broadcast). The first view of a network tab per
// character session asks ("/<command>"), and the answer to that one question is kept
// out of the scrollback (ReplyEater): the status line, and the "Your directory page:"
// line that may follow it. Every later status line is shown and moves On.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.UI.Data;
/// <summary>What a status line says: on the network (as <see cref="Address"/>) or off it.</summary>
internal readonly record struct NetworkStatus(bool On, string? Address);
internal static class ChatNetwork
{
// -1 unknown, 0 off the network, 1 on it. An int so any thread can read and write it whole.
private static int _on = -1;
private static volatile string? _address;
private static volatile string? _joinProblem;
/// <summary>
/// Is the player on the network this session? null = not known yet (the first view of the
/// tab asks); a line is then sent as if on. Any thread.
/// </summary>
public static bool? On
{
get => Volatile.Read(ref _on) switch { 0 => false, 1 => true, _ => null };
set => Volatile.Write(ref _on, value == null ? -1 : value.Value ? 1 : 0);
}
/// <summary>Is a line to be sent as if on the network? Unknown counts as on.</summary>
public static bool OnOrUnknown => On != false;
/// <summary>The network address the last "on" line named (Name@world), or null. Any thread.</summary>
public static string? Address => _address;
/// <summary>Why the last Join could not set the room option (shown in the bar), or null. Any thread.</summary>
public static string? JoinProblem
{
get => _joinProblem;
set => _joinProblem = value;
}
/// <summary>The status question's reply lines to keep out of the scrollback.</summary>
public static readonly NetworkReplyEater Eater = new();
/// <summary>The once-per-session status question: asked only once it was actually sent.</summary>
public static readonly NetworkQueryState Query = new();
/// <summary>A Join waiting for the mod to say this character is on (then the room option is set).</summary>
public static readonly NetworkPendingJoin PendingJoin = new();
/// <summary>A new character session (login, logout): nothing known, ask again. Any thread.</summary>
public static void ResetSession()
{
On = null;
_address = null;
_joinProblem = null;
Query.Reset();
Eater.Clear();
PendingJoin.Clear();
}
/// <summary>
/// One incoming line (the pump): a status line moves On and the address; true when the line is
/// part of the status question's answer and is to be left out of the scrollback.
/// <paramref name="applyJoin"/>: an "on" line answered a pending Join, so its room option is due.
/// "This world is not on the Dereth Network." ends any wait (no answer is coming) and is shown.
/// </summary>
internal static bool Observe(string text, int chatType, long nowMs, out bool applyJoin)
{
applyJoin = false;
if (IsWorldNotOnLine(text, chatType))
{
Eater.Clear();
PendingJoin.Clear();
return false;
}
NetworkStatus? status = Classify(text, chatType);
if (status is { } s)
{
On = s.On;
_address = s.On ? s.Address : null;
applyJoin = PendingJoin.OnStatus(s, nowMs);
}
return Eater.Take(status, text, chatType, nowMs);
}
/// <summary>
/// What Join does with the room options, given the room an earlier Join turned on and recorded
/// (<paramref name="recorded"/>, null when none), the room the Global rule tracks now and whether
/// that one is on already. A recorded room that is no longer the current one is turned off (Join
/// turned it on: that is what the record means); the current one is turned on only when it is
/// off, and recorded only then (or kept, when it was ours already).
/// </summary>
internal static JoinPlanResult JoinPlan(string? recorded, string current, bool currentIsOn)
{
bool same = recorded != null && string.Equals(recorded, current, StringComparison.OrdinalIgnoreCase);
string? turnOff = recorded != null && !same ? recorded : null;
if (currentIsOn) return new JoinPlanResult(turnOff, null, same ? recorded : null);
return new JoinPlanResult(turnOff, current, current);
}
// -- The mod's lines --
// ACE ChatMessageType: Broadcast 0x00 (the mod's ShowSystem), System 0x05. A player's speech,
// tells and channel lines are other types, so a player saying these words is never a status.
internal static bool IsSystemType(int chatType) => chatType is 0x00 or 0x05;
internal const string OnPrefix = "You are on the Dereth Network as ";
internal const string OnAlreadyPrefix = "You are on the Dereth Network already, as ";
internal const string NotOnPrefix = "You are not on the Dereth Network";
internal const string OffPrefix = "You are off the Dereth Network";
internal const string DirectoryPrefix = "Your directory page:";
internal const string WorldNotOnLine = "This world is not on the Dereth Network."; // NetworkWorld.NotOnNetworkLine
/// <summary>The mod's answer on a world that is not on the network (nothing else follows it).</summary>
internal static bool IsWorldNotOnLine(string text, int chatType) =>
!string.IsNullOrEmpty(text) && IsSystemType(chatType) && string.Equals(text.Trim(), WorldNotOnLine, StringComparison.Ordinal);
/// <summary>
/// What a line says about this character and the network, or null when it says nothing (or is not
/// a system line). On lines carry the address: "...as Ann@alpha." up to the first ". " or the end.
/// </summary>
internal static NetworkStatus? Classify(string text, int chatType)
{
if (string.IsNullOrEmpty(text) || !IsSystemType(chatType)) return null;
string t = text.Trim();
if (t.StartsWith(OnAlreadyPrefix, StringComparison.Ordinal))
return AddressAfter(t, OnAlreadyPrefix.Length) is { } a ? new NetworkStatus(true, a) : null;
if (t.StartsWith(OnPrefix, StringComparison.Ordinal))
return AddressAfter(t, OnPrefix.Length) is { } a ? new NetworkStatus(true, a) : null;
if (t.StartsWith(NotOnPrefix, StringComparison.Ordinal) || t.StartsWith(OffPrefix, StringComparison.Ordinal))
return new NetworkStatus(false, null);
return null;
}
/// <summary>The status answer's second line ("Your directory page: https://...").</summary>
internal static bool IsDirectoryLine(string text, int chatType) =>
!string.IsNullOrEmpty(text) && IsSystemType(chatType)
&& text.TrimStart().StartsWith(DirectoryPrefix, StringComparison.Ordinal);
private static string? AddressAfter(string t, int start)
{
int end = t.IndexOf(". ", start, StringComparison.Ordinal);
string a = (end >= 0 ? t[start..end] : t[start..].TrimEnd('.')).Trim();
return a.Length > 0 && a.IndexOf('@') > 0 ? a : null;
}
/// <summary>The settings key of "Join turned the room option on" for one character on one server.</summary>
internal static string JoinKey(string server, string character) =>
(server ?? "").Trim().ToLowerInvariant() + "/" + (character ?? "").Trim();
/// <summary>
/// What to send for a line typed on a network tab, or null when it must not be sent. The line is
/// trimmed; empty is null; a line starting with / or @ is a command and goes unchanged; any other
/// goes as "/&lt;command&gt; global &lt;text&gt;" while on the network, and is not sent off it.
/// </summary>
internal static string? Rewrite(string line, string command, bool onNetwork)
{
string text = (line ?? string.Empty).Trim();
if (text.Length == 0) return null;
if (text[0] == '/' || text[0] == '@') return text;
return onNetwork ? "/" + command + " global " + text : null;
}
}
/// <summary>What Join does: the room to turn off first (or null), the room to turn on (or null), and the room to record after (null: none).</summary>
internal readonly record struct JoinPlanResult(string? TurnOff, string? TurnOn, string? Record);
/// <summary>
/// The once-per-session status question: None (ask when a network tab is viewed), Queued (asked
/// for, not sent yet: not asked again meanwhile), Sent (answered or not, never again this session).
/// A queued question that could not be sent (the tab changed first) goes back to None. Any thread.
/// </summary>
internal sealed class NetworkQueryState
{
private const int None = 0, Queued = 1, Sent = 2;
private int _state;
/// <summary>True when the question is still to be asked; the caller queues it now.</summary>
public bool TryQueue() => Interlocked.CompareExchange(ref _state, Queued, None) == None;
/// <summary>The question went out: never again this session.</summary>
public void MarkSent() => Volatile.Write(ref _state, Sent);
/// <summary>The queued question was dropped unsent: the next view asks again.</summary>
public void Dropped() => Interlocked.CompareExchange(ref _state, None, Queued);
public bool WasSent => Volatile.Read(ref _state) == Sent;
public void Reset() => Volatile.Write(ref _state, None);
}
/// <summary>
/// A Join waiting for the mod's answer: the room option is set only when an "on" status line
/// arrives within <see cref="TimeoutMs"/> of the Join. Anything else (an "off" line, silence, a
/// refusal such as a name that cannot be an address) sets nothing, and the wait just lapses.
/// Any thread.
/// </summary>
internal sealed class NetworkPendingJoin
{
public const long TimeoutMs = 15_000;
private readonly object _lock = new();
private long _since = -1;
/// <summary>Join was just sent.</summary>
public void Begin(long nowMs)
{
lock (_lock) _since = nowMs;
}
public void Clear()
{
lock (_lock) _since = -1;
}
/// <summary>Is a Join waiting (and not lapsed) at <paramref name="nowMs"/>?</summary>
public bool IsPending(long nowMs)
{
lock (_lock)
{
if (_since >= 0 && nowMs - _since > TimeoutMs) _since = -1;
return _since >= 0;
}
}
/// <summary>A status line arrived: true (once) when it is the "on" that a waiting Join was waiting for.</summary>
public bool OnStatus(NetworkStatus status, long nowMs)
{
lock (_lock)
{
if (_since < 0) return false;
if (nowMs - _since > TimeoutMs) { _since = -1; return false; }
if (!status.On) return false; // an earlier answer still in flight; keep waiting
_since = -1;
return true;
}
}
}
/// <summary>
/// Paces the network bar's work: one chat line through AC's window proc per window message, and
/// at least <see cref="GapMs"/> between two (OnLoginCommandRunner.InterCommandGapMs is 250 ms too).
/// Work older than <see cref="MaxAgeMs"/> is dropped. Pure; ChatModel holds one.
/// </summary>
internal sealed class NetworkOpPacer
{
public const long GapMs = 250;
public const long MaxAgeMs = 10_000;
private long _lastMs = long.MinValue / 2; // read whole on any thread (Interlocked: a 32-bit process)
/// <summary>Has the gap since the last op passed at <paramref name="nowMs"/>? Any thread.</summary>
public bool IsDue(long nowMs) => nowMs - Interlocked.Read(ref _lastMs) >= GapMs;
/// <summary>May one op run at <paramref name="nowMs"/>? If so it is counted as run then. One thread.</summary>
public bool TryTake(long nowMs)
{
if (!IsDue(nowMs)) return false;
Interlocked.Exchange(ref _lastMs, nowMs);
return true;
}
/// <summary>Is an op queued at <paramref name="queuedMs"/> too old to run at <paramref name="nowMs"/>?</summary>
public static bool IsStale(long queuedMs, long nowMs) => nowMs - queuedMs > MaxAgeMs;
}
/// <summary>
/// The answer to the one status question a session asks: the first status line within
/// <see cref="StatusWindowMs"/> of the question, and a "Your directory page:" line within
/// <see cref="DirectoryWindowMs"/> after that status line (only an "on" answer has one). Nothing
/// else is ever eaten: a status line nobody asked for, or one too late, is shown. Any thread.
/// </summary>
internal sealed class NetworkReplyEater
{
public const long StatusWindowMs = 10_000;
public const long DirectoryWindowMs = 2_000;
private readonly object _lock = new();
private long _queryAt = -1, _statusAt = -1;
/// <summary>The question was just sent.</summary>
public void Query(long nowMs)
{
lock (_lock) { _queryAt = nowMs; _statusAt = -1; }
}
public void Clear()
{
lock (_lock) { _queryAt = -1; _statusAt = -1; }
}
/// <summary>Is this line (already classified as <paramref name="status"/>) part of the answer?</summary>
public bool Take(NetworkStatus? status, string text, int chatType, long nowMs)
{
lock (_lock)
{
if (status is { } s)
{
bool asked = _queryAt >= 0 && nowMs - _queryAt >= 0 && nowMs - _queryAt <= StatusWindowMs;
_queryAt = -1;
_statusAt = asked && s.On ? nowMs : -1;
return asked;
}
if (_statusAt >= 0 && ChatNetwork.IsDirectoryLine(text, chatType))
{
bool soon = nowMs - _statusAt <= DirectoryWindowMs;
_statusAt = -1;
return soon;
}
return false;
}
}
}

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,17 @@ 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>"server/Character" -> the room whose Hear option the network bar's Join turned on (Leave turns it off again); absent while none.</summary>
[JsonPropertyName("networkJoinRooms")] public Dictionary<string, string>? NetworkJoinRooms { 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,24 @@
// 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. An entry may add "network": { "kind": "dereth",
// "command": "dn" } (the chat network the tab belongs to): "kind" must be
// dereth, "command" is optional (default dn) and 1-32 of a-z and 0-9; a
// bad network is dropped and reported but the entry is kept. 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 +163,19 @@ 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>The chat network this tab belongs to ("network", 2026-11-15), or null.</summary>
public SectionNetworkDecl? Network { get; init; }
}
/// <summary>A chat network a chatTabs entry declares: Kind is "dereth"; Command is the mod's chat command word (no slash).</summary>
internal sealed record SectionNetworkDecl(string Kind, string Command);
/// <summary>One plugin's parsed manifest.</summary>
internal sealed record SectionManifest(
string Plugin,
@ -157,6 +188,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 +212,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 +315,21 @@ 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, out string note);
if (decl == null) { Note(ref error, "chatTabs: entry dropped, " + why); continue; }
if (note.Length > 0) Note(ref error, "chatTabs: " + decl.Server + "/" + decl.Id + " " + note);
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 +339,85 @@ 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, out string note)
{
why = string.Empty;
note = 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));
}
SectionNetworkDecl? network = null;
if (e.TryGetProperty("network", out JsonElement net))
{
string kind = net.ValueKind == JsonValueKind.Object ? Str(net, "kind").Trim().ToLowerInvariant() : string.Empty;
string command = net.ValueKind == JsonValueKind.Object && net.TryGetProperty("command", out _) ? Str(net, "command").Trim() : "dn";
if (kind != "dereth") note = "network dropped, kind is not dereth";
else if (!NetworkCommandValid(command)) note = "network dropped, command is not 1-32 of a-z and 0-9";
else network = new SectionNetworkDecl(kind, command);
}
return new SectionChatTabDecl(server, id, name, Bool(e, "pinned", false), room, rules.ToArray()) { Network = network };
}
/// <summary>A network command word: 1-32 characters of a-z and 0-9.</summary>
private static bool NetworkCommandValid(string s)
{
if (s.Length is < 1 or > 32) return false;
foreach (char c in s) if (!(c is >= 'a' and <= 'z' or >= '0' and <= '9')) return false;
return true;
}
/// <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

@ -96,6 +96,9 @@ internal static class Program
("panels", "panels", "panels open 1 2"),
("title", "title 42", "title banana"),
("title", "title 7", "title"),
("chatoption", "chatoption general on", "chatoption general maybe"),
("chatoption", "chatoption rp", "chatoption global off"),
("chatoption", "chatoption LFG OFF", "chatoption"),
("rl", "rl", "rl now"),
("rl", "reload", "reload now"),
("inventory", "inv", "inv now"),

View file

@ -36,6 +36,13 @@
<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" />
<!-- 2026-11-15: network tab sends. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatNetwork.cs" Link="Engine\ChatNetwork.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,13 @@ internal static class Program
RetailRules();
RetailSetting();
TabsAcrossSetting();
ServerTabSettingsRoundTrip();
ServerTabDiscovery();
ServerTabPlans();
PinBookkeeping();
NetworkRewrite();
NetworkStatusLines();
NetworkSourcePins();
SharedFileReload();
LineColorTags();
LineColorKinds();
@ -1108,6 +1116,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 +1607,450 @@ 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: network tab sends (ChatNetwork.Rewrite), pure.
private static void NetworkRewrite()
{
Case("Rewrite_PlainText");
Check(ChatNetwork.Rewrite("hello all", "derethnetwork", true) == "/derethnetwork global hello all", "on the network: sent through the command");
Check(ChatNetwork.Rewrite("hello all", "derethnetwork", false) == null, "off the network: not sent");
Case("Rewrite_CommandsPassThrough");
Check(ChatNetwork.Rewrite("/tell Bob@coldeve, hi", "dn", true) == "/tell Bob@coldeve, hi", "/tell unchanged on");
Check(ChatNetwork.Rewrite("/tell Bob@coldeve, hi", "dn", false) == "/tell Bob@coldeve, hi", "/tell unchanged off");
Check(ChatNetwork.Rewrite("@derethnetwork on", "dn", true) == "@derethnetwork on", "@command unchanged on");
Check(ChatNetwork.Rewrite("@derethnetwork on", "dn", false) == "@derethnetwork on", "@command unchanged off");
Case("Rewrite_Trimmed");
Check(ChatNetwork.Rewrite(" hi there ", "dn", true) == "/dn global hi there", "leading and trailing spaces trimmed");
Check(ChatNetwork.Rewrite(" /tell Bob, hi ", "dn", true) == "/tell Bob, hi", "a command after spaces is still a command");
Check(ChatNetwork.Rewrite(" @dn on", "dn", false) == "@dn on", "an @command after spaces is still a command");
Case("Rewrite_Empty");
Check(ChatNetwork.Rewrite("", "dn", true) == null && ChatNetwork.Rewrite("", "dn", false) == null, "empty is never sent");
Check(ChatNetwork.Rewrite(" \t ", "dn", true) == null && ChatNetwork.Rewrite(" ", "dn", false) == null, "whitespace only is never sent");
Case("NetworkState_DefaultsUnknown");
Check(ChatNetwork.On == null && ChatNetwork.OnOrUnknown, "unknown by default and treated as on");
ChatNetwork.On = false;
Check(ChatNetwork.On == false && !ChatNetwork.OnOrUnknown, "off");
ChatNetwork.On = true;
Check(ChatNetwork.On == true && ChatNetwork.OnOrUnknown, "on");
ChatNetwork.On = null;
Check(ChatNetwork.On == null, "reset to unknown");
}
// 2026-11-15 (Task 11): the Dereth.Network mod's status lines (texts verbatim from
// third_party/dereth/network/ace-mod/Dereth.Network/Core/NetworkWorld.Commands.cs, sent as
// ChatMessageType.Broadcast = 0), the answer eater, and the session state.
private static void NetworkStatusLines()
{
const int Broadcast = 0, System = 5, Speech = 2, Tell = 3, Channel = 8;
Case("Classify_OnTexts");
var on1 = ChatNetwork.Classify("You are on the Dereth Network as Ann@alpha. Anyone on the network can see when you are online, send you tells and find your profile in its directory. Type @derethnetwork help for the commands.", Broadcast);
Check(on1 is { On: true, Address: "Ann@alpha" }, "the join line: on, as Ann@alpha");
var on2 = ChatNetwork.Classify("You are on the Dereth Network already, as Ann@alpha.", Broadcast);
Check(on2 is { On: true, Address: "Ann@alpha" }, "already on: on, as Ann@alpha");
var on3 = ChatNetwork.Classify("You are on the Dereth Network as Ann@alpha. The hub is connected. You have no friends on other worlds.", Broadcast);
Check(on3 is { On: true, Address: "Ann@alpha" }, "the status line: on, as Ann@alpha");
var on4 = ChatNetwork.Classify("You are on the Dereth Network as Mary Ann@dreamweave-stage. The hub is not connected. You have 2 friends on other worlds.", System);
Check(on4 is { On: true, Address: "Mary Ann@dreamweave-stage" }, "a spaced name and a hyphenated world, System type too");
Case("Classify_OffTexts");
Check(ChatNetwork.Classify("You are not on the Dereth Network.", Broadcast) is { On: false, Address: null }, "off already");
Check(ChatNetwork.Classify("You are not on the Dereth Network. Type @derethnetwork on to join it.", Broadcast) is { On: false }, "off, with the hint");
Check(ChatNetwork.Classify("You are not on the Dereth Network. Type @derethnetwork on to join it as Ann@alpha.", Broadcast) is { On: false, Address: null }, "the status line when off: off, no address");
Check(ChatNetwork.Classify("You are off the Dereth Network. Nobody on another world can see you or tell you, and your profile is out of its directory.", Broadcast) is { On: false }, "the leave line: off");
Case("Classify_LookAlikes");
string said = "You are on the Dereth Network as Bob@alpha. The hub is connected.";
Check(ChatNetwork.Classify(said, Speech) == null, "a player saying it in Local is not a status");
Check(ChatNetwork.Classify(said, Tell) == null, "nor in a tell");
Check(ChatNetwork.Classify(said, Channel) == null, "nor on a channel");
Check(ChatNetwork.Classify("You are not on the Dereth Network.", Speech) == null, "an off text said in Local is not a status");
Check(ChatNetwork.Classify("This world is not on the Dereth Network.", Broadcast) == null, "the world's own state is not the character's");
Check(ChatNetwork.Classify("You have entered the Roleplay channel.", Broadcast) == null, "room feedback is not a status");
Check(ChatNetwork.Classify("You are on the Dereth Network as nobody.", Broadcast) == null, "an on line without an address is not taken");
Check(ChatNetwork.Classify("", Broadcast) == null, "empty");
Check(ChatNetwork.IsDirectoryLine("Your directory page: https://example.org/directory/character/", Broadcast), "the directory line");
Check(!ChatNetwork.IsDirectoryLine("Your directory page: https://example.org/x", Speech), "a directory line said in Local is not one");
Case("Eater_EatsTheAnswerOnly");
var eater = new NetworkReplyEater();
string status = "You are on the Dereth Network as Ann@alpha. The hub is connected. You have no friends on other worlds.";
string page = "Your directory page: https://example.org/directory/character/";
var st = ChatNetwork.Classify(status, Broadcast);
Check(!eater.Take(st, status, Broadcast, 1000), "a status line nobody asked for is shown");
Check(!eater.Take(null, page, Broadcast, 1100), "and so is its directory line");
eater.Query(2000);
Check(!eater.Take(null, "You have entered the Roleplay channel.", Broadcast, 2100), "an unrelated line while asking is shown");
Check(eater.Take(st, status, Broadcast, 2500), "the answer is eaten");
Check(eater.Take(null, page, Broadcast, 3000), "its directory line within 2 s is eaten");
Check(!eater.Take(null, page, Broadcast, 3100), "a second directory line is shown");
Check(!eater.Take(st, status, Broadcast, 3200), "a second status line is shown (one question, one answer)");
Case("Eater_Windows");
eater.Query(10_000);
Check(!eater.Take(st, status, Broadcast, 10_000 + NetworkReplyEater.StatusWindowMs + 1), "an answer after the window is shown");
eater.Query(30_000);
Check(eater.Take(st, status, Broadcast, 30_500), "in time: eaten");
Check(!eater.Take(null, page, Broadcast, 30_500 + NetworkReplyEater.DirectoryWindowMs + 1), "a directory line after 2 s is shown");
eater.Query(40_000);
var off = ChatNetwork.Classify("You are not on the Dereth Network. Type @derethnetwork on to join it as Ann@alpha.", Broadcast);
Check(eater.Take(off, "x", Broadcast, 40_100), "an off answer is eaten");
Check(!eater.Take(null, page, Broadcast, 40_200), "an off answer has no directory line to eat");
eater.Query(50_000);
eater.Clear();
Check(!eater.Take(st, status, Broadcast, 50_100), "a cleared question eats nothing");
Case("Observe_MovesOnAndAddress");
ChatNetwork.ResetSession();
Check(ChatNetwork.On == null && ChatNetwork.Address == null, "a new session knows nothing");
Check(ChatNetwork.Query.TryQueue() && !ChatNetwork.Query.TryQueue(), "one question queued per session");
ChatNetwork.Query.MarkSent();
ChatNetwork.Eater.Query(100);
Check(ChatNetwork.Observe(status, Broadcast, 200, out bool apply0) && !apply0, "the session's answer is eaten (no Join pending)");
Check(ChatNetwork.On == true && ChatNetwork.Address == "Ann@alpha", "and puts the character on, as Ann@alpha");
Check(ChatNetwork.OnOrUnknown && ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == "/dn global hi", "on: Global lines are sent");
Check(!ChatNetwork.Observe(said, Speech, 300, out _) && ChatNetwork.On == true, "a player's look-alike changes nothing");
Check(!ChatNetwork.Observe("You are off the Dereth Network. Nobody on another world can see you or tell you, and your profile is out of its directory.", Broadcast, 400, out _),
"a later leave line is shown");
Check(ChatNetwork.On == false && ChatNetwork.Address == null, "and puts the character off");
Check(ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == null, "off: Global lines are blocked");
ChatNetwork.JoinProblem = "x";
ChatNetwork.ResetSession();
Check(ChatNetwork.On == null && ChatNetwork.OnOrUnknown && ChatNetwork.JoinProblem == null, "logout/login: unknown again (sent as on), no problem shown");
Check(ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == "/dn global hi", "unknown: Global lines are sent");
Check(ChatNetwork.Query.TryQueue(), "and the next view asks again");
ChatNetwork.ResetSession();
// F3: the question counts as asked only once it was sent.
Case("Query_ArmedOnlyWhenSent");
var q = new NetworkQueryState();
Check(q.TryQueue(), "a new session queues the question");
Check(!q.TryQueue(), "not twice while queued (every frame views the tab)");
q.Dropped();
Check(!q.WasSent && q.TryQueue(), "dropped unsent (the tab changed, RynthChat not bound): the next view asks again");
q.MarkSent();
Check(q.WasSent && !q.TryQueue(), "sent: never again this session");
q.Dropped();
Check(q.WasSent && !q.TryQueue(), "a late drop does not undo a sent question");
q.Reset();
Check(!q.WasSent && q.TryQueue(), "a new session asks again");
// F7: a world off the network answers with one line and nothing more.
Case("WorldNotOn_ClearsTheWait");
ChatNetwork.ResetSession();
ChatNetwork.On = true;
ChatNetwork.Eater.Query(1000);
ChatNetwork.PendingJoin.Begin(1000);
Check(!ChatNetwork.Observe("This world is not on the Dereth Network.", Broadcast, 1100, out bool applyW) && !applyW, "the world's line is shown, applies nothing");
Check(ChatNetwork.On == true, "and does not move On");
Check(!ChatNetwork.PendingJoin.IsPending(1100), "it ends a waiting Join");
Check(!ChatNetwork.Observe(status, Broadcast, 1200, out _), "and the eater: a later status line is shown");
Check(!ChatNetwork.IsWorldNotOnLine("This world is not on the Dereth Network.", Speech), "said in Local it is nothing");
ChatNetwork.ResetSession();
// F5: the room option waits for the mod's "on" after a Join.
Case("PendingJoin_StateMachine");
var pj = new NetworkPendingJoin();
var onS = new NetworkStatus(true, "Ann@alpha");
var offS = new NetworkStatus(false, null);
Check(!pj.OnStatus(onS, 0), "no Join: an on line applies nothing");
pj.Begin(1000);
Check(pj.IsPending(1000) && pj.IsPending(1000 + NetworkPendingJoin.TimeoutMs), "waiting up to the timeout");
Check(!pj.OnStatus(offS, 1500) && pj.IsPending(1500), "an off line (an earlier answer still in flight) keeps waiting");
Check(pj.OnStatus(onS, 2000), "the on line applies the room");
Check(!pj.IsPending(2000) && !pj.OnStatus(onS, 2100), "once only");
pj.Begin(10_000);
Check(!pj.OnStatus(onS, 10_000 + NetworkPendingJoin.TimeoutMs + 1), "an on line after the timeout applies nothing");
Check(!pj.IsPending(10_000 + NetworkPendingJoin.TimeoutMs + 1), "and the wait is over");
pj.Begin(40_000);
Check(!pj.IsPending(40_000 + NetworkPendingJoin.TimeoutMs + 1), "silence: the wait lapses by itself");
Check(!pj.OnStatus(onS, 40_000 + NetworkPendingJoin.TimeoutMs + 2), "and nothing is applied later");
pj.Begin(60_000);
pj.Clear();
Check(!pj.OnStatus(onS, 60_100), "Leave (Clear) cancels a waiting Join");
ChatNetwork.ResetSession();
ChatNetwork.PendingJoin.Begin(5000);
Check(!ChatNetwork.Observe("This character's name cannot be a network address, so it cannot join the Dereth Network.", Broadcast, 5100, out bool applyR) && !applyR,
"a refused join applies nothing");
Check(ChatNetwork.Observe(status, Broadcast, 5200, out bool applyOn) == false && applyOn, "an on line after a Join applies the room (and, unasked, is shown)");
ChatNetwork.ResetSession();
// F4: which rooms Join turns off and on, and what it records.
Case("JoinPlan");
Check(ChatNetwork.JoinPlan(null, "Roleplay", false) == new JoinPlanResult(null, "Roleplay", "Roleplay"), "nothing recorded, room off: turn on, record");
Check(ChatNetwork.JoinPlan(null, "Roleplay", true) == new JoinPlanResult(null, null, null), "nothing recorded, room on already: touch nothing, record nothing");
Check(ChatNetwork.JoinPlan("Roleplay", "Roleplay", true) == new JoinPlanResult(null, null, "Roleplay"), "ours and still on: keep the record");
Check(ChatNetwork.JoinPlan("Roleplay", "roleplay", false) == new JoinPlanResult(null, "roleplay", "roleplay"), "ours but turned off since (any case): on again, recorded");
Check(ChatNetwork.JoinPlan("Roleplay", "General", false) == new JoinPlanResult("Roleplay", "General", "General"), "Global moved: the old room off, the new on, recorded");
Check(ChatNetwork.JoinPlan("Roleplay", "General", true) == new JoinPlanResult("Roleplay", null, null), "Global moved to a room on already: old off, new untouched, no record");
Case("OpPacer");
var pacer = new NetworkOpPacer();
Check(pacer.IsDue(0) && pacer.TryTake(0), "the first op runs at once");
Check(!pacer.IsDue(NetworkOpPacer.GapMs - 1) && !pacer.TryTake(NetworkOpPacer.GapMs - 1), "the next waits the gap");
Check(pacer.TryTake(NetworkOpPacer.GapMs), "and runs once it has passed");
Check(NetworkOpPacer.GapMs >= 250, "the gap is at least OnLoginCommandRunner's 250 ms");
Check(!NetworkOpPacer.IsStale(0, NetworkOpPacer.MaxAgeMs) && NetworkOpPacer.IsStale(0, NetworkOpPacer.MaxAgeMs + 1), "old work is dropped");
Case("JoinKey");
Check(ChatNetwork.JoinKey(" DreamWeave ", " Ann ") == "dreamweave/Ann", "server lower-cased, both trimmed, the name kept");
Case("Settings_NetworkJoinRooms");
var opts = RynthChatJsonContext.Default.RynthChatSettingsDto;
string none = JsonSerializer.Serialize(new RynthChatSettingsDto(), opts);
Check(!none.Contains("networkJoinRooms", StringComparison.Ordinal), "absent while unset");
var withRoom = new RynthChatSettingsDto { NetworkJoinRooms = new Dictionary<string, string> { ["dreamweave/Ann"] = "Roleplay" } };
string json = JsonSerializer.Serialize(withRoom, opts);
RynthChatSettingsDto back = JsonSerializer.Deserialize(json, opts)!;
Check(json.Contains("\"networkJoinRooms\":{\"dreamweave/Ann\":\"Roleplay\"}", StringComparison.Ordinal), "written as server/character -> room");
Check(back.NetworkJoinRooms is { } m && m.TryGetValue("dreamweave/Ann", out string? r) && r == "Roleplay", "and read back");
Check(JsonSerializer.Deserialize(OldFile, opts)!.NetworkJoinRooms == null, "an older file has none");
}
// 2026-11-15 (Task 11 review, F1 and F8): source scans for what the engine-side code must keep
// doing (it is not compiled into this tool). Each pin is a predicate over the source, matched on
// whole trimmed lines so a commented-out line does not count, and each is shown to fail on a
// mutated copy of the same source (the mutation proof), so a pin that passes vacuously is caught.
private static void NetworkSourcePins()
{
string? chatData = RepoFile("src", "RynthCore.Engine", "UI", "Data", "ChatData.cs");
string? options = RepoFile("src", "RynthCore.Engine", "Compatibility", "AcCharacterOptions.cs");
string? resolver = RepoFile("src", "RynthCore.Engine", "Compatibility", "HookResolver.cs");
Case("NetworkPins_FilesFound");
Check(chatData != null && options != null && resolver != null, "found ChatData.cs, AcCharacterOptions.cs and HookResolver.cs by walking up from " + AppContext.BaseDirectory);
if (chatData == null || options == null || resolver == null) return;
string data = File.ReadAllText(chatData).Replace("\r\n", "\n");
string opt = File.ReadAllText(options).Replace("\r\n", "\n");
string res = File.ReadAllText(resolver).Replace("\r\n", "\n");
// F1: a resolved address is used only when HookResolver says pattern-unique AND the pattern is unique.
Case("Pin_UniquePatternOnly");
const string uniqueLine = "r.Success && r.Source == HookResolver.ResolveSource.PatternScan && r.Detail == \"pattern-unique\"";
const string countLine = "&& IsUnique(text.Bytes, pattern) ? r.Address : IntPtr.Zero;";
static bool UniquePin(string s, string u, string c) => HasLine(s, u) && HasLine(s, c);
Check(HasLine(res, "detail = \"pattern-unique\";"), "HookResolver's own word for a single match is pattern-unique");
Check(!HasLine(res.Replace("detail = \"pattern-unique\";", "detail = \"unique\";"), "detail = \"pattern-unique\";"), "mutation: another word fails that pin");
Check(UniquePin(opt, uniqueLine, countLine), "AcCharacterOptions takes pattern-unique only, and counts the matches itself");
Check(!UniquePin(opt.Replace(" && r.Detail == \"pattern-unique\"", ""), uniqueLine, countLine), "mutation: without the Detail check the pin fails");
Check(!UniquePin(opt.Replace("&& IsUnique(text.Bytes, pattern) ", ""), uniqueLine, countLine), "mutation: without the count the pin fails");
// F8: OnSend keeps the typed line in history and rewrites after it.
Case("Pin_OnSendRewritesAfterHistory");
const string rewriteLine = "string? rewritten = ChatNetwork.Rewrite(text, network.Command, ChatNetwork.OnOrUnknown);";
static bool RewritePin(string body, string rw) => LineAt(body, rw) > LastLineAt(body, "AddHistory(text);") && LastLineAt(body, "AddHistory(text);") >= 0;
string? onSend = MethodBody(data, "private static unsafe void OnSend()");
Check(onSend != null && RewritePin(onSend, rewriteLine), "OnSend: Rewrite comes after the last AddHistory(text)");
if (onSend != null)
{
Check(!RewritePin(onSend.Replace(rewriteLine, "// " + rewriteLine), rewriteLine), "mutation: Rewrite commented out fails");
Check(!RewritePin(onSend + "\n AddHistory(text);\n", rewriteLine), "mutation: an AddHistory after the Rewrite fails");
}
// F8: the poll path runs the network status check, before the lines are published.
Case("Pin_PollRunsNetworkLines");
const string pumpLine = "try { ChatModel.PumpNetworkLines(added); }";
static bool PollPin(string body, string p) => LineAt(body, p) >= 0 && LineAt(body, p) < body.IndexOf("Publish(ChatHistory.Merge(", StringComparison.Ordinal);
string? poll = MethodBody(data, "private void PollLines()");
Check(poll != null && PollPin(poll, pumpLine), "PollLines calls PumpNetworkLines before publishing");
if (poll != null)
{
Check(!PollPin(poll.Replace(pumpLine, "// " + pumpLine), pumpLine), "mutation: commented out fails");
const string publishLine = "Publish(ChatHistory.Merge(old, added, maxLines));";
Check(LineAt(poll, publishLine) >= 0, "the publish line the mutation moves it after is there");
Check(!PollPin(poll.Replace(pumpLine, "").Replace(publishLine, publishLine + "\n " + pumpLine), pumpLine),
"mutation: moved after the publish fails");
}
// F8: login and logout reset the network session, hooked at init.
Case("Pin_SessionResets");
const string loginLine = "LoginLifecycleHooks.LoginComplete += ChatNetwork.ResetSession;";
const string logoutLine = "LogoutLifecycleHooks.LogoutComplete += ChatNetwork.ResetSession;";
string? hook = MethodBody(data, "private static void HookNetworkSession()");
string? install = MethodBody(data, "public static void InstallInput()");
static bool SessionPin(string? h, string? i, string a, string b) => h != null && i != null && HasLine(h, a) && HasLine(h, b) && HasLine(i, "HookNetworkSession();");
Check(SessionPin(hook, install, loginLine, logoutLine), "HookNetworkSession adds both resets, and InstallInput calls it");
Check(!SessionPin(hook?.Replace(loginLine, "// " + loginLine), install, loginLine, logoutLine), "mutation: no login reset fails");
Check(!SessionPin(hook?.Replace(logoutLine, "// " + logoutLine), install, loginLine, logoutLine), "mutation: no logout reset fails");
Check(!SessionPin(hook, install?.Replace("HookNetworkSession();", "// HookNetworkSession();"), loginLine, logoutLine), "mutation: never hooked fails");
// F8: TryGet and TrySet check the module (thread, login, vtable) before any call into AC.
Case("Pin_ModuleBeforeEveryCall");
const string moduleLine = "IntPtr module = Module(out why);";
const string guardLine = "if (module == IntPtr.Zero) return false;";
static bool ModulePin(string? body)
{
if (body == null) return false;
int m = LineAt(body, "IntPtr module = Module(out why);"), g = LineAt(body, "if (module == IntPtr.Zero) return false;");
if (m < 0 || g < m) return false;
// Any use of a delegate field (a call, or taking it into a local that is called) is after the guard.
foreach (string field in new[] { "_getOption", "_setOption" })
for (int at = body.IndexOf(field, StringComparison.Ordinal); at >= 0; at = body.IndexOf(field, at + 1, StringComparison.Ordinal))
if (at < g) return false;
return body.Contains("_getOption", StringComparison.Ordinal);
}
string? tryGet = MethodBody(opt, "public static bool TryGet(");
string? trySet = MethodBody(opt, "public static bool TrySet(");
Check(ModulePin(tryGet) && ModulePin(trySet), "TryGet and TrySet: Module() and its guard before every delegate call");
Check(trySet != null && trySet.Contains("_setOption)(", StringComparison.Ordinal) && trySet.Contains("_getOption;", StringComparison.Ordinal),
"TrySet does use both delegates (the pin covers them)");
Check(!ModulePin(tryGet?.Replace(moduleLine, "// " + moduleLine)), "mutation: TryGet without Module() fails");
Check(!ModulePin(trySet?.Replace(guardLine, "// " + guardLine)), "mutation: TrySet without the guard fails");
Check(!ModulePin(trySet?.Replace(moduleLine, "((delegate* unmanaged[Thiscall]<IntPtr, uint, int, void>)_setOption)(IntPtr.Zero, 0, 0);\n " + moduleLine)),
"mutation: a call before Module() fails");
}
private static string? RepoFile(params string[] parts)
{
for (string? dir = AppContext.BaseDirectory; dir != null; dir = Path.GetDirectoryName(dir))
{
string candidate = Path.Combine(new[] { dir }.Concat(parts).ToArray());
if (File.Exists(candidate)) return candidate;
}
return null;
}
/// <summary>The body (from its opening brace to the matching close) of the member whose declaration starts with <paramref name="head"/>.</summary>
private static string? MethodBody(string src, string head)
{
int at = src.IndexOf(head, StringComparison.Ordinal);
if (at < 0) return null;
int open = src.IndexOf('{', at);
if (open < 0) return null;
int depth = 0;
for (int i = open; i < src.Length; i++)
{
if (src[i] == '{') depth++;
else if (src[i] == '}' && --depth == 0) return src[open..(i + 1)];
}
return null;
}
/// <summary>The offset of the first line whose trimmed text is exactly <paramref name="line"/> (a commented-out line is not it), or -1.</summary>
private static int LineAt(string text, string line)
{
int offset = 0;
foreach (string l in text.Split('\n'))
{
if (l.Trim() == line) return offset;
offset += l.Length + 1;
}
return -1;
}
private static int LastLineAt(string text, string line)
{
int offset = 0, last = -1;
foreach (string l in text.Split('\n'))
{
if (l.Trim() == line) last = offset;
offset += l.Length + 1;
}
return last;
}
private static bool HasLine(string text, string line)
{
foreach (string l in text.Split('\n'))
if (l.Trim() == line) return true;
return false;
}
// 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,8 @@ internal static class Program
WindowTakeOver();
WindowFrameless();
ManifestBarMenu();
ManifestChatTabs();
ManifestChatTabNetwork();
BarMenuHoverTiming();
BarMenuReload();
StackCheckAfterPluginDraw();
@ -594,6 +596,109 @@ 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 ManifestChatTabNetwork()
{
const string head = "{ \"chatTabs\": [ { \"server\": \"dw\", \"id\": \"a\", \"name\": \"A\", \"rules\": []";
SectionManifest m = SectionManifestParser.Parse("DW", head + ", \"network\": { \"kind\": \"dereth\", \"command\": \"derethnetwork\" } } ] }", out string err);
Case("manifest: chatTabs network present");
Check(err.Length == 0 && m.ChatTabs.Length == 1 && m.ChatTabs[0].Network == new SectionNetworkDecl("dereth", "derethnetwork"), "kind and command parse: " + err);
Case("manifest: chatTabs network absent");
m = SectionManifestParser.Parse("DW", head + " } ] }", out err);
Check(err.Length == 0 && m.ChatTabs.Length == 1 && m.ChatTabs[0].Network == null, "no network key = null: " + err);
Case("manifest: chatTabs network bad kind");
m = SectionManifestParser.Parse("DW", head + ", \"network\": { \"kind\": \"irc\", \"command\": \"dn\" } } ] }", out err);
Check(m.ChatTabs.Length == 1 && m.ChatTabs[0].Network == null && err.Contains("network"), "key dropped, entry kept, error notes it: " + err);
Case("manifest: chatTabs network bad command");
string[] bad = { "Dn", "d n", "/dn", "", new string('a', 33) };
for (int i = 0; i < bad.Length; i++)
{
m = SectionManifestParser.Parse("DW", head + ", \"network\": { \"kind\": \"dereth\", \"command\": \"" + bad[i] + "\" } } ] }", out err);
Check(m.ChatTabs.Length == 1 && m.ChatTabs[0].Network == null && err.Contains("network"), "key dropped, entry kept, error notes it: '" + bad[i] + "'");
}
m = SectionManifestParser.Parse("DW", head + ", \"network\": { \"kind\": \"dereth\", \"command\": \"" + new string('a', 32) + "\" } } ] }", out err);
Check(err.Length == 0 && m.ChatTabs[0].Network?.Command.Length == 32, "32 characters is allowed");
Case("manifest: chatTabs network default command");
m = SectionManifestParser.Parse("DW", head + ", \"network\": { \"kind\": \"dereth\" } } ] }", out err);
Check(err.Length == 0 && m.ChatTabs[0].Network == new SectionNetworkDecl("dereth", "dn"), "absent command = dn: " + err);
}
private static void ManifestBarMenu()
{
Case("plugin windows: barMenu (v95)");