// SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI /// Explicit immutable copies from an emulated floppy to an already running host. /// This view never opens the source file, pauses/restarts the machine or launches DriveWire. struct VCCDriveWireTransferView: View { @ObservedObject var machine: MachineModel let drive: Int let sourceName: String let sourceEpoch: UInt64 @Environment(\.dismiss) private var dismiss @State private var destinations: [CompanionDiskTransfer.Destination] = [] @State private var destinationID: UUID? @State private var selectedDrive = 0 @State private var loading = false @State private var busy = false @State private var canceling = false @State private var receipt: CompanionDiskTransfer.Receipt? @State private var error: String? @State private var sending: Task? private var client: CompanionTransport.Client { get throws { CompanionTransport.Client(configuration: try CompanionValidation.configuration(forVCCPlus: false)) } } private var destination: CompanionDiskTransfer.Destination? { destinations.first { $0.id == destinationID } } private var slot: CompanionDiskTransfer.Slot? { destination?.slots.first { $0.number == selectedDrive } } private var sourceFormatSupported: Bool { guard (0.. 0 && disk.byteCount % 256 == 0 } private var completed: Bool { receipt?.status == .received } private var waiting: Bool { receipt?.status == .waitingForPermission } var body: some View { VStack(alignment: .leading, spacing: 0) { SecondaryHeader(title: "Send a Copy to DriveWire", symbol: "paperplane", subtitle: "Copy FD\(drive)'s current disk to your real CoCo's DriveWire host.") .padding(20) Divider() ScrollView { VStack(alignment: .leading, spacing: 16) { SecondaryCard { Label("Source disk", systemImage: "externaldrive").font(.headline) Text(sourceName).font(.callout.weight(.medium)).textSelection(.enabled) if !sourceFormatSupported { Label("This image uses an encoded disk format. Convert a compatible raw DSK copy before sending it to DriveWire.", systemImage: "info.circle") .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } Label("Includes current changes in memory. The emulator, source disk and save mode stay as they are.", systemImage: "doc.on.doc") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } if loading { ProgressView("Looking for DriveWire sessions…").frame(maxWidth: .infinity) } else if destinations.isEmpty { ContentUnavailableView { Label("No DriveWire sessions available", systemImage: "cable.connector") } description: { Text("Open DriveWire for VCC Plus and start the serial session you want to use, then choose Refresh. This window does not start or reconnect it.") } actions: { Button("Refresh", systemImage: "arrow.clockwise") { Task { await refresh() } } } } else { SecondaryCard { Label("Destination", systemImage: "paperplane").font(.headline) Picker("DriveWire session", selection: $destinationID) { Text("Choose a session").tag(UUID?.none) ForEach(destinations) { destination in Text(destination.name).tag(Optional(destination.id)) } }.accessibilityIdentifier("drivewire-copy-session") if let destination { Picker("Drive", selection: $selectedDrive) { ForEach(destination.slots) { slot in Text("DW\(slot.number) — " + (slot.editing ? "Editing" : slot.name ?? "Empty")) .tag(slot.number).disabled(slot.editing) } }.accessibilityIdentifier("drivewire-copy-slot") if let slot, slot.editing { Label("Finish editing this DriveWire disk before sending a copy.", systemImage: "pencil") .font(.callout).foregroundStyle(.secondary) } else if let name = slot?.name { Label("DW\(selectedDrive) currently holds \(name). DriveWire will retain its current bytes as a recoverable copy before replacing it.", systemImage: "doc.on.doc") .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } Label(destination.permissionGranted ? "This DriveWire connection has already allowed copies from VCC Plus." : "DriveWire will ask for permission before accepting the first copy on this connection.", systemImage: destination.permissionGranted ? "checkmark.shield" : "hand.raised") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } Button("Refresh Sessions", systemImage: "arrow.clockwise") { Task { await refresh() } } .disabled(busy) }.disabled(busy || completed) } if let receipt { Label(receipt.message, systemImage: completed ? "checkmark.circle" : waiting ? "hand.raised" : "xmark.circle") .font(.callout).foregroundStyle(completed ? Color.green : Color.secondary) .fixedSize(horizontal: false, vertical: true).textSelection(.enabled) .accessibilityIdentifier("drivewire-copy-status") } if let error { Label(error, systemImage: "exclamationmark.circle").font(.callout).foregroundStyle(.red) .fixedSize(horizontal: false, vertical: true).textSelection(.enabled) .accessibilityIdentifier("drivewire-copy-error") } }.padding(20) } Divider() HStack { if busy { ProgressView().controlSize(.small) } Button(completed ? "Done" : "Cancel", role: completed ? nil : .cancel) { cancelOrClose() } .disabled(canceling || (busy && receipt == nil)) .keyboardShortcut(.cancelAction) Spacer() if !completed { Button("Send Copy", systemImage: "paperplane") { beginSend() } .keyboardShortcut(.defaultAction) .disabled(!sourceFormatSupported || loading || busy || canceling || destination == nil || slot == nil || slot?.editing == true) .accessibilityIdentifier("drivewire-send-copy") } }.padding(16) } .frame(width: 600, height: 580) .interactiveDismissDisabled(busy || canceling) .task { await refresh() } .onDisappear { sending?.cancel() } } private func refresh() async { guard !busy else { return } loading = true; error = nil defer { loading = false } do { let bytes = try await client.request(method: "destinations") try Task.checkCancellation() let available = try JSONDecoder().decode([CompanionDiskTransfer.Destination].self, from: bytes) destinations = available if destinationID == nil || !available.contains(where: { $0.id == destinationID }) { destinationID = available.first?.id } if let destination, !destination.slots.contains(where: { $0.number == selectedDrive && !$0.editing }) { selectedDrive = destination.slots.first(where: { !$0.editing })?.number ?? 0 } } catch { guard !Task.isCancelled else { return } destinations = []; destinationID = nil self.error = "DriveWire could not be reached. Open a compatible signed DriveWire for VCC Plus build and try Refresh. " + error.localizedDescription } } private func beginSend() { guard let destination, let slot, !slot.editing, !busy else { return } error = nil; receipt = nil; busy = true sending = Task { defer { busy = false; sending = nil } do { try checkSource() let bytes = try await machine.snapshotDiskCopy(inDrive: drive) try Task.checkCancellation(); try checkSource() guard !bytes.isEmpty, bytes.count <= 16 * 1024 * 1024 else { throw TransferFailure(message: "Choose a floppy image within the 16 MiB transfer limit.") } guard bytes.count % 256 == 0 else { throw TransferFailure(message: "This image contains a file-format header. DriveWire needs a raw image of 256-byte sectors; export or convert a compatible disk copy first.") } let request = CompanionDiskTransfer.Request(destination: destination.id, drive: slot.number, name: transferName, bytes: bytes, expectedDiskName: slot.name, expectedMediaID: slot.mediaID) let response = try await client.request(method: "sendDisk", payload: JSONEncoder().encode(request)) var result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: response) receipt = result while result.status == .waitingForPermission { try await Task.sleep(nanoseconds: 350_000_000) let data = try await client.request(method: "transferStatus", payload: JSONEncoder().encode(result.id)) try Task.checkCancellation() result = try JSONDecoder().decode(CompanionDiskTransfer.Receipt.self, from: data) receipt = result } if result.status == .denied { error = result.message } } catch { if !Task.isCancelled { self.error = error.localizedDescription } } } } private var transferName: String { let file = URL(fileURLWithPath: sourceName).lastPathComponent let stem = (file as NSString).deletingPathExtension return (stem.isEmpty ? "Disk" : stem) + ".dsk" } private func checkSource() throws { guard machine.inputEpoch == sourceEpoch, machine.state != .closed, (0..