diff --git a/README.md b/README.md index d65960d..b24cd4c 100644 --- a/README.md +++ b/README.md @@ -639,7 +639,9 @@ machine around it is not. polled at `$c019`. A real IIe can only poll it: making it an interrupt is an Apple IIc feature that reaches a IIe through a mouse card, so it is off by default and switched at `$c05a`/`$c05b` where the IIc puts it. -- **Interrupts.** The processor has both lines. An IRQ is level triggered +- **Interrupts.** The processor has both lines. The mouse card and the serial + card both pull the IRQ, and so does vertical blanking, and they share it + properly: one letting go does not quieten another. An IRQ is level triggered and masked by the interrupt disable flag; an NMI is neither. Both are answered between instructions in seven cycles, pushing the flags with the break bit clear so a handler can tell them from a BRK. The IIe drives the @@ -648,6 +650,20 @@ machine around it is not. it needs nothing but an image file: status, read and write, and a boot block that `PR#7` runs. Thirty-two megabytes is the most any one volume can be, since the block number ProDOS passes is sixteen bits. +- **A mouse.** An AppleMouse II card in slot 4, given its own firmware: the + five bytes a program looks for to find one, and the table of eight routines + it calls through. The position and the buttons come back where the card + leaves them, in the screen holes, which are the bytes of the text page that + no character is displayed from. It is the only card here that pulls the + interrupt line of its own accord, and it does it for whatever it has been + told to: when the mouse moves, when a button goes down, or once a frame at + vertical blanking. `--mouse` fits it and lets the terminal's pointer drive + it: where the pointer is over the machine's screen is where the mouse is, + scaled to whatever the program has clamped it to. That is not what moving a + real mouse feels like, since a terminal says where the pointer is rather + than how far it moved, but it is what a terminal can say. Unlike the disk + and filing system work, this one is checked against the published interface + and the firmware running rather than against real mouse software. - **A clock card.** The machine has no clock of its own, so ProDOS stamps every file it writes with no date at all. `--clock` fits one in slot 5, given its own firmware: ProDOS finds the four bytes it looks for in the @@ -693,8 +709,7 @@ machine around it is not. and both text pages. The switches that move the processor's window about are kept apart from the ones that decide what is displayed, so a program reading auxiliary memory does not change what is on screen. -- **Not implemented.** Nothing but vertical blanking and the serial card - raises an interrupt. Slots 2, 5, 6 and 7 are the only ones that can be +- **Not implemented.** Slots 2, 4, 5, 6 and 7 are the only ones that can be filled; every other address in `$c100-$cfff` answers from the internal ROM whatever INTCXROM says. No video beyond the text screen: no low or high resolution graphics, and no mixed mode, so a @@ -726,6 +741,7 @@ machine around it is not. | `src/serial.zig` | the 6551 in a Super Serial Card | | `src/blockdevice.zig` | a ProDOS block device, and the firmware it answers with | | `src/clockcard.zig` | a clock card, and the firmware ProDOS asks the time through | +| `src/mouse.zig` | an AppleMouse II card, and the firmware a program calls it through | | `examples/typing.zig` | driving a machine from another program | | `src/main.zig` | the debugger | | `corpus/` | the SingleStepTests corpus runner, its own project | diff --git a/completions/zig65.bash b/completions/zig65.bash index cfcc554..ff4562e 100644 --- a/completions/zig65.bash +++ b/completions/zig65.bash @@ -69,7 +69,7 @@ _zig65() { # line is not offered again. The word under the cursor does not count as # already given: finishing off a flag that is spelled out in full would # otherwise offer nothing at all. - local flags='--rom --disk-rom --drives --disk1 --disk2 --hard-disk --audio --cassette-in --cassette-out --serial-rom --serial-in --serial-out --clock --clock-offset --writable --help' + local flags='--rom --disk-rom --drives --disk1 --disk2 --hard-disk --audio --cassette-in --cassette-out --serial-rom --serial-in --serial-out --mouse --clock --clock-offset --writable --help' local offered=() flag index seen for flag in $flags; do seen= diff --git a/completions/zig65.fish b/completions/zig65.fish index 55c4fb1..f2a4777 100644 --- a/completions/zig65.fish +++ b/completions/zig65.fish @@ -61,6 +61,10 @@ complete -c zig65 -l cassette-in -r \ complete -c zig65 -l cassette-out -r \ -n 'not __fish_seen_argument -l cassette-out' \ -d 'Write what the cassette output puts out to a WAV' +complete -c zig65 -l mouse \ + -n 'not __fish_seen_argument -l mouse' \ + -d 'fit a mouse card and drive it from the terminal' + complete -c zig65 -l clock \ -n 'not __fish_seen_argument -l clock' \ -d 'fit a clock card so ProDOS can date the files it writes' diff --git a/src/main.zig b/src/main.zig index 94d7507..c3e8733 100644 --- a/src/main.zig +++ b/src/main.zig @@ -69,6 +69,12 @@ const usage = \\ --hard-disk PATH put PATH in the block device in slot 7, as a ProDOS \\ volume. PR#7 starts it. The card's firmware is built \\ in, so there is no ROM to supply. + \\ --mouse fit an AppleMouse II card in slot 4 and let the + \\ terminal's mouse drive it. Where the pointer is over + \\ the machine's screen is where the mouse is, scaled to + \\ whatever the program running has clamped it to; the + \\ left and right buttons are its two. The card's + \\ firmware is built in, so there is no ROM to supply. \\ --clock fit a clock card in slot 5 and set it from the host's \\ clock, so that ProDOS puts a date on the files it \\ writes. Without one the machine does not know when it @@ -113,6 +119,8 @@ const Options = struct { cassette_out: ?[]const u8 = null, /// A ProDOS volume to put in the block device in slot 7. hard_disk: ?[]const u8 = null, + /// Whether to fit a mouse card, and let the terminal's mouse drive it. + mouse: bool = false, /// Whether to fit a clock card, and how far the machine's clock is from /// the host's, which is read as UTC. clock: bool = false, @@ -170,6 +178,8 @@ fn parseArgs(args: std.process.Args) ?Options { options.serial_in = wants.path(&it, "--serial-in"); } else if (std.mem.eql(u8, arg, "--serial-out")) { options.serial_out = wants.path(&it, "--serial-out"); + } else if (std.mem.eql(u8, arg, "--mouse")) { + options.mouse = true; } else if (std.mem.eql(u8, arg, "--clock")) { options.clock = true; } else if (std.mem.eql(u8, arg, "--clock-offset")) { @@ -789,6 +799,14 @@ const App = struct { // The block device, which needs nothing but something to put in it: // its firmware is ours and is built into the machine. + if (options.mouse) { + if (comptime !hasMouse()) { + std.debug.print("zig65: this machine has no slots to put a mouse card in\n", .{}); + std.process.exit(1); + } + self.cpu.memory.mouse_card.fitted = true; + } + // The clock, which the machine has none of on its own. It is set from // the host once and then keeps time by the machine's own cycles, so a // machine run faster than a real one sees the hours go by faster. @@ -895,6 +913,56 @@ const App = struct { return self.cpu.memory.peek(line_base + column); } + /// Whether this machine has somewhere to put a mouse. + fn hasMouse() bool { + return @hasField(CPU.Memory, "mouse_card"); + } + + /// Where the terminal's pointer is, in the units the program running has + /// clamped the mouse to. + /// + /// The machine's screen is the mousing surface: the pointer's cell within + /// it is scaled to the clamps, so a program that has asked for nought to + /// 1023 gets the whole range out of forty columns, and one that has asked + /// for a window of its own gets that. It is not what moving a real mouse + /// feels like, since a terminal says where the pointer is rather than how + /// far it has moved, but it is what a terminal can say. + fn mouseMoved(self: *App, event: vaxis.Mouse) void { + if (comptime !hasMouse()) return; + const card = &self.cpu.memory.mouse_card; + if (!card.fitted) return; + + const columns = self.machineColumns(); + const beside = self.vx.window().width >= 76 + columns + 2; + // The screen sits inside a border, so its first character is one cell + // in and one cell down from where the pane begins. + const left: i16 = @intCast((if (beside) @as(u16, 76) else 0) + 1); + const column = event.col - left; + const row = event.row - 1; + if (column < 0 or row < 0) return; + if (column >= columns or row >= video.rows) return; + + const across: i32 = @as(i32, card.high_x) - card.low_x; + const down: i32 = @as(i32, card.high_y) - card.low_y; + card.moveTo( + @intCast(card.low_x + @divTrunc(across * column, @as(i32, columns) - 1)), + @intCast(card.low_y + @divTrunc(down * row, @as(i32, video.rows) - 1)), + ); + switch (event.type) { + .press, .drag => switch (event.button) { + .left => card.setButton(0, true), + .right => card.setButton(1, true), + else => {}, + }, + .release => switch (event.button) { + .left => card.setButton(0, false), + .right => card.setButton(1, false), + else => {}, + }, + .motion => {}, + } + } + /// Whether this machine has somewhere to put a block device. fn hasBlockDevice() bool { return @hasDecl(CPU.Memory, "insertVolume"); @@ -1415,7 +1483,10 @@ const App = struct { } } }, - .mouse => |mouse| self.mouse = mouse, + .mouse => |pointer| { + self.mouse = pointer; + self.mouseMoved(pointer); + }, .winsize => |ws| try self.vx.resize(self.alloc, self.writer, ws), else => {}, } @@ -2333,7 +2404,7 @@ test "the shell completions know the same flags the usage describes" { const fish = @embedFile("zig65.fish"); const bash = @embedFile("zig65.bash"); - var storage: [16][]const u8 = undefined; + var storage: [24][]const u8 = undefined; const flags = longFlags(usage, &storage); // Enough of them to be sure the usage text was read at all. try std.testing.expect(flags.len >= 6); @@ -2364,7 +2435,7 @@ test "the shell completions know the same flags the usage describes" { // And the other way round, so that a flag that goes away is not left // being offered. Fish is read through its own spelling. - var bash_storage: [16][]const u8 = undefined; + var bash_storage: [24][]const u8 = undefined; for (longFlags(offered, &bash_storage)) |flag| { for (flags) |known| { if (std.mem.eql(u8, known, flag)) break; diff --git a/src/memory/apple2e.zig b/src/memory/apple2e.zig index 4cecf41..58a2a31 100644 --- a/src/memory/apple2e.zig +++ b/src/memory/apple2e.zig @@ -13,6 +13,7 @@ const cassette = @import("../cassette.zig"); const serial = @import("../serial.zig"); const blockdevice = @import("../blockdevice.zig"); const clockcard = @import("../clockcard.zig"); +const mouse = @import("../mouse.zig"); /// Video timing. The IIe draws a scan line every 65 cycles and a frame every /// 262 lines, which is where the machine's 1.0205MHz clock and its 59.94Hz @@ -66,6 +67,14 @@ const serial_rom_page = 0x700; const serial_rom_base = 0xc000 + serial_slot * 0x100; const serial_switch_base = 0x80 + serial_slot * 0x10; +/// Where the mouse lives: slot 4, which is where the card went and where the +/// software that uses one looks for it. +const mouse_slot = 4; +const mouse_rom_base = 0xc000 + mouse_slot * 0x100; +const mouse_switch_base = 0x80 + mouse_slot * 0x10; +/// Ours again: what a mouse card answers to is published. +const mouse_firmware = mouse.firmware(mouse_slot); + /// Where the clock lives. Any slot will do — ProDOS looks through all of /// them — so it takes slot 5, which is the free one: 2 is the serial card, 4 /// is where a mouse goes, 6 is the disk and 7 the hard disk. @@ -170,6 +179,10 @@ pub fn AppleIIe(comptime options: Options) fn (type) type { /// firmware does that on its way in and out. expansion: ?u4 = null, + /// The mouse card in slot 4. It is the only card here that + /// pulls the interrupt line of its own accord. + mouse_card: mouse.Card = .{}, + /// The clock card in slot 5, which is what lets ProDOS put a /// date on a file. A machine with none does not know when it /// is, which is the ordinary case and the default here. @@ -442,7 +455,59 @@ pub fn AppleIIe(comptime options: Options) fn (type) type { const from_video = self.vbl_interrupt_enabled and self.vbl_interrupt; const from_card = self.serial_card and self.serial_interrupts and self.acia.interrupting(self.getCPU().clock.cycles); - self.getCPU().irq = from_video or from_card; + self.getCPU().irq = from_video or from_card or self.mouse_card.interrupting(); + } + + /// What the mouse card's firmware asks for. The position and + /// the buttons go in and out through the screen holes, which + /// are the bytes of the text page no character is displayed + /// from: one set for each slot, and slot nought's are where a + /// caller leaves the clamps. + fn runMouseCommand(self: *Self, command: mouse.Command, is_write: bool, value: u8) u8 { + const card = &self.mouse_card; + const mine: u16 = mouse_slot; + switch (command) { + .result => return card.result, + .set => if (is_write) { + card.setMode(value); + self.poke(mouse.hole.mode + mine, value); + }, + .serve => card.serve(), + .read => { + const reported = card.readPosition(); + self.poke(mouse.hole.x_low + mine, @truncate(@as(u16, @bitCast(card.x)))); + self.poke(mouse.hole.x_high + mine, @intCast(@as(u16, @bitCast(card.x)) >> 8)); + self.poke(mouse.hole.y_low + mine, @truncate(@as(u16, @bitCast(card.y)))); + self.poke(mouse.hole.y_high + mine, @intCast(@as(u16, @bitCast(card.y)) >> 8)); + self.poke(mouse.hole.status + mine, reported); + }, + .clear => card.clear(), + .position => { + const x = @as(u16, self.peek(mouse.hole.x_low + mine)) | + @as(u16, self.peek(mouse.hole.x_high + mine)) << 8; + const y = @as(u16, self.peek(mouse.hole.y_low + mine)) | + @as(u16, self.peek(mouse.hole.y_high + mine)) << 8; + card.positionTo(@bitCast(x), @bitCast(y)); + }, + .clamp => if (is_write) { + // The caller leaves them in slot nought's holes: + // the low end in the X pair, the high end in the Y. + const low = @as(u16, self.peek(mouse.hole.x_low)) | + @as(u16, self.peek(mouse.hole.x_high)) << 8; + const high = @as(u16, self.peek(mouse.hole.y_low)) | + @as(u16, self.peek(mouse.hole.y_high)) << 8; + card.clamp(value, @bitCast(low), @bitCast(high)); + }, + .home => card.home(), + .init => { + card.initialise(); + self.poke(mouse.hole.mode + mine, 0); + self.poke(mouse.hole.status + mine, 0); + }, + else => {}, + } + self.updateInterrupt(); + return card.result; } /// The CPU this belongs to, recovered from the field it is embedded in. @@ -470,8 +535,11 @@ pub fn AppleIIe(comptime options: Options) fn (type) type { if (!self.vbl_latched and now >= self.frame_end - blanking_cycles) { self.vbl_latched = true; self.vbl_interrupt = true; + // The mouse is the other thing that wants telling when + // a frame ends, if it has been asked to interrupt then. + self.mouse_card.blanked(); } - if (self.vbl_interrupt_enabled and self.vbl_interrupt) + if ((self.vbl_interrupt_enabled and self.vbl_interrupt) or self.mouse_card.interrupting()) self.getCPU().irq = true; } @@ -663,6 +731,10 @@ pub fn AppleIIe(comptime options: Options) fn (type) type { &self.serial_rom[address - 0xc800] else &self.rom[address - 0xc000], + mouse_rom_base...mouse_rom_base + 0xff => if (self.mouse_card.fitted and !self.intcxrom) + &mouse_firmware[address - mouse_rom_base] + else + &self.rom[address - 0xc000], clock_rom_base...clock_rom_base + 0xff => if (self.clock_card.fitted and !self.intcxrom) &clock_firmware[address - clock_rom_base] else @@ -676,7 +748,7 @@ pub fn AppleIIe(comptime options: Options) fn (type) type { // slot 7 are next to each other, so there is no gap // between them to name. 0xc100...serial_rom_base - 1, - serial_rom_base + 0x100...clock_rom_base - 1, + serial_rom_base + 0x100...mouse_rom_base - 1, => &self.rom[address - 0xc000], 0xd000...0xdfff => if (self.read_ram) &self.zeroPageHalf().bank[@intFromBool(self.bank2)][address - 0xd000] @@ -872,6 +944,18 @@ pub fn AppleIIe(comptime options: Options) fn (type) type { self.pre_write = true; } }, + // The mouse's registers. Each one is a word with + // the card, which does the work itself and leaves the + // answer in the screen holes, as the processor on a + // real card's own board does. + mouse_switch_base...mouse_switch_base + 8 => { + if (!self.mouse_card.fitted) return 0; + return self.runMouseCommand( + @enumFromInt(@as(u4, @truncate(address - mouse_switch_base))), + is_write, + value, + ); + }, // The clock's two registers: one hands over the // string a character at a time, the other takes a // fresh reading. @@ -1742,6 +1826,127 @@ test "the Monitor's own paddle routine reads back what was set" { } } +test "the mouse card's own firmware is called the way a program calls it" { + var cpu = try machine(); + cpu.memory.mouse_card.fitted = true; + + // A program finds the routines through the table in the card's page: each + // byte in it is the low half of an address, and the page is the high half. + const set = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.set.address())); + const read = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.read.address())); + const start = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.init.address())); + + // Starting the card up and switching the mouse on, keeping the carry each + // call comes back with, which is how the firmware says it worked. + const first = [_]u8{ + 0xa2, 0xc4, // LDX #$c4 the slot, the way the card wants + 0xa0, 0x40, // LDY #$40 it told + 0x20, start, 0xc4, // JSR init + 0xa9, mouse.mode_on, // LDA #$01 + 0x20, set, 0xc4, // JSR set + 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A the carry, as a number + 0x8d, 0x00, 0x09, // STA $0900 + 0x02, // JAM + }; + try cpu.memory.loadProgram(0x0300, &first); + cpu.program_counter.value = 0x0300; + var ran: usize = 0; + while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; + + try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x0900)); + try testing.expectEqual(mouse.mode_on, cpu.memory.mouse_card.mode); + // The mode goes in the screen hole as well, where a program can see it. + try testing.expectEqual(mouse.mode_on, cpu.memory.peek(mouse.hole.mode + 4)); + + // The mouse moves and a button goes down, which is the host's doing. + cpu.memory.mouse_card.moveTo(300, 200); + cpu.memory.mouse_card.setButton(0, true); + + const second = [_]u8{ + 0xa2, 0xc4, // LDX #$c4 + 0xa0, 0x40, // LDY #$40 + 0x20, read, 0xc4, // JSR read + 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A + 0x8d, 0x01, 0x09, // STA $0901 + 0x02, // JAM + }; + try cpu.memory.loadProgram(0x0300, &second); + cpu.program_counter.value = 0x0300; + ran = 0; + while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; + + try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x0901)); + // Where the card leaves it: the position in four holes, low half and high + // half apart, and the buttons in a fifth. + try testing.expectEqual(@as(u8, 300 & 0xff), cpu.memory.peek(mouse.hole.x_low + 4)); + try testing.expectEqual(@as(u8, 300 >> 8), cpu.memory.peek(mouse.hole.x_high + 4)); + try testing.expectEqual(@as(u8, 200 & 0xff), cpu.memory.peek(mouse.hole.y_low + 4)); + try testing.expectEqual(@as(u8, 200 >> 8), cpu.memory.peek(mouse.hole.y_high + 4)); + const status = cpu.memory.peek(mouse.hole.status + 4); + try testing.expect(status & mouse.status_button0_now != 0); + try testing.expect(status & mouse.status_moved != 0); + + // And a mode the card does not know comes back with the carry set. + const third = [_]u8{ + 0xa2, 0xc4, // LDX #$c4 + 0xa0, 0x40, // LDY #$40 + 0xa9, 0xf0, // LDA #$f0 + 0x20, set, 0xc4, // JSR set + 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A + 0x8d, 0x02, 0x09, // STA $0902 + 0x02, // JAM + }; + try cpu.memory.loadProgram(0x0300, &third); + cpu.program_counter.value = 0x0300; + ran = 0; + while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; + try testing.expectEqual(@as(u8, 1), cpu.memory.peek(0x0902)); + try testing.expectEqual(mouse.mode_on, cpu.memory.mouse_card.mode); +} + +test "the mouse pulls the interrupt line, and lets go when asked" { + var cpu = try machine(); + cpu.memory.mouse_card.fitted = true; + cpu.memory.mouse_card.setMode(mouse.mode_on | mouse.mode_move_interrupt); + + try testing.expect(!cpu.irq); + cpu.memory.mouse_card.moveTo(10, 10); + // The line is worked out on the next access, which is any access at all. + _ = cpu.memory.read(u8, 0xc0c0); + try testing.expect(cpu.irq); + + // Owning up through the firmware is what takes it off the line again. + // The card asks to be called with interrupts disabled, and a handler + // would be: without that the processor answers the interrupt before the + // first instruction of this and never arrives. + cpu.flags.set(.I); + const serve = cpu.memory.peek(0xc400 + @as(u16, mouse.Entry.serve.address())); + const program = [_]u8{ + 0x20, serve, 0xc4, // JSR serve + 0xa9, 0x00, 0x2a, // LDA #$00 : ROL A nought if it was this card + 0x8d, 0x00, 0x09, // STA $0900 + 0x02, // JAM + }; + try cpu.memory.loadProgram(0x0300, &program); + cpu.program_counter.value = 0x0300; + var ran: usize = 0; + while (ran < 2000) : (ran += 1) cpu.executeInstruction() catch break; + + try testing.expectEqual(@as(u8, 0), cpu.memory.peek(0x0900)); + try testing.expect(!cpu.irq); +} + +test "a machine with no mouse card has nothing in slot four" { + var cpu = try machine(); + try testing.expect(cpu.memory.peek(0xc405) != mouse.identifiers[0].byte); + try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc0c0)); + + cpu.memory.mouse_card.fitted = true; + for (mouse.identifiers) |identifier| { + try testing.expectEqual(identifier.byte, cpu.memory.peek(0xc400 + @as(u16, identifier.at))); + } +} + test "the clock card's own firmware leaves the time where ProDOS reads it" { // What ProDOS does once it has found the signature: call the card at // $Cn08 and read the line buffer. Running the firmware is the only way to diff --git a/src/memory/apple2plus.zig b/src/memory/apple2plus.zig index 75cd10e..0f5890f 100644 --- a/src/memory/apple2plus.zig +++ b/src/memory/apple2plus.zig @@ -15,6 +15,7 @@ const cassette = @import("../cassette.zig"); const serial = @import("../serial.zig"); const blockdevice = @import("../blockdevice.zig"); const clockcard = @import("../clockcard.zig"); +const mouse = @import("../mouse.zig"); /// How fast the machine's own clock runs, which is what paces a tape being /// played in. @@ -56,6 +57,14 @@ const serial_rom_page = 0x700; const serial_rom_base = 0xc000 + serial_slot * 0x100; const serial_switch_base = 0x80 + serial_slot * 0x10; +/// Where the mouse lives: slot 4, which is where the card went and where the +/// software that uses one looks for it. +const mouse_slot = 4; +const mouse_rom_base = 0xc000 + mouse_slot * 0x100; +const mouse_switch_base = 0x80 + mouse_slot * 0x10; +/// Ours again: what a mouse card answers to is published. +const mouse_firmware = mouse.firmware(mouse_slot); + /// Where the clock lives. Any slot will do — ProDOS looks through all of /// them — so it takes slot 5, which is the free one: 2 is the serial card, 4 /// is where a mouse goes, 6 is the disk and 7 the hard disk. @@ -124,6 +133,10 @@ pub fn AppleIIPlus(comptime options: Options) fn (type) type { /// Which slot's ROM is answering at $c800, if any. expansion: ?u4 = null, + /// The mouse card in slot 4. It is the only card here that + /// pulls the interrupt line of its own accord. + mouse_card: mouse.Card = .{}, + /// The clock card in slot 5, which is what lets ProDOS put a /// date on a file. A machine with none does not know when it /// is, which is the ordinary case and the default here. @@ -347,6 +360,58 @@ pub fn AppleIIPlus(comptime options: Options) fn (type) type { if (which < self.buttons.len) self.buttons[which] = down; } + /// What the mouse card's firmware asks for. The position and + /// the buttons go in and out through the screen holes, which + /// are the bytes of the text page no character is displayed + /// from: one set for each slot, and slot nought's are where a + /// caller leaves the clamps. + fn runMouseCommand(self: *Self, command: mouse.Command, is_write: bool, value: u8) u8 { + const card = &self.mouse_card; + const mine: u16 = mouse_slot; + switch (command) { + .result => return card.result, + .set => if (is_write) { + card.setMode(value); + self.poke(mouse.hole.mode + mine, value); + }, + .serve => card.serve(), + .read => { + const reported = card.readPosition(); + self.poke(mouse.hole.x_low + mine, @truncate(@as(u16, @bitCast(card.x)))); + self.poke(mouse.hole.x_high + mine, @intCast(@as(u16, @bitCast(card.x)) >> 8)); + self.poke(mouse.hole.y_low + mine, @truncate(@as(u16, @bitCast(card.y)))); + self.poke(mouse.hole.y_high + mine, @intCast(@as(u16, @bitCast(card.y)) >> 8)); + self.poke(mouse.hole.status + mine, reported); + }, + .clear => card.clear(), + .position => { + const x = @as(u16, self.peek(mouse.hole.x_low + mine)) | + @as(u16, self.peek(mouse.hole.x_high + mine)) << 8; + const y = @as(u16, self.peek(mouse.hole.y_low + mine)) | + @as(u16, self.peek(mouse.hole.y_high + mine)) << 8; + card.positionTo(@bitCast(x), @bitCast(y)); + }, + .clamp => if (is_write) { + // The caller leaves them in slot nought's holes: + // the low end in the X pair, the high end in the Y. + const low = @as(u16, self.peek(mouse.hole.x_low)) | + @as(u16, self.peek(mouse.hole.x_high)) << 8; + const high = @as(u16, self.peek(mouse.hole.y_low)) | + @as(u16, self.peek(mouse.hole.y_high)) << 8; + card.clamp(value, @bitCast(low), @bitCast(high)); + }, + .home => card.home(), + .init => { + card.initialise(); + self.poke(mouse.hole.mode + mine, 0); + self.poke(mouse.hole.status + mine, 0); + }, + else => {}, + } + self.updateInterrupt(); + return card.result; + } + /// The CPU this belongs to, recovered from the field it is embedded in. inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("memory", self)); @@ -432,6 +497,10 @@ pub fn AppleIIPlus(comptime options: Options) fn (type) type { /// Whether anything is pulling the interrupt line, which on a /// II Plus can only be the card. fn updateInterrupt(self: *Self) void { + if (self.mouse_card.interrupting()) { + self.getCPU().irq = true; + return; + } self.getCPU().irq = self.serial_card and self.serial_interrupts and self.acia.interrupting(self.getCPU().clock.cycles); } @@ -513,6 +582,10 @@ pub fn AppleIIPlus(comptime options: Options) fn (type) type { &self.serial_rom[address - 0xc800] else &self.rom[address - 0xc000], + mouse_rom_base...mouse_rom_base + 0xff => if (self.mouse_card.fitted) + &mouse_firmware[address - mouse_rom_base] + else + &self.rom[address - 0xc000], clock_rom_base...clock_rom_base + 0xff => if (self.clock_card.fitted) &clock_firmware[address - clock_rom_base] else @@ -525,7 +598,7 @@ pub fn AppleIIPlus(comptime options: Options) fn (type) type { // Slot 6 and slot 7 are next to each other, so there is // no gap between them to name. 0xc100...serial_rom_base - 1, - serial_rom_base + 0x100...clock_rom_base - 1, + serial_rom_base + 0x100...mouse_rom_base - 1, => &self.rom[address - 0xc000], 0xd000...0xdfff => if (self.read_ram) &self.bank[@intFromBool(self.bank2)][address - 0xd000] @@ -584,6 +657,18 @@ pub fn AppleIIPlus(comptime options: Options) fn (type) type { self.key_down = false; return pressed; }, + // The mouse's registers. Each one is a word with + // the card, which does the work itself and leaves the + // answer in the screen holes, as the processor on a + // real card's own board does. + mouse_switch_base...mouse_switch_base + 8 => { + if (!self.mouse_card.fitted) return 0; + return self.runMouseCommand( + @enumFromInt(@as(u4, @truncate(address - mouse_switch_base))), + is_write, + value, + ); + }, // The clock's two registers: one hands over the // string a character at a time, the other takes a // fresh reading. diff --git a/src/mouse.zig b/src/mouse.zig new file mode 100644 index 0000000..d0e60d5 --- /dev/null +++ b/src/mouse.zig @@ -0,0 +1,537 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! An AppleMouse II card: where the mouse is, which buttons are down, and the +//! firmware a program calls to ask. +//! +//! The card is the only ordinary one that pulls the interrupt line: told to, +//! it interrupts when the mouse moves, when a button goes down, or once a +//! frame at vertical blanking. Everything else in this machine leaves the line +//! alone. +//! +//! A program finds the card by the five bytes in its ROM, and calls it through +//! a table of eight entry points. What comes back does not come back in +//! registers: the card leaves the position and the state of the buttons in the +//! screen holes, the odd bytes of the text page that no character is displayed +//! from, one set of them for each slot. +//! +//! Apple II Mouse Technical Note and the Apple IIe Technical Reference are +//! where the arrangement below comes from. + +const std = @import("std"); +const testing = std.testing; + +/// The five bytes a program looks for, and where in the page they sit. The +/// first four are the Pascal 1.1 way of saying what a card is; the last says +/// which sort of pointing device. +pub const identifiers = [_]struct { at: u8, byte: u8 }{ + .{ .at = 0x05, .byte = 0x38 }, + .{ .at = 0x07, .byte = 0x18 }, + .{ .at = 0x0b, .byte = 0x01 }, + .{ .at = 0x0c, .byte = 0x20 }, + .{ .at = 0xfb, .byte = 0xd6 }, +}; + +/// Where the table of entry points begins. Each byte in it is the low half of +/// a routine's address in the card's page. +pub const entries_at = 0x12; + +/// The eight routines, in the order the table holds them. +pub const Entry = enum(u8) { + /// Turns the mouse on or off and says what it may interrupt for. + set = 0x12, + /// Called from an interrupt handler: says whether this card caused it. + serve = 0x13, + /// Puts where the mouse is into the screen holes. + read = 0x14, + /// Puts it back to nought. + clear = 0x15, + /// Takes the position from the screen holes, which is how a program moves + /// the pointer itself. + position = 0x16, + /// Sets how far the mouse may go, which the caller leaves in slot nought's + /// screen holes. + clamp = 0x17, + /// Puts it in the corner of wherever it has been clamped to. + home = 0x18, + /// Back to how it starts: nought to 1023 both ways, and the middle of + /// nowhere in particular. + init = 0x19, + + /// Where in the card's page the byte for this routine sits. + pub fn address(self: Entry) u8 { + return @intFromEnum(self); + } +}; + +/// Where a slot's screen holes are. The text page has eight bytes in each of +/// its lines that no character comes from, and the cards were given them. +pub const hole = struct { + pub const x_low = 0x0478; + pub const y_low = 0x04f8; + pub const x_high = 0x0578; + pub const y_high = 0x05f8; + pub const status = 0x0778; + pub const mode = 0x07f8; +}; + +/// What a program may ask to be interrupted for, which is the byte it hands to +/// the first routine. +pub const mode_on = 0x01; +pub const mode_move_interrupt = 0x02; +pub const mode_button_interrupt = 0x04; +pub const mode_vbl_interrupt = 0x08; +pub const mode_known = 0x0f; + +/// What the card says in the status hole. The low half is which interrupt has +/// happened, the high half is where the buttons are now and where they were +/// when the position was last read. +pub const status_button1_was = 0x01; +pub const status_moved_interrupt = 0x02; +pub const status_button_interrupt = 0x04; +pub const status_vbl_interrupt = 0x08; +pub const status_button1_now = 0x10; +pub const status_moved = 0x20; +pub const status_button0_was = 0x40; +pub const status_button0_now = 0x80; + +/// How far the mouse may go before it is told otherwise. +pub const default_clamp_low = 0; +pub const default_clamp_high = 1023; + +/// What the firmware asks the card to do. The card does the work, as the one +/// on a real card's own processor does, and the firmware is the few bytes that +/// pass the question along. +pub const Command = enum(u4) { + set = 0, + serve = 1, + read = 2, + clear = 3, + position = 4, + clamp = 5, + home = 6, + init = 7, + /// What the last one came to: nought for the carry clear that means it + /// worked, anything else for the carry set that means it did not. + result = 8, + _, +}; + +pub const Card = struct { + /// Whether there is a card in the slot at all. + fitted: bool = false, + + x: i16 = 0, + y: i16 = 0, + low_x: i16 = default_clamp_low, + high_x: i16 = default_clamp_high, + low_y: i16 = default_clamp_low, + high_y: i16 = default_clamp_high, + + /// Where the buttons are, and where they were when the position was last + /// read, which is how a program tells a click from a hold. + button: [2]bool = @splat(false), + button_was: [2]bool = @splat(false), + + /// What it has been told it may interrupt for. + mode: u8 = 0, + /// Whether it has moved since the position was last read. + moved: bool = false, + /// Which interrupts are waiting to be owned up to. + pending: u8 = 0, + /// What the last command came to. + result: u8 = 0, + + /// Whether the mouse is switched on, which is the only bit that matters + /// when it is not. + pub fn on(self: *const Card) bool { + return self.mode & mode_on != 0; + } + + /// Whether the card is pulling the interrupt line, which it does until a + /// handler asks it to own up. + pub fn interrupting(self: *const Card) bool { + return self.fitted and self.on() and self.pending != 0; + } + + /// The byte the card leaves in the status hole. + pub fn status(self: *const Card) u8 { + var byte: u8 = self.pending; + if (self.button[1]) byte |= status_button1_now; + if (self.button_was[1]) byte |= status_button1_was; + if (self.button[0]) byte |= status_button0_now; + if (self.button_was[0]) byte |= status_button0_was; + if (self.moved) byte |= status_moved; + return byte; + } + + /// Where the host puts the mouse, in the units the program clamped it to. + pub fn moveTo(self: *Card, x: i16, y: i16) void { + const to_x = std.math.clamp(x, self.low_x, self.high_x); + const to_y = std.math.clamp(y, self.low_y, self.high_y); + if (to_x == self.x and to_y == self.y) return; + self.x = to_x; + self.y = to_y; + self.moved = true; + if (self.on() and self.mode & mode_move_interrupt != 0) { + self.pending |= status_moved_interrupt; + } + } + + pub fn moveBy(self: *Card, dx: i16, dy: i16) void { + self.moveTo(self.x +| dx, self.y +| dy); + } + + pub fn setButton(self: *Card, which: u1, down: bool) void { + if (self.button[which] == down) return; + self.button[which] = down; + // Only a press is worth interrupting for; letting go is not. + if (down and self.on() and self.mode & mode_button_interrupt != 0) { + self.pending |= status_button_interrupt; + } + } + + /// Called when the video reaches the bottom of a frame, which is the third + /// thing the card can be told to interrupt for. + pub fn blanked(self: *Card) void { + if (self.on() and self.mode & mode_vbl_interrupt != 0) { + self.pending |= status_vbl_interrupt; + } + } + + /// Turns the mouse on or off. A mode with bits in it the card does not + /// know is refused, which is what the carry says on the way out. + pub fn setMode(self: *Card, mode: u8) void { + if (mode & ~@as(u8, mode_known) != 0) { + self.result = 1; + return; + } + self.mode = mode; + if (!self.on()) self.pending = 0; + self.result = 0; + } + + /// Owning up: a handler asks whether this card was the one, and the answer + /// takes the interrupt off the line. + pub fn serve(self: *Card) void { + self.result = if (self.pending != 0) 0 else 1; + self.pending = 0; + } + + /// Reading the position hands back the status as it stood, and then moves + /// the buttons' now into their before and forgets that it moved. What a + /// program is told is therefore what has happened since it last asked, + /// which is what lets it see each press and each movement once. + pub fn readPosition(self: *Card) u8 { + const reported = self.status(); + self.button_was = self.button; + self.moved = false; + self.result = 0; + return reported; + } + + pub fn clear(self: *Card) void { + self.x = 0; + self.y = 0; + self.moved = false; + self.result = 0; + } + + pub fn home(self: *Card) void { + self.x = self.low_x; + self.y = self.low_y; + self.moved = false; + self.result = 0; + } + + /// Where a program says the mouse is, which it may do at any time. + pub fn positionTo(self: *Card, x: i16, y: i16) void { + self.x = std.math.clamp(x, self.low_x, self.high_x); + self.y = std.math.clamp(y, self.low_y, self.high_y); + self.moved = false; + self.result = 0; + } + + /// How far it may go. Nought clamps the one way and one the other, and a + /// clamp that is the wrong way round is left alone. + pub fn clamp(self: *Card, which: u8, low: i16, high: i16) void { + if (low > high) { + self.result = 1; + return; + } + if (which == 0) { + self.low_x = low; + self.high_x = high; + self.x = std.math.clamp(self.x, low, high); + } else { + self.low_y = low; + self.high_y = high; + self.y = std.math.clamp(self.y, low, high); + } + self.result = 0; + } + + /// How it starts, and what the eighth routine puts it back to. + pub fn initialise(self: *Card) void { + const fitted = self.fitted; + self.* = .{ .fitted = fitted }; + self.result = 0; + } +}; + +/// The card's ROM, which is ours: what a mouse card has to answer to is +/// published, and none of Apple's own code is needed to answer it. +/// +/// The five bytes a program looks for are at the offsets it looks at, and are +/// ordinary instructions, three of which are branches that all land on the +/// same place. That is how the real card's page begins, and why those offsets +/// were chosen. +pub fn firmware(comptime slot: u4) [256]u8 { + const io = 0xc080 + @as(u16, slot) * 0x10; + const lo: u8 = @truncate(io); + const hi: u8 = @truncate(io >> 8); + const page: u8 = 0xc0 + @as(u8, slot); + const entry_at = 0x20; + const first_routine = 0x30; + const routine_size = 6; + const finish_at = first_routine + 8 * routine_size; + + var rom: [256]u8 = @splat(0); + + const head = [_]u8{ + 0x2c, 0x58, 0xff, // $Cn00 BIT $ff58 + 0x70, 0x1b, // $Cn03 BVS $Cn20 + 0x38, // $Cn05 SEC the first of the five + 0x90, 0x18, // $Cn06 BCC $Cn20 and the second, the $18 + 0xb8, // $Cn08 CLV + 0x50, 0x15, // $Cn09 BVC $Cn20 + 0x01, 0x20, // $Cn0b ORA ($20,X) the third and the fourth + }; + @memcpy(rom[0..head.len], &head); + + // The table a program calls through: the low half of each routine's + // address, in the order the eight are always in. + for (0..8) |i| rom[entries_at + i] = first_routine + @as(u8, @intCast(i)) * routine_size; + + // Whatever runs into $Cn20 has nothing to do: a mouse is not something to + // print through or read a line from. + rom[entry_at] = 0x60; // RTS + + // The eight, each of them a word with the card and then the same ending. + for (0..8) |i| { + const command: u8 = @intCast(i); + const at = first_routine + i * routine_size; + // Setting the mode and setting the clamps are told something in the + // accumulator, so they write; the rest only ask. + const writes = command == @intFromEnum(Command.set) or command == @intFromEnum(Command.clamp); + const routine = [_]u8{ + if (writes) 0x8d else 0xad, lo + command, hi, // STA/LDA the card + 0x4c, finish_at, page, // JMP finish + }; + @memcpy(rom[at..][0..routine.len], &routine); + } + + // The ending: the carry the caller reads the answer from. + const finish = [_]u8{ + 0xad, lo + @intFromEnum(Command.result), hi, // LDA result + 0xd0, 0x02, // BNE bad + 0x18, // CLC it worked + 0x60, // RTS + 0x38, // bad: SEC + 0x60, // RTS + }; + @memcpy(rom[finish_at..][0..finish.len], &finish); + + // And the byte that says which sort of device this is. + for (identifiers) |identifier| rom[identifier.at] = identifier.byte; + + comptime { + // The identifiers must not land in anything else: the head ends + // before the last of them, and the rest are past everything written. + for (identifiers) |identifier| { + std.debug.assert(identifier.at < head.len or identifier.at >= finish_at + finish.len); + } + std.debug.assert(head.len <= entries_at); + std.debug.assert(entries_at + 8 <= entry_at); + std.debug.assert(entry_at < first_routine); + std.debug.assert(finish_at + finish.len <= 0xfb); + } + return rom; +} + +test "the firmware says what a program looks for" { + const rom = firmware(4); + // The five bytes, at the five offsets, which is the whole of how a + // program decides a slot holds a mouse. + for (identifiers) |identifier| { + try testing.expectEqual(identifier.byte, rom[identifier.at]); + } + + // The three branches in the head all land on the same place, which is why + // those offsets could be given away to the identifiers. + try testing.expectEqual(@as(u8, 0x20), 0x05 + rom[0x04]); + try testing.expectEqual(@as(u8, 0x20), 0x08 + rom[0x07]); + try testing.expectEqual(@as(u8, 0x20), 0x0b + rom[0x0a]); + + // The table is eight entry points, each inside the page and none of them + // the same as another. + var seen: [8]u8 = undefined; + for (0..8) |i| { + const at = rom[entries_at + i]; + try testing.expect(at >= 0x20); + for (seen[0..i]) |before| try testing.expect(before != at); + seen[i] = at; + // Each is a word with the card and then a jump to the same ending. + try testing.expect(rom[at] == 0xad or rom[at] == 0x8d); + try testing.expectEqual(@as(u8, 0x4c), rom[at + 3]); + } + // Setting the mode and the clamps are told something; the rest only ask. + const table = struct { + fn of(where: [256]u8, command: Command) u8 { + return where[where[entries_at + @as(usize, @intFromEnum(command))]]; + } + }; + try testing.expectEqual(@as(u8, 0x8d), table.of(rom, .set)); + try testing.expectEqual(@as(u8, 0x8d), table.of(rom, .clamp)); + try testing.expectEqual(@as(u8, 0xad), table.of(rom, .read)); +} + +test "the mouse stays inside what it has been clamped to" { + var card: Card = .{}; + card.setMode(mode_on); + card.moveTo(500, 600); + try testing.expectEqual(@as(i16, 500), card.x); + try testing.expectEqual(@as(i16, 600), card.y); + + // The corners it starts with, which are nought to 1023 both ways. + card.moveTo(-100, 5000); + try testing.expectEqual(@as(i16, 0), card.x); + try testing.expectEqual(@as(i16, 1023), card.y); + + // A window, and a position outside it is pulled in when it is set. + card.clamp(0, 100, 200); + try testing.expectEqual(@as(i16, 100), card.x); + card.clamp(1, 300, 400); + try testing.expectEqual(@as(i16, 400), card.y); + card.moveTo(1000, 1000); + try testing.expectEqual(@as(i16, 200), card.x); + try testing.expectEqual(@as(i16, 400), card.y); + + // The corner it homes to is the near one of that window. + card.home(); + try testing.expectEqual(@as(i16, 100), card.x); + try testing.expectEqual(@as(i16, 300), card.y); + + // A window the wrong way round is refused. + card.clamp(0, 500, 100); + try testing.expectEqual(@as(u8, 1), card.result); + try testing.expectEqual(@as(i16, 100), card.low_x); +} + +test "the status says where the buttons are and where they were" { + var card: Card = .{}; + card.setMode(mode_on); + + // Nothing has happened. + try testing.expectEqual(@as(u8, 0), card.status()); + + // A press shows as down now, and as not having been down before, until + // the position is read: that is what tells a program a click is new. + card.setButton(0, true); + try testing.expectEqual(status_button0_now, card.status() & (status_button0_now | status_button0_was)); + _ = card.readPosition(); + try testing.expectEqual( + status_button0_now | status_button0_was, + card.status() & (status_button0_now | status_button0_was), + ); + + // And letting go shows the other way about. + card.setButton(0, false); + try testing.expectEqual(status_button0_was, card.status() & (status_button0_now | status_button0_was)); + + // The second button has its own pair of bits. + card.setButton(1, true); + try testing.expect(card.status() & status_button1_now != 0); + try testing.expect(card.status() & status_button1_was == 0); + + // And moving shows until it is read. + card.moveTo(10, 10); + try testing.expect(card.status() & status_moved != 0); + _ = card.readPosition(); + try testing.expect(card.status() & status_moved == 0); +} + +test "it pulls the interrupt line only for what it was told to" { + var card: Card = .{ .fitted = true }; + + // Switched off, nothing it does matters. + card.moveTo(10, 10); + card.setButton(0, true); + card.blanked(); + try testing.expect(!card.interrupting()); + + // On, but told to interrupt for nothing. + card.setMode(mode_on); + card.setButton(0, false); + card.moveTo(20, 20); + card.setButton(0, true); + card.blanked(); + try testing.expect(!card.interrupting()); + + // Told to interrupt when it moves. + card.setMode(mode_on | mode_move_interrupt); + card.moveTo(30, 30); + try testing.expect(card.interrupting()); + try testing.expect(card.status() & status_moved_interrupt != 0); + + // Owning up takes it off the line, and says it was this card. + card.serve(); + try testing.expectEqual(@as(u8, 0), card.result); + try testing.expect(!card.interrupting()); + // Asked again, it says it was not. + card.serve(); + try testing.expectEqual(@as(u8, 1), card.result); + + // A press, and the end of a frame, are the other two. + card.setMode(mode_on | mode_button_interrupt); + card.setButton(0, false); + card.setButton(0, true); + try testing.expect(card.status() & status_button_interrupt != 0); + card.serve(); + + card.setMode(mode_on | mode_vbl_interrupt); + card.blanked(); + try testing.expect(card.status() & status_vbl_interrupt != 0); + card.serve(); + + // Switching the mouse off drops whatever was waiting. + card.setMode(mode_on | mode_vbl_interrupt); + card.blanked(); + try testing.expect(card.interrupting()); + card.setMode(0); + try testing.expect(!card.interrupting()); + + // And a mode with bits in it the card does not know is refused. + card.setMode(0xf0); + try testing.expectEqual(@as(u8, 1), card.result); + try testing.expectEqual(@as(u8, 0), card.mode); +} + +test "starting again puts everything back" { + var card: Card = .{ .fitted = true }; + card.setMode(mode_on | mode_move_interrupt); + card.clamp(0, 10, 20); + card.moveTo(15, 500); + card.setButton(1, true); + + card.initialise(); + try testing.expectEqual(@as(i16, 0), card.x); + try testing.expectEqual(@as(i16, 0), card.y); + try testing.expectEqual(@as(i16, default_clamp_low), card.low_x); + try testing.expectEqual(@as(i16, default_clamp_high), card.high_x); + try testing.expectEqual(@as(u8, 0), card.mode); + try testing.expect(!card.button[1]); + // But it is still in the machine. + try testing.expect(card.fitted); +} diff --git a/src/root.zig b/src/root.zig index 10bb2bc..6708899 100644 --- a/src/root.zig +++ b/src/root.zig @@ -42,6 +42,9 @@ pub const prodos = @import("prodos.zig"); /// A clock card, which is how ProDOS comes to know the date. pub const clockcard = @import("clockcard.zig"); +/// An AppleMouse II card: where the mouse is, and what it interrupts for. +pub const mouse = @import("mouse.zig"); + /// The memory models a processor can be given. Flat is the only one so far; /// a machine with banking and soft switches goes alongside it. pub const memory = @import("memory.zig"); @@ -66,6 +69,7 @@ test { _ = dos33; _ = prodos; _ = clockcard; + _ = mouse; _ = screen; _ = speaker; _ = cassette;