// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! An Apple's screen and keyboard in a terminal, for the two front ends that //! want them. //! //! There are two programs here that put a machine in a terminal window: the //! debugger, which is an 8-bit machine surrounded by registers and //! disassembly, and `gs`, which is an Apple IIgs and nothing else because a //! IIgs is a 16-bit machine and the debugger cannot drive one. They are //! different programs for a good reason, but the two things they both have to //! do — turn a keystroke into what an Apple keyboard would have sent, and get //! the machine's screen onto a terminal — are the same job twice, so it is //! done here once. //! //! Nothing in `zig65` proper knows this file exists. It is a module of its //! own, above the library and below the two programs, and it is the only place //! outside them that knows what a terminal is. const std = @import("std"); const flate = std.compress.flate; const vaxis = @import("vaxis"); const zig65 = @import("zig65"); const picture = zig65.picture; const screen = zig65.screen; const video = zig65.video; /// The solid block the Apple's character generator has where ASCII has delete. /// /// The firmware uses it as the cursor: what marks where typing will go is the /// byte `$ff` sitting in the text page. Handing a terminal the raw code /// instead draws nothing at all, which is a machine with no cursor. pub const block = "\u{2588}"; /// And the top half of one, which is how graphics are drawn without a picture: /// a terminal cell is about twice as tall as it is wide, so one cell carries /// two stacked dots as its foreground and background colours. pub const half_block = "\u{2580}"; /// Translates a keystroke into what an Apple keyboard would have produced, or /// null for a key no Apple ever had, which is dropped rather than guessed at. /// /// Everything the machine could have is passed through, which is nearly /// everything: the printable characters, return, escape, tab, delete, the /// arrows, and control with a letter. A front end keeps out of the way by /// putting its own commands behind alt, since no Apple keyboard had one. pub fn appleKey(key: vaxis.Key) ?u8 { if (key.matches(vaxis.Key.enter, .{})) return 0x0d; if (key.matches(vaxis.Key.escape, .{})) return 0x1b; if (key.matches(vaxis.Key.tab, .{})) return 0x09; // The arrows carry the control codes they sit on, which is why the Monitor // treats left and backspace as the same thing. Delete is its own code and // only the IIe had the key. if (key.matches(vaxis.Key.left, .{})) return 0x08; if (key.matches(vaxis.Key.right, .{})) return 0x15; if (key.matches(vaxis.Key.up, .{})) return 0x0b; if (key.matches(vaxis.Key.down, .{})) return 0x0a; // Both rub out, and both send $08. // // Rubbing a character out on an Apple is done by backing the cursor over // it, which is the left arrow's code and what the Monitor's line reader // understands. $7f is not that. A IIe keyboard does have a DELETE key // that sends it, but the line reader treats it as an ordinary character // and prints it, which looks like the cursor moving on and nothing being // deleted. Neither of a terminal's two keys corresponds to that key any // better than the other, so both are given the code that does what the // person pressing them means. if (key.matches(vaxis.Key.backspace, .{}) or key.matches(vaxis.Key.delete, .{})) return 0x08; // Control folds a letter down into the first thirty-two codes, as the // keyboard encoder did. Control-C is how a program is interrupted, so it // has to reach the machine rather than the terminal. It folds the *key* // rather than whatever the key typed, which is why it comes first. if (key.mods.ctrl) { if (key.codepoint > 0x7f) return null; return @as(u8, @intCast(key.codepoint)) & 0x1f; } // What the key *typed*, which is not always the key. // // A terminal speaking the Kitty keyboard protocol reports which key was // pressed and which modifiers were down, and leaves the two joined up to // whoever is reading: shift and `3` on a US keyboard, with the character // it makes alongside. Taking the codepoint by itself turns `PR#3` into // `PR33`, which is the shape of the bug — the machine gets the key and // not the character. `text` is the character, and `shifted_codepoint` is // there for a terminal that reports the shifted key without the text. if (key.text) |typed| { if (typed.len == 1 and typed[0] >= 0x20 and typed[0] < 0x7f) return typed[0]; } if (key.shifted_codepoint) |shifted| { if (shifted >= 0x20 and shifted < 0x7f) return @intCast(shifted); } const codepoint = key.codepoint; if (codepoint > 0x7f) return null; const character: u8 = @intCast(codepoint); if (character >= 0x20 and character < 0x7f) return character; return null; } /// Translates a run of text pasted from the host into the keystrokes an Apple /// keyboard would have made to type it, written through `writer`. /// /// A paste is not typing, so it needs a little tidying that a keystroke does /// not. Every shape of line ending — a bare carriage return, a bare line feed, /// or the carriage-return line-feed pair a host from the DOS lineage writes — /// becomes the single carriage return that is the key ending a line on an /// Apple, since a stray line feed left after the return is a character the line /// reader would print as it moved the cursor down. A tab becomes a space, /// because the Apple keyboards this emulates had no tab a program could read as /// one. Everything else that a keyboard could have made is passed through, and /// anything it could not — the other control codes, and bytes above ASCII — is /// dropped, so a paste carries in only what someone could have sat and typed. pub fn pasteKeys(text: []const u8, writer: *std.Io.Writer) std.Io.Writer.Error!void { var i: usize = 0; while (i < text.len) : (i += 1) { switch (text[i]) { '\r' => { // The line feed of a carriage-return line-feed pair is the // second half of one line ending, not a second ending. if (i + 1 < text.len and text[i + 1] == '\n') i += 1; try writer.writeByte(0x0d); }, '\n' => try writer.writeByte(0x0d), '\t' => try writer.writeByte(' '), 0x20...0x7e => |c| try writer.writeByte(c), else => {}, } } } /// One single-character string per code, so that a cell can be handed a stable /// slice without one being allocated for it. /// /// A frame is up to nineteen hundred characters, and each used to be turned /// into a freshly allocated string, decoded as UTF-8, run through grapheme /// segmentation and measured for width, all to establish that the letter A is /// one column wide. None of that is worth doing for a machine whose whole /// character set is seven bits. pub const ascii: [128][1]u8 = blk: { var table: [128][1]u8 = undefined; for (&table, 0..) |*entry, i| entry.* = .{@intCast(i)}; break :blk table; }; /// How often at most a changed screen is sent to a terminal that draws /// pictures. /// /// Every frame would be sixty of them a second and a frame is most of a /// megabyte encoded, which is two and a half megabytes a second down a pipe /// for a picture nobody can see move that fast. Twenty is plenty for watching /// a program draw, and a screen that changes once and stops is late by fifty /// milliseconds, which nobody has ever noticed. pub const picture_ns = 50 * std.time.ns_per_ms; /// A machine's screen, drawn into a terminal as well as the terminal allows. /// /// A terminal that speaks the Kitty graphics protocol gets the pixels: the /// whole of the machine's display, scaled into the window by the terminal. One /// that does not gets the upper half block, which is two stacked dots to a /// cell — exactly a Lo-Res screen at forty columns, and a sketch of anything /// finer. /// /// The picture is kept between frames and sent only when it changes, which is /// what `hash` is for: hashing the memory the renderer is about to read is far /// cheaper than rendering, and very much cheaper than sending. pub const Display = struct { buffer: ?picture.Buffer = null, /// The picture squeezed, and then that in base64, which is what goes down /// the wire. See `transmit` for why it is worth squeezing. squeezed: []u8 = &.{}, window: []u8 = &.{}, encoded: []u8 = &.{}, image: ?vaxis.Image = null, hash: u64 = 0, sent_at: std.Io.Timestamp = .{ .nanoseconds = 0 }, which: picture.Display = .apple2, pub fn deinit(self: *Display, gpa: std.mem.Allocator) void { if (self.buffer) |*buffer| buffer.deinit(gpa); if (self.squeezed.len != 0) gpa.free(self.squeezed); if (self.window.len != 0) gpa.free(self.window); if (self.encoded.len != 0) gpa.free(self.encoded); self.* = .{}; } /// Draws the machine's screen as a picture, and says whether it managed /// to: a caller that gets false should fall back to `halfBlocks`. /// /// `lines` is how many of the display's lines to show, which is fewer than /// all of them for a mixed screen whose bottom rows a terminal draws /// better as text. `monitor` says which display the dots are being looked /// at on: a composite colour one, a monochrome one, or the IIc's flat /// panel, which are three different things to paint the same stream as. pub fn draw( self: *Display, gpa: std.mem.Allocator, vx: *vaxis.Vaxis, writer: *std.Io.Writer, clock: std.Io.Clock, io: std.Io, into: vaxis.Window, machine: anytype, which: picture.Display, lines: u16, monitor: picture.Monitor, hash: u64, ) !void { // A buffer is thrown away and built again when the display changes, // and also when the display it is for changes *shape*: a Videoterm's // picture is the size its 6845 was told to make it, and a program may // tell it something else while this is running. const wrong_shape = if (self.buffer) |*have| !have.fits(machine) else false; if (self.buffer == null or self.which != which or wrong_shape) { if (self.buffer) |*old| old.deinit(gpa); if (self.squeezed.len != 0) gpa.free(self.squeezed); if (self.window.len != 0) gpa.free(self.window); if (self.encoded.len != 0) gpa.free(self.encoded); // Native size: the terminal does the scaling, so sending more // pixels than the machine has would only be sending them twice. self.buffer = try picture.Buffer.init(gpa, which, machine, .{ .across = 1, .down = 1 }); const dots = self.buffer.?.rgb.len; // Room for a stream that does not compress at all, which is what // deflate falls back to when nothing repeats. self.squeezed = try gpa.alloc(u8, dots + dots / 8 + 64); self.window = try gpa.alloc(u8, flate.max_window_len); self.encoded = try gpa.alloc(u8, std.base64.standard.Encoder.calcSize(self.squeezed.len)); self.image = null; self.which = which; } // Changing monitors means everything on the screen is different, so // the picture goes again whatever the hash says. if (self.buffer.?.options.monitor != monitor) { self.buffer.?.options.monitor = monitor; self.image = null; } const now: std.Io.Timestamp = .now(io, clock); const due = now.nanoseconds -| self.sent_at.nanoseconds >= picture_ns; if (self.image == null or (hash != self.hash and due)) { const buffer = &self.buffer.?; buffer.draw(machine); if (self.image) |old| vx.freeImage(writer, old.id); self.image = try transmit(vx, writer, buffer.rgb, .{ .squeezed = self.squeezed, .window = self.window, .encoded = self.encoded, }, buffer.width(), buffer.height()); self.hash = hash; self.sent_at = now; } try self.image.?.draw(into, .{ .scale = .fill, .clip_region = .{ .height = lines }, // Underneath the text *and* underneath the cell backgrounds. A // Kitty image sits above both by default, which is right for a // screen with nothing in front of it and wrong the moment anything // is: a dialog drawn over the machine's screen would be composited // under the picture of that screen and disappear. // // The protocol has two thresholds rather than one, and the // difference between them is the whole of this. Below nought an // image is drawn under the *glyphs*, which is enough to read a // dialog's words but leaves the picture showing between and behind // them, since a cell's background is still painted under the image // rather than over it. Below `-1_073_741_824` it is drawn under // the backgrounds as well, and then a cell that paints one of its // own hides the picture completely while a cell left at the // terminal's default lets it through. That is exactly the // arrangement wanted: the machine's screen shows everywhere // nothing has been drawn over it, and anything that paints itself // — see the disk picker — is solid. .z_index = -1_073_741_825, }); } }; /// Somewhere to put a picture on its way to the terminal. pub const Scratch = struct { squeezed: []u8, window: []u8, encoded: []u8, }; /// Sends a picture to a terminal that speaks the Kitty graphics protocol, /// squeezed on the way. /// /// A screen is 560 by 192 and three bytes a dot, which is 322,560 bytes, and /// 430,080 once base64 has had it. That was what it cost every time the /// picture changed — and a machine sitting at a BASIC prompt changes it about /// eight times a second: four for the flash clock, and four more because the /// firmware rewrites the cursor character. Three and a half megabytes a /// second, for a blinking cursor. /// /// So it goes compressed. `o=z` in the protocol means the pixels are a zlib /// stream, and a screen of mostly-black text is exactly what deflate is good /// at. The terminal does the expanding, which it is far better placed to do /// than the wire is to carry the difference. /// /// It is written out here rather than handed to vaxis because vaxis's own /// `transmitPreEncodedImage` has no `o=z`; everything else about the escape — /// the four kilobyte chunks and the `m=1` on all but the last — is the same /// either way. pub fn transmit( vx: *vaxis.Vaxis, writer: *std.Io.Writer, rgb: []const u8, scratch: Scratch, wide: u16, tall: u16, ) !vaxis.Image { const encoded = try squeeze(rgb, scratch); const id = vx.next_img_id; vx.next_img_id += 1; const chunk = 4096; var at: usize = 0; while (at < encoded.len) { const take = @min(chunk, encoded.len - at); const more: u8 = @intFromBool(at + take != encoded.len); if (at == 0) { try writer.print("\x1b_Gf=24,o=z,s={d},v={d},i={d},m={d};{s}\x1b\\", .{ wide, tall, id, more, encoded[at..][0..take], }); } else { try writer.print("\x1b_Gm={d};{s}\x1b\\", .{ more, encoded[at..][0..take] }); } at += take; } try writer.flush(); return .{ .id = id, .width = wide, .height = tall }; } /// Compresses the pixels and base64s the result, which is what the protocol /// takes. Split out so that a test can read it back. fn squeeze(rgb: []const u8, scratch: Scratch) ![]const u8 { var out: std.Io.Writer = .fixed(scratch.squeezed); var compressor = try flate.Compress.init(&out, scratch.window, .zlib, .level_6); try compressor.writer.writeAll(rgb); try compressor.finish(); return std.base64.standard.Encoder.encode(scratch.encoded, out.buffered()); } /// Draws the old Apple II display with the upper half block, for a terminal /// that cannot show a picture. /// /// A cell carries two dots, so a pane of forty by twenty-four is forty by /// forty-eight dots — exactly a Lo-Res screen, and exactly a Double Lo-Res one /// at eighty columns. Hi-Res does not fit and cannot: two hundred and eighty /// dots do not go into forty cells, so what is drawn is every fourteenth dot /// position, one Hi-Res byte's worth. It is enough to see that a program is /// drawing and roughly what, and not enough to read. pub fn halfBlocks(pane: vaxis.Window, machine: anytype, showing: screen.Mode, columns: u16) void { // Four scan lines to each half of a cell, which comes out even: 24 rows of // two halves is 48, and 192 lines over 48 is 4. A mixed screen is 160 // lines over the 40 halves of its 20 rows, which is the same 4. const rows: u16 = if (showing.isMixed()) 20 else 24; const between = video.height / 48; var upper: video.Line = .{}; var lower: video.Line = .{}; for (0..rows) |row_| { const row: u16 = @intCast(row_); if (video.scanLine(machine, row * 8, &upper) != .dots) continue; if (video.scanLine(machine, row * 8 + between, &lower) != .dots) continue; for (0..columns) |col_| { const col: u16 = @intCast(col_); const x = @as(usize, col) * video.width / columns; const top = video.palette[upper.colours[x]]; const bottom = video.palette[lower.colours[x]]; pane.writeCell(col, row, .{ .char = .{ .grapheme = half_block, .width = 1 }, .style = .{ .fg = .{ .rgb = [_]u8{ top.r, top.g, top.b } }, .bg = .{ .rgb = [_]u8{ bottom.r, bottom.g, bottom.b } }, }, }); } } } /// The same for Super Hi-Res, which does not fit a terminal any better. /// /// Two hundred lines into forty-eight, and six hundred and forty dots into /// eighty cells: one dot in eight across and one line in four down. It is a /// long way from the picture, and it is what there is without one. pub fn superHalfBlocks(pane: vaxis.Window, machine: anytype, columns: u16) void { var table: [zig65.superhires.palettes * zig65.superhires.colours]video.Rgb = undefined; zig65.superhires.palette(machine, &table); var upper: zig65.superhires.Line = .{}; var lower: zig65.superhires.Line = .{}; const rows = 24; for (0..rows) |row_| { const row: u16 = @intCast(row_); const y = @as(usize, row) * zig65.superhires.height / (rows * 2); zig65.superhires.scanLine(machine, @intCast(y * 2), &upper); zig65.superhires.scanLine(machine, @intCast(y * 2 + 1), &lower); for (0..columns) |col_| { const col: u16 = @intCast(col_); const x = @as(usize, col) * zig65.superhires.width / columns; const top = table[upper.entries[x]]; const bottom = table[lower.entries[x]]; pane.writeCell(col, row, .{ .char = .{ .grapheme = half_block, .width = 1 }, .style = .{ .fg = .{ .rgb = [_]u8{ top.r, top.g, top.b } }, .bg = .{ .rgb = [_]u8{ bottom.r, bottom.g, bottom.b } }, }, }); } } } /// Draws rows of the text screen as characters, which a terminal does better /// than a picture of a character generator does. /// /// `flash` is the phase of the flash clock. Flashing is drawn rather than /// handed to the terminal to blink: the machine flashes by swapping the dots /// for the gaps, so half the time a flashing character is an inverse one, and /// a terminal asked to blink instead would leave the cursor — which is a /// flashing space — as nothing at all. pub fn textRows( pane: vaxis.Window, machine: anytype, from: u16, columns: u16, page: u16, alternate: bool, flash: bool, ) void { for (from..screen.rows) |row_| { const row: u16 = @intCast(row_); const line = screen.rowBase(page, row); for (0..columns) |col_| { const col: u16 = @intCast(col_); const byte = textByte(machine, columns, line, col); const glyph = screen.decode(byte, alternate); const grapheme: []const u8 = if (glyph.character == 0x7f) block else &ascii[glyph.character & 0x7f]; pane.writeCell(col, row, .{ .char = .{ .grapheme = grapheme, .width = 1 }, .style = switch (glyph.video) { .normal => .{}, .inverse => .{ .reverse = true }, .flashing => .{ .reverse = flash }, }, }); } } } /// The byte behind one character position. /// /// A machine with no auxiliary memory has no `videoByte` to ask — the flat /// model is sixty-four kilobytes of RAM and nothing else — so it is read /// straight out of memory instead, which for that machine is the same thing. fn textByte(machine: anytype, columns: u16, line: u16, column: u16) u8 { const Machine = @typeInfo(@TypeOf(machine)).pointer.child; if (comptime !@hasDecl(Machine, "videoByte")) return machine.peek(line + column); return screen.byteAt(machine, columns, line, column); } /// A number that changes when the old Apple II display would. /// /// It hashes what the renderer is about to read rather than what it would /// produce, which is the same answer for a great deal less work: a Hi-Res /// screen is eight kilobytes of memory against a hundred and seven thousand /// dots. /// /// It hashes the *displayed* bytes rather than the page they are in, and that /// is not tidiness. Neither page is full: the text page shows 960 bytes of its /// kilobyte and the Hi-Res page 7,680 of its eight, and the gaps are the /// screen holes — which peripheral firmware uses as scratch and writes /// constantly. Hashing them means a still screen is never still, and a /// still screen that is never still is a megabyte a frame down the wire for a /// picture that has not changed. Which is exactly what happened. pub fn videoHash(machine: anytype, showing: screen.Mode, flash: bool) u64 { var hash: std.hash.Wyhash = .init(@intFromEnum(showing)); hash.update(&.{@intFromBool(flash)}); const halves: Halves = if (showing.isDoubled()) .both else .main; if (showing.isHighResolution()) { const page = machine.hiresPage(); for (0..video.height) |y| { hashRange(machine, &hash, video.hiresBase(page, @intCast(y)), 40, halves); } } else { const page = machine.displayPage(); for (0..screen.rows) |row| { hashRange(machine, &hash, screen.rowBase(page, @intCast(row)), 40, halves); } } // And the text rows as well for a mixed screen, whose bottom four come out // of the text page whatever the graphics above them are doing. if (showing.isMixed()) { const page = machine.displayPage(); for (20..screen.rows) |row| { hashRange(machine, &hash, screen.rowBase(page, @intCast(row)), 40, .both); } } return hash.final(); } /// And one that changes when a Super Hi-Res screen would. All of it is in one /// place — thirty-two kilobytes of the auxiliary half — pixels, palettes and /// the control byte a line, so there is nothing to choose between. pub fn superHash(machine: anytype) u64 { var hash: std.hash.Wyhash = .init(0); hashRange(machine, &hash, zig65.superhires.buffer, 0x8000, .auxiliary); return hash.final(); } /// Which halves of memory a range is drawn out of. const Halves = enum { main, auxiliary, both }; fn hashRange(machine: anytype, hash: *std.hash.Wyhash, base: u16, length: u17, halves: Halves) void { for (0..length) |i| { const at: u16 = base +% @as(u16, @intCast(i)); if (halves != .auxiliary) hash.update(&.{machine.videoByte(false, at)}); if (halves != .main) hash.update(&.{machine.videoByte(true, at)}); } } /// Which display the machine is being looked at on, which is the library's: /// the difference between the three is what the dots are painted as, so the /// choice belongs beside the painting. See `picture.Monitor`. pub const Monitor = picture.Monitor; /// Who draws the text: the terminal, or the machine. /// /// The terminal's own letters are crisp and cost nothing, and they are what a /// terminal that cannot show a picture gets whatever this says. The machine's /// character generator is the real thing — the actual glyphs off the actual /// chip, MouseText included, which the terminal cannot draw at all because /// `screen.decode` has to fold those thirty-two codes onto ASCII. /// /// The machine's is the default, since it is what the machine looks like. /// `alt+x` is the other. pub const TextDrawing = enum { terminal, pixels, pub fn other(self: TextDrawing) TextDrawing { return switch (self) { .terminal => .pixels, .pixels => .terminal, }; } pub fn asPixels(self: TextDrawing) bool { return self == .pixels; } pub fn describe(self: TextDrawing) []const u8 { return switch (self) { .terminal => "text drawn by the terminal", .pixels => "text drawn by the machine's character generator", }; } pub fn parse(name: []const u8) ?TextDrawing { if (std.mem.eql(u8, name, "terminal")) return .terminal; if (std.mem.eql(u8, name, "pixels")) return .pixels; return null; } }; /// The machine's screen as a mousing surface. /// /// A terminal says where its pointer is, in cells and sometimes in pixels /// inside a cell; a machine's screen is so many dots across. This turns the /// one into the other, so that dragging the pointer from one side of the pane /// to the other drags whatever the machine is showing from one side of its /// screen to the other. /// /// Nothing here is about a particular pointing device. What a caller does with /// the answer is its own business: a IIgs's mouse is on the desktop bus and /// counts how far it has moved, so its front end sends the difference between /// one answer and the last, while an AppleMouse card is told where the pointer /// is outright. pub const Surface = struct { /// How many character cells the screen is drawn in. columns: i32, rows: i32, /// Where the first of them is: a pane with a border starts one cell in and /// one cell down, and forty-column text is centred in an eighty-column /// monitor. left: i32 = 1, top: i32 = 1, /// How many pixels there are in one cell, across and down. Ones when the /// terminal reports its pointer by the cell and nothing finer, which still /// works: the arithmetic is then in whole cells. cell: [2]i32 = .{ 1, 1 }, /// How many dots the machine draws. dots: [2]i32, /// Where a pointer at this cell, this far into it, falls on the machine's /// screen — or nothing if it is not over the screen at all. pub fn dot(self: Surface, column: i32, row: i32, offset: [2]i32) ?[2]i32 { const across = column - self.left; const down = row - self.top; if (across < 0 or down < 0) return null; if (across >= self.columns or down >= self.rows) return null; const wide = @max(1, self.cell[0]); const tall = @max(1, self.cell[1]); const x = across * wide + std.math.clamp(offset[0], 0, wide - 1); const y = down * tall + std.math.clamp(offset[1], 0, tall - 1); return .{ @divTrunc(x * self.dots[0], self.columns * wide), @divTrunc(y * self.dots[1], self.rows * tall), }; } }; const testing = std.testing; test "a key gives what it typed rather than which key it was" { // `#` is shift and `3` on a US keyboard, and a terminal speaking the Kitty // keyboard protocol reports exactly that: the key is `3`, the modifier is // shift, and the character it made comes alongside. Taking the codepoint // by itself turns `PR#3` into `PR33`, which is how this was found. try testing.expectEqual(@as(?u8, '#'), appleKey(.{ .codepoint = '3', .shifted_codepoint = '#', .text = "#", .mods = .{ .shift = true }, })); // And from the shifted codepoint alone, for a terminal that reports the // key without the text. try testing.expectEqual(@as(?u8, '#'), appleKey(.{ .codepoint = '3', .shifted_codepoint = '#', .mods = .{ .shift = true }, })); // A terminal that says nothing about shift at all sends the character as // the codepoint, which is what happens over a plain pipe, and that has // always worked. try testing.expectEqual(@as(?u8, '#'), appleKey(.{ .codepoint = '#' })); try testing.expectEqual(@as(?u8, '3'), appleKey(.{ .codepoint = '3' })); } test "control folds the key rather than what the key typed" { // Control-C is how a program is interrupted and has to reach the machine, // and it is the *key* that folds: a terminal may report text alongside a // control chord and it is not what the machine wants. try testing.expectEqual(@as(?u8, 0x03), appleKey(.{ .codepoint = 'c', .mods = .{ .ctrl = true }, })); try testing.expectEqual(@as(?u8, 0x03), appleKey(.{ .codepoint = 'c', .text = "\x03", .mods = .{ .ctrl = true }, })); } test "the keys an Apple had, and the ones it did not" { try testing.expectEqual(@as(?u8, 0x0d), appleKey(.{ .codepoint = vaxis.Key.enter })); try testing.expectEqual(@as(?u8, 0x1b), appleKey(.{ .codepoint = vaxis.Key.escape })); // Both of a terminal's two rub-out keys send what the Monitor's line // reader understands, which is the left arrow's code. try testing.expectEqual(@as(?u8, 0x08), appleKey(.{ .codepoint = vaxis.Key.backspace })); try testing.expectEqual(@as(?u8, 0x08), appleKey(.{ .codepoint = vaxis.Key.delete })); try testing.expectEqual(@as(?u8, 0x08), appleKey(.{ .codepoint = vaxis.Key.left })); // And a key no Apple ever had is dropped rather than guessed at. try testing.expectEqual(@as(?u8, null), appleKey(.{ .codepoint = vaxis.Key.f1 })); try testing.expectEqual(@as(?u8, null), appleKey(.{ .codepoint = 0x2603 })); } test "pasted text becomes the keys that would have typed it" { var buffer: [64]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); // Two lines however the host ends them — a lone line feed, and the pair a // DOS-lineage host writes — come in as two lines each ended by a single // carriage return, with no stray line feed to move the cursor and print. try pasteKeys("10 PRINT\n20 END\r\n", &writer); try testing.expectEqualSlices(u8, "10 PRINT\x0d20 END\x0d", writer.buffered()); // A tab is a space, and the control codes an Apple keyboard could not make // are dropped rather than sent as themselves. writer = .fixed(&buffer); try pasteKeys("A\tB\x00\x07C", &writer); try testing.expectEqualSlices(u8, "A BC", writer.buffered()); } test "a picture goes down the wire squeezed, and comes back the same" { const gpa = testing.allocator; // A screen's worth of the sort of thing a text screen is: mostly one // colour, with a bit of another in it. const dots = 560 * 192 * 3; const rgb = try gpa.alloc(u8, dots); defer gpa.free(rgb); @memset(rgb, 0); var at: usize = 0; while (at < dots) : (at += 3 * 37) rgb[at] = 0xff; const scratch: Scratch = .{ .squeezed = try gpa.alloc(u8, dots + dots / 8 + 64), .window = try gpa.alloc(u8, flate.max_window_len), .encoded = try gpa.alloc(u8, std.base64.standard.Encoder.calcSize(dots + dots / 8 + 64)), }; defer gpa.free(scratch.squeezed); defer gpa.free(scratch.window); defer gpa.free(scratch.encoded); const sent = try squeeze(rgb, scratch); // Worth doing at all: a screen like this should come down by a long way. try testing.expect(sent.len * 8 < dots); // And it has to be the same picture on the other side, since the terminal // will be the one expanding it. const raw = try gpa.alloc(u8, sent.len); defer gpa.free(raw); var decoder = std.base64.standard.Decoder; const size = try decoder.calcSizeForSlice(sent); try decoder.decode(raw[0..size], sent); var reading: std.Io.Reader = .fixed(raw[0..size]); var window: [flate.max_window_len]u8 = undefined; var expand: flate.Decompress = .init(&reading, .zlib, &window); const back = try expand.reader.allocRemaining(gpa, .unlimited); defer gpa.free(back); try testing.expectEqualSlices(u8, rgb, back); } test "the pointer falls where it is over the machine's screen" { // Eighty columns of a screen five hundred and sixty dots wide, drawn in a // pane with a border round it, and a terminal reporting whole cells. const surface: Surface = .{ .columns = 80, .rows = 24, .dots = .{ 560, 192 } }; // The corner of the screen is one cell in and one cell down. try testing.expectEqual(@as(?[2]i32, .{ 0, 0 }), surface.dot(1, 1, .{ 0, 0 })); // Seven dots to a column at eighty columns, eight scan lines to a row. try testing.expectEqual(@as(?[2]i32, .{ 7, 8 }), surface.dot(2, 2, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, .{ 553, 184 }), surface.dot(80, 24, .{ 0, 0 })); // The border itself is not the screen, and neither is anything past it. try testing.expectEqual(@as(?[2]i32, null), surface.dot(0, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, null), surface.dot(1, 0, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, null), surface.dot(81, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, null), surface.dot(1, 25, .{ 0, 0 })); } test "a terminal that reports pixels gets the precision it is reporting" { // Ten pixels to a cell across, twenty down, which is an ordinary enough // font. Now every pixel of a cell is a different place on the screen. const surface: Surface = .{ .columns = 80, .rows = 24, .cell = .{ 10, 20 }, .dots = .{ 560, 192 }, }; try testing.expectEqual(@as(?[2]i32, .{ 0, 0 }), surface.dot(1, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, .{ 3, 3 }), surface.dot(1, 1, .{ 5, 9 })); try testing.expectEqual(@as(?[2]i32, .{ 7, 8 }), surface.dot(2, 2, .{ 0, 0 })); // An offset bigger than a cell is not a place off the screen: it is the // far edge of the cell it was reported in. try testing.expectEqual(@as(?[2]i32, .{ 6, 7 }), surface.dot(1, 1, .{ 99, 99 })); } test "forty columns are centred in an eighty column monitor" { // Which is where the pane draws them, so it is where the pointer has to // find them. Fourteen dots to a column at forty. const surface: Surface = .{ .columns = 40, .rows = 24, .left = 1 + (80 - 40) / 2, .dots = .{ 560, 192 }, }; try testing.expectEqual(@as(?[2]i32, null), surface.dot(20, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, .{ 0, 0 }), surface.dot(21, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, .{ 14, 0 }), surface.dot(22, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, .{ 546, 0 }), surface.dot(60, 1, .{ 0, 0 })); try testing.expectEqual(@as(?[2]i32, null), surface.dot(61, 1, .{ 0, 0 })); }