Async line-read, and the decoder and text handling in Bjolang

- read-event, line-read and the editor loop work in both colours. The
  leaf is read-bytes, a defbjouble: a bjoroutine awaits the glue's read,
  other code blocks. with-raw-mode takes a body of either colour.
- Cancelling the scope of a waiting line-read ends it and restores the
  terminal modes. The glue runs reads one at a time.
- The key decoder is (bjoterm keys), and widths, prompt escapes, search
  and common prefixes are (bjoterm text). Clusters and categories come
  from (std unicode grapheme) and (std unicode chars).
- Keys.cs and Text.cs are removed. The glue is termios, signals, poll
  and read.
- New tests: tests/async.bjo and tests/text.bjo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-30 21:05:59 +01:00
parent 6863503fa7
commit ce778f9b1e
11 changed files with 970 additions and 733 deletions

View file

@ -1,301 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// The decoder of terminal input: bytes in, events out.
using System.Text;
namespace Bjoterm;
/// <summary>
/// One event read from the terminal, as flat fields. (bjoterm terminal)
/// maps it to its union.
/// </summary>
public sealed class TermEvent {
public const int TimeoutKind = 0, KeyKind = 1, PasteKind = 2, ResizedKind = 3, EndKind = 4;
// The keys. Char carries the code point in Value, F the number in Value.
public const int Char = 0, Enter = 1, Tab = 2, Backspace = 3, Escape = 4,
Up = 5, Down = 6, Left = 7, Right = 8, Home = 9, End_ = 10,
PageUp = 11, PageDown = 12, Insert = 13, Delete = 14, F = 15, Unknown = 16;
public const int Shift = 1, Alt = 2, Ctrl = 4;
internal static readonly TermEvent TimedOut = new(TimeoutKind, 0, 0, 0, 0, "");
internal static readonly TermEvent End = new(EndKind, 0, 0, 0, 0, "");
private TermEvent(int kind, int key, int value, int value2, int mods, string text) {
Kind = kind;
Key = key;
Value = value;
Value2 = value2;
Mods = mods;
Text = text;
}
internal static TermEvent KeyOf(int key, int mods, int value = 0) => new(KeyKind, key, value, 0, mods, "");
internal static TermEvent UnknownOf(string text) => new(KeyKind, Unknown, 0, 0, 0, text);
internal static TermEvent Paste(string text) => new(PasteKind, 0, 0, 0, 0, text);
internal static TermEvent Resized(int cols, int rows) => new(ResizedKind, 0, cols, rows, 0, "");
public int Kind { get; }
public int Key { get; }
/// The code point of a <see cref="Char"/> key, the number of an
/// <see cref="F"/> key, or the columns of a resize.
public int Value { get; }
/// The rows of a resize.
public int Value2 { get; }
/// <see cref="Shift"/>, <see cref="Alt"/> and <see cref="Ctrl"/>.
public int Mods { get; }
/// The text of a paste, or the bytes of an unknown sequence (ESC as
/// "^[").
public string Text { get; }
}
/// <summary>
/// Decodes terminal input into events.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><see cref="Feed"/> adds bytes; <see cref="Next"/> returns the next
/// complete event, or null when the bytes so far are a partial one.</item>
/// <item><c>Next(final: true)</c> decodes a partial event as it is: a lone
/// ESC is the Escape key, ESC and one key is Alt and that key, a cut UTF-8
/// character is U+FFFD, and a cut sequence is <see cref="TermEvent.Unknown"/>.
/// The reader calls it when no more bytes came within the sequence
/// timeout.</item>
/// <item>Keys: CSI and SS3 sequences of xterm, with the modifier parameter
/// (<c>ESC [ 1 ; 5 A</c> is Ctrl-Up), the <c>~</c> keys, F1 to F12, and
/// Shift-Tab (<c>ESC [ Z</c>).</item>
/// <item>Bracketed paste: the bytes between <c>ESC [ 200 ~</c> and
/// <c>ESC [ 201 ~</c> are one paste, decoded as UTF-8 with CR LF and CR
/// made LF. A paste is not cut by the timeout.</item>
/// </list>
/// </remarks>
public sealed class Decoder {
private static readonly byte[] PasteEnd = "\x1b[201~"u8.ToArray();
private byte[] buffer = new byte[256];
private int start, end;
private bool inPaste;
public bool HasPartial => end > start;
public bool InPaste => inPaste;
public void Reset() {
start = end = 0;
inPaste = false;
}
public void Feed(byte[] data, int count) {
if (start > 0 && end == start) start = end = 0;
if (end + count > buffer.Length) {
int live = end - start;
var grown = live + count > buffer.Length ? new byte[Math.Max(buffer.Length * 2, live + count)] : buffer;
Array.Copy(buffer, start, grown, 0, live);
buffer = grown;
start = 0;
end = live;
}
Array.Copy(data, 0, buffer, end, count);
end += count;
}
/// Decodes all of <paramref name="data"/> as input that ends there: a
/// partial event at the end is decoded as it is.
public static TermEvent[] DecodeAll(byte[] data) {
var decoder = new Decoder();
decoder.Feed(data, data.Length);
var events = new List<TermEvent>();
while (decoder.Next(final: false) is { } ev) events.Add(ev);
while (decoder.Next(final: true) is { } last) events.Add(last);
return events.ToArray();
}
public TermEvent? Next(bool final) {
if (inPaste) return NextPaste();
if (end == start) return null;
var (ev, used) = Decode(start, final);
if (ev is null) return null;
start += used;
if (ev == PasteStart) {
inPaste = true;
return NextPaste();
}
return ev;
}
// A marker for ESC [ 200 ~; never returned.
private static readonly TermEvent PasteStart = TermEvent.UnknownOf("paste");
private TermEvent? NextPaste() {
var span = buffer.AsSpan(start, end - start);
int at = span.IndexOf(PasteEnd);
if (at < 0) return null;
string text = Encoding.UTF8.GetString(span[..at]).Replace("\r\n", "\n").Replace('\r', '\n');
start += at + PasteEnd.Length;
inPaste = false;
return TermEvent.Paste(text);
}
// Decodes one event at `at`. Returns (null, 0) when more bytes are
// needed and `final` is false.
private (TermEvent?, int) Decode(int at, bool final) {
int avail = end - at;
byte b = buffer[at];
if (b == 0x1b) {
if (avail == 1) return final ? (TermEvent.KeyOf(TermEvent.Escape, 0), 1) : (null, 0);
byte next = buffer[at + 1];
if (next == (byte)'[') return Csi(at, final);
if (next == (byte)'O') return Ss3(at, final);
// ESC and a key is Alt and that key.
var (key, used) = Decode(at + 1, final);
if (key is null) return (null, 0);
if (key.Kind != TermEvent.KeyKind || key.Key == TermEvent.Unknown) {
return (TermEvent.UnknownOf(Shown(at, 1 + used)), 1 + used);
}
return (TermEvent.KeyOf(key.Key, key.Mods | TermEvent.Alt, key.Value), 1 + used);
}
if (b < 0x80) return (Ascii(b), 1);
return Utf8(at, final);
}
private static TermEvent Ascii(byte b) => b switch {
0x0d => TermEvent.KeyOf(TermEvent.Enter, 0),
0x09 => TermEvent.KeyOf(TermEvent.Tab, 0),
0x7f => TermEvent.KeyOf(TermEvent.Backspace, 0),
0x08 => TermEvent.KeyOf(TermEvent.Backspace, TermEvent.Ctrl),
0x00 => TermEvent.KeyOf(TermEvent.Char, TermEvent.Ctrl, ' '),
< 0x1b => TermEvent.KeyOf(TermEvent.Char, TermEvent.Ctrl, 0x60 + b),
< 0x20 => TermEvent.KeyOf(TermEvent.Char, TermEvent.Ctrl, 0x40 + b),
_ => TermEvent.KeyOf(TermEvent.Char, 0, b),
};
private (TermEvent?, int) Utf8(int at, bool final) {
byte b = buffer[at];
int length = b >= 0xf0 && b < 0xf8 ? 4 : b >= 0xe0 ? 3 : b >= 0xc2 && b < 0xe0 ? 2 : 0;
if (length == 0) return (TermEvent.KeyOf(TermEvent.Char, 0, 0xfffd), 1);
int have = 1;
while (have < length && at + have < end && (buffer[at + have] & 0xc0) == 0x80) have++;
if (have < length) {
// Cut: wait for the rest, unless a byte that cannot continue it
// came, or no more will come.
if (at + have == end && !final) return (null, 0);
return (TermEvent.KeyOf(TermEvent.Char, 0, 0xfffd), have);
}
var status = System.Text.Rune.DecodeFromUtf8(buffer.AsSpan(at, length), out var rune, out _);
int value = status == System.Buffers.OperationStatus.Done ? rune.Value : 0xfffd;
return (TermEvent.KeyOf(TermEvent.Char, 0, value), length);
}
// ESC [ parameters intermediates final.
private (TermEvent?, int) Csi(int at, bool final) {
int i = at + 2;
while (i < end && buffer[i] >= 0x30 && buffer[i] <= 0x3f) i++;
while (i < end && buffer[i] >= 0x20 && buffer[i] <= 0x2f) i++;
if (i == end) {
if (!final) return (null, 0);
// ESC [ alone is Alt-[.
if (end - at == 2) return (TermEvent.KeyOf(TermEvent.Char, TermEvent.Alt, '['), 2);
return (TermEvent.UnknownOf(Shown(at, end - at)), end - at);
}
byte last = buffer[i];
int used = i + 1 - at;
if (last < 0x40 || last > 0x7e) return (TermEvent.UnknownOf(Shown(at, used)), used);
var parameters = Encoding.ASCII.GetString(buffer, at + 2, i - at - 2).Split(';');
int first = Number(parameters, 0, 1);
int mods = Modifiers(Number(parameters, 1, 1));
int key = last switch {
(byte)'A' => TermEvent.Up,
(byte)'B' => TermEvent.Down,
(byte)'C' => TermEvent.Right,
(byte)'D' => TermEvent.Left,
(byte)'H' => TermEvent.Home,
(byte)'F' => TermEvent.End_,
(byte)'P' or (byte)'Q' or (byte)'R' or (byte)'S' => TermEvent.F,
(byte)'Z' => TermEvent.Tab,
(byte)'~' => Tilde(first),
_ => TermEvent.Unknown,
};
if (last == (byte)'~' && first == 200) return (PasteStart, used);
if (key == TermEvent.Unknown) return (TermEvent.UnknownOf(Shown(at, used)), used);
if (last == (byte)'Z') return (TermEvent.KeyOf(TermEvent.Tab, TermEvent.Shift), used);
int number = key != TermEvent.F ? 0 : last == (byte)'~' ? FunctionNumber(first) : last - (byte)'P' + 1;
return (TermEvent.KeyOf(key, mods, number), used);
}
// ESC O key: the keys of application cursor mode, and F1 to F4.
private (TermEvent?, int) Ss3(int at, bool final) {
if (end - at < 3) {
if (!final) return (null, 0);
return (TermEvent.KeyOf(TermEvent.Char, TermEvent.Alt, 'O'), 2);
}
byte k = buffer[at + 2];
var ev = k switch {
(byte)'A' => TermEvent.KeyOf(TermEvent.Up, 0),
(byte)'B' => TermEvent.KeyOf(TermEvent.Down, 0),
(byte)'C' => TermEvent.KeyOf(TermEvent.Right, 0),
(byte)'D' => TermEvent.KeyOf(TermEvent.Left, 0),
(byte)'H' => TermEvent.KeyOf(TermEvent.Home, 0),
(byte)'F' => TermEvent.KeyOf(TermEvent.End_, 0),
(byte)'M' => TermEvent.KeyOf(TermEvent.Enter, 0),
>= (byte)'P' and <= (byte)'S' => TermEvent.KeyOf(TermEvent.F, 0, k - 'P' + 1),
_ => TermEvent.UnknownOf(Shown(at, 3)),
};
return (ev, 3);
}
private static int Tilde(int n) => n switch {
1 or 7 => TermEvent.Home,
2 => TermEvent.Insert,
3 => TermEvent.Delete,
4 or 8 => TermEvent.End_,
5 => TermEvent.PageUp,
6 => TermEvent.PageDown,
>= 11 and <= 15 or >= 17 and <= 21 or 23 or 24 => TermEvent.F,
_ => TermEvent.Unknown,
};
private static int FunctionNumber(int n) => n switch {
<= 15 => n - 10,
<= 21 => n - 11,
_ => n - 12,
};
// xterm's modifier parameter is 1 plus the bits shift 1, alt 2, ctrl 4,
// meta 8. Meta is reported as Alt.
private static int Modifiers(int parameter) {
int bits = Math.Max(0, parameter - 1);
int mods = 0;
if ((bits & 1) != 0) mods |= TermEvent.Shift;
if ((bits & 2) != 0 || (bits & 8) != 0) mods |= TermEvent.Alt;
if ((bits & 4) != 0) mods |= TermEvent.Ctrl;
return mods;
}
private static int Number(string[] parameters, int index, int missing) =>
index < parameters.Length && int.TryParse(parameters[index], out int n) ? n : missing;
private string Shown(int at, int count) {
var text = new StringBuilder();
for (int i = at; i < at + count; i++) {
byte b = buffer[i];
if (b == 0x1b) text.Append("^[");
else if (b < 0x20 || b >= 0x7f) text.Append($"\\x{b:x2}");
else text.Append((char)b);
}
return text.ToString();
}
}

