Files

350 lines
14 KiB
C++

// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "DriveWireCoWin.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <utility>
#include <vector>
namespace VCC::Mac {
// A PTY advertises an 80x24 VT-style terminal. The historical OS-9 telnet
// client writes the received bytes straight to its CoWin window. Keep shell
// output relative until a program takes ownership of the screen so connecting
// does not erase the guest's login transcript.
class DriveWireTerminal {
public:
std::vector<std::uint8_t> consume(const std::uint8_t* bytes, std::size_t count) {
std::vector<std::uint8_t> output;
for (std::size_t i = 0; i < count; ++i) parse(bytes[i], output);
if (managed) {
auto& s = screen();
// A guest can quit telnet at any time. Leave its native cursor
// visible even when a Mac program requests an invisible cursor.
renderer.draw(s.cells, s.x, s.y, true, invalidate, output);
invalidate = false;
if (returnToTranscript) {
managed = false;
returnToTranscript = false;
}
}
return output;
}
bool applicationCursor() const { return applicationKeys; }
std::string takeReply() { return std::exchange(replies, {}); }
private:
using Bytes = std::vector<std::uint8_t>;
static constexpr int width = 80, height = 24;
struct Screen {
TerminalGrid cells;
int x = 0, y = 0, savedX = 0, savedY = 0, top = 0, bottom = height-1;
bool pendingWrap = false;
Screen() { for (auto& line : cells) line.fill(' '); }
};
Screen normal, alternate;
DriveWireTerminalOutput renderer;
bool inAlternate = false, managed = false, invalidate = false, returnToTranscript = false;
bool origin = false, autoWrap = true, insert = false, applicationKeys = false;
bool g0Graphics = false, g1Graphics = false, shifted = false, selectG1 = false;
std::array<bool, width> tabs = [] {
std::array<bool, width> stops{};
for (int x = 8; x < width; x += 8) stops[x] = true;
return stops;
}();
enum class State { plain, escape, charset, intermediate, csi, string, stringEscape };
State state = State::plain;
std::array<int,16> args{};
std::size_t argument = 0;
bool privateMode = false, ignoredSequence = false;
int utfRemaining = 0;
std::string replies;
Screen& screen() { return inAlternate ? alternate : normal; }
int param(std::size_t i, int fallback = 1) const {
return i <= argument && args[i] != 0 ? args[i] : fallback;
}
void reply(const std::string& value) {
if (replies.size() + value.size() <= 128) replies += value;
}
void beginScreen() {
if (!managed) invalidate = true;
managed = true;
returnToTranscript = false;
}
void direct(Bytes& out, std::uint8_t ch, int repeat = 1) const {
if (!managed) out.insert(out.end(), repeat, ch);
}
void scroll(int top, int bottom, int number, bool down) {
auto& lines = screen().cells;
const int n = std::min(number, bottom-top+1);
if (n <= 0) return;
if (down) {
std::move_backward(lines.begin()+top, lines.begin()+bottom+1-n, lines.begin()+bottom+1);
for (int row = top; row < top+n; ++row) lines[row].fill(' ');
} else {
std::move(lines.begin()+top+n, lines.begin()+bottom+1, lines.begin()+top);
for (int row = bottom+1-n; row <= bottom; ++row) lines[row].fill(' ');
}
}
void index(bool reverse) {
auto& s = screen();
s.pendingWrap = false;
if (reverse && s.y == s.top) scroll(s.top, s.bottom, 1, true);
else if (!reverse && s.y == s.bottom) scroll(s.top, s.bottom, 1, false);
else s.y = std::clamp(s.y + (reverse ? -1 : 1), 0, height-1);
}
void move(int x, int y) {
auto& s = screen();
s.x = std::clamp(x, 0, width-1);
s.y = std::clamp(y, origin ? s.top : 0, origin ? s.bottom : height-1);
s.pendingWrap = false;
}
void horizontal(int x, Bytes& out) {
auto& s = screen();
int target = std::clamp(x, 0, width-1);
if (target == 0) direct(out, 13);
else if (target != s.x) direct(out, target < s.x ? 8 : 6, std::abs(target-s.x));
move(target, s.y);
}
void save() { auto& s = screen(); s.savedX = s.x; s.savedY = s.y; }
void restore() { auto& s = screen(); move(s.savedX, s.savedY); }
void alternateMode(bool enable, int mode) {
if (enable == inAlternate) return;
beginScreen();
if (enable && mode == 1049) save();
if (enable && mode != 47) alternate = Screen{};
inAlternate = enable;
if (!enable && mode == 1049) restore();
returnToTranscript = !enable;
}
void put(char ch, Bytes& out) {
auto& s = screen();
if (s.pendingWrap) { index(false); s.x = 0; }
auto& line = s.cells[s.y];
if (insert) std::move_backward(line.begin()+s.x, line.end()-1, line.end());
line[s.x] = ch;
direct(out, ch);
if (s.x < width-1) ++s.x;
else s.pendingWrap = autoWrap;
}
static char graphic(char ch) {
switch (ch) {
case 'q': case 'o': case 'p': case 'r': case 's': return '-';
case 'x': return '|';
case 'j': case 'k': case 'l': case 'm': case 'n':
case 't': case 'u': case 'v': case 'w': return '+';
default: return ch;
}
}
void tab(bool back) {
auto& s = screen();
int x = s.x;
do { x += back ? -1 : 1; } while (x > 0 && x < width-1 && !tabs[x]);
move(x, s.y);
}
void control(std::uint8_t ch, Bytes& out) {
auto& s = screen();
switch (ch) {
case 7: out.push_back(ch); break;
case 8: if (s.x > 0) direct(out, ch); move(s.x-1, s.y); break;
case 9: {
int oldX = s.x;
tab(false);
direct(out, 6, s.x-oldX);
break;
}
case 10: case 11: case 12: index(false); direct(out, 10); break;
case 13: move(0, s.y); direct(out, 13); break;
case 14: shifted = true; break;
case 15: shifted = false; break;
}
}
void eraseLine(int mode, Bytes& out) {
auto& s = screen();
auto& line = s.cells[s.y];
if (mode == 0) {
std::fill(line.begin()+s.x, line.end(), ' ');
direct(out, 4);
} else if (mode == 1) {
beginScreen();
std::fill(line.begin(), line.begin()+s.x+1, ' ');
} else if (mode == 2) {
line.fill(' ');
// Some CoWin erase-line paths also move the cursor.
if (!managed) { direct(out, 13); direct(out, 4); direct(out, 6, s.x); }
}
}
void eraseDisplay(int mode, Bytes& out) {
auto& s = screen();
if (mode == 3) return; // discard saved scrollback only
if (mode == 0) {
eraseLine(0, out);
for (int y = s.y+1; y < height; ++y) s.cells[y].fill(' ');
direct(out, 11);
} else if (mode == 1 || mode == 2) {
beginScreen();
for (int y = 0; y < (mode == 2 ? height : s.y); ++y) s.cells[y].fill(' ');
if (mode == 1) eraseLine(1, out);
}
}
void modes(bool on) {
for (std::size_t i = 0; i <= argument; ++i) {
if (!privateMode) {
if (args[i] == 4) { insert = on; if (on) beginScreen(); }
continue;
}
switch (args[i]) {
case 1: applicationKeys = on; break;
case 6: origin = on; beginScreen(); move(0, on ? screen().top : 0); break;
case 7: autoWrap = on; screen().pendingWrap = false; break;
case 47: case 1047: case 1049: alternateMode(on, args[i]); break;
case 1048: if (on) save(); else { beginScreen(); restore(); } break;
}
}
}
void csi(std::uint8_t final, Bytes& out) {
auto& s = screen();
const int n = param(0), mode = args[0];
if (final == 'h' || final == 'l') { modes(final == 'h'); return; }
if (privateMode) return;
switch (final) {
case 'A': case 'B': case 'e': {
const int oldY = s.y;
move(s.x, s.y + (final == 'A' ? -n : n));
direct(out, final == 'A' ? 9 : 10, std::abs(oldY-s.y));
break;
}
case 'C': case 'a': horizontal(s.x+n, out); break;
case 'D': horizontal(s.x-n, out); break;
case 'E': case 'F': beginScreen(); move(0, s.y + (final == 'E' ? n : -n)); break;
case 'G': case '`': horizontal(n-1, out); break;
case 'd': beginScreen(); move(s.x, n-1 + (origin ? s.top : 0)); break;
case 'H': case 'f': beginScreen(); move(param(1)-1, n-1 + (origin ? s.top : 0)); break;
case 'K': eraseLine(mode, out); break;
case 'J': eraseDisplay(mode, out); break;
case 's': save(); break;
case 'u': beginScreen(); restore(); break;
case 'r': {
int top = n-1, bottom = param(1,height)-1;
if (top >= bottom || bottom >= height) break;
beginScreen();
s.top = top; s.bottom = bottom;
move(0, origin ? top : 0);
break;
}
case 'L': case 'M':
if (s.y >= s.top && s.y <= s.bottom) {
beginScreen(); scroll(s.y, s.bottom, n, final == 'L');
}
break;
case 'S': case 'T': beginScreen(); scroll(s.top, s.bottom, n, final == 'T'); break;
case '@': case 'P': case 'X': {
beginScreen();
auto& line = s.cells[s.y];
auto pos = line.begin()+s.x;
const int count = std::min(n,width-s.x);
if (final == '@') std::move_backward(pos, line.end()-count, line.end());
if (final == 'P') {
std::move(pos+count, line.end(), pos);
std::fill(line.end()-count,line.end(),' ');
} else std::fill(pos,pos+count,' ');
break;
}
case 'I': case 'Z': {
int oldX = s.x;
for (int i = 0; i < std::min(n,width); ++i) tab(final == 'Z');
direct(out, final == 'Z' ? 8 : 6, std::abs(s.x-oldX));
break;
}
case 'g': if (mode == 0) tabs[s.x] = false; else if (mode == 3) tabs.fill(false); break;
case 'c': if (mode == 0) reply("\x1b[?1;0c"); break;
case 'n':
if (mode == 5) reply("\x1b[0n");
if (mode == 6) reply("\x1b[" + std::to_string(s.y+1-(origin ? s.top : 0)) +
";" + std::to_string(s.x+1) + "R");
break;
}
}
void startCSI() {
state = State::csi;
args.fill(0);
argument = 0;
ignoredSequence = false;
privateMode = false;
}
void escape(std::uint8_t ch, Bytes& out) {
state = State::plain;
switch (ch) {
case '[': startCSI(); break;
case ']': case 'P': case '^': case '_': case 'X': state = State::string; break;
case '(': case ')': selectG1 = ch == ')'; state = State::charset; break;
case '7': save(); break;
case '8': beginScreen(); restore(); break;
case 'D': index(false); direct(out, 10); break;
case 'E': control(13, out); control(10, out); break;
case 'M': beginScreen(); index(true); break;
case 'H': tabs[screen().x] = true; break;
case 'Z': reply("\x1b[?1;0c"); break;
case 'c':
*this = DriveWireTerminal{};
beginScreen();
break;
default:
if (ch >= 0x20 && ch <= 0x2f) state = State::intermediate;
}
}
static int continuationCount(std::uint8_t ch) {
return ch < 0xc2 || ch > 0xf4 ? 0 : ch < 0xe0 ? 1 : ch < 0xf0 ? 2 : 3;
}
void parse(std::uint8_t ch, Bytes& out) {
if (ch == 0x18 || ch == 0x1a) { state = State::plain; utfRemaining = 0; return; }
if (state == State::string || state == State::stringEscape) {
// A UTF-8 continuation byte in an OSC title can equal C1 ST.
if (utfRemaining && (ch & 0xc0) == 0x80) { --utfRemaining; return; }
utfRemaining = continuationCount(ch);
if (ch == 7 || ch == 0x9c || (state == State::stringEscape && ch == '\\')) state = State::plain;
else state = ch == 27 ? State::stringEscape : State::string;
return;
}
if (ch == 27) { state = State::escape; utfRemaining = 0; return; }
if (ch < 32) { control(ch, out); return; }
if (state == State::escape) { escape(ch, out); return; }
if (state == State::charset) {
if (selectG1) g1Graphics = ch == '0';
else g0Graphics = ch == '0';
state = State::plain;
return;
}
if (state == State::intermediate) { if (ch >= 0x30) state = State::plain; return; }
if (state == State::csi) {
if (ch >= '0' && ch <= '9') args[argument] = std::min(9999, 10*args[argument]+ch-'0');
else if (ch == ';') {
if (argument+1 < args.size()) ++argument;
else ignoredSequence = true;
} else if (ch == '?' && argument == 0 && !args[0]) privateMode = true;
else if (ch >= 0x40 && ch <= 0x7e) {
if (!ignoredSequence) csi(ch, out);
state = State::plain;
} else ignoredSequence = true;
return;
}
if (utfRemaining && (ch & 0xc0) == 0x80) { --utfRemaining; return; }
utfRemaining = 0;
if (ch == 0x9b) { startCSI(); return; }
if (ch == 0x90 || ch == 0x98 || ch == 0x9d || ch == 0x9e || ch == 0x9f) { state = State::string; return; }
if (ch >= 0xc0) {
utfRemaining = continuationCount(ch);
put('?', out);
} else if (ch >= 32 && ch < 127) put((shifted ? g1Graphics : g0Graphics) ? graphic(ch) : ch, out);
}
};
}