VT220 to VT525 and videotex terminals (Phases 2, 3 and 8) (#37)

* VT220 and VT320: G0-G3 and shifts, NRCS, 8-bit replies, DECSCA, DECUDK

Phase 2, part 1. The character sets move into CharsetShifting, which
VtInterpreter composes: G0-G3, GL and GR, the locking shifts (SI, SO,
LS2, LS3, LS1R-LS3R) and single shifts (SS2, SS3, and their C1 forms),
designators of two characters and 96-character sets (ESC - . /), the
national replacement sets, DEC Supplemental, DEC Technical and Latin-1,
each at the level that has it, and DECSC keeping them all.

Also:
- S7C1T/S8C1T: replies with C1 controls
- DECSCA with DECSED and DECSEL (a protected bit SGR leaves alone)
- DECSCL: the operating level and 7- or 8-bit replies
- DSR ?15, ?25, ?26 and ?6 (DECXCPR)
- DECRQPSR (DECCIR, DECTABSR), DECRQUPSS and DECAUPSS
- DECRQSS for DECSCL, DECSCA, DECSLPP, DECSCPP, DECSNLS
- DECUDK in UserKeys: Shift with F6-F20 sends what the host loaded
- F13-F20, Find and Select keys, and LK201 and UDK key bar pages
- a VT320 profile (level 3)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSyCmXjaURxSYoHxCY

* VT320 status line and DECDLD soft characters

Phase 2, part 2:
- DECSSDT and DECSASD: the indicator status line (the cursor's place)
  or the host's own, written with a cursor of its own (StatusLine);
  shown below the screen on Android and iOS, the screen a line shorter
- DECDLD (SoftFont): a soft set's glyphs read from their sixels, kept
  as code points of plane 15, designated by the host's Dscs (a GSet
  SOFT slot in CharsetShifting) and drawn from their bitmaps by both
  apps; BitmapFont now takes a width (rows as Ints), so the soft
  glyphs keep theirs (a VT320's 15x12)
- DECRQSS for DECSSDT and DECSASD; DECCIR names the soft set

Pages (NP, PP, PPA and the rest) are a VT330's and VT420's: they go
with Phase 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSyCmXjaURxSYoHxCY

* VT420, VT510, VT520, VT525: margins, rectangles, pages, colour table

Phase 3. A Vt420Interpreter extends VtInterpreter through its hooks
(an ESC, a CSI, a DCS, DECRQSS and DECRQM a subclass takes):
- DECLRMM and DECSLRM: the emulator's printing, wrapping, CR, scrolling,
  IL/DL and ICH/DCH keep between the margins
- Rectangles: DECCRA, DECERA, DECSERA, DECFRA, DECCARA and DECRARA
  (DECSACE: a stream or a rectangle), DECRQCRA's checksum, DECIC/DECDC
- DECBI and DECFI
- pages: NP, PP, PPA, PPR, PPB over six, DECXCPR telling the page
- DECSNLS, DECSLPP, DECSCPP; DECNKM, DECBKM
- VT5xx: DECRQDE, the bell volume and keyboard sequences taken;
  VT525: DECAC and the colour table (DECRQTSR 2, DECRSTS in RGB or HLS)
- VT420, VT510, VT520 and VT525 profiles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSyCmXjaURxSYoHxCY

* Viewdata (Prestel) and Minitel terminals

Phase 8. Both build on ByteControlInterpreter through a
VideotexInterpreter (the teletext palette, the mosaics' glyphs on the
emulator, a cursor wrapping round the screen):
- Mosaic: 2x3 block graphics, contiguous and separated, drawn from
  bitmaps the app makes, at plane 15 code points (the soft glyph path)
- Viewdata: the screen kept as its codes, each row drawn again from
  them with teletext Level 1's spacing attributes (set-at and
  set-after); Prestel's controls; # and Enter send 0x5f
- Minitel: row 0 the status row, US addressing, G0/G1, SS2 accents and
  symbols, ESC attributes with the background and separation taken at
  a delimiter, REP, CSI commands, PRO1-PRO3 (ENQROM answered, ROULEAU,
  Mixte's 80 columns, Téléinformatique as a VT100), its function keys
- key bars for both, captures as .vdt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSyCmXjaURxSYoHxCY

* VT525 colour table: DEC's HLS from Sixel's, not a copy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSyCmXjaURxSYoHxCY

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
NeoandClaude Opus 5.5 authored and GitHub committed 2026-11-10 17:19:36 -08:00
1 parent c0bf3e41a2
commit 0c448f7d4d
30 files changed
+2651 -157

No files matched your search

@@ -71,6 +71,10 @@ class TerminalSession(
private val _title = MutableStateFlow("")
val title: StateFlow<String> = _title.asStateFlow()
/** the status line below the screen (a VT320's, DECSSDT): "" for none */
private val _statusLine = MutableStateFlow("")
val statusLine: StateFlow<String> = _statusLine.asStateFlow()
/** Ctrl and Alt latched (the extra keys' and the volume keys'): for the next key only */
val ctrl = MutableStateFlow(false)
val alt = MutableStateFlow(false)
@@ -172,7 +176,10 @@ class TerminalSession(
while (off < end) {
val bps = synchronized(emulator) { emulator.emulatedBps }
val n = if (bps <= 0) end - off else minOf(end - off, maxOf(1, bps / 10 / (1000 / PACE_MS).toInt()))
synchronized(emulator) { emulator.append(if (off == 0 && n == data.size) data else data.copyOfRange(off, off + n), n) }
_statusLine.value = synchronized(emulator) {
emulator.append(if (off == 0 && n == data.size) data else data.copyOfRange(off, off + n), n)
emulator.statusText()
}
onChange?.invoke()
off += n
if (bps > 0) {
@@ -440,8 +440,8 @@ class TerminalView @JvmOverloads constructor(
flush(x + 1)
continue
}
val g = drawing?.glyphs
if (g != null && g.has(cp)) {
val g = drawing?.glyphFor(cp)
if (g != null) {
flush(x + 1)
drawGlyph(c, g, cp, px(x), y, px(x + 1) - px(x))
continue
@@ -489,17 +489,19 @@ class TerminalView @JvmOverloads constructor(
/** [cp]'s bitmap glyph in [g] filling the cell at ([left], [y]), [w] wide, in fillPaint's colour: each row's runs of pixels as one rectangle */
private fun drawGlyph(c: Canvas, g: org.dmodem.app.terminal.BitmapFont, cp: Int, left: Float, y: Float, w: Float) {
val h = g.height
val gw = g.width
val high = 1 shl (gw - 1)
for (r in 0 until h) {
val bits = g.row(cp, r)
if (bits == 0) continue
val top = y + floor(r * cellH / h)
val bottom = y + floor((r + 1) * cellH / h)
var col = 0
while (col < 8) {
if (bits and (0x80 ushr col) == 0) { col++; continue }
while (col < gw) {
if (bits and (high ushr col) == 0) { col++; continue }
val start = col
while (col < 8 && bits and (0x80 ushr col) != 0) col++
c.drawRect(left + floor(start * w / 8), top, left + floor(col * w / 8), bottom, fillPaint)
while (col < gw && bits and (high ushr col) != 0) col++
c.drawRect(left + floor(start * w / gw), top, left + floor(col * w / gw), bottom, fillPaint)
}
}
}
@@ -608,8 +610,8 @@ class TerminalView @JvmOverloads constructor(
textPaint.color = theme.bgArgb
textPaint.isFakeBoldText = false
textPaint.textSkewX = 0f
val g = e.glyphs
if (g != null && g.has(cp)) {
val g = e.glyphFor(cp)
if (g != null) {
fillPaint.color = theme.bgArgb
drawGlyph(c, g, cp, x, y, cw)
} else if (settings.drawBoxes && BoxDrawing.handles(cp)) {
@@ -110,6 +110,7 @@ fun TerminalScreen(
val status by ModemState.status.collectAsStateWithLifecycle()
val run by ModemState.run.collectAsStateWithLifecycle()
val title by session.title.collectAsStateWithLifecycle()
val statusLine by session.statusLine.collectAsStateWithLifecycle()
val capture by session.capture.collectAsStateWithLifecycle()
var view by remember { mutableStateOf<TerminalView?>(null) }
var showSnippets by remember { mutableStateOf(false) }
@@ -299,9 +300,20 @@ fun TerminalScreen(
)
}
}
// a VT320's status line, below the screen (the screen a line shorter)
if (statusLine.isNotEmpty()) {
Text(
statusLine,
fontFamily = FontFamily.Monospace,
fontSize = 12.sp,
maxLines = 1,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceVariant).padding(horizontal = 4.dp),
)
}
if (s.extraKeys) {
ExtraKeys(
onKey = { k -> view?.scrollToBottom(); session.sendKey(k) },
onKey = { k, shift -> view?.scrollToBottom(); session.sendKey(k, shift = shift) },
onText = { t -> view?.scrollToBottom(); session.sendTyped(t) },
fullscreen = fullscreen,
onExitFullscreen = { onFullscreen(false) },
@@ -535,7 +547,7 @@ private fun TopBar(
/** The keys a phone's keyboard hasn't got, as JuiceSSH's bar had them: Ctrl and Alt stay down for the next key. */
@Composable
private fun ExtraKeys(
onKey: (Key) -> Unit,
onKey: (Key, Boolean) -> Unit,
onText: (String) -> Unit,
fullscreen: Boolean,
onExitFullscreen: () -> Unit,
@@ -553,7 +565,7 @@ private fun ExtraKeys(
KeyRow {
for (k in row) {
when (k) {
is BarKey.Send -> KeyButton(k.label, repeat = k.repeat) { onKey(k.key) }
is BarKey.Send -> KeyButton(k.label, repeat = k.repeat) { onKey(k.key, k.shift) }
is BarKey.Type -> KeyButton(k.label) { onText(k.text) }
is BarKey.Octets -> KeyButton(k.label, swatch = k.color) {
session.sendTerminal(k.octets.toByteArray(Charsets.ISO_8859_1))
+38 -5
View File
@@ -31,7 +31,8 @@
characters drawn to fill their cells so ANSI art has no gaps. A
terminal type (Settings, and each directory entry's own) picks what it
is: xterm, ANSI-BBS (a PC's, in CP437, as SyncTERM is), DEC VT52, VT100,
VT102 or VT220, a Commodore or an Atari. Each
VT102, VT220, VT320, VT420, VT510, VT520 or VT525, a Commodore, an
Atari, Viewdata (Prestel) or a Minitel. Each
answers the device attribute requests as that terminal did, knows only
its own sequences (a VT100 has no colours, a VT220 no xterm titles or
mouse), and gives SSH its `TERM` and Telnet its TERMINAL-TYPE. The DEC
@@ -39,9 +40,28 @@
column switching (the screen refits to the width), the VT52's own
sequences and graphics (and a VT100's VT52 mode), the UK character set,
the keyboard LEDs and parameter reports, and a printer port (from the
VT102 on) whose output is saved to a text file. The key bar gains the
DEC keypad (PF1-PF4, digits, minus, comma, period, Enter, in numeric or
application mode), and a hardware numpad sends those keys. ANSI-BBS is
VT102 on) whose output is saved to a text file. The VT220 and VT320
add G0-G3 with their locking and single shifts, the national
replacement sets, DEC Supplemental and (VT320) DEC Technical and
Latin-1 as 96-character sets, 8-bit replies (S8C1T), protected
characters with selective erase (DECSCA, DECSED, DECSEL), the
conformance level (DECSCL), the printer, keyboard and user-defined key
status reports, the cursor and tab stop reports (DECCIR, DECTABSR), the
preferred supplemental set, user-defined keys (DECUDK: Shift with
F6-F20), and soft characters (DECDLD: the host's own glyphs, drawn from
its bitmaps). A VT320 also has its status line below the screen: the
cursor's place, or a line the host writes (DECSSDT, DECSASD). The VT420
adds left and right margins (DECLRMM, DECSLRM), the rectangular area
operations (copy, erase, selective erase, fill, attribute change and
reverse, as a rectangle or a stream, and the checksum), column insert
and delete, back and forward index, six pages (NP, PP, PPA, PPR, PPB),
the lines and columns asked for (DECSNLS, DECSLPP, DECSCPP), and the
keypad and backarrow modes; the VT5xx add the display extent report,
and the VT525 colour, with its colour table (DECAC, DECRQTSR, DECRSTS,
in RGB or DEC's HLS). The key bar gains the DEC keypad (PF1-PF4, digits, minus,
comma, period, Enter, in numeric or application mode), and on a VT220
or VT320 the LK201's F6-F20, Find and Select and a page of the
user-defined keys; a hardware numpad sends the keypad's keys. ANSI-BBS is
the PC's 80x25 drawn in a VGA's 8x16 code page 437 (Unscii's, public
domain), with SyncTERM's additions: ANSI music (`ESC [ |`, and a bare
`ESC [ M` when a PLAY string follows it) played as a PC speaker would,
@@ -63,7 +83,20 @@
inverse video, its cursor keys wrapping round the screen, CLEAR, EOL,
insert and delete of characters and lines, tabs, the buzzer and ESC to
show a control's character; CTRL with a letter types its graphic and
the key bar's INV key types the next character inverse. Colour
the key bar's INV key types the next character inverse. Viewdata is
Prestel's 40x24 of teletext: its attributes take a cell and change the
rest of the row (alpha and mosaic colours, flash, conceal, contiguous
or separated mosaics, hold, new and black background; double height is
drawn single), the 2x3 mosaics drawn from the app's own bitmaps, the
cursor wrapping round the screen, and # (Enter too) as the key that
sends. The Minitel is Teletel's 40x25 with its status row: US
addressing, text and mosaics (SO/SI), SS2's accents and symbols, the
ESC colours and attributes (the background and separation taking
effect at the next space or mosaic), REP, its CSI commands, the
protocol commands (it answers as a Minitel 2), scrolling or page mode,
the 80-column Mixte mode, the Téléinformatique mode as a VT100, and a
key bar of Envoi, Retour, Suite, Répétition, Correction, Sommaire,
Guide, Annulation and Connexion/Fin. Both save captures as `.vdt`. Colour
themes (VGA, xterm, Solarized, Dracula, Monokai, Gruvbox, Nord, green
and amber phosphor), fonts (Cascadia Code, Sauce Code Pro Nerd Font,
Source Code Pro, Roboto Mono, JetBrains Mono, Fira Code, OpenDyslexic
+22 -9
View File
@@ -17,6 +17,8 @@ final class TerminalModel: ObservableObject {
@Published var ctrl = false
/// the next key with Alt (the key bar's sticky Alt)
@Published var alt = false
/// the status line below the screen (a VT320's, DECSSDT): "" for none
@Published private(set) var statusText = ""
/// to the modem
var send: ((Data) -> Void)?
@@ -34,16 +36,25 @@ final class TerminalModel: ObservableObject {
revision = bridge.revision
}
/// the profile's glyphs, as they're asked for
private var glyphCache: [UInt32: [Int]?] = [:]
/// a bitmap glyph: its rows, top first, bit width - 1 the leftmost pixel
struct Glyph {
let rows: [Int]
let width: Int
}
/// the profile's bitmap glyph for [cp] (8 wide, 8 or 16 high): its rows, top first, bit 7 the leftmost pixel; nil: drawn with the font
func glyph(_ cp: UInt32) -> [Int]? {
if let g = glyphCache[cp] { return g }
let first = Int(bridge.glyphRow(cp: Int32(bitPattern: cp), row: 0))
let h = Int(bridge.glyphHeight)
let g: [Int]? = first < 0 ? nil : [first] + (1..<max(h, 1)).map { Int(bridge.glyphRow(cp: Int32(bitPattern: cp), row: Int32($0))) }
glyphCache[cp] = g
/// the profile's glyphs, as they're asked for
private var glyphCache: [UInt32: Glyph?] = [:]
/// the bitmap glyph for [cp] (the profile's, 8 wide and 8 or 16 high, or a soft character the host loaded); nil: drawn with the font
func glyph(_ cp: UInt32) -> Glyph? {
// (soft characters can be loaded again: never kept)
let soft = cp >= 0xF0000
if !soft, let g = glyphCache[cp] { return g }
let c = Int32(bitPattern: cp)
let h = Int(bridge.glyphHeightOf(cp: c))
let g: Glyph? = h == 0 ? nil : Glyph(rows: (0..<h).map { Int(bridge.glyphRow(cp: c, row: Int32($0))) },
width: Int(bridge.glyphWidthOf(cp: c)))
if !soft { glyphCache[cp] = g }
return g
}
@@ -87,6 +98,8 @@ final class TerminalModel: ObservableObject {
if !replies.isEmpty { out(replies) }
let notes = bridge.takeMusic()
if !notes.isEmpty { music.play(notes) }
let status = bridge.statusText
if status != statusText { statusText = status }
revision = bridge.revision
}
+21 -9
View File
@@ -31,6 +31,15 @@ struct TerminalScreen: View {
.onTapGesture { focused = true }
.gesture(MagnificationGesture().onEnded { s in fontSize = min(24, max(7, fontSize * Double(s))) })
}
// a VT320's status line, below the screen (the screen a line shorter)
if !model.statusText.isEmpty {
Text(model.statusText)
.font(.system(size: 12, design: .monospaced))
.lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 4)
.background(Color(.secondarySystemBackground))
}
ExtraKeys(model: model)
}
.onAppear { model.setProfile(profile) }
@@ -115,7 +124,7 @@ private struct ScreenCanvas: View {
let w = CGFloat(run.cells) * cell.width
ctx.fill(Path(CGRect(x: x, y: y, width: w, height: cell.height)), with: .color(Color(argb: run.bg)))
if run.text.trimmingCharacters(in: .whitespaces).isEmpty { continue }
if model.bridge.bitmapGlyphs {
if model.bridge.bitmapGlyphs || (model.bridge.softGlyphs && run.text.unicodeScalars.contains { $0.value >= 0xF0000 }) {
drawGlyphs(ctx, run, y: y)
continue
}
@@ -143,20 +152,23 @@ extension ScreenCanvas {
let color = GraphicsContext.Shading.color(Color(argb: run.fg))
for (i, ch) in run.text.unicodeScalars.enumerated() {
let x = CGFloat(Int(run.col) + i) * cell.width
guard let rows = model.glyph(ch.value) else {
guard let glyph = model.glyph(ch.value) else {
if ch != " " { ctx.draw(Text(String(ch)).font(Font(cell.font as CTFont)).foregroundColor(Color(argb: run.fg)), at: CGPoint(x: x, y: y), anchor: .topLeading) }
continue
}
var path = Path()
for (r, bits) in rows.enumerated() where bits != 0 {
let gw = glyph.width
let high = 1 << (gw - 1)
for (r, bits) in glyph.rows.enumerated() where bits != 0 {
var c = 0
while c < 8 {
if bits & (0x80 >> c) == 0 { c += 1; continue }
while c < gw {
if bits & (high >> c) == 0 { c += 1; continue }
let start = c
while c < 8 && bits & (0x80 >> c) != 0 { c += 1 }
let h = CGFloat(rows.count)
path.addRect(CGRect(x: x + CGFloat(start) * cell.width / 8, y: y + CGFloat(r) * cell.height / h,
width: CGFloat(c - start) * cell.width / 8, height: cell.height / h))
while c < gw && bits & (high >> c) != 0 { c += 1 }
let h = CGFloat(glyph.rows.count)
let w = CGFloat(gw)
path.addRect(CGRect(x: x + CGFloat(start) * cell.width / w, y: y + CGFloat(r) * cell.height / h,
width: CGFloat(c - start) * cell.width / w, height: cell.height / h))
}
}
ctx.fill(path, with: color)
@@ -113,7 +113,7 @@ open class AnsiBbsInterpreter(t: TerminalEmulator, profile: AnsiBbsProfile) : Vt
/** in doorway mode, a key as NUL and its scan code (Alt with a letter its own); otherwise the VT sequences */
override fun keyOctets(k: Key, shift: Boolean, alt: Boolean, ctrl: Boolean): ByteArray? {
if (!doorway) return null
if (!doorway) return super.keyOctets(k, shift, alt, ctrl)
val code = SCAN_CODES[k] ?: return null
return byteArrayOf(0, code.toByte())
}
@@ -3,30 +3,28 @@
package org.dmodem.app.terminal
/**
* Glyphs drawn from bitmaps rather than a font: 8 pixels wide and
* [height] high (8 for the home computers' character ROMs, 16 for a VGA's),
* a row a byte, its leftmost pixel the high bit. What a profile whose
* terminal had its own character ROM (Commodore's, Atari's, a PC's) draws
* its cells with.
* Glyphs drawn from bitmaps rather than a font: [width] pixels wide (8,
* or up to 24 for a soft font a host loaded) and [height] high (8 for the
* home computers' character ROMs, 16 for a VGA's), a row an Int, its
* leftmost pixel bit [width] - 1. What a profile whose terminal had its
* own character ROM (Commodore's, Atari's, a PC's) draws its cells with,
* and a DEC terminal's soft characters (DECDLD).
*/
class BitmapFont(val height: Int, private val codes: IntArray, private val rows: ByteArray) {
/** the glyphs' width in pixels */
val width: Int get() = 8
class BitmapFont(val height: Int, private val codes: IntArray, private val rows: IntArray, val width: Int = 8) {
/** the glyphs it has */
val size: Int get() = codes.size
/** whether it has [cp]'s glyph */
fun has(cp: Int): Boolean = index(cp) >= 0
/** row [row] (0 top) of [cp]'s glyph, its leftmost pixel bit 7 (0 if it has none: a blank) */
/** row [row] (0 top) of [cp]'s glyph, its leftmost pixel bit [width] - 1 (0 if it has none: a blank) */
fun row(cp: Int, row: Int): Int {
val i = index(cp)
return if (i < 0 || row !in 0 until height) 0 else rows[i * height + row].toInt() and 0xff
return if (i < 0 || row !in 0 until height) 0 else rows[i * height + row]
}
/** whether [cp]'s glyph has pixel [col] (0 left) of row [row] (0 top) set */
fun pixel(cp: Int, row: Int, col: Int): Boolean = (row(cp, row) shr (7 - col)) and 1 != 0
fun pixel(cp: Int, row: Int, col: Int): Boolean = (row(cp, row) shr (width - 1 - col)) and 1 != 0
/** [cp]'s place in [codes] (they're in order), -1 if it isn't there */
private fun index(cp: Int): Int {
@@ -49,12 +47,12 @@ class BitmapFont(val height: Int, private val codes: IntArray, private val rows:
fun parse(height: Int, s: String): BitmapFont {
val entries = s.split(';').filter { it.isNotEmpty() }
val codes = IntArray(entries.size)
val rows = ByteArray(entries.size * height)
val rows = IntArray(entries.size * height)
for ((i, e) in entries.withIndex()) {
val colon = e.indexOf(':')
codes[i] = e.substring(0, colon).toInt(16)
for (r in 0 until height) {
rows[i * height + r] = e.substring(colon + 1 + 2 * r, colon + 3 + 2 * r).toInt(16).toByte()
rows[i * height + r] = e.substring(colon + 1 + 2 * r, colon + 3 + 2 * r).toInt(16)
}
}
return BitmapFont(height, codes, rows)
@@ -77,7 +77,7 @@ abstract class ByteControlInterpreter(t: TerminalEmulator, private val machine:
protected abstract fun charOf(b: Int): Int
/** what's written now looks like: the colour, reverse, the machine's attributes */
protected fun look(): Long =
protected open fun look(): Long =
Style.of(color, Style.DEFAULT_BG, (if (reverse) Style.INVERSE else 0) or extraAttrs)
/** the colour written in from now on */
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* The code extension a VT220 and later have (ISO 2022 as DEC used it):
* four sets, G0 to G3, designated into place; GL (0x21..0x7e) and GR
* (0xa1..0xfe) each showing one of them by a locking shift; and the
* single shifts SS2 and SS3, which take one character from G2 or G3.
* A VT100 has only G0 and G1 and SO/SI, which this does as well.
*/
class CharsetShifting {
/** G0 to G3 */
val g = arrayOf(GSet.ASCII, GSet.ASCII, GSet.LATIN1, GSet.LATIN1)
/** the G set GL shows (0 to 3) */
var gl = 0
private set
/** the G set GR shows (1 to 3) */
var gr = 2
private set
/** the G set the next character comes from (SS2 2, SS3 3), or -1 */
var single = -1
private set
/** the user-preferred supplemental set (DECAUPSS), what ESC ( < designates */
var preferred = GSet.LATIN1
/** the soft set the host loaded (DECDLD), what a G set holding [GSet.SOFT] shows */
val soft = SoftFont()
/** what DECSC keeps */
class Saved(val g: Array<GSet>, val gl: Int, val gr: Int)
/** the state for DECSC */
fun save() = Saved(g.copyOf(), gl, gr)
/** what [save] kept back (null: the state at the start) */
fun restore(s: Saved?) {
if (s == null) {
reset()
return
}
s.g.copyInto(g)
gl = s.gl
gr = s.gr
single = -1
}
/** G0 and G1 ASCII, G2 and G3 the preferred supplemental set, G0 in GL and G2 in GR */
fun reset() {
g[0] = GSet.ASCII
g[1] = GSet.ASCII
g[2] = preferred
g[3] = preferred
gl = 0
gr = 2
single = -1
}
/** a locking shift: GL to G[n] (SI 0, SO 1, LS2, LS3) */
fun lockGl(n: Int) {
gl = n
}
/** a locking shift: GR to G[n] (LS1R, LS2R, LS3R) */
fun lockGr(n: Int) {
gr = n
}
/** a single shift: the next graphic character from G[n] (SS2, SS3) */
fun singleShift(n: Int) {
single = n
}
/** G[slot] given [set] */
fun designate(slot: Int, set: GSet) {
g[slot] = set
}
/**
* a graphic code point as the sets show it: 0x20..0x7f through GL's
* set, 0xa0..0xff through GR's when [eightBit] (the line's octets are
* the code points, as Latin-1 decodes them); a single shift's set
* taking either for one character
*/
fun map(cp: Int, eightBit: Boolean): Int {
val s = single
single = -1
return when {
cp in 0x20..0x7f -> show(g[if (s >= 0) s else gl], cp)
eightBit && cp in 0xa0..0xff -> show(g[if (s >= 0) s else gr], cp - 0x80)
else -> cp
}
}
/** [cp] (0x20..0x7f) as [set] has it, the soft set's from [soft] */
private fun show(set: GSet, cp: Int): Int = if (set == GSet.SOFT) soft.map(cp) else set.map(cp)
/** the designator G[n] was given (the soft set's its own; one with none, ASCII's) */
fun designator(n: Int): String = (if (g[n] == GSet.SOFT) soft.designator else g[n].designator) ?: "B"
/** whether G[n] holds a 96-character set */
fun is96(n: Int): Boolean = if (g[n] == GSet.SOFT) soft.is96 else g[n].is96
}
@@ -105,30 +105,86 @@ class TermDecoder(var charset: TermCharset) {
}
/**
* A 94-character set a G0-G3 slot can hold: what its 0x21..0x7e stand for.
* [final] is the character that designates it (ESC ( B for ASCII); a set
* with none is chosen another way (a VT52's ESC F).
* A character set a G0-G3 slot can hold: what its 0x21..0x7e stand for
* (a 96-character set's 0x20..0x7f). [designators] are what follow the
* slot's intermediate to designate it (ESC ( B for ASCII, ESC ( % 5 for
* DEC Supplemental; a 96-character set's after ESC - . or /); a set with
* none is chosen another way (a VT52's ESC F). [level] is the VT level
* that has it (the national sets the VT220's NRCS, Portuguese the VT320's).
*/
enum class GSet(val final: Char?) {
ASCII('B'),
enum class GSet(val designators: List<String>, val is96: Boolean = false, val level: Int = 1, private val table: String? = null) {
ASCII(listOf("B")),
/** DEC Special Graphics: line drawing in 0x5f..0x7e */
DEC_GRAPHICS('0'),
DEC_GRAPHICS(listOf("0")),
/** the United Kingdom set: ASCII with £ for # */
UK('A'),
UK(listOf("A"), table = "#£"),
/** the VT52's graphics: fractions, scan lines, subscripts in 0x5e..0x7e (its ESC F) */
VT52_GRAPHICS(null);
VT52_GRAPHICS(emptyList()),
/** DEC Supplemental Graphics (the VT220's GR): Latin-1's letters with Œ, Ÿ, œ, ÿ and ¤ where DEC put them */
DEC_SUPPLEMENTAL(listOf("%5", "<"), level = 2),
/** DEC Technical (VT320): mathematics, Greek, arrows, and the pieces of big brackets, integrals and sums */
DEC_TECHNICAL(listOf(">"), level = 3),
/** ISO Latin-1's upper half (a 96-character set) */
LATIN1(listOf("A"), is96 = true, level = 3),
DUTCH(listOf("4"), level = 2, table = "#£@¾[ij\\½]|{¨|ƒ}¼~´"),
FINNISH(listOf("C", "5"), level = 2, table = "[Ä\\Ö]Å^Ü`é{ä|ö}å~ü"),
FRENCH(listOf("R", "f"), level = 2, table = "#£@à[°\\ç]§{é|ù}è~¨"),
FRENCH_CANADIAN(listOf("Q", "9"), level = 2, table = "@à[â\\ç]ê^î`ô{é|ù}è~û"),
GERMAN(listOf("K"), level = 2, table = "@§[Ä\\Ö]Ü{ä|ö}ü~ß"),
ITALIAN(listOf("Y"), level = 2, table = "#£@§[°\\ç]é`ù{à|ò}è~ì"),
NORWEGIAN_DANISH(listOf("E", "6", "`"), level = 2, table = "@Ä[Æ\\Ø]Å^Ü`ä{æ|ø}å~ü"),
SPANISH(listOf("Z"), level = 2, table = "#£@§[¡\\Ñ]¿{°|ñ}ç"),
SWEDISH(listOf("H", "7"), level = 2, table = "@É[Ä\\Ö]Å^Ü`é{ä|ö}å~ü"),
SWISS(listOf("="), level = 2, table = "#ù@à[é\\ç]ê^î_è`ô{ä|ö}ü~û"),
PORTUGUESE(listOf("%6"), level = 3, table = "[Ã\\Ç]Õ{ã|ç}õ"),
/** the soft set the host loaded (DECDLD): designated by the designator it gave, mapped by [CharsetShifting] */
SOFT(emptyList(), level = 2);
/** [cp] as this set has it */
/** the national set's replacements: each ASCII character and what it is here */
private val replaced: Map<Int, Int> by lazy {
val t = table ?: return@lazy emptyMap()
(t.indices step 2).associate { t[it].code to t[it + 1].code }
}
/** the designator a slot is given this set by (its first) */
val designator: String? get() = designators.firstOrNull()
/** [cp] (0x20..0x7f, as GL has it) as this set has it */
fun map(cp: Int): Int = when (this) {
ASCII -> cp
DEC_GRAPHICS -> TerminalEmulator.decGraphics(cp)
UK -> if (cp == '#'.code) '£'.code else cp
VT52_GRAPHICS -> if (cp in 0x5e..0x7e) VT52[cp - 0x5e] else cp
DEC_SUPPLEMENTAL -> if (cp in 0x21..0x7e) SUPPLEMENTAL_ODD[cp] ?: (cp + 0x80) else cp
DEC_TECHNICAL -> if (cp in 0x21..0x7e) TECHNICAL[cp - 0x21].code else cp
LATIN1 -> if (cp in 0x20..0x7f) cp + 0x80 else cp
else -> replaced[cp] ?: cp
}
companion object {
/** the set [final] designates (ESC ( [final]), or null for one not known */
fun byFinal(final: Int): GSet? = entries.firstOrNull { it.final?.code == final }
/** the set of the size [is96] that [designator] (ESC ( [designator]) names, or null for one not known */
fun byDesignator(designator: String, is96: Boolean = false): GSet? =
entries.firstOrNull { it.is96 == is96 && designator in it.designators }
/** the set [final] designates as a 94-character set (ESC ( [final]), or null for one not known */
fun byFinal(final: Int): GSet? = byDesignator(final.toChar().toString())
/** where DEC Supplemental isn't Latin-1: ¤ at 0x28, Œ Ÿ œ ÿ, the codes it left empty (shown blank) */
private val SUPPLEMENTAL_ODD: Map<Int, Int> = mapOf(
0x28 to 0xa4, 0x57 to 0x152, 0x5d to 0x178, 0x77 to 0x153, 0x7d to 0xff,
) + listOf(0x24, 0x26, 0x2c, 0x2d, 0x2e, 0x2f, 0x34, 0x38, 0x3e, 0x50, 0x5e, 0x70, 0x7e).associateWith { 0x20 }
/**
* DEC Technical, 0x21..0x7e (as xterm draws it: the brackets', the
* integral's and the sum's pieces as Unicode's nearest; the codes DEC
* left empty blank).
*/
private const val TECHNICAL =
"⎷┌─⌠⌡│⎡⎣⎤⎦⎛⎝⎞⎠⎨⎬" +
"⎲⎳╲╱⌝⌟⟩ ≤≠≥∫∴" +
"∝∞÷Δ∇ΦΓ∼≃Θ×Λ⇔⇒≡Π" +
"Ψ Σ √ΩΞΥ⊂⊃∩∪∧∨¬" +
"αβχδεφγηιθκλ ν∂π" +
"ψρστ ƒωξυζ←↑→↓"
/**
* The VT52's graphics, 0x5e..0x7e (DECscope User's Manual EK-VT5X-OP-001,
@@ -12,7 +12,7 @@ sealed class BarKey {
abstract val label: String
/** a key that isn't a character; [repeat]: held down, it repeats */
data class Send(val key: Key, override val label: String, val repeat: Boolean = false) : BarKey()
data class Send(val key: Key, override val label: String, val repeat: Boolean = false, val shift: Boolean = false) : BarKey()
/** text typed */
data class Type(val text: String, override val label: String = text) : BarKey()
@@ -83,6 +83,52 @@ object KeyBars {
),
)
/** an LK201's top row past F5: F6-F20 (F15 Help, F16 Do), Find and Select */
val LK201_FUNCTION = KeyBarPage(
"F6+",
listOf(
(5 until 13).map { fn(it) },
listOf(fn(13), BarKey.Send(Key.F15, "HELP"), BarKey.Send(Key.F16, "DO")) + (16 until 20).map { fn(it) } +
BarKey.Send(Key.FIND, "FIND"),
listOf(BarKey.Send(Key.SELECT, "SEL"), BarKey.Send(Key.INSERT, "INS"), BarKey.Send(Key.DELETE, "REM"), BarKey.NextPage),
),
)
/** F6-F20 with Shift: the keys the host loaded (DECUDK) */
val USER_DEFINED = KeyBarPage(
"UDK",
listOf(
(5 until 13).map { fn(it, shift = true) },
(13 until 20).map { fn(it, shift = true) } + BarKey.NextPage,
),
)
/** Prestel's keypad: *, # (that sends), the digits, and the cursor keys */
val VIEWDATA = KeyBarPage(
"VDT",
listOf(
listOf(BarKey.Type("*"), BarKey.Type("#"), BarKey.Type("*0#", "*0#"), BarKey.Type("*#", "BACK")) +
listOf(BarKey.Send(Key.UP, "↑", repeat = true), BarKey.Send(Key.BACKSPACE, "DEL", repeat = true)),
listOf(BarKey.Ctrl, BarKey.Send(Key.LEFT, "←", repeat = true), BarKey.Send(Key.DOWN, "↓", repeat = true),
BarKey.Send(Key.RIGHT, "→", repeat = true), BarKey.Send(Key.ESCAPE, "ESC"), BarKey.NextPage),
),
)
/** the Minitel's function keys (SEP and the key's code) */
val MINITEL = KeyBarPage(
"MTL",
listOf(
listOf(
minitel(0x41, "ENVOI"), minitel(0x42, "RETOUR"), minitel(0x48, "SUITE"), minitel(0x43, "RÉPÉT"),
minitel(0x47, "CORR"),
),
listOf(
minitel(0x46, "SOMM"), minitel(0x44, "GUIDE"), minitel(0x45, "ANNUL"), minitel(0x49, "CX/FIN"),
BarKey.NextPage,
),
),
)
/** a Commodore's: RUN/STOP, CLR/HOME, INST/DEL, RVS ON/OFF, C=, the cursor keys, its symbols */
val COMMODORE_MAIN = KeyBarPage(
"C=",
@@ -150,8 +196,15 @@ object KeyBars {
/** a DEC terminal's: the standard ones and its keypad */
val DEC = STANDARD + DEC_KEYPAD
/** F[n + 1] */
private fun fn(n: Int) = BarKey.Send(Key.entries[Key.F1.ordinal + n], "F${n + 1}")
/** a VT220's and later: a DEC terminal's, the LK201's other function keys, and the user-defined ones */
val LK201 = DEC + LK201_FUNCTION + USER_DEFINED
/** F[n + 1] (with Shift: ⇧ before its name) */
private fun fn(n: Int, shift: Boolean = false) =
BarKey.Send(Key.entries[Key.F1.ordinal + n], (if (shift) "⇧" else "") + "F${n + 1}", shift = shift)
/** the Minitel's key [code] (sent after SEP) */
private fun minitel(code: Int, label: String) = BarKey.Octets("\u0013" + code.toChar(), label)
/** the keypad's [n] */
private fun kp(n: Int) = BarKey.Send(Key.entries[Key.KP_0.ordinal + n], "$n")
@@ -6,6 +6,8 @@ package org.dmodem.app.terminal
enum class Key {
UP, DOWN, RIGHT, LEFT, HOME, END, PAGE_UP, PAGE_DOWN, INSERT, DELETE,
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
/** an LK201's F13-F20 (F15 its Help, F16 its Do), and its Find and Select */
F13, F14, F15, F16, F17, F18, F19, F20, FIND, SELECT,
TAB, ENTER, BACKSPACE, ESCAPE,
/** the DEC keypad: PF1-PF4 above it, its digits, minus, comma, period and Enter */
PF1, PF2, PF3, PF4,
@@ -86,6 +88,16 @@ class KeyEncoder {
Key.F10 -> tilde(21)
Key.F11 -> tilde(23)
Key.F12 -> tilde(24)
Key.F13 -> tilde(25)
Key.F14 -> tilde(26)
Key.F15 -> tilde(28)
Key.F16 -> tilde(29)
Key.F17 -> tilde(31)
Key.F18 -> tilde(32)
Key.F19 -> tilde(33)
Key.F20 -> tilde(34)
Key.FIND -> tilde(1)
Key.SELECT -> tilde(4)
Key.TAB -> if (shift) "\u001b[Z" else prefix + "\t"
Key.ENTER -> prefix + enter.bytes
Key.BACKSPACE -> prefix + (if (ctrl) "\u0008" else backspace.code.toChar().toString())
@@ -0,0 +1,382 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A Minitel (France Télécom's Teletel, CEPT-2) as MiniPavi's 3615
* services expect it: 40x25, row 0 its status row; text (G0) and mosaics
* (G1, by SO) with the accents' SS2; its ESC attributes (colours, flash,
* sizes drawn single, inverse, conceal; the background and the mosaics'
* separation taking effect at the next space or mosaic, as CEPT-2's zones
* do); the CSI cursor and erase commands; the PRO1-PRO3 protocol
* commands (it answers who it is); the 80-column Mixte mode; and the
* Téléinformatique mode, a VT100. Its keys: Envoi, Retour, Suite,
* Annulation, Sommaire, Guide, Correction, Répétition, Connexion/Fin.
*/
open class MinitelProfile : VideotexProfile() {
override val id get() = "minitel"
override val label get() = "Minitel"
override val term get() = "minitel"
override val telnetType get() = "MINITEL"
override val rows get() = 25
override val keyBar: List<KeyBarPage> get() = listOf(KeyBars.MINITEL, KeyBars.MAIN)
/** a [MinitelInterpreter] */
override fun interpreter(t: TerminalEmulator): TerminalInterpreter = MinitelInterpreter(t, this)
}
/** The Minitel's videotex mode, and its Téléinformatique mode handed to a VT100 */
open class MinitelInterpreter(t: TerminalEmulator, private val m: MinitelProfile) : VideotexInterpreter(t, m) {
private var bg = 0
/** the background asked for, taken at the next delimiter (a space, a mosaic) */
private var nextBg = 0
private var flash = false
private var conceal = false
/** the mosaics separated (G1's underline), from the next delimiter on */
private var separated = false
private var nextSeparated = false
/** G1 (the mosaics) in use, by SO */
private var mosaic = false
/** the screen scrolls (PRO2 ROULEAU), rather than the cursor going back to row 1 */
private var scrolling = false
/** Mixte mode: 80 columns of text */
private var mixte = false
/** the last character shown, for REP */
private var last = ' '.code
// what's half read: an ESC sequence, US's address, REP's count, SS2's accent, a CSI's parameters
private var pending = ByteArray(0)
private var want = 0
private var expecting = Expect.NONE
private enum class Expect { NONE, ESC, PRO, US, REP, SS2, ACCENT, CSI, SEP }
private var accent = 0
private val csi = StringBuilder()
/** Téléinformatique mode: a VT100 reads what comes, until ESC [ ? { */
private var teleinfo: VtInterpreter? = null
/** how much of the way out of Téléinformatique mode has come */
private var exitMatch = 0
init {
at(0, 1)
}
/** the row the cursor moves in from: row 1 (row 0 is the status row) */
override val firstRow: Int get() = 1
/** as at the start: videotex mode, white on black, G0, page mode, the cursor at row 1 */
override fun reset() {
super.reset()
teleinfo = null
mixte = false
scrolling = false
attributes()
expecting = Expect.NONE
at(0, 1)
}
/** the attributes as a row starts: white on black, steady, revealed, G0, contiguous */
private fun attributes() {
color = 7
bg = 0
nextBg = 0
flash = false
conceal = false
reverse = false
separated = false
nextSeparated = false
mosaic = false
t.style = look()
}
/** what's written looks like: the colour, the zone's background, flash, inverse, conceal */
override fun look(): Long = Style.of(
color, bg,
(if (reverse) Style.INVERSE else 0) or (if (flash) Style.BLINK else 0) or (if (conceal) Style.INVISIBLE else 0),
)
/** an octet: to the VT100 in Téléinformatique mode, else the rest of a sequence, a control or a character */
override fun process(cp: Int) {
val b = cp and 0x7f
teleinfo?.let { vt ->
if (leavesTeleinfo(b)) return
vt.process(b)
return
}
if (expecting != Expect.NONE) {
sequence(b)
return
}
if (control(b)) return
if (b >= 0x20) show(b)
}
/** whether [b] ends ESC [ ? { (Téléinformatique mode left: the videotex screen back) */
private fun leavesTeleinfo(b: Int): Boolean {
val exit = "\u001b[?{"
exitMatch = if (b == exit[exitMatch].code) exitMatch + 1 else if (b == 0x1b) 1 else 0
if (exitMatch < exit.length) return false
exitMatch = 0
teleinfo = null
t.requestedColumns = m.columns
t.requestedRows = m.rows
clear()
attributes()
at(0, 1)
return true
}
/** the Minitel's controls: true if [b] was one */
override fun control(b: Int): Boolean {
when (b) {
0x00 -> {}
// (DEL: G1's full block, nothing in G0)
0x7f -> if (mosaic) show(b)
0x07 -> bell()
0x08 -> back()
0x09 -> forward()
0x0a -> lineDown()
0x0b -> lineUp()
0x0c -> {
clear()
attributes()
at(0, 1)
}
0x0d -> at(0, t.cursorY)
0x0e -> if (!mixte) { mosaic = true; separated = false; nextSeparated = false }
0x0f -> mosaic = false
0x11 -> t.cursorVisible = true
0x14 -> t.cursorVisible = false
0x12 -> expecting = Expect.REP
0x13 -> expecting = Expect.SEP
0x18 -> {
t.style = Style.erased(look())
t.eraseLine(0)
t.style = look()
}
0x19 -> expecting = Expect.SS2
0x1b -> expecting = Expect.ESC
0x1e -> {
attributes()
at(0, 1)
}
0x1f -> { pending = ByteArray(0); expecting = Expect.US }
else -> return b < 0x20
}
return true
}
/** octet [b] of the sequence under way */
private fun sequence(b: Int) {
val e = expecting
expecting = Expect.NONE
when (e) {
Expect.ESC -> esc(b)
Expect.PRO -> {
pending += b.toByte()
if (pending.size < want) expecting = Expect.PRO else protocol(pending)
}
Expect.US -> {
pending += b.toByte()
if (pending.size < 2) expecting = Expect.US else address(pending[0].toInt(), pending[1].toInt())
}
Expect.REP -> repeat((b - 0x40).coerceIn(0, 63)) { show(last) }
Expect.SEP -> {}
Expect.SS2 -> supplementary(b)
Expect.ACCENT -> show(accented(b, accent))
Expect.CSI -> {
if (b in 0x30..0x3f) {
csi.append(b.toChar())
expecting = Expect.CSI
} else {
command(b)
}
}
Expect.NONE -> {}
}
}
/** US's address: row and column as 0x40 + n, or as two digits each (US 3/x) */
private fun address(a: Int, b: Int) {
val (row, col) = if (a in 0x30..0x32) {
((a - 0x30) * 10 + (b - 0x30)) to 1
} else {
(a - 0x40) to (b - 0x40)
}
attributes()
at((col - 1).coerceIn(0, t.cols - 1), row.coerceIn(0, t.rows - 1))
}
/** the code after ESC: an attribute (0x40-0x5f), CSI, a protocol command, the cursor's position asked */
private fun esc(b: Int) {
when (b) {
in 0x40..0x47 -> color = b - 0x40
in 0x50..0x57 -> nextBg = b - 0x50
0x48 -> flash = true
0x49 -> flash = false
// (sizes: drawn single)
0x4c, 0x4d, 0x4e, 0x4f -> {}
0x58 -> conceal = true
0x5f -> conceal = false
0x59 -> nextSeparated = false
0x5a -> nextSeparated = true
0x5c -> reverse = false
0x5d -> reverse = true
0x5b -> { csi.setLength(0); expecting = Expect.CSI }
0x39, 0x3a, 0x3b -> { pending = ByteArray(0); want = b - 0x38; expecting = Expect.PRO }
// the cursor's place asked: US, its row and column
0x61 -> t.reply("\u001f${(0x40 + t.cursorY).toChar()}${(0x41 + t.cursorX).toChar()}")
}
t.style = look()
}
/** a protocol command (PRO1-PRO3)'s [p]: who it is (ENQROM), scrolling, Mixte and Téléinformatique modes; the rest taken */
private fun protocol(p: ByteArray) {
val a = p[0].toInt()
val b = p.getOrElse(1) { 0 }.toInt()
when {
p.size == 1 && a == 0x7b -> t.reply(IDENTITY)
p.size == 2 && a == 0x69 && b == 0x43 -> scrolling = true
p.size == 2 && a == 0x6a && b == 0x43 -> scrolling = false
p.size == 2 && a == 0x32 && b == 0x7d -> {
mixte = true
mosaic = false
t.requestedColumns = 80
}
p.size == 2 && a == 0x32 && b == 0x7e -> {
mixte = false
t.requestedColumns = m.columns
}
p.size == 2 && a == 0x31 && b == 0x7d -> {
// Téléinformatique: an 80x24 VT100
t.requestedColumns = 80
t.requestedRows = 24
teleinfo = VtInterpreter(t, TELEINFO)
exitMatch = 0
t.style = Style.NORMAL
}
}
}
/** a CSI's command [final] with the parameters gathered: the cursor's moves, erasing, insert and delete */
private fun command(final: Int) {
val ps = csi.toString().split(';').map { it.toIntOrNull() ?: 0 }
/** parameter [i], [d] when missing or 0 */
fun p(i: Int, d: Int) = ps.getOrNull(i)?.takeIf { it != 0 } ?: d
t.style = Style.erased(look())
when (final.toChar()) {
'A' -> at(t.cursorX, (t.cursorY - p(0, 1)).coerceAtLeast(firstRow))
'B' -> at(t.cursorX, t.cursorY + p(0, 1))
'C' -> at(t.cursorX + p(0, 1), t.cursorY)
'D' -> at(t.cursorX - p(0, 1), t.cursorY)
'H' -> at(p(1, 1) - 1, p(0, 1))
'J' -> t.eraseDisplay(ps.getOrNull(0) ?: 0)
'K' -> t.eraseLine(ps.getOrNull(0) ?: 0)
'P' -> t.deleteChars(p(0, 1))
'@' -> t.insertChars(p(0, 1))
'L' -> t.insertLines(p(0, 1))
'M' -> t.deleteLines(p(0, 1))
'h' -> if (ps.getOrNull(0) == 4) t.insertMode = true
'l' -> if (ps.getOrNull(0) == 4) t.insertMode = false
}
t.style = look()
}
/** SS2's G2 character [b]: an accent to put on the next letter, or a symbol */
private fun supplementary(b: Int) {
if (b in 0x41..0x4b) {
accent = b
expecting = Expect.ACCENT
return
}
G2[b]?.let { show(it) }
}
/** letter [b] with accent [a] (SS2 A grave, B acute, C circumflex, H diaeresis, K cedilla), or the letter */
private fun accented(b: Int, a: Int): Int {
if (a == 0x4b) return if (b == 'c'.code) 'ç'.code else if (b == 'C'.code) 'Ç'.code else b
val i = ACCENTED_BASE.indexOf(b.toChar())
val letters = TYPED_ACCENTS.firstOrNull { it.first == a }?.second
return if (i < 0 || letters == null) b else letters[i].code
}
/** a character shown: a mosaic in G1 (0x40-0x5f its letters), else G0's; a space or a mosaic takes the zone's attributes */
private fun show(b: Int) {
val isMosaic = mosaic && b < 0x80 && (b < 0x40 || b >= 0x60)
if (isMosaic || b == ' '.code) {
bg = nextBg
separated = nextSeparated
}
val c = if (isMosaic) Mosaic.code(Mosaic.bits(b), separated) else b
last = b
t.style = look()
t.print(c)
if (t.pendingWrap) {
t.carriageReturn()
lineDown()
}
}
/** the next row (from the last: row 1 again, or the screen scrolled in ROULEAU) */
override fun lineDown() {
if (t.cursorY >= t.rows - 1 && scrolling) {
val x = t.cursorX
t.index()
at(x, t.cursorY)
} else {
super.lineDown()
}
}
/** (characters are [show]n, not looked up) */
override fun charOf(b: Int): Int = b
/** Enter as Envoi, Backspace as Correction (SEP and the key's code); the rest as a VT100's (the cursor keys' CSI) */
override fun keyOctets(k: Key, shift: Boolean, alt: Boolean, ctrl: Boolean): ByteArray? {
if (teleinfo != null) return null
return when (k) {
Key.ENTER -> byteArrayOf(0x13, 0x41)
Key.BACKSPACE -> byteArrayOf(0x13, 0x47)
else -> null
}
}
/** an accented letter typed as SS2, its accent and the letter; the rest as ASCII */
override fun charOctets(cp: Int, alt: Boolean, ctrl: Boolean): ByteArray? {
if (teleinfo != null || ctrl || alt) return null
if (cp < 0x80) return null
for ((accent, letters) in TYPED_ACCENTS) {
val i = letters.indexOf(cp.toChar())
if (i >= 0) return byteArrayOf(0x19, accent.toByte(), ACCENTED_BASE[i % ACCENTED_BASE.length].code.toByte())
}
if (cp == 'ç'.code) return byteArrayOf(0x19, 0x4b, 'c'.code.toByte())
G2.entries.firstOrNull { it.value == cp }?.let { return byteArrayOf(0x19, it.key.toByte()) }
return null
}
companion object {
/** ENQROM's answer: a Telic Minitel 2 */
private const val IDENTITY = "\u0001Cv;\u0004"
/** the VT100 Téléinformatique mode is */
private val TELEINFO = Vt100Profile()
/** the letters an accent goes on, lower case then upper */
private const val ACCENTED_BASE = "aeuioAEUIO"
/** the accents as typed: SS2's accent and the accented letters (in [ACCENTED_BASE]'s order) */
private val TYPED_ACCENTS = listOf(
0x41 to "àèùìòÀÈÙÌÒ", 0x42 to "áéúíóÁÉÚÍÓ", 0x43 to "âêûîôÂÊÛÎÔ", 0x48 to "äëüïöÄËÜÏÖ",
)
/** G2's symbols, by SS2's code */
private val G2 = mapOf(
0x23 to '£'.code, 0x24 to '$'.code, 0x26 to '#'.code, 0x27 to '§'.code,
0x2c to '←'.code, 0x2d to '↑'.code, 0x2e to '→'.code, 0x2f to '↓'.code,
0x30 to '°'.code, 0x31 to '±'.code, 0x38 to '÷'.code,
0x3c to '¼'.code, 0x3d to '½'.code, 0x3e to '¾'.code,
0x6a to 'Œ'.code, 0x7a to 'œ'.code, 0x7b to 'ß'.code,
)
}
}
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* Teletext's and videotex's block graphics: a cell split into 2x3 blocks,
* six bits saying which are lit, contiguous (the blocks touching) or
* separated (each with a gap round it). Drawn from bitmaps the app makes
* (not a font's sextants, which have no separated set), kept as code
* points of their own in plane 15.
*/
object Mosaic {
/** the contiguous mosaics' code points: this and the six bits; the separated ones' from [BASE] + 0x40 */
const val BASE = 0xf1000
/** the glyphs' size: each block 3 pixels wide and 3 high */
private const val W = 6
private const val H = 9
/** every mosaic but the blank one, contiguous then separated */
val font: BitmapFont by lazy {
val codes = ArrayList<Int>()
val rows = ArrayList<Int>()
for (sep in listOf(false, true)) {
for (mask in 1 until 64) {
codes.add(code(mask, sep))
for (y in 0 until H) rows.add(row(mask, sep, y))
}
}
BitmapFont(H, codes.toIntArray(), rows.toIntArray(), W)
}
/** the code point of the mosaic with blocks [mask] lit (bit 0 top left, 1 top right, 2 and 3 the middle, 4 and 5 the bottom), space for none */
fun code(mask: Int, separated: Boolean): Int =
if (mask and 0x3f == 0) ' '.code else BASE + (mask and 0x3f) + (if (separated) 0x40 else 0)
/**
* a teletext mosaic character's six bits (0x20-0x3f, 0x60-0x7f): its
* low five bits, and bit 6 for the bottom right block
*/
fun bits(c: Int): Int = (c and 0x1f) or ((c and 0x40) shr 1)
/** pixel row [y] of mosaic [mask], the leftmost pixel bit 5 */
private fun row(mask: Int, sep: Boolean, y: Int): Int {
val band = y / 3
// (separated: each block's last row and column dark)
if (sep && y % 3 == 2) return 0
var r = 0
if (mask and (1 shl (band * 2)) != 0) r = r or (if (sep) 0b110000 else 0b111000)
if (mask and (1 shl (band * 2 + 1)) != 0) r = r or (if (sep) 0b000110 else 0b000111)
return r
}
}
@@ -0,0 +1,148 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A VT420's rectangular area operations on [t]'s screen: copy (DECCRA),
* erase (DECERA, DECSERA), fill (DECFRA), attributes changed or reversed
* (DECCARA, DECRARA, as a rectangle or as the stream of characters
* between two corners: DECSACE) and the checksum (DECRQCRA). An area is
* its top, left, bottom and right, from 1, relative to the margins in
* origin mode, as the sequences give it.
*/
class Rectangles(private val t: TerminalEmulator) {
/** DECSACE: DECCARA and DECRARA change the stream from one corner to the other (false) or the rectangle (true) */
var rectangle = false
/** an area as the screen's rows and columns (from 0, inclusive), or null when it is empty */
class Area(val top: Int, val left: Int, val bottom: Int, val right: Int)
/**
* the area [p] gives from index [at] (Pt; Pl; Pb; Pr, each defaulting to
* the page's edge), from the margins in origin mode, cut to the screen;
* as a [stream] its left can be right of its right on lines after the first
*/
fun area(p: (Int, Int) -> Int, at: Int = 0, stream: Boolean = false): Area? {
val oy = if (t.originMode) t.top else 0
val ox = if (t.originMode) t.left else 0
val maxY = if (t.originMode) t.bottom else t.rows - 1
val maxX = if (t.originMode) t.right else t.cols - 1
val top = (p(at, 1) - 1 + oy).coerceIn(0, maxY)
val left = (p(at + 1, 1) - 1 + ox).coerceIn(0, maxX)
val bottom = (p(at + 2, maxY - oy + 1) - 1 + oy).coerceIn(0, maxY)
val right = (p(at + 3, maxX - ox + 1) - 1 + ox).coerceIn(0, maxX)
return if (top > bottom || left > right && !(stream && top < bottom)) null else Area(top, left, bottom, right)
}
/** DECCRA: [a]'s cells copied with its top left at row [toY], column [toX] (from 0), cut to the screen */
fun copy(a: Area, toY: Int, toX: Int) {
val h = minOf(a.bottom - a.top + 1, t.rows - toY)
val w = minOf(a.right - a.left + 1, t.cols - toX)
if (h <= 0 || w <= 0) return
// (taken first, so an area copied over itself is right)
val chars = Array(h) { y -> IntArray(w) { x -> t.line(a.top + y).chars[a.left + x] } }
val styles = Array(h) { y -> LongArray(w) { x -> t.line(a.top + y).styles[a.left + x] } }
for (y in 0 until h) {
val l = t.line(toY + y)
for (x in 0 until w) l.set(toX + x, chars[y][x], styles[y][x])
}
}
/** DECERA (DECSERA if [selective]: the cells DECSCA protects kept): [a]'s cells blanked */
fun erase(a: Area, selective: Boolean) {
val e = Style.erased(t.style)
for (y in a.top..a.bottom) {
val l = t.line(y)
for (x in a.left..a.right) {
if (selective && Style.attrs(l.styles[x]) and Style.PROTECTED != 0) continue
l.set(x, 0, e)
}
}
}
/** DECFRA: [a] filled with [cp] in the current rendition */
fun fill(a: Area, cp: Int) {
for (y in a.top..a.bottom) {
val l = t.line(y)
for (x in a.left..a.right) l.set(x, cp, t.style)
}
}
/**
* DECCARA ([reverse] false: the SGR attributes [ps] set or cleared; 0
* all of them off) or DECRARA (true: those [ps] names reversed) over
* [a], as a rectangle or a stream as [rectangle] says
*/
fun attributes(a: Area, ps: List<Int>, reverse: Boolean) {
var on = 0
var off = 0
for (n in ps.ifEmpty { listOf(0) }) {
when (n) {
0 -> off = off or CHANGEABLE
1 -> on = on or Style.BOLD
4 -> on = on or Style.UNDERLINE
5 -> on = on or Style.BLINK
7 -> on = on or Style.INVERSE
8 -> on = on or Style.INVISIBLE
22 -> off = off or Style.BOLD
24 -> off = off or Style.UNDERLINE
25 -> off = off or Style.BLINK
27 -> off = off or Style.INVERSE
28 -> off = off or Style.INVISIBLE
}
}
each(a) { l, x ->
val s = l.styles[x]
var at = Style.attrs(s)
at = if (reverse) at xor ((on or off) and CHANGEABLE) else (at and off.inv()) or on
l.styles[x] = Style.withAttrs(s, at)
}
}
/** DECRQCRA's checksum of [a]: the characters (a blank as a space) and their attributes summed, negated, 16 bits */
fun checksum(a: Area): Int {
var sum = 0
for (y in a.top..a.bottom) {
val l = t.line(y)
for (x in a.left..a.right) {
val cp = l.chars[x].let { if (it <= 0) ' '.code else it }
val at = Style.attrs(l.styles[x])
sum += cp
if (at and Style.PROTECTED != 0) sum += 0x04
if (at and Style.INVISIBLE != 0) sum += 0x08
if (at and Style.ANY_UNDERLINE != 0) sum += 0x10
if (at and Style.INVERSE != 0) sum += 0x20
if (at and Style.BLINK != 0) sum += 0x40
if (at and Style.BOLD != 0) sum += 0x80
}
}
return (-sum) and 0xffff
}
/** DECIC: [n] blank columns in at column [at], within the margins and the scrolling region (the right margin's pushed off) */
fun insertColumns(at: Int, n: Int) {
val e = Style.erased(t.style)
for (y in t.top..t.bottom) t.line(y).insertCells(at, n, e, t.right + 1)
}
/** DECDC: [n] columns at column [at] deleted, within the margins and the region (blank ones in at the right margin) */
fun deleteColumns(at: Int, n: Int) {
val e = Style.erased(t.style)
for (y in t.top..t.bottom) t.line(y).deleteCells(at, n, e, t.right + 1)
}
/** [f] on each of [a]'s cells: its rectangle's, or (as a stream) from its first corner along the lines to its second */
private fun each(a: Area, f: (Line, Int) -> Unit) {
for (y in a.top..a.bottom) {
val l = t.line(y)
val from = if (rectangle || y == a.top) a.left else 0
val to = if (rectangle || y == a.bottom) a.right else t.cols - 1
for (x in from..to) f(l, x)
}
}
companion object {
/** the attributes DECCARA and DECRARA change */
private const val CHANGEABLE = Style.BOLD or Style.UNDERLINE or Style.BLINK or Style.INVERSE or Style.INVISIBLE
}
}
@@ -26,6 +26,8 @@ object Style {
/** SGR 4:3 (and the dotted and dashed ones, 4:4 and 4:5) */
const val CURLY_UNDERLINE = 512
const val OVERLINE = 1024
/** DECSCA's: not erased by DECSED and DECSEL (not drawn: it isn't a rendition) */
const val PROTECTED = 2048
/** any of the underlines */
const val ANY_UNDERLINE = UNDERLINE or DOUBLE_UNDERLINE or CURLY_UNDERLINE
@@ -141,24 +143,26 @@ class Line(cols: Int, style: Long = Style.NORMAL) {
size = LineSize.SINGLE
}
/** [n] blank cells at [at], those at the end pushed off */
fun insertCells(at: Int, n: Int, style: Long) {
if (at >= cols || n <= 0) return
val k = minOf(n, cols - at)
chars.copyInto(chars, at + k, at, cols - k)
styles.copyInto(styles, at + k, at, cols - k)
extras?.let { it.copyInto(it, at + k, at, cols - k) }
/** [n] blank cells at [at], those at [end] (the line's end, or a right margin's) pushed off */
fun insertCells(at: Int, n: Int, style: Long, end: Int = cols) {
val e = end.coerceAtMost(cols)
if (at >= e || n <= 0) return
val k = minOf(n, e - at)
chars.copyInto(chars, at + k, at, e - k)
styles.copyInto(styles, at + k, at, e - k)
extras?.let { it.copyInto(it, at + k, at, e - k) }
clear(at, at + k, style)
}
/** [n] cells at [at] removed, blank ones in from the end */
fun deleteCells(at: Int, n: Int, style: Long) {
if (at >= cols || n <= 0) return
val k = minOf(n, cols - at)
chars.copyInto(chars, at, at + k, cols)
styles.copyInto(styles, at, at + k, cols)
extras?.let { it.copyInto(it, at, at + k, cols) }
clear(cols - k, cols, style)
/** [n] cells at [at] removed, blank ones in from [end] (the line's end, or a right margin's) */
fun deleteCells(at: Int, n: Int, style: Long, end: Int = cols) {
val e = end.coerceAtMost(cols)
if (at >= e || n <= 0) return
val k = minOf(n, e - at)
chars.copyInto(chars, at, at + k, e)
styles.copyInto(styles, at, at + k, e)
extras?.let { it.copyInto(it, at, at + k, e) }
clear(e - k, e, style)
}
/** [n] columns wide: cut or padded with blank cells (a wide character cut at the edge gone) */
@@ -0,0 +1,123 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A soft character set a host loaded (DECDLD, a VT220's and later): its
* characters' bitmaps, sent as sixels, and the designator (Dscs) that
* puts it in a G set. Its characters are kept as code points of their
* own in a private use plane ([BASE] + the character, 0x20..0x7f), so a
* cell holding one is told from text, and drawn from [font].
*/
class SoftFont {
/** the designator the host gave it (ESC ( and this designates it), or null before any is loaded */
var designator: String? = null
private set
/** a 96-character set (DECDLD's Pcss 1), or 94 */
var is96 = false
private set
/** the characters' cell, in pixels */
var width = 8
private set
var height = 10
private set
private val glyphs = HashMap<Int, IntArray>()
/** the glyphs as a font of [BASE]'s code points, or null when there are none */
var font: BitmapFont? = null
private set
/**
* a DECDLD: [params] (Pfn; Pcn; Pe; Pcmw; Pss; Pt; Pcmh; Pcss) and
* [data], the designator and then the glyphs' sixels (each glyph's
* columns, its bands of six rows parted by /, the glyphs by ;)
*/
fun load(params: IntArray, data: String) {
/** parameter [i], 0 when missing */
fun p(i: Int) = params.getOrElse(i) { 0 }
// the designator: intermediates, then a final 0x30..0x7e
var i = 0
while (i < data.length && data[i].code in 0x20..0x2f) i++
if (i >= data.length || data[i].code !in 0x30..0x7e) return
val dscs = data.substring(0, i + 1)
val w = when (val m = p(3)) {
0 -> if (p(4) == 2) 9 else 15
1 -> 15
2 -> 5
3 -> 6
4 -> 7
else -> m
}.coerceIn(1, MAX)
// (a VT320's cell is 15x12 at 80 columns, a VT220's 10 high)
val h = (if (p(6) == 0) (if (w >= 15) 12 else 10) else p(6)).coerceIn(1, MAX)
// Pe: 0 and 2 every character erased first, 1 only those loaded replaced
if (p(2) != 1 || dscs != designator || w != width || h != height) glyphs.clear()
designator = dscs
is96 = p(7) == 1
width = w
height = h
// Pcn: the first character's place (a 94-character set's from 1, its 0x21)
var ch = 0x20 + maxOf(p(1), if (is96) 0 else 1)
for (g in data.substring(i + 1).split(';')) {
if (ch > 0x7f || (!is96 && ch > 0x7e)) break
glyphs[ch] = glyph(g, w, h)
ch++
}
build()
}
/** one glyph's sixels as rows of [w] pixels (the leftmost bit w - 1), [h] of them */
private fun glyph(s: String, w: Int, h: Int): IntArray {
val rows = IntArray(h)
var band = 0
var col = 0
for (c in s) {
when (c) {
'/' -> { band++; col = 0 }
in '?'..'~' -> {
val bits = c.code - 0x3f
if (col < w) {
for (b in 0 until 6) {
val y = band * 6 + b
if (bits and (1 shl b) != 0 && y < h) rows[y] = rows[y] or (1 shl (w - 1 - col))
}
}
col++
}
}
}
return rows
}
/** [font] made from the glyphs */
private fun build() {
if (glyphs.isEmpty()) {
font = null
return
}
val chars = glyphs.keys.sorted()
val rows = IntArray(chars.size * height)
for ((n, c) in chars.withIndex()) glyphs[c]!!.copyInto(rows, n * height)
font = BitmapFont(height, IntArray(chars.size) { BASE + chars[it] }, rows, width)
}
/** [cp] (0x20..0x7f, as GL has it) as the soft set's code point, or as it is when it hasn't that character */
fun map(cp: Int): Int = if (glyphs.containsKey(cp)) BASE + cp else cp
/** whether [designator] (of a 96-character set if [is96]) names this set */
fun names(designator: String, is96: Boolean): Boolean = this.designator == designator && this.is96 == is96
/** none loaded (RIS) */
fun reset() {
glyphs.clear()
designator = null
font = null
}
companion object {
/** the soft characters' code points: plane 15's, this and the character */
const val BASE = 0xf0000
/** the largest cell a glyph has, in pixels */
private const val MAX = 24
}
}
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A VT320's host-writable status line (DECSSDT 2): one line below the
* screen that the host writes to after DECSASD 1, with a cursor of its
* own that moves only along it.
*/
class StatusLine(cols: Int) {
val line = Line(cols)
/** the cursor's column on it */
var x = 0
private set
/** [cp] written at the cursor in [style], the cursor after it (staying at the last column) */
fun print(cp: Int, style: Long) {
line.set(x, cp, style)
if (x < line.cols - 1) x++
}
/** the cursor to column [col] (from 0), kept on the line */
fun moveTo(col: Int) {
x = col.coerceIn(0, line.cols - 1)
}
/** EL on it: right of the cursor (0), left of it (1), all of it (2) */
fun erase(mode: Int, style: Long) {
when (mode) {
0 -> line.clear(x, line.cols, style)
1 -> line.clear(0, x + 1, style)
2 -> line.clear(0, line.cols, style)
}
}
/** its columns made [cols] */
fun resize(cols: Int) {
line.resize(cols)
x = x.coerceIn(0, cols - 1)
}
/** blank, the cursor at its start */
fun clear() {
line.blank(Style.NORMAL)
x = 0
}
}
@@ -127,13 +127,24 @@ class TerminalBridge(cols: Int, rows: Int) {
/** the bitmap glyphs' height: 8, 16 for a VGA's (0: none) */
val glyphHeight: Int get() = emulator.glyphs?.height ?: 0
/** row [row] (0 top) of [cp]'s bitmap glyph, its leftmost pixel bit 7; -1 if the profile has no glyph for it (drawn with the font) */
/** row [row] (0 top) of [cp]'s bitmap glyph (the profile's, or a soft character's), its leftmost pixel bit [glyphWidthOf] - 1; -1 if it has none (drawn with the font) */
fun glyphRow(cp: Int, row: Int): Int {
val g = emulator.glyphs ?: return -1
if (!g.has(cp)) return -1
val g = emulator.glyphFor(cp) ?: return -1
return g.row(cp, row)
}
/** [cp]'s bitmap glyph's width in pixels (8 for the profile's; a soft character's its own), 0 for none */
fun glyphWidthOf(cp: Int): Int = emulator.glyphFor(cp)?.width ?: 0
/** [cp]'s bitmap glyph's height in pixels, 0 for none */
fun glyphHeightOf(cp: Int): Int = emulator.glyphFor(cp)?.height ?: 0
/** whether the host loaded soft characters (DECDLD): code points from 0xF0000 drawn from their glyphs */
val softGlyphs: Boolean get() = emulator.softGlyphs != null
/** what the status line below the screen shows ("" for none: no line) */
val statusText: String get() = emulator.statusText()
/** the swatch (ARGB) the key at ([row], [col]) of page [page] shows, 0 for none */
fun keyBarColor(page: Int, row: Int, col: Int): Int = (keyAt(page, row, col) as? BarKey.Octets)?.color ?: 0
@@ -166,7 +177,7 @@ class TerminalBridge(cols: Int, rows: Int) {
/** what the key at ([row], [col]) of page [page] sends, as octets in Latin-1 ("" for one that doesn't) */
fun keyBarPress(page: Int, row: Int, col: Int, ctrl: Boolean = false, alt: Boolean = false): String =
when (val k = keyAt(page, row, col)) {
is BarKey.Send -> key(k.key.name, alt = alt, ctrl = ctrl)
is BarKey.Send -> key(k.key.name, shift = k.shift, alt = alt, ctrl = ctrl)
is BarKey.Type -> typed(k.text, ctrl, alt)
is BarKey.Octets -> k.octets
else -> ""
@@ -174,6 +174,45 @@ class TerminalEmulator(
private var tabs = BooleanArray(cols) { it % 8 == 0 && it > 0 }
/** DECLRMM: left and right margins in use (a VT420's) */
internal var lrMargins = false
set(v) {
field = v
if (!v) { left = 0; right = cols - 1 }
}
/** the margins' columns (inclusive): the screen's edges unless [lrMargins] and DECSLRM set them */
internal var left = 0
private set
internal var right = cols - 1
private set
/** the page of the main screen shown and written (0 first; a VT420 has 6) */
var page = 0
private set
/** the pages not shown, by number (made as they're first gone to) */
private val pages = HashMap<Int, Array<Line>>()
/** page [n] shown and written (its cursor home if [home]); the others kept, the alternate screen left alone */
internal fun selectPage(n: Int, home: Boolean) {
if (n == page) {
if (home) cursorPosition(0, 0)
return
}
pages[page] = main
val next = pages.remove(n)?.takeIf { it.size == rows && it[0].cols == cols } ?: Array(rows) { Line(cols) }
if (screen === main) screen = next
main = next
page = n
if (home) cursorPosition(0, 0)
revision++
}
/** whether the cursor is between the left and right margins (always, without them) */
internal val withinMargins: Boolean get() = cursorX in left..right
/** the margins are the screen's edges (the fast path: whole lines move) */
private val fullWidth: Boolean get() = left == 0 && right == cols - 1
/** the last character printed (REP repeats it) */
internal var lastChar = ' '.code
private set
@@ -230,6 +269,28 @@ class TerminalEmulator(
/** the glyphs its cells are drawn with, a bitmap font the profile's machine had (null: the view's font) */
val glyphs: BitmapFont? get() = profile.glyphs
/** the soft characters the host loaded (DECDLD), their code points [SoftFont.BASE]'s; null for none */
var softGlyphs: BitmapFont? = null
internal set
/** the bitmap glyph [cp] is drawn with: a soft character's, the profile's, or null for the view's font */
fun glyphFor(cp: Int): BitmapFont? =
softGlyphs?.takeIf { cp >= SoftFont.BASE && it.has(cp) } ?: glyphs?.takeIf { it.has(cp) }
/** DECSSDT's status line: 0 none, 1 the terminal's indicators, 2 the host's */
var statusType = 0
internal set
/** the host-writable status line's text and cursor */
internal val statusLine = StatusLine(cols)
/** what the status line shows ("" for none): the cursor's place as the indicators have it, or the host's text */
fun statusText(): String = when (statusType) {
1 -> "${(cursorY + 1).toString().padStart(4, '0')},${(minOf(cursorX, cols - 1) + 1).toString().padStart(3, '0')}"
2 -> statusLine.line.text().ifEmpty { " " }
else -> ""
}
/** text, as code points (the tests, local echo) */
fun appendText(s: String) {
var i = 0
@@ -245,9 +306,12 @@ class TerminalEmulator(
fun line(row: Int): Line =
if (row >= 0) screen[row] else history[history.size + row]
/** [s] to the remote, as Latin-1 octets */
/** replies' controls in their 8-bit forms (S8C1T: CSI as 9B, DCS as 90, ST as 9C) */
internal var eightBitReplies = false
/** [s] to the remote, as Latin-1 octets (its ESC Fe's as C1 controls, when [eightBitReplies]) */
internal fun reply(s: String) {
output(s.latin1())
output((if (eightBitReplies) ESC_FE.replace(s) { (it.groupValues[1][0].code + 0x40).toChar().toString() } else s).latin1())
}
// ------------------------------------------------------------------
@@ -353,8 +417,8 @@ class TerminalEmulator(
}
pendingWrap = false
}
// (a line of double width holds half as many)
val lc = lineWidth(cursorY)
// (a line of double width holds half as many; within the margins, the right one's the edge)
val lc = if (withinMargins && !fullWidth) minOf(right + 1, lineWidth(cursorY)) else lineWidth(cursorY)
if (cursorX >= lc) cursorX = lc - 1
// a wide character with one column left: to the next line (the last cell left blank)
if (w == 2 && cursorX == lc - 1) {
@@ -365,15 +429,15 @@ class TerminalEmulator(
lineFeed()
}
val line = screen[cursorY]
if (insertMode) line.insertCells(cursorX, w, style)
if (insertMode) line.insertCells(cursorX, w, style, lc)
// (half of a wide character written over: its other half blanked)
unpair(line, cursorX)
if (w == 2) unpair(line, cursorX + 1)
line.set(cursorX, cp, style)
if (w == 2) line.set(cursorX + 1, Line.WIDE_TAIL, style)
link?.let { l -> for (k in 0 until w) line.extraFor(cursorX + k).link = l }
if (cursorX + w >= lineWidth(cursorY)) {
cursorX = lineWidth(cursorY) - 1
if (cursorX + w >= lc) {
cursorX = lc - 1
pendingWrap = true
} else {
cursorX += w
@@ -398,6 +462,7 @@ class TerminalEmulator(
internal fun setColumnMode(wide: Boolean) {
requestedColumns = if (wide) 132 else 80
for (l in screen) l.blank(Style.NORMAL)
lrMargins = false
top = 0
bottom = rows - 1
cursorX = 0
@@ -427,9 +492,9 @@ class TerminalEmulator(
if (cp == 0x200D) joinNext = true
}
/** the cursor to the line's start */
/** the cursor to the line's start (the left margin's, from within or right of it) */
internal fun carriageReturn() {
cursorX = 0
cursorX = if (cursorX >= left) left else 0
pendingWrap = false
}
@@ -451,7 +516,7 @@ class TerminalEmulator(
internal fun index() {
pendingWrap = false
if (cursorY == bottom) {
scrollUp(top, bottom)
if (withinMargins) scrollUp(top, bottom)
} else if (cursorY < rows - 1) {
cursorY++
}
@@ -461,7 +526,7 @@ class TerminalEmulator(
internal fun reverseIndex() {
pendingWrap = false
if (cursorY == top) {
scrollDown(top, bottom)
if (withinMargins) scrollDown(top, bottom)
} else if (cursorY > 0) {
cursorY--
}
@@ -469,6 +534,12 @@ class TerminalEmulator(
/** the region's lines up one, the top one to the scrollback (the whole main screen's) */
internal fun scrollUp(t: Int, b: Int) {
if (!fullWidth) {
// (between the margins: the cells move, the lines stay)
for (y in t until b) copyCells(screen[y + 1], screen[y])
screen[b].clear(left, right + 1, Style.erased(style))
return
}
val gone = screen[t]
if (screen === main && t == 0 && b == rows - 1 && historyMax > 0) {
val kept = Line(cols)
@@ -483,27 +554,52 @@ class TerminalEmulator(
/** lines [t] to [b] down one, a blank one at the top (the bottom one gone) */
internal fun scrollDown(t: Int, b: Int) {
if (!fullWidth) {
for (y in b downTo t + 1) copyCells(screen[y - 1], screen[y])
screen[t].clear(left, right + 1, Style.erased(style))
return
}
val gone = screen[b]
for (y in b downTo t + 1) screen[y] = screen[y - 1]
gone.blank(Style.erased(style))
screen[t] = gone
}
/** the cursor to ([x], [y]) on the screen, or within the scrolling region if [clampToRegion] and it is in it */
/** cells [left] to [right] of [from] into [to] (a scroll between the margins) */
private fun copyCells(from: Line, to: Line) {
for (x in left..right) {
to.set(x, from.chars[x], from.styles[x])
from.extra(x)?.let { to.extraFor(x).also { e -> e.combining = it.combining; e.image = it.image; e.link = it.link } }
}
}
/** the cursor to ([x], [y]) on the screen, or within the scrolling region if [clampToRegion] and it is in it (and between the margins, from between them) */
internal fun moveCursor(x: Int, y: Int, clampToRegion: Boolean = false) {
val (lo, hi) = if (clampToRegion && cursorY in top..bottom) top to bottom else 0 to rows - 1
val (l, r) = if (withinMargins) left to right else 0 to cols - 1
cursorY = y.coerceIn(lo, hi)
cursorX = x.coerceIn(0, lineWidth(cursorY) - 1)
cursorX = x.coerceIn(l, minOf(r, lineWidth(cursorY) - 1))
pendingWrap = false
}
/** CUP: the cursor to ([x], [y]), from the region's top in origin mode */
/** CUP: the cursor to ([x], [y]), from the region's top (and the left margin) in origin mode */
internal fun cursorPosition(x: Int, y: Int) {
cursorY = if (originMode) (y + top).coerceIn(top, bottom) else y.coerceIn(0, rows - 1)
cursorX = x.coerceIn(0, lineWidth(cursorY) - 1)
cursorX = if (originMode) (x + left).coerceIn(left, right) else x.coerceIn(0, lineWidth(cursorY) - 1)
cursorX = cursorX.coerceAtMost(lineWidth(cursorY) - 1)
pendingWrap = false
}
/** DECSLRM: the left and right margins columns [l] to [r] (ignored unless left < right), the cursor home */
internal fun setMargins(l: Int, r: Int) {
val ll = l.coerceIn(0, cols - 1)
val rr = r.coerceIn(0, cols - 1)
if (ll >= rr) return
left = ll
right = rr
cursorPosition(0, 0)
}
/** DECSTBM: the scrolling region lines [t] to [b] (ignored unless top < bottom), the cursor home */
internal fun setRegion(t: Int, b: Int) {
val tt = t.coerceIn(0, rows - 1)
@@ -545,25 +641,39 @@ class TerminalEmulator(
if (cursorX < cols) tabs[cursorX] = false
}
/** the columns with tab stops (from 0), for DECTABSR */
internal fun tabStops(): List<Int> = tabs.indices.filter { tabs[it] }
/** TBC 3: every tab stop cleared */
internal fun clearTabs() {
tabs.fill(false)
}
/** ED: the screen erased below the cursor (0), above it (1), all of it (2), or the scrollback (3) */
internal fun eraseDisplay(mode: Int) {
/** cells [from] until [to] of [l] erased in [e]: all of them, or (DECSED, DECSEL: [selective]) those DECSCA didn't protect */
private fun erase(l: Line, from: Int, to: Int, e: Long, selective: Boolean) {
if (!selective) {
if (from <= 0 && to >= l.cols) l.blank(e) else l.clear(from, to, e)
return
}
for (x in from.coerceAtLeast(0) until to.coerceAtMost(l.cols)) {
if (Style.attrs(l.styles[x]) and Style.PROTECTED == 0) l.clear(x, x + 1, e)
}
}
/** ED (DECSED if [selective]): the screen erased below the cursor (0), above it (1), all of it (2), or the scrollback (3) */
internal fun eraseDisplay(mode: Int, selective: Boolean = false) {
val e = Style.erased(style)
when (mode) {
0 -> {
screen[cursorY].clear(cursorX, cols, e)
for (y in cursorY + 1 until rows) { screen[y].blank(e) }
erase(screen[cursorY], cursorX, cols, e, selective)
for (y in cursorY + 1 until rows) erase(screen[y], 0, cols, e, selective)
}
1 -> {
for (y in 0 until cursorY) { screen[y].blank(e) }
screen[cursorY].clear(0, cursorX + 1, e)
for (y in 0 until cursorY) erase(screen[y], 0, cols, e, selective)
erase(screen[cursorY], 0, cursorX + 1, e, selective)
}
2 -> {
for (y in 0 until rows) { screen[y].blank(e) }
for (y in 0 until rows) erase(screen[y], 0, cols, e, selective)
// ANSI.SYS homes the cursor with ESC[2J; BBSes count on it
if (homeOnClear) { cursorX = 0; cursorY = 0 }
}
@@ -572,14 +682,14 @@ class TerminalEmulator(
pendingWrap = false
}
/** EL: the line erased right of the cursor (0), left of it (1), or all of it (2) */
internal fun eraseLine(mode: Int) {
/** EL (DECSEL if [selective]): the line erased right of the cursor (0), left of it (1), or all of it (2) */
internal fun eraseLine(mode: Int, selective: Boolean = false) {
val e = Style.erased(style)
val l = screen[cursorY]
when (mode) {
0 -> l.clear(cursorX, cols, e)
1 -> l.clear(0, cursorX + 1, e)
2 -> l.clear(0, cols, e)
0 -> erase(l, cursorX, cols, e, selective)
1 -> erase(l, 0, cursorX + 1, e, selective)
2 -> erase(l, 0, cols, e, selective)
}
if (mode != 1) l.wrapped = false
pendingWrap = false
@@ -591,29 +701,35 @@ class TerminalEmulator(
pendingWrap = false
}
/** ICH: [n] blank cells inserted at the cursor */
/** ICH: [n] blank cells inserted at the cursor (those past the right margin, from within the margins, kept) */
internal fun insertChars(n: Int) {
screen[cursorY].insertCells(cursorX, n, Style.erased(style))
if (withinMargins) screen[cursorY].insertCells(cursorX, n, Style.erased(style), right + 1)
pendingWrap = false
}
/** DCH: [n] cells deleted at the cursor */
/** DCH: [n] cells deleted at the cursor (blanks in at the right margin) */
internal fun deleteChars(n: Int) {
screen[cursorY].deleteCells(cursorX, n, Style.erased(style))
if (withinMargins) screen[cursorY].deleteCells(cursorX, n, Style.erased(style), right + 1)
pendingWrap = false
}
/** IL: [n] blank lines inserted at the cursor's, within the region */
/** IL: [n] blank lines inserted at the cursor's, within the region (and the margins) */
internal fun insertLines(n: Int) {
if (cursorY !in top..bottom) return
if (cursorY !in top..bottom || !withinMargins) return
repeat(n.coerceAtMost(bottom - cursorY + 1)) { scrollDown(cursorY, bottom) }
cursorX = 0
cursorX = left
pendingWrap = false
}
/** DL: [n] lines deleted at the cursor's, blank ones in at the region's bottom */
internal fun deleteLines(n: Int) {
if (cursorY !in top..bottom) return
if (cursorY !in top..bottom || !withinMargins) return
if (!fullWidth) {
repeat(n.coerceAtMost(bottom - cursorY + 1)) { scrollUp(cursorY, bottom) }
cursorX = left
pendingWrap = false
return
}
repeat(n.coerceAtMost(bottom - cursorY + 1)) {
// (not to the scrollback: the region starts at the cursor)
val gone = screen[cursorY]
@@ -676,6 +792,7 @@ class TerminalEmulator(
insertMode = false
top = 0
bottom = rows - 1
lrMargins = false
style = Style.NORMAL
interpreter.softReset()
savedMain = null
@@ -684,7 +801,12 @@ class TerminalEmulator(
/** everything as it was at the start (RIS), the scrollback kept */
fun reset() {
selectPage(0, home = false)
pages.clear()
softReset()
statusType = 0
statusLine.clear()
softGlyphs = null
screen = main
for (l in main) { l.blank(Style.NORMAL) }
for (l in alt) { l.blank(Style.NORMAL) }
@@ -741,6 +863,10 @@ class TerminalEmulator(
screen = if (wasAlt) alt else main
cols = newCols
rows = newRows
statusLine.resize(cols)
// (the pages not shown don't follow the size: they start again)
pages.clear()
lrMargins = false
top = 0
bottom = rows - 1
tabs = BooleanArray(cols) { it % 8 == 0 && it > 0 }
@@ -803,6 +929,9 @@ class TerminalEmulator(
/** the largest sixel image (pixels a side) */
const val MAX_IMAGE = 2048
/** an ESC Fe (ESC [, ESC P, ST's ESC and backslash ...): what has a C1 form */
private val ESC_FE = Regex("\u001b([\\x40-\\x5f])")
/** xterm's colours: the 16, the 6x6x6 cube, the greys; default fg light grey, bg black */
fun xtermColor(i: Int): Int {
val sixteen = intArrayOf(
@@ -122,6 +122,69 @@ open class Vt220Profile : Vt102Profile() {
override val primaryDa get() = "\u001b[?62;1;2;6;7;8;9c"
// a VT220, firmware 1.0
override val secondaryDa: String? get() = "\u001b[>1;10;0c"
/** a DEC terminal's keys, the LK201's F6-F20 and the user-defined ones */
override val keyBar: List<KeyBarPage> get() = KeyBars.LK201
}
/** DEC VT320: level 3, DEC Technical, the requests a VT320 answers (DECRQSS, DECRQPSR, DECRQUPSS) */
open class Vt320Profile : Vt220Profile() {
override val id get() = "vt320"
override val label get() = "DEC VT320"
override val term get() = "vt320"
override val telnetType get() = "DEC-VT320"
override val level get() = 3
// 132 columns, printer, selective erase, user-defined keys, NRCS, technical set
override val primaryDa get() = "\u001b[?63;1;2;6;7;8;9c"
// a VT320, firmware 1.0
override val secondaryDa: String? get() = "\u001b[>24;10;0c"
}
/** DEC VT420: level 4, left and right margins, rectangular areas, six pages */
open class Vt420Profile : Vt320Profile() {
override val id get() = "vt420"
override val label get() = "DEC VT420"
override val term get() = "vt420"
override val telnetType get() = "DEC-VT420"
override val level get() = 4
// 132 columns, printer, selective erase, user-defined keys, NRCS, technical set, locator, text macros, rectangles
override val primaryDa get() = "\u001b[?64;1;2;6;7;8;9;15;18;21;28c"
// a VT420, firmware 1.0
override val secondaryDa: String? get() = "\u001b[>41;10;0c"
/** a [Vt420Interpreter] */
override fun interpreter(t: TerminalEmulator): TerminalInterpreter = Vt420Interpreter(t, this)
}
/** DEC VT510: level 5, the display extent and the PC keyboard's modes */
open class Vt510Profile : Vt420Profile() {
override val id get() = "vt510"
override val label get() = "DEC VT510"
override val term get() = "vt510"
override val telnetType get() = "DEC-VT510"
override val level get() = 5
override val primaryDa get() = "\u001b[?65;1;2;6;7;8;9;15;18;21;28c"
override val secondaryDa: String? get() = "\u001b[>61;10;0c"
}
/** DEC VT520: a VT510 with more sessions (one here) */
open class Vt520Profile : Vt510Profile() {
override val id get() = "vt520"
override val label get() = "DEC VT520"
override val term get() = "vt520"
override val telnetType get() = "DEC-VT520"
override val secondaryDa: String? get() = "\u001b[>64;10;0c"
}
/** DEC VT525: a VT520 in colour (SGR's, DECAC's, the colour table) */
open class Vt525Profile : Vt520Profile() {
override val id get() = "vt525"
override val label get() = "DEC VT525"
override val term get() = "vt525"
override val telnetType get() = "DEC-VT525"
// a VT520's, and colour (22)
override val primaryDa get() = "\u001b[?65;1;2;6;7;8;9;15;18;21;22;28c"
override val secondaryDa: String? get() = "\u001b[>65;10;0c"
override val features: Set<VtFeature> get() = super.features + VtFeature.COLOR
}
/** xterm: a VT220 with colours, sixel and its own extensions */
@@ -130,6 +193,8 @@ open class XtermProfile : Vt220Profile() {
override val label get() = "xterm"
override val term get() = "xterm-256color"
override val telnetType get() = "XTERM-256COLOR"
/** a DEC terminal's keys (a PC keyboard's F-keys, not an LK201's) */
override val keyBar: List<KeyBarPage> get() = KeyBars.DEC
// a VT220 with sixel graphics (4) and ANSI colour (22)
override val primaryDa get() = "\u001b[?62;4;22c"
// xterm, patch 390
@@ -159,6 +224,13 @@ object TerminalProfiles {
val VT100: TerminalProfile = Vt100Profile()
val VT102: TerminalProfile = Vt102Profile()
val VT220: TerminalProfile = Vt220Profile()
val VT320: TerminalProfile = Vt320Profile()
val VT420: TerminalProfile = Vt420Profile()
val VIEWDATA: TerminalProfile = ViewdataProfile()
val MINITEL: TerminalProfile = MinitelProfile()
val VT510: TerminalProfile = Vt510Profile()
val VT520: TerminalProfile = Vt520Profile()
val VT525: TerminalProfile = Vt525Profile()
val XTERM: TerminalProfile = XtermProfile()
val ANSI_BBS: TerminalProfile = AnsiBbsProfile()
val C64: TerminalProfile = C64Profile()
@@ -175,7 +247,7 @@ object TerminalProfiles {
val DEFAULT: TerminalProfile get() = XTERM
/** in the pickers' order */
val all: List<TerminalProfile> = listOf(XTERM, ANSI_BBS, VT52, VT100, VT102, VT220, C64, C128, C128_80, PLUS4, VIC20, PET, PET80, ATARI, ATARI_INTL)
val all: List<TerminalProfile> = listOf(XTERM, ANSI_BBS, VT52, VT100, VT102, VT220, VT320, VT420, VT510, VT520, VT525, C64, C128, C128_80, PLUS4, VIC20, PET, PET80, ATARI, ATARI_INTL, VIEWDATA, MINITEL)
/** the profile [id] names, or null for none or one not known */
fun byId(id: String?): TerminalProfile? = all.firstOrNull { it.id == id }
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A VT220's user-defined keys (DECUDK): what the host loads into F6 to
* F20, sent when the key is pressed with Shift. The keys go by DEC's
* numbers (17 F6 ... 34 F20, as their CSI ~ sequences have them); the
* host can lock them against more loading until the terminal is reset.
*/
class UserKeys {
private val keys = HashMap<Int, ByteArray>()
/** loading them refused (DECUDK's Pl 0, or the set-up's lock) */
var locked = false
private set
/**
* a DECUDK's data: [clear] 0 (or none) all keys cleared first, 1 only
* those given replaced; [lock] 0 (or none) locked after, 1 left
* unlocked; [data] "key/hex-string" pairs between semicolons
*/
fun load(clear: Int, lock: Int, data: String) {
if (locked) return
if (clear == 0) keys.clear()
for (def in data.split(';')) {
val slash = def.indexOf('/')
if (slash < 0) continue
val key = def.substring(0, slash).toIntOrNull() ?: continue
if (key !in KEYS) continue
val hex = def.substring(slash + 1)
if (hex.isEmpty()) {
keys.remove(key)
continue
}
val out = ByteArray(hex.length / 2)
var ok = hex.length % 2 == 0
for (i in out.indices) {
val v = hex.substring(2 * i, 2 * i + 2).toIntOrNull(16)
if (v == null) { ok = false; break }
out[i] = v.toByte()
}
if (ok && out.size <= 256) keys[key] = out
}
locked = lock == 0
}
/** DEC's key [number]'s string, or null when none is loaded */
fun get(number: Int): ByteArray? = keys[number]
/** [k]'s string when it is one of the keys and has one */
fun forKey(k: Key): ByteArray? = NUMBERS[k]?.let { keys[it] }
/** all cleared and unlocked (RIS) */
fun reset() {
keys.clear()
locked = false
}
companion object {
/** the keys a host can load: F6-F10, F11-F14, Help and Do (F15, F16), F17-F20 */
val KEYS = setOf(17, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 31, 32, 33, 34)
/** the function keys' numbers */
private val NUMBERS = mapOf(
Key.F6 to 17, Key.F7 to 18, Key.F8 to 19, Key.F9 to 20, Key.F10 to 21,
Key.F11 to 23, Key.F12 to 24, Key.F13 to 25, Key.F14 to 26, Key.F15 to 28, Key.F16 to 29,
Key.F17 to 31, Key.F18 to 32, Key.F19 to 33, Key.F20 to 34,
)
}
}
@@ -0,0 +1,234 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A videotex terminal from a phone company (Prestel's, the Minitel): 40
* columns of text and 2x3 block mosaics in eight colours, its octets read
* as they come. What they share: the palette, the mosaics drawn from the
* app's bitmaps ([Mosaic]), a cursor that wraps round the screen rather
* than scrolling it.
*/
abstract class VideotexProfile : TerminalProfile(), ByteMachine {
override val columns get() = 40
/** teletext's eight: black, red, green, yellow, blue, magenta, cyan, white */
override val palette: IntArray get() = TELETEXT
override val defaultColor get() = 7
override val background get() = 0
/** a capture as the frames' octets (.vdt, as viewdata and Minitel editors keep them) */
override val captureExtension: String? get() = ".vdt"
companion object {
val TELETEXT = intArrayOf(
0xff000000.toInt(), 0xffff0000.toInt(), 0xff00ff00.toInt(), 0xffffff00.toInt(),
0xff0000ff.toInt(), 0xffff00ff.toInt(), 0xff00ffff.toInt(), 0xffffffff.toInt(),
)
}
}
/** What both videotex terminals' interpreters share: the mosaics' glyphs on the emulator, and the cursor's moves round the screen */
abstract class VideotexInterpreter(t: TerminalEmulator, m: VideotexProfile) : ByteControlInterpreter(t, m) {
init {
t.softGlyphs = Mosaic.font
}
/** the mosaics' glyphs gone with the profile */
override fun detach() {
super.detach()
t.softGlyphs = null
}
/** as at the start, the mosaics' glyphs back on the emulator (RIS took them) */
override fun reset() {
super.reset()
t.softGlyphs = Mosaic.font
}
/** the first row the cursor moves in (a Minitel's row 0 is its status row) */
protected open val firstRow: Int get() = 0
/** the cursor to ([x], [y]) */
protected fun at(x: Int, y: Int) {
t.moveCursor(x, y)
}
/** the cursor left (from a row's start the one above's end, from the first row's the last's) */
protected fun back() {
when {
t.cursorX > 0 -> at(t.cursorX - 1, t.cursorY)
else -> at(t.cols - 1, if (t.cursorY > firstRow) t.cursorY - 1 else t.rows - 1)
}
}
/** the cursor right (from a row's end the next one's start) */
protected fun forward() {
if (t.cursorX < t.cols - 1) at(t.cursorX + 1, t.cursorY) else { at(0, t.cursorY); lineDown() }
}
/** the cursor down a row (from the last, the first: the screen doesn't scroll) */
protected open fun lineDown() {
at(t.cursorX, if (t.cursorY < t.rows - 1) t.cursorY + 1 else firstRow)
}
/** the cursor up a row (from the first, the last) */
protected fun lineUp() {
at(t.cursorX, if (t.cursorY > firstRow) t.cursorY - 1 else t.rows - 1)
}
}
/**
* Viewdata as Prestel had it (and the revival services, Telstar among
* them): 40x24 of teletext Level 1. Its attributes are spacing
* characters, each taking a cell and changing the rest of its row (alpha
* or mosaic colours, flash, conceal, contiguous or separated mosaics,
* hold, new and black background; double height drawn single), so the
* screen is kept as the codes that came and each row drawn again from
* them when one of its cells changes. # is the key that sends.
*/
open class ViewdataProfile : VideotexProfile() {
override val id get() = "viewdata"
override val label get() = "Viewdata (Prestel)"
override val term get() = "viewdata"
override val telnetType get() = "VIEWDATA"
override val rows get() = 24
override val keyBar: List<KeyBarPage> get() = listOf(KeyBars.VIEWDATA)
/** a [ViewdataInterpreter] */
override fun interpreter(t: TerminalEmulator): TerminalInterpreter = ViewdataInterpreter(t, this)
}
/** Prestel's controls and teletext's attributes over a screen of codes */
open class ViewdataInterpreter(t: TerminalEmulator, private val m: ViewdataProfile) : VideotexInterpreter(t, m) {
/** the codes on the screen (0x00-0x1f the attributes, else characters) */
private var cells = Array(m.rows) { IntArray(m.columns) { ' '.code } }
/** an ESC came: the next code is an attribute */
private var escaped = false
/** as at the start: the screen's codes blank */
override fun reset() {
super.reset()
cells = Array(m.rows) { IntArray(m.columns) { ' '.code } }
escaped = false
}
/** an octet, without its parity bit: after ESC an attribute, else a control or a character */
override fun process(cp: Int) {
val b = cp and 0x7f
if (escaped) {
escaped = false
if (b in 0x40..0x5f) store(b - 0x40)
return
}
if (!control(b) && b >= 0x20) store(b)
}
/** Prestel's controls: BS, HT, LF, VT, FF (clear), CR, RS (home), cursor on and off, ENQ, ESC */
override fun control(b: Int): Boolean {
when (b) {
0x08 -> back()
0x09 -> forward()
0x0a -> lineDown()
0x0b -> lineUp()
0x0c -> {
for (r in cells) r.fill(' '.code)
for (y in 0 until minOf(t.rows, cells.size)) draw(y)
home()
}
0x0d -> at(0, t.cursorY)
0x1e -> home()
0x11 -> t.cursorVisible = true
0x14 -> t.cursorVisible = false
0x1b -> escaped = true
else -> return b < 0x20
}
return true
}
/** (characters are [store]d, not drawn as they come) */
override fun charOf(b: Int): Int = b
/** code [c] put at the cursor, its row drawn again, the cursor on */
private fun store(c: Int) {
val y = t.cursorY
val x = t.cursorX
if (y in cells.indices && x in cells[y].indices) {
cells[y][x] = c
draw(y)
}
forward()
}
/** row [y] drawn from its codes, as a teletext decoder does: each attribute applied at or after its cell */
private fun draw(y: Int) {
if (y >= t.rows) return
val line = t.line(y)
var fg = 7
var bg = 0
var mosaic = false
var separated = false
var hold = false
var held = ' '.code
var flash = false
var conceal = false
for (x in 0 until minOf(t.cols, cells[y].size)) {
val c = cells[y][x]
var shown: Int
if (c < 0x20) {
// set-at
when (c) {
0x09 -> flash = false
0x0c -> held = ' '.code
0x18 -> conceal = true
0x19 -> separated = false
0x1a -> separated = true
0x1c -> bg = 0
0x1d -> bg = fg
0x1e -> hold = true
}
shown = if (hold && mosaic) held else ' '.code
line.set(x, shown, look(fg, bg, flash, conceal))
// set-after
when (c) {
in 0x01..0x07 -> { fg = c; if (mosaic) held = ' '.code; mosaic = false; conceal = false }
in 0x11..0x17 -> { fg = c - 0x10; mosaic = true; conceal = false }
0x08 -> flash = true
0x1f -> hold = false
}
continue
}
shown = if (mosaic && (c < 0x40 || c >= 0x60)) {
Mosaic.code(Mosaic.bits(c), separated).also { held = it }
} else {
G0.getOrNull(c - 0x20) ?: c
}
line.set(x, shown, look(fg, bg, flash, conceal))
}
}
/** a cell's look: colours [fg] and [bg], flashing, concealed */
private fun look(fg: Int, bg: Int, flash: Boolean, conceal: Boolean): Long =
Style.of(fg, bg, (if (flash) Style.BLINK else 0) or (if (conceal) Style.INVISIBLE else 0))
/** Enter and # send #, Prestel's 0x5f; Backspace BS */
override fun keyOctets(k: Key, shift: Boolean, alt: Boolean, ctrl: Boolean): ByteArray? = when (k) {
Key.ENTER -> byteArrayOf(0x5f)
Key.BACKSPACE -> byteArrayOf(0x08)
else -> null
}
/** what's typed as Prestel's codes: # as 0x5f, £ as 0x23 */
override fun charOctets(cp: Int, alt: Boolean, ctrl: Boolean): ByteArray? = when (cp) {
'#'.code -> byteArrayOf(0x5f)
'£'.code -> byteArrayOf(0x23)
else -> if (cp in 0x20..0x7e) byteArrayOf(cp.toByte()) else null
}
companion object {
/** teletext's English set, 0x20-0x7f: £ for #, arrows, fractions, # for _, a dash, ‖, ÷ and a block */
private val G0 = IntArray(0x60) { 0x20 + it }.also {
for ((c, u) in listOf(0x23 to '£', 0x5b to '←', 0x5c to '½', 0x5d to '→', 0x5e to '↑', 0x5f to '#',
0x60 to '—', 0x7b to '¼', 0x7c to '‖', 0x7d to '¾', 0x7e to '÷', 0x7f to '■')) it[c - 0x20] = u.code
}
}
}
@@ -0,0 +1,221 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.math.roundToInt
/**
* A VT420's and VT5xx's sequences over the VT320's: left and right
* margins (DECLRMM, DECSLRM), the rectangular area operations, column
* insert and delete (DECIC, DECDC) and the back and forward index (DECBI,
* DECFI), pages (NP, PP, PPA, PPR, PPB), the lines and columns asked for
* (DECSNLS, DECSLPP, DECSCPP), the keypad and backarrow modes (DECNKM,
* DECBKM), and from the VT510 on the display extent (DECRQDE), the bell
* volumes, and (a VT525's) the colour table (DECAC, DECRQTSR, DECRSTS).
*/
open class Vt420Interpreter(t: TerminalEmulator, profile: DecProfile) : VtInterpreter(t, profile) {
private val rectangles = Rectangles(t)
/** DECBKM: the backarrow key sends BS (set) or DEL */
private var backarrowBs = false
/** the VT420's ESC 6 (DECBI) and ESC 9 (DECFI) */
override fun extraEsc(cp: Int): Boolean {
if (operatingLevel < 4) return false
when (cp.toChar()) {
'6' -> backIndex()
'9' -> forwardIndex()
else -> return false
}
return true
}
/** DECBI: the cursor left one, or at the left margin the area between the margins moved right a column */
private fun backIndex() {
if (t.cursorX > t.left) {
t.moveCursor(t.cursorX - 1, t.cursorY)
} else if (t.cursorX == t.left && t.cursorY in t.top..t.bottom) {
rectangles.insertColumns(t.left, 1)
}
}
/** DECFI: the cursor right one, or at the right margin the area between the margins moved left a column */
private fun forwardIndex() {
if (t.cursorX < t.right) {
t.moveCursor(t.cursorX + 1, t.cursorY)
} else if (t.cursorX == t.right && t.cursorY in t.top..t.bottom) {
rectangles.deleteColumns(t.left, 1)
}
}
/** the VT420's and VT5xx's CSIs (each at the level that has it) */
override fun extraCsi(final: Int, marker: Int, inter: Int): Boolean {
if (operatingLevel < 4) return false
val c = final.toChar()
if (marker == '?'.code) {
if (inter == 0 && (c == 'h' || c == 'l')) {
// (the others still the parser's)
for (i in 0 until maxOf(paramCount, 1)) mode(param(i), c == 'h')
}
return false
}
if (marker != 0) return false
val i = inter.toChar()
when {
inter == 0 && c == 's' && t.lrMargins -> t.setMargins(p(0, 1) - 1, p(1, t.cols) - 1)
inter == 0 && c == 'U' -> page(t.page + p(0, 1), home = true)
inter == 0 && c == 'V' -> page(t.page - p(0, 1), home = true)
i == ' ' && c == 'P' -> page(p(0, 1) - 1, home = false)
i == ' ' && c == 'Q' -> page(t.page + p(0, 1), home = false)
i == ' ' && c == 'R' -> page(t.page - p(0, 1), home = false)
// DECIC, DECDC: only from between the margins and in the region
i == '\'' && c == '}' -> if (t.withinMargins && t.cursorY in t.top..t.bottom) rectangles.insertColumns(t.cursorX, p(0, 1))
i == '\'' && c == '~' -> if (t.withinMargins && t.cursorY in t.top..t.bottom) rectangles.deleteColumns(t.cursorX, p(0, 1))
i == '$' && c == 'v' -> rectangles.area(::p)?.let { a ->
// DECCRA: the area to Ptd; Pld (from the margins in origin mode)
val oy = if (t.originMode) t.top else 0
val ox = if (t.originMode) t.left else 0
rectangles.copy(a, p(5, 1) - 1 + oy, p(6, 1) - 1 + ox)
}
i == '$' && c == 'z' -> rectangles.area(::p)?.let { rectangles.erase(it, selective = false) }
i == '$' && c == '{' -> rectangles.area(::p)?.let { rectangles.erase(it, selective = true) }
i == '$' && c == 'x' -> rectangles.area(::p, at = 1)?.let { a ->
// DECFRA: a printable character only
val ch = param(0)
if (ch in 0x20..0x7e || ch in 0xa0..0xff) rectangles.fill(a, ch)
}
i == '$' && (c == 'r' || c == 't') -> rectangles.area(::p, stream = !rectangles.rectangle)?.let { a ->
rectangles.attributes(a, (4 until paramCount).map { param(it) }, reverse = c == 't')
}
i == '*' && c == 'x' -> rectangles.rectangle = param(0) == 2
// DECRQCRA: Pid; Pp; the area
i == '*' && c == 'y' -> {
val a = rectangles.area(::p, at = 2)
val sum = if (a == null) 0 else rectangles.checksum(a)
t.reply("\u001bP${param(0)}!~${sum.toString(16).uppercase().padStart(4, '0')}\u001b\\")
}
// DECSNLS: lines on the screen; DECSLPP (24 and more: lines a page); DECSCPP: 80 or 132 columns
i == '*' && c == '|' -> t.requestedRows = p(0, 24).coerceIn(1, 255)
inter == 0 && c == 't' && param(0) >= 24 -> t.requestedRows = param(0).coerceAtMost(255)
i == '$' && c == '|' -> t.requestedColumns = if (p(0, 80) > 80) 132 else 80
else -> return level5(i, c)
}
return true
}
/** a VT5xx's: the display extent (DECRQDE), the bell volumes, the keyboard's (taken), a VT525's colours */
private fun level5(i: Char, c: Char): Boolean {
if (operatingLevel < 5) return false
when {
i == '"' && c == 'v' -> t.reply("\u001b[${t.rows};${t.cols};1;1;${t.page + 1}\"w")
// DECSWBV, DECSMBV, DECSKCV, DECTME: there's nothing here for them to set
i == ' ' && (c == 't' || c == 'u' || c == '=' || c == '~') -> {}
// DECAC: the normal text's colours (Ps1 1) from the table's 16
i == ',' && c == '|' && profile.has(VtFeature.COLOR) -> if (param(0) == 1) {
t.setColorOverride(256, color(param(1)))
t.setColorOverride(257, color(param(2)))
}
// DECATC: the alternate text colours (drawn as the attributes' own)
i == ',' && c == '}' -> {}
// DECRQTSR 2: the colour table (DECCTR)
i == '$' && c == 'u' && param(0) == 2 && profile.has(VtFeature.COLOR) -> t.reply(colorTable())
else -> return false
}
return true
}
/** colour [n] of the 16 as the screen shows it now */
private fun color(n: Int): Int {
val i = n.coerceIn(0, 15)
return t.colorOverride(i).takeIf { it != -1 } ?: t.defaultColor(i)
}
/** DECCTR: the 16 colours, each Pc; 2 (RGB); its red, green and blue in percent */
private fun colorTable(): String {
/** a channel (0-255) in percent */
fun pct(v: Int) = (v * 100 / 255.0).roundToInt()
val entries = (0 until 16).joinToString("/") { n ->
val c = color(n)
"$n;2;${pct((c shr 16) and 0xff)};${pct((c shr 8) and 0xff)};${pct(c and 0xff)}"
}
return "\u001bP2\$s$entries\u001b\\"
}
/** DECRSTS ($p) with Ps 2: the colour table restored from DECCTR's entries (Pu 1 HLS, 2 RGB) */
override fun wantsDcs(final: Int, inter: Int): Boolean =
final == 'p'.code && inter == '$'.code && operatingLevel >= 5 && profile.has(VtFeature.COLOR)
/** the text of a DCS [wantsDcs] took: DECRSTS's colour table */
override fun extraDcs(kind: String, params: IntArray, text: String) {
if (kind != "\$p" || params.getOrElse(0) { 0 } != 2) return
for (entry in text.split('/')) {
val f = entry.split(';').map { it.toIntOrNull() ?: 0 }
if (f.size < 5 || f[0] !in 0..15) continue
val argb = when (f[1]) {
1 -> Sixel.hls(f[2], f[3], f[4])
2 -> rgb(f[2], f[3], f[4])
else -> continue
}
t.setColorOverride(f[0], argb)
}
}
/** red, green and blue in percent as a colour */
private fun rgb(r: Int, g: Int, b: Int): Int {
/** a percentage as 0-255 */
fun c(v: Int) = (v.coerceIn(0, 100) * 255 / 100.0).roundToInt()
return (0xff shl 24) or (c(r) shl 16) or (c(g) shl 8) or c(b)
}
/** page [n] (from 0, kept to the 6 there are) gone to */
private fun page(n: Int, home: Boolean) {
t.selectPage(n.coerceIn(0, PAGES - 1), home)
}
/** a VT420's DEC modes: DECNKM (66), DECBKM (67), DECLRMM (69); DECKPM (81) taken */
private fun mode(m: Int, on: Boolean) {
when (m) {
66 -> t.appKeypad = on
67 -> backarrowBs = on
69 -> t.lrMargins = on
}
}
/** DECRQM's answers for the modes [mode] has */
override fun extraModeState(m: Int): Int {
if (operatingLevel < 4) return 0
/** DECRQM's 1 for set, 2 for reset */
fun b(v: Boolean) = if (v) 1 else 2
return when (m) {
66 -> b(t.appKeypad)
67 -> b(backarrowBs)
69 -> b(t.lrMargins)
else -> 0
}
}
/** DECRQSS for the margins (DECSLRM) and DECSACE */
override fun extraStatus(q: String): String? = when {
operatingLevel < 4 -> null
q == "s" -> "${t.left + 1};${t.right + 1}s"
q == "*x" -> "${if (rectangles.rectangle) 2 else 1}*x"
else -> null
}
/** DECBKM set: the backarrow key sends BS; else as ever (the user's setting, the VT320's keys) */
override fun keyOctets(k: Key, shift: Boolean, alt: Boolean, ctrl: Boolean): ByteArray? {
if (k == Key.BACKSPACE && backarrowBs && !alt && !ctrl) return byteArrayOf(0x08)
return super.keyOctets(k, shift, alt, ctrl)
}
/** DECSTR: DECSACE back to the stream, the backarrow as at the start */
override fun softReset() {
super.softReset()
rectangles.rectangle = false
backarrowBs = false
}
companion object {
/** the pages a VT420 has */
const val PAGES = 6
}
}
@@ -12,13 +12,21 @@ import org.dmodem.app.terminal.TerminalEmulator.MouseMode
* the levels that read more extend this class.
*/
open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : TerminalInterpreter(t) {
// G0, G1 and which of them is in use
private var g0 = GSet.ASCII
private var g1 = GSet.ASCII
private var shiftOut = false
/** G0-G3, GL and GR (a VT100 uses G0, G1 and SO/SI of them) */
protected val sets = CharsetShifting()
/** G0, G1 and the shift, as DECSC saves them */
private class Charsets(val g0: GSet, val g1: GSet, val so: Boolean)
/** the keys the host loaded (DECUDK, a VT220's and later) */
protected val userKeys = UserKeys()
/** the level DECSCL set it to work at (at most the profile's) */
protected var operatingLevel = profile.level
private set
/** a designation's intermediates after the first (ESC ( % 5's %) */
private var designation = ""
/** what's written goes to the host-writable status line (DECSASD 1), not the screen */
private var statusActive = false
/** VT52 mode (DECANM reset): its interpreter, until ESC < */
private var vt52: Vt52Interpreter? = null
@@ -45,7 +53,12 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
// a DCS's handler: a sixel image, or a request's text
private var sixel: Sixel? = null
private var dcsText: StringBuilder? = null
private var dcsKind = 0
/** what the DCS's text is for: its intermediate and final, as "$q" (DECRQSS), "|" (DECUDK) */
private var dcsKind = ""
/** the DCS's first two parameters, as it began (all of them in [dcsParams]) */
private var dcsP0 = 0
private var dcsP1 = 0
private var dcsParams = IntArray(0)
/** xterm's extensions known */
protected val xterm: Boolean get() = profile.has(VtFeature.XTERM)
@@ -118,17 +131,25 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
0x90 -> startDcs()
0x98, 0x9e, 0x9f -> state = State.STRING
0x84 -> t.index()
0x8e -> if (operatingLevel >= 2) sets.singleShift(2)
0x8f -> if (operatingLevel >= 2) sets.singleShift(3)
0x85 -> { t.carriageReturn(); t.index() }
0x8d -> t.reverseIndex()
0x88 -> t.setTab()
}
return
}
t.print((if (shiftOut) g1 else g0).map(cp))
val c = sets.map(cp, t.decoder.charset == TermCharset.LATIN1)
if (statusActive) t.statusLine.print(c, t.style) else t.print(c)
}
/** a C0 control: ENQ's answerback, the bell, BS, HT, LF/VT/FF, CR, SO/SI, CAN/SUB, ESC */
private fun control(cp: Int) {
if (statusActive && (cp == 0x0d || cp == 0x08)) {
// (on the status line only CR and BS move the cursor)
t.statusLine.moveTo(if (cp == 0x0d) 0 else t.statusLine.x - 1)
return
}
when (cp) {
0x05 -> if (t.answerback.isNotEmpty()) t.reply(t.answerback)
0x07 -> t.listener?.onBell()
@@ -140,8 +161,8 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
if (t.newlineMode) t.carriageReturn()
}
0x0d -> t.carriageReturn()
0x0e -> shiftOut = true
0x0f -> shiftOut = false
0x0e -> sets.lockGl(1)
0x0f -> sets.lockGl(0)
0x18, 0x1a -> state = State.GROUND
0x1b -> state = State.ESC
}
@@ -150,12 +171,17 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** the character after ESC: a sequence begun, or its one-character command done */
private fun esc(cp: Int) {
state = State.GROUND
if (extraEsc(cp)) return
when (cp.toChar()) {
'[' -> startCsi()
']' -> { osc.setLength(0); state = State.OSC }
'P' -> startDcs()
'X', '^', '_' -> state = State.STRING
'(', ')', '*', '+', '#', ' ', '%' -> { intermediate = cp; state = State.ESC_INTER }
'(', ')', '*', '+', '-', '.', '/', '#', ' ', '%' -> {
intermediate = cp
designation = ""
state = State.ESC_INTER
}
'7' -> t.saveCursor()
'8' -> t.restoreCursor()
'D' -> t.index()
@@ -165,6 +191,8 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
'c' -> t.reset()
// DECID: as DA1
'Z' -> t.reply(profile.primaryDa)
// the locking shifts (LS2, LS3, LS1R-LS3R) and single shifts (SS2, SS3): a VT220's
'n', 'o', '~', '}', '|', 'N', 'O' -> if (operatingLevel >= 2) shift(cp.toChar())
'=' -> t.appKeypad = true
'>' -> t.appKeypad = false
'\\' -> {}
@@ -172,12 +200,50 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
}
}
/** the character after ESC and an intermediate: G0's or G1's set designated, a line's size, DECALN */
/** ESC [c]'s shift: GL to G2 or G3, GR to G1-G3, or the next character from G2 or G3 */
private fun shift(c: Char) {
when (c) {
'n' -> sets.lockGl(2)
'o' -> sets.lockGl(3)
'~' -> sets.lockGr(1)
'}' -> sets.lockGr(2)
'|' -> sets.lockGr(3)
'N' -> sets.singleShift(2)
'O' -> sets.singleShift(3)
}
}
/** whether this terminal (at the level it works at) has [set] */
private fun knows(set: GSet): Boolean = xterm || set.level <= operatingLevel
/** G[slot] given the 94- or 96-character set [designator] names (< the preferred supplemental set), if this terminal has it */
private fun designate(slot: Int, designator: String, is96: Boolean) {
if (slot >= 2 && operatingLevel < 2 && !xterm) return
val set = when {
sets.soft.names(designator, is96) -> GSet.SOFT
designator == "<" && !is96 -> sets.preferred
else -> GSet.byDesignator(designator, is96) ?: return
}
if (knows(set)) sets.designate(slot, set)
}
/** the character after ESC and an intermediate: a set designated (ESC ( to ESC /), a line's size, DECALN, S7C1T/S8C1T */
private fun escInter(cp: Int) {
val i = intermediate.toChar()
if (cp in 0x20..0x2f && i in "()*+-./" && designation.isEmpty()) {
// a designator of two characters (DEC Supplemental's % 5)
designation = cp.toChar().toString()
return
}
state = State.GROUND
when (intermediate.toChar()) {
'(' -> GSet.byFinal(cp)?.let { g0 = it }
')' -> GSet.byFinal(cp)?.let { g1 = it }
val d = designation + cp.toChar()
when (i) {
'(', ')', '*', '+' -> designate("()*+".indexOf(i), d, is96 = false)
'-', '.', '/' -> designate("-./".indexOf(i) + 1, d, is96 = true)
' ' -> when (cp.toChar()) {
'F' -> t.eightBitReplies = false
'G' -> if (operatingLevel >= 2) t.eightBitReplies = true
}
'#' -> when (cp.toChar()) {
'3' -> t.setLineSize(LineSize.DOUBLE_TOP)
'4' -> t.setLineSize(LineSize.DOUBLE_BOTTOM)
@@ -239,6 +305,21 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
*/
protected open fun extraCsi(final: Int, marker: Int, inter: Int): Boolean = false
/** an ESC and the character [cp] a subclass carries out (a VT420's DECBI, DECFI): true if it did */
protected open fun extraEsc(cp: Int): Boolean = false
/** DECRQSS's answer for [q] a subclass has (without the DCS around it), or null */
protected open fun extraStatus(q: String): String? = null
/** DECRQM's answer for DEC mode [m] a subclass has (1 set, 2 reset), or 0 */
protected open fun extraModeState(m: Int): Int = 0
/** whether a subclass takes the text of a DCS ended by [final] with [inter]mediate (0 none) */
protected open fun wantsDcs(final: Int, inter: Int): Boolean = false
/** a DCS [wantsDcs] took, ended: its intermediate and final as [kind] ("$p"), its parameters and its text */
protected open fun extraDcs(kind: String, params: IntArray, text: String) {}
/** how many parameters the CSI has */
protected val paramCount: Int get() = nParams
@@ -253,6 +334,7 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
private fun dispatchCsi(final: Int) {
if (extraCsi(final, privateMarker, intermediate)) return
val c = final.toChar()
if (statusActive && statusCsi(c)) return
if (privateMarker == '?'.code) {
if (intermediate == '$'.code && c == 'p') {
// DECRQM: a DEC mode asked about
@@ -262,8 +344,10 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
when (c) {
'h' -> for (i in 0 until maxOf(nParams, 1)) decMode(params[i], true)
'l' -> for (i in 0 until maxOf(nParams, 1)) decMode(params[i], false)
'J' -> t.eraseDisplay(p(0, 0))
'K' -> t.eraseLine(p(0, 0))
// DECSED and DECSEL: what DECSCA didn't protect erased (a VT220's)
'J' -> t.eraseDisplay(p(0, 0), selective = operatingLevel >= 2)
'K' -> t.eraseLine(p(0, 0), selective = operatingLevel >= 2)
'n' -> decStatus(p(0, 0))
'S' -> if (xterm) graphicsAttributes(p(0, 0), p(1, 0))
'i' -> if (profile.has(VtFeature.PRINTER)) when (p(0, 0)) {
1 -> printer.printLine(t.cursorY)
@@ -295,6 +379,23 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
intermediate == ' '.code && c == 'q' -> t.cursorStyle = p(0, 0).coerceIn(0, 6)
// DECRQM: an ANSI mode asked about
intermediate == '$'.code && c == 'p' -> t.reply("\u001b[${p(0, 0)};${ansiModeState(p(0, 0))}\$y")
// DECSCA: the characters written from now protected from DECSED and DECSEL (1) or not
intermediate == '"'.code && c == 'q' && operatingLevel >= 2 -> {
val a = Style.attrs(t.style) and Style.PROTECTED.inv()
t.style = Style.withAttrs(t.style, if (p(0, 0) == 1) a or Style.PROTECTED else a)
}
// DECSCL: the level to work at (61 a VT100 ... 6n this one's), and 7-bit (1) or 8-bit replies
intermediate == '"'.code && c == 'p' && profile.level >= 2 -> conformance(p(0, 0), param(1))
// DECRQPSR: the cursor's state (DECCIR) or the tab stops (DECTABSR)
intermediate == '$'.code && c == 'w' && (operatingLevel >= 3 || xterm) -> presentationState(p(0, 0))
// DECSSDT: no status line (0), the indicators (1), the host's (2); DECSASD: writing to the screen (0) or to it (1)
intermediate == '$'.code && c == '~' && operatingLevel >= 3 -> {
t.statusType = p(0, 0).coerceIn(0, 2)
if (t.statusType != 2) statusActive = false
}
intermediate == '$'.code && c == '}' && operatingLevel >= 3 -> statusActive = p(0, 0) == 1 && t.statusType == 2
// DECRQUPSS: the user-preferred supplemental set
intermediate == '&'.code && c == 'u' && (operatingLevel >= 3 || xterm) -> t.reply(preferredSetString())
}
return
}
@@ -391,6 +492,7 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** DECRQM's answer for a DEC mode: 1 set, 2 reset, 0 not one known */
private fun decModeState(m: Int): Int {
extraModeState(m).takeIf { it != 0 }?.let { return it }
/** DECRQM's 1 for set, 2 for reset */
fun b(v: Boolean) = if (v) 1 else 2
val dec = when (m) {
@@ -464,8 +566,10 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** SGR: the CSI's parameters applied to the current rendition (none: back to normal); colours only if the profile has them */
private fun sgr() {
// (DECSCA's protection isn't a rendition: SGR leaves it)
val kept = Style.attrs(t.style) and Style.PROTECTED
if (nParams == 0) {
t.style = Style.NORMAL
t.style = Style.withAttrs(Style.NORMAL, kept)
return
}
val color = profile.has(VtFeature.COLOR)
@@ -546,7 +650,7 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
if (v != 0 && v != 38 && v != 48 && v != 58 && v !in 30..49 && v !in 90..107) s = Style.withAttrs(s, a)
i++
}
t.style = s
t.style = Style.withAttrs(s, Style.attrs(s) or kept)
}
/** an OSC ended: the title, colours set, asked or reset, the clipboard, a hyperlink (xterm's: a DEC terminal ignores them) */
@@ -639,7 +743,10 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
private fun dcsStart(final: Int) {
sixel = null
dcsText = null
dcsKind = 0
dcsKind = ""
dcsP0 = param(0)
dcsP1 = param(1)
dcsParams = IntArray(nParams) { params[it] }
val max = TerminalEmulator.MAX_IMAGE
when {
final == 'q'.code && intermediate == 0 && privateMarker == 0 && profile.has(VtFeature.SIXEL) -> {
@@ -649,10 +756,15 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
sixel = Sixel(transparent = p(1, 0) == 1, maxWidth = maxW, maxHeight = maxH)
}
// DECRQSS (VT320 and later, xterm), XTGETTCAP: their text collected
final == 'q'.code && intermediate == '$'.code && (profile.level >= 3 || xterm) ||
final == 'q'.code && intermediate == '+'.code && xterm -> {
final == 'q'.code && intermediate == '$'.code && (operatingLevel >= 3 || xterm) ||
final == 'q'.code && intermediate == '+'.code && xterm ||
// DECUDK (a VT220's), DECAUPSS (a VT320's)
final == '|'.code && intermediate == 0 && operatingLevel >= 2 ||
final == '{'.code && intermediate == 0 && operatingLevel >= 2 ||
final == 'u'.code && intermediate == '!'.code && (operatingLevel >= 3 || xterm) ||
wantsDcs(final, intermediate) -> {
dcsText = StringBuilder()
dcsKind = intermediate
dcsKind = (if (intermediate != 0) intermediate.toChar().toString() else "") + final.toChar()
}
}
}
@@ -660,7 +772,8 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** a DCS's data character: to the sixel image, or to the request's text */
private fun dcsPut(cp: Int) {
sixel?.let { it.feed(cp); return }
dcsText?.let { if (it.length < 1024) it.appendCp(cp) }
// (a soft font's glyphs: up to 96 of them)
dcsText?.let { if (it.length < (if (dcsKind == "{") 65536 else 1024)) it.appendCp(cp) }
}
/** the DCS cancelled: its image or text dropped */
@@ -677,17 +790,34 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
}
dcsText?.let { q ->
dcsText = null
if (dcsKind == '$'.code) statusString(q.toString()) else t.reply("\u001bP0+r\u001b\\")
when (dcsKind) {
"\$q" -> statusString(q.toString())
"|" -> userKeys.load(dcsP0, dcsP1, q.toString())
"{" -> {
sets.soft.load(dcsParams, q.toString())
t.softGlyphs = sets.soft.font
}
"!u" -> assignPreferred(dcsP0, q.toString())
"+q" -> t.reply("\u001bP0+r\u001b\\")
else -> extraDcs(dcsKind, dcsParams, q.toString())
}
}
}
/** DECRQSS: the graphic rendition, the scrolling region, the cursor's style */
private fun statusString(q: String) {
val ok = when (q) {
val ok = extraStatus(q) ?: when (q) {
"m" -> sgrString() + "m"
"r" -> "${t.top + 1};${t.bottom + 1}r"
" q" -> "${t.cursorStyle.coerceAtLeast(1)} q"
"\"q" -> "0\"q"
"\"q" -> "${if (Style.attrs(t.style) and Style.PROTECTED != 0) 1 else 0}\"q"
"\"p" -> "${60 + operatingLevel};${if (t.eightBitReplies) 0 else 1}\"p"
// the lines a page has (DECSLPP), the columns (DECSCPP), the lines on the screen (DECSNLS)
"t" -> "${t.rows}t"
"\$|" -> "${t.cols}\$|"
"*|" -> "${t.rows}*|"
"\$~" -> "${t.statusType}\$~"
"\$}" -> "${if (statusActive) 1 else 0}\$}"
else -> null
}
t.reply(if (ok != null) "\u001bP1\$r$ok\u001b\\" else "\u001bP0\$r\u001b\\")
@@ -727,17 +857,95 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
// ------------------------------------------------------------------
// the interpreter's own state
/** G0, G1 and the shift for DECSC */
override fun charsetState(): Any = Charsets(g0, g1, shiftOut)
/** G0-G3 and the shifts for DECSC */
override fun charsetState(): Any = sets.save()
/** G0, G1 and the shift as DECSC saved them (none: ASCII in both) */
/** G0-G3 and the shifts as DECSC saved them (none: as at the start) */
override fun restoreCharsetState(s: Any?) {
val c = s as? Charsets
g0 = c?.g0 ?: GSet.ASCII
g1 = c?.g1 ?: GSet.ASCII
shiftOut = c?.so ?: false
sets.restore(s as? CharsetShifting.Saved)
}
/** DECSCL: [level] 61-65 (a VT100 to a VT5xx, at most this one), [c1] 1 for 7-bit replies; a soft reset after */
private fun conformance(level: Int, c1: Int) {
if (level !in 61..65) return
operatingLevel = minOf(level - 60, profile.level)
t.eightBitReplies = operatingLevel >= 2 && c1 != 1
t.softReset()
}
/**
* a CSI while writing to the status line: the cursor along it (CUF,
* CUB, CHA, CUP's column), EL on it; SGR, the modes and DECSASD as
* ever (false: carried out as usual); the rest ignored
*/
private fun statusCsi(c: Char): Boolean {
val s = t.statusLine
if (privateMarker != 0 || intermediate != 0) return privateMarker == 0 && intermediate == '$'.code && c != '}' && c != '~'
when (c) {
'C' -> s.moveTo(s.x + p(0, 1))
'D' -> s.moveTo(s.x - p(0, 1))
'G', '`' -> s.moveTo(p(0, 1) - 1)
'H', 'f' -> s.moveTo(p(1, 1) - 1)
'K' -> s.erase(p(0, 0), Style.erased(t.style))
'm', 'h', 'l' -> return false
}
return true
}
/** DSR with ?: the printer (15), the user-defined keys (25), the keyboard (26), the cursor with its page (6) */
private fun decStatus(n: Int) {
if (n == 6) {
val y = if (t.originMode) t.cursorY - t.top else t.cursorY
t.reply("\u001b[?${y + 1};${minOf(t.cursorX, t.cols - 1) + 1};${t.page + 1}R")
return
}
if (operatingLevel < 2) return
when (n) {
15 -> t.reply(if (profile.has(VtFeature.PRINTER)) "\u001b[?10n" else "\u001b[?13n")
25 -> t.reply(if (userKeys.locked) "\u001b[?21n" else "\u001b[?20n")
// North American, ready, an LK201
26 -> t.reply("\u001b[?27;1;0;0n")
}
}
/** DECRQPSR's answers: the cursor (1, DECCIR) or the tab stops (2, DECTABSR) */
private fun presentationState(n: Int) {
when (n) {
1 -> t.reply("\u001bP1\$u${cursorInformation()}\u001b\\")
2 -> t.reply("\u001bP2\$u${t.tabStops().joinToString("/") { (it + 1).toString() }}\u001b\\")
}
}
/** DECCIR's: the cursor's row, column and page; its rendition, protection and flags; GL, GR and the sets' sizes and designators */
private fun cursorInformation(): String {
val a = Style.attrs(t.style)
/** 0x40 with the bits the flags given set, as DECCIR's characters are */
fun bits(vararg f: Boolean): Char = (0x40 + f.withIndex().sumOf { (i, on) -> if (on) 1 shl i else 0 }).toChar()
val rend = bits(a and Style.BOLD != 0, a and Style.ANY_UNDERLINE != 0, a and Style.BLINK != 0, a and Style.INVERSE != 0)
val att = bits(a and Style.PROTECTED != 0)
val flag = bits(t.originMode, sets.single == 2, sets.single == 3, t.pendingWrap)
val css = bits(sets.is96(0), sets.is96(1), sets.is96(2), sets.is96(3))
val desig = (0..3).joinToString("") { sets.designator(it) }
val y = if (t.originMode) t.cursorY - t.top else t.cursorY
return "${y + 1};${minOf(t.cursorX, t.cols - 1) + 1};1;$rend;$att;$flag;${sets.gl};${sets.gr};$css;$desig"
}
/** DECRQUPSS's answer: the preferred supplemental set (0 for a 94-character one, 1 for 96) and its designator */
private fun preferredSetString(): String {
val s = sets.preferred
return "\u001bP${if (s.is96) 1 else 0}!u${s.designator}\u001b\\"
}
/** DECAUPSS: the preferred supplemental set made [designator]'s ([size] 0 a 94-character set, 1 a 96-character one): DEC Supplemental or Latin-1 */
private fun assignPreferred(size: Int, designator: String) {
val s = GSet.byDesignator(designator, is96 = size == 1) ?: return
if (s == GSet.DEC_SUPPLEMENTAL || s == GSet.LATIN1) sets.preferred = s
}
/** with Shift, F6-F20 send what the host loaded into them (DECUDK), if it did */
override fun keyOctets(k: Key, shift: Boolean, alt: Boolean, ctrl: Boolean): ByteArray? =
if (shift && !alt && !ctrl && operatingLevel >= 2) userKeys.forKey(k) else null
/** VT52 mode: a [Vt52Interpreter] reads what comes, with DEC Special Graphics, until its ESC < */
private fun enterVt52() {
vt52 = Vt52Interpreter(t, GSet.DEC_GRAPHICS, "\u001b/Z") {
@@ -751,8 +959,14 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
restoreCharsetState(null)
}
/** RIS: the parser in its ground state, no DCS under way */
/** RIS: the parser in its ground state, no DCS under way, the level the profile's, the keys and preferred set cleared */
override fun reset() {
operatingLevel = profile.level
t.eightBitReplies = false
userKeys.reset()
sets.preferred = GSet.LATIN1
sets.soft.reset()
statusActive = false
softReset()
vt52 = null
t.vt52Keys = false
@@ -166,7 +166,9 @@ class DecLevelTest {
/** a DEC profile's key bar has the keypad page; the next page's label wraps */
@Test
fun keyBars() {
assertEquals(KeyBars.DEC, TerminalProfiles.VT220.keyBar)
assertEquals(KeyBars.DEC, TerminalProfiles.VT100.keyBar)
assertEquals(KeyBars.LK201, TerminalProfiles.VT220.keyBar)
assertEquals(KeyBars.DEC, TerminalProfiles.XTERM.keyBar)
assertEquals(KeyBars.STANDARD, TerminalProfiles.XTERM.keyBar.take(2))
assertEquals("KP", KeyBars.nextLabel(KeyBars.DEC, 1))
assertEquals("ABC", KeyBars.nextLabel(KeyBars.DEC, 2))
@@ -0,0 +1,122 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.Test
class VideotexTest {
private val replies = StringBuilder()
private val keys = KeyEncoder()
/** a terminal of [profile] at its own size, whose replies are kept */
private fun term(profile: TerminalProfile, cols: Int = 40, rows: Int = 25): TerminalEmulator {
replies.setLength(0)
return TerminalEmulator(cols, rows, 100, profile) { b -> b.forEach { replies.append((it.toInt() and 0xff).toChar()) } }
}
/** [s] fed in as Latin-1 octets */
private fun TerminalEmulator.send(s: String) = append(s.latin1())
/** the mosaics: six bits each, contiguous and separated, drawn 6x9 */
@Test
fun mosaics() {
assertEquals(' '.code, Mosaic.code(0, false))
assertEquals(0x3f, Mosaic.bits(0x7f))
assertEquals(0x01, Mosaic.bits(0x21))
val all = Mosaic.code(0x3f, false)
assertEquals(0b111111, Mosaic.font.row(all, 0))
val sep = Mosaic.code(0x3f, true)
assertEquals(0b110110, Mosaic.font.row(sep, 0))
assertEquals(0, Mosaic.font.row(sep, 2))
}
/** Viewdata: 40x24, attributes taking a cell and changing the rest of the row, written in again when one changes */
@Test
fun viewdataAttributes() {
val t = term(TerminalProfiles.VIEWDATA, rows = 24)
assertEquals(40, t.requestedColumns)
assertEquals(24, t.requestedRows)
// red text, then yellow mosaics: a full block (0x7f) and a top left one (0x21)
t.send("\u001bAHi\u001bS\u007f!")
val l = t.line(0)
assertEquals(' '.code, l.chars[0])
assertEquals("Hi", l.text(1, 3))
assertEquals(1, Style.fg(l.styles[1]))
assertEquals(Mosaic.code(0x3f, false), l.chars[4])
assertEquals(Mosaic.code(0x01, false), l.chars[5])
assertEquals(3, Style.fg(l.styles[4]))
assertNotNull(t.glyphFor(l.chars[4]))
// the attribute at column 0 changed to green: the whole row follows
t.send("\u001e\u001bB")
assertEquals(2, Style.fg(t.line(0).styles[1]))
// new background (0x1d) takes the colour; teletext's # and £
t.send("\r\n\u001bD\u001b]#_")
val m = t.line(1)
assertEquals(4, Style.bg(m.styles[2]))
assertEquals("£#", m.text(2, 4))
// separated mosaics, and the cursor wrapping round from the last row to the first
t.send("\u000c\u001bQ\u001bZ\u007f")
assertEquals(Mosaic.code(0x3f, true), t.line(0).chars[2])
t.send("\u000b")
assertEquals(23, t.cursorY)
// Enter and # send Prestel's #
assertContentEquals(byteArrayOf(0x5f), t.keyOctets(keys, Key.ENTER))
assertContentEquals(byteArrayOf(0x5f), t.charOctets(keys, '#'.code))
}
/** the Minitel: row 0 its status row, US addressing, colours, the zone's background at a delimiter, SS2's accents, mosaics */
@Test
fun minitelVideotex() {
val t = term(TerminalProfiles.MINITEL)
assertEquals(25, t.requestedRows)
assertEquals(1, t.cursorY)
// row 5 column 3, red on a blue zone: the background from the space on
t.send("\u001fEC\u001bA\u001bTa b")
val l = t.line(5)
assertEquals("a b", l.text(2, 5))
assertEquals(1, Style.fg(l.styles[2]))
assertEquals(0, Style.bg(l.styles[2]))
assertEquals(4, Style.bg(l.styles[3]))
// SS2 accents, a G2 symbol, REP
t.send("\u001fFA\u0019Be\u0019Aa\u0019Kc\u0019#x\u0012B")
assertEquals("éàç£xxx", t.line(6).text(0, 7))
// mosaics by SO, separated by ESC Z from the next one on
t.send("\u001fGA\u000e\u007f\u001bZ\u007f\u000fA")
val g = t.line(7)
assertEquals(Mosaic.code(0x3f, false), g.chars[0])
assertEquals(Mosaic.code(0x3f, true), g.chars[1])
assertEquals('A'.code, g.chars[2])
// FF clears and goes to row 1; the cursor wraps from the last row to row 1
t.send("\u000c")
assertEquals(1, t.cursorY)
t.send("\u000b")
assertEquals(24, t.cursorY)
t.send("\n")
assertEquals(1, t.cursorY)
}
/** the Minitel's protocol: who it is, where the cursor is, CSI, its keys, and the Téléinformatique mode (a VT100) */
@Test
fun minitelProtocol() {
val t = term(TerminalProfiles.MINITEL)
t.send("\u001b9{")
assertEquals("\u0001Cv;\u0004", replies.toString())
replies.setLength(0)
t.send("\u001b[3;5H\u001ba")
assertEquals("\u001fCE", replies.toString())
assertContentEquals(byteArrayOf(0x13, 0x41), t.keyOctets(keys, Key.ENTER))
assertContentEquals(byteArrayOf(0x19, 0x42, 'e'.code.toByte()), t.charOctets(keys, 'é'.code))
// Téléinformatique: 80x24, a VT100's sequences, until ESC [ ? {
t.send("\u001b:1}")
assertEquals(80, t.requestedColumns)
t.send("\u001b[2;3HZ")
assertEquals('Z'.code, t.line(1).chars[2])
t.send("\u001b[?{")
assertEquals(40, t.requestedColumns)
assertEquals(1, t.cursorY)
}
}
@@ -0,0 +1,193 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.Test
class Vt320Test {
private val replies = StringBuilder()
private val keys = KeyEncoder()
/** a terminal of [profile] whose replies are kept */
private fun term(profile: TerminalProfile = TerminalProfiles.VT320, cols: Int = 20, rows: Int = 4): TerminalEmulator {
replies.setLength(0)
return TerminalEmulator(cols, rows, 100, profile) { b -> b.forEach { replies.append((it.toInt() and 0xff).toChar()) } }
}
/** [s] fed in as Latin-1 octets */
private fun TerminalEmulator.send(s: String) = append(s.latin1())
/** the replies so far, then forgotten */
private fun taken(): String = replies.toString().also { replies.setLength(0) }
/** G2 and G3 designated and shifted in: locking (LS2, LS3), single (SS2, SS3, and their C1 forms), and GR's (LS1R-LS3R) */
@Test
fun shifts() {
val t = term()
// G2 DEC Graphics, G3 DEC Technical; q in G2 a line, a in G3 an alpha
t.send("\u001b*0\u001b+>q\u001bNq\u001bOaq")
assertEquals("q─αq", t.line(0).text().substring(0, 4))
t.send("\r\u001bnq\u001boa\u000fq")
assertEquals("─αq", t.line(0).text().substring(0, 3))
// (C1 controls and GR: only when the line's octets are Latin-1's)
t.decoder.charset = TermCharset.LATIN1
t.send("\r\u008eq\u008fa")
assertEquals("─α", t.line(0).text().substring(0, 2))
// G1 DEC Graphics in GR by LS1R, then G2 Latin-1 by LS2R
t.send("\r\u001b)0\u001b~ñ\u001b.A\u001b}é")
assertEquals("─é", t.line(0).text().substring(0, 2))
// a VT100 has no G2 or G3
val v = term(TerminalProfiles.VT100)
v.send("\u001b*0\u001bNq")
assertEquals("q", v.line(0).text().substring(0, 1))
}
/** two-character designators, the national sets, 96-character sets, and DECSC keeping them */
@Test
fun designations() {
val t = term()
// DEC Supplemental in G0: 0x28 is ¤, 0x57 Œ
t.send("\u001b(%5(W\u001b(B")
assertEquals("¤Œ", t.line(0).text().substring(0, 2))
// German in G0: [ is Ä, } ü
t.send("\r\u001b(K[}\u001b(B")
assertEquals("Äü", t.line(0).text().substring(0, 2))
// Latin-1 as a 96-character set in G1, shifted into GL: A is Á
t.send("\r\u001b-A\u000eA\u000f")
assertEquals("Á", t.line(0).text().substring(0, 1))
// saved and restored with the cursor
t.send("\r\u001b(0\u001b7\u001b(B\u001b8q")
assertEquals("─", t.line(0).text().substring(0, 1))
// DEC Technical is a VT320's, not a VT220's
val v = term(TerminalProfiles.VT220)
v.send("\u001b(>a")
assertEquals("a", v.line(0).text().substring(0, 1))
}
/** DECSCA protects what's written from DECSED and DECSEL, but not from ED and EL; SGR leaves it */
@Test
fun selectiveErase() {
val t = term()
t.send("ab\u001b[1\"q\u001b[0mCD\u001b[0\"qef")
t.send("\u001b[?2K")
assertEquals(" CD ", t.line(0).text().padEnd(6))
t.send("\u001b[2K")
assertEquals(" ", t.line(0).text().padEnd(6))
t.send("\r\u001b[1\"qX\u001b[0\"qy\r\u001b[?J")
assertEquals("X ", t.line(0).text().padEnd(2))
t.send("\u001bP\$q\"q\u001b\\")
assertEquals("\u001bP1\$r0\"q\u001b\\", taken())
}
/** S8C1T's 8-bit replies, S7C1T's 7-bit, DECSCL's level and its report */
@Test
fun controlsAndLevel() {
val t = term()
t.send("\u001b G\u001b[5n")
assertEquals("\u009b0n", taken())
t.send("\u001b F\u001b[5n")
assertEquals("\u001b[0n", taken())
t.send("\u001b[62;1\"p\u001bP\$q\"p\u001b\\")
// (at level 2 DECRQSS is gone: a VT220 hasn't got it)
assertEquals("", taken())
t.send("\u001b[63;0\"p\u001bP\$q\"p\u001b\\")
assertEquals("\u0090" + "1\$r63;0\"p\u009c", taken())
t.send("\u001bc\u001b[c")
assertEquals("\u001b[?63;1;2;6;7;8;9c", taken())
t.send("\u001b[>c")
assertEquals("\u001b[>24;10;0c", taken())
}
/** DSR's DEC questions, DECCIR, DECTABSR and the preferred supplemental set */
@Test
fun reports() {
val t = term()
t.send("\u001b[?15n\u001b[?25n\u001b[?26n")
assertEquals("\u001b[?10n\u001b[?20n\u001b[?27;1;0;0n", taken())
t.send("\u001b[2;3H\u001b[?6n")
assertEquals("\u001b[?2;3;1R", taken())
t.send("\u001b[1;7m\u001b*0\u001b}\u001b[1\$w")
assertEquals("\u001bP1\$u2;3;1;I;@;@;0;2;H;BB0A\u001b\\", taken())
t.send("\u001b[3g\u001bH\u001b[2\$w")
assertEquals("\u001bP2\$u3\u001b\\", taken())
t.send("\u001b[&u")
assertEquals("\u001bP1!uA\u001b\\", taken())
t.send("\u001bP0!u%5\u001b\\\u001b[&u")
assertEquals("\u001bP0!u%5\u001b\\", taken())
// ESC ( < : the preferred set
t.send("\u001b(<(")
assertEquals("¤", t.line(1).text().substring(2, 3))
}
/** DECUDK: Shift and F6-F20 send what the host loaded, until it locks them and RIS clears them */
@Test
fun userDefinedKeys() {
val t = term()
// F6 "hi", F20 "ok", left unlocked
t.send("\u001bP0;1|17/6869;34/6f6b\u001b\\")
assertContentEquals("hi".encodeToByteArray(), t.keyOctets(keys, Key.F6, shift = true))
assertContentEquals("ok".encodeToByteArray(), t.keyOctets(keys, Key.F20, shift = true))
assertEquals("\u001b[17~", t.keyOctets(keys, Key.F6).decodeToString())
// more loaded, F6 kept (Pc 1); then locked
t.send("\u001bP1;0|18/41\u001b\\")
assertContentEquals("hi".encodeToByteArray(), t.keyOctets(keys, Key.F6, shift = true))
assertContentEquals("A".encodeToByteArray(), t.keyOctets(keys, Key.F7, shift = true))
t.send("\u001bP0;1|17/42\u001b\\\u001b[?25n")
assertEquals("\u001b[?21n", taken())
assertContentEquals("hi".encodeToByteArray(), t.keyOctets(keys, Key.F6, shift = true))
t.send("\u001bc")
assertEquals("\u001b[17;2~", t.keyOctets(keys, Key.F6, shift = true).decodeToString())
// the LK201's other keys
assertEquals("\u001b[28~", keys.key(Key.F15, false))
assertEquals("\u001b[1~", keys.key(Key.FIND, false))
assertNull(UserKeys().get(17))
}
/** DECSSDT and DECSASD: the host's status line written, the cursor kept on it, the indicators; RIS takes it away */
@Test
fun statusLine() {
val t = term()
t.send("\u001b[2\$~\u001b[1\$}Hello\rJ\u001b[3GL\u001b[0\$}x")
assertEquals("JeLlo", t.statusText().substring(0, 5))
assertEquals("x", t.line(0).text())
t.send("\u001bP\$q\$~\u001b\\")
assertEquals("\u001bP1\$r2\$~\u001b\\", taken())
t.send("\u001b[1\$~")
assertEquals("0001,002", t.statusText())
t.send("\u001bc")
assertEquals("", t.statusText())
// (a VT220 has none)
val v = term(TerminalProfiles.VT220)
v.send("\u001b[2\$~")
assertEquals("", v.statusText())
}
/** DECDLD: soft characters loaded as sixels, designated by their Dscs, drawn from their glyphs */
@Test
fun softFont() {
val t = term()
// two characters 8x10 from 0x21, designated SP @
t.send("\u001bP0;1;0;8;0;2;10;0{ @~~~~~~~~/????????;@\u001b\\")
t.send("\u001b( @!\"#\u001b(B!")
val l = t.line(0)
assertEquals(SoftFont.BASE + 0x21, l.chars[0])
assertEquals(SoftFont.BASE + 0x22, l.chars[1])
assertEquals('#'.code, l.chars[2])
assertEquals('!'.code, l.chars[3])
val g = t.glyphFor(SoftFont.BASE + 0x21)!!
assertEquals(8, g.width)
assertEquals(10, g.height)
assertEquals(0xff, g.row(SoftFont.BASE + 0x21, 5))
assertEquals(0, g.row(SoftFont.BASE + 0x21, 6))
assertEquals(0x80, g.row(SoftFont.BASE + 0x22, 0))
// DECCIR names the soft set's designator
t.send("\u001b( @\u001b[1\$w")
assertEquals(" @BAA", taken().substringAfterLast(';').removeSuffix("\u001b\\"))
t.send("\u001bc")
assertNull(t.glyphFor(SoftFont.BASE + 0x21))
}
}
@@ -0,0 +1,168 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.Test
class Vt420Test {
private val replies = StringBuilder()
private val keys = KeyEncoder()
/** a terminal of [profile] whose replies are kept */
private fun term(profile: TerminalProfile = TerminalProfiles.VT420, cols: Int = 10, rows: Int = 4): TerminalEmulator {
replies.setLength(0)
return TerminalEmulator(cols, rows, 100, profile) { b -> b.forEach { replies.append((it.toInt() and 0xff).toChar()) } }
}
/** [s] fed in as Latin-1 octets */
private fun TerminalEmulator.send(s: String) = append(s.latin1())
/** the replies so far, then forgotten */
private fun taken(): String = replies.toString().also { replies.setLength(0) }
/** row [y]'s text, [n] cells of it (blanks as spaces) */
private fun TerminalEmulator.row(y: Int, n: Int = cols): String = line(y).text().padEnd(n).substring(0, n)
/** DECLRMM and DECSLRM: text wraps at the right margin to the left one, and scrolls only between them */
@Test
fun margins() {
val t = term()
t.send("0123456789\r\n0123456789\r\n0123456789\r\n0123456789")
t.send("\u001b[?69h\u001b[3;6s")
assertEquals(0, t.cursorX)
// (CUP from home: column 3 is within the margins)
t.send("\u001b[4;3HABCDEF")
assertEquals("0123456789", t.row(0))
assertEquals("01ABCD6789", t.row(2))
assertEquals("01EF 6789", t.row(3))
// CSI s is DECSLRM now; DECRQSS tells the margins
t.send("\u001bP\$qs\u001b\\")
assertEquals("\u001bP1\$r3;6s\u001b\\", taken())
// reset: CSI s saves the cursor again
t.send("\u001b[?69l\u001b[?69\$p")
assertEquals("\u001b[?69;2\$y", taken())
}
/** DECCRA, DECERA, DECFRA, DECSERA and the checksum */
@Test
fun rectangles() {
val t = term()
t.send("abcdefghij\r\nklmnopqrst")
// fill rows 3-4, columns 2-3 with X
t.send("\u001b[88;3;2;4;3\$x")
assertEquals(" XX ", t.row(2))
assertEquals(" XX ", t.row(3))
// copy rows 1-2, columns 1-3 to row 3, column 6
t.send("\u001b[1;1;2;3;1;3;6;1\$v")
assertEquals(" XX abc ", t.row(2))
assertEquals(" XX klm ", t.row(3))
// erase rows 1-2, columns 2-9
t.send("\u001b[1;2;2;9\$z")
assertEquals("a j", t.row(0))
// a protected cell kept by DECSERA, not by DECERA
t.send("\u001b[1;1H\u001b[1\"qP\u001b[0\"q\u001b[1;1;1;10\${")
assertEquals("P", t.row(0, 1))
// the checksum of row 1, columns 1-2: P and a blank, protected P
t.send("\u001b[7;1;1;1;1;2*y")
val sum = (-('P'.code + 0x04 + ' '.code)) and 0xffff
assertEquals("\u001bP7!~${sum.toString(16).uppercase().padStart(4, '0')}\u001b\\", taken())
}
/** DECCARA and DECRARA, in a stream or (DECSACE 2) a rectangle */
@Test
fun attributes() {
val t = term()
t.send("abcdefghij\r\nklmnopqrst")
// bold from row 1 column 9 to row 2 column 2: a stream
t.send("\u001b[1;9;2;2;1\$r")
assertEquals(Style.BOLD, Style.attrs(t.line(0).styles[9]))
assertEquals(Style.BOLD, Style.attrs(t.line(1).styles[0]))
assertEquals(0, Style.attrs(t.line(1).styles[5]))
// as a rectangle, inverse reversed over columns 1-2
t.send("\u001b[2*x\u001b[1;1;2;2;7\$t")
assertEquals(Style.INVERSE, Style.attrs(t.line(0).styles[0]))
assertEquals(Style.BOLD or Style.INVERSE, Style.attrs(t.line(1).styles[0]))
assertEquals(0, Style.attrs(t.line(0).styles[5]))
t.send("\u001bP\$q*x\u001b\\")
assertEquals("\u001bP1\$r2*x\u001b\\", taken())
}
/** DECIC and DECDC, DECBI and DECFI */
@Test
fun columns() {
val t = term()
t.send("0123456789\r\n0123456789")
t.send("\u001b[1;3H\u001b[2'}")
assertEquals("01 234567", t.row(0))
assertEquals("01 234567", t.row(1))
t.send("\u001b[3'~")
assertEquals("0134567 ", t.row(0))
// DECBI at the left edge: everything right a column; DECFI at the right edge: left a column
t.send("\u001b[1;1H\u001b6")
assertEquals(" 0134567 ", t.row(0))
t.send("\u001b[1;10H\u001b9")
assertEquals("0134567 ", t.row(0))
}
/** NP, PP, PPA, PPR and PPB: the pages kept apart, DECXCPR telling the page */
@Test
fun pages() {
val t = term()
t.send("one\u001b[U")
assertEquals(1, t.page)
assertEquals(0, t.cursorX)
t.send("two\u001b[?6n")
assertEquals("\u001b[?1;4;2R", taken())
t.send("\u001b[1 P")
assertEquals("one", t.row(0, 3))
t.send("\u001b[1 Q")
assertEquals("two", t.row(0, 3))
t.send("\u001b[9 Q")
assertEquals(Vt420Interpreter.PAGES - 1, t.page)
t.send("\u001bc")
assertEquals(0, t.page)
}
/** the lines and columns asked for, the keypad and backarrow modes, and the identities */
@Test
fun modesAndIdentity() {
val t = term()
t.send("\u001b[36*|")
assertEquals(36, t.requestedRows)
t.send("\u001b[132\$|")
assertEquals(132, t.requestedColumns)
t.send("\u001b[?66h")
assertEquals(true, t.appKeypad)
t.send("\u001b[?67h")
assertContentEquals(byteArrayOf(8), t.keyOctets(keys, Key.BACKSPACE))
t.send("\u001b[c\u001b[>c")
assertEquals("\u001b[?64;1;2;6;7;8;9;15;18;21;28c\u001b[>41;10;0c", taken())
val v = term(TerminalProfiles.VT520)
v.send("\u001b[\"v\u001b[>c")
assertEquals("\u001b[4;10;1;1;1\"w\u001b[>64;10;0c", taken())
// a VT320 hasn't the VT420's
val o = term(TerminalProfiles.VT320)
o.send("\u001b[36*|")
assertEquals(0, o.requestedRows)
}
/** a VT525's colours: DECAC, and the colour table reported (DECRQTSR) and restored (DECRSTS) */
@Test
fun colorTable() {
val t = term(TerminalProfiles.VT525)
t.send("\u001bP2\$p1;2;100;0;0/2;1;240;50;100\u001b\\")
assertEquals(0xffff0000.toInt(), t.colorOverride(1))
// (DEC's hue 240 is green)
assertEquals(0xff00ff00.toInt(), t.colorOverride(2))
t.send("\u001b[2\$u")
val table = taken()
assertEquals(true, table.startsWith("\u001bP2\$s0;2;"))
assertEquals(true, table.contains("/1;2;100;0;0/2;2;0;100;0/"))
t.send("\u001b[1;1;2,|")
assertEquals(0xffff0000.toInt(), t.colorOverride(256))
assertEquals(0xff00ff00.toInt(), t.colorOverride(257))
}
}