diff --git a/docs/design/design-tokens.md b/docs/design/design-tokens.md index c1130b4..6e228ff 100644 --- a/docs/design/design-tokens.md +++ b/docs/design/design-tokens.md @@ -65,20 +65,33 @@ Index → hex. This **is** `AnsiColor.Indexed(0..15)`: xterm-256: indices 16–231 are the 6×6×6 cube, 232–255 the grayscale ramp — computed by the standard xterm formula (the prototype shows representative -samples). The renderer maps any `AnsiColor.Indexed(n)` for `n` in 0–255. - -## Styled-segment render contract - -Maps `StyledSegment` (`TextStyle` = fg/bg/bold/underline/inverse) to a rendered -span. Equivalent to the prototype's `runStyle`: - -- Default foreground (no fg set) → `--pho` (`#c4d1c8`); default background → - transparent (the `--outbg` shows through). -- `Foreground = Indexed(n)` → palette/cube hex; `Background = Indexed(n)` → - hex + small horizontal padding (`0 2px`). -- **Inverse**: swap — foreground becomes `--outbg`, background becomes the - segment's foreground colour (or `--pho` if none). -- **Bold** → font-weight 700. **Underline** → `text-decoration: underline`. +samples). `OutputPalette` holds these sixteen; the cube and ramp are xterm's. + +## Output render contract + +Server output is decoded by MarkupString (`OutputDecoder`) and written as +MarkupString's HTML (`OutputHtml`); `OutputView` shows each line and attaches +`MarkupString.Web`'s script, whose stylesheet (`markupstring.css`) the hosts +load before `app.css`. Equivalent to the prototype's `runStyle`: + +- Default foreground (no fg set) → no inline colour, so `.sc-line`'s `--pho` + (`#c4d1c8`) shows; default background → transparent (the `--outbg` shows + through). +- The sixteen standard colours are written as `var(--ms-ansi-N, …)`; + `OutputView` sets `--ms-ansi-0` to `--ms-ansi-15` from `OutputPalette`. + Other palette colours and truecolour are written as sent. A span with a + background also gets a small horizontal padding (`0 2px`). +- **Inverse**: swap — foreground becomes `--ms-bg` (`--outbg`), background + becomes the span's foreground colour, or `--ms-fg` (`--pho`) if none. +- **Bold**, **faint**, **italic**, **underline**, **overline**, + **strikethrough**, **blink**, **conceal** → `ms-*` classes from + `markupstring.css`; blink stops under reduced motion. +- Command links are `a.ms-cmd-link[xch_cmd]` and web links `a[href]`, in the + accent colour unless the server coloured them; an MXP menu is `.ms-menu`, and + the script opens its choices in a popup. The script calls back into + `OutputView` to send a command; clears and panes are not acted on. +- A Highlight trigger wraps the line in `span.sc-highlight`, whose + `--sc-highlight` colour overrides the server's. - Glow (when enabled): `text-shadow: 0 0 6px rgba(150,210,170,.28)` on the feed. ## Connection-state palette (drives tabs, pills, dots) diff --git a/src/SharpClient.App/SharpClient.App.csproj b/src/SharpClient.App/SharpClient.App.csproj index c185067..4206811 100644 --- a/src/SharpClient.App/SharpClient.App.csproj +++ b/src/SharpClient.App/SharpClient.App.csproj @@ -119,7 +119,7 @@ 4.6.1: SendNAWS moved to NAWSProtocol.SendWindowSizeAsync, the client names itself only through WithClientIdentity (TelnetConnection sets it), and FSharp.Core is gone, so AOT and trimming can be turned back on once a trimmed APK is checked on a device. --> - + diff --git a/src/SharpClient.App/wwwroot/index.html b/src/SharpClient.App/wwwroot/index.html index b3ca941..2c0e07c 100644 --- a/src/SharpClient.App/wwwroot/index.html +++ b/src/SharpClient.App/wwwroot/index.html @@ -6,6 +6,7 @@ SharpClient.App + diff --git a/src/SharpClient.Core/Connection/TelnetConnection.cs b/src/SharpClient.Core/Connection/TelnetConnection.cs index 25e300a..c6a37da 100644 --- a/src/SharpClient.Core/Connection/TelnetConnection.cs +++ b/src/SharpClient.Core/Connection/TelnetConnection.cs @@ -41,7 +41,7 @@ public sealed class TelnetConnection : ITelnetConnection private static readonly TimeSpan TlsHandshakeTimeout = TimeSpan.FromSeconds(20); // TNC names nobody unless told to: without this, TTYPE answers UNKNOWN and NEW-ENVIRON sends no - // CLIENT_NAME. MTTS claims what AnsiParser renders: 16, 256 and 24-bit colour over UTF-8. + // CLIENT_NAME. MTTS claims what the output view draws: 16, 256 and 24-bit colour over UTF-8. private static ClientIdentity Identity { get; } = new("SharpClient") { TerminalType = "XTERM", diff --git a/src/SharpClient.Core/Rendering/AnsiColor.cs b/src/SharpClient.Core/Rendering/AnsiColor.cs deleted file mode 100644 index 9a9a2c2..0000000 --- a/src/SharpClient.Core/Rendering/AnsiColor.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace SharpClient.Core.Rendering; - -public enum AnsiColorKind -{ - Default, - Indexed, - - /// 24-bit colour (SGR 38;2 / 48;2). holds 0xRRGGBB. - Rgb, -} - -public readonly record struct AnsiColor(AnsiColorKind Kind, int Index) -{ - public static AnsiColor Default => new(AnsiColorKind.Default, 0); - - public static AnsiColor Indexed(int index) => new(AnsiColorKind.Indexed, index); - - public static AnsiColor Rgb(int r, int g, int b) => - new(AnsiColorKind.Rgb, (Math.Clamp(r, 0, 255) << 16) | (Math.Clamp(g, 0, 255) << 8) | Math.Clamp(b, 0, 255)); -} diff --git a/src/SharpClient.Core/Rendering/AnsiPalette.cs b/src/SharpClient.Core/Rendering/AnsiPalette.cs deleted file mode 100644 index b43add2..0000000 --- a/src/SharpClient.Core/Rendering/AnsiPalette.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace SharpClient.Core.Rendering; - -public static class AnsiPalette -{ - // Shared across the Rendering layer — SegmentStyle references this rather than duplicating. - internal const string PhosphorDefault = "#c4d1c8"; - - private static readonly string[] Base16 = - [ - "#3a3f4b", "#e06c75", "#8fc16f", "#e5c07b", "#61afef", "#c678dd", "#56b6c2", "#abb2bf", - "#5c6672", "#ff8088", "#b5e890", "#ffd596", "#7cc4ff", "#e29bf0", "#6fd3df", "#e8edf2", - ]; - - private static readonly int[] CubeSteps = [0, 95, 135, 175, 215, 255]; - - public static string ToHex(int index) - { - if (index is >= 0 and < 16) - { - return Base16[index]; - } - - if (index is >= 16 and <= 231) - { - var n = index - 16; - var r = CubeSteps[n / 36 % 6]; - var g = CubeSteps[n / 6 % 6]; - var b = CubeSteps[n % 6]; - return Rgb(r, g, b); - } - - if (index is >= 232 and <= 255) - { - var v = 8 + (index - 232) * 10; - return Rgb(v, v, v); - } - - return PhosphorDefault; - } - - private static string Rgb(int r, int g, int b) => - $"#{r:x2}{g:x2}{b:x2}"; -} diff --git a/src/SharpClient.Core/Rendering/AnsiParser.cs b/src/SharpClient.Core/Rendering/AnsiParser.cs deleted file mode 100644 index b0407d3..0000000 --- a/src/SharpClient.Core/Rendering/AnsiParser.cs +++ /dev/null @@ -1,591 +0,0 @@ -using System.Text; - -namespace SharpClient.Core.Rendering; - -public static class AnsiParser -{ - private const char Escape = '\e'; - - public static IReadOnlyList Parse(string line, MxpParserState? mxp = null) - { - var segments = new List(); - var text = new StringBuilder(); - var style = TextStyle.Default; - var index = 0; - - // Pending command-link metadata, carried onto every segment flushed while a - // / link is open (so SGR changes inside a link stay clickable). - string? pendingCommand = null; - string? pendingHint = null; - var inSend = false; - var sendShorthand = false; - var inAnchor = false; - - void Flush() - { - if (text.Length == 0) - { - return; - } - - segments.Add(new StyledSegment(text.ToString(), style) - { - Command = pendingCommand, - Hint = pendingHint, - }); - text.Clear(); - } - - void AddImage(string? url, string label) - { - if (url is null) - { - return; - } - - Flush(); - segments.Add(new StyledSegment(label, style) - { - ImageUrl = url, - Command = pendingCommand, - Hint = pendingHint, - }); - } - - void HandleTag(string raw) - { - var body = raw.Trim(); - var isClose = body.StartsWith('/'); - if (isClose) - { - body = body[1..].TrimStart(); - } - - var sp = body.IndexOfAny([' ', '\t']); - var name = (sp < 0 ? body : body[..sp]).ToLowerInvariant(); - var attrs = sp < 0 ? string.Empty : body[(sp + 1)..]; - - if (!isClose) - { - if (name == "send" && mxp!.IsMxpActive) - { - // Secure elements are only honoured on a Secure line; otherwise the - // tag is stripped and its inner text flows through as plain text. - if (mxp.IsSecure) - { - Flush(); - var href = GetAttr(attrs, "href"); - pendingHint = GetAttr(attrs, "hint"); - if (href is not null) - { - pendingCommand = href; - sendShorthand = false; - } - else - { - pendingCommand = null; - sendShorthand = true; // inner text becomes the command at - } - - inSend = true; - } - } - else if (name == "a" && mxp!.IsPuebloActive) - { - var cmd = GetAttr(attrs, "xch_cmd"); - if (cmd is not null) - { - Flush(); - pendingCommand = cmd; - pendingHint = GetAttr(attrs, "xch_hint"); - inAnchor = true; - } - } - else if (name == "image" && mxp!.IsMxpActive && mxp.IsSecure) - { - // IMAGE is not an open tag, so like SEND it needs a Secure line. - var fileName = GetAttr(attrs, "fname") ?? FirstPositional(attrs); - var url = fileName is null - ? null - : ImageSource.ResolveMxp(fileName, GetAttr(attrs, "url"), GetAttr(attrs, "t")); - AddImage(url, ImageSource.DisplayName(fileName)); - } - else if (name == "img" && mxp!.IsPuebloActive) - { - // is Pueblo's mode switch, not a picture: it has no src. - var src = GetAttr(attrs, "src"); - AddImage(src is null ? null : ImageSource.ResolvePueblo(src), GetAttr(attrs, "alt") ?? ImageSource.DisplayName(src)); - } - // Any other tag (or a non-command anchor) is stripped silently. - } - else - { - if (name == "send" && inSend) - { - if (sendShorthand && pendingCommand is null) - { - pendingCommand = text.ToString(); - } - - Flush(); - pendingCommand = null; - pendingHint = null; - inSend = false; - sendShorthand = false; - } - else if (name == "a" && inAnchor) - { - Flush(); - pendingCommand = null; - pendingHint = null; - inAnchor = false; - } - // Other closing tags are stripped silently. - } - } - - while (index < line.Length) - { - var current = line[index]; - if (current == Escape && index + 1 < line.Length && line[index + 1] == '[') - { - var end = index + 2; - while (end < line.Length && !IsCsiFinal(line[end])) - { - end++; - } - - if (end < line.Length) - { - var final = line[end]; - var parameters = line.Substring(index + 2, end - (index + 2)); - if (final == 'm') - { - Flush(); - style = ApplySgr(style, parameters); - } - else if (final == 'z' && mxp is not null && mxp.IsMxpActive) - { - if (int.TryParse(parameters, out var mode)) - { - mxp.ApplyMode(mode); - } - } - - index = end + 1; - continue; - } - - break; - } - - if (current == Escape) - { - index++; - continue; - } - - // MXP / Pueblo markup. Locked MXP lines (mode 2) suppress all parsing. - var markup = mxp is not null - && (mxp.IsPuebloActive || (mxp.IsMxpActive && mxp.LineMode != 2)); - - if (current == '<' && markup) - { - // Quote-aware scan for the tag terminator so a '>' inside a quoted attribute - // value (e.g. ) doesn't truncate the tag. - var gt = FindTagEnd(line, index + 1); - if (gt < 0) - { - text.Append(current); // unterminated tag: treat '<' as literal - index++; - continue; - } - - HandleTag(line.Substring(index + 1, gt - (index + 1))); - index = gt + 1; - continue; - } - - // HTML entity decoding only happens inside MXP/Pueblo markup (after tag tokenisation, - // on text runs). In plain ANSI output '&' is always literal. A lone or unrecognised - // '&' is emitted verbatim — never dropped. - if (current == '&' && markup && TryDecodeEntity(line, index, out var entity, out var consumed)) - { - text.Append(entity); - index += consumed; - continue; - } - - text.Append(current); - index++; - } - - Flush(); - return segments; - } - - /// Extract an attribute value (quoted or unquoted) from a tag body, case-insensitively. - private static string? GetAttr(string body, string name) - { - var from = 0; - while (from < body.Length) - { - var idx = body.IndexOf(name, from, StringComparison.OrdinalIgnoreCase); - if (idx < 0) - { - return null; - } - - var atTokenStart = idx == 0 || body[idx - 1] is ' ' or '\t'; - var j = idx + name.Length; - while (j < body.Length && body[j] is ' ' or '\t') - { - j++; - } - - if (atTokenStart && j < body.Length && body[j] == '=') - { - j++; - while (j < body.Length && body[j] is ' ' or '\t') - { - j++; - } - - if (j < body.Length && body[j] is '"' or '\'') - { - var quote = body[j]; - var start = ++j; - while (j < body.Length && body[j] != quote) - { - j++; - } - - return DecodeEntities(body[start..j]); - } - else - { - var start = j; - while (j < body.Length && body[j] is not (' ' or '\t')) - { - j++; - } - - return DecodeEntities(body[start..j]); - } - } - - from = idx + name.Length; - } - - return null; - } - - /// The first attribute given without a name (MXP allows <IMAGE map.png URL=...>). - private static string? FirstPositional(string body) - { - var i = 0; - while (i < body.Length) - { - while (i < body.Length && body[i] is ' ' or '\t') - { - i++; - } - - if (i >= body.Length) - { - return null; - } - - var quoted = body[i] is '"' or '\''; - var start = i; - if (quoted) - { - var quote = body[i++]; - start = i; - while (i < body.Length && body[i] != quote) - { - i++; - } - - var value = body[start..i]; - i++; - return DecodeEntities(value); - } - - var isNamed = false; - while (i < body.Length && body[i] is not (' ' or '\t')) - { - if (body[i] == '=') - { - isNamed = true; - i++; - if (i < body.Length && body[i] is '"' or '\'') - { - var quote = body[i++]; - while (i < body.Length && body[i] != quote) - { - i++; - } - - i++; - } - - continue; - } - - i++; - } - - if (!isNamed) - { - return DecodeEntities(body[start..i]); - } - } - - return null; - } - - /// - /// Scan from for the '>' that closes a tag, skipping over single- or - /// double-quoted attribute values so a literal '>' inside an attribute doesn't end the tag early - /// (the Pueblo reference client guards this exact case). Returns -1 if unterminated. - /// - private static int FindTagEnd(string s, int start) - { - var quote = '\0'; - for (var k = start; k < s.Length; k++) - { - var c = s[k]; - if (quote != '\0') - { - if (c == quote) - { - quote = '\0'; - } - } - else if (c is '"' or '\'') - { - quote = c; - } - else if (c == '>') - { - return k; - } - } - - return -1; - } - - /// Decode every HTML entity in a string (used for attribute values). - private static string DecodeEntities(string s) - { - if (s.IndexOf('&') < 0) - { - return s; - } - - var sb = new StringBuilder(s.Length); - var i = 0; - while (i < s.Length) - { - if (s[i] == '&' && TryDecodeEntity(s, i, out var decoded, out var consumed)) - { - sb.Append(decoded); - i += consumed; - } - else - { - sb.Append(s[i]); - i++; - } - } - - return sb.ToString(); - } - - /// - /// Try to decode the HTML entity beginning at (must point at '&'). - /// Handles the core named entities, &apos;/&nbsp;/&copy;/&reg;/&trade;, - /// and numeric &#NN; (decimal) / &#xNN; (hex), decoding to full Unicode. - /// Named lookup is case-insensitive (friendlier than the reference client). A terminating ';' - /// is required; an unrecognised or unterminated sequence returns false so the caller emits the - /// literal '&' (entities are never silently dropped). Numeric values below U+0020 or outside - /// the Unicode range are consumed but produce no output (control chars are ignored, per MXP). - /// - private static bool TryDecodeEntity(string s, int i, out string decoded, out int consumed) - { - decoded = string.Empty; - consumed = 0; - - if (i >= s.Length || s[i] != '&') - { - return false; - } - - var semi = s.IndexOf(';', i + 1); - if (semi < 0 || semi - (i + 1) is 0 or > 12) - { - return false; // no terminator, empty, or implausibly long - } - - var name = s[(i + 1)..semi]; - consumed = semi - i + 1; - - if (name[0] == '#') - { - var isHex = name.Length > 1 && name[1] is 'x' or 'X'; - var digits = isHex ? name[2..] : name[1..]; - var v = 0; - var ok = digits.Length > 0 && (isHex - ? int.TryParse(digits, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out v) - : int.TryParse(digits, out v)); - if (!ok) - { - consumed = 0; - return false; - } - - if (v < 0x20 || v > 0x10FFFF || (v >= 0xD800 && v <= 0xDFFF)) - { - decoded = string.Empty; // ignore control / invalid / surrogate code points - return true; - } - - decoded = char.ConvertFromUtf32(v); - return true; - } - - var mapped = name.ToLowerInvariant() switch - { - "lt" => "<", - "gt" => ">", - "amp" => "&", - "quot" => "\"", - "apos" => "'", - "nbsp" => " ", - "copy" => "©", - "reg" => "®", - "trade" => "™", - _ => null, - }; - - if (mapped is null) - { - consumed = 0; - return false; - } - - decoded = mapped; - return true; - } - - private static bool IsCsiFinal(char c) => c is >= '@' and <= '~'; - - private static TextStyle ApplySgr(TextStyle style, string parameters) - { - if (parameters.Length == 0) - { - return TextStyle.Default; - } - - var codes = parameters.Split(';'); - for (var i = 0; i < codes.Length; i++) - { - if (!int.TryParse(codes[i], out var code)) - { - continue; - } - - switch (code) - { - case 0: - style = TextStyle.Default; - break; - case 1: - style = style with { Bold = true }; - break; - case 4: - style = style with { Underline = true }; - break; - case 7: - style = style with { Inverse = true }; - break; - case 22: - style = style with { Bold = false }; - break; - case 24: - style = style with { Underline = false }; - break; - case 27: - style = style with { Inverse = false }; - break; - case 39: - style = style with { Foreground = AnsiColor.Default }; - break; - case 49: - style = style with { Background = AnsiColor.Default }; - break; - case 38 when TryReadExtended(codes, ref i, out var fg): - style = style with { Foreground = fg }; - break; - case 48 when TryReadExtended(codes, ref i, out var bg): - style = style with { Background = bg }; - break; - case >= 30 and <= 37: - style = style with { Foreground = AnsiColor.Indexed(code - 30) }; - break; - case >= 90 and <= 97: - style = style with { Foreground = AnsiColor.Indexed(code - 90 + 8) }; - break; - case >= 40 and <= 47: - style = style with { Background = AnsiColor.Indexed(code - 40) }; - break; - case >= 100 and <= 107: - style = style with { Background = AnsiColor.Indexed(code - 100 + 8) }; - break; - } - } - - return style; - } - - private static bool TryReadExtended(string[] codes, ref int i, out AnsiColor colour) - { - colour = AnsiColor.Default; - if (i + 1 >= codes.Length) - { - return false; - } - - if (codes[i + 1] == "5") - { - if (i + 2 < codes.Length && int.TryParse(codes[i + 2], out var n)) - { - colour = AnsiColor.Indexed(n); - i += 2; - return true; - } - - return false; - } - - if (codes[i + 1] == "2") - { - // Truecolor: "2" + R + G + B. A short or malformed sequence is still consumed, so its - // components are not read as SGR codes of their own, and leaves the colour at default. - var remaining = codes.Length - 1 - i; - if (remaining >= 4 - && int.TryParse(codes[i + 2], out var r) - && int.TryParse(codes[i + 3], out var g) - && int.TryParse(codes[i + 4], out var b)) - { - colour = AnsiColor.Rgb(r, g, b); - } - - i += Math.Min(4, remaining); - return true; - } - - return false; - } -} diff --git a/src/SharpClient.Core/Rendering/ImageSource.cs b/src/SharpClient.Core/Rendering/ImageSource.cs index a12fae3..fcc074a 100644 --- a/src/SharpClient.Core/Rendering/ImageSource.cs +++ b/src/SharpClient.Core/Rendering/ImageSource.cs @@ -10,47 +10,13 @@ public static class ImageSource private const int MaxNameLength = 48; /// - /// MXP <IMAGE>: "The classname is appended to the URL, along with the name of the - /// graphics file itself", so URL=http://h/img/ T=maps map.png is http://h/img/maps/map.png. - /// Without URL= the name must itself be absolute; a bare file name refers to a local media - /// directory this client does not have. + /// The address an image the decoder read (MXP <IMAGE>, Pueblo <img>) may be loaded + /// from: an absolute http(s) URL, normalised, or a data:image URI. Null for anything else, including a + /// bare file name, which refers to a local media directory this client does not have. /// - public static string? ResolveMxp(string fileName, string? url, string? type) + public static string? Resolve(string source) { - var name = fileName.Trim(); - if (name.Length == 0) - { - return null; - } - - if (IsDataImage(name)) - { - return string.IsNullOrWhiteSpace(url) ? name : null; - } - - if (string.IsNullOrWhiteSpace(url)) - { - return Absolute(name); - } - - var basePath = EnsureSlash(url.Trim()); - if (!string.IsNullOrWhiteSpace(type)) - { - basePath = EnsureSlash(basePath + type.Trim().Trim('/')); - } - - if (!Uri.TryCreate(basePath, UriKind.Absolute, out var baseUri) || !IsWeb(baseUri)) - { - return null; - } - - return Uri.TryCreate(baseUri, name, out var full) && IsWeb(full) ? full.AbsoluteUri : null; - } - - /// Pueblo <img src>, which is plain HTML: an absolute URL or a data:image URI. - public static string? ResolvePueblo(string src) - { - var value = src.Trim(); + var value = source.Trim(); return IsDataImage(value) ? value : Absolute(value); } @@ -89,7 +55,5 @@ private static bool IsDataImage(string value) => private static string? Absolute(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && IsWeb(uri) ? uri.AbsoluteUri : null; - private static string EnsureSlash(string value) => value.EndsWith('/') ? value : value + "/"; - private static bool IsWeb(Uri uri) => uri.Scheme is "http" or "https"; } diff --git a/src/SharpClient.Core/Rendering/MxpParserState.cs b/src/SharpClient.Core/Rendering/MxpParserState.cs deleted file mode 100644 index 1cad530..0000000 --- a/src/SharpClient.Core/Rendering/MxpParserState.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace SharpClient.Core.Rendering; - -/// -/// Per-session markup-negotiation state for MXP (telnet option 91) and Pueblo. -/// Passed to on each line so the -/// parser knows whether clickable command-links are permitted on the current line. -/// -public sealed class MxpParserState -{ - /// Whether MXP telnet option 91 was successfully negotiated. - public bool IsMxpActive { get; set; } - - /// Whether the server switched this connection into Pueblo HTML mode. - public bool IsPuebloActive { get; set; } - - /// - /// Current MXP line mode. Per-line modes (0=Open,1=Secure,2=Locked,3=Reset) revert to - /// at each newline; lock modes (5,6) change the default. - /// - public int LineMode { get; set; } - - /// Persistent default mode — 0 (Open) or 1 (Secure, via Lock-Secure). - public int DefaultLineMode { get; set; } - - /// Reset the transient line mode to the persistent default. Call at line start. - public void BeginLine() => LineMode = DefaultLineMode; - - /// Apply an ESC[#z mode sequence. - public void ApplyMode(int mode) - { - switch (mode) - { - case 0 or 1 or 2: - LineMode = mode; - break; - case 3: // Reset: close tags, revert to Open for this line - LineMode = 0; - break; - case 5: // Lock Open: Open becomes the persistent default - LineMode = 0; - DefaultLineMode = 0; - break; - case 6: // Lock Secure: Secure becomes the persistent default - LineMode = 1; - DefaultLineMode = 1; - break; - } - } - - /// True when the current line permits Secure elements (SEND / A). - public bool IsSecure => LineMode == 1; -} diff --git a/src/SharpClient.Core/Rendering/MxpTags.cs b/src/SharpClient.Core/Rendering/MxpTags.cs index 305cb6e..7be9dc5 100644 --- a/src/SharpClient.Core/Rendering/MxpTags.cs +++ b/src/SharpClient.Core/Rendering/MxpTags.cs @@ -1,80 +1,51 @@ +using MarkupString.Mxp.Decoding; + namespace SharpClient.Core.Rendering; /// -/// What SharpClient's MXP rendering () acts on, for answering a server's -/// <SUPPORT>. A tag or attribute is listed only when the parser does something with it: -/// claiming more makes a server send markup that is then shown stripped. +/// What SharpClient's MXP rendering ( and the output view) acts on, for answering +/// a server's <SUPPORT>. A tag or attribute is listed only when the client does something with it: +/// claiming more makes a server send markup that is then shown stripped. Sound, frames, variables and +/// relocation are decoded but not acted on, so they are not claimed. /// public static class MxpTags { /// The MXP revision answered to <VERSION>. public const string MxpRevision = "1.0"; - // Each rendered tag with the attributes the parser reads from it. + // Each rendered tag with the attributes the client reads from it. SEND's PROMPT is not claimed: + // a prompt link is sent as a command, since there is no prompt-into-input yet. private static readonly (string Tag, string[] Attributes)[] s_rendered = [ + ("b", []), ("bold", []), ("strong", []), + ("i", []), ("italic", []), ("em", []), + ("u", []), ("underline", []), + ("s", []), ("strikeout", []), + ("h", []), ("high", []), + ("c", ["fore", "back"]), ("color", ["fore", "back"]), + ("font", ["color", "back"]), + ("br", []), ("sbr", []), ("p", []), ("nobr", []), + ("a", ["href", "hint"]), ("send", ["href", "hint"]), - ("image", ["fname", "url", "t"]), + ("image", ["fname", "url", "t", "w", "h"]), + ("element", []), ("entity", []), ("attlist", []), ("tag", []), ]; - public static IReadOnlyList Supported { get; } = [.. s_rendered.Select(r => r.Tag)]; - - private static readonly Dictionary s_attributes = - s_rendered.ToDictionary(r => r.Tag, r => r.Attributes, StringComparer.OrdinalIgnoreCase); - /// - /// The answer to a <SUPPORT> naming : every supported tag when - /// it named nothing, otherwise each entry as supported or not. tag.attr is supported when the - /// parser reads that attribute; tag.* expands to each attribute of a supported tag, as the - /// specification asks, and is -tag.* for a tag this client does not render. + /// The MXP options SharpClient decodes with. holds the tags above, so + /// the decoder and the <SUPPORT> answer agree. /// - public static (IReadOnlyList Supported, IReadOnlyList Unsupported) Answer(IReadOnlyList asked) + public static MxpOptions Options { get; } = new() { - if (asked.Count == 0) - { - return (Supported, []); - } - - var supported = new List(); - var unsupported = new List(); - foreach (var entry in asked) - { - var name = entry.Trim('"', '\''); - if (name.Length == 0) - { - continue; - } + Supports = s_rendered.ToDictionary(r => r.Tag, r => (IReadOnlyList)r.Attributes, StringComparer.OrdinalIgnoreCase), + }; - var dot = name.IndexOf('.', StringComparison.Ordinal); - if (dot < 0) - { - (IsSupported(name) ? supported : unsupported).Add(name); - continue; - } - - var tag = name[..dot]; - var attribute = name[(dot + 1)..]; - var tagSupported = s_attributes.TryGetValue(tag, out var known); - var attributes = known ?? Array.Empty(); - if (attribute == "*") - { - if (tagSupported) - { - supported.AddRange(attributes.Select(a => $"{tag}.{a}")); - } - else - { - unsupported.Add(name); - } - } - else - { - (attributes.Contains(attribute, StringComparer.OrdinalIgnoreCase) ? supported : unsupported).Add(name); - } - } - - return (supported, unsupported); - } + public static IReadOnlyList Supported { get; } = [.. s_rendered.Select(r => r.Tag)]; - private static bool IsSupported(string tag) => s_attributes.ContainsKey(tag); + /// + /// The answer to a <SUPPORT> naming : every supported tag when it + /// named nothing, otherwise each entry as supported or not (). + /// + public static (IReadOnlyList Supported, IReadOnlyList Unsupported) Answer(IReadOnlyList asked) => + Options.Answer(asked); } diff --git a/src/SharpClient.Core/Rendering/OutputDecoder.cs b/src/SharpClient.Core/Rendering/OutputDecoder.cs new file mode 100644 index 0000000..16952ea --- /dev/null +++ b/src/SharpClient.Core/Rendering/OutputDecoder.cs @@ -0,0 +1,98 @@ +using MarkupString; +using MarkupString.Ansi.Decoding; +using MarkupString.Decoding; +using MarkupString.Mxp.Decoding; +using MarkupString.Pueblo.Decoding; + +namespace SharpClient.Core.Rendering; + +/// +/// One connection's decoder: turns each line the telnet layer delivers into +/// lines, keeping the style, MXP line mode and open elements from line to line. Calls are serialised: +/// the read loop decodes while negotiation and state changes arrive on other threads. +/// +public sealed class OutputDecoder +{ + /// ANSI/VT, MXP and Pueblo. MXP and Pueblo stay off until telnet negotiates them. + public static DecoderRegistry Registry { get; } = DecoderRegistry.Empty.WithVt().WithMxp(MxpTags.Options).WithPueblo(); + + private readonly Lock _lock = new(); + private readonly Decoder _decoder = Registry.CreateDecoder(new DecoderOptions + { + // The telnet layer answers MXP /, and there is no path for VT replies yet, + // so the decoder answers nothing. + Identity = new ClientIdentity { Name = "SharpClient", Answers = ClientAnswers.None }, + }); + + /// The text protocol that is on: mxp, pueblo, or null. + public string? ActiveProtocol + { + get + { + lock (_lock) + { + return _decoder.ActiveProtocol; + } + } + } + + /// MXP was negotiated (telnet option 91). + public void EnableMxp() + { + lock (_lock) + { + _decoder.EnableProtocol(MxpDecoding.Protocol); + } + } + + /// The server switched the connection to Pueblo. + public void EnablePueblo() + { + lock (_lock) + { + _decoder.EnableProtocol(PuebloDecoding.Protocol); + } + } + + /// The connection ended: forget the style, protocols and anything half-read. + public void Reset() + { + lock (_lock) + { + _decoder.Reset(); + } + } + + /// + /// The lines one telnet line makes. Usually one; an MXP <BR> or Pueblo <br> makes + /// more. A telnet line that only closed a line already ended by <br> adds no blank line. + /// + public IReadOnlyList Decode(string raw) + { + lock (_lock) + { + return DecodeLocked(raw); + } + } + + private List DecodeLocked(string raw) + { + var fed = _decoder.Feed(raw); + var lines = new List(fed.Count + 1); + foreach (var line in fed) + { + lines.Add(line.Content); + } + + // The telnet line always ends here, so a line mode such as MXP secure (ESC[1z) ends with it even + // when a
already closed the last display line. Only the empty line that leaves is dropped. + var pending = _decoder.HasPendingLine; + var ended = _decoder.EndLine(); + if (pending || lines.Count == 0) + { + lines.Add(ended.Content); + } + + return lines; + } +} diff --git a/src/SharpClient.Core/Rendering/OutputHtml.cs b/src/SharpClient.Core/Rendering/OutputHtml.cs new file mode 100644 index 0000000..2fbd958 --- /dev/null +++ b/src/SharpClient.Core/Rendering/OutputHtml.cs @@ -0,0 +1,40 @@ +using MarkupString; +using MarkupString.Ansi; +using MarkupString.Html; + +namespace SharpClient.Core.Rendering; + +/// +/// How SharpClient's output view writes a decoded line: MarkupString's HTML, which the page shows with +/// MarkupString.Web's stylesheet and script. Pictures go through , and a +/// Highlight trigger through . Web links pass . +/// +public static class OutputHtml +{ + /// + /// Which link addresses become links: , also refusing one with a control character + /// or a space at either end, which a browser would strip (java&#9;script: runs as javascript:). + /// + public static UrlPolicy Links { get; } = UrlPolicy.Safe.RefusingControlCharacters(); + + /// The registry that shows pictures. + public static MarkupRegistry WithPictures { get; } = Build(showImages: true); + + /// The registry that shows a picture's name in its place. + public static MarkupRegistry WithPictureNames { get; } = Build(showImages: false); + + /// The HTML for one line. + public static string Render(MarkupText line, bool showImages = true) + { + ArgumentNullException.ThrowIfNull(line); + return line.Render(MarkupFormat.Html, showImages ? WithPictures : WithPictureNames); + } + + private static MarkupRegistry Build(bool showImages) => + MarkupRegistry.Empty + .WithAnsi() + .WithHtml() + .With(new OutputImageEmitter(showImages)) + .With(TriggerHighlightEmitter.Instance) + .WithLinks(Links); +} diff --git a/src/SharpClient.Core/Rendering/OutputImageEmitter.cs b/src/SharpClient.Core/Rendering/OutputImageEmitter.cs new file mode 100644 index 0000000..c82ebca --- /dev/null +++ b/src/SharpClient.Core/Rendering/OutputImageEmitter.cs @@ -0,0 +1,63 @@ +using System.Buffers; +using System.Globalization; +using System.Net; +using MarkupString; + +namespace SharpClient.Core.Rendering; + +/// +/// Writes an MXP <IMAGE> or Pueblo <img> for the output view. Only an address +/// accepts is loaded; any other shows nothing. With images off, the +/// picture's description or file name is shown instead. +/// +public sealed class OutputImageEmitter(bool showImages) : IMarkupEmitter +{ + public Type MarkupType => typeof(ImageMarkup); + + public MarkupFormat Format => MarkupFormat.Html; + + public void Emit(IMarkup markup, ReadOnlySpan body, in EmitContext context, IBufferWriter output) + { + ArgumentNullException.ThrowIfNull(markup); + ArgumentNullException.ThrowIfNull(output); + + var image = (ImageMarkup)markup; + + // A picture sized in cells covers several runs; it is drawn once, where it starts. + if (!image.StartsPicture(context) || ImageSource.Resolve(image.Source) is not { } source) + { + return; + } + + var name = WebUtility.HtmlEncode(image.Description ?? ImageSource.DisplayName(image.Source)); + if (!showImages) + { + output.Write(name); + return; + } + + // no-referrer: the image host learns nothing about where it was shown. + output.Write("\"");"); + } + + private static void WriteSize(string attribute, int? value, IBufferWriter output) + { + if (value is not { } size) + { + return; + } + + output.Write(attribute); + output.Write(size.ToString(CultureInfo.InvariantCulture)); + output.Write("\""); + } +} diff --git a/src/SharpClient.Core/Rendering/OutputPalette.cs b/src/SharpClient.Core/Rendering/OutputPalette.cs new file mode 100644 index 0000000..e8e536e --- /dev/null +++ b/src/SharpClient.Core/Rendering/OutputPalette.cs @@ -0,0 +1,43 @@ +using MarkupString; +using MarkupString.Ansi.Decoding; + +namespace SharpClient.Core.Rendering; + +/// +/// SharpClient's colours for the sixteen standard ANSI colours; the 256-colour cube and grey ramp are +/// xterm's. The output view hands the sixteen to MarkupString's HTML as --ms-ansi-N +/// (). +/// +public sealed class OutputPalette : AnsiColors +{ + public static OutputPalette Instance { get; } = new(); + + private static readonly RgbColor[] s_base16 = + [ + Hex(0x3a3f4b), Hex(0xe06c75), Hex(0x8fc16f), Hex(0xe5c07b), Hex(0x61afef), Hex(0xc678dd), Hex(0x56b6c2), Hex(0xabb2bf), + Hex(0x5c6672), Hex(0xff8088), Hex(0xb5e890), Hex(0xffd596), Hex(0x7cc4ff), Hex(0xe29bf0), Hex(0x6fd3df), Hex(0xe8edf2), + ]; + + private OutputPalette() + { + } + + public override RgbColor Standard(int index, bool bright) => s_base16[(index & 7) + (bright ? 8 : 0)]; + + public override RgbColor Xterm(int index) => index is >= 0 and < 16 ? s_base16[index] : base.Xterm(index); + + /// Palette entry (0–255) in this palette. + public RgbColor Entry(int index) => index < 16 ? Standard(index & 7, index >= 8) : Xterm(index); + + /// + /// The sixteen colours as the CSS custom properties MarkupString's HTML reads them from + /// (--ms-ansi-0 to --ms-ansi-15), for a style attribute. + /// + public static string CustomProperties { get; } = + string.Join(";", s_base16.Select((color, index) => $"--ms-ansi-{index}:{Hex(color)}")); + + /// as #rrggbb. + public static string Hex(RgbColor color) => $"#{color.R:x2}{color.G:x2}{color.B:x2}"; + + private static RgbColor Hex(int rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); +} diff --git a/src/SharpClient.Core/Rendering/SegmentStyle.cs b/src/SharpClient.Core/Rendering/SegmentStyle.cs deleted file mode 100644 index 72478be..0000000 --- a/src/SharpClient.Core/Rendering/SegmentStyle.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Text; - -namespace SharpClient.Core.Rendering; - -public static class SegmentStyle -{ - // PhosphorDefault is the single source of truth: AnsiPalette.PhosphorDefault (internal const). - private const string OutputBackground = "#090c10"; - - public static string ToCss(StyledSegment segment) - { - var style = segment.Style; - var fg = Resolve(style.Foreground, AnsiPalette.PhosphorDefault); - string? bg = style.Background.Kind == AnsiColorKind.Default - ? null - : Resolve(style.Background, AnsiPalette.PhosphorDefault); - - if (style.Inverse) - { - (fg, bg) = (OutputBackground, fg); - } - - var sb = new StringBuilder(); - sb.Append("color:").Append(fg).Append(';'); - if (bg is not null) - { - sb.Append("background:").Append(bg).Append(';'); - sb.Append("padding:0 2px;"); - } - - if (style.Bold) - { - sb.Append("font-weight:700;"); - } - - if (style.Underline) - { - sb.Append("text-decoration:underline;"); - } - - return sb.ToString(); - } - - private static string Resolve(AnsiColor color, string fallback) => color.Kind switch - { - AnsiColorKind.Indexed => AnsiPalette.ToHex(color.Index), - AnsiColorKind.Rgb => $"#{color.Index & 0xFFFFFF:x6}", - _ => fallback, - }; -} diff --git a/src/SharpClient.Core/Rendering/StyledSegment.cs b/src/SharpClient.Core/Rendering/StyledSegment.cs deleted file mode 100644 index 1ed1b15..0000000 --- a/src/SharpClient.Core/Rendering/StyledSegment.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace SharpClient.Core.Rendering; - -public readonly record struct StyledSegment(string Text, TextStyle Style) -{ - /// - /// If non-null, this segment is a clickable command-link (MXP <SEND> or Pueblo - /// <a xch_cmd>). Clicking it sends this string to the server. Null for normal text. - /// - public string? Command { get; init; } - - /// Optional tooltip for a command link. Null if unspecified. - public string? Hint { get; init; } - - /// - /// If non-null, this segment is an inline image (MXP <IMAGE> or Pueblo <img>) and - /// is its alternative text. Always an absolute http(s) URL or a data:image URI. - /// - public string? ImageUrl { get; init; } -} diff --git a/src/SharpClient.Core/Rendering/TextStyle.cs b/src/SharpClient.Core/Rendering/TextStyle.cs deleted file mode 100644 index 8245443..0000000 --- a/src/SharpClient.Core/Rendering/TextStyle.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace SharpClient.Core.Rendering; - -public readonly record struct TextStyle -{ - public AnsiColor Foreground { get; init; } - - public AnsiColor Background { get; init; } - - public bool Bold { get; init; } - - public bool Underline { get; init; } - - public bool Inverse { get; init; } - - public static TextStyle Default => new() - { - Foreground = AnsiColor.Default, - Background = AnsiColor.Default, - }; -} diff --git a/src/SharpClient.Core/Rendering/TriggerHighlight.cs b/src/SharpClient.Core/Rendering/TriggerHighlight.cs new file mode 100644 index 0000000..adf3fe1 --- /dev/null +++ b/src/SharpClient.Core/Rendering/TriggerHighlight.cs @@ -0,0 +1,45 @@ +using System.Buffers; +using MarkupString; + +namespace SharpClient.Core.Rendering; + +/// A Highlight trigger's colour over a line: palette entry (0–255). +public sealed record TriggerHighlightMarkup(int Index) : IMarkup; + +/// +/// Writes as a span.sc-highlight that sets --sc-highlight. +/// The stylesheet gives that colour to everything inside, over the server's own colours. +/// +public sealed class TriggerHighlightEmitter : IMarkupEmitter +{ + public static TriggerHighlightEmitter Instance { get; } = new(); + + private TriggerHighlightEmitter() + { + } + + public Type MarkupType => typeof(TriggerHighlightMarkup); + + public MarkupFormat Format => MarkupFormat.Html; + + public void Emit(IMarkup markup, ReadOnlySpan body, in EmitContext context, IBufferWriter output) + { + ArgumentNullException.ThrowIfNull(markup); + ArgumentNullException.ThrowIfNull(output); + + var highlight = (TriggerHighlightMarkup)markup; + if (context.StartsRegion(markup)) + { + output.Write(""); + } + + output.Write(body); + + if (context.EndsRegion(markup)) + { + output.Write(""); + } + } +} diff --git a/src/SharpClient.Core/Sessions/Session.cs b/src/SharpClient.Core/Sessions/Session.cs index f1da93d..a9ad05e 100644 --- a/src/SharpClient.Core/Sessions/Session.cs +++ b/src/SharpClient.Core/Sessions/Session.cs @@ -1,3 +1,5 @@ +using MarkupString; +using MarkupString.Ansi; using SharpClient.Core.Connection; using SharpClient.Core.Domain; using SharpClient.Core.Persistence; @@ -7,7 +9,16 @@ namespace SharpClient.Core.Sessions; -public sealed record ScrollbackLine(IReadOnlyList Segments); +/// +/// One line of output, decoded. writes it for the output view. Each line is +/// equal only to itself: the view keys lines by them, and a server can send the same text twice. +/// +public sealed record ScrollbackLine(MarkupText Content) +{ + public bool Equals(ScrollbackLine? other) => ReferenceEquals(this, other); + + public override int GetHashCode() => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this); +} public sealed class Session : ISession { @@ -33,7 +44,7 @@ public sealed class Session : ISession private readonly List _scrollback = []; private readonly List _negotiationLog = []; private readonly List _gmcpLog = []; - private readonly MxpParserState _mxp = new(); + private readonly OutputDecoder _decoder = new(); private event Action? _protocolChanged; public Session( @@ -114,7 +125,8 @@ public Task ConnectAsync(string host, int port, CancellationToken cancellationTo public Task ReconnectAsync() => _connection.ReconnectAsync(); - private static readonly TextStyle EchoStyle = TextStyle.Default with { Foreground = AnsiColor.Indexed(8) }; + // Bright black (palette 8): dim against the server's own output. + private static readonly AnsiMarkup EchoStyle = AnsiMarkup.Create(foreground: new AnsiColor.Standard(0, Bright: true)); public async Task SendAsync(string line) { @@ -124,7 +136,7 @@ public async Task SendAsync(string line) // Local echo: MUSH/MUD servers normally don't echo your commands back, so // show what was typed in the scrollback (dim, prefixed) for visibility. - var echo = new ScrollbackLine([new StyledSegment("> " + line, EchoStyle)]); + var echo = new ScrollbackLine(MarkupText.Wrap(EchoStyle, "> " + line)); lock (_scrollbackLock) { _scrollback.Add(echo); @@ -151,46 +163,49 @@ public async ValueTask DisposeAsync() private void OnPuebloEnabled() { - _mxp.IsPuebloActive = true; + _decoder.EnablePueblo(); _protocolChanged?.Invoke(); } private void OnMxpEnabled() { - _mxp.IsMxpActive = true; + _decoder.EnableMxp(); _protocolChanged?.Invoke(); } private async void OnLineReceived(string raw) { - // Reset per-line MXP mode to the negotiated default before parsing this line. - _mxp.BeginLine(); + // The decoder keeps the style, MXP line mode and open elements from line to line. + var decoded = _decoder.Decode(raw); - IReadOnlyList segments; + IReadOnlyList lines; IReadOnlyList sendCommands; IReadOnlyList notifications; if (_triggerEngine is not null && _triggerRules is not null) { - var outcome = _triggerEngine.Apply(raw, _triggerRules, _mxp); - segments = outcome.Segments; + var outcome = _triggerEngine.Apply(raw, decoded, _triggerRules); + lines = outcome.Lines; sendCommands = outcome.SendCommands; notifications = outcome.Notifications; } else { - segments = AnsiParser.Parse(raw, _mxp); + lines = decoded; sendCommands = []; notifications = []; } - var line = new ScrollbackLine(segments); - lock (_scrollbackLock) + foreach (var content in lines) { - _scrollback.Add(line); - } + var line = new ScrollbackLine(content); + lock (_scrollbackLock) + { + _scrollback.Add(line); + } - LineAppended?.Invoke(line); + LineAppended?.Invoke(line); + } foreach (var cmd in sendCommands) { @@ -220,10 +235,7 @@ private void OnStateChanged(ConnectionState state) // server it reaches may not offer either. if (previous == ConnectionState.Connected && state != ConnectionState.Connected) { - _mxp.IsMxpActive = false; - _mxp.IsPuebloActive = false; - _mxp.DefaultLineMode = 0; - _mxp.LineMode = 0; + _decoder.Reset(); } StateChanged?.Invoke(state); diff --git a/src/SharpClient.Core/SharpClient.Core.csproj b/src/SharpClient.Core/SharpClient.Core.csproj index d58c403..be72a8c 100644 --- a/src/SharpClient.Core/SharpClient.Core.csproj +++ b/src/SharpClient.Core/SharpClient.Core.csproj @@ -7,8 +7,13 @@ - + + + + + + diff --git a/src/SharpClient.Core/Triggers/ITriggerEngine.cs b/src/SharpClient.Core/Triggers/ITriggerEngine.cs index 12e2ae1..a7fea6c 100644 --- a/src/SharpClient.Core/Triggers/ITriggerEngine.cs +++ b/src/SharpClient.Core/Triggers/ITriggerEngine.cs @@ -1,16 +1,16 @@ using SharpClient.Core.Domain; -using SharpClient.Core.Rendering; +using MarkupString; namespace SharpClient.Core.Triggers; public sealed record TriggerOutcome( - IReadOnlyList Segments, + IReadOnlyList Lines, IReadOnlyList SendCommands, IReadOnlyList Notifications); public interface ITriggerEngine { - // Parse rawLine via AnsiParser (with optional MXP/Pueblo markup state), apply Highlight - // rules (restyle matched runs), collect Send/Notify actions. Disabled rules are ignored. - public TriggerOutcome Apply(string rawLine, IReadOnlyList rules, MxpParserState? mxp = null); + // Match rules against rawLine (as the server sent it), apply Highlight rules to the decoded lines it + // made, and collect Send/Notify actions. Disabled rules are ignored. + public TriggerOutcome Apply(string rawLine, IReadOnlyList lines, IReadOnlyList rules); } diff --git a/src/SharpClient.Core/Triggers/TriggerEngine.cs b/src/SharpClient.Core/Triggers/TriggerEngine.cs index 6afa5a9..4d7a0c5 100644 --- a/src/SharpClient.Core/Triggers/TriggerEngine.cs +++ b/src/SharpClient.Core/Triggers/TriggerEngine.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Text.RegularExpressions; +using MarkupString; using SharpClient.Core.Domain; using SharpClient.Core.Rendering; @@ -15,12 +16,11 @@ public sealed class TriggerEngine : ITriggerEngine private static readonly ConcurrentDictionary<(string Pattern, RegexOptions Options), Regex> RegexCache = new(); - public TriggerOutcome Apply(string rawLine, IReadOnlyList rules, MxpParserState? mxp = null) + public TriggerOutcome Apply(string rawLine, IReadOnlyList lines, IReadOnlyList rules) { - IReadOnlyList segments = AnsiParser.Parse(rawLine, mxp); var sendCommands = new List(); var notifications = new List(); - AnsiColor? highlightForeground = null; + int? highlightForeground = null; foreach (var rule in rules) { @@ -44,23 +44,23 @@ public TriggerOutcome Apply(string rawLine, IReadOnlyList rules, Mx break; case TriggerActionKind.Highlight: // v1: whole-line highlight simplification — apply the highlight foreground to every - // segment regardless of where the match occurred. Per-segment span highlighting is + // run regardless of where the match occurred. Per-segment span highlighting is // deferred to a future phase. Later Highlight rules override earlier ones. if (int.TryParse(rule.ActionValue, out var index) && index is >= 0 and <= 255) { - highlightForeground = AnsiColor.Indexed(index); + highlightForeground = index; } break; } } - if (highlightForeground.HasValue) + if (highlightForeground is { } fg) { - var fg = highlightForeground.Value; - segments = segments.Select(s => s with { Style = s.Style with { Foreground = fg } }).ToList(); + var highlight = new TriggerHighlightMarkup(fg); + lines = lines.Select(line => MarkupText.Wrap(highlight, line)).ToList(); } - return new TriggerOutcome(segments, sendCommands, notifications); + return new TriggerOutcome(lines, sendCommands, notifications); } private static bool Matches(string rawLine, TriggerRule rule) diff --git a/src/SharpClient.UI/Components/OutputView.razor b/src/SharpClient.UI/Components/OutputView.razor index fc8ecac..4b008d8 100644 --- a/src/SharpClient.UI/Components/OutputView.razor +++ b/src/SharpClient.UI/Components/OutputView.razor @@ -1,50 +1,136 @@ +@using System.Runtime.CompilerServices +@using System.Text.Json +@using Microsoft.JSInterop @using SharpClient.Core.Rendering @using SharpClient.Core.Sessions +@implements IAsyncDisposable +@inject IJSRuntime JS -
+@* Each line is MarkupString's HTML. markupstring.js (MarkupString.Web) runs its command links and menus. *@ +
@foreach (var line in Lines) { -
- @foreach (var segment in line.Segments) - { - @if (segment.ImageUrl is not null && ShowImages) - { - @* no-referrer: the image host learns nothing about where it was shown. *@ - @if (segment.Command is not null && OnSendCommand is not null) - { - - } - else - { - @segment.Text - } - } - else if (segment.Command is not null && OnSendCommand is not null) - { - - } - else - { - @(segment.Text.Length == 0 ? " " : segment.Text) - } - } -
+
@HtmlOf(line)
}
@code { + /// Where Blazor serves MarkupString.Web's script from. + public const string ScriptPath = "./_content/MarkupString.Web/markupstring.js"; + + // Effects the script would carry out on elements Blazor owns. They come here instead and are ignored: + // a clear would remove scrollback lines, and a pane would move a line's text out of it. Relocation and + // login prompts need the connection, which the view does not have. + private static readonly string[] s_forwarded = ["clear", "pane", "relocate", "login"]; + + // A line's HTML depends only on the line and whether images are shown, so each is written once. + private static readonly ConditionalWeakTable s_withPictures = new(); + private static readonly ConditionalWeakTable s_withPictureNames = new(); + + private ElementReference _root; + private IJSObjectReference? _module; + private IJSObjectReference? _runtime; + private DotNetObjectReference? _self; + private bool _disposed; + [Parameter] public IReadOnlyList Lines { get; set; } = []; - /// Invoked when a clickable MXP/Pueblo command-link is clicked. + /// Invoked when a clickable MXP/Pueblo command link, or one of its menu choices, is clicked. [Parameter] public Func? OnSendCommand { get; set; } - /// When false, an image segment renders as its text (its name or alt text) instead. + /// When false, an image renders as its text (its name or alt text) instead. [Parameter] public bool ShowImages { get; set; } = true; + + private Microsoft.AspNetCore.Components.MarkupString HtmlOf(ScrollbackLine line) => new(ShowImages + ? s_withPictures.GetValue(line, static l => OutputHtml.Render(l.Content, showImages: true)) + : s_withPictureNames.GetValue(line, static l => OutputHtml.Render(l.Content, showImages: false))); + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) + { + return; + } + + try + { + _module = await JS.InvokeAsync("import", ScriptPath); + if (_disposed) + { + await ReleaseAsync(); + return; + } + + _self = DotNetObjectReference.Create(this); + _runtime = await _module.InvokeAsync( + "attachDotNet", _root, _self, new { forward = s_forwarded, sounds = false }); + if (_disposed) + { + // The view went away while the script attached: undo what DisposeAsync could not see. + await ReleaseAsync(); + } + } + catch (JSDisconnectedException) + { + // The page went away first. + } + catch (Exception) when (_disposed) + { + // Disposed mid-attach; whatever failed belonged to the view that is gone. + } + } + + /// A command link or menu choice was clicked. + [JSInvokable] + public Task Send(string command) => OnSendCommand?.Invoke(command) ?? Task.CompletedTask; + + /// + /// A prompt link (MXP SEND PROMPT, Pueblo xch_mode=prompt) was clicked. There is no way to + /// put text in the input line from here yet, so it is sent, as before. + /// + [JSInvokable] + public Task Prompt(string command) => Send(command); + + /// An effect in : ignored. + [JSInvokable] + public Task OnEffect(string name, JsonElement detail) => Task.CompletedTask; + + public async ValueTask DisposeAsync() + { + _disposed = true; + await ReleaseAsync(); + } + + private async Task ReleaseAsync() + { + var runtime = _runtime; + var module = _module; + _runtime = null; + _module = null; + try + { + if (runtime is not null) + { + await runtime.InvokeVoidAsync("detach"); + await runtime.DisposeAsync(); + } + + if (module is not null) + { + await module.DisposeAsync(); + } + } + catch (JSDisconnectedException) + { + // The page went away first. + } + finally + { + _self?.Dispose(); + _self = null; + } + } } diff --git a/src/SharpClient.UI/SharpClient.UI.csproj b/src/SharpClient.UI/SharpClient.UI.csproj index 7eb2d72..dea06b0 100644 --- a/src/SharpClient.UI/SharpClient.UI.csproj +++ b/src/SharpClient.UI/SharpClient.UI.csproj @@ -11,6 +11,7 @@ + diff --git a/src/SharpClient.UI/wwwroot/app.css b/src/SharpClient.UI/wwwroot/app.css index e89e0e1..772eece 100644 --- a/src/SharpClient.UI/wwwroot/app.css +++ b/src/SharpClient.UI/wwwroot/app.css @@ -638,27 +638,68 @@ body { .sc-modal-submit { margin-top: 4px; font-size: 14px; font-weight: 600; color: #0a0c10; background: var(--acc2); border: none; border-radius: 10px; padding: 13px; cursor: pointer; } .sc-modal-submit:disabled { opacity: .5; cursor: not-allowed; } -/* ── MXP / Pueblo clickable command-links ──────────────────────────────── */ -.sc-link { - background: none; - border: none; - padding: 0; - margin: 0; - font: inherit; - cursor: pointer; - color: var(--acc2); +/* ── MarkupString output (markupstring.css styles the ms-* classes) ──────── */ +/* The client's colours: reverse video swaps against the output's own, and the sixteen standard + colours (--ms-ansi-N) are set on .sc-output by OutputView, from OutputPalette. */ +.sc-output { + --ms-fg: var(--pho); + --ms-bg: var(--outbg); +} + +/* A SEND menu's popup is put on , outside .sc-output. */ +:root { + --ms-menu-fg: var(--tx); + --ms-menu-bg: var(--panel); + --ms-menu-border: var(--bd); + --ms-menu-active-fg: var(--acc); + --ms-menu-active-bg: var(--acc-soft); +} +.ms-menu-popup { + font-family: var(--mono); + font-size: var(--out-fs); + border-radius: 4px; +} + +/* A little room either side, so a coloured background does not crowd the glyphs. */ +.sc-line [style*="background-color"] { + padding: 0 2px; +} + +/* Command links (MXP SEND, Pueblo xch_cmd), SEND menus, and web links (OSC 8, MXP A, Pueblo a href). + A link takes the accent colour only when the server gave it none: one inside a coloured span keeps it. */ +.sc-line :is(a.ms-cmd-link, a[href], .ms-menu) { text-decoration: underline; text-underline-offset: 2px; - /* A clickable command link is an inline-block button; let its text wrap (and break long tokens) - so it can never be the one element that refuses to wrap and forces horizontal overflow. */ - white-space: normal; overflow-wrap: anywhere; - text-align: left; } -.sc-link:hover { +.sc-line :is(a.ms-cmd-link, a[href], .ms-menu):not([style^="color"] *) { + color: var(--acc2); +} +.sc-line :is(a.ms-cmd-link, a[href], .ms-menu):hover { color: var(--acc); background: var(--acc-soft); } +.sc-line a.ms-expired { + color: inherit; + text-decoration: none; + background: none; +} + +/* A Highlight trigger's colour, over whatever the server gave. */ +.sc-highlight, +.sc-highlight * { + color: var(--sc-highlight) !important; +} + +/* SGR 8: concealed text stays hidden when the glow's text-shadow is on. */ +.sc-line .ms-conceal { + text-shadow: none; +} + +/* SGR 5 / 6. Players who find it distracting have reduced motion set. */ +@media (prefers-reduced-motion: reduce) { + .ms-blink { animation: none; } +} /* ── Bottom nav ────────────────────────────────────────────────────────── */ .sc-nav { @@ -877,8 +918,3 @@ body { vertical-align: bottom; } -.sc-image-link { - padding: 0; - border: 0; - background: none; -} diff --git a/src/SharpClient.Web/Components/App.razor b/src/SharpClient.Web/Components/App.razor index 5d31766..2930fd2 100644 --- a/src/SharpClient.Web/Components/App.razor +++ b/src/SharpClient.Web/Components/App.razor @@ -7,6 +7,7 @@ + diff --git a/src/SharpClient.Web/SharpClient.Web.csproj b/src/SharpClient.Web/SharpClient.Web.csproj index a8630e5..07c2af3 100644 --- a/src/SharpClient.Web/SharpClient.Web.csproj +++ b/src/SharpClient.Web/SharpClient.Web.csproj @@ -12,7 +12,7 @@ - + diff --git a/tests/SharpClient.Tests/Presentation/SessionsViewModelTests.cs b/tests/SharpClient.Tests/Presentation/SessionsViewModelTests.cs index 0c71b0b..072a003 100644 --- a/tests/SharpClient.Tests/Presentation/SessionsViewModelTests.cs +++ b/tests/SharpClient.Tests/Presentation/SessionsViewModelTests.cs @@ -125,7 +125,7 @@ public async Task LineAppendedOnActiveSessionRaisesVmChanged() vm.Changed += () => fired = true; // Simulate server line arriving on the active session. - session.Append(new ScrollbackLine([])); + session.Append(new ScrollbackLine(MarkupString.MarkupText.Empty)); await Assert.That(fired).IsTrue(); } diff --git a/tests/SharpClient.Tests/Rendering/AnsiPaletteTests.cs b/tests/SharpClient.Tests/Rendering/AnsiPaletteTests.cs deleted file mode 100644 index 88497f4..0000000 --- a/tests/SharpClient.Tests/Rendering/AnsiPaletteTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -using SharpClient.Core.Rendering; - -namespace SharpClient.Tests.Rendering; - -public sealed class AnsiPaletteTests -{ - [Test] - [Arguments(0, "#3a3f4b")] - [Arguments(1, "#e06c75")] - [Arguments(7, "#abb2bf")] - [Arguments(8, "#5c6672")] - [Arguments(15, "#e8edf2")] - public async Task BaseSixteenMatchDesignTokens(int index, string hex) - { - await Assert.That(AnsiPalette.ToHex(index)).IsEqualTo(hex); - } - - [Test] - public async Task CubeBlackIsIndex16() - { - await Assert.That(AnsiPalette.ToHex(16)).IsEqualTo("#000000"); - } - - [Test] - public async Task CubeWhiteIsIndex231() - { - await Assert.That(AnsiPalette.ToHex(231)).IsEqualTo("#ffffff"); - } - - [Test] - public async Task GrayscaleRampStartsDark() - { - await Assert.That(AnsiPalette.ToHex(232)).IsEqualTo("#080808"); - } - - [Test] - public async Task OutOfRangeFallsBackToPhosphor() - { - await Assert.That(AnsiPalette.ToHex(999)).IsEqualTo("#c4d1c8"); - } - - [Test] - public async Task GrayscaleRampEndsAtIndex255() - { - // v = 8 + (255 − 232) × 10 = 8 + 230 = 238 = 0xEE - await Assert.That(AnsiPalette.ToHex(255)).IsEqualTo("#eeeeee"); - } - - [Test] - public async Task MidCubeIndex100Maps() - { - // n = 100 − 16 = 84; r = CubeSteps[84/36%6]=CubeSteps[2]=135=0x87 - // g = CubeSteps[84/6%6]=CubeSteps[2]=135=0x87; b = CubeSteps[84%6]=CubeSteps[0]=0=0x00 - await Assert.That(AnsiPalette.ToHex(100)).IsEqualTo("#878700"); - } - - [Test] - public async Task NegativeIndexFallsBackToPhosphor() - { - await Assert.That(AnsiPalette.ToHex(-1)).IsEqualTo("#c4d1c8"); - } -} diff --git a/tests/SharpClient.Tests/Rendering/AnsiParserTests.cs b/tests/SharpClient.Tests/Rendering/AnsiParserTests.cs deleted file mode 100644 index f49591a..0000000 --- a/tests/SharpClient.Tests/Rendering/AnsiParserTests.cs +++ /dev/null @@ -1,148 +0,0 @@ -using SharpClient.Core.Rendering; - -namespace SharpClient.Tests.Rendering; - -public sealed class AnsiParserTests -{ - [Test] - public async Task DefaultStyleHasDefaultColours() - { - var style = TextStyle.Default; - - await Assert.That(style.Foreground).IsEqualTo(AnsiColor.Default); - await Assert.That(style.Background).IsEqualTo(AnsiColor.Default); - await Assert.That(style.Bold).IsFalse(); - } - - [Test] - public async Task IndexedColourCarriesItsIndex() - { - var colour = AnsiColor.Indexed(200); - - await Assert.That(colour.Kind).IsEqualTo(AnsiColorKind.Indexed); - await Assert.That(colour.Index).IsEqualTo(200); - } - - [Test] - public async Task PlainTextIsOneDefaultSegment() - { - var segments = AnsiParser.Parse("hello world"); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("hello world"); - await Assert.That(segments[0].Style).IsEqualTo(TextStyle.Default); - } - - [Test] - public async Task RedForegroundAppliesToFollowingText() - { - var segments = AnsiParser.Parse("\e[31mred\e[0m normal"); - - await Assert.That(segments.Count).IsEqualTo(2); - await Assert.That(segments[0].Text).IsEqualTo("red"); - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Indexed(1)); - await Assert.That(segments[1].Text).IsEqualTo(" normal"); - await Assert.That(segments[1].Style.Foreground).IsEqualTo(AnsiColor.Default); - } - - [Test] - public async Task BrightForegroundMapsToHighIndex() - { - var segments = AnsiParser.Parse("\e[92mbright"); - - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Indexed(10)); - } - - [Test] - public async Task Xterm256ForegroundIsParsed() - { - var segments = AnsiParser.Parse("\e[38;5;208morange"); - - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Indexed(208)); - } - - [Test] - public async Task BoldAndUnderlineCombine() - { - var segments = AnsiParser.Parse("\e[1;4mhi"); - - await Assert.That(segments[0].Style.Bold).IsTrue(); - await Assert.That(segments[0].Style.Underline).IsTrue(); - } - - [Test] - public async Task NonSgrCsiIsStripped() - { - var segments = AnsiParser.Parse("a\e[2Kb"); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("ab"); - } - - [Test] - public async Task EmptyLineProducesNoSegments() - { - var segments = AnsiParser.Parse(string.Empty); - - await Assert.That(segments.Count).IsEqualTo(0); - } - - [Test] - public async Task TruecolorForegroundIsParsedAndLeavesBackgroundAlone() - { - var segments = AnsiParser.Parse("\e[38;2;40;50;60mX"); - - await Assert.That(segments[0].Style.Background).IsEqualTo(AnsiColor.Default); - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Rgb(40, 50, 60)); - } - - [Test] - public async Task TruecolorBackgroundIsParsed() - { - var segments = AnsiParser.Parse("\e[48;2;10;20;30mX"); - - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Default); - await Assert.That(segments[0].Style.Background).IsEqualTo(AnsiColor.Rgb(10, 20, 30)); - await Assert.That(segments[0].Text).IsEqualTo("X"); - } - - [Test] - public async Task TruecolorFollowedByOtherCodesAppliesBoth() - { - var segments = AnsiParser.Parse("\e[1;38;2;255;128;0;4mX"); - - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Rgb(255, 128, 0)); - await Assert.That(segments[0].Style.Bold).IsTrue(); - await Assert.That(segments[0].Style.Underline).IsTrue(); - } - - [Test] - public async Task TruncatedTruecolorIsConsumedWithoutColour() - { - // "38;2;40" is missing G and B: nothing is coloured, and "40" is not read as a background. - var segments = AnsiParser.Parse("\e[38;2;40mX"); - - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Default); - await Assert.That(segments[0].Style.Background).IsEqualTo(AnsiColor.Default); - } - - [Test] - public async Task OutOfRangeTruecolorComponentsAreClamped() - { - var segments = AnsiParser.Parse("\e[38;2;300;-5;128mX"); - - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Rgb(255, 0, 128)); - } - - [Test] - public async Task TrailingNewlineIsPreservedInSegmentText() - { - // A line delivered from the server may include a trailing '\n'. - // AnsiParser is not responsible for stripping it — the raw character - // must survive into the segment text unchanged. - var segments = AnsiParser.Parse("hello\n"); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("hello\n"); - } -} diff --git a/tests/SharpClient.Tests/Rendering/InlineImageTests.cs b/tests/SharpClient.Tests/Rendering/InlineImageTests.cs deleted file mode 100644 index fb9940a..0000000 --- a/tests/SharpClient.Tests/Rendering/InlineImageTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -using SharpClient.Core.Rendering; - -namespace SharpClient.Tests.Rendering; - -public sealed class InlineImageTests -{ - private static MxpParserState Mxp() => new() { IsMxpActive = true }; - - private static MxpParserState Pueblo() => new() { IsPuebloActive = true }; - - [Test] - public async Task MxpImageOnSecureLineJoinsUrlTypeAndName() - { - var segments = AnsiParser.Parse("\e[1z", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].ImageUrl).IsEqualTo("https://h.example/img/maps/map.png"); - await Assert.That(segments[0].Text).IsEqualTo("map.png"); - } - - [Test] - public async Task MxpImageAcceptsFnameAttribute() - { - var segments = AnsiParser.Parse("\e[1z", Mxp()); - - await Assert.That(segments[0].ImageUrl).IsEqualTo("https://h.example/a/b.jpg?x=1"); - await Assert.That(segments[0].Text).IsEqualTo("b.jpg"); - } - - [Test] - public async Task MxpImageOnOpenLineIsIgnored() - { - var segments = AnsiParser.Parse("before after", Mxp()); - - await Assert.That(segments.Any(s => s.ImageUrl is not null)).IsFalse(); - } - - [Test] - public async Task MxpImageWithBareFileNameAndNoUrlIsIgnored() - { - var segments = AnsiParser.Parse("\e[1z", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(0); - } - - [Test] - public async Task ImagesAreIgnoredWithoutMxpOrPueblo() - { - var segments = AnsiParser.Parse("\e[1z", new MxpParserState()); - - await Assert.That(segments.Any(s => s.ImageUrl is not null)).IsFalse(); - } - - [Test] - public async Task PuebloImgUsesSrcAndAlt() - { - var segments = AnsiParser.Parse("Look: \"a!", Pueblo()); - - await Assert.That(segments.Count).IsEqualTo(3); - await Assert.That(segments[1].ImageUrl).IsEqualTo("https://h.example/cat.gif"); - await Assert.That(segments[1].Text).IsEqualTo("a cat"); - await Assert.That(segments[2].Text).IsEqualTo("!"); - } - - [Test] - public async Task PuebloModeSwitchImgIsNotAPicture() - { - var segments = AnsiParser.Parse("", Pueblo()); - - await Assert.That(segments.Count).IsEqualTo(0); - } - - [Test] - [Arguments("javascript:alert(1)")] - [Arguments("file:///etc/passwd")] - [Arguments("/local/path.png")] - [Arguments("content://media/1")] - public async Task NonWebSchemesAreRefused(string src) - { - var segments = AnsiParser.Parse($"", Pueblo()); - - await Assert.That(segments.Count).IsEqualTo(0); - } - - [Test] - public async Task DataImageIsAccepted() - { - var segments = AnsiParser.Parse("", Pueblo()); - - await Assert.That(segments[0].ImageUrl).IsEqualTo("data:image/png;base64,iVBORw0KGgo="); - } - - [Test] - public async Task ImageInsideASendLinkIsClickable() - { - var segments = AnsiParser.Parse("\e[1z", Mxp()); - - await Assert.That(segments[0].ImageUrl).IsEqualTo("https://h.example/m.png"); - await Assert.That(segments[0].Command).IsEqualTo("look map"); - } -} diff --git a/tests/SharpClient.Tests/Rendering/LineHtml.cs b/tests/SharpClient.Tests/Rendering/LineHtml.cs new file mode 100644 index 0000000..c3db16c --- /dev/null +++ b/tests/SharpClient.Tests/Rendering/LineHtml.cs @@ -0,0 +1,84 @@ +using System.Text.RegularExpressions; +using AngleSharp.Dom; +using AngleSharp.Html.Parser; +using MarkupString; +using SharpClient.Core.Rendering; +using SharpClient.Core.Sessions; + +namespace SharpClient.Tests.Rendering; + +/// What the output view shows for a line (), parsed, for asserting on. +internal static partial class LineHtml +{ + private static readonly HtmlParser s_parser = new(); + + // What the stylesheet gives MarkupString's colour properties: the client's palette (OutputView sets + // --ms-ansi-N from OutputPalette), and the output's text colour and background (--pho, --outbg). + private const string OutputForeground = "#c4d1c8"; + private const string OutputBackground = "#090c10"; + + public static string Html(this ScrollbackLine line, bool showImages = true) => OutputHtml.Render(line.Content, showImages); + + /// The line's elements, inside a div standing for .sc-line. + public static IElement Dom(this MarkupText line, bool showImages = true) => + s_parser.ParseDocument("
" + OutputHtml.Render(line, showImages) + "
").Body!.FirstElementChild!; + + public static IElement Dom(this ScrollbackLine line, bool showImages = true) => line.Content.Dom(showImages); + + /// The commands the line's command links send, in order. + public static IReadOnlyList Commands(this IElement root) => + [.. root.QuerySelectorAll("a[xch_cmd]").Select(a => a.GetAttribute("xch_cmd")!)]; + + /// + /// The colour the element's text is drawn in, as #rrggbb, with the stylesheet's custom properties + /// resolved; null for the output's default. + /// + public static string? Color(this IElement element) => Resolve(Declaration(element, "color")); + + public static string? BackgroundColor(this IElement element) => Resolve(Declaration(element, "background-color")); + + /// Palette entry in the client's palette. + public static string Hex(int index) => OutputPalette.Hex(OutputPalette.Instance.Entry(index)); + + /// The nearest value of in a style attribute, from the element outwards. + private static string? Declaration(IElement element, string property) + { + for (var at = element; at is not null; at = at.ParentElement) + { + foreach (var declaration in (at.GetAttribute("style") ?? string.Empty).Split(';')) + { + var colon = declaration.IndexOf(':', StringComparison.Ordinal); + if (colon > 0 && declaration[..colon].Trim() == property) + { + return declaration[(colon + 1)..].Trim(); + } + } + } + + return null; + } + + private static string? Resolve(string? value) + { + if (value is null) + { + return null; + } + + if (AnsiSlot().Match(value) is { Success: true } slot) + { + return Hex(int.Parse(slot.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture)); + } + + if (value.StartsWith("var(--ms-fg", StringComparison.Ordinal)) + { + return OutputForeground; + } + + return value.StartsWith("var(--ms-bg", StringComparison.Ordinal) ? OutputBackground : value; + } + + // var(--ms-ansi-N, …) or var(--ms-ansi-bg-N, var(--ms-ansi-N, …)): OutputView sets only --ms-ansi-N. + [GeneratedRegex(@"^var\(--ms-ansi-(?:bg-)?(\d+),")] + private static partial Regex AnsiSlot(); +} diff --git a/tests/SharpClient.Tests/Rendering/MxpParserTests.cs b/tests/SharpClient.Tests/Rendering/MxpParserTests.cs deleted file mode 100644 index eb54980..0000000 --- a/tests/SharpClient.Tests/Rendering/MxpParserTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -using SharpClient.Core.Rendering; - -namespace SharpClient.Tests.Rendering; - -public sealed class MxpParserTests -{ - private static MxpParserState Mxp() => new() { IsMxpActive = true }; - - [Test] - public async Task SendOnSecureLineProducesCommandLink() - { - var segments = AnsiParser.Parse("\e[1zNorth", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("North"); - await Assert.That(segments[0].Command).IsEqualTo("go north"); - await Assert.That(segments[0].Hint).IsEqualTo("Move north"); - } - - [Test] - public async Task ShorthandSendUsesInnerTextAsCommand() - { - var segments = AnsiParser.Parse("\e[1zlook", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("look"); - await Assert.That(segments[0].Command).IsEqualTo("look"); - } - - [Test] - public async Task SendOnOpenLineIsStrippedWithNoCommand() - { - // No ESC[1z: line stays in Open mode, where Secure elements are forbidden. - var segments = AnsiParser.Parse("North", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("North"); // inner text shown as plain - await Assert.That(segments[0].Command).IsNull(); - } - - [Test] - public async Task LockSecurePersistsAcrossLines() - { - var mxp = Mxp(); - - // Lock-Secure makes Secure the persistent default. - _ = AnsiParser.Parse("\e[6zwelcome", mxp); - mxp.BeginLine(); // simulate next line start - - var segments = AnsiParser.Parse("Quit", mxp); - - await Assert.That(segments[0].Command).IsEqualTo("quit"); - } - - [Test] - public async Task LockedModeTreatsAngleBracketsAsLiteralText() - { - var segments = AnsiParser.Parse("\e[2za c", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("a c"); - await Assert.That(segments[0].Command).IsNull(); - } - - [Test] - public async Task PuebloAnchorWithXchCmdProducesCommandLink() - { - var mxp = new MxpParserState { IsPuebloActive = true }; - - var segments = AnsiParser.Parse("
North", mxp); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("North"); - await Assert.That(segments[0].Command).IsEqualTo("go north"); - await Assert.That(segments[0].Hint).IsEqualTo("Move"); - } - - [Test] - public async Task TagsAreInertWhenNeitherMxpNorPuebloActive() - { - // Default Parse (no MXP state) must behave exactly as before — '<' is literal. - var segments = AnsiParser.Parse("y"); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("y"); - await Assert.That(segments[0].Command).IsNull(); - } - - [Test] - public async Task LinkKeepsCommandAcrossSgrChangeInside() - { - var segments = AnsiParser.Parse("\e[1z\e[31mAttack\e[0m", Mxp()); - - await Assert.That(segments.Count).IsEqualTo(1); - await Assert.That(segments[0].Text).IsEqualTo("Attack"); - await Assert.That(segments[0].Command).IsEqualTo("hit"); - await Assert.That(segments[0].Style.Foreground).IsEqualTo(AnsiColor.Indexed(1)); - } -} diff --git a/tests/SharpClient.Tests/Rendering/MxpTagsTests.cs b/tests/SharpClient.Tests/Rendering/MxpTagsTests.cs index 2f86f5b..f97e0e6 100644 --- a/tests/SharpClient.Tests/Rendering/MxpTagsTests.cs +++ b/tests/SharpClient.Tests/Rendering/MxpTagsTests.cs @@ -8,7 +8,8 @@ public sealed class MxpTagsTests public async Task EmptyRequestListsEverySupportedTag() { var (supported, unsupported) = MxpTags.Answer([]); - await Assert.That(string.Join(",", supported)).IsEqualTo("send,image"); + await Assert.That(supported).Contains("send").And.Contains("image").And.Contains("color").And.Contains("a"); + await Assert.That(supported).DoesNotContain("frame").And.DoesNotContain("sound"); await Assert.That(unsupported).IsEmpty(); } @@ -23,9 +24,9 @@ public async Task TagsAreSortedIntoSupportedAndNot() [Test] public async Task AttributesAreAnsweredPerAttribute() { - var (supported, unsupported) = MxpTags.Answer(["send.href", "send.prompt", "image.url", "color.fore"]); - await Assert.That(string.Join(",", supported)).IsEqualTo("send.href,image.url"); - await Assert.That(string.Join(",", unsupported)).IsEqualTo("send.prompt,color.fore"); + var (supported, unsupported) = MxpTags.Answer(["send.href", "send.prompt", "image.url", "image.t", "color.fore", "font.face"]); + await Assert.That(string.Join(",", supported)).IsEqualTo("send.href,image.url,image.t,color.fore"); + await Assert.That(string.Join(",", unsupported)).IsEqualTo("send.prompt,font.face"); } [Test] diff --git a/tests/SharpClient.Tests/Rendering/OutputRenderingTests.cs b/tests/SharpClient.Tests/Rendering/OutputRenderingTests.cs new file mode 100644 index 0000000..754999e --- /dev/null +++ b/tests/SharpClient.Tests/Rendering/OutputRenderingTests.cs @@ -0,0 +1,604 @@ +using AngleSharp.Dom; +using SharpClient.Core.Rendering; +using static SharpClient.Tests.Rendering.LineHtml; + +namespace SharpClient.Tests.Rendering; + +/// +/// What a line from the server looks like once decoded and written as the output view's HTML: every +/// capability the old AnsiParser had, and the SGR it used to drop. +/// +public sealed class OutputRenderingTests +{ + private const string PuebloHtml = ""; + + private static IElement Plain(string raw) => Render(new OutputDecoder(), raw); + + private static IElement Mxp(string raw) + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + return Render(decoder, raw); + } + + private static IElement Pueblo(string raw, bool showImages = true) + { + var decoder = new OutputDecoder(); + decoder.EnablePueblo(); + decoder.Decode(PuebloHtml); + return Render(decoder, raw, showImages); + } + + private static IElement Render(OutputDecoder decoder, string raw, bool showImages = true) => + decoder.Decode(raw).Single().Dom(showImages); + + /// The innermost element around . + private static IElement At(IElement root, string text) => + root.Descendants().Last(e => e.TextContent == text); + + // ── ANSI ────────────────────────────────────────────────────────────── + + [Test] + public async Task PlainTextIsJustText() + { + var line = Plain("hello world"); + + await Assert.That(line.InnerHtml).IsEqualTo("hello world"); + } + + [Test] + public async Task TextIsEscaped() + { + await Assert.That(Plain("x & y").InnerHtml).IsEqualTo("<b>x</b> & y"); + } + + [Test] + public async Task EmptyLineIsEmpty() + { + await Assert.That(Plain(string.Empty).InnerHtml).IsEmpty(); + } + + [Test] + [Arguments("\e[31m", 1)] + [Arguments("\e[92m", 10)] + [Arguments("\e[38;5;208m", 208)] + [Arguments("\e[38;5;3m", 3)] + [Arguments("\e[38:5:208m", 208)] + public async Task PaletteColoursUseTheClientPalette(string sgr, int index) + { + await Assert.That(At(Plain(sgr + "x"), "x").Color()).IsEqualTo(Hex(index)); + } + + [Test] + public async Task StandardColoursAreTheClientsOwn() + { + await Assert.That(OutputPalette.CustomProperties).Contains("--ms-ansi-1:#e06c75"); + await Assert.That(OutputPalette.CustomProperties).Contains("--ms-ansi-15:#e8edf2"); + await Assert.That(At(Plain("\e[31mx"), "x").Color()).IsEqualTo("#e06c75"); + await Assert.That(At(Plain("\e[97mx"), "x").Color()).IsEqualTo("#e8edf2"); + await Assert.That(At(Plain("\e[44mx"), "x").BackgroundColor()).IsEqualTo("#61afef"); + await Assert.That(At(Plain("\e[38;5;16mx"), "x").Color()).IsEqualTo("#000000"); + await Assert.That(At(Plain("\e[38;5;232mx"), "x").Color()).IsEqualTo("#080808"); + } + + [Test] + public async Task ResetEndsTheColour() + { + var line = Plain("\e[31mred\e[0m normal"); + + await Assert.That(At(line, "red").Color()).IsEqualTo(Hex(1)); + await Assert.That(line.LastChild!.TextContent).IsEqualTo(" normal"); + await Assert.That(line.LastChild).IsTypeOf(); + } + + [Test] + public async Task StyleCarriesToTheNextLine() + { + var decoder = new OutputDecoder(); + decoder.Decode("\e[32mgreen"); + + await Assert.That(At(Render(decoder, "still green"), "still green").Color()).IsEqualTo(Hex(2)); + } + + [Test] + public async Task TruecolorForegroundAndBackground() + { + var fg = At(Plain("\e[38;2;40;50;60mX"), "X"); + var bg = At(Plain("\e[48;2;10;20;30mX"), "X"); + + await Assert.That(fg.Color()).IsEqualTo("#28323c"); + await Assert.That(fg.BackgroundColor()).IsNull(); + await Assert.That(bg.BackgroundColor()).IsEqualTo("#0a141e"); + await Assert.That(bg.Color()).IsNull(); + } + + [Test] + public async Task TruecolorAmongOtherCodesAppliesAll() + { + var span = At(Plain("\e[1;38;2;255;128;0;4mX"), "X"); + + await Assert.That(span.Color()).IsEqualTo("#ff8000"); + await Assert.That(span.ClassList).Contains("ms-bold"); + await Assert.That(span.ClassList).Contains("ms-underline"); + } + + [Test] + public async Task TruncatedTruecolorColoursNothing() + { + // "38;2;40" is missing G and B: nothing is coloured, and "40" is not read as a background. + await Assert.That(Plain("\e[38;2;40mX").InnerHtml).IsEqualTo("X"); + } + + [Test] + [Arguments("\e[1m", "ms-bold")] + [Arguments("\e[2m", "ms-faint")] + [Arguments("\e[3m", "ms-italic")] + [Arguments("\e[4m", "ms-underline")] + [Arguments("\e[21m", "ms-underline")] + [Arguments("\e[5m", "ms-blink")] + [Arguments("\e[8m", "ms-conceal")] + [Arguments("\e[9m", "ms-strike")] + [Arguments("\e[53m", "ms-overline")] + public async Task AttributesAreDrawn(string sgr, string cssClass) + { + await Assert.That(At(Plain(sgr + "x"), "x").ClassList).Contains(cssClass); + } + + [Test] + [Arguments("\e[1m", "\e[22m")] + [Arguments("\e[3m", "\e[23m")] + [Arguments("\e[4m", "\e[24m")] + [Arguments("\e[5m", "\e[25m")] + [Arguments("\e[7m", "\e[27m")] + [Arguments("\e[9m", "\e[29m")] + public async Task AttributesTurnOff(string on, string off) + { + var line = Plain(on + "a" + off + "b"); + + await Assert.That(line.LastChild!.TextContent).IsEqualTo("b"); + await Assert.That(line.LastChild).IsTypeOf(); + } + + [Test] + public async Task InverseSwapsColoursAgainstTheOutputDefaults() + { + var coloured = At(Plain("\e[32;7mx"), "x"); + var background = At(Plain("\e[41;7mx"), "x"); + var plain = At(Plain("\e[7mx"), "x"); + + await Assert.That(coloured.Color()).IsEqualTo("#090c10"); + await Assert.That(coloured.BackgroundColor()).IsEqualTo(Hex(2)); + await Assert.That(background.Color()).IsEqualTo(Hex(1)); + await Assert.That(background.BackgroundColor()).IsEqualTo("#c4d1c8"); + // No colour to swap: ms-invert, which the stylesheet draws with --ms-bg on --ms-fg. + await Assert.That(plain.ClassList).Contains("ms-invert"); + } + + [Test] + public async Task BoldIsNotBrightened() + { + await Assert.That(At(Plain("\e[1;31mx"), "x").Color()).IsEqualTo(Hex(1)); + } + + [Test] + public async Task OtherControlSequencesAreNotShown() + { + await Assert.That(Plain("a\e[?25lb\e[Hc").TextContent).IsEqualTo("abc"); + } + + [Test] + public async Task OscHyperlinkIsAWebLink() + { + var line = Plain("see \e]8;;https://example.com/help\e\\help\e]8;;\e\\ now"); + + var link = line.QuerySelector("a")!; + await Assert.That(link.TextContent).IsEqualTo("help"); + await Assert.That(link.GetAttribute("href")).IsEqualTo("https://example.com/help"); + await Assert.That(link.GetAttribute("target")).IsEqualTo("_blank"); + await Assert.That(link.GetAttribute("rel")).IsEqualTo("noopener noreferrer"); + await Assert.That(line.QuerySelectorAll("a").Length).IsEqualTo(1); + } + + [Test] + public async Task OscHyperlinkToAScriptIsText() + { + var line = Plain("\e]8;;javascript:alert(1)\e\\x\e]8;;\e\\"); + + await Assert.That(line.InnerHtml).IsEqualTo("x"); + } + + // A browser drops tabs and newlines from a URL, and spaces and controls around it, so these are all + // javascript: links once clicked. + [Test] + [Arguments("java script:alert(1)")] + [Arguments("java script:alert(1)")] + [Arguments(" javascript:alert(1)")] + [Arguments("javascript:alert(1)")] + [Arguments(" javascript:alert(1)")] + public async Task ScriptLinkHiddenByControlCharactersIsText(string href) + { + var mxp = Mxp($"\e[1zx"); + var pueblo = Pueblo($"x"); + + await Assert.That(mxp.QuerySelector("a")).IsNull(); + await Assert.That(mxp.TextContent).IsEqualTo("x"); + await Assert.That(pueblo.QuerySelector("a")).IsNull(); + await Assert.That(pueblo.TextContent).IsEqualTo("x"); + } + + // Two equal elements side by side are two: a client that joined them would send one command for both. + [Test] + [Arguments("\e[1znorthsouth", "a[xch_cmd]")] + [Arguments("\e[1znorthsouth", ".ms-menu")] + [Arguments("\e[1znorthsouth", "a[href]")] + public async Task EqualLinksSideBySideStayTwo(string raw, string selector) + { + var links = Mxp(raw).QuerySelectorAll(selector); + + await Assert.That(links.Select(link => link.TextContent)).IsEquivalentTo(["north", "south"]); + } + + [Test] + public async Task TwoPicturesOfOneFileSideBySideAreTwo() + { + var line = Mxp("\e[1z"); + + await Assert.That(line.QuerySelectorAll("img").Length).IsEqualTo(2); + } + + [Test] + public async Task LinkWithASpaceInsideIsKept() + { + var link = Mxp("\e[1zx").QuerySelector("a")!; + + await Assert.That(link.GetAttribute("href")).IsEqualTo("https://example.com/a b"); + } + + [Test] + public async Task OscHyperlinkToAScriptBehindATabIsText() + { + var line = Plain("\e]8;;java\tscript:alert(1)\e\\x\e]8;;\e\\"); + + await Assert.That(line.QuerySelector("a")).IsNull(); + } + + [Test] + public async Task MarkupIsLiteralWithoutMxpOrPueblo() + { + var line = Plain("y 5 > 3"); + + await Assert.That(line.TextContent).IsEqualTo("y 5 > 3"); + await Assert.That(line.Commands()).IsEmpty(); + } + + // ── MXP ─────────────────────────────────────────────────────────────── + + [Test] + public async Task SendOnSecureLineIsACommandLink() + { + var line = Mxp("\e[1zNorth"); + + var link = line.QuerySelector("a.ms-cmd-link")!; + await Assert.That(link.TextContent).IsEqualTo("North"); + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("go north"); + await Assert.That(link.GetAttribute("title")).IsEqualTo("Move north"); + await Assert.That(line.TextContent).IsEqualTo("North"); + } + + [Test] + public async Task ShorthandSendSendsItsText() + { + var line = Mxp("\e[1zlook"); + + await Assert.That(line.Commands()).IsEquivalentTo(["look"]); + } + + [Test] + public async Task SendOnOpenLineShowsItsTextOnly() + { + var line = Mxp("North"); + + await Assert.That(line.InnerHtml).IsEqualTo("North"); + } + + [Test] + public async Task LockSecurePersistsAcrossLines() + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + decoder.Decode("\e[6zwelcome"); + + await Assert.That(Render(decoder, "Quit").Commands()).IsEquivalentTo(["quit"]); + } + + [Test] + public async Task SecureLineModeEndsWithTheLine() + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + decoder.Decode("\e[1zsecure"); + + await Assert.That(Render(decoder, "Quit").Commands()).IsEmpty(); + } + + [Test] + public async Task SecureLineEndingInBreakEndsWithTheTelnetLine() + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + decoder.Decode("\e[1zserver
"); + + await Assert.That(Render(decoder, "Quit").Commands()).IsEmpty(); + } + + [Test] + public async Task LockedLineShowsMarkupAsText() + { + await Assert.That(Mxp("\e[2za c").TextContent).IsEqualTo("a c"); + } + + [Test] + public async Task ColourInsideALinkKeepsTheLink() + { + var line = Mxp("\e[1z\e[31mAttack\e[0m"); + + var link = line.QuerySelector("a.ms-cmd-link")!; + await Assert.That(link.TextContent).IsEqualTo("Attack"); + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("hit"); + await Assert.That(link.Color()).IsEqualTo(Hex(1)); + } + + [Test] + public async Task SendWithSeveralCommandsIsAMenu() + { + var line = Mxp("\e[1zsword"); + + var menu = line.QuerySelector(".ms-menu")!; + await Assert.That(menu.TextContent).IsEqualTo("sword"); + await Assert.That(menu.GetAttribute("title")).IsEqualTo("Sword"); + await Assert.That(menu.GetAttribute("data-commands")) + .IsEqualTo("[{\"label\":\"Buy\",\"command\":\"buy sword\"},{\"label\":\"Look\",\"command\":\"look sword\"}]"); + } + + [Test] + public async Task PromptSendIsAPromptMenu() + { + var line = Mxp("\e[1ztalk"); + + // markupstring.js asks the view's Prompt, which sends it. + await Assert.That(line.QuerySelector(".ms-menu.ms-prompt")!.TextContent).IsEqualTo("talk"); + } + + [Test] + public async Task EntitiesAreDecoded() + { + await Assert.That(Mxp("5 > 3 & <").TextContent).IsEqualTo("5 > 3 & <"); + } + + [Test] + public async Task OpenTagsStyleText() + { + var line = Mxp("bold it u s c"); + + await Assert.That(At(line, "bold").ClassList).Contains("ms-bold"); + await Assert.That(At(line, "it").ClassList).Contains("ms-italic"); + await Assert.That(At(line, "u").ClassList).Contains("ms-underline"); + await Assert.That(At(line, "s").ClassList).Contains("ms-strike"); + await Assert.That(At(line, "c").Color()).IsEqualTo("#ff0000"); + await Assert.That(At(line, "c").BackgroundColor()).IsEqualTo("#000080"); + } + + [Test] + public async Task MxpAnchorIsAWebLink() + { + var link = Mxp("\e[1zsite").QuerySelector("a")!; + + await Assert.That(link.GetAttribute("href")).IsEqualTo("https://example.com"); + await Assert.That(link.GetAttribute("title")).IsEqualTo("Site"); + } + + [Test] + public async Task BreakStartsANewLine() + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + + var lines = decoder.Decode("one
two"); + + await Assert.That(lines.Select(l => l.Text)).IsEquivalentTo(["one", "two"]); + } + + [Test] + public async Task MxpImageOnSecureLineIsAPicture() + { + var image = Mxp("\e[1z").QuerySelector("img")!; + + await Assert.That(image.GetAttribute("src")).IsEqualTo("https://h.example/a/b.jpg?x=1"); + await Assert.That(image.GetAttribute("alt")).IsEqualTo("b.jpg"); + await Assert.That(image.GetAttribute("referrerpolicy")).IsEqualTo("no-referrer"); + await Assert.That(image.GetAttribute("loading")).IsEqualTo("lazy"); + } + + [Test] + public async Task MxpImageJoinsUrlAndName() + { + var image = Mxp("\e[1z").QuerySelector("img")!; + + await Assert.That(image.GetAttribute("src")).IsEqualTo("https://h.example/img/map.png"); + } + + [Test] + public async Task MxpImageJoinsUrlTypeAndName() + { + var image = Mxp("\e[1z").QuerySelector("img")!; + + await Assert.That(image.GetAttribute("src")).IsEqualTo("https://h.example/img/maps/map.png"); + await Assert.That(image.GetAttribute("alt")).IsEqualTo("map.png"); + } + + [Test] + public async Task MxpImageSizeIsKept() + { + var image = Mxp("\e[1z").QuerySelector("img")!; + + await Assert.That(image.GetAttribute("width")).IsEqualTo("64"); + await Assert.That(image.GetAttribute("height")).IsEqualTo("32"); + } + + [Test] + public async Task MxpImageOnOpenLineIsNotAPicture() + { + await Assert.That(Mxp("before after").QuerySelector("img")).IsNull(); + } + + [Test] + public async Task MxpImageWithBareFileNameShowsNothing() + { + await Assert.That(Mxp("\e[1z").InnerHtml).IsEmpty(); + } + + [Test] + public async Task ImageInsideASendIsClickable() + { + var link = Mxp("\e[1z").QuerySelector("a.ms-cmd-link")!; + + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("look map"); + await Assert.That(link.QuerySelector("img")!.GetAttribute("src")).IsEqualTo("https://h.example/m.png"); + } + + [Test] + public async Task ImagesAreTextWithoutMxpOrPueblo() + { + await Assert.That(Plain("\e[1z").QuerySelector("img")).IsNull(); + } + + [Test] + public async Task CustomElementsExpand() + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + decoder.Decode("\e[1z'>"); + + var hall = At(Render(decoder, "\e[1zThe Hall"), "The Hall"); + + await Assert.That(hall.ClassList).Contains("ms-bold"); + await Assert.That(hall.Color()).IsEqualTo("#ff0000"); + } + + // ── Pueblo ──────────────────────────────────────────────────────────── + + [Test] + public async Task PuebloAnchorWithXchCmdIsACommandLink() + { + var link = Pueblo("North").QuerySelector("a.ms-cmd-link")!; + + await Assert.That(link.TextContent).IsEqualTo("North"); + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("go north"); + await Assert.That(link.GetAttribute("title")).IsEqualTo("Move"); + } + + [Test] + public async Task PuebloEntitiesAreDecoded() + { + await Assert.That(Pueblo("5 > 3 && 2 < 4 "q"").TextContent).IsEqualTo("5 > 3 && 2 < 4 \"q\""); + await Assert.That(Pueblo("it's here").TextContent).IsEqualTo("it's here"); + await Assert.That(Pueblo(">>&").TextContent).IsEqualTo(">>&"); + } + + [Test] + public async Task LoneAndUnknownAmpersandsStay() + { + await Assert.That(Pueblo("Tom & Jerry").TextContent).IsEqualTo("Tom & Jerry"); + await Assert.That(Pueblo("x¬athing;y").TextContent).IsEqualTo("x¬athing;y"); + } + + [Test] + public async Task EntityInsideAnAttributeIsDecoded() + { + await Assert.That(Pueblo("go").Commands()).IsEquivalentTo(["say 5 > 3"]); + } + + [Test] + public async Task GreaterThanInsideAQuotedAttributeDoesNotEndTheTag() + { + var line = Pueblo(" 3\">go"); + + await Assert.That(line.TextContent).IsEqualTo("go"); + await Assert.That(line.Commands()).IsEquivalentTo(["say 5 > 3"]); + } + + [Test] + public async Task PuebloImgUsesSrcAndAlt() + { + var line = Pueblo("Look: \"a!"); + + var image = line.QuerySelector("img")!; + await Assert.That(image.GetAttribute("src")).IsEqualTo("https://h.example/cat.gif"); + await Assert.That(image.GetAttribute("alt")).IsEqualTo("a cat"); + await Assert.That(line.TextContent).IsEqualTo("Look: !"); + } + + [Test] + public async Task ImagesOffShowsTheirName() + { + var line = Pueblo("Look: \"a!", showImages: false); + + await Assert.That(line.QuerySelector("img")).IsNull(); + await Assert.That(line.TextContent).IsEqualTo("Look: a cat!"); + } + + [Test] + public async Task PuebloModeSwitchesAndPageClearShowNothing() + { + var line = Pueblo(""); + + await Assert.That(line.TextContent).IsEmpty(); + await Assert.That(line.QuerySelector("img")).IsNull(); + } + + [Test] + [Arguments("javascript:alert(1)")] + [Arguments("file:///etc/passwd")] + [Arguments("/local/path.png")] + [Arguments("content://media/1")] + public async Task NonWebImageSourcesShowNothing(string src) + { + await Assert.That(Pueblo($"").InnerHtml).IsEmpty(); + await Assert.That(Pueblo($"", showImages: false).InnerHtml).IsEmpty(); + } + + [Test] + public async Task DataImageIsAccepted() + { + var image = Pueblo("").QuerySelector("img")!; + + await Assert.That(image.GetAttribute("src")).IsEqualTo("data:image/png;base64,iVBORw0KGgo="); + } + + [Test] + public async Task PuebloLineEndingInBreakAddsNoBlankLine() + { + var decoder = new OutputDecoder(); + decoder.EnablePueblo(); + decoder.Decode(PuebloHtml); + + var lines = decoder.Decode("Hello
"); + + await Assert.That(lines.Select(l => l.Text)).IsEquivalentTo(["Hello"]); + } + + [Test] + public async Task ResetForgetsProtocolsAndStyle() + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + decoder.Decode("\e[31m\e[6z"); + decoder.Reset(); + + var line = Render(decoder, "y"); + + await Assert.That(decoder.ActiveProtocol).IsNull(); + await Assert.That(line.TextContent).IsEqualTo("y"); + await Assert.That(line.Children.Length).IsEqualTo(0); + } +} diff --git a/tests/SharpClient.Tests/Rendering/PuebloEntityTests.cs b/tests/SharpClient.Tests/Rendering/PuebloEntityTests.cs deleted file mode 100644 index 92f2c44..0000000 --- a/tests/SharpClient.Tests/Rendering/PuebloEntityTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using SharpClient.Core.Rendering; - -namespace SharpClient.Tests.Rendering; - -/// -/// HTML-entity handling for Pueblo/MXP markup. In Pueblo HTML mode the server entity-encodes the -/// reserved characters (e.g. a literal '>' is sent as "&gt;"), so the client must decode them -/// on render — but only inside markup mode, and a lone/unknown '&' must pass through literally. -/// -public sealed class PuebloEntityTests -{ - private static MxpParserState Pueblo() => new() { IsPuebloActive = true }; - - private static string Render(string line, MxpParserState? mxp) - { - var sb = new System.Text.StringBuilder(); - foreach (var seg in AnsiParser.Parse(line, mxp)) - { - sb.Append(seg.Text); - } - - return sb.ToString(); - } - - [Test] - public async Task DecodesCoreEntitiesInPuebloMode() - { - await Assert.That(Render("5 > 3 && 2 < 4 "q"", Pueblo())) - .IsEqualTo("5 > 3 && 2 < 4 \"q\""); - } - - [Test] - public async Task DecodesAposAndNbsp() - { - await Assert.That(Render("it's here", Pueblo())).IsEqualTo("it's here"); - } - - [Test] - public async Task DecodesNumericDecimalAndHex() - { - await Assert.That(Render(">>&", Pueblo())).IsEqualTo(">>&"); - } - - [Test] - public async Task IgnoresControlRangeNumericEntities() - { - // U+0007 (BEL) is below U+0020: consumed but produces no output (matches MXP behaviour). - await Assert.That(Render("ab", Pueblo())).IsEqualTo("ab"); - } - - [Test] - public async Task LoneAmpersandPassesThroughLiterally() - { - await Assert.That(Render("Tom & Jerry", Pueblo())).IsEqualTo("Tom & Jerry"); - } - - [Test] - public async Task UnknownEntityPassesThroughLiterally() - { - await Assert.That(Render("x¬athing;y", Pueblo())).IsEqualTo("x¬athing;y"); - } - - [Test] - public async Task DoesNotDecodeEntitiesOutsideMarkupMode() - { - // No MXP/Pueblo active: '&' and entities are plain text, never decoded. - await Assert.That(Render("5 > 3", null)).IsEqualTo("5 > 3"); - } - - [Test] - public async Task DecodesEntitiesInMxpMode() - { - await Assert.That(Render("5 > 3", new MxpParserState { IsMxpActive = true })) - .IsEqualTo("5 > 3"); - } - - [Test] - public async Task EntityInsideAttributeValueIsDecoded() - { - var segs = AnsiParser.Parse("go", Pueblo()); - - await Assert.That(segs.Count).IsEqualTo(1); - await Assert.That(segs[0].Text).IsEqualTo("go"); - await Assert.That(segs[0].Command).IsEqualTo("say 5 > 3"); - } - - [Test] - public async Task RawGreaterThanInsideQuotedAttributeDoesNotTruncateTag() - { - // A literal '>' inside a quoted attribute must not end the tag early. - var segs = AnsiParser.Parse(" 3\">go", Pueblo()); - - await Assert.That(segs.Count).IsEqualTo(1); - await Assert.That(segs[0].Text).IsEqualTo("go"); - await Assert.That(segs[0].Command).IsEqualTo("say 5 > 3"); - } -} diff --git a/tests/SharpClient.Tests/Rendering/SegmentStyleTests.cs b/tests/SharpClient.Tests/Rendering/SegmentStyleTests.cs deleted file mode 100644 index fac2d57..0000000 --- a/tests/SharpClient.Tests/Rendering/SegmentStyleTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -using SharpClient.Core.Rendering; - -namespace SharpClient.Tests.Rendering; - -public sealed class SegmentStyleTests -{ - private static StyledSegment Seg(TextStyle style) => new("x", style); - - [Test] - public async Task DefaultIsPhosphorForeground() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default)); - - await Assert.That(css).IsEqualTo("color:#c4d1c8;"); - } - - [Test] - public async Task IndexedForegroundUsesPalette() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default with { Foreground = AnsiColor.Indexed(1) })); - - await Assert.That(css).IsEqualTo("color:#e06c75;"); - } - - [Test] - public async Task TruecolorForegroundAndBackgroundAreHex() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default with - { - Foreground = AnsiColor.Rgb(255, 128, 0), - Background = AnsiColor.Rgb(1, 2, 3), - })); - - await Assert.That(css).IsEqualTo("color:#ff8000;background:#010203;padding:0 2px;"); - } - - [Test] - public async Task IndexedBackgroundAddsPadding() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default with { Background = AnsiColor.Indexed(4) })); - - await Assert.That(css).IsEqualTo("color:#c4d1c8;background:#61afef;padding:0 2px;"); - } - - [Test] - public async Task InverseSwapsForegroundAndBackground() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default with { Foreground = AnsiColor.Indexed(2), Inverse = true })); - - await Assert.That(css).IsEqualTo("color:#090c10;background:#8fc16f;padding:0 2px;"); - } - - [Test] - public async Task InverseWithDefaultForegroundUsesPhosphorBackground() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default with { Inverse = true })); - - await Assert.That(css).IsEqualTo("color:#090c10;background:#c4d1c8;padding:0 2px;"); - } - - [Test] - public async Task BoldAndUnderlineAppend() - { - var css = SegmentStyle.ToCss(Seg(TextStyle.Default with { Bold = true, Underline = true })); - - await Assert.That(css).IsEqualTo("color:#c4d1c8;font-weight:700;text-decoration:underline;"); - } -} diff --git a/tests/SharpClient.Tests/Sessions/RuntimeWiringTests.cs b/tests/SharpClient.Tests/Sessions/RuntimeWiringTests.cs index 699338c..f13c10a 100644 --- a/tests/SharpClient.Tests/Sessions/RuntimeWiringTests.cs +++ b/tests/SharpClient.Tests/Sessions/RuntimeWiringTests.cs @@ -289,7 +289,7 @@ public async Task IncomingLineFiresTriggerNotification() } [Test] - public async Task IncomingLineUsesAnsiParserWhenNoTriggerEngine() + public async Task IncomingLineIsDecodedWhenNoTriggerEngine() { var conn = new FakeTelnetConnection(); await using var session = new Session(conn); @@ -297,7 +297,7 @@ public async Task IncomingLineUsesAnsiParserWhenNoTriggerEngine() conn.Emit("plain text"); await Assert.That(session.Scrollback.Count).IsEqualTo(1); - await Assert.That(session.Scrollback[0].Segments[0].Text).IsEqualTo("plain text"); + await Assert.That(session.Scrollback[0].Content.Text).IsEqualTo("plain text"); } [Test] diff --git a/tests/SharpClient.Tests/Sessions/ScrollbackConcurrencyTests.cs b/tests/SharpClient.Tests/Sessions/ScrollbackConcurrencyTests.cs index 57538e8..057086a 100644 --- a/tests/SharpClient.Tests/Sessions/ScrollbackConcurrencyTests.cs +++ b/tests/SharpClient.Tests/Sessions/ScrollbackConcurrencyTests.cs @@ -43,7 +43,7 @@ public async Task EnumeratingScrollbackWhileLinesArriveDoesNotThrow() var seen = 0; foreach (var line in session.Scrollback) { - seen += line.Segments.Count; + seen += line.Content.Runs.Length; } } } diff --git a/tests/SharpClient.Tests/Sessions/SessionMxpTests.cs b/tests/SharpClient.Tests/Sessions/SessionMxpTests.cs index ab34387..3babd5e 100644 --- a/tests/SharpClient.Tests/Sessions/SessionMxpTests.cs +++ b/tests/SharpClient.Tests/Sessions/SessionMxpTests.cs @@ -1,9 +1,13 @@ using SharpClient.Core.Sessions; +using SharpClient.Tests.Rendering; namespace SharpClient.Tests.Sessions; public sealed class SessionMxpTests { + // What a Pueblo server sends once the client has answered PUEBLOCLIENT: leave MUD text for HTML. + private const string PuebloHtml = ""; + [Test] public async Task MxpSecureSendBecomesClickableSegment() { @@ -13,9 +17,9 @@ public async Task MxpSecureSendBecomesClickableSegment() conn.EnableMxp(); conn.Emit("\e[1zLook here"); - var line = session.Scrollback[^1]; - await Assert.That(line.Segments[0].Text).IsEqualTo("Look here"); - await Assert.That(line.Segments[0].Command).IsEqualTo("look"); + var link = session.Scrollback[^1].Dom().QuerySelector("a[xch_cmd]")!; + await Assert.That(link.TextContent).IsEqualTo("Look here"); + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("look"); } [Test] @@ -27,7 +31,7 @@ public async Task SendIsNotClickableWhenMxpNeverNegotiated() // No EnableMxp(): markup must pass through inert, never clickable. conn.Emit("\e[1zclick"); - await Assert.That(session.Scrollback[^1].Segments[0].Command).IsNull(); + await Assert.That(session.Scrollback[^1].Dom().Commands()).IsEmpty(); } [Test] @@ -37,11 +41,12 @@ public async Task PuebloModeFromTheServerEnablesLinks() await using var session = new Session(conn); conn.EnablePueblo(); + conn.Emit(PuebloHtml); conn.Emit("North"); - var line = session.Scrollback[^1]; - await Assert.That(line.Segments[0].Text).IsEqualTo("North"); - await Assert.That(line.Segments[0].Command).IsEqualTo("go north"); + var link = session.Scrollback[^1].Dom().QuerySelector("a[xch_cmd]")!; + await Assert.That(link.TextContent).IsEqualTo("North"); + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("go north"); } [Test] @@ -53,10 +58,11 @@ public async Task QuotedPuebloHelloDoesNotEnablePueblo() // A player can say the hello. Only the server's start sequence (via TNC) enables Pueblo, so // the anchor that follows must stay inert and nothing may be sent. conn.Emit("Bob says, \"This world is Pueblo 1.10 Enhanced.\""); + conn.Emit(PuebloHtml); conn.Emit("free stuff"); await Assert.That(conn.Sent).IsEmpty(); - await Assert.That(session.Scrollback[^1].Segments.All(s => s.Command is null)).IsTrue(); + await Assert.That(session.Scrollback[^1].Dom().Commands()).IsEmpty(); } [Test] @@ -67,10 +73,12 @@ public async Task MarkupStateIsDroppedWhenTheConnectionGoesDown() conn.RaiseState(SharpClient.Core.Connection.ConnectionState.Connected); conn.EnablePueblo(); + conn.Emit(PuebloHtml); conn.RaiseState(SharpClient.Core.Connection.ConnectionState.Reconnecting); conn.RaiseState(SharpClient.Core.Connection.ConnectionState.Connected); + conn.Emit(PuebloHtml); conn.Emit("North"); - await Assert.That(session.Scrollback[^1].Segments.All(s => s.Command is null)).IsTrue(); + await Assert.That(session.Scrollback[^1].Dom().Commands()).IsEmpty(); } } diff --git a/tests/SharpClient.Tests/Sessions/SessionStateTests.cs b/tests/SharpClient.Tests/Sessions/SessionStateTests.cs index 49abdb9..7cc9932 100644 --- a/tests/SharpClient.Tests/Sessions/SessionStateTests.cs +++ b/tests/SharpClient.Tests/Sessions/SessionStateTests.cs @@ -30,7 +30,7 @@ public async Task SessionParsesLinesFromAnyConnection() fake.Emit("plain"); await Assert.That(session.Scrollback.Count).IsEqualTo(1); - await Assert.That(session.Scrollback[0].Segments[0].Text).IsEqualTo("plain"); + await Assert.That(session.Scrollback[0].Content.Text).IsEqualTo("plain"); } [Test] diff --git a/tests/SharpClient.Tests/Sessions/SessionTests.cs b/tests/SharpClient.Tests/Sessions/SessionTests.cs index a89f8ed..54cc97c 100644 --- a/tests/SharpClient.Tests/Sessions/SessionTests.cs +++ b/tests/SharpClient.Tests/Sessions/SessionTests.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using SharpClient.Core.Connection; using SharpClient.Core.Sessions; +using SharpClient.Tests.Rendering; using SharpClient.Tests.Connection; using TelnetNegotiationCore.Builders; @@ -46,8 +47,10 @@ public async Task ReceivedLineIsParsedIntoScrollback() await server.SendLineAsync("\e[31mAlert\e[0m"); var line = await appended.Task.WaitAsync(TimeSpan.FromSeconds(5)); - await Assert.That(line.Segments.Count).IsEqualTo(1); - await Assert.That(line.Segments[0].Text).IsEqualTo("Alert"); + var dom = line.Dom(); + await Assert.That(dom.Children.Length).IsEqualTo(1); + await Assert.That(dom.TextContent).IsEqualTo("Alert"); + await Assert.That(dom.FirstElementChild!.Color()).IsEqualTo("#e06c75"); await Assert.That(session.Scrollback.Count).IsEqualTo(1); } @@ -63,6 +66,6 @@ public async Task SendAppendsLocalEcho() await Assert.That(conn.Sent).Contains("hello"); // ...and locally echoed into the scrollback so the user sees what they typed. await Assert.That(session.Scrollback.Count).IsEqualTo(1); - await Assert.That(session.Scrollback[0].Segments[0].Text).Contains("hello"); + await Assert.That(session.Scrollback[0].Content.Text).IsEqualTo("> hello"); } } diff --git a/tests/SharpClient.Tests/SharpClient.Tests.csproj b/tests/SharpClient.Tests/SharpClient.Tests.csproj index a413c0b..71f42cc 100644 --- a/tests/SharpClient.Tests/SharpClient.Tests.csproj +++ b/tests/SharpClient.Tests/SharpClient.Tests.csproj @@ -12,6 +12,7 @@ + diff --git a/tests/SharpClient.Tests/Triggers/TriggerEngineTests.cs b/tests/SharpClient.Tests/Triggers/TriggerEngineTests.cs index 721f239..577d30e 100644 --- a/tests/SharpClient.Tests/Triggers/TriggerEngineTests.cs +++ b/tests/SharpClient.Tests/Triggers/TriggerEngineTests.cs @@ -1,5 +1,6 @@ using SharpClient.Core.Domain; using SharpClient.Core.Rendering; +using SharpClient.Tests.Rendering; using SharpClient.Core.Triggers; namespace SharpClient.Tests.Triggers; @@ -8,24 +9,42 @@ public sealed class TriggerEngineTests { private readonly TriggerEngine _engine = new(); + private static TriggerOutcome Apply(TriggerEngine engine, string raw, IReadOnlyList rules) => + engine.Apply(raw, new OutputDecoder().Decode(raw), rules); + + /// + /// For each line, the Highlight colour over the whole of it, or null when it has none. The stylesheet + /// draws everything inside .sc-highlight in --sc-highlight. + /// + private static IReadOnlyList Highlights(TriggerOutcome outcome) => + [.. outcome.Lines.Select(line => + { + var dom = line.Dom(); + return dom.Children is [{ } only] && only.ClassList.Contains("sc-highlight") && only.TextContent == dom.TextContent + ? only.GetAttribute("style")!.Replace("--sc-highlight: ", string.Empty, StringComparison.Ordinal) + : null; + })]; + + private static string Hex(int index) => LineHtml.Hex(index); + [Test] - public async Task NoRulesReturnsAnsiParsedSegmentsAndEmptyActions() + public async Task NoRulesReturnsTheDecodedLinesAndEmptyActions() { - var outcome = _engine.Apply("hello world", []); + var decoded = new OutputDecoder().Decode("hello world"); + var outcome = _engine.Apply("hello world", decoded, []); - var expected = AnsiParser.Parse("hello world"); - await Assert.That(outcome.Segments.Count).IsEqualTo(expected.Count); - await Assert.That(outcome.Segments[0]).IsEqualTo(expected[0]); + await Assert.That(outcome.Lines).IsEqualTo(decoded); await Assert.That(outcome.SendCommands).IsEmpty(); await Assert.That(outcome.Notifications).IsEmpty(); } [Test] - public async Task NoRulesEmptyLineReturnsEmptySegmentsAndEmptyActions() + public async Task NoRulesEmptyLineReturnsOneEmptyLineAndEmptyActions() { - var outcome = _engine.Apply(string.Empty, []); + var outcome = Apply(_engine, string.Empty, []); - await Assert.That(outcome.Segments).IsEmpty(); + await Assert.That(outcome.Lines.Count).IsEqualTo(1); + await Assert.That(outcome.Lines.Single().Dom().InnerHtml).IsEmpty(); await Assert.That(outcome.SendCommands).IsEmpty(); await Assert.That(outcome.Notifications).IsEmpty(); } @@ -41,7 +60,7 @@ public async Task SubstringMatchSendIsCollected() ActionValue = "attack dragon", }; - var outcome = _engine.Apply("A dragon appears!", [rule]); + var outcome = Apply(_engine, "A dragon appears!", [rule]); await Assert.That(outcome.SendCommands).Contains("attack dragon"); await Assert.That(outcome.Notifications).IsEmpty(); @@ -58,7 +77,7 @@ public async Task SubstringMatchNotifyIsCollected() ActionValue = "HP critical!", }; - var outcome = _engine.Apply("Your health low, be careful.", [rule]); + var outcome = Apply(_engine, "Your health low, be careful.", [rule]); await Assert.That(outcome.Notifications).Contains("HP critical!"); await Assert.That(outcome.SendCommands).IsEmpty(); @@ -75,7 +94,7 @@ public async Task RegexMatchSendIsCollected() ActionValue = "loot", }; - var outcome = _engine.Apply("You kill the goblin.", [rule]); + var outcome = Apply(_engine, "You kill the goblin.", [rule]); await Assert.That(outcome.SendCommands).Contains("loot"); } @@ -91,7 +110,7 @@ public async Task RegexNoMatchContributesNothing() ActionValue = "flee", }; - var outcome = _engine.Apply("A dragon appears!", [rule]); + var outcome = Apply(_engine, "A dragon appears!", [rule]); await Assert.That(outcome.SendCommands).IsEmpty(); } @@ -107,7 +126,7 @@ public async Task SubstringNoMatchContributesNothing() ActionValue = "flee", }; - var outcome = _engine.Apply("A dragon appears!", [rule]); + var outcome = Apply(_engine, "A dragon appears!", [rule]); await Assert.That(outcome.SendCommands).IsEmpty(); } @@ -124,7 +143,7 @@ public async Task DisabledRuleIsIgnored() Enabled = false, }; - var outcome = _engine.Apply("A dragon appears!", [rule]); + var outcome = Apply(_engine, "A dragon appears!", [rule]); await Assert.That(outcome.SendCommands).IsEmpty(); } @@ -140,13 +159,13 @@ public async Task InvalidRegexPatternDoesNotThrowTreatedAsNoMatch() ActionValue = "should not appear", }; - var outcome = _engine.Apply("some line", [rule]); + var outcome = Apply(_engine, "some line", [rule]); await Assert.That(outcome.SendCommands).IsEmpty(); } [Test] - public async Task HighlightRestylesAllSegmentsWithGivenIndex() + public async Task HighlightRestylesAllSpansWithGivenIndex() { var rule = new TriggerRule { @@ -156,17 +175,13 @@ public async Task HighlightRestylesAllSegmentsWithGivenIndex() ActionValue = "196", }; - var outcome = _engine.Apply("the red dragon", [rule]); + var outcome = Apply(_engine, "the red dragon", [rule]); - await Assert.That(outcome.Segments).IsNotEmpty(); - foreach (var segment in outcome.Segments) - { - await Assert.That(segment.Style.Foreground).IsEqualTo(AnsiColor.Indexed(196)); - } + await Assert.That(Highlights(outcome)).IsEquivalentTo([(string?)Hex(196)]); } [Test] - public async Task HighlightWithAnsiInputRestylesAllSegments() + public async Task HighlightWithAnsiInputRestylesAllSpans() { var rule = new TriggerRule { @@ -176,12 +191,11 @@ public async Task HighlightWithAnsiInputRestylesAllSegments() ActionValue = "9", }; - // Two segments: "danger" (red fg) and " ahead" (default) - var outcome = _engine.Apply("\e[31mdanger\e[0m ahead", [rule]); + // "danger" is red and " ahead" default; the highlight covers both, the server's red included. + var outcome = Apply(_engine, "\e[31mdanger\e[0m ahead", [rule]); - await Assert.That(outcome.Segments.Count).IsEqualTo(2); - await Assert.That(outcome.Segments[0].Style.Foreground).IsEqualTo(AnsiColor.Indexed(9)); - await Assert.That(outcome.Segments[1].Style.Foreground).IsEqualTo(AnsiColor.Indexed(9)); + await Assert.That(Highlights(outcome)).IsEquivalentTo([(string?)Hex(9)]); + await Assert.That(outcome.Lines.Single().Dom().TextContent).IsEqualTo("danger ahead"); } [Test] @@ -195,9 +209,9 @@ public async Task HighlightInvalidActionValueDoesNotApplyHighlight() ActionValue = "not-a-number", }; - var outcome = _engine.Apply("hello world", [rule]); + var outcome = Apply(_engine, "hello world", [rule]); - await Assert.That(outcome.Segments[0].Style.Foreground).IsEqualTo(AnsiColor.Default); + await Assert.That(Highlights(outcome)).IsEquivalentTo([(string?)null]); } [Test] @@ -218,7 +232,7 @@ public async Task MultipleMatchingRulesAccumulate() ActionValue = "Dragon spotted!", }; - var outcome = _engine.Apply("The dragon roars.", [sendRule, notifyRule]); + var outcome = Apply(_engine, "The dragon roars.", [sendRule, notifyRule]); await Assert.That(outcome.SendCommands).Contains("attack"); await Assert.That(outcome.Notifications).Contains("Dragon spotted!"); @@ -242,12 +256,9 @@ public async Task LaterHighlightRuleOverridesEarlierOne() ActionValue = "9", }; - var outcome = _engine.Apply("The dragon roars.", [first, second]); + var outcome = Apply(_engine, "The dragon roars.", [first, second]); - foreach (var segment in outcome.Segments) - { - await Assert.That(segment.Style.Foreground).IsEqualTo(AnsiColor.Indexed(9)); - } + await Assert.That(Highlights(outcome)).IsEquivalentTo([(string?)Hex(9)]); } [Test] @@ -268,7 +279,7 @@ public async Task MultipleSendCommandsAllCollected() ActionValue = "loot", }; - var outcome = _engine.Apply("The dragon dies.", [rule1, rule2]); + var outcome = Apply(_engine, "The dragon dies.", [rule1, rule2]); await Assert.That(outcome.SendCommands.Count).IsEqualTo(2); await Assert.That(outcome.SendCommands).Contains("attack"); @@ -295,17 +306,13 @@ public async Task HighlightOutOfRangeActionValueSkippedFirstColourKept() ActionValue = "256", // out of range — skipped }; - var outcome = _engine.Apply("brave hero stands", [first, second]); + var outcome = Apply(_engine, "brave hero stands", [first, second]); - await Assert.That(outcome.Segments).IsNotEmpty(); - foreach (var segment in outcome.Segments) - { - await Assert.That(segment.Style.Foreground).IsEqualTo(AnsiColor.Indexed(3)); - } + await Assert.That(Highlights(outcome)).IsEquivalentTo([(string?)Hex(3)]); } [Test] - public async Task HighlightOnlyOutOfRangeActionValueLeavesSegmentsDefault() + public async Task HighlightOnlyOutOfRangeActionValueLeavesSpansDefault() { var rule = new TriggerRule { @@ -315,12 +322,8 @@ public async Task HighlightOnlyOutOfRangeActionValueLeavesSegmentsDefault() ActionValue = "256", // out of range — no highlight applied }; - var outcome = _engine.Apply("brave hero stands", [rule]); + var outcome = Apply(_engine, "brave hero stands", [rule]); - await Assert.That(outcome.Segments).IsNotEmpty(); - foreach (var segment in outcome.Segments) - { - await Assert.That(segment.Style.Foreground).IsEqualTo(AnsiColor.Default); - } + await Assert.That(Highlights(outcome)).IsEquivalentTo([(string?)null]); } } diff --git a/tests/SharpClient.UI.Tests/OutputViewLinkTests.cs b/tests/SharpClient.UI.Tests/OutputViewLinkTests.cs index 734e6ee..f9aa165 100644 --- a/tests/SharpClient.UI.Tests/OutputViewLinkTests.cs +++ b/tests/SharpClient.UI.Tests/OutputViewLinkTests.cs @@ -5,85 +5,170 @@ namespace SharpClient.UI.Tests; +/// +/// The links, menus and pictures the output view writes. markupstring.js acts on the links and menus in a +/// browser; here, its calls back into the view are . +/// public sealed class OutputViewLinkTests { - private static ScrollbackLine Line(params StyledSegment[] segments) => new(segments); + private static ScrollbackLine[] Mxp(string raw) + { + var decoder = new OutputDecoder(); + decoder.EnableMxp(); + return [.. decoder.Decode(raw).Select(content => new ScrollbackLine(content))]; + } + + private static ScrollbackLine[] Pueblo(string raw) + { + var decoder = new OutputDecoder(); + decoder.EnablePueblo(); + decoder.Decode(""); + return [.. decoder.Decode(raw).Select(content => new ScrollbackLine(content))]; + } + + private static IRenderedComponent Render(BunitContext ctx, ScrollbackLine[] lines, bool showImages = true) + { + ctx.JSInterop.Mode = JSRuntimeMode.Loose; + return ctx.Render(p => p.Add(c => c.Lines, lines).Add(c => c.ShowImages, showImages)); + } + + [Test] + public async Task CommandLinkIsAKeyboardReachableAnchorForTheScript() + { + using var ctx = new BunitContext(); + var cut = Render(ctx, Mxp("\e[1zNorth")); + + var link = cut.Find("a.ms-cmd-link"); + await Assert.That(link.TextContent).IsEqualTo("North"); + await Assert.That(link.GetAttribute("xch_cmd")).IsEqualTo("go north"); + await Assert.That(link.GetAttribute("title")).IsEqualTo("Move north"); + await Assert.That(link.GetAttribute("role")).IsEqualTo("button"); + await Assert.That(link.GetAttribute("tabindex")).IsEqualTo("0"); + } [Test] - public async Task CommandSegmentRendersClickableButtonThatSendsCommand() + public async Task CommandLinkKeepsItsColour() { using var ctx = new BunitContext(); - string? sent = null; - var line = Line(new StyledSegment("North", TextStyle.Default) { Command = "go north", Hint = "Move north" }); + var cut = Render(ctx, Mxp("\e[1z\e[31mAttack\e[0m")); - var cut = ctx.Render(p => p - .Add(c => c.Lines, new[] { line }) - .Add(c => c.OnSendCommand, cmd => { sent = cmd; return Task.CompletedTask; })); + // The stylesheet gives a link the accent colour only outside a span with a colour of its own. + await Assert.That(cut.Find("a.ms-cmd-link").ParentElement!.GetAttribute("style")).StartsWith("color: var(--ms-ansi-1,"); + } - var button = cut.Find("button.sc-link"); - await Assert.That(button.TextContent).IsEqualTo("North"); - await Assert.That(button.GetAttribute("title")).IsEqualTo("Move north"); + [Test] + public async Task PuebloCommandLinkIsACommandLink() + { + using var ctx = new BunitContext(); + var cut = Render(ctx, Pueblo("North")); - button.Click(); - await Assert.That(sent).IsEqualTo("go north"); + await Assert.That(cut.Find("a.ms-cmd-link").GetAttribute("xch_cmd")).IsEqualTo("go north"); } [Test] - public async Task PlainSegmentStillRendersSpanNotButton() + public async Task PlainTextHasNoLink() { using var ctx = new BunitContext(); - var line = Line(new StyledSegment("plain", TextStyle.Default)); + var cut = Render(ctx, Mxp("plain")); + + await Assert.That(cut.FindAll("a").Count).IsEqualTo(0); + await Assert.That(cut.Find("div.sc-line").TextContent).IsEqualTo("plain"); + } - var cut = ctx.Render(p => p - .Add(c => c.Lines, new[] { line }) - .Add(c => c.OnSendCommand, _ => Task.CompletedTask)); + [Test] + public async Task SendWithSeveralCommandsIsAMenuForTheScript() + { + using var ctx = new BunitContext(); + var cut = Render(ctx, Mxp("\e[1zsword")); - await Assert.That(cut.FindAll("button.sc-link").Count).IsEqualTo(0); - await Assert.That(cut.Find("span").TextContent).IsEqualTo("plain"); + var menu = cut.Find("span.ms-menu"); + await Assert.That(menu.TextContent).IsEqualTo("sword"); + await Assert.That(menu.GetAttribute("aria-haspopup")).IsEqualTo("menu"); + await Assert.That(menu.GetAttribute("data-commands")) + .IsEqualTo("[{\"label\":\"Buy\",\"command\":\"buy sword\"},{\"label\":\"Look\",\"command\":\"look sword\"}]"); } [Test] - public async Task ImageSegmentRendersImgWithoutReferrer() + public async Task WebLinkOpensInANewWindowWithoutAReferrer() { using var ctx = new BunitContext(); - var line = Line(new StyledSegment("a cat", TextStyle.Default) { ImageUrl = "https://h.example/cat.gif" }); + var cut = Render(ctx, Mxp("see \e]8;;https://example.com/help\e\\help\e]8;;\e\\")); - var cut = ctx.Render(p => p.Add(c => c.Lines, new[] { line })); + var link = cut.Find("a[href]"); + await Assert.That(link.GetAttribute("href")).IsEqualTo("https://example.com/help"); + await Assert.That(link.GetAttribute("target")).IsEqualTo("_blank"); + await Assert.That(link.GetAttribute("rel")).IsEqualTo("noopener noreferrer"); + await Assert.That(link.TextContent).IsEqualTo("help"); + } + + [Test] + public async Task ImageRendersImgWithoutReferrer() + { + using var ctx = new BunitContext(); + var cut = Render(ctx, Pueblo("\"a")); var img = cut.Find("img.sc-image"); await Assert.That(img.GetAttribute("src")).IsEqualTo("https://h.example/cat.gif"); await Assert.That(img.GetAttribute("alt")).IsEqualTo("a cat"); + await Assert.That(img.GetAttribute("width")).IsEqualTo("40"); await Assert.That(img.GetAttribute("referrerpolicy")).IsEqualTo("no-referrer"); - await Assert.That(cut.FindAll("button").Count).IsEqualTo(0); + await Assert.That(cut.FindAll("a").Count).IsEqualTo(0); } [Test] - public async Task ImageInsideCommandLinkIsAClickableButton() + public async Task MxpImageIsNamedAfterItsFile() { using var ctx = new BunitContext(); - string? sent = null; - var line = Line(new StyledSegment("map", TextStyle.Default) { ImageUrl = "https://h.example/m.png", Command = "look map" }); + var cut = Render(ctx, Mxp("\e[1z")); + + var img = cut.Find("img.sc-image"); + await Assert.That(img.GetAttribute("src")).IsEqualTo("https://h.example/img/maps/map.png"); + await Assert.That(img.GetAttribute("alt")).IsEqualTo("map.png"); + } - var cut = ctx.Render(p => p - .Add(c => c.Lines, new[] { line }) - .Add(c => c.OnSendCommand, cmd => { sent = cmd; return Task.CompletedTask; })); + [Test] + public async Task ImageInsideCommandLinkIsInsideTheLink() + { + using var ctx = new BunitContext(); + var cut = Render(ctx, Mxp("\e[1z")); - cut.Find("button.sc-image-link img.sc-image"); - cut.Find("button.sc-image-link").Click(); - await Assert.That(sent).IsEqualTo("look map"); + await Assert.That(cut.Find("a.ms-cmd-link img.sc-image").GetAttribute("src")).IsEqualTo("https://h.example/m.png"); + await Assert.That(cut.Find("a.ms-cmd-link").GetAttribute("xch_cmd")).IsEqualTo("look map"); } [Test] public async Task ImagesOffRendersTheTextInstead() { using var ctx = new BunitContext(); - var line = Line(new StyledSegment("a cat", TextStyle.Default) { ImageUrl = "https://h.example/cat.gif" }); + var cut = Render(ctx, Pueblo("\"a"), showImages: false); + + await Assert.That(cut.FindAll("img").Count).IsEqualTo(0); + await Assert.That(cut.Find("div.sc-line").TextContent).IsEqualTo("a cat"); + } - var cut = ctx.Render(p => p - .Add(c => c.Lines, new[] { line }) - .Add(c => c.ShowImages, false)); + [Test] + public async Task TurningImagesOffRedrawsTheLines() + { + using var ctx = new BunitContext(); + var lines = Pueblo("\"a"); + var cut = Render(ctx, lines); + + cut.Render(p => p.Add(c => c.ShowImages, false)); + + await Assert.That(cut.FindAll("img").Count).IsEqualTo(0); + await Assert.That(cut.Find("div.sc-line").TextContent).IsEqualTo("a cat"); + } + + [Test] + [Arguments("javascript:alert(1)")] + [Arguments("file:///etc/passwd")] + [Arguments("/local/path.png")] + public async Task RefusedImageSourceShowsNothing(string src) + { + using var ctx = new BunitContext(); + var cut = Render(ctx, Pueblo($"\"x\"")); await Assert.That(cut.FindAll("img").Count).IsEqualTo(0); - await Assert.That(cut.Markup).Contains("a cat"); + await Assert.That(cut.Find("div.sc-line").InnerHtml).IsEmpty(); } } diff --git a/tests/SharpClient.UI.Tests/OutputViewTests.cs b/tests/SharpClient.UI.Tests/OutputViewTests.cs index f8c4ff2..7dce66e 100644 --- a/tests/SharpClient.UI.Tests/OutputViewTests.cs +++ b/tests/SharpClient.UI.Tests/OutputViewTests.cs @@ -7,33 +7,139 @@ namespace SharpClient.UI.Tests; public sealed class OutputViewTests { - private static ScrollbackLine Line(params StyledSegment[] segments) => new(segments); + private static ScrollbackLine[] Lines(string raw) => + [.. new OutputDecoder().Decode(raw).Select(content => new ScrollbackLine(content))]; + + private static BunitContext NewContext() + { + var ctx = new BunitContext(); + ctx.JSInterop.Mode = JSRuntimeMode.Loose; + return ctx; + } + + [Test] + public async Task EachLineIsMarkupStringHtml() + { + using var ctx = NewContext(); + var lines = Lines("\e[31mred\e[0m plain"); + + var cut = ctx.Render(p => p.Add(c => c.Lines, lines)); + + var line = cut.Find("div.sc-line"); + await Assert.That(line.InnerHtml).IsEqualTo(OutputHtml.Render(lines[0].Content)); + await Assert.That(line.QuerySelector("span")!.GetAttribute("style")).StartsWith("color: var(--ms-ansi-1,"); + await Assert.That(line.TextContent).IsEqualTo("red plain"); + } + + [Test] + public async Task TheOutputCarriesTheClientPalette() + { + using var ctx = NewContext(); + + var cut = ctx.Render(p => p.Add(c => c.Lines, Lines("x"))); + + await Assert.That(cut.Find("div.sc-output").GetAttribute("style")).IsEqualTo(OutputPalette.CustomProperties); + } + + [Test] + public async Task RepeatedLinesAreEachShown() + { + using var ctx = NewContext(); + var first = Lines("You say, \"hi\""); + var cut = ctx.Render(p => p.Add(c => c.Lines, first)); + + // Blazor matches lines by key when it re-renders, so two equal keys fail there. + ScrollbackLine[] both = [.. first, .. Lines("You say, \"hi\"")]; + cut.Render(p => p.Add(c => c.Lines, both)); + + await Assert.That(cut.FindAll("div.sc-line").Count).IsEqualTo(2); + } + + [Test] + public async Task EmptyLineRendersAnEmptyLine() + { + using var ctx = NewContext(); + + var cut = ctx.Render(p => p.Add(c => c.Lines, Lines(string.Empty))); + + await Assert.That(cut.FindAll("div.sc-line").Count).IsEqualTo(1); + await Assert.That(cut.Find("div.sc-line").InnerHtml).IsEmpty(); + } [Test] - public async Task RendersOneSpanPerSegmentWithRenderContractStyle() + public async Task AttachesMarkupStringWebWithoutSoundAndKeepsItsLines() { using var ctx = new BunitContext(); - var line = Line( - new StyledSegment("red", TextStyle.Default with { Foreground = AnsiColor.Indexed(1) }), - new StyledSegment(" plain", TextStyle.Default)); + var module = ctx.JSInterop.SetupModule(OutputView.ScriptPath); + module.SetupModule("attachDotNet", _ => true); - var cut = ctx.Render(p => p.Add(c => c.Lines, new[] { line })); + ctx.Render(p => p.Add(c => c.Lines, Lines("x"))); - var spans = cut.FindAll("span"); - await Assert.That(spans.Count).IsEqualTo(2); - await Assert.That(spans[0].GetAttribute("style")).IsEqualTo("color:#e06c75;"); - await Assert.That(spans[0].TextContent).IsEqualTo("red"); - await Assert.That(spans[1].GetAttribute("style")).IsEqualTo("color:#c4d1c8;"); + var call = module.VerifyInvoke("attachDotNet"); + var options = call.Arguments[2]!; + var forward = (string[])options.GetType().GetProperty("forward")!.GetValue(options)!; + await Assert.That(options.GetType().GetProperty("sounds")!.GetValue(options) as bool?).IsFalse(); + // The lines are Blazor's: the script must not clear them or move their text to a pane. + await Assert.That(forward).Contains("clear"); + await Assert.That(forward).Contains("pane"); } [Test] - public async Task EmptySegmentRendersNonBreakingSpace() + public async Task DisposingDetachesTheScript() { using var ctx = new BunitContext(); - var line = Line(new StyledSegment(string.Empty, TextStyle.Default)); + var module = ctx.JSInterop.SetupModule(OutputView.ScriptPath); + var runtime = module.SetupModule("attachDotNet", _ => true); + runtime.SetupVoid("detach").SetVoidResult(); + var cut = ctx.Render(p => p.Add(c => c.Lines, Lines("x"))); + + await cut.Instance.DisposeAsync(); + + runtime.VerifyInvoke("detach"); + } + + [Test] + public async Task CommandsFromTheScriptAreSent() + { + using var ctx = NewContext(); + var sent = new List(); + var cut = ctx.Render(p => p + .Add(c => c.Lines, Lines("x")) + .Add(c => c.OnSendCommand, cmd => { sent.Add(cmd); return Task.CompletedTask; })); + + await cut.Instance.Send("go north"); + await cut.Instance.Prompt("say "); + + await Assert.That(sent).IsEquivalentTo(["go north", "say "]); + } + + [Test] + public async Task CommandWithoutAHandlerDoesNothing() + { + using var ctx = NewContext(); + var cut = ctx.Render(p => p.Add(c => c.Lines, Lines("x"))); + + await cut.Instance.Send("go north"); + } + + [Test] + public async Task TriggerHighlightCoversTheLine() + { + using var ctx = NewContext(); + var rule = new SharpClient.Core.Domain.TriggerRule + { + Kind = SharpClient.Core.Domain.TriggerKind.Substring, + Pattern = "danger", + Action = SharpClient.Core.Domain.TriggerActionKind.Highlight, + ActionValue = "9", + }; + const string raw = "\e[32mdanger\e[0m ahead"; + var outcome = new SharpClient.Core.Triggers.TriggerEngine().Apply(raw, new OutputDecoder().Decode(raw), [rule]); - var cut = ctx.Render(p => p.Add(c => c.Lines, new[] { line })); + var cut = ctx.Render(p => p.Add(c => c.Lines, outcome.Lines.Select(l => new ScrollbackLine(l)).ToArray())); - await Assert.That(cut.Find("span").TextContent).IsEqualTo(" "); + var highlight = cut.Find("div.sc-line > span.sc-highlight"); + await Assert.That(highlight.GetAttribute("style")).IsEqualTo("--sc-highlight: #ff8088"); + await Assert.That(highlight.TextContent).IsEqualTo("danger ahead"); } }