// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import SwiftUI import UniformTypeIdentifiers private let diskEditorMoveType = NSPasteboard.PasteboardType("com.brianholman.vccplus.disk-editor-files") /// Bounded diagnostics live only in the isolated UI-test app's own fixture folder. enum DiskEditorPromiseDiagnostics { #if VCC_UI_TESTING private static let lock = NSLock() #endif static func record(_ phase: String) { #if VCC_UI_TESTING lock.lock(); defer { lock.unlock() } guard let path = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_PROMISE_TRACE"] else { return } let url = URL(fileURLWithPath: path) let line = Data((phase + "\n").utf8) if !FileManager.default.fileExists(atPath: path) { _ = FileManager.default.createFile(atPath: path, contents: nil) } guard let handle = try? FileHandle(forWritingTo: url) else { return } defer { try? handle.close() } guard let end = try? handle.seekToEnd(), end < 16_384 else { return } try? handle.write(contentsOf: line) #endif } } #if VCC_UI_TESTING /// Observe actual mouse delivery without changing native drag eligibility. private final class DiskEditorNativeTableView: NSTableView { var dragTrace: ((String) -> Void)? override func mouseDown(with event: NSEvent) { dragTrace?("mouse-down row=\(row(at: convert(event.locationInWindow, from: nil))) key=\(window?.isKeyWindow ?? false)") super.mouseDown(with: event) } override func canDragRows(with rowIndexes: IndexSet, at mouseDownPoint: NSPoint) -> Bool { let allowed = super.canDragRows(with: rowIndexes, at: mouseDownPoint) dragTrace?("can-drag native=\(allowed) rows=\(rowIndexes)") return allowed } } #endif /// Native table supplies Finder multi-file promises and accepts ordinary host /// file URLs. Directory navigation stays inside the validated image namespace. struct DiskEditorFileTable: NSViewRepresentable { @ObservedObject var model: DiskImageEditorModel func makeCoordinator() -> Coordinator { Coordinator(model) } func makeNSView(context: Context) -> NSScrollView { #if VCC_UI_TESTING let table = DiskEditorNativeTableView() #else let table = NSTableView() #endif table.identifier = NSUserInterfaceItemIdentifier("disk-editor-files") table.setAccessibilityIdentifier("disk-editor-files"); table.allowsMultipleSelection = true table.usesAlternatingRowBackgroundColors = true; table.rowHeight = 25 table.delegate = context.coordinator; table.dataSource = context.coordinator table.target = context.coordinator; table.doubleAction = #selector(Coordinator.activate) let coordinator = context.coordinator #if VCC_UI_TESTING table.dragTrace = { [weak coordinator] in coordinator?.trace($0) } #endif table.registerForDraggedTypes([diskEditorMoveType, .fileURL]); table.setDraggingSourceOperationMask(.copy, forLocal: false) table.setDraggingSourceOperationMask(model.os9 ? .move : .copy, forLocal: true) let menu = NSMenu(); menu.delegate = context.coordinator; menu.autoenablesItems = false; table.menu = menu context.coordinator.table = table; context.coordinator.configureColumns() let scroll = NSScrollView(); scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true; scroll.documentView = table return scroll } func updateNSView(_ scroll: NSScrollView, context: Context) { context.coordinator.model = model; context.coordinator.update() } @MainActor final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate, NSMenuDelegate { var model: DiskImageEditorModel weak var table: NSTableView? var rows: [DiskEditorEntry] = [] var last: [DiskEditorEntry] = [] var os9: Bool? private var restoringSelection = false private var dragRequest: DiskEditorMoveRequest? #if VCC_UI_TESTING private var dragTraceCount = 0 private var dragTraceLines: [String] = [] #endif fileprivate func trace(_ message: @autoclosure () -> String) { #if VCC_UI_TESTING guard dragTraceCount < 250 else { return }; dragTraceCount += 1 let line = message() dragTraceLines.append(line) if dragTraceLines.count > 40 { dragTraceLines.removeFirst() } let text = "DiskEditorDrag VCC_UI_TESTING\n" + dragTraceLines.joined(separator: "\n") table?.setAccessibilityHelp(text) table?.setAccessibilityValue(text) NSLog("DiskEditorDrag %@", line) #endif } init(_ model: DiskImageEditorModel) { self.model = model } func configureColumns() { guard let table else { return } for column in table.tableColumns { table.removeTableColumn(column) } let definitions: [(String, CGFloat)] = model.os9 ? [("Name", 250), ("Size", 95), ("Type", 120), ("Attributes", 110), ("Owner", 80), ("Modified", 150)] : [("Name", 290), ("Size", 110), ("File Type", 200), ("Encoding", 120)] for (title, width) in definitions { let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(title)); column.title = title; column.width = width; column.minWidth = title == "Name" ? 160 : 70 column.sortDescriptorPrototype = NSSortDescriptor(key: title, ascending: true); table.addTableColumn(column) } table.sortDescriptors = [NSSortDescriptor(key: "Name", ascending: true)]; os9 = model.os9 trace("configure os9=\(model.os9) local-mask=\(model.os9 ? "move" : "copy")") } func update() { table?.setDraggingSourceOperationMask(model.os9 ? .move : .copy, forLocal: true) if os9 != model.os9 { configureColumns() } guard last != model.contents.entries else { return } last = model.contents.entries; reload() } func reload() { guard let table else { return } restoringSelection = true defer { restoringSelection = false } let descriptor = table.sortDescriptors.first, key = descriptor?.key ?? "Name", ascending = descriptor?.ascending ?? true rows = model.contents.entries.sorted { let result: ComparisonResult if key == "Size" { result = $0.size == $1.size ? .orderedSame : $0.size < $1.size ? .orderedAscending : .orderedDescending } else if key == "Modified" { result = $0.modified == $1.modified ? .orderedSame : $0.modified < $1.modified ? .orderedAscending : .orderedDescending } else { result = value($0, key).localizedStandardCompare(value($1, key)) } return ascending ? result == .orderedAscending : result == .orderedDescending } // Reloading emits a selection notification. Preserve the selection // before that callback can clear the model's authoritative IDs. let selectedIDs = model.selection table.reloadData() let selection = IndexSet(rows.indices.filter { selectedIDs.contains(rows[$0].id) }) table.selectRowIndexes(selection, byExtendingSelection: false) } func numberOfRows(in tableView: NSTableView) -> Int { rows.count } func value(_ entry: DiskEditorEntry, _ key: String) -> String { switch key { case "Name": return entry.name case "Size": return entry.directory ? "—" : ByteCountFormatter.string(fromByteCount: entry.size, countStyle: .file) case "Type", "File Type": return entry.type case "Encoding": return entry.encoding case "Attributes": return entry.attributes case "Owner": return "\(entry.group).\(entry.owner)" case "Modified": return entry.modified > 0 ? Date(timeIntervalSince1970: entry.modified).formatted(date: .abbreviated, time: .shortened) : "—" default: return "" } } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { guard rows.indices.contains(row), let column = tableColumn else { return nil } let entry = rows[row], text = value(entry, column.identifier.rawValue) let cell = NSTableCellView(); let label = NSTextField(labelWithString: text) label.lineBreakMode = .byTruncatingMiddle; label.translatesAutoresizingMaskIntoConstraints = false label.font = column.identifier.rawValue == "Size" ? .monospacedDigitSystemFont(ofSize: 13, weight: .regular) : .systemFont(ofSize: 13) if column.identifier.rawValue == "Size" { label.alignment = .right } cell.textField = label; cell.addSubview(label) if column.identifier.rawValue == "Name" { let icon = NSImageView(image: NSImage(systemSymbolName: entry.directory ? "folder" : "doc", accessibilityDescription: nil) ?? NSImage()) icon.translatesAutoresizingMaskIntoConstraints = false; cell.addSubview(icon) NSLayoutConstraint.activate([icon.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5), icon.widthAnchor.constraint(equalToConstant: 17), icon.centerYAnchor.constraint(equalTo: cell.centerYAnchor), label.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6)]) } else { label.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5).isActive = true } NSLayoutConstraint.activate([label.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -7), label.centerYAnchor.constraint(equalTo: cell.centerYAnchor)]) return cell } func tableViewSelectionDidChange(_ notification: Notification) { guard !restoringSelection, let table else { return } let selected = Set(table.selectedRowIndexes.compactMap { rows.indices.contains($0) ? rows[$0].id : nil }) if model.selection != selected { model.selection = selected } } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { reload() } @objc func activate() { guard !model.busy, let table, rows.indices.contains(table.clickedRow) else { return } model.activate([rows[table.clickedRow].id]) } func menuNeedsUpdate(_ menu: NSMenu) { if let table, rows.indices.contains(table.clickedRow), !table.selectedRowIndexes.contains(table.clickedRow) { table.selectRowIndexes(IndexSet(integer: table.clickedRow), byExtendingSelection: false) } menu.removeAllItems() let move = NSMenuItem(title: "Move To…", action: #selector(moveSelected), keyEquivalent: "") move.target = self; move.isEnabled = model.canMove; menu.addItem(move) } @objc private func moveSelected() { model.moveTo() } func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { trace("writer row=\(row) busy=\(model.busy) os9=\(model.os9) selected=\(tableView.selectedRowIndexes)") guard !model.busy, rows.indices.contains(row), !rows[row].directory else { return nil } if !(dragRequest.map { model.moveSourceIsCurrent($0) } ?? false) { let indexes = tableView.selectedRowIndexes.contains(row) ? tableView.selectedRowIndexes : IndexSet(integer: row) dragRequest = model.moveRequest(for: indexes.compactMap { rows.indices.contains($0) ? rows[$0] : nil }) } let payload = dragRequest.flatMap { try? JSONEncoder().encode(DiskEditorDragPayload($0)) } trace("writer request=\(dragRequest?.id.uuidString ?? "none") files=\(dragRequest?.files.count ?? 0) payload=\(payload?.count ?? 0)") return DiskEditorFilePromise.make(bytes: model.contents.bytes, entry: rows[row], machine: model.machine, sourceURL: model.sourceURL, movePayload: payload, volumeID: model.contents.volumeID) } func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) { let paths = rowIndexes.compactMap { rows.indices.contains($0) ? rows[$0].path : nil } // The advertised payload was frozen when AppKit asked for writers, // before it negotiates destination types. Do not add a type here. if dragRequest?.files.map(\.path) != paths { dragRequest = nil } trace("begin rows=\(rowIndexes) request=\(dragRequest?.id.uuidString ?? "none") types=\(session.draggingPasteboard.types?.map(\.rawValue) ?? [])") } func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) { trace("ended operation=\(operation.rawValue)") dragRequest = nil } private func ownedMove(_ info: NSDraggingInfo) -> DiskEditorMoveRequest? { guard let source = info.draggingSource as? NSTableView else { trace("refuse source-not-table class=\(info.draggingSource.map { String(describing: type(of: $0)) } ?? "nil")"); return nil } guard source === table else { trace("refuse different-table"); return nil } guard let request = dragRequest else { trace("refuse no-request"); return nil } guard model.moveSourceIsCurrent(request) else { trace("refuse stale-source"); return nil } guard let data = info.draggingPasteboard.data(forType: diskEditorMoveType), data.count <= DiskEditorIO.limit else { trace("refuse missing-or-oversized-payload"); return nil } guard let payload = try? JSONDecoder().decode(DiskEditorDragPayload.self, from: data), payload == DiskEditorDragPayload(request) else { trace("refuse mismatched-payload"); return nil } return request } private func destination(in table: NSTableView, for info: NSDraggingInfo) -> (path: String, row: Int)? { // proposedRow describes an insertion boundary, which can be the row // after the folder under the pointer. Folder moves target the row // actually under the pointer, then explicitly use an on-row drop. let row = table.row(at: table.convert(info.draggingLocation, from: nil)) if rows.indices.contains(row) { return rows[row].directory ? (rows[row].path, row) : nil } return (model.path, -1) } func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation operation: NSTableView.DropOperation) -> NSDragOperation { trace("validate proposed=\(row) operation=\(operation.rawValue) hovered=\(tableView.row(at: tableView.convert(info.draggingLocation, from: nil))) source=\(info.draggingSource.map { String(describing: type(of: $0)) } ?? "nil") types=\(info.draggingPasteboard.types?.map(\.rawValue) ?? [])") guard !model.busy else { return [] } if info.draggingSource is NSTableView || info.draggingPasteboard.availableType(from: [diskEditorMoveType]) != nil { guard let request = ownedMove(info) else { return [] } guard let target = destination(in: tableView, for: info) else { trace("refuse target-not-folder"); return [] } guard target.path.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { trace("refuse same-folder"); return [] } trace("validate move target-row=\(target.row)") tableView.setDropRow(target.row, dropOperation: .on) return .move } tableView.setDropRow(-1, dropOperation: .on); return .copy } func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation operation: NSTableView.DropOperation) -> Bool { trace("accept proposed=\(row) operation=\(operation.rawValue)") guard !model.busy else { return false } if info.draggingSource is NSTableView || info.draggingPasteboard.availableType(from: [diskEditorMoveType]) != nil { guard let request = ownedMove(info), let target = destination(in: tableView, for: info), target.path.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { trace("accept refused"); return false } trace("accept move files=\(request.files.count) target-row=\(target.row)") model.move(request, to: target.path); return true } guard let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty else { return false } model.proposeImport(urls); return true } } } enum DiskEditorFilePromise { @MainActor static func make(bytes: Data, entry: DiskEditorEntry, machine: any DiskEditorHost, sourceURL: URL?, movePayload: Data? = nil, volumeID: String? = nil) -> NSFilePromiseProvider { let delegate = DiskEditorPromiseDelegate(bytes: bytes, entry: entry, machine: machine, sourceURL: sourceURL, volumeID: volumeID) // Keep ordinary exports on the plain provider. The owned subtype uses // only the designated initializer. Both providers have weak delegates; // documented strong userInfo keeps the immutable snapshot alive. let provider: NSFilePromiseProvider if let movePayload { let owned = DiskEditorOwnedFilePromise(payload: movePayload) owned.fileType = UTType.data.identifier; owned.delegate = delegate; provider = owned } else { provider = NSFilePromiseProvider(fileType: UTType.data.identifier, delegate: delegate) } provider.userInfo = delegate return provider } } /// Advertise the owned move identity before AppKit starts type negotiation. /// Use NSFilePromiseProvider's designated init(), never its convenience init /// which would dispatch back to an unimplemented Swift subclass initializer. private final class DiskEditorOwnedFilePromise: NSFilePromiseProvider { private let payload: Data init(payload: Data) { self.payload = payload; super.init() } override func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { super.writableTypes(for: pasteboard) + [diskEditorMoveType] } override func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { type == diskEditorMoveType ? payload : super.pasteboardPropertyList(forType: type) } override func writingOptions(forType type: NSPasteboard.PasteboardType, pasteboard: NSPasteboard) -> NSPasteboard.WritingOptions { type == diskEditorMoveType ? [] : super.writingOptions(forType: type, pasteboard: pasteboard) } } /// Finder can request every selected row concurrently. Chain the complete /// async jobs, rather than only their delegate callbacks, so the shared machine /// guard and snapshot reader are used by one promise at a time. private actor DiskEditorPromiseExports { static let shared = DiskEditorPromiseExports() private var tail: Task? func write(snapshot: Data, entryPath: String, machine: any DiskEditorHost, source: URL?, destination: URL, volumeID: String?) async throws { let previous = tail let job = Task { await previous?.value DiskEditorPromiseDiagnostics.record("promise snapshot read begin") let reader = try DiskImageEditorStore(data: snapshot, selectedVolumeID: volumeID) let data = try await reader.read(entryPath) DiskEditorPromiseDiagnostics.record("promise snapshot read complete; await machine export") try await machine.savePromisedDiskEditorExport(data, to: destination, protecting: source) } tail = Task { _ = try? await job.value } try await job.value } } private final class DiskEditorPromiseDelegate: NSObject, NSFilePromiseProviderDelegate { let bytes: Data, entry: DiskEditorEntry let volumeID: String? let machine: any DiskEditorHost, sourceURL: URL? private let queue: OperationQueue = { let q = OperationQueue(); q.maxConcurrentOperationCount = 1; return q }() init(bytes: Data, entry: DiskEditorEntry, machine: any DiskEditorHost, sourceURL: URL?, volumeID: String?) { self.bytes = bytes; self.entry = entry; self.machine = machine; self.sourceURL = sourceURL; self.volumeID = volumeID } func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String { DiskEditorPromiseDiagnostics.record("promise filename"); return entry.name } func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue { queue } func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) { // A Finder promise may be fulfilled after another edit or after closing // this window. Its immutable snapshot is the version the user dragged. DiskEditorPromiseDiagnostics.record("promise write entered") let snapshot = bytes, entryPath = entry.path, machine = machine, source = sourceURL, selectedVolume = volumeID Task.detached { do { try await DiskEditorPromiseExports.shared.write(snapshot: snapshot, entryPath: entryPath, machine: machine, source: source, destination: url, volumeID: selectedVolume) DiskEditorPromiseDiagnostics.record("promise export complete") completionHandler(nil) } catch { DiskEditorPromiseDiagnostics.record("promise export error"); completionHandler(error) } } } }