#pragma once #include #include #include #include namespace VCC::Mac { using TerminalGrid = std::array, 24>; // Encode an addressed terminal screen for the stock NitrOS-9 telnet client's // output path, which passes ordinary bytes straight through to CoWin. class DriveWireTerminalOutput { public: static constexpr std::size_t maxDrawBytes = 2010; void draw(const TerminalGrid& cells, int x, int y, bool cursorVisible, bool clear, std::vector& out) { const auto start = out.size(); if (clear || !known) { out.push_back(0x0c); for (auto& row : painted) row.fill(' '); cursorX = cursorY = -1; visibilityKnown = false; known = true; } constexpr int bottom = 23; for (int row = 0; row < bottom - 1; ++row) { paintRow(row, cells[row], out); } // GRFDRV wraps immediately after the last column. To write the // bottom-right cell without scrolling away the first line, prepare // the last row one line up and move it down with CoWin's insert-line. // Ordinary changes elsewhere on the bottom row avoid that extra work. if (glyph(cells[bottom].back()) != painted[bottom].back()) { paintRow(bottom - 1, cells[bottom], out); position(0, bottom - 1, out); out.insert(out.end(), {0x1f, 0x30}); painted[bottom] = painted[bottom - 1]; painted[bottom - 1].fill(' '); } else { paintRow(bottom, cells[bottom], out); } paintRow(bottom - 1, cells[bottom - 1], out); // CoWin may move the cursor on a write, including automatic wrapping. // Reposition it even when the logical position itself didn't change. x = std::clamp(x, 0, 79); y = std::clamp(y, 0, 23); if (out.size() != start || x != cursorX || y != cursorY) { position(x, y, out); cursorX = x; cursorY = y; } if (!visibilityKnown || visible != cursorVisible) { out.insert(out.end(), {0x05, static_cast(cursorVisible ? 0x21 : 0x20)}); visible = cursorVisible; visibilityKnown = true; } } private: using Row = TerminalGrid::value_type; TerminalGrid painted{}; int cursorX = -1, cursorY = -1; bool known = false, visibilityKnown = false, visible = true; static char glyph(char ch) { const auto byte = static_cast(ch); return byte >= 0x20 && byte <= 0x7e ? ch : '?'; } static void position(int x, int y, std::vector& out) { out.insert(out.end(), {0x02, static_cast(0x20 + x), static_cast(0x20 + y)}); } void paintRow(int row, const Row& desired, std::vector& out) { auto& current = painted[row]; std::size_t x = 0; while (x < desired.size()) { if (current[x] == glyph(desired[x])) { ++x; continue; } const auto first = x; position(static_cast(x), row, out); auto lastChange = x; // Repaint short gaps: an absolute cursor move costs three bytes. // Even an alternating pattern costs at most 83 bytes per row. while (x < desired.size() && x - lastChange <= 4) { if (current[x] != glyph(desired[x])) lastChange = x; ++x; } for (auto column = first; column <= lastChange; ++column) { current[column] = glyph(desired[column]); out.push_back(static_cast(current[column])); } } } }; } // namespace VCC::Mac