From fe42387a4ca450c391b31eba4a3693a15c29ef7cde7476c16d699be34dce5265 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Bj=C3=B6rnstam?= Date: Mon, 30 Nov 2026 20:31:29 +0100 Subject: [PATCH] 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 --- .gitignore | 8 + AGENTS.md | 26 +++ LICENSE | 373 +++++++++++++++++++++++++++++++++++++++++ examples/keys.bjo | 20 +++ glue/Keys.cs | 301 +++++++++++++++++++++++++++++++++ glue/Tty.cs | 342 ++++++++++++++++++++++++++++++++++++++ manifest.bjodat | 11 ++ packages.lock.json | 10 ++ plan.org | 94 +++++++++++ src/terminal.bjo | 405 +++++++++++++++++++++++++++++++++++++++++++++ tests/keys.bjo | 95 +++++++++++ tests/terminal.bjo | 145 ++++++++++++++++ 12 files changed, 1830 insertions(+) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 LICENSE create mode 100644 examples/keys.bjo create mode 100644 glue/Keys.cs create mode 100644 glue/Tty.cs create mode 100644 manifest.bjodat create mode 100644 packages.lock.json create mode 100644 plan.org create mode 100644 src/terminal.bjo create mode 100644 tests/keys.bjo create mode 100644 tests/terminal.bjo diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca84534 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.bjo/ +publish/ +*.dll +*.exe +*.pdb +*.bjobuild +*.runtimeconfig.json +*.deps.json diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8dd362a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,26 @@ +## Comment Style + +Write plain, direct engineering comments. Do **not** imitate the overly literary +or cryptic comment style found in some older files in this repo. + +- **Use standard terms:** "returns" (not "answers"), "rejects/errors" (not "refuses"), + "resolves/looks up" (not "names/spells"), "traverses" (not "walks"). +- **Name concepts directly:** Say "trait constraints" instead of "what the code around it asks". +- **Use normal sentences with verbs:** Start docstrings with a verb ("Checks whether...", + "Returns...", "Resolves...") rather than cryptic noun fragments. +- **Keep it short:** 1–2 sentences for most functions. Only add more to explain a + non-obvious invariant or edge case. Skip comments that just restate the code. + +Examples: +- Bad: `/// Several answers as one: refused if any refuses, held if all hold, and otherwise not known yet.` +- Good: `/// Combines tri-state results: Some false if any failed, Some true if all passed, else None.` + +- Bad: `/// What a file is called, worked out from where it is.` +- Good: `/// Module identity derived from a file's path on disk.` + +## This package + +- `bjo build` builds the library and the glue in `glue/`. +- `bjo test` runs `tests/keys.bjo` (the decoder, from bytes) and + `tests/terminal.bjo` (raw mode on a pseudo-terminal, under `script`). +- `plan.org` has the decisions and the phases. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d22367a --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + 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 https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/examples/keys.bjo b/examples/keys.bjo new file mode 100644 index 0000000..48992cf --- /dev/null +++ b/examples/keys.bjo @@ -0,0 +1,20 @@ +;; Prints each key, paste and resize until Ctrl-D. +;; +;; bjo run examples/keys.bjo + +(import (std prelude)) +(import (bjoterm terminal)) + +(defun (main args) + (def (Ok term) (terminal-open) :leave ((Err e) (println (terminal-error-message e)) 1)) + (print bracketed-paste-on) + (println (styled "Press keys, paste text or resize the window. Ctrl-D ends." [StyleBold])) + (with-raw-mode term + (fun () + (let go () + (match (read-event term) + ((TermKey (KeyChar #\d) (Mods (ctrl? #t))) unit) + (TermEnd unit) + (ev (println (event->string ev)) (go)))))) + (print bracketed-paste-off) + 0) diff --git a/glue/Keys.cs b/glue/Keys.cs new file mode 100644 index 0000000..f5b8a71 --- /dev/null +++ b/glue/Keys.cs @@ -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; + +/// +/// One event read from the terminal, as flat fields. (bjoterm terminal) +/// maps it to its union. +/// +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 key, the number of an + /// key, or the columns of a resize. + public int Value { get; } + + /// The rows of a resize. + public int Value2 { get; } + + /// , and . + public int Mods { get; } + + /// The text of a paste, or the bytes of an unknown sequence (ESC as + /// "^["). + public string Text { get; } +} + +/// +/// Decodes terminal input into events. +/// +/// +/// +/// adds bytes; returns the next +/// complete event, or null when the bytes so far are a partial one. +/// Next(final: true) 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 . +/// The reader calls it when no more bytes came within the sequence +/// timeout. +/// Keys: CSI and SS3 sequences of xterm, with the modifier parameter +/// (ESC [ 1 ; 5 A is Ctrl-Up), the ~ keys, F1 to F12, and +/// Shift-Tab (ESC [ Z). +/// Bracketed paste: the bytes between ESC [ 200 ~ and +/// ESC [ 201 ~ are one paste, decoded as UTF-8 with CR LF and CR +/// made LF. A paste is not cut by the timeout. +/// +/// +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 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(); + 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(); + } +} diff --git a/glue/Tty.cs b/glue/Tty.cs new file mode 100644 index 0000000..784b532 --- /dev/null +++ b/glue/Tty.cs @@ -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; + +/// +/// The terminal of this process. +/// +/// +/// +/// One per process: returns the same object each +/// time. Linux only. +/// Modes: saves the current modes and sets raw +/// mode; restores the saved modes. They are also +/// restored at process exit. +/// 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. +/// 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. +/// One read at a time. A second concurrent +/// raises . +/// +/// +[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 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 + /// on a system other than Linux, and 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 + /// , Ctrl-C, Ctrl-Z and Ctrl-\ still send + /// their signals. Raises 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 . 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. + /// + /// below 0 waits for ever. A timeout + /// returns an event of kind . + /// The rest of a sequence is waited for + /// ; then what came is decoded alone (a + /// lone ESC is the Escape key). + /// Cancelling the token raises + /// . Bytes read before that stay + /// for the next read. + /// + public Task 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); +} diff --git a/manifest.bjodat b/manifest.bjodat new file mode 100644 index 0000000..c570a37 --- /dev/null +++ b/manifest.bjodat @@ -0,0 +1,11 @@ +(package + (name (bjoterm)) + (version "0.1.0") + (description "The terminal for Bjolang programs: raw mode, key events and escape sequences. Linux.") + (license "MPL-2.0") + + ;; Termios, poll and the key decoder. See glue/Tty.cs and glue/Keys.cs. + (csharp "glue") + + ;; A library: there is no src/main.bjo. + ) diff --git a/packages.lock.json b/packages.lock.json new file mode 100644 index 0000000..306f5d4 --- /dev/null +++ b/packages.lock.json @@ -0,0 +1,10 @@ +{ + "version": 1, + "dependencies": { + "net11.0": { + "bjoglue.bjoterm": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/plan.org b/plan.org new file mode 100644 index 0000000..6f1a091 --- /dev/null +++ b/plan.org @@ -0,0 +1,94 @@ +#+TITLE: bjoterm: the terminal for Bjolang programs + +* Goal + +A package for programs that use the terminal directly: a line editor for +a shell or a REPL, and full-screen programs. It owns the terminal while it +is in raw mode, and gives it back as it found it. + +*Phase 1 implemented (2026-11-30). Where the code differs from the text below:* +- Ctrl-J (byte 10) is ~(KeyChar #\j)~ with ~ctrl?~, not ~KeyEnter~: a + REPL can bind it to a new line. Byte 8 is ~KeyBackspace~ with ~ctrl?~. +- Bracketed paste is the program's to turn on and off: leaving raw mode + writes nothing. +- SIGTERM, SIGHUP and SIGQUIT end the process with no ~finally~ and no + ~ProcessExit~ (see ~MainExit~), so the glue restores the modes in a + handler of its own, and does not cancel the signal. +- SIGTSTP in raw mode with ~#:signals? #t~ restores the modes and stops + the process with SIGSTOP. +- ~decode-input~ is exported: the decoder on bytes, for tests and recorded + input. +- ~read-event~ is ~#:sync~. Each read polls on a thread of its own + (~LongRunning~). An async form for fibers is for phase 2. +- Under ~script~, a child that stops makes ~script~ stop itself; the test + of stop and continue sends SIGCONT to both. + +* Decisions + +1. *Linux only, for now.* The termios layout, ~TIOCGWINSZ~ and the flag + values are those of Linux (x86-64 and arm64 have the same ones). macOS + has another layout; it is a later phase. On another system + ~terminal-open~ returns ~(Err TerminalUnsupported)~. +2. *stdin and stdout must both be terminals.* Modes are set on fd 0, keys + are read from fd 0, and the size is read from fd 1. +3. *Keys are read from fd 0 directly*, with ~poll~ and ~read~, not through + the standard input port: the port cannot wait with a timeout, and a lone + ESC is told from the start of a sequence by a timeout (50 ms). Input that + the port has already buffered is not seen. +4. *.NET's ~Console~ is not used.* ~Console.ReadKey~ and ~Console.In~ make + .NET set its own terminal modes, and set them again at SIGCONT and when a + child process ends. The runtime's standard ports never touch ~Console.In~, + so as long as a program does not, the modes are ours. +5. *Raw mode is scoped.* ~(with-raw-mode term thunk)~ saves the modes, sets + raw mode, runs the thunk, and restores the saved modes in a ~finally~: + also on an exception, on Ctrl-C or SIGTERM through ~MainExit~, and at + process exit (~ProcessExit~). Nested calls are an error. +6. *What raw mode changes*: + - off: ~ECHO~, ~ICANON~, ~IEXTEN~, ~ISIG~, ~IXON~, ~ICRNL~, ~BRKINT~, + ~INPCK~, ~ISTRIP~; ~CS8~ on; ~VMIN~ 1, ~VTIME~ 0. + - ~OPOST~ stays on, so ~println~ still starts the next line at column 0. + - ~#:signals? #t~ keeps ~ISIG~: Ctrl-C, Ctrl-Z and Ctrl-\ then send + their signals, as in cooked mode. +7. *SIGCONT while raw*: the raw modes are set again, and the next event is + ~Resized~, so the program draws its screen again. The registration + cancels .NET's own SIGCONT handling, which would set .NET's modes. +8. *Ctrl-Z in raw mode is a key.* ~terminal-suspend~ restores the saved + modes, sends SIGTSTP to our process group, and sets raw mode again when + the process continues. +9. *Events* are one union: + - ~(TermKey key mods)~: ~mods~ is a ~Mods~ record of ~shift?~, ~alt?~, + ~ctrl?~. + - ~(TermPaste text)~: bracketed paste, when it is on. + - ~(TermResized cols rows)~: SIGWINCH, and after SIGCONT. + - ~TermEnd~: end of input (the terminal hung up). + Keys are ~(KeyChar c)~, ~KeyEnter~, ~KeyTab~, ~KeyBackspace~, + ~KeyEscape~, the arrows, ~KeyHome~, ~KeyEnd~, ~KeyPageUp~, + ~KeyPageDown~, ~KeyInsert~, ~KeyDelete~, ~(KeyF n)~, and + ~(KeyUnknown text)~ for a sequence the decoder does not know. Names carry + a prefix, so that a program can import the module without a prefix of + its own. +10. *Ctrl and a letter* is ~(KeyChar #\a)~ with ~ctrl?~. Tab, Enter + (13 and 10), Backspace (127 and 8) and Escape are their own keys. + ESC before a key is Alt. +11. *The decoder is C# glue*, as the read loop is. It returns a flat + record (kind, code, mods, text), and Bjolang maps it to the union, as + ~(std run)~ maps ~JobStatus~. Tests feed it bytes directly. +12. *Output is strings.* The module returns escape sequences as strings, + and the program writes them to stdout. ~terminal-flush~ flushes the + standard output port. Nothing is written behind the program's back, + except that leaving raw mode turns off what the module turned on + (bracketed paste). + +* Phases + +- *1. The terminal.* Package, glue, ~terminal-open~, ~with-raw-mode~, + ~terminal-size~, ~read-event~ with and without a timeout, the decoder + (CSI and SS3 keys with modifiers, Alt, UTF-8, bracketed paste), + ~terminal-suspend~, SIGWINCH and SIGCONT, escape sequences for the cursor, + clearing, the alternate screen and styles. Tests: the decoder from bytes; + raw mode, a key, a resize and restore under ~script~. +- *2. The line editor.* A prompt, editing keys (Emacs set), a history, + completion through a function the program gives, a multi-line buffer + for a REPL, and wide characters (East Asian width, combining marks). +- *3. Later.* macOS, mouse events, the kitty keyboard protocol, a screen + buffer that writes only what changed. diff --git a/src/terminal.bjo b/src/terminal.bjo new file mode 100644 index 0000000..7ac7a93 --- /dev/null +++ b/src/terminal.bjo @@ -0,0 +1,405 @@ +;; 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/. + +;; (bjoterm terminal): raw mode, key events and escape sequences. +;; +;; (def (Ok term) (terminal-open) :leave-with 1) +;; (with-raw-mode term +;; (fun () +;; (let go () +;; (match (read-event term) +;; ((TermKey (KeyChar #\q) _) unit) +;; (ev (println (event->string ev)) (go)))))) +;; +;; - Linux only. Standard input and standard output must be terminals. +;; - Keys are read from fd 0 directly, not through `current-input-port`. +;; Input that the port has buffered already is not seen. +;; - Do not read keys through .NET's `Console` in a program that uses this +;; module: .NET then sets its own terminal modes. +;; - Output is strings: write them to standard output. `read-event` flushes +;; `current-output-port` before it waits. +;; - See glue/Tty.cs and glue/Keys.cs for the C# side. + +(import (std prelude)) + +(export + Terminal TerminalError Key Mods TermEvent Color Style + terminal-open terminal-error-message with-raw-mode terminal-raw? + terminal-size terminal-suspend + read-event read-event/timeout + no-mods key->string event->string decode-input + ;; Escape sequences. + cursor-to cursor-up cursor-down cursor-forward cursor-back cursor-column + cursor-save cursor-restore cursor-hide cursor-show + clear-screen clear-below clear-line clear-to-line-end + alt-screen-on alt-screen-off bracketed-paste-on bracketed-paste-off + styled style-start style-reset) + +(import/class + (Tty (: Bjoterm.Tty)) + (NEvent (: Bjoterm.TermEvent))) + +(import/extern + (tty-open (: Bjoterm.Tty.Open (-> Tty) + #:exceptions (System.PlatformNotSupportedException System.IO.IOException + System.ComponentModel.Win32Exception) #:no-raise)) + (tty-size (: Bjoterm.Tty.Size (-> Tty (Array int)) #:no-raise)) + (tty-raw? (: Bjoterm.Tty.IsRaw (-> Tty bool) #:get #:no-raise)) + (enter-raw (: Bjoterm.Tty.EnterRaw (-> Tty bool void) + #:raises (System.InvalidOperationException System.ComponentModel.Win32Exception))) + (leave-raw (: Bjoterm.Tty.LeaveRaw (-> Tty void) #:no-raise)) + (tty-suspend (: Bjoterm.Tty.Suspend (-> Tty void) #:no-raise)) + (tty-read (: Bjoterm.Tty.ReadAsync (-> Tty int NEvent) #:async + #:raises (System.InvalidOperationException System.ComponentModel.Win32Exception))) + (decode-all (: Bjoterm.Decoder.DecodeAll (-> (Array byte) (Array NEvent)) #:no-raise)) + (ev-kind (: Bjoterm.TermEvent.Kind (-> NEvent int) #:get #:no-raise)) + (ev-key (: Bjoterm.TermEvent.Key (-> NEvent int) #:get #:no-raise)) + (ev-value (: Bjoterm.TermEvent.Value (-> NEvent int) #:get #:no-raise)) + (ev-value2 (: Bjoterm.TermEvent.Value2 (-> NEvent int) #:get #:no-raise)) + (ev-mods (: Bjoterm.TermEvent.Mods (-> NEvent int) #:get #:no-raise)) + (ev-text (: Bjoterm.TermEvent.Text (-> NEvent string) #:get #:no-raise))) + +;; =========================================================================== +;; Types +;; =========================================================================== + +;; The terminal of this process. +(type (: Terminal #:opaque (Record (: tty Tty)))) + +;; Why `terminal-open` failed. +;; - `TerminalUnsupported`: the system is not Linux. +;; - `NotATerminal`: standard input or standard output is not a terminal. +(type (: TerminalError (Union TerminalUnsupported (: NotATerminal string)))) + +;; The modifier keys held with a key. +(type (: Mods (Record (: shift? bool) (: alt? bool) (: ctrl? bool)))) + +;; A key. +;; - `KeyChar`: a character. Ctrl and a letter is the letter with `ctrl?`: +;; Ctrl-A is `(KeyChar #\a)`. Ctrl-J (a line feed) is `(KeyChar #\j)`, not +;; `KeyEnter`. +;; - `KeyBackspace` with `ctrl?` is byte 8, which is Ctrl-H and, on some +;; terminals, Ctrl-Backspace. +;; - `KeyF`: F1 to F12. +;; - `KeyUnknown`: a sequence the decoder does not know, with ESC shown as +;; "^[". +(type (: Key (Union (: KeyChar char) KeyEnter KeyTab KeyBackspace KeyEscape + KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd + KeyPageUp KeyPageDown KeyInsert KeyDelete + (: KeyF int) (: KeyUnknown string)))) + +;; An event read from the terminal. +;; - `TermKey`: a key and its modifiers. +;; - `TermPaste`: text pasted while bracketed paste is on, with line ends +;; made "\n". +;; - `TermResized`: the new size, columns then rows. Also after the program +;; was stopped and continued: draw the screen again. +;; - `TermEnd`: end of input; the terminal hung up. +(type (: TermEvent (Union (: TermKey Key Mods) (: TermPaste string) + (: TermResized int int) TermEnd))) + +;; A color. +;; - `Ansi`: 0 to 7 are black, red, green, yellow, blue, magenta, cyan and +;; white; 8 to 15 are their bright forms. +;; - `Palette`: 0 to 255, of the 256-color palette. +;; - `Rgb`: red, green and blue, 0 to 255 each. +(type (: Color (Union (: Ansi int) (: Palette int) (: Rgb int int int)))) + +;; A text style. +(type (: Style (Union StyleBold StyleFaint StyleItalic StyleUnderline StyleReverse + (: StyleFg Color) (: StyleBg Color)))) + +;; =========================================================================== +;; The terminal +;; =========================================================================== + +;; Opens the terminal of this process. Returns the same terminal each time. +(: (-> (Result TerminalError Terminal))) +(defun (terminal-open) + (match (tty-open) + ((Ok tty) (Ok (Terminal (tty tty)))) + ((Err e) + (match e + ((:is System.PlatformNotSupportedException) (Err TerminalUnsupported)) + (_ (Err (NotATerminal (.-Message e)))))))) + +(: (-> TerminalError string)) +(defun (terminal-error-message e) + (match e + (TerminalUnsupported "bjoterm supports only Linux") + ((NotATerminal why) why))) + +;; Runs `body` in raw mode, and restores the terminal's modes after it. +;; - Raw mode: no echo, no line editing, each byte is read as it comes. +;; Output is unchanged: "\n" still starts a line at column 0. +;; - `#:signals? #t` keeps Ctrl-C, Ctrl-Z and Ctrl-\ as signals. By default +;; they are keys. +;; - The modes are restored when `body` returns or raises, when main is +;; cancelled (Ctrl-C with `#:signals? #t`), at process exit, and at +;; SIGTERM, SIGHUP and SIGQUIT, which end the process. +;; - When the process is stopped and continued, raw mode is set again. +;; - Raises InvalidOperationException when the terminal is in raw mode +;; already. +(: (-> Terminal (-> %a) (#:signals? bool) %a)) +(defun (with-raw-mode term body #:signals? #f) + (def tty (record-ref term tty)) + (enter-raw tty signals?) + (try (body) + #:finally (leave-raw tty))) + +;; Whether the terminal is in raw mode. +(: (-> Terminal bool)) +(defun (terminal-raw? term) + (tty-raw? (record-ref term tty))) + +;; The size: columns, then rows. 80 by 24 when the terminal does not say. +(: (-> Terminal (Tuple int int))) +(defun (terminal-size term) + (def size (tty-size (record-ref term tty))) + (Tuple (array-ref size 0) (array-ref size 1))) + +;; Stops the program as Ctrl-Z does in a shell. For a program in raw mode +;; that reads Ctrl-Z as a key. +;; - The modes from before raw mode are restored while it is stopped, and +;; raw mode is set again when it continues. The next event is then +;; `TermResized`. +;; - Under a shell without job control, nothing stops. +(: (-> Terminal void)) +(defun (terminal-suspend term) + (flush-port (parameter-ref current-output-port)) + (tty-suspend (record-ref term tty))) + +;; =========================================================================== +;; Events +;; =========================================================================== + +;; Waits for the next event. Flushes `current-output-port` first. +(: (-> Terminal TermEvent) #:sync) +(defun (read-event term) + (let go () + (match (read-event/timeout term -1) + ((Some ev) ev) + (None (go))))) + +;; Waits at most `ms` milliseconds for the next event; below 0, for ever. +;; Returns None at the timeout. Flushes `current-output-port` first. +(: (-> Terminal int (Option TermEvent)) #:sync) +(defun (read-event/timeout term ms) + (flush-port (parameter-ref current-output-port)) + (match (sync/blocking (promise-join (bjo (reading (record-ref term tty) ms)))) + ((Err e) (raise e)) + ((Ok ev) (event-of ev)))) + +(: (-> Tty int NEvent)) +(defbjo (reading tty ms) + (tty-read tty ms)) + +(: (-> NEvent (Option TermEvent))) +(defun (event-of ev) + (match (ev-kind ev) + (0 None) + (1 (Some (TermKey (key-of ev) (mods-of (ev-mods ev))))) + (2 (Some (TermPaste (ev-text ev)))) + (3 (Some (TermResized (ev-value ev) (ev-value2 ev)))) + (_ (Some TermEnd)))) + +(: (-> NEvent Key)) +(defun (key-of ev) + (match (ev-key ev) + (0 (KeyChar (int->char (ev-value ev)))) + (1 KeyEnter) + (2 KeyTab) + (3 KeyBackspace) + (4 KeyEscape) + (5 KeyUp) + (6 KeyDown) + (7 KeyLeft) + (8 KeyRight) + (9 KeyHome) + (10 KeyEnd) + (11 KeyPageUp) + (12 KeyPageDown) + (13 KeyInsert) + (14 KeyDelete) + (15 (KeyF (ev-value ev))) + (_ (KeyUnknown (ev-text ev))))) + +(: (-> int Mods)) +(defun (mods-of bits) + (Mods (shift? (not (= 0 (bitwise-and bits 1)))) + (alt? (not (= 0 (bitwise-and bits 2)))) + (ctrl? (not (= 0 (bitwise-and bits 4)))))) + +;; Decodes bytes of terminal input into events, as `read-event` would +;; return them. A partial event at the end is decoded as it is: a lone ESC +;; is `KeyEscape`. For tests, and for input recorded earlier. +(: (-> (Array byte) (Vec TermEvent))) +(defun (decode-input bytes) + (loop (:for ev (decode-all bytes)) + (:acc v (vecing (match (event-of ev) + ((Some e) e) + (None TermEnd)))))) + +;; No modifier keys. +(: Mods) +(def no-mods (Mods (shift? #f) (alt? #f) (ctrl? #f))) + +;; A key as text, such as "C-a", "M-" or "S-": modifiers as +;; Emacs writes them (C- Ctrl, M- Alt, S- Shift), and names in brackets. +(: (-> Key Mods string)) +(defun (key->string key mods) + (def name + (match key + ((KeyChar #\space) "") + ((KeyChar c) (char->string c)) + (KeyEnter "") + (KeyTab "") + (KeyBackspace "") + (KeyEscape "") + (KeyUp "") + (KeyDown "") + (KeyLeft "") + (KeyRight "") + (KeyHome "") + (KeyEnd "") + (KeyPageUp "") + (KeyPageDown "") + (KeyInsert "") + (KeyDelete "") + ((KeyF n) (str "string n) ">")) + ((KeyUnknown text) (str "")))) + (str (if (record-ref mods ctrl?) "C-" "") + (if (record-ref mods alt?) "M-" "") + (if (record-ref mods shift?) "S-" "") + name)) + +;; An event as text, for logs and tests. +(: (-> TermEvent string)) +(defun (event->string ev) + (match ev + ((TermKey key mods) (str "key " (key->string key mods))) + ((TermPaste text) (str "paste " (written text))) + ((TermResized cols rows) (str "resized " (int->string cols) "x" (int->string rows))) + (TermEnd "end"))) + +;; =========================================================================== +;; Escape sequences +;; =========================================================================== +;; Each returns a string to write to standard output. Columns and rows +;; count from 0. + +(: string) +(def esc "\u{1B}") + +(: (-> string string)) +(defun (csi body) (str esc "[" body)) + +;; Moves the cursor to a column and a row, from 0. +(: (-> int int string)) +(defun (cursor-to col row) + (csi (str (int->string (+ row 1)) ";" (int->string (+ col 1)) "H"))) + +;; Moves the cursor to a column of its row, from 0. +(: (-> int string)) +(defun (cursor-column col) + (csi (str (int->string (+ col 1)) "G"))) + +(: (-> int string string)) +(defun (cursor-move n code) + (if (<= n 0) "" (csi (str (int->string n) code)))) + +;; Moves the cursor `n` rows up. Nothing for 0. +(: (-> int string)) +(defun (cursor-up n) (cursor-move n "A")) + +(: (-> int string)) +(defun (cursor-down n) (cursor-move n "B")) + +(: (-> int string)) +(defun (cursor-forward n) (cursor-move n "C")) + +(: (-> int string)) +(defun (cursor-back n) (cursor-move n "D")) + +(: string) +(def cursor-save (str esc "7")) + +(: string) +(def cursor-restore (str esc "8")) + +(: string) +(def cursor-hide (csi "?25l")) + +(: string) +(def cursor-show (csi "?25h")) + +;; Clears the screen. The cursor does not move. +(: string) +(def clear-screen (csi "2J")) + +;; Clears from the cursor to the end of the screen. +(: string) +(def clear-below (csi "J")) + +;; Clears the cursor's row. +(: string) +(def clear-line (csi "2K")) + +;; Clears from the cursor to the end of its row. +(: string) +(def clear-to-line-end (csi "K")) + +;; The alternate screen, which full-screen programs use. Leaving it shows +;; the screen as it was. +(: string) +(def alt-screen-on (csi "?1049h")) + +(: string) +(def alt-screen-off (csi "?1049l")) + +;; Bracketed paste: the terminal marks pasted text, and `read-event` +;; returns it as one `TermPaste`. Turn it off before the program ends. +(: string) +(def bracketed-paste-on (csi "?2004h")) + +(: string) +(def bracketed-paste-off (csi "?2004l")) + +(: (-> int Color string)) +(defun (color-code base c) + (match c + ((Ansi n) (if (< n 8) + (int->string (+ base n)) + (int->string (+ base 60 (- n 8))))) + ((Palette n) (str (int->string (+ base 8)) ";5;" (int->string n))) + ((Rgb r g b) (str (int->string (+ base 8)) ";2;" (int->string r) ";" (int->string g) ";" (int->string b))))) + +(: (-> Style string)) +(defun (style-code s) + (match s + (StyleBold "1") + (StyleFaint "2") + (StyleItalic "3") + (StyleUnderline "4") + (StyleReverse "7") + ((StyleFg c) (color-code 30 c)) + ((StyleBg c) (color-code 40 c)))) + +;; Starts the styles. Nothing for no styles. +(: (-> (Vec Style) string)) +(defun (style-start styles) + (if (= (vec-length styles) 0) + "" + (csi (str (string-join (vec-map style-code styles) ";") "m")))) + +;; Ends every style. +(: string) +(def style-reset (csi "0m")) + +;; `text` in the styles, and the styles ended after it. +(: (-> string (Vec Style) string)) +(defun (styled text styles) + (if (= (vec-length styles) 0) + text + (str (style-start styles) text style-reset))) diff --git a/tests/keys.bjo b/tests/keys.bjo new file mode 100644 index 0000000..fa24fac --- /dev/null +++ b/tests/keys.bjo @@ -0,0 +1,95 @@ +;; 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 key decoder: bytes of terminal input in, events out. +;; +;; bjo test tests/keys.bjo + +(import (std prelude)) +(import (std simpletest)) +(import (bjoterm terminal)) + +(: (-> (Vec int) (Array byte))) +(defun (bytes-of xs) + (def (: out (Array byte)) (make-array (vec-length xs))) + (loop (:for i (range 0 (vec-length xs))) + (:do (array-set! out i (cast byte (vec-ref xs i))))) + out) + +(: (-> string (Array byte))) +(defun (utf8 s) + (bytestring->bytes (string->bytestring s))) + +(: (-> (Array byte) string)) +(defun (decoded bytes) + (string-join (vec-map event->string (decode-input bytes)) ", ")) + +(: (-> string string string void)) +(defun (expect-keys name input expected) + (expect name (decoded (utf8 input)) expected)) + +(: string) +(def esc "\u{1B}") + +(defun (main args) + ;; Plain keys and control bytes. + (expect-keys "a letter" "a" "key a") + (expect-keys "Ctrl and a letter" "\u{1}" "key C-a") + (expect-keys "CR is Enter" "\r" "key ") + (expect-keys "LF is Ctrl-J" "\n" "key C-j") + (expect-keys "Tab" "\t" "key ") + (expect-keys "DEL is Backspace" "\u{7F}" "key ") + (expect-keys "BS is Ctrl-Backspace" "\u{8}" "key C-") + (expect "NUL is Ctrl-Space" (decoded (bytes-of [0])) "key C-") + (expect-keys "Ctrl-\\" "\u{1C}" "key C-\\") + (expect-keys "several keys" "ab" "key a, key b") + + ;; Escape and Alt. + (expect-keys "a lone ESC is Escape" esc "key ") + (expect-keys "ESC and a key is Alt" (str esc "x") "key M-x") + (expect-keys "ESC and Ctrl-A" (str esc "\u{1}") "key C-M-a") + (expect-keys "ESC ESC is Alt-Escape" (str esc esc) "key M-") + (expect-keys "ESC [ alone is Alt-[" (str esc "[") "key M-[") + + ;; CSI keys. + (expect-keys "arrows" (str esc "[A" esc "[B" esc "[C" esc "[D") + "key , key , key , key ") + (expect-keys "Home and End" (str esc "[H" esc "[F") "key , key ") + (expect-keys "Ctrl-Up" (str esc "[1;5A") "key C-") + (expect-keys "Alt-Left" (str esc "[1;3D") "key M-") + (expect-keys "Shift-Right" (str esc "[1;2C") "key S-") + (expect-keys "Ctrl-Shift-Alt-Up" (str esc "[1;8A") "key C-M-S-") + (expect-keys "the ~ keys" (str esc "[2~" esc "[3~" esc "[5~" esc "[6~" esc "[1~" esc "[4~") + "key , key , key , key , key , key ") + (expect-keys "Ctrl-PageUp" (str esc "[5;5~") "key C-") + (expect-keys "F5 to F12" (str esc "[15~" esc "[17~" esc "[21~" esc "[23~" esc "[24~") + "key , key , key , key , key ") + (expect-keys "Shift-Tab" (str esc "[Z") "key S-") + (expect-keys "Alt-Up as ESC ESC [ A" (str esc esc "[A") "key M-") + (expect-keys "Shift-F1 as CSI" (str esc "[1;2P") "key S-") + (expect-keys "an unknown sequence" (str esc "[99x") "key ") + (expect-keys "a cut sequence at the end" (str esc "[1;5") "key ") + + ;; SS3 keys. + (expect-keys "F1 to F4" (str esc "OP" esc "OQ" esc "OR" esc "OS") + "key , key , key , key ") + (expect-keys "application cursor keys" (str esc "OA" esc "OD") "key , key ") + (expect-keys "ESC O alone is Alt-O" (str esc "O") "key M-O") + + ;; UTF-8. + (expect-keys "two bytes" "é" "key é") + (expect-keys "four bytes" "😀" "key 😀") + (expect-keys "letters between keys" (str "å" esc "[A" "ö") "key å, key , key ö") + (expect "a cut character at the end" (decoded (bytes-of [195])) "key \u{FFFD}") + (expect "a byte that starts nothing" (decoded (bytes-of [255 97])) "key \u{FFFD}, key a") + (expect "a cut character before ASCII" (decoded (bytes-of [226 130 97])) "key \u{FFFD}, key a") + + ;; Bracketed paste. + (expect-keys "a paste" (str esc "[200~hello" esc "[201~") "paste \"hello\"") + (expect-keys "a paste makes line ends LF" (str esc "[200~a\r\nb\rc\nd" esc "[201~") + "paste \"a\\nb\\nc\\nd\"") + (expect-keys "keys in a paste are text" (str esc "[200~" esc "[A\u{3}" esc "[201~x") + (str "paste " (written (str esc "[A\u{3}")) ", key x")) + (expect-keys "a paste that does not end" (str esc "[200~abc") "") + (println "keys ok")) diff --git a/tests/terminal.bjo b/tests/terminal.bjo new file mode 100644 index 0000000..0b693d0 --- /dev/null +++ b/tests/terminal.bjo @@ -0,0 +1,145 @@ +;; 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/. + +;; Raw mode, reading events and restoring the modes, on a real terminal. +;; +;; bjo test tests/terminal.bjo +;; +;; The test runs itself again under `script`, which gives the child a +;; pseudo-terminal, and writes keys to it with pauses between them. The +;; parent checks what the child printed. + +(import (std prelude)) +(import (std simpletest)) +(import (std run)) +(import (bjoterm terminal)) + +(import/extern + (command-line (: System.Environment.GetCommandLineArgs (-> (Array string)) #:no-raise))) + +;; ---- the child ------------------------------------------------------------- + +;; The terminal's local modes, from `stty -a`: "icanon" or "-icanon", and +;; the same for echo. +(: (-> string)) +(defun (modes) + (match (run/output '(sh "-c" "stty -a Terminal void)) +(defun (print-events-until-q term) + (let go () + (match (read-event term) + ((TermKey (KeyChar #\q) _) unit) + (ev (println (str "event: " (event->string ev))) + (go))))) + +(: (-> void)) +(defun (child) + (match (terminal-open) + ((Err e) (println (str "open: " (terminal-error-message e)))) + ((Ok term) + (println (str "before: " (modes))) + (with-raw-mode term + (fun () + (println (str "raw: " (modes))) + (println (str "timeout: " (match (read-event/timeout term 100) + (None "none") + ((Some ev) (event->string ev))))) + ;; The size changes, and the kernel sends SIGWINCH. + (ignore (run/status '(sh "-c" "stty cols 100 rows 30 string (read-event term)))) + ;; Stopped and continued: cooked while stopped, raw after, and + ;; the next event asks for a redraw. A child stops this process, + ;; records the modes, and continues it. `script` stops itself when + ;; its child stops, so the child continues `script` too. + (ignore (run/status '(sh "-c" "kill -TSTP $PPID; sleep 0.3; stty -a /tmp/bjoterm-stopped.txt; kill -CONT $PPID $(ps -o ppid= -p $PPID)"))) + (println (str "stopped: " (match (file-read-text "/tmp/bjoterm-stopped.txt") + ((Ok text) (string-trim text)) + ((Err _) "not recorded")))) + (ignore (file-delete "/tmp/bjoterm-stopped.txt")) + (println (str "continued: " (modes))) + (println (str "event: " (event->string (read-event term)))) + (println "ready") + (print-events-until-q term))) + (println (str "after: " (modes))) + (println (str "nested: " (match (try (with-raw-mode term + (fun () (with-raw-mode term (fun () unit)))) + #:catch (System.InvalidOperationException)) + ((Ok _) "no error") + ((Err _) "raises")))) + (println (str "after-nested: " (modes) " " (if (terminal-raw? term) "raw" "not raw")))))) + +;; Raw mode, then `signal` from a child. The parent checks the modes after +;; this process has ended. +(: (-> string bool void)) +(defun (ending-child signal signals?) + (match (terminal-open) + ((Err e) (println (str "open: " (terminal-error-message e)))) + ((Ok term) + (with-raw-mode term + (fun () + (ignore (run/status '(sh "-c" ,(str "kill -" signal " $PPID")))) + (ignore (read-event term)) + (println "not ended")) + #:signals? signals?)))) + +;; ---- the parent ------------------------------------------------------------ + +(: (-> void)) +(defun (parent) + ;; The test is an assembly that `dotnet` runs. + (def self (str "dotnet " (array-ref (command-line) 0))) + ;; The keys come after "ready": `a`, Up, a lone ESC (the reader decides + ;; after its timeout), Ctrl-Up split over two writes, then `q`. + (def keys (str "sleep 2; printf 'a\\033[A'; sleep 0.3; printf '\\033'; sleep 0.3; " + "printf '\\033[1;'; sleep 0.01; printf '5A'; sleep 0.3; printf q; sleep 1")) + (def command (str "(" keys ") | script -qec '" self " child' /dev/null")) + (def out (match (run/output '(sh "-c" ,command)) + ((Ok (Tuple _ text)) (string-replace text "\r" "")) + ((Err e) (run-error-message e)))) + (expect-true "the terminal opens" (not (string-contains? out "open:"))) + (expect-true "cooked before" (string-contains? out "before: icanon echo")) + (expect-true "raw mode turns off line editing and echo" (string-contains? out "raw: -icanon -echo")) + (expect-true "read-event/timeout returns None" (string-contains? out "timeout: none")) + (expect-true "a resize is an event" (string-contains? out "event: resized 100x30")) + (expect-true "stopped in raw mode: cooked while stopped" (string-contains? out "stopped: icanon")) + (expect-true "raw again after SIGCONT" (string-contains? out "continued: -icanon -echo")) + (expect-true "and a redraw event" (string-contains? out "event: resized 100x30\nready")) + (expect-true "a letter" (string-contains? out "event: key a\n")) + (expect-true "an arrow in the same write" (string-contains? out "event: key \n")) + (expect-true "a lone ESC after the timeout" (string-contains? out "event: key \n")) + (expect-true "a sequence split over two writes" (string-contains? out "event: key C-\n")) + (expect-true "the modes come back" (string-contains? out "after: icanon echo")) + (expect-true "nested raw mode raises" (string-contains? out "nested: raises")) + (expect-true "and the modes come back after it" (string-contains? out "after-nested: icanon echo not raw")) + (unless (string-contains? out "after-nested: icanon echo not raw") + (println out)) + + (expect-true "SIGTERM in raw mode restores the modes" + (string-contains? (modes-after self "term") "exit=143 icanon")) + (expect-true "SIGINT in raw mode with #:signals? cancels main, which restores the modes" + (string-contains? (modes-after self "int") "exit=130 icanon"))) + +;; The exit code of the child that ends with `which`, and the terminal's +;; mode after it. +(: (-> string string string)) +(defun (modes-after self which) + (def command (str "sleep 3 | script -qec '" self " " which "; " + "echo exit=$? $(stty -a