diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 2f57e12..414d5ab 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -1130,12 +1130,16 @@ internal static class AcMainThreadQueue // Dispatch() itself (rather than at each caller) covers all three at once. // A full command line can't ride the uint Entry ring, so it gets its own // string queue, same shape as the WriteToChat slot above. - private static readonly System.Collections.Generic.Queue<(string Text, long At, int Epoch)> _chatCommandQueue = new(); + private static readonly System.Collections.Generic.Queue<(string Text, long At, int Epoch, ChatCommandOrigin Origin)> _chatCommandQueue = new(); private static readonly object _chatCommandLock = new(); private const int MaxChatCommandQueue = 64; // Off-thread enqueue. Drops (returns false) if the queue is full. - public static bool EnqueueChatCommand(string text) + public static bool EnqueueChatCommand(string text) => EnqueueChatCommand(text, ChatCommandOrigin.Script); + + // The same, saying who sent the line (Player: a RynthCore hotkey), for the answer of an engine + // /rc command (ChatCommandDispatcher.Dispatch, RynthCoreChatCommands). + public static bool EnqueueChatCommand(string text, ChatCommandOrigin origin) { lock (_chatCommandLock) { @@ -1144,7 +1148,7 @@ internal static class AcMainThreadQueue Interlocked.Increment(ref _dropped); return false; } - _chatCommandQueue.Enqueue((text, NowMs, Volatile.Read(ref _loginEpoch))); + _chatCommandQueue.Enqueue((text, NowMs, Volatile.Read(ref _loginEpoch), origin)); return true; } } @@ -1162,7 +1166,7 @@ internal static class AcMainThreadQueue int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { - (string Text, long At, int Epoch) item; + (string Text, long At, int Epoch, ChatCommandOrigin Origin) item; lock (_chatCommandLock) { if (_chatCommandQueue.Count == 0) return; @@ -1173,7 +1177,7 @@ internal static class AcMainThreadQueue NoteStale("a chat command", now - item.At, dropped: true); continue; } - try { ChatCommandDispatcher.Dispatch(item.Text); } + try { ChatCommandDispatcher.Dispatch(item.Text, item.Origin); } catch { } } } diff --git a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index 8745129..accbc9e 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -563,12 +563,18 @@ internal static class ChatCallbackHooks // RynthCore engine commands (/rc ...) — consume before plugins or // AC see the line so the user never broadcasts "/rc resetbar" and - // a hidden overlay bar stays recoverable. - if (RynthCoreChatCommands.TryHandle(line)) + // a hidden overlay bar stays recoverable. Typed by the player: every + // reply goes to chat. + if (RynthCoreChatCommands.TryHandle(line, ChatCommandOrigin.Player)) return 1; - if (PluginManager.DispatchChatBarEnter(line)) - return 1; + // A /rc line a plugin runs while it handles this one (RynthAi's /ra videopatch) is the + // player's too, so it answers in chat. + using (RynthCoreChatCommands.PlayerLine()) + { + if (PluginManager.DispatchChatBarEnter(line)) + return 1; + } return _originalOutgoingChat!(thisPtr, text, commandSource); } diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs index db20ad4..7ca4197 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs @@ -108,7 +108,14 @@ internal static unsafe class ChatCommandDispatcher } } - public static bool Dispatch(string? text) + /// A line from a plugin, a command file or the login commands (). + public static bool Dispatch(string? text) => Dispatch(text, ChatCommandOrigin.Script); + + /// + /// Runs a chat line as if typed. says who sent it, for the answer of an + /// engine /rc command (RynthCoreChatCommands): Player for a RynthCore hotkey, Script for the rest. + /// + public static bool Dispatch(string? text, ChatCommandOrigin origin) { if (string.IsNullOrWhiteSpace(text)) return false; @@ -128,7 +135,7 @@ internal static unsafe class ChatCommandDispatcher // from the drain, where IsOnMainThread is satisfied and the body // below runs directly — so there's only one code path to keep in sync. if (!MainThreadGuard.IsOnMainThread()) - return AcMainThreadQueue.EnqueueChatCommand(text); + return AcMainThreadQueue.EnqueueChatCommand(text, origin); try { @@ -139,7 +146,7 @@ internal static unsafe class ChatCommandDispatcher // RynthCore engine commands (/rc ...) are handled before plugin // pre-dispatch and before any AC chat routing so they work even // when the overlay is hidden and no plugin can eat the line. - if (RynthCoreChatCommands.TryHandle(trimmed)) + if (RynthCoreChatCommands.TryHandle(trimmed, origin)) return true; // Expand shorthand: /s → /say, /t → /tell, /e → /emote @@ -161,7 +168,15 @@ internal static unsafe class ChatCommandDispatcher _inPluginPreDispatch = true; try { - if (PluginManager.DispatchChatBarEnter(trimmed)) + // The player's line (a hotkey's /ra command): a /rc line a plugin runs while it + // handles it is the player's too (RynthCoreChatCommands.PlayerLine). + if (origin == ChatCommandOrigin.Player) + { + using (RynthCoreChatCommands.PlayerLine()) + if (PluginManager.DispatchChatBarEnter(trimmed)) + return true; + } + else if (PluginManager.DispatchChatBarEnter(trimmed)) return true; } catch (Exception ex) diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs new file mode 100644 index 0000000..08be2c9 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -0,0 +1,376 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ChatCommandReplies.cs +// +// How the engine's chat commands (/rc ..., /rv plates) answer. Every command a +// player types gets a clear line back: what changed and the value now, or why +// not with the usage (2026-10-28: "It should tell you whether it worked for +// every single command a player punches in"). +// +// The pure part (no AC, no engine state), so tools\ChatCommandReplyTests can +// compile it in: who a line came from and whether a reply goes to chat or only +// to the log, the two reply colours, every verb with its usage, the argument +// check made before a command runs, and the reply texts built from plain +// values. Writing the reply (log + chat) is RynthCoreChatCommands.Reply. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Engine.Compatibility; + +/// Who an engine command line came from (). +internal enum ChatCommandOrigin +{ + /// + /// A plugin (Host.InvokeChatParser: a meta, a window's button), the command files (dispatch.txt, + /// RynthRemote's sendchat), the login commands, or one of the engine's own buttons and menus. + /// A reply that says it worked goes to the log only; one that says it didn't still goes to chat. + /// + Script = 0, + + /// + /// The player: typed in AC's chat bar or RynthChat's, a RynthCore hotkey, or a line a plugin passes + /// on while it handles one the player typed (/ra videopatch runs /rc videopatch). Every reply goes + /// to chat. + /// + Player = 1, +} + +/// What a reply says: it worked (or here is the state), or it didn't. +internal enum ChatReplyKind +{ + Ok = 0, + Fail = 1, +} + +/// +/// One engine verb: its name, other spellings, usage, and the argument check made before it runs +/// ( null: the command's own handler checks its arguments and answers with its usage). +/// +internal sealed record ChatVerb(string Name, string[] Aliases, string Usage, Func? Args); + +/// What the check before a command runs found: the verb (null: unknown), its arguments, and +/// the reply when the command can't run (null: run it). +internal readonly record struct ChatVerbCheck(ChatVerb? Verb, string Args, string? Problem); + +internal static class ChatCommandReplies +{ + /// Every engine reply starts with this (the style since the first /rc command). + public const string ReplyPrefix = "[RynthCore] "; + + /// ChatMessageType 0x01, green in AC's chat: it worked, or the state. + public const int OkChatType = 1; + + /// ChatMessageType 0x1A, red: the type AC prints its own command notices in + /// ("Someone must @tell you first!", ChatCommandDispatcher.ChatTypeNotice). + public const int FailChatType = 0x1A; + + // ── who sent it, where the reply goes ────────────────────────────────── + + /// The origin a line is handled with: the player's when the caller says so, or when it + /// arrives while a line the player typed is being handed on (RynthCoreChatCommands.PlayerLine). + public static ChatCommandOrigin Effective(ChatCommandOrigin given, bool insidePlayerLine) => + given == ChatCommandOrigin.Player || insidePlayerLine ? ChatCommandOrigin.Player : ChatCommandOrigin.Script; + + /// True when the reply goes to chat as well as the log: always for the player, and for + /// anyone else only when it says the command didn't work. + public static bool ToChat(ChatReplyKind kind, ChatCommandOrigin origin) => + kind == ChatReplyKind.Fail || origin == ChatCommandOrigin.Player; + + /// The AC chat type (colour) a reply is written with. + public static int ChatType(ChatReplyKind kind) => kind == ChatReplyKind.Fail ? FailChatType : OkChatType; + + /// + /// How the modules a command hands its arguments to (the video patch, flight recorder, report, + /// AutoId, server messages, Discord relay, action gates) start a line that says the command + /// didn't work. Their other lines are the state. + /// + private static readonly string[] FailOpenings = + { + "Usage", "Unknown", "Can't", "Not dumped", "Not capturing", "Capture failed", "Report not sent", + "Log in first", "No route", "No hotkey on", "Which key", "Unlock skipped", + "Video patch unavailable", "Video patch is switched off", "Flight recorder is off", + "The server message stream is off", "The relay is off", + }; + + /// Whether a line a module returned says the command didn't work. + public static ChatReplyKind KindOfLine(string line) + { + string s = line.TrimStart(); + foreach (string f in FailOpenings) + if (s.StartsWith(f, StringComparison.OrdinalIgnoreCase)) + return ChatReplyKind.Fail; + return s.Contains("isn't available", StringComparison.OrdinalIgnoreCase) ? ChatReplyKind.Fail : ChatReplyKind.Ok; + } + + /// A module's reply lines as one answer: failed when any line says so. + public static ChatReplyKind KindOfLines(IEnumerable lines) + { + foreach (string l in lines) + if (KindOfLine(l) == ChatReplyKind.Fail) + return ChatReplyKind.Fail; + return ChatReplyKind.Ok; + } + + // ── the verbs ────────────────────────────────────────────────────────── + + public const string PlatesUsage = + "Usage: /rv plates [on|off] | all on|off | self [numbers|name|firstperson|lock|debuffs] [on|off] | " + + "self fixed|follow|unlock|reset | self debuffs size <50-200%> | " + + "debuffs [on|off] | debuffs size <50-200%> | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " + + "gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist |max | players [on|off] | portals [on|off] | portals dist | " + + "all|engaged |dist |max |scale |opacity |lift | " + + "names|hp|level|weak|distance|fade|click [on|off] | reset | status | test"; + + public const string ServerUsage = + "Usage: /rc server [ auto|on|off] | pick |auto | [aelrynth|other|auto] | names ilt [add|remove ]"; + + public const string HotkeyUsage = + "Usage: /rc hotkey list | add | remove | enable|disable | actions | status | on|off"; + + /// The Classic dashboard look's tabs, in order (RynthAiDashboardState.SetClassicTab's index). + public static readonly string[] ClassicTabNames = { "main", "monsters", "gear", "buffs", "route", "loot", "meta", "tuning" }; + + private static ChatVerb V(string name, string usage, Func? args, params string[] aliases) => + new(name, aliases, usage, args); + + private static bool NoArgs(string a) => a.Length == 0; + + private static Func Words(params string[] allowed) => + a => Array.Exists(allowed, w => w.Equals(a, StringComparison.OrdinalIgnoreCase)); + + private static bool PanelArgs(string a) => TryPanelMode(a, out _); + + /// + /// Every /rc verb RynthCoreChatCommands answers. Keep it in step with TryHandle: a verb missing + /// here is answered as unknown before its handler runs (tools\ChatCommandReplyTests reads TryHandle + /// and checks both ways). + /// + public static readonly ChatVerb[] Verbs = + { + V("vendor", "Usage: /rc vendor list | info | status | buy [n] | sell [id ...]", null), + V("imgui", "Usage: /rc imgui on|off|fonttest|diag", Words("", "on", "off", "fonttest", "diag")), + V("ui", "Usage: /rc ui list | open|close|popout|redock|snap | channels | retailvitals [on|off] | retailtoolbar [on|off] | barsize [0-10|+|-|status] | barrows [1-6|+|-] | baricons [2-30|none|+|-]", null), + V("chathold", "Usage: /rc chathold [on|off|status]", Words("", "on", "off", "status")), + V("discord", "Usage: /rc discord [on|off|status|window|test [route]|resume [route]]", null), + V("plates", PlatesUsage, null, "nameplates"), + V("server", ServerUsage, null), + V("ilt", "Usage: /rc ilt [auto|on|off]", Words("", "on", "ilt", "off", "other", "auto")), + V("mastery", "Usage: /rc mastery (the Aelrynth mastery feed's state; asks the server again)", null), + V("worldlayer", "Usage: /rc worldlayer [auto|uipass|transition|endscene|status]", + Words("", "status", "auto", "uipass", "ui", "transition", "zenable", "endscene")), + V("acmouse", "Usage: /rc acmouse [watch [seconds]]", a => a.Length == 0 || IsVerb(a, "watch", out _), "mouseover"), + V("video", "Usage: /rc video [status|enable|disable|off|world|unfocused|all|fps ]", null, "videopatch"), + V("hooks", "Usage: /rc hooks [status] | /rc hooks on|off ", null, "uihooks"), + V("flightdump", "Usage: /rc flightdump [note] | /rc flightdump auto ", null), + V("quit", "Usage: /rc quit (closes the client, as its close button)", null, "exit"), + V("report", "Usage: /rc report [what went wrong] (alone: opens the Report a problem panel)", null), + V("flight", "Usage: /rc flight [status|mark |on|off|auto on|off]", null), + V("autoid", "Usage: /rc autoid [all|limited|off] (alone: status)", null), + V("netmsg", "Usage: /rc netmsg [status|on|off|log on|off|capture on|off]", null), + V("vtank", "Usage: /rc vtank [clear]", Words("", "clear")), + V("bounties", "Usage: /rc bounties [show|hide|toggle]", PanelArgs, "bounty", "bountys"), + V("guardian", "Usage: /rc guardian [show|hide|toggle]", PanelArgs, "guardians"), + V("dashboard", "Usage: /rc dashboard classic|modern|tab <" + string.Join("|", ClassicTabNames) + ">", DashboardArgs), + V("miniremote", "Usage: /rc miniremote [show|hide|toggle|tab |section ]", + a => TryPanelMode(a, out _) || IsVerb(a, "tab", out _) || IsVerb(a, "section", out _), "remote"), + V("oracle-skills", "Usage: /rc oracle-skills ", a => OracleSkillsTab(a) != InvalidTab), + V("skills", "Usage: /rc skills [show|hide|toggle]", PanelArgs), + V("progression", "Usage: /rc progression (opens the Progress tab)", NoArgs, "progress"), + V("spells", "Usage: /rc spells [show|hide|toggle]", PanelArgs), + V("hotkeys", "Usage: /rc hotkeys (opens Settings > Hotkeys) | /rc hotkeys (as /rc hotkey)", null), + V("diagnostics", "Usage: /rc diagnostics (opens Settings > Diagnostics, the server picker)", NoArgs, "serverpick"), + V("settings", "Usage: /rc settings [tab]", null), + V("shortcuts", "Usage: /rc shortcuts [use <1-18> | set <1-18> [id] | clear <1-18>]", ShortcutsArgs), + V("keymap", "Usage: /rc keymap check|bind|unbind | dump, e.g. /rc keymap bind UseQuickSlot_10 F11", KeymapArgs), + V("panels", "Usage: /rc panels [open|close|toggle ]", PanelsArgs), + 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"), + V("sense", "Usage: /rc sense (opens or closes the Sense panel)", NoArgs), + V("characters", "Usage: /rc characters (opens or closes RynthNet's Characters window)", NoArgs, "chars"), + V("itemcount", "Usage: /rc itemcount (opens or closes the Item Count panel)", NoArgs, "itemhud"), + V("resetbar", "Usage: /rc resetbar (moves the RynthCore bar back to the top-left corner)", NoArgs, "barreset"), + V("actionstate", "Usage: /rc actionstate (the client's item-action gates)", NoArgs, "actions"), + V("unlockactions", "Usage: /rc unlockactions (opens the client's item-action gates now)", NoArgs, "unlock"), + V("vitals", "Usage: /rc vitals (the old vitals HUD is gone: /rv plates self)", NoArgs, "hud"), + }; + + /// The verb names (its name or another spelling), or null. + public static ChatVerb? Find(string word) + { + foreach (ChatVerb v in Verbs) + { + if (v.Name.Equals(word, StringComparison.OrdinalIgnoreCase)) return v; + foreach (string a in v.Aliases) + if (a.Equals(word, StringComparison.OrdinalIgnoreCase)) return v; + } + return null; + } + + /// The usage of the verb called . + public static string Usage(string name) => Find(name)?.Usage ?? "Usage: /rc " + name; + + /// The check made before a /rc command runs: is the line after "/rc ". + public static ChatVerbCheck Check(string sub) + { + string s = sub.Trim(); + int sp = s.IndexOf(' '); + string word = sp < 0 ? s : s.Substring(0, sp); + string args = sp < 0 ? string.Empty : s.Substring(sp + 1).Trim(); + if (word.Length == 0) + return new ChatVerbCheck(null, string.Empty, "Usage: /rc . " + CommandList()); + ChatVerb? v = Find(word); + if (v == null) + return new ChatVerbCheck(null, args, UnknownReply(word)); + if (v.Args != null && !v.Args(args)) + return new ChatVerbCheck(v, args, v.Usage); + return new ChatVerbCheck(v, args, null); + } + + /// "RynthCore's commands: /rc acmouse, actionstate, ...": every verb by its name. + public static string CommandList() + { + var names = new List(Verbs.Length); + foreach (ChatVerb v in Verbs) names.Add(v.Name); + names.Sort(StringComparer.Ordinal); + return "RynthCore's commands: /rc " + string.Join(", ", names) + "."; + } + + /// The answer to a /rc verb the engine doesn't have. + public static string UnknownReply(string word) => $"Unknown command '/rc {word}'. {CommandList()}"; + + /// "/rc vendor" for "/rc vendor buy 1": the command's name in a reply. + public static string CommandName(string trimmedLine) + { + string s = trimmedLine.Trim(); + int first = s.IndexOf(' '); + if (first < 0) return s; + int second = s.IndexOf(' ', first + 1); + return second < 0 ? s : s.Substring(0, second); + } + + // ── argument parsing (shared with RynthCoreChatCommands) ─────────────── + + /// "verb" or "verb args..." (case-insensitive); args trimmed. + public static bool IsVerb(string sub, string verb, out string args) + { + args = string.Empty; + if (sub.Equals(verb, StringComparison.OrdinalIgnoreCase)) return true; + if (!sub.StartsWith(verb + " ", StringComparison.OrdinalIgnoreCase)) return false; + args = sub.Substring(verb.Length + 1).Trim(); + return true; + } + + /// + /// "" / "toggle" → null (flip), "show" / "on" / "open" → true, "hide" / "off" / "close" → + /// false. False for anything else. + /// + public static bool TryPanelMode(string args, out bool? show) + { + show = null; + switch (args.Trim().ToLowerInvariant()) + { + case "": case "toggle": return true; + case "show": case "on": case "open": show = true; return true; + case "hide": case "off": case "close": show = false; return true; + default: return false; + } + } + + /// What "/rc oracle-skills" can't take. + public const int InvalidTab = -2; + + /// "/rc oracle-skills <x>": -1 off, 0 skills, 1 attributes, 2 progress, for anything else. + public static int OracleSkillsTab(string args) => args.Trim().ToLowerInvariant() switch + { + "off" or "clear" or "none" or "-1" => -1, + "0" or "skills" or "skill" => 0, + "1" or "attrs" or "attributes" or "vitals" => 1, + "2" or "progress" or "progression" => 2, + _ => InvalidTab, + }; + + /// The Classic look's tab index for , or -1. + public static int ClassicTab(string name) => + Array.FindIndex(ClassicTabNames, n => n.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)); + + private static bool DashboardArgs(string a) => + a.Length == 0 || a.Equals("classic", StringComparison.OrdinalIgnoreCase) || a.Equals("modern", StringComparison.OrdinalIgnoreCase) + || (IsVerb(a, "tab", out string tab) && ClassicTab(tab) >= 0); + + /// "use N", "set N [id]", "clear N" (more words are ignored, as before), or nothing (the list). + private static bool ShortcutsArgs(string a) + { + string[] sa = a.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (sa.Length == 0) return true; + return sa.Length >= 2 && int.TryParse(sa[1], out _) + && (sa[0].Equals("use", StringComparison.OrdinalIgnoreCase) || sa[0].Equals("set", StringComparison.OrdinalIgnoreCase) + || sa[0].Equals("clear", StringComparison.OrdinalIgnoreCase)); + } + + /// "check|bind|unbind <action> <key>", "dump", or nothing (the keymap's state). + private static bool KeymapArgs(string a) + { + string[] ka = a.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); + if (ka.Length == 0) return true; + string verb = ka[0].ToLowerInvariant(); + return verb == "dump" || (verb is "check" or "bind" or "unbind" && ka.Length == 3); + } + + /// "<op> <id>" (open, close, anything else toggles, as before), or nothing (the list). + private static bool PanelsArgs(string a) + { + string[] pa = a.Split(' ', StringSplitOptions.RemoveEmptyEntries); + return pa.Length == 0 || (pa.Length == 2 && TryPanelId(pa[1], out _)); + } + + /// An AC panel id: decimal, or hex with 0x. + public static bool TryPanelId(string text, out uint id) => + uint.TryParse(text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), + text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? NumberStyles.HexNumber : NumberStyles.Integer, + null, out id); + + // ── reply texts ──────────────────────────────────────────────────────── + + /// "Bounties panel opened." / "... closed." / "... is already open.": a panel after + /// show (true), hide (false) or toggle (null), from whether it was open before. + public static string PanelReply(string label, bool? show, bool wasOpen) + { + if (show is bool want && want == wasOpen) + return $"{label} is already {(want ? "open" : "closed")}."; + bool nowOpen = show ?? !wasOpen; + return $"{label} {(nowOpen ? "opened" : "closed")}."; + } + + /// "Settings opened on Hotkeys." / "Settings switched to Hotkeys." + public static string SettingsTabReply(string tab, bool wasOpen) => + $"Settings {(wasOpen ? "switched to" : "opened on")} {tab}."; + + /// The answer when a command threw. + public static string Failed(string command, string error, string message) => + $"{command} failed: {error}: {message} (the RynthCore log has more)."; + + /// The answer when a command ran and its handler said nothing (a gap: the log names it). + public static string Done(string command) => $"{command}: done."; + + /// "/rc oracle-skills": what RynthOracle's window embeds now. + public static string OracleSkillsReply(int tab) => tab switch + { + 0 => "RynthOracle's window shows the Skills tab.", + 1 => "RynthOracle's window shows the Attributes tab.", + 2 => "RynthOracle's window shows the Progress tab.", + _ => "RynthOracle's window shows none of the Skills tabs.", + }; + + /// "/rc dashboard ...": the look now (and the Classic tab), and whether the dashboard opened. + public static string DashboardReply(bool classic, string? tab, bool hasDashboard) + { + var sb = new StringBuilder("RynthAi dashboard: ").Append(classic ? "Classic" : "Modern").Append(" look"); + if (tab != null) sb.Append(", ").Append(tab.ToLowerInvariant()).Append(" tab"); + sb.Append(hasDashboard ? "." : " (RynthAi's dashboard isn't loaded, so nothing opened)."); + return sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/ChatRateLimiter.cs b/src/RynthCore.Engine/Compatibility/ChatRateLimiter.cs new file mode 100644 index 0000000..38df3a9 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ChatRateLimiter.cs @@ -0,0 +1,51 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ChatRateLimiter.cs +// +// How many plugin chat lines (WriteToChat off AC's thread) go to AC's chat, and +// when (2026-10-28). A token bucket: a burst of up to Burst lines at once, then +// one line per IntervalMs. It used to drop any line within 100 ms of the one +// before, so a command's help or list reached chat as its first line only +// ("/rn help", "/ilt help", "/rthreads stats"). The steady rate is unchanged +// (10 a second), which is what keeps a retry loop's spam ("Casting: X" dozens +// of times) away from AC's AddTextToScroll and its 0x00460D1D crash. +// +// Pure (no AC, no engine state), so tools\ChatCommandReplyTests compiles it in. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class ChatRateLimiter +{ + public const int DefaultBurst = 12; + public const int DefaultIntervalMs = 100; + + private readonly int _burst; + private readonly int _intervalMs; + private readonly object _lock = new(); + private double _tokens; + private long _at; + + public ChatRateLimiter(int burst = DefaultBurst, int intervalMs = DefaultIntervalMs) + { + _burst = Math.Max(1, burst); + _intervalMs = Math.Max(1, intervalMs); + _tokens = _burst; + } + + /// True when a line may go at (a monotonic clock, e.g. + /// Environment.TickCount64), and counts it; false when the burst is spent. + public bool TryTake(long nowMs) + { + lock (_lock) + { + if (_at != 0 && nowMs > _at) + _tokens = Math.Min(_burst, _tokens + (nowMs - _at) / (double)_intervalMs); + if (_at == 0 || nowMs > _at) _at = nowMs; + if (_tokens < 1) return false; + _tokens -= 1; + return true; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index 5d9e39c..b5733f7 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -1112,10 +1112,11 @@ internal static class ClientHelperHooks // also hook the same function in ChatCallbackHooks.IncomingChatAddTextDetour, // which fires when AC processes our own WriteToChat output — guard // against unbounded recursion into ourselves. - private const int WriteToChatMinIntervalMs = 100; + // A burst of up to 12 lines, then one per 100 ms (ChatRateLimiter, 2026-10-28; it was one line + // per 100 ms, which cut every multi-line command reply to its first line). + private static readonly ChatRateLimiter _chatLimiter = new(); [System.Runtime.CompilerServices.ModuleInitializer] internal static void EnsureChatRateLimiterReady() { /* triggers static init */ } - private static long _lastWriteToChatTick; [ThreadStatic] private static int _writeToChatDepth; public static bool WriteToChat(string? text, int chatType) @@ -1130,11 +1131,8 @@ internal static class ClientHelperHooks // dropped before they queue, and drained messages are never re-dropped. if (!MainThreadGuard.IsOnMainThread()) { - long now = Environment.TickCount64; - long last = System.Threading.Interlocked.Read(ref _lastWriteToChatTick); - if (last != 0 && now - last < WriteToChatMinIntervalMs) + if (!_chatLimiter.TryTake(Environment.TickCount64)) return false; - System.Threading.Interlocked.Exchange(ref _lastWriteToChatTick, now); return AcMainThreadQueue.EnqueueWriteToChat(text!, chatType); } diff --git a/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs b/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs index a2ddd4d..8c5dcb6 100644 --- a/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs +++ b/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs @@ -405,9 +405,12 @@ internal static unsafe class DecalBridgeHost // VTank, UB and MagTools already ran them). if (arg0 == 0) break; - if (RynthCoreChatCommands.TryHandle(text)) + // Decal hands the bridge typed lines and its plugins' InvokeChatParser lines (a VTank + // meta's chat command) alike, so these count as the player's: every reply shows. + if (RynthCoreChatCommands.TryHandle(text, ChatCommandOrigin.Player)) break; - PluginManager.DispatchChatBarEnter(text); + using (RynthCoreChatCommands.PlayerLine()) + PluginManager.DispatchChatBarEnter(text); break; } diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index a76c6f8..c45d55b 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -11,6 +11,12 @@ namespace RynthCore.Engine.Compatibility; /// dispatch.txt / OnLoginCommandRunner / Host.InvokeChatParser — /// /// +/// Every command answers (2026-10-28): what changed and the value now, or why not with the +/// usage; an unknown verb or arguments a verb can't take get the usage before anything runs +/// (). Typed by the player (AC's chat bar, RynthChat's box, +/// a hotkey, or a plugin passing on a typed line) every reply goes to chat; sent by a plugin, a +/// command file, the login commands or an engine button, a success goes to the log only and a +/// failure still to chat (). All replies go through Reply / Fail. /// Commands: /// /// /rc resetbar — recover the RynthCore overlay bar when it has @@ -106,229 +112,259 @@ internal static class RynthCoreChatCommands /// The Settings tab with the server picker (UI/Data/SettingsData.cs "Diagnostics"). private const string DiagnosticsTabName = "Diagnostics"; + // The line being handled on this thread: who sent it, and whether it has answered yet. + [ThreadStatic] private static ChatCommandOrigin _origin; + [ThreadStatic] private static bool _answered; + + // Above 0 while a line the player typed is handed on (to the plugins, or by RynthChat's box). + [ThreadStatic] private static int _playerLineDepth; + + /// + /// Until disposed, every line handled on this thread is the player's: a /rc command a plugin runs + /// while it handles a line the player typed answers in chat (RynthAi's /ra videopatch runs + /// /rc videopatch through Host.InvokeChatParser, on the same thread, before returning). + /// using (RynthCoreChatCommands.PlayerLine()) PluginManager.DispatchChatBarEnter(line); + /// + internal static PlayerLineScope PlayerLine() + { + _playerLineDepth++; + return default; + } + + /// Ends a . + internal readonly struct PlayerLineScope : IDisposable + { + public void Dispose() + { + if (_playerLineDepth > 0) _playerLineDepth--; + } + } + /// /// True if was a RynthCore engine command and has /// been handled — the caller must consume it (do NOT forward to AC chat - /// or to plugins). + /// or to plugins). Every handled line answers (): + /// in chat for the Player; for a Script, a success goes + /// to the log only and a failure to chat. /// - public static bool TryHandle(string? line) + public static bool TryHandle(string? line, ChatCommandOrigin origin) { if (string.IsNullOrWhiteSpace(line)) return false; string trimmed = line.Trim(); + if (!IsEngineLine(trimmed)) + return false; + ChatCommandOrigin outerOrigin = _origin; + bool outerAnswered = _answered; + _origin = ChatCommandReplies.Effective(origin, _playerLineDepth > 0); + _answered = false; + try + { + try { Handle(trimmed); } + catch (Exception ex) { Failed(ChatCommandReplies.CommandName(trimmed), ex); } + if (!_answered) + { + // A handler that said nothing is a gap to fill (this log line names it), never silence. + RynthLog.Compat($"RynthCoreChatCommands: '{trimmed}' wrote no reply."); + Reply(ChatCommandReplies.Done(ChatCommandReplies.CommandName(trimmed))); + } + return true; + } + finally + { + _origin = outerOrigin; + _answered = outerAnswered; + } + } + + /// "/rc", "/rc ..." and "/rv plates|nameplates ..." are the engine's; every other "/rv" line + /// goes on to the RynthVision plugin. + private static bool IsEngineLine(string trimmed) + { + if (trimmed.Equals("/rc", StringComparison.OrdinalIgnoreCase) || trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase)) + return true; + if (!trimmed.StartsWith("/rv ", StringComparison.OrdinalIgnoreCase)) + return false; + string rv = trimmed.Substring(4).Trim(); + return IsVerb(rv, "plates", out _) || IsVerb(rv, "nameplates", out _); + } + + /// Runs one engine line (). An exception is answered by TryHandle. + private static void Handle(string trimmed) + { // /rv plates ... : the RynthVision overlays live engine-side, so the engine answers // before the plugin's "/rv" prefix handler would (it runs after this, on pre-dispatch). if (trimmed.StartsWith("/rv ", StringComparison.OrdinalIgnoreCase)) { string rv = trimmed.Substring(4).Trim(); - if (IsVerb(rv, "plates", out string rvArgs) || IsVerb(rv, "nameplates", out rvArgs)) - { - try { HandlePlatesCommand(rvArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rv plates failed - {ex.GetType().Name}: {ex.Message}"); } - return true; - } - return false; + if (!IsVerb(rv, "plates", out string rvArgs)) + IsVerb(rv, "nameplates", out rvArgs); + HandlePlatesCommand(rvArgs); + return; } - if (!trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase)) - return false; + string sub = trimmed.Length > 3 ? trimmed.Substring(3).Trim() : string.Empty; - string sub = trimmed.Substring(Prefix.Length).Trim(); - - // /rc vendor [list|info|status|buy [n]|sell [id ...]] - if (sub.Equals("vendor", StringComparison.OrdinalIgnoreCase) - || sub.StartsWith("vendor ", StringComparison.OrdinalIgnoreCase)) + // An unknown verb, or arguments the verb can't take, answers with the usage before anything + // runs ("/rc" alone lists the commands). Commands with their own handler check theirs there. + ChatVerbCheck check = ChatCommandReplies.Check(sub); + if (check.Problem != null) { - try { VendorTrade.HandleChatCommand(sub.Length > 6 ? sub.Substring(7) : string.Empty); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc vendor failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + Fail(check.Problem); + return; } - // /rc imgui [on|off|fonttest] - if (sub.Equals("imgui", StringComparison.OrdinalIgnoreCase) - || sub.StartsWith("imgui ", StringComparison.OrdinalIgnoreCase)) + // /rc vendor [list|info|status|buy [n]|sell [id ...]]: VendorTrade's own + // "[RC]" lines are the reply (to chat from the main-thread drain, and to the log). + if (IsVerb(sub, "vendor", out string vendorArgs)) { - try { HandleImGuiCommand(sub.Length > 5 ? sub.Substring(6).Trim() : string.Empty); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc imgui failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + VendorTrade.HandleChatCommand(vendorArgs); + AnswersItself(); + return; + } + + // /rc imgui [on|off|fonttest|diag] + if (IsVerb(sub, "imgui", out string imguiArgs)) + { + HandleImGuiCommand(imguiArgs); + return; } // /rc ui list | open|close|popout|redock|snap | bar settings (HandleUiCommand) - if (sub.Equals("ui", StringComparison.OrdinalIgnoreCase) - || sub.StartsWith("ui ", StringComparison.OrdinalIgnoreCase)) + if (IsVerb(sub, "ui", out string uiArgs)) { - try { HandleUiCommand(sub.Length > 2 ? sub.Substring(3).Trim() : string.Empty); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc ui failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleUiCommand(uiArgs); + return; } // /rc chathold [on|off|status]: lines a plugin eats stay out of AC's chat window too if (IsVerb(sub, "chathold", out string holdArgs)) { - try { HandleChatHoldCommand(holdArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc chathold failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleChatHoldCommand(holdArgs); + return; } // /rc discord [on|off|status|window|test [route]|resume [route]] : RynthChat's Discord relay if (IsVerb(sub, "discord", out string discordArgs)) { - try { HandleDiscordCommand(discordArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc discord failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleDiscordCommand(discordArgs); + return; } // /rc plates [on|off|all|engaged|dist N|max N|scale X|opacity X|lift X|names|hp|level|weak|distance|fade|reset|status] if (IsVerb(sub, "plates", out string platesArgs) || IsVerb(sub, "nameplates", out platesArgs)) { - try { HandlePlatesCommand(platesArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc plates failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandlePlatesCommand(platesArgs); + return; } // /rc server [ auto|on|off | names ilt ...] : the servers, why each is active, per-character overrides if (IsVerb(sub, "server", out string serverArgs)) { - try { HandleServerCommand(serverArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc server failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleServerCommand(serverArgs); + return; } // /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a per-character override if (IsVerb(sub, "ilt", out string iltArgs)) { - try { HandleIltCommand(iltArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc ilt failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleIltCommand(iltArgs); + return; } // /rc mastery : the Aelrynth mastery feed's state, and ask the server again if (IsVerb(sub, "mastery", out _)) { - try { HandleMasteryCommand(); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc mastery failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleMasteryCommand(); + return; } // /rc worldlayer [auto|uipass|transition|endscene] : where the world overlays draw if (IsVerb(sub, "worldlayer", out string worldArgs)) { - try { HandleWorldLayerCommand(worldArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc worldlayer failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleWorldLayerCommand(worldArgs); + return; } // /rc acmouse [watch [seconds]] : what AC's own UI has under the cursor (the 3D world or // one of its windows) - whether a nameplate there may take the click (AcMouseOver) if (IsVerb(sub, "acmouse", out string acMouseArgs) || IsVerb(sub, "mouseover", out acMouseArgs)) { - try + string[] p = acMouseArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (p.Length > 0 && p[0].Equals("watch", StringComparison.OrdinalIgnoreCase)) { - string[] p = acMouseArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (p.Length > 0 && p[0].Equals("watch", StringComparison.OrdinalIgnoreCase)) - { - int secs = p.Length > 1 && int.TryParse(p[1], out int n) ? n : 20; - AcMouseOver.Watch(secs); - Reply($"Watching AC's mouse-over for {Math.Clamp(secs, 1, 120)} s: move the cursor over the world and over AC's windows."); - } - else - { - Reply(AcMouseOver.Describe()); - } + int secs = p.Length > 1 && int.TryParse(p[1], out int n) ? n : 20; + AcMouseOver.Watch(secs); + Reply($"Watching AC's mouse-over for {Math.Clamp(secs, 1, 120)} s: move the cursor over the world and over AC's windows."); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc acmouse failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + else + { + Reply(AcMouseOver.Describe()); + } + return; } // /rc video [status|off|world|unfocused|all|fps ] : the video patch (stop drawing the 3D world) if (IsVerb(sub, "video", out string videoArgs) || IsVerb(sub, "videopatch", out videoArgs)) { - try - { - foreach (string l in D3D9.VideoPatch.HandleCommand(videoArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc video failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(D3D9.VideoPatch.HandleCommand(videoArgs)); + return; } // /rc hooks [on|off ] : the UI hooks (screen mode, client cleanup, tooltip, drag/drop) if (IsVerb(sub, "hooks", out string hooksArgs) || IsVerb(sub, "uihooks", out hooksArgs)) { - try { HandleHooksCommand(hooksArgs); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hooks failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + HandleHooksCommand(hooksArgs); + return; } // /rc flightdump [note] | /rc flightdump auto : write the flight recorder now if (IsVerb(sub, "flightdump", out string dumpArgs)) { - try - { - foreach (string l in Net.FlightRecorder.HandleDumpCommand(dumpArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc flightdump failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(Net.FlightRecorder.HandleDumpCommand(dumpArgs)); + return; } // /rc quit | /rc exit : close the client cleanly (as its close button; the character logs off) if (IsVerb(sub, "quit", out _) || IsVerb(sub, "exit", out _)) { Reply("Closing the client."); - try { ServerDisconnectClose.CloseClientNow("/rc quit"); } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc quit failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ServerDisconnectClose.CloseClientNow("/rc quit"); + return; } // /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log) if (IsVerb(sub, "report", out string reportArgs)) { - try - { - foreach (string l in Report.ProblemReport.HandleCommand(reportArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc report failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + var lines = new System.Collections.Generic.List(Report.ProblemReport.HandleCommand(reportArgs)); + if (lines.Count == 0) + Reply("Report a problem: the panel is open (or /rc report sends one from chat)."); + else + ReplyLines(lines); + return; } // /rc flight [status|mark |on|off|auto on|off] : the flight recorder if (IsVerb(sub, "flight", out string flightArgs)) { - try - { - foreach (string l in Net.FlightRecorder.HandleCommand(flightArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc flight failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(Net.FlightRecorder.HandleCommand(flightArgs)); + return; } // /rc autoid [all|limited|off] : which background appraisals AutoId sends (alone: status) if (IsVerb(sub, "autoid", out string autoIdArgs)) { - try - { - foreach (string l in AutoIdService.HandleCommand(autoIdArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc autoid failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(AutoIdService.HandleCommand(autoIdArgs)); + return; } // /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream if (IsVerb(sub, "netmsg", out string netArgs)) { - try - { - foreach (string l in Net.ServerMessageStream.HandleCommand(netArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc netmsg failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(Net.ServerMessageStream.HandleCommand(netArgs)); + return; } // /rc vtank [clear] : what the engine knows about VTank's macro (Decal bridge only); @@ -338,7 +374,7 @@ internal static class RynthCoreChatCommands if (vtankArgs.Equals("clear", StringComparison.OrdinalIgnoreCase)) Reply(VTankWatch.Clear() ? "VTank marked as not running; RynthAi's macro can start again." : "VTank was already marked as not running."); Reply(VTankWatch.Describe()); - return true; + return; } // /rc bounties|guardian [show|hide|toggle] : the ILT section's panels, like the bar's @@ -347,12 +383,12 @@ internal static class RynthCoreChatCommands if (IsVerb(sub, "bounties", out string panelArgs) || IsVerb(sub, "bounty", out panelArgs) || IsVerb(sub, "bountys", out panelArgs)) { IltPanel(ImGuiBackend.Panels.BountiesFace.Title, "Bounties", "RynthILT", panelArgs); - return true; + return; } if (IsVerb(sub, "guardian", out panelArgs) || IsVerb(sub, "guardians", out panelArgs)) { IltPanel(ImGuiBackend.Panels.GuardianFace.Title, "Guardian", "RynthILT", panelArgs); - return true; + return; } // /rc dashboard [classic|modern|tab ] : the RynthAi dashboard's look (the title bar buttons and @@ -361,7 +397,7 @@ internal static class RynthCoreChatCommands if (IsVerb(sub, "dashboard", out string dashArgs)) { DashboardCommand(dashArgs.Trim()); - return true; + return; } // /rc miniremote [show|hide|toggle|tab |section ] : the ImGui Mini Remote panel, like @@ -373,43 +409,8 @@ internal static class RynthCoreChatCommands // "section" opens it on one of its sections (char = Session Stats, map, skills, ...; "remote" = the remote). if (IsVerb(sub, "miniremote", out string remoteArgs) || IsVerb(sub, "remote", out remoteArgs)) { - if (IsVerb(remoteArgs, "tab", out string moved) && MovedTabCommand(moved) is string movedTo) - UI.ServerMenus.Run(movedTo); - else if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title)) - Reply("The Mini Remote panel isn't available (the ImGui layer is off?)."); - else if (IsVerb(remoteArgs, "tab", out string tab) - && tab.Length > 0 && ImGuiBackend.Panels.MiniRemoteFace.TryRequestSurface("section:" + tab.Trim().ToLowerInvariant())) - { - // A RynthAi that publishes sections: its tabs are sections here. - ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); - } - else if (IsVerb(remoteArgs, "tab", out tab)) - { - ImGuiBackend.Panels.MiniRemoteFace.RequestSection(UI.Sections.SectionCatalog.RemoteId); - ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); - UI.Data.RynthAiCommands.ApplyRemoteCommand("hub", tab.Length > 0 ? "tab " + tab : "tab"); - } - else if (IsVerb(remoteArgs, "section", out string section)) - { - string id = UI.Sections.SectionManifestParser.Id(section); - var snap = UI.Sections.SectionRegistry.Current; - if (id != UI.Sections.SectionCatalog.RemoteId && snap.Find(id) == null) - { - var names = new System.Collections.Generic.List { UI.Sections.SectionCatalog.RemoteId }; - foreach (UI.Sections.SectionView v in snap.Sections) names.Add(v.Id); - Reply($"Usage: /rc miniremote section <{string.Join("|", names)}>"); - } - else - { - ImGuiBackend.Panels.MiniRemoteFace.RequestSection(id); - ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); - } - } - else if (!TryPanelMode(remoteArgs, out bool? show)) - Reply("Usage: /rc miniremote [show|hide|toggle|tab |section ]"); - else - SetPanelOpen(ImGuiBackend.Panels.MiniRemoteFace.Title, show); - return true; + MiniRemoteCommand(remoteArgs); + return; } // /rc oracle-skills : RynthOracle says which SkillsFace body to embed @@ -417,24 +418,17 @@ internal static class RynthCoreChatCommands // Oracle has the tabs, which hides the standalone Skills bar icon and routes /rc skills there. if (IsVerb(sub, "oracle-skills", out string oracleSkillsArgs)) { - string a = oracleSkillsArgs.Trim().ToLowerInvariant(); - int tab = a switch + int tab = ChatCommandReplies.OracleSkillsTab(oracleSkillsArgs); + if (tab == ChatCommandReplies.InvalidTab) { - "off" or "clear" or "none" or "-1" => -1, - "0" or "skills" or "skill" => 0, - "1" or "attrs" or "attributes" or "vitals" => 1, - "2" or "progress" or "progression" => 2, - _ => -2, - }; - if (tab == -2) - Reply("Usage: /rc oracle-skills "); - else - { - ImGuiBackend.Panels.OracleSkillsEmbed.Announce(); - if (tab < 0) ImGuiBackend.Panels.OracleSkillsEmbed.Clear(); - else ImGuiBackend.Panels.OracleSkillsEmbed.SetActiveTab(tab); + Fail(ChatCommandReplies.Usage("oracle-skills")); + return; } - return true; + ImGuiBackend.Panels.OracleSkillsEmbed.Announce(); + if (tab < 0) ImGuiBackend.Panels.OracleSkillsEmbed.Clear(); + else ImGuiBackend.Panels.OracleSkillsEmbed.SetActiveTab(tab); + Reply(ChatCommandReplies.OracleSkillsReply(tab)); + return; } // /rc skills [show|hide|toggle] : RynthOracle's Skills tab when Oracle provides it (see @@ -443,29 +437,45 @@ internal static class RynthCoreChatCommands if (IsVerb(sub, "skills", out string skillsArgs)) { if (!TryPanelMode(skillsArgs, out bool? show)) - Reply("Usage: /rc skills [show|hide|toggle]"); - else if (!ImGuiBackend.Panels.SkillsRouting.SetOpen(show)) - Reply("The Skills panel isn't available (the ImGui layer is off?)."); - return true; + { + Fail(ChatCommandReplies.Usage("skills")); + return; + } + bool oracle = ImGuiBackend.Panels.SkillsRouting.OracleTabsAvailable; + bool wasShowing = oracle + ? UI.ScriptWindows.ScriptWindowRegistry.IsOpen(ImGuiBackend.Panels.SkillsRouting.OracleKey) + && ImGuiBackend.Panels.OracleSkillsEmbed.ActiveTab == 0 + : ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SkillsFace.Title); + if (!ImGuiBackend.Panels.SkillsRouting.SetOpen(show)) + Fail("The Skills panel isn't available (the ImGui layer is off?)."); + else + Reply(ChatCommandReplies.PanelReply(oracle ? "RynthOracle's Skills tab" : "Skills panel", show, wasShowing)); + return; } - if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase) - || sub.Equals("progress", StringComparison.OrdinalIgnoreCase)) + if (IsVerb(sub, "progression", out _) || IsVerb(sub, "progress", out _)) { + bool oracle = ImGuiBackend.Panels.SkillsRouting.OracleTabsAvailable; if (!ImGuiBackend.Panels.SkillsRouting.Open(2)) - Reply("The Skills panel isn't available (the ImGui layer is off?)."); - return true; + Fail("The Skills panel isn't available (the ImGui layer is off?)."); + else + Reply(oracle ? "RynthOracle's Progress tab opened." : "Skills panel opened on Progression."); + return; } // /rc spells [show|hide|toggle] : RynthAi's Spells window (spell catalog, buff profiles). if (IsVerb(sub, "spells", out string spellsArgs)) { if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.RynthAiFace.Title)) - Reply("The Spells window comes with RynthAi; it isn't installed."); + Fail("The Spells window comes with RynthAi; it isn't installed."); else if (!TryPanelMode(spellsArgs, out bool? show)) - Reply("Usage: /rc spells [show|hide|toggle]"); + Fail(ChatCommandReplies.Usage("spells")); else + { UI.Data.RynthAiCommands.ApplyRemoteCommand("spells", show == null ? "toggle" : show.Value ? "show" : "hide"); - return true; + Reply(show == null ? "Opening or closing RynthAi's Spells window (toggle)." + : show.Value ? "Opening RynthAi's Spells window." : "Closing RynthAi's Spells window."); + } + return; } // /rc hotkeys : Settings > Hotkeys. /rc hotkey list|add|remove|enable|disable|actions|status|on|off @@ -473,28 +483,20 @@ internal static class RynthCoreChatCommands if (IsVerb(sub, "hotkeys", out string hotkeyArgs) && hotkeyArgs.Length == 0) { if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title)) - Reply("The Settings panel isn't available (the ImGui layer is off?). /rc hotkey list|add|remove work here in chat."); + Fail("The Settings panel isn't available (the ImGui layer is off?). /rc hotkey list|add|remove work here in chat."); else - { - ImGuiBackend.Panels.SettingsFace.RequestTab(ImGuiBackend.Panels.HotkeysSettingsUi.TabName); - if (!ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SettingsFace.Title)) - UI.PanelRouter.Toggle(ImGuiBackend.Panels.SettingsFace.Title); - } - return true; + OpenSettingsTab(ImGuiBackend.Panels.HotkeysSettingsUi.TabName); + return; } // /rc diagnostics : Settings > Diagnostics, where a server is forced for this character (the // server picker). The one place to force a server since 2026.10.5.54, so plugins link here. if ((IsVerb(sub, "diagnostics", out string diagArgs) || IsVerb(sub, "serverpick", out diagArgs)) && diagArgs.Length == 0) { if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title)) - Reply("The Settings panel isn't available (the ImGui layer is off?). /rc server auto|on|off works here in chat."); + Fail("The Settings panel isn't available (the ImGui layer is off?). /rc server auto|on|off works here in chat."); else - { - ImGuiBackend.Panels.SettingsFace.RequestTab(DiagnosticsTabName); - if (!ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SettingsFace.Title)) - UI.PanelRouter.Toggle(ImGuiBackend.Panels.SettingsFace.Title); - } - return true; + OpenSettingsTab(DiagnosticsTabName); + return; } // /rc settings [tab] : the Settings panel (toggled), or opened on a tab ("/rc settings buffing"). // A plugin's own window links to a tab this way (RynthAi's dashboard: the Buffing key's @@ -506,27 +508,28 @@ internal static class RynthCoreChatCommands string[] sa = shortcutArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (sa.Length >= 2 && sa[0].Equals("use", StringComparison.OrdinalIgnoreCase) && int.TryParse(sa[1], out int useSlot)) { - Reply(AcShortcuts.Enqueue(AcShortcuts.Op.Use, useSlot - 1, 0) - ? $"Using shortcut {useSlot}." : $"Shortcut {useSlot} can't be used ({AcShortcuts.Status})"); - return true; + Answer(AcShortcuts.Enqueue(AcShortcuts.Op.Use, useSlot - 1, 0), + $"Using shortcut {useSlot}.", $"Shortcut {useSlot} can't be used ({AcShortcuts.Status})"); + return; } // /rc shortcuts set N: the selected item into slot N; clear N: empty it (the retail toolbar's way). if (sa.Length >= 2 && sa[0].Equals("set", StringComparison.OrdinalIgnoreCase) && int.TryParse(sa[1], out int setSlot)) { uint sel = sa.Length >= 3 && uint.TryParse(sa[2].Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint given) ? given : ClientHelperHooks.GetSelectedItemId(); - Reply(sel == 0 ? "Select the item first." - : AcShortcuts.Enqueue(AcShortcuts.Op.Set, setSlot - 1, sel) ? $"Shortcut {setSlot}: 0x{sel:X8}." : $"Shortcut {setSlot} can't be set ({AcShortcuts.Status})"); - return true; + if (sel == 0) Fail("Select the item first."); + else Answer(AcShortcuts.Enqueue(AcShortcuts.Op.Set, setSlot - 1, sel), + $"Shortcut {setSlot}: 0x{sel:X8}.", $"Shortcut {setSlot} can't be set ({AcShortcuts.Status})"); + return; } if (sa.Length >= 2 && sa[0].Equals("clear", StringComparison.OrdinalIgnoreCase) && int.TryParse(sa[1], out int clearSlot)) { - Reply(AcShortcuts.Enqueue(AcShortcuts.Op.Clear, clearSlot - 1, 0) - ? $"Shortcut {clearSlot} emptied." : $"Shortcut {clearSlot} can't be emptied ({AcShortcuts.Status})"); - return true; + Answer(AcShortcuts.Enqueue(AcShortcuts.Op.Clear, clearSlot - 1, 0), + $"Shortcut {clearSlot} emptied.", $"Shortcut {clearSlot} can't be emptied ({AcShortcuts.Status})"); + return; } AcShortcuts.Slot[] slots = AcShortcuts.Slots; - if (slots.Length == 0) { Reply("No shortcut slots read yet (in the world? " + AcShortcuts.Status + ")"); return true; } + if (slots.Length == 0) { Fail("No shortcut slots read yet (in the world? " + AcShortcuts.Status + ")"); return; } Reply($"Shortcuts (keymap {System.IO.Path.GetFileName(AcKeymap.FilePath)}):"); for (int i = 0; i < slots.Length; i++) { @@ -535,7 +538,7 @@ internal static class RynthCoreChatCommands string keys = AcKeymap.KeysText($"UseQuickSlot_{i + 1}"); Reply($" {i + 1,2}: {what}{(keys.Length > 0 ? " [" + keys + "]" : "")}"); } - return true; + return; } // /rc keymap [check|bind|unbind | reload]: AC's keys, changed so every client follows @@ -553,63 +556,58 @@ internal static class RynthCoreChatCommands if (verb == "check") { int r = AcKeymapLive.Check(action, key, out string msg); - Reply(r == 0 ? $"{key} is free for {action}." : msg); + if (r == 0) Reply($"{key} is free for {action}."); + else Fail(msg); } else if (!AcKeymapLive.Enqueue(action, key, verb == "bind" ? AcKeymapLive.Op.Bind : AcKeymapLive.Op.Unbind, out string why)) - Reply(why); - return true; + Fail(why); + else + AnswersItself(); // AC's thread says how the change went (AcKeymapLive.DrainRequests) + return; } if (verb == "dump") { - AcKeymapLive.RequestDump(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "rynthcore-keymap-memory.keymap")); - return true; + string dumpPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "rynthcore-keymap-memory.keymap"); + AcKeymapLive.RequestDump(dumpPath); + if (AcKeymapLive.CanChange) + AnswersItself(); // written on AC's next tick, which says so in chat (AcKeymapLive.Tick) + else + Fail($"AC's keys can't be read here yet ({AcKeymapLive.Status}); they're written to {dumpPath} once they can."); + return; } Reply($"Keymap {AcKeymap.FilePath} - {AcKeymapLive.Status} Usage: /rc keymap check|bind|unbind | dump, e.g. /rc keymap bind UseQuickSlot_10 F11"); - return true; + return; } // /rc panels [open|close|toggle ]: AC's own panels (AcPanels): their ids, classes and which are open. if (IsVerb(sub, "panels", out string acPanelArgs)) { string[] pa = acPanelArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (pa.Length == 2 && uint.TryParse(pa[1].Replace("0x", "", StringComparison.OrdinalIgnoreCase), - pa[1].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer, - null, out uint panelId)) + if (pa.Length == 2 && ChatCommandReplies.TryPanelId(pa[1], out uint panelId)) { AcPanels.Op op = pa[0].ToLowerInvariant() switch { "open" => AcPanels.Op.Open, "close" => AcPanels.Op.Close, _ => AcPanels.Op.Toggle }; - if (!AcPanels.Enqueue(panelId, op)) Reply("Can't: " + AcPanels.Status); - return true; + if (!AcPanels.Enqueue(panelId, op)) Fail("Can't: " + AcPanels.Status); + else Reply($"AC panel {panelId}: {op.ToString().ToLowerInvariant()} requested."); + return; } var panels = AcPanels.List(names: true); Reply($"AC panels ({panels.Count}; {AcPanels.Status}):"); foreach (var p in panels) Reply($" {p.Id,3} {p.Class}{(p.Open ? " - open" : "")}"); - return true; + return; } if (IsVerb(sub, "settings", out string settingsArgs)) { - string settingsTitle = ImGuiBackend.Panels.SettingsFace.Title; - if (!ImGuiBackend.ImGuiPanelHost.HasFace(settingsTitle)) - Reply("The Settings panel isn't available (the ImGui layer is off?)."); - else if (settingsArgs.Length == 0) - UI.PanelRouter.Toggle(settingsTitle); - else - { - ImGuiBackend.Panels.SettingsFace.RequestTab(settingsArgs); - if (!ImGuiBackend.ImGuiPanelHost.IsOpen(settingsTitle)) UI.PanelRouter.Toggle(settingsTitle); - } - return true; + SettingsCommand(settingsArgs); + return; } if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs)) { - try - { - foreach (string l in Hotkeys.HotkeyService.HandleCommand(hotkeyArgs)) - Reply(l); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hotkey failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + // The parser's own errors (an unknown verb, a bad key) are the failures; the rest is what changed. + bool bad = Hotkeys.HotkeyCommandParser.Parse(hotkeyArgs).Verb == Hotkeys.HotkeyVerb.Error; + ReplyLines(Hotkeys.HotkeyService.HandleCommand(hotkeyArgs), bad ? ChatReplyKind.Fail : ChatReplyKind.Ok); + return; } switch (sub.ToLowerInvariant()) @@ -620,87 +618,71 @@ internal static class RynthCoreChatCommands // loader's reload shuts this engine down, and this handler runs // inside AC's outgoing-chat hook. RynthLog.Compat("RynthCoreChatCommands: /rc rl — engine reload requested."); + Reply("Reloading RynthCore (as the bar's RL button)."); EntryPoint.NoteManualReload(); // by hand: not held for combat (EntryPoint.DeferReloadWhilePluginsObject) System.Threading.ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null); - return true; + return; case "inv": case "inventory": // The ImGui Inventory panel (open/close), like its bar button. - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.InventoryFace.Title)) - Reply("The Inventory panel isn't available (the ImGui layer is off?)."); - else - UI.PanelRouter.Toggle(ImGuiBackend.Panels.InventoryFace.Title); - return true; + TogglePanel(ImGuiBackend.Panels.InventoryFace.Title, "Inventory panel", + "The Inventory panel isn't available (the ImGui layer is off?)."); + return; case "sense": // The ImGui Sense panel (open/close), like its bar button. - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SenseFace.Title)) - Reply("The Sense panel isn't available (the ImGui layer is off?)."); - else - UI.PanelRouter.Toggle(ImGuiBackend.Panels.SenseFace.Title); - return true; + TogglePanel(ImGuiBackend.Panels.SenseFace.Title, "Sense panel", + "The Sense panel isn't available (the ImGui layer is off?)."); + return; case "characters": case "chars": // The Characters window: RynthNet's own since 2026-10-21 (a plugin window, keyed by its title). - if (!ImGuiBackend.ImGuiPanelHost.HasFace(CharactersWindowTitle)) - Reply("The Characters window comes with the RynthNet plugin (add it in the launcher's Plugins tab)."); - else - UI.PanelRouter.Toggle(CharactersWindowTitle); - return true; + TogglePanel(CharactersWindowTitle, "Characters window", + "The Characters window comes with the RynthNet plugin (add it in the launcher's Plugins tab)."); + return; case "itemcount": case "itemhud": // The ImGui Item Count panel (open/close), like its bar button. - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.ItemCountFace.Title)) - Reply("The Item Count panel isn't available (the ImGui layer is off?)."); - else - UI.PanelRouter.Toggle(ImGuiBackend.Panels.ItemCountFace.Title); - return true; + TogglePanel(ImGuiBackend.Panels.ItemCountFace.Title, "Item Count panel", + "The Item Count panel isn't available (the ImGui layer is off?)."); + return; case "resetbar": case "barreset": RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position."); ImGuiBackend.RynthCoreShell.RequestExternalReset(); - return true; + Reply("RynthCore bar moved back to the top-left corner."); + return; case "actionstate": case "actions": // Read-only: every client-side gate on item use/equip/move // (ClientActionGates). Works while those are locked — chat still does. - try - { - foreach (string stateLine in ClientActionGates.DescribeLines()) - Reply(stateLine); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc actionstate failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(ClientActionGates.DescribeLines()); + return; case "unlockactions": case "unlock": - try - { - foreach (string unlockLine in ClientActionGates.RequestUnlock()) - Reply(unlockLine); - } - catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc unlockactions failed - {ex.GetType().Name}: {ex.Message}"); } - return true; + ReplyLines(ClientActionGates.RequestUnlock()); + return; case "vitals": case "hud": { // The old D3D9 vitals HUD is gone (2026-09-29): your vitals are the // RynthVision player plate now. - Reply("The old vitals HUD was removed. Your health/stamina/mana bars are the RynthVision player plate: /rv plates self [on|off]."); - return true; + Fail("The old vitals HUD was removed. Your health/stamina/mana bars are the RynthVision player plate: /rv plates self [on|off]."); + return; } default: // Consume anything else under the /rc namespace so a typo - // does not leak into world chat. - RynthLog.Compat($"RynthCoreChatCommands: unknown subcommand '/rc {sub}'."); - return true; + // does not leak into world chat (ChatCommandReplies.Check answers first). + Fail(ChatCommandReplies.UnknownReply(sub)); + return; } } @@ -763,7 +745,7 @@ internal static class RynthCoreChatCommands else if (parts[1] == "-") next = cur - 1; else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next)) { - Reply("Usage: /rc ui barsize [0-10|+|-|status]"); + Fail("Usage: /rc ui barsize [0-10|+|-|status]"); return; } else if (parts[1][0] is '+' or '-') @@ -786,7 +768,7 @@ internal static class RynthCoreChatCommands else if (parts[1] == "-") next = cur - 1; else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next)) { - Reply("Usage: /rc ui barrows [1-6|+|-|status]"); + Fail("Usage: /rc ui barrows [1-6|+|-|status]"); return; } else if (parts[1][0] is '+' or '-') @@ -811,7 +793,7 @@ internal static class RynthCoreChatCommands next = UI.BarLayout.NoLimit; else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next)) { - Reply("Usage: /rc ui baricons [2-30|none|+|-|status]"); + Fail("Usage: /rc ui baricons [2-30|none|+|-|status]"); return; } ImGuiBackend.ImGuiBar.SetRowLayout(ImGuiBackend.ImGuiBar.Rows, next); @@ -824,6 +806,9 @@ internal static class RynthCoreChatCommands if (parts[0].Equals("channels", StringComparison.OrdinalIgnoreCase)) { ImGuiBackend.Panels.ChatFace.ToggleChannelsRequested = true; + Reply(ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.ChatFace.Title) + ? "Chat: the channels drawer opens or closes." + : "Chat: the channels drawer opens or closes the next time the chat window shows."); return; } @@ -841,7 +826,7 @@ internal static class RynthCoreChatCommands return; } if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) && verb == "snap") title = "__bar"; - else if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) { Reply($"No ImGui panel named '{title}'."); return; } + else if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) { Fail($"No ImGui panel named '{title}'."); return; } switch (verb) { case "open": ImGuiBackend.ImGuiPanelHost.Open(title); break; @@ -860,11 +845,11 @@ internal static class RynthCoreChatCommands // The old face choice: nothing to pick any more (nothing is stored either). if (parts.Length == 2 && UI.PanelFaceStore.TryParseFace(parts[1], out _)) { - Reply("The Avalonia / Both faces are gone: docked panels and the bar always show their ImGui face."); + Fail("The Avalonia / Both faces are gone: docked panels and the bar always show their ImGui face."); return; } - Reply("Usage: /rc ui list | /rc ui open|close|popout|redock|snap | /rc ui retailvitals [on|off] | /rc ui retailtoolbar [on|off] | /rc ui barsize [0-10|+|-|status] | /rc ui barrows [1-6|+|-] | /rc ui baricons [2-30|none|+|-]"); + Fail("Usage: /rc ui list | /rc ui open|close|popout|redock|snap | /rc ui retailvitals [on|off] | /rc ui retailtoolbar [on|off] | /rc ui barsize [0-10|+|-|status] | /rc ui barrows [1-6|+|-] | /rc ui baricons [2-30|none|+|-]"); } /// @@ -907,7 +892,7 @@ internal static class RynthCoreChatCommands Reply($"ImGui layer is {(Plugins.EngineSettings.EnableImGuiBackend ? "ON" : "OFF")}. Usage: /rc imgui on|off|fonttest|diag"); return; default: - Reply("Usage: /rc imgui on|off|fonttest|diag"); + Fail("Usage: /rc imgui on|off|fonttest|diag"); return; } } @@ -933,15 +918,13 @@ internal static class RynthCoreChatCommands case "status": break; default: - Reply("Usage: /rc chathold [on|off|status]"); + Fail("Usage: /rc chathold [on|off|status]"); return; } Reply(ChatCallbackHooks.HoldStatusText()); } - /// "verb" or "verb args..." (case-insensitive); args trimmed. - private const string ServerUsage = - "Usage: /rc server [ auto|on|off] | pick |auto | [aelrynth|other|auto] | names ilt [add|remove ]"; + private const string ServerUsage = ChatCommandReplies.ServerUsage; /// /// /rc server: every server the engine and the plugins know, whether each is active and why. @@ -963,7 +946,7 @@ internal static class RynthCoreChatCommands if (first == "pick") { // One server for this character (every other off), or "auto": the Diagnostics page's picker. - if (words.Length != 2) { Reply(ServerUsage); return; } + if (words.Length != 2) { Fail(ServerUsage); return; } UI.Sections.ServerSelectionStore.Apply(words[1], out string message); Reply(message); ReplyServers(); @@ -979,7 +962,7 @@ internal static class RynthCoreChatCommands "auto" => ServerInfo.Mode.Auto, _ => null, }; - if (legacy == null) { Reply(ServerUsage); return; } + if (legacy == null) { Fail(ServerUsage); return; } SetServerForce(ServerInfo.ServerId, legacy switch { ServerInfo.Mode.ForceAelrynth => UI.Sections.ServerForce.On, @@ -989,12 +972,12 @@ internal static class RynthCoreChatCommands } else if (words.Length == 2) { - if (!UI.Sections.ServerForceText.TryParse(words[1], out UI.Sections.ServerForce mode)) { Reply(ServerUsage); return; } + if (!UI.Sections.ServerForceText.TryParse(words[1], out UI.Sections.ServerForce mode)) { Fail(ServerUsage); return; } if (!SetServerForce(first, mode)) return; } else if (words.Length > 2) { - Reply(ServerUsage); + Fail(ServerUsage); return; } @@ -1012,12 +995,12 @@ internal static class RynthCoreChatCommands if (id.Length == 0 || (!UI.Sections.SectionRegistry.IsBuiltInServer(id) && UI.Sections.SectionRegistry.Current.Server(id) == null)) { - Reply($"No server called '{serverId}'. /rc server lists them."); + Fail($"No server called '{serverId}'. /rc server lists them."); return false; } if (!UI.Sections.ServerForceStore.Set(id, mode, out string where)) { - Reply($"Server override not changed: {where}."); + Fail($"Server override not changed: {where}."); return false; } UI.Sections.SectionRegistry.Invalidate(); @@ -1051,7 +1034,7 @@ internal static class RynthCoreChatCommands { if (words.Length < 2 || !words[1].Equals(IltInfo.ServerId, StringComparison.OrdinalIgnoreCase)) { - Reply("Usage: /rc server names ilt [add|remove ] (other servers' lists come from their plugins)."); + Fail("Usage: /rc server names ilt [add|remove ] (other servers' lists come from their plugins)."); return; } if (words.Length >= 4) @@ -1059,20 +1042,21 @@ internal static class RynthCoreChatCommands bool add = words[2].Equals("add", StringComparison.OrdinalIgnoreCase); if (!add && !words[2].Equals("remove", StringComparison.OrdinalIgnoreCase)) { - Reply("Usage: /rc server names ilt [add|remove ]"); + Fail("Usage: /rc server names ilt [add|remove ]"); return; } string pattern = string.Join(' ', words, 3, words.Length - 3); bool changed = Plugins.EngineSettings.EditIltServerName(pattern, add); - Reply(changed - ? $"Infinite Leaftide world names: {(add ? "added" : "removed")} \"{pattern}\" (engine.json)." - : $"Infinite Leaftide world names: \"{pattern}\" was {(add ? "already there (or too long)" : "not there")}."); + if (changed) + Reply($"Infinite Leaftide world names: {(add ? "added" : "removed")} \"{pattern}\" (engine.json)."); + else + Fail($"Infinite Leaftide world names: \"{pattern}\" was {(add ? "already there (or too long)" : "not there")}."); IltInfo.Invalidate(); UI.Sections.SectionRegistry.Invalidate(); } else if (words.Length == 3) { - Reply("Usage: /rc server names ilt [add|remove ]"); + Fail("Usage: /rc server names ilt [add|remove ]"); return; } Reply($"Infinite Leaftide lists: {IltInfo.ListsDescription}."); @@ -1092,7 +1076,7 @@ internal static class RynthCoreChatCommands case "auto": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.Auto); break; case "": break; default: - Reply("Usage: /rc ilt [auto|on|off]"); + Fail("Usage: /rc ilt [auto|on|off]"); return; } IltVerdict v = IltInfo.Current; @@ -1109,7 +1093,7 @@ internal static class RynthCoreChatCommands { if (!ServerInfo.IsAelrynth) { - Reply("Mastery: not on Aelrynth, so nothing is asked (/rc server for why)."); + Fail("Mastery: not on Aelrynth, so nothing is asked (/rc server for why)."); return; } MasterySnapshot? s = MasteryFeed.Snapshot; @@ -1141,26 +1125,16 @@ internal static class RynthCoreChatCommands return; } if (arg.Length > 0 && !arg.Equals("status", StringComparison.OrdinalIgnoreCase)) - Reply("Usage: /rc worldlayer [auto|uipass|transition|endscene]"); + Fail("Usage: /rc worldlayer [auto|uipass|transition|endscene]"); Reply(D3D9.Nav3DRenderInjector.Describe()); Reply(ImGuiBackend.UnderUiLayer.Describe()); } /// /// "" / "toggle" → null (flip), "show" / "on" / "open" → true, "hide" / "off" / "close" → - /// false. False for anything else. + /// false. False for anything else (). /// - private static bool TryPanelMode(string args, out bool? show) - { - show = null; - switch (args.Trim().ToLowerInvariant()) - { - case "": case "toggle": return true; - case "show": case "on": case "open": show = true; return true; - case "hide": case "off": case "close": show = false; return true; - default: return false; - } - } + private static bool TryPanelMode(string args, out bool? show) => ChatCommandReplies.TryPanelMode(args, out show); /// Opens (true), closes (false) or toggles (null) an ImGui panel, like its bar button. private static void SetPanelOpen(string title, bool? show) @@ -1169,43 +1143,156 @@ internal static class RynthCoreChatCommands UI.PanelRouter.Toggle(title); } - private static readonly string[] ClassicTabNames = { "main", "monsters", "gear", "buffs", "route", "loot", "meta", "tuning" }; + /// Opens or closes an ImGui panel (its bar button), and says which; when there's none. + private static void TogglePanel(string title, string label, string missing) + { + if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) + { + Fail(missing); + return; + } + bool wasOpen = ImGuiBackend.ImGuiPanelHost.IsOpen(title); + UI.PanelRouter.Toggle(title); + Reply(ChatCommandReplies.PanelReply(label, null, wasOpen)); + } + + /// Settings, opened on (or switched to it when open). + private static void OpenSettingsTab(string tab) + { + string title = ImGuiBackend.Panels.SettingsFace.Title; + bool wasOpen = ImGuiBackend.ImGuiPanelHost.IsOpen(title); + ImGuiBackend.Panels.SettingsFace.RequestTab(tab); + if (!wasOpen) + UI.PanelRouter.Toggle(title); + Reply(ChatCommandReplies.SettingsTabReply(tab, wasOpen)); + } + + /// "/rc settings [tab]": the Settings panel (toggled), or opened on a tab. + private static void SettingsCommand(string tabName) + { + string title = ImGuiBackend.Panels.SettingsFace.Title; + if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) + { + Fail("The Settings panel isn't available (the ImGui layer is off?)."); + return; + } + if (tabName.Length == 0) + { + TogglePanel(title, "Settings", "The Settings panel isn't available (the ImGui layer is off?)."); + return; + } + UI.Data.SettingsTab? tab = Array.Find(UI.Data.SettingsSchema.Tabs, t => t.Name.Equals(tabName, StringComparison.OrdinalIgnoreCase)); + if (tab != null) + { + OpenSettingsTab(tab.Name); + return; + } + // As before, Settings opens anyway (on the tab it was on); the reply says the name was wrong. + bool wasOpen = ImGuiBackend.ImGuiPanelHost.IsOpen(title); + ImGuiBackend.Panels.SettingsFace.RequestTab(tabName); + if (!wasOpen) + UI.PanelRouter.Toggle(title); + Fail($"No Settings tab called '{tabName}' (tabs: {string.Join(", ", Array.ConvertAll(UI.Data.SettingsSchema.Tabs, t => t.Name))}); " + + (wasOpen ? "Settings stays on its tab." : "Settings opened on its last tab.")); + } /// "/rc dashboard [classic|modern|tab <name>]": the RynthAi dashboard's look and the Classic look's tab. private static void DashboardCommand(string args) { string title = ImGuiBackend.Panels.RynthAiFace.Title; - string usage = "Usage: /rc dashboard classic|modern|tab <" + string.Join("|", ClassicTabNames) + ">"; + string usage = ChatCommandReplies.Usage("dashboard"); if (args.Length == 0) { Reply("The RynthAi dashboard's look is " + (UI.RynthAiDashboardState.Classic ? "Classic" : "Modern") + ". " + usage); return; } + bool classic; + string? tabName = null; if (IsVerb(args, "tab", out string tab)) { - int i = Array.FindIndex(ClassicTabNames, n => n.Equals(tab.Trim(), StringComparison.OrdinalIgnoreCase)); - if (i < 0) { Reply(usage); return; } + int i = ChatCommandReplies.ClassicTab(tab); + if (i < 0) { Fail(usage); return; } UI.RynthAiDashboardState.SetClassicTab(i); ImGuiBackend.Panels.RynthAiFace.SwitchLook(classic: true); + classic = true; + tabName = ChatCommandReplies.ClassicTabNames[i]; } - else if (args.Equals("classic", StringComparison.OrdinalIgnoreCase)) ImGuiBackend.Panels.RynthAiFace.SwitchLook(classic: true); - else if (args.Equals("modern", StringComparison.OrdinalIgnoreCase)) ImGuiBackend.Panels.RynthAiFace.SwitchLook(classic: false); - else { Reply(usage); return; } - if (ImGuiBackend.ImGuiPanelHost.HasFace(title) && !ImGuiBackend.ImGuiPanelHost.IsOpen(title)) + else if (args.Equals("classic", StringComparison.OrdinalIgnoreCase)) { ImGuiBackend.Panels.RynthAiFace.SwitchLook(classic: true); classic = true; } + else if (args.Equals("modern", StringComparison.OrdinalIgnoreCase)) { ImGuiBackend.Panels.RynthAiFace.SwitchLook(classic: false); classic = false; } + else { Fail(usage); return; } + bool hasDashboard = ImGuiBackend.ImGuiPanelHost.HasFace(title); + if (hasDashboard && !ImGuiBackend.ImGuiPanelHost.IsOpen(title)) ImGuiBackend.ImGuiPanelHost.Open(title); + Reply(ChatCommandReplies.DashboardReply(classic, tabName, hasDashboard)); } /// "/rc bounties|guardian [show|hide|toggle]": one of the ILT section's panels. private static void IltPanel(string title, string label, string plugin, string args) { if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) - Reply($"The {label} panel isn't available (the {plugin} plugin isn't installed, or the ImGui layer is off)."); + Fail($"The {label} panel isn't available (the {plugin} plugin isn't installed, or the ImGui layer is off)."); else if (!TryPanelMode(args, out bool? show)) - Reply($"Usage: /rc {label.ToLowerInvariant()} [show|hide|toggle]"); + Fail($"Usage: /rc {label.ToLowerInvariant()} [show|hide|toggle]"); else if (show != false && !IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(title)) - Reply($"{label} is an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why)."); + Fail($"{label} is an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why)."); else + { + bool wasOpen = ImGuiBackend.ImGuiPanelHost.IsOpen(title); SetPanelOpen(title, show); + Reply(ChatCommandReplies.PanelReply(label + " panel", show, wasOpen)); + } + } + + /// "/rc miniremote [show|hide|toggle|tab <tab>|section <id>]" (the comment at its verb in Handle). + private static void MiniRemoteCommand(string remoteArgs) + { + string remoteTitle = ImGuiBackend.Panels.MiniRemoteFace.Title; + if (IsVerb(remoteArgs, "tab", out string moved) && MovedTabCommand(moved) is string movedTo) + { + UI.ServerMenus.Run(movedTo); + Reply($"The {moved.Trim().ToLowerInvariant()} tab is RynthOracle's now: ran {movedTo}."); + } + else if (!ImGuiBackend.ImGuiPanelHost.HasFace(remoteTitle)) + Fail("The Mini Remote panel isn't available (the ImGui layer is off?)."); + else if (IsVerb(remoteArgs, "tab", out string tab) + && tab.Length > 0 && ImGuiBackend.Panels.MiniRemoteFace.TryRequestSurface("section:" + tab.Trim().ToLowerInvariant())) + { + // A RynthAi that publishes sections: its tabs are sections here. + ImGuiBackend.ImGuiPanelHost.Open(remoteTitle); + Reply($"Mini Remote opened on {tab.Trim().ToLowerInvariant()}."); + } + else if (IsVerb(remoteArgs, "tab", out tab)) + { + ImGuiBackend.Panels.MiniRemoteFace.RequestSection(UI.Sections.SectionCatalog.RemoteId); + ImGuiBackend.ImGuiPanelHost.Open(remoteTitle); + UI.Data.RynthAiCommands.ApplyRemoteCommand("hub", tab.Length > 0 ? "tab " + tab : "tab"); + Reply(tab.Length > 0 ? $"Mini Remote opened; RynthAi was asked for its {tab} tab." : "Mini Remote opened on RynthAi's remote."); + } + else if (IsVerb(remoteArgs, "section", out string section)) + { + string id = UI.Sections.SectionManifestParser.Id(section); + var snap = UI.Sections.SectionRegistry.Current; + if (id != UI.Sections.SectionCatalog.RemoteId && snap.Find(id) == null) + { + var names = new System.Collections.Generic.List { UI.Sections.SectionCatalog.RemoteId }; + foreach (UI.Sections.SectionView v in snap.Sections) names.Add(v.Id); + Fail($"Usage: /rc miniremote section <{string.Join("|", names)}>"); + } + else + { + ImGuiBackend.Panels.MiniRemoteFace.RequestSection(id); + ImGuiBackend.ImGuiPanelHost.Open(remoteTitle); + Reply($"Mini Remote opened on section {id}."); + } + } + else if (!TryPanelMode(remoteArgs, out bool? show)) + Fail(ChatCommandReplies.Usage("miniremote")); + else + { + bool wasOpen = ImGuiBackend.ImGuiPanelHost.IsOpen(remoteTitle); + SetPanelOpen(remoteTitle, show); + Reply(ChatCommandReplies.PanelReply("Mini Remote", show, wasOpen)); + } } /// @@ -1219,14 +1306,8 @@ internal static class RynthCoreChatCommands _ => null, }; - private static bool IsVerb(string sub, string verb, out string args) - { - args = string.Empty; - if (sub.Equals(verb, StringComparison.OrdinalIgnoreCase)) return true; - if (!sub.StartsWith(verb + " ", StringComparison.OrdinalIgnoreCase)) return false; - args = sub.Substring(verb.Length + 1).Trim(); - return true; - } + /// "verb" or "verb args..." (case-insensitive); args trimmed (). + private static bool IsVerb(string sub, string verb, out string args) => ChatCommandReplies.IsVerb(sub, verb, out args); /// /// /rv plates (alias /rc plates): the RynthVision nameplates and combat text @@ -1237,21 +1318,16 @@ internal static class RynthCoreChatCommands /// private static void HandlePlatesCommand(string args) { - const string usage = "Usage: /rv plates [on|off] | all on|off | self [numbers|name|firstperson|lock|debuffs] [on|off] | " + - "self fixed|follow|unlock|reset | self debuffs size <50-200%> | " + - "debuffs [on|off] | debuffs size <50-200%> | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " + - "gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist |max | players [on|off] | portals [on|off] | portals dist | " + - "all|engaged |dist |max |scale |opacity |lift | " + - "names|hp|level|weak|distance|fade|click [on|off] | reset | status | test"; + const string usage = ChatCommandReplies.PlatesUsage; if (!ImGuiBackend.Hud.HudFeed.VisionInstalled) { - Reply("RynthVision isn't in the plugin list (launcher, Plugins tab), so its nameplates and combat text are off."); + Fail("RynthVision isn't in the plugin list (launcher, Plugins tab), so its nameplates and combat text are off."); return; } if (!ImGuiBackend.Hud.MonsterHudSettings.Loaded) { ImGuiBackend.Hud.MonsterHudSettings.EnsureLoadQueued(); - Reply("Nameplate settings are still loading - try again in a moment."); + Fail("Nameplate settings are still loading - try again in a moment."); return; } @@ -1292,7 +1368,7 @@ internal static class RynthCoreChatCommands { if (!S.TryParseDebuffIconSize(parts.Length > 3 ? parts[3] : null, out int sdi)) { - Reply($"usage: /rv plates self debuffs size {S.MinDebuffIconSize}-{S.MaxDebuffIconSize} (percent; now {S.SelfDebuffIconSize}%)"); + Fail($"Usage: /rv plates self debuffs size {S.MinDebuffIconSize}-{S.MaxDebuffIconSize} (percent; now {S.SelfDebuffIconSize}%)"); return; } S.SelfDebuffIconSize = sdi; @@ -1317,11 +1393,11 @@ internal static class RynthCoreChatCommands "right" => ImGuiBackend.Hud.SelfPlatePosition.Right, _ => null, }; - if (p == null) { Reply("usage: /rv plates self position above|below|left|right"); return; } + if (p == null) { Fail("Usage: /rv plates self position above|below|left|right"); return; } S.SelfPosition = p.Value; break; } - default: Reply(usage); return; + default: Fail(usage); return; } break; case "click": @@ -1337,7 +1413,7 @@ internal static class RynthCoreChatCommands // The monster plates' icon size ("debuffs size 150"); your own row's is "self debuffs size". if (!S.TryParseDebuffIconSize(subValue, out int mdi)) { - Reply($"usage: /rv plates debuffs size {S.MinDebuffIconSize}-{S.MaxDebuffIconSize} (percent; now {S.MonsterDebuffIconSize}%)"); + Fail($"Usage: /rv plates debuffs size {S.MinDebuffIconSize}-{S.MaxDebuffIconSize} (percent; now {S.MonsterDebuffIconSize}%)"); return; } S.MonsterDebuffIconSize = mdi; @@ -1357,12 +1433,12 @@ internal static class RynthCoreChatCommands case "kills": case "kill": case "burst": S.NumKills = Flag(subValue, S.NumKills); break; case "restores": case "stamina": case "mana": S.NumRestores = Flag(subValue, S.NumRestores); break; case "size": - if (!TryNum(subValue, out float nsz)) { Reply("usage: /rv plates numbers size 0.5-2.5"); return; } + if (!TryNum(subValue, out float nsz)) { Fail("Usage: /rv plates numbers size 0.5-2.5"); return; } S.NumSize = Math.Clamp(nsz, S.MinNumSize, S.MaxNumSize); break; case "time": case "duration": - if (!TryNum(subValue, out float ntm)) { Reply("usage: /rv plates numbers time 0.5-3"); return; } + if (!TryNum(subValue, out float ntm)) { Fail("Usage: /rv plates numbers time 0.5-3"); return; } S.NumTime = Math.Clamp(ntm, S.MinNumTime, S.MaxNumTime); break; - default: Reply(usage); return; + default: Fail(usage); return; } break; case "gains": @@ -1370,40 +1446,40 @@ internal static class RynthCoreChatCommands switch (sub) { case "size": - if (!TryNum(subValue, out float gsz)) { Reply("usage: /rv plates gains size 0.5-2.5"); return; } + if (!TryNum(subValue, out float gsz)) { Fail("Usage: /rv plates gains size 0.5-2.5"); return; } S.GainSize = Math.Clamp(gsz, S.MinNumSize, S.MaxNumSize); break; case "time": case "duration": - if (!TryNum(subValue, out float gtm)) { Reply("usage: /rv plates gains time 0.5-3"); return; } + if (!TryNum(subValue, out float gtm)) { Fail("Usage: /rv plates gains time 0.5-3"); return; } S.GainTime = Math.Clamp(gtm, S.MinNumTime, S.MaxNumTime); break; case null: S.Gains = Flag(subValue, S.Gains); break; case "xp": S.GainXp = Flag(subValue, S.GainXp); break; case "lum": case "luminance": S.GainLum = Flag(subValue, S.GainLum); break; case "radiance": S.GainRadiance = Flag(subValue, S.GainRadiance); break; - default: Reply(usage); return; + default: Fail(usage); return; } break; case "dist": case "range": - if (!TryNum(value, out float d)) { Reply(usage); return; } + if (!TryNum(value, out float d)) { Fail(usage); return; } S.MaxDistance = Math.Clamp(d, S.MinDistance, S.MaxDistanceLimit); break; case "max": - if (!TryNum(value, out float n)) { Reply(usage); return; } + if (!TryNum(value, out float n)) { Fail(usage); return; } S.MaxPlates = Math.Clamp((int)Math.Round(n), S.MinPlates, S.MaxPlatesLimit); break; case "scale": - if (!TryNum(value, out float sc)) { Reply(usage); return; } + if (!TryNum(value, out float sc)) { Fail(usage); return; } S.Scale = Math.Clamp(sc, S.MinScale, S.MaxScale); break; case "opacity": case "alpha": - if (!TryNum(value, out float o)) { Reply(usage); return; } + if (!TryNum(value, out float o)) { Fail(usage); return; } if (o > 1f) o /= 100f; // "opacity 80" means 80 % S.Opacity = Math.Clamp(o, S.MinOpacity, S.MaxOpacity); break; case "lift": case "height": - if (!TryNum(value, out float h)) { Reply(usage); return; } + if (!TryNum(value, out float h)) { Fail(usage); return; } S.HeightLift = Math.Clamp(h, S.MinLift, S.MaxLift); break; case "npcs": @@ -1412,12 +1488,12 @@ internal static class RynthCoreChatCommands { case null: S.NpcNames = Flag(subValue, S.NpcNames); break; case "dist": case "range": - if (!TryNum(subValue, out float nd)) { Reply("usage: /rv plates npcs dist 5-80"); return; } + if (!TryNum(subValue, out float nd)) { Fail("Usage: /rv plates npcs dist 5-80"); return; } S.NpcMaxDistance = Math.Clamp(nd, S.MinNpcDistance, S.MaxNpcDistanceLimit); break; case "max": - if (!TryNum(subValue, out float nm)) { Reply("usage: /rv plates npcs max 1-40"); return; } + if (!TryNum(subValue, out float nm)) { Fail("Usage: /rv plates npcs max 1-40"); return; } S.MaxNpcLabels = Math.Clamp((int)Math.Round(nm), S.MinNpcLabels, S.MaxNpcLabelsLimit); break; - default: Reply(usage); return; + default: Fail(usage); return; } break; case "portals": @@ -1426,9 +1502,9 @@ internal static class RynthCoreChatCommands { case null: S.PortalNames = Flag(subValue, S.PortalNames); break; case "dist": case "range": - if (!TryNum(subValue, out float pd)) { Reply("usage: /rv plates portals dist 5-120"); return; } + if (!TryNum(subValue, out float pd)) { Fail("Usage: /rv plates portals dist 5-120"); return; } S.PortalMaxDistance = Math.Clamp(pd, S.MinPortalDistance, S.MaxPortalDistanceLimit); break; - default: Reply(usage); return; + default: Fail(usage); return; } break; case "players": @@ -1454,7 +1530,7 @@ internal static class RynthCoreChatCommands Reply("Sample combat numbers, a kill burst and gains spawned around you."); return; default: - Reply(usage); + Fail(usage); return; } @@ -1486,12 +1562,14 @@ internal static class RynthCoreChatCommands string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (parts.Length == 2 && (parts[0].Equals("on", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("off", StringComparison.OrdinalIgnoreCase))) { - Reply(UiHookRegistry.SetEnabled(parts[1], parts[0].Equals("on", StringComparison.OrdinalIgnoreCase))); + string said = UiHookRegistry.SetEnabled(parts[1], parts[0].Equals("on", StringComparison.OrdinalIgnoreCase)); + if (said.StartsWith("No UI hook called", StringComparison.Ordinal)) Fail(said); + else Reply(said); return; } if (parts.Length != 0 && !(parts.Length == 1 && parts[0].Equals("status", StringComparison.OrdinalIgnoreCase))) { - Reply("Usage: /rc hooks [status] | /rc hooks on|off "); + Fail("Usage: /rc hooks [status] | /rc hooks on|off "); return; } foreach (string line in UiHookRegistry.DescribeLines()) @@ -1510,23 +1588,65 @@ internal static class RynthCoreChatCommands { if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.ChatDiscordFace.Title)) { - Reply("The Discord relay needs the RynthChat plugin."); + Fail("The Discord relay needs the RynthChat plugin."); return; } string verb = args.Trim(); if (verb.Equals("window", StringComparison.OrdinalIgnoreCase) || verb.Equals("show", StringComparison.OrdinalIgnoreCase) || verb.Equals("settings", StringComparison.OrdinalIgnoreCase)) { - UI.PanelRouter.Toggle(ImGuiBackend.Panels.ChatDiscordFace.Title); + TogglePanel(ImGuiBackend.Panels.ChatDiscordFace.Title, "Discord relay window", "The Discord relay needs the RynthChat plugin."); return; } - foreach (string line in UI.Data.Discord.ChatDiscord.HandleCommand(verb)) - Reply(line); + ReplyLines(UI.Data.Discord.ChatDiscord.HandleCommand(verb)); } - private static void Reply(string text) + // ── replies (ChatCommandReplies says where each goes and its colour) ───── + + /// It worked, or the state now: in chat (green) for the player, the log only for a script. + private static void Reply(string text) => Reply(text, ChatReplyKind.Ok, ChatCommandReplies.ToChat(ChatReplyKind.Ok, _origin)); + + /// It didn't (the usage, an unknown verb, can't): in chat (red) whoever sent the command. + private static void Fail(string text) => Reply(text, ChatReplyKind.Fail, ChatCommandReplies.ToChat(ChatReplyKind.Fail, _origin)); + + /// when , else as a failure. + private static void Answer(bool ok, string okText, string failText) { - RynthLog.Compat($"RynthCoreChatCommands: {text}"); - AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1); + if (ok) Reply(okText); + else Fail(failText); + } + + /// + /// A module's reply lines as one answer (, or + /// when the caller knows): when it failed every line goes to chat, so a + /// script's failure keeps its context; each line keeps its own colour. + /// + private static void ReplyLines(System.Collections.Generic.IEnumerable lines, ChatReplyKind? kind = null) + { + var list = new System.Collections.Generic.List(lines); + ChatReplyKind all = kind ?? ChatCommandReplies.KindOfLines(list); + bool toChat = ChatCommandReplies.ToChat(all, _origin); + foreach (string l in list) + Reply(l, kind ?? ChatCommandReplies.KindOfLine(l), toChat); + } + + /// The command writes its own answer, now or from AC's thread later (VendorTrade's + /// "[RC]" lines, AcKeymapLive's result): nothing more to say here. + private static void AnswersItself() => _answered = true; + + /// A command that threw: the log (with the type) and chat. + private static void Failed(string command, Exception ex) + { + RynthLog.Compat($"RynthCoreChatCommands: {command} failed - {ex.GetType().Name}: {ex.Message}"); + Fail(ChatCommandReplies.Failed(command, ex.GetType().Name, ex.Message)); + } + + /// The one writer: the log always, chat (AC's main-thread queue) when . + private static void Reply(string text, ChatReplyKind kind, bool toChat) + { + _answered = true; + RynthLog.Compat($"RynthCoreChatCommands: {text}{(toChat ? "" : " (log only: a script's command)")}"); + if (toChat) + AcMainThreadQueue.EnqueueWriteToChat(ChatCommandReplies.ReplyPrefix + text, ChatCommandReplies.ChatType(kind)); } } diff --git a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs index 3ffb5bd..b1a1f59 100644 --- a/src/RynthCore.Engine/Hotkeys/HotkeyService.cs +++ b/src/RynthCore.Engine/Hotkeys/HotkeyService.cs @@ -353,7 +353,8 @@ internal static class HotkeyService if (b.IsCommand) { if (b.Command.Trim().Length == 0) return; - if (!AcMainThreadQueue.EnqueueChatCommand(b.Command.Trim())) + // The player pressed it: a /rc command answers in chat, as typed. + if (!AcMainThreadQueue.EnqueueChatCommand(b.Command.Trim(), ChatCommandOrigin.Player)) Reply("Hotkey: the chat command queue is full; try again."); return; } @@ -386,7 +387,7 @@ internal static class HotkeyService Reply($"Hotkey {b.Combo}: '{a.Name}' has no {a.Param!.ToLowerInvariant()} (edit it in Settings > Hotkeys)."); return; } - if (!AcMainThreadQueue.EnqueueChatCommand(HotkeyActions.ChatFor(a, b))) + if (!AcMainThreadQueue.EnqueueChatCommand(HotkeyActions.ChatFor(a, b), ChatCommandOrigin.Player)) Reply("Hotkey: the chat command queue is full; try again."); return; } diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index 47834c3..42e62bc 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -22,7 +22,10 @@ // nothing out there the margin is 0 and the picture is just the panel. The // window grows by the margin and moves so the panel stays put (LayeredWindow // .Present). Before this, the window was the panel and a tooltip below the -// one-button-high popped-out bar was cut off at its edge. +// one-button-high popped-out bar was cut off at its edge. A tooltip in the +// margin lets clicks through; a menu, or a window of the face's own drawn +// past the panel (RynthAi's dashboard drawers, 2026-10-24), takes them where +// it is drawn (transparent pixels still let them through). // // Threads: everything here runs on AC's main thread, which both renders // (EndScene) and dispatches the game and pop-out WndProcs. No locks. @@ -507,7 +510,8 @@ internal static unsafe class ImGuiPopOuts // a menu). Only a menu there takes clicks; a tooltip lets them through. ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); UpdateMargins(pop, drawData.NativePtr, w, h); - window.MarginsClickThrough = !ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId | ImGuiPopupFlags.AnyPopupLevel); + window.MarginsClickThrough = !ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId | ImGuiPopupFlags.AnyPopupLevel) + && !WindowPastPanel(drawData.NativePtr, pop.OriginX, pop.OriginY, pop.OriginX + w, pop.OriginY + h, pop.DisplayW, pop.DisplayH); int sx = pop.OriginX - pop.MarginL, sy = pop.OriginY - pop.MarginT; int sw = w + pop.MarginL + pop.MarginR, sh = h + pop.MarginT + pop.MarginB; if (drawData.NativePtr != null) @@ -627,46 +631,81 @@ internal static unsafe class ImGuiPopOuts out float x0, out float y0, out float x1, out float y1) { x0 = px0; y0 = py0; x1 = px1; y1 = py1; + if (dd == null) return false; + ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data; + for (int n = 0; n < dd->CmdListsCount; n++) + ListOverflow(lists[n], px0, py0, px1, py1, displayW, displayH, ref x0, ref y0, ref x1, ref y1); + return px0 - x0 > OverflowSlack || py0 - y0 > OverflowSlack || x1 - px1 > OverflowSlack || y1 - py1 > OverflowSlack; + } + + /// + /// A window other than a tooltip draws past the panel: a face's own window (a dashboard's + /// drawers). Popups count too, but IsPopupOpen already says so. ImGui names a tooltip + /// window "##Tooltip_NN" and its draw list after its window. + /// + private static bool WindowPastPanel(ImDrawData* dd, float px0, float py0, float px1, float py1, float displayW, float displayH) + { if (dd == null) return false; ImDrawList** lists = (ImDrawList**)dd->CmdLists.Data; for (int n = 0; n < dd->CmdListsCount; n++) { ImDrawList* list = lists[n]; - if (list == null) continue; - int vtxCount = list->VtxBuffer.Size, idxCount = list->IdxBuffer.Size; - ImDrawVert* vtx = (ImDrawVert*)list->VtxBuffer.Data; - ushort* idx = (ushort*)list->IdxBuffer.Data; - ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data; - for (int c = 0; c < list->CmdBuffer.Size; c++) - { - ImDrawCmd* cmd = &cmds[c]; - if (cmd->UserCallback != IntPtr.Zero || cmd->ElemCount == 0) continue; - float cx0 = Math.Max(cmd->ClipRect.X, 0f), cy0 = Math.Max(cmd->ClipRect.Y, 0f); - float cx1 = Math.Min(cmd->ClipRect.Z, displayW), cy1 = Math.Min(cmd->ClipRect.W, displayH); - if (cx1 <= cx0 || cy1 <= cy0) continue; - if (cx0 >= px0 && cy0 >= py0 && cx1 <= px1 && cy1 <= py1) continue; // can't draw outside the panel - - float vx0 = float.MaxValue, vy0 = float.MaxValue, vx1 = float.MinValue, vy1 = float.MinValue; - long start = cmd->IdxOffset, end = Math.Min((long)idxCount, start + cmd->ElemCount); - long vbase = cmd->VtxOffset; - for (long i = start; i < end; i++) - { - long v = vbase + idx[i]; - if (v >= vtxCount) continue; - Vector2 pos = vtx[v].pos; - if (pos.X < vx0) vx0 = pos.X; - if (pos.Y < vy0) vy0 = pos.Y; - if (pos.X > vx1) vx1 = pos.X; - if (pos.Y > vy1) vy1 = pos.Y; - } - vx0 = Math.Max(vx0, cx0); vy0 = Math.Max(vy0, cy0); - vx1 = Math.Min(vx1, cx1); vy1 = Math.Min(vy1, cy1); - if (vx1 <= vx0 || vy1 <= vy0) continue; - x0 = Math.Min(x0, vx0); y0 = Math.Min(y0, vy0); - x1 = Math.Max(x1, vx1); y1 = Math.Max(y1, vy1); - } + if (list == null || IsTooltipList(list)) continue; + float x0 = px0, y0 = py0, x1 = px1, y1 = py1; + ListOverflow(list, px0, py0, px1, py1, displayW, displayH, ref x0, ref y0, ref x1, ref y1); + if (px0 - x0 > OverflowSlack || py0 - y0 > OverflowSlack || x1 - px1 > OverflowSlack || y1 - py1 > OverflowSlack) + return true; + } + return false; + } + + private static bool IsTooltipList(ImDrawList* list) + { + byte* name = list->_OwnerName; + if (name == null) return false; + ReadOnlySpan prefix = "##Tooltip"u8; + for (int i = 0; i < prefix.Length; i++) + if (name[i] != prefix[i]) return false; + return true; + } + + /// Widens the bounds by what one draw list shows outside the panel (see ). + private static void ListOverflow(ImDrawList* list, float px0, float py0, float px1, float py1, float displayW, float displayH, + ref float x0, ref float y0, ref float x1, ref float y1) + { + if (list == null) return; + int vtxCount = list->VtxBuffer.Size, idxCount = list->IdxBuffer.Size; + ImDrawVert* vtx = (ImDrawVert*)list->VtxBuffer.Data; + ushort* idx = (ushort*)list->IdxBuffer.Data; + ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data; + for (int c = 0; c < list->CmdBuffer.Size; c++) + { + ImDrawCmd* cmd = &cmds[c]; + if (cmd->UserCallback != IntPtr.Zero || cmd->ElemCount == 0) continue; + float cx0 = Math.Max(cmd->ClipRect.X, 0f), cy0 = Math.Max(cmd->ClipRect.Y, 0f); + float cx1 = Math.Min(cmd->ClipRect.Z, displayW), cy1 = Math.Min(cmd->ClipRect.W, displayH); + if (cx1 <= cx0 || cy1 <= cy0) continue; + if (cx0 >= px0 && cy0 >= py0 && cx1 <= px1 && cy1 <= py1) continue; // can't draw outside the panel + + float vx0 = float.MaxValue, vy0 = float.MaxValue, vx1 = float.MinValue, vy1 = float.MinValue; + long start = cmd->IdxOffset, end = Math.Min((long)idxCount, start + cmd->ElemCount); + long vbase = cmd->VtxOffset; + for (long i = start; i < end; i++) + { + long v = vbase + idx[i]; + if (v >= vtxCount) continue; + Vector2 pos = vtx[v].pos; + if (pos.X < vx0) vx0 = pos.X; + if (pos.Y < vy0) vy0 = pos.Y; + if (pos.X > vx1) vx1 = pos.X; + if (pos.Y > vy1) vy1 = pos.Y; + } + vx0 = Math.Max(vx0, cx0); vy0 = Math.Max(vy0, cy0); + vx1 = Math.Min(vx1, cx1); vy1 = Math.Min(vy1, cy1); + if (vx1 <= vx0 || vy1 <= vy0) continue; + x0 = Math.Min(x0, vx0); y0 = Math.Min(y0, vy0); + x1 = Math.Max(x1, vx1); y1 = Math.Max(y1, vy1); } - return px0 - x0 > OverflowSlack || py0 - y0 > OverflowSlack || x1 - px1 > OverflowSlack || y1 - py1 > OverflowSlack; } /// Folds the picture's placement into the draw-data hash. diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs index c0117af..5b5051a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsDrawerBodies.cs @@ -13,7 +13,10 @@ // pinned My settings, the rows the player pinned (QuickSettingsDrawer.cs) // Each is the same drawer the engine's own dashboard shows, so a value changed // here is saved the same way and a pin made here is the same pin. A drawer -// that wasn't drawn in a frame drops its hub subscriptions (EndFrame). +// not drawn for 2 s drops its hub subscriptions (EndFrame). Not "this frame": +// a popped-out dashboard draws at its own rate (30 Hz at most, 10 idle), so a +// drawer there missed most game frames, let its sources go each time and came +// back empty (2026-10-24). // // 2026-10-27: RynthVision draws the whole Vision window itself (it takes over // the engine's VisionFace, "takeOver"), but two of its tabs set things that are @@ -23,8 +26,8 @@ // engine's Vision panel shows (MonsterHudSettingsUi), saved the same way: // nameplates the "Nameplates" tab // combattext the "Combat text" tab -// They draw popped out too (the engine's Vision panel did); the three drawers -// above stay docked-only (UiKit.RenderSettingsDrawer, DrawsPoppedOut). +// They draw popped out too (the engine's Vision panel did), as the three +// drawers above do since 2026-10-24. // // AC thread only (inside RynthAi's or RynthVision's window, and EndFrame after // the panels). @@ -42,8 +45,9 @@ internal static class SettingsDrawerBodies private static RynthAiFace.PatrolDrawer? _patrol; private static QuickSettingsDrawer? _pinned; - // The frame each was last drawn in (EndFrame counts frames). - private static long _frame, _rangesDrawn = -1, _patrolDrawn = -1, _pinnedDrawn = -1; + // When each was last drawn (Environment.TickCount64). + private static long _rangesDrawn = long.MinValue / 2, _patrolDrawn = long.MinValue / 2, _pinnedDrawn = long.MinValue / 2; + private const long KeepMs = 2000; /// /// Draws 's body at the cursor, pixels wide, in at most @@ -65,7 +69,7 @@ internal static class SettingsDrawerBodies case "ranges": { _ranges ??= new RangesSlideOut(); - _rangesDrawn = _frame; + _rangesDrawn = Environment.TickCount64; _ranges.Update(true); float h = RangesSlideOut.BodyHeight(k); ImGuiNET.ImGui.PushID("##sdb_ranges"); @@ -78,7 +82,7 @@ internal static class SettingsDrawerBodies case "patrol": { _patrol ??= new RynthAiFace.PatrolDrawer(); - _patrolDrawn = _frame; + _patrolDrawn = Environment.TickCount64; _patrol.Update(true); RynthAiFace.UseScale(k); float h = room > 0 ? room : 400 * k; @@ -93,7 +97,7 @@ internal static class SettingsDrawerBodies case "pinned": { _pinned ??= new QuickSettingsDrawer(); - _pinnedDrawn = _frame; + _pinnedDrawn = Environment.TickCount64; _pinned.Update(true); float h = room > 0 ? room : 120 * k; float want; @@ -114,9 +118,6 @@ internal static class SettingsDrawerBodies } } - /// True for the bodies that draw in a popped-out window too (the Vision tabs). - public static bool DrawsPoppedOut(string key) => key is "nameplates" or "combattext"; - /// /// A Vision tab RynthVision's window shows (the engine's rows: MonsterHudSettingsUi), in Ui11 as the /// engine's Vision panel drew them. Returns the height drawn. @@ -138,12 +139,12 @@ internal static class SettingsDrawerBodies return MathF.Max(0f, ImGuiNET.ImGui.GetCursorScreenPos().Y - at.Y); } - /// After the panels each frame: a body that wasn't drawn this frame lets its hub sources go. + /// After the panels each frame: a body not drawn for lets its hub sources go. public static void EndFrame() { - if (_ranges != null && _rangesDrawn != _frame) _ranges.Update(false); - if (_patrol != null && _patrolDrawn != _frame) _patrol.Update(false); - if (_pinned != null && _pinnedDrawn != _frame) _pinned.Update(false); - _frame++; + long now = Environment.TickCount64; + if (_ranges != null && now - _rangesDrawn > KeepMs) _ranges.Update(false); + if (_patrol != null && now - _patrolDrawn > KeepMs) _patrol.Update(false); + if (_pinned != null && now - _pinnedDrawn > KeepMs) _pinned.Update(false); } } diff --git a/src/RynthCore.Engine/Net/FlightRecorder.cs b/src/RynthCore.Engine/Net/FlightRecorder.cs index 998a98a..3f2f503 100644 --- a/src/RynthCore.Engine/Net/FlightRecorder.cs +++ b/src/RynthCore.Engine/Net/FlightRecorder.cs @@ -381,8 +381,11 @@ internal static unsafe class FlightRecorder if (rest.Equals("off", StringComparison.OrdinalIgnoreCase)) { _autoOff = true; return new[] { "Automatic flight dumps off for this session." }; } if (rest.Equals("on", StringComparison.OrdinalIgnoreCase)) { _autoOff = false; return new[] { "Automatic flight dumps on." }; } return new[] { "Usage: /rc flight auto on|off" }; - default: + case "status": return StatusLines(); + default: + // A word it doesn't take: the usage, not the status (every command answers a typo so). + return new[] { "Usage: /rc flight [status|mark |on|off|auto on|off]" }; } } diff --git a/src/RynthCore.Engine/Plugins/UiKit.cs b/src/RynthCore.Engine/Plugins/UiKit.cs index 125a6f6..8eedee1 100644 --- a/src/RynthCore.Engine/Plugins/UiKit.cs +++ b/src/RynthCore.Engine/Plugins/UiKit.cs @@ -213,8 +213,10 @@ internal static unsafe class UiKit /// "patrol", "pinned"; SettingsDrawerBodies) at the cursor, pixels wide /// and at most tall (0 = its own height); flags 1: open My settings' list /// of settings to pin. Since 2026-10-27 also the Vision window's engine-owned tabs for RynthVision's - /// own window ("nameplates", "combattext"), which draw popped out too. Returns the height it wants - /// (pixels), -1 for another key or outside a panel's draw on AC's thread (docked, for the drawers). + /// own window ("nameplates", "combattext"). All of them draw popped out too (2026-10-24: RynthAi's + /// popped-out dashboard has its drawers; SettingsDrawerBodies keeps a body's sources between its + /// draws). Returns the height it wants (pixels), -1 for another key or outside a panel's draw on + /// AC's thread. /// public static float RenderSettingsDrawer(byte* key, float width, float room, int flags) { @@ -224,7 +226,6 @@ internal static unsafe class UiKit || !float.IsFinite(width) || !float.IsFinite(room)) return -1f; string? name = Marshal.PtrToStringUTF8((IntPtr)key); if (string.IsNullOrEmpty(name) || name.Length > MaxKeyLength) return -1f; - if (ImGuiPopOuts.InPopOutFrame && !SettingsDrawerBodies.DrawsPoppedOut(name)) return -1f; return SettingsDrawerBodies.Draw(name, width, MathF.Max(0f, room), (flags & 1) != 0); } catch (Exception ex) diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index b44684a..9b39002 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -1137,7 +1137,13 @@ internal static class ChatModel IntPtr send = SendLinePtr; if (text.Length == 0 || send == IntPtr.Zero) return; IntPtr ptr = Marshal.StringToHGlobalAnsi(text); - try { ((delegate* unmanaged[Cdecl])send)(ptr); } + // 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). + try + { + using (RynthCoreChatCommands.PlayerLine()) + ((delegate* unmanaged[Cdecl])send)(ptr); + } finally { Marshal.FreeHGlobal(ptr); } } diff --git a/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs index 40a6899..4a99719 100644 --- a/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs +++ b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs @@ -644,7 +644,7 @@ internal static class ChatDiscord ? $"No route{(rest.Length > 0 ? $" named '{rest}'" : "s")}. Add one in Chat > gear > Discord (or /rc discord window)." : $"{(verb == "test" ? "Test sent to" : "Resumed")} {n} route(s)."); break; - default: + case "status": reply.Add($"Discord relay: {SwitchLine()} {StatusLine()}"); if (s.Characters.Length > 0) reply.Add(" On for: " + string.Join(", ", Array.ConvertAll(s.Characters, c => c.ToString()))); @@ -658,6 +658,10 @@ internal static class ChatDiscord } reply.Add("/rc discord on|off (this character) | window | test [route] | resume [route] | status"); break; + default: + // A word it doesn't take: the usage, not the status (every command answers a typo so). + reply.Add("Usage: /rc discord [on|off|status|window|test [route]|resume [route]]"); + break; } return reply; } diff --git a/src/RynthCore.Engine/UI/ServerMenus.cs b/src/RynthCore.Engine/UI/ServerMenus.cs index 9fe75a9..33e87d0 100644 --- a/src/RynthCore.Engine/UI/ServerMenus.cs +++ b/src/RynthCore.Engine/UI/ServerMenus.cs @@ -74,13 +74,19 @@ internal static class ServerMenus /// /// Runs an item's command: an engine "/rc" command directly, anything else through the - /// chat dispatcher (plugins' commands, as if typed). Render thread. + /// chat dispatcher (plugins' commands, as if typed). Render thread. A click on an engine + /// button or menu is a Script's command: what it opens is the answer, so only a failure + /// reaches chat. /// - public static void Run(string command) + /// Answer in chat as for a typed command: a click whose result the player + /// wants to read (the server window's "Treat this world as ..." prints the server summary). Other + /// clicks stay quiet unless they fail. + public static void Run(string command, bool showReply = false) { string cmd = SectionManifestParser.Command(command); if (cmd.Length == 0) return; - if (Compatibility.RynthCoreChatCommands.TryHandle(cmd)) return; + var origin = showReply ? Compatibility.ChatCommandOrigin.Player : Compatibility.ChatCommandOrigin.Script; + if (Compatibility.RynthCoreChatCommands.TryHandle(cmd, origin)) return; if (cmd.StartsWith("/rc ", StringComparison.OrdinalIgnoreCase)) { RynthLog.UI($"ServerMenus: '{cmd}' is not an engine command."); @@ -255,7 +261,7 @@ internal static class ServerMenus foreach (MenuGroup g in groups) { if (ImGuiNET.ImGui.MenuItem("Treat this world as " + g.Server.Name + "##srvforce_" + g.Server.Id)) - Run(ForceCommand(g.Server.Id)); + Run(ForceCommand(g.Server.Id), showReply: true); SafeImGui.SetItemTooltip("Saved for this character. Undo with /rc server " + g.Server.Id + " auto, or in the Mini Remote's Char section."); } return true; diff --git a/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj b/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj new file mode 100644 index 0000000..550dec1 --- /dev/null +++ b/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj @@ -0,0 +1,28 @@ + + + + + Exe + net10.0 + enable + enable + true + ChatCommandReplyTests + + + + + + + + + diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs new file mode 100644 index 0000000..d888bc8 --- /dev/null +++ b/tools/ChatCommandReplyTests/Program.cs @@ -0,0 +1,388 @@ +using System.Text.RegularExpressions; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Hotkeys; + +namespace ChatCommandReplyTests; + +/// +/// How the engine's chat commands answer (ChatCommandReplies.cs) without AC: every /rc verb with a +/// valid and an invalid form, where each reply goes and its colour, the reply texts, and a read of +/// RynthCoreChatCommands.cs so the verb list can't drift from TryHandle. The dispatcher needs the +/// live engine (panels, settings, AC), so the decision before a command runs is what is tested. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + WhereRepliesGo(); + EveryVerbValidAndInvalid(); + HandlerVerbsPassThrough(); + UnknownAndBare(); + ModuleLinesClassified(); + ParsersShared(); + ReplyTexts(); + SourceMatchesCatalog(); + ChatBurst(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL CHAT COMMAND REPLY TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + // ── where a reply goes ────────────────────────────────────────────────── + + private static void WhereRepliesGo() + { + Case("where a reply goes, and its colour"); + Check(ChatCommandReplies.ToChat(ChatReplyKind.Ok, ChatCommandOrigin.Player), "the player's success: chat"); + Check(ChatCommandReplies.ToChat(ChatReplyKind.Fail, ChatCommandOrigin.Player), "the player's failure: chat"); + Check(!ChatCommandReplies.ToChat(ChatReplyKind.Ok, ChatCommandOrigin.Script), "a script's success: the log only"); + Check(ChatCommandReplies.ToChat(ChatReplyKind.Fail, ChatCommandOrigin.Script), "a script's failure: chat"); + Check(ChatCommandReplies.Effective(ChatCommandOrigin.Script, insidePlayerLine: true) == ChatCommandOrigin.Player, + "a plugin's line while it handles one the player typed is the player's"); + Check(ChatCommandReplies.Effective(ChatCommandOrigin.Script, insidePlayerLine: false) == ChatCommandOrigin.Script, "a plugin's own line is a script's"); + Check(ChatCommandReplies.Effective(ChatCommandOrigin.Player, insidePlayerLine: false) == ChatCommandOrigin.Player, "typed stays the player's"); + Check(default(ChatCommandOrigin) == ChatCommandOrigin.Script, "the default (an unset [ThreadStatic]) is a script's"); + Check(ChatCommandReplies.ChatType(ChatReplyKind.Ok) == 1, "success: chat type 1 (green), as every reply before"); + Check(ChatCommandReplies.ChatType(ChatReplyKind.Fail) == 0x1A, "failure: 0x1A, AC's own command-notice red"); + Check(ChatCommandReplies.ReplyPrefix == "[RynthCore] ", "the prefix is unchanged"); + } + + // ── every verb: a valid and an invalid form ──────────────────────────── + + /// Verbs whose arguments are checked before they run: (form that runs, form answered with the usage). + private static readonly (string Verb, string Valid, string Invalid)[] Checked = + { + ("imgui", "imgui on", "imgui frob"), + ("imgui", "imgui", "imgui on off"), + ("chathold", "chathold status", "chathold frob"), + ("ilt", "ilt auto", "ilt frob"), + ("worldlayer", "worldlayer uipass", "worldlayer frob"), + ("acmouse", "acmouse watch 30", "acmouse frob"), + ("acmouse", "mouseover", "mouseover frob"), + ("vtank", "vtank clear", "vtank frob"), + ("bounties", "bounties show", "bounties frob"), + ("bounties", "bounty", "bountys frob"), + ("guardian", "guardian hide", "guardians frob"), + ("dashboard", "dashboard tab loot", "dashboard tab frob"), + ("dashboard", "dashboard classic", "dashboard frob"), + ("dashboard", "dashboard", "dashboard modern now"), + ("miniremote", "miniremote section map", "miniremote frob"), + ("miniremote", "remote toggle", "remote frob"), + ("miniremote", "miniremote tab pets", "miniremote shows"), + ("oracle-skills", "oracle-skills attrs", "oracle-skills frob"), + ("oracle-skills", "oracle-skills off", "oracle-skills"), + ("skills", "skills toggle", "skills frob"), + ("progression", "progression", "progression now"), + ("progression", "progress", "progress now"), + ("spells", "spells show", "spells frob"), + ("diagnostics", "diagnostics", "diagnostics now"), + ("diagnostics", "serverpick", "serverpick now"), + ("shortcuts", "shortcuts use 5", "shortcuts use five"), + ("shortcuts", "shortcuts", "shortcuts frob"), + ("shortcuts", "shortcuts set 3 0x50000001", "shortcuts set"), + ("shortcuts", "shortcuts clear 18", "shortcuts clear"), + ("keymap", "keymap bind UseQuickSlot_10 F11", "keymap bind F11"), + ("keymap", "keymap check /ra start Ctrl+F1", "keymap frob"), + ("keymap", "keymap dump", "keymap unbind"), + ("keymap", "keymap", "keymap check x"), + ("panels", "panels open 0x1F", "panels open"), + ("panels", "panels toggle 12", "panels open twelve"), + ("panels", "panels", "panels open 1 2"), + ("rl", "rl", "rl now"), + ("rl", "reload", "reload now"), + ("inventory", "inv", "inv now"), + ("inventory", "inventory", "inventory now"), + ("sense", "sense", "sense now"), + ("characters", "chars", "characters now"), + ("itemcount", "itemhud", "itemcount now"), + ("resetbar", "barreset", "resetbar now"), + ("actionstate", "actions", "actionstate now"), + ("unlockactions", "unlock", "unlockactions now"), + ("vitals", "hud", "vitals now"), + }; + + private static void EveryVerbValidAndInvalid() + { + Case("every checked verb: the valid form runs, the invalid one gets the usage"); + foreach (var (verb, valid, invalid) in Checked) + { + ChatVerbCheck ok = ChatCommandReplies.Check(valid); + Check(ok.Problem == null && ok.Verb?.Name == verb, $"'/rc {valid}' runs as {verb} (got {ok.Verb?.Name ?? "unknown"}: {ok.Problem})"); + ChatVerbCheck bad = ChatCommandReplies.Check(invalid); + Check(bad.Verb?.Name == verb && bad.Problem != null && bad.Problem == bad.Verb.Usage, + $"'/rc {invalid}' answers with {verb}'s usage (got {bad.Problem ?? "no reply"})"); + Check(bad.Problem != null && bad.Problem.StartsWith("Usage: /rc ", StringComparison.Ordinal), + $"'/rc {invalid}': the reply is a usage line"); + Check(ChatCommandReplies.KindOfLine(bad.Problem ?? "") == ChatReplyKind.Fail, $"'/rc {invalid}': a failure (red, and shown to a script too)"); + } + + Case("every verb in the list has a valid and an invalid form here"); + var covered = new HashSet(Checked.Select(c => c.Verb)); + foreach (var h in Handled) covered.Add(h.Verb); + foreach (ChatVerb v in ChatCommandReplies.Verbs) + { + Check(covered.Contains(v.Name), $"{v.Name} is tested"); + Check(v.Usage.StartsWith("Usage: /r", StringComparison.Ordinal) && v.Usage.Length > 12, $"{v.Name} has a usage line"); + Check(v.Usage.Contains(v.Name, StringComparison.OrdinalIgnoreCase), $"{v.Name}'s usage names it"); + } + } + + /// + /// Verbs whose own handler checks the arguments (Args null): the check before they run lets the + /// invalid form through, and the handler or module answers with its usage (Who), in red because + /// the line starts "Usage" (ModuleLinesClassified) or is the parser's error (hotkey). + /// + private static readonly (string Verb, string Valid, string Invalid, string Who)[] Handled = + { + ("vendor", "vendor list", "vendor frob", "VendorTrade: '[RC] /rc vendor list | info | ...'"), + ("ui", "ui list", "ui frob", "HandleUiCommand: its usage"), + ("discord", "discord status", "discord frob", "ChatDiscord.HandleCommand: its usage"), + ("plates", "plates status", "plates frob", "HandlePlatesCommand: the plates usage"), + ("plates", "nameplates off", "nameplates frob", "HandlePlatesCommand: the plates usage"), + ("server", "server ilt auto", "server a b c", "HandleServerCommand: the server usage"), + ("mastery", "mastery", "mastery", "HandleMasteryCommand (takes no arguments; ignores any, as before)"), + ("video", "video world", "video frob", "VideoPatch.HandleCommand: its usage"), + ("video", "videopatch fps 30", "videopatch fps x", "VideoPatch.HandleCommand: the fps usage"), + ("hooks", "hooks status", "hooks frob", "HandleHooksCommand: its usage"), + ("hooks", "uihooks off Tooltip", "uihooks on", "HandleHooksCommand: its usage"), + ("flightdump", "flightdump before the wall", "flightdump", "FlightRecorder (any text is the note)"), + ("quit", "quit", "exit", "closes the client (takes no arguments)"), + ("report", "report the map froze", "report", "ProblemReport (alone: opens the panel)"), + ("flight", "flight mark here", "flight frob", "FlightRecorder.HandleCommand: its usage"), + ("autoid", "autoid limited", "autoid frob", "AutoIdService.HandleCommand: its usage"), + ("netmsg", "netmsg log on", "netmsg frob", "ServerMessageStream.HandleCommand: its usage"), + ("hotkeys", "hotkeys", "hotkeys frob", "HotkeyCommandParser: unknown verb + usage"), + ("settings", "settings Hotkeys", "settings frob", "SettingsCommand: no tab called 'frob' (tabs: ...)"), + ("hotkey", "hotkey list", "hotkey frob", "HotkeyCommandParser: unknown verb + usage"), + ("hotkey", "hotkey add F5 /ra start", "hotkey add F5", "HotkeyCommandParser: the add usage"), + }; + + private static void HandlerVerbsPassThrough() + { + Case("verbs that check their own arguments: both forms reach the handler"); + foreach (var (verb, valid, invalid, who) in Handled) + { + ChatVerbCheck ok = ChatCommandReplies.Check(valid); + Check(ok.Problem == null && ok.Verb?.Name == verb, $"'/rc {valid}' runs as {verb}"); + ChatVerbCheck bad = ChatCommandReplies.Check(invalid); + Check(bad.Problem == null && bad.Verb?.Name == verb, $"'/rc {invalid}' reaches {verb}'s handler, which answers: {who}"); + } + + Case("the /rc hotkey parser answers every invalid form (compiled in)"); + foreach (string args in new[] { "frob", "add F5", "add NotAKey /ra start", "remove", "enable", "add F5 notanaction" }) + { + HotkeyCommand c = HotkeyCommandParser.Parse(args); + Check(c.Verb == HotkeyVerb.Error && c.Error.Length > 0, $"'/rc hotkey {args}': {c.Error}"); + } + foreach (string args in new[] { "", "list", "add F5 /ra start", "remove F5", "on", "off", "status", "actions" }) + Check(HotkeyCommandParser.Parse(args).Verb != HotkeyVerb.Error, $"'/rc hotkey {args}' runs"); + } + + private static void UnknownAndBare() + { + Case("unknown verbs and a bare /rc answer with the command list"); + ChatVerbCheck unknown = ChatCommandReplies.Check("frobnicate now"); + Check(unknown.Verb == null && unknown.Problem != null && unknown.Problem.StartsWith("Unknown command '/rc frobnicate'", StringComparison.Ordinal), + $"an unknown verb says so: {unknown.Problem}"); + Check(ChatCommandReplies.KindOfLine(unknown.Problem ?? "") == ChatReplyKind.Fail, "and is a failure"); + foreach (ChatVerb v in ChatCommandReplies.Verbs) + Check(unknown.Problem!.Contains(v.Name, StringComparison.Ordinal), $"the list names {v.Name}"); + ChatVerbCheck bare = ChatCommandReplies.Check(""); + Check(bare.Verb == null && bare.Problem != null && bare.Problem.StartsWith("Usage: /rc .", StringComparison.Ordinal), "'/rc' alone: the usage and the list"); + Check(ChatCommandReplies.Check("window save").Problem!.StartsWith("Unknown command '/rc window'", StringComparison.Ordinal), + "'/rc window save' (sent by /ub window save) is not an engine verb, and now says so"); + Check(ChatCommandReplies.Check(" SKILLS Show ").Problem == null, "case and spaces as IsVerb takes them"); + } + + private static void ModuleLinesClassified() + { + Case("module reply lines: failures and state"); + string[] fails = + { + "Usage: /rc video fps <0|5-60> (now none).", + "Usage: /rc autoid [all|limited|off] (alone: status)", + "usage: /rv plates numbers size 0.5-2.5", + "Video patch unavailable: no hook.", + "Video patch is switched off (/rc hooks on VideoPatch to switch it back on).", + "Flight recorder is off.", + "Not dumped: the last automatic dump was 10 s ago (one per 5 min).", + "Not capturing.", + "Capture failed: access denied", + "The server message stream is off; /rc netmsg on first (engine.json must allow it).", + "Report not sent: one report a minute.", + "The Report a problem panel isn't available (the ImGui layer is off?). Use /rc report to send one from chat.", + "Log in first: the relay is switched on or off for the character you're playing.", + "The relay is off: /rc discord on, or use Send test in the Discord panel (/rc discord window).", + "No route named 'x'. Add one in Chat > gear > Discord (or /rc discord window).", + "Unknown '/rc hotkey frob'. Usage: ...", + "No hotkey on F5.", + "Unlock skipped: not on the game thread.", + "Can't: no AC panel functions", + }; + foreach (string f in fails) + Check(ChatCommandReplies.KindOfLine(f) == ChatReplyKind.Fail, $"failure: {f}"); + string[] oks = + { + "Video patch: WORLD - AC's 3D world isn't drawn; AC's UI and the panels are. /rc video off to restore.", + "Flight recorder: recording, 120 entries recorded", + "Flight recorder paused for this session (/rc flight on resumes).", + "Automatic flight dumps on.", + "AutoId: limited (selected target; ...). Saved in engine.json.", + "Server message log off.", + "Hotkeys on.", + "No hotkeys. Add one in Settings > Hotkeys (/rc hotkeys) or with /rc hotkey add .", + "Hotkey added: F5 - /ra start.", + "Sending your report (with your recent RynthCore log; use the panel, /rc report, to leave the log out)...", + "Discord relay on for Someone. 2 routes.", + "Action state (what the client checks before a use, equip or move):", + "Unlock queued for the next game tick.", + }; + foreach (string o in oks) + Check(ChatCommandReplies.KindOfLine(o) == ChatReplyKind.Ok, $"state: {o}"); + Check(ChatCommandReplies.KindOfLines(new[] { "Video patch: off - normal drawing.", "Usage: /rc video fps <0|5-60>" }) == ChatReplyKind.Fail, + "one failing line makes the answer a failure (all of it then reaches a script's chat)"); + Check(ChatCommandReplies.KindOfLines(Array.Empty()) == ChatReplyKind.Ok, "no lines: not a failure"); + } + + private static void ParsersShared() + { + Case("the parsers the dispatcher and the check share"); + Check(ChatCommandReplies.IsVerb("skills show", "skills", out string a) && a == "show", "IsVerb: verb and args"); + Check(ChatCommandReplies.IsVerb("SKILLS", "skills", out a) && a == "", "IsVerb: case, no args"); + Check(!ChatCommandReplies.IsVerb("skillset", "skills", out _), "IsVerb: a longer word is another verb"); + Check(!ChatCommandReplies.IsVerb("flightdump x", "flight", out _), "IsVerb: flight is not flightdump"); + foreach (var (args, want) in new (string, bool?)[] { ("", null), ("toggle", null), ("show", true), ("on", true), ("open", true), ("hide", false), ("off", false), ("close", false) }) + Check(ChatCommandReplies.TryPanelMode(args, out bool? show) && show == want, $"TryPanelMode '{args}'"); + Check(!ChatCommandReplies.TryPanelMode("frob", out _), "TryPanelMode: anything else is wrong"); + Check(ChatCommandReplies.OracleSkillsTab("skills") == 0 && ChatCommandReplies.OracleSkillsTab("attributes") == 1 + && ChatCommandReplies.OracleSkillsTab("progression") == 2 && ChatCommandReplies.OracleSkillsTab("none") == -1 + && ChatCommandReplies.OracleSkillsTab("frob") == ChatCommandReplies.InvalidTab, "oracle-skills tabs"); + Check(ChatCommandReplies.ClassicTab("LOOT") == 5 && ChatCommandReplies.ClassicTab("frob") == -1, "the Classic tabs by name"); + Check(ChatCommandReplies.TryPanelId("0x1F", out uint id) && id == 0x1F && ChatCommandReplies.TryPanelId("12", out id) && id == 12 + && !ChatCommandReplies.TryPanelId("twelve", out _), "AC panel ids: decimal or 0x hex"); + } + + private static void ReplyTexts() + { + Case("reply texts"); + Check(ChatCommandReplies.PanelReply("Inventory panel", null, wasOpen: false) == "Inventory panel opened.", "toggle a closed panel"); + Check(ChatCommandReplies.PanelReply("Inventory panel", null, wasOpen: true) == "Inventory panel closed.", "toggle an open panel"); + Check(ChatCommandReplies.PanelReply("Mini Remote", true, wasOpen: false) == "Mini Remote opened.", "show a closed panel"); + Check(ChatCommandReplies.PanelReply("Mini Remote", true, wasOpen: true) == "Mini Remote is already open.", "show an open panel"); + Check(ChatCommandReplies.PanelReply("Bounties panel", false, wasOpen: false) == "Bounties panel is already closed.", "hide a closed panel"); + Check(ChatCommandReplies.PanelReply("Bounties panel", false, wasOpen: true) == "Bounties panel closed.", "hide an open panel"); + Check(ChatCommandReplies.SettingsTabReply("Hotkeys", false) == "Settings opened on Hotkeys.", "Settings opened on a tab"); + Check(ChatCommandReplies.SettingsTabReply("Hotkeys", true) == "Settings switched to Hotkeys.", "Settings switched tab"); + Check(ChatCommandReplies.DashboardReply(true, "loot", true) == "RynthAi dashboard: Classic look, loot tab.", "dashboard tab"); + Check(ChatCommandReplies.DashboardReply(false, null, false) == "RynthAi dashboard: Modern look (RynthAi's dashboard isn't loaded, so nothing opened).", "dashboard without RynthAi"); + for (int t = -1; t <= 2; t++) + Check(ChatCommandReplies.OracleSkillsReply(t).StartsWith("RynthOracle's window shows", StringComparison.Ordinal), $"oracle-skills {t}"); + Check(ChatCommandReplies.Failed("/rc vendor", "NullReferenceException", "x") == "/rc vendor failed: NullReferenceException: x (the RynthCore log has more).", "a thrown command"); + Check(ChatCommandReplies.Done("/rc sense") == "/rc sense: done.", "the gap filler"); + Check(ChatCommandReplies.CommandName("/rc vendor buy 1") == "/rc vendor" && ChatCommandReplies.CommandName("/rc") == "/rc" + && ChatCommandReplies.CommandName("/rv plates self on") == "/rv plates", "a command's name in a reply"); + } + + // ── the source: catalog and TryHandle in step, one writer ────────────── + + private static void SourceMatchesCatalog() + { + Case("RynthCoreChatCommands.cs: the verbs TryHandle routes are the catalog's, both ways"); + string? path = FindRepoFile(Path.Combine("src", "RynthCore.Engine", "Compatibility", "RynthCoreChatCommands.cs")); + Check(path != null, "found RynthCoreChatCommands.cs by walking up"); + if (path == null) return; + string src = File.ReadAllText(path); + int start = src.IndexOf("private static void Handle(string trimmed)", StringComparison.Ordinal); + int end = src.IndexOf("private static void HandleUiCommand", StringComparison.Ordinal); + Check(start > 0 && end > start, "found Handle()"); + if (start < 0 || end < start) return; + string handle = src.Substring(start, end - start); + + var routed = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (Match m in Regex.Matches(handle, @"IsVerb\(sub, ""([^""]+)""")) + routed.Add(m.Groups[1].Value); + int sw = handle.IndexOf("switch (sub.ToLowerInvariant())", StringComparison.Ordinal); + Check(sw > 0, "found the no-argument switch"); + if (sw > 0) + foreach (Match m in Regex.Matches(handle.Substring(sw), @"case ""([a-z-]+)"":")) + routed.Add(m.Groups[1].Value); + Check(routed.Count >= 60, $"read {routed.Count} spellings from Handle()"); + + var listed = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (ChatVerb v in ChatCommandReplies.Verbs) + { + listed.Add(v.Name); + foreach (string al in v.Aliases) listed.Add(al); + } + foreach (string r in routed) + Check(listed.Contains(r), $"'{r}' (routed in Handle) is in ChatCommandReplies.Verbs, so it isn't answered as unknown"); + foreach (string l in listed) + Check(routed.Contains(l), $"'{l}' (in the list) is routed in Handle"); + + Case("RynthCoreChatCommands.cs: every reply goes through the one writer"); + Check(Regex.Matches(src, @"EnqueueWriteToChat\(").Count == 1, "one EnqueueWriteToChat (the writer in Reply)"); + Check(!Regex.IsMatch(src, @"\bReply\(\$?""[Uu]sage"), "no usage line is written as a success (they go through Fail)"); + Check(!Regex.IsMatch(src, @"\bReply\((usage|ServerUsage)\)"), "nor the usage constants"); + Check(!Regex.IsMatch(src, @"catch \(Exception ex\) \{ RynthLog\.Compat"), "no command's exception is only logged"); + } + + private static string? FindRepoFile(string relative) + { + string? dir = AppContext.BaseDirectory; + while (dir != null) + { + string candidate = Path.Combine(dir, relative); + if (File.Exists(candidate)) return candidate; + dir = Path.GetDirectoryName(dir); + } + return null; + } + + // ── the chat rate limit (ChatRateLimiter, 2026-10-28) ────────── + + private static void ChatBurst() + { + Case("plugin chat: a burst of 12 lines goes at once, then one per 100 ms"); + var r = new ChatRateLimiter(); + int sent = 0; + for (int i = 0; i < 20; i++) if (r.TryTake(1000)) sent++; + Check(sent == 12, $"a 20-line reply at one moment: 12 go (got {sent})"); + Check(!r.TryTake(1050), "50 ms later: still spent"); + Check(r.TryTake(1100), "100 ms later: one more"); + Check(!r.TryTake(1100), "and only one"); + int steady = 0; + for (long t = 1200; t <= 3100; t += 100) if (r.TryTake(t)) steady++; + Check(steady == 20, $"one a line every 100 ms keeps going (20 of 20, got {steady})"); + var idle = new ChatRateLimiter(); + idle.TryTake(1000); + int after = 0; + for (int i = 0; i < 30; i++) if (idle.TryTake(60_000)) after++; + Check(after == 12, $"a long quiet spell refills to 12, no more (got {after})"); + var back = new ChatRateLimiter(); + for (int i = 0; i < 12; i++) back.TryTake(5000); + Check(!back.TryTake(4000), "a clock that went backwards refills nothing"); + int spam = 0; + var loop = new ChatRateLimiter(); + for (long t = 0; t < 1000; t += 5) if (loop.TryTake(10_000 + t)) spam++; + Check(spam <= 22, $"a retry loop sending every 5 ms for 1 s: at most 12 + 10 (got {spam})"); + } + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"-- {name}"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } +} diff --git a/tools/ChatHistoryBench/ChatHistoryBench.csproj b/tools/ChatHistoryBench/ChatHistoryBench.csproj index 293e2a6..23151d7 100644 --- a/tools/ChatHistoryBench/ChatHistoryBench.csproj +++ b/tools/ChatHistoryBench/ChatHistoryBench.csproj @@ -60,6 +60,12 @@ + + + + +