View file

@ -1,208 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// Text on a terminal: grapheme clusters and their widths in columns.
using System.Globalization;
using System.Text;
namespace Bjoterm;
/// <summary>
/// Grapheme clusters and display widths.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>Clusters are .NET's extended grapheme clusters (UAX #29). The
/// line editor moves and deletes by cluster.</item>
/// <item>Widths follow <c>wcwidth</c>: 2 for East Asian wide and
/// fullwidth characters and for emoji shown as emoji, 0 for combining
/// marks and format characters, 1 otherwise. A terminal's own table can
/// differ for new emoji.</item>
/// <item>A C0 control or DEL is shown as <c>^X</c>, 2 columns. A C1
/// control (U+0080 to U+009F) is shown as U+FFFD, 1 column.</item>
/// </list>
/// </remarks>
public static class Text {
/// The grapheme clusters of <paramref name="text"/>. CR LF is one.
public static string[] Clusters(string text) {
var result = new List<string>();
var e = StringInfo.GetTextElementEnumerator(text);
while (e.MoveNext()) result.Add(e.GetTextElement());
return result.ToArray();
}
/// The clusters of a prompt: as <see cref="Clusters"/>, except that an
/// escape sequence (CSI, or OSC ended by BEL or ST) is one item, of
/// width 0.
public static string[] PromptClusters(string text) {
var result = new List<string>();
int i = 0, plain = 0;
while (i < text.Length) {
int seq = EscapeLength(text, i);
if (seq == 0) {
i++;
continue;
}
if (i > plain) result.AddRange(Clusters(text[plain..i]));
result.Add(text.Substring(i, seq));
i += seq;
plain = i;
}
if (text.Length > plain) result.AddRange(Clusters(text[plain..]));
return result.ToArray();
}
/// The columns <paramref name="cluster"/> takes. 0 for an escape
/// sequence from <see cref="PromptClusters"/>.
public static int Width(string cluster) {
if (cluster.Length == 0) return 0;
if (cluster.Length > 1 && cluster[0] == '\x1b') return 0;
int first = char.ConvertToUtf32(cluster, 0);
if (first < 0x20 || first == 0x7f) return 2;
if (first >= 0x80 && first < 0xa0) return 1;
int width = RuneWidth(first);
if (width == 2) return 2;
// Emoji presentation, or a flag of two regional indicators.
if (cluster.Contains('️')) return 2;
if (first >= 0x1f1e6 && first <= 0x1f1ff && cluster.Length >= 4) return 2;
if (width == 0) {
// A cluster that starts with a mark: the widest of its parts.
int widest = 0;
foreach (var rune in cluster.EnumerateRunes()) widest = Math.Max(widest, RuneWidth(rune.Value));
return widest;
}
return width;
}
/// The columns of <paramref name="text"/>, escape sequences as 0.
public static int TextWidth(string text) {
int total = 0;
foreach (var cluster in PromptClusters(text)) total += Width(cluster);
return total;
}
/// What is written for <paramref name="cluster"/>: <c>^X</c> for a C0
/// control or DEL, U+FFFD for a C1 control, else the cluster.
public static string Shown(string cluster) {
if (cluster.Length == 0) return cluster;
if (cluster.Length > 1 && cluster[0] == '\x1b') return cluster;
int first = cluster[0];
if (first < 0x20) return "^" + (char)(first + 0x40);
if (first == 0x7f) return "^?";
if (first >= 0x80 && first < 0xa0) return "<22>";
return cluster;
}
/// Whether <paramref name="cluster"/> is part of a word: it starts with
/// a letter, a digit or '_'.
public static bool IsWord(string cluster) {
if (cluster.Length == 0) return false;
var rune = Rune.GetRuneAt(cluster, 0);
return Rune.IsLetterOrDigit(rune) || rune.Value == '_';
}
/// The cluster index of the first occurrence of
/// <paramref name="query"/> in <paramref name="text"/> that starts and
/// ends on cluster boundaries, or -1. Ordinal; case matters.
public static int Find(string text, string query) {
var clusters = Clusters(text);
var starts = new int[clusters.Length + 1];
for (int i = 0; i < clusters.Length; i++) starts[i + 1] = starts[i] + clusters[i].Length;
int from = 0;
while (from <= text.Length) {
int at = text.IndexOf(query, from, StringComparison.Ordinal);
if (at < 0) return -1;
int index = Array.BinarySearch(starts, at);
if (index >= 0 && Array.BinarySearch(starts, at + query.Length) >= 0) return index;
from = at + 1;
}
return -1;
}
/// The longest common prefix of <paramref name="texts"/>, whole
/// clusters only. Empty for no texts.
public static string CommonPrefix(string[] texts) {
if (texts.Length == 0) return "";
var first = Clusters(texts[0]);
int length = first.Length;
foreach (var text in texts.AsSpan(1)) {
var other = Clusters(text);
int same = 0;
while (same < length && same < other.Length && first[same] == other[same]) same++;
length = same;
}
return string.Concat(first.AsSpan(0, length));
}
/// The width of one code point, as <c>wcwidth</c>.
public static int RuneWidth(int c) {
if (c == 0) return 0;
if (c == 0x200b || (c >= 0x1160 && c <= 0x11ff)) return 0;
if (!Rune.IsValid(c)) return 1;
switch (Rune.GetUnicodeCategory(new Rune(c))) {
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.Format:
return c == 0xad ? 1 : 0;
}
return IsWide(c) ? 2 : 1;
}
private static bool IsWide(int c) {
if (c < 0x1100) return false;
int lo = 0, hi = Wide.Length / 2 - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (c < Wide[mid * 2]) hi = mid - 1;
else if (c > Wide[mid * 2 + 1]) lo = mid + 1;
else return true;
}
return false;
}
// Ranges of East Asian Wide and Fullwidth code points, and of emoji
// with emoji presentation by default (Unicode 15). Sorted, inclusive.
private static readonly int[] Wide = [
0x1100, 0x115f, 0x231a, 0x231b, 0x2329, 0x232a, 0x23e9, 0x23ec, 0x23f0, 0x23f0,
0x23f3, 0x23f3, 0x25fd, 0x25fe, 0x2614, 0x2615, 0x2648, 0x2653, 0x267f, 0x267f,
0x2693, 0x2693, 0x26a1, 0x26a1, 0x26aa, 0x26ab, 0x26bd, 0x26be, 0x26c4, 0x26c5,
0x26ce, 0x26ce, 0x26d4, 0x26d4, 0x26ea, 0x26ea, 0x26f2, 0x26f3, 0x26f5, 0x26f5,
0x26fa, 0x26fa, 0x26fd, 0x26fd, 0x2705, 0x2705, 0x270a, 0x270b, 0x2728, 0x2728,
0x274c, 0x274c, 0x274e, 0x274e, 0x2753, 0x2755, 0x2757, 0x2757, 0x2795, 0x2797,
0x27b0, 0x27b0, 0x27bf, 0x27bf, 0x2b1b, 0x2b1c, 0x2b50, 0x2b50, 0x2b55, 0x2b55,
0x2e80, 0x303e, 0x3041, 0x33ff, 0x3400, 0x4dbf, 0x4e00, 0x9fff, 0xa000, 0xa4cf,
0xa960, 0xa97f, 0xac00, 0xd7a3, 0xf900, 0xfaff, 0xfe10, 0xfe19, 0xfe30, 0xfe6f,
0xff00, 0xff60, 0xffe0, 0xffe6, 0x16fe0, 0x16fe4, 0x17000, 0x18aff, 0x1b000, 0x1b2ff,
0x1f004, 0x1f004, 0x1f0cf, 0x1f0cf, 0x1f18e, 0x1f18e, 0x1f191, 0x1f19a, 0x1f200, 0x1f202,
0x1f210, 0x1f23b, 0x1f240, 0x1f248, 0x1f250, 0x1f251, 0x1f260, 0x1f265, 0x1f300, 0x1f320,
0x1f32d, 0x1f335, 0x1f337, 0x1f37c, 0x1f37e, 0x1f393, 0x1f3a0, 0x1f3ca, 0x1f3cf, 0x1f3d3,
0x1f3e0, 0x1f3f0, 0x1f3f4, 0x1f3f4, 0x1f3f8, 0x1f43e, 0x1f440, 0x1f440, 0x1f442, 0x1f4fc,
0x1f4ff, 0x1f53d, 0x1f54b, 0x1f54e, 0x1f550, 0x1f567, 0x1f57a, 0x1f57a, 0x1f595, 0x1f596,
0x1f5a4, 0x1f5a4, 0x1f5fb, 0x1f64f, 0x1f680, 0x1f6c5, 0x1f6cc, 0x1f6cc, 0x1f6d0, 0x1f6d2,
0x1f6d5, 0x1f6d7, 0x1f6dc, 0x1f6df, 0x1f6eb, 0x1f6ec, 0x1f6f4, 0x1f6fc, 0x1f7e0, 0x1f7eb,
0x1f7f0, 0x1f7f0, 0x1f90c, 0x1f93a, 0x1f93c, 0x1f945, 0x1f947, 0x1f9ff, 0x1fa70, 0x1faff,
0x20000, 0x2fffd, 0x30000, 0x3fffd,
];
// The length of an escape sequence at `i`, or 0.
private static int EscapeLength(string text, int i) {
if (text[i] != '\x1b' || i + 1 >= text.Length) return 0;
char kind = text[i + 1];
if (kind == '[') {
int j = i + 2;
while (j < text.Length && text[j] >= 0x20 && text[j] <= 0x3f) j++;
return j < text.Length && text[j] >= 0x40 && text[j] <= 0x7e ? j + 1 - i : 0;
}
if (kind == ']') {
for (int j = i + 2; j < text.Length; j++) {
if (text[j] == '\a') return j + 1 - i;
if (text[j] == '\x1b' && j + 1 < text.Length && text[j + 1] == '\\') return j + 2 - i;
}
return 0;
}
return 0;
}
}

