// SPDX-License-Identifier: GPL-3.0-or-later import Foundation enum DiskFiles { static let extensions = ["dsk", "jvc", "os9", "dmk", "vdk"] static let limit = 16 * 1024 * 1024 struct Image: Sendable { let data: Data; let readOnly: Bool } enum Failure: LocalizedError { case notFile, tooLarge, extensionType, romSize, changed, readOnly, cartridgeROM, orchestraROM var errorDescription: String? { switch self { case .orchestraROM: return "Choose an 8 KiB Orchestra-90 ROM. The stereo sound hardware can also be used without a ROM." case .cartridgeROM: return "Choose a raw cartridge ROM (1 byte to 256 KiB), not a Windows DLL or a disk image." case .notFile: return "Choose a regular disk image or disk ROM file." case .tooLarge: return "Disk images must be no larger than 16 MiB." case .extensionType: return "Choose a DSK, JVC, OS-9, DMK or VDK floppy disk image." case .romSize: return "Choose an 8 or 16 KiB disk ROM, such as disk11.rom. The CoCo 3 system ROM is selected separately." case .changed: return "The disk file changed outside this drive. Use Save As to keep your changes in a separate file, or reinsert the disk." case .readOnly: return "The disk file is no longer writable. Restore write access and retry, or use Save As." } } } private static func read(_ url: URL, limit: Int) throws -> Data { guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile } let file = try FileHandle(forReadingFrom: url) defer { try? file.close() } var bytes = Data() while bytes.count <= limit { guard let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - bytes.count)), !chunk.isEmpty else { break } bytes.append(chunk) } return bytes } static func readROM(_ url: URL) throws -> Data { let bytes = try read(url, limit: 16384) guard bytes.count == 8192 || bytes.count == 16384 else { throw Failure.romSize } return bytes } static func readCartridgeROM(_ url: URL) throws -> Data { guard !extensions.contains(url.pathExtension.lowercased()), !["dll", "exe"].contains(url.pathExtension.lowercased()) else { throw Failure.cartridgeROM } let bytes = try read(url, limit: 262144) guard !bytes.isEmpty, bytes.count <= 262144, !bytes.starts(with: [0x4d, 0x5a]) else { throw Failure.cartridgeROM } return bytes } static func readOrchestraROM(_ url: URL) throws -> Data { let bytes = try readCartridgeROM(url) guard bytes.count == 8192 else { throw Failure.orchestraROM } return bytes } static func readSpeechChipROM(_ url: URL, speech: Bool) throws -> Data { let size = speech ? 2048 : 4096 let bytes = try read(url, limit: size) guard bytes.count == size else { throw ProfileFailure.message(speech ? "Choose the 2 KiB SP0256-AL2 speech ROM." : "Choose the 4 KiB PIC7040 firmware ROM.") } return bytes } static func readSDCROM(_ url: URL) throws -> Data { let bytes = try readCartridgeROM(url) guard bytes.count == 8192 || bytes.count == 16384 else { throw ProfileFailure.message("Choose an 8 or 16 KiB SDC-DOS ROM. The CoCo system ROM and FD-502 disk ROM are separate.") } return bytes } static func validateSDCFolder(_ url: URL) throws { guard url.isFileURL, try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true, FileManager.default.isReadableFile(atPath: url.path) else { throw ProfileFailure.message("The SD card folder is unavailable. Reconnect it or choose its new location in Cartridges.") } } static func readCartridgeAssignment(_ slot: CartridgeAssignments.Slot) throws -> Data { if slot.kind == .sdc { guard let rom = slot.url, let folder = slot.sdcFolderURL else { throw ProfileFailure.message("CoCo SDC needs an SDC-DOS ROM and an SD card folder. Choose both in Cartridges.") } try validateSDCFolder(folder) return try readSDCROM(rom) } if slot.kind == .speechSound { guard let pic = slot.url, let speech = slot.speechROMURL else { throw ProfileFailure.message("Speech/Sound needs both its PIC firmware and speech ROM. Choose both files in Cartridges.") } return try readSpeechChipROM(pic, speech: false) + readSpeechChipROM(speech, speech: true) } guard let url = slot.url else { return Data() } return try slot.kind == .orchestra90 ? readOrchestraROM(url) : readCartridgeROM(url) } static func readImage(_ url: URL) throws -> Image { guard extensions.contains(url.pathExtension.lowercased()) else { throw Failure.extensionType } let bytes = try read(url, limit: limit) guard bytes.count <= limit else { throw Failure.tooLarge } return Image(data: bytes, readOnly: !FileManager.default.isWritableFile(atPath: url.path)) } /// A separate BASIC export must not bypass mounted-media write protection, /// pending saves, temporary changes or source-document conflict handling. static func exportBASIC(_ bytes: Data, to url: URL, protecting references: [URL]) throws { try writeDevelopmentFile(bytes, to: url, protecting: references) } static func writeDevelopmentFile(_ bytes: Data, to url: URL, protecting references: [URL], allowEmpty: Bool = false, replacing expected: Data? = nil, requireNew: Bool = false) throws { try DiskEditorIO.write(bytes, to: url, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew) } /// File promises already own destination coordination through completion. static func writeReceivedFilePromise(_ bytes: Data, to url: URL, protecting references: [URL]) throws { try DiskEditorIO.write(bytes, to: url, protecting: references, allowEmpty: true, requireNew: true, coordinated: false) } static func export(_ bytes: Data, to url: URL) throws { try bytes.write(to: url, options: .atomic) } // Coordinate with cooperating document apps and compare with the last bytes // we read/wrote. Never recreate a missing source or overwrite external edits. static func saveAutomatically(_ bytes: Data, to url: URL, expected: Data) throws { var coordinationError: NSError? var writeError: Error? NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in do { // The selected .dsk may be a symlink to a differently named file. let current = try read(target, limit: limit) guard current.count <= limit else { throw Failure.tooLarge } guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly } guard current == expected else { throw Failure.changed } try export(bytes, to: target) } catch { writeError = error } } if let error = coordinationError { throw error } if let error = writeError { throw error } } }