// SPDX-License-Identifier: GPL-3.0-or-later #include #import "VCCMachineController.h" #include "../../../src/core/MachineSession.h" #include "../../../src/core/DebugDisassembler.h" #include "MacAudioOutput.h" #include "DriveWireEndpoint.h" #include "../../../src/core/FramePacing.h" #include "../../../src/devices/FD502/Fd502Device.h" #include "../../../src/devices/RomCartridge.h" #include "../../../src/devices/RamDiskDevice.h" #include "../../../src/devices/Orchestra90Device.h" #include "../../../src/devices/SpeechSoundDevice.h" #include "../../../src/devices/SDCDevice.h" #include "../../../src/devices/HardDisk/HardDiskDevice.h" #include "../../../src/core/BinaryImage.h" #include #include #include #include #include #include #include #include @interface VCCTraceRecord () @property(nonatomic, readwrite) NSUInteger index; @property(nonatomic, readwrite) uint64_t clock, frame; @property(nonatomic, readwrite) NSInteger cycles; @property(nonatomic, readwrite) uint16_t address; @property(nonatomic, readwrite, copy) NSString *kind, *instruction, *detail, *before, *after; @end @implementation VCCTraceRecord @end @interface VCCTraceSnapshot () @property(nonatomic, readwrite) BOOL armed, capturing; @property(nonatomic, readwrite) uint64_t identifier; @property(nonatomic, readwrite) NSUInteger total, limit, offset; @property(nonatomic, readwrite, copy) NSString *status; @property(nonatomic, readwrite, copy) NSArray *records; @end @implementation VCCTraceSnapshot @end static NSString* TraceRegisters(const VCC::CPUState& state, bool extended) { auto common = [NSString stringWithFormat:@"PC %04X A %02X B %02X X %04X Y %04X U %04X S %04X DP %02X CC %02X", state.PC, state.A, state.B, state.X, state.Y, state.U, state.S, state.DP, state.CC]; return extended ? [common stringByAppendingFormat:@" E %02X F %02X V %04X MD %02X", state.E, state.F, state.V, state.MD] : common; } static NSString* TraceKind(VCC::TraceEvent event) { switch (event) { case VCC::TraceEvent::Instruction: return @"Instruction"; case VCC::TraceEvent::IRQRequested: return @"IRQ requested"; case VCC::TraceEvent::IRQMasked: return @"IRQ masked"; case VCC::TraceEvent::IRQServicing: return @"IRQ servicing"; case VCC::TraceEvent::IRQExecuting: return @"IRQ vector"; case VCC::TraceEvent::ScreenHSYNCLow: return @"HSYNC low"; case VCC::TraceEvent::ScreenHSYNCHigh: return @"HSYNC high"; case VCC::TraceEvent::ScreenVSYNCLow: return @"VSYNC low"; case VCC::TraceEvent::ScreenVSYNCHigh: return @"VSYNC high"; case VCC::TraceEvent::ScreenReg: return @"Video register"; case VCC::TraceEvent::ScreenTopBorder: return @"Top border"; case VCC::TraceEvent::ScreenRender: return @"Active display"; case VCC::TraceEvent::ScreenBottomBorder: return @"Bottom border"; case VCC::TraceEvent::EmulatorCycle: return @"Scheduler"; default: return @"Event"; } } static std::vector DebugAddresses(NSArray* values, unsigned maximum) { if (values.count > maximum) throw std::invalid_argument("Too many debugger addresses"); std::vector result; for (NSNumber* value in values) { const double n = value.doubleValue; if (!std::isfinite(n) || n < 0 || n > 65535 || n != std::floor(n)) throw std::invalid_argument("Use logical addresses from 0000 to FFFF"); result.push_back(uint16_t(n)); } return result; } @interface VCCDebugInstruction () @property(nonatomic, readwrite) uint16_t address; @property(nonatomic, readwrite, copy) NSData *bytes; @property(nonatomic, readwrite, copy) NSString *mnemonic, *operand; @property(nonatomic, readwrite) BOOL valid; @end @implementation VCCDebugInstruction @end @interface VCCDebugMemoryCapture () @property(nonatomic, readwrite) VCCMachineSnapshot *machine; @property(nonatomic, readwrite) uint32_t address, capacity; @property(nonatomic, readwrite, copy) NSData *bytes, *available; @property(nonatomic, readwrite, copy) NSArray *instructions; @property(nonatomic, readwrite, copy) NSArray *instructionOffsets; @end @implementation VCCDebugMemoryCapture @end @interface VCCDebugGraphicsPixel () @property(nonatomic, readwrite) uint32_t address; @property(nonatomic, readwrite) uint8_t value, mask; @property(nonatomic, readwrite) BOOL available; @property(nonatomic, readwrite) NSNumber *attributeAddress, *attributeValue; @end @implementation VCCDebugGraphicsPixel @end @interface VCCDebugGraphicsCapture () @property(nonatomic, readwrite) VCCMachineSnapshot *machine; @property(nonatomic, readwrite, copy) NSString *errorMessage; - (void)takePreview:(VCC::Mac::DebugGraphicsPreview&)preview; @end @implementation VCCDebugGraphicsCapture { VCC::Mac::DebugGraphicsPreview _source; NSData *_rgba; NSString *_modeName; } - (void)takePreview:(VCC::Mac::DebugGraphicsPreview&)preview { _modeName = [NSString stringWithUTF8String:preview.modeName.c_str()]; NSMutableData *rgba = [NSMutableData dataWithLength:preview.pixels.size() * 4]; auto* out = static_cast(rgba.mutableBytes); for (const auto rgb : preview.pixels) { *out++ = uint8_t(rgb >> 16); *out++ = uint8_t(rgb >> 8); *out++ = uint8_t(rgb); *out++ = 255; } _rgba = rgba; // Keep only the packed RGBA buffer and source-byte metadata after publication. std::vector().swap(preview.pixels); _source = std::move(preview); } - (NSString *)modeName { return _modeName ?: @""; } - (NSData *)rgba { return _rgba ?: [NSData data]; } - (NSInteger)width { return _source.width; } - (NSInteger)height { return _source.height; } - (uint32_t)address { return _source.address; } - (BOOL)physical { return _source.physical; } - (VCCDebugGraphicsPixel *)pixelAtX:(NSInteger)x y:(NSInteger)y { if (!_rgba || x < 0 || y < 0 || x >= self.width || y >= self.height) return nil; const auto selection = _source.pixelInfo(unsigned(x), unsigned(y)); const auto i = selection.byteIndex; auto result = [VCCDebugGraphicsPixel new]; result.address = _source.byteAddresses[i]; result.available = _source.available[i] != 0; result.value = _source.bytes[i]; result.mask = selection.mask; if (_source.bytesPerCell == 2) { result.attributeAddress = @(_source.byteAddresses[i + 1]); if (_source.available[i + 1]) result.attributeValue = @(_source.bytes[i + 1]); } return result; } - (BOOL)hasSameLayoutAs:(VCCDebugGraphicsCapture *)other { if (!_rgba || !other->_rgba || self.machine.generation != other.machine.generation) return NO; const auto& otherSource = other->_source; return (_source.physical || self.machine.debuggerMappingFingerprint == other.machine.debuggerMappingFingerprint) && _source.physical == otherSource.physical && _source.address == otherSource.address && _source.width == otherSource.width && _source.height == otherSource.height && _source.modeName == otherSource.modeName && _source.bytesPerCell == otherSource.bytesPerCell && _source.pixelsPerByte == otherSource.pixelsPerByte && _source.linesPerRow == otherSource.linesPerRow && _source.rowByteOffsets == otherSource.rowByteOffsets && _source.byteAddresses == otherSource.byteAddresses; } @end @interface VCCMemoryMapping () @property(nonatomic, readwrite) uint16_t page; @property(nonatomic, readwrite) uint32_t ramAddress, sourceAddress; @property(nonatomic, readwrite) NSInteger source; @end @implementation VCCMemoryMapping @end @interface VCCMMUSnapshot () @property(nonatomic, readwrite) BOOL enabled, ramVectors, allRAM; @property(nonatomic, readwrite) NSUInteger activeTask, romMap, prefix; @property(nonatomic, readwrite) uint32_t ramByteCount, vectorRAMAddress; @property(nonatomic, readwrite, copy) NSArray *task0, *task1; @property(nonatomic, readwrite, copy) NSArray *effective; @end @implementation VCCMMUSnapshot @end @interface VCCDebuggerSnapshot () @property(nonatomic, readwrite) VCCMachineSnapshot *machine; @property(nonatomic, readwrite, copy) NSDictionary *registers; @property(nonatomic, readwrite, copy) NSArray *instructions; @property(nonatomic, readwrite, copy) NSArray *breakpoints, *disabledBreakpoints; @property(nonatomic, readwrite) uint16_t memoryAddress; @property(nonatomic, readwrite, copy) NSData *memory, *memoryAvailable; @property(nonatomic, readwrite, copy) NSData *logicalMemory, *logicalMemoryAvailable; @property(nonatomic, readwrite, copy) NSString *stopReason; @property(nonatomic, readwrite) VCCMMUSnapshot *mmu; @property(nonatomic, readwrite) uint32_t physicalAddress; @property(nonatomic, readwrite, copy) NSData *physicalMemory; @end @implementation VCCDebuggerSnapshot @end @implementation VCCMachineProfile - (instancetype)init { if ((self = [super init])) { _ram = 1; _overclock = _frameInterval = 1; _physicalSlot = 4; _videoOutput = 1; _volume = 0.5; _sound = _clockEnabled = _clockReadOnly = YES; _diskROMName = @""; _kinds = @[@0,@0,@0,@0,@0]; _cartridgeROMs = @[[NSData data],[NSData data],[NSData data],[NSData data],[NSData data]]; _cartridgeNames = @[@"",@"",@"",@"",@""]; _sdcFolders = @[@"",@"",@"",@"",@""]; _sdcReadOnly = @[@YES,@YES,@YES,@YES,@YES]; _images = @[[NSData data],[NSData data],[NSData data],[NSData data],[NSData data],[NSData data]]; _imageNames = @[@"",@"",@"",@"",@"",@""]; _readOnly = _protectedImages = @[@NO,@NO,@NO,@NO,@NO,@NO]; } return self; } - (id)copyWithZone:(NSZone*)zone { auto value = [[VCCMachineProfile allocWithZone:zone] init]; value.use6309 = self.use6309; value.fastForward = self.fastForward; value.sound = self.sound; value.multiPak = self.multiPak; value.clockEnabled = self.clockEnabled; value.clockReadOnly = self.clockReadOnly; value.cassetteWAV = self.cassetteWAV; value.fastCassette = self.fastCassette; value.ram = self.ram; value.overclock = self.overclock; value.frameInterval = self.frameInterval; value.videoOutput = self.videoOutput; value.physicalSlot = self.physicalSlot; value.volume = self.volume; value.systemROM = self.systemROM; value.diskROM = self.diskROM; value.cassette = self.cassette; value.diskROMName = self.diskROMName; value.kinds = [[NSArray alloc] initWithArray:self.kinds copyItems:YES]; value.readOnly = [[NSArray alloc] initWithArray:self.readOnly copyItems:YES]; value.protectedImages = [[NSArray alloc] initWithArray:self.protectedImages copyItems:YES]; value.cartridgeROMs = [[NSArray alloc] initWithArray:self.cartridgeROMs copyItems:YES]; value.images = [[NSArray alloc] initWithArray:self.images copyItems:YES]; value.cartridgeNames = [[NSArray alloc] initWithArray:self.cartridgeNames copyItems:YES]; value.imageNames = [[NSArray alloc] initWithArray:self.imageNames copyItems:YES]; value.sdcFolders = [[NSArray alloc] initWithArray:self.sdcFolders copyItems:YES]; value.sdcReadOnly = [[NSArray alloc] initWithArray:self.sdcReadOnly copyItems:YES]; return value; } @end @interface VCCDiskSnapshot () @property(nonatomic, readwrite) BOOL mounted, dirty, writeProtected, sourceReadOnly; @property(nonatomic, readwrite, copy) NSString *name; @property(nonatomic, readwrite, copy) NSString *floppyExtension; @property(nonatomic, readwrite) BOOL formatWriteProtected; @property(nonatomic, readwrite) NSUInteger tracks, sides, byteCount; @property(nonatomic, readwrite) uint64_t readEvents, writeEvents; @end @implementation VCCDiskSnapshot @end @interface VCCDiskEditCapture () @property(nonatomic, readwrite, copy) NSData *data; @property(nonatomic, readwrite, copy) NSString *name; @property(nonatomic, readwrite) uint64_t token; @property(nonatomic, readwrite) NSInteger drive; @property(nonatomic, readwrite) BOOL canApply; @end @implementation VCCDiskEditCapture @end @interface VCCHardDiskSave () @property(nonatomic, readwrite, copy) NSData *data; @property(nonatomic, readwrite) uint64_t token; @property(nonatomic, readwrite) NSUInteger byteCount; @end @implementation VCCHardDiskSave @end @interface VCCPrinterOutput () @property(nonatomic, readwrite, copy) NSData *bytes; @property(nonatomic, readwrite) uint64_t revision, droppedBytes; @property(nonatomic, readwrite) NSUInteger capacity; @property(nonatomic, readwrite) BOOL enabled; @end @implementation VCCPrinterOutput @end @interface VCCJoystickInputSnapshot () @property(nonatomic, readwrite) NSUInteger x, y, buttons, mode; @end @implementation VCCJoystickInputSnapshot @end @interface VCCMachineSnapshot () @property(nonatomic, readwrite) NSUInteger pasteRemaining; @property(nonatomic, readwrite) BOOL printerEnabled; @property(nonatomic, readwrite) uint64_t printerRevision, printerDroppedBytes; @property(nonatomic, readwrite) NSUInteger printerByteCount; @property(nonatomic, readwrite) VCCMachineState state; @property(nonatomic, readwrite) uint64_t generation, frames, cycles; @property(nonatomic, readwrite, copy) NSArray *joystickInputs; @property(nonatomic, readwrite) BOOL keyboardInputHeld; @property(nonatomic, readwrite) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision; @property(nonatomic, readwrite) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping; @property(nonatomic, readwrite) BOOL debuggerBankedDevelopment; @property(nonatomic, readwrite) BOOL basicDebugAttached, assistantCompiledReturned; @property(nonatomic, readwrite, nullable) NSNumber *assistantDirectPrompt, *assistantEmptyBASIC; @property(nonatomic, readwrite, copy, nullable) NSString *assistantLoadedSource; @property(nonatomic, readwrite) NSInteger basicStoppedLine; @property(nonatomic, readwrite) NSInteger basicSourceOffset; @property(nonatomic, readwrite) NSUInteger basicSourceLength; @property(nonatomic, readwrite) BOOL basicStepping, basicCanStepOut; @property(nonatomic, readwrite) NSInteger basicErrorLine; @property(nonatomic, readwrite, copy) NSString *basicErrorCode; @property(nonatomic, readwrite, copy) NSString *basicDebugStatus; @property(nonatomic, readwrite) uint16_t programCounter; @property(nonatomic, readwrite) CGRect activeVideoRect; @property(nonatomic, readwrite, copy, nullable) NSData *pixels; @property(nonatomic, readwrite, copy, nullable) NSString *errorMessage; @property(nonatomic, readwrite) BOOL use6309, fastForward; @property(nonatomic, readwrite) NSUInteger ramConfiguration, cpuOverclock, frameInterval; @property(nonatomic, readwrite) uint64_t presentedFrame, pixelRevision; @property(nonatomic, readwrite) NSInteger videoOutput; @property(nonatomic, readwrite) BOOL audioEnabled; @property(nonatomic, readwrite) BOOL driveWireEnabled; @property(nonatomic, readwrite, copy) NSString *macShellStatus; @property(nonatomic, readwrite) uint64_t macShellRequestID; @property(nonatomic, readwrite) uint64_t audioUnderruns, audioOverruns, audioConsumed; @property(nonatomic, readwrite) uint64_t audioSubmitted, audioSignalSamples, audioBuffered, audioStarts; @property(nonatomic, readwrite) uint64_t audioMaximumRequest, audioMaximumRefillGapNanoseconds; @property(nonatomic, readwrite) BOOL tapeMounted, tapeMotor, tapeDirty, tapeFast, tapeWAV; @property(nonatomic, readwrite) NSInteger tapeMode; @property(nonatomic, readwrite) uint64_t tapePosition, tapeLength; @property(nonatomic, readwrite) uint64_t tapeReadEvents, tapeWriteEvents; @property(nonatomic, readwrite) BOOL diskEnabled, diskBusy, diskMotor, diskConnected, diskEditorLocked; @property(nonatomic, readwrite) BOOL hardDiskConnected, hardClockEnabled, hardClockReadOnly; @property(nonatomic, readwrite) NSUInteger hardSelectedDrive, hardSector, hardStatus; @property(nonatomic, readwrite) uint64_t hardFlushRequests; @property(nonatomic, readwrite, copy) NSArray *hardDisks; @property(nonatomic, readwrite) BOOL sdcReadOnly; @property(nonatomic, readwrite, copy) NSArray *sdcDriveNames; @property(nonatomic, readwrite, copy) NSString *sdcDirectory; @property(nonatomic, readwrite, copy, nullable) NSString *sdcError; @property(nonatomic, readwrite) uint64_t sdcReadCount, sdcWriteCount; @property(nonatomic, readwrite) BOOL multiPakEnabled; @property(nonatomic, readwrite) NSUInteger physicalSlot, romSlot, ioSlot; @property(nonatomic, readwrite, copy) NSArray *cartridgeKinds; @property(nonatomic, readwrite, copy) NSArray *cartridgeNames; @property(nonatomic, readwrite, copy) NSString *diskROMName; @property(nonatomic, readwrite) NSInteger diskSelectedDrive; @property(nonatomic, readwrite) NSUInteger diskTrack, diskSector, diskSide; @property(nonatomic, readwrite, copy) NSArray *disks; @end @implementation VCCCompiledRunLease { std::atomic _valid; } - (instancetype)init { if ((self = [super init])) _valid.store(true); return self; } - (BOOL)isValid { return _valid.load(); } - (void)invalidate { _valid.store(false); } @end @implementation VCCMachineSnapshot - (NSArray *)assistantDeviceBlockers { NSMutableArray *reasons = [NSMutableArray array]; if (self.driveWireEnabled || ![self.macShellStatus isEqualToString:@"idle"]) [reasons addObject:@"Disable DriveWire networking and end Mac shell access before running a shared program."]; if (self.tapeMounted || self.tapeMode == 2) [reasons addObject:@"Eject the cassette and end recording before running a shared program."]; for (VCCDiskSnapshot *drive in [self.disks arrayByAddingObjectsFromArray:self.hardDisks]) if (drive.mounted && !drive.writeProtected) { [reasons addObject:@"Eject writable disks or enable write protection before running a shared program."]; break; } for (NSNumber *kind in self.cartridgeKinds) if (kind.integerValue != 0 && kind.integerValue != 2) { [reasons addObject:@"Choose a BASIC setup with only a floppy controller before running a shared program."]; break; } return reasons; } @end namespace { struct Worker { VCC::Mac::DriveWireShell shell; uint64_t shellGeneration = 0, mediaRevision = 0; std::string assistantPasteRun; VCCCompiledRunLease *compiledKeyLease = nil; VCCMachineSnapshot *compiledKeyExpected = nil; bool compiledKeyAssembly = false; std::optional> assistantProgram; VCC::Mac::MachineSession machine; VCC::Mac::MacAudioOutput audio; bool audioEnabled = false, fastForward = false; VCC::Mac::FramePacer pacer; VCC::Mac::AudioProgress audioProgress; std::chrono::steady_clock::time_point previousAudioTick{}; uint64_t maximumAudioGap = 0; std::shared_ptr capturedFrame; NSData* capturedPixels = nil; uint64_t pixelRevision = 0; bool closed = false; std::string error; std::string diskROMName; struct Export { uint64_t token; std::vector bytes; }; std::array, 4> exports; std::array diskNames; std::array readOnly{}; uint64_t nextExport = 0; struct DiskEdit { uint64_t token, generation, mediaRevision; unsigned drive; std::vector original; std::optional prepared; bool hardDisk = false; std::optional preparedHard; }; std::optional diskEdit; uint64_t nextDiskEdit = 0; void requireNoDiskEditor() const { if (diskEdit) throw std::logic_error("Close the Disk Image Editor before running, resetting or changing the CoCo and its media."); } DiskEdit& requireDiskEditor(uint64_t token) { if (!diskEdit || diskEdit->token != token) throw std::logic_error("This disk edit session has ended. Reopen the disk to edit it."); auto& edit = *diskEdit; const auto* floppyImage = !edit.hardDisk && floppy() ? floppy()->image(edit.drive) : nullptr; const auto* hardImage = edit.hardDisk ? hardDevice->image(edit.drive) : nullptr; const bool unchanged = edit.hardDisk ? hardImage && hardImage->bytes() == edit.original : floppyImage && floppyImage->bytes() == edit.original; if (closed || machine.snapshot().generation != edit.generation || mediaRevision != edit.mediaRevision || !unchanged || (floppy() && floppy()->snapshot().busy)) throw std::logic_error("The mounted disk or machine changed. Keep your edited copy and reopen the disk."); return edit; } std::shared_ptr hardDevice = std::make_shared(); struct HardExport { uint64_t token; VCC::Devices::HardDiskImage::Save saved; }; std::array,2> hardExports; std::array hardNames; std::array hardReadOnly{}; void clearHardDrive(unsigned drive) { ++mediaRevision; hardExports[drive].reset(); hardNames[drive].clear(); hardReadOnly[drive] = false; } std::shared_ptr diskDevice; std::shared_ptr ramDevice; std::array cartridgeKinds{2, 0, 0, 0, 0}; VCC::Devices::CartridgeBus::Slots cartridgeDevices; std::array cartridgeNames; void applyLayout(bool enabled, unsigned physical) { shell.stop(); for (unsigned i = 0; i < 5; ++i) if (cartridgeKinds[i] == 2) cartridgeDevices[i] = diskDevice; machine.cartridges().configure(cartridgeDevices, enabled, physical); } VCC::Devices::Fd502Device* floppy() { return diskDevice.get(); } VCC::Devices::Fd502Device& requireFloppy() { auto* disk = floppy(); if (!disk) throw std::logic_error("Choose a disk ROM to enable the floppy controller"); return *disk; } void pauseForDisks() { if (auto* disk = floppy(); disk && disk->snapshot().busy) throw std::logic_error("Disk operation in progress. Press Run to let it finish, or reset the machine before changing disks."); machine.pause(); } void clearDrive(unsigned drive) { ++mediaRevision; exports[drive].reset(); diskNames[drive].clear(); readOnly[drive] = false; } }; unsigned HardDriveIndex(NSInteger value) { if (value < 0 || value > 1) throw std::invalid_argument("Hard disk drive must be 0 or 1"); return static_cast(value); } unsigned DriveIndex(NSInteger value) { if (value < 0 || value > 3) throw std::invalid_argument("Floppy drive must be 0 through 3"); return static_cast(value); } std::vector OwnedBytes(NSData* data, NSUInteger limit) { if (data.length > limit) throw std::invalid_argument("Selected file is too large"); if (!data.length) return {}; const auto* begin = static_cast(data.bytes); return {begin, begin + data.length}; } std::vector CodeGuards(NSArray *addresses, NSArray *bytes) { if (addresses.count != bytes.count || bytes.count > 65536) throw std::invalid_argument("Code guard addresses and bytes must have matching bounded counts"); auto parsed = DebugAddresses(addresses, 65536); std::vector guards; std::size_t total = 0; for (NSUInteger i = 0; i < bytes.count; ++i) { if (bytes[i].length > 65536 - total) throw std::invalid_argument("Code guards exceed address space"); total += bytes[i].length; guards.push_back({parsed[i], OwnedBytes(bytes[i], 65536)}); } return guards; } std::vector BankedModules(NSArray *> *modules) { if (!modules || !modules.count || modules.count > 256) throw std::invalid_argument("Supply 1 to 256 banked modules"); std::vector result; for (NSDictionary *module in modules) { if (![module isKindOfClass:NSDictionary.class]) throw std::invalid_argument("Invalid banked module"); NSString *identifier = module[@"id"]; NSArray *pages = module[@"pages"], *addresses = module[@"addresses"], *bytes = module[@"bytes"]; if (![identifier isKindOfClass:NSString.class] || ![pages isKindOfClass:NSArray.class] || ![addresses isKindOfClass:NSArray.class] || ![bytes isKindOfClass:NSArray.class]) throw std::invalid_argument("Banked modules require id, pages, addresses and bytes"); for (id address in addresses) if (![address isKindOfClass:NSNumber.class]) throw std::invalid_argument("Invalid banked code address"); for (id data in bytes) if (![data isKindOfClass:NSData.class]) throw std::invalid_argument("Invalid banked instruction bytes"); VCC::Mac::DebugBankedModule parsed; parsed.identifier = identifier.UTF8String; parsed.guards = CodeGuards(addresses, bytes); if (id qualified = module[@"breakpoints"]) { if (![qualified isKindOfClass:NSArray.class]) throw std::invalid_argument("Module breakpoints must be an array"); for (id point in qualified) if (![point isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)point) == CFBooleanGetTypeID()) throw std::invalid_argument("Module breakpoints require logical integer addresses"); parsed.breakpointAddresses = DebugAddresses(qualified, 1024); } if (!pages.count || pages.count > 8) throw std::invalid_argument("Supply 1 to 8 page mappings per module"); for (NSDictionary *page in pages) { if (![page isKindOfClass:NSDictionary.class]) throw std::invalid_argument("Invalid banked page mapping"); NSNumber *logical = page[@"logicalPage"], *physical = page[@"physicalPage"]; if (![logical isKindOfClass:NSNumber.class] || ![physical isKindOfClass:NSNumber.class]) throw std::invalid_argument("Banked pages require logicalPage and physicalPage"); const double l = logical.doubleValue, p = physical.doubleValue; if (!std::isfinite(l) || !std::isfinite(p) || l < 0 || l > 7 || l != std::floor(l) || p < 0 || p > 1023 || p != std::floor(p)) throw std::invalid_argument("Invalid logical or physical RAM page"); parsed.pages.push_back({static_cast(l), static_cast(p)}); } result.push_back(std::move(parsed)); } return result; } VCC::Mac::Snapshot AssemblyIdentity(VCCMachineSnapshot *snapshot) { VCC::Mac::Snapshot expected; expected.generation = snapshot.generation; expected.debuggerProgramRevision = snapshot.debuggerProgramRevision; expected.debuggerMappingFingerprint = snapshot.debuggerMappingFingerprint; expected.cpu.PC = snapshot.programCounter; expected.cycles = snapshot.cycles; return expected; } VCC::Devices::DiskImage LoadFloppyImage(NSData *data, NSString *name, bool protect) { using namespace VCC::Devices; auto image = DiskImage::load(OwnedBytes(data, DiskImage::maxBytes), protect); NSString *ext = name.pathExtension.lowercaseString; if (([ext isEqualToString:@"dmk"] && image.format() != DiskFormat::DMK) || ([ext isEqualToString:@"vdk"] && image.format() != DiskFormat::VDK)) throw std::invalid_argument("The disk contents do not match the selected image format"); return image; } VCCMachineSnapshot *Capture(Worker& worker) { const auto value = worker.machine.snapshot(); auto result = [VCCMachineSnapshot new]; result.diskEditorLocked = worker.diskEdit.has_value(); auto joystickInputs = [NSMutableArray arrayWithCapacity:2]; for (const auto& port : value.joysticks) { auto input = [VCCJoystickInputSnapshot new]; input.x = port.x; input.y = port.y; input.buttons = port.buttons; input.mode = port.mode; [joystickInputs addObject:input]; } result.joystickInputs = joystickInputs; result.keyboardInputHeld = value.keyboardHeld; switch (value.state) { case VCC::Mac::RunState::Empty: result.state = VCCMachineStateEmpty; break; case VCC::Mac::RunState::Paused: result.state = VCCMachineStatePaused; break; case VCC::Mac::RunState::Running: result.state = VCCMachineStateRunning; break; } result.pasteRemaining = worker.machine.pasteRemaining(); const auto& printer = worker.machine.printer(); result.printerEnabled = printer.enabled(); result.printerRevision = printer.revision(); result.printerDroppedBytes = printer.droppedBytes(); result.printerByteCount = printer.bytes().size(); result.use6309 = value.configuration.processor == VCC::Mac::Processor::HD6309; result.ramConfiguration = value.configuration.ram; result.cpuOverclock = value.configuration.overclock; result.frameInterval = value.configuration.frameInterval; result.fastForward = worker.fastForward; result.presentedFrame = value.frame ? value.frame->number : 0; result.videoOutput = static_cast(value.videoOutput); result.audioEnabled = worker.audioEnabled; result.driveWireEnabled = worker.machine.driveWireEnabled(); if (worker.shellGeneration != value.generation) { worker.shell.stop(); worker.shellGeneration = value.generation; } result.macShellStatus = [NSString stringWithUTF8String:worker.shell.status().c_str()]; result.macShellRequestID = worker.shell.requestID(); result.audioConsumed = worker.audio.buffer().consumed.load(); result.audioSubmitted = worker.audio.buffer().submitted.load(); result.audioSignalSamples = worker.audio.buffer().signalSamples.load(); result.audioBuffered = worker.audio.buffer().size(); result.audioStarts = worker.audio.starts(); result.audioMaximumRequest = worker.audio.buffer().maximumRequest.load(); result.audioMaximumRefillGapNanoseconds = worker.maximumAudioGap; result.audioUnderruns = worker.audio.buffer().underruns.load(); result.audioOverruns = worker.audio.buffer().overruns.load(); const auto tape = worker.machine.cassette().snapshot(); result.tapeMounted=tape.mounted; result.tapeMotor=tape.motor; result.tapeDirty=tape.dirty; result.tapeFast=tape.fast; result.tapeWAV=tape.format==VCC::Mac::TapeFormat::WAV; result.tapeMode=static_cast(tape.mode); result.tapePosition=tape.position; result.tapeLength=tape.length; result.tapeReadEvents = tape.readEvents; result.tapeWriteEvents = tape.writeEvents; auto& bus = worker.machine.cartridges(); result.multiPakEnabled = bus.multiPak(); result.physicalSlot = bus.physicalSlot(); result.romSlot = bus.romSlot(); result.ioSlot = bus.ioSlot(); result.sdcDriveNames = @[@"", @""]; result.sdcDirectory = @""; result.sdcReadOnly = YES; auto names = [NSMutableArray arrayWithCapacity:5]; for (unsigned i = 0; i < 5; ++i) { [names addObject:bus.at(i) ? (worker.cartridgeKinds[i] == 2 ? @"Floppy controller" : worker.cartridgeKinds[i] == 3 ? @"Virtual hard disk" : worker.cartridgeKinds[i] == 4 ? @"RAM disk (512 KB)" : worker.cartridgeKinds[i] == 5 ? @"Orchestra-90" : worker.cartridgeKinds[i] == 6 ? @"Speech/Sound Cartridge" : worker.cartridgeKinds[i] == 7 ? @"CoCo SDC" : [NSString stringWithUTF8String:worker.cartridgeNames[i].c_str()]) : @""]; if (auto* sdc = dynamic_cast(bus.at(i)); sdc && (bus.multiPak() ? i > 0 : i == 0)) { const auto status = sdc->snapshot(); result.sdcDriveNames = @[[NSString stringWithUTF8String:status.drives[0].name.c_str()], [NSString stringWithUTF8String:status.drives[1].name.c_str()]]; result.sdcDirectory = [NSString stringWithUTF8String:status.currentDirectory.c_str()]; result.sdcReadOnly = status.writeProtected; result.sdcReadCount = status.drives[0].reads + status.drives[1].reads; result.sdcWriteCount = status.drives[0].writes + status.drives[1].writes; if (!status.error.empty()) result.sdcError = [NSString stringWithUTF8String:status.error.c_str()]; } if (bus.at(i) == worker.hardDevice.get() && (bus.multiPak() ? i > 0 : i == 0)) result.hardDiskConnected = YES; if (bus.at(i) && bus.at(i) == worker.floppy() && (bus.multiPak() ? i > 0 : i == 0)) result.diskConnected = YES; } result.cartridgeNames = names; auto kinds = [NSMutableArray arrayWithCapacity:5]; for (unsigned i = 0; i < 5; ++i) [kinds addObject:@(worker.cartridgeKinds[i])]; result.cartridgeKinds = kinds; result.diskROMName = [NSString stringWithUTF8String:worker.diskROMName.c_str()]; result.diskSelectedDrive = -1; auto* floppy = worker.floppy(); result.diskEnabled = floppy != nullptr; if (floppy) { const auto disk = floppy->snapshot(); result.diskBusy = disk.busy; result.diskMotor = disk.motor; result.diskSelectedDrive = disk.drive; result.diskTrack = disk.head; result.diskSector = disk.sector; result.diskSide = disk.side; } auto drives = [NSMutableArray arrayWithCapacity:4]; for (unsigned i = 0; i < 4; ++i) { auto disk = [VCCDiskSnapshot new]; disk.name = [NSString stringWithUTF8String:worker.diskNames[i].c_str()]; disk.sourceReadOnly = worker.readOnly[i]; disk.readEvents = floppy ? floppy->readEvents(i) : 0; disk.writeEvents = floppy ? floppy->writeEvents(i) : 0; if (const auto* image = floppy ? floppy->image(i) : nullptr) { disk.mounted = YES; disk.dirty = image->dirty(); disk.writeProtected = image->writeProtected(); switch (image->format()) { case VCC::Devices::DiskFormat::DMK: disk.floppyExtension = @"dmk"; break; case VCC::Devices::DiskFormat::VDK: disk.floppyExtension = @"vdk"; break; default: { NSString *ext = disk.name.pathExtension.lowercaseString; disk.floppyExtension = [@[@"dsk", @"os9", @"jvc"] containsObject:ext] ? ext : @"dsk"; } } disk.formatWriteProtected = image->formatWriteProtected(); disk.tracks = image->geometry().tracks; disk.sides = image->geometry().sides; disk.byteCount = image->bytes().size(); } [drives addObject:disk]; } result.disks = drives; auto hardDrives = [NSMutableArray arrayWithCapacity:2]; for (unsigned i = 0; i < 2; ++i) { auto disk = [VCCDiskSnapshot new]; disk.name = [NSString stringWithUTF8String:worker.hardNames[i].c_str()]; disk.sourceReadOnly = worker.hardReadOnly[i]; disk.readEvents = worker.hardDevice->readEvents(i); disk.writeEvents = worker.hardDevice->writeEvents(i); if (auto* image = worker.hardDevice->image(i)) { disk.mounted = YES; disk.dirty = image->dirty(); disk.writeProtected = image->writeProtected(); disk.byteCount = image->bytes().size(); } [hardDrives addObject:disk]; } result.hardDisks = hardDrives; result.hardSelectedDrive = worker.hardDevice->selectedDrive(); result.hardSector = worker.hardDevice->selectedSector(); result.hardStatus = worker.hardDevice->result(); result.hardClockEnabled = worker.hardDevice->isClockEnabled(); result.hardClockReadOnly = worker.hardDevice->isClockReadOnly(); result.hardFlushRequests = worker.hardDevice->flushRequests(); if (worker.closed) result.state = VCCMachineStateClosed; result.generation = value.generation; result.frames = value.frames; result.debuggerProgramRevision = value.debuggerProgramRevision; result.debuggerMappingFingerprint = value.debuggerMappingFingerprint; result.debuggerDevelopmentAttached = value.debuggerDevelopmentAttached; result.debuggerBankedDevelopment = value.debuggerBankedDevelopment; result.debuggerAssemblyAttached = value.debuggerAssemblyAttached; result.assistantMediaRevision = worker.mediaRevision; result.assistantCompiledReturned = worker.machine.sharedCompiledCallReturned(); result.debuggerSourceStepping = value.debuggerSourceStepping; result.basicDebugAttached = value.basicDebugAttached; result.basicStoppedLine = value.basicStoppedLine; result.basicSourceOffset = value.basicSourceOffset; result.basicSourceLength = value.basicSourceLength; result.basicStepping = value.basicStepping; result.basicCanStepOut = value.basicCanStepOut; result.basicErrorLine = value.basicErrorLine; result.basicErrorCode = [NSString stringWithUTF8String:value.basicErrorCode.c_str()]; result.basicDebugStatus = [NSString stringWithUTF8String:value.basicDebugStatus.c_str()]; result.cycles = value.cycles; result.programCounter = value.cpu.PC; if (value.frame != worker.capturedFrame) { worker.capturedPixels = value.frame ? [NSData dataWithBytes:value.frame->pixels.data() length:value.frame->pixels.size() * sizeof(std::uint32_t)] : nil; worker.capturedFrame = value.frame; ++worker.pixelRevision; } result.pixelRevision = worker.pixelRevision; result.pixels = worker.capturedPixels; const auto area = value.frame ? value.frame->activeArea : VCC::VideoRect{0, 0, 640, 480}; result.activeVideoRect = CGRectMake(area.x, area.y, area.width, area.height); if (!worker.error.empty()) result.errorMessage = [NSString stringWithUTF8String:worker.error.c_str()]; return result; } void CheckAssistantGuestDevices(VCCMachineSnapshot *current) { NSString *reason = current.assistantDeviceBlockers.firstObject; if (reason) throw std::logic_error(reason.UTF8String); } void CheckCompiledRun(Worker& worker, VCCCompiledRunLease *lease, VCCMachineSnapshot *expected, bool assembly, bool finalScreen = false) { if (!lease.valid) throw std::logic_error("stale_run"); auto current = Capture(worker); if (!worker.assistantProgram || *worker.assistantProgram != std::make_pair(current.generation, current.debuggerProgramRevision) || current.generation != expected.generation || current.debuggerProgramRevision != expected.debuggerProgramRevision || current.debuggerMappingFingerprint != expected.debuggerMappingFingerprint || current.use6309 != expected.use6309 || !current.debuggerDevelopmentAttached || bool(current.debuggerAssemblyAttached) != assembly || (current.state != VCCMachineStateRunning && current.state != VCCMachineStatePaused)) throw std::logic_error("stale_run"); CheckAssistantGuestDevices(current); if (expected.assistantMediaRevision != current.assistantMediaRevision) throw std::logic_error("media_changed"); if (finalScreen) { if (!worker.machine.sharedCompiledCallReturned()) throw std::logic_error("run_not_finished"); return; } if (!worker.machine.sharedCompiledCallActive()) throw std::logic_error(worker.machine.sharedCompiledCallReturned() ? "run_finished" : "unverified_program_entry"); } void AdvanceWorker(Worker& worker) { if (worker.compiledKeyLease) { if (worker.machine.pasteRemaining()) { try { CheckCompiledRun(worker, worker.compiledKeyLease, worker.compiledKeyExpected, worker.compiledKeyAssembly); } catch (const std::exception&) { worker.machine.cancelPaste(); } } if (!worker.machine.pasteRemaining()) { worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; } } worker.machine.advance(); } // Called inside the emulator queue before every assistant load, observation or key. void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSString *source, const char *sourceChanged = "The program in BASIC memory changed. Review it before continuing.") { auto current = Capture(worker); if (current.generation != expected.generation || current.debuggerProgramRevision != expected.debuggerProgramRevision) throw std::logic_error("The CoCo or its loaded program changed. Start a new reviewed run."); if (current.assistantMediaRevision != expected.assistantMediaRevision) throw std::logic_error("The mounted media changed. Start a new reviewed run."); if (current.state != VCCMachineStateRunning && current.state != VCCMachineStatePaused) throw std::logic_error("Start a supported CoCo BASIC system before running."); CheckAssistantGuestDevices(current); if (worker.machine.basicReadSource() != [source UTF8String]) throw std::logic_error(sourceChanged); } } @implementation VCCMachineController { dispatch_queue_t _queue; dispatch_source_t _timer; std::shared_ptr _worker; } - (instancetype)init { if ((self = [super init])) { _worker = std::make_shared(); // Audio production has a short deadline even when the window is inactive. // Keep it off the main thread, with interactive scheduling priority. auto attributes = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0); _queue = dispatch_queue_create("com.brianholman.vccplus.mac.machine", attributes); _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue); // Refill on the owner queue; the real-time callback only consumes samples. dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 0), 2*NSEC_PER_MSEC, NSEC_PER_MSEC/2); auto worker = _worker; dispatch_source_set_event_handler(_timer, ^{ if (worker->closed) return; try { if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) { if (worker->audio.running()) worker->audio.stop(); worker->pacer.reset(); worker->audioProgress.reset(); return; } if (worker->fastForward) { // Yield after at most four frames or eight milliseconds so // input, pause, and automatic media saves keep getting turns. const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(8); for (unsigned i = 0; i < 4; ++i) { AdvanceWorker(*worker); worker->machine.takeAudio(); if (std::chrono::steady_clock::now() >= deadline) break; } } else if (worker->audioEnabled) { const auto tick = std::chrono::steady_clock::now(); if (worker->audio.running() && worker->previousAudioTick.time_since_epoch().count()) worker->maximumAudioGap = std::max(worker->maximumAudioGap, uint64_t(std::chrono::duration_cast(tick - worker->previousAudioTick).count())); worker->previousAudioTick = tick; if(worker->audio.needsRestart()) { worker->audio.stop(); worker->audioProgress.reset(); } // Roughly 100 ms ahead, at most four frames per queue turn. // The physical audio clock paces production; guest clocks stay fixed. for(unsigned i=0;i<4 && worker->audio.buffer().size()machine.takeAudio(); worker->audio.buffer().write(samples.data(), samples.size()); if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) break; } if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) { worker->audio.stop(); worker->pacer.reset(); worker->audioProgress.reset(); return; } const bool starting = !worker->audio.running(); if (!starting || worker->audio.buffer().size() >= VCC::Mac::audioTargetSamples) { worker->audio.start(); // Graph creation precedes consumption; start both timing // measurements only after the output graph is running. if (starting) { worker->previousAudioTick = std::chrono::steady_clock::now(); worker->audioProgress.reset(); } } if (worker->audioProgress.stalled(std::chrono::steady_clock::now(), worker->audio.buffer().consumed.load())) throw std::runtime_error("Audio output stopped consuming samples. Emulation continues without sound; turn Sound on to retry."); } else { if (worker->pacer.ready(std::chrono::steady_clock::now())) { AdvanceWorker(*worker); worker->machine.takeAudio(); } } } catch (const std::exception& error) { worker->error=error.what(); worker->audio.stop(); worker->audioEnabled=false; worker->pacer.reset(); worker->audioProgress.reset(); } }); dispatch_resume(_timer); } return self; } - (void)perform:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { [self performAllowingDiskEditor:NO operation:operation completion:completion]; } - (void)inspect:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { [self performAllowingDiskEditor:YES operation:operation completion:completion]; } - (void)performAllowingDiskEditor:(BOOL)allow operation:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { auto worker = _worker; dispatch_async(_queue, ^{ try { if (!allow) worker->requireNoDiskEditor(); operation(*worker); } catch (const std::exception& error) { worker->error = error.what(); } VCCMachineSnapshot *snapshot = Capture(*worker); dispatch_async(dispatch_get_main_queue(), ^{ completion(snapshot); }); }); } - (void)command:(void (^)(Worker&))operation completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); operation(worker); } completion:completion]; } - (void)applyProfile:(VCCMachineProfile*)profile completion:(void (^)(BOOL, VCCMachineSnapshot*))completion { VCCMachineProfile* p = [profile copy]; __block BOOL applied = NO; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); if (p.ram < 0 || p.ram > 3 || p.overclock < 1 || p.overclock > 16 || p.frameInterval < 1 || p.frameInterval > 6 || p.videoOutput < 0 || p.videoOutput > 2 || p.physicalSlot < 1 || p.physicalSlot > 4 || !std::isfinite(p.volume) || p.volume < 0 || p.volume > 1 || p.kinds.count != 5 || p.cartridgeROMs.count != 5 || p.cartridgeNames.count != 5 || p.sdcFolders.count != 5 || p.sdcReadOnly.count != 5 || p.images.count != 6 || p.imageNames.count != 6 || p.readOnly.count != 6 || p.protectedImages.count != 6) throw std::invalid_argument("Invalid profile configuration"); auto systemROM = OwnedBytes(p.systemROM, 32768); if (p.systemROM && systemROM.size() != 32768) throw std::invalid_argument("A 32 KiB system ROM is required"); // Build disconnected replacements. Parsing failures leave the current // CPU, media, dirty flags and save acknowledgement tokens untouched. std::shared_ptr floppy; if (p.diskROM) floppy = std::make_shared(OwnedBytes(p.diskROM, 16384)); auto hard = std::make_shared(); hard->configureClock(p.clockEnabled, p.clockReadOnly); for (unsigned i = 0; i < 6; ++i) { if (![p.images[i] length]) continue; const bool protect = [p.readOnly[i] boolValue] || [p.protectedImages[i] boolValue]; if (i < 4) { if (!floppy) throw std::invalid_argument("A floppy image requires a floppy ROM"); floppy->mount(i, LoadFloppyImage(p.images[i], p.imageNames[i], protect)); } else hard->mount(i - 4, VCC::Devices::HardDiskImage(OwnedBytes(p.images[i], VCC::Devices::HardDiskImage::maxBytes), protect)); } VCC::Mac::CassetteDeck tape; if (p.cassette) tape.mount(OwnedBytes(p.cassette, VCC::Mac::CassetteDeck::maxBytes), p.cassetteWAV ? VCC::Mac::TapeFormat::WAV : VCC::Mac::TapeFormat::CAS); tape.setFast(p.fastCassette); VCC::Devices::CartridgeBus::Slots slots; std::array kinds; std::array names; unsigned floppyCount = 0, hardCount = 0, ramCount = 0, orchestraCount = 0, speechCount = 0, sdcCount = 0; std::shared_ptr ram; for (unsigned i = 0; i < 5; ++i) { kinds[i] = [p.kinds[i] intValue]; names[i] = [p.cartridgeNames[i] UTF8String]; switch (kinds[i]) { case 0: break; case 1: slots[i] = std::make_shared(OwnedBytes(p.cartridgeROMs[i], 262144)); break; case 2: slots[i] = floppy; if (i) ++floppyCount; break; case 3: slots[i] = hard; if (i) ++hardCount; break; case 4: if (!ram) ram = std::make_shared(); slots[i] = ram; if (i) ++ramCount; break; case 7: if ([p.cartridgeROMs[i] length]) slots[i] = std::make_shared( OwnedBytes(p.cartridgeROMs[i], 16384), [p.sdcFolders[i] UTF8String], [p.sdcReadOnly[i] boolValue]); if (i) ++sdcCount; break; case 6: slots[i] = std::make_shared(OwnedBytes(p.cartridgeROMs[i], 6144)); if (i) ++speechCount; break; case 5: slots[i] = std::make_shared(OwnedBytes(p.cartridgeROMs[i], 8192)); if (i) ++orchestraCount; break; default: throw std::invalid_argument("Unknown profile cartridge device"); } } if (floppyCount > 1 || hardCount > 1 || ramCount > 1 || orchestraCount > 1 || speechCount > 1 || sdcCount > 1) throw std::invalid_argument("Duplicate Multi-Pak devices"); auto* oldFloppy = worker.floppy(); if (oldFloppy && oldFloppy->snapshot().busy) throw std::logic_error("Finish the floppy operation before loading a profile"); for (unsigned i = 0; i < 4; ++i) if (oldFloppy && oldFloppy->image(i) && oldFloppy->image(i)->dirty()) throw std::logic_error("Save or discard modified floppy images before loading a profile"); for (unsigned i = 0; i < 2; ++i) if (worker.hardDevice->image(i) && worker.hardDevice->image(i)->dirty()) throw std::logic_error("Save or discard modified hard disks before loading a profile"); const auto oldTape = worker.machine.cassette().snapshot(); if (oldTape.dirty || oldTape.mode == VCC::Mac::TapeMode::Recording) throw std::logic_error("Stop and export or discard the cassette recording before loading a profile"); worker.error.clear(); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); worker.previousAudioTick = {}; worker.machine.shutdown(); worker.diskDevice = std::move(floppy); worker.hardDevice = std::move(hard); worker.ramDevice = std::move(ram); worker.cartridgeDevices = std::move(slots); worker.cartridgeKinds = kinds; worker.cartridgeNames = std::move(names); worker.diskROMName = p.diskROMName.UTF8String; for (unsigned i = 0; i < 4; ++i) { worker.clearDrive(i); worker.diskNames[i] = [p.imageNames[i] UTF8String]; worker.readOnly[i] = [p.readOnly[i] boolValue]; } for (unsigned i = 0; i < 2; ++i) { worker.clearHardDrive(i); worker.hardNames[i] = [p.imageNames[i+4] UTF8String]; worker.hardReadOnly[i] = [p.readOnly[i+4] boolValue]; } worker.machine.cassette() = std::move(tape); worker.applyLayout(p.multiPak, unsigned(p.physicalSlot)); VCC::Mac::MachineConfiguration config; config.processor = p.use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809; config.ram = unsigned(p.ram); config.overclock = unsigned(p.overclock); config.frameInterval = unsigned(p.frameInterval); worker.machine.configure(config); worker.machine.setVideoOutput(static_cast(p.videoOutput)); worker.fastForward = p.fastForward; worker.audioEnabled = p.sound; worker.audio.buffer().gain.store(p.volume); applied = YES; if (p.systemROM) worker.machine.load(systemROM, config.processor); } completion:^(VCCMachineSnapshot* snapshot) { completion(applied, snapshot); }]; } - (void)configureMachineWith6309:(BOOL)use6309 ram:(NSInteger)ram overclock:(NSInteger)overclock frameInterval:(NSInteger)interval fastForward:(BOOL)fastForward completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); // Reject before touching audio, RAM, preferences, or media. if (ram < 0 || ram > 3 || overclock < 1 || overclock > 16 || interval < 1 || interval > 6) throw std::invalid_argument("Unsupported machine settings"); VCC::Mac::MachineConfiguration value; value.processor = use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809; value.ram = unsigned(ram); value.overclock = unsigned(overclock); value.frameInterval = unsigned(interval); const auto previous = worker.machine.snapshot().configuration; const bool restart = previous.processor != value.processor || previous.ram != value.ram; if (restart) { if (auto* disk = worker.floppy(); disk && disk->snapshot().busy) throw std::logic_error("Wait for the disk operation to finish before changing CPU or memory."); if (worker.machine.cassette().snapshot().mode == VCC::Mac::TapeMode::Recording) throw std::logic_error("Stop the cassette recording before changing CPU or memory."); } if (restart || worker.fastForward != bool(fastForward)) { worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); worker.previousAudioTick = {}; } worker.machine.configure(value); worker.fastForward = fastForward; worker.error.clear(); } completion:completion]; } - (void)setVideoOutput:(NSInteger)output completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); if (output < 0 || output > 2) throw std::invalid_argument("Unsupported video output"); worker.machine.setVideoOutput(static_cast(output)); worker.error.clear(); } completion:completion]; } - (void)loadDiagnosticWithCompletion:(VCCMachineCompletion)completion { [self loadDiagnosticWith6309:NO completion:completion]; } - (void)loadDiagnosticWith6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.loadDiagnostic(use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809); } completion:completion]; } - (void)loadROM:(NSData *)rom use6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion { NSData *owned = [rom copy]; [self command:^(Worker& worker) { if (owned.length != 0x8000) throw std::invalid_argument("A 32 KiB CoCo 3 ROM image is required"); const auto *begin = static_cast(owned.bytes); worker.machine.load({begin, begin + owned.length}, use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809); } completion:completion]; } - (void)setJoystick:(NSUInteger)port x:(NSUInteger)x y:(NSUInteger)y buttons:(NSUInteger)buttons mode:(NSUInteger)mode { auto worker = _worker; dispatch_async(_queue, ^{ if (!worker->closed && !worker->diskEdit) worker->machine.setJoystick((unsigned)port, (unsigned)MIN(x, 16383), (unsigned)MIN(y, 16383), (unsigned)buttons, (unsigned)mode); }); } - (void)pasteChords:(NSArray *)chords completion:(VCCMachineCompletion)completion { NSArray *owned = [chords copy]; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); if (owned.count > 65536) throw std::invalid_argument("Paste is too large"); std::vector keys; for (NSNumber* value in owned) keys.push_back(value.unsignedLongLongValue); worker.machine.paste(keys); worker.assistantPasteRun.clear(); worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; } completion:completion]; } - (void)assistantPaste:(NSArray *)chords runID:(NSString *)runID direct:(BOOL)direct expected:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { worker.error.clear(); CheckAssistantMachine(worker, expected, source); if (worker.machine.pasteRemaining()) throw std::logic_error("Guest keyboard input is pending."); if (worker.machine.snapshot().state != VCC::Mac::RunState::Running || chords.count < 1 || chords.count > 8 || (direct ? !worker.machine.basicAtDirectPrompt() : !worker.machine.basicExecutingStoredSource())) throw std::logic_error("The guest is not at the expected BASIC input state."); std::vector keys; for (NSNumber *value in chords) keys.push_back(value.unsignedLongLongValue); worker.machine.paste(keys); worker.assistantPasteRun = runID.UTF8String; worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; } completion:completion]; } - (void)cancelAssistantPaste:(NSString *)runID { auto worker = _worker; dispatch_async(_queue, ^{ if (worker->assistantPasteRun == runID.UTF8String) { worker->machine.cancelPaste(); worker->assistantPasteRun.clear(); } }); } - (void)compiledGuest:(VCCCompiledRunLease *)lease runID:(NSString *)runID expected:(VCCMachineSnapshot *)expected assembly:(BOOL)assembly key:(NSNumber *)key readScreen:(BOOL)readScreen finalScreen:(BOOL)finalScreen completion:(void (^)(NSString *, VCCMachineSnapshot *))completion { __block NSString *text = nil; [self perform:^(Worker& worker) { worker.error.clear(); CheckCompiledRun(worker, lease, expected, assembly, finalScreen); if (finalScreen) { if (const auto *saved = worker.machine.sharedCompiledReturnScreen()) text = [NSString stringWithUTF8String:saved->c_str()]; return; } if (readScreen) text = [NSString stringWithUTF8String:worker.machine.copyScreenText().c_str()]; if (key) { if (worker.machine.snapshot().state != VCC::Mac::RunState::Running) throw std::logic_error("run_paused"); if (worker.machine.pasteRemaining()) throw std::logic_error("input_busy"); worker.machine.pasteSharedCompiledKey(key.unsignedLongLongValue); worker.assistantPasteRun = runID.UTF8String; worker.compiledKeyLease = lease; worker.compiledKeyExpected = expected; worker.compiledKeyAssembly = assembly; } } completion:^(VCCMachineSnapshot *snapshot) { completion(text, snapshot); }]; } - (void)checkReviewedBASIC:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { CheckAssistantMachine(worker, expected, source); } completion:completion]; } - (void)assistantScreen:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(void (^)(NSDictionary*, VCCMachineSnapshot*))completion { __block NSDictionary *observation = nil; [self perform:^(Worker& worker) { worker.error.clear(); CheckAssistantMachine(worker, expected, source); auto text = worker.machine.copyScreenText(); auto page = worker.machine.debuggerGraphicsPreview(true, true, 0, VCC::Mac::DebugGraphicsMode::SG4, false); auto colors = [NSMutableArray array]; if (page.text && page.bytesPerCell == 2 && page.width && page.linesPerRow) { // Sample the middle of an actual space between words in each text row. // Its glyph is blank, so the renderer's pixel gives the background for // this cell under the active RGB/composite signal and the live palette. unsigned row = 0, previous = ~0u; for (unsigned y = 0; y < page.height; ++y) { unsigned offset = page.rowByteOffsets[y]; if (offset == previous) continue; previous = offset; unsigned columns = page.bytesPerRow / page.bytesPerCell; bool word = false; for (unsigned c = 0; c + 1 < columns; ++c) { auto cell = offset + c * page.bytesPerCell; if (page.bytes[cell] != ' ') { word = true; continue; } if (!word || page.bytes[cell + page.bytesPerCell] == ' ') continue; unsigned px = (2*c+1) * page.width / (2*columns); unsigned py = std::min(y + page.linesPerRow/2, page.height-1); unsigned rgb = page.pixels[py*page.width + px] & 0xffffff; unsigned attribute = page.bytes[cell+1]; [colors addObject:@{@"row":@(row), @"column":@(c), @"rgb":@(rgb), @"attribute":@(attribute), @"palette_index":@(attribute & 7), @"palette_value":@(page.palette[attribute & 7])}]; break; } ++row; } } observation = @{@"text":[NSString stringWithUTF8String:text.c_str()], @"colors":colors, @"columns":@(page.bytesPerRow / page.bytesPerCell), @"direct_prompt":@(worker.machine.basicAtDirectPrompt())}; } completion:^(VCCMachineSnapshot *snapshot) { completion(observation, snapshot); }]; } - (void)cancelPasteWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { worker.machine.cancelPaste(); } completion:completion]; } - (void)copyScreenTextWithCompletion:(void (^)(NSString*, VCCMachineSnapshot*))completion { __block NSString* text = nil; [self inspect:^(Worker& worker) { worker.error.clear(); text = [NSString stringWithUTF8String:worker.machine.copyScreenText().c_str()]; } completion:^(VCCMachineSnapshot* snapshot) { completion(text, snapshot); }]; } - (void)inspectScreenTextWithCompletion:(void (^)(NSString*, VCCMachineSnapshot*))completion { __block NSString* text = nil; [self inspect:^(Worker& worker) { // Unlike Copy, this is a probe: boot and games may legitimately have no // readable hardware text. Preserve any existing machine error as well. try { text = [NSString stringWithUTF8String:worker.machine.copyScreenText().c_str()]; } catch (const std::logic_error&) { } } completion:^(VCCMachineSnapshot* snapshot) { completion(text, snapshot); }]; } - (void)setPrinterEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); worker.machine.printer().setEnabled(enabled); } completion:completion]; } - (void)clearPrinterOutputWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); worker.machine.printer().clear(); } completion:completion]; } - (void)printerOutputWithCompletion:(void (^)(VCCPrinterOutput *, VCCMachineSnapshot *))completion { auto output = [VCCPrinterOutput new]; [self inspect:^(Worker& worker) { const auto& printer = worker.machine.printer(); output.bytes = [NSData dataWithBytes:printer.bytes().data() length:printer.bytes().size()]; output.revision = printer.revision(); output.droppedBytes = printer.droppedBytes(); output.enabled = printer.enabled(); output.capacity = VCC::Mac::PrinterCapture::capacity; } completion:^(VCCMachineSnapshot* snapshot) { completion(output, snapshot); }]; } - (void)setKeyboardMask:(uint64_t)keys { auto worker = _worker; dispatch_async(_queue, ^{ if (!worker->closed && !worker->diskEdit) worker->machine.setKeyboard(keys); }); } - (void)launchAssembly:(NSData *)binary points:(NSArray *)points addresses:(NSArray *)addresses bytes:(NSArray *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping completion:(VCCMachineCompletion)completion { [self launchAssembly:binary points:points addresses:addresses bytes:bytes pauseAtEntry:pauseAtEntry requires6309:requires6309 generation:generation revision:revision mapping:mapping shared:NO completion:completion]; } - (void)launchAssembly:(NSData *)binary points:(NSArray *)points addresses:(NSArray *)addresses bytes:(NSArray *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping shared:(BOOL)shared completion:(VCCMachineCompletion)completion { NSData *image = [binary copy]; NSArray *stops = [points copy], *locations = [addresses copy]; NSArray *instructions = [[NSArray alloc] initWithArray:bytes copyItems:YES]; [self command:^(Worker& worker) { if (shared) CheckAssistantGuestDevices(Capture(worker)); worker.machine.launchAssembly(OwnedBytes(image, VCC::Mac::BinaryImage::maxBytes), DebugAddresses(stops, 1024), CodeGuards(locations, instructions), pauseAtEntry, requires6309, generation, revision, mapping); if (shared) { const auto active = worker.machine.snapshot(); worker.machine.armSharedCompiledCall(); worker.assistantProgram = std::make_pair(active.generation, active.debuggerProgramRevision); } } completion:completion]; } - (void)pauseAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.pauseAssembly(AssemblyIdentity(expected)); } completion:completion]; } - (void)controlAssembly:(BOOL)step expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.controlAssembly(step, AssemblyIdentity(expected)); } completion:completion]; } - (void)updateAssembly:(NSArray *)points expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { NSArray *stops = [points copy]; [self command:^(Worker& worker) { worker.machine.updateAssembly(DebugAddresses(stops, 1024), AssemblyIdentity(expected)); } completion:completion]; } - (void)clearAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.clearAssembly(AssemblyIdentity(expected)); } completion:completion]; } - (void)startReviewedC:(NSData *)binary disk:(NSData *)disk name:(NSString *)name stop:(uint16_t)stop expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { CheckAssistantMachine(worker, expected, @"", "occupied_basic_program"); auto current = Capture(worker); if (disk && (current.disks.count < 1 || current.disks[0].mounted)) throw std::logic_error("Eject the disk in FD0 before running the Hello Disk example."); if (current.basicDebugAttached || current.debuggerAssemblyAttached || (current.debuggerDevelopmentAttached && !worker.machine.sharedCompiledCallReturned()) || current.pasteRemaining) throw std::logic_error("Finish the active debugging or paste session before running this C build."); if (!worker.machine.basicAtDirectPrompt()) throw std::logic_error("Waiting for an empty Disk BASIC prompt."); auto program = OwnedBytes(binary, VCC::Mac::BinaryImage::maxBytes); if (disk) { auto image = LoadFloppyImage(disk, name, true); worker.requireFloppy().mount(0, std::move(image)); worker.clearDrive(0); worker.diskNames[0] = name.UTF8String; worker.readOnly[0] = true; } try { worker.machine.debuggerLoadBinary(program, stop); const auto active = worker.machine.snapshot(); worker.machine.armSharedCompiledCall(); worker.assistantProgram = std::make_pair(active.generation, active.debuggerProgramRevision); } catch (...) { if (disk) { worker.requireFloppy().eject(0, false); worker.clearDrive(0); } throw; } } completion:completion]; } - (void)continueReviewedC:(VCCMachineSnapshot *)expected name:(NSString *)name stop:(uint16_t)stop bytes:(NSData *)bytes completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { auto current = Capture(worker); const NSUInteger byteCount = bytes.length; CheckAssistantGuestDevices(current); if (current.generation != expected.generation || current.debuggerProgramRevision != expected.debuggerProgramRevision || current.debuggerMappingFingerprint != expected.debuggerMappingFingerprint || current.state != VCCMachineStatePaused || current.programCounter != stop || !current.debuggerDevelopmentAttached || current.debuggerAssemblyAttached || !byteCount || (name.length && (!current.disks.firstObject.writeProtected || ![current.disks.firstObject.name isEqualToString:name]))) throw std::logic_error("The source stop, running program, or mounted project disk changed."); if (byteCount > 65536u - stop) throw std::invalid_argument("Memory range is outside the selected address space"); auto actual = worker.machine.debuggerMemoryRange(stop, static_cast(byteCount), false); if (actual.bytes.size() != byteCount || memcmp(actual.bytes.data(), bytes.bytes, byteCount) || std::find(actual.available.begin(), actual.available.end(), 0) != actual.available.end()) throw std::logic_error("The instruction in guest memory differs from the linked source map."); if (name.length) { worker.machine.debuggerClearDevelopmentBreakpoints(); worker.machine.resume(); } else worker.machine.debuggerContinueFromEntry(stop); } completion:completion]; } - (void)ejectReviewedCDisk:(NSString *)name completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { if (worker.readOnly[0] && worker.diskNames[0] == name.UTF8String) { worker.requireFloppy().eject(0, false); worker.clearDrive(0); } } completion:completion]; } - (void)debuggerLoadBinary:(NSData *)binary breakpoint:(uint16_t)breakpoint completion:(VCCMachineCompletion)completion { NSData *owned = [binary copy]; [self command:^(Worker& worker) { worker.machine.debuggerLoadBinary(OwnedBytes(owned, VCC::Mac::BinaryImage::maxBytes), breakpoint); } completion:completion]; } - (void)debuggerLoadBinary:(NSData *)binary breakpoints:(NSArray *)breakpoints completion:(VCCMachineCompletion)completion { NSData *owned = [binary copy]; NSArray *points = [breakpoints copy]; [self command:^(Worker& worker) { worker.machine.debuggerLoadBinary(OwnedBytes(owned, VCC::Mac::BinaryImage::maxBytes), DebugAddresses(points, 1024)); } completion:completion]; } - (void)debuggerArmDevelopmentBreakpoints:(NSArray *)breakpoints guardAddresses:(NSArray *)guardAddresses guardBytes:(NSArray *)guardBytes completion:(VCCMachineCompletion)completion { NSArray *points = [breakpoints copy], *addresses = [guardAddresses copy]; NSArray *bytes = [[NSArray alloc] initWithArray:guardBytes copyItems:YES]; [self command:^(Worker& worker) { auto guards = CodeGuards(addresses, bytes); worker.machine.debuggerArmDevelopmentBreakpoints(DebugAddresses(points, 1024), guards); } completion:completion]; } - (void)debuggerArmBankedDevelopmentBreakpoints:(NSArray *)breakpoints modules:(NSArray *> *)modules completion:(VCCMachineCompletion)completion { NSArray *points = [breakpoints copy]; // Freeze the nested arrays and NSData before crossing onto the machine queue. NSArray *owned = CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (__bridge CFPropertyListRef)modules, kCFPropertyListImmutable)); [self command:^(Worker& worker) { worker.machine.debuggerArmBankedDevelopmentBreakpoints(DebugAddresses(points, 1024), BankedModules(owned)); } completion:completion]; } - (void)debuggerClearDevelopmentBreakpointsWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.debuggerClearDevelopmentBreakpoints(); } completion:completion]; } - (void)quickLoadBinary:(NSData *)binary completion:(VCCMachineCompletion)completion { NSData *owned = [binary copy]; [self command:^(Worker& worker) { worker.machine.quickLoad(OwnedBytes(owned, VCC::Mac::BinaryImage::maxBytes)); } completion:completion]; } - (void)requestNitros9BootWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.machine.requestNitros9Boot(); } completion:completion]; } - (void)resumeWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.resume(); } completion:completion]; } - (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress completion:(void (^)(VCCDebuggerSnapshot *))completion { [self debuggerSnapshotAtAddress:address followPC:followPC memoryAddress:memoryAddress physicalAddress:0 physicalMemory:NO completion:completion]; } - (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress physicalAddress:(uint32_t)physicalAddress physicalMemory:(BOOL)physicalMemory completion:(void (^)(VCCDebuggerSnapshot *))completion { auto result = [VCCDebuggerSnapshot new]; result.registers = @{}; result.instructions = @[]; result.breakpoints = @[]; result.disabledBreakpoints = @[]; result.memory = [NSData data]; result.memoryAvailable = [NSData data]; result.logicalMemory = [NSData data]; result.logicalMemoryAvailable = [NSData data]; result.memoryAddress = memoryAddress; result.stopReason = @"Load a machine to inspect it."; result.physicalMemory = [NSData data]; result.mmu = [VCCMMUSnapshot new]; result.mmu.task0 = @[]; result.mmu.task1 = @[]; result.mmu.effective = @[]; [self inspect:^(Worker& worker) { if (worker.closed) return; if (worker.machine.snapshot().state == VCC::Mac::RunState::Empty) return; // An inspector can outlive a profile/RAM-size change. Recover its // physical cursor on this queue using the current installed capacity. constexpr uint32_t capacities[] = {0x20000, 0x80000, 0x200000, 0x800000}; const auto capacity = capacities[worker.machine.snapshot().configuration.ram]; const auto physicalStart = physicalAddress < capacity ? physicalAddress : capacity - 256; const auto debug = worker.machine.debuggerSnapshot(0, 65536, physicalStart, physicalMemory ? 256 : 0); result.logicalMemory = [NSData dataWithBytes:debug.memory.data() length:debug.memory.size()]; result.logicalMemoryAvailable = [NSData dataWithBytes:debug.memoryAvailable.data() length:debug.memoryAvailable.size()]; const auto& mapping = debug.mmu; auto mmu = result.mmu; mmu.enabled = mapping.Enabled; mmu.activeTask = mapping.ActiveTask; mmu.ramVectors = mapping.RamVectors; mmu.romMap = mapping.RomMap; mmu.allRAM = mapping.AllRAM; mmu.prefix = mapping.Prefix; mmu.ramByteCount = mapping.RAMBytes; mmu.vectorRAMAddress = mapping.RAMVectorAddress; auto task0 = [NSMutableArray array], task1 = [NSMutableArray array]; auto effective = [NSMutableArray array]; for (unsigned i = 0; i < 8; ++i) { [task0 addObject:@(mapping.Task0[i])]; [task1 addObject:@(mapping.Task1[i])]; const auto& bank = mapping.Effective[i]; auto row = [VCCMemoryMapping new]; row.page = bank.Page; row.ramAddress = bank.RAMStart; row.source = static_cast(bank.Source); row.sourceAddress = bank.SourceStart; [effective addObject:row]; } mmu.task0 = task0; mmu.task1 = task1; mmu.effective = effective; result.physicalAddress = debug.physicalAddress; result.physicalMemory = [NSData dataWithBytes:debug.physicalMemory.data() length:debug.physicalMemory.size()]; const auto& cpu = debug.cpu; auto registers = [NSMutableDictionary dictionaryWithDictionary:@{ @"A": @(cpu.A), @"B": @(cpu.B), @"DP": @(cpu.DP), @"CC": @(cpu.CC), @"X": @(cpu.X), @"Y": @(cpu.Y), @"U": @(cpu.U), @"S": @(cpu.S), @"PC": @(cpu.PC)}]; const bool use6309 = worker.machine.snapshot().configuration.processor == VCC::Mac::Processor::HD6309; if (use6309) [registers addEntriesFromDictionary:@{@"E": @(cpu.E), @"F": @(cpu.F), @"V": @(cpu.V), @"MD": @(cpu.MD)}]; result.registers = registers; auto breakpoints = [NSMutableArray array]; for (auto pc : debug.breakpoints) [breakpoints addObject:@(pc)]; result.breakpoints = breakpoints; auto disabled = [NSMutableArray array]; for (auto point : debug.disabledBreakpoints) [disabled addObject:@(point)]; result.disabledBreakpoints = disabled; result.stopReason = [NSString stringWithUTF8String:debug.stopReason.c_str()]; auto instructions = [NSMutableArray array]; uint16_t cursor = followPC ? cpu.PC : address; for (unsigned row = 0; row < 48; ++row) { const auto line = VCC::Mac::Disassemble(debug.memory, cpu, use6309, cursor, 1).front(); auto item = [VCCDebugInstruction new]; item.address = line.address; bool available = true; for (std::size_t i = 0; i < line.bytes.size(); ++i) available &= debug.memoryAvailable[uint16_t(line.address + i)] != 0; item.bytes = available ? [NSData dataWithBytes:line.bytes.data() length:line.bytes.size()] : [NSData data]; item.mnemonic = available ? [NSString stringWithUTF8String:line.mnemonic.c_str()] : @"—"; item.operand = available ? [NSString stringWithUTF8String:line.operand.c_str()] : @"I/O unavailable"; item.valid = available && line.valid; [instructions addObject:item]; // Unknown I/O bytes cannot determine an instruction's length. // Advance one address so safe bytes on the far side remain visible. cursor = uint16_t(cursor + (available ? line.bytes.size() : 1)); } result.instructions = instructions; uint8_t bytes[256], available[256]; for (unsigned i = 0; i < 256; ++i) { const auto offset = uint16_t(memoryAddress + i); bytes[i] = debug.memory[offset]; available[i] = debug.memoryAvailable[offset]; } result.memory = [NSData dataWithBytes:bytes length:sizeof(bytes)]; result.memoryAvailable = [NSData dataWithBytes:available length:sizeof(available)]; } completion:^(VCCMachineSnapshot *snapshot) { result.machine = snapshot; completion(result); }]; } - (void)debuggerMemoryAtAddress:(uint32_t)address count:(uint32_t)count physical:(BOOL)physical logicalAddress:(uint16_t)logicalAddress os9:(BOOL)os9 decode:(BOOL)decode completion:(void (^)(VCCDebugMemoryCapture *))completion { auto result = [VCCDebugMemoryCapture new]; result.bytes = [NSData data]; result.available = [NSData data]; result.instructions = @[]; result.instructionOffsets = @[]; [self inspect:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); if (decode && count > 65536) throw std::invalid_argument("Decode at most 64 KiB at once"); const auto capture = worker.machine.debuggerMemoryRange(address, count, physical); result.address = capture.address; result.capacity = capture.capacity; result.bytes = [NSData dataWithBytes:capture.bytes.data() length:capture.bytes.size()]; result.available = [NSData dataWithBytes:capture.available.data() length:capture.available.size()]; if (decode) { const bool use6309 = worker.machine.snapshot().configuration.processor == VCC::Mac::Processor::HD6309; const auto decoded = VCC::Mac::DisassembleRange(capture.bytes, capture.available, use6309, physical ? logicalAddress : uint16_t(address), 128, os9); auto rows = [NSMutableArray array]; auto offsets = [NSMutableArray array]; unsigned offset = 0; for (const auto& line : decoded) { auto item = [VCCDebugInstruction new]; item.address = line.address; item.bytes = line.available ? [NSData dataWithBytes:line.bytes.data() length:line.bytes.size()] : [NSData data]; item.mnemonic = [NSString stringWithUTF8String:line.mnemonic.c_str()]; item.operand = [NSString stringWithUTF8String:line.operand.c_str()]; item.valid = line.valid; [rows addObject:item]; [offsets addObject:@(offset)]; offset += line.bytes.size(); } result.instructions = rows; result.instructionOffsets = offsets; } } completion:^(VCCMachineSnapshot *snapshot) { result.machine = snapshot; completion(result); }]; } - (void)debuggerGraphicsCurrentPage:(BOOL)currentPage address:(uint32_t)address physical:(BOOL)physical mode:(NSInteger)mode alternatePalette:(BOOL)alternatePalette completion:(void (^)(VCCDebugGraphicsCapture *))completion { auto result = [VCCDebugGraphicsCapture new]; [self inspect:^(Worker& worker) { // A preview failure belongs to this request. Preserve any existing machine error. try { if (worker.closed) throw std::logic_error("The machine controller has shut down"); if (!currentPage && (mode < 0 || mode > 9)) throw std::invalid_argument("Unknown graphics mode"); auto preview = worker.machine.debuggerGraphicsPreview(currentPage, physical, address, static_cast(currentPage ? 0 : mode), alternatePalette); [result takePreview:preview]; } catch (const std::exception& error) { result.errorMessage = [NSString stringWithUTF8String:error.what()]; } } completion:^(VCCMachineSnapshot *snapshot) { result.machine = snapshot; completion(result); }]; } - (void)debuggerStepWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.debuggerStep(); worker.machine.takeAudio(); } completion:completion]; } - (void)debuggerStepSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion { NSArray *ownedAddresses = [addresses copy], *ownedLocations = [locations copy]; NSArray *ownedBytes = [[NSArray alloc] initWithArray:bytes copyItems:YES]; [self command:^(Worker& worker) { if (mode < 0 || mode > 2 || ownedAddresses.count != ownedLocations.count || ownedAddresses.count != ownedBytes.count) throw std::invalid_argument("Invalid C step mode or source locations"); const auto parsed = DebugAddresses(ownedAddresses, 65536); std::vector instructions; for (NSUInteger i = 0; i < parsed.size(); ++i) { const double location = ownedLocations[i].doubleValue; if (!std::isfinite(location) || location < 0 || location > UINT32_MAX || location != std::floor(location)) throw std::invalid_argument("Invalid C source location identity"); instructions.push_back({parsed[i], uint32_t(location), OwnedBytes(ownedBytes[i], 8)}); } worker.machine.debuggerStepSource(static_cast(mode), instructions, generation, programRevision, mappingFingerprint, programCounter); } completion:completion]; } - (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion { NSArray *ownedAddresses = [addresses copy], *ownedLocations = [locations copy]; NSArray *ownedBytes = [[NSArray alloc] initWithArray:bytes copyItems:YES]; NSArray *identifiers = [[NSArray alloc] initWithArray:moduleIdentifiers copyItems:YES]; [self command:^(Worker& worker) { if (mode < 0 || mode > 2 || ownedAddresses.count != ownedLocations.count || ownedAddresses.count != ownedBytes.count || ownedAddresses.count != identifiers.count) throw std::invalid_argument("Invalid banked C step mode or source locations"); if (!worker.machine.snapshot().debuggerBankedDevelopment) throw std::invalid_argument("Arm verified banked modules before banked C stepping"); const auto parsed = DebugAddresses(ownedAddresses, 65536); std::vector instructions; for (NSUInteger i = 0; i < parsed.size(); ++i) { const double location = ownedLocations[i].doubleValue; if (!std::isfinite(location) || location < 0 || location > UINT32_MAX || location != std::floor(location)) throw std::invalid_argument("Invalid C source location identity"); instructions.push_back({parsed[i], uint32_t(location), OwnedBytes(ownedBytes[i], 8), identifiers[i].UTF8String}); } worker.machine.debuggerStepSource(static_cast(mode), instructions, generation, programRevision, mappingFingerprint, programCounter); } completion:completion]; } - (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); worker.machine.debuggerSetPC(address); } completion:completion]; } - (void)debuggerSetBreakpoints:(NSArray *)addresses completion:(VCCMachineCompletion)completion { NSArray *owned = [addresses copy]; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); if (owned.count > 1024) throw std::invalid_argument("Use at most 1,024 breakpoints"); std::vector points; for (NSNumber *value in owned) { const double n = value.doubleValue; if (!std::isfinite(n) || n < 0 || n > 65535 || n != std::floor(n)) throw std::invalid_argument("Breakpoint addresses must be hexadecimal 0000 through FFFF"); points.push_back(uint16_t(n)); } worker.machine.debuggerSetBreakpoints(std::move(points)); } completion:completion]; } - (void)debuggerConfigureBreakpoints:(NSArray *)enabled disabled:(NSArray *)disabled completion:(VCCMachineCompletion)completion { NSArray *on = [enabled copy], *off = [disabled copy]; [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.debuggerConfigureBreakpoints(DebugAddresses(on, 1024), DebugAddresses(off, 1024)); } completion:completion]; } - (void)debuggerStartTrace:(NSUInteger)maximum starts:(NSArray *)starts stops:(NSArray *)stops screen:(BOOL)screen scheduler:(BOOL)scheduler completion:(VCCMachineCompletion)completion { NSArray *begin = [starts copy], *end = [stops copy]; [self perform:^(Worker& worker) { worker.error.clear(); if (maximum > 100000) throw std::invalid_argument("Use at most 100,000 trace samples"); worker.machine.debuggerStartTrace(unsigned(maximum), DebugAddresses(begin, 32), DebugAddresses(end, 32), screen, scheduler); } completion:completion]; } - (void)debuggerStopTraceWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.debuggerStopTrace(); } completion:completion]; } - (void)debuggerClearTraceWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.debuggerClearTrace(); } completion:completion]; } - (void)debuggerTraceAtOffset:(NSUInteger)offset completion:(void (^)(VCCTraceSnapshot *, VCCMachineSnapshot *))completion { auto result = [VCCTraceSnapshot new]; result.records = @[]; result.status = @"No trace"; [self inspect:^(Worker& worker) { const auto trace = worker.machine.debuggerTrace(offset); result.identifier = trace.identifier; result.armed = trace.armed; result.capturing = trace.capturing; result.total = trace.total; result.offset = trace.offset; result.limit = trace.limit; result.status = [NSString stringWithUTF8String:trace.status.c_str()]; auto rows = [NSMutableArray array]; std::vector memory(65536); for (std::size_t i = 0; i < trace.records.size(); ++i) { const auto& row = trace.records[i]; auto item = [VCCTraceRecord new]; item.index = trace.offset + i; item.clock = row.clock; item.frame = row.frame; item.address = row.before.PC; item.cycles = row.cycles; item.kind = TraceKind(row.event); item.before = TraceRegisters(row.before, trace.use6309); item.after = TraceRegisters(row.after, trace.use6309); item.instruction = @""; item.detail = [NSString stringWithFormat:@"Line %u%@%s", row.line, row.detail.empty() ? @"" : @" · ", row.detail.c_str()]; if (row.event == VCC::TraceEvent::Instruction) { for (unsigned byte = 0; byte < row.availableBytes; ++byte) memory[uint16_t(row.before.PC + byte)] = row.bytes[byte]; const auto instruction = VCC::Mac::Disassemble(memory, row.before, trace.use6309, row.before.PC, 1).front(); item.instruction = instruction.bytes.size() <= row.availableBytes ? [NSString stringWithFormat:@"%s %s", instruction.mnemonic.c_str(), instruction.operand.c_str()] : @"I/O bytes unavailable"; } [rows addObject:item]; } result.records = rows; } completion:^(VCCMachineSnapshot* machine) { completion(result, machine); }]; } - (void)debuggerExportTraceFrom:(NSUInteger)first count:(NSUInteger)count completion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion { auto captured = std::make_shared(); __block BOOL valid = NO; [self inspect:^(Worker& worker) { worker.error.clear(); *captured = worker.machine.debuggerTraceForExport(first, count); valid = YES; } completion:^(VCCMachineSnapshot* initial) { if (!valid) { completion(nil, initial); return; } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ NSString* text = nil; NSString* failure = nil; try { const auto csv = VCC::Mac::FormatDebugTraceCSV(*captured); text = [NSString stringWithUTF8String:csv.c_str()]; } catch (const std::exception& error) { failure = [NSString stringWithUTF8String:error.what()]; } // Formatting never blocks the emulator queue. Deliver a current // machine snapshot, not the stale state from export's beginning. [self inspect:^(Worker& worker) { if (failure) worker.error = failure.UTF8String; } completion:^(VCCMachineSnapshot* current) { completion(text, current); }]; }); }]; } - (void)basicLoadSource:(NSString *)source run:(BOOL)run completion:(VCCMachineCompletion)completion { [self basicLoadSource:source run:run breakpoints:@[] completion:completion]; } - (void)basicLoadSource:(NSString *)source run:(BOOL)run breakpoints:(NSArray *)lines completion:(VCCMachineCompletion)completion { [self loadBASICSource:source run:run points:lines expected:nil existing:nil completion:completion]; } - (void)assistantLoadSource:(NSString *)source breakpoints:(NSArray *)lines expected:(VCCMachineSnapshot *)expected existing:(NSString *)existing completion:(VCCMachineCompletion)completion { [self loadBASICSource:source run:YES points:lines expected:expected existing:existing completion:completion]; } - (void)loadBASICSource:(NSString *)source run:(BOOL)run points:(NSArray *)lines expected:(VCCMachineSnapshot *)expected existing:(NSString *)existing completion:(VCCMachineCompletion)completion { __block NSString *installed = nil; NSString *owned = [source copy]; NSArray *points = [lines copy]; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); if (expected) CheckAssistantMachine(worker, expected, existing); NSData *utf8 = [owned dataUsingEncoding:NSUTF8StringEncoding]; if (!utf8 || utf8.length > 1024 * 1024) throw std::invalid_argument("BASIC source must be at most 1 MB of text"); const std::string text(static_cast(utf8.bytes), utf8.length); std::vector requested; if (points.count > 1024) throw std::invalid_argument("At most 1024 BASIC breakpoints are supported"); for (NSNumber *point in points) { if (point.integerValue < 0 || point.integerValue > 63999) throw std::invalid_argument("Invalid BASIC breakpoint number"); requested.push_back(point.unsignedShortValue); } worker.machine.basicLoadSource(text, run, requested); if (expected) { const auto active = worker.machine.snapshot(); worker.assistantProgram = std::make_pair(active.generation, active.debuggerProgramRevision); installed = [NSString stringWithUTF8String:worker.machine.basicReadSource().c_str()]; } // Reset host buffering only after a successful transfer. Rejected loads // preserve the running program and its audio state. worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); } completion:^(VCCMachineSnapshot *snapshot) { snapshot.assistantLoadedSource = installed; completion(snapshot); }]; } - (void)basicSetBreakpoints:(NSArray *)lines source:(NSString *)source completion:(VCCMachineCompletion)completion { NSArray *points = [lines copy]; NSString *owned = [source copy]; [self perform:^(Worker& worker) { worker.error.clear(); if (worker.closed) throw std::logic_error("The machine controller has shut down"); NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; if (!data || data.length > 1024 * 1024 || points.count > 1024) throw std::invalid_argument("BASIC source or breakpoint limit exceeded"); std::vector requested; for (NSNumber *point in points) { if (point.integerValue < 0 || point.integerValue > 63999) throw std::invalid_argument("Invalid BASIC breakpoint number"); requested.push_back(point.unsignedShortValue); } worker.machine.basicSetBreakpoints(std::string(static_cast(data.bytes), data.length), requested); } completion:completion]; } - (void)basicContinueSource:(NSString *)source completion:(VCCMachineCompletion)completion { NSString *owned = [source copy]; [self command:^(Worker& worker) { NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); worker.machine.basicContinue(std::string(static_cast(data.bytes), data.length)); } completion:completion]; } - (void)basicStepSource:(NSString *)source over:(BOOL)over completion:(VCCMachineCompletion)completion { NSString *owned = [source copy]; [self command:^(Worker& worker) { NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); worker.machine.basicStep(std::string(static_cast(data.bytes), data.length), over); } completion:completion]; } - (void)basicStepOutSource:(NSString *)source completion:(VCCMachineCompletion)completion { NSString *owned = [source copy]; [self command:^(Worker& worker) { NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); worker.machine.basicStepOut(std::string(static_cast(data.bytes), data.length)); } completion:completion]; } - (void)basicClearDebugWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { worker.error.clear(); worker.machine.basicClearDebug(); } completion:completion]; } - (void)basicExportSource:(NSString *)source name:(NSString *)name cassette:(BOOL)cassette completion:(void (^)(NSData *, VCCMachineSnapshot *))completion { NSString *owned = [source copy], *filename = [name copy]; __block NSData *result = nil; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); NSData *utf8 = [owned dataUsingEncoding:NSUTF8StringEncoding]; NSData *nameBytes = [filename dataUsingEncoding:NSUTF8StringEncoding]; if (!utf8 || utf8.length > 1024 * 1024 || !nameBytes || nameBytes.length > 8) throw std::invalid_argument("Use BASIC source up to 1 MB and a name of 1–8 letters or digits"); const std::string text(utf8.length ? static_cast(utf8.bytes) : "", utf8.length); const std::string stem(nameBytes.length ? static_cast(nameBytes.bytes) : "", nameBytes.length); const auto bytes = worker.machine.basicExportSource(text, stem, cassette ? VCC::Mac::BasicExportFormat::Cassette : VCC::Mac::BasicExportFormat::Disk); result = [NSData dataWithBytes:bytes.data() length:bytes.size()]; } completion:^(VCCMachineSnapshot *snapshot) { completion(result, snapshot); }]; } - (void)basicInspectSource:(NSString *)source completion:(void (^)(NSArray *> *, VCCMachineSnapshot *))completion { NSString *owned = [source copy]; __block NSArray *result = nil; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); NSData *data = [owned dataUsingEncoding:NSUTF8StringEncoding]; if (!data || data.length > 1024 * 1024) throw std::invalid_argument("BASIC source limit exceeded"); const auto variables = worker.machine.basicInspect(std::string(static_cast(data.bytes), data.length)); NSMutableArray *rows = [NSMutableArray array]; for (const auto& v : variables) { NSMutableArray *dimensions = [NSMutableArray array], *elements = [NSMutableArray array]; for (auto length : v.dimensions) [dimensions addObject:@(length)]; for (const auto& text : v.elements) [elements addObject:[NSString stringWithUTF8String:text.c_str()]]; [rows addObject:@{@"name": [NSString stringWithUTF8String:v.name.c_str()], @"kind": [NSString stringWithUTF8String:v.kind.c_str()], @"value": [NSString stringWithUTF8String:v.value.c_str()], @"address": @(v.address), @"dimensions": dimensions, @"elements": elements}]; } result = rows; } completion:^(VCCMachineSnapshot *snapshot) { completion(result, snapshot); }]; } - (void)basicReadSourceWithCompletion:(void (^)(NSString *, VCCMachineSnapshot *))completion { __block NSString *source = nil; [self inspect:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); const auto text = worker.machine.basicReadSource(); source = [[NSString alloc] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding]; if (!source) throw std::runtime_error("The BASIC program cannot be represented as editable text"); } completion:^(VCCMachineSnapshot *snapshot) { completion(source, snapshot); }]; } - (void)debuggerWriteMemoryAtAddress:(uint16_t)address data:(NSData *)data completion:(VCCMachineCompletion)completion { NSData *owned = [data copy]; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); worker.machine.debuggerWriteMemory(address, OwnedBytes(owned, 256)); } completion:completion]; } - (void)pauseWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.pause(); } completion:completion]; } - (void)softResetWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.softReset(); } completion:completion]; } - (void)resetWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.reset(); } completion:completion]; } - (void)startMacShellWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed || !worker.machine.driveWireEnabled()) throw std::logic_error("Enable DriveWire networking before starting a Mac shell session."); worker.shell.arm(); worker.error.clear(); } completion:completion]; } - (void)stopMacShellWithCompletion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { worker.shell.stop(); worker.error.clear(); } completion:completion]; } - (void)decideMacShellRequest:(uint64_t)requestID allow:(BOOL)allow completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed || !worker.machine.driveWireEnabled() || !worker.shell.decide(requestID, allow)) throw std::logic_error("This guest shell request has ended."); worker.error.clear(); } completion:completion]; } - (void)setDriveWireEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); if (enabled && worker.assistantProgram) { const auto active = worker.machine.snapshot(); if (std::make_pair(active.generation, active.debuggerProgramRevision) == *worker.assistantProgram && !worker.machine.basicAtDirectPrompt()) throw std::logic_error("Return the shared program to the BASIC prompt before enabling DriveWire."); } if (worker.machine.driveWireEnabled() != bool(enabled)) { worker.shell.stop(); VCC::Devices::DriveWireFactory factory; if (enabled) { factory = [owner = &worker](const std::string& host, uint16_t port) { return VCC::Mac::openDriveWireEndpoint(owner->shell, host, port); }; } worker.machine.setDriveWireFactory(std::move(factory)); } worker.error.clear(); } completion:completion]; } - (void)setAudioEnabled:(BOOL)enabled volume:(float)volume completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); // Gain/mute changes must not flush buffered sound or advance the guest // to refill it. Only an actual output enable/disable changes the clock. if (worker.audioEnabled != bool(enabled)) { worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); worker.audioEnabled = enabled; worker.error.clear(); } worker.audio.buffer().gain.store(std::isfinite(volume) ? std::clamp(volume,0.0f,1.0f) : 0.0f); } completion:completion]; } - (void)mountTape:(NSData*)data wav:(BOOL)wav completion:(VCCMachineCompletion)completion { NSData *owned=[data copy]; [self command:^(Worker& worker) { if(worker.machine.cassette().snapshot().dirty) throw std::logic_error("Export or discard the recording first"); if(owned.length>VCC::Mac::CassetteDeck::maxBytes) throw std::invalid_argument("Tape exceeds 64 MiB"); const auto *begin=static_cast(owned.bytes); std::vector bytes; if(owned.length) bytes.assign(begin,begin+owned.length); worker.machine.cassette().mount(bytes,wav?VCC::Mac::TapeFormat::WAV:VCC::Mac::TapeFormat::CAS); ++worker.mediaRevision; } completion:completion]; } - (void)tapeAction:(NSInteger)action completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { auto& tape=worker.machine.cassette(); if(action>=3 && tape.snapshot().dirty) throw std::logic_error("Export or discard the recording first"); switch(action) { case 0: tape.stop(); break; case 1: tape.play(); break; case 2: tape.rewind(); break; case 3: tape.eject(); ++worker.mediaRevision; break; case 4: tape.record(VCC::Mac::TapeFormat::CAS); ++worker.mediaRevision; break; case 5: tape.record(VCC::Mac::TapeFormat::WAV); ++worker.mediaRevision; break; default: throw std::invalid_argument("Unknown tape action"); } } completion:completion]; } - (void)seekTape:(uint64_t)position completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.cassette().seek(position); } completion:completion]; } - (void)setTapeFast:(BOOL)enabled completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.cassette().setFast(enabled); } completion:completion]; } - (void)exportTapeWithCompletion:(void (^)(NSData*,VCCMachineSnapshot*))completion { __block NSData *data=nil; [self command:^(Worker& worker) { auto bytes=worker.machine.cassette().exportImage(); data=[NSData dataWithBytes:bytes.data() length:bytes.size()]; } completion:^(VCCMachineSnapshot *snapshot) { completion(data,snapshot); }]; } - (void)discardTapeWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { // One queue operation: a recording tick cannot make it dirty again // between confirming discard and ejecting the in-memory image. auto& tape=worker.machine.cassette(); tape.stop(); tape.markSaved(); tape.eject(); ++worker.mediaRevision; } completion:completion]; } - (void)markTapeSavedWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.machine.cassette().markSaved(); } completion:completion]; } - (void)configureCartridges:(NSArray*)kinds roms:(NSArray*)roms names:(NSArray*)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot completion:(VCCMachineCompletion)completion { [self configureCartridges:kinds roms:roms names:names multiPak:enabled physicalSlot:slot sdcFolders:@[@"",@"",@"",@"",@""] sdcReadOnly:@[@YES,@YES,@YES,@YES,@YES] completion:completion]; } - (void)configureCartridges:(NSArray*)kinds roms:(NSArray*)roms names:(NSArray*)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot sdcFolders:(NSArray*)folders sdcReadOnly:(NSArray*)readOnly completion:(VCCMachineCompletion)completion { NSArray *roots = [[NSArray alloc] initWithArray:folders copyItems:YES]; NSArray *protectedCards = [[NSArray alloc] initWithArray:readOnly copyItems:YES]; // Copy each payload, not only the container, before crossing the queue. NSMutableArray *bytes = [NSMutableArray new]; for (NSData* data in roms) [bytes addObject:[data copy]]; NSArray *types = [kinds copy]; NSArray *labels = [[NSArray alloc] initWithArray:names copyItems:YES]; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.error.clear(); if (types.count != 5 || bytes.count != 5 || labels.count != 5 || roots.count != 5 || protectedCards.count != 5 || slot < 1 || slot > 4) throw std::invalid_argument("Invalid cartridge layout"); VCC::Devices::CartridgeBus::Slots next; std::array nextKinds; std::array nextNames; unsigned floppyCount = 0, hardCount = 0, ramCount = 0, orchestraCount = 0, speechCount = 0, sdcCount = 0; std::shared_ptr ram; for (unsigned i = 0; i < 5; ++i) { int kind = [types[i] intValue]; if (kind < 0 || kind > 7) throw std::invalid_argument("Unknown cartridge device"); nextKinds[i] = kind; nextNames[i] = [labels[i] UTF8String]; if (kind == 1 && [bytes[i] length]) next[i] = std::make_shared(OwnedBytes(bytes[i], 262144)); if (kind == 7) { if ([bytes[i] length]) next[i] = std::make_shared( OwnedBytes(bytes[i], 16384), [roots[i] UTF8String], [protectedCards[i] boolValue]); if (i) ++sdcCount; } if (kind == 6) { next[i] = std::make_shared(OwnedBytes(bytes[i], 6144)); if (i) ++speechCount; } if (kind == 5) { auto rom = OwnedBytes(bytes[i], 8192); // Retain DAC latches on reset, slot moves and unrelated changes. // Retained single/MPI modes may have different optional ROMs. // Prefer this assignment, then an MPI slot move, before the // retained single mode (which may have its own playback state). for (unsigned previous : {i, 1u, 2u, 3u, 4u, 0u}) { auto device = std::dynamic_pointer_cast(worker.cartridgeDevices[previous]); if (device && device->hasROM(rom)) { next[i] = device; break; } } if (!next[i]) next[i] = std::make_shared(std::move(rom)); if (i > 0) ++orchestraCount; } if (kind == 4) { if (!ram) ram = worker.ramDevice ? worker.ramDevice : std::make_shared(); next[i] = ram; if (i > 0) ++ramCount; } if (kind == 3) { next[i] = worker.hardDevice; if (i > 0) ++hardCount; } if (kind == 2) { next[i] = worker.diskDevice; if (i > 0) ++floppyCount; } } if (sdcCount > 1) throw std::invalid_argument("Only one CoCo SDC is supported in the Multi-Pak"); if (speechCount > 1) throw std::invalid_argument("Only one Speech/Sound Cartridge is supported in the Multi-Pak"); if (orchestraCount > 1) throw std::invalid_argument("Only one Orchestra-90 is supported in the Multi-Pak"); if (ramCount > 1) throw std::invalid_argument("Only one RAM disk is supported in the Multi-Pak"); if (hardCount > 1) throw std::invalid_argument("Only one virtual hard-disk controller is supported in the Multi-Pak"); if (floppyCount > 1) throw std::invalid_argument("Only one floppy controller is supported in the Multi-Pak"); worker.pauseForDisks(); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); worker.machine.cartridges().configure(next, enabled, static_cast(slot)); worker.ramDevice = std::move(ram); worker.cartridgeDevices = std::move(next); worker.cartridgeKinds = nextKinds; worker.cartridgeNames = std::move(nextNames); if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); } completion:completion]; } - (void)pauseForDiskChangeWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.pauseForDisks(); } completion:completion]; } - (void)loadDiskROM:(NSData*)rom name:(NSString*)name completion:(VCCMachineCompletion)completion { NSData *owned = [rom copy]; NSString *label = [name copy]; [self command:^(Worker& worker) { auto bytes = OwnedBytes(owned, 16384); // Construct/validate first, preserving the previous device on failure. auto next = VCC::Devices::makeDevice(VCC::Devices::DeviceKind::FD502, bytes); worker.pauseForDisks(); if (auto* existing = worker.floppy()) existing->setROM(bytes); else worker.diskDevice = std::shared_ptr(static_cast(next.release())); worker.applyLayout(worker.machine.cartridges().multiPak(), worker.machine.cartridges().physicalSlot()); worker.diskROMName = label.UTF8String; if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); } completion:completion]; } - (void)disableDisksWithCompletion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { auto& floppy = worker.requireFloppy(); for (unsigned i = 0; i < 4; ++i) if (floppy.image(i) && floppy.image(i)->dirty()) throw std::logic_error("Save or discard all modified disks before disabling the controller"); worker.pauseForDisks(); worker.diskDevice.reset(); worker.applyLayout(worker.machine.cartridges().multiPak(), worker.machine.cartridges().physicalSlot()); worker.diskROMName.clear(); for (unsigned i = 0; i < 4; ++i) worker.clearDrive(i); if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); } completion:completion]; } - (void)mountDisk:(NSData*)data drive:(NSInteger)drive name:(NSString*)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion { [self mountDisk:data drive:drive name:name readOnly:readOnly reset:VCCDiskInsertionResetNone completion:completion]; } - (void)mountDisk:(NSData*)data drive:(NSInteger)drive name:(NSString*)name readOnly:(BOOL)readOnly reset:(VCCDiskInsertionReset)reset completion:(VCCMachineCompletion)completion { NSData *owned = [data copy]; NSString *label = [name copy]; [self command:^(Worker& worker) { if (reset < VCCDiskInsertionResetNone || reset > VCCDiskInsertionResetColdRestart) throw std::invalid_argument("Unknown disk insertion reset option"); const auto index = DriveIndex(drive); auto image = LoadFloppyImage(owned, label, readOnly); auto& floppy = worker.requireFloppy(); if (const auto* current = floppy.image(index); current && current->dirty()) throw std::logic_error("Save or discard the modified disk before replacing it"); worker.pauseForDisks(); if (reset == VCCDiskInsertionResetSoftReset) worker.machine.softReset(); else if (reset == VCCDiskInsertionResetColdRestart) worker.machine.reset(); floppy.mount(index, std::move(image)); worker.clearDrive(index); worker.diskNames[index] = label.UTF8String; worker.readOnly[index] = readOnly; } completion:completion]; } - (void)createDiskInDrive:(NSInteger)drive completion:(VCCMachineCompletion)completion { [self createDiskInDrive:drive format:VCCFloppyFormatStandard completion:completion]; } - (void)createDiskInDrive:(NSInteger)drive format:(VCCFloppyFormat)format completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { using VCC::Devices::DiskFormat; DiskFormat kind; std::string name; switch (format) { case VCCFloppyFormatStandard: kind = DiskFormat::JVC; name = "Untitled.dsk"; break; case VCCFloppyFormatTrackDMK: kind = DiskFormat::DMK; name = "Untitled.dmk"; break; case VCCFloppyFormatSectorVDK: kind = DiskFormat::VDK; name = "Untitled.vdk"; break; default: throw std::invalid_argument("Unknown floppy image format"); } const auto index = DriveIndex(drive); auto disk = VCC::Devices::DiskImage::blank({}, kind); worker.pauseForDisks(); worker.requireFloppy().mount(index, std::move(disk)); worker.clearDrive(index); worker.diskNames[index] = name; } completion:completion]; } - (void)ejectDiskInDrive:(NSInteger)drive discard:(BOOL)discard completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { const auto index = DriveIndex(drive); worker.pauseForDisks(); worker.requireFloppy().eject(index, discard); worker.clearDrive(index); } completion:completion]; } - (void)setDiskWriteProtected:(BOOL)enabled drive:(NSInteger)drive completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { const auto index = DriveIndex(drive); if (!enabled && worker.readOnly[index]) throw std::logic_error("This image was opened from a read-only file"); auto& floppy = worker.requireFloppy(); auto* image = floppy.image(index); if (!enabled && image && image->formatWriteProtected()) throw std::logic_error("The disk image header specifies write protection"); worker.pauseForDisks(); const bool changed = image && image->writeProtected() != bool(enabled); floppy.setWriteProtected(index, enabled); if (changed) ++worker.mediaRevision; } completion:completion]; } - (void)exportDiskInDrive:(NSInteger)drive completion:(void (^)(NSData*,uint64_t,VCCMachineSnapshot*))completion { __block NSData *data = nil; __block uint64_t token = 0; [self command:^(Worker& worker) { const auto index = DriveIndex(drive); worker.pauseForDisks(); auto* image = worker.requireFloppy().image(index); if (!image) throw std::logic_error("Insert a disk first"); token = ++worker.nextExport; worker.exports[index] = Worker::Export{token, image->bytes()}; data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; } completion:^(VCCMachineSnapshot *snapshot) { completion(data,token,snapshot); }]; } - (void)snapshotDiskCopyInDrive:(NSInteger)drive completion:(void (^)(NSData*,VCCMachineSnapshot*))completion { __block NSData *data = nil; [self perform:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); const auto index = DriveIndex(drive); auto* floppy = worker.floppy(); if (!floppy || !floppy->image(index)) throw std::logic_error("Insert a disk first"); if (floppy->snapshot().busy) throw std::logic_error("Wait for the current disk transfer to finish before copying this disk"); worker.error.clear(); const auto& bytes = floppy->image(index)->bytes(); data = [NSData dataWithBytes:bytes.data() length:bytes.size()]; } completion:^(VCCMachineSnapshot *snapshot) { completion(data, snapshot); }]; } - (void)markDiskSavedInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString*)name completion:(VCCMachineCompletion)completion { NSString *label = [name copy]; [self command:^(Worker& worker) { const auto index = DriveIndex(drive); auto& floppy = worker.requireFloppy(); auto* image = floppy.image(index); const auto& exported = worker.exports[index]; if (!exported || exported->token != token || !image || floppy.snapshot().busy || image->bytes() != exported->bytes) throw std::logic_error("Disk changed while saving; the current disk still needs to be saved"); floppy.markSaved(index); worker.exports[index].reset(); worker.diskNames[index] = label.UTF8String; } completion:completion]; } - (void)beginDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture *, VCCMachineSnapshot *))completion { __block VCCDiskEditCapture *capture = nil; [self inspect:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.requireNoDiskEditor(); const auto index = DriveIndex(drive); auto& floppy = worker.requireFloppy(); const auto* image = floppy.image(index); if (!image) throw std::logic_error("Insert a disk before opening its editor."); if (floppy.snapshot().busy) throw std::logic_error("Wait for the floppy operation to finish before editing. A paused transfer must finish before opening the editor."); if (worker.machine.pasteRemaining()) throw std::logic_error("Finish or cancel the current paste before editing a disk."); worker.error.clear(); worker.machine.pause(); worker.machine.setKeyboard(0); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); const auto token = ++worker.nextDiskEdit; worker.diskEdit = Worker::DiskEdit{token, worker.machine.snapshot().generation, worker.mediaRevision, index, image->bytes(), {}}; capture = [VCCDiskEditCapture new]; capture.token = token; capture.drive = drive; capture.data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; capture.name = [NSString stringWithUTF8String:worker.diskNames[index].c_str()]; capture.canApply = !image->writeProtected() && !worker.readOnly[index]; } completion:^(VCCMachineSnapshot *snapshot) { completion(capture, snapshot); }]; } - (void)beginHardDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture *, VCCMachineSnapshot *))completion { __block VCCDiskEditCapture *capture = nil; [self inspect:^(Worker& worker) { if (worker.closed) throw std::logic_error("The machine controller has shut down"); worker.requireNoDiskEditor(); const auto index = HardDriveIndex(drive); const auto* image = worker.hardDevice->image(index); if (!image) throw std::logic_error("Insert a hard disk before opening its editor."); if (worker.floppy() && worker.floppy()->snapshot().busy) throw std::logic_error("Wait for the floppy operation to finish before editing. A paused transfer must finish before opening the editor."); if (worker.machine.pasteRemaining()) throw std::logic_error("Finish or cancel the current paste before editing a disk."); worker.error.clear(); worker.machine.pause(); worker.machine.setKeyboard(0); worker.audio.stop(); worker.pacer.reset(); worker.audioProgress.reset(); const auto token = ++worker.nextDiskEdit; worker.diskEdit = Worker::DiskEdit{token, worker.machine.snapshot().generation, worker.mediaRevision, index, image->bytes(), {}, true, {}}; capture = [VCCDiskEditCapture new]; capture.token = token; capture.drive = drive; capture.data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; capture.name = [NSString stringWithUTF8String:worker.hardNames[index].c_str()]; capture.canApply = !image->writeProtected() && !worker.hardReadOnly[index]; } completion:^(VCCMachineSnapshot *snapshot) { completion(capture, snapshot); }]; } - (void)prepareDiskEditorToken:(uint64_t)token data:(NSData *)data completion:(void (^)(BOOL, VCCMachineSnapshot *))completion { NSData *owned = [data copy]; __block BOOL prepared = NO; [self inspect:^(Worker& worker) { auto& edit = worker.requireDiskEditor(token); edit.prepared.reset(); edit.preparedHard.reset(); if (edit.hardDisk) { const auto* current = worker.hardDevice->image(edit.drive); if (current->writeProtected() || worker.hardReadOnly[edit.drive]) throw std::logic_error("This hard disk is write protected. Save an edited copy instead."); auto next = VCC::Devices::HardDiskImage(OwnedBytes(owned, VCC::Devices::HardDiskImage::maxBytes)); if (next.bytes().size() != current->bytes().size()) throw std::logic_error("Editing must preserve this hard disk's image size. Save a separate image for conversion."); const auto tape = worker.machine.cassette().snapshot(); if (tape.dirty || tape.mode == VCC::Mac::TapeMode::Recording) throw std::logic_error("Export the cassette recording before applying disk edits and restarting the CoCo."); for (unsigned i = 0; i < 4; ++i) if (worker.floppy() && worker.floppy()->image(i) && worker.floppy()->image(i)->dirty()) throw std::logic_error("Save changes on the floppy drives before applying edits and restarting the CoCo."); for (unsigned i = 0; i < 2; ++i) if (i != edit.drive && worker.hardDevice->image(i) && worker.hardDevice->image(i)->dirty()) throw std::logic_error("Save changes on the other hard disk before applying edits and restarting the CoCo."); // Preserve existing unsaved-sector revisions and temporary-mode // bytes, then track every editor change through the normal image // write path so a later automatic save has a complete patch plan. auto replacement = *current; for (std::size_t offset = 0; offset < next.bytes().size(); offset += 256) { if (std::equal(next.bytes().begin() + offset, next.bytes().begin() + offset + 256, current->bytes().begin() + offset)) continue; std::array sector; std::copy_n(next.bytes().begin() + offset, 256, sector.begin()); if (!replacement.write(static_cast(offset / 256), sector)) throw std::logic_error("The edited hard disk could not be prepared."); } edit.preparedHard = std::move(replacement); worker.error.clear(); prepared = YES; return; } const auto* current = worker.requireFloppy().image(edit.drive); if (current->writeProtected() || worker.readOnly[edit.drive]) throw std::logic_error("This disk is write protected. Save an edited copy instead."); auto next = LoadFloppyImage(owned, [NSString stringWithUTF8String:worker.diskNames[edit.drive].c_str()], false); const auto& before = current->geometry(); const auto& after = next.geometry(); if (next.format() != current->format() || next.bytes().size() != current->bytes().size() || next.formatWriteProtected() != current->formatWriteProtected() || next.containerHeaderBytes() != current->containerHeaderBytes() || !std::equal(current->bytes().begin(), current->bytes().begin() + current->containerHeaderBytes(), next.bytes().begin()) || before.tracks != after.tracks || before.sides != after.sides || before.sectors != after.sectors || before.sizeCode != after.sizeCode || before.firstSector != after.firstSector) throw std::logic_error("Editing must preserve this disk's image format, geometry and protection header. Save a separate image for conversion."); const auto tape = worker.machine.cassette().snapshot(); if (tape.dirty || tape.mode == VCC::Mac::TapeMode::Recording) throw std::logic_error("Export the cassette recording before applying disk edits and restarting the CoCo."); for (unsigned i = 0; i < 4; ++i) if (i != edit.drive && worker.requireFloppy().image(i) && worker.requireFloppy().image(i)->dirty()) throw std::logic_error("Save changes on the other floppy drives before applying edits and restarting the CoCo."); for (unsigned i = 0; i < 2; ++i) if (worker.hardDevice->image(i) && worker.hardDevice->image(i)->dirty()) throw std::logic_error("Save changes on the hard disks before applying edits and restarting the CoCo."); edit.prepared = std::move(next); worker.error.clear(); prepared = YES; } completion:^(VCCMachineSnapshot *snapshot) { completion(prepared, snapshot); }]; } - (void)commitDiskEditorToken:(uint64_t)token restartConfirmed:(BOOL)restartConfirmed sourceSaved:(BOOL)sourceSaved completion:(void (^)(BOOL, VCCMachineSnapshot *))completion { __block BOOL applied = NO; [self inspect:^(Worker& worker) { auto& edit = worker.requireDiskEditor(token); if (!restartConfirmed) throw std::logic_error("Confirm the cold restart before applying filesystem changes."); const auto index = edit.drive; if (edit.hardDisk) { if (!edit.preparedHard) throw std::logic_error("Validate the edited hard disk before applying it."); if (worker.hardDevice->image(index)->writeProtected() || worker.hardReadOnly[index]) throw std::logic_error("This hard disk is write protected. Save an edited copy instead."); } else { if (!edit.prepared) throw std::logic_error("Validate the edited disk before applying it."); if (worker.requireFloppy().image(index)->writeProtected() || worker.readOnly[index]) throw std::logic_error("This disk is write protected. Save an edited copy instead."); } // Reset while old media remain mounted; no guest instruction can run // between reset and replacement. All replacement bytes were validated. if (worker.machine.snapshot().state != VCC::Mac::RunState::Empty) worker.machine.reset(); worker.machine.pause(); worker.machine.setKeyboard(0); if (edit.hardDisk) { auto replacement = std::move(*edit.preparedHard); if (sourceSaved) replacement.acknowledge(replacement.capture()); worker.hardDevice->eject(index, true); worker.hardDevice->mount(index, std::move(replacement)); worker.hardExports[index].reset(); } else { auto replacement = std::move(*edit.prepared); if (sourceSaved) replacement.markSaved(); else replacement.markDirty(); worker.requireFloppy().mount(index, std::move(replacement), true); worker.exports[index].reset(); } ++worker.mediaRevision; worker.assistantProgram.reset(); worker.compiledKeyLease = nil; worker.compiledKeyExpected = nil; worker.assistantPasteRun.clear(); worker.diskEdit.reset(); worker.error.clear(); applied = YES; } completion:^(VCCMachineSnapshot *snapshot) { completion(applied, snapshot); }]; } - (void)cancelDiskEditorToken:(uint64_t)token completion:(VCCMachineCompletion)completion { [self inspect:^(Worker& worker) { worker.requireDiskEditor(token); worker.machine.pause(); worker.machine.setKeyboard(0); worker.diskEdit.reset(); worker.error.clear(); } completion:completion]; } - (void)assistantReadinessWithCompletion:(VCCMachineCompletion)completion { __block NSNumber *prompt = nil, *empty = nil; [self inspect:^(Worker& worker) { if (worker.closed) return; try { // Unsupported ROMs and transient memory maps leave these fields unknown. empty = @(worker.machine.basicReadSource().empty()); prompt = @(worker.machine.basicAtDirectPrompt()); } catch (const std::exception&) { } } completion:^(VCCMachineSnapshot *snapshot) { snapshot.assistantDirectPrompt = prompt; snapshot.assistantEmptyBASIC = empty; completion(snapshot); }]; } - (void)snapshotWithCompletion:(VCCMachineCompletion)completion { [self inspect:^(Worker&) {} completion:completion]; } - (void)captureDiskForSavingInDrive:(NSInteger)drive completion:(void (^)(NSData*,uint64_t,VCCMachineSnapshot*))completion { __block NSData *data = nil; __block uint64_t token = 0; [self perform:^(Worker& worker) { const auto index = DriveIndex(drive); auto* floppy = worker.floppy(); if (worker.closed || !floppy || floppy->snapshot().busy) return; auto* image = floppy->image(index); if (!image || !image->dirty() || image->writeProtected() || worker.readOnly[index]) return; token = ++worker.nextExport; worker.exports[index] = Worker::Export{token, image->bytes()}; data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; } completion:^(VCCMachineSnapshot *snapshot) { completion(data,token,snapshot); }]; } - (void)acknowledgeDiskSaveInDrive:(NSInteger)drive token:(uint64_t)token completion:(VCCMachineCompletion)completion { [self perform:^(Worker& worker) { const auto index = DriveIndex(drive); auto* floppy = worker.floppy(); if (worker.closed || !floppy) return; auto* image = floppy->image(index); const auto& exported = worker.exports[index]; if (!exported || exported->token != token) return; // Partial transfers have not changed image bytes yet; their eventual // commit will mark dirty again even if this acknowledgement clears it. if (image && image->bytes() == exported->bytes) floppy->markSaved(index); worker.exports[index].reset(); } completion:completion]; } - (void)mountHardDisk:(NSData*)data drive:(NSInteger)drive name:(NSString*)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion { NSData* owned = [data copy]; NSString* label = [name copy]; [self command:^(Worker& worker) { auto index = HardDriveIndex(drive); auto image = VCC::Devices::HardDiskImage(OwnedBytes(owned, VCC::Devices::HardDiskImage::maxBytes), readOnly); worker.pauseForDisks(); worker.hardDevice->mount(index, std::move(image)); worker.clearHardDrive(index); worker.hardNames[index] = label.UTF8String; worker.hardReadOnly[index] = readOnly; } completion:completion]; } - (void)createHardDiskInDrive:(NSInteger)drive size:(NSUInteger)size completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { auto index = HardDriveIndex(drive); auto image = VCC::Devices::HardDiskImage::blank(size); worker.pauseForDisks(); worker.hardDevice->mount(index, std::move(image)); worker.clearHardDrive(index); worker.hardNames[index] = "Untitled.vhd"; } completion:completion]; } - (void)hardDiskAction:(NSInteger)action drive:(NSInteger)drive completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { auto index = HardDriveIndex(drive); worker.pauseForDisks(); if (action == 0 || action == 1) { worker.hardDevice->eject(index, action == 1); worker.clearHardDrive(index); } else if (action == 2 || action == 3) { auto* image = worker.hardDevice->image(index); if (!image) throw std::logic_error("No hard disk is mounted"); if (action == 3 && worker.hardReadOnly[index]) throw std::logic_error("This file is read-only. Save a writable copy first"); if (image->writeProtected() != (action == 2)) ++worker.mediaRevision; image->protect(action == 2); } else throw std::invalid_argument("Unknown hard disk action"); } completion:completion]; } - (void)configureHardClock:(BOOL)enabled readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion { [self command:^(Worker& worker) { worker.pauseForDisks(); worker.hardDevice->configureClock(enabled, readOnly); } completion:completion]; } - (void)captureHardDiskInDrive:(NSInteger)drive full:(BOOL)full completion:(void (^)(VCCHardDiskSave*,VCCMachineSnapshot*))completion { __block VCCHardDiskSave* result = nil; void (^capture)(Worker&) = ^(Worker& worker) { if (worker.closed) return; auto index = HardDriveIndex(drive); auto* image = worker.hardDevice->image(index); if (!image) return; if (full) worker.pauseForDisks(); else if (!image->dirty() || image->writeProtected() || worker.hardReadOnly[index]) return; auto saved = image->capture(); result = [VCCHardDiskSave new]; result.token = ++worker.nextExport; result.byteCount = saved.length; if (full) result.data = [NSData dataWithBytes:image->bytes().data() length:image->bytes().size()]; else { NSMutableData* patches = [NSMutableData dataWithCapacity:saved.records.size() * 260]; for (const auto& record : saved.records) { std::uint8_t indexBytes[4]{std::uint8_t(record.sector), std::uint8_t(record.sector >> 8), std::uint8_t(record.sector >> 16), std::uint8_t(record.sector >> 24)}; [patches appendBytes:indexBytes length:4]; [patches appendBytes:record.bytes.data() length:256]; } result.data = patches; } worker.hardExports[index] = Worker::HardExport{result.token, std::move(saved)}; }; VCCMachineCompletion finish = ^(VCCMachineSnapshot* snapshot) { completion(result, snapshot); }; if (full) [self command:capture completion:finish]; else [self perform:capture completion:finish]; } - (void)acknowledgeHardDiskInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString*)name completion:(VCCMachineCompletion)completion { NSString* label = [name copy]; [self perform:^(Worker& worker) { auto index = HardDriveIndex(drive); auto* image = worker.hardDevice->image(index); auto& saved = worker.hardExports[index]; if (worker.closed || !image || !saved || saved->token != token) return; image->acknowledge(saved->saved); saved.reset(); if (label) { worker.hardNames[index] = label.UTF8String; worker.hardReadOnly[index] = false; } } completion:completion]; } - (void)shutdownWithCompletion:(VCCMachineCompletion)completion { dispatch_source_cancel(_timer); [self inspect:^(Worker& worker) { worker.diskEdit.reset(); worker.closed = true; worker.shell.stop(); worker.audio.stop(); worker.machine.shutdown(); worker.error.clear(); } completion:completion]; } - (void)dealloc { dispatch_source_cancel(_timer); auto worker = _worker; // Worker blocks never retain self; deallocation cannot originate on _queue. dispatch_sync(_queue, ^{ worker->closed = true; worker->audio.stop(); worker->machine.shutdown(); }); } @end