View file

@ -4,7 +4,8 @@
*/
// The terminal on fd 0 and fd 1: raw mode, the size, signals, and reading
// events. (bjoterm terminal) is the Bjolang side.
// bytes. (bjoterm terminal) is the Bjolang side: it decodes the bytes, and
// waits for the rest of a sequence.
using System.ComponentModel;
using System.Runtime.InteropServices;
@ -23,18 +24,17 @@ namespace Bjoterm;
/// mode; <see cref="LeaveRaw"/> restores the saved modes. They are also
/// restored at process exit.</item>
/// <item>Signals, registered at the first open:
/// - SIGWINCH: the next read returns a resize.
/// - SIGCONT in raw mode: raw mode is set again, the next read returns a
/// resize, and .NET's own handling (which sets .NET's modes) is
/// cancelled.
/// - SIGWINCH: <see cref="TakeResized"/> returns true once, and a read
/// that waits returns <see cref="Resized"/>.
/// - SIGCONT in raw mode: raw mode is set again, it counts as a resize,
/// and .NET's own handling (which sets .NET's modes) is cancelled.
/// - SIGTSTP in raw mode (only with ISIG on): the saved modes are restored
/// and the process stops with SIGSTOP. SIGCONT then sets raw mode
/// again.</item>
/// <item>SIGTERM, SIGHUP and SIGQUIT in raw mode: the saved modes are
/// restored, and the signal is not cancelled. A program that cancels one of
/// them to go on running is in cooked mode after it.</item>
/// <item>One read at a time. A second concurrent <see cref="ReadAsync"/>
/// raises <see cref="InvalidOperationException"/>.</item>
/// <item>Reads run one at a time.</item>
/// </list>
/// </remarks>
[SupportedOSPlatform("linux")]
@ -53,8 +53,11 @@ public sealed unsafe class Tty {
private const int EINTR = 4, EAGAIN = 11;
private const int SIGTSTP = 20, SIGSTOP = 19;
/// The time to wait for the rest of a sequence after its first bytes.
public const int SequenceTimeoutMs = 50;
/// What <see cref="ReadAsync"/> returns at end of input.
public const int EndOfInput = -1;
/// What <see cref="ReadAsync"/> returns after a resize.
public const int Resized = -2;
private static readonly object openGate = new();
private static Tty? opened;
@ -62,7 +65,6 @@ public sealed unsafe class Tty {
private readonly object gate = new();
private readonly byte[] saved = new byte[TermiosSize];
private readonly byte[] raw = new byte[TermiosSize];
private readonly Decoder decoder = new();
private readonly List<PosixSignalRegistration> registrations = new();
private readonly int wakeRead, wakeWrite;
// Inside EnterRaw ... LeaveRaw.
@ -70,7 +72,7 @@ public sealed unsafe class Tty {
// The raw modes are set on the terminal now.
private bool rawSet;
private int resized;
private int reading;
private readonly object readGate = new();
private Tty(int wakeRead, int wakeWrite) {
this.wakeRead = wakeRead;
@ -135,7 +137,6 @@ public sealed unsafe class Tty {
raw[CcOffset + VTIME] = 0;
ApplyRaw();
rawWanted = true;
decoder.Reset();
}
}
@ -164,56 +165,40 @@ public sealed unsafe class Tty {
}
}
/// Reads the next event.
/// Whether the terminal was resized, or the process continued, since
/// the last call.
public bool TakeResized() => Interlocked.Exchange(ref resized, 0) != 0;
/// Reads bytes into <paramref name="buffer"/>.
/// <list type="bullet">
/// <item><paramref name="timeoutMs"/> below 0 waits for ever. A timeout
/// returns an event of kind <see cref="TermEvent.Timeout"/>.</item>
/// <item>The rest of a sequence is waited for
/// <see cref="SequenceTimeoutMs"/>; then what came is decoded alone (a
/// lone ESC is the Escape key).</item>
/// <item>Returns the count read; 0 after <paramref name="timeoutMs"/>
/// (below 0 waits for ever); <see cref="EndOfInput"/>; or
/// <see cref="Resized"/> when a resize came first.</item>
/// <item>Cancelling the token raises
/// <see cref="OperationCanceledException"/>. Bytes read before that stay
/// for the next read.</item>
/// <see cref="OperationCanceledException"/>. Nothing has been read
/// then.</item>
/// <item>Reads run one at a time: a read waits for the one before it.
/// A cancelled read ends soon after, as its wait is woken.</item>
/// </list>
public Task<TermEvent> ReadAsync(int timeoutMs, CancellationToken cancel) {
if (Interlocked.Exchange(ref reading, 1) != 0) {
throw new InvalidOperationException("Another read of the terminal is in progress.");
}
public Task<int> ReadAsync(byte[] buffer, int timeoutMs, CancellationToken cancel) {
// poll blocks the thread, so the read runs on a thread of its own.
return Task.Factory.StartNew(() => {
try {
lock (readGate) {
using var wake = cancel.Register(Wake);
return Read(timeoutMs, cancel);
} finally {
Volatile.Write(ref reading, 0);
return Read(buffer, timeoutMs, cancel);
}
// Not the caller's token: a task cancelled before it starts would
// never clear `reading`.
// Not the caller's token: the task always runs, and raises from
// Read when the token is cancelled.
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private TermEvent Read(int timeoutMs, CancellationToken cancel) {
private int Read(byte[] buffer, int timeoutMs, CancellationToken cancel) {
long deadline = timeoutMs < 0 ? long.MaxValue : Environment.TickCount64 + timeoutMs;
var buffer = new byte[4096];
pollfd* fds = stackalloc pollfd[2];
while (true) {
if (Interlocked.Exchange(ref resized, 0) != 0) {
var size = Size();
return TermEvent.Resized(size[0], size[1]);
}
var ready = decoder.Next(final: false);
if (ready is not null) return ready;
cancel.ThrowIfCancellationRequested();
int wait;
if (decoder.HasPartial && !decoder.InPaste) {
wait = SequenceTimeoutMs;
} else if (deadline == long.MaxValue) {
wait = -1;
} else {
wait = (int)Math.Max(0, deadline - Environment.TickCount64);
}
if (Volatile.Read(ref resized) != 0) return Resized;
int wait = deadline == long.MaxValue ? -1 : (int)Math.Max(0, deadline - Environment.TickCount64);
fds[0] = new pollfd { fd = 0, events = POLLIN };
fds[1] = new pollfd { fd = wakeRead, events = POLLIN };
int n = poll(fds, 2, wait);
@ -221,31 +206,22 @@ public sealed unsafe class Tty {
if (Marshal.GetLastPInvokeError() == EINTR) continue;
throw LastError();
}
if ((fds[1].revents & POLLIN) != 0) DrainWake();
if ((fds[1].revents & POLLIN) != 0) {
DrainWake();
continue;
}
if ((fds[0].revents & (POLLIN | POLLHUP | POLLERR)) != 0) {
long got;
fixed (byte* b = buffer) {
got = read(0, b, buffer.Length);
}
if (got < 0) {
int errno = Marshal.GetLastPInvokeError();
if (errno == EINTR || errno == EAGAIN) continue;
throw LastError(errno);
}
if (got == 0) {
return decoder.Next(final: true) ?? TermEvent.End;
}
decoder.Feed(buffer, (int)got);
continue;
}
if (n == 0) {
if (decoder.HasPartial && !decoder.InPaste) {
var last = decoder.Next(final: true);
if (last is not null) return last;
continue;
}
if (Environment.TickCount64 >= deadline) return TermEvent.TimedOut;
if (got > 0) return (int)got;
if (got == 0) return EndOfInput;
int errno = Marshal.GetLastPInvokeError();
if (errno == EINTR || errno == EAGAIN) continue;
throw LastError(errno);
}
if (n == 0) return 0;
}
}