feat(chat): standard UB-IT-style chat filters, plain-text custom rule modes and a line tester

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-05 00:13:13 -04:00
commit 51307657d9
4 changed files with 794 additions and 141 deletions

View file

@ -0,0 +1,70 @@
# RynthChat: standard (canned) filters and easier custom rules
**Date:** 2026-10-05
**Component:** RynthCore Engine — RynthChat filters panel (`UI/Panels/RynthChatFiltersPanel.cs`)
## Summary
The Chat Filters window used to be a list of raw regex rows. It now has a
**Standard filters** page of ready-made tick-boxes, modelled on UtilityBelt-IT's
chat filter categories. Custom rules now work with plain text, so you no longer
need to know regex.
## Standard filters page
38 canned filters in 6 groups. Each group has **All on** / **All off** buttons and
an "n/total on" count, and a search box at the top narrows the list.
| Group | Filters |
|---------|---------|
| Combat | Your attacks evaded, You evade attacks, Damage you deal, Damage you take, Your spells resisted, You resist spells, Not-a-PK failures, Dirty Fighting procs, Monster death messages |
| Casting | Your spell words, Others' spell words, Spell fizzles, Component usage, Your buff casts, Buffs others cast on you, Spell expiry (keeps Brilliance / Prodigal / Spectral) |
| Items | Healing kit success / failure, Salvage results / failures, Aura of the Craftsman, Mana stone usage, Periodic healing ticks |
| Social | Trade / buff bot spam (-t- / -b-), Failed assess on you, Kill task complete, General / Trade / LFG / Roleplay / Society channels |
| NPCs | Master Arbitrator (Colosseum) |
| Pets | Pet hits, Pet attacks evaded, Pet damage taken, Pet died, Pet recall blocked, Pet heal overflow |
- **Tick a box** to hide those lines. **Type a tab name** beside it to move them
to that tab instead; the tab is created automatically, like custom rules do.
- **Hover a filter** to see what it catches and an example line.
- **Player chat is protected:** filters on system text skip the Chat and Channels
tabs, so a player typing the same words in Local is never hidden.
- **Spell words:** ACE sends incantations as chat type 0x11, which RynthChat files
under Combat. "Your spell words" therefore never hides real Local speech.
## Custom rules page
- **Match modes:** each rule has a click-to-cycle mode button: **Contains**,
**Starts with**, **Ends with** (plain text, case-insensitive) or **Regex**.
- New rules default to Contains.
- Plain-text modes match the message itself, so the timestamp prefix can't
break "Starts with".
- Regex mode keeps the old behaviour (matches "hh:mm:ss Sender: message"), so
existing rules load and behave exactly as before.
- **Order:** first match wins, and ▲▼ reorder rules. Custom rules are checked
before the standard filters, so a custom rule can override a preset.
## Line tester
Paste any chat line at the bottom of the window to see which custom rule or
standard filter catches it, and whether it is hidden or moved.
- **"as System / Combat / …":** picks the channel the line is treated as arriving on.
- **Not filtered:** if nothing catches the line, the tester names the standard
filter you'd need to tick.
- **Make rule:** turns the test text into a Contains rule, ready to trim down.
## Settings
Saved in `%APPDATA%\RynthCore\rynthchat_settings.json`:
- `filters[].mode`: match mode. When missing, the rule is treated as Regex.
- `presets[]`: `{ id, enabled, tab }`, written only for filters you changed.
- Deleting a custom tab also turns off any standard filter that moved lines to it.
## Files
- New: `src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs`
- Rewritten: `src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs`
- Modified: `src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs` (match modes,
preset routing, tester, persistence)

View file

