// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import SwiftUI @MainActor final class AssemblyDevelopmentModel: ObservableObject { struct SourceLine: Hashable, Codable, Sendable { let path: String let line: Int } struct Selection { let id = UUID(); let buffer: UUID; let range: NSRange } enum Action { case assemble, run, debug, exportBinary(URL), exportDisk(URL, String, dosBoot: Bool) } struct Attachment { let document: UUID let artifact: AssemblyBuildArtifact var expected: VCCMachineSnapshot var guards: [UInt16: Data] } let machine: MachineModel let service: AssemblyBuildService private(set) var recoveryURL: URL private let recoveryQueue = DispatchQueue(label: "VCCPlus.AssemblyRecovery") private var recoveryTask: Task? @Published private(set) var documents: [AssemblyWorkspaceDocument] @Published private(set) var activeID: UUID @Published private(set) var artifact: AssemblyBuildArtifact? @Published private(set) var diagnostics: [AssemblyDiagnostic] = [] @Published var message = "Ready to assemble." @Published var buildLog = "" @Published private(set) var working = false @Published private(set) var cursor = 0 @Published private(set) var selection: Selection? @Published private(set) var executionLine: SourceLine? @Published private(set) var execution = "" @Published private(set) var commanding = false @Published private(set) var attached = false @Published private(set) var paused = false @Published private(set) var displayRequest = 0 private var cursors: [UUID: Int] = [:] private var fileRequest = UUID() private var work: Task? private var revision = UUID() var workspaceRevision: UUID { revision } @Published private(set) var sourceRevision = UUID() private var connection: Attachment? // Remember ownership across source edits so a repeat Run can replace our own bytes immediately. private var owner: (document: UUID, generation: UInt64, revision: UInt64)? private var reading = false private var checking = false private var nextCheck = Date.distantPast private var index: Int { documents.firstIndex { $0.id == activeID }! } var document: AssemblyWorkspaceDocument { documents[index] } var buffer: AssemblyBuffer { document.buffers.first { $0.path == document.selectedPath }! } var cpu: AssemblyCPU { document.cpu } init(machine: MachineModel, service: AssemblyBuildService = .init(), recoveryURL: URL? = nil) { self.machine = machine; self.service = service self.recoveryURL = recoveryURL ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("Assembly Workspace/Drafts.json") let first = AssemblyWorkspaceDocument.example(title: AssemblyWorkspaceDocument.starterTitle, source: AssemblyWorkspaceDocument.starterSource, cpu: .mc6809) documents = [first]; activeID = first.id while FileManager.default.fileExists(atPath: self.recoveryURL.path) { do { let saved = try AssemblyRecovery.read(from: self.recoveryURL) documents = saved.documents; activeID = saved.active message = "Restored assembly workspace." break } catch { // Preserve an unreadable record at its original location. New sessions // use a neighboring recovery file that is discovered on the next launch. self.recoveryURL = self.recoveryURL.deletingPathExtension().appendingPathExtension("recovered.json") message = "The previous Assembly draft file could not be read. It has been preserved separately." } } indexLabels() } static func lineRange(_ line: Int, text: String) -> NSRange? { guard line > 0 else { return nil } let ns = text as NSString var start = 0 for _ in 1.. = []) throws -> Set { guard !working, !commanding, !edits.isEmpty else { throw AssemblyBuildFailure("workspace_busy") } var updated = document let originalStops = updated.breakpoints for edit in edits { let before = undo ? edit.after : edit.before let after = undo ? edit.before : edit.after guard snapshot.files[edit.path] == Data(before.utf8) else { throw AssemblyBuildFailure("revision_conflict") } if let index = updated.buffers.firstIndex(where: { $0.path == edit.path }) { guard updated.buffers[index].text.utf8.elementsEqual(before.utf8) else { throw AssemblyBuildFailure("revision_conflict") } updated.buffers[index].text = after } else { // An unopened file in the live snapshot has no draft overlay. guard !undo else { throw AssemblyBuildFailure("revision_conflict") } updated.buffers.append(.init(path: edit.path, text: after, saved: before)) } updated.breakpoints = updated.breakpoints.filter { stop in guard stop.path == edit.path else { return true } guard let a = Self.lineRange(stop.line, text: before), let b = Self.lineRange(stop.line, text: after) else { return false } return (before as NSString).substring(with: a).utf8.elementsEqual((after as NSString).substring(with: b).utf8) } } updated.breakpoints.formUnion(restoreStops) documents[index] = updated fileRequest = UUID() sourceRevision = UUID() restoreCursor() invalidate("Source changed. Assemble the reviewed project revision.") scheduleRecovery() return originalStops.subtracting(updated.breakpoints) } func setCPU(_ target: AssemblyCPU) { guard cpu != target else { return } documents[index].cpu = target sourceRevision = UUID() invalidate("Build target changed. Assemble to refresh the listing and source stops.") scheduleRecovery() } private func cancelPending() { revision = UUID(); work?.cancel(); work = nil; working = false } func cancelBuild() { invalidate("Assembly cancelled.") } private func invalidate(_ reason: String) { cancelPending(); artifact = nil; diagnostics = [] if let conn = connection, conn.document == activeID { machine.clearAssembly(expected: conn.expected); connection = nil } attached = false; paused = false; execution = ""; executionLine = nil; message = reason; indexLabels() } func selectFile(_ path: String, line: Int? = nil) { let doc = document, request = UUID() fileRequest = request if doc.buffers.contains(where: { $0.path == path }) { displayFile(path, line: line); return } Task { do { let text = try await Task.detached { try CMOCProject.readText(doc.checkedURL(path), maximumBytes: CMOCProject.maximumSourceBytes) }.value guard activeID == doc.id, fileRequest == request else { return } if !document.buffers.contains(where: { $0.path == path }) { documents[index].buffers.append(.init(path: path, text: text, saved: text)); indexLabels() } displayFile(path, line: line) } catch { message = error.localizedDescription } } } private func displayFile(_ path: String, line: Int?) { if document.selectedPath != path { documents[index].selectedPath = path; restoreCursor() } if let line, let range = Self.lineRange(line, text: buffer.text) { moveCursor(range.location) selection = .init(buffer: buffer.id, range: range) } scheduleRecovery() } private func restoreCursor() { cursor = min(cursors[buffer.id] ?? 0, buffer.text.utf16.count) selection = .init(buffer: buffer.id, range: NSRange(location: cursor, length: 0)) } func editSettings() { guard document.isProject else { return } let path = AssemblyProjectSnapshot.configurationFilename if document.paths.contains(path) || document.buffers.contains(where: { $0.path == path }) { selectFile(path); return } let text = "{\n \"main\": \"main.asm\"\n}\n" documents[index].buffers.append(.init(path: path, text: text, saved: nil)) documents[index].paths.append(path) sourceRevision = UUID() displayFile(path, line: nil); invalidate("Edit project settings, then assemble to validate them.") } func reload() { let doc = document, file = buffer if file.dirty { let alert = NSAlert(); alert.messageText = "Replace edits with the saved \(file.path)?" alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Reload") guard alert.runModal() == .alertSecondButtonReturn else { return } } Task { do { let text = try await Task.detached { try CMOCProject.readText(doc.checkedURL(file.path), maximumBytes: CMOCProject.maximumSourceBytes) }.value guard activeID == doc.id, buffer.id == file.id, buffer.text == file.text, let i = document.buffers.firstIndex(where: { $0.id == file.id }) else { return } documents[index].buffers[i] = .init(path: file.path, text: text, saved: text) sourceRevision = UUID() invalidate("Reloaded \(file.path)."); scheduleRecovery() } catch { message = error.localizedDescription } } } private var protectedSourceURLs: [URL] { var urls = [recoveryURL] for doc in documents { guard let root = doc.directory else { continue } let paths = Set(doc.inputPaths ?? doc.paths).union(doc.buffers.map(\.path)) urls += paths.map { root.appendingPathComponent($0) } } return urls } func save(to copy: URL? = nil) { let doc = document, file = buffer Task { do { let url = try copy ?? doc.checkedURL(file.path) var protected = protectedSourceURLs var expected: Data? if copy == nil { // Only Save Source may replace the selected source file. protected.removeAll { $0.standardizedFileURL == url.standardizedFileURL } expected = file.saved.map { Data($0.utf8) } if expected == nil, FileManager.default.fileExists(atPath: url.path) { throw AssemblyBuildFailure("The source appeared on disk. Reload it or Save a Copy.") } } try await machine.writeDevelopmentFile(Data(file.text.utf8), to: url, protecting: protected, allowEmpty: true, replacing: expected) guard let d = documents.firstIndex(where: { $0.id == doc.id }), let i = documents[d].buffers.firstIndex(where: { $0.id == file.id }) else { return } if doc.directory == nil { documents[d].directory = try CMOCProject.physicalURL(url.deletingLastPathComponent()) documents[d].mainPath = url.lastPathComponent; documents[d].selectedPath = url.lastPathComponent documents[d].buffers[i].path = url.lastPathComponent; documents[d].title = url.lastPathComponent documents[d].breakpoints.removeAll() if activeID == doc.id { invalidate("Source saved.") } } if doc.directory == nil || copy == nil { documents[d].buffers[i].saved = file.text } message = "Saved \(url.lastPathComponent)."; scheduleRecovery() } catch { message = error.localizedDescription } } } @Published private(set) var labelLocations: [(String, SourceLine)] = [] private var labelTask: Task? private func indexLabels() { labelTask?.cancel() let doc = document, snapshot = artifact?.snapshot labelTask = Task { do { try await Task.sleep(nanoseconds: 120_000_000) } catch { return } let result = await Task.detached(priority: .utility) { let words = AssemblyReference.shared.vocabulary(target6309: doc.cpu == .hd6309) var sources = [String: String]() for (path, bytes) in snapshot?.files ?? [:] { let ext = URL(fileURLWithPath: path).pathExtension.lowercased() if ["asm", "s", "lwasm", "inc"].contains(ext) { sources[path] = String(data: bytes, encoding: .utf8) } } for file in doc.buffers where file.path == doc.mainPath || ["asm", "s", "lwasm", "inc"].contains(URL(fileURLWithPath: file.path).pathExtension.lowercased()) { sources[file.path] = file.text } return sources.flatMap { path, text in AssemblyEditorSyntax.labels(in: text, vocabulary: words).map { ($0.0, SourceLine(path: path, line: $0.1)) } }.sorted { ($0.0, $0.1.path, $0.1.line) < ($1.0, $1.1.path, $1.1.line) } }.value if !Task.isCancelled, activeID == doc.id { labelLocations = result } } } func goToDefinition() { let words = AssemblyReference.shared.vocabulary(target6309: cpu == .hd6309) guard let term = AssemblyEditorSyntax.token(in: buffer.text, offset: cursor, vocabulary: words) else { message = "Place the caret on a label."; return } let matches = labelLocations.filter { $0.0 == term } guard matches.count == 1, let match = matches.first else { message = matches.isEmpty ? "No label definition found for \(term)." : "Multiple definitions for \(term). Choose a location in Labels." return } selectFile(match.1.path, line: match.1.line) } private func scheduleRecovery() { recoveryTask?.cancel() recoveryTask = Task { do { try await Task.sleep(nanoseconds: 350_000_000) } catch { return } let state = AssemblyRecovery(documents: documents, active: activeID), url = recoveryURL recoveryQueue.async { do { try state.write(to: url) } catch { Task { @MainActor in self.message = "Could not preserve assembly drafts: " + error.localizedDescription } } } } } func prepareToQuit() -> Bool { cancelPending(); recoveryTask?.cancel() let state = AssemblyRecovery(documents: documents, active: activeID) do { try recoveryQueue.sync { try state.write(to: recoveryURL) }; return true } catch { message = "Could not preserve assembly drafts: " + error.localizedDescription let alert = NSAlert(); alert.messageText = "Could not save Assembly drafts"; alert.informativeText = message alert.runModal(); return false } } static func codeGuards(_ instructions: [AssemblyInstructionLocation]) -> [UInt16: Data] { Dictionary(grouping: instructions, by: \.address).compactMapValues { candidates in guard candidates.count == 1, let first = candidates.first, !first.bytes.isEmpty else { return nil } return Data(first.bytes) } } static func location(_ stop: SourceLine, in artifact: AssemblyBuildArtifact) -> AssemblyInstructionLocation? { let candidates = artifact.instructions.filter { $0.path == stop.path && $0.line == stop.line } guard candidates.count == 1, let candidate = candidates.first, artifact.instructions.filter({ $0.address == candidate.address }).count == 1 else { return nil } return candidate } func toggleBreakpoint() { guard !commanding else { return } let stop = SourceLine(path: buffer.path, line: cursorLine) if document.breakpoints.contains(stop) { documents[index].breakpoints.remove(stop) } else { guard let artifact, Self.location(stop, in: artifact) != nil else { message = "Assemble first and choose a line with one verified instruction. Use the listing for ambiguous or data lines."; return } documents[index].breakpoints.insert(stop) } applyStops() } func clearStops() { guard !commanding else { return } documents[index].breakpoints.removeAll(); applyStops() } private func applyStops() { scheduleRecovery() guard let conn = connection, conn.document == activeID else { return } let points = document.breakpoints.compactMap { Self.location($0, in: conn.artifact)?.address } validateForControl(conn) { self.machine.updateAssembly(breakpoints: points, guards: conn.guards, expected: conn.expected) { snapshot in self.finishCommand(snapshot, connection: conn) } } } func perform(_ action: Action) { guard !commanding, !working else { return } let doc = document, request = UUID(), previous = artifact revision = request; working = true; diagnostics = []; message = "Preparing assembly inputs…" work = Task { defer { if revision == request { working = false; work = nil } } do { let snapshot = try await Task.detached { try doc.snapshot() }.value try check(request, doc.id) documents[index].inputPaths = Array(snapshot.files.keys) let result: AssemblyBuildArtifact if let previous, previous.snapshot == snapshot { result = previous } else { if let makefile = snapshot.settings.makefile { let alert = NSAlert(); alert.messageText = "Run this project’s Makefile?" alert.informativeText = "\(doc.title) will execute \(makefile), target \(snapshot.settings.target ?? "all"), with your account’s permissions. ASFLAGS supplies the selected CPU target. The recipe controls the resulting binary. Without a verified source map, use the machine debugger." alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Run Make") guard alert.runModal() == .alertSecondButtonReturn else { throw CancellationError() } } message = "Assembling for the \(cpu.rawValue)…" result = try await service.build(snapshot) try check(request, doc.id) if doc.directory != nil { guard try await Task.detached(operation: { try doc.snapshot() }).value == snapshot else { throw AssemblyBuildFailure("Assembly inputs changed during the build. Assemble again.") } } } try check(request, doc.id) artifact = result; buildLog = result.buildLog; documents[index].paths = AssemblyWorkspaceDocument.editablePaths(snapshot) indexLabels(); message = "Assembled · " + Self.summary(result) switch action { case .assemble: break case .run, .debug: let debug: Bool if case .debug = action { debug = true } else { debug = false } try await launch(result, doc: doc, request: request, debug: debug) case .exportBinary(let url): try await write(result.binaryData, url: url, request: request, doc: doc.id) case .exportDisk(let url, let name, let dosBoot): let disk = try await service.diskImage(for: result, name: name, dosBoot: dosBoot) try check(request, doc.id) if doc.directory != nil, try await Task.detached(operation: { try doc.snapshot() }).value != snapshot { throw AssemblyBuildFailure("Project inputs changed during disk export. Assemble again.") } try await write(disk, url: url, request: request, doc: doc.id) } } catch { guard revision == request else { return } let failure = (error as? AssemblyBuildFailure)?.diagnostics ?? [] let reason = error is CancellationError ? "Assembly cancelled." : error.localizedDescription invalidate(reason); buildLog = reason; diagnostics = failure } } } private func check(_ request: UUID, _ doc: UUID) throws { try Task.checkCancellation() guard revision == request && activeID == doc else { throw CancellationError() } } private func write(_ data: Data, url: URL, request: UUID, doc: UUID) async throws { try check(request, doc) do { try await machine.writeDevelopmentFile(data, to: url, protecting: protectedSourceURLs) } catch { if revision == request { message = error.localizedDescription } return } try check(request, doc); message = "Exported \(url.lastPathComponent)." } static func summary(_ artifact: AssemblyBuildArtifact) -> String { let ranges = artifact.ranges.map { String(format: "$%04X–$%04X", $0.lowerBound, $0.upperBound) }.joined(separator: ", ") return "Load " + ranges + String(format: " · Entry $%04X", artifact.entry) } func acceptSharedBuild(_ build: AssemblyBuildArtifact) { artifact = build; diagnostics = []; buildLog = build.buildLog message = "Assembled · " + Self.summary(build) indexLabels() } func launchShared(_ build: AssemblyBuildArtifact, stillGranted: @escaping () -> Bool, confirm: ((String) -> Bool)? = nil) async throws -> VCCMachineSnapshot { guard !working, !commanding, artifact?.id == build.id, stillGranted() else { throw AssemblyBuildFailure("The shared build is no longer current.") } working = true let request = revision, priorProgram = machine.assemblyProgramRevision defer { if revision == request { working = false } } try await launch(build, doc: document, request: request, debug: false, stillGranted: stillGranted, confirm: confirm) guard let connection, connection.artifact.id == build.id, connection.expected.debuggerProgramRevision != priorProgram, stillGranted() else { throw AssemblyBuildFailure(message) } return connection.expected } private func launch(_ artifact: AssemblyBuildArtifact, doc: AssemblyWorkspaceDocument, request: UUID, debug: Bool, stillGranted: (() -> Bool)? = nil, confirm: ((String) -> Bool)? = nil) async throws { let generation = machine.basicDebug.generation, program = machine.assemblyProgramRevision let mapping = machine.assemblyMappingFingerprint let sameOwner = owner?.document == doc.id && owner?.generation == generation && owner?.revision == program guard machine.state == .paused || machine.state == .running else { message = "Start a Disk BASIC, Hard Drive BASIC or CoCoSDC machine before running. The build is ready for export."; return } if let confirm, !sameOwner { guard confirm(Self.summary(artifact)) else { throw CancellationError() } } else if !sameOwner { let alert = NSAlert(); alert.messageText = "Load this assembly program into the CoCo?" alert.informativeText = Self.summary(artifact) + "\n\nLoading replaces guest program memory and takes over any active development session. Save any BASIC program or variables you want to keep." if stillGranted != nil { alert.informativeText += "\n\nWhile this program runs, the connected assistant can read the CoCo text screen and send up to 64 individual letters, digits or spaces. Its run receipt can include the last text screen when the program returns to BASIC." } alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: debug ? "Debug from Entry" : "Run") guard alert.runModal() == .alertSecondButtonReturn else { message = "Launch cancelled. The build is ready."; return } } try check(request, doc.id) if doc.directory != nil, try await Task.detached(operation: { try doc.snapshot() }).value != artifact.snapshot { throw AssemblyBuildFailure("Inputs changed before launch. Assemble again.") } try check(request, doc.id) guard stillGranted?() != false else { throw CancellationError() } let points = doc.breakpoints.compactMap { Self.location($0, in: artifact)?.address } guard points.count == doc.breakpoints.count else { message = "An armed line no longer has one executable instruction. Remove that source stop before launching."; return } let guards = Self.codeGuards(artifact.instructions) commanding = true let result: VCCMachineSnapshot? = await withCheckedContinuation { continuation in machine.launchAssembly(artifact.binaryData, breakpoints: points, guards: guards, pauseAtEntry: debug, requires6309: doc.cpu == .hd6309, expectedGeneration: generation, expectedRevision: program, expectedMapping: mapping, shared: stillGranted != nil) { continuation.resume(returning: $0) } } commanding = false guard let result, result.errorMessage == nil else { if revision == request { message = result?.errorMessage ?? machine.fileError ?? "The CoCo is busy or unavailable." }; return } owner = (doc.id, result.generation, result.debuggerProgramRevision) guard revision == request, activeID == doc.id else { machine.clearAssembly(expected: result); return } connection = .init(document: doc.id, artifact: artifact, expected: result, guards: guards) attached = true; paused = result.state == .paused message = "Loaded · " + Self.summary(artifact) if !debug { displayRequest += 1 } refresh() } func pause() { guard attached, !commanding, let conn = connection, conn.document == activeID else { return } commanding = true machine.pauseAssembly(expected: conn.expected) { snapshot in self.finishCommand(snapshot, connection: conn) } } func control(step: Bool) { guard paused, let conn = connection, conn.document == activeID, !commanding else { return } validateForControl(conn) { self.machine.controlAssembly(step: step, expected: conn.expected) { snapshot in self.finishCommand(snapshot, connection: conn) } } } private func validateForControl(_ conn: Attachment, command: @escaping @MainActor () -> Void) { let doc = document, request = revision commanding = true Task { do { let inputs = try await Task.detached { try doc.snapshot() }.value guard request == revision, activeID == doc.id, connection?.artifact.id == conn.artifact.id else { commanding = false; return } guard inputs == conn.artifact.snapshot else { throw AssemblyBuildFailure("Project inputs changed. Run again to reconnect source debugging.") } command() } catch { commanding = false if revision == request { invalidate(error.localizedDescription) } } } } private func finishCommand(_ snapshot: VCCMachineSnapshot?, connection conn: Attachment) { commanding = false guard connection?.artifact.id == conn.artifact.id else { return } guard let snapshot, snapshot.errorMessage == nil else { invalidate(snapshot?.errorMessage ?? machine.fileError ?? "The machine changed. Run again to reconnect.") return } connection?.expected = snapshot paused = snapshot.state == .paused; refresh() } func refresh() { if let build = artifact, document.directory != nil, !checking, !working, !commanding, Date() >= nextCheck { nextCheck = Date().addingTimeInterval(2); checking = true let doc = document, request = revision Task { let copy = await Task.detached { try? doc.snapshot() }.value checking = false if revision == request, activeID == doc.id, artifact?.id == build.id, copy != build.snapshot { invalidate("A project input changed on disk. Reload any open changed file and assemble again.") } } } guard let conn = connection, conn.document == activeID, !reading, !commanding else { return } if machine.state == .running { guard machine.assemblyAttached, machine.basicDebug.generation == conn.expected.generation, machine.assemblyProgramRevision == conn.expected.debuggerProgramRevision, machine.assemblyMappingFingerprint == conn.expected.debuggerMappingFingerprint else { invalidate("The running program or memory mapping changed. Run again to reconnect."); return } if paused { paused = false } if executionLine != nil { executionLine = nil } if execution != "Running" { execution = "Running" } return } reading = true machine.readDebugger(address: 0, followPC: true, memoryAddress: 0x0400) { [weak self] capture in guard let self else { return }; reading = false guard connection?.artifact.id == conn.artifact.id, activeID == conn.document, let capture else { return } let snapshot = capture.machine guard snapshot.generation == conn.expected.generation, snapshot.debuggerProgramRevision == conn.expected.debuggerProgramRevision, snapshot.debuggerMappingFingerprint == conn.expected.debuggerMappingFingerprint, snapshot.debuggerAssemblyAttached else { invalidate("Machine program or memory mapping changed. Run again to reconnect source debugging."); return } connection?.expected = snapshot let stopped = snapshot.state == .paused if paused != stopped { paused = stopped } guard stopped else { if executionLine != nil { executionLine = nil } if execution != "Running" { execution = "Running" }; return } let memory = capture.logicalMemory, available = capture.logicalMemoryAvailable for (address, bytes) in conn.guards { let start = Int(address), end = start + bytes.count guard end <= memory.count, end <= available.count, available[start..> 8) } let cc = capture.registers["CC"]?.uint8Value let reg = String(format: "PC $%04X", pc) + (a.map { String(format: " · A $%02X", $0) } ?? "") + (cc.map { String(format: " · CC $%02X", $0) } ?? "") let status = (next.map { "Paused · \($0.path):\($0.line)" } ?? "Paused · no verified source line") + " · " + reg if execution != status { execution = status } if executionLine != next { executionLine = next if let next { selectFile(next.path, line: next.line) } } } } }