Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! A host console card: a slot card that gives an embedded Apple a console,//! its character output going to a `std.Io.Writer` and its character input//! coming from a `std.Io.Reader` that the embedder supplies.//!//! This one is for a program that embeds `zig65` as a library rather than for//! the interactive front ends, which own the terminal themselves. It is the//! way to run a machine with no screen of its own — headless, or wrapped in//! another application — and still talk to it: `PR#n` sends everything the//! machine prints to the writer, `IN#n` takes everything it reads from the//! reader. The two ends are the embedder's and the embedder owns them; this//! neither opens nor closes anything, and a card with nothing attached is a//! console switched off, which the machine cannot tell from a real one.//!//! ## The two directions, synchronously//!//! Each is done as it happens, on the access itself: a byte written to the//! card's data port is written straight to the writer, and reading the port//! takes the next byte straight from the reader, blocking until one is there.//! Blocking is the console's own behaviour — a real `RDKEY` spins until a key//! is pressed — and for a headless embedder it is what is wanted: the machine//! waits on the host the way it would wait on a person.//!//! ## The firmware//!//! Like the parallel card and the clock card, the firmware here is ours rather//! than anyone's: what a peripheral card in the output and input vectors has to//! do is published, so nothing of Apple's is needed. `PR#n` and `IN#n` do not//! call the card; they only rewrite the output vector CSW (`$36/$37`) or the//! input vector KSW (`$38/$39`) to point at `$Cn00` and return, so the card is//! first entered at `$Cn00` on the first `COUT` or `RDKEY`, where it has to//! work out whether it is being asked to put a character out or to fetch one//! in (Apple Computer, Inc., 1979, pp. 84, 95).//!//! It does that the way the Super Serial Card's firmware does (read out of//! `341-0065-a`): the entry at `$Cn00` **revectors** — it points CSW at its own//! output routine and KSW at its own input routine, giving the two vectors//! distinct low bytes so that later `COUT`s and `RDKEY`s land straight on the//! right routine and never come back through `$Cn00`. It tells the current call//! apart by whether CSW is still the raw `$Cn00`: if it is, this entry is the//! output call and is serviced as output; otherwise it is the input call. When//! both vectors are still raw — `PR#n` and `IN#n` both done and nothing printed//! or read yet — the tie goes to output, exactly as the Apple II Reference//! Manual sets out: "If both switches contain $Cn, then your subroutine should//! assume that it is being called for output" (Apple Computer, Inc., 1979,//! p. 95). The very next call fixes the other vector.//!//! ## Line endings//!//! A console is line-oriented on the host's terms and on the Apple's at once,//! and the two do not agree, so the card translates between them — the one//! place it is not a transparent pipe. On the way out the Apple's carriage//! return (`$0d`, the byte `PRINT` ends a line with) becomes the line feed a//! `std.Io.Writer` consumer expects; on the way in a line feed becomes the//! carriage return the Monitor's line reader ends a line on, and a carriage//! return from the host is dropped so a host writing `\r\n` is not read as two//! lines. The high bit is the Apple's — set on everything it prints, set on//! everything a keyboard hands it — so it is taken off on the way out and, by//! the firmware, put on on the way in.
const std = @import("std");
/// The card.////// Where the bytes go and come from are a `std.Io.Writer` and a/// `std.Io.Reader` the caller attaches, and the caller owns them: this opens/// and closes nothing. Buffering and flushing are the caller's too — nothing/// here flushes, so a caller that wants each character seen at once attaches an/// unbuffered writer or flushes it itself.pub const Card = struct { /// Whether there is a card in the slot at all. fitted: bool = false,
/// The host's console: output to the writer, input from the reader. Either /// may be absent, which is that direction switched off. out: ?*std.Io.Writer = null, in: ?*std.Io.Reader = null,
/// What was last put on the data port, which is what a read of it gives /// back when there is no reader attached — the same latch the parallel /// card keeps, so the address is never an undriven bus. latch: u8 = 0,
/// How many bytes have gone each way, which is all a caller needs to say /// the console is doing something. sent: u64 = 0, received: u64 = 0,
/// The first thing that went wrong, if anything did. Kept rather than /// returned because the card is reached from a load or store instruction, /// which has nowhere to put an error and no business stopping the machine /// over one. Whoever attached the streams looks here. trouble: ?anyerror = null,
/// Sends one character to the host, the high bit already taken off by the /// firmware. A carriage return becomes the host's line feed. pub fn send(self: *Card, byte: u8) void { self.latch = byte; self.sent +|= 1; const out = self.out orelse return; const host: u8 = if (byte == carriage_return) line_feed else byte; out.writeAll(&.{host}) catch |err| { if (self.trouble == null) self.trouble = err; }; }
/// Takes the next character from the host, blocking until one is there, /// and hands back the seven-bit byte the firmware will set the high bit on. /// A line feed becomes a carriage return and a host carriage return is /// skipped, so a line however the host ended it arrives ended by the one /// carriage return the Monitor's line reader wants. /// /// With nothing attached, or once the reader has ended or failed, it hands /// back a carriage return: a machine waiting on input gets an empty line /// rather than a byte that never comes. pub fn receive(self: *Card) u8 { const in = self.in orelse return carriage_return; while (true) { const byte = in.takeByte() catch |err| { if (self.trouble == null) self.trouble = err; return carriage_return; }; if (byte == carriage_return) continue; self.received +|= 1; const apple: u8 = if (byte == line_feed) carriage_return else byte; self.latch = apple; return apple; } }};
/// The carriage return the Apple ends a line with, and the line feed the host/// does: the two the card translates between.pub const carriage_return: u8 = 0x0d;pub const line_feed: u8 = 0x0a;
/// Where the two routines sit in the firmware page, which the dispatch at/// `$Cn00` points CSW and KSW at so that later calls reach them directly. They/// follow the dispatch, whose length fixes them.const output_entry: u8 = 27;const input_entry: u8 = output_entry + output_len;const output_len: u8 = 8;
/// The card's 256 bytes of ROM, for a card in `slot`.////// `PR#n` points CSW at `$Cn00` and `IN#n` points KSW at it, so the first/// character printed or read arrives here; the dispatch revectors the two at/// the output and input routines below and services the call. See the module/// comment for why it is shaped this way.pub fn firmware(comptime slot: u4) [256]u8 { const data = 0xc080 + @as(u16, slot) * 0x10; const lo: u8 = @truncate(data); const hi: u8 = @truncate(data >> 8); // The high byte of this card's $Cn00 page, which is what a vector pointing // at the card holds and what the dispatch compares CSWH and KSWH against. const page: u8 = 0xc0 + @as(u8, slot);
var rom: [256]u8 = @splat(0); const code = [_]u8{ // $Cn00 dispatch. The character (on output) is in A; save it, since // working out which way this call goes clobbers A. 0x48, // PHA 0xa5, 0x37, // LDA CSWH ($37) 0xc9, page, // CMP #page is the output vector ours? 0xd0, 0x0c, // BNE via_ksw no -> this is an input call 0xa5, 0x36, // LDA CSWL ($36) 0xd0, 0x08, // BNE via_ksw ours but already revectored // -> this call is input // The output vector is the raw $Cn00: this is the output call. Point // it at the output routine so the next COUT skips this dispatch, then // service it. 0xa9, output_entry, // LDA #output_entry 0x85, 0x36, // STA CSWL ($36) 0x68, // PLA the character, back in A 0x4c, output_entry, page, //JMP output // via_ksw: the input call. Point KSW at the input routine so the next // RDKEY skips this dispatch, then service it. 0xa9, input_entry, // LDA #input_entry 0x85, 0x38, // STA KSWL ($38) 0x68, // PLA 0x4c, input_entry, page, // JMP input
// output: the character is in A with its high bit set. Send it with // the bit off, and hand it back unchanged the way COUT does. 0x48, // PHA 0x29, 0x7f, // AND #$7f 0x8d, lo, hi, // STA data 0x68, // PLA 0x60, // RTS
// input: take a character from the host, set its high bit, return it. // Reading the port blocks until the host has one. 0xad, lo, hi, // LDA data 0x09, 0x80, // ORA #$80 0x60, // RTS }; @memcpy(rom[0..code.len], &code); return rom;}
/// One page for each slot, since the slot's own addresses are assembled into/// its firmware and which slot that is cannot be known until a machine is/// built. Indexed by slot number; slot 0 is not a slot and is never read.pub const firmwares: [8][256]u8 = blk: { var all: [8][256]u8 = undefined; for (0..all.len) |slot| all[slot] = firmware(@intCast(slot)); break :blk all;};
const testing = std.testing;
test "a character written to the port is a character the host has, LF for CR" { var buffer: [64]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); var card: Card = .{ .fitted = true, .out = &writer };
card.send('H'); card.send('i'); card.send(carriage_return); // The carriage return the Apple ends a line with reaches the host as its // own line feed. try testing.expectEqualStrings("Hi\n", writer.buffered()); try testing.expectEqual(@as(u64, 3), card.sent); try testing.expectEqual(carriage_return, card.latch);}
test "input hands back a line ended by one carriage return, however the host ended it" { // The host writes CR LF; the card drops the CR and turns the LF into the // single carriage return the Monitor's line reader wants. var reader: std.Io.Reader = .fixed("OK\r\n"); var card: Card = .{ .fitted = true, .in = &reader };
try testing.expectEqual(@as(u8, 'O'), card.receive()); try testing.expectEqual(@as(u8, 'K'), card.receive()); try testing.expectEqual(carriage_return, card.receive()); try testing.expectEqual(@as(u64, 3), card.received); // Past the end it hands back a carriage return rather than blocking on a // byte that will never come, and records why. try testing.expectEqual(carriage_return, card.receive()); try testing.expect(card.trouble != null);}
test "a console with nothing attached is switched off" { var card: Card = .{ .fitted = true }; card.send('x'); // The write goes nowhere and is not an error; the latch still holds it. try testing.expectEqual(@as(u64, 1), card.sent); try testing.expectEqual(@as(u8, 'x'), card.latch); try testing.expectEqual(@as(?anyerror, null), card.trouble); // A read with no reader is an empty line, not a wait forever. try testing.expectEqual(carriage_return, card.receive());}
test "the dispatch revectors the output vector and services output" { const rom = firmware(1); // $Cn00 saves the character, then compares CSWH against this card's page. try testing.expectEqual(@as(u8, 0x48), rom[0]); // PHA try testing.expectEqual(@as(u8, 0xa5), rom[1]); // LDA try testing.expectEqual(@as(u8, 0x37), rom[2]); // CSWH try testing.expectEqual(@as(u8, 0xc9), rom[3]); // CMP #page try testing.expectEqual(@as(u8, 0xc1), rom[4]); // slot 1 -> $C1
// The two BNEs to via_ksw both land on the LDA #input_entry there. try testing.expectEqual(@as(u8, 0xd0), rom[5]); try testing.expectEqual(@as(usize, 19), 7 + rom[6]); // 5,6 = BNE; next is 7 try testing.expectEqual(@as(u8, 0xd0), rom[9]); try testing.expectEqual(@as(usize, 19), 11 + rom[10]); // 9,10 = BNE; next is 11 try testing.expectEqual(@as(u8, 0xa9), rom[19]); // via_ksw: LDA #input_entry try testing.expectEqual(input_entry, rom[20]); try testing.expectEqual(@as(u8, 0x38), rom[22]); // STA KSWL
// The output path sets CSWL to the output entry and jumps there. try testing.expectEqual(output_entry, rom[12]); // LDA #output_entry try testing.expectEqual(@as(u8, 0x36), rom[14]); // STA CSWL try testing.expectEqual(@as(u8, 0x4c), rom[16]); // JMP output try testing.expectEqual(output_entry, rom[17]); try testing.expectEqual(@as(u8, 0xc1), rom[18]);}
test "the output routine sends the character and hands it back; the input routine sets the high bit" { const rom = firmware(1); // output at $Cn00 + output_entry, storing to $c090 for slot 1. try testing.expectEqual(@as(u8, 0x48), rom[output_entry]); // PHA try testing.expectEqual(@as(u8, 0x29), rom[output_entry + 1]); // AND try testing.expectEqual(@as(u8, 0x7f), rom[output_entry + 2]); // #$7f try testing.expectEqual(@as(u8, 0x8d), rom[output_entry + 3]); // STA data try testing.expectEqual(@as(u8, 0x90), rom[output_entry + 4]); // $c090 low try testing.expectEqual(@as(u8, 0xc0), rom[output_entry + 5]); // $c090 high try testing.expectEqual(@as(u8, 0x68), rom[output_entry + 6]); // PLA try testing.expectEqual(@as(u8, 0x60), rom[output_entry + 7]); // RTS
// input reads the port and sets the high bit. try testing.expectEqual(@as(u8, 0xad), rom[input_entry]); // LDA data try testing.expectEqual(@as(u8, 0x09), rom[input_entry + 3]); // ORA try testing.expectEqual(@as(u8, 0x80), rom[input_entry + 4]); // #$80 try testing.expectEqual(@as(u8, 0x60), rom[input_entry + 5]); // RTS
// A card in slot 2 stores to and reads from $c0a0, so the firmware is // built for the slot it is in. const other = firmware(2); try testing.expectEqual(@as(u8, 0xa0), other[output_entry + 4]); try testing.expectEqual(@as(u8, 0xa0), other[input_entry + 1]); try testing.expectEqual(@as(u8, 0xc2), other[4]); // and compares against $C2}
test "there is a page of firmware for every slot, and each is that slot's" { inline for (0..firmwares.len) |slot| { try testing.expectEqualSlices(u8, &firmware(slot), &firmwares[slot]); } try testing.expectEqual(@as(u8, 0x90), firmwares[1][output_entry + 4]); try testing.expectEqual(@as(u8, 0xa0), firmwares[2][output_entry + 4]);}