// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import Combine import SwiftUI import UniformTypeIdentifiers struct DiskEditorEntry: Identifiable, Hashable, Sendable { let name: String, path: String, type: String, encoding: String, attributes: String let size: Int64, modified: TimeInterval let directory: Bool let owner: Int, group: Int, permissions: Int var id: String { path } init(_ value: [String: Any]) { name = value["name"] as? String ?? ""; path = value["path"] as? String ?? name type = value["type"] as? String ?? ""; encoding = value["encoding"] as? String ?? "" attributes = value["attributes"] as? String ?? "" size = (value["size"] as? NSNumber)?.int64Value ?? 0 modified = (value["modified"] as? NSNumber)?.doubleValue ?? 0 directory = value["is_directory"] as? Bool ?? false owner = (value["owner"] as? NSNumber)?.intValue ?? 0 group = (value["group"] as? NSNumber)?.intValue ?? 0 permissions = (value["permissions"] as? NSNumber)?.intValue ?? 0 } } struct DiskEditorVolume: Identifiable, Hashable, Sendable { let id: String, name: String, format: String let offset: Int64, byteCount: Int64 init(_ value: [String: Any]) { id = value["id"] as? String ?? ""; name = value["name"] as? String ?? "Volume" format = value["format"] as? String ?? "" offset = (value["offset_bytes"] as? NSNumber)?.int64Value ?? 0 byteCount = (value["byte_count"] as? NSNumber)?.int64Value ?? 0 } } struct DiskEditorContents: Sendable { let entries: [DiskEditorEntry] let bytes: Data let format: String let capacity: Int64?, used: Int64?, free: Int64? let preservedBytes: Int64 let volumes: [DiskEditorVolume] let volumeID: String } /// Retained C libraries and working-image I/O never run on the main actor. actor DiskImageEditorStore { let directory: URL private let image: URL private let volume: URL private var volumeID: String init(data: Data, selectedVolumeID: String? = nil) throws { guard !data.isEmpty, data.count <= DiskEditorIO.imageLimit else { throw DiskEditorFailure.message("Choose a disk image within the 512 MiB limit.") } let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCDiskEditor-" + UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) directory = folder; image = folder.appendingPathComponent("Working.dsk") volume = folder.appendingPathComponent("Volume.dsk"); volumeID = "" do { try data.write(to: image, options: .atomic) let discovered = try VCCDiskImageEditorBackend.discoverVolumes(at: image).map(DiskEditorVolume.init) guard let chosen = selectedVolumeID ?? discovered.first?.id, discovered.contains(where: { $0.id == chosen }) else { throw DiskEditorFailure.message("The selected volume is unavailable in this image.") } volumeID = chosen try VCCDiskImageEditorBackend.extractVolume(chosen, imageURL: image, outputURL: volume) } catch { try? FileManager.default.removeItem(at: folder); throw error } } deinit { let folder = directory Task.detached { try? FileManager.default.removeItem(at: folder) } } func contents(at path: String) throws -> DiskEditorContents { let info = try VCCDiskImageEditorBackend.inspectImage(at: volume) let rows = try VCCDiskImageEditorBackend.listDirectory(path, imageURL: volume) let volumes = try VCCDiskImageEditorBackend.discoverVolumes(at: image).map(DiskEditorVolume.init) let bytes = try Data(contentsOf: image) let selectedSize = volumes.first(where: { $0.id == volumeID })?.byteCount ?? 0 return DiskEditorContents(entries: rows.map(DiskEditorEntry.init), bytes: bytes, format: info["format"] as? String ?? "", capacity: (info["capacity_bytes"] as? NSNumber)?.int64Value, used: (info["used_bytes"] as? NSNumber)?.int64Value, free: (info["free_bytes"] as? NSNumber)?.int64Value, preservedBytes: Int64(bytes.count) - selectedSize, volumes: volumes, volumeID: volumeID) } func selectVolume(_ id: String) throws -> DiskEditorContents { let previous = volumeID do { try VCCDiskImageEditorBackend.extractVolume(id, imageURL: image, outputURL: volume) volumeID = id return try contents(at: "") } catch { try? VCCDiskImageEditorBackend.extractVolume(previous, imageURL: image, outputURL: volume) volumeID = previous throw error } } func restore(_ bytes: Data, path: String) throws -> DiskEditorContents { let before = try Data(contentsOf: image) do { try bytes.write(to: image, options: .atomic) try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume) return try contents(at: path) } catch { try before.write(to: image, options: .atomic) try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume) throw error } } enum Change: Sendable { case importFiles([URL], type: Int, ascii: Bool, replace: Bool) case folder(String) case rename(String, String) case delete([DiskEditorEntry]) case os9Metadata(String, permissions: Int, ownerUser: Int, ownerGroup: Int) case moveFiles([String], String) } func change(_ change: Change, path: String) throws -> DiskEditorContents { let before = try Data(contentsOf: image) do { switch change { case let .importFiles(urls, type, ascii, replace): for url in urls { let data = try Self.hostBytes(url) try VCCDiskImageEditorBackend.importData(data, named: url.lastPathComponent, directory: path, imageURL: volume, fileType: type, ascii: ascii, replace: replace) } case let .folder(name): try VCCDiskImageEditorBackend.makeDirectory(name, in: path, imageURL: volume) case let .rename(old, name): try VCCDiskImageEditorBackend.renameEntry(old, to: name, imageURL: volume) case let .delete(entries): for entry in entries { try VCCDiskImageEditorBackend.deleteEntry(entry.path, directory: entry.directory, imageURL: volume) } case let .os9Metadata(path, permissions, user, group): try VCCDiskImageEditorBackend.setOS9Metadata(for: path, imageURL: volume, ownerUser: user, ownerGroup: group, permissions: permissions) case let .moveFiles(files, destination): try VCCDiskImageEditorBackend.moveFiles(files, toDirectory: destination, imageURL: volume) } try VCCDiskImageEditorBackend.replaceVolume(volumeID, imageURL: image, volumeURL: volume) return try contents(at: path) } catch { // ToolShed edits only the expendable working image. A short write // or full disk must not leave even this session half-mutated. try before.write(to: image, options: .atomic) try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume) throw error } } func read(_ path: String) throws -> Data { try VCCDiskImageEditorBackend.readFile(path, imageURL: volume) } func info(_ path: String) throws -> String { try VCCDiskImageEditorBackend.identifyFile(path, imageURL: volume) } static func hostBytes(_ url: URL, maximum: Int = DiskEditorIO.limit) throws -> Data { guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw DiskEditorFailure.message("Import regular files, not folders.") } let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } var data = Data() while let chunk = try handle.read(upToCount: min(65536, maximum + 1 - data.count)), !chunk.isEmpty { data.append(chunk) guard data.count <= maximum else { throw DiskEditorFailure.message("This file exceeds the \(maximum / (1024 * 1024)) MiB limit.") } } return data } } struct DiskEditorImportRequest: Identifiable { let id = UUID() let urls: [URL] var type: Int = 3 var ascii = true } struct DiskEditorNameRequest: Identifiable { let id = UUID() let entry: DiskEditorEntry? var name: String } struct DiskEditorInformation: Identifiable { let id = UUID() let entry: DiskEditorEntry let details: String } struct DiskEditorMoveRequest: Identifiable, Sendable { let id = UUID() let editorID: UUID, revision: UUID, sessionID: UUID let sourcePath: String let files: [DiskEditorEntry] let bytes: Data } struct DiskEditorDragPayload: Codable, Equatable { let editorID: UUID, revision: UUID, sessionID: UUID let sourcePath: String, files: [String] init(_ request: DiskEditorMoveRequest) { editorID = request.editorID; revision = request.revision; sessionID = request.sessionID sourcePath = request.sourcePath; files = request.files.map(\.path) } } @MainActor final class DiskImageEditorModel: ObservableObject { let editorID = UUID() private(set) var revision = UUID() let store: DiskImageEditorStore let machine: any DiskEditorHost let session: DiskEditorSession? let sourceURL: URL? let name: String let original: Data let sourceReadOnly: Bool weak var window: NSWindow? @Published private(set) var contents: DiskEditorContents @Published var selection = Set() @Published private(set) var path = "" @Published private(set) var busy = false @Published var error: String? @Published var notice: String? @Published var importing: DiskEditorImportRequest? @Published var naming: DiskEditorNameRequest? @Published var information: DiskEditorInformation? @Published var moving: DiskEditorMoveRequest? @Published private(set) var undoStates: [Data] = [] @Published private(set) var redoStates: [Data] = [] private var backPaths: [String] = [] var onFinished: (() -> Void)? var changed: Bool { contents.bytes != original } var selected: [DiskEditorEntry] { contents.entries.filter { selection.contains($0.id) } } var os9: Bool { contents.format == "os9" } var canApply: Bool { session?.canApply ?? !sourceReadOnly } var presentation: DiskEditorPresentation { machine.diskEditorPresentation(for: session) } var displayPath: String { "/" + path } var canBack: Bool { !backPaths.isEmpty } var canMove: Bool { os9 && !busy && !selected.isEmpty && selected.count <= 4096 && selected.allSatisfy { !$0.directory } } init(store: DiskImageEditorStore, machine: any DiskEditorHost, session: DiskEditorSession?, sourceURL: URL?, name: String, original: Data, contents: DiskEditorContents, sourceReadOnly: Bool) { self.store = store; self.machine = machine; self.session = session; self.sourceURL = sourceURL self.name = name; self.original = original; self.contents = contents; self.sourceReadOnly = sourceReadOnly } private func accept(_ value: DiskEditorContents) { if value.bytes != contents.bytes { revision = UUID() } contents = value; selection.formIntersection(Set(value.entries.map(\.id))) } func moveRequest(for files: [DiskEditorEntry]) -> DiskEditorMoveRequest? { guard os9, !busy, !files.isEmpty, files.count <= 4096, files.allSatisfy({ !$0.directory && contents.entries.contains($0) }), Set(files.map(\.id)).count == files.count else { return nil } return DiskEditorMoveRequest(editorID: editorID, revision: revision, sessionID: session?.id ?? editorID, sourcePath: path, files: files, bytes: contents.bytes) } func moveSourceIsCurrent(_ request: DiskEditorMoveRequest) -> Bool { os9 && request.editorID == editorID && request.revision == revision && request.sessionID == (session?.id ?? editorID) && request.sourcePath == path && request.bytes == contents.bytes && request.files.allSatisfy { !$0.directory && contents.entries.contains($0) } } func moveTo() { guard let request = moveRequest(for: selected) else { return } error = nil moving = request } func moveDestination(_ request: DiskEditorMoveRequest, path destination: String) async throws -> DiskEditorContents { guard moveSourceIsCurrent(request), !busy else { throw DiskEditorFailure.message("The disk or source folder changed. Close Move To and select the files again.") } let result = try await store.contents(at: destination) try Task.checkCancellation() guard moveSourceIsCurrent(request), !busy, result.bytes == request.bytes else { throw DiskEditorFailure.message("The disk changed while choosing a folder. Close Move To and select the files again.") } return result } func move(_ request: DiskEditorMoveRequest, to destination: String, expectedDestination: DiskEditorContents? = nil) { guard !busy else { return } guard moveSourceIsCurrent(request) else { error = "The dragged files or disk changed. Select the files again before moving them."; return } guard destination.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { error = "These files are already in this folder. Choose a different destination."; return } work { let target = try await self.store.contents(at: destination) guard self.moveSourceIsCurrent(request), target.bytes == request.bytes, expectedDestination.map({ $0.bytes == target.bytes && $0.entries == target.entries }) ?? true else { throw DiskEditorFailure.message("The disk or destination changed. Choose the destination again.") } let names = Set(target.entries.map { $0.name.lowercased() }) if let collision = request.files.first(where: { names.contains($0.name.lowercased()) }) { throw DiskEditorFailure.message("The destination already contains \(collision.name). Rename it or choose another folder; moving never overwrites files.") } try await self.commit(.moveFiles(request.files.map(\.path), destination)) self.moving = nil self.notice = "Moved \(request.files.count) \(request.files.count == 1 ? "file" : "files") to /\(destination). Undo is available." } } private func work(_ operation: @escaping () async throws -> Void) { guard !busy else { return }; busy = true; error = nil; notice = nil Task { do { try await operation() } catch { self.error = error.localizedDescription }; self.busy = false } } func selectVolume(_ id: String) { guard !busy, id != contents.volumeID else { return } work { let value = try await self.store.selectVolume(id) self.revision = UUID(); self.path = ""; self.backPaths = []; self.selection = [] self.moving = nil; self.information = nil; self.naming = nil; self.importing = nil self.accept(value) } } func refresh() { work { self.accept(try await self.store.contents(at: self.path)) } } func navigate(_ next: String, remember: Bool = true) { work { let value = try await self.store.contents(at: next) if remember { self.backPaths.append(self.path) } self.path = next; self.selection = []; self.accept(value) } } func back() { guard let next = backPaths.popLast() else { return }; navigate(next, remember: false) } func up() { navigate(path.split(separator: "/").dropLast().joined(separator: "/")) } func activate(_ ids: Set) { selection = ids guard let entry = selected.first, selected.count == 1 else { return } if entry.directory { navigate(entry.path) } else { export() } } func change(_ change: DiskImageEditorStore.Change) { work { try await self.commit(change) } } private func commit(_ change: DiskImageEditorStore.Change) async throws { let before = contents.bytes let value = try await store.change(change, path: path) if value.bytes != before { undoStates.append(before); redoStates.removeAll() while undoStates.count > 1 && (undoStates.count > 32 || undoStates.reduce(0, { $0 + $1.count }) > 64 * 1024 * 1024) { undoStates.removeFirst() } } accept(value) } private func confirm(_ alert: NSAlert, accepting response: NSApplication.ModalResponse = .alertFirstButtonReturn) async -> Bool { guard let window else { return false } return await withCheckedContinuation { continuation in alert.beginSheetModal(for: window) { continuation.resume(returning: $0 == response) } } } func undo() { guard !busy, let bytes = undoStates.last else { return } let current = contents.bytes work { let value = try await self.restoreNavigable(bytes) self.undoStates.removeLast(); self.redoStates.append(current); self.accept(value) } } func redo() { guard !busy, let bytes = redoStates.last else { return } let current = contents.bytes work { let value = try await self.restoreNavigable(bytes) self.redoStates.removeLast(); self.undoStates.append(current); self.accept(value) } } private func restoreNavigable(_ bytes: Data) async throws -> DiskEditorContents { // Undoing creation of the currently open folder returns to the root. do { return try await store.restore(bytes, path: path) } catch { let value = try await store.restore(bytes, path: "") path = ""; backPaths = []; return value } } func chooseImport() { let panel = NSOpenPanel(); panel.title = "Import Files into Disk Image"; panel.canChooseDirectories = false; panel.allowsMultipleSelection = true guard let window else { return } panel.beginSheetModal(for: window) { response in guard response == .OK else { return } Task { @MainActor in self.proposeImport(panel.urls) } } } func proposeImport(_ urls: [URL]) { guard !busy, !urls.isEmpty else { return } guard urls.count <= 72 else { error = "Import at most 72 files at once."; return } var request = DiskEditorImportRequest(urls: urls) let ext = urls.first?.pathExtension.lowercased() ?? "" request.type = ext == "bas" ? 0 : ext == "dat" ? 1 : ["txt", "asc"].contains(ext) ? 3 : 2 request.ascii = ["bas", "txt", "asc"].contains(ext) importing = request } func importNeedsReplacement(_ urls: [URL]) -> Bool { // Both filesystem readers compare ASCII names without casing; use the // same identity when deciding whether replacement consent is needed. let names = Set(contents.entries.map { $0.name.lowercased() }) return urls.contains { names.contains($0.lastPathComponent.lowercased()) } } func confirmImport(_ request: DiskEditorImportRequest) { importing = nil let collisions = importNeedsReplacement(request.urls) work { if collisions { let alert = NSAlert(); alert.messageText = "Replace existing files?"; alert.informativeText = "The selected names already exist in this directory. Replacement changes only the editor's working copy until you apply it." alert.addButton(withTitle: "Replace"); alert.addButton(withTitle: "Cancel") guard await self.confirm(alert) else { return } } try await self.commit(.importFiles(request.urls, type: request.type, ascii: request.ascii, replace: collisions)) } } func newFolder() { naming = DiskEditorNameRequest(entry: nil, name: "") } func rename() { guard selected.count == 1, let entry = selected.first else { return }; naming = DiskEditorNameRequest(entry: entry, name: entry.name) } func confirmName(_ request: DiskEditorNameRequest) { naming = nil if let entry = request.entry { change(.rename(entry.path, request.name)) } else { change(.folder(request.name)) } } func delete() { let entries = selected; guard !entries.isEmpty else { return } let alert = NSAlert(); alert.messageText = entries.count == 1 ? "Delete \(entries[0].name)?" : "Delete \(entries.count) entries?" alert.informativeText = "This changes the working copy. Undo is available until the editor closes. Nonempty folders must be emptied first." alert.addButton(withTitle: "Delete"); alert.addButton(withTitle: "Cancel") work { guard await self.confirm(alert) else { return } try await self.commit(.delete(entries)) } } func showInfo() { guard selected.count == 1, let entry = selected.first else { return } work { var text = "\(entry.name)\n\(entry.type)\n\(ByteCountFormatter.string(fromByteCount: entry.size, countStyle: .file))" if !entry.directory && self.os9 { do { let data = try await self.store.read(entry.path) if data.starts(with: [0x87, 0xcd]) || data.starts(with: [0x4a, 0xfc]) { do { text += "\n\n" + (try await self.store.info(entry.path)) } catch { text += "\n\nModule information unavailable: " + error.localizedDescription } } } catch { text += "\n\nContent inspection unavailable: " + error.localizedDescription } } self.information = DiskEditorInformation(entry: entry, details: text) } } func applyInformation(_ info: DiskEditorInformation, permissions: Int, ownerUser: Int, ownerGroup: Int) { guard os9, (0...127).contains(permissions), (0...255).contains(ownerUser), (0...255).contains(ownerGroup) else { error = "Choose valid OS-9 access flags and group/user values from 0 to 255."; return } guard contents.entries.first(where: { $0.id == info.entry.id }) == info.entry else { error = "This entry changed. Close File Information and open it again before saving."; return } work { try await self.commit(.os9Metadata(info.entry.path, permissions: permissions, ownerUser: ownerUser, ownerGroup: ownerGroup)) self.information = nil } } func export() { let files = selected.filter { !$0.directory }; guard !files.isEmpty, let window else { return } let snapshot = contents.bytes, volumeID = contents.volumeID if files.count == 1 { let panel = NSSavePanel(); panel.title = "Export Disk File"; panel.nameFieldStringValue = files[0].name panel.beginSheetModal(for: window) { response in guard response == .OK, let url = panel.url else { return } Task { @MainActor in self.export(files, targets: [url], snapshot: snapshot, volumeID: volumeID) } } } else { let panel = NSOpenPanel(); panel.title = "Choose Export Folder"; panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true panel.beginSheetModal(for: window) { response in guard response == .OK, let url = panel.url else { return } Task { @MainActor in self.export(files, targets: files.map { url.appendingPathComponent($0.name) }, snapshot: snapshot, volumeID: volumeID, confirmReplacement: true) } } } } private func export(_ entries: [DiskEditorEntry], targets: [URL], snapshot: Data, volumeID: String, confirmReplacement: Bool = false) { work { let existing = try await Task.detached { try targets.map { url -> Data? in if FileManager.default.fileExists(atPath: url.path) { return try DiskImageEditorStore.hostBytes(url) } return nil } }.value if confirmReplacement && existing.contains(where: { $0 != nil }) { let alert = NSAlert(); alert.messageText = "Replace exported files?" alert.informativeText = "Some filenames already exist in the selected folder. Replace those files with the selected disk files?" alert.addButton(withTitle: "Replace"); alert.addButton(withTitle: "Cancel") guard await self.confirm(alert) else { return } } let reader = try await Task.detached { try DiskImageEditorStore(data: snapshot, selectedVolumeID: volumeID) }.value for (index, pair) in zip(entries, targets).enumerated() { let (entry, target) = pair let data = try await reader.read(entry.path) try await self.machine.saveDiskEditorExport(data, to: target, protecting: self.sourceURL, replacing: existing[index], requireNew: existing[index] == nil) } self.notice = "Exported \(entries.count) \(entries.count == 1 ? "file" : "files")." } } func saveCopy() { guard let window else { return } let panel = NSSavePanel(); panel.title = "Save Edited Disk Copy"; let ext = sourceURL?.pathExtension.lowercased() ?? (session?.hardDisk == true ? "vhd" : "dsk") panel.nameFieldStringValue = ((name as NSString).deletingPathExtension) + " Edited." + ext panel.allowedContentTypes = [UTType(filenameExtension: ext) ?? .data] panel.beginSheetModal(for: window) { response in guard response == .OK, let url = panel.url else { return } Task { @MainActor in self.work { let existing = try await Task.detached { () -> Data? in if FileManager.default.fileExists(atPath: url.path) { return try DiskImageEditorStore.hostBytes(url, maximum: DiskEditorIO.imageLimit) } return nil }.value try await self.saveCopy(to: url, replacing: existing) } } } } func saveCopy(to url: URL, replacing expected: Data?) async throws { let data = contents.bytes try await machine.saveDiskEditorImageCopy(data, to: url, protecting: sourceURL, replacing: expected, requireNew: expected == nil) notice = "Saved edited copy. The original disk is unchanged." } func apply() { guard !busy, changed, canApply else { return } let alert = NSAlert() alert.messageText = presentation.applyConfirmationTitle alert.informativeText = presentation.applyConfirmationMessage alert.addButton(withTitle: presentation.applyConfirmationAction); alert.addButton(withTitle: "Cancel") work { guard await self.confirm(alert) else { return } if let session = self.session { try await self.machine.applyDiskEditor(session, data: self.contents.bytes, restartConfirmed: true) } else { guard let source = self.sourceURL else { throw DiskEditorFailure.message("The source image is unavailable. Save an edited copy instead.") } try await self.machine.saveOfflineDiskEditor(self.contents.bytes, to: source, replacing: self.original) } self.onFinished?() } } func close() { guard !busy else { return } work { if self.changed { let alert = NSAlert(); alert.messageText = "Discard unapplied disk edits?" alert.informativeText = "The original disk is unchanged. Any separately exported files or edited copy you saved are kept." alert.addButton(withTitle: "Keep Editing"); alert.addButton(withTitle: "Discard Changes") guard await self.confirm(alert, accepting: .alertSecondButtonReturn) else { return } } if let session = self.session { try await self.machine.cancelDiskEditor(session) } self.onFinished?() } } } @MainActor final class DiskImageEditorCoordinator: NSObject, NSWindowDelegate { static let shared = DiskImageEditorCoordinator() private var editor: DiskImageEditorModel? private var window: NSWindow? private var opening = false func edit(_ drive: Int, machine: any DiskEditorHost) { guard !opening, editor == nil else { window?.makeKeyAndOrderFront(nil); return } opening = true Task { var acquired: DiskEditorSession? do { let session = try await machine.beginDiskEditor(inDrive: drive); acquired = session try await present(data: session.data, name: session.name, source: session.sourceURL, session: session, machine: machine, sourceReadOnly: !session.canApply) } catch { if let acquired { try? await machine.cancelDiskEditor(acquired) } showError(error) } opening = false } } func editHardDisk(_ drive: Int, machine: any DiskEditorHost) { guard !opening, editor == nil else { window?.makeKeyAndOrderFront(nil); return } opening = true Task { var acquired: DiskEditorSession? do { let session = try await machine.beginHardDiskEditor(inDrive: drive); acquired = session try await present(data: session.data, name: session.name, source: session.sourceURL, session: session, machine: machine, sourceReadOnly: !session.canApply) } catch { if let acquired { try? await machine.cancelDiskEditor(acquired) } showError(error) } opening = false } } func open(machine: any DiskEditorHost) { guard editor == nil, !opening else { window?.makeKeyAndOrderFront(nil); return } let panel = NSOpenPanel(); panel.title = "Open Disk Image for Editing"; panel.allowedContentTypes = DiskEditorIO.extensions.compactMap { UTType(filenameExtension: $0) } panel.canChooseDirectories = false panel.begin { response in guard response == .OK, let url = panel.url else { return } Task { @MainActor in self.open(url, machine: machine) } } } func open(_ url: URL, machine: any DiskEditorHost) { guard editor == nil, !opening else { window?.makeKeyAndOrderFront(nil); return } if let drive = machine.mountedEditorDrive(for: url) { edit(drive, machine: machine); return } if let drive = machine.mountedHardDiskEditorDrive(for: url) { editHardDisk(drive, machine: machine); return } guard !machine.diskEditorSourceIsAssigned(url) else { showError(DiskEditorFailure.message("This image is assigned to another device or an SD card folder. Eject or remove that assignment before opening it in Disk Image Editor.")) return } opening = true Task { do { let image = try await Task.detached { try DiskEditorIO.readImage(url) }.value try await present(data: image.data, name: url.lastPathComponent, source: url, session: nil, machine: machine, sourceReadOnly: image.readOnly) } catch { showError(error) } opening = false } } private func present(data: Data, name: String, source: URL?, session: DiskEditorSession?, machine: any DiskEditorHost, sourceReadOnly: Bool) async throws { let store = try await Task.detached { try DiskImageEditorStore(data: data) }.value let contents = try await store.contents(at: "") let model = DiskImageEditorModel(store: store, machine: machine, session: session, sourceURL: source, name: name, original: data, contents: contents, sourceReadOnly: sourceReadOnly) var size = NSSize(width: 1050, height: 700) #if VCC_UI_TESTING // Exercise the real compact layout without relying on a synthetic // WindowServer edge-drag gesture. Never enabled in the normal app. if CommandLine.arguments.contains("--disk-editor-compact-fixture") { size = NSSize(width: 760, height: 448) } #endif let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) window.title = "Disk Image Editor"; window.subtitle = name; window.isReleasedWhenClosed = false; window.delegate = self let content = NSHostingView(rootView: DiskImageEditorView(model: model)) // This AppKit window owns its minimum size. Inferred hosting constraints // must not pin the initial table dimensions and prevent shrinking. content.sizingOptions = [] window.contentView = content; window.minSize = NSSize(width: 760, height: 480) model.window = window model.onFinished = { [weak self, weak window] in window?.delegate = nil; window?.close(); self?.window = nil; self?.editor = nil } self.window = window; editor = model; window.center(); window.makeKeyAndOrderFront(nil) } func windowShouldClose(_ sender: NSWindow) -> Bool { editor?.close(); return false } func prepareToQuit() -> Bool { guard editor != nil || opening else { return true } window?.makeKeyAndOrderFront(nil) let alert = NSAlert(); alert.messageText = "Finish disk editing before quitting" alert.informativeText = editor?.presentation.closeNotice ?? "Finish opening the Disk Image Editor before quitting." alert.addButton(withTitle: "Return to Editor") if let window { alert.beginSheetModal(for: window) } else { alert.runModal() } return false } private func showError(_ error: Error) { let alert = NSAlert(); alert.messageText = "Cannot open Disk Image Editor"; alert.informativeText = error.localizedDescription if let parent = NSApp.keyWindow ?? NSApp.mainWindow { alert.beginSheetModal(for: parent) } else { alert.runModal() } } }