@ -1,14 +1,21 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthChatFiltersPanel.cs
// Standalone editor for RynthChat regex filter rules. Registered as its own
// "ChatFilters" panel (dockable/floatable) — rules get complex enough that
// a small overlay inside the chat panel doesn't cut it.
// Editor for RynthChat filters. Registered as its own "ChatFilters" panel
// (dockable/floatable).
//
// Rule semantics (shared state lives in RynthChatPanel):
// • Regex, case-insensitive, matched against the formatted line.
// • FIRST matching rule wins — order matters, hence the ▲▼ buttons.
// • Tab name set → matching lines MOVE to that tab (still shown in All).
// • Tab name empty → matching lines are hidden everywhere.
// Two pages:
// • Standard — canned UB-IT-style filters (RynthChatPresets) grouped by
// Combat / Casting / Items / Social / NPCs / Pets. Tick to hide; type a
// tab name to move the lines there instead. Searchable.
// • Custom — user rules. Match mode Contains / Starts with / Ends with
// (plain text, no regex needed) or Regex. First match wins (▲▼ reorder).
// A tester at the bottom shows which filter would catch a pasted line.
//
// Evaluation order (RynthChatPanel.EffectiveTab): custom rules, then presets.
// Tab set → matching lines MOVE to that tab (still visible in All).
// Tab empty → matching lines are hidden everywhere.
// No ComboBox / popups: the overlay's popup hosting is unreliable, so
// pickers are click-to-cycle buttons.
// ============================================================================
using System;
@ -29,39 +36,96 @@ internal static class RynthChatFiltersPanel
private static readonly IBrush FieldBorder = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x40, 0x59));
private static readonly IBrush AccentBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x26, 0x4C, 0x59));
private static readonly IBrush ButtonBg = new SolidColorBrush(Color.FromArgb(0xFF, 0x0F, 0x1F, 0x2E));
private static readonly IBrush GroupFg = new SolidColorBrush(Color.FromArgb(0xFF, 0xE6, 0xB4, 0x50));
private static readonly IBrush ResultFg = new SolidColorBrush(Color.FromArgb(0xFF, 0x9F, 0xD8, 0xFF));
// Channels the tester can pretend a line arrived on (must match the plugin's ChatClassifier names).
private static readonly string[] TestChannels = { "System", "Combat", "Chat", "Channels", "Other" };
private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts with", "Ends with" };
internal static Control Create()
{
RynthChatPanel.EnsureSettingsLoaded();
var hint = new TextBlock
bool showStandard = true;
string search = "";
// ── Page switcher + search ───────────────────────────────────────
var standardBtn = PageButton("Standard filters");
var customBtn = PageButton("Custom rules");
var searchBox = Field("search standard filters…", 170);
var header = new StackPanel
{
Text = "Regex rules, case-insensitive — FIRST match wins (reorder with ▲▼).\n" +
"Tab set: matching lines move to that tab (still visible in All).\n" +
"Tab empty: matching lines are hidden everywhere.",
FontSize = 9,
Foreground = Brushes.Gray,
Orientation = Orientation.Horizontal,
Spacing = 4,
Margin = new Thickness(4, 4, 4, 2),
Children = { standardBtn, customBtn, searchBox },
};
var rows = new StackPanel { Orientation = Orientation.Vertical, Spacing = 4, Margin = new Thickness(4) };
var hint = new TextBlock
{
FontSize = 9,
Foreground = Brushes.Gray,
Margin = new Thickness(4, 0, 4, 2),
TextWrapping = TextWrapping.Wrap,
};
var rows = new StackPanel { Orientation = Orientation.Vertical, Spacing = 3, Margin = new Thickness(4) };
var addBtn = new Button
{
Content = "+ Add filter",
Content = "+ Add rule",
FontSize = 10,
Padding = new Thickness(8, 3),
Margin = new Thickness(4, 2, 4, 6),
Margin = new Thickness(4, 2, 4, 2),
Background = AccentBg,
Foreground = Brushes.White,
BorderThickness = new Thickness(0),
};
// ── Tester ───────────────────────────────────────────────────────
int testChannel = 0;
var testBox = Field("test: paste a chat line here", 260);
var testChanBtn = SmallBtn($"as {TestChannels[0]}", Brushes.White);
ToolTip.SetTip(testChanBtn, "Channel the test line is treated as arriving on (click to change).");
var makeRuleBtn = SmallBtn("Make rule", Brushes.White);
ToolTip.SetTip(makeRuleBtn, "Create a custom 'Contains' rule from the test text (trim it down to the part that matters).");
var testResult = new TextBlock
{
FontSize = 10,
Foreground = ResultFg,
Margin = new Thickness(4, 0, 4, 4),
TextWrapping = TextWrapping.Wrap,
};
var testPanel = new StackPanel
{
Orientation = Orientation.Vertical,
Children =
{
new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Margin = new Thickness(4, 2, 4, 2),
Children = { testBox, testChanBtn, makeRuleBtn },
},
testResult,
},
};
void RefreshTest() =>
testResult.Text = RynthChatPanel.DescribeTestLine(testBox.Text ?? "", TestChannels[testChannel]);
var bottom = new StackPanel { Orientation = Orientation.Vertical, Children = { addBtn, testPanel } };
var layout = new DockPanel { Background = PanelBg };
DockPanel.SetDock(header, Dock.Top);
DockPanel.SetDock(hint, Dock.Top);
DockPanel.SetDock(addBtn, Dock.Bottom);
DockPanel.SetDock(bottom, Dock.Bottom);
layout.Children.Add(header);
layout.Children.Add(hint);
layout.Children.Add(addBtn);
layout.Children.Add(bottom);
layout.Children.Add(new ScrollViewer
{
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
@ -69,146 +133,327 @@ internal static class RynthChatFiltersPanel
Content = rows,
});
void RebuildRows()
void Changed()
{
RynthChatPanel.NotifyFiltersChanged();
RefreshTest();
}
// ── Standard page ────────────────────────────────────────────────
void BuildStandard()
{
rows.Children.Clear();
foreach (string group in RynthChatPresets.Groups)
{
var presets = RynthChatPresets.All
.Where(p => p.Group == group && MatchesSearch(p, search))
.ToList();
if (presets.Count == 0) continue;
int on = RynthChatPresets.All.Count(p => p.Group == group && p.Enabled);
int total = RynthChatPresets.All.Count(p => p.Group == group);
var allOn = SmallBtn("All on", Brushes.White);
var allOff = SmallBtn("All off", Brushes.White);
string g = group;
allOn.Click += (_, _) =>
{
foreach (var p in RynthChatPresets.All.Where(p => p.Group == g)) p.Enabled = true;
Changed();
BuildStandard();
};
allOff.Click += (_, _) =>
{
foreach (var p in RynthChatPresets.All.Where(p => p.Group == g)) p.Enabled = false;
Changed();
BuildStandard();
};
rows.Children.Add(new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 6,
Margin = new Thickness(0, 6, 0, 1),
Children =
{
new TextBlock
{
Text = $"{group} ({on}/{total} on)",
FontSize = 11,
FontWeight = FontWeight.Bold,
Foreground = GroupFg,
VerticalAlignment = VerticalAlignment.Center,
},
allOn,
allOff,
},
});
foreach (var preset in presets)
rows.Children.Add(PresetRow(preset));
}
if (rows.Children.Count == 0)
rows.Children.Add(Muted($"No standard filter matches \"{search}\"."));
}
Control PresetRow(RynthChatPresets.Preset p)
{
var check = new CheckBox
{
IsChecked = p.Enabled,
Content = new TextBlock { Text = p.Label, FontSize = 10, Foreground = Brushes.White },
MinWidth = 210,
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(check, $"{p.Description}\n\nExample:\n{p.Example}");
check.IsCheckedChanged += (_, _) =>
{
p.Enabled = check.IsChecked == true;
Changed();
};
var tabBox = Field("hide", 110);
tabBox.Text = p.Tab;
ToolTip.SetTip(tabBox, "Leave empty to hide these lines. Type a tab name to move them to that tab instead.");
tabBox.TextChanged += (_, _) =>
{
p.Tab = (tabBox.Text ?? "").Trim();
if (p.Enabled) Changed();
};
return new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Margin = new Thickness(8, 0, 0, 0),
Children = { check, tabBox },
};
}
// ── Custom page ──────────────────────────────────────────────────
void BuildCustom()
{
var filters = RynthChatPanel.Filters;
rows.Children.Clear();
for (int i = 0; i < filters.Count; i++)
{
var r = filters[i];
int index = i;
var enabledCheck = new CheckBox
{
IsChecked = r.Enabled,
Margin = new Thickness(0, 0, 2, 0),
VerticalAlignment = VerticalAlignment.Center,
};
enabledCheck.IsCheckedChanged += (_, _) =>
{
r.Enabled = enabledCheck.IsChecked == true;
RynthChatPanel.NotifyFiltersChanged();
};
var patternBox = new TextBox
{
Text = r.Pattern,
Watermark = "regex (e.g. AutoRun)",
FontSize = 10,
MinWidth = 220,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(patternBox, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(patternBox, ScrollBarVisibility.Disabled);
patternBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
patternBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
patternBox.TextChanged += (_, _) =>
{
r.Pattern = patternBox.Text ?? "";
r.Recompile();
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
RynthChatPanel.NotifyFiltersChanged();
};
var tabBox = new TextBox
{
Text = r.Tab,
Watermark = "tab (empty = hide)",
FontSize = 10,
Width = 120,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
tabBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tabBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
tabBox.TextChanged += (_, _) =>
{
r.Tab = (tabBox.Text ?? "").Trim();
RynthChatPanel.NotifyFiltersChanged();
};
Button SmallBtn(string label, IBrush fg) => new()
{
Content = label,
FontSize = 10,
Padding = new Thickness(5, 2),
Background = ButtonBg,
Foreground = fg,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
};
var upBtn = SmallBtn("▲", Brushes.White);
upBtn.IsEnabled = index > 0;
upBtn.Click += (_, _) =>
{
if (index <= 0) return;
filters.RemoveAt(index);
filters.Insert(index - 1, r);
RebuildRows();
RynthChatPanel.NotifyFiltersChanged();
};
var downBtn = SmallBtn("▼", Brushes.White);
downBtn.IsEnabled = index < filters.Count - 1;
downBtn.Click += (_, _) =>
{
if (index >= filters.Count - 1) return;
filters.RemoveAt(index);
filters.Insert(index + 1, r);
RebuildRows();
RynthChatPanel.NotifyFiltersChanged();
};
var delBtn = SmallBtn("Delete", Brushes.IndianRed);
delBtn.Click += (_, _) =>
{
filters.Remove(r);
RebuildRows();
RynthChatPanel.NotifyFiltersChanged();
};
rows.Children.Add(new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Children = { enabledCheck, patternBox, tabBox, upBtn, downBtn, delBtn },
});
}
rows.Children.Add(CustomRow(filters, i));
if (filters.Count == 0)
{
rows.Children.Add(new TextBlock
{
Text = "No filters yet — click \"+ Add filter\".",
FontSize = 10,
Foreground = Brushes.Gray,
Margin = new Thickness(2, 6),
});
}
rows.Children.Add(Muted("No custom rules yet — click \"+ Add rule\", or use \"Make rule\" on a test line."));
}
Control CustomRow(System.Collections.Generic.List<RynthChatPanel.ChatFilterRule> filters, int index)
{
var r = filters[index];
var enabledCheck = new CheckBox
{
IsChecked = r.Enabled,
Margin = new Thickness(0, 0, 2, 0),
VerticalAlignment = VerticalAlignment.Center,
};
enabledCheck.IsCheckedChanged += (_, _) =>
{
r.Enabled = enabledCheck.IsChecked == true;
Changed();
};
var modeBtn = SmallBtn(ModeLabels[(int)r.Mode], Brushes.White);
modeBtn.MinWidth = 72;
ToolTip.SetTip(modeBtn, "Click to change how the text is matched.\n" +
"Contains / Starts with / Ends with: plain text, case-insensitive.\n" +
"Regex: regular expression against \"hh:mm:ss Sender: message\".");
var patternBox = Field(PatternWatermark(r.Mode), 210);
patternBox.Text = r.Pattern;
patternBox.BorderBrush = r.Invalid && r.Pattern.Length > 0 ? Brushes.IndianRed : FieldBorder;
patternBox.TextChanged += (_, _) =>
{
r.Pattern = patternBox.Text ?? "";
r.Recompile();
patternBox.BorderBrush = r.Invalid && r.Pattern.Length > 0 ? Brushes.IndianRed : FieldBorder;
Changed();
};
modeBtn.Click += (_, _) =>
{
r.Mode = (RynthChatPanel.FilterMatchMode)(((int)r.Mode + 1) % ModeLabels.Length);
modeBtn.Content = ModeLabels[(int)r.Mode];
patternBox.Watermark = PatternWatermark(r.Mode);
r.Recompile();
patternBox.BorderBrush = r.Invalid && r.Pattern.Length > 0 ? Brushes.IndianRed : FieldBorder;
Changed();
};
var tabBox = Field("hide", 100);
tabBox.Text = r.Tab;
ToolTip.SetTip(tabBox, "Leave empty to hide matching lines. Type a tab name to move them to that tab.");
tabBox.TextChanged += (_, _) =>
{
r.Tab = (tabBox.Text ?? "").Trim();
Changed();
};
var upBtn = SmallBtn("▲", Brushes.White);
upBtn.IsEnabled = index > 0;
upBtn.Click += (_, _) =>
{
if (index <= 0) return;
filters.RemoveAt(index);
filters.Insert(index - 1, r);
BuildCustom();
Changed();
};
var downBtn = SmallBtn("▼", Brushes.White);
downBtn.IsEnabled = index < filters.Count - 1;
downBtn.Click += (_, _) =>
{
if (index >= filters.Count - 1) return;
filters.RemoveAt(index);
filters.Insert(index + 1, r);
BuildCustom();
Changed();
};
var delBtn = SmallBtn("Delete", Brushes.IndianRed);
delBtn.Click += (_, _) =>
{
filters.Remove(r);
BuildCustom();
Changed();
};
return new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn },
};
}
// ── Page switching ───────────────────────────────────────────────
void ShowPage()
{
standardBtn.Background = showStandard ? AccentBg : ButtonBg;
customBtn.Background = showStandard ? ButtonBg : AccentBg;
searchBox.IsVisible = showStandard;
addBtn.IsVisible = !showStandard;
hint.Text = showStandard
? "Tick a box to hide those lines. Type a tab name next to it to move them to that tab instead. " +
"Hover a filter for an example line. Custom rules are checked before these."
: "Plain-text rules need no regex: pick Contains / Starts with / Ends with (click the mode button). " +
"First matching rule wins — reorder with ▲▼. Empty tab = hide; a tab name = move there.";
if (showStandard) BuildStandard(); else BuildCustom();
}
standardBtn.Click += (_, _) => { showStandard = true; ShowPage(); };
customBtn.Click += (_, _) => { showStandard = false; ShowPage(); };
searchBox.TextChanged += (_, _) =>
{
search = (searchBox.Text ?? "").Trim();
if (showStandard) BuildStandard();
};
addBtn.Click += (_, _) =>
{
var rule = new RynthChatPanel.ChatFilterRule();
// New rules default to Contains — the easiest mode for non-regex users.
var rule = new RynthChatPanel.ChatFilterRule { Mode = RynthChatPanel.FilterMatchMode.Contains };
rule.Recompile();
RynthChatPanel.Filters.Add(rule);
RebuildRows();
// Empty pattern is inert until typed — no display change yet, but
// persist the row so it survives a relaunch mid-edit.
RynthChatPanel.NotifyFiltersChanged();
BuildCustom();
// Empty pattern is inert until typed; persisting keeps the row across a relaunch mid-edit.
Changed();
};
RebuildRows();
testBox.TextChanged += (_, _) => RefreshTest();
testChanBtn.Click += (_, _) =>
{
testChannel = (testChannel + 1) % TestChannels.Length;
testChanBtn.Content = $"as {TestChannels[testChannel]}";
RefreshTest();
};
makeRuleBtn.Click += (_, _) =>
{
string text = (testBox.Text ?? "").Trim();
if (text.Length == 0) return;
var rule = new RynthChatPanel.ChatFilterRule { Mode = RynthChatPanel.FilterMatchMode.Contains, Pattern = text };
rule.Recompile();
RynthChatPanel.Filters.Add(rule);
showStandard = false;
ShowPage();
Changed();
};
ShowPage();
RefreshTest();
return layout;
}
// ── Helpers ──────────────────────────────────────────────────────────
private static bool MatchesSearch(RynthChatPresets.Preset p, string search) =>
search.Length == 0
|| p.Label.Contains(search, StringComparison.OrdinalIgnoreCase)
|| p.Description.Contains(search, StringComparison.OrdinalIgnoreCase)
|| p.Example.Contains(search, StringComparison.OrdinalIgnoreCase)
|| p.Group.Contains(search, StringComparison.OrdinalIgnoreCase);
private static string PatternWatermark(RynthChatPanel.FilterMatchMode mode) => mode switch
{
RynthChatPanel.FilterMatchMode.Contains => "text anywhere in the line",
RynthChatPanel.FilterMatchMode.StartsWith => "line starts with…",
RynthChatPanel.FilterMatchMode.EndsWith => "line ends with…",
_ => "regex (e.g. AutoRun)",
};
/// <summary>Single-line text box that hands keyboard input to Avalonia while focused.</summary>
private static TextBox Field(string watermark, double width)
{
var box = new TextBox
{
Watermark = watermark,
FontSize = 10,
Width = width,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(box, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(box, ScrollBarVisibility.Disabled);
box.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
box.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
return box;
}
private static Button SmallBtn(string label, IBrush fg) => new()
{
Content = label,
FontSize = 10,
Padding = new Thickness(5, 2),
Background = ButtonBg,
Foreground = fg,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
};
private static Button PageButton(string label) => new()
{
Content = label,
FontSize = 10,
Padding = new Thickness(8, 3),
Background = ButtonBg,
Foreground = Brushes.White,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
};
private static TextBlock Muted(string text) => new()
{
Text = text,
FontSize = 10,
Foreground = Brushes.Gray,
Margin = new Thickness(2, 6),
TextWrapping = TextWrapping.Wrap,
};
}

View file

@ -5,7 +5,9 @@
// Phase 1: read-only display alongside retail chat (retail not yet suppressed).
// • Per-channel tabs: All / Chat / Channels / System / Combat / Rynth / Other
// plus user-defined tabs fed by regex filter rules
// • Regex filter rules: move matching lines to a custom tab, or hide them
// • Filter rules (custom Contains / Starts with / Ends with / Regex, plus
// canned standard filters in RynthChatPresets): move matching lines to a
// custom tab, or hide them
// • Per-channel accent colors + timestamps
// • Auto-scroll to tail
// • Search/filter TextBox (wired; typing requires mouse hover — Phase 4 fix)
@ -126,11 +128,25 @@ internal static class RynthChatPanel
_onFiltersChanged?.Invoke();
}
/// <summary>How a custom rule's pattern is interpreted.</summary>
internal enum FilterMatchMode
{
/// <summary>Regex against the formatted line ("ts sender: text") — the original behaviour.</summary>
Regex,
/// <summary>Plain text anywhere in the message.</summary>
Contains,
/// <summary>Plain text at the start of the message.</summary>
StartsWith,
/// <summary>Plain text at the end of the message.</summary>
EndsWith,
}
internal sealed class ChatFilterRule
{
internal bool Enabled = true;
internal string Pattern = "";
internal string Tab = ""; // "" = hide matching lines
internal FilterMatchMode Mode = FilterMatchMode.Regex;
internal Regex? Compiled;
internal bool Invalid;
@ -139,33 +155,72 @@ internal static class RynthChatPanel
Compiled = null;
Invalid = false;
if (Pattern.Length == 0) { Invalid = true; return; }
// Plain-text modes match the raw message, so the timestamp prefix can't break StartsWith.
string expr = Mode switch
{
FilterMatchMode.Contains => Regex.Escape(Pattern),
FilterMatchMode.StartsWith => "^" + Regex.Escape(Pattern),
FilterMatchMode.EndsWith => Regex.Escape(Pattern.TrimEnd()) + @"\s*$",
_ => Pattern,
};
try
{
Compiled = new Regex(Pattern,
Compiled = new Regex(expr,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(50));
}
catch { Invalid = true; }
}
/// <summary>Tests the rule against a line; <paramref name="formatted"/> is used only by Regex mode.</summary>
internal bool Matches(string formatted, string rawText)
{
if (!Enabled || Compiled == null) return false;
try { return Compiled.IsMatch(Mode == FilterMatchMode.Regex ? formatted : rawText); }
catch (RegexMatchTimeoutException) { return false; }
}
}
/// <summary>Resolve where a line should display after filter rules.
/// Returns null when a hide-rule matched; otherwise the effective tab
/// (a custom tab name, or the line's classified channel).</summary>
/// Custom rules are checked first (in order, first match wins), then the
/// standard presets. Returns null when a hide-rule matched; otherwise the
/// effective tab (a custom tab name, or the line's classified channel).</summary>
private static string? EffectiveTab(ChatDisplayLine line)
{
foreach (var rule in _filters)
{
if (!rule.Enabled || rule.Compiled == null) continue;
bool hit;
try { hit = rule.Compiled.IsMatch(line.FormattedText); }
catch (RegexMatchTimeoutException) { continue; }
if (!hit) continue;
if (!rule.Matches(line.FormattedText, line.Text)) continue;
return rule.Tab.Length == 0 ? null : rule.Tab;
}
var preset = RynthChatPresets.FirstMatch(line.Text, line.Channel);
if (preset != null) return preset.Tab.Length == 0 ? null : preset.Tab;
return line.Channel;
}
/// <summary>
/// Filters-panel tester: which custom rule (index) or preset would claim a message typed by the
/// user, treating it as arriving on <paramref name="channel"/>. Returns a human-readable result.
/// </summary>
internal static string DescribeTestLine(string text, string channel)
{
if (string.IsNullOrWhiteSpace(text)) return "Type or paste a chat line to see which filter catches it.";
string formatted = $"00:00:00 {text}";
for (int i = 0; i < _filters.Count; i++)
{
var rule = _filters[i];
if (!rule.Matches(formatted, text)) continue;
return $"Custom rule #{i + 1} → {(rule.Tab.Length == 0 ? "hidden" : $"moved to '{rule.Tab}'")}";
}
var preset = RynthChatPresets.FirstMatch(text, channel);
if (preset != null)
return $"Standard filter '{preset.Label}' → {(preset.Tab.Length == 0 ? "hidden" : $"moved to '{preset.Tab}'")}";
// Not caught by an enabled filter — say which disabled preset would, to help users find the right box.
foreach (var p in RynthChatPresets.All)
if (!p.Enabled && p.Matches(text, channel))
return $"Not filtered. Tick '{p.Group} › {p.Label}' to catch it.";
return "Not filtered — no rule or standard filter matches.";
}
/// <summary>Custom tabs = explicitly created tabs plus any tab named by an
/// ENABLED rule (typing a tab name in a rule creates the tab implicitly).
/// Deleting a tab removes it from the explicit list AND disables rules
@ -179,6 +234,9 @@ internal static class RynthChatPanel
foreach (var rule in _filters)
if (rule.Enabled && rule.Tab.Length > 0 && seen.Add(rule.Tab))
yield return rule.Tab;
foreach (var t in RynthChatPresets.TargetTabs())
if (seen.Add(t))
yield return t;
}
internal static bool IsBaseTab(string tab) =>
@ -190,6 +248,9 @@ internal static class RynthChatPanel
foreach (var rule in _filters)
if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase))
rule.Enabled = false;
foreach (var p in RynthChatPresets.All)
if (string.Equals(p.Tab, tab, StringComparison.OrdinalIgnoreCase))
p.Enabled = false;
NotifyFiltersChanged();
}
@ -1403,12 +1464,24 @@ internal static class RynthChatPanel
Enabled = f.Enabled,
Pattern = f.Pattern ?? "",
Tab = (f.Tab ?? "").Trim(),
Mode = Enum.TryParse(f.Mode, true, out FilterMatchMode m) ? m : FilterMatchMode.Regex,
};
rule.Recompile();
_filters.Add(rule);
}
}
if (dto.Presets != null)
{
foreach (var ps in dto.Presets)
{
var p = ps.Id != null ? RynthChatPresets.Get(ps.Id) : null;
if (p == null) continue;
p.Enabled = ps.Enabled;
p.Tab = (ps.Tab ?? "").Trim();
}
}
if (!string.IsNullOrEmpty(dto.ActiveChannel) &&
(Tabs.Contains(dto.ActiveChannel) ||
CustomTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)))
@ -1438,7 +1511,13 @@ internal static class RynthChatPanel
Enabled = f.Enabled,
Pattern = f.Pattern,
Tab = f.Tab,
Mode = f.Mode.ToString(),
}).ToArray(),
// Only presets the user touched are written; the rest stay at their defaults (off, hide).
Presets = RynthChatPresets.All
.Where(p => p.Enabled || p.Tab.Length > 0)
.Select(p => new RynthChatPresetDto { Id = p.Id, Enabled = p.Enabled, Tab = p.Tab })
.ToArray(),
};
File.WriteAllText(path, JsonSerializer.Serialize(dto,
RynthChatJsonContext.Default.RynthChatSettingsDto));
@ -1505,6 +1584,16 @@ internal sealed class RynthChatFilterDto
[JsonPropertyName("pattern")] public string? Pattern { get; set; }
[JsonPropertyName("tab")] public string? Tab { get; set; }
[JsonPropertyName("enabled")] public bool Enabled { get; set; } = true;
/// <summary>FilterMatchMode name; missing (older settings) = Regex.</summary>
[JsonPropertyName("mode")] public string? Mode { get; set; }
}
/// <summary>Persisted state of one standard (canned) filter.</summary>
internal sealed class RynthChatPresetDto
{
[JsonPropertyName("id")] public string? Id { get; set; }
[JsonPropertyName("enabled")] public bool Enabled { get; set; }
[JsonPropertyName("tab")] public string? Tab { get; set; }
}
internal sealed class RynthChatSettingsDto
@ -1522,6 +1611,7 @@ internal sealed class RynthChatSettingsDto
[JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; }
[JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; }
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
[JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; }
}
[JsonSerializable(typeof(RynthChatLineDto[]))]

