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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The Apple Desktop Bus, as far as the Hardware Reference goes (Apple//! Computer, Inc., 1989).//!//! An Apple IIgs does not read its keyboard. A microcontroller does, over a//! four-wire bus it shares with the mouse and anything else plugged into it,//! and the machine talks to that microcontroller through four registers. This//! is those four registers.//!//! The order of the bits is worth a word, because getting it wrong is easy and//! the firmware is what caught it. The manual's figures label their bits from//! seven down to zero, and this one was read the other way up at first, which//! put every flag in the wrong place and looked perfectly plausible. What//! settled it was the ROM: there is a loop at `$ff8443` which loads a counter//! with 7,500, polls `$c027` for bit 5, and on finding it reads `$c026`. A//! machine waiting for bit 5 and then taking a byte out of the data register//! is a machine for which bit 5 is "there is a byte in the data register", and//! that is the top half of the byte, not the bottom. Every other register here//! was read the right way up; only this one was not.//!//! It is not the microcontroller. The Hardware Reference (Apple Computer, Inc.,//! 1989) sets out the registers exactly — every bit of the status register,//! which are read-only and which are not, and what sets and clears each — and//! then says the commands the host sends "are located in ROM", which is a//! polite way of saying they are in a different book. So what is here is the//! transport and not the conversation: commands are accepted and acknowledged,//! and nothing is invented about what any of them mean. A machine will find its//! keyboard and will not find anything that needs a command answered.//!//! The keyboard itself is deliberately not here either. On this machine the//! microcontroller feeds the same `$c000` an Apple II has always had, and the//! Mega II already owns that latch, so this reports what the Mega II has//! rather than keeping a second copy that could disagree with it.
const std = @import("std");
/// The microcontroller's RAM, in bytes: "96 bytes of RAM" (Parker, n.d.).const ram_size = 96;
/// The lowest address that is ROM on *either* part.////// An M50740 has three kilobytes at `$1400-$1fff` and an M50741 four at/// `$1000-$1fff`: the two "differ only in the amount of internal ROM" (Parker,/// n.d.), and which one is fitted is which machine it is -- an M50740 in a/// ROM 0 or ROM 1 and an M50741 in a ROM 3. Taking the lower of the two is/// what lets one model answer for both without being told which it is: from/// here up, a read is either a ROM this has no copy of or a hole, and saying/// nothing is right either way.const rom_at_most = 0x1000;
/// How many bytes follow a command byte before the command is complete.////// This has to be right or nothing else can be: a command's data bytes go to/// the same register the command did, so a model that does not know how many to/// expect will read the next data byte as a command and lose the thread. The/// counts are from the Firmware Reference (Apple Computer, Inc., 1987a, Chapter/// 9).fn dataBytes(command_byte: u8) u8 { return switch (command_byte) { // Abort, Reset Keyboard Microcontroller, Flush Keyboard Buffer. 0x01, 0x02, 0x03 => 0, // Set Modes and Clear Modes take the mask to set or clear. 0x04, 0x05 => 1, // Set Configuration Bytes takes three. 0x06 => 3, // Sync. The manual's description of this one is garbled in every scan // to hand — it says both that it takes configuration bytes and that it // is a one-byte command — so the count comes from the firmware // instead: the ROM sends `07 00 32 00 24` and then a byte that is // unmistakably the next command, which makes it four. 0x07 => 4, // Write Microcontroller Memory: one byte of address and one of // value. Read Microcontroller Memory: two bytes of address, low // first, because it can reach ROM as well as RAM. 0x08 => 2, 0x09 => 2, // The reading commands, which take nothing and give back. 0x0a...0x0f => 0, // Reset the System. 0x10 => 0, // Send ADB Keycode. 0x11 => 1, // Reset ADB, and the device commands: enable and disable service // requests, flush a device's buffer, poll a device. 0x40, 0x50...0x7f, 0xc0...0xff => 0, // Transmit two bytes to a device. 0x80...0xbf => 2, // Receive Bytes, and Transmit num Bytes, whose length is in the // command itself. 0x48 => 0, 0x49...0x4f => command_byte - 0x48, else => 0, };}
/// The four registers, and what little state sits behind them.pub const Adb = struct { /// Bit 6 of the status register: interrupt when the mouse has moved. mouse_interrupt: bool = false, /// Bit 4: interrupt when there is a reply waiting. data_interrupt: bool = false, /// Bit 2: interrupt when a key has been pressed. keyboard_interrupt: bool = false,
/// What the mouse has to say: two bytes, and how many of them are still /// to be taken. The X coordinate goes first and the Y second. /// /// Which way round that is took the ROM to settle, because the Hardware /// Reference says the opposite in both of the places it mentions it — that /// the first read returns Y, and that bit 1 of the status is set when X is /// what is waiting. Three things say otherwise. The firmware's own reading /// routine at `$fec4d2` wants bit 1 *clear* before the first read and set /// before the second, and keeps the first byte in X and the second in Y. /// The interrupt handler at `$fe9d6f` then adds the second one to the /// screen holes at `$04fc` and `$05fc` — which the same firmware fills /// with the *Y* clamp at `$fe9cd3`, so the second byte is Y and the first /// is X. And the bus agrees: an ADB mouse's register 0 is sixteen bits, /// the button and seven bits of Y in the high half and the second button /// and seven bits of X in the low half, so handing the low half over first /// puts X first and puts the real button in the second byte, which is /// exactly where `$fe9d31` looks for it. The manual has the pair the wrong /// way round in both sentences, consistently. mouse_data: [2]u8 = @splat(0), mouse_left: u8 = 0,
/// Where the mouse has got to since the microcontroller last took a /// reading, and which of its buttons are down. /// /// A mouse counts; the microcontroller asks it what it has counted and /// passes that on, so movement told to this is added up here and turned /// into a reading by `pollMouse`. Keeping the count is what stops a host /// that reports its pointer faster than the bus is polled from losing /// movement in a register that holds one reading, and what stops one that /// reports it in great jumps from overflowing the seven bits a reading /// has: what will not fit stays here for the next one. counts: [2]i32 = @splat(0), /// Nought is the button an Apple mouse has, one the button it does not — /// which the firmware carries anyway, in bits 4 and 0 of its status hole. buttons: [2]bool = @splat(false), reported: [2]bool = @splat(false),
/// The modifier keys at `$c025`: which of shift, control, caps lock, the /// two Apple keys and the keypad are down at this moment. modifiers: u8 = 0,
/// The modes byte, which Set Modes and Clear Modes reach a bit at a time /// and Read Modes Byte hands back. Autorepeat, the keyboard and mouse /// autopolls, and what the Reset key alone does. modes: u8 = 0, /// The three configuration bytes: the mouse and keyboard bus addresses, /// the character set and keyboard layout, and the repeat delay and rate. configuration: [3]u8 = @splat(0), /// The error byte, which Read and Clear Error Byte takes away. Nothing /// sets it, because nothing here has gone wrong. errors: u8 = 0,
/// Which keyboard layouts and character sets this microcontroller offers. /// /// The Control Panel asks, so that it can show only what the machine can /// actually do — the manual explains that the factory might pair a /// microcontroller with a megachip that supports different sets, and this /// is how the two are reconciled. /// /// What is here is a configuration of the machine being modelled rather /// than a fact about the hardware: a US machine, with one layout and one /// character set, both numbered zero. The *format* is documented — a count /// and then that many identifiers, in the order the megachip numbers them /// — and that is what is implemented. Fitting a machine with more is a /// matter of changing these, as fitting it with a different ROM is. layouts: []const u8 = &.{0}, character_sets: []const u8 = &.{0},
/// The microcontroller's own RAM, which the host can read and write a byte /// at a time. /// /// Ninety-six bytes, because that is what the part has: an M50740 holds /// "3K or 4K of ROM, 96 bytes of RAM, three interval timers, four external /// 8-bit I/O ports, and sixteen 4-bit I/O ports" (Parker, n.d.). It used /// to be a flat two hundred and fifty-six here, which made the timers and /// the ports read back whatever had been written to them -- RAM where the /// chip has hardware. See `readAddress` for the rest of the map. /// /// This much is modelled rather than invented, and the distinction /// matters. The microcontroller has RAM; what is in it at power-on is its /// firmware's business and is not documented, so it starts as zeroes. But /// a byte written to it comes back, which is the whole of what the /// machine's self-test wants: it reads location $51, writes $a5 there, and /// would read it back. Refusing to answer at all fails a memory check that /// the hardware would pass. ram: [ram_size]u8 = @splat(0),
/// The command being assembled, and how many of its data bytes are still /// to come. pending: u8 = 0, wanted: u8 = 0, received: [7]u8 = @splat(0), got: u8 = 0,
/// What the microcontroller has to say back, and how far through it the /// host has read. A reply is handed over a byte at a time, and the status /// register says there is one for as long as any of it is left. replies: [8]u8 = @splat(0), reply_length: u8 = 0, reply_at: u8 = 0,
/// How many command bytes have gone by, and which, so that the /// conversation can be read. commands: u32 = 0, trace: [64]u8 = @splat(0),
/// What the status register at `$c027` reads. /// /// `keyboard_full` is the Mega II's business rather than this one's, so it /// is passed in: on this machine the microcontroller feeds the same /// keyboard latch every Apple II has, and there should be one answer to the /// question rather than two. Which bit each of them is (Apple Computer, /// Inc., 1989, Table 6-5), which lists them from the top: the Command /// key, the Option key, whether the latch was updated without a key being /// pressed, the keypad, and whether a key is being held down — and then the /// three an Apple II always had. /// /// The two Apple keys are the interesting ones, because they are two /// things at once. A IIgs keyboard's Command and Option keys are these /// modifier bits *and* the game connector's first two buttons at `$c061` /// and `$c062`, which is how software written for an Apple II finds them. /// Anything holding one down has to say so in both places. pub const Modifier = struct { pub const command: u8 = 0x80; pub const option: u8 = 0x40; pub const updated: u8 = 0x20; pub const keypad: u8 = 0x10; pub const held: u8 = 0x08; pub const caps_lock: u8 = 0x04; pub const control: u8 = 0x02; pub const shift: u8 = 0x01; };
/// What Get Version Number answers with. /// /// A number, and not a very meaningful one, because this is not any /// particular microcontroller and the part number would be invented. What /// is *not* invented is that there is an answer at all. This command was /// left unanswered for a while on the reasoning that saying nothing was /// more honest than making a number up — and that was the same mistake the /// IWM's handshake register had already taught: a chip that is there /// always answers, and refusing to models a broken part rather than an /// unknown one. /// /// A ROM 01 never asks. A ROM 3 asks, waits, and on getting nothing puts /// "Fatal system error-> 0911" on the screen and stops — $09 being the /// desktop bus tool set. With an answer it boots. Any answer: nought, one, /// six and $ff were all tried and the machine cannot tell them apart, so /// what this holds is a choice and only the answering matters. pub const version: u8 = 0x06;
/// Holds a modifier down or lets it go. pub fn hold(self: *Adb, which: u8, down: bool) void { if (down) self.modifiers |= which else self.modifiers &= ~which; }
pub fn status(self: *const Adb, keyboard_full: bool) u8 { var value: u8 = 0; if (self.mouse_left != 0) value |= 0x80; if (self.mouse_interrupt) value |= 0x40; if (self.reply_at < self.reply_length) value |= 0x20; if (self.data_interrupt) value |= 0x10; if (keyboard_full) value |= 0x08; if (self.keyboard_interrupt) value |= 0x04; if (self.mouse_left == 1) value |= 0x02; // Bit 0 is set while a command is waiting to be taken and cleared when // the microcontroller takes it. This one takes it as it is written, so // by the time anything can read the bit it is already clear. return value; }
/// The three bits of the status register the host is allowed to write, /// which are the interrupt enables. The rest are read-only and a write to /// them does nothing: firmware writing a whole byte here must not be able /// to fake a key press. pub fn setStatus(self: *Adb, value: u8) void { self.mouse_interrupt = value & 0x40 != 0; self.data_interrupt = value & 0x10 != 0; self.keyboard_interrupt = value & 0x04 != 0; }
/// A byte written to the command register, which is either a command or /// one of the data bytes belonging to the last one. pub fn command(self: *Adb, value: u8) void { self.trace[self.commands % self.trace.len] = value; self.commands +|= 1;
if (self.wanted != 0) { if (self.got < self.received.len) self.received[self.got] = value; self.got += 1; self.wanted -= 1; if (self.wanted == 0) self.run(); return; }
self.pending = value; self.got = 0; self.wanted = dataBytes(value); if (self.wanted == 0) self.run(); }
/// Carries out a command once all of it has arrived. /// /// Only the ones whose answer this model actually holds are answered. /// Reading back the modes byte or the configuration bytes is exact, /// because setting them is what put them there. Reading the /// microcontroller's own memory, its version number, or the character sets /// and keyboard layouts it has, is not: those are the microcontroller's /// own business and nothing here knows them, so nothing is said and the /// host's wait runs out — which is what it is written to cope with. fn run(self: *Adb) void { self.reply_length = 0; self.reply_at = 0; switch (self.pending) { // Abort: give up on whatever was being assembled. 0x01 => self.wanted = 0, // Reset the keyboard microcontroller, and Sync, which resets it // and everything on the bus and sets the configuration. 0x02 => self.resetController(), 0x07 => { self.resetController(); @memcpy(self.configuration[0..3], self.received[0..3]); }, 0x04 => self.modes |= self.received[0], 0x05 => self.modes &= ~self.received[0], 0x06 => @memcpy(self.configuration[0..3], self.received[0..3]), // Write Microcontroller Memory: one byte of address and one of // value, so it reaches page zero and nothing else. Only the RAM // takes it -- a write to a port or a timer does something to the // chip rather than being stored, and storing it would be modelling // RAM where there is hardware. 0x08 => if (self.received[0] < ram_size) { self.ram[self.received[0]] = self.received[1]; }, // Read Microcontroller Memory: the low byte of the address, then // the high byte. 0x09 => { const address = @as(u16, self.received[1]) << 8 | self.received[0]; if (self.readAddress(address)) |byte| self.reply(&.{byte}); }, 0x0a => self.reply(&.{self.modes}), 0x0b => self.reply(&self.configuration), 0x0c => { self.reply(&.{self.errors}); self.errors = 0; }, 0x0d => self.reply(&.{version}), 0x0e => self.replyList(self.character_sets), 0x0f => self.replyList(self.layouts), else => {}, } }
/// What the microcontroller reads at one of its own addresses, or null /// where nothing here can say. /// /// The map is the part's, and it is worth setting out because the command /// that reaches it is documented in terms of it: "the command reads ROM or /// RAM locations, depending on the value of the high byte of the address /// sent for reading... if the third byte is 0, RAM is read; otherwise, ROM /// is read" (Apple Computer, Inc., 1987a, p. 191). That sentence is not a /// rule the firmware applies so much as a description of where things are: /// page zero is RAM and registers, and the only thing above it is ROM. /// /// ```text /// $0000-$005f RAM, ninety-six bytes /// $0060-$00cf not implemented /// $00d0-$00df the sixteen 4-bit I/O ports /// $00e0-$00e9 ports P0 to P3 and their data direction registers /// $00ea-$00f8 not implemented /// $00f9-$00ff the three timers, their prescalers, and the interrupt /// and timer control registers /// $0100-$0fff not implemented /// $1000-$13ff ROM on an M50741 (a ROM 3 machine), nothing on an M50740 /// $1400-$1fff ROM on both /// ``` /// /// (Parker, n.d.) The author of that page is careful to say the /// information "is taken from the Mitsubishi data book and the Apple IIGS /// Hardware Reference, and from my own disassemblies of the /// microcontroller ROM code" and that he cannot guarantee it is correct, /// which is worth repeating rather than quietly promoting to fact. /// /// **The ROM is not here**, and that is the one thing this cannot answer. /// It is three or four kilobytes of 740 code -- the microcontroller is a /// 6502 relative, so it could in principle be run rather than described -- /// and nothing in this project has a copy. Nothing asks for it either: a /// IIgs boot issues exactly two of these commands and both read RAM $51. /// Running the part for real is a project of its own; see the README. /// /// Everywhere that is neither RAM nor ROM answers a byte rather than /// staying silent, because the chip does: the command "returns 1 byte" /// whatever it was pointed at, and a part that answered nothing would be a /// broken part rather than an undocumented one -- the same reasoning as /// `version` above. What that byte *is* for a timer or a port is the /// chip's own business and is not modelled, so nought is a placeholder and /// is not to be trusted. fn readAddress(self: *const Adb, address: u16) ?u8 { if (address < ram_size) return self.ram[address]; if (address < 0x0100) return 0; // ports, timers, and the gaps between if (address < rom_at_most) return 0; // not implemented on either part return null; // ROM, which nothing here has }
fn resetController(self: *Adb) void { self.modes = 0; self.errors = 0; self.reply_length = 0; self.reply_at = 0; // Its RAM is not cleared: a reset command resets the part, and a part // coming out of reset finds its RAM as it left it. }
/// A count and then the things counted, which is the shape both of the /// asking-what-you-have commands use. fn replyList(self: *Adb, list: []const u8) void { if (list.len + 1 > self.replies.len) return; self.replies[0] = @intCast(list.len); @memcpy(self.replies[1 .. list.len + 1], list); self.reply_length = @intCast(list.len + 1); self.reply_at = 0; }
fn reply(self: *Adb, bytes: []const u8) void { @memcpy(self.replies[0..bytes.len], bytes); self.reply_length = @intCast(bytes.len); self.reply_at = 0; }
/// Reads the next byte of whatever the microcontroller had to say. pub fn response(self: *Adb) u8 { if (self.reply_at >= self.reply_length) return 0; const value = self.replies[self.reply_at]; self.reply_at += 1; return value; }
/// Reads the mouse register, which hands over one coordinate and then the /// other. /// /// The Hardware Reference (Apple Computer, Inc., 1989a) warns that reading /// it an odd number of times leaves the cursor moving at random, and this /// is why: there is no way back to the start of a reading, so a coordinate /// left behind is taken as the other one next time. pub fn mouseByte(self: *Adb) u8 { if (self.mouse_left == 0) return 0; const index = self.mouse_data.len - self.mouse_left; self.mouse_left -= 1; return self.mouse_data[index]; }
/// Moves the mouse, in whatever the host counts pointer movement in. pub fn moveMouse(self: *Adb, dx: i32, dy: i32) void { self.counts[0] +|= dx; self.counts[1] +|= dy; }
/// Presses a mouse button or lets it go. pub fn holdButton(self: *Adb, which: u1, down: bool) void { self.buttons[which] = down; }
/// What the microcontroller does over and over: asks the mouse what it has /// counted since last time, and puts it in the register. /// /// Nothing is said when nothing has happened, which is what leaves the /// register empty and the interrupt line alone while the mouse is still. /// A reading the host has not finished taking is not replaced either: the /// count stays with the mouse, which is where it would stay on a bus whose /// poll found the host still busy. pub fn pollMouse(self: *Adb) void { if (self.mouse_left != 0) return; const still = self.buttons[0] == self.reported[0] and self.buttons[1] == self.reported[1]; if (still and self.counts[0] == 0 and self.counts[1] == 0) return; const dx = take(&self.counts[0]); const dy = take(&self.counts[1]); self.reported = self.buttons; self.mouse_data = .{ reading(dx, self.buttons[1]), reading(dy, self.buttons[0]) }; self.mouse_left = 2; }
/// Whether the microcontroller is pulling the interrupt line. /// /// Three things can, and each of them is a pair: something waiting, and /// the enable that allows it to be spoken of. The keyboard's half of the /// pair is the Mega II's latch rather than anything kept here, for the /// same reason the status register takes it as an argument. /// /// This is what the firmware's handler reads. At `$feb97a` it shifts the /// status left and wants the enable in the sign and the full bit in the /// carry before it will call the mouse's vector, and at `$feb9a0` it does /// the same two bits further down for the reply register. pub fn interrupting(self: *const Adb, keyboard_full: bool) bool { if (self.mouse_interrupt and self.mouse_left != 0) return true; if (self.data_interrupt and self.reply_at < self.reply_length) return true; if (self.keyboard_interrupt and keyboard_full) return true; return false; }
/// Puts the machine back where it starts. pub fn reset(self: *Adb) void { self.* = .{}; }};
/// Takes as much of a count as a reading will carry and leaves the rest/// behind. Seven bits reach from -64 to 63, so a host that moves the pointer/// further than that in one poll is followed rather than jumped after.fn take(count: *i32) i8 { const room: i32 = std.math.clamp(count.*, -64, 63); count.* -= room; return @intCast(room);}
/// One byte of a reading: the button in the top bit and seven bits of two's/// complement movement under it. The bit is set when the button is *up*,/// which is the bus's way round rather than this one's.fn reading(delta: i8, down: bool) u8 { const bits: u8 = @as(u8, @bitCast(delta)) & 0x7f; return if (down) bits else bits | 0x80;}
const testing = std.testing;
test "the status register reports what is waiting" { var adb: Adb = .{}; try testing.expectEqual(@as(u8, 0x00), adb.status(false));
// The keyboard is the Mega II's to answer for, so it is passed in. try testing.expectEqual(@as(u8, 0x08), adb.status(true));
adb.moveMouse(1, 1); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x80), adb.status(false)); _ = adb.mouseByte(); // One coordinate taken, so the register is still full and the byte // waiting is the other one. try testing.expectEqual(@as(u8, 0x82), adb.status(false)); _ = adb.mouseByte(); try testing.expectEqual(@as(u8, 0x00), adb.status(false));}
test "only the interrupt enables can be written" { // A whole byte written here must not be able to fake a key press or a // mouse movement: those bits are the hardware's to set. var adb: Adb = .{}; adb.setStatus(0xff); try testing.expect(adb.mouse_interrupt); try testing.expect(adb.data_interrupt); try testing.expect(adb.keyboard_interrupt); try testing.expectEqual(@as(u8, 0x54), adb.status(false)); try testing.expectEqual(@as(u8, 0), adb.mouse_left);}
test "a command's data bytes are not mistaken for commands" { // The whole reason the lengths matter: data goes to the same register the // command did, so a model that does not know how many bytes to expect // reads the next one as a command and loses the thread for good. var adb: Adb = .{}; adb.command(0x06); // Set Configuration Bytes, three to follow adb.command(0x04); // and these are data, not Set Modes adb.command(0x05); // nor Clear Modes adb.command(0x0a); // nor Read Modes Byte try testing.expectEqualSlices(u8, &.{ 0x04, 0x05, 0x0a }, &adb.configuration); try testing.expectEqual(@as(u8, 0), adb.modes); // And nothing was answered along the way. try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);}
test "the modes byte is set, cleared and read back" { // An answer this model actually holds, because setting it is what put it // there. var adb: Adb = .{}; adb.command(0x04); // Set Modes adb.command(0x81); // reset-from-keyboard, and the keyboard autopoll off adb.command(0x05); // Clear Modes adb.command(0x01);
adb.command(0x0a); // Read Modes Byte try testing.expectEqual(@as(u8, 0x20), adb.status(false) & 0x20); try testing.expectEqual(@as(u8, 0x80), adb.response()); // One byte, and then nothing more. try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);}
test "the configuration comes back in three bytes, one at a time" { var adb: Adb = .{}; adb.command(0x06); adb.command(0x31); adb.command(0x08); adb.command(0x25);
adb.command(0x0b); // Read Configuration Bytes for ([_]u8{ 0x31, 0x08, 0x25 }) |want| { try testing.expectEqual(@as(u8, 0x20), adb.status(false) & 0x20); try testing.expectEqual(want, adb.response()); } try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);}
test "the microcontroller's RAM keeps what is written to it" { // The machine's self-test reads a location, writes a pattern and reads it // back. Refusing to answer fails a check the hardware would pass, so the // RAM is modelled — with zeroes in it, because what a real one holds at // power-on is its firmware's business and is not written down anywhere. var adb: Adb = .{};
adb.command(0x09); // Read Microcontroller Memory adb.command(0x51); // address low adb.command(0x00); // high byte zero, so RAM try testing.expectEqual(@as(u8, 0x20), adb.status(false) & 0x20); try testing.expectEqual(@as(u8, 0x00), adb.response());
adb.command(0x08); // Write Microcontroller Memory adb.command(0x51); adb.command(0xa5);
adb.command(0x09); adb.command(0x51); adb.command(0x00); try testing.expectEqual(@as(u8, 0xa5), adb.response());}
test "the microcontroller has ninety-six bytes of RAM and hardware above them" { // "96 bytes of RAM" (Parker, n.d.), at $0000-$005f, and above that the // ports and timers -- which are registers rather than memory, so a byte // written to one must not come back the way a byte written to RAM does. var adb: Adb = .{};
// The top of RAM keeps what is put in it. adb.command(0x08); adb.command(0x5f); adb.command(0x5a); try testing.expectEqual(@as(u8, 0x5a), adb.ram[0x5f]);
// One past it is not implemented on the part at all, so the write goes // nowhere and the read does not give it back. adb.command(0x08); adb.command(0x60); adb.command(0x5a); adb.command(0x09); adb.command(0x60); adb.command(0x00); try testing.expectEqual(@as(u8, 0x00), adb.response());
// And the Timer Control Register at $ff is hardware. Writing it used to // stick, because this modelled a flat two hundred and fifty-six bytes of // RAM where the chip has ninety-six and then registers. adb.command(0x08); adb.command(0xff); adb.command(0xa5); adb.command(0x09); adb.command(0xff); adb.command(0x00); try testing.expectEqual(@as(u8, 0x00), adb.response());}
test "every address answers a byte except the ROM" { // "This command returns 1 byte" (Apple Computer, Inc., 1987a, p. 191), so // a part that is there answers wherever it is pointed -- the same // reasoning as the version number. The exception is its own program, // which nothing here has a copy of. var adb: Adb = .{}; const cases = [_]struct { at: u16, answers: bool }{ .{ .at = 0x0000, .answers = true }, // RAM .{ .at = 0x005f, .answers = true }, // the last byte of it .{ .at = 0x0060, .answers = true }, // not implemented .{ .at = 0x00d0, .answers = true }, // the 4-bit ports .{ .at = 0x00e0, .answers = true }, // port P0 .{ .at = 0x00ff, .answers = true }, // the timer control register .{ .at = 0x0100, .answers = true }, // not implemented .{ .at = 0x0fff, .answers = true }, .{ .at = 0x1000, .answers = false }, // ROM on an M50741 .{ .at = 0x1400, .answers = false }, // ROM on both .{ .at = 0x1fff, .answers = false }, // the last byte of it }; for (cases) |case| { adb.command(0x09); adb.command(@truncate(case.at)); adb.command(@truncate(case.at >> 8)); const said = adb.status(false) & 0x20 != 0; try testing.expectEqual(case.answers, said); if (said) _ = adb.response(); }}
test "reading the microcontroller's ROM is not answered" { // A non-zero high byte asks for ROM, and the microcontroller's ROM is its // program: nothing here has a copy of it, so nothing is said. var adb: Adb = .{}; adb.command(0x09); adb.command(0x00); adb.command(0x14); // $1400, which is ROM on either part try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);
// $1000 is ROM on an M50741 and nothing at all on an M50740, and this // model is not told which machine it is in, so it says nothing there too: // a fabricated byte would be wrong on a ROM 3 and a guess on the others. adb.command(0x09); adb.command(0x00); adb.command(0x10); try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);}
test "a command whose answer this does not hold is still answered" { // Get Version Number asks which microcontroller this is, and this is not // any particular one — but a part that is there answers, and this command // was left silent for a while on the reasoning that saying nothing was // more honest than making a number up. A ROM 3 asks, waits, and dies with // "Fatal system error-> 0911" on getting nothing. var adb: Adb = .{}; adb.command(0x0d); try testing.expectEqual(@as(u8, 0x20), adb.status(false) & 0x20); try testing.expectEqual(Adb.version, adb.response()); try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);}
test "a command with no answer at all leaves the register empty" { // There are still such commands: the ones that do something rather than // say something. Setting the modes is not a question. var adb: Adb = .{}; adb.command(0x04); adb.command(0x80); try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);}
test "the conversation the firmware actually has" { // Byte for byte what the ROM sends, which is how the lengths above were // settled: every command lands on a command byte and none of the data is // read as one. var adb: Adb = .{}; for ([_]u8{ 0x07, 0x00, 0x32, 0x00, 0x24, 0x73, 0x09, 0x51, 0x00, 0x08, 0x51, 0xa5, 0x01, 0x0f }) |byte| adb.command(byte);
// Sync left its configuration behind. try testing.expectEqualSlices(u8, &.{ 0x00, 0x32, 0x00 }, &adb.configuration); // The write landed where the read had looked. try testing.expectEqual(@as(u8, 0xa5), adb.ram[0x51]); // And the last byte was taken as a command with nothing following it, // rather than as data for something earlier. try testing.expectEqual(@as(u8, 0x0f), adb.pending); try testing.expectEqual(@as(u8, 0), adb.wanted);}
test "asking what the machine has gets a count and then the list" { // The format is the manual's: how many follow, and then that many. What // the machine has is a configuration of this model rather than a fact // about the hardware, and a US machine has one of each. var adb: Adb = .{};
adb.command(0x0f); // Read Available Keyboard Layouts try testing.expectEqual(@as(u8, 0x01), adb.response()); // one of them try testing.expectEqual(@as(u8, 0x00), adb.response()); // and it is US try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x20);
adb.command(0x0e); // Read Available Character Sets try testing.expectEqual(@as(u8, 0x01), adb.response()); try testing.expectEqual(@as(u8, 0x00), adb.response());
// A machine fitted with more says so, without anything else changing. adb.layouts = &.{ 0, 1, 3 }; adb.command(0x0f); try testing.expectEqual(@as(u8, 0x03), adb.response()); for ([_]u8{ 0, 1, 3 }) |want| try testing.expectEqual(want, adb.response());}
test "a reading is the two coordinates, X first and then Y" { // The order is the firmware's, not the manual's: `$fec4d2` wants bit 1 of // the status clear before the first read and set before the second, and // the handler puts the second byte where the Y clamp goes. var adb: Adb = .{}; adb.moveMouse(5, -3); adb.pollMouse();
// Bit 7 says there is a reading, bit 1 that what is waiting is not yet // the second coordinate. try testing.expectEqual(@as(u8, 0x80), adb.status(false) & 0x82); // Five to the right, and the button bit set because it is not down. try testing.expectEqual(@as(u8, 0x85), adb.mouseByte()); try testing.expectEqual(@as(u8, 0x82), adb.status(false) & 0x82); // Three up, in seven bits of two's complement: $7d, and the button again. try testing.expectEqual(@as(u8, 0xfd), adb.mouseByte()); try testing.expectEqual(@as(u8, 0x00), adb.status(false) & 0x82);}
test "the button is reported by its bit being clear" { // Which is the bus's way round and not this one's, and it is the second // byte that carries the button the firmware treats as the real one. var adb: Adb = .{}; adb.holdButton(0, true); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x80), adb.mouseByte()); // no X movement try testing.expectEqual(@as(u8, 0x00), adb.mouseByte()); // and button down
// Letting go is a reading too, or nothing would ever say so. adb.holdButton(0, false); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x80), adb.mouseByte()); try testing.expectEqual(@as(u8, 0x80), adb.mouseByte());
// The second button lives in the first byte instead. adb.holdButton(1, true); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x00), adb.mouseByte()); try testing.expectEqual(@as(u8, 0x80), adb.mouseByte());}
test "a still mouse says nothing at all" { // Which is what leaves the register empty and the interrupt line alone. var adb: Adb = .{}; adb.pollMouse(); try testing.expectEqual(@as(u8, 0), adb.mouse_left); adb.moveMouse(0, 0); adb.pollMouse(); try testing.expectEqual(@as(u8, 0), adb.mouse_left);}
test "movement too far for one reading is followed rather than jumped after" { // Seven bits reach to 63, so a hundred takes two readings and nothing is // lost along the way. var adb: Adb = .{}; adb.moveMouse(100, -100); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x80 | 63), adb.mouseByte()); try testing.expectEqual(@as(u8, 0x80 | 0x40), adb.mouseByte()); // -64
adb.pollMouse(); try testing.expectEqual(@as(u8, 0x80 | 37), adb.mouseByte()); // The thirty-six still owed, in seven bits: $5c, and the button bit. try testing.expectEqual(@as(u8, 0xdc), adb.mouseByte());
// And then there is nothing more to say. adb.pollMouse(); try testing.expectEqual(@as(u8, 0), adb.mouse_left);}
test "a reading the host is halfway through is not replaced" { // The count stays with the mouse instead, which is where it would stay on // a bus whose poll found the host still busy — and replacing it would // hand over the new Y where the old one was expected. var adb: Adb = .{}; adb.moveMouse(10, 0); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x8a), adb.mouseByte());
adb.moveMouse(10, 0); adb.pollMouse(); try testing.expectEqual(@as(u8, 0x80), adb.mouseByte()); // the old Y
// Now the register is free and the second ten is still owed. adb.pollMouse(); try testing.expectEqual(@as(u8, 0x8a), adb.mouseByte());}
test "the interrupt line follows what is waiting and what is enabled" { // Both halves of the pair, which is what `$feb97a` reads: the enable in // the sign and the full bit in the carry. var adb: Adb = .{}; adb.moveMouse(1, 0); adb.pollMouse(); try testing.expect(!adb.interrupting(false));
adb.setStatus(0x40); try testing.expect(adb.interrupting(false)); _ = adb.mouseByte(); try testing.expect(adb.interrupting(false)); _ = adb.mouseByte(); try testing.expect(!adb.interrupting(false));
// The reply register is the same shape, one bit further down. adb.setStatus(0x10); adb.command(0x0a); // Read Modes Byte try testing.expect(adb.interrupting(false)); _ = adb.response(); try testing.expect(!adb.interrupting(false));
// And the keyboard's half of the pair is the Mega II's, not this one's. adb.setStatus(0x04); try testing.expect(!adb.interrupting(false)); try testing.expect(adb.interrupting(true));}