1542 lines
99 KiB
Swift
1542 lines
99 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import AppKit
|
|
import Combine
|
|
|
|
enum CMOCSourceStepMode: Int { case into, over, out }
|
|
|
|
struct CMOCEditorDocument: Identifiable {
|
|
let id: String
|
|
var text: String
|
|
var savedText: String
|
|
var savedHash: String
|
|
var conflict = false
|
|
var generated = false
|
|
var reference = false
|
|
var missing = false
|
|
var dirty: Bool { !text.utf8.elementsEqual(savedText.utf8) }
|
|
}
|
|
struct CMOCSourceBreakpoint: Hashable, Codable {
|
|
let file: String
|
|
let line: Int
|
|
}
|
|
struct CMOCBuildDiagnostic: Identifiable {
|
|
let id = UUID()
|
|
let file: String
|
|
let line: Int
|
|
let message: String
|
|
}
|
|
|
|
struct CMOCVariableTreeRow: Identifiable {
|
|
enum ID: Hashable { case node(CMOCWatchEvaluator.TreePath), page(CMOCWatchEvaluator.TreePath), limit }
|
|
enum Content {
|
|
case node(CMOCWatchEvaluator.TreeNode)
|
|
case page(CMOCWatchEvaluator.TreePath, offset: Int, total: Int, next: Int?)
|
|
case message(String)
|
|
}
|
|
let id: ID
|
|
let depth: Int
|
|
let content: Content
|
|
}
|
|
struct CMOCVariableTreeListing {
|
|
let rows: [CMOCVariableTreeRow]
|
|
let rootCount: Int
|
|
let rootOffset: Int
|
|
}
|
|
|
|
/// Documents and the exact build snapshot live independently of window lifetime.
|
|
/// The existing machine is the only authority for execution and mounted media.
|
|
@MainActor
|
|
final class CMOCDevelopmentModel: ObservableObject {
|
|
private(set) var assistantProjectID = UUID()
|
|
private(set) var assistantEditEpoch = 0
|
|
weak var assistantEditor: NSTextView?
|
|
weak var assistantEditorPool: CSourceEditor.Coordinator?
|
|
var assistantEditorFile = ""
|
|
let machine: MachineModel
|
|
let service: CMOCBuildService
|
|
@Published var source = CMOCProject.starterSource {
|
|
didSet {
|
|
guard !selecting, let index = documents.firstIndex(where: { $0.id == selectedFile }) else { return }
|
|
if source != oldValue { assistantEditEpoch += 1 }
|
|
documents[index].text = source
|
|
scheduleDraftSave(); scheduleProjectIndex(); scheduleParameterHints()
|
|
}
|
|
}
|
|
@Published private(set) var documents: [CMOCEditorDocument] = []
|
|
@Published private(set) var files: [CMOCProjectFile] = []
|
|
@Published private(set) var selectedFile = "main.c"
|
|
@Published private(set) var project: CMOCProject?
|
|
@Published private(set) var building = false
|
|
@Published private(set) var commanding = false
|
|
@Published private(set) var log = "Create or open a C project to begin. Build runs its Makefile; only build projects you trust."
|
|
@Published private(set) var message: String?
|
|
@Published private(set) var mapping: CMOCSourceMap?
|
|
@Published private(set) var projectMapping: CMOCProjectSourceMap?
|
|
@Published private(set) var artifact: CMOCBuildArtifact?
|
|
@Published private(set) var diagnostics: [CMOCBuildDiagnostic] = []
|
|
@Published var breakpointLine = 9
|
|
@Published private(set) var breakpoints: Set<CMOCSourceBreakpoint> = []
|
|
@Published private(set) var currentLine: Int?
|
|
@Published private(set) var currentFile: String?
|
|
@Published private(set) var execution = "No development program loaded"
|
|
@Published private(set) var pc: UInt16?
|
|
@Published var configurationName = "Debug" { didSet { rememberWorkspace(); scheduleProjectIndex() } }
|
|
@Published var customTarget = ""
|
|
@Published private(set) var navigationLine: Int?
|
|
@Published private(set) var navigationRequest = UUID()
|
|
private var pausedInputEpoch: UInt64?
|
|
@Published private var pausedDebugSnapshot: VCCDebuggerSnapshot?
|
|
@Published private(set) var variableMetadata: CMOCVariableDebug?
|
|
@Published private(set) var variableStatus = "Build with the bundled compiler to inspect C variables."
|
|
@Published private(set) var watches: [String] = []
|
|
@Published var watchExpression = ""
|
|
@Published private(set) var sourceStepping = false
|
|
@Published private(set) var inspectionRevision = UUID()
|
|
@Published private var capturedCallStack: CMOCCallStack?
|
|
@Published private(set) var selectedFrameIndex = 0
|
|
private let defaults: UserDefaults
|
|
private var selecting = false
|
|
private var task: Task<Void, Never>?
|
|
private var loadedGeneration: UInt64?
|
|
private var loadedRevision: UInt64?
|
|
private var loadedMapping: UInt64?
|
|
private var loadedBuild: UUID?
|
|
private var awaitingDiskLoad = false
|
|
private var reading = false
|
|
private var revision = UUID()
|
|
private var checkingFiles = false
|
|
private var nextFileCheck = Date.distantPast
|
|
private var externalBuildChange = false
|
|
private var restorationAttempted = false
|
|
@Published private(set) var launchedBuildID: UUID?
|
|
private var launchedGeneration: UInt64?
|
|
private var launchedRevision: UInt64?
|
|
@Published private(set) var latestBuildAttempt = "Not built in this session"
|
|
@Published private(set) var buildHistory: [CMOCBuildHistory.Entry] = []
|
|
@Published private(set) var historyBusy = false
|
|
@Published private(set) var historyMessage: String?
|
|
@Published private(set) var recoveryRecords: [CMOCWorkspaceRecovery.Record] = []
|
|
@Published private(set) var recoveryIssues: [String] = []
|
|
@Published private(set) var recoveryBusy = false
|
|
private var historyRemoving = false
|
|
private var historyRefreshPending = false
|
|
private var recoveryRefreshPending = false
|
|
private var recoveryProjectDirectory: URL?
|
|
private let recoveryStore: CMOCWorkspaceRecovery
|
|
private let recoveryQueue = DispatchQueue(label: "VCCPlus.CMOCRecovery")
|
|
private var recoveryDebounce: Task<Void, Never>?
|
|
|
|
|
|
init(machine: MachineModel, toolchain: URL? = nil, defaults: UserDefaults? = nil, buildRoot: URL? = nil, recoveryRoot: URL? = nil) {
|
|
self.machine = machine
|
|
self.defaults = defaults ?? machine.developmentDefaults
|
|
self.service = CMOCBuildService(toolchain: toolchain ?? Bundle.main.resourceURL!.appendingPathComponent("Toolchain"),
|
|
buildRoot: buildRoot ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("Development Builds"))
|
|
self.recoveryStore = CMOCWorkspaceRecovery(root: recoveryRoot ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("C Workspace Recovery"))
|
|
}
|
|
|
|
|
|
struct SourceLocation: Equatable {
|
|
let path: String
|
|
let line: Int
|
|
let column: Int
|
|
let length: Int
|
|
}
|
|
@Published var navigationPane = "Files"
|
|
@Published var searchQuery = "" { didSet { scheduleProjectSearch() } }
|
|
@Published var searchCaseSensitive = false { didSet { scheduleProjectSearch() } }
|
|
@Published private(set) var searchMatches: [CMOCProjectIndex.Match] = []
|
|
@Published private(set) var searchTruncated = false
|
|
@Published private(set) var indexing = false
|
|
@Published private(set) var indexMessage = "Open a project to browse its source."
|
|
@Published private(set) var indexNotes: [String] = []
|
|
@Published private(set) var projectIndex: CMOCProjectIndex?
|
|
@Published private(set) var definitionCandidates: [CMOCProjectIndex.Symbol] = []
|
|
@Published private(set) var definitionName = ""
|
|
@Published private(set) var navigationColumn: Int?
|
|
@Published private(set) var navigationLength = 0
|
|
@Published private(set) var cursorOffset = 0
|
|
@Published private(set) var editorActionRequest = UUID()
|
|
private(set) var editorAction: CMOCEditorAction = .indent
|
|
func requestEditorAction(_ action: CMOCEditorAction) {
|
|
editorAction = action; editorActionRequest = UUID()
|
|
}
|
|
@Published private(set) var completionRequest = UUID()
|
|
@Published private(set) var completionMessage = "Complete identifiers with Control-Space."
|
|
@Published private(set) var parameterHints: [CMOCCompletion.ParameterHint] = []
|
|
private var parameterTask: Task<Void, Never>?
|
|
private var parameterGeneration = UUID()
|
|
func requestCompletion() {
|
|
completionMessage = "Preparing identifier completion…"
|
|
guard project != nil, !selectedFileIsGenerated else {
|
|
completionMessage = "Completion is available in editable project C sources."; return
|
|
}
|
|
guard projectIndex != nil else {
|
|
completionMessage = "Reading project declarations; try completion again shortly."
|
|
refreshProjectIndex(); return
|
|
}
|
|
completionRequest = UUID()
|
|
}
|
|
func reportCompletion(message: String) { completionMessage = message }
|
|
func clearParameterHints() {
|
|
parameterTask?.cancel(); parameterGeneration = UUID()
|
|
if !parameterHints.isEmpty { parameterHints = [] }
|
|
}
|
|
func refreshParameterHints() { scheduleParameterHints(delay: 0) }
|
|
private func scheduleParameterHints(delay: UInt64 = 80_000_000) {
|
|
clearParameterHints()
|
|
guard let index = projectIndex, let directory = project?.directory else { return }
|
|
let path = selectedFile, text = source, offset = cursorOffset, generation = parameterGeneration
|
|
parameterTask = Task { [weak self] in
|
|
do {
|
|
if delay > 0 { try await Task.sleep(nanoseconds: delay) }
|
|
try Task.checkCancellation()
|
|
let worker = Task.detached(priority: .utility) {
|
|
CMOCCompletion.parameterHints(index: index, path: path, text: text, offset: offset)
|
|
}
|
|
let hints = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() })
|
|
guard let self, !Task.isCancelled, parameterGeneration == generation,
|
|
project?.directory == directory, selectedFile == path, source == text,
|
|
cursorOffset == offset else { return }
|
|
parameterHints = hints
|
|
} catch { }
|
|
}
|
|
}
|
|
@Published private var backwardLocations: [SourceLocation] = []
|
|
@Published private var forwardLocations: [SourceLocation] = []
|
|
private var cursorOffsets: [String: Int] = [:]
|
|
private var indexInputs = CMOCIndexInputs()
|
|
private var indexTask: Task<Void, Never>?
|
|
private var searchTask: Task<Void, Never>?
|
|
private var indexGeneration = UUID()
|
|
private var searchGeneration = UUID()
|
|
private var navigationDiskHashes: [String: String] = [:]
|
|
var currentOutline: [CMOCProjectIndex.Symbol] { projectIndex?.outline(path: selectedFile) ?? [] }
|
|
var canNavigateBack: Bool { !backwardLocations.isEmpty }
|
|
var canNavigateForward: Bool { !forwardLocations.isEmpty }
|
|
func updateCursor(offset: Int) {
|
|
cursorOffset = max(0, min(offset, source.utf16.count)); cursorOffsets[selectedFile] = cursorOffset
|
|
scheduleParameterHints()
|
|
}
|
|
private func location(path: String, text: String, offset: Int, length: Int = 0) -> SourceLocation {
|
|
let value = text as NSString, offset = min(max(0, offset), value.length)
|
|
let prefix = value.substring(to: offset) as NSString
|
|
let lines = prefix.components(separatedBy: "\n")
|
|
return .init(path: path, line: lines.count, column: (lines.last?.utf16.count ?? 0) + 1, length: length)
|
|
}
|
|
private var cursorLocation: SourceLocation { location(path: selectedFile, text: source, offset: cursorOffset) }
|
|
private func resetNavigation() {
|
|
clearParameterHints(); completionRequest = UUID()
|
|
completionMessage = "Complete identifiers with Control-Space."
|
|
indexTask?.cancel(); searchTask?.cancel(); indexGeneration = UUID(); searchGeneration = UUID()
|
|
projectIndex = nil; indexInputs = .init(); navigationDiskHashes = [:]
|
|
searchMatches = []; searchTruncated = false; definitionCandidates = []; definitionName = ""
|
|
backwardLocations = []; forwardLocations = []; cursorOffsets = [:]; cursorOffset = 0
|
|
navigationColumn = nil; navigationLength = 0; indexing = false
|
|
indexMessage = "Reading project text…"; indexNotes = []
|
|
}
|
|
private func scheduleProjectIndex() { startProjectIndex(delay: 350_000_000) }
|
|
func refreshProjectIndex() { startProjectIndex(delay: 0) }
|
|
private func startProjectIndex(delay: UInt64) {
|
|
indexTask?.cancel(); indexGeneration = UUID()
|
|
guard let project else { indexing = false; return }
|
|
indexing = true
|
|
let generation = indexGeneration, inputs = overlays, configuration = configurationName, toolchain = service.toolchain
|
|
var generated = artifact?.sources.filter { artifact?.fileHashes[$0.key] == nil } ?? [:]
|
|
for document in documents where document.generated && !document.reference && artifact?.fileHashes[document.id] == nil { generated[document.id] = Data(document.text.utf8) }
|
|
let snapshots = generated
|
|
indexTask = Task { [weak self] in
|
|
do {
|
|
if delay > 0 { try await Task.sleep(nanoseconds: delay) }
|
|
try Task.checkCancellation()
|
|
let worker = Task.detached(priority: .utility) {
|
|
let collected = try CMOCIndexInputs.load(project: project, toolchain: toolchain,
|
|
configurationName: configuration, overlays: inputs, generated: snapshots)
|
|
try Task.checkCancellation()
|
|
let index = CMOCProjectIndex(documents: collected.documents, defines: collected.defines,
|
|
includePaths: collected.includePaths, configurationUncertain: collected.configurationUncertain)
|
|
try Task.checkCancellation()
|
|
return (collected, index)
|
|
}
|
|
let (collected, index) = try await withTaskCancellationHandler(operation: { try await worker.value }, onCancel: { worker.cancel() })
|
|
guard let self, !Task.isCancelled, indexGeneration == generation, self.project?.directory == project.directory else { return }
|
|
indexInputs = collected; projectIndex = index; indexing = false
|
|
let notes = Array(Set(collected.issues + index.issues)).sorted()
|
|
indexNotes = notes
|
|
indexMessage = "\(index.symbols.count) symbols · Source-based navigation"
|
|
scheduleProjectSearch(); scheduleParameterHints()
|
|
} catch is CancellationError { }
|
|
catch {
|
|
guard let self, indexGeneration == generation else { return }
|
|
indexing = false; projectIndex = nil; searchMatches = []; definitionCandidates = []; clearParameterHints()
|
|
indexMessage = "Navigation unavailable: " + error.localizedDescription
|
|
}
|
|
}
|
|
}
|
|
private func scheduleProjectSearch() {
|
|
searchTask?.cancel(); searchGeneration = UUID(); searchMatches = []; searchTruncated = false
|
|
guard let index = projectIndex, !searchQuery.isEmpty else { return }
|
|
let generation = searchGeneration, query = searchQuery, sensitive = searchCaseSensitive
|
|
let paths = Set(index.documents.keys).subtracting(indexInputs.referencePaths)
|
|
searchTask = Task { [weak self] in
|
|
do {
|
|
try await Task.sleep(nanoseconds: 150_000_000)
|
|
let worker = Task.detached(priority: .utility) { index.search(query: query, caseSensitive: sensitive, limit: 500, paths: paths) }
|
|
let results = await withTaskCancellationHandler(operation: { await worker.value }, onCancel: { worker.cancel() })
|
|
guard let self, !Task.isCancelled, searchGeneration == generation else { return }
|
|
searchMatches = results.matches; searchTruncated = results.truncated
|
|
} catch { }
|
|
}
|
|
}
|
|
func goToDefinition() {
|
|
guard !indexing, let index = projectIndex, index.documents[selectedFile] == source else {
|
|
indexMessage = "Updating source navigation; try Go to Definition again when indexing finishes."
|
|
refreshProjectIndex(); return
|
|
}
|
|
guard let name = index.token(atUTF16Offset: cursorOffset, in: selectedFile) else {
|
|
definitionName = ""; definitionCandidates = []; navigationPane = "Definitions"
|
|
indexMessage = "Place the insertion point on a C identifier to find its definition."; return
|
|
}
|
|
definitionName = name
|
|
let position = cursorLocation
|
|
definitionCandidates = index.definitions(named: name, from: selectedFile, line: position.line, column: position.column)
|
|
if definitionCandidates.count == 1, let target = definitionCandidates.first, !target.conditional {
|
|
openSymbol(target)
|
|
} else { navigationPane = "Definitions" }
|
|
}
|
|
func openSymbol(_ symbol: CMOCProjectIndex.Symbol) {
|
|
guard projectIndex?.symbols.contains(symbol) == true else { message = "This symbol result is out of date. Refresh navigation and select it again."; return }
|
|
openIndexedLocation(.init(path: symbol.path, line: symbol.line, column: symbol.column, length: symbol.lengthUTF16))
|
|
}
|
|
func openSearchMatch(_ match: CMOCProjectIndex.Match) {
|
|
guard searchMatches.contains(match) else { message = "This search result is out of date. Search again before navigating."; return }
|
|
openIndexedLocation(.init(path: match.path, line: match.line, column: match.column, length: match.lengthUTF16))
|
|
}
|
|
private func openIndexedLocation(_ target: SourceLocation) {
|
|
guard !indexing, let expected = projectIndex?.documents[target.path] else {
|
|
message = "Source navigation is updating. Please select the result again when it finishes."; return
|
|
}
|
|
do {
|
|
let current: String?
|
|
if let document = documents.first(where: { $0.id == target.path && !$0.reference }) { current = document.text }
|
|
else if indexInputs.referencePaths.contains(target.path) { current = indexInputs.documents[target.path] }
|
|
else if indexInputs.generatedPaths.contains(target.path) { current = artifact?.sources[target.path].flatMap { String(data: $0, encoding: .utf8) } }
|
|
else { current = try project?.readText(relativePath: target.path) }
|
|
guard current == expected else { throw CMOCBuildError.message("This result changed since it was indexed. Refresh navigation and select it again.") }
|
|
navigate(to: target, recording: true)
|
|
} catch { message = error.localizedDescription; refreshProjectIndex() }
|
|
}
|
|
private func navigate(to target: SourceLocation, recording: Bool) {
|
|
let origin = cursorLocation
|
|
openFile(target.path, line: target.line)
|
|
guard selectedFile == target.path else { return }
|
|
if recording && origin != target {
|
|
if backwardLocations.last != origin { backwardLocations.append(origin) }
|
|
if backwardLocations.count > 100 { backwardLocations.removeFirst(backwardLocations.count - 100) }
|
|
forwardLocations = []
|
|
}
|
|
navigationColumn = target.column; navigationLength = target.length
|
|
let lines = source.components(separatedBy: "\n")
|
|
let line = min(max(1, target.line), max(1, lines.count))
|
|
let offset = lines.prefix(line - 1).reduce(0) { $0 + $1.utf16.count + 1 } + min(max(0, target.column - 1), lines[line - 1].utf16.count)
|
|
updateCursor(offset: offset); navigationRequest = UUID()
|
|
}
|
|
func navigateBack() {
|
|
guard let target = backwardLocations.last else { return }
|
|
let origin = cursorLocation
|
|
navigate(to: target, recording: false)
|
|
guard selectedFile == target.path else { return }
|
|
backwardLocations.removeLast(); forwardLocations.append(origin)
|
|
}
|
|
func navigateForward() {
|
|
guard let target = forwardLocations.last else { return }
|
|
let origin = cursorLocation
|
|
navigate(to: target, recording: false)
|
|
guard selectedFile == target.path else { return }
|
|
forwardLocations.removeLast(); backwardLocations.append(origin)
|
|
}
|
|
|
|
private func buildAttemptKey(_ directory: URL) -> String {
|
|
"CMOCBuildAttempt." + CMOCProject.sha256(Data(directory.resolvingSymlinksInPath().path.utf8))
|
|
}
|
|
var sourceStatus: String {
|
|
guard project != nil else { return "No project open" }
|
|
if documents.contains(where: { $0.missing }) { return "Missing files" }
|
|
if documents.contains(where: { $0.conflict }) { return "External changes" }
|
|
return unsaved ? "Unsaved edits" : "Saved"
|
|
}
|
|
var buildStatus: String {
|
|
guard let artifact else { return latestBuildAttempt }
|
|
return "Build \(artifact.id.uuidString.prefix(8)) · \(buildMatchesEditor ? "current" : "out of date")"
|
|
}
|
|
var programStatus: String {
|
|
if awaitingDiskLoad { return "Disk launch pending verification" }
|
|
guard let id = launchedBuildID else { return "No verified development launch" }
|
|
return "Program \(id.uuidString.prefix(8)) · \(id == artifact?.id ? "latest build" : "earlier or other project")"
|
|
}
|
|
private func trackLaunch(_ artifact: CMOCBuildArtifact, snapshot: VCCMachineSnapshot) {
|
|
launchedBuildID = artifact.id; launchedGeneration = snapshot.generation
|
|
launchedRevision = snapshot.debuggerProgramRevision
|
|
refreshBuildHistory()
|
|
}
|
|
private func historyProtection(_ entries: [CMOCBuildHistory.Entry]) -> Set<UUID> {
|
|
var ids = Set([artifact?.id, launchedBuildID].compactMap { $0 })
|
|
if let latest = entries.first(where: { $0.hasBinary || $0.hasDisk }) { ids.insert(latest.id) }
|
|
let media = machine.developmentAssignedMediaURLs.map { $0.resolvingSymlinksInPath().standardizedFileURL.path }
|
|
for entry in entries {
|
|
let path = entry.directory.resolvingSymlinksInPath().standardizedFileURL.path
|
|
if media.contains(where: { $0 == path || $0.hasPrefix(path + "/") || path.hasPrefix($0 + "/") }) { ids.insert(entry.id) }
|
|
}
|
|
return ids
|
|
}
|
|
func refreshBuildHistory() {
|
|
guard let project else { return }
|
|
guard !historyBusy else { historyRefreshPending = true; return }
|
|
historyBusy = true; historyRefreshPending = false
|
|
let service = service
|
|
Task {
|
|
defer {
|
|
historyBusy = false
|
|
if historyRefreshPending { refreshBuildHistory() }
|
|
}
|
|
do {
|
|
let entries = try await Task.detached(priority: .utility) { try service.history(project: project.directory) }.value
|
|
guard self.project?.directory == project.directory else { return }
|
|
let protected = historyProtection(entries)
|
|
let checked = try await Task.detached(priority: .utility) { try service.history(project: project.directory, protectedIDs: protected) }.value
|
|
guard self.project?.directory == project.directory else { return }
|
|
buildHistory = checked
|
|
} catch { historyMessage = error.localizedDescription }
|
|
}
|
|
}
|
|
func trashBuilds(_ ids: Set<UUID>) {
|
|
guard !historyBusy, !building, !commanding, !ids.isEmpty, let project else { return }
|
|
let alert = NSAlert(); alert.messageText = "Move selected build results to Trash?"
|
|
alert.informativeText = "Only verified, unchanged build snapshots can be removed. The latest and loaded builds, assigned media, and your writable Development Runs disks are protected."
|
|
alert.addButton(withTitle: "Move to Trash"); alert.addButton(withTitle: "Cancel")
|
|
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
|
historyBusy = true; historyRemoving = true; historyMessage = nil
|
|
let service = service
|
|
Task {
|
|
do {
|
|
let entries = try await Task.detached(priority: .utility) { try service.history(project: project.directory) }.value
|
|
let protected = historyProtection(entries)
|
|
let result = try await Task.detached(priority: .utility) { try service.removeBuilds(ids: ids, project: project.directory, protectedIDs: protected) }.value
|
|
historyMessage = "Moved \(result.removedIDs.count) result(s) to Trash." + (result.retained.isEmpty ? "" : " Kept \(result.retained.count): " + Set(result.retained.values).sorted().joined(separator: "; "))
|
|
} catch { historyMessage = error.localizedDescription }
|
|
historyBusy = false; historyRemoving = false; refreshBuildHistory()
|
|
}
|
|
}
|
|
func revealDevelopmentDisks() {
|
|
do {
|
|
try FileManager.default.createDirectory(at: machine.developmentRunDirectory, withIntermediateDirectories: true)
|
|
NSWorkspace.shared.open(machine.developmentRunDirectory)
|
|
} catch { historyMessage = error.localizedDescription }
|
|
}
|
|
private var recoveryDrafts: [CMOCWorkspaceRecovery.Draft] {
|
|
documents.filter { !$0.generated && !$0.reference && ($0.dirty || $0.missing || $0.conflict) }.map {
|
|
.init(path: $0.id, text: $0.text, savedText: $0.savedText, savedHash: $0.savedHash)
|
|
}
|
|
}
|
|
private func scheduleDraftSave() {
|
|
recoveryDebounce?.cancel()
|
|
recoveryDebounce = Task { [weak self] in
|
|
do { try await Task.sleep(nanoseconds: 500_000_000) } catch { return }
|
|
self?.persistDrafts()
|
|
}
|
|
}
|
|
func persistDrafts() {
|
|
scheduleProjectIndex()
|
|
recoveryDebounce?.cancel(); recoveryDebounce = nil
|
|
guard let project else { return }
|
|
let drafts = recoveryDrafts, store = recoveryStore
|
|
recoveryQueue.async { [weak self] in
|
|
do { try store.save(projectDirectory: project.directory, drafts: drafts) }
|
|
catch {
|
|
let detail = error.localizedDescription
|
|
Task { @MainActor [weak self] in
|
|
guard self?.project?.directory == project.directory else { return }
|
|
self?.message = "Could not save recovery copies: " + detail
|
|
}
|
|
}
|
|
}
|
|
}
|
|
func flushDraftRecovery(completion: @escaping @MainActor () -> Void) {
|
|
persistDrafts()
|
|
recoveryQueue.async { Task { @MainActor in completion() } }
|
|
}
|
|
func refreshRecovery() {
|
|
guard let directory = recoveryProjectDirectory else { return }
|
|
guard !recoveryBusy else { recoveryRefreshPending = true; return }
|
|
recoveryBusy = true; recoveryRefreshPending = false
|
|
let store = recoveryStore
|
|
recoveryQueue.async { [weak self] in
|
|
let result = Result { try store.scan(projectDirectory: directory) }
|
|
Task { @MainActor [weak self] in
|
|
guard let self else { return }; recoveryBusy = false
|
|
guard recoveryProjectDirectory == directory else { refreshRecovery(); return }
|
|
switch result {
|
|
case .success(let scan): recoveryRecords = scan.records.filter { $0.id != store.sessionID }; recoveryIssues = scan.issues
|
|
case .failure(let error): recoveryIssues = [error.localizedDescription]
|
|
}
|
|
if recoveryRefreshPending { refreshRecovery() }
|
|
}
|
|
}
|
|
}
|
|
func restoreRecovery(_ record: CMOCWorkspaceRecovery.Record) {
|
|
guard !building, !commanding, !recoveryBusy, !record.isFromRunningSession else { return }
|
|
guard let project, project.directory.resolvingSymlinksInPath().path == record.projectPath else {
|
|
message = "Open this draft's project to restore into the editor, or export its files to a new folder."; return
|
|
}
|
|
guard confirmDiscard() else { return }
|
|
for draft in record.drafts {
|
|
let disk = try? project.readText(relativePath: draft.path)
|
|
let conflict = disk.map { CMOCProject.sha256(Data($0.utf8)) != draft.savedHash } ?? true
|
|
let doc = CMOCEditorDocument(id: draft.path, text: draft.text, savedText: draft.savedText,
|
|
savedHash: draft.savedHash, conflict: conflict, missing: disk == nil)
|
|
if let index = documents.firstIndex(where: { $0.id == draft.path }) { documents[index] = doc }
|
|
else { documents.append(doc) }
|
|
}
|
|
if let first = record.drafts.first { selecting = true; selectedFile = first.path; source = first.text; selecting = false }
|
|
externalBuildChange = true; rememberWorkspace(); recoveryBusy = true
|
|
let store = recoveryStore, drafts = recoveryDrafts
|
|
// Publish a new durable copy before removing the prior session's copy.
|
|
recoveryQueue.async { [weak self] in
|
|
let result = Result { try store.save(projectDirectory: project.directory, drafts: drafts); try store.discard(record) }
|
|
Task { @MainActor [weak self] in
|
|
guard let self else { return }; recoveryBusy = false
|
|
if case .failure(let error) = result { message = error.localizedDescription }
|
|
else { message = "Drafts restored into the editor. Project files have not been overwritten." }
|
|
refreshRecovery()
|
|
}
|
|
}
|
|
}
|
|
func discardRecovery(_ record: CMOCWorkspaceRecovery.Record) {
|
|
guard !recoveryBusy, !record.isFromRunningSession else { return }
|
|
let alert = NSAlert(); alert.messageText = "Discard this recovery copy?"
|
|
alert.informativeText = "This removes only the saved recovery copy of \(record.drafts.count) file(s). Export it first if you may need it. Project files are unchanged."
|
|
alert.addButton(withTitle: "Discard Recovery Copy"); alert.addButton(withTitle: "Cancel")
|
|
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
|
recoveryBusy = true; let store = recoveryStore
|
|
recoveryQueue.async { [weak self] in
|
|
let result = Result { try store.discard(record) }
|
|
Task { @MainActor [weak self] in
|
|
guard let self else { return }; recoveryBusy = false
|
|
if case .failure(let error) = result { recoveryIssues = [error.localizedDescription] }
|
|
refreshRecovery()
|
|
}
|
|
}
|
|
}
|
|
func exportRecovery(_ record: CMOCWorkspaceRecovery.Record) {
|
|
let panel = NSOpenPanel(); panel.title = "Export Recovered Sources"
|
|
panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true
|
|
guard panel.runModal() == .OK, let parent = panel.url else { return }
|
|
do {
|
|
let folder = parent.appendingPathComponent("Recovered Sources-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
|
|
for draft in record.drafts {
|
|
try CMOCProject.validateRelativePath(draft.path)
|
|
let target = folder.appendingPathComponent(draft.path)
|
|
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
try CMOCProject.sourceBytes(draft.text).write(to: target, options: .withoutOverwriting)
|
|
}
|
|
NSWorkspace.shared.open(folder)
|
|
} catch { recoveryIssues = [error.localizedDescription] }
|
|
}
|
|
func saveSelectedCopy() {
|
|
guard let doc = documents.first(where: { $0.id == selectedFile }) else { return }
|
|
let panel = NSSavePanel(); panel.title = "Save Selected Copy"; panel.nameFieldStringValue = URL(fileURLWithPath: doc.id).lastPathComponent
|
|
guard panel.runModal() == .OK, let url = panel.url else { return }
|
|
do {
|
|
if let original = try project?.fileURL(relativePath: doc.id), original.resolvingSymlinksInPath() == url.resolvingSymlinksInPath() {
|
|
throw CMOCBuildError.message("Choose a different filename or folder for this recovery copy. Use Save All to update an unchanged original.")
|
|
}
|
|
try CMOCProject.sourceBytes(doc.text).write(to: url, options: .atomic)
|
|
message = "Saved a copy of \(doc.id). The editor and original file are unchanged."
|
|
} catch { message = error.localizedDescription }
|
|
}
|
|
|
|
var unsaved: Bool { documents.contains(where: \.dirty) }
|
|
var overlays: [String:String] { Dictionary(uniqueKeysWithValues: documents.filter { !$0.generated && !$0.reference }.map { ($0.id, $0.text) }) }
|
|
var selectedFileIsGenerated: Bool { documents.first(where: { $0.id == selectedFile }).map { $0.generated || $0.reference } == true }
|
|
var buildMatchesEditor: Bool {
|
|
guard let artifact, !externalBuildChange, !documents.contains(where: { $0.missing || $0.conflict }), artifact.configurationName == configurationName else { return false }
|
|
return documents.filter { !$0.reference }.allSatisfy { document in
|
|
// Build inputs include Makefile and headers, not just mapped C files.
|
|
guard let hash = (document.generated ? artifact.sourceHashes[document.id] : artifact.fileHashes[document.id]) else { return false }
|
|
return hash == CMOCProject.sha256(Data(document.text.utf8))
|
|
}
|
|
}
|
|
var breakpointAddress: UInt16? { buildMatchesEditor ? projectMapping?.addresses(file: selectedFile, line: breakpointLine).first : nil }
|
|
var canRun: Bool { !historyRemoving && !building && !commanding && machine.canQuickLoad && !runToBreakpointAddresses.isEmpty && (projectMapping?.bankedLayout == nil || artifact?.hasDisk == true) }
|
|
var bundledLibraryCatalog: [CMOCBundledLibrary] { (try? CMOCBundledLibrary.catalog(at: service.toolchain)) ?? [] }
|
|
var canLaunch: Bool { !historyRemoving && !building && !commanding && !machine.busy && !machine.diskSaving && buildMatchesEditor && (artifact?.hasBinary == true || artifact?.hasDisk == true) }
|
|
var loadedMatchesEditor: Bool { loadedBuild == artifact?.id && loadedBuild != nil && buildMatchesEditor && projectMapping != nil }
|
|
var canCommand: Bool { !commanding && !machine.busy && !machine.diskSaving && (machine.state == .running || machine.state == .paused) }
|
|
var canStepC: Bool {
|
|
canCommand && !building && loadedMatchesEditor && !awaitingDiskLoad && machine.state == .paused &&
|
|
currentLine != nil && pausedDebugSnapshot != nil && pausedInputEpoch == machine.inputEpoch
|
|
}
|
|
var canInspectC: Bool {
|
|
!building && !commanding && !machine.busy && loadedMatchesEditor && machine.state == .paused &&
|
|
pausedDebugSnapshot != nil && pausedInputEpoch == machine.inputEpoch && variableMetadata != nil
|
|
}
|
|
var callStack: CMOCCallStack? { canInspectC ? capturedCallStack : nil }
|
|
var inspectionFrame: CMOCCallStack.Frame? {
|
|
guard let frames = callStack?.frames, frames.indices.contains(selectedFrameIndex) else { return nil }
|
|
return frames[selectedFrameIndex]
|
|
}
|
|
var inspectingCaller: Bool { inspectionFrame != nil && selectedFrameIndex > 0 }
|
|
var inspectionFrameDescription: String? {
|
|
guard let frame = inspectionFrame else { return nil }
|
|
let location = frame.sourceLine.map { "\(frame.sourcePath):\($0)" } ?? frame.sourcePath
|
|
return "Frame \(frame.id) · \(frame.functionName) · \(location)"
|
|
}
|
|
func selectFrame(_ index: Int) {
|
|
guard let frames = callStack?.frames, frames.indices.contains(index) else { return }
|
|
selectedFrameIndex = index
|
|
let frame = frames[index]
|
|
openFile(frame.sourcePath, line: frame.sourceLine)
|
|
}
|
|
private var evaluator: CMOCWatchEvaluator? {
|
|
guard canInspectC, let metadata = variableMetadata, let snapshot = pausedDebugSnapshot,
|
|
let u = snapshot.registers["U"] else { return nil }
|
|
let frame = inspectionFrame
|
|
return CMOCWatchEvaluator(metadata: metadata.projected(physicalPages: Self.physicalPages(snapshot), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable), context: .init(pc: frame?.pc ?? snapshot.machine.programCounter,
|
|
u: frame?.u ?? u.uint16Value, memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable),
|
|
frameLocalsAvailable: frame?.localsInspectable == true)
|
|
}
|
|
var visibleVariables: [CMOCWatchEvaluator.Value] { evaluator?.visibleVariables() ?? [] }
|
|
func watchValue(_ expression: String) -> CMOCWatchEvaluator.Value? { evaluator?.evaluate(expression) }
|
|
var variableInspectionIdentity: String? {
|
|
canInspectC ? "\(inspectionRevision.uuidString):\(selectedFrameIndex)" : nil
|
|
}
|
|
func variableTree(watches: Bool, expanded: Set<CMOCWatchEvaluator.TreePath>,
|
|
offsets: [CMOCWatchEvaluator.TreePath: Int], rootOffset: Int) -> CMOCVariableTreeListing {
|
|
guard let evaluator else { return .init(rows: [], rootCount: 0, rootOffset: 0) }
|
|
let roots = watches ? self.watches.map { CMOCWatchEvaluator.TreePath(root: .watch($0)) } : evaluator.variableRootPaths()
|
|
let start = max(0, min(rootOffset, max(0, ((roots.count - 1) / 32) * 32)))
|
|
var rows: [CMOCVariableTreeRow] = []
|
|
var limited = false
|
|
func append(_ node: CMOCWatchEvaluator.TreeNode, depth: Int) {
|
|
guard rows.count < 255 else { limited = true; return }
|
|
rows.append(.init(id: .node(node.path), depth: depth, content: .node(node)))
|
|
guard node.childCount > 0, expanded.contains(node.path) else { return }
|
|
let offset = max(0, min(offsets[node.path] ?? 0, ((node.childCount - 1) / 32) * 32))
|
|
let page = evaluator.children(of: node.path, offset: offset)
|
|
for child in page.nodes { append(child, depth: depth + 1) }
|
|
if let error = page.error, rows.count < 255 {
|
|
rows.append(.init(id: .page(node.path), depth: depth + 1, content: .message(error)))
|
|
} else if offset > 0 || page.nextOffset != nil {
|
|
if rows.count < 255 {
|
|
rows.append(.init(id: .page(node.path), depth: depth + 1,
|
|
content: .page(node.path, offset: offset, total: page.totalCount, next: page.nextOffset)))
|
|
} else { limited = true }
|
|
}
|
|
}
|
|
for root in roots.dropFirst(start).prefix(32) { append(evaluator.treeNode(at: root), depth: 0) }
|
|
if limited {
|
|
rows.append(.init(id: .limit, depth: 0,
|
|
content: .message("Showing 255 rows. Collapse a branch to inspect more of this page.")))
|
|
}
|
|
return .init(rows: rows, rootCount: roots.count, rootOffset: start)
|
|
}
|
|
var inspectionMessage: String {
|
|
if variableMetadata == nil { return variableStatus }
|
|
if !loadedMatchesEditor { return "Run this build with unchanged sources to inspect C values." }
|
|
if machine.state == .running { return "Pause at a verified C location to inspect values." }
|
|
if pausedDebugSnapshot == nil { return "No verified C location here. Instruction stepping remains available in Debugger." }
|
|
return "Values are read from the paused CoCo. Watches never execute code or change memory."
|
|
}
|
|
private var watchKey: String? {
|
|
project.map { "CMOCWorkspace.watches." + CMOCProject.sha256(Data($0.directory.path.utf8)) }
|
|
}
|
|
func addWatch() {
|
|
let expression = watchExpression.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !expression.isEmpty, expression.count <= 256, watches.count < 32 else { return }
|
|
if !watches.contains(expression) { watches.append(expression) }
|
|
watchExpression = ""
|
|
if let watchKey { defaults.set(watches, forKey: watchKey) }
|
|
}
|
|
func removeWatch(_ expression: String) {
|
|
watches.removeAll { $0 == expression }
|
|
if let watchKey { defaults.set(watches, forKey: watchKey) }
|
|
}
|
|
var selectedBreakpoints: Set<Int> { Set(breakpoints.filter { $0.file == selectedFile }.map(\.line)) }
|
|
var executableLines: [Int] { projectMapping?.executableLines(in: selectedFile) ?? [] }
|
|
|
|
func confirmDiscard() -> Bool {
|
|
guard unsaved else { return true }
|
|
let alert = NSAlert(); alert.messageText = "Save changes to this project?"
|
|
alert.informativeText = "\(documents.filter(\.dirty).count) open file(s) contain unsaved changes."
|
|
alert.addButton(withTitle: "Save All"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes")
|
|
switch alert.runModal() {
|
|
case .alertFirstButtonReturn: return save()
|
|
case .alertThirdButtonReturn:
|
|
for i in documents.indices { documents[i].text = documents[i].savedText }
|
|
if let selected = documents.first(where: { $0.id == selectedFile }) { selecting = true; source = selected.text; selecting = false }
|
|
persistDrafts(); return true
|
|
default: return false
|
|
}
|
|
}
|
|
func newProject() {
|
|
guard !building, confirmDiscard() else { return }
|
|
let choice = NSAlert(); choice.messageText = "Choose a C project template"
|
|
choice.informativeText = "Hello Disk demonstrates multiple source files, generated data, disk-file reading and a settings-generated Makefile. Hello World asks you to pick Earth or Mars in a single C file. Talking Planet Lander uses two optional sound cartridges and a joystick. Each template creates an editable copy."
|
|
choice.addButton(withTitle: "Hello Disk"); choice.addButton(withTitle: "Hello World"); choice.addButton(withTitle: "Talking Planet Lander"); choice.addButton(withTitle: "Cancel").keyEquivalent = "\u{1b}"
|
|
let selection = choice.runModal()
|
|
guard [.alertFirstButtonReturn, .alertSecondButtonReturn, .alertThirdButtonReturn].contains(selection) else { return }
|
|
let diskTemplate = selection == .alertFirstButtonReturn
|
|
let panel = NSSavePanel(); panel.title = "Create C Project Folder"; panel.nameFieldStringValue = diskTemplate ? "HelloDisk" : (selection == .alertThirdButtonReturn ? "TalkingPlanetLander" : "HelloCoCo")
|
|
panel.canCreateDirectories = true; panel.prompt = "Create Project"
|
|
guard panel.runModal() == .OK, let url = panel.url else { return }
|
|
do {
|
|
switch selection {
|
|
case .alertFirstButtonReturn: try adopt(CMOCProject.createHelloDisk(at: url))
|
|
case .alertThirdButtonReturn: try adopt(CMOCProject.createTalkingLander(at: url))
|
|
default: try adopt(CMOCProject.create(at: url))
|
|
}
|
|
} catch { message = error.localizedDescription }
|
|
}
|
|
func openProject() {
|
|
guard !building, confirmDiscard() else { return }
|
|
let panel = NSOpenPanel(); panel.title = "Open C Project"; panel.message = "Choose a project folder with a Makefile. Opening does not run its build commands."
|
|
panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.allowsMultipleSelection = false
|
|
guard panel.runModal() == .OK, let url = panel.url else { return }
|
|
recoveryProjectDirectory = url; refreshRecovery()
|
|
do { try adopt(CMOCProject.open(at: url)) } catch { message = error.localizedDescription }
|
|
}
|
|
/// An explicit Library import opens known source without executing its Makefile.
|
|
/// Recheck the workspace after asynchronous disk validation and after review.
|
|
@discardableResult
|
|
func openImportedProject(at directory: URL, expectedProjectID: UUID,
|
|
preferredConfiguration: String? = nil,
|
|
reviewUnsaved: (() -> Bool)? = nil) async throws -> Bool {
|
|
func checkWorkspace() throws {
|
|
guard assistantProjectID == expectedProjectID else {
|
|
throw CMOCBuildError.message("The C project changed during the download. Your imported source is saved; open its folder when you are ready.")
|
|
}
|
|
guard !building, !commanding, !historyRemoving else {
|
|
throw CMOCBuildError.message("Your imported source is saved. Wait for the current C operation to finish before opening its folder.")
|
|
}
|
|
}
|
|
try checkWorkspace()
|
|
let checked = try await Task.detached(priority: .userInitiated) { try CMOCProject.open(at: directory) }.value
|
|
if let preferredConfiguration, !checked.configuration.configurations.contains(where: { $0.name == preferredConfiguration }) {
|
|
throw CMOCBuildError.message("The source package's requested build configuration is missing. Your current project is kept.")
|
|
}
|
|
try Task.checkCancellation()
|
|
try checkWorkspace()
|
|
let accepted: Bool
|
|
if let reviewUnsaved { accepted = reviewUnsaved() }
|
|
else { accepted = try await reviewImportedProjectSwitch(expectedProjectID: expectedProjectID) }
|
|
guard accepted else { return false }
|
|
try checkWorkspace()
|
|
try adopt(checked)
|
|
if let preferredConfiguration { configurationName = preferredConfiguration }
|
|
return true
|
|
}
|
|
private func reviewImportedProjectSwitch(expectedProjectID: UUID) async throws -> Bool {
|
|
guard unsaved else { return true }
|
|
guard let parent = NSApp.windows.first(where: { $0.identifier?.rawValue == "c-development" && $0.isVisible }) ?? NSApp.keyWindow else {
|
|
throw CMOCBuildError.message("Your source copy is saved. Open C Development to review unsaved changes before switching projects.")
|
|
}
|
|
let alert = NSAlert(); alert.messageText = "Save changes to this project?"
|
|
alert.informativeText = "\(documents.filter(\.dirty).count) open file(s) contain unsaved changes. Your downloaded source folder is already saved."
|
|
alert.addButton(withTitle: "Save All"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes")
|
|
parent.makeKeyAndOrderFront(nil)
|
|
let response = await LibraryReviewSheet(alert: alert, parent: parent).present()
|
|
try Task.checkCancellation()
|
|
guard assistantProjectID == expectedProjectID, !building, !commanding, !historyRemoving else {
|
|
throw CMOCBuildError.message("The C workspace changed during review. Your imported folder and current project are kept.")
|
|
}
|
|
switch response {
|
|
case .alertFirstButtonReturn: return save()
|
|
case .alertThirdButtonReturn:
|
|
for i in documents.indices { documents[i].text = documents[i].savedText }
|
|
if let selected = documents.first(where: { $0.id == selectedFile }) { selecting = true; source = selected.text; selecting = false }
|
|
persistDrafts(); return true
|
|
default: return false
|
|
}
|
|
}
|
|
func adopt(_ project: CMOCProject) throws {
|
|
guard !building, !commanding, !historyRemoving else { throw CMOCBuildError.message("Wait for the current build or launch to finish before changing projects.") }
|
|
persistDrafts()
|
|
let entries = try project.fileEntries()
|
|
let entry = project.configuration.entrySource
|
|
let text = try project.readText(relativePath: entry)
|
|
MCPCMOC.shared.closing(self)
|
|
assistantProjectID = UUID()
|
|
resetNavigation(); self.project = project; files = entries
|
|
documents = [.init(id: entry, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8)))]
|
|
selecting = true; selectedFile = entry; source = text; selecting = false
|
|
pausedDebugSnapshot = nil; capturedCallStack = nil; selectedFrameIndex = 0; sourceStepping = false
|
|
artifact = nil; mapping = nil; projectMapping = nil; loadedBuild = nil; loadedGeneration = nil; currentLine = nil; currentFile = nil; pc = nil
|
|
variableMetadata = nil; variableStatus = "Build with the bundled compiler to inspect C variables."
|
|
watches = watchKey.flatMap { defaults.stringArray(forKey: $0) }?.filter { !$0.isEmpty && $0.count <= 256 }.prefix(32).map { $0 } ?? []
|
|
watchExpression = ""
|
|
breakpoints = []; externalBuildChange = false
|
|
configurationName = project.configuration.configurations.first?.name ?? "Debug"
|
|
revision = UUID(); message = nil; execution = "No build from this project loaded"
|
|
log = "Opened \(project.directory.lastPathComponent). Build executes this project's Makefile."
|
|
diagnostics = []
|
|
let previousAttempt = defaults.string(forKey: buildAttemptKey(project.directory))
|
|
latestBuildAttempt = previousAttempt == "In progress" ? "Previous build did not report completion; rebuild to continue" : "Not built in this session"
|
|
rememberWorkspace()
|
|
buildHistory = []; historyMessage = nil; recoveryRecords = []; recoveryIssues = []
|
|
recoveryProjectDirectory = project.directory; refreshRecovery(); refreshBuildHistory(); refreshProjectIndex()
|
|
}
|
|
func restoreWorkspace() {
|
|
guard !restorationAttempted else { return }; restorationAttempted = true
|
|
guard project == nil, let path = defaults.string(forKey: "CMOCWorkspace.directory") else { return }
|
|
recoveryProjectDirectory = URL(fileURLWithPath: path); refreshRecovery()
|
|
let tabs = defaults.stringArray(forKey: "CMOCWorkspace.tabs") ?? []
|
|
let selected = defaults.string(forKey: "CMOCWorkspace.selected")
|
|
let configuration = defaults.string(forKey: "CMOCWorkspace.configuration")
|
|
do {
|
|
try adopt(CMOCProject.open(at: URL(fileURLWithPath: path)))
|
|
if let configuration, project?.configuration.configurations.contains(where: { $0.name == configuration }) == true { configurationName = configuration }
|
|
for tab in tabs where files.contains(where: { $0.relativePath == tab && $0.isEditable }) { openFile(tab) }
|
|
if let selected, documents.contains(where: { $0.id == selected }) { openFile(selected) }
|
|
} catch { message = "The previous project could not be reopened: \(error.localizedDescription)" }
|
|
}
|
|
private func rememberWorkspace() {
|
|
guard let project else { return }
|
|
defaults.set(project.directory.path, forKey: "CMOCWorkspace.directory")
|
|
defaults.set(documents.filter { !$0.reference }.map(\.id), forKey: "CMOCWorkspace.tabs")
|
|
defaults.set(selectedFile, forKey: "CMOCWorkspace.selected")
|
|
defaults.set(configurationName, forKey: "CMOCWorkspace.configuration")
|
|
}
|
|
func openFile(_ requestedPath: String, line: Int? = nil) {
|
|
let path = diagnosticPath(requestedPath)
|
|
guard let project else { return }
|
|
do {
|
|
if indexInputs.referencePaths.contains(path), let text = indexInputs.documents[path] {
|
|
let document = CMOCEditorDocument(id: path, text: text, savedText: text,
|
|
savedHash: CMOCProject.sha256(Data(text.utf8)), reference: true)
|
|
if let i = documents.firstIndex(where: { $0.id == path }) { documents[i] = document }
|
|
else { documents.append(document) }
|
|
}
|
|
if !documents.contains(where: { $0.id == path }) {
|
|
let diskText = try? project.readText(relativePath: path)
|
|
guard let text = diskText ?? artifact?.sources[path].flatMap({ String(data: $0, encoding: .utf8) }) else {
|
|
throw CMOCBuildError.message("This source file is unavailable: " + path)
|
|
}
|
|
documents.append(.init(id: path, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8)), generated: diskText == nil))
|
|
}
|
|
guard let document = documents.first(where: { $0.id == path }) else { return }
|
|
selecting = true; selectedFile = path; source = document.text; selecting = false
|
|
mapping = projectMapping?.map(forFile: path)
|
|
if !executableLines.contains(breakpointLine) { breakpointLine = executableLines.first ?? 1 }
|
|
navigationLine = line; navigationColumn = nil; navigationLength = 0
|
|
cursorOffset = min(cursorOffsets[path] ?? 0, source.utf16.count)
|
|
clearParameterHints(); scheduleParameterHints()
|
|
navigationRequest = UUID(); rememberWorkspace()
|
|
} catch { message = error.localizedDescription }
|
|
}
|
|
private func diagnosticPath(_ path: String) -> String {
|
|
guard path.hasPrefix("/") else { return path }
|
|
if let project, path.hasPrefix(project.directory.path + "/") { return String(path.dropFirst(project.directory.path.count + 1)) }
|
|
// Compile diagnostics use the controlled .workspaces/<hash>/project root.
|
|
// Require a known complete project-relative suffix; never match a basename.
|
|
if let range = path.range(of: "/project/", options: .backwards), (path.contains("/.workspaces/") || path.hasPrefix("/private/tmp/vccplus-cmoc-")) {
|
|
let relative = String(path[range.upperBound...])
|
|
if files.contains(where: { $0.relativePath == relative }) { return relative }
|
|
}
|
|
return path
|
|
}
|
|
func closeFile(_ path: String) {
|
|
guard let document = documents.first(where: { $0.id == path }) else { return }
|
|
if document.dirty {
|
|
let alert = NSAlert(); alert.messageText = "Save changes to \(path)?"
|
|
alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard")
|
|
let result = alert.runModal()
|
|
if result == .alertSecondButtonReturn { return }
|
|
if result == .alertFirstButtonReturn && !saveFile(path) { return }
|
|
}
|
|
// Keep the final tab visible, but honor the user's Save/Discard decision.
|
|
if documents.count == 1 {
|
|
if let text = try? project?.readText(relativePath: path) {
|
|
documents[0] = .init(id: path, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8)))
|
|
selecting = true; source = text; selecting = false
|
|
} else {
|
|
documents[0].text = documents[0].savedText
|
|
selecting = true; source = documents[0].text; selecting = false
|
|
}
|
|
persistDrafts(); return
|
|
}
|
|
documents.removeAll { $0.id == path }
|
|
if selectedFile == path, let first = documents.first { openFile(first.id) }
|
|
rememberWorkspace(); persistDrafts()
|
|
}
|
|
/// Prepare all affected editor drafts before publishing any of them. Files
|
|
/// stay on disk until the user explicitly saves through the normal workspace.
|
|
func applyAssistantEdits(_ edits: [MCPCMOCEdit], disk: [String: String], projectID: UUID, epoch: Int, undoing: Bool = false) throws {
|
|
guard assistantProjectID == projectID, assistantEditEpoch == epoch, !building, !commanding,
|
|
assistantEditor?.hasMarkedText() != true else { throw CMOCBuildError.message("stale_revision") }
|
|
var updated = documents
|
|
for edit in edits {
|
|
guard let saved = disk[edit.path] else { throw CMOCBuildError.message("stale_revision") }
|
|
if let i = updated.firstIndex(where: { $0.id == edit.path }) {
|
|
guard !updated[i].conflict, !updated[i].missing, !updated[i].reference, !updated[i].generated,
|
|
updated[i].text.utf8.elementsEqual(edit.before.utf8), updated[i].savedText.utf8.elementsEqual(saved.utf8)
|
|
else { throw CMOCBuildError.message("stale_revision") }
|
|
updated[i].text = edit.after
|
|
} else {
|
|
guard saved.utf8.elementsEqual(edit.before.utf8) else { throw CMOCBuildError.message("stale_revision") }
|
|
updated.append(.init(id: edit.path, text: edit.after, savedText: saved, savedHash: CMOCProject.sha256(Data(saved.utf8))))
|
|
}
|
|
}
|
|
assistantEditorPool?.setReviewedBuffers(edits, undoing: undoing)
|
|
documents = updated
|
|
if let selected = updated.first(where: { $0.id == selectedFile }) {
|
|
selecting = true; source = selected.text; selecting = false
|
|
}
|
|
assistantEditEpoch += 1
|
|
rememberWorkspace(); persistDrafts(); scheduleParameterHints()
|
|
}
|
|
|
|
/// Adopt an already captured and reviewed disk/configuration snapshot.
|
|
/// Clean tabs follow external edits; dirty drafts keep their exact bytes and
|
|
/// can only continue when their saved disk base is still unchanged.
|
|
func acceptAssistantProjectRefresh(_ updatedProject: CMOCProject, diskFiles: [String: Data],
|
|
projectID: UUID, epoch: Int) throws {
|
|
guard assistantProjectID == projectID, assistantEditEpoch == epoch,
|
|
project?.directory == updatedProject.directory, !building, !commanding,
|
|
assistantEditor?.hasMarkedText() != true else { throw CMOCBuildError.message("stale_revision") }
|
|
var updated = documents
|
|
for index in updated.indices where !updated[index].generated && !updated[index].reference {
|
|
let document = updated[index]
|
|
let bytes = diskFiles[document.id]
|
|
if document.dirty || document.conflict {
|
|
guard let bytes, CMOCProject.sha256(bytes) == document.savedHash, !document.conflict else {
|
|
throw CMOCBuildError.message("external_file_change: " + document.id + ": Your editor draft is kept; resolve its disk conflict locally before refreshing.")
|
|
}
|
|
continue
|
|
}
|
|
guard let bytes, let text = String(data: bytes, encoding: .utf8), !bytes.contains(0) else {
|
|
updated[index].missing = true; continue
|
|
}
|
|
updated[index].text = text; updated[index].savedText = text
|
|
updated[index].savedHash = CMOCProject.sha256(bytes)
|
|
updated[index].missing = false; updated[index].conflict = false
|
|
}
|
|
self.project = updatedProject
|
|
files = diskFiles.keys.sorted().map { .init(relativePath: $0, isEditable: CMOCProject.isEditable($0)) }
|
|
documents = updated
|
|
if let selected = updated.first(where: { $0.id == selectedFile }) {
|
|
selecting = true; source = selected.text; selecting = false
|
|
}
|
|
if !updatedProject.configuration.configurations.contains(where: { $0.name == configurationName }) {
|
|
configurationName = updatedProject.configuration.configurations.first?.name ?? "Debug"
|
|
}
|
|
externalBuildChange = true
|
|
rememberWorkspace(); persistDrafts(); scheduleProjectIndex()
|
|
}
|
|
|
|
@discardableResult func saveFile(_ path: String) -> Bool {
|
|
guard let project, let index = documents.firstIndex(where: { $0.id == path }) else { return false }
|
|
guard !documents[index].generated && !documents[index].reference else { message = "Reference and generated source is read-only. Edit project sources or generator inputs."; return false }
|
|
do {
|
|
let hash = try project.saveText(documents[index].text, relativePath: path, replacingSHA256: documents[index].savedHash)
|
|
documents[index].savedHash = hash; documents[index].savedText = documents[index].text; documents[index].conflict = false
|
|
message = nil; persistDrafts(); return true
|
|
} catch { message = error.localizedDescription; return false }
|
|
}
|
|
@discardableResult func save() -> Bool {
|
|
guard project != nil else { message = "Create a project before saving."; return false }
|
|
for path in documents.filter(\.dirty).map(\.id) { if !saveFile(path) { return false } }
|
|
return true
|
|
}
|
|
func reloadSelected() {
|
|
guard let project else { return }
|
|
if documents.first(where: { $0.id == selectedFile })?.reference == true { refreshProjectIndex(); return }
|
|
if documents.first(where: { $0.id == selectedFile })?.dirty == true {
|
|
let alert = NSAlert(); alert.messageText = "Reload \(selectedFile) from disk?"
|
|
alert.informativeText = "This discards unsaved edits in this file."
|
|
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Reload")
|
|
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
|
}
|
|
do {
|
|
let text = try project.readText(relativePath: selectedFile)
|
|
if let i = documents.firstIndex(where: { $0.id == selectedFile }) {
|
|
documents[i] = .init(id: selectedFile, text: text, savedText: text, savedHash: CMOCProject.sha256(Data(text.utf8)))
|
|
selecting = true; source = text; selecting = false; message = nil; persistDrafts()
|
|
}
|
|
} catch { message = error.localizedDescription }
|
|
}
|
|
func addFile() {
|
|
guard !building, !commanding, let project else { return }
|
|
let panel = NSSavePanel(); panel.title = "New Project File"; panel.nameFieldStringValue = "module.c"; panel.directoryURL = project.directory
|
|
guard panel.runModal() == .OK, let url = panel.url else { return }
|
|
let prefix = project.directory.standardizedFileURL.path + "/"
|
|
guard url.standardizedFileURL.path.hasPrefix(prefix) else { message = "Choose a location inside this project."; return }
|
|
do {
|
|
guard !FileManager.default.fileExists(atPath: url.path) else { throw CMOCBuildError.message("Choose a new filename; existing files are kept.") }
|
|
let path = String(url.standardizedFileURL.path.dropFirst(prefix.count))
|
|
_ = try project.fileURL(relativePath: path)
|
|
try Data().write(to: url, options: .withoutOverwriting)
|
|
files = try project.fileEntries(); openFile(path)
|
|
} catch { message = error.localizedDescription }
|
|
}
|
|
func editProjectConfiguration() {
|
|
guard let project else { return }
|
|
do {
|
|
let url = project.directory.appendingPathComponent("vccplus-project.json")
|
|
if !FileManager.default.fileExists(atPath: url.path) {
|
|
let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
|
try encoder.encode(project.configuration).write(to: url, options: .withoutOverwriting)
|
|
}
|
|
files = try project.fileEntries(); openFile("vccplus-project.json")
|
|
log = "Project settings are ordinary JSON. Save before building to apply changes; Makefile rules remain authoritative."
|
|
} catch { message = error.localizedDescription }
|
|
}
|
|
func applyProjectSettings(_ configuration: CMOCProjectConfiguration, makefile: String?, expectedMakefileHash: String, expectedConfigHash: String?) throws {
|
|
guard let project, !building, !commanding else { return }
|
|
let configPath = CMOCProject.configurationFilename
|
|
guard !documents.contains(where: { ($0.id == project.configuration.makefile || $0.id == configPath) && $0.dirty }) else {
|
|
throw CMOCBuildError.message("Save or reload your edited Makefile and project settings before applying this window.")
|
|
}
|
|
let validated = try configuration.validated()
|
|
let originalMakefile = try project.readText(relativePath: project.configuration.makefile)
|
|
guard CMOCProject.sha256(Data(originalMakefile.utf8)) == expectedMakefileHash else { throw CMOCBuildError.message("The Makefile changed while Project Settings was open. Reopen settings to review it.") }
|
|
let configURL = try project.fileURL(relativePath: configPath)
|
|
let oldConfig = try? Data(contentsOf: configURL)
|
|
guard oldConfig.map(CMOCProject.sha256) == expectedConfigHash else { throw CMOCBuildError.message("Project settings changed outside this window. Reopen settings to review them.") }
|
|
let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
|
let configData = try encoder.encode(validated)
|
|
// Keep the Makefile's previous version recoverable when regenerating.
|
|
if let makefile, makefile != originalMakefile {
|
|
let backups = project.directory.appendingPathComponent(".vccplus-build/Makefile Backups")
|
|
try FileManager.default.createDirectory(at: backups, withIntermediateDirectories: true)
|
|
try Data(originalMakefile.utf8).write(to: backups.appendingPathComponent(UUID().uuidString + ".make"), options: .atomic)
|
|
_ = try project.saveText(makefile, relativePath: project.configuration.makefile, replacingSHA256: expectedMakefileHash)
|
|
}
|
|
do { try configData.write(to: configURL, options: .atomic) }
|
|
catch {
|
|
if makefile != nil { try? Data(originalMakefile.utf8).write(to: project.makefileURL, options: .atomic) }
|
|
throw error
|
|
}
|
|
self.project = CMOCProject(directory: project.directory, configuration: validated)
|
|
for path in [configPath, project.configuration.makefile] {
|
|
if let i = documents.firstIndex(where: { $0.id == path }), let value = try? self.project?.readText(relativePath: path) {
|
|
documents[i] = .init(id: path, text: value, savedText: value, savedHash: CMOCProject.sha256(Data(value.utf8)))
|
|
if selectedFile == path { selecting = true; source = value; selecting = false }
|
|
}
|
|
}
|
|
files = try self.project!.fileEntries(); externalBuildChange = true
|
|
if !validated.configurations.contains(where: { $0.name == configurationName }) { configurationName = validated.configurations.first!.name }
|
|
refreshProjectIndex()
|
|
message = nil; log = makefile == nil ? "Project settings saved. The custom Makefile was kept." : "Project settings and Makefile saved. The previous Makefile is retained in .vccplus-build/Makefile Backups."
|
|
}
|
|
func build() { build(.build) }
|
|
func build(_ action: CMOCBuildAction, target: String? = nil) {
|
|
guard let project, !building, !commanding, !historyRemoving else { return }
|
|
pausedDebugSnapshot = nil; capturedCallStack = nil; selectedFrameIndex = 0; sourceStepping = false
|
|
defaults.set("In progress", forKey: buildAttemptKey(project.directory))
|
|
building = true; message = nil; currentLine = nil; currentFile = nil; latestBuildAttempt = "Building \(configurationName)…"; persistDrafts()
|
|
revision = UUID()
|
|
variableStatus = "Building C debug information…"
|
|
log = "Building a project snapshot…"; diagnostics = []
|
|
let inputs = overlays; let configuration = configurationName
|
|
task = Task {
|
|
defer {
|
|
defaults.set(latestBuildAttempt, forKey: buildAttemptKey(project.directory))
|
|
building = false; task = nil; checkExternalFiles(); refreshBuildHistory(); refreshProjectIndex()
|
|
}
|
|
do {
|
|
let built = try await service.build(project: project, overlays: inputs, action: action, configuration: configuration, target: target)
|
|
try Task.checkCancellation()
|
|
log = built.buildLog
|
|
latestBuildAttempt = "\(action == .clean ? "Clean" : "Build") succeeded"
|
|
guard built.hasBinary || built.hasDisk else {
|
|
execution = "Build action finished; the last runnable build and machine are unchanged"
|
|
return
|
|
}
|
|
var nextMapping: CMOCProjectSourceMap?
|
|
var nextVariables: CMOCVariableDebug?
|
|
diagnostics = Self.parseDiagnostics(built.buildLog, directory: built.compilationDirectory)
|
|
variableStatus = "This build has no verified C variable information."
|
|
if built.hasBinary {
|
|
do {
|
|
let verified = try await Task.detached(priority: .userInitiated) { try CMOCProjectSourceMap.parse(artifact: built) }.value
|
|
try Task.checkCancellation()
|
|
nextMapping = verified
|
|
log += "\nVerified source locations in \(verified.sourcePaths.count) C file(s)."
|
|
do {
|
|
nextVariables = try await Task.detached(priority: .userInitiated) {
|
|
try CMOCVariableDebug.parse(artifact: built, verifiedMap: verified)
|
|
}.value
|
|
try Task.checkCancellation()
|
|
variableStatus = "Compiler types and locations verified."
|
|
} catch is CancellationError { throw CancellationError() }
|
|
catch { variableStatus = error.localizedDescription }
|
|
|
|
} catch is CancellationError { throw CancellationError() }
|
|
catch { log += "\nBuild succeeded. Source debugging unavailable: \(error.localizedDescription)" }
|
|
}
|
|
try Task.checkCancellation()
|
|
artifact = built; projectMapping = nextMapping; mapping = nextMapping?.map(forFile: selectedFile); variableMetadata = nextVariables
|
|
pausedDebugSnapshot = nil; capturedCallStack = nil
|
|
if let data = try? Data(contentsOf: built.fileURL(CMOCProject.configurationFilename)),
|
|
let config = try? JSONDecoder().decode(CMOCProjectConfiguration.self, from: data).validated() {
|
|
self.project = CMOCProject(directory: project.directory, configuration: config)
|
|
}
|
|
for i in documents.indices where documents[i].generated {
|
|
if let data = built.sources[documents[i].id], let text = String(data: data, encoding: .utf8) {
|
|
documents[i].text = text; documents[i].savedText = text; documents[i].savedHash = CMOCProject.sha256(data)
|
|
if selectedFile == documents[i].id { selecting = true; source = text; selecting = false }
|
|
}
|
|
}
|
|
if !executableLines.contains(breakpointLine) { breakpointLine = executableLines.first ?? 1 }
|
|
execution = "Build finished; the machine has not been changed"
|
|
} catch is CancellationError { latestBuildAttempt = "Build cancelled"; variableStatus = "Build cancelled; the last successful result is retained."; log = "Build cancelled. The last successful result and machine are unchanged." }
|
|
catch {
|
|
message = error.localizedDescription; log = error.localizedDescription
|
|
latestBuildAttempt = "Build failed"; variableStatus = "Build failed; the last successful result is retained."
|
|
diagnostics = Self.parseDiagnostics(log, directory: nil)
|
|
}
|
|
}
|
|
}
|
|
func cancelBuild() { task?.cancel(); service.cancel() }
|
|
static func parseDiagnostics(_ text: String, directory: URL?) -> [CMOCBuildDiagnostic] {
|
|
guard let regex = try? NSRegularExpression(pattern: #"^(.+?):([0-9]+)(?::[0-9]+)?:\s*(.+)$"#) else { return [] }
|
|
return text.components(separatedBy: .newlines).compactMap { line in
|
|
let ns = line as NSString
|
|
guard let m = regex.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)), let number = Int(ns.substring(with: m.range(at: 2))), number > 0 else { return nil }
|
|
var file = ns.substring(with: m.range(at: 1))
|
|
if let directory, file.hasPrefix(directory.path + "/") { file = String(file.dropFirst(directory.path.count + 1)) }
|
|
if file.hasPrefix("./") { file = String(file.dropFirst(2)) }
|
|
return .init(file: file, line: number, message: ns.substring(with: m.range(at: 3)))
|
|
}
|
|
}
|
|
func toggleBreakpoint(_ line: Int) {
|
|
guard !commanding, !building else { return }
|
|
guard machine.pasteRemaining == 0 else { message = "Wait for the launch commands to finish before changing source breakpoints."; return }
|
|
let point = CMOCSourceBreakpoint(file: selectedFile, line: line)
|
|
if breakpoints.contains(point) { breakpoints.remove(point) }
|
|
else { breakpoints.insert(point); breakpointLine = line }
|
|
updateLiveBreakpoints()
|
|
}
|
|
private func updateLiveBreakpoints() {
|
|
guard loadedMatchesEditor, let artifact, let projectMapping, canCommand else { return }
|
|
let points = sourceBreakpointAddresses(includeFallback: false)
|
|
let wasRunning = machine.state == .running
|
|
let wasSourceStepping = sourceStepping
|
|
let wasAwaitingDiskLoad = awaitingDiskLoad
|
|
let expectedGeneration = loadedGeneration, expectedRevision = loadedRevision, expectedMapping = loadedMapping
|
|
// Discard an older poll already in flight while this command changes the
|
|
// breakpoint set. A source edit is still caught by loadedMatchesEditor.
|
|
revision = UUID(); let request = revision
|
|
commanding = true
|
|
let unchanged: (VCCMachineSnapshot) -> Bool = { snapshot in
|
|
snapshot.generation == expectedGeneration && snapshot.debuggerProgramRevision == expectedRevision &&
|
|
(projectMapping.bankedLayout != nil || wasAwaitingDiskLoad || snapshot.debuggerMappingFingerprint == expectedMapping)
|
|
}
|
|
let invalidate: (String) -> Void = { [weak self] text in
|
|
guard let self else { return }
|
|
loadedBuild = nil; loadedGeneration = nil; awaitingDiskLoad = false
|
|
currentLine = nil; currentFile = nil; pc = nil; execution = text
|
|
// Never leave this feature's old addresses armed in a changed MMU
|
|
// layout, and never resume a machine that changed during the command.
|
|
machine.clearDevelopmentBreakpoints { [weak self] in self?.commanding = false }
|
|
}
|
|
let finish = { [weak self] in
|
|
guard let self else { return }
|
|
if wasRunning && !wasSourceStepping { machine.debuggerContinue { [weak self] in self?.commanding = false; self?.refresh() } }
|
|
else { commanding = false; refresh() }
|
|
}
|
|
machine.debuggerPause { [weak self] in
|
|
guard let self else { return }
|
|
machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { [weak self] detail in
|
|
guard let self else { return }
|
|
guard revision == request, loadedMatchesEditor, let detail, unchanged(detail.machine), detail.machine.errorMessage == nil else {
|
|
invalidate("Machine or project changed; run the build again before updating source breakpoints"); return
|
|
}
|
|
if points.isEmpty, projectMapping.bankedLayout != nil {
|
|
// Removing the last stop does not discard verified bank
|
|
// evidence needed by Pause, source steps and watches.
|
|
machine.armDevelopmentBreakpoints([], sourceMap: projectMapping, pointModules: [:]) { [weak self] snapshot in
|
|
guard let self else { return }
|
|
guard revision == request, loadedMatchesEditor, let snapshot, snapshot.errorMessage == nil, unchanged(snapshot) else {
|
|
invalidate(snapshot?.errorMessage ?? "Machine changed while updating source breakpoints"); return
|
|
}
|
|
attach(artifact, snapshot: snapshot); awaitingDiskLoad = wasAwaitingDiskLoad
|
|
finish()
|
|
}
|
|
} else if points.isEmpty {
|
|
machine.clearDevelopmentBreakpoints { [weak self] in
|
|
guard let self else { return }
|
|
if wasAwaitingDiskLoad {
|
|
loadedBuild = nil; loadedGeneration = nil; currentLine = nil; currentFile = nil; pc = nil
|
|
execution = "Source breakpoints cleared before the disk program was verified"
|
|
}
|
|
awaitingDiskLoad = false; finish()
|
|
}
|
|
} else {
|
|
machine.armDevelopmentBreakpoints(points, sourceMap: projectMapping, pointModules: sourceBreakpointModules(includeFallback: false)) { [weak self] snapshot in
|
|
guard let self else { return }
|
|
guard revision == request, loadedMatchesEditor, let snapshot, snapshot.errorMessage == nil, unchanged(snapshot) else {
|
|
invalidate(snapshot?.errorMessage ?? "Machine changed while updating source breakpoints; run the build again"); return
|
|
}
|
|
// Rearming doesn't replace code. Retain a previously
|
|
// verified paused source connection so instruction steps
|
|
// keep updating even before another breakpoint is hit.
|
|
// An unverified disk launch, however, must keep waiting.
|
|
attach(artifact, snapshot: snapshot)
|
|
awaitingDiskLoad = wasAwaitingDiskLoad
|
|
finish()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
/// Every compiled instance of a C line owns its own module-qualified stop.
|
|
/// Ordinary flat programs retain their first mapped address per line.
|
|
private func sourceBreakpointSelection(includeFallback: Bool) -> [(UInt16, String?)] {
|
|
guard let projectMapping else { return [] }
|
|
func selection(_ point: CMOCSourceBreakpoint) -> [(UInt16, String?)] {
|
|
let code = projectMapping.instructions.filter { $0.sourcePath == point.file && $0.sourceLine == point.line }
|
|
if projectMapping.bankedLayout == nil { return code.first.map { [($0.address, nil)] } ?? [] }
|
|
return Dictionary(grouping: code, by: { $0.moduleID ?? "" }).values.compactMap { group in
|
|
group.min(by: { $0.address < $1.address }).map { ($0.address, $0.moduleID) }
|
|
}
|
|
}
|
|
let configured = breakpoints.flatMap(selection)
|
|
if configured.isEmpty && includeFallback {
|
|
return selection(CMOCSourceBreakpoint(file: selectedFile, line: breakpointLine))
|
|
}
|
|
return configured
|
|
}
|
|
private func sourceBreakpointAddresses(includeFallback: Bool) -> [UInt16] {
|
|
Array(Set(sourceBreakpointSelection(includeFallback: includeFallback).map { $0.0 })).sorted()
|
|
}
|
|
private func sourceBreakpointModules(includeFallback: Bool) -> [UInt16: Set<String>] {
|
|
var result: [UInt16: Set<String>] = [:]
|
|
for (address, module) in sourceBreakpointSelection(includeFallback: includeFallback) {
|
|
if let module { result[address, default: []].insert(module) }
|
|
}
|
|
return result
|
|
}
|
|
/// Normal launches use only breakpoints the user explicitly added.
|
|
var resolvedBreakpointAddresses: [UInt16] { buildMatchesEditor ? sourceBreakpointAddresses(includeFallback: false) : [] }
|
|
/// The selected-line fallback belongs only to the explicit Run to Breakpoint action.
|
|
var runToBreakpointAddresses: [UInt16] { buildMatchesEditor ? sourceBreakpointAddresses(includeFallback: true) : [] }
|
|
func confirmRun() {
|
|
guard canRun else { return }
|
|
if projectMapping?.bankedLayout != nil { confirmDiskLaunch(toBreakpoint: true); return }
|
|
let alert = NSAlert(); alert.messageText = "Run C program in this CoCo?"
|
|
alert.informativeText = "This replaces program memory without restarting or changing mounted media, then runs to a verified source breakpoint. Use a booted Disk BASIC machine. Save any BASIC program you want to keep first."
|
|
alert.addButton(withTitle: "Run to Breakpoint"); alert.addButton(withTitle: "Cancel")
|
|
if alert.runModal() == .alertFirstButtonReturn { run() }
|
|
}
|
|
func run() {
|
|
checkExternalFiles()
|
|
guard canRun, let artifact else { return }
|
|
if projectMapping?.bankedLayout != nil { launchDisk(commands: project?.configuration.launchCommands ?? [], toBreakpoint: true); return }
|
|
let addresses = runToBreakpointAddresses
|
|
guard !addresses.isEmpty else { return }
|
|
commanding = true; message = nil; currentLine = nil; revision = UUID()
|
|
machine.prepareToQuit { [weak self] in
|
|
guard let self else { return }
|
|
guard !machine.unsavedMedia else { commanding = false; message = "Save or export pending media before running. The machine is paused."; return }
|
|
guard buildMatchesEditor, self.artifact?.id == artifact.id else { commanding = false; message = "Project changed. Build again before running."; return }
|
|
machine.debuggerLoadDevelopmentBinary(artifact.binaryData, breakpoints: addresses) { [weak self] snapshot in
|
|
guard let self else { return }; commanding = false
|
|
guard let snapshot else { message = "The machine became unavailable."; return }
|
|
if let error = snapshot.errorMessage { message = error; return }
|
|
attach(artifact, snapshot: snapshot); execution = "Running to source breakpoint"; refresh()
|
|
}
|
|
}
|
|
}
|
|
private func attach(_ artifact: CMOCBuildArtifact, snapshot: VCCMachineSnapshot) {
|
|
trackLaunch(artifact, snapshot: snapshot)
|
|
loadedBuild = artifact.id; loadedGeneration = snapshot.generation
|
|
loadedRevision = snapshot.debuggerProgramRevision; loadedMapping = snapshot.debuggerMappingFingerprint
|
|
}
|
|
func launch() {
|
|
checkExternalFiles()
|
|
guard canLaunch, let project, let artifact else { return }
|
|
if project.configuration.launchMode == .disk || (!artifact.hasBinary && artifact.hasDisk) { confirmDiskLaunch(); return }
|
|
if !resolvedBreakpointAddresses.isEmpty {
|
|
guard canRun else { message = "Banked source debugging needs a declared disk image. Clear source breakpoints to run this binary without source debugging."; return }
|
|
confirmRun(); return
|
|
}
|
|
let alert = NSAlert(); alert.messageText = "Load and run the built program?"
|
|
alert.informativeText = "This replaces CoCo program memory and runs without a source breakpoint. Mounted media and machine settings are kept."
|
|
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Run")
|
|
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
|
launchQuickload()
|
|
}
|
|
/// Confirmation-free execution shared with regression tests; the UI confirms first.
|
|
func launchQuickload() {
|
|
checkExternalFiles()
|
|
guard canLaunch, let artifact, artifact.hasBinary else { return }
|
|
commanding = true; revision = UUID()
|
|
machine.prepareToQuit { [weak self] in
|
|
guard let self else { return }
|
|
guard !machine.unsavedMedia, buildMatchesEditor, self.artifact?.id == artifact.id else { commanding = false; message = "Save pending media and rebuild changed sources before running."; return }
|
|
machine.runDevelopmentBinary(artifact.binaryData) { [weak self] snapshot in
|
|
guard let self else { return }
|
|
commanding = false
|
|
guard let snapshot, snapshot.errorMessage == nil else { message = snapshot?.errorMessage ?? "Program launch failed."; return }
|
|
loadedBuild = nil; loadedGeneration = nil; awaitingDiskLoad = false
|
|
pausedDebugSnapshot = nil; currentLine = nil; currentFile = nil; pc = nil
|
|
trackLaunch(artifact, snapshot: snapshot)
|
|
execution = "Program running without source breakpoints"
|
|
}
|
|
}
|
|
}
|
|
func confirmDiskLaunch(toBreakpoint: Bool = false) {
|
|
guard canLaunch, let artifact, artifact.hasDisk, let project else { message = "Build a disk target first."; return }
|
|
guard machine.diskEnabled else { message = "Select a machine profile with its floppy controller enabled before launching this disk."; return }
|
|
let commands = project.configuration.launchCommands
|
|
let alert = NSAlert(); alert.messageText = "Mount the development disk in FD0?"
|
|
alert.informativeText = "This replaces the current FD0 assignment with a separate working copy of the build disk. Pending media must be saved first. Machine settings are kept.\n\n" + (commands.isEmpty ? "No commands will be typed. Load or boot the program yourself." : "At the BASIC prompt, these commands will be typed:\n" + commands.joined(separator: "\n"))
|
|
alert.addButton(withTitle: "Mount and Launch"); alert.addButton(withTitle: "Cancel")
|
|
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
|
launchDisk(commands: commands, toBreakpoint: toBreakpoint)
|
|
}
|
|
func launchDisk(commands: [String], toBreakpoint: Bool = false) {
|
|
checkExternalFiles()
|
|
guard let artifact, let diskPath = artifact.diskRelativePath, canLaunch else { return }
|
|
commanding = true; message = nil; revision = UUID()
|
|
machine.prepareToQuit { [weak self] in
|
|
guard let self else { return }
|
|
guard !machine.unsavedMedia, buildMatchesEditor, self.artifact?.id == artifact.id else { commanding = false; message = "Save pending media and rebuild changed sources before mounting the development disk."; return }
|
|
do {
|
|
let copyFolder = machine.developmentRunDirectory.appendingPathComponent("Run-\(UUID().uuidString)")
|
|
try FileManager.default.createDirectory(at: copyFolder, withIntermediateDirectories: true)
|
|
let copy = copyFolder.appendingPathComponent(URL(fileURLWithPath: diskPath).lastPathComponent)
|
|
try FileManager.default.copyItem(at: artifact.fileURL(diskPath), to: copy)
|
|
machine.mountDevelopmentDisk(copy) { [weak self] snapshot in
|
|
guard let self else { return }
|
|
guard let snapshot, snapshot.errorMessage == nil else { commanding = false; message = snapshot?.errorMessage ?? "Disk mounting failed."; return }
|
|
trackLaunch(artifact, snapshot: snapshot)
|
|
armDiskAndResume(artifact: artifact, commands: commands, toBreakpoint: toBreakpoint)
|
|
}
|
|
} catch { commanding = false; message = error.localizedDescription }
|
|
}
|
|
}
|
|
private func armDiskAndResume(artifact: CMOCBuildArtifact, commands: [String], toBreakpoint: Bool = false) {
|
|
let addresses = toBreakpoint ? runToBreakpointAddresses : resolvedBreakpointAddresses
|
|
let finish = { [weak self] in
|
|
guard let self else { return }
|
|
machine.debuggerContinue { [weak self] in
|
|
guard let self else { return }; commanding = false
|
|
do { if !commands.isEmpty { machine.startPaste(try CocoPaste(commands.joined(separator: "\n") + "\n", mode: .text)) } }
|
|
catch { message = error.localizedDescription }
|
|
}
|
|
}
|
|
guard let projectMapping, !addresses.isEmpty else {
|
|
// A prior debugging run may still own temporary source breakpoints.
|
|
// Clear only that set before booting; retain the assembly debugger's breakpoints.
|
|
loadedBuild = nil; loadedGeneration = nil; awaitingDiskLoad = false
|
|
pausedDebugSnapshot = nil; currentLine = nil; currentFile = nil; pc = nil
|
|
execution = "Development disk mounted; running without source breakpoints"
|
|
machine.clearDevelopmentBreakpoints(completion: finish)
|
|
return
|
|
}
|
|
machine.armDevelopmentBreakpoints(addresses, sourceMap: projectMapping, pointModules: sourceBreakpointModules(includeFallback: toBreakpoint)) { [weak self] snapshot in
|
|
guard let self else { return }
|
|
guard let snapshot, snapshot.errorMessage == nil else { commanding = false; message = snapshot?.errorMessage ?? "Cannot arm disk breakpoints."; return }
|
|
attach(artifact, snapshot: snapshot); awaitingDiskLoad = true
|
|
execution = "Waiting for the disk loader to reach verified program code"; finish()
|
|
}
|
|
}
|
|
func revealBuild() { if let artifact { NSWorkspace.shared.open(artifact.directory) } }
|
|
func toggleExecution() {
|
|
guard canCommand else { return }; commanding = true
|
|
pausedDebugSnapshot = nil; revision = UUID()
|
|
let complete = { [weak self] in self?.commanding = false; self?.refresh() }
|
|
if machine.state == .running { machine.debuggerPause(completion: complete) }
|
|
else { machine.debuggerContinue(completion: complete) }
|
|
}
|
|
func stepInstruction() {
|
|
guard canCommand, machine.state == .paused else { return }; commanding = true
|
|
pausedDebugSnapshot = nil; revision = UUID()
|
|
machine.debuggerStep { [weak self] in self?.commanding = false; self?.refresh() }
|
|
}
|
|
func stepSource(_ mode: CMOCSourceStepMode) {
|
|
checkExternalFiles()
|
|
guard canStepC, let projectMapping, let snapshot = pausedDebugSnapshot else { return }
|
|
var identities: [String: UInt32] = [:]
|
|
let instructions = projectMapping.instructions
|
|
let locations = instructions.map { instruction -> NSNumber in
|
|
let key = "\(instruction.moduleID ?? ""):\(instruction.sourcePath):\(instruction.sourceLine)"
|
|
if identities[key] == nil { identities[key] = UInt32(identities.count + 1) }
|
|
return NSNumber(value: identities[key]!)
|
|
}
|
|
commanding = true; sourceStepping = true; message = nil; revision = UUID()
|
|
pausedDebugSnapshot = nil; currentLine = nil; currentFile = nil
|
|
machine.debuggerStepSource(mode: mode.rawValue, addresses: instructions.map { NSNumber(value: $0.address) },
|
|
locations: locations, bytes: instructions.map { Data($0.bytes) }, expected: snapshot.machine,
|
|
moduleIdentifiers: projectMapping.bankedLayout == nil ? nil : instructions.map { $0.moduleID ?? "" }) { [weak self] in
|
|
guard let self else { return }
|
|
commanding = false
|
|
if let error = machine.fileError { message = error }
|
|
refresh()
|
|
}
|
|
}
|
|
func checkExternalFiles() {
|
|
guard !building, let project else { return }
|
|
do {
|
|
let entries = try project.fileEntries()
|
|
if entries.map(\.relativePath) != files.map(\.relativePath) { files = entries }
|
|
for index in documents.indices where !documents[index].generated && !documents[index].reference {
|
|
guard let disk = try? project.readText(relativePath: documents[index].id) else {
|
|
documents[index].missing = true; externalBuildChange = true
|
|
message = "\(documents[index].id) is missing or unreadable. Its editor contents are kept; use Save Selected Copy to recover them."
|
|
scheduleDraftSave(); continue
|
|
}
|
|
documents[index].missing = false
|
|
let hash = CMOCProject.sha256(Data(disk.utf8))
|
|
guard hash != documents[index].savedHash else { continue }
|
|
if documents[index].dirty || documents[index].conflict {
|
|
if !documents[index].conflict { documents[index].conflict = true; message = "\(documents[index].id) changed outside VCC Plus. Your edits are kept; use Reload File to accept the disk version." }
|
|
} else {
|
|
documents[index].text = disk; documents[index].savedText = disk; documents[index].savedHash = hash
|
|
if selectedFile == documents[index].id { selecting = true; source = disk; selecting = false }
|
|
}
|
|
}
|
|
if let artifact {
|
|
let hashes = try project.currentFileHashes(overlays: overlays)
|
|
let changed = hashes != artifact.fileHashes
|
|
if externalBuildChange != changed { externalBuildChange = changed }
|
|
}
|
|
} catch { if message != error.localizedDescription { message = error.localizedDescription }; externalBuildChange = true }
|
|
}
|
|
private func scheduleExternalCheck() {
|
|
guard !building, !checkingFiles, let project else { return }
|
|
checkingFiles = true
|
|
let saved = Dictionary(uniqueKeysWithValues: documents.map { ($0.id, $0.savedHash) })
|
|
let request = revision
|
|
Task {
|
|
defer { checkingFiles = false }
|
|
do {
|
|
let filesOnDisk = try await Task.detached(priority: .utility) { try project.inputFiles() }.value
|
|
let hashes = await Task.detached(priority: .utility) { filesOnDisk.mapValues(CMOCProject.sha256) }.value
|
|
let supportHashes = try await Task.detached(priority: .utility) {
|
|
var captured = project
|
|
if let bytes = filesOnDisk[CMOCProject.configurationFilename] {
|
|
captured.configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: bytes).validated()
|
|
}
|
|
return try captured.supportFileHashes()
|
|
}.value
|
|
guard !building, revision == request, self.project?.directory == project.directory,
|
|
saved == Dictionary(uniqueKeysWithValues: documents.map { ($0.id, $0.savedHash) }) else { return }
|
|
let entries = filesOnDisk.keys.sorted().map { CMOCProjectFile(relativePath: $0, isEditable: CMOCProject.isEditable($0)) }
|
|
if entries != files { files = entries }
|
|
for index in documents.indices where !documents[index].generated && !documents[index].reference {
|
|
guard let bytes = filesOnDisk[documents[index].id], let disk = String(data: bytes, encoding: .utf8), let hash = hashes[documents[index].id] else {
|
|
if !documents[index].missing {
|
|
documents[index].missing = true
|
|
message = "\(documents[index].id) is missing or unreadable. Its editor contents are kept; use Save Selected Copy to recover them."
|
|
scheduleDraftSave()
|
|
}
|
|
continue
|
|
}
|
|
documents[index].missing = false
|
|
guard hash != documents[index].savedHash else { continue }
|
|
if documents[index].dirty || documents[index].conflict {
|
|
if !documents[index].conflict {
|
|
documents[index].conflict = true
|
|
message = "\(documents[index].id) changed outside VCC Plus. Your edits are kept; reload the file to accept the disk version."
|
|
}
|
|
} else {
|
|
documents[index].text = disk; documents[index].savedText = disk; documents[index].savedHash = hash
|
|
if selectedFile == documents[index].id { selecting = true; source = disk; selecting = false }
|
|
}
|
|
}
|
|
let textHashes = hashes.filter { CMOCProject.isEditable($0.key) }
|
|
if textHashes != navigationDiskHashes {
|
|
navigationDiskHashes = textHashes; scheduleProjectIndex()
|
|
}
|
|
if let artifact {
|
|
var current = hashes.merging(supportHashes) { first, _ in first }
|
|
for (path, text) in overlays { current[path] = CMOCProject.sha256(Data(text.utf8)) }
|
|
let changed = current != artifact.fileHashes
|
|
if changed != externalBuildChange { externalBuildChange = changed }
|
|
}
|
|
} catch {
|
|
guard self.project?.directory == project.directory else { return }
|
|
if message != error.localizedDescription { message = error.localizedDescription }
|
|
externalBuildChange = true
|
|
}
|
|
}
|
|
}
|
|
static func physicalPages(_ snapshot: VCCDebuggerSnapshot) -> [Int: Int] {
|
|
Dictionary(uniqueKeysWithValues: snapshot.mmu.effective.enumerated().filter { $0.element.source == 0 }.map {
|
|
($0.offset, Int($0.element.sourceAddress) / 8192)
|
|
})
|
|
}
|
|
func refresh() {
|
|
if Date() >= nextFileCheck { nextFileCheck = Date().addingTimeInterval(3); scheduleExternalCheck() }
|
|
guard (loadedBuild != nil || launchedBuildID != nil), !building, !reading, !commanding else { return }
|
|
reading = true; let request = revision; let epoch = machine.inputEpoch
|
|
machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { [weak self] snapshot in
|
|
guard let self else { return }; reading = false
|
|
guard revision == request, machine.inputEpoch == epoch, let snapshot else { return }
|
|
if launchedGeneration != snapshot.machine.generation || launchedRevision != snapshot.machine.debuggerProgramRevision {
|
|
launchedBuildID = nil; launchedGeneration = nil; launchedRevision = nil
|
|
}
|
|
guard loadedBuild != nil else { return }
|
|
let previousSnapshot = pausedDebugSnapshot
|
|
let previousEpoch = pausedInputEpoch
|
|
pausedDebugSnapshot = nil
|
|
sourceStepping = snapshot.machine.debuggerSourceStepping
|
|
if loadedGeneration != snapshot.machine.generation || loadedRevision != snapshot.machine.debuggerProgramRevision || (!awaitingDiskLoad && projectMapping?.bankedLayout == nil && loadedMapping != snapshot.machine.debuggerMappingFingerprint) {
|
|
loadedBuild = nil; loadedGeneration = nil; currentLine = nil; currentFile = nil; pc = nil
|
|
execution = "Machine changed; run the build again to reconnect source locations"; return
|
|
}
|
|
guard loadedMatchesEditor else { publishStop(nil, file: nil, line: nil, text: "Project changed; build again before using source locations"); return }
|
|
if awaitingDiskLoad {
|
|
guard snapshot.machine.debuggerDevelopmentAttached else { return }
|
|
awaitingDiskLoad = false; loadedMapping = snapshot.machine.debuggerMappingFingerprint
|
|
}
|
|
if snapshot.machine.state == .running { publishStop(nil, file: nil, line: nil, text: sourceStepping ? "Stepping through C — Pause to stop" : "Running"); return }
|
|
let address = snapshot.machine.programCounter
|
|
let activeMap = projectMapping?.projected(physicalPages: Self.physicalPages(snapshot), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable)
|
|
guard let instruction = activeMap?.instruction(at: address), let live = snapshot.instructions.first,
|
|
live.address == instruction.address, Array(live.bytes) == instruction.bytes else {
|
|
publishStop(address, file: nil, line: nil, text: "Paused at \(String(format: "$%04X", address)) — no verified C line here; use Debugger for assembly"); return
|
|
}
|
|
// Variable locations are valid only while all mapped code still matches.
|
|
// Inspection reads the same immutable snapshot as PC and registers.
|
|
let memory = snapshot.logicalMemory, available = snapshot.logicalMemoryAvailable
|
|
let codeMatches = (projectMapping?.bankedLayout == nil || snapshot.machine.debuggerDevelopmentAttached) &&
|
|
activeMap?.verifiesRuntime(memory: memory, available: available) == true
|
|
if codeMatches {
|
|
pausedDebugSnapshot = snapshot; pausedInputEpoch = epoch
|
|
let sameStop = previousEpoch == epoch && previousSnapshot?.machine.programCounter == address &&
|
|
previousSnapshot?.machine.debuggerMappingFingerprint == snapshot.machine.debuggerMappingFingerprint &&
|
|
previousSnapshot?.machine.debuggerResidencyFingerprint == snapshot.machine.debuggerResidencyFingerprint &&
|
|
previousSnapshot?.registers["U"] == snapshot.registers["U"] &&
|
|
previousSnapshot?.registers["S"] == snapshot.registers["S"] &&
|
|
previousSnapshot?.logicalMemory == snapshot.logicalMemory &&
|
|
previousSnapshot?.logicalMemoryAvailable == snapshot.logicalMemoryAvailable
|
|
if !sameStop {
|
|
inspectionRevision = UUID()
|
|
selectedFrameIndex = 0
|
|
capturedCallStack = variableMetadata.flatMap { metadata in
|
|
guard let u = snapshot.registers["U"], let s = snapshot.registers["S"] else { return nil }
|
|
return CMOCCallStack.capture(metadata: metadata.projected(physicalPages: Self.physicalPages(snapshot), memory: snapshot.logicalMemory, available: snapshot.logicalMemoryAvailable), pc: address, u: u.uint16Value, s: s.uint16Value,
|
|
memory: memory, available: available)
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
publishStop(address, file: nil, line: nil, text: "Program bytes changed; run the build again before C debugging")
|
|
return
|
|
}
|
|
let changedLocation = currentFile != instruction.sourcePath || currentLine != instruction.sourceLine || pc != address
|
|
publishStop(address, file: instruction.sourcePath, line: instruction.sourceLine, text: "Paused at \(instruction.sourcePath):\(instruction.sourceLine) · \(String(format: "$%04X", address)) · \(snapshot.stopReason)")
|
|
if changedLocation { openFile(instruction.sourcePath, line: instruction.sourceLine) }
|
|
}
|
|
}
|
|
private func publishStop(_ address: UInt16?, file: String?, line: Int?, text: String) {
|
|
if pc != address { pc = address }; if currentFile != file { currentFile = file }
|
|
if currentLine != line { currentLine = line }; if execution != text { execution = text }
|
|
}
|
|
}
|