// SPDX-License-Identifier: GPL-3.0-or-later import Foundation /// An immutable copy of a mounted disk; mutations belong to the editor only. struct DiskEditorSession: Sendable { let id: UUID let token: UInt64 let drive: Int let name: String let data: Data let canApply: Bool let sourceURL: URL? let temporary: Bool let applyRestriction: String? let hardDisk: Bool init(id: UUID, token: UInt64, drive: Int, name: String, data: Data, canApply: Bool, sourceURL: URL?, temporary: Bool, applyRestriction: String?, hardDisk: Bool = false) { self.id = id; self.token = token; self.drive = drive; self.name = name; self.data = data self.canApply = canApply; self.sourceURL = sourceURL; self.temporary = temporary self.applyRestriction = applyRestriction; self.hardDisk = hardDisk } var driveLabel: String { "\(hardDisk ? "HD" : "FD")\(drive)" } } /// The editor owns its working copy and native interface. Each application owns /// media identity, guest exclusion, restart policy and the final atomic commit. @MainActor protocol DiskEditorHost: AnyObject { func beginDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession func cancelDiskEditor(_ session: DiskEditorSession) async throws func applyDiskEditor(_ session: DiskEditorSession, data: Data, restartConfirmed: Bool) async throws func saveDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws func savePromisedDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?) async throws func saveOfflineDiskEditor(_ data: Data, to url: URL, replacing original: Data) async throws func mountedEditorDrive(for url: URL) -> Int? func mountedHardDiskEditorDrive(for url: URL) -> Int? func diskEditorSourceIsAssigned(_ url: URL) -> Bool func diskEditorPresentation(for session: DiskEditorSession?) -> DiskEditorPresentation } struct DiskEditorPresentation { let context: String let applyHint: String let applyButtonTitle: String let applyConfirmationTitle: String let applyConfirmationMessage: String let applyConfirmationAction: String let closeNotice: String } extension DiskEditorHost { func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession { throw DiskEditorFailure.message("Hard-disk editing is unavailable in this application.") } func mountedHardDiskEditorDrive(for url: URL) -> Int? { nil } func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws { try await saveDiskEditorExport(data, to: url, protecting: sourceURL, replacing: expected, requireNew: requireNew) } func diskEditorPresentation(for session: DiskEditorSession?) -> DiskEditorPresentation { DiskEditorPresentation( context: session.map { "\($0.driveLabel) · CoCo paused and locked" } ?? "Unmounted image · CoCo unchanged", applyHint: session == nil ? "Edits remain in a private copy until saved." : "Applying changes requires a CoCo restart.", applyButtonTitle: session.map { "Apply to \($0.driveLabel)…" } ?? "Save Changes…", applyConfirmationTitle: session == nil ? "Save changes to this disk image?" : "Apply disk changes and restart the CoCo?", applyConfirmationMessage: session == nil ? "The original image will be replaced only if its bytes have not changed outside the editor." : "Restarting clears the running guest program and its memory so it cannot reuse old filesystem information. Mounted media and edited disk bytes are retained. Save any program or recording you need before applying.", applyConfirmationAction: session == nil ? "Save Changes" : "Restart and Apply", closeNotice: "Apply your disk changes, save an edited copy, or close the Disk Image Editor. The machine remains paused while its disk is locked.") } } #if !VCC_COMPANION_CLIENT extension MachineModel: DiskEditorHost { } #endif /// Editor-local limits keep the shared source independent of emulator ROM and /// cartridge helpers. The reader is the same bounded import reader as the editor. enum DiskEditorIO { static let limit = 16 * 1024 * 1024 static let imageLimit = 512 * 1024 * 1024 static let extensions = ["dsk", "jvc", "os9", "dmk", "vdk", "vhd", "img"] /// Run off the main actor. Both apps use this exact identity/compare/write /// implementation; application-specific media command guards remain outside. static func write(_ bytes: Data, to url: URL, protecting references: [URL], allowEmpty: Bool = false, replacing expected: Data? = nil, requireNew: Bool = false, coordinated: Bool = true, maximum: Int = limit) throws { try validateExport(bytes, to: url, allowEmpty: allowEmpty, maximum: maximum) if !coordinated { try writeValidated(bytes, to: url, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew, maximum: maximum) return } var coordinationError: NSError? var writeError: Error? DiskEditorPromiseDiagnostics.record("development export before coordinate") NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in DiskEditorPromiseDiagnostics.record("development export inside coordinate") do { try writeValidated(bytes, to: target, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew, maximum: maximum) } catch { writeError = error } } if let error = coordinationError ?? writeError as NSError? { throw error } } private static func validateExport(_ bytes: Data, to url: URL, allowEmpty: Bool, maximum: Int) throws { guard url.isFileURL, (allowEmpty || !bytes.isEmpty), bytes.count <= maximum else { throw DiskEditorFailure.message("Choose a regular file within the \(maximum / (1024 * 1024)) MiB export limit.") } } private static func writeValidated(_ bytes: Data, to url: URL, protecting references: [URL], allowEmpty: Bool, replacing expected: Data?, requireNew: Bool, maximum: Int) throws { try validateExport(bytes, to: url, allowEmpty: allowEmpty, maximum: maximum) let path = url.standardizedFileURL.resolvingSymlinksInPath().path let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) if let attributes, attributes[.type] as? FileAttributeType != .typeRegular { throw DiskEditorFailure.message("Choose a regular disk image or disk ROM file.") } if attributes != nil, !FileManager.default.isWritableFile(atPath: url.path) { throw DiskEditorFailure.message("The disk file is no longer writable. Restore write access and retry, or use Save As.") } let inode = attributes?[.systemFileNumber] as? NSNumber let volume = attributes?[.systemNumber] as? NSNumber for reference in references { let resolved = reference.standardizedFileURL.resolvingSymlinksInPath() let other = try? FileManager.default.attributesOfItem(atPath: resolved.path) let sameIdentity = inode != nil && volume != nil && inode == other?[.systemFileNumber] as? NSNumber && volume == other?[.systemNumber] as? NSNumber let inside = other?[.type] as? FileAttributeType == .typeDirectory && path.hasPrefix(resolved.path + "/") if path == resolved.path || sameIdentity || inside { throw DiskEditorFailure.message("Choose a separate file outside your assigned media and source document. To replace a mounted disk or cassette, eject it first using its normal media controls.") } } if let expected { guard attributes != nil, try DiskImageEditorStore.hostBytes(url, maximum: maximum) == expected else { throw DiskEditorFailure.message("This source file changed on disk. Reload it or save a separate copy.") } } try bytes.write(to: url, options: requireNew ? .withoutOverwriting : .atomic) } struct Image: Sendable { let data: Data; let readOnly: Bool } static func readImage(_ url: URL) throws -> Image { guard extensions.contains(url.pathExtension.lowercased()) else { throw DiskEditorFailure.message("Choose a DSK, JVC, OS-9, DMK, VDK, raw VHD or IMG disk image.") } let bytes = try DiskImageEditorStore.hostBytes(url, maximum: imageLimit) return Image(data: bytes, readOnly: !FileManager.default.isWritableFile(atPath: url.path)) } } enum DiskEditorFailure: LocalizedError { case message(String) var errorDescription: String? { switch self { case .message(let text): text } } }