2838 lines
172 KiB
Swift
2838 lines
172 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import SwiftUI
|
||
import AppKit
|
||
import Combine
|
||
import UniformTypeIdentifiers
|
||
|
||
enum DisplayOutput: Int, CaseIterable {
|
||
case rgb = 0, composite = 1, compositeAlternate = 2
|
||
var label: String {
|
||
switch self {
|
||
case .rgb: return "RGB Monitor"
|
||
case .composite: return "Composite TV"
|
||
case .compositeAlternate: return "Composite TV — Alternate Colors"
|
||
}
|
||
}
|
||
static let preferenceKey = "videoOutput"
|
||
static func remembered(in defaults: UserDefaults) -> Self {
|
||
guard let raw = defaults.object(forKey: preferenceKey) as? Int else { return .composite }
|
||
return Self(rawValue: raw) ?? .composite
|
||
}
|
||
}
|
||
|
||
enum DiskInsertionExecution: Int, CaseIterable, Sendable {
|
||
case keepCurrentState, pause, run
|
||
var label: String {
|
||
switch self {
|
||
case .keepCurrentState: return "Keep current state"
|
||
case .pause: return "Pause"
|
||
case .run: return "Run"
|
||
}
|
||
}
|
||
}
|
||
|
||
enum DiskInsertionReset: Int, CaseIterable, Sendable {
|
||
case none, softReset, coldRestart
|
||
var label: String {
|
||
switch self {
|
||
case .none: return "No Reset"
|
||
case .softReset: return "Soft Reset"
|
||
case .coldRestart: return "Cold Restart"
|
||
}
|
||
}
|
||
var explanation: String {
|
||
switch self {
|
||
case .none: return "Insert without resetting the current program."
|
||
case .softReset: return "Reset the CoCo before insertion. The current program stops; RAM is retained, but its contents may be changed by the ROM's reset routine."
|
||
case .coldRestart: return "Restart the CoCo before insertion. Programs and other contents of RAM are cleared. Mounted media are retained."
|
||
}
|
||
}
|
||
var controllerValue: VCCDiskInsertionReset {
|
||
switch self {
|
||
case .none: return .none
|
||
case .softReset: return .softReset
|
||
case .coldRestart: return .coldRestart
|
||
}
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
final class DiskMediaOpenOptions: NSObject {
|
||
let action = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28))
|
||
let drive = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28))
|
||
let execution = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28))
|
||
let reset = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28))
|
||
let view: NSStackView
|
||
private let resetExplanation = NSTextField(wrappingLabelWithString: "")
|
||
private let driveLabel = NSTextField(labelWithString: "Floppy drive")
|
||
private var hardDriveShown = false
|
||
private var floppySelection = 0
|
||
private var hardSelection = 0
|
||
init(preferred: MediaDestination?, supportsHardDisk: Bool = false) {
|
||
view = NSStackView(); view.orientation = .vertical; view.alignment = .leading; view.spacing = 6
|
||
super.init()
|
||
action.addItems(withTitles: ["Edit Disk Image", "Insert into Floppy Drive"])
|
||
if supportsHardDisk { action.addItem(withTitle: "Insert into Hard Disk") }
|
||
action.setAccessibilityLabel("Disk action"); action.identifier = NSUserInterfaceItemIdentifier("diskOpenAction")
|
||
action.setAccessibilityIdentifier("diskOpenAction")
|
||
drive.addItems(withTitles: (0..<4).map { "FD\($0)" }); drive.setAccessibilityLabel("Floppy drive")
|
||
drive.identifier = NSUserInterfaceItemIdentifier("diskOpenDrive"); drive.setAccessibilityIdentifier("diskOpenDrive")
|
||
execution.addItems(withTitles: DiskInsertionExecution.allCases.map(\.label)); execution.setAccessibilityLabel("After inserting")
|
||
execution.identifier = NSUserInterfaceItemIdentifier("diskOpenExecution"); execution.setAccessibilityIdentifier("diskOpenExecution")
|
||
reset.addItems(withTitles: DiskInsertionReset.allCases.map(\.label)); reset.setAccessibilityLabel("Before inserting")
|
||
reset.identifier = NSUserInterfaceItemIdentifier("diskOpenReset"); reset.setAccessibilityIdentifier("diskOpenReset")
|
||
if let preferred, case .floppy(let number) = preferred { action.selectItem(at: 1); drive.selectItem(at: number) }
|
||
if let preferred, case .hardDisk(let number) = preferred, supportsHardDisk { action.selectItem(at: 2); hardSelection = number }
|
||
view.addArrangedSubview(NSTextField(labelWithString: "Action")); view.addArrangedSubview(action)
|
||
view.addArrangedSubview(driveLabel); view.addArrangedSubview(drive)
|
||
view.addArrangedSubview(NSTextField(labelWithString: "Before inserting")); view.addArrangedSubview(reset)
|
||
resetExplanation.preferredMaxLayoutWidth = 340
|
||
resetExplanation.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
|
||
resetExplanation.textColor = .secondaryLabelColor
|
||
// Reserve room for the destructive-action explanation before the
|
||
// sheet opens; changing the popup must not clip its longer warning.
|
||
resetExplanation.widthAnchor.constraint(equalToConstant: 340).isActive = true
|
||
resetExplanation.heightAnchor.constraint(equalToConstant: 54).isActive = true
|
||
view.addArrangedSubview(resetExplanation)
|
||
view.addArrangedSubview(NSTextField(labelWithString: "After inserting")); view.addArrangedSubview(execution)
|
||
action.target = self; action.action = #selector(update)
|
||
reset.target = self; reset.action = #selector(update)
|
||
update()
|
||
view.setFrameSize(NSSize(width: 340, height: view.fittingSize.height))
|
||
}
|
||
@objc func update() {
|
||
let hard = action.indexOfSelectedItem == 2
|
||
if hard != hardDriveShown {
|
||
if hardDriveShown { hardSelection = drive.indexOfSelectedItem } else { floppySelection = drive.indexOfSelectedItem }
|
||
drive.removeAllItems()
|
||
drive.addItems(withTitles: hard ? ["HD0", "HD1"] : (0..<4).map { "FD\($0)" })
|
||
drive.selectItem(at: hard ? hardSelection : floppySelection)
|
||
hardDriveShown = hard
|
||
}
|
||
driveLabel.stringValue = hard ? "Hard disk drive" : "Floppy drive"
|
||
drive.setAccessibilityLabel(hard ? "Hard disk drive" : "Floppy drive")
|
||
drive.isEnabled = action.indexOfSelectedItem != 0
|
||
execution.isEnabled = action.indexOfSelectedItem == 1
|
||
reset.isEnabled = action.indexOfSelectedItem == 1
|
||
resetExplanation.stringValue = action.indexOfSelectedItem == 1
|
||
? (DiskInsertionReset(rawValue: reset.indexOfSelectedItem) ?? .none).explanation
|
||
: "Reset options apply only when inserting into a floppy drive."
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
final class MachineModel: ObservableObject {
|
||
@Published private(set) var hardware = HardwareState()
|
||
private var sdcActivityTracker = ActivityTracker()
|
||
private var activityTrackers = Array(repeating: ActivityTracker(), count: 7)
|
||
@Published private(set) var videoOutput = DisplayOutput.composite
|
||
private let displayDefaults: UserDefaults
|
||
struct BASICDebugState: Equatable, Sendable {
|
||
var attached = false
|
||
var line: Int? = nil
|
||
var sourceRange: NSRange? = nil
|
||
var stepping = false
|
||
var status = ""
|
||
var generation: UInt64 = 0
|
||
var paused = false
|
||
var cycles: UInt64 = 0
|
||
var atPrompt = false
|
||
var canStepOut = false
|
||
var errorLine: Int? = nil
|
||
var errorCode = ""
|
||
}
|
||
@Published private(set) var basicDebug = BASICDebugState()
|
||
@Published var basicWorkspaceOwner: UUID?
|
||
@Published private(set) var state: VCCMachineState = .empty
|
||
@Published private(set) var frames: UInt64 = 0
|
||
#if VCC_UI_TESTING
|
||
private(set) var uiTestSession = ""
|
||
#endif
|
||
@Published private(set) var pixels: Data?
|
||
@Published private(set) var activeVideoRect = VideoGeometry.fullFrame
|
||
@Published private(set) var title = "No ROM selected"
|
||
@Published private(set) var binaryName: String?
|
||
@Published private(set) var systemROMURL: URL?
|
||
struct GuideRequest: Equatable {
|
||
let id = UUID()
|
||
let profile: SystemProfile
|
||
}
|
||
@Published private(set) var guideRequest: GuideRequest?
|
||
@Published private(set) var profileName: String?
|
||
@Published private(set) var profileError: String?
|
||
private var cassetteURL: URL?
|
||
private var bootNitros9 = false
|
||
private var builtInNitros9 = false
|
||
private var libraryReturnToNitros9: ConfigurationProfile?
|
||
private var loadedProfileConfiguration: ConfigurationProfile?
|
||
var profileModified: Bool {
|
||
guard let baseline = loadedProfileConfiguration, profileName != nil else { return false }
|
||
return profileConfiguration != baseline || (tapeMounted && cassetteURL == nil) ||
|
||
disks.enumerated().contains { $0.element.mounted && diskAssignments.drives[$0.offset] == nil } ||
|
||
hardDisks.enumerated().contains { $0.element.mounted && hardSettings.drives[$0.offset] == nil }
|
||
}
|
||
private var profileConfiguration: ConfigurationProfile {
|
||
var p = ConfigurationProfile(name: "Current")
|
||
p.id = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!
|
||
p.machine = settings; p.videoOutput = videoOutput.rawValue; p.sound = audioEnabled; p.volume = volume
|
||
p.systemROM = systemROMURL; p.media = diskAssignments; p.media.cartridges = cartridgeAssignments
|
||
p.media.hardDisks = hardSettings; p.cassette = tapeMounted ? cassetteURL : nil; p.fastCassette = tapeFast
|
||
p.input = input.settings; p.bootNitros9 = bootNitros9 ? true : nil
|
||
return p
|
||
}
|
||
var canQuickLoad: Bool { !busy && !diskSaving && !diskEditorLocked && (state == .running || state == .paused) }
|
||
@Published private(set) var settings = MachineSettings()
|
||
var use6309: Bool { settings.use6309 }
|
||
@Published private(set) var inputEpoch: UInt64 = 0
|
||
@Published private(set) var focusRequest: UInt64 = 0
|
||
func focusDisplay() { focusRequest += 1 }
|
||
@Published var displayError: String?
|
||
@Published private(set) var fileError: String?
|
||
@Published private(set) var error: String?
|
||
@Published private(set) var busy = false
|
||
@Published private(set) var pasteRemaining = 0
|
||
@Published private(set) var driveWireEnabled = false
|
||
struct MacShellRequest: Equatable {
|
||
let id: UInt64
|
||
let generation: UInt64
|
||
let disk: [String: String]?
|
||
}
|
||
|
||
private static let shellGrantKey = "driveWireNetworking.macShellGrant"
|
||
@Published private(set) var macShellStatus = "idle"
|
||
private var macShellRequestID: UInt64 = 0
|
||
private var shellDecisionInFlight: UInt64?
|
||
private var deniedShellGeneration: UInt64?
|
||
private(set) var assemblyAttached = false
|
||
private(set) var assemblyMappingFingerprint: UInt64 = 0
|
||
private var programRevision: UInt64 = 0
|
||
private var presetProgramRevision: UInt64?
|
||
private let starterShellDiskURL: URL?
|
||
private var savedShellGrant: [String: String]? {
|
||
get { displayDefaults.dictionary(forKey: Self.shellGrantKey) as? [String: String] }
|
||
set { displayDefaults.set(newValue, forKey: Self.shellGrantKey) }
|
||
}
|
||
var hasRememberedMacShellPermission: Bool { savedShellGrant != nil }
|
||
|
||
// The built-in system disk is the grant's boundary. A Library title, a
|
||
// personal profile or new code injected by an editor/quickload must ask.
|
||
private var shellDisk: [String: String]? {
|
||
guard builtInNitros9, usageProfile == .nitros9, presetProgramRevision == programRevision,
|
||
cartridgeAssignments.slots.map(\.kind) == [.empty, .hardDisk, .empty, .empty, .floppy],
|
||
let backing = hardBackings[0], backing.url.standardizedFileURL == starterShellDiskURL else { return nil }
|
||
return ["path": backing.url.path, "sha256": backing.digest]
|
||
}
|
||
|
||
var currentSetupHasMacShellPermission: Bool {
|
||
guard let disk = shellDisk else { return false }
|
||
return disk == savedShellGrant
|
||
}
|
||
|
||
var macShellRequest: MacShellRequest? {
|
||
guard macShellStatus == "requested", macShellRequestID != 0,
|
||
driveWireEnabled, !busy, !diskSaving, shellDecisionInFlight == nil else { return nil }
|
||
return MacShellRequest(id: macShellRequestID, generation: imageGeneration, disk: shellDisk)
|
||
}
|
||
|
||
func startMacShellSession() {
|
||
guard driveWireEnabled, !busy, state != .closed else { return }
|
||
command(controller.startMacShell, onSuccess: { [self] in deniedShellGeneration = nil })
|
||
}
|
||
|
||
func stopMacShellSession() {
|
||
guard !busy, state != .closed else { return }
|
||
command(controller.stopMacShell, onSuccess: { [self] in deniedShellGeneration = imageGeneration })
|
||
}
|
||
|
||
func forgetMacShellPermission() {
|
||
savedShellGrant = nil
|
||
if macShellStatus != "idle" { stopMacShellSession() }
|
||
objectWillChange.send()
|
||
}
|
||
|
||
private func applySavedMacShellDecision() {
|
||
guard let request = macShellRequest else { return }
|
||
if deniedShellGeneration == request.generation {
|
||
decideMacShell(request, allow: false)
|
||
} else if currentSetupHasMacShellPermission {
|
||
decideMacShell(request, allow: true)
|
||
}
|
||
}
|
||
|
||
func decideMacShell(_ request: MacShellRequest, allow: Bool, remember: Bool = false) {
|
||
guard macShellRequest == request else { return }
|
||
shellDecisionInFlight = request.id
|
||
controller.decideMacShellRequest(request.id, allow: allow) { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.shellDecisionInFlight = nil
|
||
self.accept(snapshot)
|
||
guard snapshot.errorMessage == nil, self.imageGeneration == request.generation else { return }
|
||
if !allow { self.deniedShellGeneration = request.generation }
|
||
if allow, remember, let disk = request.disk, disk == self.shellDisk { self.savedShellGrant = disk }
|
||
}
|
||
}
|
||
}
|
||
|
||
private static let driveWireKey = "driveWireNetworking.enabled"
|
||
@Published private(set) var audioEnabled = true
|
||
@Published var volume: Double = 0.5
|
||
@Published private(set) var tapeMounted = false
|
||
@Published private(set) var tapeDirty = false
|
||
@Published private(set) var tapeFast = false
|
||
@Published private(set) var tapeWAV = false
|
||
@Published private(set) var tapeMode = 0
|
||
@Published private(set) var tapeMotor = false
|
||
@Published private(set) var tapePosition: UInt64 = 0
|
||
@Published private(set) var tapeLength: UInt64 = 0
|
||
@Published private(set) var tapeName = "No tape"
|
||
@Published private(set) var cartridgeAssignments = CartridgeAssignments()
|
||
@Published private(set) var cartridgeRestoreErrors: [Int: String] = [:]
|
||
@Published private(set) var cartridgeNames = Array(repeating: "", count: 5)
|
||
@Published private(set) var sdcDriveNames = ["", ""]
|
||
@Published private(set) var sdcDirectory = ""
|
||
@Published private(set) var sdcReadOnly = true
|
||
@Published private(set) var sdcReadCount: UInt64 = 0
|
||
@Published private(set) var sdcWriteCount: UInt64 = 0
|
||
@Published private(set) var sdcError: String?
|
||
@Published private(set) var romSlot = 0
|
||
@Published private(set) var ioSlot = 0
|
||
@Published private(set) var diskConnected = false
|
||
private var cartridgeBytes = Array(repeating: Data(), count: 5)
|
||
@Published private(set) var diskEnabled = false
|
||
@Published private(set) var diskBusy = false
|
||
@Published private(set) var diskMotor = false
|
||
@Published private(set) var diskROMName = ""
|
||
@Published private(set) var diskSelectedDrive = -1
|
||
@Published private(set) var diskTrack: UInt = 0
|
||
@Published private(set) var diskSector: UInt = 0
|
||
@Published private(set) var disks: [VCCDiskSnapshot] = []
|
||
var dirtyDisks: Bool { disks.contains { $0.dirty } }
|
||
var unsavedMedia: Bool { dirtyDisks || hardDisks.contains { $0.dirty } || tapeDirty || tapeMode == 2 }
|
||
// Pending automatic writes still count as unsaved for quit/replacement
|
||
// safeguards, but do not ask the user to intervene during normal disk I/O.
|
||
var mediaNeedsManualSave: Bool {
|
||
tapeDirty || tapeMode == 2 ||
|
||
disks.enumerated().contains { drive, disk in
|
||
disk.dirty && (diskTemporary[drive] || diskBackings[drive] == nil || disk.writeProtected || disk.sourceReadOnly)
|
||
} || hardDisks.enumerated().contains { drive, disk in
|
||
disk.dirty && (hardTemporary[drive] || hardBackings[drive] == nil || disk.writeProtected || disk.sourceReadOnly)
|
||
}
|
||
}
|
||
@Published private(set) var hardDisks: [VCCDiskSnapshot] = []
|
||
@Published private(set) var hardDiskConnected = false
|
||
@Published private(set) var hardSelectedDrive = 0
|
||
@Published private(set) var hardSector: UInt = 0
|
||
@Published private(set) var hardStatus: UInt = 255
|
||
@Published private(set) var hardSettings = HardDiskAssignments()
|
||
@Published private(set) var hardTemporary = [false, false]
|
||
@Published private(set) var hardRestoreErrors: [Int: String] = [:]
|
||
@Published private(set) var hardSaveErrors: [Int: String] = [:]
|
||
private struct HardBacking { var url: URL; var digest: String }
|
||
private var hardBackings: [HardBacking?] = [nil, nil]
|
||
private var nextHardSave = Date.distantPast
|
||
private var hardFlushRequests: UInt64 = 0
|
||
private var savedHardFlushRequests: UInt64 = 0
|
||
private let automaticHardDiskWriter: @Sendable (Data, Int, URL, String) async throws -> String
|
||
@Published private(set) var diskAssignments = DiskAssignments()
|
||
@Published private(set) var diskRestoreErrors: [Int: String] = [:] // -1 is the ROM
|
||
@Published private(set) var diskSettingsError: String?
|
||
@Published private(set) var diskSettingsNeedsSave = false
|
||
@Published private(set) var diskSaving = false
|
||
@Published private(set) var diskTemporary = Array(repeating: false, count: 4)
|
||
@Published private(set) var diskSaveErrors: [Int: String] = [:]
|
||
@Published private(set) var diskEditorLocked = false
|
||
private var activeDiskEditor: DiskEditorSession?
|
||
private var diskEditorBacking: Backing?
|
||
private var hardDiskEditorBacking: HardBacking?
|
||
private struct Backing { var url: URL; var bytes: Data }
|
||
private var diskBackings: [Backing?] = Array(repeating: nil, count: 4)
|
||
private var diskSaveTask: Task<Void, Never>?
|
||
private var diskMonitor: Task<Void, Never>?
|
||
private let automaticDiskWriter: @Sendable (Data, URL, Data) async throws -> Void
|
||
private let diskStore: DiskAssignmentStore
|
||
private let inputStore: InputSettingsStore
|
||
lazy var printer = PrinterModel(controller: controller)
|
||
private var existingInputHub: InputHub?
|
||
lazy var input: InputHub = {
|
||
let hub = InputHub(controller: controller, store: inputStore)
|
||
existingInputHub = hub
|
||
return hub
|
||
}()
|
||
// A read-only MCP observation must not initialize HID/timers or submit input.
|
||
func inputDiagnostics(machine observed: VCCMachineSnapshot) -> [String: Any] {
|
||
existingInputHub?.diagnostics(machine: observed) ?? InputHub.unavailableDiagnostics(machine: observed)
|
||
}
|
||
lazy var menuState = MachineMenuState(machine: self)
|
||
private let startupStore: StartupStore?
|
||
// A library-only background launch must not mount or run the user's machine.
|
||
// The same model is restored once if the user later opens VCC Plus normally.
|
||
private(set) var companionMachineRestoreDeferred = false
|
||
private var startupRestoreStarted = false
|
||
private var starterDiskROMURLs: [SystemProfile: URL] = [:]
|
||
// Identify the selected starter firmware, not a profile's editable name.
|
||
// Personal copies and relaunches keep these content-addressed references.
|
||
var usageProfile: SystemProfile? {
|
||
guard systemROMURL != nil else { return nil }
|
||
let slot = cartridgeAssignments.multiPak ? cartridgeAssignments.physicalSlot : 0
|
||
let cartridge = cartridgeAssignments.slots[slot]
|
||
if cartridge.kind == .sdc, !cartridgeNames[slot].isEmpty,
|
||
let rom = cartridge.url, starterDiskROMURLs[.cocoSDC] == rom.standardizedFileURL { return .cocoSDC }
|
||
guard diskConnected, diskEnabled, let rom = diskAssignments.rom else { return nil }
|
||
if bootNitros9 && hardDiskConnected && hardDisks[0].mounted && starterDiskROMURLs[.nitros9] == rom.standardizedFileURL { return .nitros9 }
|
||
return [SystemProfile.diskBasic, .hardDriveBasic].first { starterDiskROMURLs[$0] == rom.standardizedFileURL }
|
||
}
|
||
var hasBundledROMs: Bool { startupStore?.kit != nil }
|
||
private var mediaPromptOpen = false
|
||
let recentMedia: RecentMedia
|
||
let displayPreferences: DisplayPreferences
|
||
private var screenshotInProgress = false
|
||
private let controller: VCCMachineController
|
||
init(diskStore: DiskAssignmentStore = .standard, controller: VCCMachineController = VCCMachineController(),
|
||
displayDefaults: UserDefaults = .standard, inputStore: InputSettingsStore = .standard, startupStore: StartupStore? = nil,
|
||
restoreMediaOnLaunch: Bool = true,
|
||
automaticHardDiskWriter: @escaping @Sendable (Data, Int, URL, String) async throws -> String = { patches, length, url, expected in
|
||
try await Task.detached(priority: .utility) { try HardDiskFiles.saveAutomatically(patches, length: length, to: url, expected: expected) }.value
|
||
},
|
||
automaticDiskWriter: @escaping @Sendable (Data, URL, Data) async throws -> Void = { data, url, expected in
|
||
try await Task.detached(priority: .utility) { try DiskFiles.saveAutomatically(data, to: url, expected: expected) }.value
|
||
}) {
|
||
self.recentMedia = RecentMedia(defaults: displayDefaults)
|
||
self.displayPreferences = DisplayPreferences(defaults: displayDefaults)
|
||
self.startupStore = startupStore
|
||
self.starterShellDiskURL = startupStore?.directory.resolvingSymlinksInPath()
|
||
.appendingPathComponent("Starter Media/NitrOS-9 L2 V3.3.0.vhd").standardizedFileURL
|
||
self.inputStore = inputStore
|
||
self.displayDefaults = displayDefaults
|
||
videoOutput = DisplayOutput.remembered(in: displayDefaults)
|
||
let rememberedSettings = MachineSettings.remembered(in: displayDefaults)
|
||
settings = rememberedSettings
|
||
self.automaticHardDiskWriter = automaticHardDiskWriter
|
||
self.diskStore = diskStore; self.controller = controller; self.automaticDiskWriter = automaticDiskWriter
|
||
companionMachineRestoreDeferred = !restoreMediaOnLaunch
|
||
if restoreMediaOnLaunch { beginRememberedMachineRestore() }
|
||
}
|
||
|
||
/// The app invokes this only for an explicit foreground/open-media action,
|
||
/// never for a library request or a companion reconnect.
|
||
func restoreDeferredCompanionMachine() {
|
||
guard companionMachineRestoreDeferred else { return }
|
||
companionMachineRestoreDeferred = false
|
||
beginRememberedMachineRestore()
|
||
}
|
||
private func beginRememberedMachineRestore() {
|
||
guard !startupRestoreStarted else { return }
|
||
startupRestoreStarted = true
|
||
if let store = startupStore, let kit = store.kit {
|
||
for kind in SystemProfile.allCases {
|
||
starterDiskROMURLs[kind] = try? kit.cachedROMURL(kind.diskROMName, in: store.directory).standardizedFileURL
|
||
}
|
||
}
|
||
busy = true
|
||
if displayDefaults.bool(forKey: Self.driveWireKey) {
|
||
controller.setDriveWireEnabled(true) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot) }
|
||
}
|
||
}
|
||
controller.setAudioEnabled(true, volume: 0.5) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot) }
|
||
}
|
||
controller.setVideoOutput(videoOutput.rawValue) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot) }
|
||
}
|
||
controller.configureMachine(use6309: settings.use6309, ram: settings.ram,
|
||
overclock: settings.overclock, frameInterval: settings.frameInterval,
|
||
fastForward: settings.fastForward) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot) }
|
||
}
|
||
Task { @MainActor in
|
||
var startup: StartupStore.Selection?
|
||
do { startup = try startupStore?.prepare(diskStore: diskStore) }
|
||
catch { fileError = "Startup setup: " + error.localizedDescription }
|
||
do {
|
||
diskAssignments = try await Task.detached { try self.diskStore.load() }.value
|
||
if let saved = diskAssignments.cartridges { cartridgeAssignments = saved }
|
||
else if diskAssignments.rom != nil { cartridgeAssignments.slots[0].kind = .floppy }
|
||
await restoreCartridges()
|
||
await restoreDisks()
|
||
hardSettings = diskAssignments.hardDisks ?? HardDiskAssignments()
|
||
await restoreHardDisks()
|
||
} catch { diskSettingsError = "Could not read remembered disks: \(error.localizedDescription)" }
|
||
if let startup { await restoreStartup(startup) }
|
||
busy = false
|
||
startDiskMonitor()
|
||
}
|
||
}
|
||
private func rememberStartup() {
|
||
guard !companionMachineRestoreDeferred, let startupStore else { return }
|
||
do { try startupStore.save(.init(systemROM: systemROMURL, cassette: cassetteURL, bootNitros9: bootNitros9 ? true : nil,
|
||
builtInNitros9: builtInNitros9 ? true : nil)) }
|
||
catch { fileError = "Could not remember startup choices: " + error.localizedDescription }
|
||
}
|
||
private func restoreStartup(_ selection: StartupStore.Selection) async {
|
||
systemROMURL = selection.systemROM; cassetteURL = selection.cassette; bootNitros9 = selection.bootNitros9 == true
|
||
var ready = false
|
||
if let url = selection.systemROM {
|
||
do {
|
||
let data = try await Task.detached { try ROMImage.read(url) }.value
|
||
let result = await diskStep { controller.loadROM(data, use6309: use6309, completion: $0) }
|
||
if let error = result.errorMessage { throw ProfileFailure.message(error) }
|
||
title = url.lastPathComponent; ready = true
|
||
} catch { fileError = "System ROM unavailable: " + error.localizedDescription }
|
||
}
|
||
if let url = selection.cassette {
|
||
do {
|
||
let data = try await Task.detached { try TapeImage.read(url) }.value
|
||
let result = await diskStep { controller.mountTape(data, wav: url.pathExtension.lowercased() == "wav", completion: $0) }
|
||
if let error = result.errorMessage { throw ProfileFailure.message(error) }
|
||
tapeName = url.lastPathComponent
|
||
} catch { fileError = "Remembered cassette unavailable: " + error.localizedDescription }
|
||
}
|
||
guard await applyDriveWireDefault(selection.builtInNitros9 == true && bootNitros9) else { return }
|
||
// Ordinary defaults never type commands. NitrOS-9 profiles explicitly opt into DOS 255.
|
||
if ready && fileError == nil && diskSettingsError == nil && diskRestoreErrors.isEmpty && cartridgeRestoreErrors.isEmpty && hardRestoreErrors.isEmpty {
|
||
if bootNitros9 { _ = await diskStep(controller.requestNitros9Boot) }
|
||
let resumed = await diskStep(controller.resume)
|
||
focusRequest += 1
|
||
if resumed.errorMessage == nil, let profile = usageProfile {
|
||
guideRequest = GuideRequest(profile: profile)
|
||
}
|
||
}
|
||
}
|
||
func restoreBundledROM(system: Bool) {
|
||
guard !busy, !diskSaving, let store = startupStore, let kit = store.kit else { return }
|
||
let alert = NSAlert(); alert.messageText = "Restore bundled \(system ? "system" : "disk") ROM and restart?"
|
||
alert.informativeText = "The working program in RAM will be cleared. Mounted media and cartridge assignments are retained."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Restore ROM")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
do {
|
||
let url = try kit.rom(system ? "coco3.rom" : "disk11.rom", in: store.directory)
|
||
if system { installROM(try ROMImage.read(url), url: url) }
|
||
else { selectDiskROM(url) }
|
||
} catch { fileError = error.localizedDescription }
|
||
}
|
||
func confirmRestoreAppDefaults(onSuccess: (() -> Void)? = nil) {
|
||
guard !busy, !diskSaving, state != .closed else { return }
|
||
let alert = NSAlert(); alert.messageText = "Restore app defaults and restart?"
|
||
alert.informativeText = "This clears the program in RAM and any RAM disk contents, and restores the 6809, 512 KB, normal speed, composite color, sound, default keyboard/joystick settings, and bundled ROMs. The floppy controller returns to Multi-Pak slot 4, with the Hello World disk and stopped cassette. Other media is detached. Saved profiles and media files are kept; existing Hello World files are not overwritten. Writable disks are saved first. Unsaved temporary disks or recordings block the restore. Neither example program loads or runs automatically."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Restore Defaults")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
Task { @MainActor in if await restoreAppDefaults() { onSuccess?() } }
|
||
}
|
||
// Shared by both presentations. The profile transaction already pauses the
|
||
// worker, drains automatic writes and rejects any unsaved media atomically.
|
||
@discardableResult func restoreAppDefaults() async -> Bool {
|
||
await loadSystemProfile(.diskBasic)
|
||
}
|
||
func systemProfileUnavailableReason(_ kind: SystemProfile) -> String? {
|
||
guard let startupStore else { return StartupStore.Failure.unavailable.localizedDescription }
|
||
return startupStore.unavailableReason(for: kind)
|
||
}
|
||
func makeSystemProfile(_ kind: SystemProfile, freshMedia: Bool = false) async throws -> ConfigurationProfile {
|
||
guard !busy, state != .closed else { throw ProfileFailure.message("Wait for the current operation to finish.") }
|
||
guard let startupStore else { throw StartupStore.Failure.unavailable }
|
||
busy = true; defer { busy = false }
|
||
return try await Task.detached(priority: .userInitiated) {
|
||
try startupStore.systemProfile(kind, freshMedia: freshMedia)
|
||
}.value
|
||
}
|
||
@discardableResult func loadSystemProfile(_ kind: SystemProfile) async -> Bool {
|
||
guard !busy, !diskSaving, state != .closed else { return false }
|
||
await loadProfile(preparing: { [startupStore] in
|
||
guard let startupStore else { throw StartupStore.Failure.unavailable }
|
||
return try await Task.detached(priority: .userInitiated) { try startupStore.systemProfile(kind) }.value
|
||
}, startRunning: true, builtInNitros9: kind == .nitros9)
|
||
let succeeded = profileError == nil && fileError == nil
|
||
if succeeded { guideRequest = GuideRequest(profile: kind) }
|
||
return succeeded
|
||
}
|
||
private func startDiskMonitor() {
|
||
diskMonitor = Task { [weak self] in
|
||
while !Task.isCancelled {
|
||
do { try await Task.sleep(nanoseconds: 250_000_000) } catch { return }
|
||
if self == nil { return }
|
||
self?.poll()
|
||
self?.startAutomaticDiskSave()
|
||
}
|
||
}
|
||
}
|
||
private var polling = false
|
||
private var imageGeneration: UInt64 = 0
|
||
private var imageRevision: UInt64 = 0
|
||
|
||
private func accept(_ snapshot: VCCMachineSnapshot) {
|
||
diskEditorLocked = snapshot.diskEditorLocked
|
||
printer.observe(snapshot)
|
||
let basic = BASICDebugState(attached: snapshot.basicDebugAttached,
|
||
line: snapshot.basicStoppedLine >= 0 ? snapshot.basicStoppedLine : nil,
|
||
sourceRange: snapshot.basicSourceOffset >= 0 ? NSRange(location: snapshot.basicSourceOffset, length: Int(snapshot.basicSourceLength)) : nil,
|
||
stepping: snapshot.basicStepping,
|
||
status: snapshot.basicDebugStatus, generation: snapshot.generation,
|
||
paused: snapshot.state == .paused,
|
||
cycles: snapshot.state == .paused ? snapshot.cycles : 0,
|
||
atPrompt: snapshot.state == .paused && snapshot.programCounter == 0xac7c,
|
||
canStepOut: snapshot.basicCanStepOut,
|
||
errorLine: snapshot.basicErrorLine >= 0 ? snapshot.basicErrorLine : nil,
|
||
errorCode: snapshot.basicErrorCode)
|
||
if basic != basicDebug { basicDebug = basic }
|
||
pasteRemaining = Int(snapshot.pasteRemaining)
|
||
#if VCC_UI_TESTING
|
||
uiTestSession = "\(snapshot.generation),\(snapshot.frames),\(snapshot.audioStarts)"
|
||
#endif
|
||
if snapshot.generation != imageGeneration { binaryName = nil }
|
||
videoOutput = DisplayOutput(rawValue: snapshot.videoOutput) ?? .composite
|
||
settings = MachineSettings(use6309: snapshot.use6309, ram: Int(snapshot.ramConfiguration),
|
||
overclock: Int(snapshot.cpuOverclock), frameInterval: Int(snapshot.frameInterval),
|
||
fastForward: snapshot.fastForward)
|
||
driveWireEnabled = snapshot.driveWireEnabled
|
||
assemblyAttached = snapshot.debuggerAssemblyAttached
|
||
assemblyMappingFingerprint = snapshot.debuggerMappingFingerprint
|
||
programRevision = snapshot.debuggerProgramRevision
|
||
macShellRequestID = snapshot.macShellRequestID
|
||
if macShellStatus != snapshot.macShellStatus { macShellStatus = snapshot.macShellStatus }
|
||
audioEnabled = snapshot.audioEnabled
|
||
tapeMounted = snapshot.tapeMounted; tapeDirty = snapshot.tapeDirty
|
||
tapeMotor = snapshot.tapeMotor; tapeMode = snapshot.tapeMode
|
||
tapeFast = snapshot.tapeFast; tapeWAV = snapshot.tapeWAV
|
||
tapePosition = snapshot.tapePosition; tapeLength = snapshot.tapeLength
|
||
cartridgeNames = snapshot.cartridgeNames; romSlot = Int(snapshot.romSlot); ioSlot = Int(snapshot.ioSlot)
|
||
if sdcDriveNames != snapshot.sdcDriveNames { sdcDriveNames = snapshot.sdcDriveNames }
|
||
if sdcReadOnly != snapshot.sdcReadOnly { sdcReadOnly = snapshot.sdcReadOnly }
|
||
if sdcDirectory != snapshot.sdcDirectory { sdcDirectory = snapshot.sdcDirectory }
|
||
if sdcReadCount != snapshot.sdcReadCount { sdcReadCount = snapshot.sdcReadCount }
|
||
if sdcWriteCount != snapshot.sdcWriteCount { sdcWriteCount = snapshot.sdcWriteCount }
|
||
if sdcError != snapshot.sdcError { sdcError = snapshot.sdcError }
|
||
diskConnected = snapshot.diskConnected
|
||
hardDisks = snapshot.hardDisks; hardDiskConnected = snapshot.hardDiskConnected
|
||
hardSelectedDrive = Int(snapshot.hardSelectedDrive); hardSector = snapshot.hardSector; hardStatus = snapshot.hardStatus
|
||
hardFlushRequests = snapshot.hardFlushRequests
|
||
diskEnabled = snapshot.diskEnabled; diskBusy = snapshot.diskBusy; diskMotor = snapshot.diskMotor
|
||
diskROMName = snapshot.diskROMName; diskSelectedDrive = snapshot.diskSelectedDrive
|
||
diskTrack = snapshot.diskTrack; diskSector = snapshot.diskSector; disks = snapshot.disks
|
||
let now = ProcessInfo.processInfo.systemUptime
|
||
var activity: [ActivityTracker.State] = []
|
||
for (i, disk) in (snapshot.disks + snapshot.hardDisks).enumerated() {
|
||
activity.append(activityTrackers[i].update(reads: disk.readEvents, writes: disk.writeEvents, mounted: disk.mounted,
|
||
running: snapshot.state == .running, now: now))
|
||
}
|
||
activity.append(activityTrackers[6].update(reads: snapshot.tapeReadEvents, writes: snapshot.tapeWriteEvents,
|
||
mounted: snapshot.tapeMounted, running: snapshot.state == .running, now: now))
|
||
let sdcActivity = sdcActivityTracker.update(reads: snapshot.sdcReadCount, writes: snapshot.sdcWriteCount,
|
||
mounted: snapshot.sdcDriveNames.contains { !$0.isEmpty }, running: snapshot.state == .running, now: now)
|
||
let nextHardware = HardwareState(snapshot: snapshot, activities: activity, sdcActivity: sdcActivity)
|
||
if hardware != nextHardware { hardware = nextHardware }
|
||
state = snapshot.state
|
||
frames = snapshot.frames
|
||
error = snapshot.errorMessage
|
||
guard snapshot.pixels != nil else {
|
||
pixels = nil; activeVideoRect = VideoGeometry.fullFrame; imageGeneration = snapshot.generation; imageRevision = 0
|
||
return
|
||
}
|
||
if pixels == nil || imageGeneration != snapshot.generation || imageRevision != snapshot.pixelRevision {
|
||
pixels = snapshot.pixels
|
||
activeVideoRect = VideoGeometry.validated(snapshot.activeVideoRect)
|
||
imageGeneration = snapshot.generation; imageRevision = snapshot.pixelRevision
|
||
}
|
||
}
|
||
|
||
private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void,
|
||
onSuccess: (() -> Void)? = nil) {
|
||
guard !diskEditorLocked else { fileError = "Close the Disk Image Editor before changing the CoCo or its media."; return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
operation { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(snapshot); self?.busy = false
|
||
if snapshot.errorMessage == nil { onSuccess?() }
|
||
if snapshot.state == .running { self?.focusRequest += 1 }
|
||
}
|
||
}
|
||
}
|
||
/// Includes folders because an SDC owns every file beneath its assigned folder.
|
||
var diskEditorReferences: [URL] { developmentAssignedMediaURLs }
|
||
private static func diskEditorSameFile(_ first: URL, _ second: URL) -> Bool {
|
||
let a = first.standardizedFileURL.resolvingSymlinksInPath()
|
||
let b = second.standardizedFileURL.resolvingSymlinksInPath()
|
||
if a.path == b.path { return true }
|
||
let aa = try? FileManager.default.attributesOfItem(atPath: a.path)
|
||
let bb = try? FileManager.default.attributesOfItem(atPath: b.path)
|
||
guard let inode = aa?[.systemFileNumber] as? NSNumber,
|
||
let volume = aa?[.systemNumber] as? NSNumber else { return false }
|
||
return inode == bb?[.systemFileNumber] as? NSNumber && volume == bb?[.systemNumber] as? NSNumber
|
||
}
|
||
func diskEditorSourceIsAssigned(_ url: URL) -> Bool {
|
||
let path = url.standardizedFileURL.resolvingSymlinksInPath().path
|
||
return diskEditorReferences.contains { reference in
|
||
let resolved = reference.standardizedFileURL.resolvingSymlinksInPath()
|
||
let type = (try? FileManager.default.attributesOfItem(atPath: resolved.path))?[.type] as? FileAttributeType
|
||
return Self.diskEditorSameFile(url, reference) ||
|
||
(type == .typeDirectory && path.hasPrefix(resolved.path + "/"))
|
||
}
|
||
}
|
||
func mountedEditorDrive(for url: URL) -> Int? {
|
||
(0..<4).first { drive in
|
||
guard disks.indices.contains(drive), disks[drive].mounted,
|
||
let source = diskBackings[drive]?.url ?? diskAssignments.drives[drive]?.url else { return false }
|
||
return Self.diskEditorSameFile(url, source)
|
||
}
|
||
}
|
||
func mountedHardDiskEditorDrive(for url: URL) -> Int? {
|
||
(0..<2).first { drive in
|
||
guard hardDisks.indices.contains(drive), hardDisks[drive].mounted,
|
||
let source = hardBackings[drive]?.url ?? hardSettings.drives[drive]?.url else { return false }
|
||
return Self.diskEditorSameFile(url, source)
|
||
}
|
||
}
|
||
private func diskEditorAliasRestriction(_ drive: Int, source: URL?, hardDisk: Bool = false) -> String? {
|
||
guard let source else { return nil }
|
||
let otherFloppies = (0..<4).filter { hardDisk || $0 != drive }.compactMap { diskBackings[$0]?.url ?? diskAssignments.drives[$0]?.url }
|
||
let otherHardDisks = (0..<2).filter { !hardDisk || $0 != drive }.flatMap { [hardSettings.drives[$0]?.url, hardBackings[$0]?.url].compactMap { $0 } }
|
||
let otherReferences = otherFloppies + otherHardDisks + [cassetteURL, systemROMURL, diskAssignments.rom].compactMap { $0 } +
|
||
cartridgeAssignments.slots.flatMap { [$0.url, $0.speechROMURL, $0.sdcFolderURL].compactMap { $0 } }
|
||
let path = source.standardizedFileURL.resolvingSymlinksInPath().path
|
||
for reference in otherReferences {
|
||
let resolved = reference.standardizedFileURL.resolvingSymlinksInPath()
|
||
let type = (try? FileManager.default.attributesOfItem(atPath: resolved.path))?[.type] as? FileAttributeType
|
||
if Self.diskEditorSameFile(source, reference) || (type == .typeDirectory && path.hasPrefix(resolved.path + "/")) {
|
||
return "This file is also assigned elsewhere in the machine. Save an edited copy instead, or close the editor and remove the other assignment first."
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
/// Export owns the media-command guard through the coordinated write.
|
||
/// An editor lease is allowed here because exporting never changes it.
|
||
func saveDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?,
|
||
replacing expected: Data? = nil, requireNew: Bool = false) async throws {
|
||
try await writeDiskEditorExport(data, to: url, protecting: sourceURL,
|
||
replacing: expected, requireNew: requireNew, receivedPromise: false)
|
||
}
|
||
func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?,
|
||
replacing expected: Data? = nil, requireNew: Bool = false) async throws {
|
||
try await writeDiskEditorExport(data, to: url, protecting: sourceURL,
|
||
replacing: expected, requireNew: requireNew, receivedPromise: false,
|
||
maximum: DiskEditorIO.imageLimit)
|
||
}
|
||
/// Only the file-promise delegate uses the receiver's already-coordinated
|
||
/// destination. Keep the media guard held until the actual write completes.
|
||
func savePromisedDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?) async throws {
|
||
try await writeDiskEditorExport(data, to: url, protecting: sourceURL,
|
||
replacing: nil, requireNew: true, receivedPromise: true)
|
||
}
|
||
private func writeDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?,
|
||
replacing expected: Data?, requireNew: Bool, receivedPromise: Bool, maximum: Int = DiskEditorIO.limit) async throws {
|
||
DiskEditorPromiseDiagnostics.record("machine export entered busy=\(busy)")
|
||
guard !busy, !diskSaving, state != .closed else {
|
||
throw ProfileFailure.message("Wait for the current disk operation before exporting files.")
|
||
}
|
||
busy = true; defer { busy = false }
|
||
let references = diskEditorReferences + [sourceURL].compactMap { $0 }
|
||
try await Task.detached(priority: .userInitiated) {
|
||
if FileManager.default.fileExists(atPath: url.path), !FileManager.default.isWritableFile(atPath: url.path) {
|
||
throw ProfileFailure.message("This destination is read only. Choose a separate writable file.")
|
||
}
|
||
if receivedPromise {
|
||
DiskEditorPromiseDiagnostics.record("machine detached receiver-coordinated export")
|
||
try DiskFiles.writeReceivedFilePromise(data, to: url, protecting: references)
|
||
} else {
|
||
try DiskEditorIO.write(data, to: url, protecting: references, allowEmpty: true,
|
||
replacing: expected, requireNew: requireNew, maximum: maximum)
|
||
}
|
||
}.value
|
||
}
|
||
/// Offline replacement owns the model's media-command guard until the
|
||
/// coordinated compare-and-swap completes; the guest keeps running.
|
||
func saveOfflineDiskEditor(_ data: Data, to url: URL, replacing original: Data) async throws {
|
||
guard !busy, !diskSaving, !diskEditorLocked, state != .closed else {
|
||
throw ProfileFailure.message("Wait for the current machine or disk edit operation to finish.")
|
||
}
|
||
busy = true; defer { busy = false }
|
||
let references = diskEditorReferences
|
||
try await Task.detached(priority: .userInitiated) {
|
||
let source = try DiskEditorIO.readImage(url)
|
||
guard !source.readOnly else { throw ProfileFailure.message("This source file is read only. Save an edited copy instead.") }
|
||
try DiskEditorIO.write(data, to: url, protecting: references, replacing: original, maximum: DiskEditorIO.imageLimit)
|
||
}.value
|
||
}
|
||
func beginDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession {
|
||
guard !busy, !diskEditorLocked, state != .closed, (0..<4).contains(drive) else {
|
||
throw ProfileFailure.message("Wait for the current operation or disk editor to finish.")
|
||
}
|
||
busy = true; inputEpoch += 1; defer { busy = false }
|
||
if let task = diskSaveTask { await task.value }
|
||
// Flush existing automatic saves before taking the immutable edit lease.
|
||
await saveAutomaticDisks()
|
||
// Let an already-running transfer finish; never reset or advance a paused transfer.
|
||
for _ in 0..<100 {
|
||
let snapshot = await diskStep(controller.snapshot)
|
||
if !snapshot.diskBusy || snapshot.state != .running { break }
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
let (capture, snapshot): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.beginDiskEditor(inDrive: drive) { continuation.resume(returning: ($0, $1)) }
|
||
}
|
||
accept(snapshot)
|
||
guard let capture else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not open this disk for editing.") }
|
||
let backing = diskBackings[drive]
|
||
var restriction = capture.canApply ? nil : "This disk is write protected or its source is read only. Save an edited copy instead."
|
||
restriction = restriction ?? diskEditorAliasRestriction(drive, source: backing?.url)
|
||
if let backing, restriction == nil {
|
||
let valid = await Task.detached(priority: .userInitiated) {
|
||
(try? DiskFiles.readImage(backing.url)).map { $0.data == backing.bytes && !$0.readOnly } ?? false
|
||
}.value
|
||
if !valid { restriction = "The source file changed, disappeared or became read only. Save an edited copy instead." }
|
||
}
|
||
let session = DiskEditorSession(id: UUID(), token: capture.token, drive: drive, name: capture.name,
|
||
data: capture.data, canApply: restriction == nil, sourceURL: backing?.url,
|
||
temporary: diskTemporary[drive], applyRestriction: restriction)
|
||
activeDiskEditor = session; diskEditorBacking = backing; hardDiskEditorBacking = nil
|
||
return session
|
||
}
|
||
func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession {
|
||
guard !busy, !diskEditorLocked, state != .closed, (0..<2).contains(drive) else {
|
||
throw ProfileFailure.message("Wait for the current operation or disk editor to finish.")
|
||
}
|
||
busy = true; inputEpoch += 1; defer { busy = false }
|
||
if let task = diskSaveTask { await task.value }
|
||
await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true)
|
||
for _ in 0..<100 {
|
||
let snapshot = await diskStep(controller.snapshot)
|
||
if !snapshot.diskBusy || snapshot.state != .running { break }
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
let (capture, snapshot): (VCCDiskEditCapture?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.beginHardDiskEditor(inDrive: drive) { continuation.resume(returning: ($0, $1)) }
|
||
}
|
||
accept(snapshot)
|
||
guard let capture else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not open this hard disk for editing.") }
|
||
let backing = hardBackings[drive]
|
||
var restriction = capture.canApply ? nil : "This disk is write protected or its source is read only. Save an edited copy instead."
|
||
restriction = restriction ?? diskEditorAliasRestriction(drive, source: backing?.url, hardDisk: true)
|
||
if let backing, restriction == nil {
|
||
let valid = await Task.detached(priority: .userInitiated) {
|
||
(try? HardDiskFiles.readImage(backing.url)).map { $0.digest == backing.digest && !$0.readOnly } ?? false
|
||
}.value
|
||
if !valid { restriction = "The source file changed, disappeared or became read only. Save an edited copy instead." }
|
||
}
|
||
let session = DiskEditorSession(id: UUID(), token: capture.token, drive: drive, name: capture.name,
|
||
data: capture.data, canApply: restriction == nil, sourceURL: backing?.url,
|
||
temporary: hardTemporary[drive], applyRestriction: restriction, hardDisk: true)
|
||
activeDiskEditor = session; diskEditorBacking = nil; hardDiskEditorBacking = backing
|
||
return session
|
||
}
|
||
private func requireDiskEditor(_ session: DiskEditorSession) throws {
|
||
guard activeDiskEditor?.id == session.id, activeDiskEditor?.token == session.token,
|
||
activeDiskEditor?.drive == session.drive, activeDiskEditor?.hardDisk == session.hardDisk, diskEditorLocked else {
|
||
throw ProfileFailure.message("This disk edit session has ended. Reopen the disk to edit it.")
|
||
}
|
||
}
|
||
func cancelDiskEditor(_ session: DiskEditorSession) async throws {
|
||
try requireDiskEditor(session)
|
||
guard !busy else { throw ProfileFailure.message("Wait for the current disk edit operation to finish.") }
|
||
busy = true; defer { busy = false }
|
||
let result = await diskStep { controller.cancelDiskEditor(token: session.token, completion: $0) }
|
||
if let error = result.errorMessage { throw ProfileFailure.message(error) }
|
||
activeDiskEditor = nil; diskEditorBacking = nil; hardDiskEditorBacking = nil
|
||
}
|
||
func applyDiskEditor(_ session: DiskEditorSession, data: Data, restartConfirmed: Bool) async throws {
|
||
try requireDiskEditor(session)
|
||
guard !busy, !diskSaving else { throw ProfileFailure.message("Wait for the current disk operation to finish.") }
|
||
guard session.canApply else { throw ProfileFailure.message(session.applyRestriction ?? "Save an edited copy of this disk instead.") }
|
||
guard restartConfirmed else { throw ProfileFailure.message("Confirm the cold restart before applying disk edits.") }
|
||
if let restriction = diskEditorAliasRestriction(session.drive, source: session.sourceURL, hardDisk: session.hardDisk) { throw ProfileFailure.message(restriction) }
|
||
guard !printer.unsaved, !printer.saving else { throw ProfileFailure.message("Save the captured printer output before applying edits and restarting the CoCo.") }
|
||
guard !tapeDirty, tapeMode != 2,
|
||
!disks.enumerated().contains(where: { (session.hardDisk || $0.offset != session.drive) && $0.element.dirty }),
|
||
!hardDisks.enumerated().contains(where: { (!session.hardDisk || $0.offset != session.drive) && $0.element.dirty }) else {
|
||
throw ProfileFailure.message("Save or export changes on the other media before applying edits and restarting the CoCo.")
|
||
}
|
||
busy = true; inputEpoch += 1; defer { busy = false }
|
||
let (prepared, validation): (Bool, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.prepareDiskEditor(token: session.token, data: data) { continuation.resume(returning: ($0, $1)) }
|
||
}
|
||
accept(validation)
|
||
guard prepared else { throw ProfileFailure.message(validation.errorMessage ?? "The edited disk could not be validated.") }
|
||
let backing = diskEditorBacking
|
||
let hardBacking = hardDiskEditorBacking
|
||
var sourceSaved = false
|
||
var hardDigest: String?
|
||
var hardSourceBeforeWrite: Data?
|
||
if session.hardDisk, let hardBacking, !session.temporary {
|
||
let plan = try await Task.detached(priority: .userInitiated) {
|
||
// Include guest writes not yet acknowledged by automatic save,
|
||
// not just the differences from the editor's initial snapshot.
|
||
let source = try HardDiskFiles.readImage(hardBacking.url)
|
||
guard source.digest == hardBacking.digest else { throw HardDiskFiles.Failure.changed }
|
||
guard !source.readOnly, source.data.count <= data.count, data.count % 256 == 0 else { throw HardDiskFiles.Failure.patch }
|
||
var patches = Data()
|
||
for position in stride(from: 0, to: data.count, by: 256) where
|
||
position >= source.data.count || source.data[position..<(position + 256)] != data[position..<(position + 256)] {
|
||
let sector = UInt32(position / 256)
|
||
patches.append(contentsOf: (0..<4).map { UInt8(truncatingIfNeeded: sector >> ($0 * 8)) })
|
||
patches.append(data[position..<(position + 256)])
|
||
}
|
||
return (patches, source.data)
|
||
}.value
|
||
hardSourceBeforeWrite = plan.1
|
||
hardDigest = try await automaticHardDiskWriter(plan.0, data.count, hardBacking.url, hardBacking.digest)
|
||
sourceSaved = true
|
||
} else if let backing, !session.temporary {
|
||
try await automaticDiskWriter(data, backing.url, backing.bytes)
|
||
sourceSaved = true
|
||
}
|
||
let (applied, snapshot): (Bool, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.commitDiskEditor(token: session.token, restartConfirmed: restartConfirmed, sourceSaved: sourceSaved) {
|
||
continuation.resume(returning: ($0, $1))
|
||
}
|
||
}
|
||
accept(snapshot)
|
||
guard applied else {
|
||
if sourceSaved, let hardBacking, hardDigest != nil {
|
||
do {
|
||
let baseline = hardSourceBeforeWrite
|
||
try await Task.detached(priority: .userInitiated) {
|
||
// Reconstruct the original source from the save's
|
||
// retained baseline; guest bytes remain in the lease.
|
||
guard let baseline else { throw HardDiskFiles.Failure.patch }
|
||
try DiskEditorIO.write(baseline, to: hardBacking.url, protecting: [], replacing: data,
|
||
maximum: DiskEditorIO.imageLimit)
|
||
}.value
|
||
} catch { throw ProfileFailure.message("The CoCo retained its original disk, but restoring the source file failed: \(error.localizedDescription). Keep an edited copy and check the source file before continuing.") }
|
||
} else if sourceSaved, let backing {
|
||
do { try await automaticDiskWriter(backing.bytes, backing.url, data) }
|
||
catch { throw ProfileFailure.message("The CoCo retained its original disk, but restoring the source file failed: \(error.localizedDescription). Keep an edited copy and check the source file before continuing.") }
|
||
}
|
||
throw ProfileFailure.message(snapshot.errorMessage ?? "Could not apply the edited disk.")
|
||
}
|
||
if sourceSaved {
|
||
if session.hardDisk {
|
||
if let hardDigest { hardBackings[session.drive]?.digest = hardDigest }
|
||
hardSaveErrors[session.drive] = nil
|
||
// A filesystem edit invalidates any previous shell trust digest.
|
||
if session.drive == 0 { savedShellGrant = nil }
|
||
} else { diskBackings[session.drive]?.bytes = data; diskSaveErrors[session.drive] = nil }
|
||
}
|
||
activeDiskEditor = nil; diskEditorBacking = nil; hardDiskEditorBacking = nil; binaryName = nil; deniedShellGeneration = nil
|
||
// Native C/BASIC documents and drafts are independent and remain intact.
|
||
}
|
||
func saveDiskAssignments() {
|
||
do { try diskStore.save(diskAssignments); diskSettingsError = nil; diskSettingsNeedsSave = false }
|
||
catch {
|
||
diskSettingsNeedsSave = true
|
||
diskSettingsError = "Could not remember disk choices: \(error.localizedDescription). Your mounted disks are unchanged. Retry Saving before quitting."
|
||
}
|
||
}
|
||
private func rememberDrive(_ drive: Int, url: URL?) {
|
||
diskAssignments.drives[drive] = url.map {
|
||
DiskAssignments.Drive(url: $0, writeProtected: disks[drive].writeProtected, temporary: diskTemporary[drive])
|
||
}
|
||
diskRestoreErrors[drive] = nil
|
||
saveDiskAssignments()
|
||
}
|
||
private func setBacking(_ drive: Int, url: URL?, bytes: Data = Data()) {
|
||
diskBackings[drive] = url.map { Backing(url: $0.resolvingSymlinksInPath(), bytes: bytes) }
|
||
diskSaveErrors[drive] = nil
|
||
}
|
||
func setDiskTemporary(_ drive: Int, _ value: Bool) {
|
||
guard !busy, !diskSaving, (0..<4).contains(drive) else { return }
|
||
command(controller.pauseForDiskChange, onSuccess: { [self] in
|
||
diskTemporary[drive] = value
|
||
if let url = diskAssignments.drives[drive]?.url { rememberDrive(drive, url: url) }
|
||
})
|
||
}
|
||
func retryDiskSave(_ drive: Int) {
|
||
guard !busy, !diskSaving else { return }
|
||
diskSaveErrors[drive] = nil; startAutomaticDiskSave()
|
||
}
|
||
private func startAutomaticDiskSave() {
|
||
guard !busy, !diskSaving, !diskEditorLocked, state != .closed else { return }
|
||
guard disks.indices.contains(where: { disks[$0].dirty && !disks[$0].writeProtected && !disks[$0].sourceReadOnly && diskBackings[$0] != nil && !diskTemporary[$0] && diskSaveErrors[$0] == nil }) || (hardNeedsSaving && (Date() >= nextHardSave || hardFlushRequests != savedHardFlushRequests)) else { return }
|
||
diskSaving = true
|
||
diskSaveTask = Task { @MainActor in
|
||
await saveAutomaticDisks()
|
||
diskSaving = false; diskSaveTask = nil
|
||
}
|
||
}
|
||
private func saveAutomaticDisks() async {
|
||
for drive in 0..<4 {
|
||
guard !diskTemporary[drive], diskSaveErrors[drive] == nil, let backing = diskBackings[drive] else { continue }
|
||
let (data, token, snapshot): (Data?, UInt64, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.captureDiskForSaving(inDrive: drive) { continuation.resume(returning: ($0, $1, $2)) }
|
||
}
|
||
accept(snapshot)
|
||
guard let data else { continue }
|
||
do {
|
||
try await automaticDiskWriter(data, backing.url, backing.bytes)
|
||
// The host now contains this snapshot, even if the guest wrote
|
||
// newer sectors during I/O and the acknowledgement stays dirty.
|
||
diskBackings[drive]?.bytes = data
|
||
_ = await diskStep { controller.acknowledgeDiskSave(inDrive: drive, token: token, completion: $0) }
|
||
} catch {
|
||
diskSaveErrors[drive] = "Drive \(drive) could not save: \(error.localizedDescription)"
|
||
_ = await diskStep(controller.pause)
|
||
}
|
||
}
|
||
await saveAutomaticHardDisks()
|
||
}
|
||
private func diskStep(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
||
let snapshot = await withCheckedContinuation { continuation in
|
||
operation { continuation.resume(returning: $0) }
|
||
}
|
||
accept(snapshot)
|
||
return snapshot
|
||
}
|
||
func retryRememberedDisks() {
|
||
guard !busy, !diskSaving else { return }
|
||
busy = true; inputEpoch += 1
|
||
Task { @MainActor in await restoreDisks(); busy = false }
|
||
}
|
||
private func restoreDisks() async {
|
||
diskRestoreErrors = [:]
|
||
guard let rom = diskAssignments.rom else { return }
|
||
let paused = await diskStep(controller.pauseForDiskChange)
|
||
guard paused.errorMessage == nil else {
|
||
diskRestoreErrors[-1] = paused.errorMessage; return
|
||
}
|
||
if !diskEnabled {
|
||
do {
|
||
let bytes = try await Task.detached { try DiskFiles.readROM(rom) }.value
|
||
let result = await diskStep { controller.loadDiskROM(bytes, name: rom.lastPathComponent, completion: $0) }
|
||
if let error = result.errorMessage { throw NSError(domain: "VCC", code: 1, userInfo: [NSLocalizedDescriptionKey: error]) }
|
||
} catch {
|
||
diskRestoreErrors[-1] = "Disk ROM \(rom.lastPathComponent): \(error.localizedDescription)"; return
|
||
}
|
||
}
|
||
for drive in 0..<4 {
|
||
// Retry never replaces a mounted disk, including unexported guest writes.
|
||
guard !disks[drive].mounted, let saved = diskAssignments.drives[drive] else { continue }
|
||
do {
|
||
let image = try await Task.detached { try DiskFiles.readImage(saved.url) }.value
|
||
var result = await diskStep {
|
||
controller.mountDisk(image.data, drive: drive, name: saved.url.lastPathComponent,
|
||
readOnly: image.readOnly, completion: $0)
|
||
}
|
||
if result.errorMessage == nil && saved.writeProtected && !result.disks[drive].writeProtected {
|
||
result = await diskStep { controller.setDiskWriteProtected(true, drive: drive, completion: $0) }
|
||
}
|
||
if let error = result.errorMessage { throw NSError(domain: "VCC", code: 1, userInfo: [NSLocalizedDescriptionKey: error]) }
|
||
setBacking(drive, url: saved.url, bytes: image.data)
|
||
diskTemporary[drive] = saved.temporary
|
||
} catch { diskRestoreErrors[drive] = "Drive \(drive), \(saved.url.lastPathComponent): \(error.localizedDescription)" }
|
||
}
|
||
}
|
||
func forgetUnavailableDisks() {
|
||
guard !busy, !diskSaving, !diskEnabled else { return }
|
||
let alert = NSAlert(); alert.messageText = "Forget the remembered disk setup?"
|
||
alert.informativeText = "This removes the remembered disk ROM and drive assignments. The files will not be changed."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Forget")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
diskAssignments.rom = nil; diskAssignments.drives = Array(repeating: nil, count: 4)
|
||
diskRestoreErrors = [:]; saveDiskAssignments()
|
||
}
|
||
func loadDiagnostic() {
|
||
binaryName = nil; systemROMURL = nil; profileName = nil; bootNitros9 = false
|
||
title = "Diagnostic preview"; fileError = nil
|
||
busy = true; inputEpoch += 1
|
||
Task { @MainActor in
|
||
defer { busy = false }
|
||
let result = await diskStep { controller.loadDiagnostic(use6309: use6309, completion: $0) }
|
||
if result.errorMessage == nil { _ = await applyDriveWireDefault(false) }
|
||
}
|
||
}
|
||
var canPaste: Bool { state == .running && !busy && pasteRemaining == 0 }
|
||
func pasteClipboard(_ mode: CocoPaste.Mode = .text) {
|
||
guard canPaste else { return }
|
||
guard let text = NSPasteboard.general.string(forType: .string) else {
|
||
fileError = "The clipboard does not contain text."; return
|
||
}
|
||
do {
|
||
let paste = try CocoPaste(text, mode: mode)
|
||
if mode != .text {
|
||
let alert = NSAlert()
|
||
alert.messageText = mode == .newBASIC ? "Replace the BASIC program?" : "Merge BASIC lines?"
|
||
alert.informativeText = (mode == .newBASIC
|
||
? "This types NEW, clearing the program in CoCo memory, then enters the clipboard's numbered lines. Saved files are kept."
|
||
: "This enters the clipboard's numbered lines into the current program. Matching line numbers are replaced; a line number alone deletes that line.")
|
||
+ " Make sure the computer is waiting at the BASIC prompt. Nothing is run automatically. Cancel Paste or Pause stops further typing, but cannot undo lines already entered."
|
||
alert.addButton(withTitle: "Cancel")
|
||
alert.addButton(withTitle: mode == .newBASIC ? "Replace and Paste" : "Merge and Paste")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
}
|
||
startPaste(paste)
|
||
} catch { fileError = error.localizedDescription }
|
||
}
|
||
func startPaste(_ paste: CocoPaste) {
|
||
guard canPaste else { return }
|
||
command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) }
|
||
}
|
||
func cancelPaste() { command(controller.cancelPaste) }
|
||
func copyScreenText() {
|
||
guard !busy, state == .running || state == .paused else { return }
|
||
controller.copyScreenText { [weak self] text, snapshot in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(snapshot)
|
||
guard let text else { return }
|
||
NSPasteboard.general.clearContents()
|
||
NSPasteboard.general.setString(text, forType: .string)
|
||
}
|
||
}
|
||
}
|
||
func setKeyboard(_ mask: UInt64) { controller.setKeyboardMask(mask) }
|
||
// UI confirms CPU/RAM changes before calling this method. The controller
|
||
// checks active disk writes and recordings again on its serial queue.
|
||
func applyMachineSettings(_ value: MachineSettings) {
|
||
guard !busy, !diskSaving, state != .closed, value.valid else { return }
|
||
command({ controller.configureMachine(use6309: value.use6309, ram: value.ram,
|
||
overclock: value.overclock, frameInterval: value.frameInterval,
|
||
fastForward: value.fastForward, completion: $0) }, onSuccess: { [self] in
|
||
value.save(in: displayDefaults)
|
||
})
|
||
}
|
||
func setFastForward(_ enabled: Bool) {
|
||
var next = settings; next.fastForward = enabled; applyMachineSettings(next)
|
||
}
|
||
func openROM() {
|
||
guard !busy else { return }
|
||
busy = true; inputEpoch += 1; controller.setKeyboardMask(0)
|
||
let panel = NSOpenPanel()
|
||
panel.title = "Open CoCo 3 System ROM"
|
||
panel.message = "Select an alternative 32 KiB CoCo 3 system ROM. This choice is remembered. Bundled ROMs can be restored from Settings when available."
|
||
panel.allowedContentTypes = [UTType(filenameExtension: "rom") ?? .data, .data]
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false
|
||
panel.allowsMultipleSelection = false
|
||
panel.begin { [weak self] result in
|
||
guard let self else { return }
|
||
guard result == .OK, let url = panel.url else { self.busy = false; return }
|
||
self.busy = true; self.fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let data = try await Task.detached(priority: .userInitiated) { try ROMImage.read(url) }.value
|
||
self.installROM(data, url: url)
|
||
} catch { self.fileError = error.localizedDescription; self.busy = false }
|
||
}
|
||
}
|
||
}
|
||
func installROM(_ data: Data, url: URL) {
|
||
busy = true; inputEpoch += 1
|
||
controller.loadROM(data, use6309: use6309) { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.accept(snapshot)
|
||
guard snapshot.errorMessage == nil else { self.busy = false; return }
|
||
self.title = url.lastPathComponent; self.systemROMURL = url; self.profileName = nil
|
||
self.binaryName = nil; self.bootNitros9 = false
|
||
Task { @MainActor in
|
||
let configured = await self.applyDriveWireDefault(false)
|
||
self.rememberStartup()
|
||
self.recentMedia.record(url, as: .systemROM)
|
||
if configured { self.resume() } else { self.busy = false }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
func openBinary() {
|
||
guard canQuickLoad else { return }
|
||
prepareBinaryLoad { [self] in
|
||
let panel = NSOpenPanel()
|
||
panel.title = "Load CoCo Binary"
|
||
panel.message = "Choose a CoCo block-format .bin program. Loading replaces its memory ranges and starts the program without resetting. Cancel leaves emulation paused."
|
||
panel.allowedContentTypes = [UTType(filenameExtension: "bin") ?? .data]
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
readBinary(url)
|
||
}
|
||
}
|
||
}
|
||
func startReviewedC(_ binary: Data, disk: Data?, name: String, stop: UInt16, expected: VCCMachineSnapshot) async -> VCCMachineSnapshot {
|
||
await diskStep { controller.startReviewedC(binary, disk: disk, name: name, stop: stop, expected: expected, completion: $0) }
|
||
}
|
||
func continueReviewedC(_ expected: VCCMachineSnapshot, name: String, stop: UInt16, bytes: Data) async -> VCCMachineSnapshot {
|
||
await diskStep { controller.continueReviewedC(expected, name: name, stop: stop, bytes: bytes, completion: $0) }
|
||
}
|
||
func ejectReviewedCDisk(_ name: String) async {
|
||
_ = await diskStep { controller.ejectReviewedCDisk(name, completion: $0) }
|
||
}
|
||
func reviewedCOutput() async -> (String?, VCCMachineSnapshot) {
|
||
await withCheckedContinuation { c in controller.inspectScreenText { c.resume(returning: ($0, $1)) } }
|
||
}
|
||
|
||
func mcpReadinessSnapshot() async -> VCCMachineSnapshot {
|
||
await withCheckedContinuation { c in controller.assistantReadiness { c.resume(returning: $0) } }
|
||
}
|
||
|
||
func mcpMachineSnapshot() async -> VCCMachineSnapshot {
|
||
await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
|
||
}
|
||
|
||
func checkReviewedBASIC(_ expected: VCCMachineSnapshot, source: String) async throws -> VCCMachineSnapshot {
|
||
let state = await diskStep { controller.checkReviewedBASIC(expected, source: source, completion: $0) }
|
||
if let message = state.errorMessage { throw ProfileFailure.message(message) }
|
||
return state
|
||
}
|
||
|
||
func mcpScreen(expected: VCCMachineSnapshot, source: String) async throws -> [String: Any] {
|
||
let (screen, snapshot): ([String: Any]?, VCCMachineSnapshot) = await withCheckedContinuation { c in
|
||
controller.assistantScreen(expected: expected, source: source) { c.resume(returning: ($0, $1)) }
|
||
}
|
||
guard let screen, snapshot.errorMessage == nil else {
|
||
throw ProfileFailure.message(snapshot.errorMessage ?? "Guest text is unavailable.")
|
||
}
|
||
return screen.merging(["frame": snapshot.frames, "signal": snapshot.videoOutput, "paste_remaining": Int(snapshot.pasteRemaining)]) { _, new in new }
|
||
}
|
||
|
||
func mcpCompiledGuest(lease: VCCCompiledRunLease, runID: String, expected: VCCMachineSnapshot,
|
||
assembly: Bool, key: NSNumber?, readScreen: Bool, finalScreen: Bool = false) async throws -> [String: Any] {
|
||
let (text, state): (String?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.compiledGuest(lease: lease, runID: runID, expected: expected, assembly: assembly,
|
||
key: key, readScreen: readScreen, finalScreen: finalScreen) {
|
||
continuation.resume(returning: ($0, $1))
|
||
}
|
||
}
|
||
if let error = state.errorMessage { throw ProfileFailure.message(error) }
|
||
guard let text else { return [:] }
|
||
return ["run_id": runID, "text": text, "frame": state.frames, "signal": state.videoOutput,
|
||
"paste_remaining": Int(state.pasteRemaining), "status": state.state == .paused ? "paused" : "running"]
|
||
}
|
||
|
||
func cancelMCPInput(runID: String) { controller.cancelAssistantPaste(runID) }
|
||
|
||
func mcpPaste(_ text: String, runID: String, direct: Bool, expected: VCCMachineSnapshot, source: String) async throws {
|
||
let keys = try CocoPaste(text, mode: .text).chords.map { NSNumber(value: $0) }
|
||
let result = await diskStep { controller.assistantPaste(chords: keys, runID: runID, direct: direct, expected: expected, source: source, completion: $0) }
|
||
if let error = result.errorMessage { throw ProfileFailure.message(error) }
|
||
}
|
||
|
||
func loadBASICSource(_ source: String, run: Bool, breakpoints: Set<Int> = [],
|
||
review: (expected: VCCMachineSnapshot, existing: String)? = nil) async -> VCCMachineSnapshot? {
|
||
guard !busy, !diskSaving, state != .closed else {
|
||
fileError = "The machine is busy. Try the BASIC transfer again when it is ready."
|
||
return nil
|
||
}
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
defer { busy = false }
|
||
let points = breakpoints.sorted().map { NSNumber(value: $0) }
|
||
let result = await diskStep { completion in
|
||
if let review {
|
||
controller.assistantLoad(source: source, breakpoints: points, expected: review.expected, existing: review.existing, completion: completion)
|
||
} else {
|
||
controller.basicLoadSource(source, run: run, breakpoints: points, completion: completion)
|
||
}
|
||
}
|
||
if let error = result.errorMessage { fileError = error; return nil }
|
||
binaryName = nil
|
||
if run { focusRequest += 1 }
|
||
return result
|
||
}
|
||
func configureBASICBreakpoints(_ lines: Set<Int>, source: String) async -> Bool {
|
||
guard !busy, !diskSaving, state != .closed else { return false }
|
||
busy = true; defer { busy = false }
|
||
let snapshot = await diskStep { controller.basicSetBreakpoints(lines.sorted().map { NSNumber(value: $0) }, source: source, completion: $0) }
|
||
return snapshot.errorMessage == nil
|
||
}
|
||
func continueBASIC(source: String) async -> Bool {
|
||
guard !busy, !diskSaving, state == .paused else { return false }
|
||
busy = true; inputEpoch += 1; defer { busy = false }
|
||
let snapshot = await diskStep { controller.basicContinue(source: source, completion: $0) }
|
||
return snapshot.errorMessage == nil
|
||
}
|
||
func stepBASIC(source: String, over: Bool) async -> Bool {
|
||
guard !busy, !diskSaving, state == .paused else { return false }
|
||
busy = true; inputEpoch += 1; defer { busy = false }
|
||
let snapshot = await diskStep { controller.basicStep(source: source, over: over, completion: $0) }
|
||
return snapshot.errorMessage == nil
|
||
}
|
||
func stepOutBASIC(source: String) async -> Bool {
|
||
guard !busy, !diskSaving, state == .paused else { return false }
|
||
busy = true; inputEpoch += 1; defer { busy = false }
|
||
let snapshot = await diskStep { controller.basicStepOut(source: source, completion: $0) }
|
||
return snapshot.errorMessage == nil
|
||
}
|
||
func detachBASICDebug() {
|
||
controller.basicClearDebug { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot) }
|
||
}
|
||
}
|
||
func exportBASICSource(_ source: String, name: String, cassette: Bool) async -> Data? {
|
||
guard !busy, !diskSaving, state != .closed else {
|
||
fileError = "The machine is busy. Try exporting BASIC again when it is ready."
|
||
return nil
|
||
}
|
||
busy = true; fileError = nil
|
||
defer { busy = false }
|
||
let (data, snapshot): (Data?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.basicExportSource(source, name: name, cassette: cassette) { data, snapshot in
|
||
continuation.resume(returning: (data, snapshot))
|
||
}
|
||
}
|
||
accept(snapshot)
|
||
return snapshot.errorMessage == nil ? data : nil
|
||
}
|
||
/// Exporting source creates a separate file; it must never become an implicit
|
||
/// overwrite of an assigned disk, cassette, ROM, SD card file or editor source.
|
||
func writeBASICExport(_ data: Data, to destination: URL, sourceURL: URL?) async throws {
|
||
try await writeDevelopmentFile(data, to: destination, protecting: [sourceURL].compactMap { $0 })
|
||
}
|
||
|
||
func writeDevelopmentFile(_ data: Data, to destination: URL, protecting sources: [URL],
|
||
allowEmpty: Bool = false, replacing expected: Data? = nil) async throws {
|
||
guard !busy, !diskSaving, state != .closed else {
|
||
throw ProfileFailure.message("The machine is busy. Try saving again when the current operation finishes.")
|
||
}
|
||
busy = true
|
||
defer { busy = false }
|
||
let protected = developmentAssignedMediaURLs + sources
|
||
try await Task.detached(priority: .userInitiated) {
|
||
try DiskFiles.writeDevelopmentFile(data, to: destination, protecting: protected, allowEmpty: allowEmpty, replacing: expected)
|
||
}.value
|
||
}
|
||
func inspectBASIC(source: String, stop: BASICDebugState) async -> ([BASICVariable]?, String?) {
|
||
await withCheckedContinuation { continuation in
|
||
controller.basicInspect(source: source) { rows, snapshot in
|
||
guard snapshot.generation == stop.generation, snapshot.cycles == stop.cycles,
|
||
snapshot.state == .paused, snapshot.basicDebugAttached,
|
||
snapshot.basicStoppedLine == (stop.line ?? -1) else {
|
||
continuation.resume(returning: (nil, "The BASIC stop changed. Waiting for the current position.")); return
|
||
}
|
||
let values = rows?.compactMap(BASICVariable.init)
|
||
continuation.resume(returning: (snapshot.errorMessage == nil ? values : nil, snapshot.errorMessage))
|
||
}
|
||
}
|
||
}
|
||
func readBASICSource() async -> String? {
|
||
guard !busy, !diskSaving, state != .closed else {
|
||
fileError = "The machine is busy. Try reading BASIC again when it is ready."
|
||
return nil
|
||
}
|
||
busy = true; fileError = nil
|
||
defer { busy = false }
|
||
let (source, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.basicReadSource { text, snapshot in continuation.resume(returning: (text, snapshot)) }
|
||
}
|
||
accept(snapshot)
|
||
return snapshot.errorMessage == nil ? source : nil
|
||
}
|
||
func loadBinary(_ url: URL) {
|
||
guard canQuickLoad else { return }
|
||
prepareBinaryLoad { [self] in readBinary(url) }
|
||
}
|
||
private func prepareBinaryLoad(_ ready: @escaping () -> Void) {
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
controller.pause { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.accept(snapshot)
|
||
guard snapshot.errorMessage == nil else { self.busy = false; return }
|
||
ready()
|
||
}
|
||
}
|
||
}
|
||
private func readBinary(_ url: URL) {
|
||
Task { @MainActor in
|
||
do {
|
||
let bytes = try await Task.detached(priority: .userInitiated) { try BinaryFile.read(url) }.value
|
||
command({ controller.quickLoadBinary(bytes, completion: $0) }, onSuccess: { [self] in
|
||
binaryName = url.lastPathComponent; recentMedia.record(url, as: .binary)
|
||
})
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func setVideoOutput(_ output: DisplayOutput) {
|
||
command({ controller.setVideoOutput(output.rawValue, completion: $0) }) {
|
||
self.displayDefaults.set(output.rawValue, forKey: DisplayOutput.preferenceKey)
|
||
}
|
||
}
|
||
// The switch records a local override. A profile document can never grant
|
||
// outbound networking, even if it has the same name/ROMs as a system preset.
|
||
private func applyDriveWireDefault(_ builtInNitros9: Bool) async -> Bool {
|
||
self.builtInNitros9 = builtInNitros9
|
||
presetProgramRevision = builtInNitros9 ? programRevision : nil
|
||
let enabled = (displayDefaults.object(forKey: Self.driveWireKey) as? Bool) ?? builtInNitros9
|
||
guard enabled != driveWireEnabled else { return true }
|
||
let result = await diskStep { controller.setDriveWireEnabled(enabled, completion: $0) }
|
||
if let error = result.errorMessage { fileError = error; return false }
|
||
return true
|
||
}
|
||
|
||
func setDriveWireNetworking(_ enabled: Bool) {
|
||
guard !busy, state != .closed else { return }
|
||
command({ controller.setDriveWireEnabled(enabled, completion: $0) }, onSuccess: { [self] in
|
||
displayDefaults.set(enabled, forKey: Self.driveWireKey)
|
||
})
|
||
}
|
||
func setAudio(_ enabled: Bool) {
|
||
command { controller.setAudioEnabled(enabled, volume: Float(volume), completion: $0) }
|
||
}
|
||
func seekTape(_ position: Double) { command { controller.seekTape(UInt64(max(0, position)), completion: $0) } }
|
||
func setFastTape(_ enabled: Bool) { command { controller.setTapeFast(enabled, completion: $0) } }
|
||
func tapeAction(_ action: Int) {
|
||
if action >= 3 && tapeDirty { return }
|
||
if action == 3 { tapeName = "No tape" }
|
||
if action >= 4 { tapeName = action == 4 ? "New recording.cas" : "New recording.wav" }
|
||
command({ controller.tapeAction(action, completion: $0) }, onSuccess: { [self] in
|
||
if action >= 3 { cassetteURL = nil; rememberStartup() }
|
||
})
|
||
}
|
||
func openTape() {
|
||
guard !busy, !tapeDirty else { return }
|
||
fileError = nil
|
||
busy = true; inputEpoch += 1; controller.setKeyboardMask(0)
|
||
let panel = NSOpenPanel()
|
||
panel.title = "Insert Cassette Image"
|
||
panel.allowedContentTypes = [UTType(filenameExtension: "cas") ?? .data, .wav]
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false
|
||
panel.allowsMultipleSelection = false
|
||
panel.begin { [weak self] result in
|
||
guard let self else { return }
|
||
guard result == .OK, let url = panel.url else { self.busy = false; return }
|
||
self.readTape(url)
|
||
|
||
}
|
||
}
|
||
private func readTape(_ url: URL) {
|
||
Task { @MainActor in
|
||
do {
|
||
let data = try await Task.detached(priority: .userInitiated) { try TapeImage.read(url) }.value
|
||
command({ controller.mountTape(data, wav: url.pathExtension.lowercased() == "wav", completion: $0) }, onSuccess: { [self] in
|
||
tapeName = url.lastPathComponent; cassetteURL = url; rememberStartup()
|
||
recentMedia.record(url, as: .cassette)
|
||
})
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func exportTape() {
|
||
guard !busy, tapeMounted else { return }
|
||
busy = true; inputEpoch += 1; controller.setKeyboardMask(0); fileError = nil
|
||
controller.exportTape { [weak self] data, snapshot in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.accept(snapshot)
|
||
guard let data else { self.busy = false; return }
|
||
let panel = NSSavePanel()
|
||
panel.title = "Export Cassette Image"
|
||
panel.allowedContentTypes = [self.tapeWAV ? .wav : UTType(filenameExtension: "cas") ?? .data]
|
||
panel.nameFieldStringValue = self.tapeName
|
||
panel.begin { result in
|
||
guard result == .OK, let url = panel.url else { self.busy = false; return }
|
||
Task { @MainActor in
|
||
do {
|
||
try await Task.detached(priority: .userInitiated) { try data.write(to: url, options: .atomic) }.value
|
||
self.tapeName = url.lastPathComponent
|
||
self.command(self.controller.markTapeSaved, onSuccess: { self.cassetteURL = url; self.rememberStartup() })
|
||
} catch { self.fileError = error.localizedDescription; self.busy = false }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
func discardTape() {
|
||
let alert = NSAlert()
|
||
alert.messageText = "Discard this recording?"
|
||
alert.informativeText = "The unsaved recording will be lost. Export it first to keep a copy."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
tapeName = "No tape"
|
||
command(controller.discardTape, onSuccess: { self.cassetteURL = nil; self.rememberStartup() })
|
||
}
|
||
// Start dialogs only after the worker has frozen a safe, idle disk controller.
|
||
private func diskDialog(_ show: @escaping () -> Void) {
|
||
guard !busy, !diskSaving else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
controller.pauseForDiskChange { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.accept(snapshot)
|
||
guard snapshot.errorMessage == nil else { self.busy = false; return }
|
||
show()
|
||
}
|
||
}
|
||
}
|
||
func openDiskROM() {
|
||
diskDialog { [self] in
|
||
let panel = NSOpenPanel()
|
||
panel.title = "Choose Floppy Disk ROM"
|
||
panel.message = "Select an 8 or 16 KiB disk ROM, such as disk11.rom. This cold-resets the machine and clears its BASIC program. Mounted disks are retained. Press Run afterward."
|
||
panel.allowedContentTypes = [UTType(filenameExtension: "rom") ?? .data, .data]
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false
|
||
panel.allowsMultipleSelection = false
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
selectDiskROM(url)
|
||
}
|
||
}
|
||
}
|
||
func openDisk(_ drive: Int) {
|
||
diskDialog { [self] in
|
||
let panel = NSOpenPanel(); panel.title = "Insert Disk in Drive \(drive)"
|
||
panel.message = "Writable disks save automatically. Enable Temporary changes in the drive controls to keep changes in memory."
|
||
panel.allowedContentTypes = DiskFiles.extensions.map { UTType(filenameExtension: $0) ?? .data }
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
insertDisk(url, drive: drive)
|
||
}
|
||
}
|
||
}
|
||
func selectDiskROM(_ url: URL) {
|
||
guard !diskSaving else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let bytes = try await Task.detached(priority: .userInitiated) { try DiskFiles.readROM(url) }.value
|
||
command({ controller.loadDiskROM(bytes, name: url.lastPathComponent, completion: $0) }, onSuccess: { [self] in
|
||
diskAssignments.rom = url; diskRestoreErrors[-1] = nil
|
||
recentMedia.record(url, as: .diskROM)
|
||
// Preserve existing ROM cartridges. Use the first free slot
|
||
// only when this mode has no floppy assignment yet.
|
||
let indices = cartridgeAssignments.multiPak ? Array(1...4).reversed().map { $0 } : [0]
|
||
if !indices.contains(where: { cartridgeAssignments.slots[$0].kind == .floppy }),
|
||
let free = indices.first(where: { cartridgeAssignments.slots[$0].kind == .empty }) {
|
||
cartridgeAssignments.slots[free].kind = .floppy
|
||
}
|
||
busy = true
|
||
Task { @MainActor in
|
||
_ = await applyCartridges(cartridgeAssignments, bytes: cartridgeBytes)
|
||
diskAssignments.cartridges = cartridgeAssignments; saveDiskAssignments()
|
||
await restoreDisks(); busy = false
|
||
}
|
||
})
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func insertDisk(_ url: URL, drive: Int) {
|
||
guard !diskSaving else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let image = try await Task.detached(priority: .userInitiated) { try DiskFiles.readImage(url) }.value
|
||
command({ controller.mountDisk(image.data, drive: drive, name: url.lastPathComponent, readOnly: image.readOnly, completion: $0) },
|
||
onSuccess: { [self] in setBacking(drive, url: url, bytes: image.data); rememberDrive(drive, url: url); recentMedia.record(url, as: .floppy(drive)) })
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
/// A Finder/drop insertion has an explicit execution policy; mounting alone
|
||
/// never boots a disk or replaces the running guest program.
|
||
func insertDiskFromMedia(_ url: URL, drive: Int, execution: DiskInsertionExecution, reset: DiskInsertionReset = .none) async throws {
|
||
guard !busy, !diskSaving, !diskEditorLocked, state != .closed,
|
||
RecentMedia.isLocalFile(url), (0..<4).contains(drive) else {
|
||
throw ProfileFailure.message("Wait for the current operation before inserting this disk.")
|
||
}
|
||
guard diskConnected else { throw ProfileFailure.message("Connect a floppy controller in Cartridges before inserting this disk.") }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
defer { busy = false }
|
||
let epoch = inputEpoch
|
||
let initial = await diskStep(controller.snapshot)
|
||
_ = try await Task.detached(priority: .userInitiated) { try DiskFiles.readImage(url) }.value
|
||
let current = await diskStep(controller.snapshot)
|
||
guard inputEpoch == epoch, current.generation == initial.generation, !current.diskEditorLocked, current.state != .closed else {
|
||
throw ProfileFailure.message("The machine changed while this disk was being opened. Choose the disk again.")
|
||
}
|
||
let paused = await diskStep(controller.pauseForDiskChange)
|
||
if let error = paused.errorMessage { throw ProfileFailure.message(error) }
|
||
if let pending = diskSaveTask { await pending.value }
|
||
await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true)
|
||
let ready = await diskStep(controller.snapshot)
|
||
guard inputEpoch == epoch, ready.generation == initial.generation, !ready.diskEditorLocked else {
|
||
throw ProfileFailure.message("The machine changed while preparing to insert the disk. Choose it again.")
|
||
}
|
||
guard !unsavedMedia else {
|
||
throw ProfileFailure.message("Save As or export unsaved media before opening another file. The machine is paused; your media and recordings are kept.")
|
||
}
|
||
// Automatic saving can update the very file being inserted. Read its
|
||
// final bytes after flushing, then recheck machine identity before mount.
|
||
let image = try await Task.detached(priority: .userInitiated) { try DiskFiles.readImage(url) }.value
|
||
let final = await diskStep(controller.snapshot)
|
||
guard inputEpoch == epoch, final.generation == initial.generation, !final.diskEditorLocked, final.state != .closed else {
|
||
throw ProfileFailure.message("The machine changed while this disk was being opened. Choose the disk again.")
|
||
}
|
||
// Parse and validate the full image on the controller queue before any
|
||
// optional reset. Reset precedes installation in that same transaction.
|
||
let mounted = await diskStep { controller.mountDisk(image.data, drive: drive, name: url.lastPathComponent, readOnly: image.readOnly, reset: reset.controllerValue, completion: $0) }
|
||
if let error = mounted.errorMessage { throw ProfileFailure.message(error) }
|
||
if reset != .none { binaryName = nil; deniedShellGeneration = nil }
|
||
setBacking(drive, url: url, bytes: image.data); rememberDrive(drive, url: url)
|
||
recentMedia.record(url, as: .floppy(drive))
|
||
if execution == .run || (execution == .keepCurrentState && initial.state == .running) {
|
||
let resumed = await diskStep(controller.resume)
|
||
if let error = resumed.errorMessage { throw ProfileFailure.message("The disk was inserted, but the CoCo could not run: \(error)") }
|
||
}
|
||
}
|
||
func createDisk(_ drive: Int, format: VCCFloppyFormat = .standard) {
|
||
guard !busy, !diskSaving else { return }
|
||
command({ controller.createDisk(inDrive: drive, format: format, completion: $0) }, onSuccess: { [self] in setBacking(drive, url: nil); rememberDrive(drive, url: nil) })
|
||
}
|
||
func ejectDisk(_ drive: Int) {
|
||
guard !busy, !diskSaving else { return }
|
||
command({ controller.ejectDisk(inDrive: drive, discard: false, completion: $0) }, onSuccess: { [self] in setBacking(drive, url: nil); rememberDrive(drive, url: nil) })
|
||
}
|
||
func protectDisk(_ drive: Int, _ value: Bool) {
|
||
guard !busy, !diskSaving else { return }
|
||
command({ controller.setDiskWriteProtected(value, drive: drive, completion: $0) }, onSuccess: { [self] in
|
||
if let url = diskAssignments.drives[drive]?.url { rememberDrive(drive, url: url) }
|
||
})
|
||
}
|
||
func discardDisk(_ drive: Int) {
|
||
diskDialog { [self] in
|
||
let alert = NSAlert(); alert.messageText = "Discard changes to drive \(drive)?"
|
||
alert.informativeText = "This ejects the in-memory disk and loses its unsaved changes. The original file will not be changed."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard and Eject")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { busy = false; return }
|
||
command({ controller.ejectDisk(inDrive: drive, discard: true, completion: $0) }, onSuccess: { [self] in setBacking(drive, url: nil); rememberDrive(drive, url: nil) })
|
||
}
|
||
}
|
||
func disableDisks() {
|
||
diskDialog { [self] in
|
||
let alert = NSAlert(); alert.messageText = "Disable the floppy controller?"
|
||
alert.informativeText = "All four disks will be ejected and the machine will cold-reset, clearing its BASIC program. Save or discard modified disks first."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Disable")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { busy = false; return }
|
||
command(controller.disableDisks, onSuccess: { [self] in
|
||
diskAssignments.rom = nil; diskAssignments.drives = Array(repeating: nil, count: 4)
|
||
diskRestoreErrors = [:]; saveDiskAssignments()
|
||
diskBackings = Array(repeating: nil, count: 4); diskSaveErrors = [:]
|
||
diskTemporary = Array(repeating: false, count: 4)
|
||
})
|
||
}
|
||
}
|
||
/// Companion handoff takes immutable guest-visible bytes, including unsaved
|
||
/// writes. It neither exports/acknowledges a save nor pauses the emulator.
|
||
func snapshotDiskCopy(inDrive drive: Int) async throws -> Data {
|
||
guard !busy, !diskSaving, !diskEditorLocked, state != .closed, (0..<4).contains(drive) else {
|
||
throw ProfileFailure.message("Wait for the current media operation before copying this disk.")
|
||
}
|
||
busy = true; defer { busy = false }
|
||
let (data, snapshot): (Data?, VCCMachineSnapshot) = await withCheckedContinuation { continuation in
|
||
controller.snapshotDiskCopy(inDrive: drive) { continuation.resume(returning: ($0, $1)) }
|
||
}
|
||
accept(snapshot)
|
||
guard let data else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not copy this disk. Wait for disk activity to finish and try again.") }
|
||
return data
|
||
}
|
||
func exportDisk(_ drive: Int, to destination: URL? = nil) {
|
||
guard !busy, !diskSaving else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
controller.exportDisk(inDrive: drive) { [weak self] data, token, snapshot in
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.accept(snapshot)
|
||
guard let data else { self.busy = false; return }
|
||
if let destination {
|
||
self.finishDiskExport(data, token: token, drive: drive, url: destination); return
|
||
}
|
||
let panel = NSSavePanel(); panel.title = "Save Disk from Drive \(drive) As"
|
||
let ext = self.disks[drive].floppyExtension ?? "dsk"
|
||
panel.allowedContentTypes = [UTType(filenameExtension: ext) ?? .data]
|
||
let stem = (self.disks[drive].name as NSString).deletingPathExtension
|
||
panel.nameFieldStringValue = (stem.isEmpty ? "Untitled" : stem) + "." + ext
|
||
panel.begin { result in
|
||
guard result == .OK, let url = panel.url else { self.busy = false; return }
|
||
self.finishDiskExport(data, token: token, drive: drive, url: url)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
private func finishDiskExport(_ data: Data, token: UInt64, drive: Int, url: URL) {
|
||
Task { @MainActor in
|
||
do {
|
||
try await Task.detached(priority: .userInitiated) { try DiskFiles.export(data, to: url) }.value
|
||
command({ controller.markDiskSaved(inDrive: drive, token: token, name: url.lastPathComponent, completion: $0) },
|
||
onSuccess: { [self] in setBacking(drive, url: url, bytes: data); rememberDrive(drive, url: url) })
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func prepareToQuit(_ completion: @escaping () -> Void) {
|
||
busy = true; inputEpoch += 1
|
||
Task { @MainActor in
|
||
_ = await diskStep(controller.pause)
|
||
if let pending = diskSaveTask { await pending.value }
|
||
await saveAutomaticDisks()
|
||
await saveAutomaticHardDisks(force: true)
|
||
_ = await diskStep(controller.snapshot)
|
||
busy = false; completion()
|
||
}
|
||
}
|
||
func resume() { command(controller.resume) }
|
||
func pause() { command(controller.pause) }
|
||
|
||
// Debugger operations share the machine queue and normal busy/input state,
|
||
// but keep keyboard focus in the debugger after Continue or an edit.
|
||
func readDebugger(address: UInt16, followPC: Bool, memoryAddress: UInt16,
|
||
physicalAddress: UInt32 = 0, physicalMemory: Bool = false,
|
||
completion: @escaping (VCCDebuggerSnapshot?) -> Void) {
|
||
guard !busy, !diskSaving, state != .closed else { completion(nil); return }
|
||
controller.debuggerSnapshot(address: address, followPC: followPC, memoryAddress: memoryAddress,
|
||
physicalAddress: physicalAddress, physicalMemory: physicalMemory) { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(snapshot.machine)
|
||
completion(snapshot)
|
||
}
|
||
}
|
||
}
|
||
private func debuggerCommand(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void,
|
||
completion: @escaping () -> Void) {
|
||
developmentCommand(operation) { _ in completion() }
|
||
}
|
||
|
||
private func developmentCommand(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void,
|
||
completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard canQuickLoad else { completion(nil); return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
operation { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(snapshot); self?.busy = false; completion(snapshot)
|
||
}
|
||
}
|
||
}
|
||
var developmentDefaults: UserDefaults { displayDefaults }
|
||
/// Assigned files and live writable backings protect build snapshots from cleanup.
|
||
var developmentAssignedMediaURLs: [URL] {
|
||
var urls = [systemROMURL, cassetteURL, diskAssignments.rom].compactMap { $0 }
|
||
urls += diskAssignments.drives.compactMap { $0?.url }
|
||
urls += hardSettings.drives.compactMap { $0?.url }
|
||
urls += diskBackings.compactMap { $0?.url }
|
||
urls += hardBackings.compactMap { $0?.url }
|
||
for slot in cartridgeAssignments.slots {
|
||
urls += [slot.url, slot.speechROMURL, slot.sdcFolderURL].compactMap { $0 }
|
||
}
|
||
return urls
|
||
}
|
||
var developmentRunDirectory: URL { diskStore.url.deletingLastPathComponent().appendingPathComponent("Development Runs", isDirectory: true) }
|
||
var assemblyProgramRevision: UInt64 { programRevision }
|
||
func launchAssembly(_ data: Data, breakpoints: [UInt16], guards: [UInt16: Data],
|
||
pauseAtEntry: Bool, requires6309: Bool, expectedGeneration: UInt64,
|
||
expectedRevision: UInt64, expectedMapping: UInt64, shared: Bool = false, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard usageProfile != .nitros9, !builtInNitros9 else {
|
||
fileError = "Choose a BASIC profile to run a standalone assembly program. You can still assemble and export here."
|
||
completion(nil); return
|
||
}
|
||
guard !unsavedMedia else {
|
||
fileError = "Save pending media changes before running a development program."
|
||
completion(nil); return
|
||
}
|
||
let entries = guards.sorted { $0.key < $1.key }
|
||
developmentCommand({ controller.launchAssembly(data, points: breakpoints.map { NSNumber(value: $0) },
|
||
addresses: entries.map { NSNumber(value: $0.key) }, bytes: entries.map { $0.value },
|
||
pauseAtEntry: pauseAtEntry, requires6309: requires6309, generation: expectedGeneration,
|
||
revision: expectedRevision, mapping: expectedMapping, shared: shared, completion: $0) }, completion: completion)
|
||
}
|
||
func pauseAssembly(expected: VCCMachineSnapshot, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
developmentCommand({ controller.pauseAssembly(expected, completion: $0) }, completion: completion)
|
||
}
|
||
func controlAssembly(step: Bool, expected: VCCMachineSnapshot, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
developmentCommand({ controller.controlAssembly(step, expected: expected, completion: $0) }, completion: completion)
|
||
}
|
||
func updateAssembly(breakpoints: [UInt16], guards: [UInt16: Data], expected: VCCMachineSnapshot,
|
||
completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard breakpoints.allSatisfy({ guards[$0] != nil }) else { completion(nil); return }
|
||
developmentCommand({ controller.updateAssembly(breakpoints.map { NSNumber(value: $0) }, expected: expected,
|
||
completion: $0) }, completion: completion)
|
||
}
|
||
func clearAssembly(expected: VCCMachineSnapshot) {
|
||
// The queue checks ownership again even if a new build has launched in the meantime.
|
||
controller.clearAssembly(expected) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot) }
|
||
}
|
||
}
|
||
func debuggerLoadDevelopmentBinary(_ data: Data, breakpoints: [UInt16], completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard canQuickLoad else { completion(nil); return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
controller.debuggerLoadBinary(data, breakpoints: breakpoints.map { NSNumber(value: $0) }) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot); self?.busy = false; completion(snapshot) }
|
||
}
|
||
}
|
||
func armDevelopmentBreakpoints(_ addresses: [UInt16], guards: [UInt16:Data], completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard !busy, !diskSaving, state == .paused else { completion(nil); return }
|
||
let sorted = guards.keys.sorted()
|
||
busy = true; inputEpoch += 1
|
||
controller.debuggerArmDevelopmentBreakpoints(addresses.map { NSNumber(value: $0) },
|
||
guardAddresses: sorted.map { NSNumber(value: $0) }, guardBytes: sorted.map { guards[$0]! }) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot); self?.busy = false; completion(snapshot) }
|
||
}
|
||
}
|
||
func armDevelopmentBreakpoints(_ addresses: [UInt16], sourceMap: CMOCProjectSourceMap,
|
||
pointModules: [UInt16: Set<String>]? = nil, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard let layout = sourceMap.bankedLayout else {
|
||
armDevelopmentBreakpoints(addresses, guards: Dictionary(uniqueKeysWithValues:
|
||
sourceMap.instructions.map { ($0.address, Data($0.bytes)) }), completion: completion)
|
||
return
|
||
}
|
||
guard !busy, !diskSaving, state == .paused else { completion(nil); return }
|
||
let modules: [[String: Any]] = layout.modules.compactMap { module in
|
||
let code = module.codeGuards
|
||
guard !code.isEmpty else { return nil }
|
||
var definition: [String: Any] = ["id": module.id, "pages": module.pages.map {
|
||
["logicalPage": $0.logicalPage, "physicalPage": $0.physicalPage]
|
||
}, "addresses": code.map { NSNumber(value: $0.address) }, "bytes": code.map { Data($0.bytes) }]
|
||
if let pointModules {
|
||
definition["breakpoints"] = addresses.filter { pointModules[$0]?.contains(module.id) == true }.map { NSNumber(value: $0) }
|
||
}
|
||
return definition
|
||
}
|
||
busy = true; inputEpoch += 1
|
||
controller.debuggerArmBankedDevelopmentBreakpoints(addresses.map { NSNumber(value: $0) }, modules: modules) { [weak self] snapshot in
|
||
MainActor.assumeIsolated { self?.accept(snapshot); self?.busy = false; completion(snapshot) }
|
||
}
|
||
}
|
||
func clearDevelopmentBreakpoints(completion: @escaping () -> Void) {
|
||
debuggerCommand(controller.debuggerClearDevelopmentBreakpoints, completion: completion)
|
||
}
|
||
func runDevelopmentBinary(_ data: Data, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
// The strict development loader validates every record before mutating RAM.
|
||
guard data.count >= 5 else { completion(nil); return }
|
||
let entry = UInt16(data[data.count - 2]) << 8 | UInt16(data[data.count - 1])
|
||
debuggerLoadDevelopmentBinary(data, breakpoints: [entry]) { [weak self] snapshot in
|
||
guard let self, let snapshot, snapshot.errorMessage == nil else { completion(snapshot); return }
|
||
self.controller.debuggerClearDevelopmentBreakpoints { [weak self] cleared in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(cleared)
|
||
self?.debuggerContinue { completion(cleared) }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
func mountDevelopmentDisk(_ url: URL, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard !busy, !diskSaving, diskEnabled, !unsavedMedia else { completion(nil); return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let image = try await Task.detached { try DiskFiles.readImage(url) }.value
|
||
let snapshot = await controller.mountDisk(image.data, drive: 0, name: url.lastPathComponent, readOnly: false)
|
||
accept(snapshot); busy = false
|
||
if snapshot.errorMessage == nil {
|
||
// A working copy is writable and independently saved. The build artifact remains pristine.
|
||
diskTemporary[0] = false; setBacking(0, url: url, bytes: image.data); rememberDrive(0, url: url)
|
||
}
|
||
completion(snapshot)
|
||
} catch { fileError = error.localizedDescription; busy = false; completion(nil) }
|
||
}
|
||
}
|
||
func debuggerLoadBinary(_ data: Data, breakpoint: UInt16, completion: @escaping (VCCMachineSnapshot?) -> Void) {
|
||
guard canQuickLoad else { completion(nil); return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
controller.debuggerLoadBinary(data, breakpoint: breakpoint) { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(snapshot); self?.busy = false
|
||
if snapshot.errorMessage == nil { self?.binaryName = "main.bin" }
|
||
completion(snapshot)
|
||
}
|
||
}
|
||
}
|
||
func debuggerPause(completion: @escaping () -> Void) { debuggerCommand(controller.pause, completion: completion) }
|
||
func debuggerContinue(completion: @escaping () -> Void) { debuggerCommand(controller.resume, completion: completion) }
|
||
// Match highlights only to captures on either side of this exact instruction.
|
||
private(set) var lastDebuggerStep: (generation: UInt64, before: UInt64, after: UInt64)?
|
||
func debuggerStep(completion: @escaping () -> Void) {
|
||
guard canQuickLoad, state == .paused else { completion(); return }
|
||
let before = basicDebug
|
||
debuggerCommand(controller.debuggerStep) { [self] in
|
||
if before.generation == basicDebug.generation, basicDebug.paused, before.cycles != basicDebug.cycles {
|
||
lastDebuggerStep = (before.generation, before.cycles, basicDebug.cycles)
|
||
}
|
||
completion()
|
||
}
|
||
}
|
||
|
||
func readGraphicsPreview(currentPage: Bool, address: UInt32, physical: Bool, mode: Int,
|
||
alternatePalette: Bool) async -> VCCDebugGraphicsCapture? {
|
||
guard canQuickLoad else { return nil }
|
||
return await withCheckedContinuation { continuation in
|
||
controller.debuggerGraphics(currentPage: currentPage, address: address, physical: physical,
|
||
mode: mode, alternatePalette: alternatePalette) { capture in
|
||
continuation.resume(returning: capture)
|
||
}
|
||
}
|
||
}
|
||
func debuggerStepSource(mode: Int, addresses: [NSNumber], locations: [NSNumber], bytes: [Data],
|
||
expected: VCCMachineSnapshot, moduleIdentifiers: [String]? = nil, completion: @escaping () -> Void) {
|
||
if let moduleIdentifiers {
|
||
debuggerCommand({ controller.debuggerStepBankedSource(mode: mode, addresses: addresses, locations: locations,
|
||
bytes: bytes, moduleIdentifiers: moduleIdentifiers, generation: expected.generation,
|
||
programRevision: expected.debuggerProgramRevision, mappingFingerprint: expected.debuggerMappingFingerprint,
|
||
programCounter: expected.programCounter, completion: $0) }, completion: completion)
|
||
return
|
||
}
|
||
debuggerCommand({ controller.debuggerStepSource(mode: mode, addresses: addresses, locations: locations,
|
||
bytes: bytes, generation: expected.generation, programRevision: expected.debuggerProgramRevision,
|
||
mappingFingerprint: expected.debuggerMappingFingerprint, programCounter: expected.programCounter,
|
||
completion: $0) }, completion: completion)
|
||
}
|
||
func debuggerSetPC(_ address: UInt16, completion: @escaping () -> Void) {
|
||
debuggerCommand({ controller.debuggerSetPC(address, completion: $0) }, completion: completion)
|
||
}
|
||
func debuggerSetBreakpoints(_ addresses: [NSNumber], completion: @escaping () -> Void) {
|
||
debuggerCommand({ controller.debuggerSetBreakpoints(addresses, completion: $0) }, completion: completion)
|
||
}
|
||
func debuggerConfigureBreakpoints(_ enabled: [NSNumber], disabled: [NSNumber], completion: @escaping () -> Void) {
|
||
debuggerCommand({ controller.debuggerConfigureBreakpoints(enabled, disabled: disabled, completion: $0) }, completion: completion)
|
||
}
|
||
func readDebuggerMemory(address: UInt32, count: UInt32, physical: Bool, logicalAddress: UInt16,
|
||
os9: Bool, decode: Bool, completion: @escaping (VCCDebugMemoryCapture?) -> Void) {
|
||
guard !busy, !diskSaving, state != .closed else { completion(nil); return }
|
||
controller.debuggerMemory(address: address, count: count, physical: physical, logicalAddress: logicalAddress,
|
||
os9: os9, decode: decode) { [weak self] capture in
|
||
MainActor.assumeIsolated { self?.accept(capture.machine); completion(capture) }
|
||
}
|
||
}
|
||
func startDebuggerTrace(maximum: UInt, starts: [NSNumber], stops: [NSNumber], screen: Bool, scheduler: Bool, completion: @escaping () -> Void) {
|
||
debuggerCommand({ controller.debuggerStartTrace(maximum, starts: starts, stops: stops, screen: screen, scheduler: scheduler, completion: $0) }, completion: completion)
|
||
}
|
||
func stopDebuggerTrace(completion: @escaping () -> Void) { debuggerCommand(controller.debuggerStopTrace, completion: completion) }
|
||
func clearDebuggerTrace(completion: @escaping () -> Void) { debuggerCommand(controller.debuggerClearTrace, completion: completion) }
|
||
func readDebuggerTrace(offset: UInt, completion: @escaping (VCCTraceSnapshot?) -> Void) {
|
||
guard !busy, !diskSaving, state != .closed else { completion(nil); return }
|
||
controller.debuggerTrace(offset: offset) { [weak self] trace, machine in
|
||
MainActor.assumeIsolated { self?.accept(machine); completion(trace) }
|
||
}
|
||
}
|
||
func exportDebuggerTrace(first: UInt, count: UInt, completion: @escaping (String?) -> Void) {
|
||
guard !busy, !diskSaving, state != .closed else { completion(nil); return }
|
||
controller.debuggerExportTrace(first: first, count: count) { [weak self] text, machine in
|
||
MainActor.assumeIsolated { self?.accept(machine); completion(text) }
|
||
}
|
||
}
|
||
func debuggerWriteMemory(address: UInt16, data: Data, completion: @escaping () -> Void) {
|
||
debuggerCommand({ controller.debuggerWriteMemory(address: address, data: data, completion: $0) }, completion: completion)
|
||
}
|
||
func softReset() { command(controller.softReset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) }
|
||
func reset() { command(controller.reset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) }
|
||
func poll() {
|
||
guard !polling, !busy, state != .closed else { return }
|
||
polling = true
|
||
controller.snapshot { [weak self] snapshot in
|
||
MainActor.assumeIsolated {
|
||
self?.accept(snapshot); self?.polling = false
|
||
self?.applySavedMacShellDecision()
|
||
}
|
||
}
|
||
}
|
||
func shutdown(completion: @escaping () -> Void = {}) {
|
||
diskMonitor?.cancel(); diskMonitor = nil
|
||
busy = true
|
||
Task { @MainActor in
|
||
if let pending = diskSaveTask { await pending.value }
|
||
_ = await diskStep(controller.shutdown)
|
||
busy = false; completion()
|
||
}
|
||
}
|
||
private func applyCartridges(_ layout: CartridgeAssignments, bytes: [Data]) async -> Bool {
|
||
let result = await diskStep {
|
||
controller.configureCartridges(layout.slots.map { NSNumber(value: $0.kind.rawValue) },
|
||
roms: bytes, names: layout.slots.map { $0.url?.lastPathComponent ?? "" },
|
||
multiPak: layout.multiPak, physicalSlot: layout.physicalSlot,
|
||
sdcFolders: layout.slots.map { $0.sdcFolderURL?.path ?? "" },
|
||
sdcReadOnly: layout.slots.map { NSNumber(value: $0.sdcReadOnly ?? true) }, completion: $0)
|
||
}
|
||
return result.errorMessage == nil
|
||
}
|
||
private func restoreCartridges() async {
|
||
// Retry only unavailable ROMs; never replace a working loaded image.
|
||
var bytes = cartridgeBytes; var errors = cartridgeRestoreErrors
|
||
for index in 0..<5 where (cartridgeAssignments.slots[index].kind == .rom || cartridgeAssignments.slots[index].kind == .orchestra90 || cartridgeAssignments.slots[index].kind == .speechSound || cartridgeAssignments.slots[index].kind == .sdc) && bytes[index].isEmpty {
|
||
let assignment = cartridgeAssignments.slots[index]
|
||
guard assignment.url != nil || assignment.kind == .speechSound || assignment.kind == .sdc else { continue }
|
||
do {
|
||
bytes[index] = try await Task.detached { try DiskFiles.readCartridgeAssignment(assignment) }.value
|
||
errors[index] = nil
|
||
} catch { errors[index] = "\(index == 0 ? "Single cartridge" : "Slot \(index)"): \(error.localizedDescription)" }
|
||
}
|
||
if await applyCartridges(cartridgeAssignments, bytes: bytes) {
|
||
cartridgeBytes = bytes; cartridgeRestoreErrors = errors
|
||
}
|
||
}
|
||
func retryRememberedCartridges() {
|
||
guard !busy, !diskSaving else { return }
|
||
busy = true; inputEpoch += 1
|
||
Task { @MainActor in await restoreCartridges(); busy = false }
|
||
}
|
||
private func changeCartridges(_ layout: CartridgeAssignments, bytes: [Data], changedSlot: Int? = nil) {
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
if await applyCartridges(layout, bytes: bytes) {
|
||
cartridgeAssignments = layout; cartridgeBytes = bytes
|
||
if let changedSlot {
|
||
cartridgeRestoreErrors[changedSlot] = nil
|
||
if layout.slots[changedSlot].kind == .rom, let url = layout.slots[changedSlot].url {
|
||
recentMedia.record(url, as: .cartridge(changedSlot))
|
||
}
|
||
}
|
||
cartridgeRestoreErrors = cartridgeRestoreErrors.filter { (layout.slots[$0.key].url != nil || layout.slots[$0.key].kind == .speechSound || layout.slots[$0.key].kind == .sdc) && bytes[$0.key].isEmpty }
|
||
// First MPI activation can copy an unavailable single ROM. Keep
|
||
// recovery visible even if the original assignment is removed.
|
||
for index in 0..<5 where (layout.slots[index].url != nil || layout.slots[index].kind == .speechSound || layout.slots[index].kind == .sdc) && bytes[index].isEmpty {
|
||
if cartridgeRestoreErrors[index] == nil {
|
||
cartridgeRestoreErrors[index] = layout.slots[index].kind == .sdc ? "SDC needs an available SDC-DOS ROM and SD card folder. Choose both in Details, or retry." : "ROM unavailable. Reconnect the file and retry, or choose a replacement."
|
||
}
|
||
}
|
||
diskAssignments.cartridges = layout; saveDiskAssignments()
|
||
}
|
||
busy = false
|
||
}
|
||
}
|
||
func setMultiPak(_ enabled: Bool) {
|
||
guard !busy, !diskSaving else { return }
|
||
var layout = cartridgeAssignments; var bytes = cartridgeBytes
|
||
// First activation carries the single cartridge into slot 4. Later
|
||
// toggles preserve both configurations, including intentionally empty MPI.
|
||
if enabled && !layout.mpiConfigured {
|
||
layout.slots[4] = layout.slots[0]; bytes[4] = bytes[0]
|
||
}
|
||
if enabled { layout.mpiConfigured = true }
|
||
layout.multiPak = enabled
|
||
changeCartridges(layout, bytes: bytes)
|
||
}
|
||
func selectPhysicalSlot(_ slot: Int) {
|
||
guard !busy, !diskSaving, (1...4).contains(slot) else { return }
|
||
var layout = cartridgeAssignments; layout.physicalSlot = slot
|
||
changeCartridges(layout, bytes: cartridgeBytes)
|
||
}
|
||
func assignCartridge(_ kind: CartridgeAssignments.Kind, slot: Int, useBundledROM: Bool = true) {
|
||
guard !busy, !diskSaving, (0..<5).contains(slot), kind != .rom else { return }
|
||
var layout = cartridgeAssignments; var bytes = cartridgeBytes
|
||
var replacement = CartridgeAssignments.Slot(kind: kind)
|
||
var replacementBytes = Data()
|
||
var moved = false
|
||
if (kind == .orchestra90 || kind == .speechSound || kind == .sdc), slot > 0,
|
||
let previous = (1...4).first(where: { $0 != slot && layout.slots[$0].kind == kind }) {
|
||
replacement = layout.slots[previous]; replacementBytes = bytes[previous]
|
||
moved = true
|
||
}
|
||
if (kind == .floppy || kind == .hardDisk || kind == .ramDisk || kind == .orchestra90 || kind == .speechSound || kind == .sdc) && slot > 0 {
|
||
for index in 1...4 where layout.slots[index].kind == kind {
|
||
layout.slots[index] = .init(); bytes[index] = Data()
|
||
}
|
||
}
|
||
layout.slots[slot] = replacement; bytes[slot] = replacementBytes
|
||
if kind == .sdc, useBundledROM, !moved,
|
||
let store = startupStore, let kit = store.kit,
|
||
FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("sdcdos.rom").path) {
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let url = try await Task.detached { try kit.rom("sdcdos.rom", in: store.directory) }.value
|
||
layout.slots[slot].url = url
|
||
// The ROM is retained, but hardware stays inactive until a folder is selected.
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = "Bundled SDC-DOS ROM: " + error.localizedDescription; busy = false }
|
||
}
|
||
return
|
||
}
|
||
if kind == .speechSound, useBundledROM, !moved,
|
||
let store = startupStore, let kit = store.kit,
|
||
FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("pic-7040-510.bin").path),
|
||
FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("sp0256-al2.bin").path) {
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let (assignment, data) = try await Task.detached {
|
||
let assignment = CartridgeAssignments.Slot(kind: .speechSound,
|
||
url: try kit.rom("pic-7040-510.bin", in: store.directory),
|
||
speechROMURL: try kit.rom("sp0256-al2.bin", in: store.directory))
|
||
return (assignment, try DiskFiles.readCartridgeAssignment(assignment))
|
||
}.value
|
||
layout.slots[slot] = assignment; bytes[slot] = data
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = "Bundled Speech/Sound ROMs: " + error.localizedDescription; busy = false }
|
||
}
|
||
return
|
||
}
|
||
if kind == .orchestra90, useBundledROM, !moved,
|
||
let store = startupStore, let kit = store.kit,
|
||
FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent("orch90.rom").path) {
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let (url, data) = try await Task.detached {
|
||
let url = try kit.rom("orch90.rom", in: store.directory)
|
||
return (url, try DiskFiles.readOrchestraROM(url))
|
||
}.value
|
||
layout.slots[slot].url = url; bytes[slot] = data
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = "Bundled Orchestra-90 ROM: " + error.localizedDescription; busy = false }
|
||
}
|
||
return
|
||
}
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
}
|
||
func openSDCFolder(_ slot: Int) {
|
||
guard (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .sdc else { return }
|
||
diskDialog { [self] in
|
||
let panel = NSOpenPanel(); panel.title = "Choose SD Card Folder"
|
||
panel.message = "Choose a folder containing your extracted SDC files. Changing it restarts the CoCo and clears the working program. Read-only protection is on by default."
|
||
panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.allowsMultipleSelection = false
|
||
panel.directoryURL = cartridgeAssignments.slots[slot].sdcFolderURL
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
selectSDCFolder(url, slot: slot)
|
||
}
|
||
}
|
||
}
|
||
func selectSDCFolder(_ url: URL, slot: Int) {
|
||
guard !diskSaving, (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .sdc else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
var assignment = cartridgeAssignments.slots[slot]; assignment.sdcFolderURL = url
|
||
Task { @MainActor in
|
||
do {
|
||
let data = try await Task.detached {
|
||
try DiskFiles.validateSDCFolder(url)
|
||
// Keep a valid new folder even if the remembered ROM is missing.
|
||
// Each half can be repaired independently; incomplete hardware stays inactive.
|
||
return (try? DiskFiles.readCartridgeAssignment(assignment)) ?? Data()
|
||
}.value
|
||
var layout = cartridgeAssignments; var bytes = cartridgeBytes
|
||
layout.slots[slot] = assignment; bytes[slot] = data
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
private func selectSDCROM(_ url: URL, slot: Int) {
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
var assignment = cartridgeAssignments.slots[slot].kind == .sdc ? cartridgeAssignments.slots[slot] : .init(kind: .sdc)
|
||
assignment.url = url
|
||
Task { @MainActor in
|
||
do {
|
||
let data = try await Task.detached {
|
||
_ = try DiskFiles.readSDCROM(url)
|
||
// A missing folder must not prevent replacing a missing ROM.
|
||
return (try? DiskFiles.readCartridgeAssignment(assignment)) ?? Data()
|
||
}.value
|
||
var layout = cartridgeAssignments; var bytes = cartridgeBytes
|
||
if slot > 0 {
|
||
for i in 1...4 where i != slot && layout.slots[i].kind == .sdc {
|
||
layout.slots[i] = .init(); bytes[i] = Data()
|
||
}
|
||
}
|
||
layout.slots[slot] = assignment; bytes[slot] = data
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func setSDCReadOnly(_ protected: Bool, slot: Int) {
|
||
guard !busy, !diskSaving, (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .sdc,
|
||
(cartridgeAssignments.slots[slot].sdcReadOnly ?? true) != protected else { return }
|
||
let alert = NSAlert(); alert.messageText = protected ? "Protect the SD card folder and restart?" : "Allow changes to the SD card folder and restart?"
|
||
alert.informativeText = "This clears the working program in RAM. " + (protected
|
||
? "The guest can read files but cannot change them. Existing files are kept."
|
||
: "SDC software can write disk images and create, rename or delete files inside the selected folder. Changes save directly to those files. Use a copy of a collection if you want to preserve its originals.")
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: protected ? "Protect and Restart" : "Allow Changes and Restart")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
var layout = cartridgeAssignments; layout.slots[slot].sdcReadOnly = protected
|
||
changeCartridges(layout, bytes: cartridgeBytes, changedSlot: slot)
|
||
}
|
||
func openSpeechROM(_ slot: Int, speech: Bool) {
|
||
guard (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .speechSound else { return }
|
||
diskDialog { [self] in
|
||
let panel = NSOpenPanel()
|
||
panel.title = speech ? "Choose Speech ROM" : "Choose PIC Firmware"
|
||
panel.message = "Speech/Sound requires pic-7040-510.bin (4 KiB) and sp0256-al2.bin (2 KiB). Changing either clears the working BASIC program and restarts the machine; mounted media are retained."
|
||
panel.allowedContentTypes = ["bin", "rom"].map { UTType(filenameExtension: $0) ?? .data }
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
selectSpeechROM(url, slot: slot, speech: speech)
|
||
}
|
||
}
|
||
}
|
||
func selectSpeechROM(_ url: URL, slot: Int, speech: Bool) {
|
||
guard !diskSaving, (0..<5).contains(slot), cartridgeAssignments.slots[slot].kind == .speechSound else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
var assignment = cartridgeAssignments.slots[slot]
|
||
if speech { assignment.speechROMURL = url } else { assignment.url = url }
|
||
Task { @MainActor in
|
||
do {
|
||
let data = try await Task.detached {
|
||
_ = try DiskFiles.readSpeechChipROM(url, speech: speech)
|
||
return try assignment.url != nil && assignment.speechROMURL != nil ? DiskFiles.readCartridgeAssignment(assignment) : Data()
|
||
}.value
|
||
var layout = cartridgeAssignments; var bytes = cartridgeBytes
|
||
layout.slots[slot] = assignment; bytes[slot] = data
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func openCartridgeROM(_ slot: Int, kind: CartridgeAssignments.Kind = .rom) {
|
||
guard (0..<5).contains(slot) else { return }
|
||
diskDialog { [self] in
|
||
let panel = NSOpenPanel(); panel.title = kind == .sdc ? "Choose SDC-DOS ROM" : kind == .orchestra90 ? "Choose Orchestra-90 ROM" : "Choose Cartridge ROM"
|
||
panel.message = (kind == .sdc ? "Choose an 8 or 16 KiB SDC-DOS ROM. " : kind == .orchestra90 ? "Choose an 8 KiB Orchestra-90 ROM. " : "") + "Choose a raw ROM, not a DLL. Changing cartridges cold-resets the machine and clears its BASIC program. Replacing the last RAM disk assignment also discards its contents."
|
||
panel.allowedContentTypes = ["rom", "ccc", "bin", "pak"].map { UTType(filenameExtension: $0) ?? .data }
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
selectCartridgeROM(url, slot: slot, kind: kind)
|
||
}
|
||
}
|
||
}
|
||
func selectCartridgeROM(_ url: URL, slot: Int, kind: CartridgeAssignments.Kind = .rom) {
|
||
guard !diskSaving, (0..<5).contains(slot), kind == .rom || kind == .orchestra90 || kind == .sdc else { return }
|
||
if kind == .sdc { selectSDCROM(url, slot: slot); return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let data = try await Task.detached { try kind == .orchestra90 ? DiskFiles.readOrchestraROM(url) : DiskFiles.readCartridgeROM(url) }.value
|
||
var layout = cartridgeAssignments; var bytes = cartridgeBytes
|
||
if kind == .orchestra90 && slot > 0 {
|
||
for i in 1...4 where i != slot && layout.slots[i].kind == kind {
|
||
layout.slots[i] = .init(); bytes[i] = Data()
|
||
}
|
||
}
|
||
layout.slots[slot] = .init(kind: kind, url: url); bytes[slot] = data
|
||
changeCartridges(layout, bytes: bytes, changedSlot: slot)
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
|
||
private var hardNeedsSaving: Bool {
|
||
hardDisks.indices.contains { hardDisks[$0].dirty && !hardDisks[$0].writeProtected && !hardDisks[$0].sourceReadOnly && !hardTemporary[$0] && hardBackings[$0] != nil && hardSaveErrors[$0] == nil }
|
||
}
|
||
private func rememberHardDisk(_ drive: Int, url: URL?) {
|
||
hardSettings.drives[drive] = url.map { .init(url: $0, writeProtected: hardDisks[drive].writeProtected, temporary: hardTemporary[drive]) }
|
||
hardRestoreErrors[drive] = nil; diskAssignments.hardDisks = hardSettings; saveDiskAssignments()
|
||
}
|
||
private func saveAutomaticHardDisks(force: Bool = false) async {
|
||
guard force || Date() >= nextHardSave || hardFlushRequests != savedHardFlushRequests else { return }
|
||
savedHardFlushRequests = hardFlushRequests
|
||
for drive in 0..<2 {
|
||
guard !hardTemporary[drive], hardSaveErrors[drive] == nil, let backing = hardBackings[drive] else { continue }
|
||
let (save, snapshot): (VCCHardDiskSave?, VCCMachineSnapshot) = await withCheckedContinuation { c in
|
||
controller.captureHardDisk(inDrive: drive, full: false) { c.resume(returning: ($0, $1)) }
|
||
}
|
||
accept(snapshot); guard let save else { continue }
|
||
do {
|
||
let digest = try await automaticHardDiskWriter(save.data, Int(save.byteCount), backing.url, backing.digest)
|
||
// Our own coordinated write advances the trusted working disk;
|
||
// an externally replaced disk with the same name must ask again.
|
||
if drive == 0, let disk = shellDisk, disk == savedShellGrant,
|
||
disk["sha256"] == backing.digest {
|
||
savedShellGrant = ["path": backing.url.path, "sha256": digest]
|
||
}
|
||
hardBackings[drive]?.digest = digest
|
||
_ = await diskStep { controller.acknowledgeHardDisk(inDrive: drive, token: save.token, name: nil, completion: $0) }
|
||
} catch {
|
||
hardSaveErrors[drive] = "Hard disk \(drive) could not save: \(error.localizedDescription)"
|
||
_ = await diskStep(controller.pause)
|
||
}
|
||
}
|
||
nextHardSave = Date().addingTimeInterval(1)
|
||
}
|
||
private func restoreHardDisks() async {
|
||
hardRestoreErrors = [:]
|
||
let paused = await diskStep { controller.configureHardClock(hardSettings.clockEnabled, readOnly: hardSettings.clockReadOnly, completion: $0) }
|
||
guard paused.errorMessage == nil else { fileError = paused.errorMessage; return }
|
||
for drive in 0..<2 {
|
||
guard !hardDisks[drive].mounted, let saved = hardSettings.drives[drive] else { continue }
|
||
do {
|
||
let image = try await Task.detached { try HardDiskFiles.readImage(saved.url) }.value
|
||
var result = await diskStep { controller.mountHardDisk(image.data, drive: drive, name: saved.url.lastPathComponent, readOnly: image.readOnly, completion: $0) }
|
||
if result.errorMessage == nil && saved.writeProtected && !result.hardDisks[drive].writeProtected {
|
||
result = await diskStep { controller.hardDiskAction(2, drive: drive, completion: $0) }
|
||
}
|
||
if let error = result.errorMessage { throw NSError(domain: "VCC", code: 1, userInfo: [NSLocalizedDescriptionKey: error]) }
|
||
hardBackings[drive] = .init(url: saved.url.resolvingSymlinksInPath(), digest: image.digest)
|
||
hardTemporary[drive] = saved.temporary; hardSaveErrors[drive] = nil
|
||
} catch { hardRestoreErrors[drive] = "Hard disk \(drive), \(saved.url.lastPathComponent): \(error.localizedDescription)" }
|
||
}
|
||
}
|
||
func retryHardDisks() {
|
||
guard !busy, !diskSaving else { return }
|
||
busy = true; inputEpoch += 1
|
||
Task { @MainActor in await restoreHardDisks(); busy = false }
|
||
}
|
||
func retryHardSave(_ drive: Int) {
|
||
guard !busy, !diskSaving else { return }
|
||
hardSaveErrors[drive] = nil; nextHardSave = .distantPast; startAutomaticDiskSave()
|
||
}
|
||
func setHardTemporary(_ drive: Int, _ temporary: Bool) {
|
||
guard !busy, !diskSaving else { return }
|
||
command(controller.pauseForDiskChange, onSuccess: { [self] in
|
||
hardTemporary[drive] = temporary
|
||
if let url = hardSettings.drives[drive]?.url { rememberHardDisk(drive, url: url) }
|
||
})
|
||
}
|
||
func setHardProtection(_ drive: Int, _ protected: Bool) {
|
||
guard !busy, !diskSaving else { return }
|
||
command({ controller.hardDiskAction(protected ? 2 : 3, drive: drive, completion: $0) }, onSuccess: { [self] in
|
||
if let url = hardSettings.drives[drive]?.url { rememberHardDisk(drive, url: url) }
|
||
})
|
||
}
|
||
func setHardClock(enabled: Bool, readOnly: Bool) {
|
||
guard !busy, !diskSaving else { return }
|
||
command({ controller.configureHardClock(enabled, readOnly: readOnly, completion: $0) }, onSuccess: { [self] in
|
||
hardSettings.clockEnabled = enabled; hardSettings.clockReadOnly = readOnly
|
||
diskAssignments.hardDisks = hardSettings; saveDiskAssignments()
|
||
})
|
||
}
|
||
func openHardDisk(_ drive: Int) {
|
||
diskDialog { [self] in
|
||
let panel = NSOpenPanel(); panel.title = "Insert Hard Disk \(drive)"
|
||
panel.message = "Choose a raw VHD, OS9 or IMG sector image. Writable images save automatically unless Temporary changes is enabled."
|
||
panel.allowedContentTypes = ["vhd", "os9", "img"].map { UTType(filenameExtension: $0) ?? .data }
|
||
panel.allowsOtherFileTypes = true; panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { busy = false; return }
|
||
insertHardDisk(url, drive: drive)
|
||
}
|
||
}
|
||
}
|
||
func insertHardDisk(_ url: URL, drive: Int) {
|
||
guard !diskSaving, (0..<2).contains(drive) else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
Task { @MainActor in
|
||
do {
|
||
let image = try await Task.detached(priority: .userInitiated) { try HardDiskFiles.readImage(url) }.value
|
||
command({ controller.mountHardDisk(image.data, drive: drive, name: url.lastPathComponent, readOnly: image.readOnly, completion: $0) }, onSuccess: { [self] in
|
||
hardBackings[drive] = .init(url: url.resolvingSymlinksInPath(), digest: image.digest)
|
||
hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: url); recentMedia.record(url, as: .hardDisk(drive))
|
||
})
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
func createHardDisk(_ drive: Int, sizeKiB: Int) {
|
||
guard !busy, !diskSaving, (1...524288).contains(sizeKiB) else { return }
|
||
command({ controller.createHardDisk(inDrive: drive, size: UInt(sizeKiB * 1024), completion: $0) }, onSuccess: { [self] in
|
||
hardBackings[drive] = nil; hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: nil)
|
||
})
|
||
}
|
||
func ejectHardDisk(_ drive: Int, discard: Bool = false) {
|
||
guard !busy, !diskSaving else { return }
|
||
diskDialog { [self] in
|
||
if discard {
|
||
let alert = NSAlert(); alert.messageText = "Discard changes to hard disk \(drive)?"
|
||
alert.informativeText = "This ejects unsaved in-memory changes. Earlier automatic saves cannot be undone."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard and Eject")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { busy = false; return }
|
||
}
|
||
command({ controller.hardDiskAction(discard ? 1 : 0, drive: drive, completion: $0) }, onSuccess: { [self] in
|
||
hardBackings[drive] = nil; hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: nil)
|
||
})
|
||
}
|
||
}
|
||
func exportHardDisk(_ drive: Int, to destination: URL? = nil) {
|
||
guard !busy, !diskSaving else { return }
|
||
busy = true; inputEpoch += 1; fileError = nil
|
||
controller.captureHardDisk(inDrive: drive, full: true) { [weak self] save, snapshot in
|
||
MainActor.assumeIsolated { [self] in
|
||
guard let self else { return }; self.accept(snapshot)
|
||
guard snapshot.errorMessage == nil, let save else { self.busy = false; return }
|
||
if let destination { self.finishHardExport(save, drive: drive, url: destination); return }
|
||
let panel = NSSavePanel(); panel.title = "Save Hard Disk \(drive) As"
|
||
panel.allowedContentTypes = [UTType(filenameExtension: "vhd") ?? .data]
|
||
panel.nameFieldStringValue = (self.hardDisks[drive].name as NSString).deletingPathExtension + ".vhd"
|
||
panel.begin { [self] result in
|
||
guard result == .OK, let url = panel.url else { self.busy = false; return }
|
||
self.finishHardExport(save, drive: drive, url: url)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
private func finishHardExport(_ save: VCCHardDiskSave, drive: Int, url: URL) {
|
||
let data = save.data
|
||
Task { @MainActor in
|
||
do {
|
||
let digest = try await Task.detached(priority: .userInitiated) { try HardDiskFiles.export(data, to: url) }.value
|
||
command({ controller.acknowledgeHardDisk(inDrive: drive, token: save.token, name: url.lastPathComponent, completion: $0) }, onSuccess: { [self] in
|
||
hardBackings[drive] = .init(url: url.resolvingSymlinksInPath(), digest: digest)
|
||
hardSaveErrors[drive] = nil; rememberHardDisk(drive, url: url); recentMedia.record(url, as: .hardDisk(drive))
|
||
})
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
extension MachineModel {
|
||
func captureProfile(name: String, replacing id: UUID? = nil) async throws -> ConfigurationProfile {
|
||
guard !busy, state != .closed else { throw ProfileFailure.message("Wait for the current operation to finish.") }
|
||
busy = true
|
||
defer { busy = false }
|
||
if let pending = diskSaveTask { await pending.value }
|
||
_ = await diskStep(controller.snapshot)
|
||
var value = ConfigurationProfile(name: name.trimmingCharacters(in: .whitespacesAndNewlines))
|
||
if let id { value.id = id }
|
||
value.machine = settings; value.videoOutput = videoOutput.rawValue
|
||
value.sound = audioEnabled; value.volume = volume; value.systemROM = systemROMURL
|
||
value.media = diskAssignments; value.media.cartridges = cartridgeAssignments; value.media.hardDisks = hardSettings
|
||
for i in disks.indices where disks[i].mounted {
|
||
guard value.media.drives[i] != nil else { throw ProfileFailure.message("Save floppy drive \(i) with Save As before including it in a profile.") }
|
||
value.media.drives[i]?.writeProtected = disks[i].writeProtected
|
||
value.media.drives[i]?.temporary = diskTemporary[i]
|
||
}
|
||
for i in hardDisks.indices where hardDisks[i].mounted {
|
||
guard value.media.hardDisks?.drives[i] != nil else { throw ProfileFailure.message("Save hard disk \(i) with Save As before including it in a profile.") }
|
||
value.media.hardDisks?.drives[i]?.writeProtected = hardDisks[i].writeProtected
|
||
value.media.hardDisks?.drives[i]?.temporary = hardTemporary[i]
|
||
}
|
||
if tapeMounted && cassetteURL == nil { throw ProfileFailure.message("Export the cassette to a file before including it in a profile.") }
|
||
value.cassette = tapeMounted ? cassetteURL : nil; value.fastCassette = tapeFast
|
||
value.input = input.settings; value.bootNitros9 = bootNitros9 ? true : nil
|
||
try value.validate(); return value
|
||
}
|
||
|
||
// Called after the profile window's explicit cold-restart confirmation.
|
||
// Failures retain the old machine/media, paused for recovery. No automatic
|
||
// discard is offered for temporary images or unfinished tape recordings.
|
||
func loadProfile(_ profile: ConfigurationProfile) async {
|
||
await loadProfile(preparing: { profile }, startRunning: false)
|
||
}
|
||
@discardableResult private func loadProfile(preparing: () async throws -> ConfigurationProfile, startRunning: Bool,
|
||
builtInNitros9: Bool = false, afterStart: (() async throws -> Void)? = nil) async -> Bool {
|
||
guard !busy, state != .closed else { return false }
|
||
var committed = false
|
||
guideRequest = nil
|
||
busy = true; inputEpoch += 1; profileError = nil; fileError = nil
|
||
defer { busy = false }
|
||
do {
|
||
let paused = await diskStep(controller.pauseForDiskChange)
|
||
if let error = paused.errorMessage { throw ProfileFailure.message(error) }
|
||
if let pending = diskSaveTask { await pending.value }
|
||
await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true)
|
||
_ = await diskStep(controller.snapshot)
|
||
guard !unsavedMedia else {
|
||
throw ProfileFailure.message("The current setup has unsaved media. Save As or export your recordings, or explicitly discard them in the media controls, before loading a profile. The machine is paused.")
|
||
}
|
||
try Task.checkCancellation()
|
||
let profile = try await preparing()
|
||
try profile.validate()
|
||
let prepared = try await Task.detached(priority: .userInitiated) { [startupStore] in
|
||
let checked = try PreparedProfile.read(profile)
|
||
if try startupStore?.initializeSharedOS9(for: profile) == true { return try PreparedProfile.read(profile) }
|
||
return checked
|
||
}.value
|
||
try Task.checkCancellation()
|
||
let request = prepared.request()
|
||
let (applied, snapshot): (Bool, VCCMachineSnapshot) = await withCheckedContinuation { c in
|
||
controller.applyProfile(request) { c.resume(returning: ($0, $1)) }
|
||
}
|
||
accept(snapshot)
|
||
committed = applied
|
||
guard applied else { throw ProfileFailure.message(snapshot.errorMessage ?? "Could not load the profile.") }
|
||
// Publish the new host file/backing bookkeeping only once the worker
|
||
// has installed that exact payload. Failed preflight never persists it.
|
||
systemROMURL = profile.systemROM; title = profile.systemROM?.lastPathComponent ?? "No ROM selected"
|
||
binaryName = nil; profileName = profile.name; bootNitros9 = profile.bootNitros9 == true
|
||
cassetteURL = profile.cassette; tapeName = profile.cassette?.lastPathComponent ?? "No tape"
|
||
cartridgeAssignments = profile.media.cartridges ?? CartridgeAssignments(); cartridgeBytes = prepared.cartridges
|
||
diskAssignments = profile.media; diskAssignments.cartridges = cartridgeAssignments
|
||
hardSettings = profile.media.hardDisks ?? HardDiskAssignments(); diskAssignments.hardDisks = hardSettings
|
||
cartridgeRestoreErrors = [:]; diskRestoreErrors = [:]; hardRestoreErrors = [:]
|
||
diskSaveErrors = [:]; hardSaveErrors = [:]
|
||
diskBackings = Array(repeating: nil, count: 4); hardBackings = [nil, nil]
|
||
diskTemporary = Array(repeating: false, count: 4); hardTemporary = [false, false]
|
||
for i in 0..<4 {
|
||
if let saved = profile.media.drives[i], let image = prepared.floppies[i] {
|
||
setBacking(i, url: saved.url, bytes: image.data); diskTemporary[i] = saved.temporary
|
||
}
|
||
}
|
||
for i in 0..<2 {
|
||
if let saved = hardSettings.drives[i], let image = prepared.hardDisks[i] {
|
||
hardBackings[i] = .init(url: saved.url.resolvingSymlinksInPath(), digest: image.digest)
|
||
hardTemporary[i] = saved.temporary
|
||
}
|
||
}
|
||
nextHardSave = .distantPast; savedHardFlushRequests = hardFlushRequests
|
||
volume = profile.volume; input.settings = profile.input
|
||
_ = await applyDriveWireDefault(builtInNitros9)
|
||
rememberStartup()
|
||
loadedProfileConfiguration = profileConfiguration
|
||
settings.save(in: displayDefaults); displayDefaults.set(profile.videoOutput, forKey: DisplayOutput.preferenceKey)
|
||
saveDiskAssignments()
|
||
if let error = snapshot.errorMessage { throw ProfileFailure.message("The profile was installed, but the machine could not start: \(error)") }
|
||
if let error = diskSettingsError ?? input.error ?? fileError { throw ProfileFailure.message("The profile was loaded, but preferences could not be saved: \(error)") }
|
||
if bootNitros9 { _ = await diskStep(controller.requestNitros9Boot) }
|
||
if startRunning {
|
||
let resumed = await diskStep(controller.resume)
|
||
if let error = resumed.errorMessage { throw ProfileFailure.message(error) }
|
||
focusRequest += 1
|
||
}
|
||
try await afterStart?()
|
||
} catch { profileError = error.localizedDescription }
|
||
return committed
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
extension MachineModel {
|
||
func reportMediaError(_ message: String) { fileError = message }
|
||
func openMedia() {
|
||
guard !busy, !diskSaving, !mediaPromptOpen else { return }
|
||
mediaPromptOpen = true
|
||
let panel = NSOpenPanel(); panel.title = "Open Media"
|
||
panel.message = "Choose a disk, cassette, cartridge, system ROM or binary program. You will choose its destination before it is loaded."
|
||
panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||
panel.begin { [weak self] result in
|
||
self?.mediaPromptOpen = false
|
||
guard result == .OK, let url = panel.url else { return }
|
||
self?.offerMedia(url)
|
||
}
|
||
}
|
||
func offerMedia(_ url: URL, preferred: MediaDestination? = nil, fromHistory: Bool = false) {
|
||
guard !busy, !diskSaving, !diskEditorLocked, !mediaPromptOpen, state != .closed else { fileError = "Wait for the current operation before opening media."; return }
|
||
mediaPromptOpen = true
|
||
var sheetPending = false
|
||
defer { if !sheetPending { mediaPromptOpen = false } }
|
||
guard RecentMedia.isLocalFile(url), (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else {
|
||
fileError = "Media file unavailable: \(url.lastPathComponent). Reconnect its volume or choose the file's new location with Open Media. Recent history has been kept."; return
|
||
}
|
||
var choices = MediaDestination.choices(for: url)
|
||
// Explicit existing file selections can have nonstandard extensions.
|
||
if let preferred, preferred.valid, !choices.contains(preferred) {
|
||
guard fromHistory else { fileError = "This file does not match \(preferred.label). Drop it onto the main display to choose a compatible destination."; return }
|
||
choices.insert(preferred, at: 0)
|
||
}
|
||
guard !choices.isEmpty else { fileError = "Unsupported media type. Use a DSK/JVC/OS9, VHD/IMG, CAS/WAV, ROM/CCC/PAK or CoCo BIN file. Windows DLLs are not Mac cartridges."; return }
|
||
// OS-9 images retain both floppy and hard-disk destinations alongside
|
||
// filesystem editing; hard-disk insertion keeps its existing pause policy.
|
||
if DiskFiles.extensions.contains(url.pathExtension.lowercased()) {
|
||
let supportsHardDisk = choices.contains { if case .hardDisk = $0 { return true }; return false }
|
||
let options = DiskMediaOpenOptions(preferred: preferred, supportsHardDisk: supportsHardDisk)
|
||
let alert = NSAlert(); alert.messageText = "Open \(url.lastPathComponent)?"
|
||
alert.informativeText = "Edit the disk's files, or insert it into a drive. Floppy insertion can optionally reset the CoCo first, then keep the current running or paused state, pause, or run. Inserting does not boot the disk or run its contents. Hard-disk insertion pauses the CoCo. Unsaved media must be saved or exported first. Cancel leaves the session unchanged."
|
||
alert.accessoryView = options.view
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Open")
|
||
guard let sourceAttributes = try? FileManager.default.attributesOfItem(atPath: url.path) else {
|
||
fileError = "The disk file is unavailable. Choose it again."; return
|
||
}
|
||
let sourceVolume = sourceAttributes[.systemNumber] as? NSNumber
|
||
let sourceInode = sourceAttributes[.systemFileNumber] as? NSNumber
|
||
let sourceDate = sourceAttributes[.modificationDate] as? Date
|
||
let sourceSize = sourceAttributes[.size] as? NSNumber
|
||
let expectedEpoch = inputEpoch
|
||
let finish: @MainActor (NSApplication.ModalResponse) -> Void = { [weak self] response in
|
||
guard let self else { return }
|
||
self.mediaPromptOpen = false
|
||
guard response == .alertSecondButtonReturn else { return }
|
||
guard !self.busy, !self.diskSaving, !self.diskEditorLocked, self.state != .closed,
|
||
self.inputEpoch == expectedEpoch else {
|
||
self.fileError = "The machine changed while choosing a disk action. Open the disk again."; return
|
||
}
|
||
let current = try? FileManager.default.attributesOfItem(atPath: url.path)
|
||
guard current?[.type] as? FileAttributeType == .typeRegular,
|
||
sourceVolume != nil, sourceInode != nil,
|
||
current?[.systemNumber] as? NSNumber == sourceVolume,
|
||
current?[.systemFileNumber] as? NSNumber == sourceInode,
|
||
current?[.modificationDate] as? Date == sourceDate,
|
||
current?[.size] as? NSNumber == sourceSize else {
|
||
self.fileError = "The disk file changed while choosing an action. Open it again to use its current contents."; return
|
||
}
|
||
if options.action.indexOfSelectedItem == 0 {
|
||
DiskImageEditorCoordinator.shared.open(url, machine: self)
|
||
} else if options.action.indexOfSelectedItem == 2 {
|
||
self.loadMedia(url, destination: .hardDisk(options.drive.indexOfSelectedItem))
|
||
} else {
|
||
let drive = options.drive.indexOfSelectedItem
|
||
let execution = DiskInsertionExecution(rawValue: options.execution.indexOfSelectedItem) ?? .keepCurrentState
|
||
let reset = DiskInsertionReset(rawValue: options.reset.indexOfSelectedItem) ?? .none
|
||
Task { @MainActor in
|
||
do { try await self.insertDiskFromMedia(url, drive: drive, execution: execution, reset: reset) }
|
||
catch { self.fileError = error.localizedDescription }
|
||
}
|
||
}
|
||
}
|
||
if let window = NSApp.keyWindow ?? NSApp.mainWindow {
|
||
sheetPending = true
|
||
alert.beginSheetModal(for: window) { response in
|
||
Task { @MainActor in finish(response) }
|
||
}
|
||
} else {
|
||
finish(alert.runModal())
|
||
}
|
||
return
|
||
}
|
||
let alert = NSAlert(); alert.messageText = "Open \(url.lastPathComponent)?"
|
||
alert.informativeText = "Choose where to use this file. ROM and cartridge changes restart the computer; binary programs start immediately. Disk and cassette images are mounted without running their contents. Unsaved media must be saved or exported first. Cancel leaves the current session unchanged."
|
||
let picker = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 340, height: 28))
|
||
picker.addItems(withTitles: choices.map(\.label)); picker.setAccessibilityLabel("Media destination")
|
||
if let preferred, let index = choices.firstIndex(of: preferred) { picker.selectItem(at: index) }
|
||
else if ["ccc", "pak"].contains(url.pathExtension.lowercased()), let index = choices.firstIndex(of: .cartridge(cartridgeAssignments.multiPak ? cartridgeAssignments.physicalSlot : 0)) { picker.selectItem(at: index) }
|
||
alert.accessoryView = picker
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Open")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||
loadMedia(url, destination: choices[picker.indexOfSelectedItem])
|
||
}
|
||
// One path for recents, Finder opening and all drop targets. Preflight is
|
||
// performed before pausing; actual replacement reuses device safeguards.
|
||
// Return the existing scheduled operation for callers that need to await it.
|
||
// The floppy task covers its complete insertion; other device helpers retain
|
||
// their callback-based completion and busy state. Floppy insertion reserves
|
||
// busy inside its transaction; setting it here would reject our own request.
|
||
@discardableResult
|
||
func loadMedia(_ url: URL, destination: MediaDestination) -> Task<Void, Never>? {
|
||
guard !busy, !diskSaving, !diskEditorLocked, state != .closed, RecentMedia.isLocalFile(url), destination.valid else { return nil }
|
||
if case .floppy(let drive) = destination {
|
||
return Task { @MainActor in
|
||
do { try await insertDiskFromMedia(url, drive: drive, execution: .keepCurrentState) }
|
||
catch { fileError = error.localizedDescription }
|
||
}
|
||
}
|
||
if case .hardDisk = destination, !hardDiskConnected { fileError = "Connect the hard-disk controller in Cartridges before inserting this image."; return nil }
|
||
if case .cartridge(let slot) = destination, (cartridgeAssignments.multiPak ? slot == 0 : slot != 0) {
|
||
fileError = "This cartridge destination is not active. Choose the direct cartridge or an enabled Multi-Pak slot."; return nil
|
||
}
|
||
busy = true; fileError = nil
|
||
return Task { @MainActor in
|
||
do {
|
||
// Validate fully before disturbing current execution or files.
|
||
let bytes: Data? = try await Task.detached(priority: .userInitiated) {
|
||
switch destination {
|
||
case .systemROM: return try ROMImage.read(url)
|
||
case .diskROM: return try DiskFiles.readROM(url)
|
||
case .binary: return try BinaryFile.read(url)
|
||
case .cassette: return try TapeImage.read(url)
|
||
case .floppy: _ = try DiskFiles.readImage(url); return nil
|
||
case .hardDisk: _ = try HardDiskFiles.readImage(url); return nil
|
||
case .cartridge: return try DiskFiles.readCartridgeROM(url)
|
||
}
|
||
}.value
|
||
let paused = await diskStep(controller.pauseForDiskChange)
|
||
if let error = paused.errorMessage { throw ProfileFailure.message(error) }
|
||
if let pending = diskSaveTask { await pending.value }
|
||
await saveAutomaticDisks(); await saveAutomaticHardDisks(force: true)
|
||
_ = await diskStep(controller.snapshot)
|
||
guard !unsavedMedia else { throw ProfileFailure.message("Save As or export unsaved media before opening another file. The machine is paused; your media and recordings are kept.") }
|
||
switch destination {
|
||
case .systemROM: installROM(bytes!, url: url)
|
||
case .diskROM: selectDiskROM(url)
|
||
case .binary:
|
||
command({ controller.quickLoadBinary(bytes!, completion: $0) }, onSuccess: { [self] in binaryName = url.lastPathComponent; recentMedia.record(url, as: .binary) })
|
||
case .cassette: readTape(url)
|
||
case .floppy(let n): insertDisk(url, drive: n)
|
||
case .hardDisk(let n): insertHardDisk(url, drive: n)
|
||
case .cartridge(let n): selectCartridgeROM(url, slot: n)
|
||
}
|
||
} catch { fileError = error.localizedDescription; busy = false }
|
||
}
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
extension MachineModel {
|
||
func saveScreenshot() {
|
||
guard !screenshotInProgress else { return }
|
||
let capture: ScreenCapture
|
||
do { capture = try ScreenCapture(pixels: pixels, area: activeVideoRect) }
|
||
catch { fileError = error.localizedDescription; return }
|
||
screenshotInProgress = true; fileError = nil
|
||
let panel = NSSavePanel()
|
||
panel.title = "Save CoCo Screen"
|
||
panel.message = "Save the picture captured when you chose this command. PNG uses the active picture’s native resolution, without the window, scaling or scanline effects. The CoCo keeps running."
|
||
panel.allowedContentTypes = [.png]; panel.canCreateDirectories = true
|
||
let format = DateFormatter(); format.dateFormat = "yyyy-MM-dd HH-mm-ss"
|
||
panel.nameFieldStringValue = "VCC Screen \(format.string(from: Date())).png"
|
||
panel.begin { [weak self] result in
|
||
guard let self else { return }
|
||
guard result == .OK, let url = panel.url else { self.screenshotInProgress = false; return }
|
||
Task { @MainActor in
|
||
defer { self.screenshotInProgress = false }
|
||
do { try await Task.detached(priority: .userInitiated) { try capture.save(to: url) }.value }
|
||
catch { self.fileError = error.localizedDescription }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Library launches reuse the profile transaction; neither this preview nor the
|
||
// catalog owns a second emulator. The captured setup is configuration, not RAM.
|
||
struct PreparedLibraryLaunch {
|
||
let plan: SoftwareLibraryLaunchPlan
|
||
let profile: ConfigurationProfile
|
||
let previousSetup: ConfigurationProfile?
|
||
fileprivate let expectedConfiguration: ConfigurationProfile
|
||
fileprivate let expectedEpoch: UInt64
|
||
}
|
||
struct LibraryMachineLaunchResult {
|
||
let message: String?
|
||
}
|
||
|
||
extension MachineModel {
|
||
var canLaunchLibrarySoftware: Bool { !busy && !diskSaving && state != .closed }
|
||
|
||
func prepareLibraryLaunch(_ plan: SoftwareLibraryLaunchPlan) async throws -> PreparedLibraryLaunch {
|
||
guard canLaunchLibrarySoftware else { throw ProfileFailure.message("Wait for the current machine operation to finish.") }
|
||
busy = true; defer { busy = false }
|
||
let previous = profileConfiguration, epoch = inputEpoch
|
||
try await Task.detached(priority: .userInitiated) { try plan.validateMedia() }.value
|
||
var profile = ConfigurationProfile(name: String(plan.title.prefix(100)))
|
||
profile.machine = MachineSettings(use6309: plan.use6309, ram: plan.ramIndex,
|
||
overclock: 1, frameInterval: 1, fastForward: false)
|
||
profile.videoOutput = plan.videoOutput ?? videoOutput.rawValue
|
||
profile.sound = audioEnabled; profile.volume = volume
|
||
profile.input = input.settings
|
||
// Native keyboard controls (for example Double Dragon) must reach the
|
||
// guest rather than being consumed by keyboard-emulated joysticks.
|
||
if plan.controls["keyboard"].string != nil {
|
||
for port in 0..<2 where profile.input[port].source == .keyboard { profile.input[port].source = .none }
|
||
}
|
||
// Hardware choices the user already made remain in effect; Archive hints
|
||
// only supply an otherwise unassigned port, never replace a real controller.
|
||
for (name, port) in [("right", 0), ("left", 1)] where profile.input[port].source == .none && plan.controls["keyboard"].string == nil {
|
||
switch plan.controls[name]["suggested_input"].string {
|
||
case "keyboard-joystick": profile.input[port].source = .keyboard
|
||
case "mouse-joystick": profile.input[port].source = .mouse
|
||
default: break
|
||
}
|
||
}
|
||
let kit = startupStore?.kit, support = startupStore?.directory
|
||
func firmware(_ name: String, fallback: URL?) throws -> URL {
|
||
if let kit, let support, let url = try? kit.rom(name, in: support) { return url }
|
||
guard let fallback else { throw ProfileFailure.message("The recommended setup needs \(name). Choose that firmware in the existing machine or cartridge settings, then try again.") }
|
||
return fallback
|
||
}
|
||
profile.systemROM = try firmware("coco3.rom", fallback: systemROMURL)
|
||
var layout = CartridgeAssignments()
|
||
layout.multiPak = true; layout.mpiConfigured = true; layout.physicalSlot = plan.controllerSlot
|
||
switch plan.profile {
|
||
case .romCartridge:
|
||
guard let cartridge = plan.cartridgeURL else { throw ProfileFailure.message("Choose a cartridge file before starting this title.") }
|
||
layout.slots[plan.controllerSlot] = .init(kind: plan.cartridgeDevice == .orchestra90 ? .orchestra90 : .rom, url: cartridge)
|
||
case .diskBasic:
|
||
profile.media.rom = try firmware("disk11.rom", fallback: diskAssignments.rom)
|
||
layout.slots[plan.controllerSlot].kind = .floppy
|
||
case .cocoSDC:
|
||
let priorROM = cartridgeAssignments.slots.first { $0.kind == .sdc }?.url
|
||
layout.slots[plan.controllerSlot] = .init(kind: .sdc, url: try firmware("sdcdos.rom", fallback: priorROM),
|
||
sdcFolderURL: plan.sdcFolderURL, sdcReadOnly: false)
|
||
}
|
||
profile.media.cartridges = layout
|
||
profile.media.hardDisks = HardDiskAssignments()
|
||
for (drive, url) in plan.floppyURLs { profile.media.drives[drive] = .init(url: url, writeProtected: false) }
|
||
profile.cassette = plan.cassetteURL; profile.fastCassette = plan.cassetteURL != nil
|
||
profile.bootNitros9 = nil
|
||
try profile.validate()
|
||
let checked = profile
|
||
_ = try await Task.detached(priority: .userInitiated) { try PreparedProfile.read(checked) }.value
|
||
try Task.checkCancellation()
|
||
guard inputEpoch == epoch, profileConfiguration == previous else { throw ProfileFailure.message("The machine setup changed while preparing this title. Choose Play again to review the new setup.") }
|
||
var returnSetup = previous; returnSetup.name = "Previous Setup"
|
||
let hasUnbackedMedia = (tapeMounted && cassetteURL == nil) ||
|
||
disks.enumerated().contains { $0.element.mounted && previous.media.drives[$0.offset] == nil } ||
|
||
hardDisks.enumerated().contains { $0.element.mounted && previous.media.hardDisks?.drives[$0.offset] == nil }
|
||
return PreparedLibraryLaunch(plan: plan, profile: profile,
|
||
previousSetup: state == .empty || previous.systemROM == nil || hasUnbackedMedia ? nil : returnSetup,
|
||
expectedConfiguration: previous, expectedEpoch: epoch)
|
||
}
|
||
|
||
func launchLibrary(_ prepared: PreparedLibraryLaunch) async throws -> LibraryMachineLaunchResult {
|
||
guard canLaunchLibrarySoftware, inputEpoch == prepared.expectedEpoch,
|
||
profileConfiguration == prepared.expectedConfiguration else {
|
||
throw ProfileFailure.message("The machine setup changed after this preview. Choose Play again before restarting it.")
|
||
}
|
||
try Task.checkCancellation()
|
||
var startupMessage: String?
|
||
let returnToNitros9 = builtInNitros9 ? prepared.previousSetup : nil
|
||
let applied = await loadProfile(preparing: {
|
||
try await Task.detached(priority: .userInitiated) { try prepared.plan.validateMedia() }.value
|
||
return prepared.profile
|
||
}, startRunning: true, afterStart: { [self] in
|
||
do {
|
||
try Task.checkCancellation()
|
||
if prepared.plan.cassetteURL != nil && !prepared.plan.commands.isEmpty {
|
||
let playing = await diskStep { controller.tapeAction(1, completion: $0) }
|
||
if let error = playing.errorMessage { throw ProfileFailure.message(error) }
|
||
}
|
||
if !prepared.plan.commands.isEmpty {
|
||
let generation = imageGeneration
|
||
try await waitForLibraryPrompt(generation: generation, timeout: 15)
|
||
for (index, command) in prepared.plan.commands.enumerated() {
|
||
try Task.checkCancellation()
|
||
let paste = try CocoPaste(command + "\n", mode: .text)
|
||
let queued = await diskStep { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) }
|
||
if let error = queued.errorMessage { throw ProfileFailure.message(error) }
|
||
try await waitForLibraryPaste(generation: generation, timeout: 60)
|
||
if index + 1 < prepared.plan.commands.count || !prepared.plan.automaticallyStarts {
|
||
try await waitForLibraryPrompt(generation: generation, timeout: prepared.plan.cassetteURL == nil ? 30 : 120)
|
||
}
|
||
}
|
||
try Task.checkCancellation()
|
||
// A running game need not return to BASIC or remain in text
|
||
// mode. Still catch an immediate final RUN/EXEC/DOS failure.
|
||
let (text, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { c in
|
||
controller.inspectScreenText { c.resume(returning: ($0, $1)) }
|
||
}
|
||
guard snapshot.generation == generation, snapshot.state == .running else {
|
||
throw ProfileFailure.message("The CoCo stopped or changed while starting the software.")
|
||
}
|
||
if let error = snapshot.errorMessage { throw ProfileFailure.message(error) }
|
||
if let text, Self.libraryScreenHasBASICError(text) {
|
||
throw ProfileFailure.message("BASIC reported a loading error. Check the mounted files and instructions.")
|
||
}
|
||
}
|
||
} catch {
|
||
_ = await diskStep(controller.cancelPaste)
|
||
_ = await diskStep(controller.pause)
|
||
startupMessage = error is CancellationError ? "Automatic loading stopped. The installed setup is paused; its files are still mounted." : "The setup is installed and paused. " + error.localizedDescription + " Follow the loading instructions or return to the previous setup."
|
||
}
|
||
})
|
||
guard applied else { throw ProfileFailure.message(profileError ?? "The setup could not be installed; the previous media has been preserved.") }
|
||
libraryReturnToNitros9 = returnToNitros9
|
||
return LibraryMachineLaunchResult(message: startupMessage ?? profileError)
|
||
}
|
||
|
||
func returnLibrarySetup(_ profile: ConfigurationProfile) async throws {
|
||
guard canLaunchLibrarySoftware else { throw ProfileFailure.message("Wait for the current machine operation to finish.") }
|
||
_ = try await Task.detached(priority: .userInitiated) { try PreparedProfile.read(profile) }.value
|
||
try Task.checkCancellation()
|
||
let applied = await loadProfile(preparing: { profile }, startRunning: true, builtInNitros9: profile == libraryReturnToNitros9)
|
||
guard applied, profileError == nil else { throw ProfileFailure.message(profileError ?? "The previous setup could not be restored.") }
|
||
libraryReturnToNitros9 = nil
|
||
}
|
||
|
||
private func waitForLibraryPaste(generation: UInt64, timeout: TimeInterval) async throws {
|
||
let deadline = Date().addingTimeInterval(timeout)
|
||
while Date() < deadline {
|
||
try Task.checkCancellation()
|
||
let snapshot = await diskStep(controller.snapshot)
|
||
guard snapshot.generation == generation, snapshot.state == .running else { throw ProfileFailure.message("The CoCo stopped or changed while entering the loading command.") }
|
||
if let error = snapshot.errorMessage { throw ProfileFailure.message(error) }
|
||
if snapshot.pasteRemaining == 0 { return }
|
||
try await Task.sleep(nanoseconds: 100_000_000)
|
||
}
|
||
throw ProfileFailure.message("Entering the loading command timed out.")
|
||
}
|
||
private static func libraryScreenHasBASICError(_ text: String) -> Bool {
|
||
text.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }
|
||
.filter { !$0.isEmpty }.suffix(3).contains { $0.hasPrefix("?") && $0.contains("ERROR") }
|
||
}
|
||
#if DEBUG
|
||
func waitForMCPFixturePrompt() async throws {
|
||
let snapshot = await mcpMachineSnapshot()
|
||
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
|
||
var reason = ""
|
||
while ContinuousClock.now < deadline {
|
||
do {
|
||
let observed = try await mcpScreen(expected: snapshot, source: "")
|
||
if observed["direct_prompt"] as? Bool == true { return }
|
||
reason = observed["text"] as? String ?? ""
|
||
} catch { reason = error.localizedDescription }
|
||
try await Task.sleep(for: .milliseconds(100))
|
||
}
|
||
let (text, last): (String?, VCCMachineSnapshot) = await withCheckedContinuation { c in
|
||
controller.inspectScreenText { c.resume(returning: ($0, $1)) }
|
||
}
|
||
throw ProfileFailure.message("BASIC fixture did not reach direct input. " + reason + " Screen: " + (text ?? "(unavailable)") +
|
||
String(format: " PC %04X, frame %llu.", last.programCounter, last.frames))
|
||
}
|
||
#endif
|
||
private func waitForLibraryPrompt(generation: UInt64, timeout: TimeInterval) async throws {
|
||
let deadline = Date().addingTimeInterval(timeout)
|
||
var readyObservations = 0
|
||
while Date() < deadline {
|
||
try Task.checkCancellation()
|
||
let (text, snapshot): (String?, VCCMachineSnapshot) = await withCheckedContinuation { c in
|
||
controller.inspectScreenText { c.resume(returning: ($0, $1)) }
|
||
}
|
||
guard snapshot.generation == generation, snapshot.state == .running else { throw ProfileFailure.message("The CoCo stopped or changed while waiting for BASIC.") }
|
||
if let error = snapshot.errorMessage { throw ProfileFailure.message(error) }
|
||
// Text-mode discovery may fail transiently during boot. Only a real,
|
||
// visible BASIC prompt permits typing; a timer never implies readiness.
|
||
if let text, snapshot.pasteRemaining == 0 {
|
||
let lines = text.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
|
||
if Self.libraryScreenHasBASICError(text) {
|
||
throw ProfileFailure.message("BASIC reported a loading error. Check the mounted files and instructions.")
|
||
}
|
||
readyObservations = lines.last == "OK" ? readyObservations + 1 : 0
|
||
if readyObservations >= 2 { accept(snapshot); return }
|
||
} else { readyObservations = 0 }
|
||
try await Task.sleep(nanoseconds: 100_000_000)
|
||
}
|
||
throw ProfileFailure.message("A BASIC prompt was not detected before the loading timeout; no further commands were sent.")
|
||
}
|
||
}
|