Graphics terminals: Tektronix 4014, ReGIS and the VT340 (Phase 4) (#38)

* Graphics: Tektronix 4014, ReGIS and the VT340

A Raster drawn over the screen (PictureLayer keeps it the screen's size
and puts it on the screen as picture tiles). The Tektronix 4014 as its
own terminal and as xterm's and the VT340's Tek mode (DECSET 38, on the
alternate screen until ESC ETX). ReGIS read as it comes in DCS p: P, V,
C (circles, arcs, curves), F, T, W, S (the colour map among them), R, L
and macrographs. The VT340 profile has sixel and ReGIS sharing 16
colour registers.

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

* iOS: sixel images and graphics pictures drawn

The bridge gives each row's image tiles as runs (ImageRun) and an
image's pixels as premultiplied RGBA in Latin-1; the iOS model makes a
CGImage once per image and the canvas draws each run clipped to its
cells.

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:33:42 -08:00
1 parent f2ecdb550c
commit e8dec59b58
16 files changed
+1759 -13

No files matched your search

@@ -0,0 +1,205 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
/**
* A graphics terminal's picture (ReGIS's, a Tektronix's): its own
* coordinates ([logicalWidth] x [logicalHeight], 0,0 top left) drawn into
* [width] x [height] pixels, the screen's, so it fills the text it lies
* over. Lines (with a pattern), points, circles and arcs, filled
* polygons and text from a [BitmapFont], each in a colour and a writing
* mode; what's never drawn stays transparent (0).
*/
class Raster(val width: Int, val height: Int, private val logicalWidth: Int, private val logicalHeight: Int) {
val pixels = IntArray(width * height)
/** how a pixel is written: over what's there, replacing it, complementing it, or erasing it */
enum class Mode { OVERLAY, REPLACE, COMPLEMENT, ERASE }
var mode = Mode.OVERLAY
/** the colour drawn in (ARGB) */
var color = 0xffffffff.toInt()
/** the background (ERASE writes it; REPLACE writes it where the pattern is off) */
var background = 0
/** the line pattern: 8 bits, the first pixel the high one (0xff solid) */
var pattern = 0xff
private var patternStep = 0
/** changed since [take] */
var dirty = false
private set
/** a logical x as a pixel column */
fun px(x: Int): Int = (x.toLong() * width / logicalWidth).toInt()
/** a logical y as a pixel row */
fun py(y: Int): Int = (y.toLong() * height / logicalHeight).toInt()
/** all of it [c] (0: transparent) */
fun clear(c: Int = 0) {
pixels.fill(c)
dirty = true
}
/** pixel ([x], [y]) written as the mode says ([on]: the pattern's bit there) */
private fun put(x: Int, y: Int, on: Boolean = true) {
if (x !in 0 until width || y !in 0 until height) return
val i = y * width + x
when (mode) {
Mode.OVERLAY -> if (on) pixels[i] = color
Mode.REPLACE -> pixels[i] = if (on) color else background
Mode.COMPLEMENT -> if (on) pixels[i] = pixels[i] xor 0x00ffffff or (0xff shl 24)
Mode.ERASE -> pixels[i] = background
}
dirty = true
}
/** a point at logical ([x], [y]) */
fun point(x: Int, y: Int) {
put(px(x), py(y))
}
/** a line from logical ([x0], [y0]) to ([x1], [y1]), in the pattern */
fun line(x0: Int, y0: Int, x1: Int, y1: Int) {
pixelLine(px(x0), py(y0), px(x1), py(y1))
}
/** Bresenham's line between two pixels, the pattern stepping along it */
private fun pixelLine(ax: Int, ay: Int, bx: Int, by: Int) {
var x = ax
var y = ay
val dx = abs(bx - ax)
val dy = -abs(by - ay)
val sx = if (ax < bx) 1 else -1
val sy = if (ay < by) 1 else -1
var err = dx + dy
while (true) {
put(x, y, pattern and (0x80 ushr (patternStep and 7)) != 0)
patternStep++
if (x == bx && y == by) break
val e2 = 2 * err
if (e2 >= dy) { err += dy; x += sx }
if (e2 <= dx) { err += dx; y += sy }
}
}
/** a circle round logical ([cx], [cy]) of radius [r] (in x's units) */
fun circle(cx: Int, cy: Int, r: Int) {
arc(cx, cy, r, 0.0, 360.0)
}
/** an arc round logical ([cx], [cy]), radius [r], from [start] degrees (0 east, counterclockwise) through [sweep] */
fun arc(cx: Int, cy: Int, r: Int, start: Double, sweep: Double) {
val steps = maxOf(16, (abs(sweep) / 360 * maxOf(8, px(abs(r)) * 2) * PI).toInt())
var lx = 0
var ly = 0
for (i in 0..steps) {
val a = (start + sweep * i / steps) * PI / 180
val x = px(cx) + (px(r) * cos(a)).roundToInt()
// (the same radius in pixels both ways: round on any screen)
val y = py(cy) - (px(r) * sin(a)).roundToInt()
if (i > 0) pixelLine(lx, ly, x, y)
lx = x
ly = y
}
}
/** the polygon through logical [points] (x, y pairs) filled, by scan lines (even-odd) */
fun fill(points: List<Pair<Int, Int>>) {
if (points.size < 3) return
val p = points.map { px(it.first) to py(it.second) }
val top = p.minOf { it.second }.coerceAtLeast(0)
val bottom = p.maxOf { it.second }.coerceAtMost(height - 1)
val xs = ArrayList<Int>()
for (y in top..bottom) {
xs.clear()
for (i in p.indices) {
val (x0, y0) = p[i]
val (x1, y1) = p[(i + 1) % p.size]
if (y0 == y1) continue
if (y >= minOf(y0, y1) && y < maxOf(y0, y1)) xs.add(x0 + (y - y0) * (x1 - x0) / (y1 - y0))
}
xs.sort()
for (k in 0 until xs.size - 1 step 2) for (x in xs[k]..xs[k + 1]) put(x, y)
}
}
/**
* [text] with its top left at logical ([x], [y]), each character
* [cw] x [ch] logical units drawn from [font] (its glyph scaled to the
* cell); the logical x after it
*/
fun text(x: Int, y: Int, text: String, font: BitmapFont, cw: Int, ch: Int): Int {
var cx = x
var i = 0
while (i < text.length) {
val cp = text.codePointAtIndex(i)
i += charCountOf(cp)
glyph(cp, cx, y, font, cw, ch)
cx += cw
}
return cx
}
/** [cp]'s glyph from [font] in the cell at logical ([x], [y]), [cw] x [ch] */
private fun glyph(cp: Int, x: Int, y: Int, font: BitmapFont, cw: Int, ch: Int) {
if (!font.has(cp)) return
val left = px(x)
val top = py(y)
val w = maxOf(1, px(x + cw) - left)
val h = maxOf(1, py(y + ch) - top)
for (yy in 0 until h) {
val row = font.row(cp, yy * font.height / h)
if (row == 0) continue
for (xx in 0 until w) {
val col = xx * font.width / w
if ((row shr (font.width - 1 - col)) and 1 != 0) put(left + xx, top + yy)
}
}
}
/** the picture as an image whose tiles are [cellWidth] x [cellHeight] (the screen's cells), not dirty after */
fun take(cellWidth: Int, cellHeight: Int): TermImage {
dirty = false
return TermImage(width, height, pixels.copyOf(), cellWidth, cellHeight, picture = true)
}
}
/**
* A graphics terminal's picture over the screen's text (a Tektronix's,
* ReGIS's): a [Raster] of [logicalWidth] x [logicalHeight] kept the
* screen's size in pixels, [setUp] on each new one, and put on the screen
* when it's been drawn on.
*/
class PictureLayer(
private val t: TerminalEmulator,
private val logicalWidth: Int,
private val logicalHeight: Int,
private val setUp: (Raster) -> Unit = {},
) {
var raster: Raster = make()
private set
/** a raster the screen's size, blank */
private fun make() = Raster(
maxOf(1, t.cols * t.cellPixelWidth), maxOf(1, t.rows * t.cellPixelHeight), logicalWidth, logicalHeight,
).also(setUp)
/** the picture started again, blank (what it showed taken off the screen at the next [flush]) */
fun reset() {
raster = make().also { it.clear() }
}
/** what was drawn put on the screen (if the screen's size changed, the picture started again at the new one: what's drawn can't be redrawn) */
fun flush() {
if (maxOf(1, t.cols * t.cellPixelWidth) != raster.width || maxOf(1, t.rows * t.cellPixelHeight) != raster.height) {
reset()
}
if (raster.dirty) t.showPicture(raster.take(t.cellPixelWidth, t.cellPixelHeight))
}
}
@@ -0,0 +1,851 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
import kotlin.math.sqrt
/**
* ReGIS, DEC's graphics language (a VT340's): what comes in DCS p … ST,
* read as it comes, each command run once the next has begun (or the
* string ended). Its commands: P (position), V (vectors), C (circles,
* arcs and curves), F (fill), T (text), W (writing controls), S (screen
* controls, the colour map among them), R (reports), L (loadable
* alphabets) and @ (macrographs). Drawn on an 800x480 screen (the
* address mapping S(A) changes what the coordinates mean) over the text,
* in the 16 colour [palette] registers it shares with the sixels.
*/
class Regis(private val t: TerminalEmulator, private val palette: IntArray) {
private val layer = PictureLayer(t, WIDTH, HEIGHT)
private val raster get() = layer.raster
/** what's come and not yet run */
private val pending = StringBuilder()
// the position, in the user's coordinates
private var x = 0
private var y = 0
/** a position put on the stack: P(B) or V(B) (bounded: V(E) closes the figure), or (S) */
private class Mark(val x: Int, val y: Int, val bounded: Boolean)
private val stack = ArrayList<Mark>()
/** the writing controls: the mode, the colour register, the pattern, the pixel vector multiplier, shading */
private data class Writing(
var mode: Raster.Mode = Raster.Mode.OVERLAY,
var color: Int = 7,
var pattern: Int = 0xff,
var negate: Boolean = false,
var multiplier: Int = 1,
var shading: Boolean = false,
var shadeY: Int = 0,
)
private var writing = Writing()
/** the text controls: a character's cell (in pixels of the 800x480 screen), the way the string goes, the alphabet */
private data class TextStyle(var cellW: Int = 10, var cellH: Int = 20, var dx: Int = 1, var dy: Int = 0, var alphabet: Int = 0)
private var text = TextStyle()
private var savedText: TextStyle? = null
/** the background's colour register (S(I)) */
private var background = 0
// the address mapping (S(A)): the user's coordinates at the screen's top left and bottom right
private var ax1 = 0
private var ay1 = 0
private var ax2 = WIDTH - 1
private var ay2 = HEIGHT - 1
private val macros = HashMap<Char, String>()
/** the loaded alphabets (1-3): each character's rows */
private val alphabets = HashMap<Int, MutableMap<Int, IntArray>>()
private val alphabetNames = HashMap<Int, String>()
private val fonts = HashMap<Int, BitmapFont>()
/** the alphabet L loads into */
private var loading = 1
/** a curve's points (C(B) closed, C(S) open), in the screen's coordinates, until C(E) */
private var curve: MutableList<Pair<Int, Int>>? = null
private var curveClosed = false
/** F's polygon: the points its commands went through, in the screen's coordinates */
private var filling: MutableList<Pair<Int, Int>>? = null
/** a DCS p began: [p1] 1 or 3 starts afresh (the position, the writing and text controls as at the start) */
fun begin(p1: Int) {
pending.setLength(0)
if (p1 == 1 || p1 == 3) restart()
}
/** one code point of the string: kept until its command is whole */
fun feed(cp: Int) {
if (pending.length < MAX_PENDING) pending.appendCp(cp)
}
/** the commands that are whole run, then the picture put on the screen */
fun flush() {
runPending(final = false)
layer.flush()
}
/** the string ended: what's left of it run */
fun end() {
runPending(final = true)
}
/** the string cancelled: what hadn't run dropped */
fun abort() {
pending.setLength(0)
}
/** RIS: the picture gone, the macrographs and alphabets forgotten, the controls as at the start */
fun reset() {
pending.setLength(0)
macros.clear()
alphabets.clear()
alphabetNames.clear()
fonts.clear()
background = 0
restart()
layer.reset()
}
/** the position, the stack, the writing and text controls and the address mapping as at the start */
private fun restart() {
x = 0
y = 0
stack.clear()
writing = Writing()
text = TextStyle()
savedText = null
ax1 = 0
ay1 = 0
ax2 = WIDTH - 1
ay2 = HEIGHT - 1
curve = null
filling = null
loading = 1
}
/** [pending]'s whole commands run (all of them, if [final]) and taken off it */
private fun runPending(final: Boolean) {
if (pending.isEmpty()) return
val s = pending.toString()
val used = run(s, final, 0)
pending.setLength(0)
if (used < s.length) pending.append(s, used, s.length)
}
/**
* the commands in [s] run, each once the next has begun (or all, if
* [final]); how much of [s] was used (the rest an unfinished command)
*/
private fun run(s: String, final: Boolean, depth: Int): Int {
var i = 0
while (i < s.length) {
val c = s[i]
if (c == '@') {
val used = macrograph(s, i, final, depth)
if (used < 0) return i
i = used
continue
}
if (c.uppercaseChar() !in COMMANDS) {
i++
continue
}
val e = commandEnd(s, i)
if (e < 0 && !final) return i
val end = if (e < 0) s.length else e
command(upperOutsideQuotes(s.substring(i, end)), depth)
i = end
}
return i
}
/**
* the macrograph at [i] (@:X … @; defined, @. all cleared, @X run);
* where it ends, or -1 if it isn't whole yet
*/
private fun macrograph(s: String, i: Int, final: Boolean, depth: Int): Int {
if (i + 1 >= s.length) return if (final) s.length else -1
val c = s[i + 1]
return when (c) {
':' -> {
if (i + 2 >= s.length) return if (final) s.length else -1
val close = s.indexOf("@;", i + 3)
if (close < 0) return if (final) s.length else -1
macros[s[i + 2].uppercaseChar()] = s.substring(i + 3, close)
close + 2
}
'.' -> {
macros.clear()
i + 2
}
else -> {
if (depth < MAX_DEPTH) macros[c.uppercaseChar()]?.let { run(it, true, depth + 1) }
i + 2
}
}
}
/** where the command at [start] ends: the next command (outside quotes, brackets and parentheses), or -1 if none has begun */
private fun commandEnd(s: String, start: Int): Int {
val hex = s[start].uppercaseChar() == 'L'
var quote = 0.toChar()
var parens = 0
var brackets = 0
for (j in start + 1 until s.length) {
val c = s[j]
when {
quote != 0.toChar() -> if (c == quote) quote = 0.toChar()
c == '\'' || c == '"' -> quote = c
c == '(' -> parens++
c == ')' -> if (parens > 0) parens--
c == '[' -> brackets++
c == ']' -> if (brackets > 0) brackets--
parens > 0 || brackets > 0 -> {}
c == ';' || c == '@' -> return j
// (L's rows are hex: their letters aren't commands)
hex && c.uppercaseChar() in 'A'..'F' -> {}
c.uppercaseChar() in COMMANDS -> return j
}
}
return -1
}
/** [s] in capitals but for its quoted strings */
private fun upperOutsideQuotes(s: String): String {
val b = StringBuilder(s.length)
var quote = 0.toChar()
for (c in s) {
when {
quote != 0.toChar() -> { if (c == quote) quote = 0.toChar(); b.append(c) }
c == '\'' || c == '"' -> { quote = c; b.append(c) }
else -> b.append(c.uppercaseChar())
}
}
return b.toString()
}
/** one command (its letter first, in capitals), its writing controls of the moment (a W option of its own) undone after */
private fun command(s: String, depth: Int) {
val c = Cursor(s, 1)
val saved = writing.copy()
var temporary = false
/** a W option of the command's own: the writing controls for it alone */
fun temp(o: Opt) {
o.sub?.let { applyWriting(it, writing) }
temporary = true
}
when (s[0]) {
'P' -> position(c, ::temp)
'V' -> vector(c, ::temp)
'C' -> circle(c, ::temp)
'F' -> fill(c, depth)
'T' -> text(c, ::temp)
'W' -> c.each(onGroup = { opts -> applyWriting(opts, writing) })
'S' -> c.each(onGroup = ::screen)
'R' -> c.each(onGroup = ::report)
'L' -> load(c)
}
if (temporary) writing = saved
}
/** P: to each position, the stack's (B, S, E), a pixel vector's step */
private fun position(c: Cursor, temp: (Opt) -> Unit) {
c.each(
onPosition = { p -> resolve(p).let { (nx, ny) -> x = nx; y = ny } },
onGroup = { opts ->
for (o in opts) when (o.letter) {
'B', 'S' -> stack.add(Mark(x, y, o.letter == 'B'))
'E' -> stack.removeLastOrNull()?.let { x = it.x; y = it.y }
'W' -> temp(o)
}
},
onDigit = { d -> step(d).let { (nx, ny) -> x = nx; y = ny } },
)
}
/** V: a line to each position ([] a dot), the stack's (B begun, E back, closing a bounded figure), a pixel vector's line */
private fun vector(c: Cursor, temp: (Opt) -> Unit) {
c.each(
onPosition = { p ->
if (p.empty) dot() else resolve(p).let { (nx, ny) -> lineTo(nx, ny) }
},
onGroup = { opts ->
for (o in opts) when (o.letter) {
'B', 'S' -> stack.add(Mark(x, y, o.letter == 'B'))
'E' -> stack.removeLastOrNull()?.let { m -> if (m.bounded) lineTo(m.x, m.y) else { x = m.x; y = m.y } }
'W' -> temp(o)
}
},
onDigit = { d -> step(d).let { (nx, ny) -> lineTo(nx, ny) } },
)
}
/**
* C: a circle round the position through each one given (C: round the
* one given, through the position), an arc of A degrees, or a curve
* through the positions from B or S to E
*/
private fun circle(c: Cursor, temp: (Opt) -> Unit) {
var center = false
var arc: Int? = null
c.each(
onPosition = { p ->
val (px, py) = resolve(p)
val cv = curve
if (cv != null) {
cv.add(dx(px) to dy(py))
x = px
y = py
} else {
round(px, py, center, arc)
}
},
onGroup = { opts ->
for (o in opts) when (o.letter) {
'C' -> center = true
'A' -> arc = o.num ?: 360
'B', 'S' -> {
curve = mutableListOf(dx(x) to dy(y))
curveClosed = o.letter == 'B'
}
'E' -> curve?.let { pts -> curve = null; spline(pts, curveClosed) }
'W' -> temp(o)
}
},
onDigit = { d -> step(d).let { (nx, ny) -> x = nx; y = ny; curve?.add(dx(nx) to dy(ny)) } },
)
}
/** a circle or arc: round the position through ([px], [py]), or ([center]) round that through the position */
private fun round(px: Int, py: Int, center: Boolean, arc: Int?) {
val (cx, cy) = if (center) dx(px) to dy(py) else dx(x) to dy(y)
val (ex, ey) = if (center) dx(x) to dy(y) else dx(px) to dy(py)
val r = sqrt(((ex - cx) * (ex - cx) + (ey - cy) * (ey - cy)).toDouble())
val start = if (arc == null) 0.0 else atan2(-(ey - cy).toDouble(), (ex - cx).toDouble()) * 180 / PI
val sweep = (arc ?: 360).toDouble()
val fill = filling
if (fill != null) {
val n = 48
for (i in 0..n) {
val a = (start + sweep * i / n) * PI / 180
fill.add((cx + r * cos(a)).roundToInt() to (cy - r * sin(a)).roundToInt())
}
} else {
setUp()
raster.arc(cx, cy, r.roundToInt(), start, sweep)
}
// (an arc round a given centre leaves the position at its end)
if (center && arc != null) {
val a = (start + sweep) * PI / 180
val (ux, uy) = user((cx + r * cos(a)).roundToInt(), (cy - r * sin(a)).roundToInt())
x = ux
y = uy
}
}
/** a Catmull-Rom curve through [pts] (screen coordinates), round to the first if [closed] */
private fun spline(pts: List<Pair<Int, Int>>, closed: Boolean) {
if (pts.size < 2) return
val n = pts.size
/** the [i]th point (wrapping round a closed curve, held at the ends of an open one) */
fun at(i: Int): Pair<Int, Int> = if (closed) pts[((i % n) + n) % n] else pts[i.coerceIn(0, n - 1)]
val spans = if (closed) n else n - 1
var last = pts[0]
for (s in 0 until spans) {
val p0 = at(s - 1)
val p1 = at(s)
val p2 = at(s + 1)
val p3 = at(s + 2)
for (k in 1..STEPS) {
val u = k.toDouble() / STEPS
/** one coordinate along the span */
fun cr(a: Int, b: Int, c: Int, d: Int): Int =
(0.5 * (2 * b + (-a + c) * u + (2 * a - 5 * b + 4 * c - d) * u * u + (-a + 3 * b - 3 * c + d) * u * u * u)).roundToInt()
val next = cr(p0.first, p1.first, p2.first, p3.first) to cr(p0.second, p1.second, p2.second, p3.second)
screenLine(last.first, last.second, next.first, next.second)
last = next
}
}
}
/** F(…): the commands in its parentheses run for the outline of a polygon, then the polygon filled */
private fun fill(c: Cursor, depth: Int) {
val inner = c.parenthesised() ?: return
val outer = filling
val pts = mutableListOf(dx(x) to dy(y))
filling = pts
run(inner, true, depth + 1)
filling = outer
if (outer != null) {
outer.addAll(pts)
} else {
setUp()
raster.fill(pts)
}
}
/** T: strings drawn from the position, the text controls (S, M, H, U, D, A, B, E) set, [x,y] moving it */
private fun text(c: Cursor, temp: (Opt) -> Unit) {
c.each(
onPosition = { p -> resolve(p).let { (nx, ny) -> x = nx; y = ny } },
onGroup = { opts ->
for (o in opts) when (o.letter) {
'S' -> o.positions.firstOrNull()?.let { p ->
text.cellW = (p.x?.value ?: text.cellW).coerceIn(1, WIDTH)
text.cellH = (p.y?.value ?: text.cellH).coerceIn(1, HEIGHT)
} ?: o.num?.let { n ->
val k = n.coerceIn(0, 16)
text.cellW = if (k == 0) 10 else 10 * k
text.cellH = if (k == 0) 10 else 20 * k
}
'U', 'M' -> o.positions.firstOrNull()?.let { p ->
val unit = if (o.letter == 'M') 10 else 1
p.x?.let { text.cellW = (it.value * unit).coerceIn(1, WIDTH) }
p.y?.let { text.cellH = (it.value * unit).coerceIn(1, HEIGHT) }
}
'H' -> o.num?.let { text.cellH = (10 * it).coerceIn(1, HEIGHT) }
'D' -> o.num?.let { a ->
val r = a * PI / 180
text.dx = cos(r).roundToInt()
text.dy = -sin(r).roundToInt()
}
'A' -> o.num?.let { text.alphabet = it.coerceIn(0, 3) }
'B' -> savedText = text.copy()
'E' -> savedText?.let { text = it.copy() }
'W' -> temp(o)
}
},
onString = ::string,
)
}
/** [s] drawn at the position, a cell a character the way the string goes (CR back to its start, LF down a cell) */
private fun string(s: String) {
setUp()
var px = dx(x)
var py = dy(y)
val startX = px
val font = text.alphabet.takeIf { it > 0 }?.let(::font)
for (ch in s) {
when (ch) {
'\r' -> px = startX
'\n' -> py += text.cellH
else -> {
val cp = ch.code
val f = if (font != null && font.has(cp)) font else LegacyCharsets.VGA
if (filling == null && cp != ' '.code) raster.text(px, py, ch.toString(), f, text.cellW, text.cellH)
px += text.dx * text.cellW
py += text.dy * text.cellH
}
}
}
user(px, py).let { (ux, uy) -> x = ux; y = uy }
}
/** alphabet [n]'s loaded characters as a font (8 pixels wide, or as wide as the widest row) */
private fun font(n: Int): BitmapFont? = fonts[n] ?: alphabets[n]?.takeIf { it.isNotEmpty() }?.let { glyphs ->
val codes = glyphs.keys.sorted().toIntArray()
val height = glyphs.values.maxOf { it.size }.coerceAtLeast(1)
val widest = glyphs.values.maxOf { r -> r.maxOrNull() ?: 0 }
var width = 8
while (width < 24 && widest ushr width != 0) width += 8
val rows = IntArray(codes.size * height)
for ((i, c) in codes.withIndex()) glyphs.getValue(c).copyInto(rows, i * height)
BitmapFont(height, codes, rows, width).also { fonts[n] = it }
}
/** L: the alphabet to load (A, its name a string), then each character as a string and its rows in hex */
private fun load(c: Cursor) {
c.each(
onGroup = { opts ->
for (o in opts) if (o.letter == 'A') {
o.num?.let { loading = it.coerceIn(1, 3) }
o.str?.let { alphabetNames[loading] = it }
}
},
onString = { s ->
if (s.isNotEmpty()) {
val rows = c.hexRows()
alphabets.getOrPut(loading) { HashMap() }[s[0].code] = rows.take(MAX_ROWS).toIntArray()
fonts.remove(loading)
}
},
)
}
/** S's options: E erased, I the background, A the address mapping, M the colour map; the others (cursor, time, hard copy, scrolling) taken */
private fun screen(opts: List<Opt>) {
for (o in opts) when (o.letter) {
'E' -> {
setUp()
raster.clear(backgroundColor())
}
'I' -> background = colorIndex(o) ?: background
'A' -> {
o.positions.getOrNull(0)?.let { p -> p.x?.let { ax1 = it.value }; p.y?.let { ay1 = it.value } }
o.positions.getOrNull(1)?.let { p -> p.x?.let { ax2 = it.value }; p.y?.let { ay2 = it.value } }
}
'M' -> {
val n = o.num ?: continue
o.sub?.let(::colorOf)?.let { if (n in 0 until 16) palette[n] = it }
}
}
}
/** R's options: P the position ([x,y]), E the last error (none), L the alphabet loading */
private fun report(opts: List<Opt>) {
for (o in opts) when (o.letter) {
'P' -> t.reply("[$x,$y]\r")
'E' -> t.reply("\"0,0\"\r")
'L' -> t.reply("A$loading\"${alphabetNames[loading] ?: ""}\"\r")
}
}
/** W's options into [w]: the mode (V, R, C, E), the colour (I), the pattern (P), negative (N), shading (S), the multiplier (M) */
private fun applyWriting(opts: List<Opt>, w: Writing) {
for (o in opts) when (o.letter) {
'V' -> w.mode = Raster.Mode.OVERLAY
'R' -> w.mode = Raster.Mode.REPLACE
'C' -> w.mode = Raster.Mode.COMPLEMENT
'E' -> w.mode = Raster.Mode.ERASE
'I' -> colorIndex(o)?.let { w.color = it }
'P' -> {
val d = o.digits
if (d != null && d.length > 1 && d.all { it == '0' || it == '1' }) {
var bits = 0
for (k in 0 until 8) bits = (bits shl 1) or (d[k % d.length] - '0')
w.pattern = bits
} else {
o.num?.let { w.pattern = PATTERNS[it.coerceIn(0, 9)] }
}
}
'N' -> w.negate = (o.num ?: 1) != 0
'S' -> {
w.shading = o.str != null || (o.num ?: 1) != 0
w.shadeY = o.positions.firstOrNull()?.let { resolve(it).second } ?: y
}
'M' -> o.num?.let { w.multiplier = it.coerceIn(1, 256) }
}
}
/** an I option's colour register: a number, or the register nearest the colour in its parentheses */
private fun colorIndex(o: Opt): Int? {
o.num?.let { return it.coerceIn(0, 15) }
val c = o.sub?.let(::colorOf) ?: return null
/** the squared distance between two colours */
fun dist(a: Int, b: Int): Int {
val dr = ((a shr 16) and 0xff) - ((b shr 16) and 0xff)
val dg = ((a shr 8) and 0xff) - ((b shr 8) and 0xff)
val db = (a and 0xff) - (b and 0xff)
return dr * dr + dg * dg + db * db
}
return (0 until 16).minByOrNull { dist(palette[it], c) }
}
/** a colour as ReGIS writes one: a letter (D B R G M C Y W), or H, L and S (L alone a grey) */
private fun colorOf(opts: List<Opt>): Int? {
var h: Int? = null
var l: Int? = null
var s: Int? = null
for (o in opts) {
when (o.letter) {
'H' -> h = o.num ?: 0
'L' -> l = o.num ?: 0
'S' -> s = o.num ?: 0
else -> LETTERS[o.letter]?.let { if (o.num == null) return it }
}
}
if (h == null && l == null && s == null) return null
return Sixel.hls(h ?: 0, l ?: 50, s ?: if (h == null) 0 else 100)
}
/** the raster set to draw as the writing controls say */
private fun setUp() {
val r = raster
r.mode = writing.mode
r.color = palette[writing.color and 15] or (0xff shl 24)
r.background = backgroundColor()
r.pattern = if (writing.negate) writing.pattern.inv() and 0xff else writing.pattern
}
/** the background's colour (transparent where it's black, so the text shows through) */
private fun backgroundColor(): Int {
val c = palette[background and 15]
return if (c and 0xffffff == 0) 0 else c or (0xff shl 24)
}
/** a dot at the position */
private fun dot() {
filling?.let { it.add(dx(x) to dy(y)); return }
setUp()
raster.point(dx(x), dy(y))
}
/** a line from the position to ([nx], [ny]), the position then there */
private fun lineTo(nx: Int, ny: Int) {
screenLine(dx(x), dy(y), dx(nx), dy(ny))
x = nx
y = ny
}
/** a line between two points of the screen (or, filling, the second added to the polygon), shaded to the shading line if that's on */
private fun screenLine(x0: Int, y0: Int, x1: Int, y1: Int) {
filling?.let { it.add(x1 to y1); return }
setUp()
if (writing.shading) {
val sy = dy(writing.shadeY)
raster.fill(listOf(x0 to y0, x1 to y1, x1 to sy, x0 to sy))
}
raster.line(x0, y0, x1, y1)
}
/** where pixel vector [d] (0 right, counterclockwise to 7) goes from the position */
private fun step(d: Int): Pair<Int, Int> {
val m = writing.multiplier
val (sx, sy) = DIRECTIONS[d and 7]
// (a step is a screen pixel's, in the user's units)
val ux = sx * m * (ax2 - ax1) / (WIDTH - 1)
val uy = sy * m * (ay2 - ay1) / (HEIGHT - 1)
return (x + if (ux == 0) sx * m else ux) to (y + if (uy == 0) sy * m else uy)
}
/** a position from the position: each part given absolute, or relative (signed), or left */
private fun resolve(p: Pos): Pair<Int, Int> {
/** one part of it */
fun part(v: Part?, base: Int) = when {
v == null -> base
v.relative -> base + v.value
else -> v.value
}
return part(p.x, x) to part(p.y, y)
}
/** a user's x as the screen's */
private fun dx(ux: Int): Int = map(ux, ax1, ax2, WIDTH)
/** a user's y as the screen's */
private fun dy(uy: Int): Int = map(uy, ay1, ay2, HEIGHT)
/** [v] from [a]..[b] onto 0..[size] - 1 */
private fun map(v: Int, a: Int, b: Int, size: Int): Int {
val span = if (b == a) 1 else b - a
return ((v - a).toLong() * (size - 1) / span).toInt()
}
/** a point of the screen as the user's coordinates */
private fun user(sx: Int, sy: Int): Pair<Int, Int> =
(ax1 + (sx.toLong() * (ax2 - ax1) / (WIDTH - 1)).toInt()) to (ay1 + (sy.toLong() * (ay2 - ay1) / (HEIGHT - 1)).toInt())
/** a coordinate in a position: its value, and whether it's from the position (signed) */
private class Part(val value: Int, val relative: Boolean)
/** a position as written, [x,y]: either part left out; [] (empty) the position itself */
private class Pos(val x: Part?, val y: Part?, val empty: Boolean)
/** an option: its letter, then what follows it (a number, positions, options in parentheses, a string) */
private class Opt(val letter: Char) {
var num: Int? = null
/** the number's digits as written (a pattern's bits) */
var digits: String? = null
val positions = ArrayList<Pos>()
var sub: List<Opt>? = null
var str: String? = null
}
/** a command's text read from [i] on */
private class Cursor(val s: String, var i: Int) {
/** the character at the cursor (NUL at the end) */
fun peek(): Char = if (i < s.length) s[i] else 0.toChar()
/** blanks and commas skipped */
fun skip() {
while (i < s.length && (s[i] <= ' ' || s[i] == ',')) i++
}
/**
* each of the command's arguments in turn to its handler: positions,
* option groups, strings, pixel vector digits (anything else skipped)
*/
fun each(
onPosition: (Pos) -> Unit = {},
onGroup: (List<Opt>) -> Unit = {},
onString: (String) -> Unit = {},
onDigit: (Int) -> Unit = {},
) {
while (true) {
skip()
when (val c = peek()) {
0.toChar() -> return
'[' -> onPosition(position())
'(' -> onGroup(group())
'\'', '"' -> onString(string())
in '0'..'7' -> { i++; onDigit(c - '0') }
else -> i++
}
}
}
/** a number: a sign, digits, a fraction (dropped); null if there's none */
fun number(): Int? {
val start = i
var neg = false
if (peek() == '+' || peek() == '-') { neg = peek() == '-'; i++ }
val d = digits()
if (d.isEmpty()) { i = start; return null }
if (peek() == '.') { i++; digits() }
val v = d.takeLast(9).toInt()
return if (neg) -v else v
}
/** the digits at the cursor */
fun digits(): String {
val start = i
while (peek() in '0'..'9') i++
return s.substring(start, i)
}
/** [x,y] */
fun position(): Pos {
i++
/** one part, up to a comma or the bracket */
fun part(): Part? {
while (peek() == ' ') i++
val c = peek()
val relative = c == '+' || c == '-'
val v = number()
while (i < s.length && s[i] != ',' && s[i] != ']') i++
return v?.let { Part(it, relative) }
}
val px = part()
var py: Part? = null
val hadComma = peek() == ','
if (hadComma) { i++; py = part() }
if (peek() == ']') i++
return Pos(px, py, px == null && py == null && !hadComma)
}
/** a quoted string (a doubled quote one of it) */
fun string(): String {
val q = s[i++]
val b = StringBuilder()
while (i < s.length) {
val c = s[i++]
if (c == q) {
if (peek() == q) { b.append(q); i++ } else break
} else {
b.append(c)
}
}
return b.toString()
}
/** (…): options, each a letter and what follows it (a bare number another of the last letter's) */
fun group(): List<Opt> {
i++
val opts = ArrayList<Opt>()
var last: Opt? = null
while (i < s.length) {
skip()
val c = peek()
when {
c == ')' -> { i++; break }
c.isLetter() -> {
i++
last = Opt(c).also { opts.add(it); values(it) }
}
(c.isDigit() || c == '+' || c == '-') && last != null -> {
last = Opt(last.letter).also { opts.add(it); values(it) }
}
c == '[' && last != null -> last.positions.add(position())
c == '(' && last != null -> last.sub = group()
c == '\'' || c == '"' -> { val str = string(); last?.str = str }
else -> i++
}
}
return opts
}
/** what follows an option's letter: a number, positions, options, a string */
private fun values(o: Opt) {
while (peek() == ' ') i++
val c = peek()
if (c.isDigit() || c == '+' || c == '-') {
val start = i
o.num = number()
o.digits = s.substring(start, i).trimStart('+', '-')
}
while (true) {
while (peek() == ' ') i++
when (peek()) {
'[' -> o.positions.add(position())
'(' -> o.sub = group()
'\'', '"' -> o.str = string()
else -> return
}
}
}
/** the text inside the parentheses at the cursor (balanced, quotes kept), or null if none */
fun parenthesised(): String? {
skip()
if (peek() != '(') return null
val start = ++i
var depth = 1
var quote = 0.toChar()
while (i < s.length) {
val c = s[i++]
when {
quote != 0.toChar() -> if (c == quote) quote = 0.toChar()
c == '\'' || c == '"' -> quote = c
c == '(' -> depth++
c == ')' -> if (--depth == 0) return s.substring(start, i - 1)
}
}
return s.substring(start)
}
/** a loaded character's rows: hex numbers, commas between, up to the next string */
fun hexRows(): List<Int> {
val rows = ArrayList<Int>()
while (true) {
skip()
val start = i
while (i < s.length && s[i].uppercaseChar() in HEX) i++
if (i == start) return rows
rows.add(s.substring(start, i).takeLast(6).toInt(16))
}
}
}
companion object {
/** the VT340's screen, in pixels */
const val WIDTH = 800
const val HEIGHT = 480
/** the command letters */
private const val COMMANDS = "PVCFTWSRL"
private const val HEX = "0123456789ABCDEF"
/** how much of an unfinished command is kept */
private const val MAX_PENDING = 1 shl 20
/** how deep macrographs and fills may nest */
private const val MAX_DEPTH = 8
/** a loaded character's rows at most */
private const val MAX_ROWS = 32
/** a curve's lines between each two of its points */
private const val STEPS = 8
/** the standard patterns, 0-9 */
private val PATTERNS = intArrayOf(0x00, 0xff, 0xf0, 0xe4, 0xaa, 0xea, 0x88, 0x84, 0xc8, 0xee)
/** the pixel vectors' steps: 0 right, counterclockwise (y down) */
private val DIRECTIONS = listOf(1 to 0, 1 to -1, 0 to -1, -1 to -1, -1 to 0, -1 to 1, 0 to 1, 1 to 1)
/** ReGIS's colour letters */
private val LETTERS = mapOf(
'D' to 0xff000000.toInt(), 'B' to 0xff0000ff.toInt(), 'R' to 0xffff0000.toInt(), 'G' to 0xff00ff00.toInt(),
'M' to 0xffff00ff.toInt(), 'C' to 0xff00ffff.toInt(), 'Y' to 0xffffff00.toInt(), 'W' to 0xffffffff.toInt(),
)
}
}
@@ -61,7 +61,11 @@ object Style {
}
/** a picture (a sixel image): its pixels, and the cell size it was placed at (its tiles are cells of that size) */
class TermImage(val width: Int, val height: Int, val pixels: IntArray, val cellWidth: Int, val cellHeight: Int) {
class TermImage(
val width: Int, val height: Int, val pixels: IntArray, val cellWidth: Int, val cellHeight: Int,
/** a graphics terminal's picture over the screen ([TerminalEmulator.showPicture]'s), not an image in the text */
val picture: Boolean = false,
) {
val id = nextId++
private companion object {
@@ -0,0 +1,208 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
/**
* A Tektronix 4010/4014 storage tube as a terminal: a 4096x3120 screen
* (the 4010's 1024x780 is its high ten bits) of vectors (GS: graph mode,
* the first address a dark move), points (FS), incremental plots (RS:
* a pen and eight directions) and alpha text (US) in four sizes, with
* ESC FF to clear, the line styles, and the beam's place reported (ESC
* ENQ). Drawn into a [Raster] over the screen. As a VT240's or xterm's
* Tek mode (DECSET 38) [onExit] is given, and ESC ETX goes back.
*/
open class TektronixInterpreter(t: TerminalEmulator, private val onExit: (() -> Unit)? = null) : TerminalInterpreter(t) {
private enum class Mode { ALPHA, GRAPH, POINT, INCREMENTAL }
private var mode = Mode.ALPHA
private val layer = PictureLayer(t, WIDTH, HEIGHT) { it.color = INK }
private val raster get() = layer.raster
// the beam, in Tek's units (0,0 bottom left)
private var x = 0
private var y = TOP
/** the next address in graph mode is a dark move */
private var dark = true
/** the incremental plot's pen down */
private var pen = false
/** the character size, 0 (the largest) to 3 */
private var size = 0
private var escaped = false
// an address being read: its high and low bytes, the 4014's extra byte
private var hiX = 0
private var hiY = 0
private var loX = 0
private var loY = 0
private var extra = 0
private var lastLoY = false
init {
home()
}
/** the beam to the first line's start, in alpha mode */
private fun home() {
mode = Mode.ALPHA
x = 0
y = TOP - CHAR_H[size]
}
/** a code point: the rest of an ESC sequence, a control, an address in the plotting modes, or text in alpha mode */
override fun process(cp: Int) {
val c = cp and 0x7f
if (escaped) {
escaped = false
esc(c)
return
}
when (c) {
0x1b -> escaped = true
0x1d -> { mode = Mode.GRAPH; dark = true }
0x1c -> mode = Mode.POINT
0x1e -> { mode = Mode.INCREMENTAL; pen = false }
0x1f -> mode = Mode.ALPHA
0x07 -> t.listener?.onBell()
0x0d -> { mode = Mode.ALPHA; x = 0 }
else -> when (mode) {
Mode.ALPHA -> alpha(c)
Mode.GRAPH, Mode.POINT -> if (c >= 0x20) address(c)
Mode.INCREMENTAL -> incremental(c)
}
}
}
/** the code after ESC: clear (FF), the beam's place asked (ENQ), a character size, a line style, back to the VT (ETX) */
private fun esc(c: Int) {
when (c) {
0x0c -> {
raster.clear()
home()
}
0x05 -> report()
in '8'.code..';'.code -> size = c - '8'.code
in 0x60..0x67 -> raster.pattern = STYLES[(c - 0x60) and 7]
0x03 -> onExit?.invoke()
else -> if (c < 0x20) process(c)
}
}
/** ESC ENQ's answer: the status (alpha or graph mode), the beam's x and y as two bytes each (10-bit), CR */
private fun report() {
val sx = x shr 2
val sy = y shr 2
/** five bits as an address byte */
fun b(v: Int, tag: Int) = (tag or (v and 0x1f)).toChar()
val status = if (mode == Mode.ALPHA) 0x34 else 0x30
t.reply("${status.toChar()}${b(sx shr 5, 0x20)}${b(sx, 0x20)}${b(sy shr 5, 0x20)}${b(sy, 0x20)}\r")
}
/** text at the beam (its bottom left), the beam on; BS, HT, LF, VT moving it a character */
private fun alpha(c: Int) {
val cw = CHAR_W[size]
val ch = CHAR_H[size]
when (c) {
0x08 -> x = (x - cw).coerceAtLeast(0)
0x09 -> x += cw
0x0a -> { y -= ch; if (y < 0) y = TOP - ch }
0x0b -> y = (y + ch).coerceAtMost(TOP - ch)
in 0x20..0x7e -> {
if (x + cw > WIDTH) { x = 0; y -= ch; if (y < 0) y = TOP - ch }
if (c != 0x20) raster.text(x, row(y + ch), c.toChar().toString(), LegacyCharsets.VGA, cw, ch)
x += cw
}
}
}
/** an address byte: high (x or y), low y (or the 4014's extra byte before it), low x (the address done) */
private fun address(c: Int) {
val v = c and 0x1f
when (c shr 5) {
1 -> { if (lastLoY) hiX = v else hiY = v; lastLoY = false }
3 -> { if (lastLoY) extra = loY; loY = v; lastLoY = true }
2 -> {
loX = v
lastLoY = false
val nx = (hiX shl 7) or (loX shl 2) or (extra and 3)
val ny = (hiY shl 7) or (loY shl 2) or ((extra shr 2) and 3)
extra = 0
to(nx, ny)
}
}
}
/** the beam to ([nx], [ny]): a point plotted, a vector drawn, or (graph mode's first) a dark move */
private fun to(nx: Int, ny: Int) {
when {
mode == Mode.POINT -> raster.point(nx, row(ny))
dark -> dark = false
else -> raster.line(x, row(y), nx, row(ny))
}
x = nx
y = ny
}
/** an incremental plot's code: the pen up or down, or a step in one of eight directions (drawing with the pen down) */
private fun incremental(c: Int) {
val (dx, dy) = when (c.toChar()) {
' ' -> { pen = false; return }
'P' -> { pen = true; return }
'D' -> 0 to 1
'E' -> 1 to 1
'A' -> 1 to 0
'I' -> 1 to -1
'H' -> 0 to -1
'J' -> -1 to -1
'B' -> -1 to 0
'F' -> -1 to 1
else -> return
}
val nx = (x + dx * STEP).coerceIn(0, WIDTH - 1)
val ny = (y + dy * STEP).coerceIn(0, TOP - 1)
if (pen) raster.line(x, row(y), nx, row(ny))
x = nx
y = ny
}
/** Tek's y (from the bottom) as the raster's row (from the top) */
private fun row(ty: Int): Int = TOP - 1 - ty
/** what was drawn put on the screen */
override fun flush() {
layer.flush()
}
/** RIS: the screen cleared, the beam home, the largest characters */
override fun reset() {
layer.reset()
size = 0
escaped = false
home()
}
companion object {
/** the 4014's addressable screen, in its units */
const val WIDTH = 4096
const val HEIGHT = 3120
private const val TOP = HEIGHT
/** an incremental plot's step (the 4010's one point) */
private const val STEP = 4
/** the characters' cell in each size (74 to 133 columns, 35 to 64 lines) */
private val CHAR_W = intArrayOf(56, 51, 34, 31)
private val CHAR_H = intArrayOf(88, 82, 53, 48)
/** the line styles: solid, dotted, dot-dashed, short-dashed, long-dashed (and the 4014's others as solid) */
private val STYLES = intArrayOf(0xff, 0xaa, 0xe4, 0xcc, 0xf0, 0xff, 0xff, 0xff)
/** the phosphor's green-white */
private const val INK = 0xffc8ffc8.toInt()
}
}
/** A Tektronix 4014 on its own: the terminal is the storage tube */
open class Tek4014Profile : TerminalProfile() {
override val id get() = "tek4014"
override val label get() = "Tektronix 4014"
override val term get() = "tek4014"
override val telnetType get() = "TEK4014"
/** a [TektronixInterpreter] that never leaves */
override fun interpreter(t: TerminalEmulator): TerminalInterpreter = TektronixInterpreter(t)
}
@@ -65,6 +65,53 @@ class TerminalBridge(cols: Int, rows: Int) {
/** a row (0: the screen's top) as runs */
fun runs(row: Int): List<StyledRun> = emulator.runs(row, look)
/** the images seen in the rows asked for lately ([imageRuns]), by id, for [imagePixels] */
private val images = HashMap<Long, TermImage>()
/** a row's cells that show images (sixels, a picture), each run one image's tiles side by side */
fun imageRuns(row: Int): List<ImageRun> {
if (row == 0) images.clear()
val line = emulator.line(row)
if (line.extras == null) return emptyList()
val out = ArrayList<ImageRun>()
var x = 0
while (x < emulator.cols) {
val tile = line.extra(x)?.image
if (tile == null) { x++; continue }
val img = tile.image
images[img.id] = img
var end = x + 1
while (end < emulator.cols) {
val next = line.extra(end)?.image ?: break
if (next.image !== img || next.ty != tile.ty || next.tx != tile.tx + (end - x)) break
end++
}
out.add(ImageRun(x, end - x, img.id, tile.tx, tile.ty, img.width, img.height, img.cellWidth, img.cellHeight))
x = end
}
return out
}
/**
* image [imageId]'s pixels (one [imageRuns] gave) as Latin-1: four characters
* a pixel, red, green, blue and alpha, the colour premultiplied; "" if
* it's gone
*/
fun imagePixels(imageId: Long): String {
val img = images[imageId] ?: return ""
val b = StringBuilder(img.pixels.size * 4)
for (p in img.pixels) {
val a = (p ushr 24) and 0xff
/** a channel premultiplied by the alpha */
fun pm(c: Int) = (c * a + 127) / 255
b.append(pm((p shr 16) and 0xff).toChar())
b.append(pm((p shr 8) and 0xff).toChar())
b.append(pm(p and 0xff).toChar())
b.append(a.toChar())
}
return b.toString()
}
/** the screen's background, the theme's (ARGB) */
val background: Int get() = look.theme.bgArgb
val cursorColor: Int get() = look.theme.cursorArgb
@@ -251,6 +251,7 @@ class TerminalEmulator(
} else {
decoder.decode(data, length, sink)
}
interpreter.flush()
revision++
}
@@ -358,6 +359,36 @@ class TerminalEmulator(
// ------------------------------------------------------------------
// images
/**
* A graphics terminal's picture over the whole screen (ReGIS's, a
* Tektronix's: [img] the screen's size in pixels): the cells it draws
* in made its tiles, the cells an earlier picture drew in that this one
* doesn't given back their blank; the text elsewhere left, the cursor
* where it was.
*/
internal fun showPicture(img: TermImage) {
val cw = img.cellWidth
val ch = img.cellHeight
for (ty in 0 until rows) {
val line = screen[ty]
for (tx in 0 until cols) {
var drawn = false
scan@ for (y in ty * ch until minOf((ty + 1) * ch, img.height)) {
val row = y * img.width
for (x in tx * cw until minOf((tx + 1) * cw, img.width)) {
if (img.pixels[row + x] != 0) { drawn = true; break@scan }
}
}
if (drawn) {
line.set(tx, 0, Style.erased(style))
line.extraFor(tx).image = ImageTile(img, tx, ty)
} else if (line.extra(tx)?.image?.image?.picture == true) {
line.extra(tx)?.image = null
}
}
}
}
/**
* A sixel image put on the screen as tiles of cells (so that it scrolls
* with the text): at the cursor, scrolling the screen as it needs, the
@@ -35,6 +35,9 @@ abstract class TerminalInterpreter(protected val t: TerminalEmulator) {
/** what character [cp] typed or pasted sends on this terminal, as octets; null: [KeyEncoder]'s, in the character set */
open fun charOctets(cp: Int, alt: Boolean, ctrl: Boolean): ByteArray? = null
/** what came in a read has all been processed: a picture drawn meanwhile put on the screen */
open fun flush() {}
/** another profile's interpreter taking over: what this one set on the screen (its size, its colours) undone */
open fun detach() {}
}
@@ -50,6 +50,10 @@ enum class VtFeature {
PRINTER,
/** xterm's own: mouse and focus reports, bracketed paste, the alternate screen, OSC titles, colours, clipboard and links, XTVERSION, window reports */
XTERM,
/** Tek mode (DECSET 38): a Tektronix 4014 in the terminal */
TEK,
/** ReGIS graphics (DCS p) */
REGIS,
}
/**
@@ -139,6 +143,19 @@ open class Vt320Profile : Vt220Profile() {
override val secondaryDa: String? get() = "\u001b[>24;10;0c"
}
/** DEC VT340: a VT320 with graphics, sixel and ReGIS in 16 colour registers they share, and Tek mode */
open class Vt340Profile : Vt320Profile() {
override val id get() = "vt340"
override val label get() = "DEC VT340"
override val term get() = "vt340"
override val telnetType get() = "DEC-VT340"
// 132 columns, printer, ReGIS, sixel, selective erase, user-defined keys, NRCS, technical set
override val primaryDa get() = "\u001b[?63;1;2;3;4;6;7;8;9c"
// a VT340, firmware 1.0
override val secondaryDa: String? get() = "\u001b[>19;10;0c"
override val features: Set<VtFeature> get() = super.features + VtFeature.SIXEL + VtFeature.REGIS + VtFeature.TEK
}
/** DEC VT420: level 4, left and right margins, rectangular areas, six pages */
open class Vt420Profile : Vt320Profile() {
override val id get() = "vt420"
@@ -199,7 +216,7 @@ open class XtermProfile : Vt220Profile() {
override val primaryDa get() = "\u001b[?62;4;22c"
// xterm, patch 390
override val secondaryDa: String? get() = "\u001b[>41;390;0c"
override val features: Set<VtFeature> get() = super.features + VtFeature.COLOR + VtFeature.SIXEL + VtFeature.XTERM
override val features: Set<VtFeature> get() = super.features + VtFeature.COLOR + VtFeature.SIXEL + VtFeature.XTERM + VtFeature.TEK
// (as before profiles: BBSes reached as xterm count on ANSI.SYS's clear)
override val homeOnClear get() = true
}
@@ -225,6 +242,7 @@ object TerminalProfiles {
val VT102: TerminalProfile = Vt102Profile()
val VT220: TerminalProfile = Vt220Profile()
val VT320: TerminalProfile = Vt320Profile()
val VT340: TerminalProfile = Vt340Profile()
val VT420: TerminalProfile = Vt420Profile()
val VIEWDATA: TerminalProfile = ViewdataProfile()
val MINITEL: TerminalProfile = MinitelProfile()
@@ -242,12 +260,13 @@ object TerminalProfiles {
val PET80: TerminalProfile = Pet80Profile()
val ATARI: TerminalProfile = AtariProfile()
val ATARI_INTL: TerminalProfile = AtariInternationalProfile()
val TEK4014: TerminalProfile = Tek4014Profile()
/** the default: what the app was before profiles */
val DEFAULT: TerminalProfile get() = XTERM
/** in the pickers' order */
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)
val all: List<TerminalProfile> = listOf(XTERM, ANSI_BBS, VT52, VT100, VT102, VT220, VT320, VT340, VT420, VT510, VT520, VT525, C64, C128, C128_80, PLUS4, VIC20, PET, PET80, ATARI, ATARI_INTL, VIEWDATA, MINITEL, TEK4014)
/** the profile [id] names, or null for none or one not known */
fun byId(id: String?): TerminalProfile? = all.firstOrNull { it.id == id }
@@ -96,3 +96,20 @@ fun TerminalEmulator.runs(row: Int, look: RunLook = RunLook()): List<StyledRun>
}
return out
}
/**
* Cells of a row showing one image (the bridge's, for Swift): [cells]
* columns from [col], tile ([tx], [ty]) of image [imageId] the first, the image
* [width] x [height] pixels in tiles of [cellWidth] x [cellHeight]
*/
class ImageRun(
val col: Int,
val cells: Int,
val imageId: Long,
val tx: Int,
val ty: Int,
val width: Int,
val height: Int,
val cellWidth: Int,
val cellHeight: Int,
)
@@ -28,8 +28,8 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** 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
/** another terminal's interpreter reading what comes for now (VT52 mode, Tek mode), until it hands back */
private var sub: TerminalInterpreter? = null
/** the printer port (a VT102's and later), ended by MC 4 */
private val printer = PrinterPort(t, listOf("\u001b[4i", "\u009b4i"))
@@ -52,6 +52,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
/** a VT340's colour registers, shared by its sixels and ReGIS */
private val registers: IntArray? = if (profile.has(VtFeature.REGIS)) Sixel.defaultPalette() else null
/** ReGIS (a VT340's), made when its first DCS p comes */
private var regis: Regis? = null
/** a DCS p under way: its text is ReGIS's */
private var inRegis = false
private var dcsText: StringBuilder? = null
/** what the DCS's text is for: its intermediate and final, as "$q" (DECRQSS), "|" (DECUDK) */
private var dcsKind = ""
@@ -65,7 +71,7 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** one code point through the parser, by the state it is in (text, ESC, CSI, OSC, a string, a DCS) */
override fun process(cp: Int) {
vt52?.let { it.process(cp); return }
sub?.let { it.process(cp); return }
if (intercept(cp)) return
if (printer.controller) {
printer.feed(cp)
@@ -461,6 +467,8 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
1 -> t.appCursorKeys = on
// DECANM reset: VT52 mode, with this terminal's graphics, until ESC <
2 -> if (!on) enterVt52()
// DECTEK: a Tektronix 4014 on the alternate screen
38 -> if (on && profile.has(VtFeature.TEK)) enterTek()
// DECCOLM: 132 columns or 80
3 -> if (!xterm || allowColumns) t.setColumnMode(on)
5 -> t.reverseVideo = on
@@ -743,6 +751,7 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
private fun dcsStart(final: Int) {
sixel = null
dcsText = null
inRegis = false
dcsKind = ""
dcsP0 = param(0)
dcsP1 = param(1)
@@ -753,7 +762,11 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
// P2 = 1: the pixels not drawn left transparent
val maxW = minOf(max, t.cols * t.cellPixelWidth * 2)
val maxH = minOf(max, t.rows * t.cellPixelHeight * 4)
sixel = Sixel(transparent = p(1, 0) == 1, maxWidth = maxW, maxHeight = maxH)
sixel = Sixel(transparent = p(1, 0) == 1, sharedPalette = registers, maxWidth = maxW, maxHeight = maxH)
}
final == 'p'.code && intermediate == 0 && privateMarker == 0 && registers != null -> {
inRegis = true
(regis ?: Regis(t, registers).also { regis = it }).begin(p(0, 0))
}
// DECRQSS (VT320 and later, xterm), XTGETTCAP: their text collected
final == 'q'.code && intermediate == '$'.code && (operatingLevel >= 3 || xterm) ||
@@ -772,18 +785,25 @@ 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 }
if (inRegis) { regis?.feed(cp); return }
// (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 */
private fun dcsAbort() {
if (inRegis) regis?.abort()
inRegis = false
sixel = null
dcsText = null
}
/** the DCS ended: its sixel image placed, or its request answered */
private fun dcsEnd() {
if (inRegis) {
inRegis = false
regis?.end()
}
sixel?.let { sx ->
sixel = null
sx.finish(t.cellPixelWidth, t.cellPixelHeight)?.let { t.placeImage(it) }
@@ -948,12 +968,27 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
/** 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") {
vt52 = null
sub = Vt52Interpreter(t, GSet.DEC_GRAPHICS, "\u001b/Z") {
sub = null
t.vt52Keys = false
}
}
/** Tek mode (DECSET 38): a [TektronixInterpreter] draws on the alternate screen until its ESC ETX brings the text back */
private fun enterTek() {
t.setAltScreen(true, clear = true)
sub = TektronixInterpreter(t) {
sub = null
t.setAltScreen(false, clear = false)
}
}
/** what a sub-terminal drew put on the screen */
override fun flush() {
sub?.flush()
regis?.flush()
}
/** DECSTR: the character sets back to ASCII */
override fun softReset() {
restoreCharsetState(null)
@@ -968,12 +1003,15 @@ open class VtInterpreter(t: TerminalEmulator, val profile: DecProfile) : Termina
sets.soft.reset()
statusActive = false
softReset()
vt52 = null
if (sub is TektronixInterpreter) t.setAltScreen(false, clear = false)
sub = null
t.vt52Keys = false
printer.reset()
allowColumns = false
sixel = null
dcsText = null
regis?.reset()
inRegis = false
state = State.GROUND
}
}
@@ -0,0 +1,151 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.Test
class RegisTest {
private val replies = StringBuilder()
/** an 80x24 VT340 (10x20 cells: its 800x480 picture a pixel a pixel), whose replies are kept */
private fun term(profile: TerminalProfile = TerminalProfiles.VT340): TerminalEmulator {
replies.setLength(0)
return TerminalEmulator(80, 24, 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())
/** ReGIS [s] in its DCS (P1 0: going on from where the last left off) */
private fun TerminalEmulator.regis(s: String) = send("\u001bPp$s\u001b\\")
/** the picture's tile at cell ([x], [y]), or null */
private fun TerminalEmulator.tile(x: Int, y: Int): ImageTile? = line(y).extra(x)?.image?.takeIf { it.image.picture }
/** the picture's pixel at ([px], [py]) (0: nothing drawn), or 0 where there's no picture */
private fun TerminalEmulator.pixel(px: Int, py: Int): Int {
val tile = tile(px / 10, py / 20) ?: return 0
return tile.image.pixels[py * tile.image.width + px]
}
/** P moves, V draws from the position to each one given; relative parts and left-out ones */
@Test
fun vectors() {
val t = term()
t.regis("P[100,100]V[200,100][+0,+100]")
assertTrue(t.pixel(150, 100) != 0)
assertTrue(t.pixel(200, 150) != 0)
assertEquals(0, t.pixel(150, 150))
assertEquals(0, t.pixel(50, 100))
// R(P): the position is the last one drawn to
t.regis("R(P)")
assertEquals("[200,200]\r", replies.toString())
}
/** W(I): the colour register; S(M): a register's colour (HLS); S(E) the screen erased */
@Test
fun colours() {
val t = term()
t.regis("S(M3(H0L50S100))W(I3)P[10,10]V[50,10]")
// (DEC's hue 0 is blue)
assertEquals(0xff0000ff.toInt(), t.pixel(30, 10))
t.regis("W(I(R))P[10,30]V[50,30]")
// (the nearest register: the VT340's red)
val red = t.pixel(30, 30)
assertTrue((red shr 16 and 0xff) > 0x80 && (red and 0xff) < 0x40)
t.regis("S(E)")
assertEquals(0, t.pixel(30, 10))
assertEquals(null, t.tile(3, 0))
}
/** a circle round the position, through the point given */
@Test
fun circle() {
val t = term()
t.regis("P[400,240]C[+100]")
assertTrue(t.pixel(500, 240) != 0)
assertTrue(t.pixel(300, 240) != 0)
assertTrue(t.pixel(400, 140) != 0)
assertEquals(0, t.pixel(400, 240))
}
/** F: the polygon its vectors go round filled */
@Test
fun fill() {
val t = term()
t.regis("P[100,100]F(V[200,100][200,200][100,200][100,100])")
assertTrue(t.pixel(150, 150) != 0)
assertEquals(0, t.pixel(250, 150))
}
/** T: a string drawn at the position, cell by cell; the position after it */
@Test
fun text() {
val t = term()
t.regis("P[0,0]T'AB'R(P)")
assertTrue(t.tile(0, 0) != null)
assertTrue(t.tile(1, 0) != null)
assertEquals("[20,0]\r", replies.toString())
}
/** macrographs: defined, run (more than once), cleared */
@Test
fun macrographs() {
val t = term()
t.regis("@:AV[+50]@;P[0,100]@A@AR(P)")
assertEquals("[100,100]\r", replies.toString())
assertTrue(t.pixel(75, 100) != 0)
}
/** pixel vectors: 0 right, 6 down, the multiplier W(M) */
@Test
fun pixelVectors() {
val t = term()
t.regis("W(M10)P[100,100]V00066R(P)")
assertEquals("[130,120]\r", replies.toString())
}
/** S(A): the address mapping, the user's coordinates over the screen */
@Test
fun addressMapping() {
val t = term()
t.regis("S(A[0,0][79,47])P[40,24]V[79,24]")
// (24 of 47 is the screen's row 244)
assertTrue(t.pixel(600, 244) != 0)
assertEquals(0, t.pixel(300, 244))
}
/** DCS 1 p starts afresh: the position back at 0,0 */
@Test
fun restart() {
val t = term()
t.regis("P[100,100]")
t.send("\u001bP1pR(P)\u001b\\")
assertEquals("[0,0]\r", replies.toString())
}
/** a command split over two reads runs once it's whole */
@Test
fun split() {
val t = term()
t.send("\u001bP1pP[100,100]V[200,")
assertEquals(0, t.pixel(150, 100))
t.send("100]\u001b\\")
assertTrue(t.pixel(150, 100) != 0)
}
/** a VT340 says it has ReGIS and sixel (DA1 3 and 4); a VT320 ignores ReGIS */
@Test
fun attributes() {
val t = term()
t.send("\u001b[c")
assertEquals("\u001b[?63;1;2;3;4;6;7;8;9c", replies.toString())
val v = term(TerminalProfiles.VT320)
v.regis("P[0,0]V[799,0]")
assertEquals(null, v.tile(0, 0))
}
}
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.terminal
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.Test
class TektronixTest {
private val replies = StringBuilder()
/** an 80x24 terminal of [profile] (10x20 cells: an 800x480 picture), whose replies are kept */
private fun term(profile: TerminalProfile): TerminalEmulator {
replies.setLength(0)
return TerminalEmulator(80, 24, 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())
/** a 4010 address (10-bit [x], [y]) as its four bytes: HiY, LoY, HiX, LoX */
private fun addr(x: Int, y: Int): String = buildString {
append((0x20 or (y shr 5)).toChar())
append((0x60 or (y and 31)).toChar())
append((0x20 or (x shr 5)).toChar())
append((0x40 or (x and 31)).toChar())
}
/** whether cell ([x], [y]) shows a tile of the picture */
private fun TerminalEmulator.picture(x: Int, y: Int): Boolean = line(y).extra(x)?.image?.image?.picture == true
/** a vector: GS's first address a dark move, the next drawn to; the cells it crosses show it, the rest don't */
@Test
fun vector() {
val t = term(TerminalProfiles.TEK4014)
// along the bottom, from the left to the middle
t.send("\u001d" + addr(0, 10) + addr(511, 10))
assertTrue(t.picture(0, 23))
assertTrue(t.picture(39, 23))
assertFalse(t.picture(60, 23))
assertFalse(t.picture(0, 0))
// ESC FF: the screen cleared
t.send("\u001b\u000c")
assertFalse(t.picture(0, 23))
}
/** a dark move only: nothing drawn */
@Test
fun darkMove() {
val t = term(TerminalProfiles.TEK4014)
t.send("\u001d" + addr(500, 300))
for (y in 0 until 24) for (x in 0 until 80) assertFalse(t.picture(x, y))
}
/** alpha text drawn at the top left, in the picture */
@Test
fun alphaText() {
val t = term(TerminalProfiles.TEK4014)
t.send("HI")
assertTrue(t.picture(0, 0))
assertFalse(t.picture(0, 23))
}
/** ESC ENQ: the status and the beam's place, five bits a byte, then CR */
@Test
fun report() {
val t = term(TerminalProfiles.TEK4014)
t.send("\u001d" + addr(100, 200) + "\u001b\u0005")
assertEquals("0#$&(\r", replies.toString())
}
/** xterm's Tek mode: DECSET 38 to the tube on the alternate screen, ESC ETX back to the text */
@Test
fun xtermTekMode() {
val t = term(TerminalProfiles.XTERM)
t.send("text\u001b[?38h")
assertTrue(t.altScreen)
t.send("\u001d" + addr(0, 10) + addr(511, 10))
assertTrue(t.picture(0, 23))
t.send("\u001b\u0003")
assertFalse(t.altScreen)
assertEquals("text", t.text(0, 0, 0, 79).trimEnd())
// and the VT's sequences read again
t.send("\u001b[2J\u001b[Hok")
assertEquals("ok", t.text(0, 0, 0, 79).trimEnd())
}
/** a VT100 has no Tek mode */
@Test
fun vt100HasNone() {
val t = term(TerminalProfiles.VT100)
t.send("\u001b[?38h")
assertFalse(t.altScreen)
}
}
@@ -53,4 +53,27 @@ class TerminalBridgeTest {
assertEquals("█", t.runs(0)[0].text.take(1))
assertEquals("Û", t.typed("█"))
}
/** a picture's cells as runs of one image's tiles, its pixels as Latin-1 RGBA (premultiplied) */
@Test
fun imageRuns() {
val b = TerminalBridge(80, 24)
b.profile = "vt340"
// a red line across the top row's first ten cells
b.feed("\u001bPpS(M2(H120L50S100))W(I2)P[0,5]V[99,5]\u001b\\")
val runs = b.imageRuns(0)
assertEquals(1, runs.size)
val r = runs[0]
assertEquals(0, r.col)
assertEquals(10, r.cells)
assertEquals(0, r.tx)
assertEquals(0, r.ty)
assertEquals(800, r.width)
val px = b.imagePixels(r.imageId)
assertEquals(800 * 480 * 4, px.length)
val i = (5 * 800 + 50) * 4
assertEquals(listOf(255, 0, 0, 255), (0 until 4).map { px[i + it].code })
assertEquals(0, px[3].code)
assertTrue(b.imageRuns(1).isEmpty())
}
}