// SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import AppKit import Combine import UniformTypeIdentifiers // Text is an interpretation of the captured bytes, never their replacement. // Classic BASIC can send seven data bits; its stop bit appears as bit 7 in // the original VCC write-sampled decoder. Raw export always keeps that bit. enum PrinterText { static let previewLimit = 65_536 static func decode(_ data: Data, sevenBit: Bool) -> String { var result = "" result.reserveCapacity(data.count) var carriageReturn = false for raw in data { let byte = sevenBit ? raw & 0x7f : raw if byte == 10 && carriageReturn { carriageReturn = false; continue } carriageReturn = byte == 13 switch byte { case 13, 10: result.append("\n") case 9: result.append("\t") case 32...126: result.append(Character(UnicodeScalar(byte))) case 12: result.append("\n⟨FF⟩\n") case 27: result.append("⟨ESC⟩") default: result.append(String(format: "⟨%02X⟩", Int(byte))) } } return result } static func export(_ bytes: Data, raw: Bool, sevenBit: Bool) -> Data { raw ? bytes : Data(decode(bytes, sevenBit: sevenBit).utf8) } } @MainActor final class PrinterModel: ObservableObject { @Published private(set) var enabled = false @Published private(set) var byteCount = 0 @Published private(set) var dropped: UInt64 = 0 @Published private(set) var preview = "" @Published private(set) var busy = false @Published private(set) var saving = false @Published private(set) var unsaved = false @Published var sevenBit = true { didSet { updatePreview() } } @Published var followOutput = true @Published var error: String? private let controller: VCCMachineController private var revision: UInt64 = 0 private var savedRevision: UInt64 = 0 private var loadedRevision: UInt64 = .max private var fetching = false private var bytes = Data() var previewIsTruncated: Bool { byteCount > PrinterText.previewLimit } init(controller: VCCMachineController) { self.controller = controller } // Called by the existing machine poll. No per-frame byte copies or view // invalidation: output is fetched only after its revision actually changes. func observe(_ snapshot: VCCMachineSnapshot) { if enabled != snapshot.printerEnabled { enabled = snapshot.printerEnabled } if byteCount != Int(snapshot.printerByteCount) { byteCount = Int(snapshot.printerByteCount) } if dropped != snapshot.printerDroppedBytes { dropped = snapshot.printerDroppedBytes } revision = snapshot.printerRevision let dirty = byteCount > 0 && revision != savedRevision if unsaved != dirty { unsaved = dirty } refreshIfNeeded() } private func refreshIfNeeded() { guard !fetching, loadedRevision != revision else { return } fetching = true controller.printerOutput { [weak self] output, snapshot in MainActor.assumeIsolated { guard let self else { return } self.fetching = false self.bytes = output.bytes; self.loadedRevision = output.revision self.updatePreview(); self.observe(snapshot) } } } private func updatePreview() { let text = PrinterText.decode(Data(bytes.suffix(PrinterText.previewLimit)), sevenBit: sevenBit) if preview != text { preview = text } } func setCapture(_ value: Bool) { guard !busy else { return } busy = true; error = nil controller.setPrinterEnabled(value) { [weak self] snapshot in MainActor.assumeIsolated { self?.observe(snapshot); self?.busy = false; self?.error = snapshot.errorMessage } } } func clear() { guard !busy, !saving else { return } let alert = NSAlert() alert.messageText = "Clear printer output?" alert.informativeText = "This removes the captured output from this session. Save Text or Export Raw Bytes first to keep it. Capture will stop; the CoCo keeps running." alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Clear Output") guard alert.runModal() == .alertSecondButtonReturn else { return } busy = true; error = nil // Both commands are queued in order, so a guest write cannot refill the // cleared capture between the clear acknowledgement and the next poll. controller.setPrinterEnabled(false) { _ in } controller.clearPrinterOutput { [weak self] snapshot in MainActor.assumeIsolated { guard let self else { return } self.savedRevision = snapshot.printerRevision self.observe(snapshot); self.busy = false; self.error = snapshot.errorMessage } } } private func capture(_ completion: @escaping (VCCPrinterOutput) -> Void) { controller.printerOutput { [weak self] output, snapshot in MainActor.assumeIsolated { self?.observe(snapshot); completion(output) } } } func copy() { let sevenBit = sevenBit capture { output in NSPasteboard.general.clearContents() NSPasteboard.general.setString(PrinterText.decode(output.bytes, sevenBit: sevenBit), forType: .string) } } func save(raw: Bool) { guard !saving else { return } saving = true; error = nil let sevenBit = sevenBit capture { [weak self] output in guard let self else { return } let data = PrinterText.export(output.bytes, raw: raw, sevenBit: sevenBit) let panel = NSSavePanel() panel.title = raw ? "Export Raw Printer Bytes" : "Save Printer Text" panel.message = "Saves the output captured when you chose this command. New output continues collecting separately." panel.nameFieldStringValue = raw ? "CoCo Printer Output.bin" : "CoCo Printer Output.txt" panel.allowedContentTypes = raw ? [.data] : [.plainText] panel.canCreateDirectories = true panel.begin { [weak self] response in guard let self else { return } guard response == .OK, let url = panel.url else { self.saving = false; return } Task { @MainActor in defer { self.saving = false } do { try await Task.detached(priority: .userInitiated) { try data.write(to: url, options: .atomic) }.value self.savedRevision = output.revision self.unsaved = self.byteCount > 0 && self.revision != self.savedRevision } catch { self.error = "Could not save printer output: \(error.localizedDescription)" } } } } } func printOutput() { let window = NSApp.keyWindow let sevenBit = sevenBit capture { output in let info = NSPrintInfo.shared.copy() as! NSPrintInfo info.topMargin = 36; info.bottomMargin = 36; info.leftMargin = 36; info.rightMargin = 36 info.horizontalPagination = .fit; info.verticalPagination = .automatic info.isVerticallyCentered = false let width = max(100, info.paperSize.width - info.leftMargin - info.rightMargin) let text = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: 1)) text.isVerticallyResizable = true text.textContainer?.containerSize = NSSize(width: width, height: .greatestFiniteMagnitude) text.textContainer?.widthTracksTextView = true text.font = .monospacedSystemFont(ofSize: 10, weight: .regular) text.textColor = .black; text.backgroundColor = .white text.string = PrinterText.decode(output.bytes, sevenBit: sevenBit) if let container = text.textContainer, let layout = text.layoutManager { layout.ensureLayout(for: container) text.setFrameSize(NSSize(width: width, height: max(1, layout.usedRect(for: container).height + 12))) } let operation = NSPrintOperation(view: text, printInfo: info) operation.jobTitle = "CoCo Printer Output" if let window { operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil) } else { operation.run() } } } } struct PrinterOutputView: View { @ObservedObject var printer: PrinterModel var body: some View { VStack(spacing: 0) { SecondaryHeader(title: "Tandy Thermal Printer TP-10", badge: "printer", subtitle: "Printer output from the CoCo’s serial port").padding(20) Divider() HStack(spacing: 12) { Button { printer.setCapture(!printer.enabled) } label: { Label(printer.enabled ? "Stop Capture" : "Start Capture", systemImage: printer.enabled ? "stop.fill" : "record.circle") }.disabled(printer.busy).accessibilityIdentifier("printer-capture") Spacer() SecondaryAction(title: "Copy", systemImage: "doc.on.doc", action: printer.copy) SecondaryAction(title: "Save Text…", systemImage: "square.and.arrow.up") { printer.save(raw: false) } .disabled(printer.saving).accessibilityIdentifier("printer-save-text") SecondaryAction(title: "Print…", systemImage: "printer", action: printer.printOutput) .accessibilityIdentifier("printer-print") }.padding(16) PrinterTextView(text: printer.preview, follow: printer.followOutput) .overlay(alignment: .topLeading) { if printer.byteCount == 0 { VStack(alignment: .leading, spacing: 8) { Text(printer.enabled ? "Waiting for printer output…" : "Ready to capture printer output").font(.headline) Text("Start Capture, then use PRINT #-2, \"HELLO WORLD\" or LLIST in CoCo BASIC.") .font(.callout).foregroundStyle(.secondary) }.padding(20).allowsHitTesting(false) } } .padding(.horizontal, 16) HStack { Label(printer.enabled ? "Capturing" : "Capture stopped", systemImage: printer.enabled ? "record.circle" : "stop.circle") Text("\(printer.byteCount.formatted()) bytes\(printer.unsaved ? " · Not saved" : "")") .accessibilityIdentifier("printer-output-status") Spacer() Toggle("Follow Output", isOn: $printer.followOutput) }.font(.caption).padding(.horizontal, 16).padding(.vertical, 10) if printer.previewIsTruncated { Text("Showing the latest 64 KiB. Copy, Save and Print include all captured output.") .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16) } if printer.dropped > 0 { Label("Capture is full (1 MiB). \(printer.dropped.formatted()) additional bytes were not retained. Stop, save and clear to start a new capture.", systemImage: "exclamationmark.triangle") .font(.callout).foregroundStyle(.orange).padding(.horizontal, 16) } if let error = printer.error { Text(error).foregroundStyle(.red).textSelection(.enabled).padding(.horizontal, 16) } Divider() HStack { Toggle("7-bit BASIC Text", isOn: $printer.sevenBit) .help("Ignore the high bit for text only. Raw export always preserves every captured byte.") Spacer() SecondaryAction(title: "Export Raw Bytes…", systemImage: "doc.badge.gearshape") { printer.save(raw: true) } .disabled(printer.saving).accessibilityIdentifier("printer-save-raw") SecondaryAction(title: "Clear…", systemImage: "trash", action: printer.clear) .disabled(printer.busy || printer.saving || printer.byteCount == 0).accessibilityIdentifier("printer-clear") }.padding(16) SecondaryHelp(title: "Using printer output") { Text("Start capture before printing. Closing this window keeps capture and output; quitting requires saving or discarding unsaved output. Clear stops capture without restarting the CoCo.") Text("Text converts carriage returns to new lines. Control codes appear as ⟨ESC⟩, ⟨FF⟩ or hexadecimal markers. This is a text capture, not TP-10 graphics emulation. Raw export is unchanged.") Text("The serial output shares a PIA register with other CoCo hardware. Capture only while printing; other software can generate unrelated data. For DriveWire TCP connections, use the FD-502 Becker port in Machine Settings.") }.padding(.horizontal, 20).padding(.bottom, 16) }.frame(minWidth: 720, minHeight: 540) } } // An existing selection and scroll position survive every live refresh. The // native read-only text view provides keyboard selection, Copy and VoiceOver. private struct PrinterTextView: NSViewRepresentable { let text: String let follow: Bool func makeNSView(context: Context) -> NSScrollView { let scroll = NSScrollView() scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true scroll.borderType = .bezelBorder let view = NSTextView(frame: scroll.contentView.bounds) view.isEditable = false; view.isSelectable = true view.font = .monospacedSystemFont(ofSize: 13, weight: .regular) view.textContainerInset = NSSize(width: 12, height: 12) view.isVerticallyResizable = true; view.isHorizontallyResizable = true view.autoresizingMask = [.width] view.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) view.textContainer?.containerSize = view.maxSize view.textContainer?.widthTracksTextView = false view.setAccessibilityLabel("Captured printer output") view.setAccessibilityIdentifier("printer-text") scroll.documentView = view return scroll } func updateNSView(_ scroll: NSScrollView, context: Context) { guard let view = scroll.documentView as? NSTextView, view.string != text else { return } let range = view.selectedRange(), origin = scroll.contentView.bounds.origin view.string = text let length = (text as NSString).length let start = min(range.location, length) view.setSelectedRange(NSRange(location: start, length: min(range.length, length - start))) if follow { view.scrollRangeToVisible(NSRange(location: length, length: 0)) } else { scroll.contentView.scroll(to: origin); scroll.reflectScrolledClipView(scroll.contentView) } } }