bjoterm: raw mode, key events and escape sequences
- (bjoterm terminal): terminal-open, with-raw-mode, terminal-size, terminal-suspend, read-event and read-event/timeout, and escape sequences for the cursor, clearing, the alternate screen, bracketed paste and styles. Linux only. - glue/Tty.cs: termios, poll on fd 0, SIGWINCH, SIGCONT, SIGTSTP, and restoring the modes at SIGTERM, SIGHUP, SIGQUIT and process exit. - glue/Keys.cs: the decoder of CSI and SS3 keys with modifiers, Alt, UTF-8 and bracketed paste. - Tests: the decoder from bytes, and raw mode on a pseudo-terminal under script. plan.org has the decisions and the phases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
fe42387a4c
12 changed files with 1830 additions and 0 deletions
301
glue/Keys.cs
Normal file
301
glue/Keys.cs
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
/* 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();
|
||||
}
|
||||
}
|
||||
342
glue/Tty.cs
Normal file
342
glue/Tty.cs
Normal file
|
|
@ -0,0 +1,342 @@
|
|||
/* 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 terminal on fd 0 and fd 1: raw mode, the size, signals, and reading
|
||||
// events. (bjoterm terminal) is the Bjolang side.
|
||||
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Bjoterm;
|
||||
|
||||
/// <summary>
|
||||
/// The terminal of this process.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>One per process: <see cref="Open"/> returns the same object each
|
||||
/// time. Linux only.</item>
|
||||
/// <item>Modes: <see cref="EnterRaw"/> saves the current modes and sets raw
|
||||
/// 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.
|
||||
/// - 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>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
[SupportedOSPlatform("linux")]
|
||||
public sealed unsafe class Tty {
|
||||
// Linux termios, the same on x86-64 and arm64.
|
||||
private const int TermiosSize = 60;
|
||||
private const int IFlag = 0, CFlag = 8, LFlag = 12, CcOffset = 17;
|
||||
private const int VTIME = 5, VMIN = 6;
|
||||
private const uint BRKINT = 0x2, INPCK = 0x10, ISTRIP = 0x20, ICRNL = 0x100, IXON = 0x400;
|
||||
private const uint CS8 = 0x30;
|
||||
private const uint ISIG = 0x1, ICANON = 0x2, ECHO = 0x8, IEXTEN = 0x8000;
|
||||
private const int TCSADRAIN = 1;
|
||||
private const ulong TIOCGWINSZ = 0x5413;
|
||||
private const short POLLIN = 0x1, POLLHUP = 0x10, POLLERR = 0x8;
|
||||
private const int O_NONBLOCK = 0x800, O_CLOEXEC = 0x80000;
|
||||
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;
|
||||
|
||||
private static readonly object openGate = new();
|
||||
private static Tty? opened;
|
||||
|
||||
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.
|
||||
private bool rawWanted;
|
||||
// The raw modes are set on the terminal now.
|
||||
private bool rawSet;
|
||||
private int resized;
|
||||
private int reading;
|
||||
|
||||
private Tty(int wakeRead, int wakeWrite) {
|
||||
this.wakeRead = wakeRead;
|
||||
this.wakeWrite = wakeWrite;
|
||||
}
|
||||
|
||||
/// Opens the terminal. Raises <see cref="PlatformNotSupportedException"/>
|
||||
/// on a system other than Linux, and <see cref="IOException"/> when fd 0
|
||||
/// or fd 1 is not a terminal.
|
||||
public static Tty Open() {
|
||||
lock (openGate) {
|
||||
if (opened is not null) return opened;
|
||||
if (!OperatingSystem.IsLinux()) {
|
||||
throw new PlatformNotSupportedException("bjoterm supports only Linux for now.");
|
||||
}
|
||||
if (isatty(0) != 1) throw new IOException("Standard input is not a terminal.");
|
||||
if (isatty(1) != 1) throw new IOException("Standard output is not a terminal.");
|
||||
int* fds = stackalloc int[2];
|
||||
if (pipe2(fds, O_NONBLOCK | O_CLOEXEC) != 0) throw LastError();
|
||||
var tty = new Tty(fds[0], fds[1]);
|
||||
tty.registrations.Add(PosixSignalRegistration.Create(PosixSignal.SIGWINCH, tty.OnResize));
|
||||
tty.registrations.Add(PosixSignalRegistration.Create(PosixSignal.SIGCONT, tty.OnContinue));
|
||||
tty.registrations.Add(PosixSignalRegistration.Create(PosixSignal.SIGTSTP, tty.OnStop));
|
||||
// These end the process with no finally block and no
|
||||
// ProcessExit. They are not cancelled here.
|
||||
foreach (var signal in new[] { PosixSignal.SIGTERM, PosixSignal.SIGHUP, PosixSignal.SIGQUIT }) {
|
||||
tty.registrations.Add(PosixSignalRegistration.Create(signal, tty.OnEnd));
|
||||
}
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => tty.RestoreAtExit();
|
||||
opened = tty;
|
||||
return tty;
|
||||
}
|
||||
}
|
||||
|
||||
/// The size as [columns, rows]. [80, 24] when the terminal does not say.
|
||||
public int[] Size() {
|
||||
ushort* ws = stackalloc ushort[4];
|
||||
if (ioctl(1, TIOCGWINSZ, ws) != 0 && ioctl(0, TIOCGWINSZ, ws) != 0) return [80, 24];
|
||||
int rows = ws[0], cols = ws[1];
|
||||
return [cols > 0 ? cols : 80, rows > 0 ? rows : 24];
|
||||
}
|
||||
|
||||
public bool IsRaw {
|
||||
get { lock (gate) { return rawWanted; } }
|
||||
}
|
||||
|
||||
/// Saves the current modes and sets raw mode. With
|
||||
/// <paramref name="signals"/>, Ctrl-C, Ctrl-Z and Ctrl-\ still send
|
||||
/// their signals. Raises <see cref="InvalidOperationException"/> when
|
||||
/// raw mode is set already.
|
||||
public void EnterRaw(bool signals) {
|
||||
lock (gate) {
|
||||
if (rawWanted) throw new InvalidOperationException("The terminal is in raw mode already.");
|
||||
fixed (byte* s = saved) {
|
||||
if (tcgetattr(0, s) != 0) throw LastError();
|
||||
}
|
||||
saved.CopyTo(raw, 0);
|
||||
Clear(raw, IFlag, BRKINT | ICRNL | INPCK | ISTRIP | IXON);
|
||||
Set(raw, CFlag, CS8);
|
||||
Clear(raw, LFlag, ECHO | ICANON | IEXTEN | (signals ? 0 : ISIG));
|
||||
raw[CcOffset + VMIN] = 1;
|
||||
raw[CcOffset + VTIME] = 0;
|
||||
ApplyRaw();
|
||||
rawWanted = true;
|
||||
decoder.Reset();
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores the modes saved by <see cref="EnterRaw"/>. Does nothing
|
||||
/// outside raw mode.
|
||||
public void LeaveRaw() {
|
||||
lock (gate) {
|
||||
if (!rawWanted) return;
|
||||
rawWanted = false;
|
||||
RestoreSaved();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the process as Ctrl-Z does in cooked mode: restores the saved
|
||||
/// modes, and sends SIGTSTP to the process group. When the process
|
||||
/// continues, raw mode is set again.
|
||||
public void Suspend() {
|
||||
lock (gate) {
|
||||
if (rawSet) RestoreSaved();
|
||||
}
|
||||
kill(0, SIGTSTP);
|
||||
// SIGTSTP may be ignored or cancelled (a shell with job control).
|
||||
// Then nothing stopped, and raw mode comes back here.
|
||||
lock (gate) {
|
||||
if (rawWanted && !rawSet) ApplyRaw();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the next event.
|
||||
/// <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>Cancelling the token raises
|
||||
/// <see cref="OperationCanceledException"/>. Bytes read before that stay
|
||||
/// for the next read.</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.");
|
||||
}
|
||||
// poll blocks the thread, so the read runs on a thread of its own.
|
||||
return Task.Factory.StartNew(() => {
|
||||
try {
|
||||
using var wake = cancel.Register(Wake);
|
||||
return Read(timeoutMs, cancel);
|
||||
} finally {
|
||||
Volatile.Write(ref reading, 0);
|
||||
}
|
||||
// Not the caller's token: a task cancelled before it starts would
|
||||
// never clear `reading`.
|
||||
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
||||
}
|
||||
|
||||
private TermEvent Read(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);
|
||||
}
|
||||
|
||||
fds[0] = new pollfd { fd = 0, events = POLLIN };
|
||||
fds[1] = new pollfd { fd = wakeRead, events = POLLIN };
|
||||
int n = poll(fds, 2, wait);
|
||||
if (n < 0) {
|
||||
if (Marshal.GetLastPInvokeError() == EINTR) continue;
|
||||
throw LastError();
|
||||
}
|
||||
if ((fds[1].revents & POLLIN) != 0) DrainWake();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnResize(PosixSignalContext ctx) {
|
||||
Interlocked.Exchange(ref resized, 1);
|
||||
Wake();
|
||||
}
|
||||
|
||||
private void OnContinue(PosixSignalContext ctx) {
|
||||
lock (gate) {
|
||||
if (!rawWanted) return;
|
||||
ctx.Cancel = true;
|
||||
// In the background, setting modes would stop the process with
|
||||
// SIGTTOU. The next SIGCONT, when it is in the foreground, sets
|
||||
// them.
|
||||
if (tcgetpgrp(0) == getpgrp()) ApplyRaw();
|
||||
}
|
||||
Interlocked.Exchange(ref resized, 1);
|
||||
Wake();
|
||||
}
|
||||
|
||||
private void OnStop(PosixSignalContext ctx) {
|
||||
lock (gate) {
|
||||
if (!rawSet) return;
|
||||
ctx.Cancel = true;
|
||||
RestoreSaved();
|
||||
}
|
||||
// SIGTSTP is cancelled here, so stop with SIGSTOP. A shell reports
|
||||
// both as stopped.
|
||||
kill(Environment.ProcessId, SIGSTOP);
|
||||
}
|
||||
|
||||
private void OnEnd(PosixSignalContext ctx) => RestoreAtExit();
|
||||
|
||||
private void RestoreAtExit() {
|
||||
lock (gate) {
|
||||
if (rawSet) RestoreSaved();
|
||||
}
|
||||
}
|
||||
|
||||
// The callers hold the gate.
|
||||
private void ApplyRaw() {
|
||||
fixed (byte* r = raw) {
|
||||
if (tcsetattr(0, TCSADRAIN, r) != 0) throw LastError();
|
||||
}
|
||||
rawSet = true;
|
||||
}
|
||||
|
||||
private void RestoreSaved() {
|
||||
fixed (byte* s = saved) {
|
||||
tcsetattr(0, TCSADRAIN, s);
|
||||
}
|
||||
rawSet = false;
|
||||
}
|
||||
|
||||
private void Wake() {
|
||||
byte one = 1;
|
||||
write(wakeWrite, &one, 1);
|
||||
}
|
||||
|
||||
private void DrainWake() {
|
||||
byte* b = stackalloc byte[64];
|
||||
while (read(wakeRead, b, 64) > 0) { }
|
||||
}
|
||||
|
||||
private static void Clear(byte[] t, int offset, uint bits) =>
|
||||
BitConverter.TryWriteBytes(t.AsSpan(offset), BitConverter.ToUInt32(t, offset) & ~bits);
|
||||
|
||||
private static void Set(byte[] t, int offset, uint bits) =>
|
||||
BitConverter.TryWriteBytes(t.AsSpan(offset), BitConverter.ToUInt32(t, offset) | bits);
|
||||
|
||||
private static Win32Exception LastError() => LastError(Marshal.GetLastPInvokeError());
|
||||
|
||||
private static Win32Exception LastError(int errno) => new(errno);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct pollfd {
|
||||
public int fd;
|
||||
public short events;
|
||||
public short revents;
|
||||
}
|
||||
|
||||
[DllImport("libc", SetLastError = true)] private static extern int isatty(int fd);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int tcgetattr(int fd, byte* termios);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int tcsetattr(int fd, int when, byte* termios);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int tcgetpgrp(int fd);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int getpgrp();
|
||||
[DllImport("libc", SetLastError = true)] private static extern int ioctl(int fd, ulong request, ushort* arg);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int pipe2(int* fds, int flags);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int poll(pollfd* fds, ulong n, int timeout);
|
||||
[DllImport("libc", SetLastError = true)] private static extern long read(int fd, byte* buffer, long count);
|
||||
[DllImport("libc", SetLastError = true)] private static extern long write(int fd, byte* buffer, long count);
|
||||
[DllImport("libc", SetLastError = true)] private static extern int kill(int pid, int signal);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue