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

@ -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;
}
}