// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Driving an Apple IIe from another program. //! //! Everything a caller has to do to control a machine is here: bringing one //! up, running it, giving it keys the way its keyboard actually works, and //! reading back what it printed. It boots a real ROM, waits for the BASIC //! prompt, types a program at it, runs it, and checks the answer came out. //! //! Nothing here draws anything or reads a terminal. The machine is a value in //! a program, and this drives it as fast as the host will go: the emulator //! paces itself against a clock only because a person is watching, and a //! caller that only wants the answer has no reason to wait for it. //! //! zig build example -- /path/to/apple2e.rom const std = @import("std"); const zig65 = @import("zig65"); /// A IIe. The memory model is what decides which machine this is; the /// processor is the same either way. const Machine = zig65.CPU(zig65.clock.FakeClock, zig65.memory.AppleIIe(.{})); /// How long to give the machine before deciding it is never going to do the /// thing being waited for. Generous: it is a limit on a machine that has gone /// wrong, not a timing. const patience_cycles = 200_000_000; /// How many instructions to run between looks at the screen. Looking after /// every one would cost far more than running them. const between_looks = 20_000; /// What is on the text screen, as one run of characters. /// /// Twenty-four rows of forty, or of eighty, with nothing between them: the /// mode says which, and a screen showing graphics gives nothing at all. fn screenText(machine: *Machine, buffer: []u8) []const u8 { var writer: std.Io.Writer = .fixed(buffer); machine.memory.writeText(&writer) catch {}; return writer.buffered(); } /// Runs the machine until something it has printed says so. fn waitFor(machine: *Machine, wanted: []const u8) !void { var buffer: [zig65.screen.rows * 80]u8 = undefined; const deadline = machine.clock.cycles + patience_cycles; while (machine.clock.cycles < deadline) { for (0..between_looks) |_| machine.executeInstruction() catch {}; if (std.mem.indexOf(u8, screenText(machine, &buffer), wanted) != null) return; } return error.NeverHappened; } /// Runs the machine until it prints something, and gives up usefully when it /// never does: whatever has gone wrong, the machine has almost certainly said /// so on its screen, so that is worth showing rather than an error on its own. fn expectOnScreen(machine: *Machine, wanted: []const u8) void { waitFor(machine, wanted) catch |err| { std.debug.print("'{s}' never appeared: {s}\n", .{ wanted, @errorName(err) }); showScreen(machine); std.process.exit(1); }; } /// Types at the machine the way its keyboard works. /// /// There is one latch and no queue behind it. A key put there before the /// firmware has taken the last one is simply gone, and the firmware clears the /// latch on its way in to reading a line, so a caller that writes keys as fast /// as it can think of them will lose most of them. Each key therefore waits /// until the machine has asked for one and come away empty a good few times, /// which is what a machine sitting in a read loop looks like from outside. fn typeAt(machine: *Machine, text: []const u8) !void { for (text) |key| { const deadline = machine.clock.cycles + patience_cycles; while (machine.memory.strobe or machine.memory.empty_polls < 64) { machine.executeInstruction() catch {}; if (machine.clock.cycles > deadline) return error.NotListening; } machine.memory.pressKey(key); } } /// Prints the screen the way it looks, which needs the mode to know how wide /// the rows are. fn showScreen(machine: *Machine) void { const mode = machine.memory.mode(); const columns = mode.columns() orelse { std.debug.print("the screen is showing {s}, so there is no text on it\n", .{@tagName(mode)}); return; }; var buffer: [zig65.screen.rows * 80]u8 = undefined; const text = screenText(machine, &buffer); std.debug.print("\n{s}, {d} columns:\n", .{ @tagName(mode), columns }); for (0..zig65.screen.rows) |row| { std.debug.print(" |{s}|\n", .{text[row * columns ..][0..columns]}); } } pub fn main(init: std.process.Init) !void { var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); const rom_path = args.next() orelse { std.debug.print("usage: zig build example -- PATH-TO-ROM\n", .{}); std.process.exit(2); }; const rom = std.Io.Dir.cwd().readFileAlloc(init.io, rom_path, init.gpa, .limited(0x10000)) catch |err| { std.debug.print("cannot read '{s}': {s}\n", .{ rom_path, @errorName(err) }); std.process.exit(1); }; defer init.gpa.free(rom); // A machine is a value. It is a large one, a IIe being two lots of 64K and // the ROM, so it goes on the heap rather than the stack. const machine = try init.gpa.create(Machine); defer init.gpa.destroy(machine); try machine.init(null, null); defer machine.deinit(); try machine.memory.loadROMAtEnd(rom); // The reset line, which is what starts a machine: it puts the switches // back and sends the processor through the vector at $fffc. machine.reset(); std.debug.print("waiting for the prompt\n", .{}); expectOnScreen(machine, "]"); // A program, typed in as somebody would type it. The machine is doing all // the work here: this only presses keys. // Return is a carriage return, $0d. A line fed to this machine ending in // $0a is a line feed, which moves the cursor down and enters nothing: the // machine is older than the convention. std.debug.print("typing a program in\n", .{}); try typeAt(machine, "10 FOR I = 1 TO 5\r" ++ "20 PRINT I * I;\" \";\r" ++ "30 NEXT\r" ++ "40 PRINT\r" ++ "RUN\r"); std.debug.print("waiting for it to print its answer\n", .{}); expectOnScreen(machine, "1 4 9 16 25"); showScreen(machine); // Eighty columns are the same screen read from both halves of memory, and // the mode is how a caller knows which it is getting. std.debug.print("\nswitching it to eighty columns\n", .{}); try typeAt(machine, "PR#3\rPRINT \"AND EIGHTY COLUMNS OF IT\"\r"); expectOnScreen(machine, "AND EIGHTY COLUMNS OF IT"); showScreen(machine); std.debug.print("\nran {d} cycles, which is {d:.1} seconds of machine time\n", .{ machine.clock.cycles, @as(f64, @floatFromInt(machine.clock.cycles)) / 1_020_500.0, }); }