Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

@@ -0,0 +1,531 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import AppKit
import Combine
import CryptoKit
import UniformTypeIdentifiers
enum BASICExportKind: String, Identifiable, Sendable {
case disk, cassette
var id: String { rawValue }
var fileExtension: String { self == .disk ? "dsk" : "cas" }
var title: String { self == .disk ? "Export Disk" : "Export Cassette" }
func instructions(name: String, dosBoot: Bool) -> String {
self == .disk ? DevelopmentDiskProgram.basic(name).instructions(dos: dosBoot)
: "Open the cassette and press Play. Type CLOAD\"\(name)\", then type RUN on the next line."
}
var symbol: String { self == .disk ? "externaldrive" : "recordingtape" }
}
enum BASICExportName {
static func normalized(_ text: String) -> String? {
let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard (1...8).contains(value.utf8.count), value.utf8.allSatisfy({
(65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0)
}) else { return nil }
return value.uppercased()
}
static func suggestion(for url: URL?) -> String {
guard let url else { return "HELLO" }
let bytes = url.deletingPathExtension().lastPathComponent.utf8.filter {
(65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0)
}.prefix(8)
return bytes.isEmpty ? "HELLO" : String(decoding: bytes, as: UTF8.self).uppercased()
}
}
struct BASICEditorAction: Identifiable {
enum Operation { case replace(source: String, undoName: String), select(NSRange) }
let id = UUID()
let expectedSource: String
let operation: Operation
}
@MainActor
final class BASICDevelopmentModel: ObservableObject {
weak var assistantEditor: BASICTextView?
let machine: MachineModel
let directory: URL
let workspaceID = UUID()
private var untitledTitle = "Untitled BASIC"
private(set) var sourceRevision = 0
@Published var source = BASICLanguage.sample {
didSet {
if !source.utf8.elementsEqual(oldValue.utf8) {
sourceRevision += 1
diagnostics = []; clearInspection()
if armedSource != nil {
armedSource = nil; stoppedLine = nil; stoppedToken = nil; runtimeErrorLine = nil; runtimeErrorCode = ""
debugStatus = "Source changed. Breakpoints will apply on the next Run; the CoCo program is unchanged."
detachOwnedDebug()
}
}
if !restoring { scheduleRecovery() }
}
}
@Published private(set) var diagnostics: [BASICLanguage.Diagnostic] = []
@Published private(set) var editorAction: BASICEditorAction?
@Published private(set) var fileURL: URL?
@Published private(set) var savedSource = BASICLanguage.sample
@Published private(set) var busy = false
@Published var message: String?
@Published private(set) var status = "Ready to edit. Nothing has been loaded into the CoCo."
@Published var hint: String?
@Published var completionRequest = UUID()
@Published var documentID = UUID()
@Published var editorOffset = 0
private var fileFingerprint: String?
private var knownGuestSource: String?
@Published private(set) var breakpoints: Set<Int> = []
@Published private(set) var stoppedLine: Int?
@Published private(set) var stoppedToken: NSRange?
@Published private(set) var stepping = false
@Published private(set) var callerAvailable = false
@Published private(set) var runtimeErrorLine: Int?
@Published private(set) var runtimeErrorCode = ""
@Published private(set) var debugStatus = "Click beside a numbered line to set a breakpoint."
@Published private(set) var variables: [BASICVariable] = []
@Published private(set) var inspectionAvailable = false
@Published private(set) var inspectionStatus = "Pause at a BASIC breakpoint to inspect variables."
@Published private(set) var watches: [String] = []
@Published var watchEntry = ""
@Published var watchError: String?
private var inspectionRequest = UUID()
private var armedSource: String?
private var debugObservation: AnyCancellable?
var canContinue: Bool { machine.basicWorkspaceOwner == workspaceID && canTransfer && machine.state == .paused && machine.basicDebug.attached && source == armedSource }
var canStep: Bool { canContinue && stoppedLine != nil }
var canStepOut: Bool { canStep && callerAvailable }
var editorLocked: Bool { busy || stepping }
private var recoveryTask: Task<Void, Never>?
private var restoring = false
var dirty: Bool { !source.utf8.elementsEqual(savedSource.utf8) }
var title: String { fileURL?.lastPathComponent ?? untitledTitle }
var canTransfer: Bool { !busy && !machine.busy && (machine.state == .running || machine.state == .paused) }
struct Draft: Codable {
var source: String
var savedSource: String
var filePath: String?
var fingerprint: String?
var watches: [String]?
}
init(machine: MachineModel, directory: URL, initialSource: String? = nil, title: String? = nil) {
self.machine = machine; self.directory = directory
if let initialSource { source = initialSource; savedSource = initialSource }
if let title { untitledTitle = title }
restoreRecovery()
debugObservation = machine.$basicDebug.combineLatest(machine.$basicWorkspaceOwner).sink { [weak self] value, owner in
guard let self else { return }
if owner != self.workspaceID {
if self.armedSource != nil {
self.armedSource = nil; self.stoppedLine = nil; self.stoppedToken = nil
self.stepping = false; self.callerAvailable = false
self.runtimeErrorLine = nil; self.runtimeErrorCode = ""; self.clearInspection()
self.debugStatus = "Another BASIC workspace controls the CoCo. These breakpoints apply on your next Run."
}
return
}
// @Published sends before MachineModel stores the new value.
// Defer the read until that snapshot has been fully accepted.
Task { [weak self] in self?.refreshInspection() }
self.stoppedLine = self.armedSource == self.source && value.attached ? value.line : nil
self.stoppedToken = self.stoppedLine != nil ? value.sourceRange : nil
self.stepping = self.armedSource == self.source && value.attached && value.stepping
self.refreshRuntimeState(value)
if self.armedSource != nil && !value.attached {
self.armedSource = nil
self.debugStatus = value.status.isEmpty ? "BASIC debugging ended after the machine changed." : value.status
} else if self.armedSource != nil {
self.debugStatus = value.line.map { "Paused at BASIC line \($0). Continue keeps variables and open files." }
?? (value.status.isEmpty ? "BASIC breakpoints are active." : value.status)
}
}
}
private func detachOwnedDebug() {
guard machine.basicWorkspaceOwner == workspaceID else { return }
machine.basicWorkspaceOwner = nil
machine.detachBASICDebug()
}
private func refreshRuntimeState(_ value: MachineModel.BASICDebugState) {
let attached = machine.basicWorkspaceOwner == workspaceID && armedSource == source && value.attached
callerAvailable = attached && value.canStepOut
runtimeErrorLine = attached ? value.errorLine : nil
runtimeErrorCode = attached ? value.errorCode : ""
}
func clearInspection() {
inspectionRequest = UUID(); variables = []; inspectionAvailable = false
inspectionStatus = "Pause at a BASIC breakpoint or completed statement to inspect variables."
}
func refreshInspection() {
let stop = machine.basicDebug
guard machine.basicWorkspaceOwner == workspaceID, armedSource == source, stop.attached, stop.paused, !stop.stepping,
stop.line != nil || stop.atPrompt else { clearInspection(); return }
let text = source, request = UUID(); inspectionRequest = request
Task {
let (values, error) = await machine.inspectBASIC(source: text, stop: stop)
guard inspectionRequest == request, source == text, armedSource == text,
machine.basicWorkspaceOwner == workspaceID, machine.basicDebug == stop else { return }
variables = values ?? []; inspectionAvailable = values != nil
inspectionStatus = error ?? (values?.isEmpty == true ? "No variables have been assigned yet." : "Read-only · BASIC uses the first two characters of a name.")
}
}
func addWatch() {
guard let watch = BASICWatch(watchEntry) else {
watchError = "Use a variable name or numeric subscripts, such as A, NAME$ or A(2,3). Expressions are not evaluated."; return
}
guard watches.count < 128 || watches.contains(watch.canonical) else { watchError = "Up to 128 watches are supported."; return }
if !watches.contains(watch.canonical) { watches.append(watch.canonical) }
watchEntry = ""; watchError = nil; persistDraft()
}
func removeWatch(_ name: String) { watches.removeAll { $0 == name }; persistDraft() }
func watchValue(_ name: String) -> String {
inspectionAvailable ? (BASICWatch(name)?.value(in: variables) ?? "Invalid watch") : "Waiting for a BASIC stop"
}
static func fingerprint(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
static func readText(_ url: URL) throws -> (String, String) {
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
guard values.isRegularFile == true, let count = values.fileSize, count <= BASICLanguage.maximumSourceBytes else {
throw CocoaError(.fileReadTooLarge)
}
let data = try Data(contentsOf: url)
guard data.count <= BASICLanguage.maximumSourceBytes, !data.contains(0),
let text = String(data: data, encoding: .utf8) else { throw CocoaError(.fileReadInapplicableStringEncoding) }
return (text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n"), fingerprint(data))
}
private func restoreRecovery() {
let url = directory.appendingPathComponent("Draft.json")
guard FileManager.default.fileExists(atPath: url.path) else { return }
do {
let values = try url.resourceValues(forKeys: [.fileSizeKey])
guard let count = values.fileSize, count <= BASICLanguage.maximumSourceBytes * 12 else { throw CocoaError(.fileReadTooLarge) }
let draft = try JSONDecoder().decode(Draft.self, from: Data(contentsOf: url))
guard draft.source.utf8.count <= BASICLanguage.maximumSourceBytes,
draft.savedSource.utf8.count <= BASICLanguage.maximumSourceBytes else { throw CocoaError(.fileReadTooLarge) }
restoring = true
source = draft.source; savedSource = draft.savedSource; fileURL = draft.filePath.map { URL(fileURLWithPath: $0) }
watches = Array((draft.watches ?? []).compactMap { BASICWatch($0)?.canonical }.prefix(128))
fileFingerprint = draft.fingerprint; restoring = false
status = "Restored your BASIC workspace. The CoCo has not been changed."
} catch { message = "The saved BASIC workspace could not be restored: \(error.localizedDescription)" }
}
private func scheduleRecovery() {
recoveryTask?.cancel()
recoveryTask = Task { [weak self] in
do { try await Task.sleep(for: .milliseconds(350)) } catch { return }
self?.persistDraft()
}
}
func persistDraft() {
recoveryTask?.cancel()
guard source.utf8.count <= BASICLanguage.maximumSourceBytes else { message = "BASIC source is limited to 1 MB."; return }
do {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let value = Draft(source: source, savedSource: savedSource, filePath: fileURL?.path, fingerprint: fileFingerprint, watches: watches)
try JSONEncoder().encode(value).write(to: directory.appendingPathComponent("Draft.json"), options: .atomic)
} catch { message = "Could not save the recovery draft: \(error.localizedDescription)" }
}
func confirmDiscard(applyDiscard: Bool = true) -> Bool {
guard !busy else { message = "Wait for the BASIC operation to finish."; return false }
guard dirty else { persistDraft(); return true }
let alert = NSAlert(); alert.messageText = "Save changes to \(title)?"
alert.informativeText = "Save your readable BASIC source on the Mac before replacing it or quitting."
alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes")
switch alert.runModal() {
case .alertFirstButtonReturn: return save()
case .alertThirdButtonReturn:
if applyDiscard { source = savedSource; persistDraft() }; return true
default: return false
}
}
func newProgram() {
guard !busy, confirmDiscard() else { return }
fileURL = nil; fileFingerprint = nil; savedSource = BASICLanguage.sample; source = BASICLanguage.sample
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
documentID = UUID(); message = nil; hint = nil; status = "New example. Nothing has been loaded into the CoCo."; persistDraft()
}
func open() {
guard !busy, confirmDiscard(applyDiscard: false) else { return }
let panel = NSOpenPanel(); panel.title = "Open BASIC Source"; panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.message = "Choose readable, line-numbered BASIC text. Tokenized disk or cassette files are not source text."
panel.allowedContentTypes = [.plainText, UTType(filenameExtension: "bas") ?? .plainText]
guard panel.runModal() == .OK, let url = panel.url else { return }
openSource(at: url)
}
@discardableResult func openSource(at url: URL) -> Bool {
guard !busy else { return false }
do {
let (text, hash) = try Self.readText(url)
fileURL = url; fileFingerprint = hash; savedSource = text; source = text
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
documentID = UUID(); message = nil; hint = nil; status = "Opened \(url.lastPathComponent). The CoCo has not been changed."; persistDraft()
return true
} catch { message = "Could not open BASIC source: \(error.localizedDescription)"; return false }
}
@discardableResult func save(as: Bool = false) -> Bool {
guard !busy, source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false }
var target = fileURL
if target == nil || `as` {
let panel = NSSavePanel(); panel.title = "Save BASIC Source"; panel.nameFieldStringValue = fileURL?.lastPathComponent ?? "HelloCoCo.bas"
panel.allowedContentTypes = [UTType(filenameExtension: "bas") ?? .plainText]; panel.canCreateDirectories = true
guard panel.runModal() == .OK, let url = panel.url else { return false }; target = url
}
guard let target else { return false }
return saveSource(to: target)
}
@discardableResult func saveSource(to target: URL) -> Bool {
guard !busy, source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false }
do {
if target == fileURL, let fingerprint = fileFingerprint {
let existing = try? Self.readText(target).1
if existing != fingerprint {
let alert = NSAlert(); alert.messageText = "The BASIC source changed outside VCC Plus."
alert.informativeText = "Replace the file with your editor text? Choose Cancel to keep both and use Save As."
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Replace File")
guard alert.runModal() == .alertSecondButtonReturn else { return false }
}
}
let data = Data(source.utf8); try data.write(to: target, options: .atomic)
fileURL = target; fileFingerprint = Self.fingerprint(data); savedSource = source
message = nil; status = "Saved \(target.lastPathComponent)."; persistDraft(); return true
} catch { message = "Could not save BASIC source: \(error.localizedDescription)"; return false }
}
private var cursorBreakpointLine: Int? {
let text = source as NSString
guard editorOffset >= 0, editorOffset <= text.length else { return nil }
let range = text.lineRange(for: NSRange(location: editorOffset, length: 0))
return BASICLanguage.analyze(text.substring(with: range)).lines.first?.number
}
var cursorBreakpointHelp: String {
guard let line = cursorBreakpointLine else { return "Place the insertion point on a numbered BASIC statement to set a breakpoint" }
return BreakpointRuler.actionName(line, set: breakpoints.contains(line))
}
func toggleBreakpointAtCursor() {
guard let line = cursorBreakpointLine else {
message = "Place the insertion point on a numbered BASIC statement first."; return
}
toggleBreakpoint(line)
}
func toggleBreakpoint(_ line: Int) {
guard !busy else { return }
if breakpoints.contains(line) { breakpoints.remove(line) }
else {
let matches = BASICLanguage.analyze(source).lines.filter { $0.number == line }
guard matches.count == 1, let entry = matches.first,
NSMaxRange(entry.labelRange) < NSMaxRange(entry.range),
!(source as NSString).substring(with: NSRange(location: NSMaxRange(entry.labelRange), length: NSMaxRange(entry.range) - NSMaxRange(entry.labelRange)))
.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
message = "Breakpoints need a unique line number with a BASIC statement."; return
}
guard breakpoints.count < 1024 else { message = "At most 1024 BASIC breakpoints are supported."; return }
breakpoints.insert(line)
}
updateBreakpoints()
}
func clearBreakpoints() {
guard !busy else { return }; breakpoints = []; updateBreakpoints()
}
private func updateBreakpoints() {
message = nil
let text = source, points = breakpoints
// Before the first transfer these are editor intentions only. An
// atomic Run installs the program and its points together.
guard canTransfer, knownGuestSource != nil, machine.basicWorkspaceOwner == workspaceID else {
debugStatus = points.isEmpty ? "No BASIC breakpoints." : "\(points.count) breakpoint(s) will apply on Run."; return
}
busy = true
Task {
defer { busy = false }
let configured = await machine.configureBASICBreakpoints(points, source: text)
guard machine.basicWorkspaceOwner == workspaceID, source == text else { return }
if configured {
armedSource = text
stoppedLine = machine.basicDebug.line; stoppedToken = machine.basicDebug.sourceRange
refreshInspection()
debugStatus = stoppedLine.map { "Paused at BASIC line \($0)." } ?? "BASIC breakpoints are active."
} else {
armedSource = nil; stoppedLine = nil; detachOwnedDebug()
debugStatus = "Editor and CoCo differ. These breakpoints will apply on the next Run."
}
}
}
func stepProgram(over: Bool, out: Bool = false) {
guard out ? canStepOut : canStep else { return }
let text = source; busy = true; message = nil
Task {
defer { busy = false }
let succeeded = out ? await machine.stepOutBASIC(source: text) : await machine.stepBASIC(source: text, over: over)
if !succeeded {
message = machine.fileError ?? "The BASIC stop is no longer current."
}
}
}
func cancelStep() { guard stepping else { return }; machine.pause() }
func continueProgram() {
guard canContinue else { return }
let text = source; busy = true; message = nil
Task {
defer { busy = false }
if !((await machine.continueBASIC(source: text))) { message = machine.fileError ?? "The BASIC stop is no longer current." }
}
}
func checkSource() {
guard !busy, editorAction == nil else { return }
let analysis = BASICLanguage.analyze(source)
diagnostics = analysis.diagnostics; message = nil
status = analysis.diagnostics.isEmpty
? "No source-structure issues found. BASIC checks statement syntax when the program runs."
: "Source check found \(analysis.diagnostics.count) \(analysis.diagnostics.count == 1 ? "issue" : "issues"). Select an issue to show its source line."
}
func goToLine(_ number: Int) {
guard !busy, editorAction == nil else { return }
let analysis = BASICLanguage.analyze(source)
let matches = analysis.lines.filter { $0.number == number }
guard (0...63999).contains(number), matches.count == 1, let line = matches.first else {
message = matches.count > 1 ? "BASIC line \(number) is duplicated. Check Source before navigating."
: "No BASIC line \(number) exists in this source. Use a program line number, not an editor row."
return
}
message = nil
editorAction = .init(expectedSource: source, operation: .select(line.range))
status = "BASIC line \(number)."
}
func selectDiagnostic(_ diagnostic: BASICLanguage.Diagnostic) {
guard !busy, editorAction == nil, diagnostics.contains(where: { $0.id == diagnostic.id }) else { return }
editorAction = .init(expectedSource: source, operation: .select(diagnostic.range))
}
func renumber(start: Int, increment: Int) {
guard !busy, editorAction == nil else { return }
do {
let result = try BASICLanguage.renumber(source, start: start, step: increment)
message = nil; diagnostics = []
guard result.source != source else { status = "The program already uses those line numbers."; return }
editorAction = .init(expectedSource: source, operation: .replace(source: result.source, undoName: "Renumber BASIC"))
status = "Renumbered \(result.lineCount) lines and \(result.changedReferences) references. Undo restores the previous source."
} catch {
diagnostics = BASICLanguage.analyze(source).diagnostics
message = error.localizedDescription
}
}
func editorActionHandled(id: UUID, applied: Bool) {
guard editorAction?.id == id else { return }
if applied, case .replace(_, let name) = editorAction?.operation, name == "Renumber BASIC", !breakpoints.isEmpty {
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
debugStatus = "Line numbers changed. Set breakpoints on the renumbered program."
}
editorAction = nil
if !applied { message = "The source or insertion point changed before the edit could be applied. Try the action again." }
}
private func validateSourceStructure(_ text: String) -> Bool {
let analysis = BASICLanguage.analyze(text)
diagnostics = analysis.diagnostics
guard !analysis.hasErrors else {
message = "Fix the source errors below before loading or exporting. Select an issue to show its source line."
return false
}
return true
}
var suggestedExportName: String { BASICExportName.suggestion(for: fileURL) }
func chooseExport(_ kind: BASICExportKind, name: String, dosBoot: Bool) {
Task { _ = await performExport(kind, name: name, dosBoot: dosBoot, destination: nil) }
}
/// The save panel and regression checks share one production export path.
@discardableResult func exportImage(_ kind: BASICExportKind, name: String, dosBoot: Bool = false, to destination: URL) async -> Bool {
await performExport(kind, name: name, dosBoot: dosBoot, destination: destination)
}
private func performExport(_ kind: BASICExportKind, name: String, dosBoot: Bool, destination: URL?) async -> Bool {
guard canTransfer else { message = "Start the bundled CoCo BASIC setup before exporting."; return false }
guard let name = BASICExportName.normalized(name) else {
message = "Use 1–8 letters or numbers for the CoCo program name, without an extension."; return false
}
let text = source, sourceURL = fileURL
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
message = "Enter a line-numbered BASIC program before exporting."; return false
}
guard validateSourceStructure(text) else { return false }
busy = true; message = nil; persistDraft()
defer { busy = false }
guard let data = await machine.exportBASICSource(text, name: name, cassette: kind == .cassette) else {
message = machine.fileError ?? "Could not prepare the BASIC export."; return false
}
var target = destination
if target == nil {
let panel = NSSavePanel(); panel.title = kind.title
panel.nameFieldStringValue = name + "." + kind.fileExtension
panel.allowedContentTypes = [UTType(filenameExtension: kind.fileExtension) ?? .data]
panel.canCreateDirectories = true; panel.isExtensionHidden = false
panel.message = kind.instructions(name: name, dosBoot: dosBoot)
guard panel.runModal() == .OK, let chosen = panel.url else { return false }; target = chosen
}
guard let target else { return false }
do {
let output = kind == .disk && dosBoot ? try await DevelopmentBuildTools().bootableBASICDisk(data, name: name) : data
try await machine.writeBASICExport(output, to: target, sourceURL: sourceURL)
status = "Exported \(target.lastPathComponent). " + kind.instructions(name: name, dosBoot: dosBoot)
return true
} catch { message = "Could not export BASIC: \(error.localizedDescription)"; return false }
}
func transfer(run: Bool) {
Task { _ = await performTransfer(run: run) }
}
/// Both the editor and the reviewed run use the same source validation and replacement confirmation.
func performTransfer(run: Bool, reviewIsCurrent: (() -> Bool)? = nil) async -> (VCCMachineSnapshot, String)? {
guard canTransfer else { return nil }
let text = source
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { message = "Enter a line-numbered BASIC program first."; return nil }
guard validateSourceStructure(text) else { return nil }
busy = true; message = nil; persistDraft()
defer { busy = false }
let prior = reviewIsCurrent == nil ? nil : await machine.mcpMachineSnapshot()
guard reviewIsCurrent?() != false else { return nil }
guard let existing = await machine.readBASICSource() else { message = machine.fileError ?? "Could not inspect BASIC memory."; return nil }
if machine.assemblyAttached || (!existing.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existing != knownGuestSource) {
let alert = NSAlert(); alert.messageText = machine.assemblyAttached ? "Take over the assembly session with BASIC?" : "Replace the BASIC program in the CoCo?"
alert.informativeText = "This replaces program memory and clears its variables. Mounted media and machine settings are kept. Use Read from CoCo first if you want to save that program."
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: run ? "Replace and Run" : "Replace and Load")
guard alert.runModal() == .alertSecondButtonReturn else { return nil }
}
guard reviewIsCurrent?() != false, source == text else { return nil }
guard let snapshot = await machine.loadBASICSource(text, run: run, breakpoints: breakpoints,
review: prior.map { ($0, existing) }) else { message = machine.fileError ?? "BASIC transfer failed."; return nil }
machine.basicWorkspaceOwner = workspaceID
let loadedSource = reviewIsCurrent == nil ? await machine.readBASICSource() : snapshot.assistantLoadedSource
guard machine.basicWorkspaceOwner == workspaceID, source == text else { return nil }
knownGuestSource = loadedSource
armedSource = machine.basicDebug.attached ? text : nil
refreshRuntimeState(machine.basicDebug)
stoppedLine = machine.basicDebug.line; stoppedToken = machine.basicDebug.sourceRange
refreshInspection()
if machine.basicDebug.attached {
debugStatus = stoppedLine.map { "Paused at BASIC line \($0). Continue keeps variables and open files." }
?? (breakpoints.isEmpty ? "No BASIC breakpoints." : "BASIC breakpoints are active.")
} else {
debugStatus = machine.basicDebug.status.isEmpty ? "BASIC debugging is detached." : machine.basicDebug.status
}
status = run ? "Loaded directly into BASIC memory and started. Use CoCo Break to stop a running program." : "Loaded directly into BASIC memory. Use LIST or RUN in the CoCo."
return loadedSource.map { (snapshot, $0) }
}
func readFromCoCo() {
guard canTransfer, confirmDiscard(applyDiscard: false) else { return }
busy = true; message = nil
Task {
defer { busy = false }
guard let text = await machine.readBASICSource() else { message = machine.fileError ?? "Could not read BASIC memory."; return }
fileURL = nil; fileFingerprint = nil; savedSource = ""; source = text; knownGuestSource = text
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
documentID = UUID(); hint = nil; status = "Read from CoCo memory. Save a source copy on the Mac to keep it."; persistDraft()
}
}
func statusMessage(_ value: String) { status = value }
func cursorChanged(_ offset: Int) {
editorOffset = offset
if let keyword = BASICReferenceContext.keyword(in: source, at: offset),
let catalog = try? BASICReferenceCatalog.bundled.get() {
let candidates = catalog.entries.filter { $0.keyword == keyword }
let entry = candidates.first { $0.dialect == machine.basicReferenceDialect }
?? candidates.first { $0.dialect == .common }
?? candidates.first { $0.dialect == .disk }
hint = entry?.syntax.first
} else { hint = BASICLanguage.hint(source, at: offset) }
}
}