View file

@ -0,0 +1,248 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthChatPresets.cs
// Canned ("standard") RynthChat filters, modelled on UtilityBelt-IT's
// ChatFilter / Mag ChatFilter categories. Each preset is a tick-box in the
// ChatFilters panel that hides its lines or moves them to a tab.
//
// Presets match the raw line text (no timestamp / sender prefix). Most are
// limited to non-chat channels so a player typing the same words in Local or
// a channel is never eaten. Avalonia UI thread only, like the rest of the
// RynthChat filter state.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthChatPresets
{
/// <summary>Which RynthChat channels a preset may match.</summary>
internal enum Scope
{
/// <summary>Anything except Chat / Channels (player-typed text).</summary>
NotPlayerChat,
/// <summary>Only the Combat channel (spell incantations arrive as chat type 0x11 → Combat).</summary>
CombatOnly,
/// <summary>Only the Channels tab (General / Trade / LFG / Roleplay / Society).</summary>
ChannelsOnly,
/// <summary>Every channel.</summary>
Any,
}
internal sealed class Preset
{
internal string Id { get; }
internal string Group { get; }
internal string Label { get; }
internal string Description { get; }
internal string Example { get; }
internal Scope Where { get; }
internal Regex Pattern { get; }
// User state (persisted via RynthChatPanel settings).
internal bool Enabled;
internal string Tab = ""; // "" = hide matching lines
internal Preset(string id, string group, string label, string description, string example, Scope where, string pattern)
{
Id = id;
Group = group;
Label = label;
Description = description;
Example = example;
Where = where;
Pattern = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50));
}
/// <summary>True when this preset applies to a line on <paramref name="channel"/> with raw <paramref name="text"/>.</summary>
internal bool Matches(string text, string channel)
{
bool inScope = Where switch
{
Scope.NotPlayerChat => channel is not ("Chat" or "Channels"),
Scope.CombatOnly => channel == "Combat",
Scope.ChannelsOnly => channel == "Channels",
_ => true,
};
if (!inScope) return false;
try { return Pattern.IsMatch(text); }
catch (RegexMatchTimeoutException) { return false; }
}
}
// Kill flavour text (retail/ACE death messages). Damage lines ("... for N points of ...")
// share some verbs, so they are excluded up front.
private const string KillPattern =
@"^(?!.* for \d+ points? of )(?:" +
@"You (?:flatten|knock|split|cleave|slay|bring|beat|run|suffocate|smite|killed) .+!" +
@"|.+ is (?:reduced to cinders|torn to ribbons by your assault|shattered by your assault|incinerated by your assault|liquified by your attack|dessicated by your attack)!" +
@"|.+ catches your attack, with dire consequences!" +
@"|.+'s (?:seared corpse smolders before you|last strength dissolves before you)!" +
@"|Electricity tears .+ apart!|Blistered by lightning, .+ falls!" +
@"|Your killing blow nearly turns .+ inside-out!|The thunder of crushing .+ is followed by the deafening silence of death!" +
@"|Your attack stops .+ cold!)";
// Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ".
private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*";
private static readonly Preset[] _all =
{
// ── Combat ────────────────────────────────────────────────────────
new("combat.attack_evades", "Combat", "Your attacks evaded",
"A monster evades your melee or missile attack.",
"Drudge Slinker evaded your attack.", Scope.NotPlayerChat, @" evaded your attack\.\s*$"),
new("combat.defense_evades", "Combat", "You evade attacks",
"You evade a monster's attack.",
"You evaded Drudge Slinker!", Scope.NotPlayerChat, @"^You evaded "),
new("combat.damage_dealt", "Combat", "Damage you deal",
"Your melee, missile and war-spell hits (including critical / sneak attack prefixes).",
"You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"You .+ for \d+ points? of "),
new("combat.damage_taken", "Combat", "Damage you take",
"Monster hits and spell damage landing on you.",
"Drudge Slinker slashes you for 12 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"(?!You ).+ you (?:with .+ )?for \d+ points? of "),
new("combat.attack_resists", "Combat", "Your spells resisted",
"A target resists one of your spells.",
"Drudge Slinker resists your spell", Scope.NotPlayerChat, @" resists your spell"),
new("combat.defense_resists", "Combat", "You resist spells",
"You resist a spell, or a caster was out of range / had no valid target.",
"You resist the spell cast by Drudge Sorcerer", Scope.NotPlayerChat,
@"^You resist the spell cast by |^You have no appropriate target.*spell|^You are an invalid target for the spell|tried to cast a spell on you, but was too far away!"),
new("combat.npk", "Combat", "Not-a-PK failures",
"\"You fail to affect X, you are not a player killer!\" and the mirror message.",
"You fail to affect Bob because you are not a player killer!", Scope.NotPlayerChat,
@"^You fail to affect .+ you are not a player killer!|fails to affect you.+ is not a player killer!"),
new("combat.dirty_fighting", "Combat", "Dirty Fighting procs",
"Dirty Fighting assault announcements.",
"Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!", Scope.NotPlayerChat, @"^Dirty Fighting! .+ delivers a "),
new("combat.monster_deaths", "Combat", "Monster death messages",
"Kill flavour text (\"You flatten…\", \"…is reduced to cinders!\").",
"Drudge Slinker is reduced to cinders!", Scope.NotPlayerChat, KillPattern),
// ── Casting ───────────────────────────────────────────────────────
new("cast.mine", "Casting", "Your spell words",
"Your own incantations (\"You say, \\\"Zojak…\\\"\"). Real Local chat is untouched.",
"You say, \"Zojak Equin\"", Scope.CombatOnly, @"^You say, """),
new("cast.others", "Casting", "Others' spell words",
"Incantations from other players and monsters.",
"Bob says, \"Cruath Quareth\"", Scope.CombatOnly, @"^(?!You say).+ says, """),
new("cast.fizzle", "Casting", "Spell fizzles",
"\"Your spell fizzled.\"",
"Your spell fizzled.", Scope.NotPlayerChat, @"^Your spell fizzled\."),
new("cast.components", "Casting", "Component usage",
"\"The spell consumed the following components: …\"",
"The spell consumed the following components: Lead Scarab", Scope.NotPlayerChat, @"^The spell consumed the following components"),
new("cast.self_buffs", "Casting", "Your buff casts",
"\"You cast X on yourself…\" confirmations.",
"You cast Strength Self VII on yourself", Scope.NotPlayerChat, @"^You cast .+ on yourself"),
new("cast.buffs_on_you", "Casting", "Buffs others cast on you",
"\"Bob cast X on you…\" lines from buff bots and fellows.",
"Bob cast Strength Other VII on you", Scope.NotPlayerChat, @"^(?!You ).+ cast .+ on you\b"),
new("cast.expires", "Casting", "Spell expiry",
"\"… has expired.\" — rares (Brilliance / Prodigal / Spectral) are kept.",
"Strength Self VII has expired.", Scope.NotPlayerChat, @"^(?!.*(?:Brilliance|Prodigal|Spectral)).*\b(?:has|have) expired\."),
// ── Items & utility ───────────────────────────────────────────────
new("item.heal_ok", "Items", "Healing kit success",
"\"You heal yourself for N Health points…\"",
"You heal yourself for 80 Health points.", Scope.NotPlayerChat, @"^You .*heal yourself for "),
new("item.heal_fail", "Items", "Healing kit failure",
"\"You fail to heal yourself.\"",
"You fail to heal yourself. ", Scope.NotPlayerChat, @"^You fail to heal yourself\."),
new("item.salvage", "Items", "Salvage results",
"\"You obtain … using your knowledge of …\"",
"You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", Scope.NotPlayerChat, @"^You obtain .+ using your knowledge of "),
new("item.salvage_fail", "Items", "Salvage failures",
"\"Salvaging Failed!\" and unsuitable-item notices.",
"Salvaging Failed!", Scope.NotPlayerChat, @"^Salvaging Failed!|The following were not suitable for salvaging: "),
new("item.craftsman", "Items", "Aura of the Craftsman",
"The +5 skill augmentation notice on every craft.",
"Your Aura of the Craftman augmentation increased your skill by 5!", Scope.NotPlayerChat, @"^Your Aura of the Craftman augmentation increased your skill"),
new("item.mana_stone", "Items", "Mana stone usage",
"Mana stone give / drain / destroyed lines.",
"The Mana Stone gives 4,500 points of mana to the following items:", Scope.NotPlayerChat,
@"^The Mana Stone (?:gives|drains) |^You need .+ more mana to fully charge your items\.\s*$|^The .+ is destroyed\.\s*$"),
new("item.regen", "Items", "Periodic healing ticks",
"\"You receive N points of periodic healing.\"",
"You receive 12 points of periodic healing.", Scope.NotPlayerChat, @"^You receive .+ points of periodic healing"),
// ── Social & trade ────────────────────────────────────────────────
new("social.bot_spam", "Social", "Trade / buff bot spam",
"Lines ending in the bot tags -t- or -b-.",
"BuffBot says, \"Buffs at the Holtburg lifestone -b-\"", Scope.Any, @"-[tb]-""?\s*$"),
new("social.failed_assess", "Social", "Failed assess on you",
"\"Someone tried and failed to assess you!\"",
"Bob tried and failed to assess you!", Scope.NotPlayerChat, @"tried and failed to assess you!\s*$"),
new("social.kill_task", "Social", "Kill task complete",
"\"You have killed N Xs! Your task is complete!\"",
"You have killed 50 Drudges! Your task is complete!", Scope.NotPlayerChat, @"^You have killed \d+ .+Your task is complete!\s*$"),
new("social.general", "Social", "General channel",
"Everything said on General.",
"[General] Bob says, \"hi\"", Scope.ChannelsOnly, @"^\[General\]|says on the General channel"),
new("social.trade", "Social", "Trade channel",
"Everything said on Trade.",
"[Trade] Bob says, \"WTS\"", Scope.ChannelsOnly, @"^\[Trade\]|says on the Trade channel"),
new("social.lfg", "Social", "LFG channel",
"Everything said on LFG.",
"[LFG] Bob says, \"LF fellow\"", Scope.ChannelsOnly, @"^\[LFG\]|says on the LFG channel"),
new("social.roleplay", "Social", "Roleplay channel",
"Everything said on Roleplay.",
"[Roleplay] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[Roleplay\]|says on the Roleplay channel"),
new("social.society", "Social", "Society channel",
"Everything said on your society channel.",
"[Society] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[(?:Society|Celestial Hand|Eldrytch Web|Radiant Blood)\]|says on the (?:Society|Celestial Hand|Eldrytch Web|Radiant Blood) channel"),
// ── NPCs ──────────────────────────────────────────────────────────
new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)",
"All Master Arbitrator speech and the fellowship-lock notice.",
"Master Arbitrator tells you, \"You shall be known…\"", Scope.Any,
@"^Master Arbitrator (?:says|tells you)|^Your fellowship is now locked\..*you have 15 minutes to be recruited"),
// ── Pets (ACE custom combat pets) ─────────────────────────────────
new("pet.hit", "Pets", "Pet hits",
"\"[Pet] … hit …\" outgoing damage.",
"[Pet] Fire Banshee hit Drudge for 40 damage.", Scope.NotPlayerChat, @"^\[Pet\] .+ hit "),
new("pet.evade", "Pets", "Pet attacks evaded",
"\"[Pet] … evaded by …\"",
"[Pet] Fire Banshee's attack was evaded by Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ evaded by "),
new("pet.damage_taken", "Pets", "Pet damage taken",
"\"[Pet] … took …\" incoming damage.",
"[Pet] Fire Banshee took 25 damage from Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ took "),
new("pet.death", "Pets", "Pet died",
"\"[Pet] Your combat pet … has died.\"",
"[Pet] Your combat pet Fire Banshee has died.", Scope.NotPlayerChat, @"^\[Pet\] Your combat pet .+ has died\.\s*$"),
new("pet.recall_block", "Pets", "Pet recall blocked",
"\"Your pet was in combat recently; you cannot recall it…\"",
"Your pet was in combat recently; you cannot recall it for about 10 seconds.", Scope.NotPlayerChat,
@"^Your pet was in combat recently; you cannot recall it"),
new("pet.overflow", "Pets", "Pet heal overflow",
"\"… receives N excess … from …\" boost overflow.",
"Fire Banshee receives 20 excess health from Heal Other.", Scope.NotPlayerChat, @" receives .+ excess .+ from "),
};
private static readonly Dictionary<string, Preset> _byId =
_all.ToDictionary(p => p.Id, StringComparer.OrdinalIgnoreCase);
/// <summary>Every preset in display order.</summary>
internal static IReadOnlyList<Preset> All => _all;
/// <summary>Group names in display order.</summary>
internal static IEnumerable<string> Groups => _all.Select(p => p.Group).Distinct();
internal static Preset? Get(string id) => _byId.TryGetValue(id, out var p) ? p : null;
/// <summary>First enabled preset that matches the line, or null.</summary>
internal static Preset? FirstMatch(string text, string channel)
{
foreach (var p in _all)
if (p.Enabled && p.Matches(text, channel))
return p;
return null;
}
/// <summary>Tabs named by enabled presets (tab names create tabs implicitly, like custom rules).</summary>
internal static IEnumerable<string> TargetTabs()
=> _all.Where(p => p.Enabled && p.Tab.Length > 0).Select(p => p.Tab);
}