Identify VT terminals as DEC's were asked

internal/vt asks an ANSI terminal everything at once (ENQ answerback,
DA1, DA2, XTVERSION, its cell size), with a cursor position report last
so the answers are complete when it comes, and reads them into a name
(XTVERSION, SyncTERM's CTerm, DEC models by DA2 and firmware, tmux,
screen, mintty, rxvt, xterm, VTE, the answerback, the VT class), a VT
level, sixel and color.  A terminal that is not ANSI is asked ESC Z: a
VT52 answers.

What it said changes what the caller gets: a VT without UTF-8 (not a
PC's CP437 BBS terminal) gets line drawing in DEC Special Graphics and
Latin-1 on a VT220 or later; a DEC monochrome terminal gets bold for
color; a VT52 its own escapes (VT52Writer) with its cursor keys ignored.
Sixel now comes from the same answers.  The name shows in the profile,
the log and the API's who (terminal).  A listener's vt = no asks nothing.

Also: the terminal type and rlogin's rate are set under the BBS's lock
(who's online reads them).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-12 07:07:23 +00:00
1 parent 7ce2d8aacb
commit b20533e6ff
19 files changed
+1032 -35

No files matched your search

+2
View File
@@ -53,6 +53,7 @@ What there is:
- private mail: inbox, read, reply, delete
- [SSH](https://github.com/Neo-Desktop/bbs-sec/wiki/SSH): logging in by password or key, the text BBS encrypted
- [Commodore 64s and RIPscrip terminals](https://github.com/Neo-Desktop/bbs-sec/wiki/PETSCII-and-RIP): PETSCII at 40 columns; menus as RIP buttons
- [VT terminals identified](https://github.com/Neo-Desktop/bbs-sec/wiki/Terminal-Identification) (answerback, DA1, DA2, XTVERSION, VT52): DEC line drawing and Latin-1, bold on monochrome VTs, VT52 escapes
- who's online (and how each caller came: ssh, telnet, tn3270, rlogin, modem
with its rate), the user list, system info
- your profile: where you call from, your password, SSH keys, ANSI and UTF-8
@@ -106,6 +107,7 @@ The documentation is in the [wiki](https://github.com/Neo-Desktop/bbs-sec/wiki/)
| [TN3270](https://github.com/Neo-Desktop/bbs-sec/wiki/TN3270) | 3270 terminals, PF keys, 3270 graphics |
| [Sixel graphics](https://github.com/Neo-Desktop/bbs-sec/wiki/Sixel-Graphics) | the logo on sixel terminals |
| [PETSCII and RIP](https://github.com/Neo-Desktop/bbs-sec/wiki/PETSCII-and-RIP) | Commodore 64s and 128s; RIPscrip graphics and buttons |
| [Terminal identification](https://github.com/Neo-Desktop/bbs-sec/wiki/Terminal-Identification) | VT terminals asked what they are: DEC graphics, monochrome, VT52 |
| [Files and FTP](https://github.com/Neo-Desktop/bbs-sec/wiki/Files-and-FTP) | file areas, the FTP (FTPS) server |
| [File transfers](https://github.com/Neo-Desktop/bbs-sec/wiki/File-Transfers) | X/Y/ZMODEM, Kermit, IND$FILE |
| [Doors](https://github.com/Neo-Desktop/bbs-sec/wiki/Doors) | DOS doors in dosemu2 (Docker), Linux doors |
+4
View File
@@ -86,6 +86,10 @@ throttle_time = 600
; petscii = no Commodore 64s and 128s: yes (every caller is one),
; auto (a caller that is not ANSI is asked to press
; DEL: a C64's makes it PETSCII), no
; vt = auto ask terminals what they are (answerback, DA1, DA2,
; XTVERSION; ESC Z for a VT52): DEC line drawing for
; VTs without UTF-8, bold on monochrome VTs, a VT52's
; escapes; no: ask nothing
; rip = auto RIPscrip menus and screens for terminals that answer
; ESC [ ! (BBS terminals; modern ones are not asked),
; yes, no
+2 -1
View File
@@ -13,7 +13,8 @@ each `[listen NAME]` is a port or unix socket:
`socket_group`). Any listener may read a session header first (`header =
yes`), and with `trust_user = yes` take the caller as logged in already: see
[Modem callers](Modem-Callers) (not `ssh`, which logs its callers in itself). `petscii` and `rip` say whether
its callers may be Commodores or RIPscrip terminals: [PETSCII and RIP](PETSCII-and-RIP).
its callers may be Commodores or RIPscrip terminals: [PETSCII and RIP](PETSCII-and-RIP); `vt`
whether terminals are asked what they are: [Terminal identification](Terminal-Identification).
## The sections
+8 -1
View File
@@ -10,6 +10,7 @@
| `internal/sixel` | the sixel encoder |
| `internal/petscii` | the Commodore's character set: translating ANSI and UTF-8 out, keys in |
| `internal/rip` | RIPscrip: MegaNums, commands, menu scenes |
| `internal/vt` | terminal identification (DA1, DA2, XTVERSION, CTerm, answerback, VT52); DEC graphics and VT52 output |
| `internal/files` | file areas' storage: names, uploads, limits |
| `internal/ftp` | the FTP server: the file areas as a file system |
| `internal/news` | articles: parsing, checking, making, decoding; wildmats |
@@ -98,6 +99,12 @@ the DEL question making a caller PETSCII or not. RIP: MegaNums, the
commands and their escaping, the menu scene; a RIP terminal found by its
answer, given a .rip screen, menus as buttons, the scene cleared on a
choice and a pause before the next; an ANSI terminal without RIP given
none of it.
none of it. Terminal identification: the answers of DEC's terminals and
of emulators (VT100 to VT525, xterm old and new, VTE, tmux, SyncTERM,
PuTTY, the Linux console, a VT52) read into names, levels, sixel and
monochrome; DEC Special Graphics and Latin-1 output, escapes passing
through it; VT52 output; a VT220 given DEC graphics, Latin-1 and bold,
shown as a VT220; a VT52 given its escapes and its cursor keys ignored;
a terminal answering nothing left plain.
**See also:** [Building](Building)
+1 -1
View File
@@ -61,7 +61,7 @@ Errors are `{"error": "...", "code": "..."}`.
|---|---|---|
| `POST /login`, `POST /logout` | a session token; ending it | (none), any |
| `GET /system` | the name, sysop, counts, features | anonymous |
| `GET /who` | who is online | anonymous |
| `GET /who` | who is online (with each `terminal`, as it said what it is) | anonymous |
| `GET`, `PATCH /me` | your account; change your location or password | read |
| `GET /me/tokens`, `DELETE /me/tokens/{id}` | your tokens; revoke one | any |
| `GET /me/keys` | your SSH keys | read |
+2
View File
@@ -51,6 +51,7 @@ What there is:
- private mail: inbox, read, reply, delete
- [SSH](SSH): logging in by password or key, the text BBS encrypted
- [Commodore 64s and RIPscrip terminals](PETSCII-and-RIP): PETSCII at 40 columns; menus as RIP buttons
- [VT terminals identified](Terminal-Identification) (answerback, DA1, DA2, XTVERSION, VT52): DEC line drawing and Latin-1, bold on monochrome VTs, VT52 escapes
- who's online (and how each caller came: ssh, telnet, tn3270, rlogin, modem
with its rate), the user list, system info
- your profile: where you call from, your password, SSH keys, ANSI and UTF-8
@@ -85,6 +86,7 @@ What there is:
| [TN3270](TN3270) | 3270 terminals, PF keys, 3270 graphics |
| [Sixel graphics](Sixel-Graphics) | the logo on sixel terminals |
| [PETSCII and RIP](PETSCII-and-RIP) | Commodore 64s and 128s; RIPscrip graphics and buttons |
| [Terminal identification](Terminal-Identification) | VT terminals asked what they are: DEC graphics, monochrome, VT52 |
| [Files and FTP](Files-and-FTP) | file areas, the FTP (FTPS) server |
| [File transfers](File-Transfers) | X/Y/ZMODEM, Kermit, IND$FILE |
| [Doors](Doors) | DOS doors in dosemu2 (Docker), Linux doors |
+75
View File
@@ -0,0 +1,75 @@
The BBS asks each caller's terminal what it is, as DEC's terminals were
asked, and adapts to the answer: real VTs (and emulators set up as one)
get their line drawing and character set, monochrome ones bold instead
of color, and a VT52 its own escape codes. What the terminal said shows
in *Who's online* through the [HTTP API](HTTP-API) (`terminal`), in the
caller's profile, and in the log:
```
node 3: terminal VT220 (DA1 62;1;2;6;7;8;9, DA2 1;10;0)
node 4: terminal XTerm(390) (DA1 64;1;2;4;6;9;15;16;17;18;21;22;28, DA2 41;390;0, version XTerm(390))
node 5: terminal tmux 3.4 (DA1 1;2;4, DA2 84;0;0, version tmux 3.4)
```
## The questions
To an ANSI terminal, all at once:
| sent | asks | answered by |
|---|---|---|
| `ENQ` | the answerback message | terminals with one set (PuTTY says `PuTTY`) |
| `CSI c` | primary device attributes (DA1): the VT level and options | every VT100 and later, xterm, most emulators; SyncTERM in its CTerm form |
| `CSI > c` | secondary device attributes (DA2): the model and firmware | VT220 and later, xterm, VTE, tmux, screen, mintty |
| `CSI > 0 q` | XTVERSION: name and version | xterm, tmux, foot, kitty, WezTerm, iTerm2 |
| `CSI 16 t` | the character cell in pixels (for sixel) | xterm and others |
| `CSI 6 n` | the cursor position | every ANSI terminal: once it comes, the rest has |
The position report comes last, so the BBS waits only for it, not for a
timeout, even on a terminal that answers none of the others. To a
terminal that is not ANSI (it did not answer the BBS's first question,
the cursor position) the BBS sends a VT52's identify, `ESC Z`, which a
VT52 answers with `ESC / Z`; any other terminal shows a `Z`, which is
wiped.
## What it is called
In order: XTVERSION's name; SyncTERM by its CTerm attributes; a VT52; a
DEC terminal by its DA2 model (VT100, VT220, VT240, VT320, VT330, VT340,
VT382, VT420, VT510, VT520, VT525, DECterm) with a DEC firmware version;
emulators by their DA2 (tmux, screen, mintty, rxvt, xterm by its patch
number, VTE); the answerback; the VT class from DA1 (VT100, VT102, VT200
class ... VT500 class).
## What it changes
- **DEC character sets.** A VT (DA1 says VT100 or later) whose terminal
type does not say UTF-8 and which is not a PC's BBS terminal (`ansi`,
`syncterm` and the like, which want CP437) gets line drawing and
blocks in DEC Special Graphics (`ESC ( 0`, the `lqkxjm` characters),
Latin-1 letters as 8-bit characters on a VT220 or later (DEC
Multinational has them) on an 8-bit line, and ASCII look-alikes for
the rest. ANSI art in CP437 is drawn the same way. Typed Latin-1
letters are read as such. The profile says `DEC graphics`.
- **Monochrome.** A DEC terminal by its model and firmware (not an
emulator) without ANSI color (DA1 option 22) — VT100 to VT520 — gets
bold for the bright colors and plain text for the rest.
- **Sixel** is known from DA1 option 4 (a VT240, VT330, VT340, xterm
with it on, foot, WezTerm, mlterm), and the cell size from `CSI 16 t`.
- **VT52.** A VT52 (or a VT100 in VT52 mode) gets clearing and cursor
movement as `ESC H`, `ESC J`, `ESC K`, `ESC Y`, `ESC A`-`D`, no
attributes, ASCII only; its cursor and keypad keys are not taken as
commands.
## Turning it off
```ini
[listen modem]
type = raw
address = 127.0.0.1:2323
vt = no
```
`vt = no` asks nothing (sixel is then asked for by DA1 alone, as before)
and changes nothing; `auto` (the default) asks.
**See also:** [PETSCII and RIP](PETSCII-and-RIP), [Sixel graphics](Sixel-Graphics), [Configuration](Configuration)
+1
View File
@@ -13,6 +13,7 @@
- [TN3270](TN3270)
- [Sixel graphics](Sixel-Graphics)
- [PETSCII and RIP](PETSCII-and-RIP)
- [Terminal identification](Terminal-Identification)
**Features**
- [Files and FTP](Files-and-FTP)
+1 -1
View File
@@ -85,7 +85,7 @@ var schemas = map[string]any{
"Login": obj(map[string]any{"name": str, "password": str, "scopes": str}, "name", "password"),
"Session": obj(map[string]any{"token": str, "expires": date, "user": str, "scopes": map[string]any{"type": "array", "items": str}}),
"System": obj(map[string]any{"name": str, "sysop": str, "location": str, "motd": str, "users": num, "messages": num, "areas": num, "online": num, "features": map[string]any{"type": "object"}}),
"Node": obj(map[string]any{"node": num, "user": str, "via": str, "since": date, "doing": str}),
"Node": obj(map[string]any{"node": num, "user": str, "via": str, "since": date, "doing": str, "terminal": str}),
"Nodes": arr("Node"),
"User": obj(map[string]any{"name": str, "location": str, "sysop": boo, "created": date, "last_login": date, "calls": num, "posts": num, "node": num, "locked": boo}),
"Users": arr("User"),
+2 -1
View File
@@ -109,6 +109,7 @@ type nodeJSON struct {
Via string `json:"via"`
Since time.Time `json:"since"`
Doing string `json:"doing"`
Term string `json:"terminal,omitempty"`
}
type areaJSON struct {
@@ -269,7 +270,7 @@ func (s *Server) who(w http.ResponseWriter, r *http.Request) {
if n.User == "" {
continue
}
out = append(out, nodeJSON{n.Num, n.User, n.Via, n.Since, n.Activity})
out = append(out, nodeJSON{n.Num, n.User, n.Via, n.Since, n.Activity, n.Terminal})
}
writeJSON(w, http.StatusOK, out)
}
+21 -1
View File
@@ -65,6 +65,7 @@ type Caller struct {
Remote string // the peer's address, or the caller ID
Source string // what throttling counts failures against
Terminal string // terminal type, if told
Ident string // what the terminal said it is (a VT's identification)
Rate string // modem: tx/rx bit/s
CallerID string // modem: the caller's number
Dialed string // modem: the number dialed
@@ -199,6 +200,20 @@ func (n *Node) SetTerminal(via, terminal string) {
n.b.mu.Unlock()
}
// SetRate records the caller's line rate ("tx/rx") once known.
func (n *Node) SetRate(rate string) {
n.b.mu.Lock()
n.Caller.Rate = rate
n.b.mu.Unlock()
}
// SetIdent records what the caller's terminal said it is.
func (n *Node) SetIdent(ident string) {
n.b.mu.Lock()
n.Caller.Ident = ident
n.b.mu.Unlock()
}
// Doing sets what the caller is doing, for who's online.
func (n *Node) Doing(what string) {
n.b.mu.Lock()
@@ -213,6 +228,7 @@ type NodeInfo struct {
Via string
Since time.Time
Activity string
Terminal string // its identification, else its terminal type
}
// Nodes lists the callers online.
@@ -225,7 +241,11 @@ func (b *BBS) Nodes() []NodeInfo {
if n.user != nil {
name = n.user.Name
}
out = append(out, NodeInfo{n.Num, name, n.Caller.Describe(), n.Since, n.activity})
term := n.Caller.Ident
if term == "" {
term = n.Caller.Terminal
}
out = append(out, NodeInfo{n.Num, name, n.Caller.Describe(), n.Since, n.activity, term})
}
sort.Slice(out, func(i, j int) bool { return out[i].Num < out[j].Num })
return out
+3 -3
View File
@@ -61,9 +61,9 @@ type Config struct {
func DefaultListeners() []*Listener {
return []*Listener{
{Name: "telnet", Kind: "telnet", Address: ":2300", Via: "telnet", TN3270: true,
ANSI: "auto", UTF8: "auto", Sixel: "auto", RIP: "auto", PETSCII: "no", MaxPerIP: 4},
ANSI: "auto", UTF8: "auto", Sixel: "auto", RIP: "auto", PETSCII: "no", VT: "auto", MaxPerIP: 4},
{Name: "modem", Kind: "raw", Address: "127.0.0.1:2323", Via: "modem",
ANSI: "auto", UTF8: "no", Sixel: "no", RIP: "auto", PETSCII: "no", HeaderTimeout: 10 * time.Second},
ANSI: "auto", UTF8: "no", Sixel: "no", RIP: "auto", PETSCII: "no", VT: "auto", HeaderTimeout: 10 * time.Second},
}
}
@@ -249,7 +249,7 @@ func listener(sec *config.Section) (*Listener, error) {
def string
}{{"ansi", &l.ANSI, "auto"}, {"utf8", &l.UTF8, map[bool]string{true: "auto", false: "no"}[l.Kind == "telnet" || l.Kind == "ssh"]},
{"sixel", &l.Sixel, map[bool]string{true: "auto", false: "no"}[l.Kind == "telnet" || l.Kind == "ssh"]},
{"petscii", &l.PETSCII, "no"}, {"rip", &l.RIP, "auto"}} {
{"petscii", &l.PETSCII, "no"}, {"rip", &l.RIP, "auto"}, {"vt", &l.VT, "auto"}} {
*o.p = strings.ToLower(sec.String(o.key, o.def))
switch *o.p {
case "auto", "yes", "no":
+46 -4
View File
@@ -56,6 +56,7 @@ type Listener struct {
Sixel string // auto or yes (ask the terminal), no
PETSCII string // yes (Commodores only), auto (ask a terminal that is not ANSI), no
RIP string // auto (ask a BBS terminal program), yes, no
VT string // auto: ask terminals what they are (DA1, DA2, ESC Z ...); no
Header bool // read a session header first
HeaderTimeout time.Duration
TrustUser bool // the header's MODEM_USER (rlogin's server user) is logged in
@@ -347,7 +348,7 @@ func (s *Server) telnet(c net.Conn, l *Listener, node *bbs.Node) error {
if err != nil {
return err
}
node.Caller.Terminal = tt
node.SetTerminal(node.Caller.Via, tt)
if l.TN3270 && telnet.Is3270(tt) {
return s.tn3270(tc, l, node)
}
@@ -455,6 +456,18 @@ func (s *Server) text(rw io.ReadWriter, c deadliner, l *Listener, node *bbs.Node
t.ANSI = got
}
}
if !t.ANSI && !known && (l.VT == "auto" || l.VT == "yes") && l.ANSI != "no" {
is52, err := t.DetectVT52(time.Second)
if err != nil {
return err
}
if is52 {
t.SetVT52()
node.SetIdent("VT52")
s.B.Log.Printf("node %d: terminal VT52", node.Num)
return s.run(t, l, node)
}
}
if !t.ANSI && !known && l.PETSCII == "auto" {
pet, err := askPETSCII(t)
if err != nil {
@@ -481,7 +494,24 @@ func (s *Server) text(rw io.ReadWriter, c deadliner, l *Listener, node *bbs.Node
}
t.RIP = on || l.RIP == "yes"
}
if t.ANSI && !t.RIP && (l.Sixel == "auto" || l.Sixel == "yes") {
sixel := t.ANSI && !t.RIP && (l.Sixel == "auto" || l.Sixel == "yes")
if t.ANSI && (l.VT == "auto" || l.VT == "yes") {
in, err := t.Identify(1500 * time.Millisecond)
if err != nil {
return err
}
if in.Answered() {
node.SetIdent(in.Name())
s.B.Log.Printf("node %d: terminal %s (%s)", node.Num, in.Name(), in.Details())
}
t.Sixel = sixel && in.Sixel()
t.Mono = in.Mono()
// a VT without UTF-8 (not a PC's BBS terminal, which has CP437):
// its line drawing and Latin-1
if in.Level() > 0 && in.CTerm == "" && !t.UTF8 && !cp437Term(tt) {
t.SetDEC(in.Level() >= 2 && t.Clean8)
}
} else if sixel {
on, err := t.DetectSixel(1500 * time.Millisecond)
if err != nil {
return err
@@ -498,6 +528,18 @@ func (s *Server) run(t *textui.Term, l *Listener, node *bbs.Node) error {
type deadliner interface{ SetReadDeadline(time.Time) error }
// cp437Term: a terminal type a PC's BBS terminal program says (CP437, not
// a VT's character sets)
func cp437Term(tt string) bool {
tt = strings.ToLower(tt)
for _, p := range []string{"ansi", "syncterm", "pcansi", "qansi", "netrunner", "cterm", "scoansi"} {
if strings.HasPrefix(tt, p) {
return true
}
}
return false
}
// petsciiTerm: a terminal type a Commodore's terminal program says
func petsciiTerm(tt string) bool {
tt = strings.ToLower(tt)
@@ -553,10 +595,10 @@ func (s *Server) rlogin(c net.Conn, l *Listener, node *bbs.Node) error {
}
tt, speed, _ := strings.Cut(term, "/")
caller := node.Caller
caller.Terminal = tt
node.SetTerminal(caller.Via, tt)
if caller.Rate == "" && speed != "" {
if n, err := strconv.Atoi(speed); err == nil && n > 0 {
caller.Rate = speed + "/" + speed
node.SetRate(speed + "/" + speed)
}
}
server = strings.TrimSpace(server)
+77
View File
@@ -0,0 +1,77 @@
package server
import (
"strings"
"testing"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/ui3270"
)
// TestVT220: a VT220 on a raw line says what it is: it gets DEC line
// drawing and Latin-1, bold for colors, and shows as a VT220.
func TestVT220(t *testing.T) {
e := startFull(t, ui3270.Graphics{}, nil, screensOnly(map[string]string{"welcome.asc": "┌──┐ café ░\n"}),
&Listener{Name: "vt", Kind: "raw", Address: "vt.sock", ANSI: "auto", UTF8: "auto", Sixel: "auto", RIP: "auto", VT: "auto"})
d := e.dial("vt.sock")
d.expect("\x1b[6n")
d.send("\x1b[24;80R") // ANSI
d.expect("\x1b[!\x1b[6n")
d.send("\x1b[24;80R") // no RIP
d.expect("\x05\x1b[c\x1b[>c\x1b[>0q\x1b[16t\x1b[6n")
d.send("\x1b[?62;1;2;6;7;8;9c\x1b[>1;10;0c\x1b[24;80R")
d.expect("Name")
d.send("alice\r")
d.expect("Password: ")
d.send("alicepass1\r")
d.expect("\x1b(0lqqk\x1b(B caf\xe9 \x1b(0a\r\n\x1b(B")
d.expect("\x1b[1m[M]\x1b[0m") // bold, not yellow
d.expect("Command: ")
if n := e.b.Nodes(); len(n) != 1 || n[0].Terminal != "VT220" {
t.Errorf("nodes: %+v", n)
}
d.send("P")
d.expect("Terminal: VT220, 80x24, ANSI on, UTF-8 off, DEC graphics, sixel off, RIP off")
if strings.Contains(string(d.got), "\x1b[1;33m") {
t.Errorf("color to a VT220: %q", d.got)
}
}
// TestVT52: a terminal that does not answer ANSI's question but answers a
// VT52's identify gets the VT52's escapes and plain text.
func TestVT52(t *testing.T) {
e := start(t, nil, &Listener{Name: "vt", Kind: "raw", Address: "vt.sock", ANSI: "auto", RIP: "auto", VT: "auto"})
d := e.dial("vt.sock")
d.expect("\x1b[6n")
time.Sleep(10 * time.Millisecond) // no answer: not ANSI
d.expect("\x1bZ")
d.send("\x1b/Z")
d.expect("Name (or NEW): ")
d.send("alice\r")
d.expect("Password: ")
d.send("alicepass1\r")
d.expect("Command: ")
d.send("\x1bA") // a cursor key is no command
d.send("I")
d.expect("Sysop:")
d.expect("[Press a key]")
d.send(" ")
d.send("P")
d.expect("Terminal: VT52, 80x24")
if i := strings.Index(string(d.got), "\x1b["); i >= 0 {
t.Errorf("ANSI to a VT52: %q", d.got)
}
if n := e.b.Nodes(); len(n) != 1 || n[0].Terminal != "VT52" {
t.Errorf("nodes: %+v", n)
}
}
// TestVTPlain: a terminal that answers neither is plain, with the Z its
// VT52 question showed wiped.
func TestVTPlain(t *testing.T) {
e := start(t, nil, &Listener{Name: "vt", Kind: "raw", Address: "vt.sock", ANSI: "auto", VT: "auto"})
d := e.dial("vt.sock")
d.expect("\x1bZ")
d.expect("\r \r")
d.expect("Name (or NEW): ")
}
+138 -17
View File
@@ -20,6 +20,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/petscii"
"github.com/Neo-Desktop/bbs-sec/internal/rip"
"github.com/Neo-Desktop/bbs-sec/internal/screens"
"github.com/Neo-Desktop/bbs-sec/internal/vt"
)
// ErrIdle: the caller typed nothing for too long.
@@ -43,6 +44,14 @@ type Term struct {
PETSCII bool
// RIP: an ANSI terminal with RIPscrip graphics (RIPterm, SyncTERM)
RIP bool
// DEC: a VT without UTF-8 (SetDEC): DEC Special Graphics, Latin-1
DEC bool
// VT52: a VT52 (SetVT52): its escapes, no attributes
VT52 bool
// Mono: a terminal without color: bold for colors
Mono bool
// Ident is what the terminal said it is (vt.Info's Name), if anything
Ident string
// Clean8 is an 8-bit clean line (a modem, rlogin, telnet in binary
// mode): what X/Y/ZMODEM need
Clean8 bool
@@ -64,25 +73,57 @@ type Term struct {
// PausePrompt is Pause's ("": "[Press a key]")
PausePrompt string
pet *petscii.Writer // under w, for a PETSCII terminal
sinceKey int // lines printed since a key was read
ripScene bool // a RIP scene is on the screen
xl translator // under w: PETSCII, DEC, VT52
latin1 bool // a DEC terminal's 8-bit characters are Latin-1
sinceKey int // lines printed since a key was read
ripScene bool // a RIP scene is on the screen
}
// translator turns what the BBS writes (UTF-8, ANSI) into a terminal's.
type translator interface {
io.Writer
Settle() error // before waiting for a key
Raw(b []byte) error // bytes as they are
}
func (t *Term) setTranslator(x translator) {
t.Flush()
t.xl = x
if x == nil {
t.w = bufio.NewWriterSize(t.c, 4096)
} else {
t.w = bufio.NewWriterSize(x, 4096)
}
}
// SetDEC makes the terminal a VT without UTF-8: line drawing in DEC
// Special Graphics, Latin-1 if latin1 (a VT220's or later, on an 8-bit
// line).
func (t *Term) SetDEC(latin1 bool) {
t.DEC, t.UTF8, t.latin1 = true, false, latin1
t.setTranslator(vt.NewDECWriter(t.c, latin1))
}
// SetVT52 makes the terminal a VT52: no ANSI, its own escapes.
func (t *Term) SetVT52() {
t.VT52, t.ANSI, t.UTF8, t.Sixel, t.RIP, t.Mono = true, false, false, false, false, true
t.Cols, t.Rows = 80, 24
t.setTranslator(vt.NewVT52Writer(t.c))
}
// SetPETSCII makes the terminal a Commodore's (width 40, or a C128's 80)
// or no longer one.
func (t *Term) SetPETSCII(on bool, width int) {
t.Flush()
if !on {
t.PETSCII, t.pet = false, nil
t.w = bufio.NewWriterSize(t.c, 4096)
t.PETSCII = false
t.setTranslator(nil)
return
}
t.PETSCII, t.ANSI, t.UTF8, t.Sixel, t.RIP = true, false, false, false, false
t.Cols, t.Rows = width, 25
t.pet = petscii.NewWriter(t.c, width)
t.w = bufio.NewWriterSize(t.pet, 4096)
t.pet.Raw(petscii.Start())
pet := petscii.NewWriter(t.c, width)
t.setTranslator(pet)
pet.Raw(petscii.Start())
t.cur = t.cur[:0]
}
@@ -93,8 +134,8 @@ func (t *Term) Raw(b []byte) error {
return err
}
t.cur = t.cur[:0]
if t.pet != nil {
return t.pet.Raw(b)
if t.xl != nil {
return t.xl.Raw(b)
}
_, err := t.c.Write(b)
return err
@@ -125,7 +166,14 @@ const (
// C wraps s in a color, on an ANSI terminal.
func (t *Term) C(color, s string) string {
if !t.ANSI && !t.PETSCII {
switch {
case t.VT52 || !t.ANSI && !t.PETSCII:
return s
case t.Mono:
// bright colors bold, the rest plain
if strings.HasPrefix(color, "1") {
return "\x1b[1m" + s + "\x1b[0m"
}
return s
}
return "\x1b[" + color + "m" + s + "\x1b[0m"
@@ -154,7 +202,7 @@ func (t *Term) Print(s string) {
t.w.WriteString("\r\n")
case r < 0x80:
t.w.WriteByte(byte(r))
case (t.UTF8 || t.PETSCII) && r != utf8.RuneError:
case (t.UTF8 || t.xl != nil) && r != utf8.RuneError:
t.w.WriteRune(r)
default:
t.w.WriteByte('?')
@@ -173,8 +221,8 @@ func (t *Term) Flush() error {
if err := t.w.Flush(); err != nil {
return err
}
if t.pet != nil {
return t.pet.Settle()
if t.xl != nil {
return t.xl.Settle()
}
return nil
}
@@ -182,7 +230,7 @@ func (t *Term) Flush() error {
// Clear clears the screen (a blank line on a plain terminal).
func (t *Term) Clear() {
t.cur = t.cur[:0]
if t.ANSI || t.PETSCII {
if t.ANSI || t.PETSCII || t.VT52 {
t.w.WriteString("\x1b[2J\x1b[H")
} else {
t.w.WriteString("\r\n")
@@ -296,6 +344,9 @@ func (t *Term) next() (rune, error) {
}
b, err := t.r.ReadByte()
if b >= 0x80 {
if t.latin1 && b >= 0xa0 {
return rune(b), err
}
return utf8.RuneError, err
}
return rune(b), err
@@ -326,6 +377,16 @@ func (t *Term) skipEscape() error {
}
case 'O':
t.r.ReadByte()
case 'A', 'B', 'C', 'D':
if !t.VT52 {
t.r.UnreadByte()
} // a VT52's cursor keys
case '?':
if t.VT52 {
t.r.ReadByte() // its keypad
} else {
t.r.UnreadByte()
}
default:
t.r.UnreadByte()
}
@@ -504,7 +565,7 @@ func (t *Term) Pause() error {
// UTF-8 terminal, CP437 to any other; \n as CR LF.
func (t *Term) Art(s string) {
s = strings.ReplaceAll(s, "\n", "\r\n")
if t.UTF8 || t.PETSCII {
if t.UTF8 || t.xl != nil {
t.w.WriteString(s)
} else {
t.w.Write(screens.EncodeCP437(s))
@@ -648,6 +709,66 @@ func (t *Term) RawKey(d time.Duration) (byte, error) {
return b, err
}
// Identify asks an ANSI terminal what it is (vt.Query): its answers, and
// its character cell (for sixel) if it says.
func (t *Term) Identify(timeout time.Duration) (vt.Info, error) {
t.w.WriteString(vt.Query)
if err := t.Flush(); err != nil {
return vt.Info{}, err
}
got, err := t.collect(timeout, 1024, vt.Done)
if err != nil {
return vt.Info{}, err
}
in := vt.Parse(got)
if in.CellW > 0 {
t.CellW, t.CellH = in.CellW, in.CellH
}
t.Ident = in.Name()
return in, nil
}
// DetectVT52 asks a terminal that is not ANSI whether it is a VT52 (ESC
// Z); any other shows a Z, which is wiped.
func (t *Term) DetectVT52(timeout time.Duration) (bool, error) {
t.w.WriteString(vt.QueryVT52)
if err := t.Flush(); err != nil {
return false, err
}
got, err := t.collect(timeout, 16, func(b []byte) bool { return vt.Parse(b).VT52 })
if err != nil {
return false, err
}
if vt.Parse(got).VT52 {
t.Ident = "VT52"
return true, nil
}
t.w.WriteString("\r \r")
return false, nil
}
// collect reads what comes until done says so, max bytes, or timeout.
func (t *Term) collect(timeout time.Duration, max int, done func([]byte) bool) ([]byte, error) {
var got []byte
end := time.Now().Add(timeout)
for time.Now().Before(end) && len(got) < max {
t.c.SetReadDeadline(end)
b, err := t.r.ReadByte()
t.c.SetReadDeadline(time.Time{})
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
break
}
return nil, err
}
got = append(got, b)
if done(got) {
break
}
}
return got, nil
}
// Narrow is a screen too narrow for the usual columns (a C64's 40).
func (t *Term) Narrow() bool { return t.Cols < 60 }
+21 -5
View File
@@ -944,12 +944,24 @@ func (s *session) profile() error {
t.Printf(" Member: since %s, %d calls, %d posts\n", u.Created.Format("2006-01-02"), u.Logins, u.Posts)
onOff := map[bool]string{true: "on", false: "off"}
menu := "\n[L]ocation, [A]NSI on/off, [8]-bit UTF-8 on/off, [S]ixel on/off, [R]IP on/off, "
if t.PETSCII {
ident := ""
if t.Ident != "" {
ident = t.Ident + ", "
}
switch {
case t.PETSCII:
t.Printf(" Terminal: Commodore, %dx%d\n", t.Cols, t.Rows)
menu = "\n[L]ocation, [W]idth 40/80, "
} else {
t.Printf(" Terminal: %dx%d, ANSI %s, UTF-8 %s, sixel %s, RIP %s\n", t.Cols, t.Rows,
onOff[t.ANSI], onOff[t.UTF8], onOff[t.Sixel], onOff[t.RIP])
case t.VT52:
t.Printf(" Terminal: VT52, %dx%d\n", t.Cols, t.Rows)
menu = "\n[L]ocation, "
default:
charset := ""
if t.DEC {
charset = ", DEC graphics"
}
t.Printf(" Terminal: %s%dx%d, ANSI %s, UTF-8 %s%s, sixel %s, RIP %s\n", ident, t.Cols, t.Rows,
onOff[t.ANSI], onOff[t.UTF8], charset, onOff[t.Sixel], onOff[t.RIP])
}
if !u.External {
menu += "[P]assword, SSH [K]eys, "
@@ -970,7 +982,7 @@ func (s *session) profile() error {
return err
}
case 'A', '8', 'S', 'R':
if t.PETSCII {
if t.PETSCII || t.VT52 {
continue
}
case 'W':
@@ -986,6 +998,10 @@ func (s *session) profile() error {
}
case '8':
t.UTF8 = !t.UTF8
if t.UTF8 && t.DEC {
t.DEC = false
t.setTranslator(nil)
}
case 'R':
// on only where the terminal says it has it
if t.RIP {
+256
View File
@@ -0,0 +1,256 @@
// Package vt identifies DEC VT terminals and those that answer as one, as
// DEC's terminals were asked: the answerback message (ENQ), the primary
// and secondary device attributes (DA1, DA2), xterm's version (XTVERSION),
// SyncTERM's CTerm attributes, and a VT52's identify (ESC Z). It also
// writes for them: DECWriter (DEC Special Graphics and Latin-1 for what
// UTF-8 would carry) and VT52Writer (a VT52's escapes for ANSI's).
package vt
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// Query asks an ANSI terminal everything at once: its answerback, DA1,
// DA2, XTVERSION, its character cell (xterm's CSI 16 t), and last its
// cursor position, which every ANSI terminal answers: once that comes,
// whatever else would has.
const Query = "\x05\x1b[c\x1b[>c\x1b[>0q\x1b[16t\x1b[6n"
// QueryVT52 is a VT52's identify; a VT52 answers ESC / and a letter.
const QueryVT52 = "\x1bZ"
var (
da1Pattern = regexp.MustCompile(`\x1b\[\?([0-9;]*)c`)
da2Pattern = regexp.MustCompile(`\x1b\[>([0-9;]*)c`)
ctermPat = regexp.MustCompile(`\x1b\[=([0-9;]*)c`)
xtverPat = regexp.MustCompile(`\x1bP>\|([^\x1b\x07]{0,80})\x1b\\`)
cellPattern = regexp.MustCompile(`\x1b\[6;(\d+);(\d+)t`)
cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`)
vt52Pattern = regexp.MustCompile(`\x1b/([A-Za-z])`)
)
// Done reports whether a reply to Query is complete (the position report
// has come).
func Done(reply []byte) bool { return cprPattern.Match(reply) }
// Info is what a terminal said of itself.
type Info struct {
Answerback string // ENQ's answer, if any
DA1 []int // primary attributes: the class (1, 6, 62-65) and options
DA2 []int // secondary: the model, its firmware version, options
Version string // XTVERSION's "name(version)"
CTerm string // SyncTERM's CTerm version
VT52 bool // answered as a VT52
CellW int // a character cell in pixels, if said
CellH int
}
// Parse reads a terminal's answers.
func Parse(reply []byte) Info {
var in Info
// the answerback is what came before the first escape sequence
ab := string(reply)
if i := strings.IndexByte(ab, 0x1b); i >= 0 {
ab = ab[:i]
}
in.Answerback = printable(ab, 40)
if m := da1Pattern.FindSubmatch(reply); m != nil {
in.DA1 = numbers(string(m[1]))
}
if m := da2Pattern.FindSubmatch(reply); m != nil {
in.DA2 = numbers(string(m[1]))
}
if m := xtverPat.FindSubmatch(reply); m != nil {
in.Version = printable(string(m[1]), 60)
}
if m := ctermPat.FindSubmatch(reply); m != nil {
// "CTerm" in decimal character codes, then the version
ns := numbers(string(m[1]))
if len(ns) >= 5 && string([]byte{byte(ns[0]), byte(ns[1]), byte(ns[2]), byte(ns[3]), byte(ns[4])}) == "CTerm" {
var v []string
for _, n := range ns[5:] {
v = append(v, strconv.Itoa(n))
}
in.CTerm = strings.Join(v, ".")
if in.CTerm == "" {
in.CTerm = "?"
}
}
}
if m := cellPattern.FindSubmatch(reply); m != nil {
h, _ := strconv.Atoi(string(m[1]))
w, _ := strconv.Atoi(string(m[2]))
if w >= 4 && w <= 64 && h >= 4 && h <= 128 {
in.CellW, in.CellH = w, h
}
}
if vt52Pattern.Match(reply) {
in.VT52 = true
}
return in
}
func numbers(s string) []int {
var out []int
for _, f := range strings.Split(s, ";") {
if f == "" {
continue
}
n, err := strconv.Atoi(f)
if err != nil || n < 0 || n > 1<<20 {
continue
}
out = append(out, n)
if len(out) == 32 {
break
}
}
return out
}
func printable(s string, max int) string {
var sb strings.Builder
for _, r := range s {
if r >= 0x20 && r < 0x7f && sb.Len() < max {
sb.WriteRune(r)
}
}
return strings.TrimSpace(sb.String())
}
// Answered reports whether the terminal said anything of itself.
func (in Info) Answered() bool {
return in.DA1 != nil || in.DA2 != nil || in.Version != "" || in.CTerm != "" || in.VT52 || in.Answerback != ""
}
// Level is the VT level the terminal works at: 1 for a VT100 or VT102,
// 2 for a VT220, 3 VT320, 4 VT420, 5 VT510 and later; 0 if it did not say.
func (in Info) Level() int {
if len(in.DA1) == 0 {
return 0
}
switch c := in.DA1[0]; {
case c >= 61 && c <= 69:
return c - 60
case c == 1 || c == 6 || c == 4 || c == 7 || c == 12:
return 1
}
return 0
}
// Has reports a DA1 option of a level 2 or later terminal: 1 132 columns,
// 2 printer, 3 ReGIS, 4 sixel, 6 selective erase, 7 soft characters, 8
// user defined keys, 9 national characters, 15 technical characters, 18
// windowing, 21 horizontal scrolling, 22 ANSI color, 28 rectangular
// editing.
func (in Info) Has(opt int) bool {
if in.Level() < 2 {
return false
}
for _, o := range in.DA1[1:] {
if o == opt {
return true
}
}
return false
}
// Sixel: the terminal draws sixel graphics.
func (in Info) Sixel() bool { return in.Has(4) }
// decModels are DA2's model numbers of DEC's own terminals.
var decModels = map[int]string{
0: "VT100", 1: "VT220", 2: "VT240", 18: "VT330", 19: "VT340", 24: "VT320",
28: "DECterm", 32: "VT382", 41: "VT420", 61: "VT510", 64: "VT520", 65: "VT525",
}
// emulators are DA2's model numbers emulators use for themselves.
var emulators = map[int]string{77: "mintty", 82: "rxvt", 83: "screen", 84: "tmux", 85: "rxvt-unicode"}
// Hardware reports a DEC terminal by its DA2 (a model of DEC's, a small
// firmware version), not an emulator saying its name otherwise.
func (in Info) Hardware() bool {
if in.Version != "" || in.CTerm != "" || len(in.DA2) < 2 {
return false
}
_, dec := decModels[in.DA2[0]]
return dec && in.DA2[1] < 95
}
// Mono: a DEC terminal without color (the VT100s to the VT520: bold,
// underline, blink and reverse instead).
func (in Info) Mono() bool {
return in.Hardware() && in.DA2[0] != 65 && !in.Has(22)
}
// Name is what the terminal is, as best it said: XTVERSION's name, SyncTERM,
// the answerback, a DEC model, an emulator, or its VT class.
func (in Info) Name() string {
switch {
case in.Version != "":
return in.Version
case in.CTerm != "":
return "SyncTERM (CTerm " + in.CTerm + ")"
case in.VT52:
return "VT52"
case in.Hardware():
return decModels[in.DA2[0]]
}
if len(in.DA2) >= 2 {
p, v := in.DA2[0], in.DA2[1]
switch {
case emulators[p] != "":
return emulators[p]
case p == 41 && v >= 95:
return fmt.Sprintf("xterm (patch %d)", v)
case (p == 1 || p == 65) && v >= 1000:
return "VTE"
}
}
if in.Answerback != "" {
return in.Answerback
}
switch l := in.Level(); {
case l == 1 && in.DA1[0] == 6:
return "VT102"
case l == 1:
return "VT100"
case l >= 2:
return fmt.Sprintf("VT%d00 class", l) // 62: VT200 class, ...
}
return ""
}
// Details is the answers, for the log.
func (in Info) Details() string {
var parts []string
join := func(ns []int) string {
var s []string
for _, n := range ns {
s = append(s, strconv.Itoa(n))
}
return strings.Join(s, ";")
}
if in.DA1 != nil {
parts = append(parts, "DA1 "+join(in.DA1))
}
if in.DA2 != nil {
parts = append(parts, "DA2 "+join(in.DA2))
}
if in.Version != "" {
parts = append(parts, "version "+in.Version)
}
if in.CTerm != "" {
parts = append(parts, "CTerm "+in.CTerm)
}
if in.Answerback != "" {
parts = append(parts, fmt.Sprintf("answerback %q", in.Answerback))
}
if in.VT52 {
parts = append(parts, "VT52")
}
return strings.Join(parts, ", ")
}
+87
View File
@@ -0,0 +1,87 @@
package vt
import (
"bytes"
"testing"
)
func TestParse(t *testing.T) {
for _, c := range []struct {
name, reply, want string
level int
sixel, mono, hw bool
}{
// DEC's own
{"vt100", "\x1b[?1;2c\x1b[24;80R", "VT100", 1, false, false, false},
{"vt102", "\x1b[?6c\x1b[24;80R", "VT102", 1, false, false, false},
{"vt220", "\x1b[?62;1;2;6;7;8;9c\x1b[>1;10;0c\x1b[24;80R", "VT220", 2, false, true, true},
{"vt340", "\x1b[?63;1;2;3;4;6;8;9;15c\x1b[>19;10;0c\x1b[24;80R", "VT340", 3, true, true, true},
{"vt420", "\x1b[?64;1;2;6;8;9;15;18;21c\x1b[>41;20;0c\x1b[24;80R", "VT420", 4, false, true, true},
{"vt525", "\x1b[?65;1;2;6;8;9;15;18;21;22c\x1b[>65;10;0c\x1b[24;80R", "VT525", 5, false, false, true},
// emulators
{"xterm", "\x1b[?64;1;2;4;6;9;15;16;17;18;21;22;28c\x1b[>41;390;0c\x1bP>|XTerm(390)\x1b\\\x1b[6;20;10t\x1b[24;80R",
"XTerm(390)", 4, true, false, false},
{"old xterm", "\x1b[?63;1;2;6;9;15;22c\x1b[>41;297;0c\x1b[24;80R", "xterm (patch 297)", 3, false, false, false},
{"vte", "\x1b[?65;1;9c\x1b[>65;7600;1c\x1b[24;80R", "VTE", 5, false, false, false},
{"tmux", "\x1b[?1;2c\x1b[>84;0;0c\x1b[24;80R", "tmux", 1, false, false, false},
{"syncterm", "\x1b[=67;84;101;114;109;1;316c\x1b[24;80R", "SyncTERM (CTerm 1.316)", 0, false, false, false},
{"putty", "PuTTY\x1b[?6c\x1b[>0;136;0c\x1b[24;80R", "PuTTY", 1, false, false, false},
{"linux", "\x1b[?6c\x1b[24;80R", "VT102", 1, false, false, false},
{"vt52", "\x1b/Z", "VT52", 0, false, false, false},
{"nothing", "\x1b[24;80R", "", 0, false, false, false},
} {
in := Parse([]byte(c.reply))
if in.Name() != c.want || in.Level() != c.level || in.Sixel() != c.sixel || in.Mono() != c.mono || in.Hardware() != c.hw {
t.Errorf("%s: %q level %d sixel %v mono %v hw %v (%s)", c.name, in.Name(), in.Level(),
in.Sixel(), in.Mono(), in.Hardware(), in.Details())
}
}
in := Parse([]byte("\x1b[?64;4c\x1b[6;20;10t\x1b[24;80R"))
if in.CellW != 10 || in.CellH != 20 || !Done([]byte("\x1b[24;80R")) || Done([]byte("\x1b[?6c")) {
t.Errorf("cell %dx%d", in.CellW, in.CellH)
}
// junk is kept out of names
if in := Parse([]byte("\x01bad\x7fname\x1bP>|ev\x07il(1)\x1b\\")); in.Answerback != "badname" || in.Version != "" {
t.Errorf("%+v", in)
}
}
func TestDECWriter(t *testing.T) {
for _, c := range []struct {
in []string
latin1 bool
want string
}{
{[]string{"┌─┐\r\n└─┘ ok"}, true, "\x1b(0lqk\r\nmqj\x1b(B ok"},
{[]string{"café £5 ±1"}, true, "caf\xe9 \xa35 \xb11"},
{[]string{"café £5 ±1"}, false, "cafe \x1b(0}\x1b(B5 \x1b(0g\x1b(B1"},
{[]string{"“hi”… 日"}, true, "\"hi\"... ?"},
// escape sequences pass, and do not end the graphics
{[]string{"─\x1b[1;36m─x"}, true, "\x1b(0q\x1b[1;36mq\x1b(Bx"},
{[]string{"\xe2\x94", "\x80\x1b[", "0m"}, true, "\x1b(0q\x1b[0m"},
} {
var buf bytes.Buffer
d := NewDECWriter(&buf, c.latin1)
for _, s := range c.in {
d.Write([]byte(s))
}
d.Settle()
want := c.want
if bytes.Count([]byte(want), []byte("\x1b(0")) > bytes.Count([]byte(want), []byte("\x1b(B")) {
want += "\x1b(B"
}
if buf.String() != want {
t.Errorf("%q: %q, want %q", c.in, buf.String(), want)
}
}
}
func TestVT52Writer(t *testing.T) {
var buf bytes.Buffer
v := NewVT52Writer(&buf)
v.Write([]byte("\x1b[2J\x1b[H\x1b[1;36mTitle\x1b[0m\r\n\x1b[3;10Hx\x1b[K\x1b[2A\x1bPq#0;2;0;0;0-\x1b\\é─"))
want := "\x1bH\x1bJ\x1bY Title\r\n\x1bY\")x\x1bK\x1bA\x1bAe-"
if buf.String() != want {
t.Errorf("%q\nwant %q", buf.String(), want)
}
}
+285
View File
@@ -0,0 +1,285 @@
package vt
import (
"io"
"strconv"
"strings"
"unicode/utf8"
"golang.org/x/text/unicode/norm"
)
// seq splits a stream into text runes and whole escape sequences (ESC x,
// ESC ( x, CSI ... final, DCS or OSC ... ST), across writes.
type seq struct {
state int // 0 text, 1 ESC, 2 ESC intermediate, 3 CSI, 4 DCS/OSC, 5 ESC in DCS/OSC
buf []byte
part []byte // a rune begun
}
// feed gives each text rune to text and each sequence to esc.
func (s *seq) feed(b []byte, text func(rune), esc func([]byte)) {
for _, c := range b {
switch s.state {
case 0:
switch {
case c == 0x1b:
s.state, s.buf = 1, append(s.buf[:0], c)
case len(s.part) > 0 || c >= 0x80:
s.part = append(s.part, c)
if utf8.FullRune(s.part) || len(s.part) >= utf8.UTFMax {
r, _ := utf8.DecodeRune(s.part)
s.part = s.part[:0]
text(r)
}
default:
text(rune(c))
}
case 1:
s.buf = append(s.buf, c)
switch {
case c == '[':
s.state = 3
case c == 'P' || c == ']':
s.state = 4
case c >= 0x20 && c <= 0x2f:
s.state = 2
default:
s.state = 0
esc(s.buf)
}
case 2:
s.buf = append(s.buf, c)
if c >= 0x30 {
s.state = 0
esc(s.buf)
}
case 3:
s.buf = append(s.buf, c)
if c >= 0x40 && c <= 0x7e {
s.state = 0
esc(s.buf)
} else if len(s.buf) > 64 {
s.state = 0 // not a sequence of ours: dropped
}
case 4, 5:
s.buf = append(s.buf, c)
switch {
case c == 0x07 && s.buf[1] == ']':
s.state = 0
esc(s.buf)
case s.state == 5 && c == '\\':
s.state = 0
esc(s.buf)
default:
s.state = 4
if c == 0x1b {
s.state = 5
}
}
}
}
}
// graphics: what DEC Special Graphics (ESC ( 0) draws, by the character
// that draws it
var graphics = map[rune]byte{
'─': 'q', '━': 'q', '═': 'q', '│': 'x', '┃': 'x', '║': 'x',
'┌': 'l', '┏': 'l', '╔': 'l', '╓': 'l', '╒': 'l',
'┐': 'k', '┓': 'k', '╗': 'k', '╖': 'k', '╕': 'k',
'└': 'm', '┗': 'm', '╚': 'm', '╙': 'm', '╘': 'm',
'┘': 'j', '┛': 'j', '╝': 'j', '╜': 'j', '╛': 'j',
'├': 't', '┣': 't', '╠': 't', '╟': 't', '╞': 't',
'┤': 'u', '┫': 'u', '╣': 'u', '╢': 'u', '╡': 'u',
'┬': 'w', '┳': 'w', '╦': 'w', '╥': 'w', '╤': 'w',
'┴': 'v', '┻': 'v', '╩': 'v', '╨': 'v', '╧': 'v',
'┼': 'n', '╋': 'n', '╬': 'n', '╫': 'n', '╪': 'n',
'░': 'a', '▒': 'a', '▓': 'a', '█': 'a', '▀': 'a', '▄': 'a', '▌': 'a', '▐': 'a',
'◆': '`', '♦': '`', '≤': 'y', '≥': 'z', 'π': '{', '≠': '|', '⎺': 'o', '⎻': 'p', '⎼': 'r', '⎽': 's',
'␉': 'b', '␌': 'c', '␍': 'd', '␊': 'e', '␤': 'h', '␋': 'i',
}
// graphics also for Latin-1's, where Latin-1 cannot go
var graphicsLatin = map[rune]byte{'°': 'f', '±': 'g', '£': '}', '·': '~'}
// like: ASCII for what has no character
var like = map[rune]string{
'–': "-", '—': "-", '‘': "'", '’': "'", '‚': ",", '“': "\"", '”': "\"", '„': "\"",
'…': "...", '•': "*", '«': "<<", '»': ">>", '×': "x", '÷': "/", '©': "(c)", '®': "(R)",
'ß': "ss", 'æ': "ae", 'Æ': "AE", 'ø': "o", 'Ø': "O", ' ': " ", '¡': "!", '¿': "?",
'€': "EUR", '™': "TM", '←': "<-", '→': "->", '↑': "^", '↓': "v",
'─': "-", '│': "|", '┼': "+", '░': "#", '▒': "#", '▓': "#", '█': "#",
}
// ascii is r as ASCII: itself, a look alike, or the letter without its
// accent; "?" if none.
func ascii(r rune) string {
if r < 0x80 {
return string(r)
}
if s, ok := like[r]; ok {
return s
}
if d := norm.NFD.String(string(r)); d != string(r) {
if b, _ := utf8.DecodeRuneInString(d); b < 0x80 {
return string(b)
}
}
if _, ok := graphics[r]; ok {
return "+"
}
return "?"
}
// DECWriter writes UTF-8 to a VT that has no UTF-8: Latin-1 (a VT220's
// DEC Multinational has it) as 8-bit characters when Latin1, line
// drawing and blocks in DEC Special Graphics, anything else as ASCII.
// Escape sequences pass as they are.
type DECWriter struct {
w io.Writer
Latin1 bool
s seq
gfx bool // G0 is the graphics set
out []byte
}
// NewDECWriter writes to w.
func NewDECWriter(w io.Writer, latin1 bool) *DECWriter { return &DECWriter{w: w, Latin1: latin1} }
func (d *DECWriter) Write(b []byte) (int, error) {
d.out = d.out[:0]
d.s.feed(b, d.text, func(e []byte) { d.out = append(d.out, e...) })
if len(d.out) > 0 {
if _, err := d.w.Write(d.out); err != nil {
return 0, err
}
}
return len(b), nil
}
func (d *DECWriter) text(r rune) {
g, isG := graphics[r]
if !isG && !d.Latin1 {
g, isG = graphicsLatin[r]
}
if isG {
if !d.gfx {
d.out = append(d.out, "\x1b(0"...)
d.gfx = true
}
d.out = append(d.out, g)
return
}
if d.gfx && r >= 0x20 && r != 0x7f {
d.out = append(d.out, "\x1b(B"...)
d.gfx = false
}
switch {
case r < 0x80:
d.out = append(d.out, byte(r))
case d.Latin1 && r >= 0xa0 && r <= 0xff:
d.out = append(d.out, byte(r))
default:
d.out = append(d.out, ascii(r)...)
}
}
// Settle puts G0 back to ASCII (before the BBS waits for a key, or the
// line is given to a file transfer).
func (d *DECWriter) Settle() error {
if !d.gfx {
return nil
}
d.gfx = false
_, err := d.w.Write([]byte("\x1b(B"))
return err
}
// Raw writes b as it is.
func (d *DECWriter) Raw(b []byte) error {
if err := d.Settle(); err != nil {
return err
}
_, err := d.w.Write(b)
return err
}
// VT52Writer writes for a VT52: ANSI's clearing and cursor movement as
// its escapes, attributes and what it has no escape for dropped, ASCII
// only.
type VT52Writer struct {
w io.Writer
s seq
out []byte
}
// NewVT52Writer writes to w.
func NewVT52Writer(w io.Writer) *VT52Writer { return &VT52Writer{w: w} }
func (v *VT52Writer) Write(b []byte) (int, error) {
v.out = v.out[:0]
v.s.feed(b, func(r rune) { v.out = append(v.out, ascii(r)...) }, v.esc)
if len(v.out) > 0 {
if _, err := v.w.Write(v.out); err != nil {
return 0, err
}
}
return len(b), nil
}
func (v *VT52Writer) esc(e []byte) {
if len(e) < 3 || e[1] != '[' {
return // ESC 7, charsets, DCS (sixel), OSC: nothing on a VT52
}
params, final := string(e[2:len(e)-1]), e[len(e)-1]
if strings.ContainsAny(params, "?>=<!") {
return
}
ns := strings.Split(params, ";")
num := func(i, def int) int {
if i < len(ns) {
if n, err := strconv.Atoi(ns[i]); err == nil && n > 0 {
return min(n, 100)
}
}
return def
}
rep := func(s string, n int) {
for i := 0; i < n; i++ {
v.out = append(v.out, s...)
}
}
switch final {
case 'J':
if num(0, 0) == 2 {
v.out = append(v.out, "\x1bH\x1bJ"...)
} else {
v.out = append(v.out, "\x1bJ"...)
}
case 'K':
if num(0, 0) == 0 {
v.out = append(v.out, "\x1bK"...)
}
case 'H', 'f':
row, col := min(num(0, 1), 24), min(num(1, 1), 80)
v.out = append(v.out, 0x1b, 'Y', byte(31+row), byte(31+col))
case 'A':
rep("\x1bA", num(0, 1))
case 'B':
rep("\x1bB", num(0, 1))
case 'C':
rep("\x1bC", num(0, 1))
case 'D':
rep("\x1bD", num(0, 1))
}
}
// Settle has nothing to do on a VT52.
func (v *VT52Writer) Settle() error { return nil }
// Raw writes b as it is.
func (v *VT52Writer) Raw(b []byte) error {
_, err := v.w.Write(b)
return err
}