Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The machine-driving core, with no front end in it.//!//! A `Session` owns the processor and the machine around it and does everything//! that has nothing to do with how the machine is looked at: it paces the clock//! and runs instructions in arrears (`stepDue`, `frameDue`, `nap`), hands typed//! keys to the keyboard as it becomes ready for them (`feedKeyboard`), changes//! the disks (`insertDisk`, `insertBlank`, `ejectDisk`, `saveDisk`), moves bytes//! along the serial line (`pumpSerial`), records the speaker and the cassette//! (`captureAudio`), and keeps the run speed and the flashing and the measured//! rate. None of it draws anything or reads a key event.//!//! This is the seam a second front end is built against. The libvaxis terminal//! debugger in `main.zig` embeds one of these and adds the drawing and the//! keystrokes on top; a different front end — a window, a browser — would embed//! the same `Session`, render from the library's own screen surface//! (`zig65.screen`, `zig65.video`, `zig65.superhires`, `zig65.picture`),//! translate its own input into the model's latches (`pressKey`, `moveMouse`)//! and the `Session`'s own actions, and control time by supplying the `std.Io`//! it is given. The machine is generic over the processor and told the two//! machine-specific facts its driving needs — whether the machine has slots and//! whether a BRK is a system call rather than a breakpoint.
const std = @import("std");
const zig65 = @import("zig65");/// The host's live audio, shared with the front ends the way `terminal` is:/// re-exported so `main.zig` and `gs.zig` reach `audio.Output` and `audio.Volume`/// through the session rather than importing it a second time.pub const audio = @import("audio");const disk2 = zig65.disk2;const disk35 = zig65.disk35;const screen = zig65.screen;
/// The clock the run mode paces itself against. Monotonic, so that changing/// the system time does not make the processor lurch./// How big a file naming a disk may be.////// Sized by the largest of the four kinds rather than by the smallest, which/// is a WOZ: a recording of the bits is bigger than a description of the/// sectors, and a limit that fitted a `.dsk` turned a perfectly good WOZ into/// "stream too long".pub const disk_file_limit = @max( disk2.image_size, disk2.Floppy.nibble_size, zig65.woz.max_file_size,) + zig65.twomg.header_size + 1;
pub const pacing_clock: std.Io.Clock = .awake;
/// What the processor is doing between redraws, and why it is not running when/// it is not. Both come from the library rather than from here, because the/// Apple IIgs front end is a separate module and needs the same two words for/// the same two things -- see `zig65.debug`.pub const State = zig65.debug.State;
/// A jam and a BRK are opposites and were worth telling apart: one is the/// processor giving up, the other is it doing exactly what it was told./// Sixteen bits of address, because an eight-bit machine has no bank register.pub const Stop = zig65.debug.Stop(u16);
/// The range the run speed can be dialled through, from a microsecond an/// instruction to one a second./// How fast the machine is asked to run, in emulated cycles a second.////// Cycles rather than instructions, because an instruction is not a unit of/// time: a 6502 takes anywhere from two to seven cycles to do one, so pacing/// by instructions gives a machine whose speed depends on what it happens to/// be executing. Pacing by cycles is what the crystal on the board does, and/// it makes a real machine's speed something that can be asked for exactly.////// A IIe's own clock is 1.0205MHz, so out of the box the machine runs at the/// speed it was built to run at and the speed keys go up and down from there.pub const real_hz = 1_020_500;
pub const min_hz = 1_000;
/// How many cycles to leave between keys handed to a machine that takes them/// on an interrupt, so its handler can buffer one before the next arrives./// A millisecond at the II's rate, which is many times what SOS needs.pub const keyboard_settle = 1_000;
pub const max_hz = 1_000_000_000;
/// How long a frame is. The run mode redraws at least this often, so the/// display stays alive at slow speeds, and at most this often, so a fast speed/// does not spend all its time painting.pub const frame_ns = 16 * std.time.ns_per_ms;
/// How often the terminal may be rung at most. A program making a note flips/// the speaker a thousand times a second and the terminal should not be asked/// to keep up with that; this is about how long the Monitor's own beep lasts,/// so one beep gets one bell.pub const bell_interval_ns = 200 * std.time.ns_per_ms;
/// How long a window the running speed is worked out over.pub const measure_interval_ns = 500 * std.time.ns_per_ms;
/// How long a flashing character spends in each of its two states.////// The machine drives this off the video counter rather than anything/// adjustable, and a shade over a quarter of a second either way is what it/// looks like: about twice a second, all told.pub const flash_ns = 267 * std.time.ns_per_ms;
/// The most of a frame that may be spent running instructions, leaving the/// rest of it for drawing one.////// This is what bounds a frame rather than a count of instructions. A count/// has to be picked for the slowest thing the processor might be doing and/// then holds back everything else; a deadline lets a frame run as many/// instructions as there is time for and no more, so the display carries on/// answering however fast the machine is set to go.pub const step_budget_ns = 10 * std.time.ns_per_ms;
/// How often to look at the clock while running a batch. Asking on every/// instruction costs more than the instruction does.pub const steps_between_clock_checks = 4096;
/// Where the sound a machine makes goes: turning the log of the moments the/// cone moved into samples, and handing those to a `.wav` file, to the host's/// live audio, or to both. It renders once and fans the samples out, because/// the log is consumed as it is read and so has one reader.////// One or the other end may be absent — a `.wav` with no live audio, or live/// audio with no file — but not both, in which case there is nothing here to/// make and `open` returns null. A card's two channels have the speaker mixed/// down the middle of them; without a card there is the speaker's one./// The sound card a recording renders, if any: a Mockingboard or a Phasor./// Both turn a write log into two channels; they differ in the log they read/// and in how many chips feed those channels.pub const Board = union(enum) { mocking: zig65.mockingboard.Renderer, phasor: zig65.phasor.Renderer, soundspeech: zig65.soundspeech.Renderer,};
pub const Recording = struct { /// The compact-disc rate the file used before live audio was a thing, and /// the fallback when nothing is playing to say what rate the graph wants. const default_rate = 44_100;
/// The file, if one was asked for. wav: ?*zig65.wav.Writer = null, /// The host's live audio, borrowed from the front end that owns it so that /// it outlives a machine reset, which makes a fresh recording but keeps the /// one open stream. Null when nothing is playing. out: ?*audio.Output = null, renderer: zig65.speaker.Renderer, /// The sound card, if there is one: it makes two channels of its own, and /// the speaker goes down the middle of them. A Mockingboard and a Phasor /// both do this; which one is here decides which log the samples come from. board: ?Board = null, /// The leveled line, if the machine has one: an Apple III's six-bit /// sound DAC, mixed into the speaker's channel since they share the cone. dac: ?zig65.speaker.LevelRenderer = null, samples: [16 * 1024]f32 = undefined, both: [32 * 1024]f32 = undefined,
/// Opens a recording for whichever of the two ends is wanted, or returns /// null when neither is: a `.wav` at `path` if `path` is given, live audio /// through `out` if it is playing. The rate is the live graph's when there /// is one, so the renderers match it, and the file takes that rate too; /// otherwise it is the old compact-disc rate. pub fn open( io: std.Io, alloc: std.mem.Allocator, path: ?[]const u8, out: ?*audio.Output, cycles_per_second: f64, cycle: u64, with_board: bool, with_phasor: bool, with_soundspeech: bool, with_dac: bool, ) !?*Recording { const live = if (out) |o| o.live() else false; if (path == null and !live) return null; const rate: u32 = if (live) out.?.rate else default_rate;
var wav: ?*zig65.wav.Writer = null; if (path) |p| wav = try zig65.wav.Writer.create( io, alloc, p, rate, // A card makes two channels of its own; without one there is only // the speaker, and the speaker is one. if (with_board or with_phasor or with_soundspeech) 2 else 1, ); errdefer if (wav) |w| w.finish(io, alloc);
const self = try alloc.create(Recording); self.* = .{ .wav = wav, .out = if (live) out else null, .renderer = .init(cycles_per_second, @floatFromInt(rate), cycle), .board = if (with_phasor) .{ .phasor = .init(cycles_per_second, @floatFromInt(rate), cycle) } else if (with_soundspeech) .{ .soundspeech = .init(cycles_per_second, @floatFromInt(rate), cycle) } else if (with_board) .{ .mocking = .init(cycles_per_second, @floatFromInt(rate), cycle) } else null, .dac = if (with_dac) .init(cycles_per_second, @floatFromInt(rate), cycle) else null, }; return self; }
/// Renders however much sound the line has made since the last look and /// hands it to the file and the speaker. The line is the machine's speaker /// or its cassette output: the same hardware twice over, so the same /// recording twice over. fn take(self: *Recording, log: anytype, board_log: anytype, phasor_log: anytype, soundspeech_log: anytype, dac_log: anytype, until: u64) !void { while (true) { const flips = log.taken(); const done = self.renderer.render(flips, until, &self.samples); log.consume(done.flips); if (done.samples == 0) break;
// The DAC, if there is one, is added into the speaker's samples // before they are written, the two sharing the one cone. if (self.dac) |*dac| { const mixed = dac.render(dac_log.taken(), until, self.samples[0..done.samples]); dac_log.consume(mixed.entries); }
if (self.board) |*board| { // Both renderers step a sample at the same rate from the same // cycle, so they agree about how many there are; the smaller // is taken in case they ever do not. A Mockingboard reads the // mockingboard log, a Phasor the phasor log; the mixing below // is the same either way. var made_samples: usize = 0; switch (board.*) { .mocking => |*r| { const made = r.render(board_log.taken(), until, self.both[0 .. done.samples * 2]); board_log.consume(made.entries); made_samples = made.samples; }, .phasor => |*r| { const made = r.render(phasor_log.taken(), until, self.both[0 .. done.samples * 2]); phasor_log.consume(made.entries); made_samples = made.samples; }, .soundspeech => |*r| { const made = r.render(soundspeech_log.taken(), until, self.both[0 .. done.samples * 2]); soundspeech_log.consume(made.entries); made_samples = made.samples; }, } const frames = @min(done.samples, made_samples / 2); // One speaker and two channels, so it goes down the middle of // them, which is where a machine with a card in it sounds like // it is coming from. The mix is left in `both` so the file and // the speaker are handed the very same samples. for (0..frames) |i| { self.both[i * 2] += self.samples[i]; self.both[i * 2 + 1] += self.samples[i]; } if (self.wav) |w| for (0..frames) |i| { try w.putFloat(self.both[i * 2]); try w.putFloat(self.both[i * 2 + 1]); }; if (self.out) |o| o.playStereo(self.both[0 .. frames * 2]); } else { if (self.wav) |w| for (self.samples[0..done.samples]) |sample| try w.putFloat(sample); if (self.out) |o| o.playMono(self.samples[0..done.samples]); } } }
/// Puts the sizes in the file's header right and closes it. The live audio /// is not touched: the front end owns it and keeps it across a reset. fn close(self: *Recording, io: std.Io, alloc: std.mem.Allocator) void { if (self.wav) |w| w.finish(io, alloc); alloc.destroy(self); }};
/// The printer on the end of the parallel card's cable, which here is a file.////// Heap-allocated and used through a pointer for the same reason the recording/// above is: a buffered writer holds a pointer into itself, so one that gets/// copied to a new address stops working, and the bug shows up as a truncated/// file long after the copy.pub const Printer = struct { file: std.Io.File, writer: std.Io.File.Writer, /// The writer's own buffer, held here so it lives as long as the writer. /// Buffered because the card is written a byte at a time: a printer that /// made a system call per character would slow the machine down to the /// speed of the disk. buffer: []u8,
pub fn open(io: std.Io, alloc: std.mem.Allocator, path: []const u8) !*Printer { const file = try std.Io.Dir.cwd().createFile(io, path, .{}); errdefer file.close(io);
const self = try alloc.create(Printer); errdefer alloc.destroy(self); const buffer = try alloc.alloc(u8, 4096); errdefer alloc.free(buffer);
self.* = .{ .file = file, .writer = file.writer(io, buffer), .buffer = buffer }; return self; }
fn close(self: *Printer, io: std.Io, alloc: std.mem.Allocator) void { self.writer.interface.flush() catch {}; self.file.close(io); alloc.free(self.buffer); alloc.destroy(self); }};
/// The Mockingboard log a recording is handed on a machine that cannot have/// the card: empty, and never looked at.pub var no_board_log: zig65.mockingboard.Log(false) = .{};/// The same, for the Phasor.pub var no_phasor_log: zig65.phasor.Log(false) = .{};/// And the Sound/Speech card.pub var no_soundspeech_log: zig65.soundspeech.Log(false) = .{};
/// A tape read off disk, as the levels the machine's input can see.pub const Tape = struct { levels: []u8, sample_rate: u32,
/// Reads a WAV into the sides of zero a tape is made of. /// /// Uncompressed sixteen bit PCM, which is what this writes; the first /// channel of however many, since the machine has one input. Everything /// else about the waveform is thrown away, because everything else about /// it is thrown away by the hardware too: the input is a zero crossing /// detector and which side of zero a sample was on is the whole of what /// reaches the processor. pub fn read(io: std.Io, alloc: std.mem.Allocator, path: []const u8) !Tape { const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(1 << 30)); defer alloc.free(bytes); if (bytes.len < 12 or !std.mem.eql(u8, bytes[0..4], "RIFF") or !std.mem.eql(u8, bytes[8..12], "WAVE")) return error.NotAWav;
var channels: u16 = 1; var bits: u16 = 16; var rate: u32 = 0; var at: usize = 12; while (at + 8 <= bytes.len) { const name = bytes[at..][0..4]; const size = std.mem.readInt(u32, bytes[at + 4 ..][0..4], .little); const body = at + 8; if (body + size > bytes.len) break; if (std.mem.eql(u8, name, "fmt ") and size >= 16) { channels = std.mem.readInt(u16, bytes[body + 2 ..][0..2], .little); rate = std.mem.readInt(u32, bytes[body + 4 ..][0..4], .little); bits = std.mem.readInt(u16, bytes[body + 14 ..][0..2], .little); } else if (std.mem.eql(u8, name, "data")) { if (bits != 16 or channels == 0 or rate == 0) return error.UnsupportedWav; const frame = 2 * @as(usize, channels); const frames = size / frame; const levels = try alloc.alloc(u8, frames); for (levels, 0..) |*level, i| { const sample = std.mem.readInt(i16, bytes[body + i * frame ..][0..2], .little); level.* = @intFromBool(sample > 0); } return .{ .levels = levels, .sample_rate = rate }; } // Chunks are padded to an even length. at = body + size + (size & 1); } return error.NoSamples; }};
pub fn Session(comptime CPU: type, comptime has_slots: bool, comptime brk_is_syscall: bool) type { return struct { const Self = @This();
io: std.Io, alloc: std.mem.Allocator, cpu: CPU, state: State, /// How fast the machine is asked to run, in emulated cycles a second. target_hz: u64, /// Cycles the machine owes for time that has passed and has not run yet. /// Kept rather than worked out afresh so that the remainder of a frame /// that did not divide evenly is not thrown away, which at a slow enough /// speed would mean never running anything at all. owed_cycles: i96, /// When the next frame is due. The emulator wakes for frames and nothing /// else, running whatever the time since the last one was worth. next_frame: std.Io.Timestamp, /// When time was last turned into cycles owed. Only meaningful while /// running. last_step: std.Io.Timestamp, /// Why the processor last stopped, or null if it stopped because the user /// said so. stopped: ?Stop, /// How many times the machine's speaker had clicked as of the last look. speaker_clicks: u64, /// When the terminal was last rung. last_bell: std.Io.Timestamp, /// How fast the machine is actually running, in emulated cycles a second. /// /// What was asked for and what the terminal leaves time for are two /// different things, and the difference is the only honest answer to /// whether the emulator is keeping up. Worked out over the last half /// second rather than instant by instant, which would only flicker. measured_hz: f64, measured_at: std.Io.Timestamp, measured_cycles: u64,
/// Which half of its cycle a flashing character is in. /// /// This is the cursor. The Monitor marks where it is by leaving the /// character under it flashing, and on an empty line that character is a /// space, so the whole of the cursor is the flashing rather than anything /// written: draw a flashing space as a plain space and there is no cursor /// on the screen at all. flash: bool, flash_at: std.Io.Timestamp, /// Keys typed at the machine that it has not taken yet. /// /// A terminal hands over a burst of keystrokes in one go, far faster than /// any program could poll for them, and the machine's keyboard holds /// exactly one at a time. Buffering them here rather than in the machine /// keeps the machine honest: it still has one latch, and the queue is the /// host being a slower typist than it really is. /// /// Long enough for a line of eighty columns and then some. It used to be /// sixty-four, which was enough for anything typed at a forty column /// screen and quietly lost the end of anything longer. typed: [256]u8, typed_len: usize, /// The cycle the last key was handed over, for pacing the next one. last_key: u64, /// Text pasted from the host, waiting to go into the keyboard one key /// at a time. It is kept apart from `typed` and grown as it needs to be /// because a paste can be a whole program, far more than the type-ahead /// buffer holds, and it is fed at the same measured pace, so a pasted /// line is entered exactly as a typed one would be. `paste_at` is how /// far through it the machine has been fed; the buffer is emptied and /// the cursor reset once the last byte has gone in. paste: std.ArrayList(u8), paste_at: usize,
/// What is in the drives. /// /// A floppy is a third of a megabyte once it is laid out the way a drive /// reads it, which is far too much to put inside the machine for the sake /// of a machine that may not even have drives. The emulator owns them and /// hands the card a pointer, which is also what makes swapping one out a /// matter of handing over a different pointer. floppies: [2]?*disk2.Floppy, /// The eight hundred kilobyte disk in the drive a IIc Plus has built /// in, if there is one. It is kept apart from `floppies` because it is /// a different mechanism holding a different kind of disk, not a third /// five-and-a-quarter drive: eight hundred kilobytes laid out in blocks /// rather than a hundred and forty in sectors. floppy35: ?*disk35.Floppy, /// Where that one came from, on the same terms as `disk_paths`. disk35_path: ?[]u8, /// The blocks in the intelligent drive on the port, if a machine that /// can have one has one. Not a `Floppy`, because a UniDisk 3.5 is not /// worked as a surface: what the machine asks for is a numbered block /// and what it gets back is five hundred and twelve bytes, so what has /// to be kept is the image itself. unidisk_blocks: [2]?[]u8, /// Where those came from, on the same terms as `disk_paths`. unidisk_path: [2]?[]u8, /// Where each disk came from, kept so that it can be named on screen and /// written back to. disk_paths: [2]?[]u8, /// What to show on the drive line for a disk with no file behind it: /// a blank disk made in memory. A static string, so it is not freed. disk_labels: [2]?[]const u8, /// Whether the machine may write to its disks and whether those writes are /// saved back over the file. Off unless the command line said otherwise: /// quietly rewriting someone's disk images is not a good default. writable: bool, /// Where what the speaker plays is being written, if anywhere. recording: ?*Recording, /// Where the parallel card's bytes go, if a printer was asked for. printer: ?*Printer, /// Which of the Apple keys are being held down, as far as the machine is /// concerned. buttons: [2]bool, /// Where what the cassette output puts out is being written, if anywhere. tape_recording: ?*Recording, /// The tape loaded to play in, if any. Held so it can be wound back. tape: ?Tape, /// The volume in the block device, and where it came from. volume: ?*zig65.blockdevice.Volume, /// The whole file the volume came out of, which is not the same thing when /// the file is a 2IMG: the volume is a slice of this with the header in /// front of it, and it is this that gets written back. volume_file: ?[]u8, volume_path: ?[]u8, /// The memory on a memory expansion card, which the card borrows /// rather than owns, and the file it is kept in between runs when the /// battery option is fitted. memory_card_ram: ?[]u8, ramcharger_path: ?[]u8, /// Each SCSI drive's image and where it came from, by the identity it /// is hooked up at, so that what the machine wrote to one reaches its /// file when the machine stops. A hard disk rather than a floppy: /// nobody ejects one, so it is written back on the way out rather than /// on a command. scsi_images: [7]?[]u8 = @splat(null), scsi_paths: [7]?[]u8 = @splat(null), /// The firmware images the cards in the machine point into. /// /// A card borrows its ROM rather than copying it, which is what keeps /// a slot cheap enough that a machine can have seven of them: eight /// kilobytes of RamFactor firmware in every slot would be sixty-four /// kilobytes of a machine nobody asked for. The bytes belong here and /// have to outlive the machine, which is the whole of the discipline — /// the same one `memory_card_ram` above has always been under, and the /// same one `config.read` describes: what a program reads once, it /// keeps for as long as it runs. firmware: std.ArrayList([]u8), /// Where what the machine sends down the serial line goes. serial_out: ?std.Io.File, /// A writer the serial output goes to instead of the file, when the /// front end has put something on the far end of the line that is not a /// file -- an ImageWriter II emulator, say, which is a `std.Io.Writer` /// that renders the print stream to pages. The library does not know or /// care what it is; it takes precedence over `serial_out` when set. serial_sink: ?*std.Io.Writer, /// What is waiting to be sent to it, and how far through that is. serial_in: ?[]u8, serial_in_at: usize, /// The cycle the next byte in is due, so that it arrives at the rate the /// card was set to rather than as fast as the machine will take it. serial_in_due: u64, /// A Hayes modem on the serial line, dialing out over TCP, when one is /// attached in place of the serial files. Null when the port is a file /// or nothing; when it is here, the serial pump goes through it. modem: ?zig65.modem.Modem, modem_line: zig65.modem.Line, /// The cycle the modem's next byte to the machine is due, paced by the /// card's rate the same as the serial input is. modem_in_due: u64, /// Where a Passport MIDI card's output is written as a Standard MIDI /// File, and a file being fed to its input with the timing it carries. midi_out: ?*zig65.smf.Writer, midi_in: ?zig65.smf.Delivery, midi_in_at: usize, /// The host end of an Uthernet II: the four sockets that stand in for /// the W5100's. Idle and costing nothing until a card is fitted and a /// program opens a socket. uthernet: zig65.uthernet.Ports, /// The host end of an Uthernet (the original): the multicast group its /// CS8900A's frames cross. Opened by the front end when the card is /// fitted, since joining the group can fail, and null otherwise. ethernet: ?zig65.ethernet.Bridge, /// The last thing worth saying about a disk, and which drive it was about. /// It goes on that drive's line rather than to the terminal, which is busy /// being a screen. note: [72]u8, note_len: usize, note_drive: ?u1,
/// The one line the debugger has to say things in that are not about a /// drive: what a key just did, and whether it worked. message: [72]u8, message_len: usize,
/// How many columns the machine's screen is showing. A machine that /// cannot be asked shows forty, which is all any of them could do before /// the IIe. pub fn machineColumns(self: *Self) u16 { if (comptime @hasDecl(CPU.Memory, "columns")) return self.cpu.memory.columns(); return 40; }
/// What the machine's display is doing. A machine that cannot be asked is /// showing forty columns of text, which is all any of them could do before /// the IIe. pub fn machineMode(self: *Self) screen.Mode { if (comptime @hasDecl(CPU.Memory, "mode")) return self.cpu.memory.mode(); return .text; }
/// Which text page the screen is drawn from. pub fn displayPage(self: *Self) u16 { if (comptime @hasDecl(CPU.Memory, "displayPage")) return self.cpu.memory.displayPage(); return 0x0400; }
/// The byte behind one character position on the screen. /// /// In eighty column mode the two halves of memory are read alternately, /// the auxiliary one supplying the even columns, so each pair of columns /// comes from the same address in the two halves. In forty columns it is /// main memory and nothing else, whatever the processor happens to be /// reading through at the time. pub fn videoByte(self: *Self, line_base: u16, column: u16) u8 { if (comptime @hasDecl(CPU.Memory, "videoByte")) { if (self.machineColumns() == 80) { return self.cpu.memory.videoByte(column % 2 == 0, line_base + column / 2); } return self.cpu.memory.videoByte(false, line_base + column); } return self.cpu.memory.peek(line_base + column); }
/// Whether this machine has a slot an eighty column card could be in. pub fn hasVidexCard() bool { return @hasDecl(CPU.Memory, "videxCard"); }
pub fn hasUltraTermCard() bool { return @hasDecl(CPU.Memory, "ultraTermCard"); }
/// Whether this machine has somewhere to put a clock card. The flat model /// is 64K of RAM and nothing else, so it has nowhere to put anything. pub fn hasClock() bool { return @hasDecl(CPU.Memory, "fitClock") or @hasField(CPU.Memory, "clock"); }
/// Whether this machine has somewhere to put a mouse. pub fn hasMouse() bool { return @hasDecl(CPU.Memory, "mouseCard"); }
/// Whether this machine has somewhere to put a block device. pub fn hasBlockDevice() bool { return @hasDecl(CPU.Memory, "insertVolume"); }
/// Whether this machine has somewhere to put a memory expansion card. pub fn hasMemoryCard() bool { return @hasDecl(CPU.Memory, "fitMemoryCard"); }
/// Whether this machine is a IIc, which has the memory expansion /// connector inside the case rather than a slot to put a card in. pub fn hasMemoryExpansion() bool { return @hasDecl(CPU.Memory, "has_memory_expansion") and CPU.Memory.has_memory_expansion; }
/// Saves what a battery-backed card was holding, and gives the memory /// back. /// /// Takes ownership of a card's firmware and hands back what to point /// the card at. The bytes live until the session does. pub fn keepFirmware(self: *Self, bytes: []u8) ![]u8 { try self.firmware.append(self.alloc, bytes); return bytes; }
/// Writes a SCSI disk back to the file it came out of. /// /// A hard disk rather than a floppy: nobody ejects one and there is no /// command that means "I have finished with it", so the moment to save /// it is when the machine stops. The whole image goes back, because a /// SCSI disk is blocks and the file is those blocks -- there is no /// wrapper to preserve and no sector order to put right. pub fn closeScsi(self: *Self) void { for (&self.scsi_images, &self.scsi_paths) |*image, *path| { const bytes = image.* orelse continue; if (path.*) |where| { std.Io.Dir.cwd().writeFile(self.io, .{ .sub_path = where, .data = bytes }) catch {}; self.alloc.free(where); path.* = null; } self.alloc.free(bytes); image.* = null; } }
/// Only if the machine wrote to it, and only if there is a battery: a /// card without the RamCharger loses what was in it when the power /// goes, which is the whole difference between the two. pub fn closeMemoryCard(self: *Self) void { const ram = self.memory_card_ram orelse return; if (comptime hasMemoryCard()) { if (self.cpu.memory.memoryCard()) |card| { if (card.dirty) if (self.ramcharger_path) |path| { std.Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = ram }) catch {}; }; } self.cpu.memory.ejectMemoryCard(); } self.alloc.free(ram); self.memory_card_ram = null; if (self.ramcharger_path) |path| self.alloc.free(path); self.ramcharger_path = null; }
/// Saves the volume back if the machine wrote to it, and puts it away. pub fn closeVolume(self: *Self) void { if (comptime hasBlockDevice()) { const volume = self.volume orelse return; const file = self.volume_file orelse volume.image; if (volume.dirty and !volume.write_protected) { if (self.volume_path) |path| { // The whole file, header and all: the volume is a slice of // it, so what the machine wrote is already in place. std.Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = file }) catch {}; } } self.cpu.memory.insertVolume(0, null); self.alloc.free(file); self.alloc.destroy(volume); self.volume = null; self.volume_file = null; if (self.volume_path) |path| self.alloc.free(path); self.volume_path = null; } }
/// Whether this machine has somewhere to put a serial card. /// Whether this machine has a slot to put a printer card in. /// /// The field alone is not the answer here. A IIe and a IIc are the /// same memory model with a switch on it, so both have the card in /// them; a IIc has no slots, and what is at $c090 on one is its second /// serial port rather than a card. pub fn hasParallel() bool { // An Apple III has no `slots.zig` slots and does have a parallel // card -- the UPIC -- so this asks for the call rather than for // the Apple II's slot apparatus. `has_slots` is what the machine // that has no cards at all answers with. return @hasDecl(CPU.Memory, "fitPrinter") and (has_slots or @hasDecl(CPU.Memory, "fitCard")); }
pub fn hasSerial() bool { return @hasDecl(CPU.Memory, "loadSerialROM"); }
pub fn hasVidex() bool { return @hasDecl(CPU.Memory, "loadVidexROM"); }
pub fn hasUltraTerm() bool { return @hasDecl(CPU.Memory, "loadUltraTermROM"); }
/// Moves bytes each way along the serial line. /// /// Out is whatever the machine has sent since the last look. In is paced: /// a byte goes in only when the card has room and enough time has passed /// for one to have arrived at the rate the card was set to, since a card /// that hands over its input as fast as the machine will take it is not a /// serial port at all. pub fn pumpSerial(self: *Self) void { if (comptime hasSerial()) { if (self.modem != null) return self.pumpModem(); // The far end is a writer the front end attached (an // ImageWriter, say) if there is one, otherwise the output file. // Either way the bytes are consumed only once there is somewhere // to put them, so nothing is lost when nothing is listening. if (self.serial_sink) |sink| { const sent = self.cpu.memory.serialSent(); if (sent.len > 0) { sink.writeAll(sent) catch {}; self.cpu.memory.serialConsume(sent.len); } } else if (self.serial_out) |file| { const sent = self.cpu.memory.serialSent(); if (sent.len > 0) { file.writeStreamingAll(self.io, sent) catch {}; self.cpu.memory.serialConsume(sent.len); } } // Not until the machine has looked for input: anything handed // over before the firmware opens the port is thrown away by the // reset it does on its way in, and the file would lose its first // byte for no reason a person could see. if (self.serial_in) |bytes| if (self.cpu.memory.serialListening()) { while (self.serial_in_at < bytes.len and self.cpu.clock.cycles >= self.serial_in_due) { const acia = self.cpu.memory.serialAcia() orelse break; if (!acia.receiving()) break; _ = self.cpu.memory.serialReceive(bytes[self.serial_in_at]); self.serial_in_at += 1; self.serial_in_due = self.cpu.clock.cycles + acia.cyclesPerByte(); } }; } }
/// The serial line's far end when a modem is attached: the machine's /// bytes go to the modem, the modem's go back paced by the card's rate, /// and what the modem dials crosses the host's TCP. fn pumpModem(self: *Self) void { const mdm = &(self.modem.?); const acia = self.cpu.memory.serialAcia() orelse return; const cycle = self.cpu.clock.cycles; // Keep the modem's timing and reported speed current with the card. mdm.cycles_per_tick = acia.cycles_per_second / 50; self.modem_line.connect_rate = acia.baud();
const sent = self.cpu.memory.serialSent(); for (sent) |byte| mdm.fromMachine(byte, cycle); if (sent.len > 0) self.cpu.memory.serialConsume(sent.len); mdm.tick(cycle);
switch (mdm.takeWants()) { .nothing => {}, .dial => |d| self.modem_line.dial(d.host, d.port), .hangup => self.modem_line.hangup(), // A ringing call is answered when it is accepted in `pump`. .answer => {}, } self.modem_line.pump(mdm);
// The modem's bytes to the machine, one per byte-time, when the // card has room — the slow line draining the modem's buffer. while (mdm.to_machine_len > 0 and cycle >= self.modem_in_due) { if (!acia.receiving()) break; _ = self.cpu.memory.serialReceive(mdm.machineBytes()[0]); mdm.takeMachine(1); self.modem_in_due = cycle + acia.cyclesPerByte(); } }
/// Whether this machine can hold a Passport MIDI interface. pub fn hasMidi() bool { return @hasDecl(CPU.Memory, "midiAcia"); }
/// Moves MIDI each way through a Passport card. Out is timestamped with /// the cycle each byte went out on and written to a Standard MIDI File; /// in is paced by the times the file carries and by the chip having /// room, so a sequence plays back at the speed it was recorded at. pub fn pumpMidi(self: *Self) void { if (comptime hasMidi()) { if (self.midi_out) |writer| { const sent = self.cpu.memory.midiSent(); if (sent.len > 0) { const times = self.cpu.memory.midiSentAt(); for (sent, times) |byte, cycle| writer.feed(&.{byte}, cycle) catch {}; self.cpu.memory.midiConsume(sent.len); } } if (self.midi_in) |delivery| if (self.cpu.memory.midiListening()) { while (self.midi_in_at < delivery.bytes.len and self.cpu.clock.cycles >= delivery.at[self.midi_in_at]) { const acia = self.cpu.memory.midiAcia() orelse break; if (!acia.receiving()) break; _ = self.cpu.memory.midiReceive(delivery.bytes[self.midi_in_at]); self.midi_in_at += 1; } }; } }
/// Whether this machine can hold an Uthernet II. pub fn hasEthernet() bool { return @hasDecl(CPU.Memory, "ethernetChip"); }
/// Drives the Uthernet II's host sockets one step: takes what each of /// the W5100's sockets wants done, does it against the machine's own /// sockets, and moves bytes each way. Quiet — and free — until a card /// is fitted and a program has opened a socket. Called once a frame, /// the way the serial and MIDI lines are. pub fn pumpEthernet(self: *Self) void { if (comptime hasEthernet()) { if (self.cpu.memory.ethernetChip()) |chip| self.uthernet.pump(chip); } }
/// Whether this machine can hold an Uthernet (its CS8900A). pub fn hasCs8900() bool { return @hasDecl(CPU.Memory, "cs8900Chip"); }
/// Moves Ethernet frames each way for an Uthernet: whatever the CS8900A /// has queued goes onto the multicast group, and frames from the group /// that are addressed to this card are handed to the chip. Quiet until /// a card is fitted and the group joined. Called once a frame. pub fn pumpCs8900(self: *Self) void { if (comptime hasCs8900()) { const bridge = &(self.ethernet orelse return); const chip = self.cpu.memory.cs8900Chip() orelse return; if (chip.sent()) |frame| { bridge.send(frame); chip.didSend(); } var buffer: [zig65.cs8900.max_frame]u8 = undefined; while (chip.canReceive()) { const frame = bridge.receive(&buffer) orelse break; if (zig65.ethernet.addressedTo(frame, chip.mac())) chip.receive(frame); } } }
/// Whether this machine has a cassette port whose timing is being kept. pub fn hasCassette() bool { return @hasDecl(CPU.Memory, "playTape"); }
/// Whether this machine has the game connector's buttons. pub fn hasButtons() bool { return @hasDecl(CPU.Memory, "setButton"); }
/// Whether this machine has the game connector's analog paddles. An /// Apple III has the buttons but reads no paddles, so the two are asked /// separately. pub fn hasPaddles() bool { return @hasDecl(CPU.Memory, "setPaddle"); }
/// Whether this machine has the game connector's annunciator outputs. /// /// An Apple II, II Plus and IIe do; a IIc does not -- "the Apple IIc /// family does not support the four annunciator outputs" (Apple /// Computer, Inc., 1989b, Appendix D) -- and neither does a machine /// with no game connector at all. pub fn hasAnnunciators() bool { if (comptime !@hasDecl(CPU.Memory, "has_annunciators")) return false; return CPU.Memory.has_annunciators; }
/// What the four annunciator pins are doing, as a string of four /// digits with a dot for a pin that is off. /// /// Nothing inside the machine can ask this -- "there is no way to read /// the state of an annunciator" -- which is exactly why it is worth /// showing: a program driving one has no other way to find out whether /// it worked, and neither has anybody watching it. pub fn annunciators(self: *const Self, into: *[4]u8) []const u8 { if (comptime !hasAnnunciators()) return ""; for (into, 0..) |*digit, which| { digit.* = if (self.cpu.memory.annunciator(@intCast(which))) '0' + @as(u8, @intCast(which)) else '.'; } return into; }
/// Turns one of the Apple keys on or off, since a terminal has no way to /// say that a key is being held. pub fn holdButton(self: *Self, which: u2) void { if (comptime hasButtons()) { self.buttons[which] = !self.buttons[which]; self.cpu.memory.setButton(which, self.buttons[which]); } }
/// Whether this machine has a speaker whose timing is being kept. Sixty /// four kilobytes of flat memory has neither. pub fn hasSpeaker() bool { return @hasField(CPU.Memory, "speaker_log"); }
/// Whether this machine is one that could have a disk drive at all. The /// flat memory model has no slots and no soft switches to put one behind. pub fn hasDrives() bool { // The call, not a field. This used to ask whether the model had a // field named `disk`, which was true of every machine that had a // Disk II until a II Plus's cards moved into `slots.zig` and it // stopped having one. After that a II Plus answered no here, and // because every drive operation in this file is wrapped in a // `comptime` check of it, `insertDisk` became a function that // silently did nothing: the card was fitted, the boot scan found // it, and the drive it was supposed to be reading was never given // a disk. The machine sat in the card's PROM reading an empty // drive forever, which looks exactly like a machine that will not // boot. Asking for `drives()` asks for the thing actually used. return @hasDecl(CPU.Memory, "drives"); }
/// Whether the drive comes on a card that has to be fitted first, with /// a boot PROM of its own. A IIc and a III have the controller on the /// board and the driver in the machine's ROM. pub fn wantsCard() bool { return @hasDecl(CPU.Memory, "loadCardROM"); }
/// The count the disk controller keeps time by. A III runs its /// processor at 2 MHz and its disk state machine at the Disk II's /// 1 MHz, and says which count is which; everything else has one. pub fn diskCycles(self: *Self) u64 { if (comptime @hasDecl(CPU.Memory, "diskCycles")) return self.cpu.memory.diskCycles(); return self.cpu.clock.cycles; }
/// The speed the machine was built to run at, which is where the /// speed keys start from and come back to. A III says its own; the /// rest share the II's crystal. pub const machine_hz: u64 = if (@hasDecl(CPU.Memory, "cycles_per_second")) CPU.Memory.cycles_per_second else real_hz;
/// Whether this machine has a display that can be drawn as pixels rather /// than merely read as characters. /// /// The flat model is sixty-four kilobytes of RAM and nothing else: no /// switches to ask what the display is doing and no second half of memory /// to draw it out of. Nothing here calls the drawing for it at run time — /// `machineMode` answers text for a machine that cannot be asked — but a /// comptime guard is still needed, because instantiating `video.scanLine` /// against a model with no `mode` is an error whether or not it is ever /// reached. pub fn hasVideo() bool { return @hasDecl(CPU.Memory, "mode") and @hasDecl(CPU.Memory, "hiresPage"); }
/// Says something about a drive, on that drive's line. Anything longer /// than fits is cut: this is a place to be told what happened, not to read /// a file name back character by character. pub fn say(self: *Self, drive: u1, comptime format: []const u8, args: anytype) void { const written = std.fmt.bufPrint(&self.note, format, args) catch self.note[0..]; self.note_len = written.len; self.note_drive = drive; }
/// Says something on the debugger's own line, which is the one place here /// that is not about a drive or a register. pub fn announce(self: *Self, comptime format: []const u8, args: anytype) void { const written = std.fmt.bufPrint(&self.message, format, args) catch self.message[0..]; self.message_len = written.len; }
/// Puts a disk in a drive, taking out whatever was there. /// /// A 2IMG says which way round its sectors are and whether it was write /// protected, and is believed. A bare image says nothing, so the file's /// name is all there is to go on: DOS sector order unless it is a `.po`. /// Puts a blank formatted DOS 3.3 disk in the drive, made in memory /// with no file behind it: it is scratch space, laid out the way INIT /// leaves a disk — volume 254, an empty catalog, every sector free — /// with no DOS on it, so it holds files for a machine that booted /// from something else. Ejecting it loses it, since there is nothing /// to save it back to. pub fn insertBlank(self: *Self, drive: u1) void { if (comptime !Self.hasDrives()) return; const image = self.alloc.alloc(u8, disk2.image_size) catch return; defer self.alloc.free(image); _ = zig65.dos33.Disk.format(image, 254) catch return; const floppy = self.alloc.create(disk2.Floppy) catch return; floppy.* = .{}; floppy.load(image, .dos) catch { self.alloc.destroy(floppy); return; }; // Writable whatever --writable says: that switch is about saving // back over a file, and there is no file. The machine can write to // it or format it further, and the changes live until it is ejected. floppy.write_protected = false;
self.ejectDisk(drive); self.floppies[drive] = floppy; self.disk_paths[drive] = null; self.disk_labels[drive] = "blank DOS 3.3 disk"; self.cpu.memory.drives().insert(drive, floppy); if (self.note_drive != null and self.note_drive.? == drive) { self.note_len = 0; self.note_drive = null; } }
/// Puts a disk in a drive. `writable` overrides the machine-wide /// `--writable` for this one disk: a library entry carries its own flag, /// so a boot disk can be kept read only while the disk that follows it /// into the same drive is written to. Null means fall back to the /// machine-wide setting, which is what a path typed at the prompt does. /// Puts an eight hundred kilobyte disk in the drive a IIc Plus has /// built in, and says whether it took it. A disk that is not that size /// is not this drive's, and the caller falls through to the /// five-and-a-quarter one — which is how the IIgs sorts the two out as /// well. fn insert35( self: *Self, controller: *disk35.Controller, image: anytype, path: []const u8, writable: ?bool, ) !bool { const floppy = try self.alloc.create(disk35.Floppy); errdefer self.alloc.destroy(floppy); floppy.* = .{}; floppy.load(image.data) catch { // Not eight hundred kilobytes, so not this drive's disk. self.alloc.destroy(floppy); return false; }; const may_write = writable orelse self.writable; floppy.write_protected = !may_write or image.write_protected; const kept = try self.alloc.dupe(u8, path); errdefer self.alloc.free(kept);
self.eject35(); self.floppy35 = floppy; self.disk35_path = kept; controller.insert(0, floppy); return true; }
/// Puts a block image in the intelligent drive on the port, and says /// whether it took it. /// /// The drive was sold to hold eight hundred kilobytes, so that is what /// is offered to it; anything else falls through to the /// five-and-a-quarter drives, which is how the 3.5-inch drive on the /// other IIc sorts itself out too. What is kept is the image rather /// than a surface: this drive is asked for numbered blocks and answers /// with their contents, and has no notion of a track. fn insertUnidisk( self: *Self, chain: *zig65.unidisk.Chain, which: u1, image: anytype, path: []const u8, writable: ?bool, ) !bool { const wanted = 1600 * zig65.unidisk.block_size; if (image.data.len < wanted) return false;
const blocks = try self.alloc.dupe(u8, image.data[0..wanted]); errdefer self.alloc.free(blocks); const kept = try self.alloc.dupe(u8, path); errdefer self.alloc.free(kept);
self.ejectUnidisk(which); self.unidisk_blocks[which] = blocks; self.unidisk_path[which] = kept; const may_write = writable orelse self.writable; const drive = &chain.drives[which]; drive.blocks = blocks; drive.write_protected = !may_write or image.write_protected; drive.fitted = true; return true; }
/// Takes whatever is in the intelligent drive out again, and unplugs /// the drive with it: an empty one and none at all are the same thing /// to the firmware, which finds a drive by its answering at all. pub fn ejectUnidisk(self: *Self, which: u1) void { if (comptime !Self.hasDrives()) return; self.saveUnidisk(which); if (self.cpu.memory.unidisk()) |chain| { const drive = &chain.drives[which]; drive.blocks = null; drive.fitted = false; drive.reset(); } if (self.unidisk_blocks[which]) |blocks| self.alloc.free(blocks); self.unidisk_blocks[which] = null; if (self.unidisk_path[which]) |path| self.alloc.free(path); self.unidisk_path[which] = null; }
/// Takes whatever is in that drive out again. pub fn eject35(self: *Self) void { if (comptime !Self.hasDrives()) return; if (self.floppy35 == null) return; // Taking a disk out is the moment to write it back, the same as // for the five-and-a-quarter drives. self.save35(); if (self.cpu.memory.disks35()) |controller| _ = controller.eject(0); if (self.floppy35) |floppy| self.alloc.destroy(floppy); self.floppy35 = null; if (self.disk35_path) |path| self.alloc.free(path); self.disk35_path = null; }
pub fn insertDisk(self: *Self, drive: u1, path: []const u8, writable: ?bool) !void { if (comptime Self.hasDrives()) { // A ShrinkIt archive holds a compressed disk, so it is bigger // than the disk in it only by luck; the limit is the archive's // and the disk that comes out is checked against its own size // by the drive. const file = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.alloc, .limited(disk_file_limit)); defer self.alloc.free(file); const opened = try zig65.diskfile.open(self.alloc, file, path); defer opened.deinit(self.alloc); const image = opened.image;
// A machine with a three-and-a-half inch drive gets first // refusal on anything that is not a recording of a // five-and-a-quarter surface, and the way to tell is to try // loading it: eight hundred kilobytes fits that drive and // nothing else does. This is how the IIgs decides too, in // `session16.insert`. if (!image.isWoz() and !image.isNibble()) { if (self.cpu.memory.disks35()) |controller| { if (try self.insert35(controller, image, path, writable)) return; } // And on the machines with no such drive of their own, the // same size of disk belongs to the intelligent one on the // port. The two are never both there: a IIc Plus has the // drive in its case and no room on the connector for this, // and the machines that take this have no drive in the case. if (self.cpu.memory.unidisk()) |chain| { if (try self.insertUnidisk(chain, drive, image, path, writable)) return; } }
const floppy = try self.alloc.create(disk2.Floppy); errdefer self.alloc.destroy(floppy); floppy.* = .{}; if (image.isWoz()) { // The bits themselves, track lengths and all, which is the // only form that keeps what the timing-based protections // are made of. try floppy.loadWoz(try zig65.woz.open(image.data)); } else if (image.isNibble()) { // A recording of the surface rather than a description of // the sectors on it, which is how a disk that was // protected survives at all: it goes in as it stands and // nothing here has to understand any of it. try floppy.loadNibbles(image.data); } else { try floppy.load(image.data, image.order() orelse return error.NibbleImage); } // A disk out of an archive obeys --writable like any other now // that saving it back re-archives rather than writing the raw // disk over the file, which write-back does through the owned // buffer the archive was unpacked into. const may_write = writable orelse self.writable; floppy.write_protected = !may_write or image.write_protected; const kept = try self.alloc.dupe(u8, path); errdefer self.alloc.free(kept);
self.ejectDisk(drive); self.floppies[drive] = floppy; self.disk_paths[drive] = kept; self.disk_labels[drive] = null; self.cpu.memory.drives().insert(drive, floppy); // Whatever was last said about this drive was about the disk that // is no longer in it. if (self.note_drive != null and self.note_drive.? == drive) { self.note_len = 0; self.note_drive = null; } } }
/// Takes the disk out, saving it first if it was written to. pub fn ejectDisk(self: *Self, drive: u1) void { if (comptime Self.hasDrives()) { if (self.floppies[drive] == null) return; self.saveDisk(drive); _ = self.cpu.memory.drives().eject(drive); if (self.floppies[drive]) |floppy| self.alloc.destroy(floppy); self.floppies[drive] = null; if (self.disk_paths[drive]) |path| self.alloc.free(path); self.disk_paths[drive] = null; self.disk_labels[drive] = null; } }
/// The most a snapshot file is allowed to be: a IIgs with eight /// megabytes of memory and disks in every drive is the biggest, and /// this is comfortably past it. const snapshot_limit = 64 * 1024 * 1024;
/// Writes the whole machine — memory, processor, every chip, and the /// disks in its drives — to a file, so it can be brought back exactly /// with `loadSnapshot`. pub fn saveSnapshot(self: *Self, path: []const u8) !void { var writer: zig65.snapshot.Writer = .{ .gpa = self.alloc }; defer writer.deinit(); try zig65.snapshot.writeHeader(&writer, CPU); try writer.value(CPU, &self.cpu); try self.writeDisks(&writer); try std.Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = writer.list.items }); }
/// Brings a machine back from a snapshot file, disks and all. The state /// is read into this live machine, so it must be the machine the /// snapshot was taken of — a snapshot of another model, or of one with /// a different amount of memory, is refused rather than loaded wrong. pub fn loadSnapshot(self: *Self, path: []const u8) !void { const data = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.alloc, .limited(snapshot_limit)); defer self.alloc.free(data); var reader: zig65.snapshot.Reader = .{ .data = data, .gpa = self.alloc }; try zig65.snapshot.readHeader(&reader, CPU); try reader.value(CPU, &self.cpu); try self.readDisks(&reader); }
/// The disk section of a snapshot: each drive's surface, so a snapshot /// survives a disk being written to or swapped. A drive with nothing in /// it writes a single zero; a drive with a disk writes a one and then /// the disk itself. fn writeDisks(self: *Self, writer: *zig65.snapshot.Writer) !void { if (comptime hasDrives()) { inline for (0..2) |drive| { if (self.floppies[drive]) |floppy| { try writer.int(u8, 1); try writer.value(disk2.Floppy, floppy); } else try writer.int(u8, 0); } if (self.floppy35) |floppy| { try writer.int(u8, 1); try writer.value(disk35.Floppy, floppy); } else try writer.int(u8, 0); } if (comptime hasBlockDevice()) { if (self.volume) |volume| { try writer.int(u8, 1); try writer.value(zig65.blockdevice.Volume, volume); } else try writer.int(u8, 0); } }
/// Reads the disk section back, drive by drive, in the order it was /// written. A five-and-a-quarter or three-and-a-half disk is rebuilt /// from the snapshot whether or not the same one is in the drive now — /// its surface is fixed-size and self-contained. The hard disk is read /// into the volume already fitted, since a hard disk is not something /// swapped mid-run and its image is sized by the file it came from. fn readDisks(self: *Self, reader: *zig65.snapshot.Reader) !void { if (comptime hasDrives()) { inline for (0..2) |drive| { if (try reader.int(u8) != 0) { const floppy = self.floppies[drive] orelse try self.alloc.create(disk2.Floppy); if (self.floppies[drive] == null) floppy.* = .{}; try reader.value(disk2.Floppy, floppy); if (self.floppies[drive] == null) { self.floppies[drive] = floppy; self.disk_paths[drive] = null; self.disk_labels[drive] = "from a snapshot"; self.cpu.memory.drives().insert(@intCast(drive), floppy); } } else self.ejectDisk(@intCast(drive)); } if (try reader.int(u8) != 0) { const controller = self.cpu.memory.disks35(); // Read the surface even if there is nowhere to put it, so // the rest of the section stays in step. const floppy = self.floppy35 orelse try self.alloc.create(disk35.Floppy); if (self.floppy35 == null) floppy.* = .{}; try reader.value(disk35.Floppy, floppy); if (self.floppy35 == null) { if (controller) |c| { self.floppy35 = floppy; self.disk35_path = null; c.insert(0, floppy); } else self.alloc.destroy(floppy); } } else self.eject35(); } if (comptime hasBlockDevice()) { if (try reader.int(u8) != 0) { // Into the fitted volume, whose image is the right size for // this file. A snapshot with a hard disk restored onto a // machine with none is refused rather than half-read. const volume = self.volume orelse return error.NoHardDisk; try reader.value(zig65.blockdevice.Volume, volume); } } }
/// Writes a disk back over the file it came from, if the machine changed /// it and was allowed to. /// /// What is written is the file as it was, with every sector that can be /// found and read on the disk put back into it. Anything unreadable keeps /// what the file already had rather than becoming a hole: a disk the /// machine has been writing to is not necessarily one this can make sense /// of end to end, and losing what was there would be the worse answer. pub fn saveDisk(self: *Self, drive: u1) void { if (comptime !Self.hasDrives()) return; const floppy = self.floppies[drive] orelse return; const path = self.disk_paths[drive] orelse return; if (!floppy.dirty or floppy.write_protected) return; if (self.saved(drive, path, zig65.writeback.floppy(self.io, self.alloc, path, floppy))) floppy.dirty = false; }
/// Puts a file back where it came from, beside it and then moved into /// place rather than over the top of it. /// /// Overwriting means a moment where the file is neither the old disk /// nor the new one, and the one thing worse than losing what the /// machine wrote is losing what was there before it started. Says so /// either way, and answers whether it worked. fn replaceFile(self: *Self, path: []const u8, contents: []const u8, drive: u1) bool { return self.saved(drive, path, zig65.writeback.moveIntoPlace(self.io, self.alloc, path, contents)); }
/// Says how a save went, on the named drive's line. fn saved(self: *Self, drive: u1, path: []const u8, outcome: zig65.writeback.Error!void) bool { const name = std.fs.path.basename(path); outcome catch |err| { switch (err) { error.CannotReRead => self.say(drive, "cannot re-read {s}", .{name}), error.NotTheSameDisk => self.say(drive, "{s} is not the disk that came out", .{name}), error.CannotWrite => self.say(drive, "cannot write {s}", .{name}), } return false; }; self.say(drive, "saved {s}", .{name}); return true; }
/// Writes back what was written to the 3.5-inch drive in the case. pub fn save35(self: *Self) void { if (comptime !Self.hasDrives()) return; const floppy = self.floppy35 orelse return; const path = self.disk35_path orelse return; if (!floppy.dirty or floppy.write_protected) return; if (self.saved(0, path, zig65.writeback.floppy35(self.io, self.alloc, path, floppy))) floppy.dirty = false; }
/// And what was written to an intelligent drive on the port. pub fn saveUnidisk(self: *Self, which: u1) void { if (comptime !Self.hasDrives()) return; const chain = self.cpu.memory.unidisk() orelse return; const drive = &chain.drives[which]; // The session's own pointer rather than the drive's, because they // are the same memory and only one of them survives an eject: a // `CONTROL` call with control code $04 has the drive let go of the // disk from inside the machine, and what was written to it still // has to reach the file. const blocks = self.unidisk_blocks[which] orelse return; const path = self.unidisk_path[which] orelse return; if (!drive.dirty or drive.write_protected) return; if (self.saved(which, path, zig65.writeback.blocks(self.io, self.alloc, path, blocks))) drive.dirty = false; }
/// Turns the flashing over when its half of the cycle is up. pub fn measureFlash(self: *Self) void { // A machine that can be asked answers from its own cycle count, which // is where the flash clock comes from on the hardware: the same // counter that draws the screen. Everything else here is timed that // way too — the clock card, vertical blanking, a disk turning — so a // machine run fast flashes fast and a halted one holds still. if (comptime @hasDecl(CPU.Memory, "flashing")) { self.flash = self.cpu.memory.flashing(); return; } const now: std.Io.Timestamp = .now(self.io, pacing_clock); if (now.nanoseconds - self.flash_at.nanoseconds < flash_ns) return; self.flash = !self.flash; self.flash_at = now; }
/// Works out how fast the machine has actually been running, over a /// window long enough not to jitter. pub fn measureSpeed(self: *Self) void { const now: std.Io.Timestamp = .now(self.io, pacing_clock); const elapsed = now.nanoseconds - self.measured_at.nanoseconds; if (elapsed < measure_interval_ns) return; const cycles = self.cpu.clock.cycles -| self.measured_cycles; self.measured_hz = @as(f64, @floatFromInt(cycles)) / (@as(f64, @floatFromInt(elapsed)) / std.time.ns_per_s); self.measured_at = now; self.measured_cycles = self.cpu.clock.cycles; }
/// How many times the machine must ask for a key and come away empty /// before it is handed one. High enough that the peeks the firmware makes /// while it is busy do not add up to it, low enough that a genuine read /// loop, which asks every few cycles, passes it immediately. pub const poll_threshold = 64;
/// Hands the machine the next typed key, once it has taken the last one. pub fn feedKeyboard(self: *Self) void { if (!@hasDecl(CPU.Memory, "pressKey")) return; // Pasted text is fed ahead of anything typed since, so a paste // arrives in the order it was pasted; both go through the same // pacing below. const pasting = self.paste_at < self.paste.items.len; if (!pasting and self.typed_len == 0) return; // The strobe still being set means the program has not read the // previous key, so it would be overwritten unseen. if (@hasField(CPU.Memory, "strobe") and self.cpu.memory.strobe) return; // Waiting until the machine is properly sitting in a read loop before // handing a key over. Handing one over any earlier loses it: the // firmware peeks at the keyboard while it is busy and clears the latch // on its way in to reading a line, so a key left there too early is // thrown away unseen. That is what was eating the first character of // every line typed at speed. // A machine whose software takes keys on an interrupt, as SOS // does, has no read loop to wait for and says so. const by_interrupt = if (comptime @hasDecl(CPU.Memory, "takesKeysByInterrupt")) self.cpu.memory.takesKeysByInterrupt() else false; if (!by_interrupt and @hasField(CPU.Memory, "empty_polls") and self.cpu.memory.empty_polls < poll_threshold) return; // On an interrupt-driven machine the strobe clears inside the // handler, before the key is safely in the type-ahead buffer; // handing over the next one that instant beats the handler to it. // A short gap since the last key lets it finish, which is what // stops a line typed at speed from losing all but its first // character. if (by_interrupt and self.cpu.clock.cycles - self.last_key < keyboard_settle) return; if (pasting) { self.cpu.memory.pressKey(self.paste.items[self.paste_at]); self.last_key = self.cpu.clock.cycles; self.paste_at += 1; // Emptied once the last pasted byte has gone in, so the buffer // does not grow without bound over a session of pastes. if (self.paste_at >= self.paste.items.len) { self.paste.clearRetainingCapacity(); self.paste_at = 0; } return; } self.cpu.memory.pressKey(self.typed[0]); self.last_key = self.cpu.clock.cycles; std.mem.copyForwards(u8, self.typed[0 .. self.typed_len - 1], self.typed[1..self.typed_len]); self.typed_len -= 1; }
/// Runs one instruction. The two ways an instruction can decline to hand on /// control are not the same thing and are no longer treated as though they /// were: a jam wedges the processor, a BRK does not. pub fn step(self: *Self) void { // Taken before the step, because executing an opcode moves the program // counter past it. const address = self.cpu.program_counter.value;
self.cpu.executeInstruction() catch |err| { switch (err) { // The processor has stopped fetching and will not start again. // A reset is the only way out, so this is the one thing that // halts. error.Jam => { self.state = .halted; self.stopped = .{ .jam = .{ .address = address, .opcode = self.cpu.memory.peek(address), } }; }, // BRK has already done its whole job: pushed the return address // and flags, set the interrupt disable, and vectored. The // processor is in perfectly good order, so it stops somewhere it // can be continued from rather than somewhere it needs rescuing. // // Except on an Apple III, where BRK is not a breakpoint at all: // it is how a program calls SOS — "BRK, followed by the call // number and the address of the parameter list" is every system // call there is — so stopping on it would stop the operating // system at its first call. There it is just an instruction. error.Break => { if (comptime brk_is_syscall) return; self.state = .single_step; self.stopped = .{ .brk = .{ .address = address, .vector = self.cpu.program_counter.value, } }; }, // Every one of the 256 opcodes decodes, so the table never comes // back empty and this cannot happen. error.IllegalOpcode => unreachable, } return; };
// The instruction ran to completion, so whatever stopped the processor // last time is no longer what it is doing now. self.stopped = null; }
/// Runs whatever instructions the clock says have come due, up to a frame's /// worth. Reads the clock once rather than once an instruction, which at a /// microsecond apiece would cost more than the emulation. /// Runs whatever the time since the last look is worth, up to what there /// is time for. /// /// Instructions are run in arrears, in a batch once a frame, rather than /// one to a wake-up. A wake-up per instruction at a megahertz is a million /// trips through the system call that sleeps, each to do a few nanoseconds /// of work, which is how the emulator came to spend almost all of its time /// not emulating. pub fn stepDue(self: *Self) void { var now: std.Io.Timestamp = .now(self.io, pacing_clock); const deadline = now.nanoseconds + step_budget_ns;
// What the time since the last look is worth, in cycles. const elapsed = now.nanoseconds - self.last_step.nanoseconds; self.last_step = now; self.owed_cycles += @divFloor(elapsed * @as(i96, @intCast(self.target_hz)), std.time.ns_per_s); // A machine that has fallen behind does not owe the whole of however // long it was behind for. Carrying that forward would only make the // next frame later still, and the frame after that later again. const most = @divFloor(@as(i96, @intCast(self.target_hz)) * frame_ns, std.time.ns_per_s); if (self.owed_cycles > most) self.owed_cycles = most;
var since_check: usize = 0; while (self.state == .running and self.owed_cycles > 0) { const before = self.cpu.clock.cycles; self.step(); self.owed_cycles -= @intCast(self.cpu.clock.cycles -| before); // Keys are handed over as the machine becomes ready for them // rather than once a frame, so typing keeps pace with the machine // rather than with the display. self.feedKeyboard();
since_check += 1; if (since_check < steps_between_clock_checks) continue; since_check = 0; now = .now(self.io, pacing_clock); if (now.nanoseconds >= deadline) break; } }
/// Whether a frame is due, and if so books it in. Drawing more often than /// the eye can see is the most expensive thing this program can do. pub fn frameDue(self: *Self) bool { const now: std.Io.Timestamp = .now(self.io, pacing_clock); if (now.nanoseconds < self.next_frame.nanoseconds) return false; self.next_frame.nanoseconds += frame_ns; // A frame that came late does not owe a run of catch-up frames. if (self.next_frame.nanoseconds < now.nanoseconds) self.next_frame.nanoseconds = now.nanoseconds + frame_ns; return true; }
/// Waits for the next frame, which is the only thing worth waking for: /// the instructions owed by then are run in one go when it arrives. pub fn nap(self: *Self) !void { const now: std.Io.Timestamp = .now(self.io, pacing_clock); const wait = self.next_frame.nanoseconds - now.nanoseconds; if (wait > 0) try self.io.sleep(.{ .nanoseconds = wait }, pacing_clock); }
/// Does what the reset line does, and lets a halted processor go again. /// /// A machine that was running goes on running, from the reset vector. That /// is what the reset key was: the way out of trouble without reaching for /// the power switch, and on a real Apple the machine comes straight back /// up rather than stopping to be looked at. Stopping it here would mean /// pressing reset and then having to say run as well, every time. /// /// A halted processor is the one exception, and comes back stopped. A JAM /// is worth looking at from its first instruction rather than its /// thousandth, and the state has to change to something in any case, since /// halted is the one state a processor cannot be started out of. pub fn reset(self: *Self) void { self.cpu.reset(); self.stopped = null; if (self.state == .halted) self.state = .single_step; self.last_step = .now(self.io, pacing_clock); self.owed_cycles = 0; // Whatever was typed was meant for the machine that was running, not // the one about to start. The queue is the host's own invention and // nothing on a real Apple holds a key across a reset, so it goes // rather than being handed to the firmware as it comes up. Anything // pasted but not yet typed in goes with it, for the same reason. self.typed_len = 0; // The length alone, not `clearRetainingCapacity`: that poisons the // buffer, and reset runs against a machine some tests bring up with // its fields undefined, exactly as `typed` is cleared by its length // just above rather than by touching the array. self.paste.items.len = 0; self.paste_at = 0; }
/// Enters the run state, timing the first instruction from now rather than /// from whenever the state was last left. pub fn start(self: *Self) void { if (self.state == .halted) return; self.state = .running; self.last_step = .now(self.io, pacing_clock); self.owed_cycles = 0; }
/// Lets go of the machine and everything opened for it: recordings and /// the printer flushed and closed, disks saved and taken out, cards put /// away, files closed. The front end restores its own display separately. pub fn deinit(self: *Self) void { // The recording's header is only right once it is closed. if (self.recording) |recording| recording.close(self.io, self.alloc); self.recording = null; // Whatever the printer has not written yet, before the file goes. if (self.printer) |printer| printer.close(self.io, self.alloc); self.printer = null; if (self.tape_recording) |recording| recording.close(self.io, self.alloc); self.tape_recording = null; if (self.tape) |tape| self.alloc.free(tape.levels); self.tape = null; self.closeVolume(); self.closeMemoryCard(); self.closeScsi(); for (self.firmware.items) |bytes| self.alloc.free(bytes); self.firmware.deinit(self.alloc); self.paste.deinit(self.alloc); if (self.serial_out) |file| file.close(self.io); self.serial_out = null; // Hangs up and closes the modem's socket, if one was dialing. self.modem_line.deinit(); if (self.serial_in) |bytes| self.alloc.free(bytes); self.serial_in = null; if (self.midi_out) |writer| writer.finish(self.io, self.alloc); self.midi_out = null; if (self.midi_in) |delivery| delivery.deinit(self.alloc); self.midi_in = null; // Closes whatever host sockets the Uthernet II left open. self.uthernet.deinit(); // And leaves the Uthernet's multicast group. if (self.ethernet) |*bridge| bridge.close(); self.ethernet = null; // Taking the disks out saves anything written to them, and that // is every drive the machine might have: the two on the card, the // one in the case, and the two an intelligent chain can hold. self.ejectDisk(0); self.ejectDisk(1); self.eject35(); self.ejectUnidisk(0); self.ejectUnidisk(1); self.cpu.deinit(); }
/// Whether the machine has made a noise since the last look worth /// signalling, spacing the reports out so a note does not become a /// thousand of them a second. The frontend decides how to signal it. pub fn bellDue(self: *Self) bool { if (@hasField(CPU.Memory, "speaker_clicks")) { const clicks = self.cpu.memory.speaker_clicks; defer self.speaker_clicks = clicks; if (clicks == self.speaker_clicks) return false;
const now: std.Io.Timestamp = .now(self.io, pacing_clock); if (now.nanoseconds - self.last_bell.nanoseconds < bell_interval_ns) return false; self.last_bell = now; return true; } return false; }
/// Writes however much sound the speaker and the cassette have made since /// the last look, closing a recording that can no longer be written. pub fn captureAudio(self: *Self) void { if (comptime hasSpeaker()) if (self.recording) |recording| { // A machine with no slots has no card to have kept a log, // and the recording was opened without a board to want one. var no_board: zig65.mockingboard.Log(false) = .{}; const board_log = if (comptime @hasField(CPU.Memory, "mockingboard_log")) &self.cpu.memory.mockingboard_log else &no_board; var no_phasor: zig65.phasor.Log(false) = .{}; const phasor_log = if (comptime @hasField(CPU.Memory, "phasor_log")) &self.cpu.memory.phasor_log else &no_phasor; var no_soundspeech: zig65.soundspeech.Log(false) = .{}; const soundspeech_log = if (comptime @hasField(CPU.Memory, "soundspeech_log")) &self.cpu.memory.soundspeech_log else &no_soundspeech; var no_dac: zig65.speaker.LevelLog(false) = .{}; const dac_log = if (comptime @hasField(CPU.Memory, "dac_log")) &self.cpu.memory.dac_log else &no_dac; recording.take( &self.cpu.memory.speaker_log, board_log, phasor_log, soundspeech_log, dac_log, self.cpu.clock.cycles, ) catch { recording.close(self.io, self.alloc); self.recording = null; }; }; if (comptime hasCassette()) if (self.tape_recording) |recording| { var no_dac2: zig65.speaker.LevelLog(false) = .{}; recording.take( &self.cpu.memory.cassette_log, // A tape is one channel, so these are never read; they // only have to exist, and an Apple-1 has no slot for // the card. if (comptime @hasField(CPU.Memory, "mockingboard_log")) &self.cpu.memory.mockingboard_log else &no_board_log, &no_phasor_log, &no_soundspeech_log, // The cassette is the II's, which has no DAC. &no_dac2, self.cpu.clock.cycles, ) catch { recording.close(self.io, self.alloc); self.tape_recording = null; }; }; } };}
const testing = std.testing;
test "a machine's cards are found by asking it, and every probe answers" { // These decide what a front end offers, and they fail *open*: a probe that // stopped matching would simply be false, nothing would fail to compile, // and the debugger would quietly come up with no eighty-column card, no // mouse, no clock and no printer. So they are asserted rather than // trusted, once per machine that ought to have the thing. const IIe = Session( zig65.Chip(.{ .processor = .@"65C02" }, zig65.clock.FakeClock, zig65.memory.AppleIIe(.{})), true, false, ); try testing.expect(IIe.hasVidexCard()); try testing.expect(IIe.hasUltraTermCard()); try testing.expect(IIe.hasMouse()); try testing.expect(IIe.hasClock()); try testing.expect(IIe.hasParallel()); try testing.expect(IIe.hasSerial()); try testing.expect(IIe.hasVidex()); try testing.expect(IIe.hasUltraTerm()); try testing.expect(IIe.hasBlockDevice()); try testing.expect(IIe.hasMemoryCard()); try testing.expect(IIe.hasDrives());
// A II Plus has the same slots and the same cards in them. const IIPlus = Session( zig65.Chip(.{}, zig65.clock.FakeClock, zig65.memory.AppleIIPlus(.{})), true, false, ); try testing.expect(IIPlus.hasVidexCard()); try testing.expect(IIPlus.hasMouse()); try testing.expect(IIPlus.hasClock()); try testing.expect(IIPlus.hasParallel()); try testing.expect(IIPlus.hasSerial()); // The line that was not here. `hasDrives` asked whether the model had a // field named `disk`, which a II Plus stopped having when its cards moved // into `slots.zig`, so it answered no -- and every drive operation in this // file is wrapped in a comptime check of it, which made `insertDisk` a // function that silently did nothing. A II Plus fitted its card, found it // in the boot scan, and sat in the card's PROM reading a drive that never // got a disk. Failing open, exactly as the comment above says. try testing.expect(IIPlus.hasDrives()); try testing.expect(IIPlus.hasBlockDevice());
// A IIc has the same memory model as a IIe with a switch on it, so it has // the fields; what it does not have is slots, which is why `hasParallel` // asks that as well. What is at $c090 on a IIc is its second serial port. const IIc = Session( zig65.Chip(.{ .processor = .@"65C02" }, zig65.clock.FakeClock, zig65.memory.AppleIIc(.{})), false, false, ); try testing.expect(!IIc.hasParallel());
// And the flat model is 64K of RAM and nothing else: nowhere to put // anything, and every probe says so. const Flat = Session( zig65.Chip(.{}, zig65.clock.FakeClock, zig65.memory.Flat(.{})), false, false, ); try testing.expect(!Flat.hasVidexCard()); try testing.expect(!Flat.hasMouse()); try testing.expect(!Flat.hasClock()); try testing.expect(!Flat.hasParallel()); try testing.expect(!Flat.hasSerial()); try testing.expect(!Flat.hasBlockDevice()); try testing.expect(!Flat.hasDrives());}
test "a machine's annunciators show as digits, and a machine without them shows nothing" { const IIe = Session( zig65.Chip(.{ .processor = .@"65C02" }, zig65.clock.FakeClock, zig65.memory.AppleIIe(.{})), true, false, ); try testing.expect(IIe.hasAnnunciators());
var session: IIe = undefined; try session.cpu.init(null, null); defer session.cpu.deinit();
// Annunciator 3 comes up set, because a machine with double resolution off // is a machine whose third annunciator pin is high -- one latch, two // names. The other three come up clear. var digits: [4]u8 = undefined; try testing.expectEqualStrings("...3", session.annunciators(&digits));
session.cpu.memory.write(u8, 0xc059, 0); // annunciator 0 on session.cpu.memory.write(u8, 0xc05e, 0); // annunciator 3 off, double res on try testing.expectEqualStrings("0...", session.annunciators(&digits));
// A IIc has no annunciator pins to show, and says so at comptime rather // than drawing four dots for outputs that are not on the machine. const IIc = Session( zig65.CMOS(zig65.clock.FakeClock, zig65.memory.AppleIIc(.{})), false, false, ); try testing.expect(!IIc.hasAnnunciators());}