// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import Combine enum ProfileFailure: LocalizedError { case message(String) var errorDescription: String? { if case .message(let text) = self { return text }; return nil } } // Profiles contain configuration and local file references only, never ROM, // disk, tape, RAM, or execution-state bytes. Version changes require migration. struct ConfigurationProfile: Codable, Equatable, Identifiable { var version = 1 var id = UUID() var name: String var machine = MachineSettings() var videoOutput = 1 var sound = true var volume = 0.5 var systemROM: URL? var media = DiskAssignments() var input = InputSettings() var cassette: URL? var fastCassette = false var bootNitros9: Bool? // Missing in older profiles means ordinary BASIC startup. enum Reference: Hashable { case systemROM, floppyROM, cartridge(Int), speechROM(Int), sdcFolder(Int), floppy(Int), hardDisk(Int), cassette var label: String { switch self { case .systemROM: return "System ROM" case .floppyROM: return "Floppy ROM" case .sdcFolder(let slot): return "SD card folder — \(slot == 0 ? "single cartridge" : "Multi-Pak slot \(slot)")" case .speechROM(let slot): return "Speech ROM — \(slot == 0 ? "single cartridge" : "Multi-Pak slot \(slot)")" case .cartridge(let slot): return slot == 0 ? "Single cartridge" : "Multi-Pak slot \(slot)" case .floppy(let drive): return "Floppy drive \(drive)" case .hardDisk(let drive): return "Hard disk \(drive)" case .cassette: return "Cassette" } } } var references: [(key: Reference, url: URL)] { var result: [(Reference, URL)] = [] if let systemROM { result.append((.systemROM, systemROM)) } if let url = media.rom { result.append((.floppyROM, url)) } for (i, slot) in (media.cartridges?.slots ?? []).enumerated() { if let url = slot.url { result.append((.cartridge(i), url)) } if let url = slot.speechROMURL { result.append((.speechROM(i), url)) } if let url = slot.sdcFolderURL { result.append((.sdcFolder(i), url)) } } for (i, drive) in media.drives.enumerated() { if let drive { result.append((.floppy(i), drive.url)) } } for (i, drive) in (media.hardDisks?.drives ?? []).enumerated() { if let drive { result.append((.hardDisk(i), drive.url)) } } if let cassette { result.append((.cassette, cassette)) } return result } mutating func replace(_ reference: Reference, with url: URL) { switch reference { case .systemROM: systemROM = url case .floppyROM: media.rom = url case .cartridge(let i): media.cartridges?.slots[i].url = url case .speechROM(let i): media.cartridges?.slots[i].speechROMURL = url case .sdcFolder(let i): media.cartridges?.slots[i].sdcFolderURL = url case .floppy(let i): media.drives[i]?.url = url case .hardDisk(let i): media.hardDisks?.drives[i]?.url = url case .cassette: cassette = url } } func validate() throws { guard version == 1, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, name.count <= 100, !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), machine.valid, (0...2).contains(videoOutput), volume.isFinite, (0...1).contains(volume) else { throw ProfileFailure.message("Invalid profile settings or unsupported profile version.") } try media.validate(); _ = try input.validated() guard references.allSatisfy({ _, url in url.isFileURL && url.path.hasPrefix("/") && url.path.count <= 8192 && (url.host == nil || url.host == "" || url.host == "localhost") && url.query == nil && url.fragment == nil }) else { throw ProfileFailure.message("Profiles must reference local files. Choose replacement files on this Mac.") } } } struct ProfileStore { static let maxBytes = 65536 let directory: URL static let standard = Self(directory: AppIdentity.supportDirectory.appendingPathComponent("Profiles", isDirectory: true)) func file(_ id: UUID) -> URL { directory.appendingPathComponent(id.uuidString).appendingPathExtension("vccprofile") } static func read(_ url: URL) throws -> ConfigurationProfile { let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } let data = try handle.read(upToCount: maxBytes + 1) ?? Data() guard data.count <= maxBytes else { throw ProfileFailure.message("The profile exceeds 64 KB.") } let profile = try JSONDecoder().decode(ConfigurationProfile.self, from: data) try profile.validate(); return profile } static func write(_ profile: ConfigurationProfile, to url: URL) throws { try profile.validate() let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let data = try encoder.encode(profile) guard data.count <= maxBytes else { throw ProfileFailure.message("The profile exceeds 64 KB.") } try data.write(to: url, options: .atomic) } func load() throws -> [ConfigurationProfile] { guard FileManager.default.fileExists(atPath: directory.path) else { return [] } let urls = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) .filter { $0.pathExtension == "vccprofile" } guard urls.count <= 128 else { throw ProfileFailure.message("The profile library supports up to 128 profiles.") } return try urls.map { url in let value = try Self.read(url) guard url.lastPathComponent == file(value.id).lastPathComponent else { throw ProfileFailure.message("A profile's identifier does not match its library filename: \(url.lastPathComponent)") } return value }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } func save(_ value: ConfigurationProfile) throws { try value.validate() let existing = try load() guard !existing.contains(where: { $0.id != value.id && $0.name.caseInsensitiveCompare(value.name) == .orderedSame }) else { throw ProfileFailure.message("A profile with that name already exists. Choose another name or update the existing profile.") } guard existing.count < 128 || existing.contains(where: { $0.id == value.id }) else { throw ProfileFailure.message("The profile library supports up to 128 profiles.") } try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) try Self.write(value, to: file(value.id)) } func delete(_ id: UUID) throws { try FileManager.default.removeItem(at: file(id)) } } @MainActor final class ProfileLibrary: ObservableObject { @Published private(set) var profiles: [ConfigurationProfile] = [] @Published var error: String? private let store: ProfileStore init(store: ProfileStore = .standard) { self.store = store; reload() } func reload() { do { profiles = try store.load(); error = nil } catch { self.error = error.localizedDescription } } @discardableResult func save(_ profile: ConfigurationProfile) -> Bool { do { try store.save(profile); reload(); return error == nil } catch { self.error = error.localizedDescription; return false } } func delete(_ id: UUID) { do { try store.delete(id); reload() } catch { self.error = error.localizedDescription } } } struct PreparedProfile { let profile: ConfigurationProfile var systemROM: Data? var diskROM: Data? var cartridges = Array(repeating: Data(), count: 5) var floppies: [DiskFiles.Image?] = Array(repeating: nil, count: 4) var hardDisks: [HardDiskFiles.Image?] = Array(repeating: nil, count: 2) var cassette: Data? static func read(_ profile: ConfigurationProfile) throws -> Self { try profile.validate() var result = Self(profile: profile) var failures: [String] = [] for (key, url) in profile.references { do { switch key { case .systemROM: result.systemROM = try ROMImage.read(url) case .floppyROM: result.diskROM = try DiskFiles.readROM(url) case .cartridge(let i): result.cartridges[i] = try DiskFiles.readCartridgeAssignment(profile.media.cartridges!.slots[i]) case .sdcFolder: try DiskFiles.validateSDCFolder(url) case .speechROM(let i): result.cartridges[i] = try DiskFiles.readCartridgeAssignment(profile.media.cartridges!.slots[i]) case .floppy(let i): let image = try DiskFiles.readImage(url) guard !image.data.isEmpty else { throw ProfileFailure.message("The floppy image is empty.") } result.floppies[i] = image case .hardDisk(let i): result.hardDisks[i] = try HardDiskFiles.readImage(url) case .cassette: result.cassette = try TapeImage.read(url) } } catch { failures.append("\(key.label): \(url.path)\n\(error.localizedDescription)") } } guard failures.isEmpty else { throw ProfileFailure.message("Profile files need attention. Use Replace… to select their locations.\n\n" + failures.joined(separator: "\n\n")) } return result } func request() -> VCCMachineProfile { let request = VCCMachineProfile(), p = profile, layout = p.media.cartridges ?? CartridgeAssignments() let hard = p.media.hardDisks ?? HardDiskAssignments() request.use6309 = p.machine.use6309; request.ram = p.machine.ram; request.overclock = p.machine.overclock request.frameInterval = p.machine.frameInterval; request.fastForward = p.machine.fastForward request.videoOutput = p.videoOutput; request.sound = p.sound; request.volume = Float(p.volume) request.systemROM = systemROM; request.diskROM = diskROM; request.diskROMName = p.media.rom?.lastPathComponent ?? "" request.multiPak = layout.multiPak; request.physicalSlot = layout.physicalSlot request.kinds = layout.slots.map { NSNumber(value: $0.kind.rawValue) }; request.cartridgeROMs = cartridges request.cartridgeNames = layout.slots.map { $0.url?.lastPathComponent ?? "" } request.sdcFolders = layout.slots.map { $0.sdcFolderURL?.path ?? "" } request.sdcReadOnly = layout.slots.map { NSNumber(value: $0.sdcReadOnly ?? true) } request.images = floppies.map { $0?.data ?? Data() } + hardDisks.map { $0?.data ?? Data() } request.imageNames = (p.media.drives + hard.drives).map { $0?.url.lastPathComponent ?? "" } request.readOnly = floppies.map { NSNumber(value: $0?.readOnly ?? false) } + hardDisks.map { NSNumber(value: $0?.readOnly ?? false) } request.protectedImages = (p.media.drives + hard.drives).map { NSNumber(value: $0?.writeProtected ?? false) } request.clockEnabled = hard.clockEnabled; request.clockReadOnly = hard.clockReadOnly request.cassette = cassette; request.cassetteWAV = p.cassette?.pathExtension.lowercased() == "wav" request.fastCassette = p.fastCassette return request } } // A derived, read-only companion to v1 profiles, not unversioned file metadata. // It describes connected hardware; it never promises an arbitrary image boots. struct ProfileGuidance { let title: String let coverage: String let explanation: String init(_ profile: ConfigurationProfile) { let layout = profile.media.cartridges ?? CartridgeAssignments() let slots = layout.multiPak ? Array(layout.slots.dropFirst()) : [layout.slots[0]] let floppy = slots.contains { $0.kind == .floppy } let hard = slots.contains { $0.kind == .hardDisk } let rom = slots.contains { $0.kind == .rom } let orchestra = slots.contains { $0.kind == .orchestra90 } let ramDisk = slots.contains { $0.kind == .ramDisk } let sdc = slots.contains { $0.kind == .sdc } coverage = ramDisk ? "Custom configuration: conventional controls for RAM disk" : layout.multiPak ? "System view: Multi-Pak layout" : slots[0].kind == .empty ? "System view: computer, cassette and input" : "Custom configuration: conventional display for direct-connected hardware" if sdc { title = "CoCo SDC" explanation = "The selected Mac folder represents an SD card. SDC-DOS lets supporting software browse and mount images from it. Select the SDC startup slot, then use DRIVE 0,\"NAME.DSK\" to mount an image. Read-only protection is on by default; when disabled, guest writes and file-management commands change files in that folder. Profiles remember the folder and ROM, not mounted-image or program state." } else if ramDisk { title = "Volatile RAM disk" explanation = "The 512 KB RAM disk needs supporting software, not a boot ROM. It is not a Disk BASIC drive. Resets retain its contents; loading a profile, quitting, or removing its last assignment discards them. Profiles remember the assignment only. Existing floppy and hard-disk media remain separate." } else if slots.contains(where: { $0.kind == .speechSound }) { title = "Speech/Sound Cartridge" explanation = "Supporting CoCo programs send speech and music commands to this cartridge. It needs both internal chip ROMs, but has no boot program; leave your disk controller as the startup slot. Sound and volume use the normal Mac controls. Profiles retain the ROM locations, not playback state." } else if orchestra { title = "Orchestra-90 stereo sound" explanation = "Supporting software can play stereo through Orchestra-90 without a ROM. An optional 8 KiB ROM adds its music program; select that slot as the startup slot to boot it. Sound and volume use the normal Mac audio controls. The ROM location is remembered, but profiles do not save music or playback state." } else if hard { title = "Expanded storage" explanation = "The floppy and virtual hard-disk controllers are separate devices. A compatible disk ROM or OS-9 boot disk is needed; attaching a VHD does not boot it." } else if floppy { title = "Floppy software" explanation = "The FD-502-based controller serves FD0–FD3. With a compatible Disk BASIC ROM, DIR lists the selected disk. Follow that software's loading or boot instructions; insertion alone does not run it." } else if rom { title = "Cartridge software" explanation = "The cartridge is program ROM, not a disk image. In Multi-Pak mode, the startup slot chooses the initial cartridge; software can change live routing. Loading this profile restarts and leaves the machine paused." } else { title = "BASIC and cassette" explanation = "Choose a compatible system ROM, then Run. For tape loading, Play prepares the recorder and CLOAD in BASIC starts the computer-controlled transfer. After recording with CSAVE, export the tape to keep its file." } } }