Files
VCCPlusOSS/platforms/macos/App/CMOCDevelopmentView.swift
T

1440 lines
99 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
import AppKit
struct CMOCDevelopmentView: View {
@ObservedObject var model: CMOCDevelopmentModel
@StateObject private var finder = SourceFind()
@ObservedObject private var menu: MachineMenuState
@Environment(\.openWindow) private var openWindow
@State private var showSettings = false
@State private var showHistory = false
@State private var showRecovery = false
@State private var selectedHintID = ""
@State private var outputTab = "Build Log"
@State private var expandedVariables: Set<CMOCWatchEvaluator.TreePath> = []
@State private var variableOffsets: [CMOCWatchEvaluator.TreePath: Int] = [:]
@State private var variableRootOffset = 0
@FocusState private var searchFocused: Bool
init(model: CMOCDevelopmentModel) { self.model = model; self.menu = model.machine.menuState }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
header.padding(16)
Divider()
toolbar.padding(.horizontal, 16).padding(.vertical, 10)
workspaceStatus
Divider()
if let message = model.message {
HStack(alignment: .top) {
Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange)
Text(message).textSelection(.enabled).lineLimit(4).accessibilityIdentifier("cmoc.error")
}.font(.callout).padding(10).frame(maxWidth: .infinity, alignment: .leading).background(.orange.opacity(0.08))
}
HSplitView {
navigator.frame(minWidth: 190, idealWidth: 240, maxWidth: 340)
VStack(spacing: 0) {
navigationBar
tabs
sourceAssistanceBar
if model.inspectingCaller {
HStack {
Label(model.inspectionFrameDescription ?? "Caller", systemImage: "square.stack.3d.up")
.lineLimit(2).accessibilityIdentifier("cmoc.frame.context")
Spacer(minLength: 4)
Button("Show Current Frame") { model.selectFrame(0) }
.accessibilityIdentifier("cmoc.frame.current")
}.font(.caption).padding(8).background(Color.accentColor.opacity(0.08))
}
SourceFindBar(finder: finder, source: model.source, readOnly: model.selectedFileIsGenerated)
VSplitView {
CSourceEditor(finder: finder, text: $model.source,
currentLine: model.loadedMatchesEditor && model.currentFile == model.selectedFile ? model.currentLine : nil,
file: model.selectedFile, readOnly: model.selectedFileIsGenerated, breakpoints: model.selectedBreakpoints,
breakpointControlsEnabled: model.project != nil && !model.building && !model.commanding && !menu.values.pasting,
navigationLine: model.navigationLine, navigationColumn: model.navigationColumn,
navigationLength: model.navigationLength, navigationRequest: model.navigationRequest,
toggleBreakpoint: model.toggleBreakpoint, cursorChanged: model.updateCursor,
goToDefinition: model.goToDefinition,
completionIndex: model.projectIndex, completionRequest: model.completionRequest,
completionStatus: model.reportCompletion, parameterHints: model.refreshParameterHints,
clearParameterHints: model.clearParameterHints,
editorAction: model.editorAction, editorActionRequest: model.editorActionRequest, attach: { path, editor, pool in
model.assistantEditorFile = path; model.assistantEditor = editor; model.assistantEditorPool = pool
})
.id(model.project?.directory.path ?? "empty")
.frame(minHeight: showsVariableInspector ? 120 : 160).accessibilityIdentifier("cmoc.editor")
output.frame(minHeight: showsVariableInspector ? 220 : 90,
idealHeight: showsVariableInspector ? 280 : 180, maxHeight: 310)
}
}.frame(minWidth: 565)
}
Divider()
debugBar.padding(.horizontal, 14).padding(.vertical, 9)
HStack {
Image(systemName: model.currentLine == nil ? "info.circle" : "stop.circle.fill")
Text(model.execution).lineLimit(2).textSelection(.enabled).accessibilityIdentifier("cmoc.execution")
Spacer(minLength: 0)
if model.artifact != nil && !model.buildMatchesEditor {
Label("Build out of date", systemImage: "exclamationmark.triangle").foregroundStyle(.orange)
}
}.font(.caption).padding(.horizontal, 14).padding(.bottom, 10)
}.frame(minWidth: 900, minHeight: 650)
.focusedSceneValue(\.sourceFind, finder)
.focusedSceneValue(\.projectSearch, { model.navigationPane = "Search"; searchFocused = true })
.onChange(of: model.variableInspectionIdentity) { _, _ in
expandedVariables.removeAll(); variableOffsets.removeAll(); variableRootOffset = 0
}
.onChange(of: outputTab) { _, _ in variableRootOffset = 0 }
.onChange(of: model.navigationPane) { _, pane in
if pane == "Search" { searchFocused = true }
}
.sheet(isPresented: $showSettings) { CMOCProjectSettingsView(model: model) }
.sheet(isPresented: $showHistory) { CMOCBuildHistoryView(model: model) }
.sheet(isPresented: $showRecovery) { CMOCRecoveryView(model: model) }
.onDisappear { model.persistDrafts(); MCPCMOC.shared.closing(model) }
.task {
model.restoreWorkspace()
while !Task.isCancelled {
model.refresh()
try? await Task.sleep(nanoseconds: 200_000_000)
}
}
}
private var showsVariableInspector: Bool { outputTab == "Variables" || outputTab == "Watches" }
private var header: some View {
HStack(spacing: 12) {
Image(systemName: "curlybraces.square").font(.largeTitle).foregroundStyle(.tint)
VStack(alignment: .leading, spacing: 3) {
Text(model.project?.directory.lastPathComponent ?? "C Development").font(.title2.bold()).lineLimit(1).truncationMode(.middle)
Text("CMOC · Project workspace").foregroundStyle(.secondary).font(.callout)
}
Spacer(minLength: 8)
Button("Assistant…", systemImage: "link") { MCPCMOC.shared.showAccess(model) }.disabled(model.project == nil)
Button { showHistory = true } label: { Label("Build History", systemImage: "clock.arrow.circlepath") }
.accessibilityIdentifier("cmoc.history")
Button { showRecovery = true } label: { Label(model.recoveryRecords.isEmpty ? "Recovery" : "Recovery (\(model.recoveryRecords.count))", systemImage: "doc.badge.clock") }
.accessibilityIdentifier("cmoc.recovery")
.help("Review saved recovery copies of unsaved editor text")
Button { showSettings = true } label: { Label("Project Settings", systemImage: "slider.horizontal.3") }
.disabled(model.project == nil || model.building).accessibilityIdentifier("cmoc.settings")
Button { openWindow(id: "debugger") } label: { Label("Debugger", systemImage: "ladybug") }
}
}
private var workspaceStatus: some View {
HStack(alignment: .top, spacing: 12) {
statusItem("Source", text: model.sourceStatus, symbol: "doc.text", identifier: "source")
statusItem("Build", text: model.buildStatus, symbol: "hammer", identifier: "build", detail: model.artifact == nil ? nil : model.latestBuildAttempt)
statusItem("CoCo", text: model.programStatus, symbol: "desktopcomputer", identifier: "program")
}.padding(.horizontal, 16).padding(.bottom, 9)
}
private func statusItem(_ title: String, text: String, symbol: String, identifier: String, detail: String? = nil) -> some View {
VStack(alignment: .leading, spacing: 2) {
Label(title, systemImage: symbol).font(.caption.weight(.medium)).foregroundStyle(.secondary)
Text(text).font(.caption).lineLimit(2).fixedSize(horizontal: false, vertical: true)
if let detail { Text(detail).font(.caption).foregroundStyle(.secondary).lineLimit(1) }
}.frame(maxWidth: .infinity, alignment: .leading)
.help(text).accessibilityElement(children: .combine).accessibilityIdentifier("cmoc.status." + identifier)
}
private var toolbar: some View {
HStack(spacing: 8) {
Button { model.newProject() } label: { Label("New", systemImage: "doc.badge.plus") }
Button { model.openProject() } label: { Label("Open", systemImage: "folder") }
Button { model.save() } label: { Label("Save All", systemImage: "square.and.arrow.down") }
.disabled(model.project == nil || !model.unsaved).keyboardShortcut("s", modifiers: [.command])
Divider().frame(height: 22)
Picker("Configuration", selection: $model.configurationName) {
ForEach(model.project?.configuration.configurations ?? [], id: \.name) { Text($0.name).tag($0.name) }
}.labelsHidden().frame(width: 100).disabled(model.building).accessibilityLabel("Build configuration")
Button { model.build() } label: { Label("Build", systemImage: "hammer") }
.disabled(model.project == nil || model.building).accessibilityIdentifier("cmoc.build")
Menu {
Button("Rebuild", systemImage: "arrow.clockwise") { model.build(.rebuild) }
Button("Clean", systemImage: "trash") { model.build(.clean) }
Button("Build Disk", systemImage: "externaldrive") { model.build(.disk) }
.disabled(model.project?.configuration.diskTarget == nil)
Divider()
Button("Show Build Products", systemImage: "folder") { model.revealBuild() }.disabled(model.artifact == nil)
Button("Edit Makefile", systemImage: "doc.text") { if let project = model.project { model.openFile(project.configuration.makefile) } }
Button("Reload File from Disk", systemImage: "arrow.clockwise") { model.reloadSelected() }
Button("Save Selected Copy…", systemImage: "square.and.arrow.up") { model.saveSelectedCopy() }
.disabled(model.documents.isEmpty).accessibilityIdentifier("cmoc.saveCopy")
} label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 28)
.disabled(model.project == nil || model.building).help("Show build and file actions").accessibilityLabel("Build and file actions")
if model.building { ProgressView().controlSize(.small); Button { model.cancelBuild() } label: { Image(systemName: "xmark.circle.fill") }.help("Cancel Build").accessibilityLabel("Cancel Build") }
Spacer(minLength: 0)
Button { model.launch() } label: { Label(model.project?.configuration.launchMode == .disk ? "Launch Disk" : "Run", systemImage: "play.fill") }
.disabled(!model.canLaunch).accessibilityIdentifier("cmoc.launch")
}.controlSize(.regular).disabled(model.commanding)
}
private var navigator: some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 4) {
navigationMode("Files", symbol: "folder")
Button {
model.navigationPane = "Search"; searchFocused = true
} label: { Image(systemName: "magnifyingglass").frame(maxWidth: .infinity).contentShape(Rectangle()) }
.buttonStyle(.plain).padding(.vertical, 7)
.background(model.navigationPane == "Search" ? Color.accentColor.opacity(0.16) : .clear, in: RoundedRectangle(cornerRadius: 5))
.help("Find in Project (⇧⌘F)").accessibilityLabel("Find in Project").accessibilityIdentifier("cmoc.navigation.search")
navigationMode("Outline", symbol: "list.bullet.indent")
navigationMode("Definitions", symbol: "arrow.turn.down.right")
}.padding(.horizontal, 8).padding(.vertical, 5)
Divider()
switch model.navigationPane {
case "Search": projectSearch
case "Outline": symbolOutline
case "Definitions": definitionResults
default: projectFiles
}
}.background(.background)
}
private func navigationMode(_ title: String, symbol: String) -> some View {
let lowercasedTitle: String = title.lowercased()
let highlight: Color = model.navigationPane == title ? Color.accentColor.opacity(0.16) : Color.clear
let helpText: String = "Show " + lowercasedTitle + " in the project navigator"
let accessibilityTitle: String = title + " navigator"
let identifier: String = "cmoc.navigation." + lowercasedTitle
return Button { model.navigationPane = title } label: { Image(systemName: symbol).frame(maxWidth: .infinity).contentShape(Rectangle()) }
.buttonStyle(.plain).padding(.vertical, 7)
.background(highlight, in: RoundedRectangle(cornerRadius: 5))
.help(helpText).accessibilityLabel(accessibilityTitle)
.accessibilityIdentifier(identifier)
}
private var navigationBar: some View {
HStack(spacing: 8) {
SourceFindButton(finder: finder)
Button { model.navigateBack() } label: { Image(systemName: "chevron.left") }
.disabled(!model.canNavigateBack).keyboardShortcut("[", modifiers: .command)
.help("Back (⌘[)").accessibilityLabel("Back to Previous Location").accessibilityIdentifier("cmoc.navigation.back")
Button { model.navigateForward() } label: { Image(systemName: "chevron.right") }
.disabled(!model.canNavigateForward).keyboardShortcut("]", modifiers: .command)
.help("Forward (⌘])").accessibilityLabel("Forward to Next Location").accessibilityIdentifier("cmoc.navigation.forward")
Button { model.goToDefinition() } label: { Label("Go to Definition", systemImage: "arrow.turn.down.right") }
.disabled(model.project == nil).keyboardShortcut("j", modifiers: [.command, .control])
.help("Find definitions or declarations for the identifier at the insertion point (⌃⌘J). Ambiguous matches are listed for review.")
.accessibilityIdentifier("cmoc.navigation.definition")
Button { model.requestCompletion() } label: { Label("Complete", systemImage: "text.cursor") }
.disabled(model.project == nil || model.selectedFileIsGenerated || model.projectIndex == nil)
.help("Complete a C identifier (Control-Space). Inserts a name only; arrows select, Return accepts and Escape dismisses.")
.accessibilityIdentifier("cmoc.completion.request")
Menu {
ForEach(CMOCEditorAction.allCases, id: \.self) { action in
Button(action.rawValue) { model.requestEditorAction(action) }
.disabled(action != .match && model.selectedFileIsGenerated)
.accessibilityIdentifier("cmoc.edit." + action.rawValue)
}
} label: { Label("Edit", systemImage: "text.alignleft") }
.disabled(!["c", "h"].contains((model.selectedFile as NSString).pathExtension.lowercased()))
.help("Indent: Control-]; Outdent: Control-[; Comment: Command-/; Matching bracket: Control-M")
.accessibilityIdentifier("cmoc.edit.menu")
if model.selectedFileIsGenerated {
Image(systemName: "lock").foregroundStyle(.secondary)
.help("Read-only header or generated build source").accessibilityLabel("Read-only source")
}
Spacer(minLength: 4)
if model.indexing { ProgressView().controlSize(.mini).accessibilityLabel("Indexing project") }
Text(model.indexMessage).font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
.help(model.indexMessage).accessibilityIdentifier("cmoc.navigation.status")
if !model.indexNotes.isEmpty {
Menu {
ForEach(model.indexNotes, id: \.self) { Text($0) }
} label: { Image(systemName: "info.circle") }
.menuStyle(.borderlessButton).fixedSize()
.help("Show source navigation notes")
.accessibilityLabel("Source navigation notes")
.accessibilityIdentifier("cmoc.navigation.notes")
}
Button { model.refreshProjectIndex() } label: { Image(systemName: "arrow.clockwise") }
.disabled(model.project == nil || model.indexing).help("Refresh Project Index")
.accessibilityLabel("Refresh Project Index").accessibilityIdentifier("cmoc.navigation.refresh")
}.controlSize(.small).padding(.horizontal, 10).padding(.vertical, 6).background(.bar)
}
private var sourceAssistanceBar: some View {
HStack(alignment: .top, spacing: 8) {
Button { model.refreshParameterHints() } label: { Image(systemName: "function") }
.buttonStyle(.plain).help("Show parameter hints for the call at the insertion point (Control-Shift-Space)")
.accessibilityLabel("Show Parameter Hints").accessibilityIdentifier("cmoc.parameters.request")
if let hint = model.parameterHints.first(where: { $0.id == selectedHintID }) ?? model.parameterHints.first {
VStack(alignment: .leading, spacing: 3) {
Text(hint.signature).font(.system(.caption, design: .monospaced)).lineLimit(1).truncationMode(.middle)
.textSelection(.enabled).help(hint.signature + "\n" + hint.sourcePath)
.accessibilityIdentifier("cmoc.parameters.signature")
Text(parameterDescription(hint)).font(.caption.weight(.medium)).foregroundStyle(.tint)
.lineLimit(1).help(parameterDescription(hint)).accessibilityIdentifier("cmoc.parameters.active")
}
Spacer(minLength: 2)
if hint.conditional { Image(systemName: "questionmark.circle").foregroundStyle(.secondary).help("Source-based candidate; declaration or build settings may be uncertain.") }
if model.parameterHints.count > 1 {
Menu {
ForEach(model.parameterHints) { candidate in
Button(candidate.signature + " — " + candidate.sourcePath) { selectedHintID = candidate.id }
}
} label: { Text("\(model.parameterHints.count) candidates") }
.fixedSize().accessibilityLabel("Parameter hint candidates").accessibilityIdentifier("cmoc.parameters.candidates")
}
} else {
Text(model.completionMessage.isEmpty ? "Parameter hints appear inside function calls. Complete inserts identifier names." : model.completionMessage)
.font(.caption).foregroundStyle(.secondary).lineLimit(2)
.accessibilityIdentifier("cmoc.completion.status")
Spacer(minLength: 2)
}
}.frame(height: 34, alignment: .top).padding(.horizontal, 10).padding(.vertical, 6).background(.bar)
}
private func parameterDescription(_ hint: CMOCCompletion.ParameterHint) -> String {
guard !hint.parameters.isEmpty else { return "No parameters" }
let active = hint.activeParameter
if hint.parameters.indices.contains(active) { return "Argument \(active + 1): \(hint.parameters[active])" }
if hint.parameters.last == "..." { return "Argument \(active + 1): variadic value (…)" }
return "Argument \(active + 1): beyond this declaration’s parameter list"
}
private var projectSearch: some View {
VStack(alignment: .leading, spacing: 0) {
TextField("Find in Project", text: $model.searchQuery)
.textFieldStyle(.roundedBorder).focused($searchFocused)
.accessibilityIdentifier("cmoc.search.query").padding(.horizontal, 9).padding(.top, 9)
Toggle("Match case", isOn: $model.searchCaseSensitive)
.toggleStyle(.checkbox).font(.caption).padding(9).accessibilityIdentifier("cmoc.search.case")
if !model.searchQuery.isEmpty {
Text("\(model.searchMatches.count) match\(model.searchMatches.count == 1 ? "" : "es")\(model.searchTruncated ? " · showing first results" : "")")
.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 10).padding(.bottom, 6)
}
if model.searchQuery.isEmpty {
navigationEmpty("Search project text", detail: "Includes unsaved editor changes. Search is literal; regular expressions are not used.", symbol: "magnifyingglass")
} else if model.searchMatches.isEmpty && !model.indexing {
navigationEmpty("No matches", detail: "Try another word or turn off Match case.", symbol: "magnifyingglass")
} else {
List(model.searchMatches) { match in
Button { model.openSearchMatch(match) } label: {
VStack(alignment: .leading, spacing: 3) {
Text("\(match.path):\(match.line)").font(.caption.weight(.medium)).lineLimit(2).truncationMode(.middle)
Text(match.preview).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).lineLimit(2)
}.padding(.vertical, 3).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())
}.buttonStyle(.plain).help("\(match.path):\(match.line):\(match.column)")
.accessibilityLabel("Search match in \(match.path), line \(match.line), \(match.preview)")
.accessibilityIdentifier("cmoc.search.result.\(match.id)")
}.listStyle(.sidebar).accessibilityLabel("Project search results")
}
}
}
private var symbolOutline: some View {
VStack(alignment: .leading, spacing: 0) {
Text(URL(fileURLWithPath: model.selectedFile).lastPathComponent).font(.caption.weight(.semibold))
.lineLimit(1).truncationMode(.middle).padding(10).help(model.selectedFile)
if model.currentOutline.isEmpty {
navigationEmpty("No C symbols", detail: "Functions, global declarations, types and macros appear here for the current C source or header.", symbol: "list.bullet.indent")
} else {
List(model.currentOutline) { symbol in navigationSymbol(symbol, showPath: false) }
.listStyle(.sidebar).accessibilityLabel("Current file symbols")
}
}
}
private var definitionResults: some View {
VStack(alignment: .leading, spacing: 0) {
Text(model.definitionName.isEmpty ? "DEFINITIONS" : model.definitionName)
.font(.caption.weight(.semibold)).lineLimit(2).padding(10)
Text("Source-based candidates, not compiler-verified bindings. Conditional or duplicate declarations may need your choice.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 10).padding(.bottom, 8)
if model.definitionCandidates.isEmpty {
navigationEmpty(model.definitionName.isEmpty ? "Choose an identifier" : "No definition found", detail: model.definitionName.isEmpty ? "Place the insertion point on a C identifier and choose Go to Definition." : "No candidate is available in the indexed source. Macros and custom build settings can limit source-based lookup.", symbol: "arrow.turn.down.right")
} else {
List(model.definitionCandidates) { symbol in navigationSymbol(symbol, showPath: true) }
.listStyle(.sidebar).accessibilityLabel("Definition candidates")
}
}
}
private func navigationEmpty(_ title: String, detail: String, symbol: String) -> some View {
VStack(alignment: .leading, spacing: 7) {
Label(title, systemImage: symbol).font(.callout.weight(.medium))
Text(detail).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
}.padding(12).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
private func navigationSymbol(_ symbol: CMOCProjectIndex.Symbol, showPath: Bool) -> some View {
Button { model.openSymbol(symbol) } label: {
VStack(alignment: .leading, spacing: 3) {
HStack(alignment: .firstTextBaseline, spacing: 6) {
Image(systemName: symbolIcon(symbol.kind.rawValue)).foregroundStyle(.secondary)
Text(symbol.name).font(.system(.callout, design: .monospaced)).lineLimit(1).truncationMode(.middle)
Spacer(minLength: 0)
Text("\(symbol.line)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
}
Text(showPath ? symbol.path : symbol.kind.rawValue.capitalized)
.font(.caption).foregroundStyle(.secondary).lineLimit(2).truncationMode(.middle)
if symbol.conditional { Label("Conditional candidate", systemImage: "questionmark.circle").font(.caption2).foregroundStyle(.secondary) }
if !symbol.isDefinition { Text("Declaration").font(.caption2).foregroundStyle(.secondary) }
}.padding(.vertical, 3).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())
}.buttonStyle(.plain).help(symbol.signature + "\n\(symbol.path):\(symbol.line):\(symbol.column)")
.accessibilityLabel("\(symbol.name), \(symbol.kind.rawValue), \(symbol.path), line \(symbol.line)" + (symbol.conditional ? ", conditional" : ""))
.accessibilityIdentifier("cmoc.symbol.\(symbol.id)")
}
private func symbolIcon(_ kind: String) -> String {
switch kind.lowercased() {
case "function": return "function"
case "macro": return "number"
case "struct", "union", "type", "typedef": return "square.stack.3d.up"
case "enum", "enumerator": return "list.number"
default: return "shippingbox"
}
}
private var projectFiles: some View {
VStack(alignment: .leading, spacing: 0) {
HStack { Text("PROJECT").font(.caption.bold()).foregroundStyle(.secondary); Spacer(); Button { model.addFile() } label: { Image(systemName: "doc.badge.plus") }.buttonStyle(.plain).help("New Project File").accessibilityLabel("New Project File").disabled(model.project == nil || model.commanding || model.building) }.padding(12)
List {
OutlineGroup(CMOCNavigatorNode.tree(model.files), children: \.children) { node in
if let file = node.file {
Button {
if file.isEditable { model.openFile(file.relativePath) }
} label: {
HStack(spacing: 7) {
Image(systemName: symbol(file.relativePath)).foregroundStyle(.secondary).frame(width: 16)
Text(node.name).lineLimit(1).truncationMode(.middle)
Spacer(minLength: 0)
if model.documents.first(where: { $0.id == file.relativePath })?.dirty == true { Circle().fill(.secondary).frame(width: 6, height: 6).accessibilityLabel("Unsaved changes") }
}.padding(.vertical, 3).contentShape(Rectangle())
}.buttonStyle(.plain).disabled(!file.isEditable)
.listRowBackground(model.selectedFile == file.relativePath ? Color.accentColor.opacity(0.14) : Color.clear)
.accessibilityLabel("Open " + file.relativePath).help(file.relativePath)
} else {
Label(node.name, systemImage: "folder").foregroundStyle(.secondary).help(node.id)
}
}
}.listStyle(.sidebar).accessibilityLabel("Project files")
if !model.breakpoints.isEmpty {
Divider()
Text("BREAKPOINTS").font(.caption.bold()).foregroundStyle(.secondary).padding(12)
ScrollView {
VStack(alignment: .leading, spacing: 8) {
ForEach(model.breakpoints.sorted { ($0.file, $0.line) < ($1.file, $1.line) }, id: \.self) { point in
Button { model.openFile(point.file, line: point.line); model.breakpointLine = point.line } label: {
Label("\(point.file):\(point.line)", systemImage: "stop.circle.fill").lineLimit(1)
}.buttonStyle(.plain).foregroundStyle(model.projectMapping?.addresses(file: point.file, line: point.line).isEmpty == false ? Color.accentColor : Color.secondary)
}
}.padding(.horizontal, 12).padding(.bottom, 12)
}.frame(maxHeight: 130)
}
}.background(.background)
}
private func symbol(_ path: String) -> String {
switch URL(fileURLWithPath: path).pathExtension.lowercased() {
case "c", "h": return "curlybraces"
case "dsk": return "externaldrive"
case "png", "jpg": return "photo"
default: return path.hasSuffix("Makefile") ? "hammer" : "doc.text"
}
}
private var tabs: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
ForEach(model.documents) { doc in
HStack(spacing: 8) {
Button { model.openFile(doc.id) } label: {
HStack(spacing: 5) {
if doc.missing || doc.conflict {
Image(systemName: doc.missing ? "doc.badge.ellipsis" : "exclamationmark.triangle")
.foregroundStyle(.orange).accessibilityLabel(doc.missing ? "File missing" : "Changed outside the editor")
}
Text(URL(fileURLWithPath: doc.id).lastPathComponent + (doc.dirty ? " •" : "")).lineLimit(1)
}
}.buttonStyle(.plain).help(doc.id)
Button { model.closeFile(doc.id) } label: { Image(systemName: "xmark").font(.caption2) }.buttonStyle(.plain).help("Close " + doc.id).accessibilityLabel("Close " + doc.id)
}.padding(.horizontal, 12).padding(.vertical, 9)
.background(model.selectedFile == doc.id ? Color.accentColor.opacity(0.1) : Color.clear)
Divider().frame(height: 22)
}
}
}.background(.bar)
}
private var output: some View {
VStack(alignment: .leading, spacing: 0) {
HStack {
Picker("Development inspector", selection: $outputTab) {
Text("Build Log").tag("Build Log")
Text("Issues (\(model.diagnostics.count))").tag("Issues")
Text("Call Stack").tag("Call Stack")
Text("Variables").tag("Variables")
Text("Watches").tag("Watches")
}.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 540).accessibilityIdentifier("cmoc.inspector")
Spacer()
}.padding(7)
if outputTab == "Build Log" {
HStack {
Spacer()
TextField("Make target…", text: $model.customTarget).frame(width: 140).accessibilityLabel("Custom Make target")
Button("Build Target") { model.build(.custom, target: model.customTarget) }.disabled(model.customTarget.isEmpty || model.project == nil || model.building || model.commanding)
}.padding(.horizontal, 7).padding(.bottom, 7)
}
Divider()
if outputTab == "Variables" || outputTab == "Watches" {
if let stack = model.callStack, !stack.frames.isEmpty {
HStack {
Picker("Inspect frame", selection: Binding(get: { model.selectedFrameIndex }, set: model.selectFrame)) {
ForEach(stack.frames) { frame in
Text("\(frame.id): \(frame.functionName)").tag(frame.id)
}
}.accessibilityIdentifier("cmoc.frame.picker")
if model.inspectingCaller { Text("Caller values").foregroundStyle(.secondary) }
}.font(.caption).padding(.horizontal, 10).padding(.top, 6)
}
}
if outputTab == "Watches" {
HStack {
TextField("Expression, e.g. score or player.x", text: $model.watchExpression)
.textFieldStyle(.roundedBorder).onSubmit { model.addWatch() }.accessibilityIdentifier("cmoc.watch.expression")
.help("Read-only names, fields, array indexes and pointers. Arithmetic uses checked 64-bit watch integers, not target C overflow rules. Stored floating-point values can be inspected; floating-point arithmetic, calls, assignments and casts are unavailable.")
Button { model.addWatch() } label: { Label("Add Watch", systemImage: "plus") }
.disabled(model.watchExpression.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.watches.count >= 32)
.accessibilityIdentifier("cmoc.watch.add")
}.padding(.horizontal, 10).padding(.vertical, 6)
}
ScrollView {
if outputTab == "Call Stack" {
callStackInspector
} else if outputTab == "Variables" || outputTab == "Watches" {
variableInspector
} else if outputTab == "Issues" {
LazyVStack(alignment: .leading, spacing: 6) {
ForEach(model.diagnostics) { issue in
Button { model.openFile(issue.file, line: issue.line) } label: {
Label("\(issue.file):\(issue.line): \(issue.message)", systemImage: "exclamationmark.circle").multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading)
}.buttonStyle(.plain).padding(.vertical, 3)
}
if model.diagnostics.isEmpty { Text("No compiler issues.").foregroundStyle(.secondary) }
}.padding(10)
} else {
Text(model.log).font(.system(.caption, design: .monospaced)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(10)
}
}
}.background(.background)
}
private var callStackInspector: some View {
VStack(alignment: .leading, spacing: 8) {
if let stack = model.callStack {
Text("Select a frame to view its source, then use Variables or Watches to inspect it. Stepping always controls frame 0.")
.font(.caption).foregroundStyle(.secondary)
ForEach(stack.frames) { frame in
Button { model.selectFrame(frame.id) } label: {
HStack(spacing: 10) {
Text("\(frame.id)").monospacedDigit().foregroundStyle(.secondary).frame(width: 22)
Image(systemName: frame.id == 0 ? "pause.circle" : "arrow.turn.up.left").foregroundStyle(.secondary)
Text(frame.functionName).fontWeight(.medium)
Spacer(minLength: 4)
Text(frame.sourcePath + (frame.sourceLine.map { ":\($0)" } ?? ""))
.foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
Image(systemName: frame.id == model.selectedFrameIndex ? "checkmark.circle.fill" : "circle")
.foregroundStyle(frame.id == model.selectedFrameIndex ? Color.accentColor : Color.secondary)
}.padding(7).contentShape(Rectangle())
.background(frame.id == model.selectedFrameIndex ? Color.accentColor.opacity(0.1) : Color.clear)
.clipShape(RoundedRectangle(cornerRadius: 5))
}.buttonStyle(.plain).accessibilityIdentifier("cmoc.frame.\(frame.id)")
.accessibilityLabel("Frame \(frame.id), \(frame.functionName), \(frame.sourcePath), line \(frame.sourceLine ?? 0)")
.accessibilityValue(frame.id == model.selectedFrameIndex ? "Selected" : "")
}
Text(stack.termination).font(.caption).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("cmoc.stack.boundary")
} else {
Text(model.inspectionMessage).font(.caption).foregroundStyle(.secondary)
}
}.padding(10).frame(maxWidth: .infinity, alignment: .leading)
}
private var variableInspector: some View {
let listing = model.variableTree(watches: outputTab == "Watches", expanded: expandedVariables,
offsets: variableOffsets, rootOffset: variableRootOffset)
return VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .top) {
Text(model.inspectionMessage).font(.caption).foregroundStyle(.secondary)
.accessibilityIdentifier("cmoc.variables.status")
Spacer(minLength: 4)
if !expandedVariables.isEmpty {
Button("Collapse All", systemImage: "chevron.up.chevron.down") { expandedVariables.removeAll() }
.buttonStyle(.borderless).accessibilityIdentifier("cmoc.tree.collapse")
}
}
if listing.rootCount > 32 {
HStack {
Button("Previous Variables", systemImage: "chevron.left") { changeRootPage(max(0, listing.rootOffset - 32)) }
.disabled(listing.rootOffset == 0)
Text("\(listing.rootOffset + 1)–\(min(listing.rootOffset + 32, listing.rootCount)) of \(listing.rootCount)")
Button("Next Variables", systemImage: "chevron.right") { changeRootPage(listing.rootOffset + 32) }
.disabled(listing.rootOffset + 32 >= listing.rootCount)
}.buttonStyle(.borderless)
}
ForEach(listing.rows) { row in treeRow(row) }
if model.canInspectC && listing.rootCount == 0 {
Text(outputTab == "Watches" ? "Add a read-only C expression to follow it between stops." : "No C variables in this scope.")
.foregroundStyle(.secondary)
}
if !model.canInspectC && outputTab == "Watches" {
ForEach(model.watches, id: \.self) { expression in
HStack {
variableRow(name: expression, type: "", value: "Unavailable", error: nil)
removeWatchButton(expression)
}
}
}
}.font(.system(.caption, design: .monospaced)).padding(10).frame(maxWidth: .infinity, alignment: .leading)
}
private func changeRootPage(_ offset: Int) {
variableRootOffset = offset; expandedVariables.removeAll(); variableOffsets.removeAll()
}
@ViewBuilder private func treeRow(_ row: CMOCVariableTreeRow) -> some View {
switch row.content {
case .node(let node):
HStack(alignment: .top, spacing: 5) {
if node.childCount > 0 {
let action = (expandedVariables.contains(node.path) ? "Collapse " : "Expand ") + treePathLabel(node.path)
Button {
if expandedVariables.contains(node.path) { expandedVariables.remove(node.path) }
else { expandedVariables.insert(node.path) }
} label: {
Image(systemName: expandedVariables.contains(node.path) ? "chevron.down" : "chevron.right")
.frame(width: 16, height: 18).contentShape(Rectangle())
}.buttonStyle(.plain)
.help(action).accessibilityLabel(action)
.accessibilityIdentifier("cmoc.tree.expand." + treePathLabel(node.path))
.accessibilityValue(expandedVariables.contains(node.path) ? "Expanded" : "Collapsed")
} else { Color.clear.frame(width: 16, height: 1).accessibilityHidden(true) }
variableRow(name: node.name, type: node.typeName, value: node.value, error: node.error)
.help(node.address.map { String(format: "Storage: $%04X", $0) } ?? "")
if node.path.components.isEmpty, case .watch(let expression) = node.path.root {
removeWatchButton(expression)
}
}.padding(.leading, CGFloat(min(row.depth, 6)) * 12)
case .page(let path, let offset, let total, let next):
HStack {
Button("Previous", systemImage: "chevron.left") { variableOffsets[path] = max(0, offset - 32) }
.disabled(offset == 0).accessibilityLabel("Previous children of " + treePathLabel(path))
Text("\(offset + 1)–\(min(offset + 32, total)) of \(total)").foregroundStyle(.secondary)
Button("Next", systemImage: "chevron.right") { if let next { variableOffsets[path] = next } }
.disabled(next == nil).accessibilityLabel("Next children of " + treePathLabel(path))
.accessibilityIdentifier("cmoc.tree.next." + treePathLabel(path))
}.buttonStyle(.borderless).padding(.leading, CGFloat(min(row.depth, 6)) * 12 + 21)
case .message(let text):
Text(text).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
.padding(.leading, CGFloat(min(row.depth, 6)) * 12)
}
}
private func removeWatchButton(_ expression: String) -> some View {
Button {
model.removeWatch(expression)
expandedVariables = expandedVariables.filter { $0.root != .watch(expression) }
variableOffsets = variableOffsets.filter { $0.key.root != .watch(expression) }
} label: { Image(systemName: "minus.circle") }
.buttonStyle(.plain).help("Remove watch " + expression).accessibilityLabel("Remove watch " + expression)
}
private func treePathLabel(_ path: CMOCWatchEvaluator.TreePath) -> String {
let root: String
switch path.root { case .variable(let name), .watch(let name): root = name }
return root + path.components.map {
switch $0 { case .index(let index): return "[\(index)]"; case .member(let name): return "." + name; case .pointee: return ".Pointee" }
}.joined()
}
private func variableRow(name: String, type: String, value: String, error: String?) -> some View {
VStack(alignment: .leading, spacing: 3) {
HStack(alignment: .firstTextBaseline, spacing: 12) {
Text(name).fontWeight(.medium).frame(minWidth: 90, alignment: .leading)
Text(type).foregroundStyle(.secondary)
Spacer(minLength: 4)
Text(value).foregroundStyle(error == nil ? Color.primary : Color.secondary)
}.textSelection(.enabled)
if let error { Text(error).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }
}.accessibilityElement(children: .combine)
}
private var breakpointAction: String {
let verb = model.selectedBreakpoints.contains(model.breakpointLine) ? "Remove" : "Set"
return "\(verb) breakpoint on line \(model.breakpointLine)"
}
private var debugBar: some View {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 8) {
Picker("Source breakpoint", selection: $model.breakpointLine) {
if model.executableLines.isEmpty { Text("Build for source lines").tag(model.breakpointLine) }
else { ForEach(model.executableLines, id: \.self) { Text("Line \($0)").tag($0) } }
}.frame(width: 220).disabled(!model.buildMatchesEditor || model.executableLines.isEmpty).accessibilityIdentifier("cmoc.breakpoint")
Button { model.toggleBreakpoint(model.breakpointLine) } label: { Image(systemName: model.selectedBreakpoints.contains(model.breakpointLine) ? "minus.circle" : "plus.circle") }.disabled(model.project == nil).help(breakpointAction).accessibilityLabel(breakpointAction)
Button { model.confirmRun() } label: { Label("Run to Breakpoint", systemImage: "play.fill") }.disabled(!model.canRun).accessibilityIdentifier("cmoc.run")
Spacer(minLength: 0)
Button { model.toggleExecution() } label: { Label(model.machine.state == .running ? "Pause" : "Continue", systemImage: model.machine.state == .running ? "pause.fill" : "play") }.disabled(!model.canCommand)
}
HStack(spacing: 10) {
Label("C Step", systemImage: "curlybraces").foregroundStyle(.secondary)
Button { model.stepSource(.over) } label: { Label("Over", systemImage: "arrow.turn.down.right") }
.help("Execute the current C line in frame 0, stepping over called functions. Selecting a caller does not change execution.").accessibilityIdentifier("cmoc.step.over")
.disabled(!model.canStepC)
Button { model.stepSource(.into) } label: { Label("Into", systemImage: "arrow.down.to.line") }
.help("Stop at the next mapped C line, entering a called function when source is available.").accessibilityIdentifier("cmoc.step.into")
.disabled(!model.canStepC)
Button { model.stepSource(.out) } label: { Label("Out", systemImage: "arrow.up.to.line") }
.help("Finish this function and stop at its return address. Unmapped callers remain available in the assembly debugger.").accessibilityIdentifier("cmoc.step.out")
.disabled(!model.canStepC)
Spacer(minLength: 0)
Button { model.stepInstruction() } label: { Label("Instruction", systemImage: "arrow.right.to.line") }
.disabled(!model.canCommand || model.machine.state != .paused).help("Execute one CPU instruction.")
}
}.controlSize(.small)
}
}
private struct CMOCBuildHistoryView: View {
@ObservedObject var model: CMOCDevelopmentModel
@Environment(\.dismiss) private var dismiss
@State private var selected: Set<UUID> = []
private var eligible: Set<UUID> { Set(model.buildHistory.filter { $0.protectionReason == nil }.map(\.id)) }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack {
Label("Build History", systemImage: "clock.arrow.circlepath").font(.title2.bold())
Spacer()
if model.historyBusy { ProgressView().controlSize(.small).accessibilityLabel("Reading build history") }
Button("Refresh", systemImage: "arrow.clockwise") { model.refreshBuildHistory() }
.disabled(model.historyBusy).accessibilityIdentifier("cmoc.history.refresh")
}.padding(18)
Text("Completed builds for this project. The latest result, loaded programs and changed files are protected. Removing a build moves it to the Trash; development disks stay in their own folder.")
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 18).padding(.bottom, 12)
if let message = model.historyMessage {
Text(message).font(.callout).foregroundStyle(.orange).textSelection(.enabled)
.padding(.horizontal, 18).padding(.bottom, 10).accessibilityIdentifier("cmoc.history.message")
}
Divider()
ScrollView {
if model.buildHistory.isEmpty {
VStack(spacing: 8) {
Image(systemName: "hammer").font(.largeTitle).foregroundStyle(.secondary)
Text(model.project == nil ? "Open a project to review its builds" : "No completed builds recorded yet").font(.headline)
Text("Builds made before history was added remain untouched.").foregroundStyle(.secondary)
}.frame(maxWidth: .infinity).padding(35)
} else {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(model.buildHistory) { entry in
historyRow(entry)
Divider().padding(.leading, 38)
}
}.padding(.horizontal, 18)
}
}.frame(maxWidth: .infinity, maxHeight: .infinity)
Divider()
HStack(spacing: 10) {
Button("Development Disks", systemImage: "externaldrive") { model.revealDevelopmentDisks() }
.accessibilityIdentifier("cmoc.history.disks")
Spacer()
Button("Move Selected to Trash…", systemImage: "trash") {
model.trashBuilds(selected.intersection(eligible)); selected.removeAll()
}.disabled(selected.intersection(eligible).isEmpty || model.historyBusy || model.building || model.commanding)
.accessibilityIdentifier("cmoc.history.trash")
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
}.padding(18)
}.frame(width: 690, height: 470)
.onAppear { model.refreshBuildHistory() }
.onChange(of: model.buildHistory.map(\.id)) { _, _ in selected.formIntersection(eligible) }
}
private func historyRow(_ entry: CMOCBuildHistory.Entry) -> some View {
let latestID = model.artifact?.id ?? model.buildHistory.first(where: { $0.hasBinary || $0.hasDisk })?.id
let isLatest = entry.id == latestID
let isLaunched = entry.id == model.launchedBuildID
return HStack(alignment: .top, spacing: 10) {
Toggle("Build from " + entry.createdAt.formatted(date: .abbreviated, time: .shortened), isOn: Binding(
get: { selected.contains(entry.id) },
set: { if $0 { selected.insert(entry.id) } else { selected.remove(entry.id) } }))
.toggleStyle(.checkbox).labelsHidden().disabled(entry.protectionReason != nil || model.historyBusy)
.help(entry.protectionReason ?? (selected.contains(entry.id) ? "Deselect this build for cleanup" : "Select this build for cleanup"))
.accessibilityIdentifier("cmoc.history.select.\(entry.id)")
VStack(alignment: .leading, spacing: 5) {
HStack {
Text(entry.createdAt.formatted(date: .abbreviated, time: .shortened)).fontWeight(.medium)
Spacer()
Text(ByteCountFormatter.string(fromByteCount: entry.byteCount, countStyle: .file)).foregroundStyle(.secondary)
}
HStack(spacing: 10) {
Text(entry.configurationName + " · " + entry.action.capitalized)
Text(entry.id.uuidString.prefix(8)).font(.system(.caption, design: .monospaced))
if entry.hasBinary { Label("Program", systemImage: "curlybraces") }
if entry.hasDisk { Label("Disk", systemImage: "externaldrive") }
}.font(.caption).foregroundStyle(.secondary)
if isLatest || isLaunched {
HStack(spacing: 10) {
if isLatest { Label("Latest build", systemImage: "checkmark.seal") }
if isLaunched { Label("Launched in CoCo", systemImage: "desktopcomputer") }
}.font(.caption).foregroundStyle(.tint)
}
if let reason = entry.protectionReason,
reason != "Protected build or assigned media" || (!isLatest && !isLaunched) {
Label(reason, systemImage: "lock").font(.caption).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
Button { NSWorkspace.shared.activateFileViewerSelecting([entry.directory]) } label: { Image(systemName: "folder") }
.buttonStyle(.borderless).help("Show Build in Finder").accessibilityLabel("Show build from " + entry.createdAt.formatted(date: .abbreviated, time: .shortened) + " in Finder")
}.padding(.vertical, 12)
}
}
private struct CMOCRecoveryView: View {
@ObservedObject var model: CMOCDevelopmentModel
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack {
Label("Editor Recovery", systemImage: "doc.badge.clock").font(.title2.bold())
Spacer()
if model.recoveryBusy { ProgressView().controlSize(.small).accessibilityLabel("Reading recovery copies") }
Button("Refresh", systemImage: "arrow.clockwise") { model.refreshRecovery() }
.disabled(model.recoveryBusy).accessibilityIdentifier("cmoc.recovery.refresh")
}.padding(18)
Text("Unsaved editor text is kept separately from project files. Restore a copy into the editor, or export it to a folder for safekeeping. Files on disk are never silently replaced.")
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 18).padding(.bottom, 12)
if let message = model.message {
Label(message, systemImage: "info.circle").font(.callout).textSelection(.enabled).lineLimit(3)
.padding(.horizontal, 18).padding(.bottom, 10).accessibilityIdentifier("cmoc.recovery.message")
}
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
ForEach(Array(model.recoveryIssues.enumerated()), id: \.offset) { _, issue in
Label(issue, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)
.textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
}
if model.recoveryRecords.isEmpty {
VStack(spacing: 8) {
Image(systemName: "checkmark.shield").font(.largeTitle).foregroundStyle(.secondary)
Text("No recovery copies to review").font(.headline)
Text("Current edits are saved automatically. Copies from earlier sessions appear here.").foregroundStyle(.secondary)
}.frame(maxWidth: .infinity).padding(.vertical, 25)
}
ForEach(model.recoveryRecords) { record in
recoveryRow(record)
Divider()
}
}.padding(18)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
Divider()
HStack {
Text("Copies from another running app can be exported; close that app before restoring or discarding them.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 20)
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
}.padding(18)
}.frame(width: 690, height: 470)
.onAppear { model.persistDrafts(); model.refreshRecovery() }
}
private func recoveryRow(_ record: CMOCWorkspaceRecovery.Record) -> some View {
VStack(alignment: .leading, spacing: 7) {
HStack {
Text(record.modifiedAt.formatted(date: .abbreviated, time: .shortened)).fontWeight(.medium)
Spacer()
Text("\(record.drafts.count) file\(record.drafts.count == 1 ? "" : "s")").foregroundStyle(.secondary)
}
Text(record.drafts.prefix(4).map(\.path).joined(separator: ", ") + (record.drafts.count > 4 ? "…" : ""))
.font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled)
HStack(spacing: 10) {
if record.isFromRunningSession {
Label("Open in another app session", systemImage: "lock").font(.caption).foregroundStyle(.secondary)
}
Spacer(minLength: 0)
Button("Export…", systemImage: "square.and.arrow.up") { model.exportRecovery(record) }
.disabled(model.recoveryBusy).accessibilityIdentifier("cmoc.recovery.export.\(record.id)")
Button("Restore", systemImage: "arrow.uturn.backward") { model.restoreRecovery(record) }
.disabled(record.isFromRunningSession || model.recoveryBusy || model.building || model.commanding)
.accessibilityIdentifier("cmoc.recovery.restore.\(record.id)")
Button { model.discardRecovery(record) } label: { Image(systemName: "trash") }
.disabled(record.isFromRunningSession || model.recoveryBusy)
.help("Discard Recovery Copy").accessibilityLabel("Discard recovery copy from " + record.modifiedAt.formatted(date: .abbreviated, time: .shortened))
}.controlSize(.small)
}.padding(.vertical, 4)
}
}
/// A stable native text view; machine polling never replaces its contents,
/// selection, undo stack or first responder. Highlighting changes attributes only.
struct CSourceEditor: NSViewRepresentable {
var finder: SourceFind? = nil
@Binding var text: String
let currentLine: Int?
var file = "main.c"
var readOnly = false
var breakpoints: Set<Int> = []
var breakpointControlsEnabled = true
var navigationLine: Int? = nil
var navigationColumn: Int? = nil
var navigationLength = 0
var navigationRequest = UUID()
var toggleBreakpoint: (Int) -> Void = { _ in }
var cursorChanged: (Int) -> Void = { _ in }
var goToDefinition: () -> Void = {}
var completionIndex: CMOCProjectIndex?
var completionRequest = UUID()
var completionStatus: (String) -> Void = { _ in }
var parameterHints: () -> Void = {}
var clearParameterHints: () -> Void = {}
var editorAction: CMOCEditorAction = .indent
var editorActionRequest = UUID()
var attach: (String, NSTextView, Coordinator) -> Void = { _, _, _ in }
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView(); scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true; scroll.borderType = .bezelBorder
let editor = context.coordinator.makeEditor(file: file, text: text)
scroll.documentView = editor
scroll.verticalRulerView = CLineRuler(scrollView: scroll, orientation: .verticalRuler)
scroll.hasVerticalRuler = true; scroll.rulersVisible = true
context.coordinator.activeFile = file
context.coordinator.highlight(editor, line: currentLine)
updateNSView(scroll, context: context)
return scroll
}
static func dismantleNSView(_ scroll: NSScrollView, coordinator: Coordinator) {
for editor in coordinator.editors.values { (editor as? CMOCCompletionTextView)?.invalidateCompletion() }
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
context.coordinator.parent = self
let coordinator = context.coordinator
let changedFile = coordinator.activeFile != file
if changedFile {
(scroll.documentView as? CMOCCompletionTextView)?.invalidateCompletion()
let hadFocus = (scroll.window?.firstResponder as? NSTextView) === scroll.documentView
let editor = coordinator.editors[file] ?? coordinator.makeEditor(file: file, text: text)
scroll.documentView = editor
scroll.verticalRulerView?.clientView = editor
coordinator.activeFile = file
coordinator.line = nil
if hadFocus { scroll.window?.makeFirstResponder(editor) }
}
guard let editor = scroll.documentView as? NSTextView else { return }
finder?.editor = editor
attach(file, editor, coordinator)
editor.setAccessibilityLabel("C source editor, " + file)
if readOnly { (editor as? CMOCCompletionTextView)?.invalidateCompletion() }
editor.isEditable = !readOnly
(editor as? CMOCEditingTextView)?.sourceEditingEnabled = ["c", "h"].contains((file as NSString).pathExtension.lowercased())
if !editor.string.utf8.elementsEqual(text.utf8) {
(editor as? CMOCCompletionTextView)?.invalidateCompletion()
editor.string = text; editor.undoManager?.removeAllActions()
coordinator.highlight(editor, line: currentLine)
} else if coordinator.line != currentLine { coordinator.highlight(editor, line: currentLine) }
if let ruler = scroll.verticalRulerView as? CLineRuler {
ruler.points = breakpoints; ruler.active = breakpointControlsEnabled; ruler.onClick = toggleBreakpoint
if changedFile { ruler.invalidateMarkers() }
}
if coordinator.navigationRequest != navigationRequest {
coordinator.navigationRequest = navigationRequest
if let navigationLine { coordinator.navigate(editor, to: navigationLine, column: navigationColumn ?? 1, length: navigationLength) }
}
if coordinator.completionRequest != completionRequest {
coordinator.completionRequest = completionRequest
let request = completionRequest, requestedFile = file
Task { @MainActor [weak editor, weak coordinator] in
guard let editor, let coordinator, coordinator.parent.completionRequest == request,
coordinator.activeFile == requestedFile, editor === coordinator.editors[requestedFile], editor.isEditable else { return }
editor.window?.makeFirstResponder(editor)
coordinator.parent.completionStatus("Finding completions…")
editor.complete(nil)
}
}
if coordinator.editorActionRequest != editorActionRequest {
coordinator.editorActionRequest = editorActionRequest
let request = editorActionRequest, requestedFile = file, action = editorAction
Task { @MainActor [weak editor, weak coordinator] in
guard let editor = editor as? CMOCEditingTextView, let coordinator,
coordinator.parent.editorActionRequest == request, coordinator.activeFile == requestedFile,
editor === coordinator.editors[requestedFile] else { return }
editor.window?.makeFirstResponder(editor); editor.performSourceAction(action)
}
}
if changedFile { coordinator.reportCursor(editor) }
}
@MainActor final class Coordinator: NSObject, NSTextViewDelegate {
var parent: CSourceEditor
var line: Int?
var activeFile = ""
var editors: [String: NSTextView] = [:]
var undoManagers: [ObjectIdentifier: UndoManager] = [:]
private var suspendedUndo: [String: (UndoManager, NSRange)] = [:]
private var updatingReviewedBuffers = false
/// Per-tab typing history belongs to the preceding text. Keep it while
/// the panel owns grouped Undo, then reattach it only on exact rollback.
func setReviewedBuffers(_ changes: [MCPCMOCEdit], undoing: Bool) {
if !undoing { suspendedUndo.removeAll() }
updatingReviewedBuffers = true
defer { updatingReviewedBuffers = false }
for change in changes {
guard let editor = editors[change.path], editor.string.utf8.elementsEqual(change.before.utf8) else { continue }
let key = ObjectIdentifier(editor)
editor.breakUndoCoalescing()
if !undoing, let manager = undoManagers[key] {
suspendedUndo[change.path] = (manager, editor.selectedRange())
}
undoManagers[key] = UndoManager()
(editor as? CMOCCompletionTextView)?.invalidateCompletion()
editor.string = change.after
highlight(editor, line: nil)
if undoing, let (manager, selection) = suspendedUndo.removeValue(forKey: change.path) {
undoManagers[key] = manager
editor.setSelectedRange(selection)
}
}
}
func undoManager(for view: NSTextView) -> UndoManager? { undoManagers[ObjectIdentifier(view)] }
var navigationRequest: UUID?
var completionRequest: UUID
var editorActionRequest: UUID
init(_ parent: CSourceEditor) {
self.parent = parent; completionRequest = parent.completionRequest; editorActionRequest = parent.editorActionRequest
}
func makeEditor(file: String, text: String) -> NSTextView {
let editor = CNavigationTextView(frame: .zero)
editor.definitionAction = { [weak self, weak editor] in
guard let self, let editor, self.activeFile == file else { return }
self.parent.cursorChanged(editor.selectedRange().location)
self.parent.goToDefinition()
}
editor.completionProvider = { [weak self, weak editor] text, offset in
guard let self, let editor, self.activeFile == file, self.parent.file == file,
editor === self.editors[file], !self.parent.readOnly, let index = self.parent.completionIndex else { return [] }
return CMOCCompletion.suggestions(index: index, path: file, text: text, offset: offset)
}
editor.completionStatus = { [weak self] message in self?.parent.completionStatus(message) }
editor.assistanceFocusLost = { [weak self, weak editor] in
Task { @MainActor [weak self, weak editor] in
guard let self, let editor, self.activeFile == file,
editor.window?.firstResponder !== editor else { return }
self.parent.clearParameterHints()
}
}
editor.parameterHintAction = { [weak self, weak editor] in
guard let self, let editor, self.activeFile == file else { return }
self.parent.cursorChanged(editor.selectedRange().location); self.parent.parameterHints()
}
undoManagers[ObjectIdentifier(editor)] = UndoManager()
editor.isRichText = false; editor.allowsUndo = true; editor.isAutomaticQuoteSubstitutionEnabled = false
editor.isAutomaticDashSubstitutionEnabled = false; editor.isAutomaticTextReplacementEnabled = false
editor.isAutomaticSpellingCorrectionEnabled = false; editor.isContinuousSpellCheckingEnabled = false
editor.font = .monospacedSystemFont(ofSize: 13, weight: .regular)
editor.textContainerInset = NSSize(width: 12, height: 10)
editor.isVerticallyResizable = true; editor.isHorizontallyResizable = true
editor.minSize = NSSize(width: 0, height: 0); editor.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
editor.textContainer?.containerSize = editor.maxSize; editor.textContainer?.widthTracksTextView = false
editor.autoresizingMask = [.width]; editor.string = text; editor.delegate = self
editor.setAccessibilityLabel("C source editor, " + file); editor.setAccessibilityIdentifier("cmoc.source")
editors[file] = editor
highlight(editor, line: nil)
return editor
}
func navigate(_ editor: NSTextView, to line: Int, column: Int, length: Int) {
(editor as? CMOCCompletionTextView)?.invalidateCompletion()
let lines = (editor.string as NSString).components(separatedBy: "\n")
guard line > 0, line <= lines.count else { return }
let lineLength = (lines[line - 1] as NSString).length
let within = min(max(0, column - 1), lineLength)
let offset = lines.prefix(line - 1).reduce(0) { $0 + ($1 as NSString).length + 1 } + within
let range = NSRange(location: offset, length: min(max(0, length), lineLength - within))
editor.setSelectedRange(range)
// Include the start of the line so short declarations do not open
// with their return type hidden by horizontal scrolling.
editor.scrollRangeToVisible(NSRange(location: offset - within, length: within + range.length))
editor.scrollRangeToVisible(range)
editor.window?.makeFirstResponder(editor)
}
func textViewDidChangeSelection(_ notification: Notification) {
guard let editor = notification.object as? NSTextView, editor === editors[activeFile] else { return }
(editor as? CMOCEditingTextView)?.refreshBracketHighlight()
reportCursor(editor)
}
func reportCursor(_ editor: NSTextView) {
let file = activeFile, offset = editor.selectedRange().location
// NSTextView can notify while SwiftUI is updating its view. Publish
// after that update, and discard callbacks from a tab left behind.
Task { @MainActor [weak self, weak editor] in
guard let self, let editor, self.activeFile == file, self.parent.file == file,
editor === self.editors[file], editor.selectedRange().location == offset else { return }
if editor.hasMarkedText() || editor.selectedRange().length > 0 { self.parent.clearParameterHints() }
else { self.parent.cursorChanged(offset) }
}
}
func textDidChange(_ notification: Notification) {
guard !updatingReviewedBuffers, let editor = notification.object as? NSTextView, editor === editors[activeFile] else { return }
(editor as? CMOCCompletionTextView)?.invalidateCompletion()
parent.text = editor.string; highlight(editor, line: nil)
(editor as? CMOCEditingTextView)?.refreshBracketHighlight()
}
func highlight(_ editor: NSTextView, line: Int?) {
self.line = line
guard let storage = editor.textStorage else { return }
let full = NSRange(location: 0, length: storage.length)
storage.beginEditing()
storage.addAttributes([.foregroundColor: NSColor.textColor, .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)], range: full)
storage.removeAttribute(.backgroundColor, range: full)
let patterns: [(String, NSColor)] = [
(#"\b(?:int|char|void|unsigned|signed|long|short|const|volatile|struct|enum|typedef|return|if|else|while|for|do|switch|case|break|continue|sizeof|asm|__asm)\b"#, .systemPurple),
(#"(?m)^\s*#.*$"#, .systemOrange),
(#"\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'"#, .systemRed),
(#"(?m)//[^\n]*|/\*[\s\S]*?\*/"#, .secondaryLabelColor)
]
for (pattern, color) in patterns {
guard let regex = try? NSRegularExpression(pattern: pattern) else { continue }
for match in regex.matches(in: editor.string, range: full) { storage.addAttribute(.foregroundColor, value: color, range: match.range) }
}
if let line, line > 0 {
let lines = (editor.string as NSString).components(separatedBy: "\n")
if line <= lines.count {
let start = lines.prefix(line - 1).reduce(0) { $0 + ($1 as NSString).length + 1 }
let range = NSRange(location: start, length: (lines[line - 1] as NSString).length)
storage.addAttribute(.backgroundColor, value: NSColor.systemYellow.withAlphaComponent(0.25), range: range)
if !editor.hasMarkedText() { editor.scrollRangeToVisible(range) }
}
}
storage.endEditing()
(editor.enclosingScrollView?.verticalRulerView as? CLineRuler)?.invalidateMarkers()
}
}
}
/// The definition command uses the clicked C identifier and leaves AppKit's
/// standard editing actions intact. It is navigation only, including in headers.
private final class CNavigationTextView: CMOCEditingTextView {
var definitionAction: (() -> Void)?
@objc private func findDefinition(_ sender: Any?) { definitionAction?() }
@objc private func showParameterHints(_ sender: Any?) { parameterHintAction?() }
@objc private func completeIdentifier(_ sender: Any?) {
let selected = selectedRange()
if selected.length > 0 { setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
complete(sender)
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift])
if modifiers == [.command, .control], event.charactersIgnoringModifiers?.lowercased() == "j" {
definitionAction?(); return true
}
return super.performKeyEquivalent(with: event)
}
override func menu(for event: NSEvent) -> NSMenu? {
let location = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
let current = selectedRange()
if current.length == 0 || !NSLocationInRange(location, current) {
let text = string as NSString
func identifier(_ index: Int) -> Bool {
guard index >= 0, index < text.length else { return false }
let character = text.character(at: index)
return character == 95 || (65...90).contains(character) || (97...122).contains(character) || (48...57).contains(character)
}
var start = min(location, text.length), end = min(location, text.length)
if !identifier(start), identifier(start - 1) { start -= 1; end = start }
while identifier(start - 1) { start -= 1 }
while identifier(end) { end += 1 }
setSelectedRange(NSRange(location: start, length: end - start))
}
let menu = super.menu(for: event) ?? NSMenu()
let identifier = NSUserInterfaceItemIdentifier("cmoc.editor.goToDefinition")
if let existing = menu.items.first(where: { $0.identifier == identifier }) {
existing.target = self; return menu
}
let item = NSMenuItem(title: "Go to Definition", action: #selector(findDefinition(_:)), keyEquivalent: "j")
item.target = self; item.identifier = identifier; item.keyEquivalentModifierMask = [.command, .control]
let completion = NSMenuItem(title: "Complete Identifier", action: #selector(completeIdentifier(_:)), keyEquivalent: " ")
completion.target = self; completion.keyEquivalentModifierMask = [.control]; completion.isEnabled = isEditable
let hints = NSMenuItem(title: "Show Parameter Hints", action: #selector(showParameterHints(_:)), keyEquivalent: " ")
hints.target = self; hints.keyEquivalentModifierMask = [.control, .shift]
let actions: [(String, Selector)] = [
("Indent", #selector(indentSource(_:))), ("Outdent", #selector(outdentSource(_:))),
("Toggle Line Comment", #selector(toggleSourceComment(_:))), ("Go to Matching Bracket", #selector(matchSourceBracket(_:)))
]
for (title, selector) in actions.reversed() {
let action = NSMenuItem(title: title, action: selector, keyEquivalent: "")
action.target = self; action.isEnabled = sourceEditingEnabled && (selector == #selector(matchSourceBracket(_:)) || isEditable)
menu.insertItem(action, at: 0)
}
menu.insertItem(.separator(), at: 0); menu.insertItem(hints, at: 0); menu.insertItem(completion, at: 0); menu.insertItem(item, at: 0)
return menu
}
}
/// A focused project builder, not a graphical editor for every GNU Make feature.
private struct CMOCProjectSettingsView: View {
@ObservedObject var model: CMOCDevelopmentModel
@Environment(\.dismiss) private var dismiss
@State private var configuration = CMOCProjectConfiguration()
@State private var recipe = CMOCMakefileSettings()
@State private var managed = false
@State private var section = "Build"
@State private var error: String?
@State private var originalMakefile = ""
@State private var configHash: String?
private let sections = ["Build", "Sources", "Libraries", "Resources", "Disk & Run", "Preview"]
var body: some View {
VStack(spacing: 0) {
HStack {
Image(systemName: "slider.horizontal.3").font(.title2).foregroundStyle(.tint)
VStack(alignment: .leading) { Text("Project Settings").font(.title2.bold()); Text(model.project?.directory.lastPathComponent ?? "").foregroundStyle(.secondary) }
Spacer()
}.padding(20)
Picker("Settings section", selection: $section) { ForEach(sections, id: \.self) { Text($0).tag($0) } }.pickerStyle(.segmented).labelsHidden().padding(.horizontal, 20).padding(.bottom, 12)
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 18) {
switch section {
case "Build": buildSettings
case "Sources": sourceSettings
case "Libraries": librarySettings
case "Resources": resourceSettings
case "Disk & Run": diskSettings
default: preview
}
}.padding(20).frame(maxWidth: .infinity, alignment: .leading)
}
if let error { Text(error).foregroundStyle(.red).textSelection(.enabled).padding(.horizontal, 20).padding(.vertical, 8) }
Divider()
HStack {
Text(managed ? "Generate an ordinary Makefile from these settings." : "Use your existing Makefile and configure its targets.").font(.caption).foregroundStyle(.secondary)
Spacer(); Button("Cancel", role: .cancel) { dismiss() }
Button(managed ? "Save & Generate" : "Save Settings") { apply() }.keyboardShortcut(.defaultAction)
}.padding(16)
}.frame(width: 760, height: 640)
.onAppear {
guard let project = model.project else { return }
configuration = project.configuration
recipe = configuration.makefileSettings ?? CMOCMakefileSettings()
if configuration.makefileSettings == nil {
recipe.sources = model.files.filter { $0.relativePath.hasSuffix(".c") }.map(\.relativePath)
recipe.executable = configuration.binary ?? "program.bin"
recipe.diskImage = configuration.diskImage
}
managed = configuration.makefileSettings != nil
originalMakefile = (try? project.readText(relativePath: configuration.makefile)) ?? ""
if let data = try? Data(contentsOf: project.directory.appendingPathComponent(CMOCProject.configurationFilename)) { configHash = CMOCProject.sha256(data) }
}
}
private var buildSettings: some View {
VStack(alignment: .leading, spacing: 16) {
Picker("Makefile management", selection: $managed) { Text("Generate from settings").tag(true); Text("Custom Makefile").tag(false) }.pickerStyle(.radioGroup)
Text("Generated projects cover C modules, libraries, generated resources and Disk BASIC disks. Custom Makefiles remain fully editable; VCC Plus does not attempt to interpret their rules.").font(.callout).foregroundStyle(.secondary)
Divider()
if managed {
LabeledContent("Executable") { TextField("program.bin", text: $recipe.executable) }
LabeledContent("Load address (hex)") { TextField("2800", text: $recipe.origin).frame(width: 140) }
LabeledContent("Highest load address (hex)") { TextField("Optional, e.g. 7F80", text: optional($recipe.limit)).frame(width: 180) }
LabeledContent("Stack bytes") { TextField("2048", value: $recipe.stackSpace, format: .number).frame(width: 140) }
Picker("Release optimization", selection: $recipe.releaseOptimization) { Text("None (−O0)").tag("-O0"); Text("Level 1").tag("-O1"); Text("Level 2").tag("-O2") }
Text("Debug builds disable optimization and retain intermediate files for verified source breakpoints.").font(.caption).foregroundStyle(.secondary)
} else {
LabeledContent("Build target") { TextField("Makefile default", text: $configuration.buildTarget) }
Text("Leave blank to let Make choose its default goal, including .DEFAULT_GOAL and included Makefiles. Set a target only to override it.").font(.caption).foregroundStyle(.secondary)
LabeledContent("Clean target") { TextField("clean", text: $configuration.cleanTarget) }
LabeledContent("Binary output") { TextField("program.bin", text: optional($configuration.binary)) }
}
Text("Build-support folders").font(.headline)
Text("Optional sibling folders copied beside the project for builds, one per line. For example ../tools. Include only folders this Makefile needs.").font(.caption).foregroundStyle(.secondary)
paths($configuration.buildSupportDirectories).frame(height: 65).accessibilityLabel("Build-support folders")
CMOCPlaytestMediaSettings(paths: $configuration.playtestDisks)
Stepper("Parallel jobs: \(configuration.jobs)", value: $configuration.jobs, in: 1...32)
Text("Project files stay portable. Builds run from an isolated copy, and opening settings never runs a command.").font(.caption).foregroundStyle(.secondary)
}.textFieldStyle(.roundedBorder)
}
private var sourceSettings: some View {
VStack(alignment: .leading, spacing: 12) {
Text("C source files").font(.headline)
Text("One project-relative path per line. Headers are tracked through compiler dependencies. Generated C files can be listed before they exist.").foregroundStyle(.secondary).font(.callout)
paths($recipe.sources).frame(height: 170).disabled(!managed)
Text("Include directories").font(.headline)
paths($recipe.includePaths).frame(height: 90).disabled(!managed)
LabeledContent("Initially opened file") { TextField("main.c", text: $configuration.entrySource) }
Text("Preprocessor definitions").font(.headline)
Text("One NAME or NAME=value per line. For example MAX_WORD_LEN=5 or DISPLAY_NAME=\"My Game\".").font(.caption).foregroundStyle(.secondary)
paths($recipe.defines).frame(height: 85).disabled(!managed)
DisclosureGroup("Additional compiler and linker options") {
VStack(alignment: .leading, spacing: 8) {
Text("Compiler options (one argument per line)").font(.caption)
paths($recipe.compilerOptions).frame(height: 70)
Text("Linker options (one argument per line)").font(.caption)
paths($recipe.linkerOptions).frame(height: 70)
}
}.disabled(!managed)
}
}
private var librarySettings: some View {
VStack(alignment: .leading, spacing: 14) {
if managed { generatedLibrarySettings; Divider() }
Group {
HStack {
Text("Bundled libraries").font(.headline)
Spacer()
Button("Add Library", systemImage: "plus") {
if let library = model.bundledLibraryCatalog.first(where: { item in !configuration.bundledLibraries.contains(where: { $0.library == item.id }) && item.available }) {
configuration.bundledLibraries.append(.init(library: library.id))
}
}.accessibilityIdentifier("cmoc.library.add")
}
Text("Use selected libraries from this app without editing the Makefile. Map its library-directory variables, or append a library to its linker-flags variable. Copies stay in the isolated build folder.").font(.callout).foregroundStyle(.secondary)
ForEach(configuration.bundledLibraries.indices, id: \.self) { index in
VStack(alignment: .leading, spacing: 8) {
HStack {
Picker("Library", selection: $configuration.bundledLibraries[index].library) {
ForEach(model.bundledLibraryCatalog) { library in
Text("\(library.id) · \(library.version)\(library.available ? "" : " — unavailable")").tag(library.id)
}
if !model.bundledLibraryCatalog.contains(where: { $0.id == configuration.bundledLibraries[index].library }) {
Text(configuration.bundledLibraries[index].library + " — unavailable").tag(configuration.bundledLibraries[index].library)
}
}
Button { configuration.bundledLibraries.remove(at: index) } label: { Image(systemName: "minus.circle") }
.help("Remove library " + configuration.bundledLibraries[index].library).accessibilityLabel("Remove library " + configuration.bundledLibraries[index].library)
}
LabeledContent("Minimum version") { TextField("Optional", text: $configuration.bundledLibraries[index].minimumVersion).accessibilityLabel("Minimum version for " + configuration.bundledLibraries[index].library) }
LabeledContent("Directory variable") { TextField("For example: DECBFILE_LIB_DIR", text: $configuration.bundledLibraries[index].directoryVariable).accessibilityLabel("Directory variable for " + configuration.bundledLibraries[index].library) }
LabeledContent("Append to linker variable") { TextField("For example: LIBS (optional)", text: $configuration.bundledLibraries[index].linkVariable).accessibilityLabel("Linker variable for " + configuration.bundledLibraries[index].library) }
if let library = model.bundledLibraryCatalog.first(where: { $0.id == configuration.bundledLibraries[index].library }) {
Text(library.license).font(.caption).foregroundStyle(.secondary)
}
}.padding(12).background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 8))
}
if configuration.bundledLibraries.isEmpty { Text("No bundled-library overrides. The Makefile controls its own dependencies.").foregroundStyle(.secondary) }
Text("Directory bindings provide headers and prebuilt archives, not a library Makefile. Linker additions preserve the Makefile’s existing flags and follow the order above. Leave either variable blank when it is not needed. Missing libraries and incompatible versions stop the build.").font(.caption).foregroundStyle(.secondary)
}
}.textFieldStyle(.roundedBorder)
}
private var generatedLibrarySettings: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Linked libraries").font(.headline)
Text("Names without the lib prefix or .a suffix; for example decbfile, bgraph, bsound or bcontrol. Use sdc to browse a CoCo SDC card or mount a disk image, bank for reserved CoCo 3 RAM, gime for double-buffered graphics, ssc for Speech/Sound, and orch90 for stereo. For joystick presses and releases, add input followed by bcontrol. Use vcccompat for TP-10 printer output and sequential cassette text files. For disk streams add decbfile after vcccompat, or add wydealloc after vcccompat for bounded allocation. Add dskcon-standalone after decbfile to use the optional standalone disk driver when included in your toolchain. It requires explicit initialization and interrupt handling; see its header and Licenses & Notices. Library order is preserved.").font(.callout).foregroundStyle(.secondary)
paths($recipe.libraries).frame(height: 80)
Text("Additional library directories").font(.headline)
paths($recipe.libraryPaths).frame(height: 60)
HStack { Text("Library subprojects").font(.headline); Spacer(); Button("Add", systemImage: "plus") { recipe.libraryProjects.append(.init()) } }
ForEach(recipe.libraryProjects.indices, id: \.self) { index in
VStack(alignment: .leading, spacing: 5) {
HStack {
TextField("Directory", text: $recipe.libraryProjects[index].directory)
TextField("Make target", text: $recipe.libraryProjects[index].target)
let directory = recipe.libraryProjects[index].directory
let action = directory.isEmpty ? "Remove library project" : "Remove library project " + directory
Button { recipe.libraryProjects.remove(at: index) } label: { Image(systemName: "minus.circle") }
.help(action).accessibilityLabel(action)
}
TextField("Archive path from project root", text: $recipe.libraryProjects[index].archive)
}.padding(8).background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
}
}.disabled(!managed).textFieldStyle(.roundedBorder)
}
private var resourceSettings: some View {
VStack(alignment: .leading, spacing: 14) {
HStack { Text("Generated resources").font(.headline); Spacer(); Button("Add Rule", systemImage: "plus") { recipe.generatedResources.append(.init()) } }
Text("Use a rule for dictionary data, fonts or generated C. Declare all inputs and outputs so Make can rebuild only when needed. Commands are shell recipes and execute only when you build.").font(.callout).foregroundStyle(.secondary)
ForEach(recipe.generatedResources.indices, id: \.self) { index in
VStack(alignment: .leading, spacing: 8) {
HStack { Text("Rule \(index + 1)").font(.headline); Spacer(); Button("Remove", systemImage: "minus.circle") { recipe.generatedResources.remove(at: index) } }
Text("Input files (one per line)").font(.caption); paths($recipe.generatedResources[index].inputs).frame(height: 55)
Text("Output files (one per line)").font(.caption); paths($recipe.generatedResources[index].outputs).frame(height: 55)
Text("Commands").font(.caption); TextEditor(text: $recipe.generatedResources[index].command).font(.system(.body, design: .monospaced)).frame(height: 85).border(.quaternary)
}.padding(10).background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 8))
}
if recipe.generatedResources.isEmpty { Text("No generated resources configured.").foregroundStyle(.secondary) }
}.disabled(!managed)
}
private var diskSettings: some View {
VStack(alignment: .leading, spacing: 12) {
if managed {
LabeledContent("Disk image output") { TextField("game.dsk (optional)", text: optional($recipe.diskImage)) }
Text("Disk contents").font(.headline)
Text("The executable is added automatically. List other files here, one per line. Disk BASIC filenames must fit its 8.3 naming rules.").font(.callout).foregroundStyle(.secondary)
paths($recipe.diskFiles).frame(height: 100)
Picker("DOS boot", selection: $recipe.diskBootMode) {
Text("None").tag(CMOCDiskBootMode.none)
Text("Run this program").tag(CMOCDiskBootMode.program)
Text("Custom bootloader").tag(CMOCDiskBootMode.custom)
}.accessibilityIdentifier("cmoc.disk-boot-mode")
if recipe.diskBootMode == .custom {
LabeledContent("Bootloader binary") { TextField("autostart.bin", text: optional($recipe.diskBootLoader)) }
Text("Type DOS to start the custom bootloader.").font(.caption).foregroundStyle(.secondary)
}
let program = DevelopmentDiskProgram.binary((recipe.executable as NSString).lastPathComponent.uppercased())
Text(program.instructions(dos: recipe.diskBootMode == .program))
.font(.caption).foregroundStyle(.secondary)
} else {
LabeledContent("Disk target") { TextField("disk", text: optional($configuration.diskTarget)) }
LabeledContent("Disk image output") { TextField("game.dsk", text: optional($configuration.diskImage)) }
}
Divider()
Picker("Launch method", selection: $configuration.launchMode) { Text("Quickload executable").tag(CMOCLaunchMode.quickload); Text("Mount disk in FD0").tag(CMOCLaunchMode.disk) }
Text("Commands after mounting").font(.headline)
paths($configuration.launchCommands).frame(height: 90)
if managed && recipe.diskBootMode == .program && configuration.launchCommands != ["DOS"] {
Button("Use DOS after mounting", systemImage: "terminal") { configuration.launchCommands = ["DOS"] }
.help("Changes only the saved launch commands; nothing runs until you choose Launch Disk.")
}
Text("For example: LOADM\"GAME\":EXEC, or DOS for a bootable disk. Launch asks first; commands require the CoCo to be waiting at BASIC. Machine profiles and RAM are not changed automatically.").font(.caption).foregroundStyle(.secondary)
}.textFieldStyle(.roundedBorder)
}
private var preview: some View {
VStack(alignment: .leading, spacing: 12) {
Text(managed ? "Generated Makefile Preview" : "Current Makefile").font(.headline)
Text(managed ? ((try? recipe.generateMakefile(makefileName: configuration.makefile)) ?? "Complete the settings to preview the Makefile.") : originalMakefile)
.font(.system(.caption, design: .monospaced)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
}
}
private func optional(_ value: Binding<String?>) -> Binding<String> { Binding(get: { value.wrappedValue ?? "" }, set: { value.wrappedValue = $0.isEmpty ? nil : $0 }) }
private func paths(_ value: Binding<[String]>) -> some View {
TextEditor(text: Binding(get: { value.wrappedValue.joined(separator: "\n") }, set: { value.wrappedValue = $0.components(separatedBy: "\n") }))
.font(.system(.body, design: .monospaced)).border(.quaternary)
}
private func apply() {
do {
func clean(_ list: [String]) -> [String] { list.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } }
recipe.sources = clean(recipe.sources); recipe.includePaths = clean(recipe.includePaths); recipe.libraries = clean(recipe.libraries)
recipe.libraryPaths = clean(recipe.libraryPaths); recipe.diskFiles = clean(recipe.diskFiles)
recipe.defines = clean(recipe.defines); recipe.compilerOptions = clean(recipe.compilerOptions); recipe.linkerOptions = clean(recipe.linkerOptions)
for i in recipe.generatedResources.indices { recipe.generatedResources[i].inputs = clean(recipe.generatedResources[i].inputs); recipe.generatedResources[i].outputs = clean(recipe.generatedResources[i].outputs) }
configuration.launchCommands = clean(configuration.launchCommands)
configuration.buildSupportDirectories = clean(configuration.buildSupportDirectories)
configuration.playtestDisks = clean(configuration.playtestDisks)
var makefile: String?
if managed {
makefile = try recipe.generateMakefile(makefileName: configuration.makefile)
configuration.makefileSettings = recipe; configuration.binary = recipe.executable
configuration.diskImage = recipe.diskImage; configuration.diskTarget = recipe.diskImage == nil ? nil : "disk"
configuration.buildTarget = recipe.diskImage == nil ? "build" : "disk"; configuration.cleanTarget = "clean"
configuration.configurations = [.init(name: "Debug"), .init(name: "Release", makeArguments: ["VCC_CONFIGURATION=Release"])]
if makefile != originalMakefile {
let alert = NSAlert(); alert.messageText = "Replace the project's Makefile?"
alert.informativeText = "The Preview tab shows the generated rules. Any custom rules in the current Makefile will be replaced; a backup is kept in the project’s .vccplus-build folder."
alert.addButton(withTitle: "Replace Makefile"); alert.addButton(withTitle: "Cancel")
guard alert.runModal() == .alertFirstButtonReturn else { return }
}
} else { configuration.makefileSettings = nil }
try model.applyProjectSettings(configuration, makefile: makefile, expectedMakefileHash: CMOCProject.sha256(Data(originalMakefile.utf8)), expectedConfigHash: configHash)
dismiss()
} catch { self.error = error.localizedDescription }
}
}
private struct CMOCNavigatorNode: Identifiable {
let id: String
let name: String
let file: CMOCProjectFile?
let children: [CMOCNavigatorNode]?
static func tree(_ files: [CMOCProjectFile], prefix: String = "") -> [Self] {
let direct = files.filter { $0.relativePath.hasPrefix(prefix) }
let names = Set(direct.map { String($0.relativePath.dropFirst(prefix.count).split(separator: "/").first ?? "") }).sorted()
return names.compactMap { name in
guard !name.isEmpty else { return nil }
let path = prefix + name
if let file = direct.first(where: { $0.relativePath == path }) { return Self(id: path, name: name, file: file, children: nil) }
return Self(id: path, name: name, file: nil, children: tree(direct, prefix: path + "/"))
}
}
}
/// Shared by the native project form and its unshown layout regression fixture.
struct CMOCPlaytestMediaSettings: View {
@Binding var paths: [String]
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("Additional playtest disk outputs").font(.headline)
Text("Optional project-relative .dsk or .os9 products, one per line (up to eight, 512 KB each). The Make recipe must build them. Reviewed assistant playtests can exchange private copies in FD0 while paused; the primary boot disk is listed separately.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
TextEditor(text: Binding(get: { paths.joined(separator: "\n") },
set: { paths = $0.components(separatedBy: "\n") }))
.font(.system(.body, design: .monospaced)).frame(height: 65).border(.quaternary)
.accessibilityLabel("Additional playtest disk outputs")
}
}
}