diff --git a/src/XTerm.NET.Tests/ColorPaletteTests.cs b/src/XTerm.NET.Tests/ColorPaletteTests.cs
index c7e5602..c7cf0a5 100644
--- a/src/XTerm.NET.Tests/ColorPaletteTests.cs
+++ b/src/XTerm.NET.Tests/ColorPaletteTests.cs
@@ -713,6 +713,55 @@ public void ResolveBackground_EachSgrEncoding_ResolvesToTheColourNamed(string sg
Assert.Equal(expected, terminal.Colors.Take().ResolveBackground(attributes));
}
+ ///
+ /// Every underline colour encoding, through real SGR. Bold and a red foreground are set
+ /// throughout, so an underline that took the foreground or bold's brightening would show.
+ ///
+ [Theory]
+ [InlineData("4", null)] // no SGR 58: follows the text
+ [InlineData("4;58;5;1;59", null)] // SGR 59 clears it again
+ [InlineData("4;58;5;1", 0xCD0000)]
+ [InlineData("4:3;58:5:1", 0xCD0000)] // curly underline, colon form
+ [InlineData("4;58;5;9", 0xFF0000)]
+ [InlineData("4;58;5;100", 0x878700)]
+ [InlineData("4;58;2;1;2;3", 0x010203)]
+ [InlineData("4;58:2::1:2:3", 0x010203)]
+ [InlineData("4;58;2;0;1;1", 0x000101)] // numerically 257, and still RGB
+ [InlineData("4;58;2;255;255;255", 0xFFFFFF)]
+ public void ResolveUnderline_EachSgrEncoding_ResolvesToTheColourNamed(string sgr, int? expected)
+ {
+ var terminal = CreateTerminal(new ThemeOptions { Foreground = "#102030" });
+ terminal.Write(Esc.Csi($"1;31;{sgr}m") + "X");
+
+ var attributes = terminal.Buffer.Lines[terminal.Buffer.YBase]![0].Attributes;
+ Assert.Equal(expected, terminal.Colors.Take().ResolveUnderline(attributes));
+ }
+
+ [Fact]
+ public void ResolveUnderline_ReadsThePaletteAsItStands()
+ {
+ var snapshot = new ColorPalette(new ThemeOptions { Red = "#ff8800" }).Take();
+ var attributes = AttributeData.Default;
+
+ attributes.SetUnderlineColor(1, (int)ColorMode.Palette256);
+ Assert.Equal(0xFF8800, snapshot.ResolveUnderline(attributes));
+
+ attributes.ResetUnderlineColor();
+ Assert.Null(snapshot.ResolveUnderline(attributes));
+ }
+
+ [Fact]
+ public void ResolveUnderline_IndexPastThePalette_FollowsTheText()
+ {
+ var snapshot = new ColorPalette(new ThemeOptions()).Take();
+ var attributes = AttributeData.Default;
+
+ // Only the direct setter can store one; SGR 58;5 ignores an index past 255.
+ attributes.SetUnderlineColor(ColorPalette.Size, (int)ColorMode.Palette256);
+
+ Assert.Null(snapshot.ResolveUnderline(attributes));
+ }
+
[Fact]
public void ResolveBackground_ReadsThePaletteAsItStands()
{
diff --git a/src/XTerm.NET.Tests/EncodeKeyTests.cs b/src/XTerm.NET.Tests/EncodeKeyTests.cs
new file mode 100644
index 0000000..145788b
--- /dev/null
+++ b/src/XTerm.NET.Tests/EncodeKeyTests.cs
@@ -0,0 +1,201 @@
+using XTerm;
+using XTerm.Input;
+using XTerm.Options;
+
+namespace XTerm.Tests;
+
+///
+/// against what the Avalonia TerminalView sends for the same
+/// keystroke today, mode by mode. The expected bytes are literals, not calls to the generators the
+/// method delegates to, so a wrong choice of generator shows as a wrong answer.
+///
+public class EncodeKeyTests
+{
+ private const string E = "\u001b";
+
+ public enum Mode { Legacy, CursorKeys, Keypad, KittyDisambiguate, KittyAllEvents, Win32, Win32AndKitty }
+
+ private static Terminal Make(Mode mode)
+ {
+ var t = new Terminal(new TerminalOptions());
+ switch (mode)
+ {
+ case Mode.CursorKeys: t.Write($"{E}[?1h"); break;
+ case Mode.Keypad: t.Write($"{E}="); break;
+ case Mode.KittyDisambiguate: t.Write($"{E}[>1u"); break;
+ case Mode.KittyAllEvents: t.Write($"{E}[>11u"); break;
+ case Mode.Win32: t.Write($"{E}[?9001h"); break;
+ case Mode.Win32AndKitty: t.Write($"{E}[?9001h{E}[>1u"); break;
+ }
+ return t;
+ }
+
+ /// Modifiers spelled as a short string: s(hift), c(trl), a(lt), m(eta/super).
+ private static KeyEvent Ev(string key, string code, string mods = "") => new()
+ {
+ Key = key,
+ Code = code,
+ ShiftKey = mods.Contains('s'),
+ CtrlKey = mods.Contains('c'),
+ AltKey = mods.Contains('a'),
+ MetaKey = mods.Contains('m'),
+ };
+
+ public static TheoryData Presses => new()
+ {
+ // Legacy: the keys TerminalView sends through GenerateKeyInput, and text through
+ // GenerateCharInput or as typed.
+ { Mode.Legacy, "ArrowUp", "ArrowUp", "", $"{E}[A" },
+ { Mode.Legacy, "ArrowLeft", "ArrowLeft", "c", $"{E}[1;5D" },
+ { Mode.Legacy, "ArrowRight", "ArrowRight", "s", $"{E}[1;2C" },
+ { Mode.Legacy, "Home", "Home", "", $"{E}[H" },
+ { Mode.Legacy, "PageDown", "PageDown", "", $"{E}[6~" },
+ { Mode.Legacy, "Delete", "Delete", "", $"{E}[3~" },
+ { Mode.Legacy, "F1", "F1", "", $"{E}OP" },
+ { Mode.Legacy, "F5", "F5", "", $"{E}[15~" },
+ { Mode.Legacy, "F12", "F12", "s", $"{E}[24;2~" },
+ { Mode.Legacy, "Enter", "Enter", "", "\r" },
+ { Mode.Legacy, "Tab", "Tab", "", "\t" },
+ { Mode.Legacy, "Tab", "Tab", "s", $"{E}[Z" },
+ { Mode.Legacy, "Backspace", "Backspace", "", "\u007f" },
+ { Mode.Legacy, "Backspace", "Backspace", "c", "\b" },
+ { Mode.Legacy, "Escape", "Escape", "", E },
+ { Mode.Legacy, "a", "KeyA", "", "a" },
+ { Mode.Legacy, "A", "KeyA", "s", "A" },
+ { Mode.Legacy, " ", "Space", "", " " },
+ { Mode.Legacy, "é", "KeyE", "", "é" },
+ { Mode.Legacy, "c", "KeyC", "c", "\u0003" },
+ { Mode.Legacy, " ", "Space", "c", "\u0000" },
+ { Mode.Legacy, "x", "KeyX", "a", $"{E}x" },
+ { Mode.Legacy, "a", "KeyA", "ca", $"{E}\u0001" },
+ { Mode.Legacy, "a", "KeyA", "m", "a" }, // no Super in legacy
+ { Mode.Legacy, "Shift", "ShiftLeft", "s", null }, // a bare modifier sends nothing
+ { Mode.Legacy, "7", "Numpad7", "", "7" },
+
+ // DECCKM: cursor keys switch to SS3, modified ones do not.
+ { Mode.CursorKeys, "ArrowUp", "ArrowUp", "", $"{E}OA" },
+ { Mode.CursorKeys, "Home", "Home", "", $"{E}OH" },
+ { Mode.CursorKeys, "ArrowUp", "ArrowUp", "c", $"{E}[1;5A" },
+
+ // DECKPAM: the keypad, told apart from the main digits by its code.
+ { Mode.Keypad, "7", "Numpad7", "", $"{E}Ow" },
+ { Mode.Keypad, "+", "NumpadAdd", "", $"{E}Ok" },
+ { Mode.Keypad, "Enter", "NumpadEnter", "", $"{E}OM" },
+ { Mode.Keypad, "7", "Digit7", "", "7" },
+
+ // Kitty, disambiguate only: the ambiguous keys become CSI u, plain text stays text.
+ { Mode.KittyDisambiguate, "Escape", "Escape", "", $"{E}[27u" },
+ { Mode.KittyDisambiguate, "c", "KeyC", "c", $"{E}[99;5u" },
+ { Mode.KittyDisambiguate, "a", "KeyA", "m", $"{E}[97;9u" }, // Super is Kitty's bit 8
+ { Mode.KittyDisambiguate, "a", "KeyA", "", "a" },
+ { Mode.KittyDisambiguate, "ArrowUp", "ArrowUp", "", $"{E}[A" },
+ { Mode.KittyDisambiguate, "Enter", "Enter", "", "\r" },
+ { Mode.KittyDisambiguate, "Shift", "ShiftLeft", "s", null },
+
+ // Win32 input mode: one key-down record, VK ; scan ; char ; down ; state ; repeat.
+ { Mode.Win32, "a", "KeyA", "", $"{E}[65;0;97;1;0;1_" },
+ { Mode.Win32, "A", "KeyA", "s", $"{E}[65;0;65;1;16;1_" },
+ { Mode.Win32, "c", "KeyC", "c", $"{E}[67;0;3;1;8;1_" },
+ { Mode.Win32, "ArrowUp", "ArrowUp", "", $"{E}[38;0;0;1;256;1_" },
+ { Mode.Win32, "Enter", "Enter", "", $"{E}[13;0;13;1;0;1_" },
+ { Mode.Win32, "Escape", "Escape", "", $"{E}[27;0;27;1;0;1_" },
+ { Mode.Win32, "Backspace", "Backspace", "", $"{E}[8;0;8;1;0;1_" },
+ { Mode.Win32, " ", "Space", "", $"{E}[32;0;32;1;0;1_" },
+ { Mode.Win32, "F5", "F5", "", $"{E}[116;0;0;1;0;1_" },
+ { Mode.Win32, "Shift", "ShiftLeft", "s", $"{E}[16;0;0;1;16;1_" },
+ { Mode.Win32, "Alt", "AltRight", "a", $"{E}[18;0;0;1;257;1_" },
+ { Mode.Win32, "7", "Numpad7", "", $"{E}[103;0;55;1;0;1_" },
+ // NumLock off: the keypad key is navigation, and gets the navigation key's VK.
+ { Mode.Win32, "Home", "Numpad7", "", $"{E}[36;0;0;1;0;1_" },
+ { Mode.Win32, "ArrowUp", "Numpad8", "", $"{E}[38;0;0;1;0;1_" },
+ { Mode.Win32, "Delete", "NumpadDecimal", "", $"{E}[46;0;0;1;0;1_" },
+ // Shifted OEM keys, named by their physical code.
+ { Mode.Win32, "?", "Slash", "s", $"{E}[191;0;63;1;16;1_" },
+ { Mode.Win32, ":", "Semicolon", "s", $"{E}[186;0;58;1;16;1_" },
+ { Mode.Win32, "\"", "Quote", "s", $"{E}[222;0;34;1;16;1_" },
+ { Mode.Win32, "{", "BracketLeft", "s", $"{E}[219;0;123;1;16;1_" },
+ { Mode.Win32, "|", "Backslash", "s", $"{E}[220;0;124;1;16;1_" },
+ { Mode.Win32, "~", "Backquote", "s", $"{E}[192;0;126;1;16;1_" },
+ { Mode.Win32, "/", "Slash", "", $"{E}[191;0;47;1;0;1_" },
+ // A layout whose character names no key: the physical code is all there is to go on.
+ { Mode.Win32, "é", "Slash", "", $"{E}[191;0;233;1;0;1_" },
+ // And with no physical code at all, from the character on a US layout.
+ { Mode.Win32, "?", "", "s", $"{E}[191;0;63;1;16;1_" },
+ { Mode.Win32AndKitty, "?", "Slash", "s", $"{E}[191;0;63;1;16;1_" },
+
+ // Win32 is a transport and keeps its precedence over a negotiated Kitty protocol.
+ { Mode.Win32AndKitty, "Escape", "Escape", "", $"{E}[27;0;27;1;0;1_" },
+ };
+
+ [Theory]
+ [MemberData(nameof(Presses))]
+ public void Press_MatchesTheControl(Mode mode, string key, string code, string mods, string? expected)
+ {
+ var t = Make(mode);
+
+ Assert.Equal(expected, t.EncodeKey(Ev(key, code, mods)));
+ }
+
+ [Fact]
+ public void Legacy_Release_SendsNothing()
+ {
+ var t = Make(Mode.Legacy);
+
+ Assert.Null(t.EncodeKey(Ev("a", "KeyA"), KittyKeyboardEventType.Release));
+ Assert.Null(t.EncodeKey(Ev("ArrowUp", "ArrowUp"), KittyKeyboardEventType.Release));
+ }
+
+ [Fact]
+ public void Legacy_Repeat_IsAnotherPress()
+ {
+ var t = Make(Mode.Legacy);
+
+ Assert.Equal($"{E}[A", t.EncodeKey(Ev("ArrowUp", "ArrowUp"), KittyKeyboardEventType.Repeat));
+ }
+
+ [Fact]
+ public void Kitty_ReleaseIsReportedOnlyWhenTheFlagsAskForIt()
+ {
+ Assert.Null(Make(Mode.KittyDisambiguate).EncodeKey(Ev("Escape", "Escape"), KittyKeyboardEventType.Release));
+
+ Assert.Equal($"{E}[27;1:3u",
+ Make(Mode.KittyAllEvents).EncodeKey(Ev("Escape", "Escape"), KittyKeyboardEventType.Release));
+ }
+
+ [Fact]
+ public void Win32_Release_IsAKeyUpRecord()
+ {
+ var t = Make(Mode.Win32);
+
+ Assert.Equal($"{E}[65;0;97;0;0;1_", t.EncodeKey(Ev("a", "KeyA"), KittyKeyboardEventType.Release));
+ }
+
+ [Fact]
+ public void Win32_ShiftedOemKey_ReleasesToo()
+ {
+ var t = Make(Mode.Win32);
+
+ Assert.Equal($"{E}[191;0;63;0;16;1_",
+ t.EncodeKey(Ev("?", "Slash", "s"), KittyKeyboardEventType.Release));
+ }
+
+ [Fact]
+ public void Win32_TakesTheVirtualKeyFromKeyCodeWhenGiven()
+ {
+ var t = Make(Mode.Win32);
+ var ev = Ev("q", "", "");
+ ev.KeyCode = 0x51;
+
+ Assert.Equal($"{E}[81;0;113;1;0;1_", t.EncodeKey(ev));
+ }
+
+ [Fact]
+ public void LockedKeyboard_SendsNothing()
+ {
+ var t = new Terminal(new TerminalOptions { KeyboardActionModeAllowed = true });
+ t.Write($"{E}[2h");
+
+ Assert.Null(t.EncodeKey(Ev("a", "KeyA")));
+ Assert.Null(t.EncodeKey(Ev("ArrowUp", "ArrowUp")));
+ }
+}
diff --git a/src/XTerm.NET.Tests/RowChangeTrackingTests.cs b/src/XTerm.NET.Tests/RowChangeTrackingTests.cs
new file mode 100644
index 0000000..72dd5c2
--- /dev/null
+++ b/src/XTerm.NET.Tests/RowChangeTrackingTests.cs
@@ -0,0 +1,375 @@
+using XTerm;
+using XTerm.Options;
+
+namespace XTerm.Tests;
+
+///
+/// and : every kind of
+/// visible change marks the rows it reached and no others, and a change that touches no cell --
+/// a cursor move, an SGR on its own -- marks nothing.
+///
+public class RowChangeTrackingTests
+{
+ private static readonly string Esc = ((char)0x1B).ToString();
+
+ private static Terminal Make(int cols = 20, int rows = 5) =>
+ new(new TerminalOptions { Cols = cols, Rows = rows });
+
+ /// The rows that changed after , as indexes.
+ private static int[] Changed(Terminal t, long since)
+ {
+ Span rows = stackalloc bool[t.Rows];
+ t.CopyChangedRows(since, rows);
+ var result = new List();
+ for (int y = 0; y < rows.Length; y++)
+ {
+ if (rows[y])
+ result.Add(y);
+ }
+ return result.ToArray();
+ }
+
+ private static int[] AllRows(Terminal t) => Enumerable.Range(0, t.Rows).ToArray();
+
+ [Fact]
+ public void ReadingTwiceWithNothingWritten_DoesNotMove()
+ {
+ var t = Make();
+ var v = t.RefreshContentVersion();
+
+ Assert.Equal(v, t.RefreshContentVersion());
+ Assert.Empty(Changed(t, v));
+ }
+
+ [Fact]
+ public void ContentVersion_IsAPureRead_OfTheLastLook()
+ {
+ var t = Make();
+ var looked = t.RefreshContentVersion();
+
+ t.Write("hello");
+
+ // Reading the property does not look at the buffer, however often it is read.
+ Assert.Equal(looked, t.ContentVersion);
+ Assert.Equal(looked, t.ContentVersion);
+
+ var after = t.RefreshContentVersion();
+ Assert.NotEqual(looked, after);
+ Assert.Equal(after, t.ContentVersion);
+ }
+
+ [Fact]
+ public void ContentVersion_IsZeroBeforeTheFirstLook_WhichMeansEveryRow()
+ {
+ var t = Make();
+ t.Write("x");
+
+ Assert.Equal(0, t.ContentVersion);
+ Assert.Equal(AllRows(t), Changed(t, t.ContentVersion));
+ }
+
+ [Fact]
+ public void TheUsualLoop_CopyChangedRowsThenContentVersion_NeedsNoRefresh()
+ {
+ var t = Make();
+ Span rows = stackalloc bool[t.Rows];
+
+ long since = t.ContentVersion;
+ t.CopyChangedRows(since, rows);
+ since = t.ContentVersion;
+
+ t.Write($"{Esc}[4;1Hx");
+
+ Assert.Equal(1, t.CopyChangedRows(since, rows));
+ Assert.True(rows[3]);
+ since = t.ContentVersion;
+
+ Assert.Equal(0, t.CopyChangedRows(since, rows));
+ }
+
+ [Fact]
+ public void FirstLook_ReportsEveryRowAsChangedSinceZero()
+ {
+ var t = Make();
+
+ Assert.Equal(AllRows(t), Changed(t, 0));
+ }
+
+ [Fact]
+ public void Print_MarksOnlyTheRowWrittenTo()
+ {
+ var t = Make();
+ t.Write($"{Esc}[3;1H");
+ var v = t.RefreshContentVersion();
+
+ t.Write("hello");
+
+ Assert.NotEqual(v, t.RefreshContentVersion());
+ Assert.Equal([2], Changed(t, v));
+ }
+
+ [Fact]
+ public void Print_SpanningAWrap_MarksBothRows()
+ {
+ var t = Make(cols: 10);
+ var v = t.RefreshContentVersion();
+
+ t.Write("0123456789abc");
+
+ Assert.Equal([0, 1], Changed(t, v));
+ }
+
+ [Fact]
+ public void CursorOnlyMoves_DoNotCount()
+ {
+ var t = Make();
+ t.Write("x");
+ var v = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[4;7H{Esc}[2A{Esc}[3C\r{Esc}7{Esc}8");
+
+ Assert.Equal(v, t.RefreshContentVersion());
+ Assert.Empty(Changed(t, v));
+ }
+
+ [Fact]
+ public void NoOpWrites_DoNotCount()
+ {
+ var t = Make();
+ t.Write("x");
+ var v = t.RefreshContentVersion();
+
+ // Nothing at all, and an SGR on its own: the pen changes, no cell does.
+ t.Write("");
+ t.Write(ReadOnlySpan.Empty);
+ t.Write($"{Esc}[1;31m");
+
+ Assert.Equal(v, t.RefreshContentVersion());
+ }
+
+ [Fact]
+ public void AttributeOnlyChange_Counts()
+ {
+ var t = Make();
+ t.Write("a");
+ var v = t.RefreshContentVersion();
+
+ // The same character back in the same cell, in red: only its attributes differ.
+ t.Write($"\r{Esc}[31ma");
+
+ Assert.Equal([0], Changed(t, v));
+ }
+
+ [Fact]
+ public void EraseInLine_MarksThatRow()
+ {
+ var t = Make();
+ t.Write("one\r\ntwo\r\nthree");
+ var v = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[2;1H{Esc}[K");
+
+ Assert.Equal([1], Changed(t, v));
+ }
+
+ [Fact]
+ public void EraseCharacters_MarksThatRow()
+ {
+ var t = Make();
+ t.Write("one\r\ntwo\r\nthree");
+ var v = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[3;2H{Esc}[2X");
+
+ Assert.Equal([2], Changed(t, v));
+ }
+
+ [Fact]
+ public void ClearScreen_MarksEveryRow()
+ {
+ var t = Make();
+ t.Write("one\r\ntwo");
+ var v = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[2J");
+
+ Assert.Equal(AllRows(t), Changed(t, v));
+ }
+
+ [Fact]
+ public void LineFeedAtTheBottom_ScrollsAndMarksEveryRow()
+ {
+ var t = Make(rows: 4);
+ t.Write("a\r\nb\r\nc\r\nd");
+ var v = t.RefreshContentVersion();
+
+ // No cell is written by the scroll itself: every row now shows a different line.
+ t.Write("\n");
+
+ Assert.Equal(AllRows(t), Changed(t, v));
+ }
+
+ [Fact]
+ public void ScrollUp_MarksEveryRowInTheRegion()
+ {
+ var t = Make(rows: 4);
+ t.Write("a\r\nb\r\nc\r\nd");
+ var v = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[S");
+
+ Assert.Equal(AllRows(t), Changed(t, v));
+ }
+
+ [Fact]
+ public void ScrollWithFullScrollback_StillMarksEveryRow()
+ {
+ // Scrollback 0 recycles the top line to the bottom instead of allocating one.
+ var t = new Terminal(new TerminalOptions { Cols = 10, Rows = 3, Scrollback = 0 });
+ t.Write("a\r\nb\r\nc");
+ var v = t.RefreshContentVersion();
+
+ t.Write("\n");
+
+ Assert.Equal(AllRows(t), Changed(t, v));
+ }
+
+ [Fact]
+ public void ViewportScroll_MarksEveryRow()
+ {
+ var t = Make(rows: 3);
+ t.Write("1\r\n2\r\n3\r\n4\r\n5\r\n6");
+ var v = t.RefreshContentVersion();
+
+ t.ScrollLines(-1);
+
+ Assert.Equal(AllRows(t), Changed(t, v));
+ }
+
+ [Fact]
+ public void Resize_MarksEveryRowOfTheNewSize()
+ {
+ var t = Make(rows: 5);
+ t.Write("x");
+ var v = t.RefreshContentVersion();
+
+ t.Resize(20, 7);
+
+ Assert.Equal(AllRows(t), Changed(t, v));
+ Assert.Equal(7, Changed(t, v).Length);
+ }
+
+ [Fact]
+ public void AlternateScreenSwitch_MarksEveryRow_BothWays()
+ {
+ var t = Make();
+ t.Write("main");
+ var v = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[?1049h");
+ Assert.Equal(AllRows(t), Changed(t, v));
+
+ v = t.RefreshContentVersion();
+ t.Write($"{Esc}[?1049l");
+ Assert.Equal(AllRows(t), Changed(t, v));
+ }
+
+ private static string Sized(string metadata, string text) => $"{Esc}]66;{metadata};{text}{Esc}\\";
+
+ [Fact]
+ public void SizedText_MarksEveryRowItCovers()
+ {
+ // Stored on row 0's line alone, drawn over rows 0-2.
+ var t = Make();
+ var v = t.RefreshContentVersion();
+
+ t.Write(Sized("s=3", "X"));
+
+ Assert.Equal([0, 1, 2], Changed(t, v));
+ }
+
+ [Fact]
+ public void ErasingSizedText_MarksEveryRowItCovered()
+ {
+ var t = Make();
+ t.Write(Sized("s=3", "X"));
+ var v = t.RefreshContentVersion();
+
+ // The run is gone, so only what it USED to cover can say rows 1-2 changed.
+ t.Write($"\r{Esc}[K");
+
+ Assert.Equal([0, 1, 2], Changed(t, v));
+ }
+
+ [Fact]
+ public void SizedText_AnchoredAboveTheViewport_MarksTheRowsItReachesInto()
+ {
+ var t = Make(rows: 5);
+ t.Write(Sized("s=3", "X"));
+ t.Write("\r\n\r\n\r\n\r\n\r\n"); // one scroll: the anchor is now just above the top row
+ Assert.Equal(1, t.Buffer.ViewportY);
+ var v = t.RefreshContentVersion();
+
+ t.Buffer.GetLine(0)!.Fill(XTerm.Buffer.BufferCell.Space);
+
+ Assert.Equal([0, 1], Changed(t, v));
+ }
+
+ [Fact]
+ public void ZeroRowTerminal_CanBeObservedBeforeLayout_ThenResized()
+ {
+ // A host constructs at zero rows before layout, which the constructor accepts.
+ var t = new Terminal(new TerminalOptions { Cols = 20, Rows = 0 });
+
+ var v = t.RefreshContentVersion();
+ Assert.Equal(0, t.CopyChangedRows(v, Span.Empty));
+ Assert.Throws(() => t.GetRowVersion(0));
+
+ t.Resize(20, 5);
+
+ Assert.Equal([0, 1, 2, 3, 4], Changed(t, v));
+ }
+
+ [Fact]
+ public void RowVersion_IsTheVersionTheRowLastChangedAt()
+ {
+ var t = Make();
+ var before = t.RefreshContentVersion();
+
+ t.Write($"{Esc}[2;1Hx");
+ var after = t.RefreshContentVersion();
+
+ Assert.Equal(after, t.GetRowVersion(1));
+ Assert.True(t.GetRowVersion(0) <= before);
+ Assert.Throws(() => t.GetRowVersion(t.Rows));
+ }
+
+ [Fact]
+ public void TwoObservers_EachSeeTheirOwnChanges()
+ {
+ var t = Make();
+ var first = t.RefreshContentVersion();
+
+ t.Write("a");
+ var second = t.RefreshContentVersion();
+ t.Write($"{Esc}[3;1Hb");
+
+ // The second observer looked between the writes; the first did not.
+ Assert.Equal([0, 2], Changed(t, first));
+ Assert.Equal([2], Changed(t, second));
+ }
+
+ [Fact]
+ public void CopyChangedRows_ReturnsTheCount_AndClearsPastTheGrid()
+ {
+ var t = Make(rows: 3);
+ var v = t.RefreshContentVersion();
+ t.Write("a");
+
+ Span rows = [true, true, true, true, true];
+ var count = t.CopyChangedRows(v, rows);
+
+ Assert.Equal(1, count);
+ Assert.Equal(new[] { true, false, false, false, false }, rows.ToArray());
+ }
+}
diff --git a/src/XTerm.NET/Buffer/BufferLine.Version.cs b/src/XTerm.NET/Buffer/BufferLine.Version.cs
new file mode 100644
index 0000000..2f2c2b0
--- /dev/null
+++ b/src/XTerm.NET/Buffer/BufferLine.Version.cs
@@ -0,0 +1,51 @@
+namespace XTerm.Buffer;
+
+public partial class BufferLine
+{
+ private long _version;
+
+ ///
+ /// A counter that moves every time this line's visible content changes: its cells, their
+ /// attributes, its line attribute, or the images and sized text drawn on it.
+ ///
+ ///
+ /// Only equality means anything. Two reads that agree saw the same content; two that
+ /// differ saw at least one write between them, which may have put back what was there. It is
+ /// per line and starts at zero, so it says nothing about other lines -- a scroll moves lines
+ /// without writing to them. and
+ /// combine it with which line sits on which row.
+ /// Moved at the same places that clear , which is the invalidation a
+ /// renderer already depends on, so the two cannot disagree. Read it under the same contract as
+ /// the line's cells: on the thread that writes to the terminal, or serialized with it.
+ ///
+ public long Version => _version;
+
+ ///
+ /// How many rows BELOW this one its sized text (OSC 66) reaches: a scale-3 run anchored here is
+ /// drawn over the next two lines too, which hold nothing of it themselves.
+ ///
+ internal int SizedRunReach
+ {
+ get
+ {
+ var runs = _sizedRuns;
+ if (runs is null)
+ return 0;
+
+ var reach = 0;
+ foreach (var run in runs)
+ reach = Math.Max(reach, run.Rows - 1);
+ return reach;
+ }
+ }
+
+ ///
+ /// Every write to the line comes through here: the renderer's cache is stale, and the version
+ /// moves. One increment, no branch, so it costs the print path nothing measurable.
+ ///
+ private void MarkChanged()
+ {
+ Cache = null;
+ _version++;
+ }
+}
diff --git a/src/XTerm.NET/Buffer/BufferLine.cs b/src/XTerm.NET/Buffer/BufferLine.cs
index 9c90fc5..47313ab 100644
--- a/src/XTerm.NET/Buffer/BufferLine.cs
+++ b/src/XTerm.NET/Buffer/BufferLine.cs
@@ -7,7 +7,7 @@ namespace XTerm.Buffer;
/// Represents a single line in the terminal buffer.
/// Contains an array of cells and metadata about the line.
///
-public class BufferLine : IEnumerable
+public partial class BufferLine : IEnumerable
{
private BufferCell[] _cells;
@@ -85,7 +85,7 @@ public LineAttribute LineAttribute
set
{
_lineAttribute = value;
- Cache = null;
+ MarkChanged();
}
}
@@ -137,7 +137,7 @@ public BufferCell this[int index]
HasWideCells = true;
_cells[index] = value;
- Cache = null;
+ MarkChanged();
}
}
}
@@ -199,7 +199,7 @@ public void SetCell(int index, ref BufferCell cell)
if (_sixel is not null)
ClearSixel(index, 1);
- Cache = null;
+ MarkChanged();
}
}
@@ -237,7 +237,7 @@ public void SetSingleWidthRun(int index, ReadOnlySpan text, AttributeData
if (_sixel is not null)
ClearSixel(index, text.Length);
- Cache = null;
+ MarkChanged();
}
///
@@ -265,7 +265,7 @@ public void SetSingleWidthRun(int index, ReadOnlySpan ascii, AttributeData
if (_sixel is not null)
ClearSixel(index, ascii.Length);
- Cache = null;
+ MarkChanged();
}
///
@@ -304,7 +304,7 @@ public void Resize(int cols, BufferCell fillCell)
Array.Copy(_cells, newCells, cols);
_cells = newCells;
}
- Cache = null;
+ MarkChanged();
_length = cols;
// A block cut in half by a narrowing does not survive it: the run says which columns hold
@@ -363,7 +363,7 @@ public void Fill(BufferCell fillCell, int startCol = 0, int endCol = -1)
if (_sizedRuns is not null)
EraseSizedRunsOver(startCol, Math.Max(0, Math.Min(endCol, _length) - startCol));
- Cache = null;
+ MarkChanged();
}
///
@@ -413,7 +413,7 @@ public void CopyCellsFrom(BufferLine src, int srcCol, int destCol, int length, b
if (src._sixel is not null || _sixel is not null)
CopySixelCells(src, srcCol, destCol, length);
- Cache = null;
+ MarkChanged();
}
private void CopySixelCells(BufferLine src, int srcCol, int destCol, int length)
@@ -495,7 +495,7 @@ public void ReplaceCells(int startCol, int endCol, BufferCell fillCell)
{
_cells[startCol++] = fillCell;
}
- Cache = null;
+ MarkChanged();
}
///
@@ -513,7 +513,7 @@ public bool ClearImages()
_images = null;
_sixel = null;
_sixelShared = false;
- Cache = null;
+ MarkChanged();
return true;
}
@@ -535,7 +535,7 @@ internal void PaintSixel(Graphics.TerminalImage image, int sourceY, int column)
{
var strip = WritableSixel(null, image.CellWidth, image.CellHeight);
strip.Paint(image, sourceY, column);
- Cache = null;
+ MarkChanged();
}
/// Drops this line's Sixel pixels altogether. What the image budget reclaims through.
@@ -548,7 +548,7 @@ internal long DropSixel()
var bytes = _sixel.ByteCount;
_sixel = null;
_sixelShared = false;
- Cache = null;
+ MarkChanged();
return bytes;
}
@@ -931,7 +931,7 @@ private void EraseSizedRunsOver(int column, int count, bool blankAll = false, in
_cells[c] = blank;
}
- Cache = null;
+ MarkChanged();
}
if (_sizedRuns.Count == 0)
@@ -1141,7 +1141,7 @@ internal bool RemoveImages(HashSet doomed)
_placements = null;
PruneImages();
- Cache = null;
+ MarkChanged();
return true;
}
@@ -1159,13 +1159,13 @@ internal void AddPlacement(Graphics.LinePlacement placement, Graphics.TerminalIm
{
if (ReferenceEquals(held, image))
{
- Cache = null;
+ MarkChanged();
return;
}
}
_images.Add(image);
- Cache = null;
+ MarkChanged();
}
///
@@ -1190,7 +1190,7 @@ internal bool RemovePlacements(Func predicate)
_placements = null;
PruneImages();
- Cache = null;
+ MarkChanged();
return true;
}
@@ -1330,7 +1330,7 @@ public void ResetInPlace(BufferCell fillCell, bool isWrapped = false)
// marked in the middle of a program's output.
ClearMarks();
- Cache = null;
+ MarkChanged();
}
///
@@ -1406,6 +1406,7 @@ public void CopyFrom(BufferLine line)
// wide character would otherwise carry that latch forever.
HasWideCells = line.HasWideCells;
this.Cache = line.Cache;
+ _version++;
}
public IEnumerator GetEnumerator()
diff --git a/src/XTerm.NET/Common/ColorPalette.cs b/src/XTerm.NET/Common/ColorPalette.cs
index 726714e..a09f4bb 100644
--- a/src/XTerm.NET/Common/ColorPalette.cs
+++ b/src/XTerm.NET/Common/ColorPalette.cs
@@ -486,6 +486,29 @@ public int ResolveForeground(in AttributeData attributes, bool drawBoldTextInBri
};
}
+ ///
+ /// Resolves the colour a cell's underline is drawn in, from its underline colour (SGR 58), as
+ /// 0xRRGGBB, or null when the underline follows the text colour.
+ ///
+ /// The cell's attributes.
+ ///
+ /// SGR 58;5;n resolves through this palette and SGR 58;2;r;g;b comes through as named;
+ /// bold changes neither. SGR 59, or no SGR 58 at all, is null: draw the underline in whatever
+ /// gave the text, after the host's inverse and dim -- which is
+ /// why this does not answer with the foreground itself. An index past the palette, which only
+ /// a direct can store, is null too.
+ ///
+ public int? ResolveUnderline(in AttributeData attributes)
+ {
+ if (!attributes.TryGetUnderlineColor(out var color, out var mode))
+ return null;
+
+ if (mode == (int)ColorMode.RGB)
+ return color & 0xFFFFFF;
+
+ return (uint)color < (uint)colors.Length ? colors[color] : null;
+ }
+
/// Gets whether the background is light enough that dark text belongs on it.
public bool IsLightBackground => ColorPalette.IsLight(Background);
diff --git a/src/XTerm.NET/Terminal.KeyEncoding.cs b/src/XTerm.NET/Terminal.KeyEncoding.cs
new file mode 100644
index 0000000..6525897
--- /dev/null
+++ b/src/XTerm.NET/Terminal.KeyEncoding.cs
@@ -0,0 +1,322 @@
+using XTerm.Input;
+using XTerm.Options;
+using Win32State = XTerm.Input.Win32InputGenerator.ControlKeyState;
+
+namespace XTerm;
+
+///
+/// One entry point that encodes a key for whichever keyboard protocol is live.
+///
+public partial class Terminal
+{
+ ///
+ /// Encodes one key event the way the running application is currently reading keys: Win32
+ /// input records, then the Kitty keyboard protocol, then the legacy encodings.
+ ///
+ ///
+ /// Precedence. (DECSET 9001) first: it is a different
+ /// transport rather than a competing encoding, and a process reading INPUT_RECORDs reads them for
+ /// every key. Then , through .
+ /// Otherwise the legacy generators, which honour DECCKM ()
+ /// and DECKPAM ().
+ /// The key model is the browser's, as already is for Kitty.
+ /// is what the key means: a name for a functional key
+ /// ("ArrowUp", "Enter", "Backspace", "F5", "Shift") or the
+ /// text it typed ("a", "A", "@", " "). is
+ /// the physical key ("KeyA", "Numpad7", "AltRight"); the keypad is told apart
+ /// from the main keys by it alone. , when set, is taken as the
+ /// Windows virtual-key code, which is what browsers report there.
+ /// Modifiers. Shift, Alt and Ctrl map to every protocol.
+ /// is Super (Cmd, the Windows key): Kitty encodes it, and neither the legacy encodings nor a
+ /// Win32 record can, so there it is dropped -- has no Super member for
+ /// that reason. Report AltGr as the character it composed with Ctrl and Alt clear; reported as
+ /// Ctrl+Alt it is encoded as that chord.
+ /// Not here: host policy that rewrites keys before encoding them (Alt+Left as
+ /// ESC b, Cmd shortcuts, selection editing), lock-key state in Win32 records (the event
+ /// does not carry it), and ConPTY's need for a Win32 record for a bare Escape outside Win32 mode,
+ /// which is a fact about the transport -- a host on ConPTY decides that.
+ ///
+ /// The key event.
+ /// Press, repeat or release. Only Win32 records and Kitty (when its
+ /// flags ask) report releases; the legacy encodings return null for one.
+ /// The bytes to send, or null when this event sends nothing: the keyboard is locked
+ /// (KAM), a bare modifier outside Win32 and Kitty, a release legacy cannot express, or a key no
+ /// protocol here has an encoding for.
+ public string? EncodeKey(KeyEvent ev, KittyKeyboardEventType eventType = KittyKeyboardEventType.Press)
+ {
+ ArgumentNullException.ThrowIfNull(ev);
+
+ if (KeyboardLocked)
+ return null;
+
+ if (Win32InputMode)
+ {
+ var record = EncodeWin32Record(ev, isKeyDown: eventType != KittyKeyboardEventType.Release);
+ if (record is not null)
+ return record;
+ // No virtual key for it: fall through, as the control does.
+ }
+
+ if (KittyKeyboardActive)
+ return GenerateKittyKeyInput(ev, eventType);
+
+ if (eventType == KittyKeyboardEventType.Release)
+ return null;
+
+ var modifiers = GetLegacyModifiers(ev);
+
+ if (TryGetLegacyNamedKey(ev, out var key))
+ return NullIfEmpty(_keyboardInput.GenerateKeySequence(key, modifiers));
+
+ if (ev.Key.Length == 0 || IsFunctionalKeyName(ev.Key))
+ return null;
+
+ if ((modifiers & (KeyModifiers.Control | KeyModifiers.Alt)) != 0 && ev.Key.Length == 1)
+ return NullIfEmpty(_keyboardInput.GenerateCharSequence(ev.Key[0], modifiers));
+
+ // Plain text: Shift is already in the character.
+ return ev.Key;
+ }
+
+ private static string? NullIfEmpty(string s) => s.Length == 0 ? null : s;
+
+ /// A name rather than text: more than one character and no character outside ASCII letters
+ /// and digits. "Shift", "F13", "Unidentified" -- not "ab" typed by an IME, which has spaces or
+ /// non-ASCII, nor a two-unit emoji.
+ private static bool IsFunctionalKeyName(string key)
+ {
+ if (key.Length < 2 || !char.IsAsciiLetterUpper(key[0]))
+ return false;
+ foreach (var c in key)
+ {
+ if (!char.IsAsciiLetterOrDigit(c))
+ return false;
+ }
+ return true;
+ }
+
+ private static bool TryGetLegacyNamedKey(KeyEvent ev, out Key key)
+ {
+ if (ev.Code.StartsWith("Numpad", StringComparison.Ordinal))
+ {
+ Key? pad = ev.Code switch
+ {
+ "Numpad0" => Key.Keypad0, "Numpad1" => Key.Keypad1, "Numpad2" => Key.Keypad2,
+ "Numpad3" => Key.Keypad3, "Numpad4" => Key.Keypad4, "Numpad5" => Key.Keypad5,
+ "Numpad6" => Key.Keypad6, "Numpad7" => Key.Keypad7, "Numpad8" => Key.Keypad8,
+ "Numpad9" => Key.Keypad9,
+ "NumpadDecimal" => Key.KeypadDecimal,
+ "NumpadDivide" => Key.KeypadDivide,
+ "NumpadMultiply" => Key.KeypadMultiply,
+ "NumpadSubtract" => Key.KeypadSubtract,
+ "NumpadAdd" => Key.KeypadAdd,
+ "NumpadEnter" => Key.KeypadEnter,
+ _ => null
+ };
+
+ // With NumLock off the keypad digits are navigation keys, and Key says which.
+ if (pad is { } p && (ev.Key.Length == 1 || p == Key.KeypadEnter))
+ {
+ key = p;
+ return true;
+ }
+ }
+
+ Key? named = ev.Key switch
+ {
+ "Enter" => Key.Enter,
+ "Tab" => Key.Tab,
+ "Backspace" => Key.Backspace,
+ "Escape" => Key.Escape,
+ "ArrowUp" => Key.UpArrow,
+ "ArrowDown" => Key.DownArrow,
+ "ArrowLeft" => Key.LeftArrow,
+ "ArrowRight" => Key.RightArrow,
+ "Home" => Key.Home,
+ "End" => Key.End,
+ "PageUp" => Key.PageUp,
+ "PageDown" => Key.PageDown,
+ "Insert" => Key.Insert,
+ "Delete" => Key.Delete,
+ _ => null
+ };
+
+ if (named is { } n)
+ {
+ key = n;
+ return true;
+ }
+
+ if (ev.Key.Length is 2 or 3
+ && ev.Key[0] == 'F'
+ && int.TryParse(ev.Key.AsSpan(1), out var number)
+ && number is >= 1 and <= 20)
+ {
+ key = (Key)((int)Key.F1 + number - 1);
+ return true;
+ }
+
+ key = default;
+ return false;
+ }
+
+ ///
+ /// One Win32 INPUT_RECORD for the key, or null when it has no virtual-key code.
+ ///
+ private static string? EncodeWin32Record(KeyEvent ev, bool isKeyDown)
+ {
+ var vk = ev.KeyCode > 0 ? ev.KeyCode : GetVirtualKey(ev);
+ if (vk is <= 0 or > ushort.MaxValue)
+ return null;
+
+ var unicode = 0;
+ if (ev.Key.Length == 1 || (ev.Key.Length == 2 && char.IsSurrogatePair(ev.Key, 0)))
+ {
+ unicode = char.ConvertToUtf32(ev.Key, 0);
+ }
+ else
+ {
+ unicode = ev.Key switch
+ {
+ "Enter" => 0x0D,
+ "Tab" => 0x09,
+ "Backspace" => 0x08,
+ "Escape" => 0x1B,
+ _ => 0
+ };
+ }
+
+ // Ctrl with a character sends its control code, which console programs expecting ^C read.
+ if (ev.CtrlKey && unicode != 0)
+ {
+ unicode = unicode switch
+ {
+ >= 'a' and <= 'z' => unicode - 'a' + 1,
+ >= 'A' and <= 'Z' => unicode - 'A' + 1,
+ 0x20 or '@' => 0x00,
+ '[' => 0x1B,
+ '\\' => 0x1C,
+ ']' => 0x1D,
+ '^' => 0x1E,
+ '_' => 0x1F,
+ '?' => 0x7F,
+ _ => unicode
+ };
+ }
+
+ var state = Win32State.None;
+ if (ev.ShiftKey) state |= Win32State.ShiftPressed;
+ if (ev.CtrlKey) state |= Win32State.LeftCtrlPressed;
+ if (ev.AltKey) state |= Win32State.LeftAltPressed;
+
+ // A modifier key names its own side; the flags above cannot.
+ if (ev.Code == "AltRight")
+ state = (state & ~Win32State.LeftAltPressed) | Win32State.RightAltPressed;
+ if (ev.Code == "ControlRight")
+ state = (state & ~Win32State.LeftCtrlPressed) | Win32State.RightCtrlPressed;
+
+ if (IsEnhancedKey(ev))
+ state |= Win32State.EnhancedKey;
+
+ // Scan code 0: there is no hardware event to take one from.
+ return $"\u001b[{vk};0;{unicode};{(isKeyDown ? 1 : 0)};{(int)state};1_";
+ }
+
+ private static bool IsEnhancedKey(KeyEvent ev) => ev.Code switch
+ {
+ "NumpadDivide" or "NumLock" or "ControlRight" or "AltRight" or "PrintScreen" or "Pause" => true,
+ _ => !ev.Code.StartsWith("Numpad", StringComparison.Ordinal) && ev.Key is
+ "Insert" or "Delete" or "Home" or "End" or "PageUp" or "PageDown"
+ or "ArrowUp" or "ArrowDown" or "ArrowLeft" or "ArrowRight"
+ };
+
+ private static int GetVirtualKey(KeyEvent ev)
+ {
+ var code = ev.Code;
+
+ // The physical key first, so a shifted or composed character still names its key.
+ if (code.Length == 4 && code.StartsWith("Key", StringComparison.Ordinal) && char.IsAsciiLetterUpper(code[3]))
+ return code[3];
+ if (code.Length == 6 && code.StartsWith("Digit", StringComparison.Ordinal) && char.IsAsciiDigit(code[5]))
+ return code[5];
+ // A keypad digit is VK_NUMPADn only while it types its digit. With NumLock off it is Home,
+ // an arrow, Insert..., and Key says which: that key's own VK, below, is what the console sends.
+ var typesCharacter = ev.Key.Length == 1;
+ if (code.Length == 7 && code.StartsWith("Numpad", StringComparison.Ordinal) && char.IsAsciiDigit(code[6]))
+ {
+ if (typesCharacter)
+ return 0x60 + code[6] - '0';
+ }
+
+ var vk = code switch
+ {
+ "NumpadMultiply" => 0x6A,
+ "NumpadAdd" => 0x6B,
+ "NumpadSubtract" => 0x6D,
+ "NumpadDecimal" when typesCharacter => 0x6E,
+ "NumpadDivide" => 0x6F,
+ "NumpadEnter" => 0x0D,
+ "MetaLeft" or "OSLeft" => 0x5B,
+ "MetaRight" or "OSRight" => 0x5C,
+
+ // The OEM keys, by position: the character a shifted one types ("?", ":", "{") has no
+ // VK of its own, so the physical key is the only way to name it.
+ "Semicolon" => 0xBA,
+ "Equal" => 0xBB,
+ "Comma" => 0xBC,
+ "Minus" => 0xBD,
+ "Period" => 0xBE,
+ "Slash" => 0xBF,
+ "Backquote" => 0xC0,
+ "BracketLeft" => 0xDB,
+ "Backslash" => 0xDC,
+ "BracketRight" => 0xDD,
+ "Quote" => 0xDE,
+ "IntlBackslash" => 0xE2,
+ "Space" => 0x20,
+ _ => 0
+ };
+ if (vk != 0)
+ return vk;
+
+ vk = ev.Key switch
+ {
+ "ArrowLeft" => 0x25, "ArrowUp" => 0x26, "ArrowRight" => 0x27, "ArrowDown" => 0x28,
+ "Home" => 0x24, "End" => 0x23, "PageUp" => 0x21, "PageDown" => 0x22,
+ "Insert" => 0x2D, "Delete" => 0x2E,
+ "Backspace" => 0x08, "Tab" => 0x09, "Enter" => 0x0D, "Escape" => 0x1B,
+ "Pause" => 0x13, "CapsLock" => 0x14, "NumLock" => 0x90, "ScrollLock" => 0x91,
+ "PrintScreen" => 0x2C,
+ "Shift" => 0x10, "Control" => 0x11, "Alt" => 0x12, "Meta" => 0x5B,
+ _ => 0
+ };
+ if (vk != 0)
+ return vk;
+
+ if (ev.Key.Length is 2 or 3
+ && ev.Key[0] == 'F'
+ && int.TryParse(ev.Key.AsSpan(1), out var number)
+ && number is >= 1 and <= 24)
+ return 0x70 + number - 1;
+
+ if (ev.Key.Length != 1)
+ return 0;
+
+ var c = ev.Key[0];
+ vk = Win32InputGenerator.GetVirtualKeyCode(c);
+ return vk != 0 ? vk : ShiftedUsKey(c);
+ }
+
+ ///
+ /// The key a shifted character is on, for a host that gave no physical code: the US layout,
+ /// which is the same assumption makes.
+ ///
+ private static int ShiftedUsKey(char c) => c switch
+ {
+ ')' => 0x30, '!' => 0x31, '@' => 0x32, '#' => 0x33, '$' => 0x34,
+ '%' => 0x35, '^' => 0x36, '&' => 0x37, '*' => 0x38, '(' => 0x39,
+ ':' => 0xBA, '+' => 0xBB, '<' => 0xBC, '_' => 0xBD, '>' => 0xBE,
+ '?' => 0xBF, '~' => 0xC0, '{' => 0xDB, '|' => 0xDC, '}' => 0xDD, '"' => 0xDE,
+ _ => 0
+ };
+}
diff --git a/src/XTerm.NET/Terminal.RowChanges.cs b/src/XTerm.NET/Terminal.RowChanges.cs
new file mode 100644
index 0000000..51322ef
--- /dev/null
+++ b/src/XTerm.NET/Terminal.RowChanges.cs
@@ -0,0 +1,181 @@
+using XTerm.Buffer;
+
+namespace XTerm;
+
+///
+/// Which visible rows changed, for a host that has no renderer of its own to tell it.
+///
+///
+/// What counts as a change. The content of a visible row: its cells and their
+/// attributes, its line attribute, the images and sized text on it -- and which buffer line the
+/// row shows at all. That last part is what makes a scroll, a resize, a viewport scroll and the
+/// alternate-screen switch count without any of them writing to the lines they move: the row
+/// shows a different line, so it changed. A write that puts back what was there still counts;
+/// nothing compares cell contents.
+/// What does not. The cursor: moving it changes no row, and a host reads
+/// / and
+/// directly. Nor screen-wide presentation state -- the palette,
+/// , the title -- which belongs to no row.
+/// How. A write costs one increment on the line it touches
+/// (), and nothing else on the print path. The comparison happens
+/// when a host asks -- , and
+/// each look at every visible row once, against what the previous
+/// look saw, and stamp the rows that differ with a new . Asking is
+/// O(rows), never O(cells). itself only reads the result. Because the stamps live here rather than with the caller, any number
+/// of observers can each keep their own last-seen version.
+/// Sized text. An OSC 66 run is stored on its anchor line alone but drawn over the
+/// rows below it, so when a line changes, every visible row its sized text covered before or
+/// covers now is stamped with it -- including from an anchor above the top of the viewport.
+/// Threads. The same contract as : call these on the thread
+/// that writes to the terminal, or serialized with it. The three methods read the buffer and
+/// update the stamps, so they are not safe to call concurrently with a write or with each other.
+/// reads one field and writes nothing, so it can be read from any
+/// thread, without a lock -- what it reports is the last look, not the buffer as it is now.
+///
+public partial class Terminal
+{
+ private long _contentVersion;
+ private BufferLine?[] _seenLines = [];
+ private long[] _seenLineVersions = [];
+ private int[] _seenReach = [];
+ private long[] _rowVersions = [];
+
+ ///
+ /// Lines above the viewport that are watched too: the most a sized run anchored above it can
+ /// reach into it.
+ ///
+ private const int AboveViewport = Common.TextSizing.MaxScale - 1;
+
+ ///
+ /// The version as of the last look: the value ,
+ /// or last brought up to date.
+ ///
+ ///
+ /// A pure read: it does not look at the buffer, so a write since the last look is not in
+ /// it yet. To ask "has anything changed?", call . Zero
+ /// before the first look, which is also the value that reports every row as changed.
+ /// The usual loop needs no refresh of its own: pass the value from last round to
+ /// , which looks first, then read this for the next round.
+ ///
+ public long ContentVersion => Volatile.Read(ref _contentVersion);
+
+ ///
+ /// Looks at the visible rows, stamps the ones that changed since the last look, and returns
+ /// the up-to-date .
+ ///
+ ///
+ /// It moves once per look that found a change, however many rows or writes that change
+ /// spanned, and not at all when nothing did. Compare it for equality, or pass an earlier value
+ /// to to learn which rows moved. Same threading contract as
+ /// ; see the remarks on this class.
+ ///
+ public long RefreshContentVersion()
+ {
+ SyncRowVersions();
+ return _contentVersion;
+ }
+
+ ///
+ /// The at which visible row (0 is the top
+ /// of the viewport) last changed. Looks at the visible rows first, as
+ /// does.
+ ///
+ /// The row is outside the viewport.
+ public long GetRowVersion(int row)
+ {
+ SyncRowVersions();
+ if ((uint)row >= (uint)_rowVersions.Length)
+ throw new ArgumentOutOfRangeException(nameof(row), row, "Not a visible row.");
+ return _rowVersions[row];
+ }
+
+ ///
+ /// Marks, in , every visible row that changed after
+ /// , and returns how many did.
+ ///
+ ///
+ /// Index 0 is the top of the viewport. Rows past the span's end are not reported, and
+ /// entries past are set false. Pass 0 to get every row.
+ /// Looks at the visible rows first, as does. The
+ /// usual loop: pass last round's version here (0 the first time), render or snapshot the
+ /// marked rows, then read -- now current -- for the next round.
+ /// Nothing allocates.
+ ///
+ public int CopyChangedRows(long sinceVersion, Span changed)
+ {
+ SyncRowVersions();
+
+ var rows = _rowVersions;
+ var count = 0;
+ for (int y = 0; y < changed.Length; y++)
+ {
+ var isChanged = y < rows.Length && rows[y] > sinceVersion;
+ changed[y] = isChanged;
+ if (isChanged)
+ count++;
+ }
+
+ return count;
+ }
+
+ private void SyncRowVersions()
+ {
+ var buffer = _buffer;
+ var rows = Rows;
+
+ // Watched lines: AboveViewport of them above the top row, then every visible row. Index i
+ // is the line at ViewportY - AboveViewport + i, so visible row y is index y + AboveViewport.
+ var first = buffer.ViewportY - AboveViewport;
+ var watched = rows + AboveViewport;
+
+ // A different row count -- a resize, or the first look -- changes every row. The old
+ // stamps describe a grid that is not there any more. Keyed on the WATCHED count, which
+ // is never zero: a terminal built with zero rows (before layout) has a zero-length
+ // _rowVersions on its first look too, and must still get its watched arrays.
+ if (_seenLines.Length != watched)
+ {
+ _seenLines = new BufferLine?[watched];
+ _seenLineVersions = new long[watched];
+ _seenReach = new int[watched];
+ _rowVersions = new long[rows];
+ var all = Interlocked.Increment(ref _contentVersion);
+ for (int i = 0; i < watched; i++)
+ {
+ var line = buffer.GetLine(first + i);
+ _seenLines[i] = line;
+ _seenLineVersions[i] = line?.Version ?? 0;
+ _seenReach[i] = line?.SizedRunReach ?? 0;
+ }
+ Array.Fill(_rowVersions, all);
+ return;
+ }
+
+ long stamp = 0;
+ for (int i = 0; i < watched; i++)
+ {
+ var line = buffer.GetLine(first + i);
+ var version = line?.Version ?? 0;
+ if (ReferenceEquals(line, _seenLines[i]) && version == _seenLineVersions[i])
+ continue;
+
+ var reach = line?.SizedRunReach ?? 0;
+ var covered = Math.Max(reach, _seenReach[i]);
+ _seenLines[i] = line;
+ _seenLineVersions[i] = version;
+ _seenReach[i] = reach;
+
+ // The row itself, and the rows its sized text covered before or covers now. A line
+ // above the viewport with nothing reaching into it stamps nothing, and moves nothing.
+ var from = Math.Max(0, i - AboveViewport);
+ var to = Math.Min(rows - 1, i - AboveViewport + covered);
+ if (from > to)
+ continue;
+
+ if (stamp == 0)
+ stamp = Interlocked.Increment(ref _contentVersion);
+
+ for (int y = from; y <= to; y++)
+ _rowVersions[y] = stamp;
+ }
+ }
+}
diff --git a/src/XTerm.NET/Terminal.cs b/src/XTerm.NET/Terminal.cs
index 00a3f3d..5900d67 100644
--- a/src/XTerm.NET/Terminal.cs
+++ b/src/XTerm.NET/Terminal.cs
@@ -13,7 +13,7 @@ namespace XTerm;
/// Main terminal class - the core of xterm.js functionality.
/// Manages buffer, parser, input handler, and terminal state.
///
-public class Terminal : IDisposable
+public partial class Terminal : IDisposable
{
private readonly EscapeSequenceParser _parser;
private readonly InputHandler _inputHandler;