// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); const zig65 = @import("zig65"); const disk2 = zig65.disk2; const screen = zig65.screen; const video = zig65.video; const picture = zig65.picture; const videx = zig65.videx; const ultraterm = zig65.ultraterm; const ramfactor = zig65.ramfactor; const vaxis = @import("vaxis"); const terminal = @import("terminal"); const config = @import("config"); const romid = zig65.romid; const gs = @import("gs"); const sess = @import("session8"); const imagewriter2 = @import("imagewriter2"); // const ehbasic = @embedFile("ehbasic"); pub const panic = vaxis.panic_handler; /// An ImageWriter II on the far end of the serial line, turning the machine's /// print stream into pages. /// /// It is the front end's, not the library's: the serial card takes a /// `*std.Io.Writer` and does not know a printer is on the other end, so this /// lives here and hands the card `emulator.interface`. Kept on the heap so the /// pointers between its parts -- the emulator into the document, the document's /// page sink back into this -- stay put while the session writes to it. /// /// The emulator is the user's own `imagewriter2`, a faithful model of the /// printer rather than a text-to-picture filter: bytes drain into its /// `std.Io.Writer` and pages fall out as they finish, each rendered to a PNG. const ImageWriter = struct { io: std.Io, alloc: std.mem.Allocator, /// Where the first page is written; later pages are numbered from it, so a /// one-page job is exactly the file named. path: []const u8, /// How many pages have been written, for the numbering and a closing word. written: usize = 0, document: imagewriter2.Document = undefined, emulator: imagewriter2.Emulator = undefined, /// The buffer the emulator's `std.Io.Writer` interprets out of. buffer: [4096]u8 = undefined, fn open(io: std.Io, alloc: std.mem.Allocator, path: []const u8) !*ImageWriter { const self = try alloc.create(ImageWriter); self.* = .{ .io = io, .alloc = alloc, .path = path }; self.document = imagewriter2.Document.init(alloc, .{}, .{ .context = self, .emit = emit }); self.emulator = imagewriter2.Emulator.init(alloc, &self.document, &self.buffer, .{}); return self; } /// The `std.Io.Writer` the serial card's output drains into. fn writer(self: *ImageWriter) *std.Io.Writer { return &self.emulator.interface; } /// Finishes the page in progress, hands over every page still in the /// machine, and lets go of everything. The last page of a job leaves no /// other way out, so this must be called before the program ends. fn close(self: *ImageWriter) void { self.emulator.finish() catch {}; self.document.deinit(); self.emulator.deinit(); self.alloc.destroy(self); } /// One finished page, written to its file. fn emit(context: ?*anyopaque, index: usize, page: *imagewriter2.Page) anyerror!void { const self: *ImageWriter = @ptrCast(@alignCast(context.?)); const numbered = self.written != 0; const path = if (!numbered) self.path else name: { const dot = std.mem.lastIndexOfScalar(u8, self.path, '.') orelse self.path.len; break :name try std.fmt.allocPrint(self.alloc, "{s}-{d}{s}", .{ self.path[0..dot], index + 1, self.path[dot..], }); }; defer if (numbered) self.alloc.free(path); try page.writePng(self.io, path); self.written += 1; } }; pub const std_options: std.Options = .{ .log_scope_levels = &.{ .{ .scope = .vaxis, .level = .warn }, .{ .scope = .vaxis_parser, .level = .warn }, }, }; /// Which machine the debugger puts around the processor. /// /// This was a build option once, because the memory model is a comptime /// parameter and so the choice had to be made before there was a processor to /// ask. It is a flag now: the debugger is generic over the machine and every /// one of them is compiled in, which costs a larger executable and buys a /// program that can be handed to somebody without asking them first which /// Apple they meant. pub const Machine = enum { /// Sixty-four kilobytes of RAM and nothing else. Not an Apple: it is what /// a test program or a bare 6502 monitor wants, with no I/O in the way. flat, /// The 1976 machine: a 6502, 4K or 8K of RAM, the Woz Monitor in 256 /// bytes of PROM, and a terminal on the other side of a PIA in place of /// a video display. It wants the Woz Monitor as its ROM, and its two /// buttons are alt+b for RESET and alt+c for CLEAR SCREEN. i, /// The 1977 machine: Integer BASIC and the old Monitor in ROM on the same /// board as the II Plus, which could be populated with anything from 4K to /// 48K. `--revision 0` makes it one of the very first boards, before the /// colour-burst killer, the Hi-Res half-dot delay and the power-up reset. ii, @"ii+", iie, iic, /// The 1980 machine: a 6502 at 2 MHz with 128K, 256K or 512K behind a bank /// register, SOS instead of DOS, and a Disk II mechanism built into the /// case. It wants the Sara ROM as its ROM, and boots from a disk or not /// at all. The board's own hardware is here, the clock chip with it, and /// `--hard-disk` puts a ProFile on the interface card in slot 4 where /// SOS's .PROFILE driver looks, and `--parallel-out` a Universal Parallel /// Interface Card in slot 1; either goes in any of the four slots, which /// is what `--slot N=block` and `--slot N=parallel` are for on this /// machine. iii, /// The sixteen-bit machine, which is a different program entirely and is /// in `gs.zig` rather than here. iigs, pub fn parse(name: []const u8) ?Machine { inline for (@typeInfo(Machine).@"enum".fields) |field| { if (std.mem.eql(u8, name, field.name)) return @enumFromInt(field.value); } // The name people actually write for it, and the one the ROM files // carry, neither of which is a legal Zig identifier. if (std.mem.eql(u8, name, "iigs") or std.mem.eql(u8, name, "gs")) return .iigs; // A III Plus is a III with a clock chip that worked, running the same // software from the same ROM; the caller fits the chip, and the // machine is this one. if (std.mem.eql(u8, name, "iii+") or std.mem.eql(u8, name, "3")) return .iii; return null; } /// Whether this is one of the eight-bit machines, which are the ones the /// debugger below knows how to be. pub fn isEightBit(self: Machine) bool { return self != .iigs; } /// Whether this machine has the Apple II's seven slots, and so takes the /// Apple II cards in `slots.zig`. A IIc has everything soldered down and /// the flat model is memory and nothing else. A III has four slots of its /// own with its own two cards in them -- see `apple3.SlotCard` -- and they /// are not these: a Videoterm in an Apple III would be a card the machine /// has no driver for, so it answers no here on purpose. pub fn hasSlots(self: Machine) bool { return self == .ii or self == .@"ii+" or self == .iie; } /// Whether a disk in this machine needs a card fitted before anything can /// read it. A IIc has its drive soldered into the case, a III has one in /// the case and its controller on the board, and a IIgs has two of them /// built in, so on those a disk needs nothing but a disk; the machines /// with slots have nothing in them until something is put there. pub fn needsDiskCard(self: Machine) bool { return self == .ii or self == .@"ii+" or self == .iie; } }; /// A kind of card, for saying which slot one goes in. /// /// The names are what somebody types after `--slot 4=`, and they are the /// names the switches that configure each card already use: `--disk-rom` fits /// a `disk`, `--videx-rom` a `videx`, `--ramfactor-rom` a `ramfactor`. There /// is one name for a thing rather than two. pub const CardKind = enum { disk, serial, videx, ultraterm, mouse, mockingboard, phasor, soundspeech, passport, uthernet, uthernet1, clock, ramfactor, block, scsi, transporter, parallel, /// Where one goes when nobody says. These are the slots the software of /// the day looked in, which is why they were the slots people used. pub fn defaultSlot(self: CardKind) u3 { return switch (self) { .parallel => 1, // The Passport manual bases its addresses on slot 2, "the // standard slot used for serial communications devices in the // Apple" (Bethke & Borowicz, 1985, §4.1). .serial, .passport => 2, // Slot 3 is where the modern Apple II TCP/IP software looks for an // Uthernet: IP65 and Contiki both default to it. .videx, .ultraterm, .uthernet, .uthernet1 => 3, .mouse, .mockingboard, .phasor, .soundspeech => 4, .clock, .ramfactor => 5, .disk => 6, .block, .scsi, .transporter => 7, }; } pub fn parse(name: []const u8) ?CardKind { inline for (@typeInfo(CardKind).@"enum".fields) |field| { if (std.mem.eql(u8, name, field.name)) return @field(CardKind, field.name); } return null; } /// What to call it in a message to whoever is choosing. pub fn shown(self: CardKind) []const u8 { return switch (self) { .disk => "a Disk II controller", .serial => "a Super Serial Card", .videx => "a Videx Videoterm", .ultraterm => "a Videx UltraTerm", .mouse => "a mouse card", .mockingboard => "a Mockingboard", .phasor => "a Phasor", .soundspeech => "a Sound/Speech Mockingboard", .passport => "a Passport MIDI interface", .uthernet => "an Uthernet II", .uthernet1 => "an Uthernet", .clock => "a clock card", .ramfactor => "a RamFactor", .block => "a block device", .scsi => "an Apple II SCSI Card", .transporter => "a Corvus Transporter", .parallel => "a parallel printer card", }; } }; /// And which processor goes in it. An enhanced IIe is a IIe with a 65C02 in /// the socket, which is the whole of the difference as far as this is /// concerned. The IIgs has a 65816 and no say in the matter. pub const Processor = enum { @"6502", RP2A03, @"65C02", R65C02, W65C02, pub fn parse(name: []const u8) ?Processor { inline for (@typeInfo(Processor).@"enum".fields) |field| { if (std.ascii.eqlIgnoreCase(name, field.name)) return @enumFromInt(field.value); } return null; } }; /// The two character generator chips a IIe could have. pub const VideoRom = enum { /// 342-0133, the original IIe's. original, /// 342-0265, the enhancement's, with MouseText where the original had a /// second copy of the inverse capitals. A IIc has this one. enhanced, pub fn parse(name: []const u8) ?VideoRom { inline for (@typeInfo(VideoRom).@"enum".fields) |field| { if (std.ascii.eqlIgnoreCase(name, field.name)) return @enumFromInt(field.value); } return null; } pub fn set(self: VideoRom) zig65.font.Set { return switch (self) { .original => .apple2e, .enhanced => .apple2e_enhanced, }; } }; /// The processor a machine was sold with, for when --processor does not say. /// /// A IIc had a 65C02 from the first one sold. A IIe had a 6502 until the 1985 /// enhancement put a 65C02 in beside new ROMs, and the ROMs say which they /// are: "the identification byte at $FBC0 has been changed. In the original /// Apple IIe it was $EA (decimal 234), in the enhanced Apple IIe it is $E0 /// (decimal 224)" (Apple Computer, Inc., 1985b, p. xxix). So the ROM file /// chooses, by the byte that sits $440 from its end. Everything else is a /// 6502; a file that cannot be read is left for the machine's own loading to /// complain about. fn shippedProcessor(io: std.Io, gpa: std.mem.Allocator, options: Options) Processor { switch (options.machine) { .iic => return .@"65C02", .iie => { const file = std.Io.Dir.cwd().readFileAlloc(io, options.rom, gpa, .limited(rom_limit)) catch return .@"6502"; defer gpa.free(file); if (file.len >= 0x440 and file[file.len - 0x440] == 0xe0) return .@"65C02"; return .@"6502"; }, else => return .@"6502", } } /// The processor and the machine around it. /// /// The logs are switched on for every machine that has the hardware they are /// about: --audio and --cassette-out ask for them, and the cost is a compare /// and a store on the accesses that work each line. The flat model has no bus /// log at all, because nothing in the debugger reads one and it would cost a /// store on every access. fn Cpu(comptime machine: Machine, comptime processor: Processor) type { const which: zig65.Processor = switch (processor) { .@"6502" => .@"6502", .RP2A03 => .RP2A03, .@"65C02" => .@"65C02", .R65C02 => .R65C02, .W65C02 => .W65C02, }; const logs: zig65.memory.Options = .{ .speaker_log = true, .cassette_log = true, .mockingboard_log = true, }; return switch (machine) { .flat => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.Flat(.{})), .i => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.AppleI(logs)), .ii => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.AppleII(logs)), .@"ii+" => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.AppleIIPlus(logs)), // A IIc is a IIe with everything soldered down, and it had a 65C02 in // it from the first one sold, so `--machine iic` wants // `--processor 65C02` to be the machine it actually was. .iic => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.AppleIIc(logs)), .iie => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.AppleIIe(logs)), .iii => zig65.Chip(.{ .processor = which }, zig65.clock.FakeClock, zig65.memory.AppleIII(logs)), .iigs => @compileError("the IIgs is not one of these: see gs.zig"), }; } /// The largest ROM that can be loaded, which is the whole address space. A /// ROM is placed so that its last byte lands at $ffff, where the processor /// looks for its vectors, so a larger one has nowhere to go. const rom_limit = 0x10000; const usage = \\usage: zig65 --rom PATH [--machine NAME] [--disk-rom PATH] [--drives N] \\ [--disk1 PATH] [--disk2 PATH] \\ zig65 --config PATH [more switches] \\ zig65 id FILE... \\ \\ id FILE... say what each ROM file is and which switch wants it. \\ A file this has been tested against is named exactly; \\ one it has not is read instead -- the signature bytes \\ a card carries, the byte a machine says which it is \\ in, the text inside -- and what can be seen is said. \\ The exit status is how many it could not place. \\ \\ --machine NAME which Apple to be: flat, i, ii, ii+, iie, iic, iii, \\ iii+ or iigs. Defaults to iie. iii+ is a III with \\ its clock chip fitted, which is what Apple changed. Every one of them is compiled \\ in, so this needs no rebuild. flat is sixty-four \\ kilobytes of RAM and nothing else, which is what a \\ bare test program wants; i is the 1976 Apple-1, \\ which wants the 256-byte Woz Monitor as its ROM and \\ has alt+c for its CLEAR SCREEN button; ii is the \\ 1977 Apple II, which wants an Integer BASIC ROM; \\ iigs is the sixteen-bit machine and a different \\ program around it, with no debugger panes and its \\ own keys. \\ --memory SIZE how much RAM the machine has. A IIgs counts it all, \\ the Mega II's 128K included: 1M, 512K, 8M; a \\ machine with nothing in its expansion slot has \\ 256K, which is the default and is what one shipped \\ with, and eight megabytes is as far as the address \\ space goes. An Apple II took 4K, 8K, 12K, 16K, 20K, \\ 24K, 32K, 36K or 48K, in the configurations Apple \\ sold, and 12K-hires is the one that put two rows \\ under the Hi-Res page instead of in a run; a II \\ Plus took 16K, 32K or 48K. Both default to 48K. An \\ Apple-1 took 4K, which is what was supplied and the \\ default, or 8K, the second bank at $E000 where its \\ BASIC lives. A IIe and a IIc have their 128K and no \\ choice. An Apple III took 128K or 256K, and 512K \\ with the upgrade board; 128K is the default. \\ --revision N which Apple II board: 0 for the first ones, which \\ had no power-up reset, coloured text, and Hi-Res in \\ violet, green and white only; 1 for every board \\ after, which is the default and is every II Plus. \\ --processor NAME which chip is in the socket: 6502, RP2A03, 65C02, \\ R65C02 or W65C02. Defaults to the one the machine \\ was sold with: a 65C02 in a IIc, and in a IIe whose \\ ROM is the 1985 enhanced firmware — the ROM says \\ which it is at $fbc0 — and a 6502 in everything \\ else. A IIgs has a 65816 and ignores this. \\ --video-rom NAME which character generator a IIe has: original, the \\ 1983 chip, or enhanced, the one with MouseText that \\ came with the enhanced firmware. Defaults to the one \\ that matches the ROM; this is for an owner who \\ changed one chip and not the other. \\ --config PATH read the settings below from PATH, a Ziggy file, so \\ that a machine you use often is written down once \\ rather than typed out every time. A field is named \\ after its switch with the dashes turned into \\ underscores, everything in it is optional, and a \\ switch on the command line beats the file. \\ Cards are the exception: a file describes one in \\ .slots, beside the slot it is in, rather than in a \\ field named after the card -- which is what lets a \\ file say a thing this command line cannot, two \\ controllers with different disks in them. See \\ examples/apple2e.ziggy, and .ziggy-schema at the top \\ of the repository, which is what an editor reads. \\ --rom PATH load PATH at the top of memory. The file is placed so \\ that its last byte lands at $ffff, where the processor \\ looks for its vectors, so it can be at most 64K. \\ Required: no ROM is built in. \\ --disk-rom PATH fit a Disk II card in slot 6 and give it PATH as its \\ boot ROM, which is the 256 byte P5 PROM. Without one \\ there is no card and nothing to start a disk from. \\ --aci-rom PATH fit an Apple-1 Cassette Interface, the one card that \\ machine had, and give it PATH as its PROM: 256 bytes, \\ which appear at $c100 and are entered from the Monitor \\ with C100R. Its jacks are what --cassette-in and \\ --cassette-out reach on an Apple-1, which has no port \\ of its own. --machine i only. \\ --slot N=CARD put a card in slot N rather than where that kind of \\ card has always gone. N is 1 to 7; CARD is disk, \\ serial, videx, ultraterm, mouse, mockingboard, \\ phasor, soundspeech, passport, uthernet, uthernet1, \\ clock, ramfactor, block, transporter or parallel. The \\ switch \\ that configures the card is the same either way, so \\ --slot 5=disk --disk-rom P5 puts the controller in \\ slot 5, and a machine boots it because the ROM scans \\ every slot from 7 down. Two cards in one slot is an \\ error rather than one quietly beating the other. \\ --machine ii, ii+ and iie only: a IIc has no slots. \\ --drives N how many drives are on the card: 0, 1 or 2. The card \\ only ever had two connectors. Defaults to 2. \\ --disk1 PATH put a disk in the first drive. A .dsk or .do file is \\ --disk2 PATH read in DOS sector order and a .po in ProDOS order; \\ a 2IMG says which it is and is believed. A .nib is a \\ recording of the surface rather than a description of \\ the sectors, which is how a copy-protected disk \\ survives, and goes in as it stands. A ShrinkIt \\ archive — .shk or .sdk — is unpacked and the disk \\ inside it used, read only, since writing one back \\ would mean compressing it. \\ An eight hundred kilobyte image goes to whichever \\ 3.5-inch drive the machine has: the one in a IIc \\ Plus's case, or, on a IIc with the 32K ROM, the \\ UniDisk 3.5 on its port. \\ --unidisk PATH put an 800K image in a UniDisk 3.5 on the disk port, \\ --unidisk2 PATH and in the one daisy-chained behind it. --machine iigs \\ only, because that is the machine with drives of its \\ own on the same socket: everywhere else --disk1 goes \\ there by itself. A IIgs given one takes its empty \\ 3.5-inch drives off the cable, since those sit in \\ front of it and the startup stops at the first device \\ it finds. \\ --monitor NAME monochrome, which is the default, colour, ntsc, or \\ flat-panel. Which display the machine is being looked \\ at on: monochrome ignores the colour the dots make, \\ which is sharper and is the only way eighty column \\ text is readable. colour applies the four-dots rule \\ and draws flat blocks; ntsc demodulates the signal \\ the way a television did, so colours bleed and a lone \\ dot is a smudge rather than a block. flat-panel is \\ the Apple IIc's Flat Panel Display of 1984, a liquid \\ crystal panel of the same 560 by 192 dots, dark on a \\ pale ground. alt+m goes round the four while it runs. \\ --text NAME pixels, which is the default, or terminal. Whether \\ the machine's own character generator draws the text \\ or the terminal's letters do. A terminal that cannot \\ show a picture gets its own letters whatever this \\ says. alt+x changes it while it runs. \\ --halted come up stopped at the reset vector rather than \\ running. alt+r starts it. \\ --screenshot PATH where alt+g writes a picture of the screen, as a \\ PNG. Defaults to screen.png in the working \\ directory. The whole display, 560 by 192, rather \\ than what the terminal is showing. \\ --snapshot PATH boot straight into a save state: the machine is built \\ from the rest of these settings, then the snapshot is \\ read on top of it. alt+w writes a companion config \\ beside every snapshot, so `--config that.ziggy` brings \\ the machine up exactly where it was left. \\ Save states otherwise need no flag: alt+w writes the \\ whole machine -- memory, processor, chips and the disks \\ in its drives -- to a file typed at a prompt, and alt+l \\ reads one back. It has to be the same machine it was \\ taken of. \\ --audio PATH record what the machine plays to PATH, as a WAV: the \\ speaker on an eight-bit machine, or the Ensoniq's \\ thirty-two oscillators on a IIgs. An eight-bit \\ machine is held at its own 1.0205MHz while \\ recording, since sound played faster or slower is \\ the wrong sound. Nothing stops the file growing: \\ about five megabytes a minute, until it is closed. \\ --no-audio do not play the machine's sound live. It plays out \\ loud by default, through the host's audio, and \\ --audio still records a file whatever this is. \\ --volume N how loud live audio starts, 0 to 100. alt+, and \\ alt+. change it while it runs, alt+/ mutes it. \\ --mute start with live audio muted, the volume kept. \\ --cassette-in PATH play a WAV into the cassette input, as a tape. \\ alt+t winds it back and plays it again. \\ --cassette-out PATH write what the cassette output puts out to PATH, \\ as a WAV, which is a tape a real machine could read. \\ --scsi-rom PATH an Apple II SCSI Card's own 16K of firmware, which is \\ Apple's and so is not here. Fits the card in slot 7 \\ unless --slot says otherwise. Unlike the block device, \\ this is the real card: an NCR 5380 on a real SCSI bus, \\ running Apple's ROM. \\ --scsi PATH hook a drive up to that card's bus, as a ProDOS volume. \\ Give it again for another: they go on at the highest \\ identity still free, counting down from six the way \\ an owner setting jumpers would, and --scsi 3:PATH \\ says which. Seven is the card's own. A SCSI disk is \\ blocks and a command set, so any size up to what a \\ 32-bit block number reaches goes on one. \\ --hard-disk PATH put PATH in the block device in slot 7, as a ProDOS \\ volume. PR#7 starts it. Give it twice on a IIgs, \\ which uses both of the card's drives and boots from \\ it in preference to the floppies. The card's firmware is built \\ in, so there is no ROM to supply. On an Apple III it \\ is a ProFile on its interface card in slot 4, which \\ is where SOS's .PROFILE driver looks; a five-megabyte \\ image is 9728 blocks, and the utilities format it. \\ --mockingboard fit a Mockingboard in slot 4: two sound chips, three \\ voices each, and the two 6522s a program drives them \\ through. With --audio the recording becomes the two \\ channels the card has, with the speaker down the \\ middle of them. A slot holds one card, so this and \\ --mouse are not both. \\ --mockingboard-speech the same, with an SSI 263A speech chip in the \\ socket, as a Mockingboard C or a Phasor had: it \\ answers at $Cn40 and interrupts through CA1. \\ --phasor fit a Phasor in slot 4: Applied Engineering's superset \\ of the Mockingboard, four sound chips behind the same \\ two 6522s with a speech chip and a software-latched \\ mode. It comes up Mockingboard-compatible; its own \\ software selects Phasor mode to reach all four chips. \\ With --audio the recording is the card's two channels. \\ --sound-speech fit a Sound/Speech Mockingboard in slot 4: the first of \\ the family, one AY-3-8910 and a Votrax SC-01 speech \\ chip driven through a second 6522. The voice is an \\ approximation, the chip's own formants never published. \\ --passport fit a Passport Designs MIDI interface in slot 2: a \\ 6840 timer and a 6850 serial chip, with no firmware, \\ the card most Apple II MIDI software was written for. \\ --midi-in PATH fit a Passport card and play the Standard MIDI File at \\ PATH into it, timed as the file says. \\ --midi-out PATH fit a Passport card and write what the machine sends \\ as a Standard MIDI File at PATH, timed by the machine's \\ own clock. \\ --uthernet fit an Uthernet II in slot 3: a WIZnet W5100 whose \\ TCP/IP stack is in the chip, so the four sockets a \\ program opens are mapped to the host's own. TCP and \\ UDP, client and server; Linux only. The card carries \\ no firmware, so there is no ROM to supply. \\ --uthernet1 fit an Uthernet (the original) in slot 3: a CS8900A, a \\ raw Ethernet controller the driver's own stack sits on. \\ Its frames cross a UDP multicast group other emulators \\ share, so instances can talk to each other; not a route \\ to the real internet. Linux only, no firmware. \\ --ethernet-interface ADDR the interface to carry that virtual Ethernet \\ on, an address like 127.0.0.1 so two instances on one \\ host hear each other. The system chooses if unset. \\ --mac ADDR the hardware address to give a fitted Ethernet card, \\ as 00:11:22:33:44:55 or 0011.2233.4455; distinct ones \\ let two instances on one virtual Ethernet be told apart. \\ --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. \\ With no mouse card, the pointer is the game paddles \\ instead: across the screen turns paddle 0, down it \\ turns paddle 1, and the two mouse buttons are the game \\ connector's two (which alt+o and alt+s also press). \\ --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 \\ is, which is what an Apple II is like. The card's \\ firmware is built in, so there is no ROM to supply. \\ On an Apple III it fills the clock chip's socket on \\ the board instead, which Apple left empty in most of \\ them, so SOS shows the date and stamps its files. \\ --clock-offset N how many hours the machine's clock is from UTC, \\ since the host's is read as UTC and the machine knows \\ nothing of time zones. Implies --clock. \\ --ramfactor-rom PATH fit an Applied Engineering RamFactor in slot 5 and \\ give it PATH as its firmware, which is 8K. A megabyte \\ of memory the processor reaches four addresses at a \\ time, which the firmware turns into a ProDOS RAMdisk \\ called /RAM5. PR#5 reaches the partition manager. A \\ slot holds one card, so this and --clock are not both. \\ --ramfactor SIZE how much memory is on it: 256K, 512K, 768K or 1024K, \\ which are the one to four blocks of eight chips the \\ card has sockets for. A megabyte by default. \\ --ramcharger PATH fit the RamCharger, the battery that kept a \\ RamFactor's memory alive while the machine was off, and \\ keep the card's memory in PATH between runs. Without it \\ a RAMdisk lasts as long as the machine is switched on, \\ which is what a card without the battery was like. \\ --memory-expansion SIZE put an Apple IIc Memory Expansion Card in the \\ connector inside a IIc's case: 256K, 512K, 768K or 1M. \\ It needs no firmware, because what drives it is in the \\ machine's own ROM — so it wants one of the later IIc \\ ROMs, since the first one knows nothing about it. \\ --parallel-out PATH fit a parallel printer card in slot 1 and send what \\ it prints to PATH. PR#1 starts printing and PR#0 \\ stops. The card's firmware is built in, so there is \\ no ROM to supply; it strips the high bit the Apple \\ sets on every character and adds a line feed after \\ each carriage return, both of which are what the \\ card did. \\ --serial-rom PATH fit a Super Serial Card in slot 2 and give it PATH \\ as its firmware, which is the 2K 341-0065 ROM. \\ --videx-rom PATH fit a Videx Videoterm in slot 3 and give it PATH as \\ its firmware, which is the 1K Videoterm ROM. An Apple \\ II Plus has forty columns and no way to have more; \\ this is the card that was sold to fix that. \\ --videx-charset PATH the card's character generator, a 2K part holding \\ 128 glyphs. Required with --videx-rom: an eighty \\ column card with an empty socket shows nothing. \\ --videx-alternate PATH a second character generator for the other \\ socket, reached by the high bit of a character. The \\ inverse video and lower case modifications are this. \\ A Videoterm has its own monitor and does not switch the \\ Apple's off, so alt+v says which of the two to look at. \\ --ultraterm-rom PATH fit a Videx UltraTerm in slot 3 instead, and give it \\ PATH as its firmware, which is 4K. The card after the \\ Videoterm: four kilobytes of screen memory, nine \\ display formats up to 160 columns, and an attribute \\ for every character. A slot holds one card, so this \\ and --videx-rom are alternatives. \\ --ultraterm-charset PATH its character generator, a 4K part holding both \\ the standard and the alternate set. Required with \\ --ultraterm-rom. Unlike a Videoterm this card has a \\ switch for which picture reaches the monitor, so there \\ is nothing to choose with alt+v: PR#3 switches to it. \\ --serial-in PATH send the contents of PATH to the machine, at the \\ rate the card has been set to. \\ --serial-out PATH write what the machine sends to PATH. On a IIgs \\ these two are the modem port, which is channel B of \\ the SCC, rather than a card in a slot. \\ --imagewriter PATH put an ImageWriter II on the serial line and render \\ what the machine prints to PATH as PNG pages, later \\ pages numbered from it. Needs --serial-rom, and takes \\ the line --serial-out otherwise would. \\ --modem put a Hayes modem on the serial line instead of the \\ files: AT commands, and ATDT host:port dials out over \\ TCP, so a terminal program can reach a telnet BBS. On a \\ IIe it is the Super Serial Card, so it needs \\ --serial-rom; on a IIgs it is the SCC modem port, built \\ in. Linux only. \\ --modem-answer PORT the same, and also listen on PORT so something can \\ telnet in and be answered as an incoming call. \\ --printer-out PATH write what a IIgs sends out of its printer port to \\ PATH. That port is channel A of the same chip, and is \\ not a card in a slot either. \\ --localtalk put a IIgs on a LocalTalk network: the multicast group \\ other emulators share, LocalTalk over UDP, so that two \\ of these, or this and a Mini vMac, are on one cable. \\ The firmware has to be told to use it, which is the \\ Control Panel or --appletalk. \\ --localtalk-log PATH write every frame that crosses to PATH. \\ --localtalk-interface ADDR be on the network through the interface \\ with this address rather than whichever the system \\ picks. Two of these on one host need 127.0.0.1 where \\ the host does not loop multicast back on its network \\ interface. \\ --appletalk set a IIgs's Control Panel to AppleTalk before it \\ starts: slot 7 to the built-in AppleTalk and slot 1 \\ over to it, which is how an owner turned it on. \\ --battery-ram PATH keep a IIgs's parameter RAM in PATH between runs, \\ which is what its battery did: the Control Panel \\ stays set. \\ --writable let the machine write to its disks, and save the \\ changes back over the file when the disk is taken out \\ or the emulator is closed. Off by default: a disk is \\ write protected unless this says otherwise. \\ -h, --help show this and exit \\ ; /// What the command line asked for. const Options = struct { /// Which Apple this is, and what is in its socket. These used to be build /// options, because the memory model is a comptime parameter; every /// combination is compiled in now and these choose between them. machine: Machine = .iie, /// Which chip is in the socket, or null for the one the machine was sold /// with: see `shippedProcessor`. processor: ?Processor = null, /// Which character generator a IIe has, when the one that came with its /// firmware is not the one wanted. video_rom: ?VideoRom = null, /// The ROM to load at the top of memory. rom: []const u8, /// The Disk II card's own ROM, without which there is no card. disk_rom: ?[]const u8 = null, /// The Apple-1 Cassette Interface's PROM, without which there is no card /// — and on that machine no cassette port either, since the port is on the /// card. aci_rom: ?[]const u8 = null, /// How many drives are on the card. The card has two connectors and no /// way of telling what is on the end of either, so this only decides /// whether selecting the second one reaches anything. drives: u2 = 2, /// What to put in them at the start. disks: [2]?[]const u8 = .{ null, null }, /// Whether the machine may write to its disks, and whether those writes /// are saved back over the file afterwards. writable: bool = false, /// A library of named disks the alt-1/alt-2 picker offers, out of the /// config file. Empty unless one was named there. library: []const config.Disk = &.{}, /// Where to record what the speaker plays, if anywhere. audio: ?[]const u8 = null, /// Whether to play the machine's sound live, out of a real speaker. On by /// default where the platform and a running daemon allow it; a machine /// with no daemon to talk to falls back to silence rather than failing. /// `--audio` still records a file whatever this is. sound: bool = true, /// How loud live audio starts, nought to a hundred, and whether it starts /// muted. The keys that work the volume move from here. volume: u8 = 80, mute: bool = false, /// Where alt+g writes a picture of the machine's screen. screenshot: []const u8 = "screen.png", /// A save state to boot straight into: the machine is built from /// everything else, and then the snapshot is read on top of it. snapshot: ?[]const u8 = null, /// Which monitor the machine is being looked at on, and who draws the /// text. Both are switchable while it runs, at alt+m and alt+x; these are /// only where it starts. monitor: terminal.Monitor = .monochrome, text: terminal.TextDrawing = .pixels, /// Whether to come up stopped rather than running. A machine is a machine /// and should run; a debugger is sometimes wanted stopped at the reset /// vector with nothing executed yet. halted: bool = false, /// A tape to play into the cassette input, and where to write what the /// cassette output puts out. cassette_in: ?[]const u8 = null, cassette_out: ?[]const u8 = null, /// The ProDOS volumes to put in the block device in slot 7. The card has /// two drives; a IIgs uses both and the eight-bit machines the first. hard_disks: [2]?[]const u8 = .{ null, null }, /// An Apple II SCSI Card's own sixteen kilobytes of firmware, and the /// disk on the bus behind it. The firmware is Apple's, like a Disk II's /// boot PROM, so it has to be supplied rather than being here. scsi_rom: ?[]const u8 = null, /// The drives on that card's bus, by the identity each is hooked up at. /// Seven of them, because a SCSI bus holds eight devices and the card is /// one of them. scsi_disks: [7]?[]const u8 = @splat(null), /// The 800K images to put in the intelligent drives on the disk port. A /// IIc with the 32K ROM takes one there without being asked, by the size /// of what `--disk1` was given; a IIgs has drives of its own on the same /// socket, so there it has to be said. unidisks: [2]?[]const u8 = .{ null, null }, /// Which card goes in which slot, where somebody has said. Indexed by /// slot number; slot 0 is not a slot and is always null. /// /// A card nobody places goes where it has always gone — see /// `CardKind.defaultSlot` — so a command line that says nothing about /// slots gets the machine it always got. slots: [8]?CardKind = @splat(null), /// Whether to fit a mouse card, and let the terminal's mouse drive it. mouse: bool = false, /// Whether to fit a Mockingboard, which is the other card slot 4 can hold. mockingboard: bool = false, /// Whether to fit a Phasor, Applied Engineering's four-chip superset of /// the Mockingboard. phasor: bool = false, /// Whether to fit a Sound/Speech Mockingboard, an AY and a Votrax SC-01. soundspeech: bool = false, /// Whether to fit a Passport MIDI interface, the 6840-and-6850 card that /// gave an Apple II a MIDI port. passport: bool = false, /// Whether to fit an Uthernet II, the WIZnet W5100 Ethernet card whose /// sockets are mapped to the host's. uthernet: bool = false, /// Whether to fit an Uthernet (the original), the CS8900A card whose raw /// frames cross a UDP multicast group. uthernet1: bool = false, /// The address of the interface to carry the Uthernet's virtual Ethernet /// on, or none for whichever the system chooses; 127.0.0.1 lets two /// instances on one host hear each other. ethernet_interface: ?[]const u8 = null, /// The hardware address to give a fitted Ethernet card, or none to leave /// it as it comes up. Two instances on one virtual Ethernet want distinct /// ones so a frame can be addressed to one and not the other. mac: ?[]const u8 = null, /// Whether that Mockingboard has an SSI 263A speech chip in its socket, as /// a Mockingboard C, a Phasor or an Echo+ did. It answers at $Cn40 and /// interrupts through the first 6522's CA1. speech: 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, /// `--machine iii+`: an Apple III Plus, which is a III with its clock /// chip's socket filled and working — Apple's only change to the board /// that this can see, the rest being the interlaced video ROM and the /// keyboard. The machine is the same model; this fits the chip. plus: bool = false, clock_offset: i8 = 0, /// A memory expansion card in the same slot: its firmware, how much /// memory is on it, and where its contents are kept between runs if it /// has the battery option. ramfactor_rom: ?[]const u8 = null, ramfactor_size: ?usize = null, /// How much memory is on a IIc's memory expansion card, if one is in the /// connector inside the case. It needs no firmware: the driver is in the /// machine's own ROM. memory_expansion: ?usize = null, ramcharger: ?[]const u8 = null, /// How much RAM the machine has, in bytes. A IIgs counts the Mega II's /// 128K; an Apple II or II Plus counts its rows of chips, in the /// configurations Apple sold; a IIe and a IIc have no say. memory: ?usize = null, /// Whether a twelve-kilobyte Apple II is laid out for Hi-Res, with two /// rows under the picture rather than in a run from zero. memory_hires: bool = false, /// Which revision of Apple II board, where it matters: 0 is the first. revision: ?u8 = null, /// Where the parallel printer card's bytes go. Naming a file is what /// fits the card: a printer card with nothing on the end of its cable /// would be a card nobody could tell was there. parallel_out: ?[]const u8 = null, /// The Super Serial Card's own firmware, without which there is no card, /// and where its two directions go. serial_rom: ?[]const u8 = null, videx_rom: ?[]const u8 = null, videx_charset: ?[]const u8 = null, videx_alternate: ?[]const u8 = null, ultraterm_rom: ?[]const u8 = null, ultraterm_charset: ?[]const u8 = null, serial_in: ?[]const u8 = null, serial_out: ?[]const u8 = null, /// An ImageWriter II on the far end of the serial line, rendering what the /// machine prints to PNG pages under this path. Takes the line the output /// file otherwise would, so it needs the card and rules out `--serial-out`. imagewriter: ?[]const u8 = null, /// Whether a Hayes modem is on the serial line instead of the files, and /// the port it answers incoming calls on if it is to listen. modem: bool = false, modem_answer: ?u16 = null, printer_out: ?[]const u8 = null, /// A Standard MIDI File fed to a Passport card's input, and one written /// from what it sends. midi_in: ?[]const u8 = null, midi_out: ?[]const u8 = null, /// A IIgs on a LocalTalk network, and the log of what crossed it. localtalk: bool = false, localtalk_log: ?[]const u8 = null, localtalk_interface: ?[]const u8 = null, /// A IIgs with AppleTalk set in its Control Panel, and the file its /// parameter RAM is kept in between runs. appletalk: bool = false, battery_ram: ?[]const u8 = null, }; /// A size written the way people write one: `1M`, `512K`, or a plain number /// of bytes. Nothing clever — no decimals, no spaces — because the only sizes /// worth naming here are the ones a IIgs could actually have. /// A memory size for `--memory`, with the one suffix a size can carry: an /// Apple II's twelve kilobytes could be laid out for Hi-Res, which is asked /// for as `12K-hires`. fn parseMemory(text: []const u8, hires: *bool) ?usize { const suffix = "-hires"; if (std.mem.endsWith(u8, text, suffix)) { hires.* = true; return parseSize(text[0 .. text.len - suffix.len]); } return parseSize(text); } fn parseSize(text: []const u8) ?usize { if (text.len == 0) return null; const last = text[text.len - 1]; const scale: usize = switch (last) { 'k', 'K' => 1024, 'm', 'M' => 1024 * 1024, else => 1, }; const digits = if (scale == 1) text else text[0 .. text.len - 1]; const count = std.fmt.parseInt(usize, digits, 10) catch return null; return count * scale; } /// Reads the command line. Returns null when the program was only asked to /// explain itself and there is nothing further to do. A malformed command line /// is reported and exits, rather than being returned as an error, because a /// stack trace is not a useful thing to show someone who mistyped a flag. /// Puts what a configuration file said into the options, before the command /// line gets its say. /// /// Only what the file actually mentions: every field of a configuration is /// optional, which is what lets a switch beat the file without either of them /// having to know what the other did. /// What one `.slots` entry says about the card in it. /// /// The settings still land in the flat `Options` the fitting reads, because /// there is exactly one card of each kind on a command line and that is what /// those fields are for. A file can say more than a command line can — two /// controllers with different disks in them — and that is a thing to grow into /// here rather than a reason to have two of everything now. fn applyCard(options: *Options, kind: CardKind, entry: config.Slot) void { const wants = struct { fn rom(what: []const u8, given: ?[]const u8) []const u8 { return given orelse { std.debug.print("zig65: a {s} needs its firmware: give the slot a .rom\n", .{what}); std.process.exit(2); }; } }; switch (kind) { .disk => { options.disk_rom = wants.rom("Disk II controller", entry.rom); if (entry.drives) |count| options.drives = @intCast(@min(count, 2)); if (entry.disk1) |path| options.disks[0] = path; if (entry.disk2) |path| options.disks[1] = path; }, .serial => { options.serial_rom = wants.rom("Super Serial Card", entry.rom); if (entry.in) |path| options.serial_in = path; if (entry.out) |path| options.serial_out = path; if (entry.modem) |yes| options.modem = yes; }, .videx => { options.videx_rom = wants.rom("Videoterm", entry.rom); options.videx_charset = wants.rom("Videoterm", entry.charset); if (entry.alternate) |path| options.videx_alternate = path; }, .ultraterm => { options.ultraterm_rom = wants.rom("UltraTerm", entry.rom); options.ultraterm_charset = wants.rom("UltraTerm", entry.charset); }, .mouse => options.mouse = true, .mockingboard => options.mockingboard = true, .phasor => options.phasor = true, .soundspeech => options.soundspeech = true, .passport => { options.passport = true; if (entry.in) |path| options.midi_in = path; if (entry.out) |path| options.midi_out = path; }, .uthernet => options.uthernet = true, .uthernet1 => options.uthernet1 = true, .clock => { options.clock = true; if (entry.offset) |hours| options.clock_offset = hours; }, .ramfactor => { options.ramfactor_rom = wants.rom("RamFactor", entry.rom); if (entry.memory) |text| options.ramfactor_size = parseSize(text) orelse { std.debug.print("zig65: a RamFactor's .memory wants a size like 512K, not '{s}'\n", .{text}); std.process.exit(2); }; if (entry.battery) |path| options.ramcharger = path; }, .block => { if (entry.image) |path| options.hard_disks[0] = path; if (entry.image2) |path| options.hard_disks[1] = path; }, .scsi => { if (entry.rom) |path| options.scsi_rom = path; if (entry.image) |path| options.scsi_disks[6] = path; if (entry.image2) |path| options.scsi_disks[5] = path; }, .parallel => { if (entry.out) |path| options.parallel_out = path; }, // Its PROM is Corvus's and there is no switch for one yet; a file can // still put the card in a slot, and `--transporter` will find it there // when there is one. .transporter => {}, } } /// Which slot a card goes in: where `--slot` put it, or where that kind has /// always gone. fn slotFor(options: Options, kind: CardKind) u3 { for (options.slots, 0..) |maybe, slot| { if (maybe == kind) return @intCast(slot); } return kind.defaultSlot(); } /// The same, for an Apple III, whose four slots are numbered 1 to 4 and whose /// two cards are its own. /// /// The names are shared with the Apple II's on purpose rather than by /// accident: a III's ProFile interface card *is* its block device and the /// UPIC *is* its parallel printer card, so `--slot 2=block` and /// `--slot 3=parallel` say the same thing about this machine that they say /// about a IIe. Only the defaults differ, because the slots do — a block /// device goes in 7 on a II and a III has no slot 7. fn slotForIII(options: Options, kind: CardKind, fallback: u3) u3 { for (options.slots, 0..) |maybe, slot| { if (maybe == kind) { if (slot < 1 or slot > 4) { std.debug.print( "zig65: an Apple III has four slots, numbered 1 to 4, and no slot {d}\n", .{slot}, ); std.process.exit(2); } return @intCast(slot); } } return fallback; } /// A memory size back into the text a config wants: "512K", "1M", or the /// twelve-kilobyte Apple II layout under the Hi-Res page. fn sizeText(gpa: std.mem.Allocator, bytes: usize, hires: bool) ![]const u8 { if (hires) return gpa.dupe(u8, "12K-hires"); if (bytes != 0 and bytes % (1024 * 1024) == 0) return std.fmt.allocPrint(gpa, "{d}M", .{bytes / (1024 * 1024)}); if (bytes % 1024 == 0) return std.fmt.allocPrint(gpa, "{d}K", .{bytes / 1024}); return std.fmt.allocPrint(gpa, "{d}", .{bytes}); } /// The monitor as a config names it; only the flat panel is spelled with a /// dash rather than as its enum tag. fn monitorText(monitor: terminal.Monitor) []const u8 { return switch (monitor) { .monochrome => "monochrome", .colour => "colour", .ntsc => "ntsc", .flat_panel => "flat-panel", }; } /// Builds a config that rebuilds this machine and boots into `snapshot_path`. /// The cards go in with their firmware so the snapshot's slots line up, and /// the hard disks and SCSI volumes go in too, since a snapshot is read into a /// volume already fitted; the floppies do not, because the snapshot carries /// their surfaces. Everything comes from `gpa`, meant to be an arena the caller /// throws away. fn machineConfig(gpa: std.mem.Allocator, options: Options, snapshot_path: []const u8) !config.Config { var slots: std.ArrayList(config.Slot) = .empty; if (options.disk_rom) |rom| try slots.append(gpa, .{ .slot = slotFor(options, .disk), .card = "disk", .rom = rom, .drives = options.drives }); if (options.serial_rom) |rom| try slots.append(gpa, .{ .slot = slotFor(options, .serial), .card = "serial", .rom = rom, .in = options.serial_in, .out = options.serial_out, .modem = if (options.modem) true else null }); if (options.mockingboard) try slots.append(gpa, .{ .slot = slotFor(options, .mockingboard), .card = "mockingboard" }); if (options.phasor) try slots.append(gpa, .{ .slot = slotFor(options, .phasor), .card = "phasor" }); if (options.soundspeech) try slots.append(gpa, .{ .slot = slotFor(options, .soundspeech), .card = "soundspeech" }); if (options.mouse) try slots.append(gpa, .{ .slot = slotFor(options, .mouse), .card = "mouse" }); if (options.clock) try slots.append(gpa, .{ .slot = slotFor(options, .clock), .card = "clock", .offset = options.clock_offset }); if (options.ramfactor_rom) |rom| try slots.append(gpa, .{ .slot = slotFor(options, .ramfactor), .card = "ramfactor", .rom = rom, .memory = if (options.ramfactor_size) |s| try sizeText(gpa, s, false) else null }); if (options.scsi_rom) |rom| try slots.append(gpa, .{ .slot = slotFor(options, .scsi), .card = "scsi", .rom = rom, .image = options.scsi_disks[6], .image2 = options.scsi_disks[5] }); if (options.hard_disks[0] != null or options.hard_disks[1] != null) try slots.append(gpa, .{ .slot = slotFor(options, .block), .card = "block", .image = options.hard_disks[0], .image2 = options.hard_disks[1] }); if (options.videx_rom) |rom| try slots.append(gpa, .{ .slot = slotFor(options, .videx), .card = "videx", .rom = rom, .charset = options.videx_charset, .alternate = options.videx_alternate }); if (options.ultraterm_rom) |rom| try slots.append(gpa, .{ .slot = slotFor(options, .ultraterm), .card = "ultraterm", .rom = rom, .charset = options.ultraterm_charset }); if (options.parallel_out) |out| try slots.append(gpa, .{ .slot = slotFor(options, .parallel), .card = "parallel", .out = out }); if (options.passport) try slots.append(gpa, .{ .slot = slotFor(options, .passport), .card = "passport", .in = options.midi_in, .out = options.midi_out }); if (options.uthernet) try slots.append(gpa, .{ .slot = slotFor(options, .uthernet), .card = "uthernet" }); if (options.uthernet1) try slots.append(gpa, .{ .slot = slotFor(options, .uthernet1), .card = "uthernet1" }); return .{ .machine = @tagName(options.machine), .processor = if (options.processor) |p| @tagName(p) else null, .rom = options.rom, .video_rom = if (options.video_rom) |v| @tagName(v) else null, .aci_rom = options.aci_rom, .memory = if (options.memory) |m| try sizeText(gpa, m, options.memory_hires) else null, .memory_expansion = if (options.memory_expansion) |m| try sizeText(gpa, m, false) else null, .revision = options.revision, .writable = if (options.writable) true else null, .monitor = monitorText(options.monitor), .speech = if (options.mockingboard and options.speech) true else null, .slots = if (slots.items.len == 0) null else try slots.toOwnedSlice(gpa), .snapshot = snapshot_path, }; } fn applyConfig(options: *Options, rom: *?[]const u8, file: config.Config) void { if (file.machine) |name| options.machine = Machine.parse(name) orelse { std.debug.print("zig65: no such machine as '{s}'\n", .{name}); std.process.exit(2); }; // A III Plus is the same machine with a clock chip in its socket. if (file.machine) |name| if (std.mem.eql(u8, name, "iii+")) { options.plus = true; }; if (file.processor) |name| options.processor = Processor.parse(name) orelse { std.debug.print("zig65: no such processor as '{s}'\n", .{name}); std.process.exit(2); }; if (file.rom) |path| rom.* = path; if (file.video_rom) |name| options.video_rom = VideoRom.parse(name) orelse { std.debug.print("zig65: video_rom wants original or enhanced, not '{s}'\n", .{name}); std.process.exit(2); }; if (file.aci_rom) |path| options.aci_rom = path; if (file.disk1) |path| options.disks[0] = path; if (file.disk2) |path| options.disks[1] = path; if (file.writable) |yes| options.writable = yes; if (file.library) |disks| options.library = disks; if (file.unidisk) |path| options.unidisks[0] = path; if (file.unidisk2) |path| options.unidisks[1] = path; if (file.memory_expansion) |text| options.memory_expansion = parseSize(text) orelse { std.debug.print("zig65: memory_expansion wants a size like 1M, not '{s}'\n", .{text}); std.process.exit(2); }; // The cards. A card is described where it sits, so this is the one place // the file says anything about one, and each entry carries what that card // needs — which is what lets two of a kind be told apart. if (file.slots) |entries| for (entries) |entry| { if (entry.slot < 1 or entry.slot > 7) { std.debug.print("zig65: '{d}' is not a slot: an Apple II has seven, numbered 1 to 7\n", .{entry.slot}); std.process.exit(2); } const kind = CardKind.parse(entry.card) orelse { std.debug.print("zig65: no such card as '{s}'\n", .{entry.card}); std.process.exit(2); }; if (options.slots[entry.slot]) |already| { std.debug.print("zig65: slot {d} already has {s} in it\n", .{ entry.slot, already.shown() }); std.process.exit(2); } options.slots[entry.slot] = kind; applyCard(options, kind, entry); }; if (file.screenshot) |path| options.screenshot = path; if (file.snapshot) |path| options.snapshot = path; if (file.halted) |yes| options.halted = yes; if (file.audio) |path| options.audio = path; if (file.sound) |yes| options.sound = yes; if (file.speech) |yes| options.speech = yes; if (file.volume) |v| options.volume = v; if (file.mute) |yes| options.mute = yes; if (file.cassette_in) |path| options.cassette_in = path; if (file.cassette_out) |path| options.cassette_out = path; if (file.memory) |text| options.memory = parseMemory(text, &options.memory_hires) orelse { std.debug.print("zig65: memory wants a size like 1M, 512K or 48K, not '{s}'\n", .{text}); std.process.exit(2); }; if (file.revision) |n| options.revision = n; if (file.printer_out) |path| options.printer_out = path; if (file.localtalk) |yes| options.localtalk = yes; if (file.localtalk_log) |path| options.localtalk_log = path; if (file.localtalk_interface) |address| options.localtalk_interface = address; if (file.ethernet_interface) |address| options.ethernet_interface = address; if (file.mac) |address| options.mac = address; if (file.appletalk) |yes| options.appletalk = yes; if (file.battery_ram) |path| options.battery_ram = path; if (file.monitor) |name| options.monitor = terminal.Monitor.parse(name) orelse { std.debug.print("zig65: monitor wants monochrome, colour, ntsc or flat-panel, not '{s}'\n", .{name}); std.process.exit(2); }; if (file.text) |name| options.text = terminal.TextDrawing.parse(name) orelse { std.debug.print("zig65: text wants terminal or pixels, not '{s}'\n", .{name}); std.process.exit(2); }; // The one setting this machine has nowhere to put. A IIgs has two drives // on its block device and this has one, and saying nothing about the // second would be the file quietly not working. } fn parseArgs(args: std.process.Args, io: std.Io, gpa: std.mem.Allocator) ?Options { var rom: ?[]const u8 = null; var options: Options = .{ .rom = "" }; // The configuration first, so that everything after it can override what // the file said. It is looked for in its own pass rather than in order, // because a file that only counted when it came before the switches would // be a rule nobody should have to remember. { // Asking for help is not asking for a machine, and should work // whatever the file says — or whether there is one at all. var looking: std.process.Args.Iterator = .init(args); _ = looking.skip(); var asked_for_help = false; while (looking.next()) |arg| { if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) asked_for_help = true; } var scan: std.process.Args.Iterator = .init(args); _ = scan.skip(); while (!asked_for_help) { const arg = scan.next() orelse break; if (!std.mem.eql(u8, arg, "--config")) continue; const path = scan.next() orelse { std.debug.print("zig65: --config needs a path\n\n{s}", .{usage}); std.process.exit(2); }; var trouble: config.Trouble = undefined; const file = config.read(io, gpa, path, &trouble) catch { std.debug.print("zig65: ", .{}); trouble.say(); std.process.exit(2); }; applyConfig(&options, &rom, file); } } var it: std.process.Args.Iterator = .init(args); _ = it.skip(); // the name the program was invoked by const wants = struct { fn path(iterator: *std.process.Args.Iterator, flag: []const u8) []const u8 { return iterator.next() orelse { std.debug.print("zig65: {s} needs a path\n\n{s}", .{ flag, usage }); std.process.exit(2); }; } }; while (it.next()) |arg| { if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { std.debug.print("{s}", .{usage}); return null; } else if (std.mem.eql(u8, arg, "--config")) { // Already read, above. _ = wants.path(&it, "--config"); } else if (std.mem.eql(u8, arg, "--machine")) { const name = wants.path(&it, "--machine"); options.machine = Machine.parse(name) orelse { std.debug.print("zig65: no such machine as '{s}'\n\n{s}", .{ name, usage }); std.process.exit(2); }; // A III Plus is the same machine with a clock chip in its socket. if (std.mem.eql(u8, name, "iii+")) options.plus = true; } else if (std.mem.eql(u8, arg, "--processor")) { const name = wants.path(&it, "--processor"); options.processor = Processor.parse(name) orelse { std.debug.print("zig65: no such processor as '{s}'\n\n{s}", .{ name, usage }); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--rom")) { rom = wants.path(&it, "--rom"); } else if (std.mem.eql(u8, arg, "--video-rom")) { const name = wants.path(&it, "--video-rom"); options.video_rom = VideoRom.parse(name) orelse { std.debug.print("zig65: --video-rom wants original or enhanced, not '{s}'\n\n{s}", .{ name, usage }); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--disk-rom")) { options.disk_rom = wants.path(&it, "--disk-rom"); } else if (std.mem.eql(u8, arg, "--aci-rom")) { options.aci_rom = wants.path(&it, "--aci-rom"); } else if (std.mem.eql(u8, arg, "--disk1")) { options.disks[0] = wants.path(&it, "--disk1"); } else if (std.mem.eql(u8, arg, "--disk2")) { options.disks[1] = wants.path(&it, "--disk2"); } else if (std.mem.eql(u8, arg, "--slot")) { const text = wants.path(&it, "--slot"); const equals = std.mem.indexOfScalar(u8, text, '=') orelse { std.debug.print("zig65: --slot wants SLOT=CARD, as in --slot 4=mockingboard, not '{s}'\n", .{text}); std.process.exit(2); }; const number = std.fmt.parseInt(u8, text[0..equals], 10) catch 0; if (number < 1 or number > 7) { std.debug.print("zig65: '{s}' is not a slot: an Apple II has seven, numbered 1 to 7\n", .{text[0..equals]}); std.process.exit(2); } const kind = CardKind.parse(text[equals + 1 ..]) orelse { std.debug.print("zig65: no such card as '{s}'. There is ", .{text[equals + 1 ..]}); inline for (@typeInfo(CardKind).@"enum".fields, 0..) |field, n| { if (n > 0) std.debug.print(", ", .{}); std.debug.print("{s}", .{field.name}); } std.debug.print("\n", .{}); std.process.exit(2); }; if (options.slots[number]) |already| { std.debug.print("zig65: slot {d} already has {s} in it\n", .{ number, already.shown() }); std.process.exit(2); } options.slots[number] = kind; } else if (std.mem.eql(u8, arg, "--unidisk")) { options.unidisks[0] = wants.path(&it, "--unidisk"); } else if (std.mem.eql(u8, arg, "--unidisk2")) { options.unidisks[1] = wants.path(&it, "--unidisk2"); } else if (std.mem.eql(u8, arg, "--audio")) { options.audio = wants.path(&it, "--audio"); } else if (std.mem.eql(u8, arg, "--no-audio")) { options.sound = false; } else if (std.mem.eql(u8, arg, "--volume")) { const text = wants.path(&it, "--volume"); options.volume = std.fmt.parseInt(u8, text, 10) catch { std.debug.print("zig65: --volume wants a number from 0 to 100, not '{s}'\n", .{text}); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--mute")) { options.mute = true; } else if (std.mem.eql(u8, arg, "--screenshot")) { options.screenshot = wants.path(&it, "--screenshot"); } else if (std.mem.eql(u8, arg, "--snapshot")) { options.snapshot = wants.path(&it, "--snapshot"); } else if (std.mem.eql(u8, arg, "--monitor")) { const name = wants.path(&it, "--monitor"); options.monitor = terminal.Monitor.parse(name) orelse { std.debug.print("zig65: --monitor wants monochrome, colour, ntsc or flat-panel, not '{s}'\n", .{name}); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--text")) { const name = wants.path(&it, "--text"); options.text = terminal.TextDrawing.parse(name) orelse { std.debug.print("zig65: --text wants terminal or pixels, not '{s}'\n", .{name}); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--halted")) { options.halted = true; } else if (std.mem.eql(u8, arg, "--cassette-in")) { options.cassette_in = wants.path(&it, "--cassette-in"); } else if (std.mem.eql(u8, arg, "--cassette-out")) { options.cassette_out = wants.path(&it, "--cassette-out"); } else if (std.mem.eql(u8, arg, "--hard-disk")) { // The card has two drives, so a second --hard-disk fills the // second rather than replacing the first. const path = wants.path(&it, "--hard-disk"); if (options.hard_disks[0] == null) options.hard_disks[0] = path else options.hard_disks[1] = path; } else if (std.mem.eql(u8, arg, "--scsi-rom")) { options.scsi_rom = wants.path(&it, "--scsi-rom"); } else if (std.mem.eql(u8, arg, "--scsi")) { // `--scsi PATH` hooks a drive up at the highest identity still // free, counting down from six the way an owner setting jumpers // would; `--scsi ID:PATH` says which. Seven is the card's. const given = wants.path(&it, "--scsi"); var id: u3 = 6; var path = given; if (given.len > 1 and given[1] == ':' and given[0] >= '0' and given[0] <= '6') { id = @intCast(given[0] - '0'); path = given[2..]; } else { while (options.scsi_disks[id] != null) : (id -= 1) { if (id == 0) { std.debug.print("zig65: a SCSI bus holds seven drives and they are all taken\n", .{}); std.process.exit(2); } } } if (options.scsi_disks[id] != null) { std.debug.print("zig65: there is already a drive at SCSI {d}\n", .{id}); std.process.exit(2); } options.scsi_disks[id] = path; } else if (std.mem.eql(u8, arg, "--memory")) { const text = wants.path(&it, "--memory"); options.memory = parseMemory(text, &options.memory_hires) orelse { std.debug.print("zig65: --memory wants a size like 1M, 512K or 48K, not '{s}'\n\n{s}", .{ text, usage }); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--revision")) { const text = wants.path(&it, "--revision"); options.revision = std.fmt.parseInt(u8, text, 10) catch { std.debug.print("zig65: --revision wants 0 or 1, not '{s}'\n\n{s}", .{ text, usage }); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--parallel-out")) { options.parallel_out = wants.path(&it, "--parallel-out"); } else if (std.mem.eql(u8, arg, "--serial-rom")) { options.serial_rom = wants.path(&it, "--serial-rom"); } else if (std.mem.eql(u8, arg, "--videx-rom")) { options.videx_rom = wants.path(&it, "--videx-rom"); } else if (std.mem.eql(u8, arg, "--videx-charset")) { options.videx_charset = wants.path(&it, "--videx-charset"); } else if (std.mem.eql(u8, arg, "--videx-alternate")) { options.videx_alternate = wants.path(&it, "--videx-alternate"); } else if (std.mem.eql(u8, arg, "--ultraterm-rom")) { options.ultraterm_rom = wants.path(&it, "--ultraterm-rom"); } else if (std.mem.eql(u8, arg, "--ultraterm-charset")) { options.ultraterm_charset = wants.path(&it, "--ultraterm-charset"); } else if (std.mem.eql(u8, arg, "--serial-in")) { 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, "--imagewriter")) { options.imagewriter = wants.path(&it, "--imagewriter"); } else if (std.mem.eql(u8, arg, "--modem")) { options.modem = true; } else if (std.mem.eql(u8, arg, "--modem-answer")) { options.modem = true; options.modem_answer = std.fmt.parseInt(u16, wants.path(&it, "--modem-answer"), 10) catch { std.debug.print("zig65: --modem-answer wants a port number\n", .{}); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--printer-out")) { options.printer_out = wants.path(&it, "--printer-out"); } else if (std.mem.eql(u8, arg, "--passport")) { options.passport = true; } else if (std.mem.eql(u8, arg, "--uthernet")) { options.uthernet = true; } else if (std.mem.eql(u8, arg, "--uthernet1")) { options.uthernet1 = true; } else if (std.mem.eql(u8, arg, "--ethernet-interface")) { options.ethernet_interface = wants.path(&it, "--ethernet-interface"); } else if (std.mem.eql(u8, arg, "--mac")) { options.mac = wants.path(&it, "--mac"); } else if (std.mem.eql(u8, arg, "--midi-in")) { options.passport = true; options.midi_in = wants.path(&it, "--midi-in"); } else if (std.mem.eql(u8, arg, "--midi-out")) { options.passport = true; options.midi_out = wants.path(&it, "--midi-out"); } else if (std.mem.eql(u8, arg, "--localtalk")) { options.localtalk = true; } else if (std.mem.eql(u8, arg, "--localtalk-log")) { options.localtalk_log = wants.path(&it, "--localtalk-log"); } else if (std.mem.eql(u8, arg, "--localtalk-interface")) { options.localtalk_interface = wants.path(&it, "--localtalk-interface"); } else if (std.mem.eql(u8, arg, "--appletalk")) { options.appletalk = true; } else if (std.mem.eql(u8, arg, "--battery-ram")) { options.battery_ram = wants.path(&it, "--battery-ram"); } else if (std.mem.eql(u8, arg, "--mouse")) { options.mouse = true; } else if (std.mem.eql(u8, arg, "--mockingboard")) { options.mockingboard = true; } else if (std.mem.eql(u8, arg, "--phasor")) { options.phasor = true; } else if (std.mem.eql(u8, arg, "--sound-speech")) { options.soundspeech = true; } else if (std.mem.eql(u8, arg, "--mockingboard-speech")) { options.mockingboard = true; options.speech = true; } else if (std.mem.eql(u8, arg, "--clock")) { options.clock = true; } else if (std.mem.eql(u8, arg, "--clock-offset")) { const hours = wants.path(&it, "--clock-offset"); options.clock_offset = std.fmt.parseInt(i8, hours, 10) catch { std.debug.print("zig65: --clock-offset wants a number of hours, not '{s}'\n", .{hours}); std.process.exit(2); }; if (options.clock_offset < -12 or options.clock_offset > 14) { std.debug.print("zig65: --clock-offset is hours from UTC, so between -12 and 14\n", .{}); std.process.exit(2); } options.clock = true; } else if (std.mem.eql(u8, arg, "--ramfactor-rom")) { options.ramfactor_rom = wants.path(&it, "--ramfactor-rom"); } else if (std.mem.eql(u8, arg, "--ramfactor")) { const text = wants.path(&it, "--ramfactor"); options.ramfactor_size = parseSize(text) orelse { std.debug.print("zig65: --ramfactor wants a size like 512K, not '{s}'\n\n{s}", .{ text, usage }); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--memory-expansion")) { const text = wants.path(&it, "--memory-expansion"); options.memory_expansion = parseSize(text) orelse { std.debug.print("zig65: --memory-expansion wants a size like 512K, not '{s}'\n\n{s}", .{ text, usage }); std.process.exit(2); }; } else if (std.mem.eql(u8, arg, "--ramcharger")) { options.ramcharger = wants.path(&it, "--ramcharger"); } else if (std.mem.eql(u8, arg, "--writable")) { options.writable = true; } else if (std.mem.eql(u8, arg, "--drives")) { const count = wants.path(&it, "--drives"); options.drives = std.fmt.parseInt(u2, count, 10) catch { std.debug.print("zig65: --drives takes 0, 1 or 2, not '{s}'\n\n{s}", .{ count, usage }); std.process.exit(2); }; if (options.drives > 2) { std.debug.print("zig65: a Disk II card has room for two drives\n\n{s}", .{usage}); std.process.exit(2); } } else { std.debug.print("zig65: unrecognised argument '{s}'\n\n{s}", .{ arg, usage }); std.process.exit(2); } } options.rom = rom orelse { std.debug.print("zig65: --rom is required\n\n{s}", .{usage}); std.process.exit(2); }; // A disk with nothing to read it is worth saying out loud rather than // quietly ignoring: the card is what reads a disk, and it is a separate // ROM from the machine's own. for (options.disks, 1..) |disk, which| { // A IIc reads a disk with what is soldered into it, so there is no // card ROM to ask for there. if (disk != null and options.disk_rom == null and options.machine.needsDiskCard()) { std.debug.print("zig65: --disk{d} needs --disk-rom: without the card's ROM there is no drive to put it in\n\n{s}", .{ which, usage }); std.process.exit(2); } if (disk != null and which > options.drives and options.machine.needsDiskCard()) { std.debug.print("zig65: --disk{d} needs --drives {d}\n\n{s}", .{ which, which, usage }); std.process.exit(2); } } // Only a IIgs takes this, and saying so is better than putting a disk // somewhere it will not be looked for: every other machine that can have // one of these has no drive of its own to confuse it with, and --disk1 // reaches it by the size of the image. for (options.unidisks, 1..) |disk, which| { if (disk != null and options.machine != .iigs) { std.debug.print("zig65: --unidisk{s} is for --machine iigs; elsewhere an 800K image handed to --disk1 goes to the UniDisk 3.5 by itself\n\n{s}", .{ if (which == 1) "" else "2", usage, }); std.process.exit(2); } } return options; } /// What a byte on the text page means. It is not ASCII: the Apple II keeps /// the character in the low five bits and what to do with it in the high /// three, so printing the byte as though it were a character gives nonsense. /// The screen and keyboard pieces the IIgs front end shares with this one. const block = terminal.block; const half_block = terminal.half_block; const ascii = terminal.ascii; /// How wide the machine's screen is drawn, and how tall, borders included. /// /// Fixed at eighty columns whatever the machine is showing. A monitor does not /// change size when the program switches to forty columns or to graphics — the /// dots get wider, and that is the machine's business rather than the /// window's. Sizing the pane to the mode instead made the whole layout jump /// about every time a program called `PR#3`. const monitor_width = 80 + 2; const monitor_height = screen.rows + 2; /// And how wide the debugger's own panes are, which has not changed. const panes_width = 76; /// How often at most a changed screen is sent to a terminal that draws /// pictures. /// /// Every frame would be sixty of them a second and a frame is most of a /// megabyte encoded, which is two and a half megabytes a second down a pipe /// for a picture nobody can see move that fast. Twenty is plenty for watching /// a program draw, and a screen that changes once and stops is late by fifty /// milliseconds, which nobody has ever noticed. const picture_ns = 50 * std.time.ns_per_ms; const Event = union(enum) { key_press: vaxis.Key, key_release: vaxis.Key, mouse: vaxis.Mouse, focus_in, // window has gained focus focus_out, // window has lost focus paste_start, // bracketed paste start paste_end, // bracketed paste end paste: []const u8, // osc 52 paste, caller must free color_report: vaxis.Color.Report, // osc 4, 10, 11, 12 response color_scheme: vaxis.Color.Scheme, // light / dark OS theme changes winsize: vaxis.Winsize, // the window size has changed. This event is always sent when the loop // is started }; /// A path being typed at the debugger, which is the one time keys are not the /// machine's. Changing a disk needs a name from somewhere and a terminal has /// nowhere else to put one. const Prompt = struct { drive: u1, 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: u1, selection: usize = 0, /// The list of 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: every disk in a reasonable /// library and the three fixed choices under it. const picker_choices_max = 64; fn Debugger(comptime machine: Machine, comptime processor: Processor) type { return struct { const Self = @This(); /// The processor and the machine around it, together. Everything below /// asks this what it can do rather than asking which machine it is: /// `@hasDecl` and `@hasField` against the memory model is how a IIe's /// drives, a IIc's soldered-in ones and the flat model's absence of /// both are told apart, so a machine added later needs nothing here. pub const CPU = Cpu(machine, processor); const SessionT = sess.Session(CPU, machine.hasSlots(), machine == .iii); /// The machine and everything that drives it, with no front end in /// it. The terminal debugger is this plus the drawing and the keys. session: SessionT, /// The host's live audio, opened once at startup and kept for the life /// of the program: a machine reset makes a fresh recording but the one /// stream stays open, so the sound does not flicker. The recording /// borrows this; the volume keys work it. Silent until `init` opens it. audio: sess.audio.Output = .{}, io: std.Io, alloc: std.mem.Allocator, should_quit: bool, tty_buf: [128]u8, tty: vaxis.Tty, writer: *std.Io.Writer, vx: vaxis.Vaxis, mouse: ?vaxis.Mouse, memory_page: u8 = 0, /// A path being typed, while a disk is being changed. prompt: ?Prompt, /// A path being typed for a save state, `alt+w` to write one and /// `alt+l` to load one. snapshot_prompt: ?SnapshotPrompt = null, /// The machine's screen as a picture, for a terminal that can show one. display: terminal.Display, /// Which monitor the machine is being looked at on, and who draws the /// text. See `terminal.Monitor` and `terminal.TextDrawing`. monitor: terminal.Monitor, text: terminal.TextDrawing, /// Which monitor the terminal is looking at when a Videoterm is /// fitted: the card's, or the Apple's own. `alt+v` swaps them. videx: bool = true, /// Where alt+g writes a picture of the screen. screenshot: []const u8, /// How the machine was built, kept so that `alt+w` can write a config /// beside a snapshot that builds the same machine and boots into it. options: Options, /// 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, /// A paste in progress. The terminal wraps a paste between a start and /// an end event (bracketed paste), and the keys arriving between them /// are gathered here as the bytes they stand for rather than handed to /// the machine one at a time, so the whole paste can be tidied — its /// line endings especially — before it is fed in. See /// `terminal.pasteKeys`, and `alt+y` copies the other way. pasting: bool, paste_buf: std.ArrayList(u8), /// An ImageWriter II on the serial line, rendering the machine's print /// stream to PNG pages, when `--imagewriter` asked for one. Null /// otherwise. Held here so it is finished and freed when the program /// ends; the session writes to it through `serial_sink`. imagewriter: ?*ImageWriter, /// Brings up the terminal and the processor in place, and loads the Apple /// II+ ROM so there is something to step through. pub fn init( self: *Self, io: std.Io, alloc: std.mem.Allocator, env_map: *std.process.Environ.Map, options: Options, ) !void { const rom_path = options.rom; self.io = io; self.alloc = alloc; self.session.io = io; self.session.alloc = alloc; self.should_quit = false; // Every field is set here: the struct is brought up undefined, so a // default written on the declaration never runs. These three had // only their declaration defaults and so were read undefined — the // snapshot prompt's garbage `.len` was an out-of-bounds slice on // the very first frame the moment the stack it landed on was not // zero, which the config path, doing its parsing first, makes sure // of. self.memory_page = 0; self.snapshot_prompt = null; self.picker = null; self.videx = true; // Left undefined otherwise when the machine has no speaker or // --no-audio was given, and deinit would close a garbage stream. self.audio = .{}; self.pasting = false; self.paste_buf = .empty; self.imagewriter = null; self.session.floppies = .{ null, null }; self.session.floppy35 = null; self.session.disk35_path = null; self.session.unidisk_blocks = .{ null, null }; self.session.unidisk_path = .{ null, null }; self.session.disk_paths = .{ null, null }; self.session.disk_labels = .{ null, null }; self.session.writable = options.writable; self.prompt = null; self.session.recording = null; self.session.printer = null; self.session.buttons = .{ false, false }; self.session.tape_recording = null; self.session.tape = null; self.session.volume = null; self.session.volume_file = null; self.session.volume_path = null; self.session.memory_card_ram = null; self.session.firmware = .empty; self.session.ramcharger_path = null; // Only filled per drive when a SCSI card is fitted, so the arrays // themselves have to start empty or deinit frees whatever the // undefined memory held -- the same class of bug the snapshot // prompt was, reached now that the machine survives to quit. self.session.scsi_images = @splat(null); self.session.scsi_paths = @splat(null); self.session.serial_out = null; self.session.serial_in = null; self.session.serial_in_at = 0; self.session.serial_in_due = 0; self.session.modem = null; self.session.modem_line = .{}; self.session.modem_in_due = 0; self.session.midi_out = null; self.session.midi_in = null; self.session.midi_in_at = 0; self.session.uthernet = .{}; self.session.ethernet = null; self.session.note_len = 0; self.session.note_drive = null; self.session.message_len = 0; self.screenshot = options.screenshot; self.options = options; self.library = options.library; self.display = .{}; self.monitor = options.monitor; self.text = options.text; try self.session.cpu.init(null, null); // Whatever the command line named. There is no ROM built in, so there // is nothing to fall back to. const rom = std.Io.Dir.cwd().readFileAlloc(io, rom_path, alloc, .limited(rom_limit)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ rom_path, @errorName(err) }); if (err == error.StreamTooLong) std.debug.print("zig65: a ROM can be at most {d} bytes\n", .{rom_limit}); std.process.exit(1); }; defer alloc.free(rom); if (rom.len == 0) { std.debug.print("zig65: '{s}' is empty\n", .{rom_path}); std.process.exit(1); } try self.session.cpu.memory.loadROMAtEnd(rom); // How much RAM is on the board, and which board it is. Only the // two machines whose boards came in variations take either. if (comptime @hasDecl(CPU.Memory, "fitRam")) { if (options.memory) |bytes| { const layout: zig65.memory.apple2plus.Layout = if (options.memory_hires) .hires else .contiguous; self.session.cpu.memory.fitRam(bytes, layout) catch { std.debug.print("zig65: {d}K is not a way this board was populated; see --memory in --help\n", .{bytes / 1024}); std.process.exit(1); }; } if (options.revision) |n| { if (n == 0 and comptime machine == .ii) { self.session.cpu.memory.revision = .zero; } else if (n > 1 or n == 0) { std.debug.print("zig65: --revision wants 0 or 1, and only an Apple II was ever Revision 0\n", .{}); std.process.exit(1); } } } else if (comptime @hasDecl(CPU.Memory, "fitMemory")) { if (options.memory) |bytes| { self.session.cpu.memory.fitMemory(bytes) catch { const took = if (comptime machine == .iii) "an Apple III took 128K, 256K or 512K" else "an Apple-1 board took 4K or 8K"; std.debug.print("zig65: {s}, not {d}K\n", .{ took, bytes / 1024 }); std.process.exit(1); }; } if (options.revision != null) { std.debug.print("zig65: --revision is about the Apple II's board\n", .{}); std.process.exit(1); } } else if (options.revision != null) { std.debug.print("zig65: --revision is about the Apple II's board; this machine has one board\n", .{}); std.process.exit(1); } // Which IIe this is, and whether the chips agree. The enhancement // was four chips sold together, and the model fits the character // generator that goes with the firmware it finds; an owner who // changed one and not the other says so with --video-rom. if (comptime machine == .iie) { if (options.video_rom) |chip| self.session.cpu.memory.fitCharacterGenerator(chip.set()); if (self.session.cpu.memory.firmware == .enhanced and comptime (processor == .@"6502" or processor == .RP2A03)) { self.session.announce("enhanced firmware on a {s}: it was written for the 65C02 that came with it, and uses its instructions", .{@tagName(processor)}); } } else if (options.video_rom != null) { std.debug.print("zig65: --video-rom is about a IIe's character generator; this machine has the one it has\n", .{}); std.process.exit(1); } // The card, if the command line asked for one. It is a separate ROM // from the machine's: the machine has no idea how to read a disk, and // what it does at startup is look through the slots for something that // does and hand over to it. if (comptime SessionT.hasDrives() and !SessionT.wantsCard()) { // A IIc's drive is soldered into the case and its driver is in the // machine's own ROM, so there is no card to fit and no boot PROM // to supply. --drives says whether the socket on the back has one // on the end of it as well. A III is the same: its controller // is on the board and its first drive is in the case. self.session.cpu.memory.drives().fitted = @max(1, options.drives); } else if (options.disk_rom) |card_path| { if (comptime !SessionT.wantsCard()) { std.debug.print("zig65: this machine has no slots to put a disk card in\n", .{}); std.process.exit(1); } const card_bytes = std.Io.Dir.cwd().readFileAlloc(io, card_path, alloc, .limited(0x101)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ card_path, @errorName(err) }); std.process.exit(1); }; // The card keeps these bytes rather than a copy of them, so // the session holds them for as long as the machine does. const card = self.session.keepFirmware(card_bytes) catch @panic("out of memory"); self.session.cpu.memory.fitDisk(slotFor(options, .disk), card) catch { std.debug.print("zig65: '{s}' is {d} bytes; a Disk II boot ROM is 256\n", .{ card_path, card.len }); std.process.exit(1); }; self.session.cpu.memory.drives().fitted = options.drives; } // The Apple-1's Cassette Interface. Its PROM is its program, and the // machine has no idea a tape exists until the card is there: the // port is on the card. if (options.aci_rom) |card_path| { if (comptime @hasDecl(CPU.Memory, "fitCassetteInterface")) { // Read whole, so that a file of the wrong size is told // its size rather than that it could not be read. const card = std.Io.Dir.cwd().readFileAlloc(io, card_path, alloc, .limited(1 << 20)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ card_path, @errorName(err) }); std.process.exit(1); }; defer alloc.free(card); self.session.cpu.memory.fitCassetteInterface(card) catch { std.debug.print("zig65: '{s}' is {d} bytes; the Cassette Interface's PROM is 256\n", .{ card_path, card.len }); std.process.exit(1); }; } else { std.debug.print("zig65: --aci-rom is the Apple-1's Cassette Interface, and this is not an Apple-1\n", .{}); std.process.exit(1); } } // Power on. A Revision 0 Apple II had no power-up reset: the // processor started from whatever its lines happened to hold // and the owner pressed RESET (Sather, 1983, Appendix G). So that // board is not reset here, and the debugger says why the screen // is what it is. const unreset = if (comptime machine == .ii) self.session.cpu.memory.revision == .zero else false; if (unreset) { self.session.announce("Revision 0: no power-up reset. Press reset (alt+b), then run (alt+r).", .{}); } else { self.session.cpu.reset(); } self.tty = try vaxis.Tty.init(io, &self.tty_buf); self.writer = self.tty.writer(); self.vx = try vaxis.init(io, self.alloc, env_map, .{}); self.mouse = null; // Start stopped, so that the ROM is not already somewhere unexpected // by the time the first frame is drawn. self.session.state = if (options.halted) .single_step else .running; // A processor nobody has reset is not running anything worth // showing; it waits for the key the owner of that board pressed. if (unreset) self.session.state = .halted; self.session.target_hz = SessionT.machine_hz; self.session.owed_cycles = 0; self.session.last_step = .now(io, sess.pacing_clock); self.session.next_frame = .now(io, sess.pacing_clock); self.session.stopped = null; self.session.typed_len = 0; self.session.paste = .empty; self.session.paste_at = 0; self.session.serial_sink = null; self.session.last_key = 0; self.session.speaker_clicks = 0; self.session.last_bell = .now(io, sess.pacing_clock); self.session.measured_hz = 0; self.session.measured_at = .now(io, sess.pacing_clock); self.session.measured_cycles = 0; self.session.flash = false; self.session.flash_at = .now(io, sess.pacing_clock); // sess.Recording, if it was asked for. The speed goes with it: sound played // faster or slower than the machine played it is the wrong sound, so // the machine is held at its own rate and the speed keys are refused. if (comptime SessionT.hasSpeaker()) { // Live audio, on by default: open the host's speaker so the // machine can be heard. It falls back to silence if there is no // daemon to talk to, and it is kept for the life of the program // -- a reset makes a fresh recording but not a fresh stream. if (options.sound) { var volume = sess.audio.Volume.fromPercent(options.volume); volume.muted = options.mute; self.audio = sess.audio.Output.open(alloc, "zig65", volume); } // The recording renders the speaker once and hands it to the // file, the live speaker, or both. A file holds the machine to // its own rate -- sound played faster than the machine played it // is the wrong sound -- but live audio does not, and drops what // it cannot keep up with instead, so the speed keys still work // when only it is playing. if (options.audio != null or self.audio.live()) { if (options.audio != null) self.session.target_hz = SessionT.machine_hz; self.session.recording = sess.Recording.open( io, alloc, options.audio, &self.audio, SessionT.machine_hz, self.session.cpu.clock.cycles, options.mockingboard, options.phasor, options.soundspeech, @hasField(CPU.Memory, "dac_log"), ) catch |err| { std.debug.print("zig65: cannot record to '{s}': {s}\n", .{ options.audio orelse "the speaker", @errorName(err) }); std.process.exit(1); }; } } else if (options.audio != null) { std.debug.print("zig65: this machine has no speaker to record\n", .{}); std.process.exit(1); } // The printer card in slot 1. What is on the end of its cable is // a file, which is the one thing a terminal can be a printer for. if (options.parallel_out) |path| { if (comptime !SessionT.hasParallel()) { std.debug.print("zig65: this machine has no slots to put a printer card in\n", .{}); std.process.exit(1); } self.session.printer = sess.Printer.open(io, alloc, path) catch |err| { std.debug.print("zig65: cannot print to '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; if (comptime SessionT.hasParallel()) { // An Apple III's parallel card is the UPIC, and its four // slots are numbered differently from a II's seven. const slot = if (comptime @hasDecl(CPU.Memory, "fitCard")) slotForIII(options, .parallel, 1) else slotFor(options, .parallel); self.session.cpu.memory.fitPrinter(slot, &self.session.printer.?.writer.interface); } } // The cassette port. Neither of these holds the machine to its own // speed the way recording the speaker does: both are worked out from // the machine's clock rather than the wall, so a tape written by a // machine running ten times over still plays back at the speed a real // one would, and a tape read in loads ten times as fast, exactly as // the program reading it does. if (comptime SessionT.hasCassette()) { if (comptime @hasDecl(CPU.Memory, "fitCassetteInterface")) { if (options.aci_rom == null and (options.cassette_in != null or options.cassette_out != null)) { std.debug.print("zig65: an Apple-1 has no cassette port of its own: --aci-rom PATH fits the Cassette Interface, which has one\n", .{}); std.process.exit(1); } } if (options.cassette_out) |path| { // The cassette is one line like the speaker, so this one is // never the card's two channels. self.session.tape_recording = sess.Recording.open( io, alloc, path, // The cassette output is a data signal saved to a // file, not something to play live, so no live output. null, SessionT.machine_hz, self.session.cpu.clock.cycles, false, false, false, false, ) catch |err| { std.debug.print("zig65: cannot record to '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (options.cassette_in) |path| { self.session.tape = sess.Tape.read(io, alloc, path) catch |err| { std.debug.print("zig65: cannot play '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; self.session.cpu.memory.playTape(self.session.tape.?.levels, self.session.tape.?.sample_rate); } } else if (options.cassette_in != null or options.cassette_out != null) { std.debug.print("zig65: this machine has no cassette port\n", .{}); std.process.exit(1); } // The block device, which needs nothing but something to put in it: // its firmware is ours and is built into the machine. if (options.mockingboard and options.mouse) { std.debug.print("zig65: a slot holds one card, and both of these want slot 4\n", .{}); std.process.exit(2); } if (options.mockingboard) { if (comptime !SessionT.hasMouse()) { std.debug.print("zig65: this machine has no slots to put a sound card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitMockingboard(slotFor(options, .mockingboard), options.speech); } if (options.phasor) { if (comptime !SessionT.hasMouse()) { std.debug.print("zig65: this machine has no slots to put a sound card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitPhasor(slotFor(options, .phasor)); } if (options.soundspeech) { if (comptime !SessionT.hasMouse()) { std.debug.print("zig65: this machine has no slots to put a sound card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitSoundSpeech(slotFor(options, .soundspeech)); } if (options.mouse) { if (comptime !SessionT.hasMouse()) { std.debug.print("zig65: this machine has no slots to put a mouse card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitMouse(slotFor(options, .mouse)); } // 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. if (options.clock or options.plus) { if (comptime !SessionT.hasClock()) { std.debug.print("zig65: this machine has no slots to put a clock card in\n", .{}); std.process.exit(1); } const nanoseconds = std.Io.Timestamp.now(io, .real).nanoseconds; const seconds: i64 = @intCast(@divFloor(nanoseconds, std.time.ns_per_s)); const shifted = seconds + @as(i64, options.clock_offset) * 60 * 60; if (comptime @hasDecl(CPU.Memory, "fitClock")) { self.session.cpu.memory.fitClock(slotFor(options, .clock), .fromEpoch(shifted), self.session.cpu.clock.cycles); } else { // An Apple III has the chip's socket on the board, and // this puts a chip in it, set as the owner of one would // have set it. self.session.cpu.memory.clock.set(.fromEpoch(shifted), self.session.cpu.clock.cycles); self.session.cpu.memory.clock.fitted = true; } } // And the other card that can be in slot 5: a megabyte of memory // behind four addresses, which its own firmware turns into a // RAMdisk. The ROM is Applied Engineering's, so naming it is what // fits the card; the memory is allocated here because a card can // carry sixteen times what the machine itself has and putting it // in the memory model would put it on the stack. if (options.ramfactor_rom) |path| { if (comptime !SessionT.hasMemoryCard()) { std.debug.print("zig65: this machine has no slots to put a memory expansion card in\n", .{}); std.process.exit(1); } const size = options.ramfactor_size orelse ramfactor.max_ram; if (size == 0 or size % ramfactor.block_size != 0 or size > ramfactor.max_ram) { std.debug.print( "zig65: a RamFactor holds one to four blocks of 256K, so --ramfactor is 256K, 512K, 768K or 1024K\n", .{}, ); std.process.exit(1); } const firmware = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(ramfactor.rom_size + 1)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(firmware) catch @panic("out of memory"); if (firmware.len != ramfactor.rom_size) { std.debug.print( "zig65: '{s}' is {d} bytes; a RamFactor ROM is {d}\n", .{ path, firmware.len, ramfactor.rom_size }, ); std.process.exit(1); } // A card with the RamCharger on it comes up holding whatever // it held when the machine was switched off, which is what the // battery was for. Without one the chips come up empty, and // the firmware finds an unformatted card and formats it. var ram: []u8 = undefined; if (options.ramcharger) |kept| { ram = std.Io.Dir.cwd().readFileAlloc(io, kept, alloc, .limited(ramfactor.max_ram + 1)) catch |err| switch (err) { // No file yet is a battery that has never been // charged, not a mistake: the card starts empty and // the file is written when the machine is switched // off. error.FileNotFound => fresh: { const empty = try alloc.alloc(u8, size); @memset(empty, 0); break :fresh empty; }, else => { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ kept, @errorName(err) }); std.process.exit(1); }, }; if (ram.len != size) { std.debug.print( "zig65: '{s}' holds {d} bytes and the card has {d}; a RamCharger keeps what the card had\n", .{ kept, ram.len, size }, ); std.process.exit(1); } self.session.ramcharger_path = try alloc.dupe(u8, kept); } else { ram = try alloc.alloc(u8, size); @memset(ram, 0); } self.session.memory_card_ram = ram; if (comptime SessionT.hasMemoryCard()) self.session.cpu.memory.fitRamFactor(slotFor(options, .ramfactor), firmware, ram) catch { std.debug.print("zig65: that is not a RamFactor's worth of ROM and memory\n", .{}); std.process.exit(1); }; } // An Apple II SCSI Card, whose firmware is Apple's and so has to // be handed over. The disk on its bus is a plain ProDOS volume: // there are no tracks and no sectors on a SCSI disk, only blocks // and a command set, so anything `diskfile` can open as an image // goes on it whole. if (comptime @hasDecl(CPU.Memory, "fitScsi")) { if (options.scsi_rom) |path| { const firmware = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .unlimited) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(firmware) catch @panic("out of memory"); self.session.cpu.memory.fitScsi(slotFor(options, .scsi), firmware) catch { std.debug.print( "zig65: '{s}' is {d} bytes; an Apple II SCSI Card's firmware is {d}\n", .{ path, firmware.len, zig65.slots.Card.Scsi.rom_size }, ); std.process.exit(1); }; const card = self.session.cpu.memory.scsiCard(slotFor(options, .scsi)).?; for (options.scsi_disks, 0..) |maybe, id| { const image = maybe orelse continue; const bytes = std.Io.Dir.cwd().readFileAlloc(io, image, alloc, .unlimited) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ image, @errorName(err) }); std.process.exit(1); }; self.session.scsi_images[id] = bytes; card.attach(@intCast(id), bytes, false) catch { std.debug.print("zig65: SCSI {d} is the card's own identity\n", .{id}); std.process.exit(2); }; self.session.scsi_paths[id] = alloc.dupe(u8, image) catch @panic("out of memory"); } } else if (blk: { for (options.scsi_disks) |maybe| if (maybe != null) break :blk true; break :blk false; }) { std.debug.print( "zig65: --scsi needs --scsi-rom: the driver is in the card's own firmware, which is Apple's\n", .{}, ); std.process.exit(1); } } if (options.ramcharger != null or options.ramfactor_size != null) { std.debug.print( "zig65: --ramfactor and --ramcharger need --ramfactor-rom: the RAMdisk is in the card's own firmware\n", .{}, ); std.process.exit(1); } // And the IIc's own memory expansion card, which is not a card in // a slot and wants no firmware: what drives it is in the machine's // ROM, in the bank $C028 switches in, so the later ROMs find it // and the first one has no idea it is there. if (options.memory_expansion) |size| { if (comptime !SessionT.hasMemoryExpansion()) { std.debug.print("zig65: only a IIc has the memory expansion connector\n", .{}); std.process.exit(1); } if (size == 0 or size % ramfactor.block_size != 0 or size > 1024 * 1024) { std.debug.print( "zig65: the memory expansion card holds 256K, 512K, 768K or 1M\n", .{}, ); std.process.exit(1); } const ram = try alloc.alloc(u8, size); @memset(ram, 0); self.session.memory_card_ram = ram; if (comptime SessionT.hasMemoryExpansion()) self.session.cpu.memory.fitMemoryExpansion(ram) catch { std.debug.print("zig65: that is not a memory expansion card's worth of memory\n", .{}); std.process.exit(1); }; } if (options.hard_disks[0]) |path| { if (comptime !SessionT.hasBlockDevice()) { std.debug.print("zig65: this machine has no slots to put a block device in\n", .{}); std.process.exit(1); } const file = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited((32 << 20) + zig65.twomg.header_size)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; // A 2IMG says what it holds and where; a ShrinkIt archive is // unpacked and the disk taken out of it; anything else is // taken as blocks end to end, which is the only thing a hard // disk image is. const opened = zig65.diskfile.open(alloc, file, path) catch |err| { std.debug.print("zig65: cannot make sense of '{s}': {s}\n", .{ path, zig65.diskfile.explain(err), }); std.process.exit(1); }; const image = opened.image; if (image.data.len < zig65.blockdevice.block_size) { std.debug.print("zig65: '{s}' is smaller than one block\n", .{path}); std.process.exit(1); } // A disk that came out of an archive obeys --writable like any // other now that write-back re-archives it into the file // rather than writing the raw disk over it. The archive itself // is let go of straight away; what is kept is the disk that // came out of it. var kept = file; const locked = !options.writable or image.write_protected; if (opened.owned) |unpacked| { alloc.free(file); kept = unpacked; } const volume = try alloc.create(zig65.blockdevice.Volume); volume.* = .{ .image = image.data, // Either the switch or the file's own write-protect tab is // enough to keep the machine off it. .write_protected = locked, }; self.session.volume = volume; self.session.volume_file = kept; self.session.volume_path = try alloc.dupe(u8, path); if (comptime SessionT.hasBlockDevice()) { // Fit the card where it was asked for, before the volume // goes in it: `insertVolume` would otherwise fit one at // the slot a block device has always gone in. if (comptime @hasDecl(CPU.Memory, "fitBlockDevice")) self.session.cpu.memory.fitBlockDevice(slotFor(options, .block)) catch {}; // An Apple III's block device is a ProFile on an interface // card, and which slot that card is in is something SOS is // told rather than something the machine decides, so it // moves like any other -- see `default_profile_slot`. It // stays in slot 4 unless asked, because that is what every // SOS.DRIVER that came to hand is configured for. if (comptime @hasDecl(CPU.Memory, "fitCard")) self.session.cpu.memory.fitCard( slotForIII(options, .block, zig65.memory.apple3.default_profile_slot), .profile, ) catch {}; self.session.cpu.memory.insertVolume(0, volume); } } // The serial card, which like the disk card is only there once its // own firmware has been loaded. if (options.videx_rom) |path| { if (comptime !SessionT.hasVidex()) { std.debug.print("zig65: this machine has no slot to put an eighty column card in\n", .{}); std.process.exit(1); } const charset_path = options.videx_charset orelse { std.debug.print("zig65: --videx-rom needs --videx-charset: the card draws with a character generator, and an empty socket draws nothing\n", .{}); std.process.exit(1); }; const firmware = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(videx.firmware_size + 1)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(firmware) catch @panic("out of memory"); const charset = std.Io.Dir.cwd().readFileAlloc(io, charset_path, alloc, .limited(videx.charset_size + 1)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ charset_path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(charset) catch @panic("out of memory"); const alternate: ?[]const u8 = if (options.videx_alternate) |second| both: { break :both std.Io.Dir.cwd().readFileAlloc(io, second, alloc, .limited(videx.charset_size + 1)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ second, @errorName(err) }); std.process.exit(1); }; } else null; if (alternate) |second| _ = self.session.keepFirmware(@constCast(second)) catch @panic("out of memory"); if (comptime SessionT.hasVidex()) self.session.cpu.memory.fitVidex(slotFor(options, .videx), firmware, charset, alternate) catch { std.debug.print( "zig65: a Videoterm ROM is {d} bytes and a character generator {d}; got {d} and {d}\n", .{ videx.firmware_size, videx.charset_size, firmware.len, charset.len }, ); std.process.exit(1); }; } if (options.ultraterm_rom) |path| { if (comptime !SessionT.hasUltraTerm()) { std.debug.print("zig65: this machine has no slot to put an eighty column card in\n", .{}); std.process.exit(1); } const charset_path = options.ultraterm_charset orelse { std.debug.print("zig65: --ultraterm-rom needs --ultraterm-charset: the card draws with a character generator, and an empty socket draws nothing\n", .{}); std.process.exit(1); }; const firmware = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(ultraterm.firmware_size + 1)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(firmware) catch @panic("out of memory"); const charset = std.Io.Dir.cwd().readFileAlloc(io, charset_path, alloc, .limited(ultraterm.charset_size + 1)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ charset_path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(charset) catch @panic("out of memory"); if (comptime SessionT.hasUltraTerm()) self.session.cpu.memory.fitUltraTerm(slotFor(options, .ultraterm), firmware, charset) catch { std.debug.print( "zig65: an UltraTerm ROM is {d} bytes and a character generator {d}; got {d} and {d}\n", .{ ultraterm.firmware_size, ultraterm.charset_size, firmware.len, charset.len }, ); std.process.exit(1); }; } if (options.serial_rom) |path| { if (comptime !SessionT.hasSerial()) { std.debug.print("zig65: this machine has no slots to put a serial card in\n", .{}); std.process.exit(1); } const firmware = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(0x801)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; _ = self.session.keepFirmware(firmware) catch @panic("out of memory"); if (comptime SessionT.hasSerial()) self.session.cpu.memory.fitSerial(slotFor(options, .serial), firmware) catch { std.debug.print("zig65: '{s}' is {d} bytes; a Super Serial Card ROM is 2048\n", .{ path, firmware.len }); std.process.exit(1); }; } if (options.serial_out) |path| { self.session.serial_out = std.Io.Dir.cwd().createFile(io, path, .{}) catch |err| { std.debug.print("zig65: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (options.serial_in) |path| { self.session.serial_in = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(1 << 24)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if ((options.serial_in != null or options.serial_out != null) and options.serial_rom == null) { std.debug.print("zig65: --serial-in and --serial-out need --serial-rom: without the card's firmware there is no card\n", .{}); std.process.exit(1); } // An ImageWriter II on the serial line, rendering the print stream // to pages. It takes the line the output file otherwise would, so // it needs the card and rules out the other two things that end of // the line can be. if (options.imagewriter) |path| { if (options.serial_rom == null) { std.debug.print("zig65: --imagewriter needs --serial-rom: the printer is on the Super Serial Card\n", .{}); std.process.exit(1); } if (options.serial_out != null) { std.debug.print("zig65: --imagewriter is the serial line's far end, so not with --serial-out\n", .{}); std.process.exit(1); } if (options.modem) { std.debug.print("zig65: --imagewriter and --modem both want the serial line; pick one\n", .{}); std.process.exit(1); } self.imagewriter = ImageWriter.open(io, alloc, path) catch |err| { std.debug.print("zig65: cannot set up the ImageWriter: {s}\n", .{@errorName(err)}); std.process.exit(1); }; self.session.serial_sink = self.imagewriter.?.writer(); } // A Hayes modem on the serial line, dialing out over TCP. It needs // the card, and it takes the line the files otherwise would. if (options.modem) { if (options.serial_rom == null) { std.debug.print("zig65: --modem needs --serial-rom: the modem is on the Super Serial Card\n", .{}); std.process.exit(1); } if (options.serial_in != null or options.serial_out != null) { std.debug.print("zig65: --modem uses the serial line, so not with --serial-in or --serial-out\n", .{}); std.process.exit(1); } self.session.modem = .{}; if (options.modem_answer) |port| self.session.modem_line.listen(port); } // The Passport MIDI interface, and the Standard MIDI Files at each // end of it. It carries no firmware, so unlike the serial card it // needs no ROM to be a card. if (options.passport) { if (comptime !SessionT.hasMidi()) { std.debug.print("zig65: this machine has no slots to put a MIDI card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitPassport(slotFor(options, .passport)); if (options.midi_out) |path| { self.session.midi_out = zig65.smf.Writer.create(io, alloc, path, SessionT.machine_hz) catch |err| { std.debug.print("zig65: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } if (options.midi_in) |path| { const file = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(1 << 24)) catch |err| { std.debug.print("zig65: cannot read '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; defer alloc.free(file); // A MIDI byte is ten bits at 31,250 baud, so the input is // spaced no closer than that however the file is timed. const byte_cycles = SessionT.machine_hz * 10 / 31_250; self.session.midi_in = zig65.smf.read(alloc, file, SessionT.machine_hz, byte_cycles) catch |err| { std.debug.print("zig65: cannot read the MIDI file '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } } else if (options.midi_in != null or options.midi_out != null) { std.debug.print("zig65: --midi-in and --midi-out need a Passport card; add --passport\n", .{}); std.process.exit(1); } // The Uthernet II. Like the Passport it carries no firmware; the // W5100 answers at four of the slot's device-select addresses and // the host end of its sockets is pumped once a frame. if (options.uthernet) { if (comptime !SessionT.hasEthernet()) { std.debug.print("zig65: this machine has no slots to put an Ethernet card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitUthernet(slotFor(options, .uthernet)); } // The Uthernet (the original): the CS8900A, and the multicast // group standing in for its Ethernet. Joining the group can fail, // so unlike the socket-mapped Uthernet II the wire is opened here. if (options.uthernet1) { if (comptime !SessionT.hasCs8900()) { std.debug.print("zig65: this machine has no slots to put an Ethernet card in\n", .{}); std.process.exit(1); } self.session.cpu.memory.fitCs8900(slotFor(options, .uthernet1)); const nanoseconds = std.Io.Timestamp.now(io, .real).nanoseconds; const tag: u32 = @truncate(@as(u96, @bitCast(nanoseconds)) ^ (@as(u96, @intCast(std.os.linux.getpid())) << 20)); var interface: ?[4]u8 = null; if (options.ethernet_interface) |given| { interface = zig65.ethernet.parseAddress(given) orelse { std.debug.print("zig65: --ethernet-interface wants an address like 127.0.0.1, not '{s}'\n", .{given}); std.process.exit(1); }; } self.session.ethernet = zig65.ethernet.Bridge.open(tag, interface) catch |err| blk: { std.debug.print("zig65: cannot join the Ethernet group: {s}\n", .{@errorName(err)}); break :blk null; }; } // A hardware address for whichever Ethernet card is fitted, set // over what the card comes up with; a driver may still write its // own. Parsed by macaddress, through the library. if (options.mac) |given| { const address = zig65.ethernet.parseMac(given) orelse { std.debug.print("zig65: --mac wants a hardware address like 00:11:22:33:44:55, not '{s}'\n", .{given}); std.process.exit(2); }; if (comptime SessionT.hasEthernet()) if (self.session.cpu.memory.ethernetChip()) |c| c.setMac(address); if (comptime SessionT.hasCs8900()) if (self.session.cpu.memory.cs8900Chip()) |c| c.setMac(address); } // Disks last, so that anything wrong with them is reported after the // machine itself is in one piece. for (options.disks, 0..) |path, which| { if (path) |name| self.session.insertDisk(@intCast(which), name, null) catch |err| { std.debug.print("zig65: cannot put '{s}' in drive {d}: {s}\n", .{ name, which + 1, @errorName(err) }); std.process.exit(1); }; } // And a save state on top of all of it, if one was named: the // machine is built the ordinary way first, so its shape matches the // snapshot, and then the snapshot is read into it. if (options.snapshot) |path| self.session.loadSnapshot(path) catch |err| { std.debug.print("zig65: cannot load the snapshot '{s}': {s}\n", .{ path, @errorName(err) }); std.process.exit(1); }; } /// Whether the terminal is looking at the card's monitor rather than /// at the Apple's. /// /// A Videoterm does not switch the Apple's video off. It draws its own /// picture on its own monitor, and an owner had two screens on the desk /// and looked at one of them — which is why this is a choice and not a /// consequence, and why `alt+v` makes it. A terminal has room for one /// of the two, so fitting the card looks at the card, on the grounds /// that nobody fits one in order to keep looking at the other. fn videxShowing(self: *Self) bool { if (comptime !SessionT.hasVidexCard()) return false; return self.videx and self.session.cpu.memory.videxCard() != null; } /// Draws the card's screen: eighty columns by twenty-four, which is /// exactly the monitor pane, so there is nothing to centre. /// /// The terminal draws with its own letters here whatever `alt+x` says, /// because what the card's character generator would draw is a /// different typeface rather than a different character, and a /// terminal has no way to show one. The cursor is drawn rather than /// handed to the terminal, as the machine's own is. fn drawVidex(self: *Self, pane: vaxis.Window) void { if (comptime !SessionT.hasVidexCard()) return; const card = self.session.cpu.memory.videxCard() orelse return; for (0..videx.rows) |row| { for (0..videx.columns) |col| { const byte = card.characterAt(row, col) & 0x7f; const character: u8 = if (byte < 0x20 or byte == 0x7f) ' ' else byte; const cursor = card.cursorIn(row, col) != null; pane.writeCell(@intCast(col), @intCast(row), .{ .char = .{ .grapheme = &ascii[character], .width = 1 }, .style = if (cursor) .{ .reverse = true } else .{}, }); } } } /// Whether the UltraTerm is the card putting a picture on the monitor. /// /// No key decides this, unlike the Videoterm's `alt+v`, and that is the /// difference between the two cards rather than an inconsistency here. /// A Videoterm had a monitor of its own and an owner chose which to /// look at; an UltraTerm has "an electronic switch that will /// automatically select the proper video signal", so the card is /// asked instead, and `PR#3` is what throws it. fn ultraTermShowing(self: *Self) bool { if (comptime !SessionT.hasUltraTermCard()) return false; const card = self.session.cpu.memory.ultraTermCard() orelse return false; return card.driving(); } /// Draws the UltraTerm's screen. /// /// The pane is eighty columns and the card may be showing a hundred and /// sixty, so what will not fit is left off rather than squeezed: a /// terminal cell is a character and there is no half of one. The /// picture written by `alt+g` has all of them. /// /// Its three attributes go to the three the terminal has that mean the /// same thing. Lowlight is dim and highlight is not, which is the way /// round a terminal is: its ordinary brightness is the bright one. fn drawUltraTerm(self: *Self, pane: vaxis.Window) void { if (comptime !SessionT.hasUltraTermCard()) return; const card = self.session.cpu.memory.ultraTermCard() orelse return; const rows = @min(screen.rows, card.rowsShown()); const columns = @min(80, card.columnsShown()); for (0..rows) |row| { for (0..columns) |col| { const byte = card.characterAt(row, col); const attrs = card.attributesOf(byte); const code = byte & 0x7f; const character: u8 = if (code < 0x20 or code == 0x7f) ' ' else code; const cursor = card.cursorIn(row, col) != null; pane.writeCell(@intCast(col), @intCast(row), .{ .char = .{ .grapheme = &ascii[character], .width = 1 }, .style = .{ .reverse = attrs.inverse != cursor, .dim = !attrs.highlight, }, }); } } } /// 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: *Self, event: vaxis.Mouse) void { // A mouse card, if one is fitted, is what the pointer drives. if (comptime SessionT.hasMouse()) { if (self.session.cpu.memory.mouseCard()) |card| { const columns = self.session.machineColumns(); // The screen sits inside a border at the top left, so its // first character is one cell in and one cell down from the // corner — and forty-column text is centred in an // eighty-column monitor, which the pointer has to be told // about too. const left: i16 = @intCast(1 + (80 - columns) / 2); const column = event.col - left; const row = event.row - 1; if (column < 0 or row < 0) return; if (column >= columns or row >= screen.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, screen.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 => {}, } return; } } // Otherwise the pointer is the game paddles, the way AppleWin uses a // PC mouse: a paddle is a knob turned from one end to the other, and // moving the mouse across the screen turns paddle 0, down it turns // paddle 1, with the two mouse buttons the game connector's two. if (comptime SessionT.hasPaddles()) self.mouseToPaddles(event); } /// The terminal pointer driving the paddles and the two game buttons, /// for a machine with a game connector and no mouse card. fn mouseToPaddles(self: *Self, event: vaxis.Mouse) void { const memory = &self.session.cpu.memory; const columns = self.session.machineColumns(); const left: i16 = @intCast(1 + (80 - columns) / 2); const column = event.col - left; const row = event.row - 1; // A paddle reads nought to 255 across whatever it is pointed at; // here that is the visible screen. A pointer off the screen leaves // the paddles where they were rather than snapping them to an edge. if (column >= 0 and row >= 0 and column < columns and row < screen.rows) { memory.setPaddle(0, @intCast(@divTrunc(255 * @as(i32, column), @as(i32, columns) - 1))); memory.setPaddle(1, @intCast(@divTrunc(255 * @as(i32, row), @as(i32, screen.rows) - 1))); } switch (event.type) { .press, .drag => switch (event.button) { .left => memory.setButton(0, true), .right => memory.setButton(1, true), else => {}, }, .release => switch (event.button) { .left => memory.setButton(0, false), .right => memory.setButton(1, false), else => {}, }, .motion => {}, } } /// Writes a picture of the machine's screen. /// /// It is the whole display rather than what the terminal is showing: five /// hundred and sixty dots by a hundred and ninety-two, in the sixteen /// colours, with the lines doubled so that a dot comes out roughly square. /// A terminal cell cannot do that and this is the way to see what the /// machine is actually drawing. fn writeScreenshot(self: *Self) void { self.saveScreenshot() catch |err| { self.session.announce("could not write {s}: {s}", .{ self.screenshot, @errorName(err) }); return; }; self.session.announce("wrote the screen to {s}", .{self.screenshot}); } /// Copies the text on the machine's screen to the host's clipboard, the /// way a person reading it would: each row with its blank right margin /// dropped, the rows joined by newlines, and the empty rows at the foot /// of the screen left off. It goes over OSC 52, the terminal's own /// clipboard, so it reaches wherever the terminal pastes; `alt+y` runs /// it, and a paste comes back the other way through the terminal's own /// paste. See `terminal.pasteKeys`. /// /// Only the Apple's own text page is copied. A graphics screen has no /// text on it, and an eighty-column card or the UltraTerm draws text the /// Apple's screen memory does not hold, so those are declined rather /// than copied as whatever the Apple's own page happens still to carry. fn copyScreen(self: *Self) void { if (comptime !@hasDecl(CPU.Memory, "writeText")) { self.session.announce("this machine has no text screen to copy", .{}); return; } if (self.videxShowing() or self.ultraTermShowing()) { self.session.announce("only the Apple's own screen is copied, not the card's", .{}); return; } const columns = self.session.machineMode().columns() orelse { self.session.announce("no text on the screen to copy", .{}); return; }; // The screen comes out as its rows run together with nothing between // them; it is cut back into rows of the right width here so each can // lose its trailing spaces. var flat: std.Io.Writer.Allocating = .init(self.alloc); defer flat.deinit(); self.session.cpu.memory.writeText(&flat.writer) catch { self.session.announce("could not read the screen", .{}); return; }; var lined: std.Io.Writer.Allocating = .init(self.alloc); defer lined.deinit(); var at: usize = 0; const text = flat.written(); while (at < text.len) : (at += columns) { const row = text[at..@min(at + columns, text.len)]; lined.writer.writeAll(std.mem.trimEnd(u8, row, " ")) catch return; lined.writer.writeByte('\n') catch return; } const trimmed = std.mem.trimEnd(u8, lined.written(), " \n"); if (trimmed.len == 0) { self.session.announce("the screen is blank", .{}); return; } self.vx.copyToSystemClipboard(self.writer, trimmed, self.alloc) catch |err| { self.session.announce("could not copy the screen: {s}", .{@errorName(err)}); return; }; self.session.announce("copied the screen to the clipboard", .{}); } fn saveScreenshot(self: *Self) !void { if (comptime !SessionT.hasVideo()) return error.NoDisplay; // Whichever monitor is being looked at is the one photographed, // and a Videoterm's is not the machine's video: it is the card's // own dots out of the card's own character generator, which is a // picture the terminal cannot show and this can. if (self.videxShowing()) { try picture.write(self.io, self.alloc, .videoterm, &self.session.cpu.memory, self.screenshot, .{}); return; } if (self.ultraTermShowing()) { try picture.write(self.io, self.alloc, .ultraterm, &self.session.cpu.memory, self.screenshot, .{}); return; } // What is on the screen, including which monitor it is being looked at // on. try picture.write(self.io, self.alloc, .apple2, &self.session.cpu.memory, self.screenshot, .{ .monitor = self.monitor, }); } /// Rings the terminal if the machine has made a noise since the last look. /// /// A terminal has one sound and no pitch, so a tone cannot be reproduced, /// only reported. Anything the speaker does becomes a bell, and the bells /// are spaced out, because the alternative is a thousand of them a second /// for as long as the note lasts. /// Rings the terminal if the machine has made a noise since the last /// look. A terminal has one sound and no pitch, so a tone is reported, /// not reproduced; the session decides when a report is due. fn ringBell(self: *Self) !void { if (self.session.bellDue()) try self.writer.writeByte(0x07); } /// Puts the terminal back the way it was found, after the session has /// let go of the machine and everything it had open. pub fn deinit(self: *Self) void { self.session.deinit(); self.paste_buf.deinit(self.alloc); // Finishes the page in progress and writes it out: the last page of // a print job leaves no other way, so a machine that printed and // quit still gets its final page. if (self.imagewriter) |iw| iw.close(); // After the session, which lets go of the recording that borrowed // this: the stream is the front end's to close. self.audio.close(); self.display.deinit(self.alloc); self.vx.deinit(self.alloc, self.writer); self.tty.deinit(); } /// The event loop: give the processor its turn, drain whatever input has /// arrived, redraw, repeat. Each pass gets a fresh arena, so drawing can /// allocate freely without bookkeeping. /// /// What the processor's turn costs depends on the state. Running, it takes /// whatever instructions are due and then naps until the next one or the /// next frame. Halted or single stepping there is nothing to do until the /// user does something, so the loop blocks on input instead of spinning. pub fn run(self: *Self) !void { var loop: vaxis.Loop(Event) = .init(self.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)); try self.vx.setMouseMode(self.writer, true); // So a paste arrives wrapped in a start and an end rather than as // a burst of keystrokes indistinguishable from fast typing, which // is what lets it be tidied before it reaches the machine. try self.vx.setBracketedPaste(self.writer, true); while (!self.should_quit) { var arena = std.heap.ArenaAllocator.init(self.alloc); defer arena.deinit(); const alloc = arena.allocator(); self.session.feedKeyboard(); if (self.session.state == .running) self.session.stepDue(); self.session.measureSpeed(); self.session.measureFlash(); self.session.pumpSerial(); self.session.pumpMidi(); self.session.pumpEthernet(); self.session.pumpCs8900(); self.session.captureAudio(); try self.ringBell(); // Draw before waiting, never after. Waiting first would leave the // screen blank until the user pressed something, which is exactly // when they would most like to see where the processor is. // // A stopped processor draws whenever something happens, since // nothing else is going on and what happened is worth seeing. A // running one draws on the frame and not otherwise. if (self.session.state != .running or self.session.frameDue()) { try self.draw(alloc); try self.vx.render(self.writer); try self.writer.flush(); } switch (self.session.state) { .running => try self.session.nap(), .halted, .single_step => try loop.pollEvent(), } while (try loop.tryEvent()) |event| { try self.update(event, alloc); } } } /// Applies one input event. /// /// Tab decides who the keyboard is talking to. With the debugger /// listening, space runs one instruction, r and p run and pause the /// processor, ctrl-r resets it, plus and minus change the speed, and page /// up and down move the memory view. With the machine listening, keys go /// to its keyboard instead. Ctrl-c quits either way. pub fn update(self: *Self, event: Event, alloc: std.mem.Allocator) !void { _ = alloc; switch (event) { .key_press => |key| { // A paste in progress takes the keys before anything else: // between the terminal's start and end markers they are the // pasted text, not commands, and they are gathered rather // than acted on so the whole paste can be tidied at its end. if (self.pasting) { self.gatherPaste(key); return; } // 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.should_quit = true; return; } // A disk being chosen takes the keys next: the picker is a // list to move through, not something the machine sees. if (self.picker != null) { self.pickerKey(key); return; } // A save state's path is typed the same way a disk's is. if (self.snapshot_prompt != null) { self.snapshotPromptKey(key); return; } // While a disk is being changed the keys are the debugger's: // a path has to be typed somewhere. if (self.prompt != null) { self.promptKey(key); return; } // Alt is the debugger's, because no Apple keyboard had one, so // nothing behind it can be a key the machine was owed. if (key.mods.alt) { self.command(key); return; } // Everything else belongs to the machine. A model without a // keyboard, which is to say a bare processor, has nowhere to // put it. if (@hasDecl(CPU.Memory, "pressKey")) { if (terminal.appleKey(key)) |character| { if (self.session.typed_len < self.session.typed.len) { self.session.typed[self.session.typed_len] = character; self.session.typed_len += 1; } } } }, .mouse => |pointer| { self.mouse = pointer; self.mouseMoved(pointer); }, .winsize => |ws| try self.vx.resize(self.alloc, self.writer, ws), // A paste, wrapped by the terminal in a start and an end. The // keys in between are gathered by the branch above; here the // window is opened and, at its close, what was gathered is // tidied and handed to the machine. .paste_start => { self.pasting = true; self.paste_buf.clearRetainingCapacity(); }, .paste_end => self.finishPaste(), else => {}, } } /// Gathers one key of a paste as the byte it stands for, so the whole /// paste can be tidied by `terminal.pasteKeys` once it is complete. /// /// The terminal sends a pasted carriage return, line feed or tab as the /// control byte itself, which the parser turns into the matching key — /// return, control-J and tab — so those are turned back into their bytes /// here for `pasteKeys` to make sense of the line endings. Everything /// else is taken as what it typed. fn gatherPaste(self: *Self, key: vaxis.Key) void { const byte: u8 = if (key.matches(vaxis.Key.enter, .{})) '\r' else if (key.matches('j', .{ .ctrl = true })) '\n' else if (key.matches(vaxis.Key.tab, .{})) '\t' else if (key.text) |t| (if (t.len == 1) t[0] else return) else if (key.codepoint < 0x80) @intCast(key.codepoint) else return; self.paste_buf.append(self.alloc, byte) catch {}; } /// Closes a paste: tidies what was gathered into the keystrokes an Apple /// keyboard would have made and queues them to be typed into the machine. fn finishPaste(self: *Self) void { self.pasting = false; // A bare processor has no keyboard to feed, so a paste is dropped // rather than piling up in a queue nothing ever drains. if (comptime !@hasDecl(CPU.Memory, "pressKey")) { self.paste_buf.clearRetainingCapacity(); return; } if (self.paste_buf.items.len == 0) return; var keys: std.Io.Writer.Allocating = .init(self.alloc); defer keys.deinit(); terminal.pasteKeys(self.paste_buf.items, &keys.writer) catch return; self.session.paste.appendSlice(self.alloc, keys.written()) catch {}; self.paste_buf.clearRetainingCapacity(); } /// Acts on one of the debugger's own commands, which are the keystrokes /// with alt held. /// A key typed into the disk prompt. Return puts the disk in, escape /// changes nothing, and an empty line takes out whatever was there. fn promptKey(self: *Self, key: vaxis.Key) void { const prompt = &(self.prompt.?); if (key.matches(vaxis.Key.escape, .{})) { self.prompt = null; return; } if (key.matches(vaxis.Key.enter, .{})) { // Taken away from the prompt before the prompt is put away: what // was typed lives inside the optional, and clearing that leaves // nothing worth reading behind. var typed: [prompt.buffer.len]u8 = undefined; const length = prompt.len; @memcpy(typed[0..length], prompt.buffer[0..length]); const drive = prompt.drive; const path = typed[0..length]; self.prompt = null; if (path.len == 0) { self.session.ejectDisk(drive); self.session.note_len = 0; self.session.note_drive = null; return; } self.session.insertDisk(drive, path, null) catch |err| { self.session.say(drive, "{s}", .{@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 a path is refused if it is empty. fn snapshotPromptKey(self: *Self, 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 (path.len == 0) return; if (loading) { self.session.loadSnapshot(path) catch |err| { self.session.announce("could not load {s}: {s}", .{ path, @errorName(err) }); return; }; self.session.announce("loaded {s}", .{path}); } else { self.session.saveSnapshot(path) catch |err| { self.session.announce("could not save {s}: {s}", .{ path, @errorName(err) }); return; }; // A config beside it, so it can be booted straight into. self.writeCompanionConfig(path) catch |err| { self.session.announce("saved {s}, but not its config: {s}", .{ path, @errorName(err) }); return; }; self.session.announce("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; } } /// Writes a config beside a snapshot that rebuilds this machine and /// boots into it. The config is built in an arena thrown away straight /// after, since none of what goes into it outlives the write. fn writeCompanionConfig(self: *Self, snapshot_path: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(self.session.alloc); defer arena.deinit(); const a = arena.allocator(); const cfg = try machineConfig(a, self.options, snapshot_path); const companion = try config.companionPath(a, snapshot_path); try config.write(self.session.io, self.session.alloc, 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: *Self, 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 occupied = self.session.floppies[picker.drive] != null; const list = Picker.choices(self.library, occupied, &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]; self.session.insertDisk(drive, disk.path, disk.writable) catch |err| { self.session.say(drive, "{s}", .{@errorName(err)}); }; }, .eject => { self.session.ejectDisk(drive); self.session.note_len = 0; self.session.note_drive = null; }, .blank => self.session.insertBlank(drive), // The old way, kept for a disk that is not in the library: // the picker hands the keyboard to the path prompt. .path => self.prompt = .{ .drive = drive }, } return; } } fn command(self: *Self, key: vaxis.Key) void { if (key.matches(vaxis.Key.page_up, .{ .alt = true })) self.memory_page -%= 1; if (key.matches(vaxis.Key.page_down, .{ .alt = true })) self.memory_page +%= 1; // Space means one instruction, which is also how a running processor is // stopped. A halted one has nowhere to step to. if (key.matches(vaxis.Key.space, .{ .alt = true }) and self.session.state != .halted) { self.session.state = .single_step; self.session.step(); } if (key.matches('r', .{ .alt = true })) self.session.start(); if (key.matches('p', .{ .alt = true }) and self.session.state == .running) self.session.state = .single_step; if (key.matches('b', .{ .alt = true })) { self.session.reset(); // A disk being changed is abandoned when the machine is reset. self.prompt = null; self.picker = null; } // The Apple-1's other button. It is on the display, not the // processor, so it is not a reset and clears nothing else. if (key.matches('c', .{ .alt = true }) and comptime @hasDecl(CPU.Memory, "clearScreen")) { self.session.cpu.memory.clearScreen(); self.session.announce("CLEAR SCREEN", .{}); } // Yank the screen's text to the host clipboard. Not alt+c, which is // the Apple-1's CLEAR SCREEN button; y is the editor's word for it. if (key.matches('y', .{ .alt = true })) self.copyScreen(); if (key.matches('g', .{ .alt = true })) self.writeScreenshot(); // 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 }; if (key.matches('l', .{ .alt = true })) self.snapshot_prompt = .{ .loading = true }; if (key.matches('x', .{ .alt = true })) { self.text = self.text.other(); self.session.announce("{s}", .{self.text.describe()}); } if (key.matches('m', .{ .alt = true })) { self.monitor = self.monitor.other(); self.session.announce("looking at it on {s}", .{self.monitor.describe()}); } if (comptime SessionT.hasVidexCard()) { if (key.matches('v', .{ .alt = true }) and self.session.cpu.memory.videxCard() != null) { self.videx = !self.videx; self.session.announce("looking at {s}", .{ if (self.videx) "the Videoterm" else "the Apple's own screen", }); } } // The two drives. Alt-1 and alt-2 open the picker, which lists the // library and offers a blank disk or a typed path. if (comptime SessionT.hasDrives()) { // Only a drive that is actually there can be offered a disk. if (key.matches('1', .{ .alt = true }) and self.session.cpu.memory.drives().fitted > 0) self.picker = .{ .drive = 0 }; if (key.matches('2', .{ .alt = true }) and self.session.cpu.memory.drives().fitted > 1) self.picker = .{ .drive = 1 }; // And with shift, a blank formatted disk straight in, with no // prompt: the shifted digit is matched too, for terminals that // send alt+shift+1 as alt+`!` rather than as a modifier. if ((key.matches('1', .{ .alt = true, .shift = true }) or key.matches('!', .{ .alt = true })) and self.session.cpu.memory.drives().fitted > 0) self.session.insertBlank(0); if ((key.matches('2', .{ .alt = true, .shift = true }) or key.matches('@', .{ .alt = true })) and self.session.cpu.memory.drives().fitted > 1) self.session.insertBlank(1); } // The two Apple keys, which are the game connector's first two // buttons. A terminal cannot say that a key is being held down, so // these are switches: pressed until pressed again, and shown on the // status line while they are down. if (comptime SessionT.hasButtons()) { if (key.matches('o', .{ .alt = true })) self.session.holdButton(0); if (key.matches('s', .{ .alt = true })) self.session.holdButton(1); } // Winding the tape back, which is the nearest a file gets to pressing // play on a recorder. if (comptime SessionT.hasCassette()) { if (key.matches('t', .{ .alt = true })) if (self.session.tape) |tape| { self.session.cpu.memory.playTape(tape.levels, tape.sample_rate); self.session.say(0, "tape wound back", .{}); }; // The live volume: quieter, louder, or muted. Nothing to hear // on a machine with no speaker, but the keys are harmless there. if (key.matches(',', .{ .alt = true })) { self.audio.volume.quieter(); self.announceVolume(); } if (key.matches('.', .{ .alt = true })) { self.audio.volume.louder(); self.announceVolume(); } if (key.matches('/', .{ .alt = true })) { self.audio.volume.toggleMute(); self.announceVolume(); } } // Not while a file is being written. What is written is what the // machine played, and a machine played faster is playing something // else; live audio does not mind -- it just drops what it cannot // keep up with -- so it does not hold the speed keys back. if (self.session.recording == null or self.session.recording.?.wav == null) self.speed(key); } /// Says how loud the live audio is now, after a volume key. fn announceVolume(self: *Self) void { var buffer: [8]u8 = undefined; self.session.announce("volume {s}", .{self.audio.volume.describe(&buffer)}); } /// The keys that change how fast the machine runs: double it, halve it, or /// put it back to the rate the machine's own crystal gives. fn speed(self: *Self, key: vaxis.Key) void { // Plus and equals both double, since they are the same key and // reaching for shift to make a machine go faster is a nuisance. if (key.matches('+', .{ .alt = true }) or key.matches('=', .{ .alt = true })) self.session.target_hz = @min(sess.max_hz, self.session.target_hz *| 2); if (key.matches('-', .{ .alt = true })) self.session.target_hz = @max(sess.min_hz, self.session.target_hz / 2); // Nought puts it back to the speed the machine was built to run at, // which is a long way back from either end once it has been doubled a // dozen times. if (key.matches('0', .{ .alt = true })) self.session.target_hz = SessionT.machine_hz; } /// Draws the machine's screen into the pane, as well as the terminal /// allows: a picture where it can show one, and the upper half block where /// it cannot. Both live in `tools/terminal.zig`, since the Apple IIgs /// front end wants exactly the same two things. fn drawScreen(self: *Self, pane: vaxis.Window, showing: screen.Mode) void { if (comptime !SessionT.hasVideo()) return; const as_text = !self.text.asPixels() and (showing.isText() or showing.isMixed()); const lines: u16 = if (as_text and showing.isMixed()) video.height - 4 * 8 else video.height; const rows: u16 = if (as_text and showing.isMixed()) 20 else 24; // The picture goes below the text, which is what lets anything // drawn over the screen — the disk picker, say — stay in front of // it. See the `z_index` on the draw in `tools/terminal.zig`. if (self.vx.caps.kitty_graphics) { const into = pane.child(.{ .x_off = 0, .y_off = 0, .width = pane.width, .height = rows, }); if (self.display.draw( self.alloc, &self.vx, self.writer, sess.pacing_clock, self.io, into, &self.session.cpu.memory, .apple2, lines, self.monitor, terminal.videoHash(&self.session.cpu.memory, showing, self.session.flash), )) |_| return else |_| {} } // Sampled at eighty across whatever the machine is showing, so that a // forty-column screen fills the monitor with each of its dots twice as // wide — which is what the machine does to them. terminal.halfBlocks(pane, &self.session.cpu.memory, showing, 80); } /// Paints the whole screen: the registers and flags, the disassembly around /// the program counter, and a page of memory. pub fn draw(self: *Self, alloc: std.mem.Allocator) !void { const non_printable_characters: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x66, 0x66, 0x66 }, }, }; try self.vx.setTitle(self.writer, "🍏 Zig 6502 🍏"); const win = self.vx.window(); win.clear(); self.vx.setMouseShape(.default); // The machine's screen at the top left, always the same size, with // the debugger's own panes beside it if the terminal is wide enough // for both and underneath it if not: rather than clip the screen, // which is the thing worth looking at, everything else moves. const columns = self.session.machineColumns(); const beside = win.width >= monitor_width + panes_width; const panes_left: i17 = if (beside) monitor_width else 0; // What the machine is doing goes directly under its screen whichever // way round the rest is, and the memory and registers go beside the // two if there is room and below them if there is 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. const status_height: u16 = 7 + if (comptime SessionT.hasDrives()) @as(u16, 1) else 0; const panes_top: i17 = if (beside) 0 else monitor_height + status_height; const screen_pane = win.child(.{ .x_off = 0, .y_off = 0, .width = monitor_width, .height = monitor_height, .border = .{ .where = .all, }, }); { // Graphics first, if there are any: a mixed screen is graphics // with four rows of text over the bottom of it, and the text is // drawn second so that it wins where they overlap. const on_the_card = self.videxShowing() or self.ultraTermShowing(); const showing = self.session.machineMode(); // A picture of the screen is a Kitty graphics image, which a // terminal composites below its text, the picture being drawn // with a negative stacking order, so anything over the screen // stays in front of it. const as_pixels = self.text.asPixels() and self.vx.caps.kitty_graphics; if (!on_the_card and (!showing.isText() or as_pixels)) self.drawScreen(screen_pane, showing); if (self.videxShowing()) self.drawVidex(screen_pane); if (self.ultraTermShowing()) self.drawUltraTerm(screen_pane); // The text page is not stored in the order it is shown. Three // rows eight apart on the display share each 128-byte block, // which is how 960 characters fit into a kilobyte. const screen_base = self.session.displayPage(); // A machine without the switch never has the alternate set. const alternate = if (@hasField(CPU.Memory, "altchar")) self.session.cpu.memory.altchar else false; // A graphics screen has no text rows at all, and a mixed one has // the last four. const first_text_row: u16 = if (on_the_card or as_pixels) 24 else if (showing.isText()) 0 else if (showing.isMixed()) 20 else 24; // Forty columns are centred in an eighty-column monitor. A real // machine draws each dot twice as wide instead, which a terminal // cannot do with its own letters — but leaving them against the // left edge looks like a bug rather than a screen. const indent: u16 = (80 - columns) / 2; for (first_text_row..24) |row_| { const row: u16 = @intCast(row_); const line_base = screen.rowBase(screen_base, row); for (0..columns) |col_| { const col: u16 = @intCast(col_); const glyph = screen.decode(self.session.videoByte(line_base, col), alternate); // Written as a cell rather than printed as text: the // character is known to be one column of seven bit ASCII, // so none of what printing does to work that out is needed. const grapheme: []const u8 = if (glyph.character == 0x7f) block else &ascii[glyph.character & 0x7f]; screen_pane.writeCell(col + indent, row, .{ .char = .{ .grapheme = grapheme, .width = 1 }, .style = switch (glyph.video) { .normal => .{}, .inverse => .{ .reverse = true }, // Flashing is drawn rather than handed to the // terminal to blink. The machine flashes by // swapping the dots for the gaps, so half the time // a flashing character is an inverse one, and a // terminal asked to blink instead would leave the // cursor, which is a flashing space, as nothing at // all. Terminals that refuse to blink are also // common enough that it is not worth relying on. .flashing => .{ .reverse = self.session.flash }, }, }); } } } const memoryview = win.child(.{ .x_off = panes_left, .y_off = panes_top, .width = panes_width, .height = 20, .border = .{ .where = .all, }, }); { _ = memoryview.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "Current Memory Page: 0x{x:0>2}\n", .{self.memory_page}), }, .{ .row_offset = 0, .col_offset = 0, }, ); for (0..16) |line_| { const line: u16 = @intCast(line_); var col_offset: u16 = 0; const memory_line: usize = (@as(usize, self.memory_page) << 8) + (line * 16); _ = memoryview.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "{x:0>4}", .{memory_line}) }, .{ .row_offset = 2 + line, .col_offset = col_offset, }, ); col_offset += 4; _ = memoryview.printSegment( .{ .text = try std.fmt.allocPrint(alloc, ":", .{}), .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 2 + line, .col_offset = col_offset, }, ); col_offset += 2; // The sixteen bytes as one piece of text rather than sixteen. // They are all the same style, and a segment costs the same // whether it is two characters or fifty. const hex = try alloc.alloc(u8, 16 * 3); for (0..16) |col| { const memory_address: u16 = @intCast(memory_line + col); _ = try std.fmt.bufPrint(hex[col * 3 ..][0..3], " {x:0>2}", .{self.session.cpu.memory.peek(memory_address)}); } _ = memoryview.printSegment( .{ .text = hex }, .{ .row_offset = 2 + line, .col_offset = col_offset, }, ); col_offset += 16 * 3 + 2; _ = memoryview.printSegment( .{ .text = "│", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 2 + line, .col_offset = col_offset, }, ); col_offset += 1; for (0..16) |col| { const memory_address: u16 = @intCast(memory_line + col); const row_offset = 2 + line; switch (self.session.cpu.memory.peek(memory_address)) { 0x00...0x20 => |byte| { _ = memoryview.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "{u}", .{@as(u21, 0x2400) + byte}), .style = non_printable_characters, }, .{ .row_offset = row_offset, .col_offset = col_offset, }, ); }, 0x7f => { _ = memoryview.printSegment( .{ .text = "␡", .style = non_printable_characters, }, .{ .row_offset = row_offset, .col_offset = col_offset, }, ); }, 0x80...0xff => { _ = memoryview.printSegment( .{ .text = "□", .style = non_printable_characters, }, .{ .row_offset = row_offset, .col_offset = col_offset, }, ); }, else => |byte| { _ = memoryview.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "{c}", .{byte}), }, .{ .row_offset = row_offset, .col_offset = col_offset, }, ); }, } col_offset += 1; } _ = memoryview.printSegment( .{ .text = "│", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 2 + line, .col_offset = col_offset, }, ); } } const register = win.child(.{ .x_off = panes_left, .y_off = panes_top + 20, .width = panes_width, .height = 6, .border = .{ .where = .all, }, }); { _ = register.printSegment( .{ .text = "Registers:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 0, .col_offset = 0, }, ); _ = register.printSegment( .{ .text = "A:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 1, .col_offset = 0, }, ); _ = register.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "0x{0x:0>2} 0b{0b:0>8}", .{self.session.cpu.registers.get(.A)}), }, .{ .row_offset = 1, .col_offset = 3, }, ); _ = register.printSegment( .{ .text = "X:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 2, .col_offset = 0, }, ); _ = register.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "0x{0x:0>2} 0b{0b:0>8}", .{self.session.cpu.registers.get(.X)}), }, .{ .row_offset = 2, .col_offset = 3, }, ); _ = register.printSegment( .{ .text = "Y:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 3, .col_offset = 0, }, ); _ = register.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "0x{0x:0>2} 0b{0b:0>8}", .{self.session.cpu.registers.get(.Y)}), }, .{ .row_offset = 3, .col_offset = 3, }, ); _ = register.printSegment( .{ .text = "Program:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 1, .col_offset = 20, }, ); _ = register.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "0x{0x:0>4}", .{self.session.cpu.program_counter.value}), }, .{ .row_offset = 1, .col_offset = 29, }, ); _ = register.printSegment( .{ .text = "Stack:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 2, .col_offset = 22, }, ); _ = register.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "0x{0x:0>4}", .{self.session.cpu.stack.pointer}), }, .{ .row_offset = 2, .col_offset = 29, }, ); _ = register.printSegment( .{ .text = "Flags:", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 0, .col_offset = 39, }, ); const flag_set_style: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x00, 0xff, 0x00 }, }, }; const flag_clear_style: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0xff, 0x00, 0x00 }, }, }; _ = register.printSegment( .{ .text = "N", .style = if (self.session.cpu.flags.isSet(.N)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 41, }, ); _ = register.printSegment( .{ .text = "V", .style = if (self.session.cpu.flags.isSet(.V)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 43, }, ); _ = register.printSegment( .{ .text = "-", .style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 }, }, }, }, .{ .row_offset = 2, .col_offset = 45, }, ); _ = register.printSegment( .{ .text = "B", .style = if (self.session.cpu.flags.isSet(.B)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 47, }, ); _ = register.printSegment( .{ .text = "D", .style = if (self.session.cpu.flags.isSet(.D)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 49, }, ); _ = register.printSegment( .{ .text = "I", .style = if (self.session.cpu.flags.isSet(.I)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 51, }, ); _ = register.printSegment( .{ .text = "Z", .style = if (self.session.cpu.flags.isSet(.Z)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 53, }, ); _ = register.printSegment( .{ .text = "C", .style = if (self.session.cpu.flags.isSet(.C)) flag_set_style else flag_clear_style, }, .{ .row_offset = 2, .col_offset = 55, }, ); } const status = win.child(.{ .x_off = 0, .y_off = monitor_height, // What the processor is doing, why it stopped if it did, how to // tell it to do something else, and then a row for each drive. .width = monitor_width, .height = status_height, .border = .{ .where = .all, }, }); { const dim: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x66, 0x66, 0x66 }, }, }; const state_colour: [3]u8 = switch (self.session.state) { .running => .{ 0x44, 0xcc, 0x44 }, .halted => .{ 0xcc, 0x44, 0x44 }, .single_step => .{ 0xcc, 0xcc, 0x44 }, }; _ = status.printSegment( .{ .text = self.session.state.name(), .style = .{ .fg = .{ .rgb = state_colour, }, }, }, .{ .row_offset = 0, .col_offset = 0, }, ); // Where it stopped, and for a jam what stopped it. The program // counter has moved past the opcode by now, so without this there // is nothing on screen pointing at the instruction responsible. // The annunciators, which nothing inside the machine can // read back. A program that has just set one has no way to ask // whether it took, so this is the only place it shows. if (comptime SessionT.hasAnnunciators()) { var digits: [4]u8 = undefined; _ = self.session.annunciators(&digits); _ = status.print(&.{ .{ .text = "annunciators ", .style = dim }, .{ .text = try alloc.dupe(u8, &digits) }, }, .{ .row_offset = 1, .col_offset = 56 }); } if (self.session.stopped) |stop| { _ = status.printSegment( .{ .text = switch (stop) { .jam => |jam| try std.fmt.allocPrint( alloc, "${x:0>2} at ${x:0>4} jammed the processor; ^R to reset", .{ jam.opcode, jam.address }, ), .brk => |brk| try std.fmt.allocPrint( alloc, "BRK at ${x:0>4}, vectored to ${x:0>4}; r or space to carry on", .{ brk.address, brk.vector }, ), }, .style = .{ .fg = .{ .rgb = state_colour, }, }, }, .{ .row_offset = 1, .col_offset = 0, }, ); } _ = status.printSegment( .{ .text = try std.fmt.allocPrint(alloc, "{d:.2} MHz asked {d:.2} MHz run{s}{s}{s}", .{ @as(f64, @floatFromInt(self.session.target_hz)) / 1_000_000.0, self.session.measured_hz / 1_000_000.0, if (self.session.recording != null) " recording" else "", if (self.session.buttons[0]) " open apple" else "", if (self.session.buttons[1]) " solid apple" else "", }), .style = dim, }, .{ .row_offset = 0, .col_offset = 28, }, ); _ = status.printSegment( .{ // Alt for all of them: everything else is the machine's. .text = "alt+ space step r run p pause b reset m/x video g screen y copy +/- rate q quit", .style = dim, }, .{ .row_offset = 2, .col_offset = 0, }, ); if (comptime SessionT.hasDrives()) { // A IIc has no card and needs none: the drive is in the case // and its driver is in the machine's own ROM, so asking for a // boot PROM there would be asking for a thing that does not // exist. const no_card = if (comptime SessionT.wantsCard()) self.session.cpu.memory.cardIn(.disk) == null else false; if (no_card) { _ = status.printSegment( .{ .text = "no disk card fitted: --disk-rom PATH fits one", .style = dim }, .{ .row_offset = 3, .col_offset = 0 }, ); } else if (self.session.cpu.memory.drives().fitted == 0) { _ = status.printSegment( .{ .text = "no drives fitted: --drives N puts them on the card", .style = dim }, .{ .row_offset = 3, .col_offset = 0 }, ); } else for (0..self.session.cpu.memory.drives().fitted) |which| { try self.drawDrive(alloc, status, @intCast(3 + which), @intCast(which)); } } // And the debugger's own line, underneath everything else. A // save-state path being typed takes it over, the way a disk // path takes over its drive's line. const row: u16 = if (comptime SessionT.hasDrives()) 5 else 4; if (self.snapshot_prompt) |prompt| { const typed: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0xbb, 0xbb, 0xbb } } }; _ = status.print(&[_]vaxis.Cell.Segment{ .{ .text = if (prompt.loading) "load state: " else "save state: ", .style = dim }, .{ .text = prompt.buffer[0..prompt.len], .style = typed }, .{ .text = "_ return acts, escape cancels", .style = dim }, }, .{ .row_offset = row, .col_offset = 0 }); } else if (self.session.message_len != 0) { _ = status.printSegment( .{ .text = self.session.message[0..self.session.message_len], .style = dim }, .{ .row_offset = row, .col_offset = 0 }, ); } } // Last of all, over everything, the disk picker if one is open. try self.drawPicker(alloc, win); } /// 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. The box is /// sized to the longest line and centred, and a disk says whether it /// would go in read only or writable, since that is the whole reason a /// library entry carries the flag. fn drawPicker(self: *Self, 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 occupied = self.session.floppies[picker.drive] != null; const list = Picker.choices(self.library, occupied, &buffer); // Which of the library's disks is the one already in this drive, so // that the list can say so rather than leaving somebody to remember // it. What the drive holds is kept as the path it was opened from, // which is the same thing a library entry names, so the two compare // outright. const in_drive: ?usize = found: { const here = self.session.disk_paths[picker.drive] orelse break :found null; for (self.library, 0..) |entry, n| { if (std.mem.eql(u8, entry.path, here)) break :found n; } break :found null; }; // Each choice's label, built once so the box can be sized to the // widest before anything is drawn. 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, "Drive {d} — insert a disk", .{@as(u8, picker.drive) + 1}); const footer = "\u{2191}\u{2193} move \u{23ce} choose esc cancel"; // A rule sits between the library and the fixed choices when there // are both, so the box holds a row for every choice plus that rule. 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| { // The rule goes in front of the first fixed choice, which is the // first one that is not a library disk. It runs the full width. 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; } // The highlight runs the width of the box, not just the text, so // the selected row reads as a bar rather than reversed words. 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 that 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 }); } /// One drive's line: which drive it is, whether it is turning, and what is /// in it. /// /// The light is the one a real machine had on the front, and it is lit for /// the same reason: this drive is the one selected and its motor is /// running. It is the difference between a machine reading a disk and one /// sitting on an empty drive waiting for a disk that is not coming, which /// otherwise looks exactly like an emulator that has stopped working. fn drawDrive( self: *Self, alloc: std.mem.Allocator, into: vaxis.Window, row: u16, which: u1, ) !void { const light_grey: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0xbb, 0xbb, 0xbb } } }; const dark_grey: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0x44, 0x44, 0x44 } } }; const red: vaxis.Style = .{ .fg = .{ .rgb = [_]u8{ 0xcc, 0x44, 0x44 } } }; const spinning = self.session.cpu.memory.drives().turningAt(self.session.diskCycles()) and self.session.cpu.memory.drives().selected == which; const number: vaxis.Cell.Segment = .{ .text = try std.fmt.allocPrint(alloc, "{d} ", .{@as(u8, which) + 1}), .style = dark_grey, }; const light: vaxis.Cell.Segment = .{ .text = "\u{2b24} ", .style = if (spinning) red else dark_grey, }; // A path being typed for this drive takes the line over: it is the one // thing about the drive worth looking at while it is being typed. if (self.prompt) |prompt| { if (prompt.drive == which) { _ = into.print(&[_]vaxis.Cell.Segment{ number, light, .{ .text = prompt.buffer[0..prompt.len], .style = light_grey }, .{ .text = "_ return inserts, empty ejects, escape cancels", .style = dark_grey }, }, .{ .row_offset = row, .col_offset = 0 }); return; } } const what: vaxis.Cell.Segment = if (self.session.disk_paths[which]) |path| .{ .text = std.fs.path.basename(path), .style = light_grey } else if (self.session.disk_labels[which]) |label| .{ .text = label, .style = light_grey } else .{ .text = "empty", .style = dark_grey }; // Anything that went wrong with this drive is said after what is in // it, since it is about that drive and nowhere else would say which. const noted = self.session.note_len > 0 and self.session.note_drive != null and self.session.note_drive.? == which; const said: vaxis.Cell.Segment = if (noted) .{ .text = try std.fmt.allocPrint(alloc, " {s}", .{self.session.note[0..self.session.note_len]}), .style = dark_grey } else .{ .text = "", .style = dark_grey }; _ = into.print( &[_]vaxis.Cell.Segment{ number, light, what, said }, .{ .row_offset = row, .col_offset = 0 }, ); } }; } /// The machine a command line gets when it says nothing, and the one the tests /// below use: an Apple IIe with the NMOS processor it was sold with. const App = Debugger(.iie, .@"6502"); const AppCPU = App.CPU; /// Runs one machine until the user quits. /// /// Generic, and called from a table of every machine and processor there is, /// because the memory model is a comptime parameter: a machine cannot be /// chosen with an `if` at run time, only picked out of a set that was all /// compiled. So this is instantiated once per combination and the switch below /// decides which of them the program actually runs. fn runDebugger(comptime machine: Machine, comptime processor: Processor, init: std.process.Init, options: Options) !void { const Machine8 = Debugger(machine, processor); var app: Machine8 = undefined; try app.init(init.io, init.gpa, init.environ_map, options); defer app.deinit(); try app.run(); } /// Runs whichever machine was asked for. /// `zig65 id FILE...`, which says what each file is and which flag wants it. /// /// A subcommand rather than a flag, because it is a different program: it runs /// no machine, takes no ROM of its own, and answers about files rather than /// about a IIe. Anything else on the command line is a file to look at. /// /// The exit status is the number of files nothing could be said about, so a /// script can ask "are these all ROMs I can use" and get an answer without /// reading the text. fn identifyFiles(init: std.process.Init, it: *std.process.Args.Iterator) !void { const io = init.io; const gpa = std.heap.smp_allocator; var unrecognised: u8 = 0; var any = false; while (it.next()) |path| { any = true; const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited) catch |err| { std.debug.print("{s}: cannot read it: {s}\n", .{ path, @errorName(err) }); unrecognised +|= 1; continue; }; defer gpa.free(bytes); var buffer: [256]u8 = undefined; switch (romid.identify(bytes, &buffer)) { .known => |entry| { std.debug.print("{s}: {s}\n", .{ path, entry.what }); std.debug.print(" {d} bytes, catalogued as '{s}'\n", .{ entry.size, entry.file }); if (entry.flag) |flag| { std.debug.print(" zig65 {s} '{s}'\n", .{ flag, path }); } else { std.debug.print(" nothing here takes this one\n", .{}); } }, .guessed => |what| { var hex: [64]u8 = undefined; std.debug.print("{s}: not one of the ROMs this has been tested against.\n", .{path}); std.debug.print(" Reading it: {s}\n", .{what}); std.debug.print(" {d} bytes, sha256 {s}\n", .{ bytes.len, romid.hash(bytes, &hex) }); unrecognised +|= 1; }, .unknown => { var hex: [64]u8 = undefined; std.debug.print("{s}: not recognised, and nothing in it says what it is.\n", .{path}); std.debug.print(" {d} bytes, sha256 {s}\n", .{ bytes.len, romid.hash(bytes, &hex) }); unrecognised +|= 1; }, } } if (!any) { std.debug.print("zig65 id: give it some files to look at\n", .{}); std.process.exit(2); } if (unrecognised != 0) std.process.exit(1); } pub fn main(init: std.process.Init) !void { // The one subcommand, taken before anything else on the line means what it // usually means: `id` is not a machine and its arguments are not flags. { var it = init.minimal.args.iterate(); _ = it.next(); // the program's own name if (it.next()) |first| { if (std.mem.eql(u8, first, "id")) return identifyFiles(init, &it); } } const options = parseArgs(init.minimal.args, init.io, std.heap.smp_allocator) orelse return; // A IIgs is a different program: a sixteen-bit processor, a machine with // no slots to speak of and no debugger around it. It lives in gs.zig and // is reached from the same command line rather than from a second one. if (options.machine == .iigs) return gs.run(init, .{ .rom = options.rom, .disk = options.disks[0], .hard_disks = options.hard_disks, .unidisks = options.unidisks, .library = options.library, .screenshot = options.screenshot, .snapshot = options.snapshot, .monitor = options.monitor, .text = options.text, .audio = options.audio, .sound = options.sound, .volume = options.volume, .mute = options.mute, .memory = options.memory, .serial_in = options.serial_in, .serial_out = options.serial_out, .printer_out = options.printer_out, .localtalk = options.localtalk, .localtalk_log = options.localtalk_log, .localtalk_interface = options.localtalk_interface, .appletalk = options.appletalk, .battery_ram = options.battery_ram, .uthernet = options.uthernet, .uthernet1 = options.uthernet1, .ethernet_interface = options.ethernet_interface, .mac = options.mac, .modem = options.modem, .modem_answer = options.modem_answer, .halted = options.halted, }); // And the eight-bit machines, one instantiation apiece. The loops are // `inline` and the comparisons are ordinary run-time ones, so what this // compiles to is a jump table over every pairing and what it costs is an // executable holding all of them. const processor = options.processor orelse shippedProcessor(init.io, std.heap.smp_allocator, options); inline for (comptime std.enums.values(Machine)) |m| { if (comptime m.isEightBit()) { inline for (comptime std.enums.values(Processor)) |p| { if (options.machine == m and processor == p) return runDebugger(m, p, init, options); } } } unreachable; } test "a jam halts the processor and says what did it" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.state = .running; app.session.stopped = null; try app.session.cpu.memory.loadProgram(0x0200, &[_]u8{0x02}); app.session.cpu.program_counter.value = 0x0200; app.session.step(); try std.testing.expectEqual(sess.State.halted, app.session.state); // The address is the JAM itself, not where the program counter ended up, // which is the whole reason it is recorded before the step. try std.testing.expectEqual(@as(u16, 0x0200), app.session.stopped.?.jam.address); try std.testing.expectEqual(@as(u8, 0x02), app.session.stopped.?.jam.opcode); try std.testing.expect(app.session.cpu.program_counter.value != 0x0200); } test "a BRK stops without wedging the processor" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); // The vector BRK goes through. On a real machine that is in ROM, and a // machine model rightly refuses to let loadProgram put it in RAM, so it // arrives the way the machine would have it. var rom: [0x4000]u8 = @splat(0); rom[0x3ffe] = 0x00; rom[0x3fff] = 0x30; try app.session.cpu.memory.loadROMAtEnd(&rom); app.session.state = .running; app.session.stopped = null; try app.session.cpu.memory.loadProgram(0x0200, &[_]u8{0x00}); app.session.cpu.program_counter.value = 0x0200; app.session.step(); // Stopped, but in a state it can be continued from: a BRK is the processor // doing as it was told, not giving up. try std.testing.expectEqual(sess.State.single_step, app.session.state); try std.testing.expectEqual(@as(u16, 0x0200), app.session.stopped.?.brk.address); try std.testing.expectEqual(@as(u16, 0x3000), app.session.stopped.?.brk.vector); try std.testing.expectEqual(@as(u16, 0x3000), app.session.cpu.program_counter.value); // And it does carry on, straight into the handler. try app.session.cpu.memory.loadProgram(0x3000, &[_]u8{0xea}); app.session.start(); try std.testing.expectEqual(sess.State.running, app.session.state); app.session.step(); try std.testing.expectEqual(@as(?sess.Stop, null), app.session.stopped); try std.testing.expectEqual(@as(u16, 0x3001), app.session.cpu.program_counter.value); } test "an ordinary instruction leaves the state alone" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.state = .running; app.session.stopped = null; try app.session.cpu.memory.loadProgram(0x0200, &[_]u8{0xea}); app.session.cpu.program_counter.value = 0x0200; app.session.step(); try std.testing.expectEqual(sess.State.running, app.session.state); try std.testing.expectEqual(@as(?sess.Stop, null), app.session.stopped); } test "only a reset restarts a jammed processor" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.state = .halted; app.session.stopped = .{ .jam = .{ .address = 0x0200, .opcode = 0x02 } }; // Neither running nor stepping gets it going again. app.session.start(); try std.testing.expectEqual(sess.State.halted, app.session.state); app.session.reset(); try std.testing.expectEqual(sess.State.single_step, app.session.state); try std.testing.expectEqual(@as(?sess.Stop, null), app.session.stopped); // And now it will run. app.session.start(); try std.testing.expectEqual(sess.State.running, app.session.state); } test "the text page interleave puts three rows in each block" { // Three rows eight apart share a block, forty bytes each. const base = struct { fn of(row: u16) u16 { return 0x0400 + 0x80 * (row % 8) + 0x28 * (row / 8); } }.of; try std.testing.expectEqual(@as(u16, 0x0400), base(0)); try std.testing.expectEqual(@as(u16, 0x0480), base(1)); try std.testing.expectEqual(@as(u16, 0x0780), base(7)); try std.testing.expectEqual(@as(u16, 0x0428), base(8)); try std.testing.expectEqual(@as(u16, 0x0450), base(16)); try std.testing.expectEqual(@as(u16, 0x07d0), base(23)); // Every row lands somewhere different, which the old arithmetic did not // manage: it gave the same address to all eight rows of a group. var seen: [24]u16 = undefined; for (0..24) |r| seen[r] = base(@intCast(r)); for (0..24) |a| for (a + 1..24) |b| try std.testing.expect(seen[a] != seen[b]); } /// The long flags named in a piece of text: anything that looks like --name. /// Comment lines are skipped, since both completion files talk about the /// program in prose, and so is the bare -- that ends a shell command's own /// options. fn longFlags(text: []const u8, into: [][]const u8) [][]const u8 { var count: usize = 0; var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |line| { const bare = std.mem.trimStart(u8, line, " \t\\"); if (std.mem.startsWith(u8, bare, "#")) continue; var at: usize = 0; while (std.mem.indexOfPos(u8, line, at, "--")) |found| { var end = found + 2; while (end < line.len and (std.ascii.isAlphanumeric(line[end]) or line[end] == '-')) end += 1; at = end; if (end == found + 2) continue; const flag = line[found..end]; for (into[0..count]) |seen| { if (std.mem.eql(u8, seen, flag)) break; } else { if (count == into.len) @panic("more flags than there is room for"); into[count] = flag; count += 1; } } } return into[0..count]; } test "the shell completions know the same flags the usage describes" { const fish = @embedFile("zig65.fish"); const bash = @embedFile("zig65.bash"); // Room to spare: the panic in `longFlags` when this fills up is the point // of it, but a test that stops the moment a flag is added is a test that // gets in the way rather than one that catches anything. var storage: [96][]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); // What the bash completion actually offers, which is the one list in it // that matters: a flag can appear elsewhere in that file, in the branch // that says what it takes, while no longer being offered at all. const marker = "local flags='"; const list_start = (std.mem.indexOf(u8, bash, marker) orelse return error.CompletionListNotFound) + marker.len; const list_end = list_start + (std.mem.indexOfScalar(u8, bash[list_start..], '\'') orelse return error.CompletionListNotFound); const offered = bash[list_start..list_end]; for (flags) |flag| { // Bash spells them out; fish names them without the dashes. if (std.mem.indexOf(u8, offered, flag) == null) { std.debug.print("the bash completion does not offer {s}\n", .{flag}); return error.MissingFromCompletion; } var wanted: [32]u8 = undefined; const named = try std.fmt.bufPrint(&wanted, "-l {s}", .{flag[2..]}); if (std.mem.indexOf(u8, fish, named) == null) { std.debug.print("the fish completion does not offer {s}\n", .{flag}); return error.MissingFromCompletion; } } // 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: [96][]const u8 = undefined; for (longFlags(offered, &bash_storage)) |flag| { for (flags) |known| { if (std.mem.eql(u8, known, flag)) break; } else { std.debug.print("the bash completion offers {s}, which the usage does not describe\n", .{flag}); return error.UnknownFlagInCompletion; } } // Only the rules themselves: -l means something else entirely to the rest // of fish, where it is how a local variable is declared. var lines = std.mem.splitScalar(u8, fish, '\n'); while (lines.next()) |line| { if (!std.mem.startsWith(u8, line, "complete ")) continue; var at: usize = 0; while (std.mem.indexOfPos(u8, line, at, "-l ")) |found| { var end = found + 3; while (end < line.len and (std.ascii.isAlphanumeric(line[end]) or line[end] == '-')) end += 1; at = end; var wanted: [32]u8 = undefined; const flag = try std.fmt.bufPrint(&wanted, "--{s}", .{line[found + 3 .. end]}); for (flags) |known| { if (std.mem.eql(u8, known, flag)) break; } else { std.debug.print("the fish completion offers {s}, which the usage does not describe\n", .{flag}); return error.UnknownFlagInCompletion; } } } } test "the keyboard sends what an Apple keyboard would" { const key = struct { fn plain(codepoint: u21) vaxis.Key { return .{ .codepoint = codepoint }; } fn control(codepoint: u21) vaxis.Key { return .{ .codepoint = codepoint, .mods = .{ .ctrl = true } }; } }; // Rubbing a character out is backing the cursor over it. $7f is not that: // the line reader treats it as a character and prints it, which is the // cursor moving on and nothing being deleted. try std.testing.expectEqual(@as(?u8, 0x08), terminal.appleKey(key.plain(vaxis.Key.backspace))); try std.testing.expectEqual(@as(?u8, 0x08), terminal.appleKey(key.plain(vaxis.Key.delete))); // The arrows carry the control codes they sit on, which is why the left // arrow and backspace are the same thing. try std.testing.expectEqual(@as(?u8, 0x08), terminal.appleKey(key.plain(vaxis.Key.left))); try std.testing.expectEqual(@as(?u8, 0x15), terminal.appleKey(key.plain(vaxis.Key.right))); try std.testing.expectEqual(@as(?u8, 0x0b), terminal.appleKey(key.plain(vaxis.Key.up))); try std.testing.expectEqual(@as(?u8, 0x0a), terminal.appleKey(key.plain(vaxis.Key.down))); try std.testing.expectEqual(@as(?u8, 0x0d), terminal.appleKey(key.plain(vaxis.Key.enter))); try std.testing.expectEqual(@as(?u8, 0x1b), terminal.appleKey(key.plain(vaxis.Key.escape))); try std.testing.expectEqual(@as(?u8, 0x09), terminal.appleKey(key.plain(vaxis.Key.tab))); try std.testing.expectEqual(@as(?u8, ' '), terminal.appleKey(key.plain(' '))); try std.testing.expectEqual(@as(?u8, 'A'), terminal.appleKey(key.plain('A'))); try std.testing.expectEqual(@as(?u8, 'a'), terminal.appleKey(key.plain('a'))); // Control folds a letter into the first thirty-two codes, as the keyboard // encoder did: control-C stops a program and control-G rings the bell. try std.testing.expectEqual(@as(?u8, 0x03), terminal.appleKey(key.control('c'))); try std.testing.expectEqual(@as(?u8, 0x07), terminal.appleKey(key.control('g'))); // A key no Apple had is dropped rather than guessed at. try std.testing.expectEqual(@as(?u8, null), terminal.appleKey(key.plain(vaxis.Key.f1))); try std.testing.expectEqual(@as(?u8, null), terminal.appleKey(key.plain(vaxis.Key.home))); try std.testing.expectEqual(@as(?u8, null), terminal.appleKey(key.plain(0x2022))); } test "a reset drops what was typed at the machine that was running" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.stopped = null; app.prompt = null; app.session.typed = undefined; app.session.typed_len = 5; app.session.reset(); try std.testing.expectEqual(@as(usize, 0), app.session.typed_len); } test "a reset leaves a running machine running" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.stopped = null; app.prompt = null; app.session.typed = undefined; app.session.typed_len = 0; app.session.last_key = 0; // Running through a reset carries on running: the reset key was never a // way of stopping the machine. app.session.state = .running; app.session.reset(); try std.testing.expectEqual(sess.State.running, app.session.state); // Stepping through one stays stepping. app.session.state = .single_step; app.session.reset(); try std.testing.expectEqual(sess.State.single_step, app.session.state); // A halted processor is the exception: it comes back stopped, which is // also the only way it can be started again at all. app.session.state = .halted; app.session.reset(); try std.testing.expectEqual(sess.State.single_step, app.session.state); app.session.start(); try std.testing.expectEqual(sess.State.running, app.session.state); } test "the speed keys double, halve, and come back to the machine's own speed" { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.state = .running; app.prompt = null; // Not recording: the speed keys are refused while it is, since what is // written has to be what the machine played. app.session.recording = null; app.session.target_hz = sess.real_hz; const alt = struct { fn key(codepoint: u21) vaxis.Key { return .{ .codepoint = codepoint, .mods = .{ .alt = true } }; } }; app.command(alt.key('+')); try std.testing.expectEqual(@as(u64, sess.real_hz * 2), app.session.target_hz); // Equals doubles as well: it is the same key without the shift. app.command(alt.key('=')); try std.testing.expectEqual(@as(u64, sess.real_hz * 4), app.session.target_hz); app.command(alt.key('-')); try std.testing.expectEqual(@as(u64, sess.real_hz * 2), app.session.target_hz); // However far it has been taken, nought brings it back. for (0..10) |_| app.command(alt.key('=')); try std.testing.expect(app.session.target_hz > sess.real_hz * 100); app.command(alt.key('0')); try std.testing.expectEqual(@as(u64, sess.real_hz), app.session.target_hz); // And neither end runs away. for (0..40) |_| app.command(alt.key('+')); try std.testing.expectEqual(@as(u64, sess.max_hz), app.session.target_hz); for (0..40) |_| app.command(alt.key('-')); try std.testing.expectEqual(@as(u64, sess.min_hz), app.session.target_hz); } test "a reset stops a drive that was left turning" { if (comptime App.SessionT.hasDrives()) { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.state = .running; app.session.stopped = null; app.prompt = null; app.session.typed = undefined; app.session.typed_len = 0; app.session.last_key = 0; app.session.last_key = 0; // With a controller in it, since a machine with no card has no // drives to leave turning: `drives()` answers for a port with nothing // on it, and a reset that stopped *that* would be proving nothing. var prom: [0x100]u8 = @splat(0); app.session.cpu.memory.loadCardROM(&prom) catch unreachable; // A machine left sitting on a drive that is going nowhere has its // motor running, and nothing in the firmware is going to turn it off. app.session.cpu.memory.drives().motor = true; app.session.reset(); try std.testing.expect(!app.session.cpu.memory.drives().motor); } } test "a reset puts the machine's switches back" { if (comptime @hasField(AppCPU.Memory, "read_ram")) { var app: App = undefined; app.session.io = std.testing.io; try app.session.cpu.init(null, null); defer app.session.cpu.deinit(); app.session.state = .running; app.session.stopped = null; app.prompt = null; app.session.typed = undefined; app.session.typed_len = 0; app.session.last_key = 0; app.session.last_key = 0; // The language card paged in over the ROM is the case that matters: // the vector the processor resets through lives up there, so the // switch has to be back before it is read. app.session.cpu.memory.card_switches.read_ram = true; // Which switch the internal ROM is on is a IIe and IIc thing; a II // Plus has slots and nothing to switch over them. const has_slot_rom = comptime @hasField(AppCPU.Memory, "intcxrom"); if (has_slot_rom) app.session.cpu.memory.intcxrom = true; app.session.reset(); try std.testing.expect(!app.session.cpu.memory.card_switches.read_ram); if (has_slot_rom) try std.testing.expect(!app.session.cpu.memory.intcxrom); } }