// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! An Apple IIgs you can use, and a debugger around it. //! //! `bootgs` runs a IIgs ROM and then tells you what it did, which is the right //! shape for finding out what the machine wants and the wrong shape for using //! one. This is the other shape: a window with the machine's screen in it and //! a keyboard that reaches it. //! //! zig build gs -- ROM [DISK] //! //! It is not `src/main.zig`. That file is an eight-bit machine surrounded by //! panes, and it cannot drive this one: a 65816 is a different core with //! different registers, registers whose *width* changes under it, and a //! twenty-four bit program counter that does not carry into its own bank. So //! the panes here are this processor's rather than a 6502's with more digits, //! and what the two front ends share is what they can — the terminal in //! `tools/terminal.zig`, and the run state in `zig65.debug`. //! //! The panes start out of the way, which is the other difference. The //! eight-bit program was written as a debugger with a machine in it; this one //! was written the other way about, and somebody using a IIgs as a IIgs would //! rather have the terminal to themselves. `alt+d` opens them, and so does //! anything that stops the processor, since there is nothing else to look at //! on a machine that is not running. //! //! Every key this program keeps for itself is behind alt, because the Apple //! owns the keyboard: `alt+q` quits, `alt+b` presses reset, `alt+g` writes a //! picture of the screen, `alt+space` steps, `alt+r` runs, `alt+p` pauses, //! `alt+f` points the memory view at the program counter, and `alt+[` and //! `alt+]` change bank. Everything else goes to the machine. const std = @import("std"); const ltoudp = @import("ltoudp.zig"); const session16 = @import("session16.zig"); const terminal = @import("terminal"); const config = @import("config"); const vaxis = @import("vaxis"); const zig65 = @import("zig65"); const audio = @import("audio"); const disk2 = zig65.disk2; const disk35 = zig65.disk35; const picture = zig65.picture; const screen = zig65.screen; const diskfile = zig65.diskfile; // The machine type and the numbers that pace it live in the driving core in // session16.zig now; these aliases keep this front end reading as it did. const CPU = session16.CPU; const Memory = session16.Memory; const cycles_per_second = session16.cycles_per_second; const pacing_clock = session16.pacing_clock; const sample_rate = session16.sample_rate; const Drive = session16.Drive; /// A path being typed at the machine, which is the one time keys are not the /// machine's. const Prompt = struct { drive: Drive, buffer: [256]u8 = undefined, len: usize = 0, }; /// A path being typed for a save state, and which way it goes: writing the /// machine to the file, or reading it back. const SnapshotPrompt = struct { loading: bool, buffer: [256]u8 = undefined, len: usize = 0, }; /// One thing the disk picker can do, once something is chosen from it. const Choice = union(enum) { /// Insert the library disk with this index. disk: usize, /// Take whatever is in the drive out. eject, /// Put a fresh blank writable disk in. blank, /// Type a path, which is the picker handing off to the old prompt. path, }; /// A disk being chosen for a drive from the library and the fixed choices /// below it. It takes the keyboard while it is open, and the arrow keys move a /// highlight down a list that `Choice` above enumerates. const Picker = struct { drive: Drive, selection: usize = 0, /// The choices in the order they are shown: every disk in the library, /// then — only when the drive has something in it — eject, then a blank /// disk, then the path prompt. Key handling and drawing both read this so /// the highlight and the action can never disagree. fn choices(library: []const config.Disk, occupied: bool, into: []Choice) []Choice { var n: usize = 0; for (library, 0..) |_, i| { if (n >= into.len) break; into[n] = .{ .disk = i }; n += 1; } if (occupied and n < into.len) { into[n] = .eject; n += 1; } if (n < into.len) { into[n] = .blank; n += 1; } if (n < into.len) { into[n] = .path; n += 1; } return into[0..n]; } }; /// How many choices a picker's list can hold. const picker_choices_max = 64; /// How wide the debugger's panes are. The memory view sets it: four digits of /// address, sixteen bytes as hexadecimal, and the same sixteen as characters, /// with a border round the lot. const panes_width = 4 + 2 + 16 * 3 + 1 + 16 + 2; const Event = union(enum) { key_press: vaxis.Key, mouse: vaxis.Mouse, winsize: vaxis.Winsize, }; const App = struct { /// The machine and everything that drives it, with no front end in it. /// This front end reaches the processor, the disks, the pacing and the /// rest through here; see `session16.zig`. session: session16.Session, /// The host's live audio: the Ensoniq out of a real speaker. Opened once /// at startup and kept for the life of the program; the recording captures /// samples for it and the run loop drains them here. Silent until opened. audio: audio.Output = .{}, tty_buffer: [128]u8 = undefined, tty: vaxis.Tty = undefined, writer: *std.Io.Writer = undefined, vx: vaxis.Vaxis = undefined, display: terminal.Display = .{}, /// A path being typed at one of the drives, which is the one time keys are /// not the machine's. prompt: ?Prompt = null, /// A path being typed for a save state, `alt+w` to write one and `alt+l` /// to load one. snapshot_prompt: ?SnapshotPrompt = null, /// The named disks the alt-1/alt-2 picker offers, from the config file. library: []const config.Disk = &.{}, /// A disk being chosen from the library, or none. It takes the keyboard /// while it is up, the way the path prompt does. picker: ?Picker = null, /// Where alt+g writes a picture of the screen. screenshot: []const u8, /// How the machine was built, kept so `alt+w` can write a config beside a /// snapshot that builds the same machine and boots into it. params: Params, /// Which monitor the machine is being looked at on, and who draws the /// text. Two settings rather than one, because they are two questions: /// see `terminal.Monitor` and `terminal.TextDrawing`. monitor: terminal.Monitor = .monochrome, text: terminal.TextDrawing = .pixels, /// Where the terminal's pointer was last seen over the machine's screen, /// in the dots the machine draws. Nothing while it is somewhere else. pointer: ?[2]i32 = null, /// Which page of memory the view is looking at, and which of the two /// hundred and fifty-six banks it is a page of. /// /// Two numbers rather than one because that is how the processor thinks: /// a 65816's address is a bank and sixteen bits inside it, the counter /// does not carry from one into the next, and a program that has walked /// off the end of a bank has wrapped to its start rather than gone on. /// Paging past `$ff` therefore wraps inside the bank, and changing bank is /// a separate key. memory_page: u8 = 0, memory_bank: u8 = 0, /// Whether the machine's own panes are shown at all. /// /// The eight-bit front end always shows them, because it was written as a /// debugger with a machine in it. This one was written the other way /// about, and somebody using a IIgs as a IIgs would rather have the /// terminal to themselves -- so the panes are here when they are wanted /// and out of the way when they are not, and `alt+d` is the switch. panes: bool = false, quit: bool = false, /// While a disk is being changed the keys are this program's: a path has /// to be typed somewhere. Return puts it in, an empty line takes out /// whatever was there, and escape changes nothing. fn promptKey(self: *App, key: vaxis.Key) void { const prompt = &(self.prompt.?); if (key.matches(vaxis.Key.escape, .{})) { self.prompt = null; return; } if (key.matches(vaxis.Key.enter, .{})) { var typed: [prompt.buffer.len]u8 = undefined; const length = prompt.len; @memcpy(typed[0..length], prompt.buffer[0..length]); const drive = prompt.drive; self.prompt = null; if (length == 0) { self.session.eject(drive); return; } self.session.insert(typed[0..length], null) catch |err| { self.session.say("{s}: {s}", .{ typed[0..length], @errorName(err) }); }; return; } if (key.matches(vaxis.Key.backspace, .{}) or key.matches(vaxis.Key.delete, .{})) { if (prompt.len > 0) prompt.len -= 1; return; } const codepoint = key.codepoint; if (codepoint < 0x20 or codepoint > 0x7e) return; if (prompt.len < prompt.buffer.len) { prompt.buffer[prompt.len] = @intCast(codepoint); prompt.len += 1; } } /// A key typed into the save-state prompt. Return acts on the path, escape /// changes nothing, and an empty path is refused. fn snapshotPromptKey(self: *App, key: vaxis.Key) void { const prompt = &(self.snapshot_prompt.?); if (key.matches(vaxis.Key.escape, .{})) { self.snapshot_prompt = null; return; } if (key.matches(vaxis.Key.enter, .{})) { var typed: [prompt.buffer.len]u8 = undefined; const length = prompt.len; @memcpy(typed[0..length], prompt.buffer[0..length]); const loading = prompt.loading; const path = typed[0..length]; self.snapshot_prompt = null; if (length == 0) return; if (loading) { self.session.loadSnapshot(path) catch |err| { self.session.say("could not load {s}: {s}", .{ path, @errorName(err) }); return; }; self.session.say("loaded {s}", .{path}); } else { self.session.saveSnapshot(path) catch |err| { self.session.say("could not save {s}: {s}", .{ path, @errorName(err) }); return; }; self.writeCompanionConfig(path) catch |err| { self.session.say("saved {s}, but not its config: {s}", .{ path, @errorName(err) }); return; }; self.session.say("saved to {s}, with a config beside it", .{path}); } return; } if (key.matches(vaxis.Key.backspace, .{}) or key.matches(vaxis.Key.delete, .{})) { if (prompt.len > 0) prompt.len -= 1; return; } const codepoint = key.codepoint; if (codepoint < 0x20 or codepoint > 0x7e) return; if (prompt.len < prompt.buffer.len) { prompt.buffer[prompt.len] = @intCast(codepoint); prompt.len += 1; } } /// Whether the named drive has a disk in it, which is what decides if the /// picker offers to eject one. The 3.5-inch drive is the first slot and the /// 5.25-inch the second, the way `session16` keeps them. fn occupied(self: *const App, drive: Drive) bool { const slot: usize = switch (drive) { .three_and_a_half => 0, .five_and_a_quarter => 1, }; return self.session.slots[slot].len > 0; } /// Writes a config beside a snapshot that rebuilds this IIgs and boots into /// it. A IIgs is one machine with its cards built in, so there is little to /// say beyond the ROM, the memory, and the hard disks and intelligent /// drives the snapshot reads back into. The floppies are left out, the /// snapshot carrying their surfaces. fn writeCompanionConfig(self: *App, snapshot_path: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(self.session.gpa); defer arena.deinit(); const a = arena.allocator(); const p = self.params; var slots: std.ArrayList(config.Slot) = .empty; if (p.hard_disks[0] != null or p.hard_disks[1] != null) try slots.append(a, .{ .slot = 7, .card = "block", .image = p.hard_disks[0], .image2 = p.hard_disks[1] }); if (p.uthernet) try slots.append(a, .{ .slot = 1, .card = "uthernet" }); if (p.uthernet1) try slots.append(a, .{ .slot = 1, .card = "uthernet1" }); const memory: ?[]const u8 = if (p.memory) |m| if (m % (1024 * 1024) == 0) try std.fmt.allocPrint(a, "{d}M", .{m / (1024 * 1024)}) else try std.fmt.allocPrint(a, "{d}K", .{m / 1024}) else null; const cfg: config.Config = .{ .machine = "iigs", .rom = p.rom, .memory = memory, .slots = if (slots.items.len == 0) null else try slots.toOwnedSlice(a), .unidisk = p.unidisks[0], .unidisk2 = p.unidisks[1], .snapshot = snapshot_path, }; const companion = try config.companionPath(a, snapshot_path); try config.write(self.session.io, self.session.gpa, companion, cfg); } /// A key typed into the disk picker. Up and down move the highlight, return /// acts on what it is over, and escape closes it changing nothing. fn pickerKey(self: *App, key: vaxis.Key) void { const picker = &(self.picker.?); if (key.matches(vaxis.Key.escape, .{})) { self.picker = null; return; } var buffer: [picker_choices_max]Choice = undefined; const list = Picker.choices(self.library, self.occupied(picker.drive), &buffer); if (list.len == 0) { self.picker = null; return; } if (picker.selection >= list.len) picker.selection = list.len - 1; if (key.matches(vaxis.Key.up, .{})) { if (picker.selection > 0) picker.selection -= 1; return; } if (key.matches(vaxis.Key.down, .{})) { if (picker.selection + 1 < list.len) picker.selection += 1; return; } if (key.matches(vaxis.Key.enter, .{})) { const drive = picker.drive; const choice = list[picker.selection]; self.picker = null; switch (choice) { .disk => |i| { const disk = self.library[i]; // The IIgs puts a disk in whichever drive it fits, so the // library entry's path is what matters here, not the drive // the picker was opened on. self.session.insert(disk.path, disk.writable) catch |err| { self.session.say("{s}: {s}", .{ disk.path, @errorName(err) }); }; }, .eject => self.session.eject(drive), .blank => self.session.insertBlank(drive), // The old way, for a disk that is not in the library: the picker // hands the keyboard to the path prompt. .path => self.prompt = .{ .drive = drive }, } return; } } /// The machine's screen as a mousing surface, as the pane draws it. /// /// The pane puts the screen one cell in and one cell down from the corner /// and is only as wide as the mode needs, so forty-column text starts in /// the same place eighty-column text does. /// The keys that drive the processor rather than being typed at it. /// /// Returns whether the key was one of them, so that anything left over /// goes on to the machine. Everything here is behind alt, which is the /// whole of how this program and the Apple share a keyboard. fn debuggerKey(self: *App, key: vaxis.Key) bool { // Space is one instruction, and is also how a running machine is // stopped: the first press pauses it and the ones after that step. A // halted processor has nowhere to step to, so it does nothing. if (key.matches(vaxis.Key.space, .{ .alt = true })) { if (self.session.state != .halted) { self.session.state = .single_step; self.session.step(); self.panes = true; } return true; } if (key.matches('r', .{ .alt = true })) { self.session.start(); return true; } if (key.matches('p', .{ .alt = true })) { if (self.session.state == .running) self.session.state = .single_step; self.panes = true; return true; } if (key.matches('d', .{ .alt = true })) { self.panes = !self.panes; return true; } // The memory view: a page at a time within a bank, and a bank at a // time with the brackets. Both wrap, because both registers do. if (key.matches(vaxis.Key.page_up, .{ .alt = true })) { self.memory_page -%= 1; return true; } if (key.matches(vaxis.Key.page_down, .{ .alt = true })) { self.memory_page +%= 1; return true; } if (key.matches('[', .{ .alt = true })) { self.memory_bank -%= 1; return true; } if (key.matches(']', .{ .alt = true })) { self.memory_bank +%= 1; return true; } // And back to wherever the processor is, which is the address one // actually wants to look at nine times in ten. The bank is the // program bank rather than the data bank: this follows the // instructions. if (key.matches('f', .{ .alt = true })) { self.memory_bank = self.session.cpu.registers.program_bank; self.memory_page = @intCast(self.session.cpu.program_counter.value >> 8); self.panes = true; return true; } // Save states: write one, or load one, each into a path typed at a // prompt the way a disk's is. if (key.matches('w', .{ .alt = true })) { self.snapshot_prompt = .{ .loading = false }; return true; } if (key.matches('l', .{ .alt = true })) { self.snapshot_prompt = .{ .loading = true }; return true; } // How fast it is asked to run. Plus and equals both double, since they // are the same key and reaching for shift to make a machine go faster // is a nuisance; nought puts it back to the speed the machine's own // crystal gives, which is a long way back once it has been doubled a // dozen times. if (key.matches('+', .{ .alt = true }) or key.matches('=', .{ .alt = true })) { self.session.target_hz = @min(session16.max_hz, self.session.target_hz *| 2); return true; } if (key.matches('-', .{ .alt = true })) { self.session.target_hz = @max(session16.min_hz, self.session.target_hz / 2); return true; } if (key.matches('0', .{ .alt = true })) { self.session.target_hz = session16.cycles_per_second; return true; } // The live volume: quieter, louder, or muted. if (key.matches(',', .{ .alt = true })) { self.audio.volume.quieter(); self.announceVolume(); return true; } if (key.matches('.', .{ .alt = true })) { self.audio.volume.louder(); self.announceVolume(); return true; } if (key.matches('/', .{ .alt = true })) { self.audio.volume.toggleMute(); self.announceVolume(); return true; } return false; } /// Says how loud the live audio is now, after a volume key. fn announceVolume(self: *App) void { var buffer: [8]u8 = undefined; self.session.say("volume {s}", .{self.audio.volume.describe(&buffer)}); } fn surface(self: *const App) terminal.Surface { const super = self.session.cpu.memory.superHiRes(); const wide = self.vx.screen.width_pix; const tall = self.vx.screen.height_pix; return .{ .columns = if (super) 80 else self.session.cpu.memory.mega2.columns(), .rows = screen.rows, .cell = .{ if (self.vx.screen.width == 0 or wide == 0) 1 else wide / self.vx.screen.width, if (self.vx.screen.height == 0 or tall == 0) 1 else tall / self.vx.screen.height, }, .dots = if (super) .{ zig65.superhires.width, zig65.superhires.height } else .{ zig65.video.width, zig65.video.height }, }; } /// The terminal's pointer, turned into the movement a mouse would have /// counted. /// /// A mouse says how far it has moved and a terminal says where the pointer /// is, so what the machine is told is the difference between where the /// pointer is now and where it was last seen. Coming back onto the screen /// after leaving it is not a movement: the pointer is picked up where it /// landed rather than dragged across from wherever it went out. /// /// The two cursors will drift apart, because the machine's is its own: it /// is clamped to whatever the program running has asked for and moves as /// far as that program decides each report is worth. That is what a /// relative pointing device is, and there is nothing to be done about it /// from this side. fn mouseMoved(self: *App, event: vaxis.Mouse) void { const adb = &self.session.cpu.memory.adb; // A button let go of is let go of wherever the pointer has got to, so // this comes before asking whether the pointer is over the screen. switch (event.type) { .press, .release => { const down = event.type == .press; switch (event.button) { .left => adb.holdButton(0, down), .right => adb.holdButton(1, down), else => {}, } }, else => {}, } const at = self.surface().dot(event.col, event.row, .{ event.xoffset, event.yoffset }) orelse { self.pointer = null; return; }; defer self.pointer = at; const was = self.pointer orelse return; adb.moveMouse(at[0] - was[0], at[1] - was[1]); } fn writeScreenshot(self: *App) void { const super = self.session.cpu.memory.superHiRes(); const which: picture.Display = if (super) .super_hires else .apple2; // What is on the screen, including which monitor it is being looked // at on. picture.write( self.session.io, self.session.gpa, which, &self.session.cpu.memory.mega2, self.screenshot, .{ .monitor = self.monitor }, ) catch |err| { self.session.say("could not write {s}: {s}", .{ self.screenshot, @errorName(err) }); return; }; self.session.say("wrote the {s} screen to {s}", .{ @tagName(which), self.screenshot }); } fn draw(self: *App, alloc: std.mem.Allocator) !void { // The hard disk's light, worked out once a frame: the transfers having // gone up since the last one is the heads having moved. const accesses = self.session.cpu.memory.hard_disk.accesses; self.session.volume_lit = accesses != self.session.volume_accesses; self.session.volume_accesses = accesses; // A drive on the port is lit the same way, and for the same reason: it // has no motor this side of the cable, only packets going back and // forth. var packets: u64 = 0; for (&self.session.cpu.memory.iwm.unidisk.drives) |*drive| packets += drive.replied; self.session.unidisk_lit = packets != self.session.unidisk_packets; self.session.unidisk_packets = packets; const win = self.vx.window(); win.clear(); const mega2 = &self.session.cpu.memory.mega2; const super = self.session.cpu.memory.superHiRes(); const showing = mega2.mode(); // Eighty columns of screen and a border, which is what a IIgs can want // at most, and a line underneath to say how it is going. const columns: u16 = if (super) 80 else mega2.columns(); const machine_width: u16 = columns + 2; // The border round the display, which on this machine is a real thing // a program sets rather than a decoration: the low four bits of // `$c034`. A terminal has no margin to paint, so what it gets is the // frame around the screen -- which is where a border is, and is the // one place a terminal can put one without taking room from the // machine's own picture. const border = self.session.cpu.memory.borderColour(); const pane = win.child(.{ .x_off = 0, .y_off = 0, .width = columns + 2, .height = 26, .border = .{ .where = .all, .style = .{ .fg = .{ .rgb = [_]u8{ border.r, border.g, border.b } } }, }, }); // A text screen is drawn as text: a terminal makes a better job of // characters than a picture of a character generator does, and sending // a picture of one would be a megabyte a frame for something the // terminal can draw for nothing. // Whether the text on the screen is drawn as text. A terminal makes a // better job of characters than a picture of a character generator // does, and sending a picture of a text screen would be a megabyte a // frame for something the terminal draws for nothing — unless the // character generator is what you want to see, which is what alt+x is // for. const as_text = !super and !self.text.asPixels() and (showing.isText() or showing.isMixed()); var drawn = false; // The picture goes below the text, so anything drawn over the screen — // the disk picker, say — stays in front of it. See the `z_index` on the // draw in `tools/terminal.zig`. if (self.vx.caps.kitty_graphics and (super or !showing.isText() or self.text.asPixels())) { const lines: u16 = if (super) zig65.superhires.height else if (as_text and showing.isMixed()) zig65.video.height - 4 * 8 else zig65.video.height; const rows: u16 = if (as_text and showing.isMixed()) 20 else 24; const into = pane.child(.{ .x_off = 0, .y_off = 0, .width = pane.width, .height = rows, }); const hash = if (super) terminal.superHash(mega2) else terminal.videoHash(mega2, showing, mega2.flashing()); if (self.display.draw( self.session.gpa, &self.vx, self.writer, pacing_clock, self.session.io, into, mega2, if (super) .super_hires else .apple2, lines, self.monitor, hash, )) |_| { drawn = true; } else |_| {} } if (!drawn) { if (super) terminal.superHalfBlocks(pane, mega2, columns) else if (!showing.isText()) terminal.halfBlocks(pane, mega2, showing, mega2.columns()); } // The whole screen for a text mode, and the bottom four rows of a // mixed one. if (as_text) { const from: u16 = if (showing.isText()) 0 else 20; terminal.textRows( pane, mega2, from, mega2.columns(), mega2.displayPage(), mega2.alternateCharacters(), mega2.flashing(), ); } // As wide as the window allows: the line has more to say than forty // columns hold, and clipping it hides the half that says what the keys // are. // Four rows inside the border: what it is doing, the two drives, and // a line for this program to say things on. It used to be one, which // meant the line it says things on was drawn outside the pane and // never seen at all. // One line for each drive the machine has something in, and always // the two floppy ones, since those are what alt+1 and alt+2 change. const hard: u16 = if (self.session.volumes[1] != null) 2 else if (self.session.volumes[0] != null) 1 else 0; // Worked out before the box rather than while filling it, because it // decides how tall the box has to be. Without that the last line drawn // falls off the bottom, which is what happened to the line this // program says things on as soon as a network was on the machine. const network_rows: u16 = if (self.session.network != null) 1 else 0; // What it holds: what the processor is doing, the two floppy drives, // a row for each hard disk and one for the network, a line to say // things on, and the keys. const status_rows: u16 = 1 + 2 + hard + network_rows + 1 + 1; // Wide enough for the longest line it holds, which is the key line: // eighty-six characters with the debugger's keys on it. Narrower than // that and it wraps, and a key line that wraps is a key line nobody // reads. const status_width: u16 = @max(machine_width, @min(win.width, 88)); const status = win.child(.{ .x_off = 0, .y_off = 26, .width = status_width, .height = status_rows + 2, .border = .{ .where = .all }, }); const dim: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x66, 0x66, 0x66 } } }; var line: [128]u8 = undefined; const said = try std.fmt.bufPrint(&line, "{d:.2} MHz {s} {s}{s}{s}", .{ self.session.measured_hz / 1_000_000.0, @tagName(self.monitor), if (super) "Super Hi-Res" else @tagName(showing), if (self.session.apple[0]) " open apple" else "", if (self.session.apple[1]) " solid apple" else "", }); // What the processor is doing, in front of everything else, and // coloured: a machine that is not running should say so where the eye // lands first rather than in a corner. const state_colour: [3]u8 = switch (self.session.state) { .running => .{ 0x44, 0xcc, 0x44 }, .halted => .{ 0xcc, 0x44, 0x44 }, .single_step => .{ 0xcc, 0xcc, 0x44 }, }; _ = status.print(&.{ .{ .text = self.session.state.name(), .style = .{ .fg = .{ .rgb = state_colour } } }, .{ .text = " " }, .{ .text = said, .style = dim }, }, .{ .row_offset = 0 }); // The two drives, with the light on the one that is turning. A 3.5-inch // drive's light is its spindle rather than its enable line: a IIgs can // have the drive selected and holding the disk with the disk standing // still, which a Disk II cannot. const lit: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0xcc, 0x44, 0x44 } } }; const dark: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 } } }; const turning = [2]bool{ self.session.cpu.memory.iwm.disks35.drives[0].spindle, self.session.cpu.memory.iwm.drives.motor, }; // The intelligent drive stands where the 3.5-inch one would, because // that is where it stands on the cable: putting one on the port takes // the machine's own empty 3.5-inch drives off it, and the two are // never both there to be shown. const on_port = &self.session.cpu.memory.iwm.unidisk.drives[0]; for ([2]Drive{ .three_and_a_half, .five_and_a_quarter }, 0..) |drive, which| { const row: u16 = @intCast(1 + which); const port = which == 0 and on_port.fitted; _ = status.print(&.{ .{ .text = try std.fmt.allocPrint(alloc, "{d} ", .{which + 1}), .style = dim }, .{ .text = "\u{2b24} ", .style = if (if (port) self.session.unidisk_lit else turning[which]) lit else dark, }, .{ .text = try std.fmt.allocPrint(alloc, "{s:<10} ", .{ if (port) "UniDisk" else drive.name(), }), .style = dim }, .{ .text = if (port) self.session.unidisk_slots[0].shown() else self.session.slots[which].shown(), .style = dim, }, }, .{ .row_offset = row }); } // And the hard disk, whose light is its transfers rather than a motor: // the heads move when there is something to fetch and are still the // rest of the time, so what lights it is the count having gone up // since the last frame was drawn. for (0..hard) |which| { _ = status.print(&.{ .{ .text = "7 ", .style = dim }, .{ .text = "\u{2b24} ", .style = if (self.session.volume_lit) lit else dark }, .{ .text = try std.fmt.allocPrint(alloc, "{s:<10} ", .{ if (which == 0) "hard disk" else " drive 2", }), .style = dim }, .{ .text = self.session.volume_slots[which].shown(), .style = dim }, }, .{ .row_offset = @intCast(3 + which) }); } // And the network, whose light is a frame having crossed in the last // quarter of a second, in either direction. What it says is what the // firmware has done with it: nothing until AppleTalk is turned on in // the Control Panel, then the node number it settled on. if (self.session.network) |*net| { const now = self.session.cpu.clock.cycles; const crossed = net.bridge.lit(now, cycles_per_second / 4); const what = if (net.bridge.attach(&self.session.cpu.memory.scc) == null) try std.fmt.allocPrint(alloc, "waiting for the firmware to turn AppleTalk on", .{}) else if (net.bridge.node) |node| try std.fmt.allocPrint(alloc, "node {d}, {d} out, {d} in", .{ node, net.bridge.sent, net.bridge.received }) else try std.fmt.allocPrint(alloc, "{d} in, nothing sent yet", .{net.bridge.received}); _ = status.print(&.{ .{ .text = "7 ", .style = dim }, .{ .text = "\u{2b24} ", .style = if (crossed) lit else dark }, .{ .text = "AppleTalk ", .style = dim }, .{ .text = what, .style = dim }, }, .{ .row_offset = @intCast(3 + hard) }); } // And either a path being typed, or why the processor stopped, or // whatever was last worth saying. const said_at: u16 = 3 + hard + network_rows; // Where it stopped, and what stopped it. The program counter has moved // past the opcode by the time this is known, so without carrying the // address there would be nothing on screen pointing at the instruction // responsible. if (self.session.stopped) |stop| { _ = status.printSegment(.{ .text = switch (stop) { .jam => |jam| try std.fmt.allocPrint( alloc, "${x:0>2} at ${x:0>2}/{x:0>4} stopped the processor; alt+b resets", .{ jam.opcode, @as(u8, @intCast(jam.address >> 16)), @as(u16, @truncate(jam.address)) }, ), .brk => |brk| try std.fmt.allocPrint( alloc, "BRK at ${x:0>2}/{x:0>4}, vectored to ${x:0>2}/{x:0>4}; alt+r carries on", .{ @as(u8, @intCast(brk.address >> 16)), @as(u16, @truncate(brk.address)), @as(u8, @intCast(brk.vector >> 16)), @as(u16, @truncate(brk.vector)), }, ), }, .style = .{ .fg = .{ .rgb = state_colour } }, }, .{ .row_offset = said_at }); } else if (self.snapshot_prompt) |prompt| { _ = status.print(&.{ .{ .text = if (prompt.loading) "load state: " else "save state: ", .style = dim }, .{ .text = prompt.buffer[0..prompt.len] }, .{ .text = "_ return acts, escape cancels", .style = dim }, }, .{ .row_offset = said_at }); } else if (self.prompt) |prompt| { _ = status.print(&.{ .{ .text = try std.fmt.allocPrint(alloc, "{s} disk: ", .{prompt.drive.name()}), .style = dim, }, .{ .text = prompt.buffer[0..prompt.len] }, .{ .text = "_ return puts it in, empty takes it out, escape cancels", .style = dim }, }, .{ .row_offset = said_at }); } else if (self.session.message_len != 0) { _ = status.printSegment( .{ .text = self.session.message[0..self.session.message_len], .style = dim }, .{ .row_offset = said_at }, ); } // The debugger's own panes, if they are wanted: beside the machine if // the terminal is wide enough for both and underneath it if not. // Underneath rather than above, because a terminal too short for all // of it should lose the memory view rather than the line that says // what the keys are. if (self.panes) { // Right of *both* boxes, not just the screen: the status line is // wider than a forty-column screen and the panes would otherwise // be drawn straight through it. const column = @max(machine_width, status_width); const beside = win.width >= column + panes_width; const left: i17 = if (beside) column else 0; const top: i17 = if (beside) 0 else 26 + @as(i17, status_rows + 2); const registers = win.child(.{ .x_off = left, .y_off = top, .width = panes_width, .height = 8, .border = .{ .where = .all }, }); try self.drawRegisters(alloc, registers); const memory = win.child(.{ .x_off = left, .y_off = top + 8, .width = panes_width, .height = 20, .border = .{ .where = .all }, }); try self.drawMemory(alloc, memory); } // And the keys, on the last line of the box, where somebody who has // forgotten one looks. The debugger's half only when its panes are up: // a IIgs being used as a IIgs has no use for being told how to step. _ = status.printSegment(.{ .text = if (self.panes) "alt+ space step r run p pause b reset d hide +/- rate 1/2 disk g screen q quit" else "alt+ b reset o/s apple 1/2 disk m/x video d debug g screen q quit", .style = dim, }, .{ .row_offset = status_rows - 1 }); // Last of all, over everything, the disk picker if one is open. try self.drawPicker(alloc, win); } /// The processor, drawn as it is rather than as a 6502 with more of it. /// /// A 65816's registers do not have fixed widths: M and X say whether the /// accumulator and the index registers are eight bits or sixteen, and the /// same register reads as a different number depending. So each is shown /// at the width the flags say it has, with the accumulator's hidden half /// shown beside it in the narrow case -- because that half is still there, /// still holds what was put in it, and is exactly what makes the second /// accumulator a place to keep something. /// /// The three that place things -- D, DBR and PBR -- have no eight-bit /// equivalent at all and are the difference between an address and a /// number on this processor, so they are given a row of their own rather /// than being tucked in beside the others. fn drawRegisters(self: *App, alloc: std.mem.Allocator, pane: vaxis.Window) !void { const cpu = self.session.cpu; const label: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x66, 0x66, 0x66 } } }; const narrow_a = cpu.flags.isSet(.M); const narrow_xy = cpu.flags.isSet(.X); _ = pane.printSegment(.{ .text = "Registers", .style = label }, .{ .row_offset = 0 }); // The accumulator, at whatever width it is being used at. The high // half is shown greyed beside a narrow one rather than hidden: B is // not gone, it is just not what A means this instruction. const a = cpu.registers.get(.A); _ = pane.print(&.{ .{ .text = "A ", .style = label }, .{ .text = if (narrow_a) try std.fmt.allocPrint(alloc, " ${x:0>2}", .{@as(u8, @truncate(a))}) else try std.fmt.allocPrint(alloc, "${x:0>4}", .{a}) }, .{ .text = if (narrow_a) try std.fmt.allocPrint(alloc, " B ${x:0>2}", .{@as(u8, @truncate(a >> 8))}) else " ", .style = label }, }, .{ .row_offset = 1 }); // The index registers, which have no hidden half: narrowing them // clears the top byte outright, which is the one asymmetry between // them and the accumulator and is the processor's rather than this // model's. inline for ([_]@TypeOf(.enum_literal){ .X, .Y }, 0..) |which, i| { const value = cpu.registers.get(which); _ = pane.print(&.{ .{ .text = @tagName(which) ++ " ", .style = label }, .{ .text = if (narrow_xy) try std.fmt.allocPrint(alloc, " ${x:0>2}", .{@as(u8, @truncate(value))}) else try std.fmt.allocPrint(alloc, "${x:0>4}", .{value}) }, }, .{ .row_offset = @intCast(2 + i) }); } // The stack pointer as the register reads, which in emulation mode is // forced into page one however far it has wandered. _ = pane.print(&.{ .{ .text = "S ", .style = label }, .{ .text = try std.fmt.allocPrint(alloc, "${x:0>4}", .{cpu.stack.get()}) }, }, .{ .row_offset = 4 }); // Where instructions come from, which is a bank and a counter and not // one number: the counter does not carry into the bank, so a program // at the top of a bank wraps to the bottom of the same one. _ = pane.print(&.{ .{ .text = "PC ", .style = label }, .{ .text = try std.fmt.allocPrint(alloc, "${x:0>2}/{x:0>4}", .{ cpu.registers.program_bank, cpu.program_counter.value, }) }, }, .{ .row_offset = 1, .col_offset = 16 }); // And where data goes when the instruction does not say. _ = pane.print(&.{ .{ .text = "DBR ", .style = label }, .{ .text = try std.fmt.allocPrint(alloc, "${x:0>2}", .{cpu.registers.data_bank}) }, }, .{ .row_offset = 2, .col_offset = 16 }); // The direct page, which is the 6502's zero page allowed to move. _ = pane.print(&.{ .{ .text = "D ", .style = label }, .{ .text = try std.fmt.allocPrint(alloc, "${x:0>4}", .{cpu.registers.direct}) }, }, .{ .row_offset = 3, .col_offset = 16 }); // The status register, and the emulation line beside it. E is not a // bit of P at all -- it is reached only through XCE, which swaps it // with the carry -- but it is the single most important thing about // what the processor is doing, since it decides whether this is a // 65816 or a 6502 pretending, so it is shown with the rest. const set: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0xcc, 0x44 } } }; const clear: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 } } }; _ = pane.printSegment(.{ .text = "Flags", .style = label }, .{ .row_offset = 4, .col_offset = 16 }); var col: u16 = 22; inline for (@typeInfo(@TypeOf(cpu.flags).Name).@"enum".fields) |field| { _ = pane.printSegment(.{ .text = field.name, .style = if (cpu.flags.isSet(@field(@TypeOf(cpu.flags).Name, field.name))) set else clear, }, .{ .row_offset = 4, .col_offset = col }); col += 1; } _ = pane.printSegment(.{ .text = " E", .style = if (cpu.flags.emulation) set else clear, }, .{ .row_offset = 4, .col_offset = col }); // In emulation mode M and X are forced set and mean nothing, which is // worth saying rather than leaving two flags looking meaningful. if (cpu.flags.emulation) { _ = pane.printSegment( .{ .text = "emulating: M and X are forced", .style = label }, .{ .row_offset = 5, .col_offset = 16 }, ); } // And the two ways a processor can be doing nothing while still being // perfectly well: waiting for an interrupt, or stopped until reset. if (cpu.waiting) { _ = pane.printSegment( .{ .text = "WAI: waiting for an interrupt", .style = label }, .{ .row_offset = 5, .col_offset = 16 }, ); } } /// A page of memory, in hexadecimal and as characters. /// /// Sixteen bytes to a row and sixteen rows to a page, addressed as the /// processor addresses them: a bank and an offset inside it. `peek` is /// used rather than `read`, so that looking at a page of I/O does not /// throw the switches that live there -- a debugger that changed the /// machine by being looked at would be worse than no debugger. fn drawMemory(self: *App, alloc: std.mem.Allocator, pane: vaxis.Window) !void { const label: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x66, 0x66, 0x66 } } }; const faint: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 } } }; _ = pane.print(&.{ .{ .text = "Memory ", .style = label }, .{ .text = try std.fmt.allocPrint(alloc, "${x:0>2}/{x:0>2}00", .{ self.memory_bank, self.memory_page }) }, .{ .text = " alt+ pgup/pgdn page [ ] bank f follow", .style = faint }, }, .{ .row_offset = 0 }); const base = @as(u24, self.memory_bank) << 16 | @as(u24, self.memory_page) << 8; for (0..16) |row| { var hex: [16 * 3]u8 = undefined; var text: [16]u8 = undefined; for (0..16) |column| { // Wrapping inside the bank rather than carrying out of it, // which is what the processor does with an address. const at: u24 = (base & 0xff0000) | ((base +% @as(u24, @intCast(row * 16 + column))) & 0xffff); const byte = self.session.cpu.memory.peek(at); _ = std.fmt.bufPrint(hex[column * 3 ..][0..3], "{x:0>2} ", .{byte}) catch {}; // High bit set is how an Apple stores a character it means, so // the top half is shown as text with the bit taken off and the // bottom half -- which is control codes and the like -- as a // dot. const stripped = byte & 0x7f; text[column] = if (stripped >= 0x20 and stripped < 0x7f) stripped else '.'; } _ = pane.print(&.{ .{ .text = try std.fmt.allocPrint(alloc, "{x:0>4}", .{ @as(u16, @truncate(base +% @as(u24, @intCast(row * 16)))), }), .style = faint }, .{ .text = " " }, .{ .text = try alloc.dupe(u8, &hex) }, .{ .text = " " }, .{ .text = try alloc.dupe(u8, &text), .style = label }, }, .{ .row_offset = @intCast(2 + row) }); } } /// The disk picker: a box over the screen listing the library and the /// fixed choices, the one under the highlight in reverse video. It is /// drawn from the same `Picker.choices` list the keys act on, so what the /// highlight is over is exactly what return will do. fn drawPicker(self: *App, alloc: std.mem.Allocator, win: vaxis.Window) !void { const picker = self.picker orelse return; // A box drawn over the machine's screen has to paint its own // background. The picture of that screen goes beneath the text — see // the `z_index` in `tools/terminal.zig` — but it is still above any // cell left at the terminal's default background, and `clear` fills // with exactly those: `fill(.{ .default = true })`. A box that set // only foreground colours therefore had the screen showing straight // through it. Filling with a background of its own is what makes it // opaque, and it is why `chosen` names both colours rather than asking // for reverse video, which would have swapped in whatever the terminal // happened to be using. const ink = [_]u8{ 0xcc, 0xcc, 0xcc }; const faint = [_]u8{ 0x88, 0x88, 0x88 }; const paper = [_]u8{ 0x1c, 0x1c, 0x1c }; const normal: vaxis.Style = .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = paper } }; const dim: vaxis.Style = .{ .fg = .{ .rgb = faint }, .bg = .{ .rgb = paper } }; const chosen: vaxis.Style = .{ .fg = .{ .rgb = paper }, .bg = .{ .rgb = ink } }; var buffer: [picker_choices_max]Choice = undefined; const list = Picker.choices(self.library, self.occupied(picker.drive), &buffer); // Which of the library's disks is already in this drive, so that the // list can say so rather than leaving somebody to remember it. This // machine keeps only the name of what it was given and not the path it // came from, so the comparison is between file names — two library // entries with the same file name in different directories would both // be marked, which is a smaller wrong than marking neither. const in_drive: ?usize = found: { const slot: usize = switch (picker.drive) { .three_and_a_half => 0, .five_and_a_quarter => 1, }; if (self.session.slots[slot].len == 0) break :found null; const here = self.session.slots[slot].shown(); for (self.library, 0..) |entry, n| { if (std.mem.eql(u8, std.fs.path.basename(entry.path), here)) break :found n; } break :found null; }; var labels: [picker_choices_max][]const u8 = undefined; var widest: usize = "New blank writable disk".len; for (list, 0..) |choice, i| { labels[i] = switch (choice) { .disk => |n| try std.fmt.allocPrint(alloc, "{s} ({s})", .{ self.library[n].name, if (self.library[n].writable orelse false) "rw" else "ro", }), .eject => "Eject the disk", .blank => "New blank writable disk", .path => "Type a path…", }; widest = @max(widest, labels[i].len); } const title = try std.fmt.allocPrint(alloc, "{s} drive — insert a disk", .{picker.drive.name()}); const footer = "\u{2191}\u{2193} move \u{23ce} choose esc cancel"; const disks = self.library.len; const rule = disks > 0 and disks < list.len; // Two columns in front of every label, for the mark against whichever // disk is in the drive. const marked = 2; const inside_width: u16 = @intCast(@max(@max(widest + marked, title.len), footer.len) + 2); // Interior rows: the title, a blank, every choice, the rule if any, a // blank, and the footer. const rows: u16 = @intCast(list.len + @as(usize, if (rule) 1 else 0) + 4); const width = inside_width + 2; const height = rows + 2; const box = win.child(.{ .x_off = @intCast(@max(0, (@as(i17, win.width) - width) >> 1)), .y_off = @intCast(@max(0, (@as(i17, win.height) - height) >> 1)), .width = width, .height = height, .border = .{ .where = .all, .style = normal }, }); box.fill(.{ .style = normal }); _ = box.printSegment(.{ .text = title, .style = dim }, .{ .row_offset = 0, .col_offset = 1 }); var row: u16 = 2; for (list, 0..) |_, i| { if (rule and i == disks) { var x: u16 = 1; while (x <= inside_width) : (x += 1) { box.writeCell(x, row, .{ .char = .{ .grapheme = "\u{2500}", .width = 1 }, .style = dim }); } row += 1; } if (i == picker.selection) { var x: u16 = 1; while (x <= inside_width) : (x += 1) { box.writeCell(x, row, .{ .char = .{ .grapheme = " ", .width = 1 }, .style = chosen }); } } const style = if (i == picker.selection) chosen else normal; // The mark for what is already in the drive, in a column of its // own so every label starts in the same place whether or not one // of them carries it. if (in_drive) |which| { if (list[i] == .disk and list[i].disk == which) { _ = box.printSegment(.{ .text = "\u{25cf}", .style = style }, .{ .row_offset = row, .col_offset = 1 }); } } _ = box.printSegment(.{ .text = labels[i], .style = style }, .{ .row_offset = row, .col_offset = 1 + marked }); row += 1; } _ = box.printSegment(.{ .text = footer, .style = dim }, .{ .row_offset = row + 1, .col_offset = 1 }); } fn update(self: *App, event: Event) void { switch (event) { .mouse => |pointer| self.mouseMoved(pointer), .winsize => |size| self.vx.resize(self.session.gpa, self.writer, size) catch {}, .key_press => |key| { // Quitting comes before any of it. A dialog that swallows the // key which closes the program is a dialog somebody has to // work out how to get out of first, and the picker wants only // unmodified keys anyway — the arrows, return and escape — so // nothing is being taken from it. if (key.matches('q', .{ .alt = true })) { self.quit = true; return; } // A disk being chosen takes the keys next, then a path being // typed; only after both does anything reach the machine. if (self.picker != null) { self.pickerKey(key); return; } if (self.snapshot_prompt != null) { self.snapshotPromptKey(key); return; } if (self.prompt != null) { self.promptKey(key); return; } if (key.matches('1', .{ .alt = true })) { self.picker = .{ .drive = .three_and_a_half }; return; } if (key.matches('2', .{ .alt = true })) { self.picker = .{ .drive = .five_and_a_quarter }; return; } if (key.matches('b', .{ .alt = true })) { self.session.reset(); self.session.say("reset", .{}); return; } // The debugger's own keys. All of them behind alt, like every // other key this program keeps for itself: the machine owns // the keyboard and this owns the modifier. if (self.debuggerKey(key)) return; if (key.matches('g', .{ .alt = true })) { self.writeScreenshot(); return; } if (key.matches('o', .{ .alt = true })) { self.session.holdApple(0); return; } if (key.matches('s', .{ .alt = true })) { self.session.holdApple(1); return; } if (key.matches('x', .{ .alt = true })) { self.text = self.text.other(); self.session.say("{s}", .{self.text.describe()}); return; } if (key.matches('m', .{ .alt = true })) { self.monitor = self.monitor.other(); self.session.say("looking at it on {s}", .{self.monitor.describe()}); return; } if (key.mods.alt) return; if (terminal.appleKey(key)) |byte| { if (self.session.typed_len < self.session.typed.len) { const Modifier = zig65.adb.Adb.Modifier; var mods: u8 = Modifier.held; if (key.mods.ctrl) mods |= Modifier.control; if (key.mods.shift) mods |= Modifier.shift; self.session.typed[self.session.typed_len] = byte; self.session.typed_mods[self.session.typed_len] = mods; self.session.typed_len += 1; } } }, } } fn run(self: *App) !void { var loop: vaxis.Loop(Event) = .init(self.session.io, &self.tty, &self.vx); try loop.installResizeHandler(); try loop.start(); defer loop.stop(); try self.vx.enterAltScreen(self.writer); try self.vx.queryTerminal(self.writer, .fromSeconds(1)); // A IIgs has a mouse the way it has a keyboard — there is no version // of the machine without one — so the pointer is handed over without // being asked for. What that costs is selecting text with the mouse, // which most terminals still allow with shift held. try self.vx.setMouseMode(self.writer, true); self.session.last_step = .now(self.session.io, pacing_clock); self.session.next_frame = self.session.last_step; self.session.measured_at = self.session.last_step; self.session.started = self.session.last_step; self.session.started_cycles = self.session.cpu.clock.cycles; while (!self.quit) { self.session.stepDue(); // Play whatever the Ensoniq made since the last look. The chip is // sampled inside the machine, into the recording's own buffer; // here, outside it, is where those samples reach the speaker. if (self.audio.live()) if (self.session.recording) |*rec| { self.audio.playMono(rec.captured()); rec.clearCaptured(); }; self.session.measureSpeed(); if (self.session.frameDue()) { var arena: std.heap.ArenaAllocator = .init(self.session.gpa); defer arena.deinit(); try self.draw(arena.allocator()); try self.vx.render(self.writer); try self.writer.flush(); } while (try loop.tryEvent()) |event| self.update(event); // Nothing to do until the next frame is due, so wait for it rather // than spinning: the machine is paced by the wall, not by us. const now: std.Io.Timestamp = .now(self.session.io, pacing_clock); const wait = self.session.next_frame.nanoseconds - now.nanoseconds; if (wait > 0) try self.session.io.sleep(.{ .nanoseconds = wait }, pacing_clock); } } }; /// What this front end needs from a command line. /// /// Named rather than passed the whole of the debugger's options struct, so /// that this file says what it uses and so that the two do not have to import /// each other. `main` in `main.zig` reads the command line for both machines /// and fills this in. pub const Params = struct { /// A IIgs system ROM, in any of the arrangements `iigsrom.identify` knows. rom: []const u8, /// A disk for whichever built-in drive it fits: an 800K 3.5-inch image or /// a 140K 5.25-inch one, settled by how big it is. disk: ?[]const u8 = null, /// The two drives of the ProDOS block device in slot 7. hard_disks: [2]?[]const u8 = .{ null, null }, /// The two intelligent drives on the disk port, if the machine is to have /// any: 800K images for a UniDisk 3.5 and the one daisy-chained behind it. unidisks: [2]?[]const u8 = .{ null, null }, /// The named disks the alt-1/alt-2 picker offers, from the config file. library: []const config.Disk = &.{}, /// Where alt+g writes a picture of the screen. screenshot: []const u8 = "screen.png", /// A save state to boot straight into, once the machine is built. snapshot: ?[]const u8 = null, /// Which monitor it is being looked at on, and who draws the text. monitor: terminal.Monitor = .monochrome, text: terminal.TextDrawing = .pixels, /// Where the Ensoniq's output is written, if anywhere. This is the `.wav` /// file, kept whatever live audio does. audio: ?[]const u8 = null, /// Live audio: the Ensoniq out of a real speaker, on by default where a /// daemon answers, and how loud it starts and whether muted. sound: bool = true, volume: u8 = 80, mute: bool = false, /// The two ends of the modem port's wire, which is channel B of the SCC. /// The printer port is channel A of the same chip and is reached the same /// way; nothing here writes to it yet. serial_in: ?[]const u8 = null, serial_out: ?[]const u8 = null, /// Where the printer port's output goes, which is channel A. printer_out: ?[]const u8 = null, /// Whether the machine is on a LocalTalk network — the multicast group /// other emulators share — and where to write every frame that crosses. localtalk: bool = false, localtalk_log: ?[]const u8 = null, /// The address of the interface to be on the network through, if the /// system is not to choose. localtalk_interface: ?[]const u8 = null, /// Whether to set the Control Panel to AppleTalk before the machine /// comes up, and where the parameter RAM is kept between runs. appletalk: bool = false, battery_ram: ?[]const u8 = null, /// Whether to fit an Uthernet II (a WIZnet W5100) in slot 1, its sockets /// mapped to the host's. Its slot must be set to "Your Card" in the /// Control Panel, as on a real machine. uthernet: bool = false, /// Whether to fit an Uthernet (the original, a CS8900A) in slot 1, its raw /// frames on a UDP multicast group. The same Control Panel proviso applies. uthernet1: bool = false, /// The interface to carry that virtual Ethernet on, and a hardware address /// for whichever Ethernet card is fitted. ethernet_interface: ?[]const u8 = null, mac: ?[]const u8 = null, /// A Hayes modem on the SCC's modem port, dialing over TCP, and the port it /// answers incoming calls on if it is to listen. modem: bool = false, modem_answer: ?u16 = null, /// How much RAM the machine has altogether, in bytes, counting the Mega /// II's 128K. Nothing means a machine with nothing in its expansion slot. memory: ?usize = null, /// Whether to come up stopped at the reset vector rather than running, /// with the debugger's panes already open. `alt+r` starts it. halted: bool = false, }; /// Sets the Control Panel to AppleTalk the way an owner did, with the machine /// having come up once to write its defaults: slot 7 to the built-in /// AppleTalk, and slot 1 to the choice that hands the printer port over to /// it. ROM 01 and ROM 3 code that choice differently — one gives slot 1 two /// options and the other three — and each throws the whole parameter RAM /// away over a value it does not know, so the newer code is tried first and /// the older is what a ROM 01 gets after it has done that. fn presetAppleTalk(cpu: *CPU) void { const Rtc = zig65.rtc.Rtc; var ran: usize = 0; while (ran < 4_000_000 and !Rtc.sealed(&cpu.memory.rtc.ram)) : (ran += 1) { cpu.executeInstruction() catch break; } if (!Rtc.sealed(&cpu.memory.rtc.ram)) return; for ([_]u8{ 2, 1 }) |choice| { cpu.memory.rtc.ram[Rtc.slot_7] = 0; cpu.memory.rtc.ram[Rtc.slot_1] = choice; cpu.memory.rtc.ram[Rtc.slot_1_appletalk] = choice; Rtc.seal(&cpu.memory.rtc.ram); cpu.reset(); ran = 0; while (ran < 400_000 and cpu.memory.rtc.ram[Rtc.slot_7] == 0) : (ran += 1) { cpu.executeInstruction() catch break; } if (cpu.memory.rtc.ram[Rtc.slot_7] == 0) break; } cpu.reset(); } /// Runs an Apple IIgs in the terminal until the user quits. pub fn run(init: std.process.Init, params: Params) !void { const io = init.io; const screenshot = params.screenshot; const monitor = params.monitor; const text = params.text; const audio_path = params.audio; const disk_path = params.disk; const hard_disks = params.hard_disks; const machine_rom = params.rom; const gpa = std.heap.smp_allocator; const rom = try std.Io.Dir.cwd().readFileAlloc(io, machine_rom, gpa, .unlimited); defer gpa.free(rom); const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); // A memory expansion card, if one was asked for. There is no register to // set: the firmware sizes memory at power-on by writing to each bank and // reading it back, so fitting a card is nothing more than letting the RAM // answer. What is asked for is the machine's total, and the Mega II's 128K // is part of that and is not on the card. if (params.memory) |bytes| { const bank = zig65.memory16.bank_size; const mega2 = 2 * bank; const fast = if (bytes > mega2) bytes - mega2 else 0; try cpu.memory.expand(@intCast(@min(@as(usize, Memory.max_banks), fast / bank))); } defer cpu.deinit(); try cpu.memory.loadROM(rom); // An Uthernet II, if one was asked for: a WIZnet W5100 in slot 1, whose // host sockets the session pumps. As on a real IIgs, the slot has to be // set to "Your Card" in the Control Panel for the firmware to let the card // answer — the same battery-RAM setting AppleTalk needs — so this fits the // card and leaves that to the owner. if (params.uthernet) cpu.memory.fitUthernet(1); // And an Uthernet (the original), likewise in slot 1; the multicast group // its CS8900A's frames cross is opened once the session is up. if (params.uthernet1) cpu.memory.fitCs8900(1); // A hardware address for whichever Ethernet card was fitted, over what it // comes up with; a driver may still write its own. if (params.mac) |given| { const address = zig65.ethernet.parseMac(given) orelse { std.debug.print("gs: --mac wants a hardware address like 00:11:22:33:44:55, not '{s}'\n", .{given}); std.process.exit(2); }; if (cpu.memory.ethernetChip()) |c| c.setMac(address); if (cpu.memory.cs8900Chip()) |c| c.setMac(address); } // The clock, set from the host once and then kept by the machine's own // cycles. Read as UTC, since this machine knows nothing of time zones. const nanoseconds = std.Io.Timestamp.now(io, .real).nanoseconds; const unix: i64 = @intCast(@divFloor(nanoseconds, std.time.ns_per_s)); cpu.memory.rtc.set(@intCast(unix + zig65.rtc.Rtc.epoch_1904), 0); const floppy = try gpa.create(disk2.Floppy); defer gpa.destroy(floppy); floppy.* = .{}; const floppy35 = try gpa.create(disk35.Floppy); defer gpa.destroy(floppy35); floppy35.* = .{}; // The parameter RAM, which on a real machine has a battery behind it // and here has a file: what the Control Panel was set to last time is // what it is set to now. A file the firmware would not accept — the // wrong size, or a checksum that does not agree — is left alone, and // the firmware writes its defaults as it would over a flat battery. if (params.battery_ram) |path| { if (std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(zig65.rtc.Rtc.ram_size + 1))) |kept| { defer gpa.free(kept); if (kept.len == zig65.rtc.Rtc.ram_size and zig65.rtc.Rtc.sealed(kept[0..zig65.rtc.Rtc.ram_size])) { @memcpy(&cpu.memory.rtc.ram, kept); } else { std.debug.print("gs: '{s}' is not a parameter RAM the firmware would keep, so it is starting afresh\n", .{path}); } } else |err| if (err != error.FileNotFound) { std.debug.print("gs: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); } } cpu.reset(); // AppleTalk is a Control Panel setting, and the Control Panel is the // parameter RAM, so this does what an owner did: lets the machine come up // once and write its defaults, sets slot 7 to the built-in AppleTalk and // slot 1 to the choice that gives it the printer port, and starts the // machine again. A parameter RAM that already says so is left as it is. if (params.appletalk and cpu.memory.rtc.ram[zig65.rtc.Rtc.slot_7] != 0) presetAppleTalk(cpu); const app = try gpa.create(App); defer gpa.destroy(app); app.* = .{ .session = .{ .io = io, .gpa = gpa, .cpu = cpu, .floppy35 = floppy35, .floppy = floppy, // A machine asked to come up stopped sits on its reset vector // until somebody says otherwise. Single step rather than halted, // because halted is the one state a processor cannot be started // out of and this one has nothing wrong with it. .state = if (params.halted) .single_step else .running, }, .screenshot = screenshot, .params = params, .monitor = monitor, .text = text, .library = params.library, // Coming up stopped means coming up wanting to see the processor; // there is nothing else to look at on a machine that is not running. .panes = params.halted, }; if (params.serial_out) |path| { app.session.serial_out = std.Io.Dir.cwd().createFile(io, path, .{}) catch |err| { std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (params.serial_in) |path| { app.session.serial_in = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited) catch |err| { std.debug.print("gs: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (params.printer_out) |path| { app.session.printer_out = std.Io.Dir.cwd().createFile(io, path, .{}) catch |err| { std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (params.localtalk) { // The tag on every datagram this end sends, which only has to tell // this process from any other on the group: the clock, and the // process number for two started in the same instant. const tag: u32 = @truncate(@as(u96, @bitCast(nanoseconds)) ^ (@as(u96, @intCast(std.os.linux.getpid())) << 20)); var interface: ?[4]u8 = null; if (params.localtalk_interface) |given| { interface = zig65.ethernet.parseAddress(given) orelse { std.debug.print("gs: --localtalk-interface wants an address like 127.0.0.1, not '{s}'\n", .{given}); std.process.exit(1); }; } app.session.network = ltoudp.Network.open(tag, interface) catch |err| { std.debug.print("gs: cannot join the LocalTalk group: {s}\n", .{@errorName(err)}); std.process.exit(1); }; } if (params.localtalk_log) |path| { app.session.network_log = std.Io.Dir.cwd().createFile(io, path, .{}) catch |err| { std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (params.uthernet1) { const tag: u32 = @truncate(@as(u96, @bitCast(nanoseconds)) ^ (@as(u96, @intCast(std.os.linux.getpid())) << 20)); var interface: ?[4]u8 = null; if (params.ethernet_interface) |given| { interface = zig65.ethernet.parseAddress(given) orelse { std.debug.print("gs: --ethernet-interface wants an address like 127.0.0.1, not '{s}'\n", .{given}); std.process.exit(1); }; } app.session.ethernet = zig65.ethernet.Bridge.open(tag, interface) catch |err| blk: { std.debug.print("gs: cannot join the Ethernet group: {s}\n", .{@errorName(err)}); break :blk null; }; } if (params.modem) { app.session.modem = .{}; if (params.modem_answer) |answer_port| app.session.modem_line.listen(answer_port); } // What the Control Panel was set to, kept for next time. defer if (params.battery_ram) |path| { std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = &cpu.memory.rtc.ram }) catch |err| { std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); }; }; // Live audio, on by default: the Ensoniq out of a real speaker. Falls back // to silence if there is no daemon, and is kept for the life of the program // -- see the App field. `--audio` still records a file whatever this is. if (params.sound) { var volume = audio.Volume.fromPercent(params.volume); volume.muted = params.mute; app.audio = audio.Output.open(gpa, "zig65 IIgs", volume); } // A recording that writes a file, plays live, or both. One channel, because // a IIgs has one speaker: the chip has sixteen output channels and a stereo // card decoded three of the bits that name them, but that was a card people // bought rather than part of the machine, and there is none here. The rate // is the live graph's when there is one, so the two agree, and the file // takes it too. if (audio_path != null or app.audio.live()) { const rate: u64 = if (app.audio.live()) app.audio.rate else sample_rate; var file: ?*zig65.wav.Writer = null; if (audio_path) |path| file = zig65.wav.Writer.create(io, gpa, path, @intCast(rate), 1) catch |err| { std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; app.session.recording = .{ .file = file, .capture = app.audio.live(), .cycles_per_second = cycles_per_second, .rate = rate, .started = cpu.clock.cycles, }; // The machine does the sampling, because the only place the chip can // be looked at as often as the recording wants is where the chip is // wound forward. cpu.memory.sound = &app.session.recording.?; } if (disk_path) |path| app.session.insert(path, null) catch |err| { std.debug.print("gs: cannot read '{s}': {s}\n", .{ path, diskfile.explain(err) }); std.process.exit(1); }; // The drives on the port come after the machine's own, because putting one // there takes the empty 3.5-inch drives off the cable and a disk that went // in one of those has to have gone in first to keep it. for (params.unidisks, 0..) |maybe, which| { const path = maybe orelse continue; app.session.insertUnidisk(@intCast(which), path, null) catch |err| { std.debug.print("gs: cannot put '{s}' in the UniDisk 3.5: {s}\n", .{ path, diskfile.explain(err) }); std.process.exit(1); }; } for (hard_disks, 0..) |maybe, which| { const path = maybe orelse continue; app.session.mount(@intCast(which), path) catch |err| { std.debug.print("gs: cannot read '{s}': {s}\n", .{ path, diskfile.explain(err) }); std.process.exit(1); }; } // And a save state on top, if one was named: the machine is built the // ordinary way first so its shape matches, then the snapshot is read in. if (params.snapshot) |path| app.session.loadSnapshot(path) catch |err| { std.debug.print("gs: cannot load the snapshot '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; // Everything the session opened — disks written back and taken out, the // recording finished, the ports and the network closed — in one place. The // terminal below is torn down separately. defer app.session.deinit(); // The live stream is the front end's, not the session's, so it is closed // here. The recording only ever borrowed samples into a buffer of its own. defer app.audio.close(); app.tty = try vaxis.Tty.init(io, &app.tty_buffer); defer app.tty.deinit(); app.writer = app.tty.writer(); app.vx = try vaxis.init(io, gpa, init.environ_map, .{}); defer { app.display.deinit(gpa); app.vx.deinit(gpa, app.writer); } try app.run(); const ended: std.Io.Timestamp = .now(io, pacing_clock); // What it managed, said on the way out, because a machine that cannot keep // up with the one it is pretending to be is a different machine and the // only honest thing is to say so. const seconds = @as(f64, @floatFromInt(ended.nanoseconds - app.session.started.nanoseconds)) / std.time.ns_per_s; const ran = cpu.clock.cycles - app.session.started_cycles; std.debug.print("ran {d} cycles in {d:.1} seconds, which is {d:.2} MHz against {d:.2} asked for\n", .{ ran, seconds, @as(f64, @floatFromInt(ran)) / seconds / 1_000_000.0, @as(f64, cycles_per_second) / 1_000_000.0, }); } const testing = std.testing; /// An app with a processor in it and nothing else, for the tests below. Every /// field the keys touch is set; the rest is left `undefined`, which is what /// the eight-bit front end's own tests do and for the same reason — a real one /// is assembled by `run` out of files and terminals that a test has neither of. fn bareApp(gpa: std.mem.Allocator, cpu: *CPU) App { return .{ .session = .{ .io = testing.io, .gpa = gpa, .cpu = cpu, .floppy35 = undefined, .floppy = undefined, }, .screenshot = "screen.png", .params = undefined, }; } /// A key with alt held, which is every key this program keeps for itself. fn alt(codepoint: u21) vaxis.Key { return .{ .codepoint = codepoint, .mods = .{ .alt = true } }; } test "space stops a running machine and then steps it" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); var app = bareApp(gpa, cpu); cpu.memory.poke(0x0300, 0xea); // NOP cpu.memory.poke(0x0301, 0xea); cpu.program_counter.jump(0x0300); // The first press takes it out of running, and runs the one instruction // that press asked for. try testing.expect(app.debuggerKey(alt(' '))); try testing.expectEqual(session16.State.single_step, app.session.state); try testing.expectEqual(@as(u16, 0x0301), cpu.program_counter.value); // And it opens the panes, since somebody stepping wants to see what they // stepped into. try testing.expect(app.panes); try testing.expect(app.debuggerKey(alt(' '))); try testing.expectEqual(@as(u16, 0x0302), cpu.program_counter.value); // Running again, and pausing without stepping. try testing.expect(app.debuggerKey(alt('r'))); try testing.expectEqual(session16.State.running, app.session.state); try testing.expect(app.debuggerKey(alt('p'))); try testing.expectEqual(session16.State.single_step, app.session.state); try testing.expectEqual(@as(u16, 0x0302), cpu.program_counter.value); } test "a halted machine has nowhere to step to" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); var app = bareApp(gpa, cpu); cpu.memory.poke(0x0400, 0xdb); // STP cpu.program_counter.jump(0x0400); app.session.step(); try testing.expectEqual(session16.State.halted, app.session.state); // Neither space nor r moves it. Only the reset key does, which is the // whole meaning of halted. const was = cpu.program_counter.value; try testing.expect(app.debuggerKey(alt(' '))); try testing.expectEqual(session16.State.halted, app.session.state); try testing.expectEqual(was, cpu.program_counter.value); try testing.expect(app.debuggerKey(alt('r'))); try testing.expectEqual(session16.State.halted, app.session.state); app.session.reset(); try testing.expectEqual(session16.State.single_step, app.session.state); try testing.expect(app.debuggerKey(alt('r'))); try testing.expectEqual(session16.State.running, app.session.state); } test "the memory view walks pages within a bank and banks with the brackets" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); var app = bareApp(gpa, cpu); try testing.expectEqual(@as(u8, 0), app.memory_page); try testing.expectEqual(@as(u8, 0), app.memory_bank); // A page back from the bottom of a bank is the top of the same bank, not // the top of the one below: the program counter does not carry into the // bank register and neither does this. try testing.expect(app.debuggerKey(alt(vaxis.Key.page_up))); try testing.expectEqual(@as(u8, 0xff), app.memory_page); try testing.expectEqual(@as(u8, 0), app.memory_bank); try testing.expect(app.debuggerKey(alt(vaxis.Key.page_down))); try testing.expectEqual(@as(u8, 0), app.memory_page); try testing.expectEqual(@as(u8, 0), app.memory_bank); // The bank moves on its own key, and wraps on its own. try testing.expect(app.debuggerKey(alt('['))); try testing.expectEqual(@as(u8, 0xff), app.memory_bank); try testing.expect(app.debuggerKey(alt(']'))); try testing.expectEqual(@as(u8, 0), app.memory_bank); // And it can be sent to wherever the processor is, which follows the // *program* bank rather than the data one. cpu.registers.program_bank = 0xe1; cpu.program_counter.jump(0x4c00); try testing.expect(app.debuggerKey(alt('f'))); try testing.expectEqual(@as(u8, 0xe1), app.memory_bank); try testing.expectEqual(@as(u8, 0x4c), app.memory_page); } test "the speed keys double, halve, and come back to the machine's own speed" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); var app = bareApp(gpa, cpu); try testing.expectEqual(@as(u64, cycles_per_second), app.session.target_hz); try testing.expect(app.debuggerKey(alt('+'))); try testing.expectEqual(@as(u64, cycles_per_second * 2), app.session.target_hz); // Equals doubles as well: it is the same key without the shift. try testing.expect(app.debuggerKey(alt('='))); try testing.expectEqual(@as(u64, cycles_per_second * 4), app.session.target_hz); try testing.expect(app.debuggerKey(alt('-'))); try testing.expectEqual(@as(u64, cycles_per_second * 2), app.session.target_hz); // However far it has been taken, nought brings it back. for (0..10) |_| _ = app.debuggerKey(alt('=')); try testing.expect(app.session.target_hz > cycles_per_second * 100); try testing.expect(app.debuggerKey(alt('0'))); try testing.expectEqual(@as(u64, cycles_per_second), app.session.target_hz); // And neither end runs away. for (0..40) |_| _ = app.debuggerKey(alt('+')); try testing.expectEqual(@as(u64, session16.max_hz), app.session.target_hz); for (0..40) |_| _ = app.debuggerKey(alt('-')); try testing.expectEqual(@as(u64, session16.min_hz), app.session.target_hz); } test "a key the debugger does not want is left for the machine" { const gpa = testing.allocator; const cpu = try gpa.create(CPU); defer gpa.destroy(cpu); try cpu.init(gpa, null); defer cpu.deinit(); var app = bareApp(gpa, cpu); // The keys this program already had, which must keep working. try testing.expect(!app.debuggerKey(alt('q'))); try testing.expect(!app.debuggerKey(alt('b'))); try testing.expect(!app.debuggerKey(alt('g'))); try testing.expect(!app.debuggerKey(alt('m'))); try testing.expect(!app.debuggerKey(alt('x'))); try testing.expect(!app.debuggerKey(alt('o'))); try testing.expect(!app.debuggerKey(alt('s'))); try testing.expect(!app.debuggerKey(alt('1'))); try testing.expect(!app.debuggerKey(alt('2'))); // And an ordinary letter, which belongs to the Apple. try testing.expect(!app.debuggerKey(.{ .codepoint = 'a', .mods = .{} })); }