Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,330 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
enum AppCredits {
|
||||
static func resource(_ name: String, extension ext: String) -> URL? {
|
||||
Bundle.main.url(forResource: name, withExtension: ext, subdirectory: "About")
|
||||
}
|
||||
static func text(_ name: String) -> String {
|
||||
guard let url = resource(name, extension: "txt"), let text = try? String(contentsOf: url, encoding: .utf8) else {
|
||||
return "This build is missing its bundled \(name) notice. Please rebuild or reinstall the complete application."
|
||||
}
|
||||
return text
|
||||
}
|
||||
static var hasDiskLibrary: Bool {
|
||||
guard let resources = Bundle.main.resourceURL else { return false }
|
||||
return FileManager.default.fileExists(atPath: resources.appendingPathComponent("Toolchain/LICENSES/DECBFILE-NOTICE.txt").path)
|
||||
}
|
||||
static var hasStandaloneDiskLibrary: Bool {
|
||||
guard let resources = Bundle.main.resourceURL else { return false }
|
||||
return FileManager.default.fileExists(atPath: resources.appendingPathComponent("Toolchain/LICENSES/DSKCON-STANDALONE-NOTICE.txt").path)
|
||||
}
|
||||
static var diskLibraryNotice: String {
|
||||
let core = "The ROM-backed core of decbfile, by Pierre Sarrazin, is public-domain software and retains its upstream no-warranty notice. It provides disk-file access through the Disk BASIC ROM loaded in the emulated CoCo. That ROM is separate third-party software and is not covered by the library’s public-domain dedication or VCC Plus’s GPL license."
|
||||
guard hasStandaloneDiskLibrary else { return core }
|
||||
return core + "\n\nThis build also includes Pierre Sarrazin’s standalone floppy disk driver as an optional development library. His upstream notice declares it public domain except for the portions taken from Disk Extended Color BASIC. Those portions are separate third-party code and are not covered by VCC Plus’s GPL license or the library’s public-domain dedication. Their respective owners retain their rights. Linking this driver is an explicit project choice; it allows disk access without keeping Disk BASIC mapped. Rights-holder inquiries or removal requests may be sent to [email protected]."
|
||||
}
|
||||
static var developmentTools: String {
|
||||
let introduction = "CMOC by Pierre Sarrazin · LWTools by William Astle and contributors · mcpp by Kiyoshi Matsui and contributors · GNU Make by the Free Software Foundation and contributors · Perl by Larry Wall and contributors.\n\nCMOC, LWTools and GNU Make are GPL-licensed. mcpp uses a BSD license. Perl is available under the GNU GPL version 1 or later, or the Artistic License. Exact upstream source snapshots and licenses are retained in the repository. The bundled toolchain excludes the separately supplied floating-point ROM. Any included standalone Disk BASIC-derived driver is identified separately below.\n\n"
|
||||
guard let base = Bundle.main.resourceURL?.appendingPathComponent("Toolchain/LICENSES"),
|
||||
let files = try? FileManager.default.contentsOfDirectory(at: base, includingPropertiesForKeys: nil) else {
|
||||
return introduction + "The optional development toolchain is not included in this build."
|
||||
}
|
||||
return introduction + (hasDiskLibrary ? diskLibraryNotice + "\n\n" : "") + files.sorted { $0.lastPathComponent < $1.lastPathComponent }.map {
|
||||
"—— " + $0.lastPathComponent + " ——\n\n" + ((try? String(contentsOf: $0, encoding: .utf8)) ?? "Notice unavailable.")
|
||||
}.joined(separator: "\n\n")
|
||||
}
|
||||
static var version: String {
|
||||
let info = Bundle.main.infoDictionary ?? [:]
|
||||
return "Version \(info["CFBundleShortVersionString"] as? String ?? "Development") (build \(info["CFBundleVersion"] as? String ?? "—"))"
|
||||
}
|
||||
}
|
||||
|
||||
private struct CreditArtwork: View {
|
||||
let name: String
|
||||
var ext = "pdf"
|
||||
let label: String
|
||||
var body: some View {
|
||||
if let url = AppCredits.resource(name, extension: ext), let image = NSImage(contentsOf: url) {
|
||||
Image(nsImage: image).resizable().scaledToFit().accessibilityLabel(label)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Both windows read the same approved notices; no duplicate legal copy in views.
|
||||
private struct LegalNoticesView: View {
|
||||
private let notices = [
|
||||
("Copyright & Trademarks", "CopyrightNotice"),
|
||||
("Original Artwork", "ArtworkNotice"),
|
||||
("ROMs & Third-Party Software", "ROMNotice"),
|
||||
("DriveWire protocol", "DriveWireCredit")
|
||||
]
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
ForEach(notices, id: \.1) { title, resource in
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(title).font(.headline).accessibilityAddTraits(.isHeader)
|
||||
Text(AppCredits.text(resource)).textSelection(.enabled)
|
||||
if resource == "DriveWireCredit" {
|
||||
Link("DriveWire project and specification", destination: URL(string: "https://github.com/DrPitre/DriveWire")!)
|
||||
} else if resource == "ArtworkNotice" {
|
||||
Link("SockMaster’s CoCo 3 and CM-8 illustration on CoCopedia",
|
||||
destination: URL(string: "https://www.cocopedia.com/wiki/File:COCO-CM8.GIF")!)
|
||||
}
|
||||
}
|
||||
}
|
||||
if AppCredits.hasDiskLibrary {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Disk File Library").font(.headline).accessibilityAddTraits(.isHeader)
|
||||
Text(AppCredits.diskLibraryNotice).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
Link("Contact: [email protected]", destination: URL(string: "mailto:[email protected]")!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AboutVCCView: View {
|
||||
@Environment(\.colorScheme) private var colorScheme
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
var body: some View {
|
||||
ScrollViewReader { proxy in
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 12) {
|
||||
Button { proxy.scrollTo("mac-credits", anchor: .top) } label: { Label("Mac credits", systemImage: "desktopcomputer") }
|
||||
.accessibilityIdentifier("about-mac-credits")
|
||||
Button { proxy.scrollTo("notices", anchor: .top) } label: { Label("Notices", systemImage: "doc.text") }
|
||||
.accessibilityIdentifier("about-notices")
|
||||
Button { proxy.scrollTo("windows-credits", anchor: .top) } label: { Label("Windows credits", systemImage: "person.2") }
|
||||
.accessibilityIdentifier("about-windows-credits")
|
||||
Spacer(minLength: 4)
|
||||
Button { openWindow(id: "credits") } label: { Label("Licenses…", systemImage: "text.book.closed") }
|
||||
.accessibilityIdentifier("about-licenses")
|
||||
}.buttonStyle(.bordered).controlSize(.small).padding(14)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 22) {
|
||||
HStack(alignment: .top, spacing: 20) {
|
||||
Image(nsImage: NSApplication.shared.applicationIconImage)
|
||||
.resizable().scaledToFit().frame(width: 96, height: 96)
|
||||
.accessibilityLabel("VCC Plus app icon").accessibilityIdentifier("about-app-icon")
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("VCC Plus OSS").font(.title.bold()).accessibilityAddTraits(.isHeader)
|
||||
Text(AppCredits.version).foregroundStyle(.secondary)
|
||||
Button("Release History…") { openWindow(id: "release-history") }
|
||||
.accessibilityIdentifier("about-release-history")
|
||||
Text("Designed by Brian Holman").font(.headline)
|
||||
Text("Sponsored by Dezota LLC").font(.headline)
|
||||
}
|
||||
}.id("mac-credits")
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("""
|
||||
VCC Plus brings the wonder of the Color Computer to a new generation—and new possibilities to those who grew up with it. Reimagined for the Mac, it combines classic computing with a browsable software library, an integrated C development environment, and a native interface.
|
||||
|
||||
Built on decades of outstanding work by the Color Computer community and developed with the assistance of OpenAI’s ChatGPT and Codex, VCC Plus connects that rich legacy with today’s tools—honoring the creators, preserving their attributions, and respecting the licenses that make this work possible.
|
||||
""")
|
||||
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
.textSelection(.enabled)
|
||||
HStack(alignment: .center) {
|
||||
CreditArtwork(name: "founder", label: "Brian Holman, founder illustration")
|
||||
.frame(width: 64, height: 85).accessibilityIdentifier("about-founder")
|
||||
Spacer(minLength: 24)
|
||||
Link(destination: URL(string: "https://www.dezota.com")!) {
|
||||
CreditArtwork(name: colorScheme == .dark ? "dezota-dark" : "dezota", label: "Dezota LLC corporate logo").frame(width: 156, height: 36)
|
||||
}.buttonStyle(.plain).help("Open the Dezota LLC website").accessibilityLabel("Dezota LLC website")
|
||||
.accessibilityIdentifier("about-sponsor")
|
||||
}.frame(maxWidth: .infinity)
|
||||
}
|
||||
Divider()
|
||||
LegalNoticesView().id("notices")
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Text("Original Windows VCC").font(.title2.bold()).accessibilityAddTraits(.isHeader)
|
||||
CreditArtwork(name: "windows-vcc", ext: "bmp", label: "Original VCC logo")
|
||||
.frame(height: 82).frame(maxWidth: .infinity)
|
||||
HStack(spacing: 24) {
|
||||
CreditArtwork(name: "windows-founders", ext: "bmp", label: "Artwork from the original Windows About window").frame(width: 130, height: 100)
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("VCC — Virtual Color Computer").font(.headline)
|
||||
Text("Windows VCC Version 2.1.10.0").foregroundStyle(.secondary)
|
||||
Text("Another classic computer canceled before it's time!").italic()
|
||||
}
|
||||
}
|
||||
Text(AppCredits.text("WindowsAbout")).textSelection(.enabled)
|
||||
Link("Original VCC project", destination: URL(string: "https://github.com/VCCE/VCC")!)
|
||||
}.id("windows-credits")
|
||||
}.frame(maxWidth: 700, alignment: .leading).padding(24).frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
}.frame(minWidth: 620, minHeight: 520)
|
||||
}
|
||||
}
|
||||
|
||||
struct LicenseCreditsView: View {
|
||||
@State private var selected: String? = "Overview"
|
||||
private let notices = [
|
||||
("Overview", "VCC Plus Notices"),
|
||||
("GPL", "GNU General Public License"),
|
||||
("ThirdPartyNotices", "Third-Party Notices"),
|
||||
("WindowsAbout", "Original Windows VCC"),
|
||||
("DevelopmentTools", "C Development Tools")
|
||||
]
|
||||
var body: some View {
|
||||
HSplitView {
|
||||
List(selection: $selected) {
|
||||
Section("Documents") {
|
||||
ForEach(notices, id: \.0) { key, title in
|
||||
Label(title, systemImage: key == "GPL" ? "text.book.closed" : "doc.text")
|
||||
.padding(.vertical, 5).tag(key)
|
||||
.accessibilityIdentifier("license-document-" + key)
|
||||
}
|
||||
}
|
||||
}.listStyle(.sidebar).frame(minWidth: 180, idealWidth: 210, maxWidth: 250)
|
||||
.accessibilityLabel("License documents")
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
Text(notices.first { $0.0 == (selected ?? "Overview") }?.1 ?? "VCC Plus Notices")
|
||||
.font(.headline).padding(18).accessibilityAddTraits(.isHeader)
|
||||
Divider()
|
||||
ScrollView {
|
||||
Group {
|
||||
if selected == nil || selected == "Overview" { LegalNoticesView() }
|
||||
else { Text(selected == "DevelopmentTools" ? AppCredits.developmentTools : AppCredits.text(selected!)).textSelection(.enabled) }
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).padding(20)
|
||||
}.id(selected)
|
||||
}.frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity)
|
||||
}.frame(minWidth: 640, minHeight: 500)
|
||||
}
|
||||
}
|
||||
|
||||
private struct KeyboardHelpSection {
|
||||
let title: String
|
||||
let symbol: String
|
||||
let commands: [(String, String)]
|
||||
let paragraphs: [String]
|
||||
func matches(_ query: String) -> Bool {
|
||||
query.isEmpty || ([title] + commands.flatMap { [$0.0, $0.1] } + paragraphs)
|
||||
.contains { $0.localizedCaseInsensitiveContains(query) }
|
||||
}
|
||||
}
|
||||
|
||||
struct KeyboardHelpView: View {
|
||||
@State private var search = ""
|
||||
private let sections: [KeyboardHelpSection] = [
|
||||
KeyboardHelpSection(title: "Focus & CoCo keys", symbol: "keyboard", commands: [
|
||||
("⌘1", "Show Emulator — reopen or bring it forward"),
|
||||
("⌥⌘K", "Focus the CoCo display"),
|
||||
("⌥⌘U", "Focus Mac controls")
|
||||
], paragraphs: [
|
||||
"Use Input → Focus Mac Controls to leave the CoCo display, then Tab and Shift-Tab to move through native controls. Enable Keyboard navigation in macOS System Settings → Keyboard if needed. Space activates a focused button; Escape dismisses a menu or popover. Input → Focus CoCo Display returns typing to the guest.",
|
||||
"System view’s Devices list and the Media, Machine and Input menus provide native alternatives to the illustrated controls. VoiceOver can read the Mac controls, labels and media status. It cannot interpret arbitrary CoCo graphics or applications; Copy CoCo Screen Text works only in supported text modes.",
|
||||
"Return → ENTER · Escape → BREAK · Home → CLEAR · Delete → backspace/left · Arrow keys → CoCo arrows · F1/F2 → CoCo F1/F2. Use Fn or Globe with function keys if macOS assigns them to hardware controls.",
|
||||
"Input → Keyboard and Joysticks offers Natural, CoCo and Compact layouts. Natural uses the Mac’s typed characters; CoCo follows physical US CoCo key positions. In Compact mode, Tab supplies CLEAR and the unshifted grave key supplies BREAK. Control and Option supply the CoCo Control and Alt keys.",
|
||||
"Keyboard joystick assignments reserve their configured direction/fire keys. Change the port’s input source when you need those keys for typing. Held keys are released when the display loses focus."
|
||||
]),
|
||||
KeyboardHelpSection(title: "Machine", symbol: "cpu", commands: [
|
||||
("⇧⌘O", "Choose a CoCo 3 system ROM"),
|
||||
("⇧⌘P", "Configuration Profiles"),
|
||||
("⌘,", "Machine Settings"),
|
||||
("⇧⌘F", "Emulator window: toggle fast-forward (sound is silenced)"),
|
||||
("⌘Q", "Quit, with unsaved-media protection")
|
||||
], paragraphs: [
|
||||
"Windows VCC’s F3–F12 application shortcuts are not mapped wholesale on Mac. Use Run/Pause and Restart in the toolbar, Display for video output, Machine for fast-forward and CPU settings, Cartridge for devices, and View for full screen. F1/F2 remain guest keys."
|
||||
]),
|
||||
KeyboardHelpSection(title: "Media", symbol: "externaldrive", commands: [
|
||||
("⌘O", "Open Media; choose its destination"),
|
||||
("⇧⌘B", "Load and run a CoCo binary"),
|
||||
("⇧⌘D", "Floppy Disks"),
|
||||
("⇧⌘T", "Cassette")
|
||||
], paragraphs: [
|
||||
"Drop one media file onto the main display, a System drive or cartridge, or a drive row. Choose the destination and confirm. File → Open Recent Media remembers the last 12 successful file selections. Clear Recent Media removes history, not files or mounted media."
|
||||
]),
|
||||
KeyboardHelpSection(title: "Display", symbol: "display", commands: [
|
||||
("⇧⌘E", "Expand/return the monitor in System view"),
|
||||
("⇧⌘S", "Save the active CoCo picture as a PNG")
|
||||
], paragraphs: [
|
||||
"Display → Display Settings offers sharp, smooth and integer-pixel scaling, plus optional scanlines. These remembered Mac preferences preserve the running session. Save CoCo Screen captures the current active picture as a PNG at native resolution without scaling, scanlines or the surrounding window; the CoCo keeps running while you choose where to save."
|
||||
]),
|
||||
KeyboardHelpSection(title: "BASIC Development", symbol: "terminal", commands: [
|
||||
("⌃⇧H", "Quick Help for the command at the insertion point"),
|
||||
("Option-click a command", "Open its BASIC reference topic"),
|
||||
("⌃Space", "Show BASIC keyword completions"),
|
||||
("Tab", "Accept a faint keyword suggestion"),
|
||||
("⌘F in the reference", "Find a command or topic")
|
||||
], paragraphs: [
|
||||
"Develop → BASIC Quick Reference is available offline. Browse syntax, parameters, related commands and error explanations. RGB-DOS and SDC-DOS additions are labeled separately. A topic stays open while you edit.",
|
||||
"Open Example creates a separate editable workspace with its own recovery draft. Opening it does not load or run anything. Use Run when ready; the existing safeguards apply before replacing the CoCo program. Only the workspace that most recently loaded a program controls its BASIC debugger."
|
||||
]),
|
||||
KeyboardHelpSection(title: "Debugger", symbol: "ladybug", commands: [
|
||||
("⌥⌘D", "Show Debugger"),
|
||||
("⌥⌘R", "Pause / continue execution"),
|
||||
("⌥⌘I", "Step one instruction while paused")
|
||||
], paragraphs: []),
|
||||
KeyboardHelpSection(title: "Find in a source editor", symbol: "magnifyingglass", commands: [
|
||||
("⌘F", "Find in the current BASIC, C or assembly file"),
|
||||
("⌥⌘F", "Find and replace in this file"),
|
||||
("⌘G", "Select the next match"),
|
||||
("⇧⌘G", "Select the previous match"),
|
||||
("⌘E", "Use the selected source text for Find"),
|
||||
("Escape", "Close the find bar and return to the source")
|
||||
], paragraphs: [
|
||||
"Replace edits one selected match. Replace All in File edits the current file in one Undo step. You can search a read-only header. To search across C project files, choose the magnifying-glass tab in the left sidebar."
|
||||
]),
|
||||
KeyboardHelpSection(title: "C Development", symbol: "curlybraces.square", commands: [
|
||||
("⌥⌘C", "Open C Development"),
|
||||
("⇧⌘F", "C workspace: Find in Project")
|
||||
], paragraphs: [
|
||||
"Build uses the current editor contents, including unsaved edits. Save All writes your files to disk. For a source-debug build, set a breakpoint on an executable line, run to it, then use the C stepping controls, call stack, Variables and Watches. Open Debugger to inspect individual machine instructions, registers or memory."
|
||||
]),
|
||||
KeyboardHelpSection(title: "Clipboard", symbol: "doc.on.clipboard", commands: [
|
||||
("⌘C / ⌘V", "Copy screen / paste text when the CoCo display has focus"),
|
||||
("⇧⌘C / ⇧⌘V", "Explicit CoCo screen copy / text paste")
|
||||
], paragraphs: [
|
||||
"Edit offers BASIC Merge and Replace, with confirmation. Wait at the BASIC prompt first. Neither starts the program. Text paste executes Return only where the clipboard contains a newline. Cancel Paste, Pause or a CoCo key stops remaining input; already entered text is retained. BASIC lines are limited to 249 characters to prevent truncation."
|
||||
]),
|
||||
]
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 12) {
|
||||
Label("Find a shortcut or topic", systemImage: "keyboard").font(.headline)
|
||||
Spacer()
|
||||
TextField("Search keyboard help", text: $search).textFieldStyle(.roundedBorder)
|
||||
.frame(maxWidth: 260).accessibilityLabel("Search keyboard help")
|
||||
.accessibilityIdentifier("keyboard-help-search")
|
||||
}.padding(16)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Text("Click the CoCo display before typing. Native text fields keep their usual Mac editing shortcuts.")
|
||||
.foregroundStyle(.secondary)
|
||||
ForEach(sections.filter { $0.matches(search.trimmingCharacters(in: .whitespacesAndNewlines)) }, id: \.title) { section in
|
||||
SecondaryCard {
|
||||
Label(section.title, systemImage: section.symbol).font(.headline)
|
||||
.accessibilityAddTraits(.isHeader)
|
||||
Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 9) {
|
||||
ForEach(section.commands, id: \.0) { key, action in
|
||||
GridRow {
|
||||
Text(key).font(.system(.body, design: .monospaced))
|
||||
.frame(width: 110, alignment: .leading)
|
||||
Text(action).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !section.paragraphs.isEmpty {
|
||||
SecondaryHelp(title: section.title == "Focus & CoCo keys" ? "Navigation and CoCo key layouts" : "Using " + section.title.lowercased()) {
|
||||
ForEach(section.paragraphs, id: \.self) { paragraph in
|
||||
Text(paragraph).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sections.contains(where: { $0.matches(search.trimmingCharacters(in: .whitespacesAndNewlines)) }) {
|
||||
Label("No matching shortcuts or topics", systemImage: "magnifyingglass")
|
||||
.foregroundStyle(.secondary).padding(.vertical, 20)
|
||||
}
|
||||
}.padding(20).frame(maxWidth: 760, alignment: .leading).frame(maxWidth: .infinity)
|
||||
}
|
||||
}.frame(minWidth: 620, minHeight: 500)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import ImageIO
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// ImageIO can be decoding a large diagram when the user moves through several rows.
|
||||
/// Only one bitmap is decoded at a time, and superseded selections skip the decode.
|
||||
actor ArchivePreviewDecoder {
|
||||
static let shared = ArchivePreviewDecoder()
|
||||
|
||||
func read(_ url: URL, format: String, number: Int) throws -> ArchiveInlineContent {
|
||||
try Task.checkCancellation()
|
||||
if format == "image" { return try ArchiveInlineContent.loadImage(at: url, number: number) }
|
||||
return try ArchiveInlineContent.loadText(at: url)
|
||||
}
|
||||
}
|
||||
|
||||
enum ArchiveInlineContent: Sendable {
|
||||
case image(CGImage)
|
||||
case text(String)
|
||||
case worksheet(String)
|
||||
|
||||
/// Decode away from the main actor. Some original diagrams are over 260 megapixels.
|
||||
static func loadImage(at url: URL, number: Int = 1) throws -> Self {
|
||||
let options = [kCGImageSourceShouldCache: false] as CFDictionary
|
||||
guard number > 0, let source = CGImageSourceCreateWithURL(url as CFURL, options),
|
||||
let type = CGImageSourceGetType(source) as String?,
|
||||
[UTType.jpeg, .png, .gif, .tiff, .bmp, .webP].contains(where: { $0.identifier == type }) else {
|
||||
throw PreviewError.image
|
||||
}
|
||||
if let image = thumbnail(source, index: number - 1) { return .image(image) }
|
||||
if type == UTType.tiff.identifier, number == 1,
|
||||
let corrected = tiffWithoutDuplicatePalette(at: url), let image = thumbnail(corrected, index: 0) {
|
||||
return .image(image)
|
||||
}
|
||||
throw PreviewError.image
|
||||
}
|
||||
|
||||
private static func thumbnail(_ source: CGImageSource, index: Int) -> CGImage? {
|
||||
let options = [kCGImageSourceShouldCache: false] as CFDictionary
|
||||
guard index < CGImageSourceGetCount(source),
|
||||
let properties = CGImageSourceCopyPropertiesAtIndex(source, index, options) as? [CFString: Any],
|
||||
let width = properties[kCGImagePropertyPixelWidth] as? Int, width > 0,
|
||||
let height = properties[kCGImagePropertyPixelHeight] as? Int, height > 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Bound the decoded bitmap to 16 megapixels, retaining aspect and EXIF orientation.
|
||||
let ratio = min(1, sqrt(16_000_000 / (Double(width) * Double(height))))
|
||||
let longest = max(1, Int((Double(max(width, height)) * ratio).rounded(.down)))
|
||||
let thumbnailOptions: [CFString: Any] = [
|
||||
kCGImageSourceCreateThumbnailFromImageAlways: true,
|
||||
kCGImageSourceCreateThumbnailWithTransform: true,
|
||||
kCGImageSourceThumbnailMaxPixelSize: longest,
|
||||
kCGImageSourceShouldCacheImmediately: true
|
||||
]
|
||||
return CGImageSourceCreateThumbnailAtIndex(source, index, thumbnailOptions as CFDictionary)
|
||||
}
|
||||
|
||||
/// The Glenside IDE schematic has two ColorMap tags in its classic TIFF directory.
|
||||
/// Keep the first palette, as libtiff does, in a bounded in-memory copy for ImageIO.
|
||||
private static func tiffWithoutDuplicatePalette(at url: URL) -> CGImageSource? {
|
||||
let limit = 8 * 1024 * 1024
|
||||
guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= limit,
|
||||
var bytes = try? Data(contentsOf: url), bytes.count >= 8, bytes.count <= limit else { return nil }
|
||||
let littleEndian = bytes.starts(with: [0x49, 0x49, 42, 0])
|
||||
guard littleEndian || bytes.starts(with: [0x4d, 0x4d, 0, 42]) else { return nil }
|
||||
func integer(at start: Int, count: Int) -> Int {
|
||||
(0..<count).reduce(0) { result, index in
|
||||
let offset = littleEndian ? count - 1 - index : index
|
||||
return (result << 8) | Int(bytes[start + offset])
|
||||
}
|
||||
}
|
||||
let directory = integer(at: 4, count: 4)
|
||||
guard directory >= 8, directory + 2 <= bytes.count else { return nil }
|
||||
let count = integer(at: directory, count: 2)
|
||||
let first = directory + 2
|
||||
let end = first + count * 12
|
||||
guard count >= 2, end + 4 <= bytes.count else { return nil }
|
||||
for entry in stride(from: first + 12, to: end, by: 12) {
|
||||
guard integer(at: entry - 12, count: 2) == 320, integer(at: entry, count: 2) == 320 else { continue }
|
||||
let values = integer(at: entry + 4, count: 4)
|
||||
guard (6...(3 * 65_536)).contains(values), values.isMultiple(of: 3),
|
||||
(values / 3).nonzeroBitCount == 1,
|
||||
[entry - 12, entry].allSatisfy({ tag in
|
||||
let palette = integer(at: tag + 8, count: 4)
|
||||
return integer(at: tag + 2, count: 2) == 3 && integer(at: tag + 4, count: 4) == values
|
||||
&& palette >= 8 && palette + 2 * values <= bytes.count
|
||||
}) else { return nil }
|
||||
// Slide just the remaining directory entries and the next-directory pointer.
|
||||
// Strip offsets and all data elsewhere in the file retain their positions.
|
||||
let rest = bytes[(entry + 12)..<(end + 4)]
|
||||
bytes.replaceSubrange(entry..<(entry + rest.count), with: rest)
|
||||
bytes[directory + (littleEndian ? 0 : 1)] = UInt8(truncatingIfNeeded: count - 1)
|
||||
bytes[directory + (littleEndian ? 1 : 0)] = UInt8((count - 1) >> 8)
|
||||
return CGImageSourceCreateWithData(bytes as CFData, nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
static func loadText(at url: URL) throws -> Self {
|
||||
let limit = 8 * 1024 * 1024
|
||||
guard let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= limit else { throw PreviewError.text }
|
||||
let data = try Data(contentsOf: url, options: .mappedIfSafe)
|
||||
guard data.count <= limit else { throw PreviewError.text }
|
||||
// A number of the Archive's floppy-era text files have NUL/EOF sector padding.
|
||||
let text: String?
|
||||
if data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) {
|
||||
text = String(data: data, encoding: .utf16)
|
||||
} else {
|
||||
var end = data.endIndex
|
||||
while end > data.startIndex {
|
||||
let last = data[end - 1]
|
||||
guard last == 0 || last == 0x1a || last == 0xff else { break }
|
||||
end -= 1
|
||||
}
|
||||
if !data[end...].contains(0) && !data[end...].contains(0x1a) { end = data.endIndex }
|
||||
let bytes = data[..<end]
|
||||
let start = bytes.starts(with: [0xef, 0xbb, 0xbf]) ? bytes.dropFirst(3) : bytes
|
||||
text = String(data: start, encoding: .utf8)
|
||||
?? String(data: start, encoding: .windowsCP1252)
|
||||
?? String(data: start, encoding: .isoLatin1)
|
||||
}
|
||||
guard let text else { throw PreviewError.text }
|
||||
return .text(text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n"))
|
||||
}
|
||||
|
||||
private enum PreviewError: LocalizedError {
|
||||
case image, text
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .image: return "The image could not be opened at the cited location."
|
||||
case .text: return "The original could not be read as an Archive text document."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ArchiveInlinePreview: View {
|
||||
let content: ArchiveInlineContent
|
||||
let title: String
|
||||
|
||||
var body: some View {
|
||||
switch content {
|
||||
case .image(let image): ArchiveInlineImage(image: image, title: title)
|
||||
case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title)
|
||||
case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ArchiveInlineImage: View {
|
||||
let image: CGImage
|
||||
let title: String
|
||||
@State private var zoom = 0
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Button("Fit Image") { zoom = 0 }.disabled(zoom == 0)
|
||||
Button { zoom -= 1 } label: { Image(systemName: "minus.magnifyingglass") }
|
||||
.disabled(zoom == 0).accessibilityLabel("Zoom out")
|
||||
Button { zoom += 1 } label: { Image(systemName: "plus.magnifyingglass") }
|
||||
.disabled(zoom >= 5).accessibilityLabel("Zoom in")
|
||||
Spacer()
|
||||
}.padding(6)
|
||||
Divider()
|
||||
GeometryReader { geometry in
|
||||
let width = CGFloat(image.width), height = CGFloat(image.height)
|
||||
let fit = min(1, min(geometry.size.width / width, geometry.size.height / height))
|
||||
let scale = fit * pow(2.0, CGFloat(zoom))
|
||||
ScrollView([.horizontal, .vertical]) {
|
||||
Image(image, scale: 1, label: Text(title))
|
||||
.resizable()
|
||||
.frame(width: width * scale, height: height * scale)
|
||||
.accessibilityIdentifier("archive-inline-image")
|
||||
.frame(minWidth: geometry.size.width, minHeight: geometry.size.height)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ArchiveInlineText: NSViewRepresentable {
|
||||
let text: String
|
||||
let worksheet: Bool
|
||||
let title: String
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSTextView.scrollableTextView()
|
||||
guard let view = scroll.documentView as? NSTextView else { return scroll }
|
||||
view.isEditable = false
|
||||
view.isSelectable = true
|
||||
view.isRichText = false
|
||||
view.usesFindBar = true
|
||||
view.isIncrementalSearchingEnabled = true
|
||||
view.textContainerInset = NSSize(width: 12, height: 10)
|
||||
view.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)
|
||||
view.textColor = .textColor
|
||||
view.backgroundColor = .textBackgroundColor
|
||||
view.setAccessibilityIdentifier("archive-inline-text")
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let view = scroll.documentView as? NSTextView else { return }
|
||||
view.setAccessibilityLabel(title)
|
||||
guard view.string != text else { return }
|
||||
view.string = text
|
||||
scroll.hasHorizontalScroller = worksheet
|
||||
view.isHorizontallyResizable = worksheet
|
||||
view.textContainer?.widthTracksTextView = !worksheet
|
||||
if worksheet, let font = view.font {
|
||||
// The indexed worksheet starts each row with its original row number. Align
|
||||
// columns for reading while keeping the original tabs in a copied selection.
|
||||
var widths: [CGFloat] = []
|
||||
for row in text.split(separator: "\n") {
|
||||
for (index, cell) in row.components(separatedBy: "\t").enumerated() {
|
||||
if index == widths.count { widths.append(0) }
|
||||
widths[index] = max(widths[index], (cell as NSString).size(withAttributes: [.font: font]).width)
|
||||
}
|
||||
}
|
||||
var location: CGFloat = 0
|
||||
let style = NSMutableParagraphStyle()
|
||||
style.lineBreakMode = .byClipping
|
||||
style.tabStops = widths.map { width in
|
||||
location += ceil(width) + 18
|
||||
return NSTextTab(textAlignment: .left, location: location)
|
||||
}
|
||||
let width = location + 2 * (view.textContainerInset.width + 6)
|
||||
view.textContainer?.containerSize = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
|
||||
view.setFrameSize(NSSize(width: max(scroll.contentSize.width, width), height: view.frame.height))
|
||||
view.textStorage?.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: (text as NSString).length))
|
||||
}
|
||||
view.setSelectedRange(NSRange(location: 0, length: 0))
|
||||
scroll.contentView.scroll(to: .zero)
|
||||
scroll.reflectScrolledClipView(scroll.contentView)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
struct ArchiveMemberRange: Hashable, Sendable {
|
||||
let offset, compressedBytes: Int64
|
||||
let method: Int
|
||||
let archiveBytes: Int64
|
||||
}
|
||||
|
||||
struct ArchiveReaderSection: Sendable {
|
||||
let number: Int
|
||||
let label: String?
|
||||
let text: String
|
||||
}
|
||||
|
||||
struct ArchiveDocument: Identifiable, Hashable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let collection: String
|
||||
let sourceURL: URL
|
||||
let memberPath: String?
|
||||
let pageCount: Int?
|
||||
let deliveryURL: URL?
|
||||
let deliveryBytes: Int64?
|
||||
var format: String = "pdf"
|
||||
var sourceBytes: Int64?
|
||||
var memberRange: ArchiveMemberRange?
|
||||
var deliverySHA256: String? { deliveryURL == nil ? nil : id }
|
||||
var citation: String { cite(nil, at: sourceURL) }
|
||||
|
||||
func cite(_ locator: String?, at url: URL) -> String {
|
||||
([title, memberPath, locator, "Color Computer Archive", url.absoluteString] as [String?])
|
||||
.compactMap { $0 }.joined(separator: " · ")
|
||||
}
|
||||
}
|
||||
|
||||
struct ArchiveHit: Identifiable, Hashable, Sendable {
|
||||
let id: String
|
||||
let document: ArchiveDocument
|
||||
let page: Int?
|
||||
let locator: String
|
||||
let ocr: Bool
|
||||
let sourceURL: URL
|
||||
var locationNumber: Int = 1
|
||||
var citation: String { document.cite(locator, at: sourceURL) }
|
||||
}
|
||||
|
||||
struct ArchiveExample: Identifiable, Hashable, Sendable {
|
||||
let title: String
|
||||
let kind: String
|
||||
let language: String
|
||||
let author: String
|
||||
let provenance: String
|
||||
let source: String
|
||||
let sourceSHA256: String
|
||||
var id: String { sourceSHA256 }
|
||||
}
|
||||
|
||||
enum ArchiveLibraryError: LocalizedError {
|
||||
case missing, incompatible, input(String), damaged
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missing: return "This build has no Archive search index. Install a build with the index or prepare it using the knowledge tools before rebuilding."
|
||||
case .incompatible: return "This Archive index belongs to a different database or version. Rebuild with a compatible Archive Library index."
|
||||
case .input(let message): return message
|
||||
case .damaged: return "The Archive index could not be read. Replace it with a verified copy and rebuild the app."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Native and MCP clients use one serialized read-only connection. SQLite periodically
|
||||
/// checks the current task for cancellation, including while ranking a common term.
|
||||
actor ArchiveLibraryCatalog {
|
||||
static let shared = ArchiveLibraryCatalog(url: Bundle.main.url(forResource: "ArchiveLibrary", withExtension: "sqlite", subdirectory: "ArchiveLibrary"))
|
||||
private let url: URL?
|
||||
private var connection: LibrarySQLite?
|
||||
private var hasReaderSections = false
|
||||
|
||||
init(url: URL?) { self.url = url }
|
||||
|
||||
private func database() throws -> LibrarySQLite {
|
||||
try Task.checkCancellation()
|
||||
if let connection { return connection }
|
||||
guard let url, url.isFileURL, FileManager.default.fileExists(atPath: url.path) else { throw ArchiveLibraryError.missing }
|
||||
let db = try LibrarySQLite(url: url, cancellable: true, describeError: { _ in ArchiveLibraryError.damaged })
|
||||
try db.execute("PRAGMA trusted_schema=OFF")
|
||||
try db.execute("PRAGMA query_only=ON")
|
||||
guard try db.rows("PRAGMA application_id").first?["application_id"] == String(0x56434341),
|
||||
let version = try db.rows("PRAGMA user_version").first?["user_version"],
|
||||
["1", "2"].contains(version) else { throw ArchiveLibraryError.incompatible }
|
||||
hasReaderSections = version == "2"
|
||||
connection = db
|
||||
return db
|
||||
}
|
||||
|
||||
func collections() throws -> [String] {
|
||||
try database().rows("""
|
||||
SELECT collection FROM document
|
||||
UNION SELECT collection || '/' || issue_year AS collection FROM document
|
||||
WHERE issue_year IS NOT NULL AND substr(collection,-5) != '/' || issue_year
|
||||
ORDER BY collection COLLATE NOCASE,collection
|
||||
""")
|
||||
.compactMap { $0["collection"] }
|
||||
}
|
||||
|
||||
private func scope(_ collection: String?) throws -> (sql: String, values: [String]) {
|
||||
guard let collection, !collection.isEmpty else { return ("", []) }
|
||||
guard collection.utf8.count <= 2048, !collection.contains("\0") else { throw ArchiveLibraryError.input("Invalid Archive collection.") }
|
||||
return (" AND (d.collection=? OR instr(d.collection, ? || '/')=1 OR d.collection || '/' || d.issue_year=?)", [collection, collection, collection])
|
||||
}
|
||||
|
||||
private func bounds(_ limit: Int, _ offset: Int) throws -> [String] {
|
||||
guard (1...50).contains(limit), (0...250_000).contains(offset) else { throw ArchiveLibraryError.input("Archive pages allow 1–50 results and offsets up to 250,000.") }
|
||||
return [String(limit), String(offset)]
|
||||
}
|
||||
|
||||
func browse(collection: String?, limit: Int, offset: Int) throws -> [ArchiveDocument] {
|
||||
let filter = try scope(collection)
|
||||
let values = try filter.values + bounds(limit, offset)
|
||||
let rows = try database().rows("""
|
||||
SELECT d.* FROM document d WHERE 1=1 \(filter.sql)
|
||||
ORDER BY d.title COLLATE NOCASE,d.sha256 LIMIT ? OFFSET ?
|
||||
""", values)
|
||||
return try rows.map(document)
|
||||
}
|
||||
|
||||
private static let compounds = ["module directory", "width 80", "width 40", "disk basic", "extended basic"]
|
||||
|
||||
private func match(_ query: String) throws -> String {
|
||||
guard query.count <= 256, !query.contains("\0") else { throw ArchiveLibraryError.input("Use at most 256 characters for an Archive search.") }
|
||||
let words = query.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init)
|
||||
guard !words.isEmpty, words.count <= 16 else { throw ArchiveLibraryError.input("Enter between one and sixteen words or numbers.") }
|
||||
let required = words.map { "\"\($0)\"" }.joined(separator: " AND ")
|
||||
let pairs = Set(zip(words, words.dropFirst()).map { $0 + " " + $1 })
|
||||
let boosts = Self.compounds.filter(pairs.contains).map { "\"vccphrase\($0.replacingOccurrences(of: " ", with: ""))\"" }
|
||||
guard !boosts.isEmpty else { return required }
|
||||
return "(\(required)) OR ((\(required)) AND (\(boosts.joined(separator: " OR "))))"
|
||||
}
|
||||
|
||||
func search(query: String, collection: String?, limit: Int, offset: Int) throws -> [ArchiveHit] {
|
||||
let expression = try match(query)
|
||||
let filter = try scope(collection)
|
||||
let values = try [expression] + filter.values + bounds(limit, offset)
|
||||
let rows = try database().rows("""
|
||||
SELECT d.*,p.page_number,p.page_label,p.locator_kind,p.is_ocr
|
||||
FROM page_terms JOIN page p ON p.id=page_terms.rowid JOIN document d ON d.id=p.document_id
|
||||
WHERE page_terms MATCH ? \(filter.sql)
|
||||
ORDER BY bm25(page_terms,1.0,4.0),p.id LIMIT ? OFFSET ?
|
||||
""", values)
|
||||
return try rows.map(hit)
|
||||
}
|
||||
|
||||
func citation(id: String) throws -> ArchiveHit? {
|
||||
let fields = id.components(separatedBy: ":")
|
||||
guard fields.count == 4, fields[0] == "sha256", Self.isSHA(fields[1]),
|
||||
let n = Int32(fields[3]), n > 0, String(n) == fields[3] else { return nil }
|
||||
let rows = try database().rows("""
|
||||
SELECT d.*,p.page_number,p.page_label,p.locator_kind,p.is_ocr
|
||||
FROM document d JOIN page p ON p.document_id=d.id
|
||||
WHERE d.sha256=? AND p.locator_kind=? AND p.page_number=?
|
||||
""", Array(fields[1...3]))
|
||||
return try rows.first.map(hit)
|
||||
}
|
||||
|
||||
private static func isSHA(_ value: String) -> Bool {
|
||||
value.utf8.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }
|
||||
}
|
||||
|
||||
private func document(_ row: [String: String]) throws -> ArchiveDocument {
|
||||
guard let sha = row["sha256"], Self.isSHA(sha), let title = row["title"], let collection = row["collection"],
|
||||
let link = row["source_url"].flatMap(URL.init(string:)), link.scheme == "https",
|
||||
link.host == "colorcomputerarchive.com", link.path.hasPrefix("/repo/Documents/"),
|
||||
link.user == nil, link.password == nil, link.port == nil else { throw ArchiveLibraryError.damaged }
|
||||
let delivery = row["delivery_url"].flatMap(URL.init(string:))
|
||||
var memberRange: ArchiveMemberRange?
|
||||
if let offset = row["member_offset"].flatMap(Int64.init),
|
||||
let compressed = row["member_compressed_bytes"].flatMap(Int64.init),
|
||||
let method = row["member_method"].flatMap(Int.init),
|
||||
let bytes = row["archive_bytes"].flatMap(Int64.init) {
|
||||
memberRange = ArchiveMemberRange(offset: offset, compressedBytes: compressed, method: method, archiveBytes: bytes)
|
||||
}
|
||||
return ArchiveDocument(id: sha, title: title, collection: collection, sourceURL: link,
|
||||
memberPath: row["member_path"], pageCount: row["page_count"].flatMap(Int.init),
|
||||
deliveryURL: delivery, deliveryBytes: delivery == nil ? nil : row["byte_size"].flatMap(Int64.init),
|
||||
format: row["format"] ?? "pdf", sourceBytes: row["byte_size"].flatMap(Int64.init), memberRange: memberRange)
|
||||
}
|
||||
|
||||
private func hit(_ row: [String: String]) throws -> ArchiveHit {
|
||||
let doc = try document(row)
|
||||
guard let kind = row["locator_kind"], let number = row["page_number"].flatMap(Int.init), number > 0 else { throw ArchiveLibraryError.damaged }
|
||||
let label = row["page_label"].flatMap { $0.isEmpty ? nil : $0 }
|
||||
let locator: String
|
||||
var source = doc.sourceURL
|
||||
switch kind {
|
||||
case "pdf_page":
|
||||
if let label, label != String(number) {
|
||||
locator = "PDF page \(number) (label \(label))"
|
||||
} else {
|
||||
locator = "PDF page \(number)"
|
||||
}
|
||||
if doc.memberPath == nil, var parts = URLComponents(url: source, resolvingAgainstBaseURL: false) {
|
||||
parts.fragment = "page=\(number)"
|
||||
if let link = parts.url { source = link }
|
||||
}
|
||||
case "worksheet": locator = label ?? "Worksheet \(number)"
|
||||
case "section": locator = label ?? "Section \(number)"
|
||||
case "image": locator = label ?? "Image \(number)"
|
||||
default: throw ArchiveLibraryError.damaged
|
||||
}
|
||||
return ArchiveHit(id: "sha256:\(doc.id):\(kind):\(number)", document: doc,
|
||||
page: kind == "pdf_page" ? number : nil, locator: locator,
|
||||
ocr: row["is_ocr"] == "1", sourceURL: source, locationNumber: number)
|
||||
}
|
||||
|
||||
func readerSection(documentID: String, number: Int) throws -> ArchiveReaderSection? {
|
||||
guard Self.isSHA(documentID), number > 0 else { return nil }
|
||||
let db = try database()
|
||||
guard hasReaderSections else { return nil }
|
||||
let rows = try db.rows("""
|
||||
SELECT p.page_label,s.text FROM document d JOIN page p ON p.document_id=d.id
|
||||
JOIN reader_section s ON s.page_id=p.id WHERE d.sha256=? AND p.page_number=?
|
||||
""", [documentID, String(number)])
|
||||
guard let row = rows.first, let text = row["text"] else { return nil }
|
||||
return ArchiveReaderSection(number: number, label: row["page_label"], text: text)
|
||||
}
|
||||
|
||||
func examples(documentID: String, page: Int) throws -> [ArchiveExample] {
|
||||
guard Self.isSHA(documentID), page > 0 else { return [] }
|
||||
let rows = try database().rows("""
|
||||
SELECT * FROM reviewed_example WHERE original_sha256=? AND ? BETWEEN first_page AND last_page
|
||||
ORDER BY title,source_sha256
|
||||
""", [documentID, String(page)])
|
||||
return try rows.map(reviewedExample)
|
||||
}
|
||||
|
||||
func basicExample(sourceSHA256: String) throws -> ArchiveExample? {
|
||||
guard Self.isSHA(sourceSHA256) else { return nil }
|
||||
let rows = try database().rows("SELECT * FROM reviewed_example WHERE source_sha256=? AND kind='basic_program' LIMIT 1", [sourceSHA256])
|
||||
return try rows.first.map(reviewedExample)
|
||||
}
|
||||
|
||||
private func reviewedExample(_ row: [String: String]) throws -> ArchiveExample {
|
||||
guard let title = row["title"], let kind = row["kind"], let language = row["language"],
|
||||
let author = row["author"], let provenance = row["provenance"], let source = row["source"],
|
||||
let sha = row["source_sha256"],
|
||||
SHA256.hash(data: Data(source.utf8)).map({ String(format: "%02x", $0) }).joined() == sha else {
|
||||
throw ArchiveLibraryError.damaged
|
||||
}
|
||||
return ArchiveExample(title: title, kind: kind, language: language, author: author,
|
||||
provenance: provenance, source: source, sourceSHA256: sha)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import PDFKit
|
||||
import Compression
|
||||
|
||||
struct ArchiveAssetReceipt: Sendable {
|
||||
let url: URL
|
||||
let sha256: String
|
||||
let bytes: Int64
|
||||
let fileExtension: String
|
||||
let memberRange: ArchiveMemberRange?
|
||||
|
||||
init?(document: ArchiveDocument) {
|
||||
let sha = document.id
|
||||
guard sha.utf8.count == 64, sha.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { return nil }
|
||||
if document.format == "pdf" {
|
||||
guard let url = document.deliveryURL, let bytes = document.deliveryBytes,
|
||||
bytes > 0, bytes <= 4 * 1024 * 1024 * 1024, Self.acceptsPDF(url) else { return nil }
|
||||
self.url = url
|
||||
self.bytes = bytes
|
||||
fileExtension = "pdf"
|
||||
memberRange = nil
|
||||
} else {
|
||||
guard let bytes = document.sourceBytes, bytes > 0, bytes <= 128 * 1024 * 1024,
|
||||
Self.acceptsSource(document.sourceURL) else { return nil }
|
||||
let ext: String
|
||||
if let member = document.memberPath {
|
||||
guard let range = document.memberRange, (0...1_073_741_824).contains(range.archiveBytes),
|
||||
range.offset >= 0, range.compressedBytes > 0, range.compressedBytes <= range.archiveBytes,
|
||||
range.offset <= range.archiveBytes - range.compressedBytes,
|
||||
range.method == 8 || (range.method == 0 && range.compressedBytes == bytes),
|
||||
document.sourceURL.pathExtension.lowercased() == "zip" else { return nil }
|
||||
ext = (member as NSString).pathExtension.lowercased()
|
||||
memberRange = range
|
||||
} else {
|
||||
ext = document.sourceURL.pathExtension.lowercased()
|
||||
memberRange = nil
|
||||
}
|
||||
switch document.format {
|
||||
case "image" where ["jpg","jpeg","gif","png","tif","tiff"].contains(ext): break
|
||||
case "text" where ["txt","bas"].contains(ext): break
|
||||
default: return nil
|
||||
}
|
||||
url = document.sourceURL
|
||||
self.bytes = bytes
|
||||
fileExtension = ext
|
||||
}
|
||||
sha256 = sha
|
||||
}
|
||||
|
||||
private static func acceptsPDF(_ url: URL) -> Bool {
|
||||
SoftwareLibraryInstaller.acceptsDownloadURL(url) && url.path.hasPrefix("/dl/software/CoCoLibrary/Documents/")
|
||||
&& url.pathExtension.lowercased() == "pdf"
|
||||
}
|
||||
|
||||
private static func acceptsSource(_ url: URL) -> Bool {
|
||||
url.scheme == "https" && url.host == "colorcomputerarchive.com" && url.user == nil && url.password == nil
|
||||
&& (url.port == nil || url.port == 443) && url.query == nil && url.fragment == nil
|
||||
&& url.path.hasPrefix("/repo/Documents/") && !url.pathComponents.contains("..") && !url.pathComponents.contains(".")
|
||||
&& !url.path.contains("\\") && !url.path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
|
||||
}
|
||||
|
||||
func acceptsResponseURL(_ url: URL) -> Bool {
|
||||
fileExtension == "pdf" ? Self.acceptsPDF(url) : Self.acceptsSource(url)
|
||||
}
|
||||
|
||||
var rangeHeader: String? {
|
||||
memberRange.map { "bytes=\($0.offset)-\($0.offset + $0.compressedBytes - 1)" }
|
||||
}
|
||||
|
||||
/// Servers may return the complete ZIP instead of honoring a byte-range request.
|
||||
func responseSize(_ response: HTTPURLResponse) -> Int64? {
|
||||
guard let final = response.url, acceptsResponseURL(final) else { return nil }
|
||||
guard let range = memberRange else { return response.statusCode == 200 ? bytes : nil }
|
||||
if response.statusCode == 200 { return range.archiveBytes }
|
||||
let header = "bytes \(range.offset)-\(range.offset + range.compressedBytes - 1)/\(range.archiveBytes)"
|
||||
return response.statusCode == 206 && response.value(forHTTPHeaderField: "Content-Range") == header ? range.compressedBytes : nil
|
||||
}
|
||||
}
|
||||
|
||||
private enum ArchiveReaderError: LocalizedError {
|
||||
case changed, unavailable, location, space, download, page
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .changed: return "The downloaded file does not match the edition in the Archive index."
|
||||
case .unavailable: return "This edition is available at the Archive source."
|
||||
case .location: return "The Archive file could not be cached. Check the free space and permissions."
|
||||
case .space: return "There is not enough free space to cache this Archive file."
|
||||
case .download: return "The Archive file could not be downloaded. Check your connection and try again."
|
||||
case .page: return "This PDF could not be opened at the cited page. Use the Archive source to inspect the original."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ArchiveReadProgress: Sendable {
|
||||
case checking, downloading(Int64, Int64), verifying
|
||||
}
|
||||
|
||||
actor ArchiveAssetCache {
|
||||
#if VCC_UI_TESTING
|
||||
static let shared: ArchiveAssetCache = {
|
||||
let directory = ProcessInfo.processInfo.environment["VCC_ARCHIVE_TEST_CACHE"].map { URL(fileURLWithPath: $0, isDirectory: true) }
|
||||
?? FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveUITest-" + UUID().uuidString, isDirectory: true)
|
||||
return ArchiveAssetCache(directory: directory)
|
||||
}()
|
||||
#else
|
||||
static let shared = ArchiveAssetCache()
|
||||
#endif
|
||||
private let directory: URL?
|
||||
private let configuration: URLSessionConfiguration
|
||||
|
||||
init(directory: URL? = nil, configuration: URLSessionConfiguration? = nil) {
|
||||
self.directory = directory
|
||||
if let configuration {
|
||||
self.configuration = configuration
|
||||
} else {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 45
|
||||
config.timeoutIntervalForResource = 3600
|
||||
config.urlCache = nil
|
||||
self.configuration = config
|
||||
}
|
||||
}
|
||||
|
||||
func localCopy(_ receipt: ArchiveAssetReceipt, progress: @escaping @Sendable (ArchiveReadProgress) -> Void) async throws -> URL {
|
||||
try Task.checkCancellation()
|
||||
let fm = FileManager.default
|
||||
let directory = self.directory ?? AppIdentity.supportDirectory.appendingPathComponent(
|
||||
receipt.fileExtension == "pdf" ? "ArchiveLibrary/PDFs" : "ArchiveLibrary/Assets", isDirectory: true)
|
||||
try fm.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let info = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard info.isDirectory == true, info.isSymbolicLink != true else { throw ArchiveReaderError.location }
|
||||
let target = directory.appendingPathComponent(receipt.sha256 + "." + receipt.fileExtension)
|
||||
progress(.checking)
|
||||
if let attributes = try? fm.attributesOfItem(atPath: target.path) {
|
||||
guard attributes[.type] as? FileAttributeType == .typeRegular else { throw ArchiveReaderError.location }
|
||||
if (attributes[.size] as? NSNumber)?.int64Value == receipt.bytes,
|
||||
try SoftwareLibraryManualCache.fingerprint(target) == receipt.sha256 { return target }
|
||||
}
|
||||
let transferBytes = receipt.memberRange?.compressedBytes ?? receipt.bytes
|
||||
let disk = try fm.attributesOfFileSystem(forPath: directory.path)
|
||||
let free = (disk[.systemFreeSize] as? NSNumber)?.int64Value
|
||||
let reserved: Int64 = 32 * 1024 * 1024 + (receipt.memberRange == nil ? 0 : receipt.bytes)
|
||||
if let free, free < transferBytes + reserved { throw ArchiveReaderError.space }
|
||||
var request = URLRequest(url: receipt.url)
|
||||
request.setValue("VCCPlus/ArchiveLibrary", forHTTPHeaderField: "User-Agent")
|
||||
request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
|
||||
request.setValue(receipt.rangeHeader, forHTTPHeaderField: "Range")
|
||||
let temporary = directory.appendingPathComponent(UUID().uuidString + ".download")
|
||||
defer { try? fm.removeItem(at: temporary) }
|
||||
let observer = ArchiveAssetTransfer(receipt: receipt, available: free.map { $0 - reserved }, destination: temporary, progress: progress)
|
||||
progress(.downloading(0, transferBytes))
|
||||
let http = try await observer.download(request, configuration: configuration)
|
||||
try Task.checkCancellation()
|
||||
progress(.verifying)
|
||||
// Only atomically replace the cached edition after its final bytes have been verified.
|
||||
let staged = directory.appendingPathComponent(UUID().uuidString + ".partial")
|
||||
defer { try? fm.removeItem(at: staged) }
|
||||
if let range = receipt.memberRange {
|
||||
try Self.unpack(range, from: temporary, offset: http.statusCode == 206 ? 0 : range.offset, to: staged, bytes: receipt.bytes)
|
||||
} else {
|
||||
try fm.moveItem(at: temporary, to: staged)
|
||||
}
|
||||
guard try SoftwareLibraryManualCache.fingerprint(staged) == receipt.sha256 else { throw ArchiveReaderError.changed }
|
||||
try Task.checkCancellation()
|
||||
if fm.fileExists(atPath: target.path) {
|
||||
guard try fm.attributesOfItem(atPath: target.path)[.type] as? FileAttributeType == .typeRegular else { throw ArchiveReaderError.location }
|
||||
_ = try fm.replaceItemAt(target, withItemAt: staged)
|
||||
} else { try fm.moveItem(at: staged, to: target) }
|
||||
return target
|
||||
}
|
||||
|
||||
/// No archive paths become local filenames. Decode only the indexed member body
|
||||
/// and cap both compressed input and output, including the full-ZIP HTTP 200 path.
|
||||
private static func unpack(_ range: ArchiveMemberRange, from source: URL, offset: Int64, to output: URL, bytes: Int64) throws {
|
||||
let input = try FileHandle(forReadingFrom: source)
|
||||
defer { try? input.close() }
|
||||
try input.seek(toOffset: UInt64(offset))
|
||||
try Data().write(to: output, options: .withoutOverwriting)
|
||||
let writer = try FileHandle(forWritingTo: output)
|
||||
defer { try? writer.close() }
|
||||
var written: Int64 = 0
|
||||
func write(_ chunk: Data?) throws {
|
||||
try Task.checkCancellation()
|
||||
guard let chunk else { return }
|
||||
written += Int64(chunk.count)
|
||||
guard written <= bytes else { throw ArchiveReaderError.changed }
|
||||
try writer.write(contentsOf: chunk)
|
||||
}
|
||||
let decoder = range.method == 8 ? try OutputFilter(.decompress, using: .zlib, writingTo: write) : nil
|
||||
var remaining = range.compressedBytes
|
||||
while remaining > 0 {
|
||||
try Task.checkCancellation()
|
||||
guard let chunk = try input.read(upToCount: Int(min(remaining, 65536))), !chunk.isEmpty else { throw ArchiveReaderError.changed }
|
||||
remaining -= Int64(chunk.count)
|
||||
if let decoder { try decoder.write(chunk) } else { try write(chunk) }
|
||||
}
|
||||
try decoder?.finalize()
|
||||
guard written == bytes else { throw ArchiveReaderError.changed }
|
||||
}
|
||||
}
|
||||
|
||||
private final class ArchiveAssetTransfer: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
|
||||
private let receipt: ArchiveAssetReceipt
|
||||
private let available: Int64?
|
||||
private let destination: URL
|
||||
private let progress: @Sendable (ArchiveReadProgress) -> Void
|
||||
private let lock = NSLock() // Synchronizes task registration, cancellation, and completion.
|
||||
private var continuation: CheckedContinuation<HTTPURLResponse, Error>?
|
||||
// Foundation invokes the callbacks below on this session's serial delegate queue.
|
||||
private var rejection: ArchiveReaderError?
|
||||
private var lastReport: UInt64 = 0
|
||||
private var response: HTTPURLResponse?
|
||||
|
||||
init(receipt: ArchiveAssetReceipt, available: Int64?, destination: URL, progress: @escaping @Sendable (ArchiveReadProgress) -> Void) {
|
||||
self.receipt = receipt
|
||||
self.available = available
|
||||
self.destination = destination
|
||||
self.progress = progress
|
||||
}
|
||||
|
||||
func download(_ request: URLRequest, configuration: URLSessionConfiguration) async throws -> HTTPURLResponse {
|
||||
// The async download(for:) helper does not forward incremental download
|
||||
// callbacks. An explicit delegate task also lets us enforce the byte cap in flight.
|
||||
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
|
||||
defer { session.invalidateAndCancel() }
|
||||
let task = session.downloadTask(with: request)
|
||||
let result = try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { (reply: CheckedContinuation<HTTPURLResponse, Error>) in
|
||||
lock.withLock {
|
||||
guard !Task.isCancelled else { reply.resume(throwing: CancellationError()); return }
|
||||
continuation = reply
|
||||
task.resume()
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
if self.lock.withLock({ self.continuation != nil }) { task.cancel() }
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
return result
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
||||
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
|
||||
guard let url = request.url, receipt.acceptsResponseURL(url) else { completionHandler(nil); return }
|
||||
var redirected = request
|
||||
redirected.setValue(receipt.rangeHeader, forHTTPHeaderField: "Range")
|
||||
redirected.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
|
||||
completionHandler(redirected)
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
|
||||
guard rejection == nil, let http = downloadTask.response as? HTTPURLResponse, let expected = receipt.responseSize(http) else {
|
||||
rejection = rejection ?? .download
|
||||
return
|
||||
}
|
||||
guard available.map({ expected <= $0 }) ?? true else { rejection = .space; return }
|
||||
do {
|
||||
guard (try location.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) == expected else {
|
||||
rejection = .changed
|
||||
return
|
||||
}
|
||||
// Foundation removes its temporary file when this delegate method returns.
|
||||
try FileManager.default.moveItem(at: location, to: destination)
|
||||
response = http
|
||||
} catch { rejection = .location }
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
||||
let reply = lock.withLock {
|
||||
let reply = continuation
|
||||
continuation = nil
|
||||
return reply
|
||||
}
|
||||
if let rejection { reply?.resume(throwing: rejection) }
|
||||
else if (error as? URLError)?.code == .cancelled { reply?.resume(throwing: CancellationError()) }
|
||||
else if error == nil, let response { reply?.resume(returning: response) }
|
||||
else { reply?.resume(throwing: ArchiveReaderError.download) }
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
guard let response = downloadTask.response as? HTTPURLResponse, let expected = receipt.responseSize(response) else {
|
||||
rejection = .download
|
||||
downloadTask.cancel()
|
||||
return
|
||||
}
|
||||
guard totalBytesWritten <= expected, totalBytesExpectedToWrite <= expected else {
|
||||
rejection = .changed
|
||||
downloadTask.cancel()
|
||||
return
|
||||
}
|
||||
if let available, expected > available {
|
||||
rejection = .space
|
||||
downloadTask.cancel()
|
||||
return
|
||||
}
|
||||
let now = DispatchTime.now().uptimeNanoseconds
|
||||
guard lastReport == 0 || now - lastReport >= 120_000_000 || totalBytesWritten == expected else { return }
|
||||
lastReport = now
|
||||
progress(.downloading(totalBytesWritten, expected))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class ArchiveReaderModel: ObservableObject {
|
||||
let view = PDFView()
|
||||
@Published private(set) var referenceID: String?
|
||||
@Published private(set) var document: PDFDocument?
|
||||
@Published private(set) var preview: ArchiveInlineContent?
|
||||
@Published private(set) var sectionLabel: String?
|
||||
@Published private(set) var cancelled = false
|
||||
@Published private(set) var progress: ArchiveReadProgress?
|
||||
@Published private(set) var error: String?
|
||||
@Published private(set) var page = 1
|
||||
@Published var find = "" { didSet { if find != oldValue { resetFind() } } }
|
||||
@Published private(set) var findMessage: String?
|
||||
@Published private(set) var isFinding = false
|
||||
private var request: Task<Void, Never>?
|
||||
private var findTask: Task<Void, Never>?
|
||||
private var findRequestID = UUID()
|
||||
private var requestID = UUID()
|
||||
private var localURL: URL?
|
||||
private var lastMatch: (page: Int, range: NSRange)?
|
||||
private var pendingPage = 1
|
||||
let remembersPage: Bool
|
||||
private let cache: ArchiveAssetCache
|
||||
private let catalog: ArchiveLibraryCatalog
|
||||
|
||||
init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared) {
|
||||
self.remembersPage = remembersPage
|
||||
self.cache = cache
|
||||
self.catalog = catalog
|
||||
view.displayMode = .singlePageContinuous
|
||||
view.autoScales = true
|
||||
view.displaysPageBreaks = true
|
||||
view.setAccessibilityLabel("Archive PDF")
|
||||
}
|
||||
func stop() {
|
||||
requestID = UUID(); request?.cancel(); request = nil; progress = nil
|
||||
resetFind()
|
||||
}
|
||||
func reset() {
|
||||
stop()
|
||||
document = nil; view.document = nil; preview = nil; sectionLabel = nil
|
||||
referenceID = nil; error = nil; localURL = nil; page = 1; find = ""; cancelled = false
|
||||
}
|
||||
func cancel() {
|
||||
stop()
|
||||
cancelled = true
|
||||
}
|
||||
func retry(_ record: ArchiveDocument) {
|
||||
open(record, page: pendingPage)
|
||||
}
|
||||
private func rememberPage() {
|
||||
if remembersPage, let referenceID { UserDefaults.standard.set(page, forKey: "archive-library.page." + referenceID) }
|
||||
}
|
||||
static func savedPage(for id: String) -> Int { max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) }
|
||||
func updatePage() {
|
||||
guard let document, let current = view.currentPage, current.document === document else { return }
|
||||
let index = document.index(for: current)
|
||||
guard index >= 0, index < document.pageCount else { return }
|
||||
page = index + 1
|
||||
rememberPage()
|
||||
}
|
||||
func go(to number: Int) {
|
||||
guard let document, number > 0, number <= document.pageCount, let target = document.page(at: number - 1) else { return }
|
||||
view.go(to: target); updatePage()
|
||||
}
|
||||
func open(_ record: ArchiveDocument, page number: Int) {
|
||||
if referenceID == record.id {
|
||||
if document != nil { go(to: number); return }
|
||||
if preview != nil && page == number { return }
|
||||
if progress != nil && (record.format == "pdf" || number == pendingPage) {
|
||||
pendingPage = number
|
||||
return
|
||||
}
|
||||
}
|
||||
reset()
|
||||
referenceID = record.id
|
||||
pendingPage = number
|
||||
let identity = requestID
|
||||
progress = .checking
|
||||
request = Task {
|
||||
do {
|
||||
switch record.format {
|
||||
case "pdf", "image", "text":
|
||||
guard let receipt = ArchiveAssetReceipt(document: record) else { throw ArchiveReaderError.unavailable }
|
||||
let url = try await cache.localCopy(receipt) { event in
|
||||
Task { @MainActor in
|
||||
guard self.requestID == identity, self.progress != nil else { return }
|
||||
self.progress = event
|
||||
}
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
if record.format == "pdf" {
|
||||
let parsed = await Task.detached(priority: .userInitiated) { PDFDocument(url: url) }.value
|
||||
try Task.checkCancellation()
|
||||
let target = pendingPage
|
||||
guard let parsed, !parsed.isLocked, target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page }
|
||||
localURL = url; document = parsed; view.document = parsed; view.autoScales = true; go(to: target)
|
||||
} else {
|
||||
let content = try await ArchivePreviewDecoder.shared.read(url, format: record.format, number: number)
|
||||
try Task.checkCancellation()
|
||||
page = number; preview = content; rememberPage()
|
||||
}
|
||||
default:
|
||||
guard let section = try await catalog.readerSection(documentID: record.id, number: number) else {
|
||||
throw ArchiveReaderError.unavailable
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
page = section.number; sectionLabel = section.label
|
||||
preview = record.format == "office-xls" ? .worksheet(section.text) : .text(section.text)
|
||||
rememberPage()
|
||||
}
|
||||
progress = nil
|
||||
} catch {
|
||||
guard requestID == identity else { return }
|
||||
progress = nil
|
||||
if !Task.isCancelled { self.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func resetFind() {
|
||||
findRequestID = UUID(); findTask?.cancel(); findTask = nil; isFinding = false; findMessage = nil; lastMatch = nil
|
||||
}
|
||||
func findNext() {
|
||||
guard let localURL, let document, !isFinding, !find.isEmpty else { return }
|
||||
let text = find, current = page
|
||||
let start = lastMatch.flatMap { $0.page == page ? NSMaxRange($0.range) : nil } ?? 0
|
||||
let identity = UUID(); findRequestID = identity; isFinding = true; findMessage = nil
|
||||
findTask = Task {
|
||||
let result = await Self.nextMatch(in: localURL, text: text, page: current, start: start)
|
||||
guard !Task.isCancelled, findRequestID == identity, self.document === document else { return }
|
||||
isFinding = false
|
||||
guard let (number, range) = result, let target = document.page(at: number - 1), let selection = target.selection(for: range) else {
|
||||
findMessage = "No matching text in the PDF’s text layer."; return
|
||||
}
|
||||
view.setCurrentSelection(selection, animate: false); view.go(to: selection); updatePage(); lastMatch = (number, range)
|
||||
}
|
||||
}
|
||||
private nonisolated static func nextMatch(in url: URL, text: String, page: Int, start: Int) async -> (Int, NSRange)? {
|
||||
guard let doc = PDFDocument(url: url), doc.pageCount > 0, page > 0, page <= doc.pageCount else { return nil }
|
||||
for offset in 0...doc.pageCount {
|
||||
if Task.isCancelled { return nil }
|
||||
let index = (page - 1 + offset) % doc.pageCount
|
||||
let match: NSRange? = autoreleasepool {
|
||||
guard let raw = doc.page(at: index)?.string as NSString? else { return nil }
|
||||
let lower = offset == 0 ? min(start, raw.length) : 0
|
||||
let upper = offset == doc.pageCount ? min(start, raw.length) : raw.length
|
||||
let range = raw.range(of: text, options: [.caseInsensitive], range: NSRange(location: lower, length: upper - lower))
|
||||
return range.location == NSNotFound ? nil : range
|
||||
}
|
||||
if let match { return (index + 1, match) }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private struct ArchivePDFSurface: NSViewRepresentable {
|
||||
let view: PDFView
|
||||
func makeNSView(context: Context) -> PDFView { view }
|
||||
func updateNSView(_ nsView: PDFView, context: Context) {}
|
||||
}
|
||||
|
||||
struct ArchiveReaderPane: View {
|
||||
let record: ArchiveDocument
|
||||
let hit: ArchiveHit?
|
||||
@ObservedObject var reader: ArchiveReaderModel
|
||||
let requestedPage: Int
|
||||
let catalog: ArchiveLibraryCatalog
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var examples: [ArchiveExample] = []
|
||||
@State private var exampleError: String?
|
||||
@State private var loadedExampleKey: String?
|
||||
@State private var copies: String?
|
||||
@State private var pageField = "1"
|
||||
@FocusState private var findFocused: Bool
|
||||
|
||||
private var isCurrent: Bool { reader.referenceID == record.id }
|
||||
private var loaded: Bool { isCurrent && reader.document != nil }
|
||||
private var visiblePage: Int? {
|
||||
guard record.format == "pdf" else { return nil }
|
||||
return loaded ? reader.page : (hit?.page ?? requestedPage)
|
||||
}
|
||||
private var exampleKey: String { record.id + "/" + String(visiblePage ?? 0) }
|
||||
private var atHit: Bool {
|
||||
guard let hit else { return false }
|
||||
if loaded || (isCurrent && reader.preview != nil) { return hit.locationNumber == reader.page }
|
||||
return true
|
||||
}
|
||||
private var source: URL {
|
||||
if atHit, let hit { return hit.sourceURL }
|
||||
guard record.memberPath == nil, record.sourceURL.pathExtension.lowercased() == "pdf", let visiblePage,
|
||||
var parts = URLComponents(url: record.sourceURL, resolvingAgainstBaseURL: false) else { return record.sourceURL }
|
||||
parts.fragment = "page=\(visiblePage)"; return parts.url ?? record.sourceURL
|
||||
}
|
||||
private var citation: String {
|
||||
if atHit, let hit { return hit.citation }
|
||||
return record.cite(visiblePage.map { "PDF page \($0)" } ?? (isCurrent ? reader.sectionLabel : nil), at: source)
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text(record.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary)
|
||||
Text(record.title).font(.title3.weight(.semibold)).lineLimit(3).textSelection(.enabled)
|
||||
if let member = record.memberPath { Text("ZIP member · " + member).font(.caption).textSelection(.enabled) }
|
||||
if atHit, let hit { Label(hit.locator + (hit.ocr ? " · OCR match" : ""), systemImage: "text.magnifyingglass").font(.caption).foregroundStyle(.secondary) }
|
||||
if loadedExampleKey == exampleKey, !examples.isEmpty { exampleActions }
|
||||
if let exampleError { Text(exampleError).font(.caption).foregroundStyle(.secondary) }
|
||||
}.padding(12)
|
||||
Divider()
|
||||
if loaded, let pdf = reader.document {
|
||||
VStack(spacing: 7) {
|
||||
HStack {
|
||||
Button { reader.go(to: reader.page - 1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous PDF page").disabled(reader.page <= 1)
|
||||
TextField("Page", text: $pageField).frame(width: 46).accessibilityLabel("PDF page number").onSubmit {
|
||||
if let n = Int(pageField) { reader.go(to: min(max(n, 1), pdf.pageCount)) }; pageField = String(reader.page)
|
||||
}
|
||||
Text("of \(pdf.pageCount)").foregroundStyle(.secondary)
|
||||
Button { reader.go(to: reader.page + 1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next PDF page").disabled(reader.page >= pdf.pageCount)
|
||||
Spacer()
|
||||
Button { reader.view.zoomOut(nil) } label: { Image(systemName: "minus.magnifyingglass") }.accessibilityLabel("Zoom out")
|
||||
Button { reader.view.zoomIn(nil) } label: { Image(systemName: "plus.magnifyingglass") }.accessibilityLabel("Zoom in")
|
||||
Button("Fit") { reader.view.autoScales = true }.accessibilityLabel("Fit page")
|
||||
}
|
||||
HStack {
|
||||
Button { findFocused = true } label: { Image(systemName: "magnifyingglass") }
|
||||
.buttonStyle(.borderless).keyboardShortcut("f").accessibilityLabel("Focus Find in PDF")
|
||||
TextField("Find in PDF", text: $reader.find).focused($findFocused).onSubmit { reader.findNext() }.accessibilityIdentifier("archive-pdf-find")
|
||||
if reader.isFinding { ProgressView().controlSize(.small) }
|
||||
Button("Find Next") { reader.findNext() }.keyboardShortcut("g").disabled(reader.find.isEmpty || reader.isFinding)
|
||||
}
|
||||
if let message = reader.findMessage { Text(message).font(.caption).foregroundStyle(.secondary) }
|
||||
}.padding(8)
|
||||
ArchivePDFSurface(view: reader.view).id(ObjectIdentifier(reader.view)).accessibilityIdentifier("archive-pdf-surface")
|
||||
.onReceive(NotificationCenter.default.publisher(for: .PDFViewPageChanged, object: reader.view)) { _ in reader.updatePage() }
|
||||
} else if isCurrent, let preview = reader.preview {
|
||||
if let count = record.pageCount, count > 1 {
|
||||
HStack {
|
||||
Button { reader.open(record, page: reader.page - 1) } label: { Image(systemName: "chevron.left") }
|
||||
.accessibilityLabel("Previous section").disabled(reader.page <= 1)
|
||||
TextField("Section", text: $pageField).frame(width: 44).accessibilityLabel("Section number").onSubmit {
|
||||
if let n = Int(pageField) { reader.open(record, page: min(max(n, 1), count)) }
|
||||
pageField = String(reader.page)
|
||||
}
|
||||
Text("of \(count)")
|
||||
Button { reader.open(record, page: reader.page + 1) } label: { Image(systemName: "chevron.right") }
|
||||
.accessibilityLabel("Next section").disabled(reader.page >= count)
|
||||
if let label = reader.sectionLabel { Text(label).lineLimit(2).help(label) }
|
||||
Spacer(minLength: 0)
|
||||
}.padding(8)
|
||||
}
|
||||
ArchiveInlinePreview(content: preview, title: record.title)
|
||||
.id(record.id + "/" + String(reader.page))
|
||||
} else {
|
||||
VStack(spacing: 12) {
|
||||
if isCurrent, let progress = reader.progress {
|
||||
switch progress {
|
||||
case .checking: ProgressView("Opening document…")
|
||||
case .verifying: ProgressView("Verifying download…")
|
||||
case .downloading(let done, let total):
|
||||
ProgressView(value: Double(done), total: Double(total)) { Text("Downloading…") }
|
||||
Text(ByteCountFormatter.string(fromByteCount: done, countStyle: .file) + " of " + ByteCountFormatter.string(fromByteCount: total, countStyle: .file)).font(.caption).monospacedDigit()
|
||||
}
|
||||
Button("Cancel") { reader.cancel() }
|
||||
} else if isCurrent, reader.error != nil || reader.cancelled {
|
||||
Text(reader.error ?? "Loading cancelled.").multilineTextAlignment(.center)
|
||||
Button("Try Again") { reader.retry(record) }
|
||||
} else {
|
||||
ProgressView("Opening document…")
|
||||
}
|
||||
}.padding(16).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("Color Computer Archive").font(.caption).foregroundStyle(.secondary)
|
||||
Link("Archive source", destination: source)
|
||||
}
|
||||
Spacer()
|
||||
if let copies { Text(copies).font(.caption).foregroundStyle(.secondary) }
|
||||
Button("Copy Citation") { copy(citation, success: "Citation copied") }.accessibilityIdentifier("archive-copy-citation")
|
||||
}.padding(10)
|
||||
}
|
||||
.onChange(of: reader.page, initial: true) { _, value in pageField = String(value) }
|
||||
.task(id: hit?.id ?? record.id) {
|
||||
guard !Task.isCancelled else { return }
|
||||
reader.open(record, page: requestedPage)
|
||||
}
|
||||
.task(id: exampleKey) {
|
||||
examples = []; loadedExampleKey = nil; exampleError = nil; copies = nil
|
||||
guard let page = visiblePage else { return }
|
||||
do {
|
||||
let entries = try await catalog.examples(documentID: record.id, page: page)
|
||||
try Task.checkCancellation()
|
||||
examples = entries; loadedExampleKey = exampleKey
|
||||
} catch { if !Task.isCancelled { exampleError = "Example information could not be read." } }
|
||||
}
|
||||
}
|
||||
@ViewBuilder private var exampleActions: some View {
|
||||
if let first = examples.first, examples.count == 1 {
|
||||
HStack {
|
||||
Button(first.kind == "snippet" ? "Copy Snippet" : "Copy Example") { copy(first.source, success: "Source copied") }
|
||||
.help(first.title + " · " + first.author + "\n" + first.provenance)
|
||||
if first.kind == "basic_program" { Button("Open in BASIC Editor") { openExample(first) } }
|
||||
Menu { Text(first.title); Text(first.language); Text(first.author); Text(first.provenance) } label: { Image(systemName: "info.circle") }
|
||||
.menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Example source information")
|
||||
}
|
||||
} else {
|
||||
Menu("Examples on this page") {
|
||||
ForEach(examples) { item in
|
||||
Menu(item.title) {
|
||||
Button(item.kind == "snippet" ? "Copy Snippet" : "Copy Example") { copy(item.source, success: "Source copied") }
|
||||
if item.kind == "basic_program" { Button("Open in BASIC Editor") { openExample(item) } }
|
||||
Divider(); Text(item.author); Text(item.language); Text(item.provenance)
|
||||
}
|
||||
}
|
||||
}.fixedSize().accessibilityIdentifier("archive-examples")
|
||||
}
|
||||
}
|
||||
private func openExample(_ item: ArchiveExample) { openWindow(id: "basic-example", value: "archive/" + item.sourceSHA256) }
|
||||
private func copy(_ text: String, success: String) {
|
||||
let pasteboard = NSPasteboard.general
|
||||
pasteboard.clearContents(); copies = pasteboard.setString(text, forType: .string) ? success : "Copy failed"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
private struct ArchiveCollection: Identifiable {
|
||||
let id: String
|
||||
let name: String
|
||||
let children: [Self]?
|
||||
|
||||
static func tree(_ paths: [String]) -> [Self] {
|
||||
var descendants: [String: Set<String>] = [:]
|
||||
for path in paths {
|
||||
var parent = ""
|
||||
for component in path.split(separator: "/") {
|
||||
let child = parent.isEmpty ? String(component) : parent + "/" + component
|
||||
descendants[parent, default: []].insert(child); parent = child
|
||||
}
|
||||
}
|
||||
func items(_ parent: String) -> [Self] {
|
||||
(descendants[parent] ?? []).sorted { $0.localizedStandardCompare($1) == .orderedAscending }.map { path in
|
||||
Self(id: path, name: String(path.split(separator: "/").last ?? ""), children: descendants[path] == nil ? nil : items(path))
|
||||
}
|
||||
}
|
||||
return items("")
|
||||
}
|
||||
}
|
||||
|
||||
private struct ArchiveBrowseRequest: Equatable { let collection: String; let offset: Int; let retry: Int }
|
||||
private struct ArchiveSearchRequest: Equatable { let query: String; let collection: String?; let offset: Int; let retry: Int }
|
||||
private struct ArchiveResultGroup: Identifiable {
|
||||
let document: ArchiveDocument
|
||||
var hits: [ArchiveHit]
|
||||
var id: String { document.id }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class ArchiveLibraryQuery: ObservableObject {
|
||||
@Published var text: String
|
||||
init(_ text: String = "") { self.text = text }
|
||||
}
|
||||
|
||||
struct ArchiveLibraryView: View {
|
||||
@AppStorage("archive-library.collection") private var collection = ""
|
||||
@AppStorage("archive-library.browse-selection") private var browseID: String?
|
||||
@AppStorage("archive-library.browse-offset") private var browseOffset = 0
|
||||
@AppStorage("archive-library.scope") private var localScope = false
|
||||
@State private var collections: [ArchiveCollection] = []
|
||||
@State private var documents: [ArchiveDocument] = []
|
||||
@State private var hits: [ArchiveHit] = []
|
||||
@State private var searchID: String?
|
||||
@State private var searchOffset = 0
|
||||
@StateObject private var archiveQuery: ArchiveLibraryQuery
|
||||
@State private var browseMore = false
|
||||
@State private var searchMore = false
|
||||
@State private var browseBusy = true
|
||||
@State private var searchBusy = false
|
||||
@State private var browseError: String?
|
||||
@State private var searchError: String?
|
||||
@State private var retry = 0
|
||||
@State private var compactReader = false
|
||||
@State private var showCollections = false
|
||||
@State private var searchBrowseCollection: String?
|
||||
@State private var searchFolder: String?
|
||||
@FocusState private var queryFocused: Bool
|
||||
@StateObject private var browseReader: ArchiveReaderModel
|
||||
@StateObject private var searchReader: ArchiveReaderModel
|
||||
private let batch = 35
|
||||
private let catalog: ArchiveLibraryCatalog
|
||||
|
||||
init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil) {
|
||||
self.catalog = catalog
|
||||
_browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog))
|
||||
_archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery())
|
||||
_searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: false, catalog: catalog))
|
||||
}
|
||||
|
||||
private var query: String { archiveQuery.text }
|
||||
private var searching: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||||
private var browseDocument: ArchiveDocument? { documents.first { $0.id == browseID } }
|
||||
private var hit: ArchiveHit? { hits.first { $0.id == searchID } }
|
||||
private var selected: ArchiveDocument? { searching ? hit?.document : browseDocument }
|
||||
private var reader: ArchiveReaderModel { searching ? searchReader : browseReader }
|
||||
private var requestedPage: Int { searching ? (hit?.locationNumber ?? 1) : browseID.map(ArchiveReaderModel.savedPage) ?? 1 }
|
||||
private var sidebarPath: String { searching ? (searchFolder ?? collection) : collection }
|
||||
private var scopePath: String? {
|
||||
if searching, let searchFolder, !searchFolder.isEmpty { return searchFolder }
|
||||
return !collection.isEmpty ? collection : (searchBrowseCollection ?? browseDocument?.collection)
|
||||
}
|
||||
private var key: ArchiveSearchRequest { .init(query: query, collection: localScope ? scopePath : nil, offset: searchOffset, retry: retry) }
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
let narrow = geometry.size.width < 790
|
||||
let side = geometry.size.width >= 990
|
||||
VStack(spacing: 0) {
|
||||
header(narrow: narrow, sidebar: side)
|
||||
Divider()
|
||||
HSplitView {
|
||||
if side { sidebar.frame(minWidth: 150, idealWidth: 180, maxWidth: 220) }
|
||||
if !narrow || !compactReader { listing.frame(minWidth: narrow ? 180 : 220, idealWidth: 290, maxWidth: narrow ? .infinity : 365) }
|
||||
if !narrow || compactReader {
|
||||
// An empty reader must accept the full pane height, just like the PDF reader.
|
||||
detail.frame(minWidth: narrow ? 230 : 330, maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
.frame(minWidth: 430, minHeight: 320)
|
||||
.task(id: retry) {
|
||||
do { let paths = try await catalog.collections(); try Task.checkCancellation(); collections = ArchiveCollection.tree(paths) }
|
||||
catch { if !Task.isCancelled { browseError = error.localizedDescription } }
|
||||
}
|
||||
.task(id: ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)) { await loadBrowse() }
|
||||
.task(id: key) { await loadSearch(key) }
|
||||
.onChange(of: query) { old, new in
|
||||
if old.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !new.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
searchBrowseCollection = browseDocument?.collection
|
||||
if browseReader.progress != nil { browseReader.stop() }
|
||||
}
|
||||
searchID = nil; searchOffset = 0; compactReader = false; searchReader.reset()
|
||||
if !searching { searchBrowseCollection = nil; searchFolder = nil }
|
||||
}
|
||||
.onChange(of: localScope) { _, _ in searchOffset = 0; searchID = nil; compactReader = false; searchReader.reset() }
|
||||
.onChange(of: browseID) { _, id in
|
||||
if id == nil { browseReader.reset() }
|
||||
else if !searching { compactReader = true }
|
||||
}
|
||||
.onChange(of: searchID) { _, id in
|
||||
if id == nil { searchReader.reset() }
|
||||
else if searching { compactReader = true }
|
||||
}
|
||||
.onDisappear { browseReader.stop(); searchReader.stop() }
|
||||
}
|
||||
|
||||
private func header(narrow: Bool, sidebar side: Bool) -> some View {
|
||||
HStack {
|
||||
if narrow, compactReader {
|
||||
Button { compactReader = false } label: { Label(searching ? "Results" : "Browse", systemImage: "chevron.left") }
|
||||
} else if !side {
|
||||
Button { showCollections.toggle() } label: { Label("Collections", systemImage: "sidebar.left") }
|
||||
.popover(isPresented: $showCollections) { sidebar.frame(width: 255, height: 360) }
|
||||
}
|
||||
HStack(spacing: 5) {
|
||||
Button { queryFocused = true } label: { Image(systemName: "magnifyingglass").foregroundStyle(.secondary) }
|
||||
.buttonStyle(.plain).keyboardShortcut("f", modifiers: [.command, .shift]).accessibilityLabel("Focus Archive search")
|
||||
TextField("Search Archive", text: $archiveQuery.text).textFieldStyle(.plain).focused($queryFocused)
|
||||
.accessibilityLabel("Search Archive").accessibilityIdentifier("archive-search")
|
||||
Button { archiveQuery.text = ""; queryFocused = true } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) }
|
||||
.buttonStyle(.plain).accessibilityLabel("Clear Archive search")
|
||||
.opacity(query.isEmpty ? 0 : 1).disabled(query.isEmpty).accessibilityHidden(query.isEmpty)
|
||||
}.padding(6).background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
|
||||
Picker("Search scope", selection: $localScope) {
|
||||
Text("Entire Archive").tag(false)
|
||||
Text(scopePath?.split(separator: "/").last.map(String.init) ?? "Current collection").tag(true).disabled(scopePath == nil)
|
||||
}.labelsHidden().frame(width: narrow ? 115 : 160).accessibilityLabel("Archive search scope")
|
||||
Button { MCPArchiveAccess.shared.show() } label: { Image(systemName: "link") }
|
||||
.help("Archive Search connection for MCP").accessibilityLabel("Archive Search connection for MCP")
|
||||
}.padding(8)
|
||||
}
|
||||
|
||||
private var sidebar: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
Button { chooseCollection("") } label: {
|
||||
Label("All Documents", systemImage: "books.vertical")
|
||||
.fontWeight(sidebarPath.isEmpty ? .semibold : .regular)
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(6)
|
||||
.background(sidebarPath.isEmpty ? Color.accentColor.opacity(0.13) : .clear, in: RoundedRectangle(cornerRadius: 5))
|
||||
}.buttonStyle(.plain).padding(7).accessibilityAddTraits(sidebarPath.isEmpty ? .isSelected : [])
|
||||
List(selection: Binding<String?>(get: { sidebarPath.isEmpty ? nil : sidebarPath }, set: { if let value = $0 { chooseCollection(value) } })) {
|
||||
Section("Collections") {
|
||||
OutlineGroup(collections, children: \.children) { folder in
|
||||
Label(folder.name, systemImage: folder.children == nil ? "folder" : "folder.fill").tag(folder.id)
|
||||
}
|
||||
}
|
||||
}.listStyle(.sidebar).accessibilityLabel("Archive collections")
|
||||
}
|
||||
}
|
||||
|
||||
private func chooseCollection(_ path: String) {
|
||||
showCollections = false
|
||||
if searching {
|
||||
if path != sidebarPath { searchID = nil; searchReader.reset() }
|
||||
searchFolder = path; searchOffset = 0; localScope = !path.isEmpty; compactReader = false
|
||||
return
|
||||
}
|
||||
guard path != collection else { return }
|
||||
collection = path; browseID = nil; browseOffset = 0; compactReader = false; browseReader.reset()
|
||||
}
|
||||
|
||||
private var listing: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack {
|
||||
Text(searching ? "Matching pages" : (collection.isEmpty ? "All Documents" : String(collection.split(separator: "/").last ?? ""))).font(.headline)
|
||||
Spacer()
|
||||
if searching ? searchBusy : browseBusy { ProgressView().controlSize(.small) }
|
||||
}.padding(10)
|
||||
Divider()
|
||||
if let error = searching ? searchError : browseError {
|
||||
VStack(spacing: 8) { Text(error).multilineTextAlignment(.center); Button("Try Again") { retry += 1 } }.padding().frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
// Keeping the browse List mounted preserves its scroll position and selection through a search.
|
||||
ZStack {
|
||||
browseList.opacity(searching ? 0 : 1).allowsHitTesting(!searching).accessibilityHidden(searching).disabled(searching)
|
||||
if searching { resultsList }
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Button { moveBatch(-1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous results").disabled((searching ? searchOffset : browseOffset) == 0)
|
||||
let count = searching ? hits.count : documents.count
|
||||
if count > 0 { let offset = searching ? searchOffset : browseOffset; Text("\(offset + 1)–\(offset + count)").font(.caption).monospacedDigit() }
|
||||
Button { moveBatch(1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next results").disabled(!(searching ? searchMore : browseMore))
|
||||
Spacer()
|
||||
}.padding(8)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var browseList: some View {
|
||||
List(selection: $browseID) {
|
||||
ForEach(documents) { doc in
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(doc.title).lineLimit(2)
|
||||
Text(doc.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
}.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id)
|
||||
.simultaneousGesture(TapGesture().onEnded { browseID = doc.id; compactReader = true })
|
||||
}
|
||||
}.accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list")
|
||||
.onKeyPress(.return, action: readSelectedWithKeyboard)
|
||||
.overlay { if documents.isEmpty, !browseBusy { ContentUnavailableView("No documents in this collection", systemImage: "books.vertical") } }
|
||||
}
|
||||
|
||||
private var groups: [ArchiveResultGroup] {
|
||||
var ordered: [ArchiveResultGroup] = []; var indices: [String: Int] = [:]
|
||||
for item in hits {
|
||||
if let index = indices[item.document.id] { ordered[index].hits.append(item) }
|
||||
else { indices[item.document.id] = ordered.count; ordered.append(.init(document: item.document, hits: [item])) }
|
||||
}
|
||||
return ordered
|
||||
}
|
||||
private var resultsList: some View {
|
||||
List(selection: $searchID) {
|
||||
ForEach(groups) { group in
|
||||
Section {
|
||||
ForEach(group.hits) { result in
|
||||
HStack { Text(result.locator); if result.ocr { Text("OCR").font(.caption).foregroundStyle(.secondary) } }
|
||||
.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id)
|
||||
.simultaneousGesture(TapGesture().onEnded { searchID = result.id; compactReader = true })
|
||||
}
|
||||
} header: { Text(group.document.title).lineLimit(3).textCase(nil) }
|
||||
}
|
||||
}.accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list")
|
||||
.onKeyPress(.return, action: readSelectedWithKeyboard)
|
||||
.overlay { if hits.isEmpty, !searchBusy { ContentUnavailableView("No matching pages", systemImage: "magnifyingglass") } }
|
||||
}
|
||||
|
||||
@ViewBuilder private var detail: some View {
|
||||
if let selected {
|
||||
ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog)
|
||||
} else { ContentUnavailableView("Choose a document", systemImage: "book.pages", description: Text("Browse a collection or search the Archive.")) }
|
||||
}
|
||||
private func moveBatch(_ direction: Int) {
|
||||
if searching { searchOffset = max(0, searchOffset + direction * batch); searchID = nil }
|
||||
else { browseOffset = max(0, browseOffset + direction * batch); browseID = nil }
|
||||
}
|
||||
private func readSelectedWithKeyboard() -> KeyPress.Result {
|
||||
guard selected != nil else { return .ignored }
|
||||
// On compact layouts Return can reopen the current row after Back.
|
||||
Task { @MainActor in compactReader = true }
|
||||
return .handled
|
||||
}
|
||||
private func loadBrowse() async {
|
||||
let request = ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)
|
||||
browseBusy = true; browseError = nil
|
||||
do {
|
||||
let rows = try await catalog.browse(collection: collection.isEmpty ? nil : collection, limit: batch + 1, offset: browseOffset)
|
||||
try Task.checkCancellation()
|
||||
guard request == ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry) else { return }
|
||||
documents = Array(rows.prefix(batch)); browseMore = rows.count > batch
|
||||
if !documents.contains(where: { $0.id == browseID }) { browseID = nil }
|
||||
browseBusy = false
|
||||
} catch { if !Task.isCancelled { browseError = error.localizedDescription; browseBusy = false } }
|
||||
}
|
||||
private func loadSearch(_ request: ArchiveSearchRequest) async {
|
||||
searchError = nil; hits = []; searchMore = false
|
||||
guard searching else { searchBusy = false; return }
|
||||
searchBusy = true
|
||||
do {
|
||||
try await Task.sleep(for: .milliseconds(180))
|
||||
let rows = try await catalog.search(query: request.query, collection: request.collection, limit: batch + 1, offset: request.offset)
|
||||
try Task.checkCancellation(); guard key == request else { return }
|
||||
hits = Array(rows.prefix(batch)); searchMore = rows.count > batch
|
||||
if !hits.contains(where: { $0.id == searchID }) { searchID = nil }; searchBusy = false
|
||||
} catch { if !Task.isCancelled { searchError = error.localizedDescription; searchBusy = false } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
struct AssemblyDiagnostic: Hashable, Sendable {
|
||||
let path: String
|
||||
let line: Int
|
||||
let message: String
|
||||
}
|
||||
|
||||
struct AssemblyBuildFailure: LocalizedError {
|
||||
let message: String
|
||||
let diagnostics: [AssemblyDiagnostic]
|
||||
init(_ message: String, diagnostics: [AssemblyDiagnostic] = []) {
|
||||
self.message = message
|
||||
self.diagnostics = diagnostics
|
||||
}
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
struct AssemblyInstructionLocation: Hashable, Sendable {
|
||||
let path: String
|
||||
let line: Int
|
||||
let address: UInt16
|
||||
let bytes: [UInt8]
|
||||
}
|
||||
|
||||
struct AssemblyBuildArtifact: Sendable {
|
||||
let id: UUID
|
||||
let snapshot: AssemblyProjectSnapshot
|
||||
let binaryData: Data
|
||||
let entry: UInt16
|
||||
let ranges: [ClosedRange<UInt16>]
|
||||
let listing: String
|
||||
let symbols: String
|
||||
let buildLog: String
|
||||
let instructions: [AssemblyInstructionLocation]
|
||||
}
|
||||
|
||||
/// Export accepts the full DECB address space. The machine's loader separately
|
||||
/// decides whether a given block and entry are safe in its current RAM mapping.
|
||||
private struct AssemblyImage {
|
||||
let entry: UInt16
|
||||
let ranges: [ClosedRange<UInt16>]
|
||||
let bytes: [Int: UInt8]
|
||||
init(_ data: Data) throws {
|
||||
var offset = 0, ranges: [ClosedRange<UInt16>] = [], memory: [Int: UInt8] = [:]
|
||||
var entry: UInt16?, ambiguous = false
|
||||
while offset + 5 <= data.count {
|
||||
let type = data[offset], length = Int(data[offset + 1]) * 256 + Int(data[offset + 2])
|
||||
let start = Int(data[offset + 3]) * 256 + Int(data[offset + 4])
|
||||
offset += 5
|
||||
if type == 255 {
|
||||
guard length == 0, offset == data.count else { throw AssemblyBuildFailure("Malformed DECB execution record.") }
|
||||
entry = UInt16(start)
|
||||
break
|
||||
}
|
||||
guard type == 0, length <= data.count - offset else { throw AssemblyBuildFailure("Malformed DECB load block.") }
|
||||
if length > 0 {
|
||||
let end = start + length - 1
|
||||
ranges.append(UInt16(start)...UInt16(min(end, 65535)))
|
||||
if end > 65535 { ranges.append(0...UInt16(end - 65536)); ambiguous = true }
|
||||
for index in 0..<length {
|
||||
if memory.updateValue(data[offset + index], forKey: start + index) != nil { ambiguous = true }
|
||||
}
|
||||
}
|
||||
offset += length
|
||||
}
|
||||
guard let entry else { throw AssemblyBuildFailure("The binary is missing its DECB execution record.") }
|
||||
self.entry = entry
|
||||
self.ranges = ranges
|
||||
self.bytes = ambiguous ? [:] : memory
|
||||
}
|
||||
}
|
||||
|
||||
struct DevelopmentBuildTools: Sendable {
|
||||
let toolchain: URL
|
||||
init(toolchain: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/Toolchain")) {
|
||||
self.toolchain = toolchain
|
||||
}
|
||||
|
||||
static func readFile(_ url: URL, limit: Int) throws -> Data {
|
||||
let properties = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard properties.isRegularFile == true, properties.isSymbolicLink != true,
|
||||
let size = properties.fileSize, size <= limit else {
|
||||
throw AssemblyBuildFailure("The file is missing, linked, or exceeds its size limit: " + url.lastPathComponent)
|
||||
}
|
||||
let handle = try FileHandle(forReadingFrom: url)
|
||||
defer { try? handle.close() }
|
||||
let bytes = try handle.read(upToCount: limit + 1) ?? Data()
|
||||
guard bytes.count <= limit else { throw AssemblyBuildFailure("File grew beyond its size limit.") }
|
||||
return bytes
|
||||
}
|
||||
|
||||
func withWorkspace<T: Sendable>(_ body: @escaping @Sendable (URL, DevelopmentProcessControl) throws -> T) async throws -> T {
|
||||
let control = DevelopmentProcessControl()
|
||||
return try await withTaskCancellationHandler {
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
try control.checkCancellation()
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCC-Development-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let result = try body(root, control)
|
||||
try control.checkCancellation()
|
||||
return result
|
||||
}.value
|
||||
} onCancel: { control.cancel() }
|
||||
}
|
||||
|
||||
func run(_ name: String, _ arguments: [String], in folder: URL,
|
||||
control: DevelopmentProcessControl, cpu: AssemblyCPU = .mc6809) throws -> (status: Int32, text: String) {
|
||||
let bin = toolchain.appendingPathComponent("bin")
|
||||
let executable = bin.appendingPathComponent(name)
|
||||
guard FileManager.default.isExecutableFile(atPath: executable.path) else {
|
||||
throw AssemblyBuildFailure("The bundled development tool is missing: " + name)
|
||||
}
|
||||
let environment = ["PATH": bin.path + ":/usr/bin:/bin", "LC_ALL": "C", "TMPDIR": folder.path,
|
||||
"LWASM": "lwasm", "LWLINK": "lwlink", "ASFLAGS": "--" + cpu.rawValue,
|
||||
"VCC_TOOLCHAIN": toolchain.path]
|
||||
return try control.run(executable: executable, arguments: arguments, directory: folder,
|
||||
environment: environment, timeout: 120)
|
||||
}
|
||||
|
||||
/// BASIC already produced a fresh tokenized disk. Stage only that image so a
|
||||
/// failed tool invocation cannot alter a mounted disk or the chosen destination.
|
||||
func bootableBASICDisk(_ disk: Data, name: String) async throws -> Data {
|
||||
guard let name = BASICExportName.normalized(name) else { throw AssemblyBuildFailure("Invalid Disk BASIC program name.") }
|
||||
return try await withWorkspace { root, control in
|
||||
let url = root.appendingPathComponent("export.dsk")
|
||||
try disk.write(to: url)
|
||||
try installBootLoader(.basic(name), in: root, control: control)
|
||||
return try Self.readFile(url, limit: 35 * 18 * 256)
|
||||
}
|
||||
}
|
||||
|
||||
func installBootLoader(_ program: DevelopmentDiskProgram, in root: URL, control: DevelopmentProcessControl) throws {
|
||||
// Both callers validate the on-disk name before it becomes a C literal.
|
||||
let command = program.bootCommand.replacingOccurrences(of: "\"", with: "\\\"")
|
||||
let source = "#define COMMAND \"\(command)\"\n" + CMOCMakefileSettings.dosBootLoaderSource
|
||||
try Data(source.utf8).write(to: root.appendingPathComponent("loader.c"))
|
||||
let compiled = try run("cmoc", ["--dos", "-O0", "--limit=2800", "-o", "loader.bin", "loader.c"], in: root, control: control)
|
||||
guard compiled.status == 0 else { throw AssemblyBuildFailure("Could not build the DOS bootloader.\n" + compiled.text) }
|
||||
let installed = try run("install-coco-boot-loader", ["export.dsk", "loader.bin"], in: root, control: control)
|
||||
guard installed.status == 0 else { throw AssemblyBuildFailure("Could not install the DOS bootloader.\n" + installed.text) }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct AssemblyBuildService: Sendable {
|
||||
let tools: DevelopmentBuildTools
|
||||
init(toolchain: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/Toolchain")) {
|
||||
tools = DevelopmentBuildTools(toolchain: toolchain)
|
||||
}
|
||||
|
||||
func build(_ snapshot: AssemblyProjectSnapshot) async throws -> AssemblyBuildArtifact {
|
||||
try await tools.withWorkspace { root, control in
|
||||
try snapshot.validate()
|
||||
let workspace = root.appendingPathComponent("src")
|
||||
let output = root.appendingPathComponent("out")
|
||||
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
|
||||
for (path, data) in snapshot.files {
|
||||
try control.checkCancellation()
|
||||
let url = workspace.appendingPathComponent(path)
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try data.write(to: url, options: .withoutOverwriting)
|
||||
}
|
||||
var log = "", listings: [String] = [], symbols = ""
|
||||
var objects: [String] = [], modules: [(object: String, records: String)] = []
|
||||
func invoke(_ tool: String, _ args: [String]) throws -> String {
|
||||
let result = try tools.run(tool, args, in: workspace, control: control, cpu: snapshot.cpu)
|
||||
let command = ([tool] + args).joined(separator: " ")
|
||||
if log.utf8.count < 512 * 1024 { log += command + "\n" + result.text + "\n" }
|
||||
guard result.status == 0 else {
|
||||
throw AssemblyBuildFailure(command + "\n" + result.text, diagnostics: Self.diagnostics(result.text, files: snapshot.files))
|
||||
}
|
||||
return result.text
|
||||
}
|
||||
var binaryURL = output.appendingPathComponent("program.bin")
|
||||
let settings = snapshot.settings
|
||||
if let makefile = settings.makefile, let binary = settings.binary {
|
||||
_ = try invoke("make", ["-B", "-f", "./" + makefile, "MAKE=make", "--", settings.target ?? "all"])
|
||||
binaryURL = workspace.appendingPathComponent(binary)
|
||||
guard binaryURL.resolvingSymlinksInPath().path == workspace.resolvingSymlinksInPath().appendingPathComponent(binary).path else {
|
||||
throw AssemblyBuildFailure("The Makefile must produce a regular binary within the build folder.")
|
||||
}
|
||||
log += "Custom Make declares the CPU target in its recipe. Its instruction set and source locations are unverified. Use the machine debugger.\n"
|
||||
} else {
|
||||
let linked = settings.linkScript != nil
|
||||
_ = try invoke("lwasm", ["--version"])
|
||||
for (index, path) in ([snapshot.mainPath] + (settings.modules ?? [])).enumerated() {
|
||||
let stem = "../out/module" + String(index)
|
||||
let object = stem + ".o"
|
||||
let flags = ["--project-inputs", "--" + snapshot.cpu.rawValue, linked ? "--obj" : "--decb", "--error-format=gcc", "-I."]
|
||||
let fileArg = "./" + path
|
||||
_ = try invoke("lwasm", flags + ["--tabs=0", "--list=" + stem + ".lst", "--project-map=" + stem + ".lines",
|
||||
"--symbol-dump=" + stem + ".sym", "-o", linked ? object : "../out/program.bin", fileArg])
|
||||
let records = try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(stem + ".lines"), limit: 4 * 1024 * 1024)
|
||||
let list = try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(stem + ".lst"), limit: 8 * 1024 * 1024)
|
||||
let listing = String(decoding: list, as: UTF8.self)
|
||||
guard listings.reduce(listing.utf8.count, { $0 + $1.utf8.count }) <= 16 * 1024 * 1024 else {
|
||||
throw AssemblyBuildFailure("Combined listings exceed 16 MB.")
|
||||
}
|
||||
modules.append((object, String(decoding: records, as: UTF8.self)))
|
||||
listings.append(listing)
|
||||
if linked { objects.append(object) }
|
||||
else {
|
||||
symbols = String(decoding: try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(stem + ".sym"), limit: 4 * 1024 * 1024), as: UTF8.self)
|
||||
}
|
||||
}
|
||||
if let script = settings.linkScript {
|
||||
_ = try invoke("lwlink", ["--version"])
|
||||
_ = try invoke("lwlink", ["--decb", "--script=./" + script, "--map=../out/link.map", "-o", "../out/program.bin"] + objects)
|
||||
symbols = String(decoding: try DevelopmentBuildTools.readFile(output.appendingPathComponent("link.map"), limit: 4 * 1024 * 1024), as: UTF8.self)
|
||||
}
|
||||
}
|
||||
let binary = try DevelopmentBuildTools.readFile(binaryURL, limit: BinaryFile.limit)
|
||||
let image = try AssemblyImage(binary)
|
||||
var instructions: [AssemblyInstructionLocation] = []
|
||||
for (object, records) in modules {
|
||||
try control.checkCancellation()
|
||||
var sections: [String: CMOCSourceMap.VerifiedSection]?
|
||||
if settings.linkScript != nil {
|
||||
do {
|
||||
let data = try DevelopmentBuildTools.readFile(workspace.appendingPathComponent(object), limit: 8 * 1024 * 1024)
|
||||
sections = try CMOCSourceMap.verifiedSections(object: data, objectName: object, linkMap: Data(symbols.utf8), binary: binary).sections
|
||||
} catch {
|
||||
log += "Source locations unavailable for " + object + ". " + error.localizedDescription + "\n"
|
||||
continue
|
||||
}
|
||||
}
|
||||
instructions += Self.locations(records, files: snapshot.files, image: image, sections: sections)
|
||||
}
|
||||
// Repeated include expansions or two rows claiming a PC are ambiguous.
|
||||
let addresses = Dictionary(grouping: instructions, by: \.address)
|
||||
let lines = Dictionary(grouping: instructions) { $0.path + "\n" + String($0.line) }
|
||||
let verified = instructions.filter { addresses[$0.address]?.count == 1 && lines[$0.path + "\n" + String($0.line)]?.count == 1 }
|
||||
return AssemblyBuildArtifact(id: UUID(), snapshot: snapshot, binaryData: binary, entry: image.entry,
|
||||
ranges: image.ranges, listing: listings.joined(separator: "\n"), symbols: symbols, buildLog: log, instructions: verified)
|
||||
}
|
||||
}
|
||||
|
||||
func diskImage(for artifact: AssemblyBuildArtifact, name: String, dosBoot: Bool = false) async throws -> Data {
|
||||
let dosName = name.uppercased()
|
||||
guard dosName.range(of: #"\A[A-Z0-9][A-Z0-9_-]{0,7}\z"#, options: .regularExpression) != nil else {
|
||||
throw AssemblyBuildFailure("Use a Disk BASIC name of one to eight letters or digits, with optional hyphens or underscores.")
|
||||
}
|
||||
return try await tools.withWorkspace { root, control in
|
||||
let image = root.appendingPathComponent("export.dsk")
|
||||
try Data(repeating: 0xff, count: 35 * 18 * 256).write(to: image)
|
||||
if dosBoot {
|
||||
try tools.installBootLoader(.binary(dosName), in: root, control: control)
|
||||
}
|
||||
let file = dosName + ".BIN"
|
||||
try artifact.binaryData.write(to: root.appendingPathComponent(file))
|
||||
let result = try tools.run("writecocofile", ["export.dsk", file], in: root, control: control)
|
||||
guard result.status == 0 else { throw AssemblyBuildFailure(result.text) }
|
||||
return try DevelopmentBuildTools.readFile(image, limit: 35 * 18 * 256)
|
||||
}
|
||||
}
|
||||
|
||||
private static func diagnostics(_ text: String, files: [String: Data]) -> [AssemblyDiagnostic] {
|
||||
let pattern = try! NSRegularExpression(pattern: #"^(.+?):([0-9]+): (?:error|warning): (.+)$"#)
|
||||
return text.components(separatedBy: .newlines).compactMap { row in
|
||||
guard let fields = groups(pattern, row), let number = Int(fields[2]),
|
||||
let path = sourcePath(fields[1], in: Set(files.keys)) else { return nil }
|
||||
return AssemblyDiagnostic(path: path, line: number, message: fields[3])
|
||||
}
|
||||
}
|
||||
|
||||
private static func groups(_ regex: NSRegularExpression, _ row: String) -> [String]? {
|
||||
let ns = row as NSString
|
||||
guard let match = regex.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) else { return nil }
|
||||
return (0..<match.numberOfRanges).map { ns.substring(with: match.range(at: $0)) }
|
||||
}
|
||||
|
||||
private static func sourcePath(_ token: String, in inputs: Set<String>) -> String? {
|
||||
var token = token
|
||||
while token.hasPrefix("./") { token.removeFirst(2) }
|
||||
guard !token.isEmpty else { return nil }
|
||||
let candidates = inputs.filter { path in
|
||||
path == token || path.hasSuffix("/" + token)
|
||||
}
|
||||
return candidates.count == 1 ? candidates.first : nil
|
||||
}
|
||||
|
||||
/// Physical source names, lines and section names come directly from LWASM.
|
||||
/// The display listing abbreviates names and can include macro expansions.
|
||||
private static func locations(_ records: String, files: [String: Data], image: AssemblyImage,
|
||||
sections: [String: CMOCSourceMap.VerifiedSection]?) -> [AssemblyInstructionLocation] {
|
||||
var result: [AssemblyInstructionLocation] = []
|
||||
for row in records.split(whereSeparator: \.isNewline) {
|
||||
let fields = row.split(separator: "\t", omittingEmptySubsequences: false)
|
||||
guard fields.count == 5, let line = Int(fields[1]), line > 0, let offset = Int(fields[3], radix: 16),
|
||||
(0..<65536).contains(offset) else { continue }
|
||||
let path = String(fields[0]), digits = Array(fields[4])
|
||||
guard files[path] != nil, (2...16).contains(digits.count), digits.count.isMultiple(of: 2) else { continue }
|
||||
let original = stride(from: 0, to: digits.count, by: 2).compactMap { UInt8(String(digits[$0...($0 + 1)]), radix: 16) }
|
||||
guard original.count * 2 == digits.count else { continue }
|
||||
let address: Int, bytes: [UInt8]
|
||||
if let sections {
|
||||
guard let section = sections[String(fields[2])], let final = section.final,
|
||||
offset + original.count <= section.original.count,
|
||||
section.original[offset..<(offset + original.count)].elementsEqual(original) else { continue }
|
||||
address = section.base + offset
|
||||
bytes = Array(final[offset..<(offset + original.count)])
|
||||
} else {
|
||||
guard fields[2].isEmpty else { continue }
|
||||
address = offset
|
||||
bytes = original
|
||||
}
|
||||
guard address + bytes.count <= 65536,
|
||||
bytes.enumerated().allSatisfy({ image.bytes[address + $0.offset] == $0.element }) else { continue }
|
||||
result.append(.init(path: path, line: line, address: UInt16(address), bytes: bytes))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
struct AssemblyBuffer: Codable, Identifiable, Sendable {
|
||||
var id = UUID()
|
||||
var path: String
|
||||
var text: String
|
||||
var saved: String?
|
||||
var dirty: Bool { saved.map { !text.utf8.elementsEqual($0.utf8) } ?? true }
|
||||
}
|
||||
|
||||
struct AssemblyWorkspaceDocument: Codable, Identifiable, Sendable {
|
||||
var id = UUID()
|
||||
var title: String
|
||||
var directory: URL?
|
||||
var isProject = false
|
||||
var mainPath: String
|
||||
var buffers: [AssemblyBuffer]
|
||||
var selectedPath: String
|
||||
var cpu: AssemblyCPU = .mc6809
|
||||
var breakpoints = Set<AssemblyDevelopmentModel.SourceLine>()
|
||||
var paths: [String] = []
|
||||
var inputPaths: [String]?
|
||||
|
||||
static let starterTitle = "Hello World — Earth or Mars"
|
||||
static let starterSource = DevelopmentStarterSource.planet(withExtension: "asm")
|
||||
?? "; The Earth or Mars example is missing. Reinstall VCC Plus to restore it.\n"
|
||||
|
||||
static func example(title: String, source: String, cpu: AssemblyCPU) -> Self {
|
||||
let file = AssemblyBuffer(path: "main.asm", text: source, saved: nil)
|
||||
return Self(title: title, mainPath: file.path, buffers: [file], selectedPath: file.path, cpu: cpu)
|
||||
}
|
||||
|
||||
static func open(_ url: URL, folder: Bool) throws -> Self {
|
||||
let physical = URL(fileURLWithPath: try CMOCProject.physicalURL(url).path, isDirectory: folder)
|
||||
let snapshot = try folder ? AssemblyProjectSnapshot.read(directory: physical) : AssemblyProjectSnapshot.readSource(at: physical)
|
||||
guard let data = snapshot.files[snapshot.mainPath], let text = String(data: data, encoding: .utf8) else {
|
||||
throw AssemblyBuildFailure("The entry source must be a UTF-8 text file.")
|
||||
}
|
||||
return Self(title: physical.lastPathComponent, directory: folder ? physical : physical.deletingLastPathComponent(),
|
||||
isProject: folder, mainPath: snapshot.mainPath,
|
||||
buffers: [.init(path: snapshot.mainPath, text: text, saved: text)], selectedPath: snapshot.mainPath,
|
||||
paths: editablePaths(snapshot), inputPaths: Array(snapshot.files.keys))
|
||||
}
|
||||
|
||||
static func editablePaths(_ snapshot: AssemblyProjectSnapshot) -> [String] {
|
||||
snapshot.files.keys.filter {
|
||||
["asm", "s", "inc", "lwasm", "link", "lw", "json", "mk"].contains(URL(fileURLWithPath: $0).pathExtension.lowercased()) ||
|
||||
$0 == snapshot.settings.linkScript || $0 == snapshot.settings.makefile || $0 == "Makefile" || $0 == snapshot.mainPath
|
||||
}.sorted()
|
||||
}
|
||||
|
||||
func checkedURL(_ path: String) throws -> URL {
|
||||
try CMOCProject.validateRelativePath(path)
|
||||
guard let directory else { throw AssemblyBuildFailure("Save the source before opening relative files.") }
|
||||
let url = directory.appendingPathComponent(path)
|
||||
let candidate = FileManager.default.fileExists(atPath: url.path) ? url : url.deletingLastPathComponent()
|
||||
// directory was canonicalized at Open/Save. Foundation standardization
|
||||
// may shorten /private/var to /var; compare the two physical spellings.
|
||||
guard try CMOCProject.physicalURL(candidate).path == candidate.path,
|
||||
(try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)) == nil else {
|
||||
throw AssemblyBuildFailure("The project path now points through a symbolic link: " + path)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
func snapshot() throws -> AssemblyProjectSnapshot {
|
||||
guard let directory else {
|
||||
guard let entry = buffers.first(where: { $0.path == mainPath }) else { throw AssemblyBuildFailure("Entry source is missing.") }
|
||||
return .single(source: entry.text, path: mainPath, cpu: cpu)
|
||||
}
|
||||
var overlays: [String: String] = [:]
|
||||
for buffer in buffers {
|
||||
let url = try checkedURL(buffer.path)
|
||||
if let saved = buffer.saved {
|
||||
guard try CMOCProject.readText(url, maximumBytes: CMOCProject.maximumSourceBytes) == saved else {
|
||||
throw AssemblyBuildFailure("\(buffer.path) changed on disk. Reload it or save your edits separately.")
|
||||
}
|
||||
} else if FileManager.default.fileExists(atPath: url.path) {
|
||||
throw AssemblyBuildFailure("\(buffer.path) appeared on disk. Reload it before building.")
|
||||
}
|
||||
if buffer.dirty { overlays[buffer.path] = buffer.text }
|
||||
}
|
||||
if isProject { return try .read(directory: directory, mainPath: mainPath, overlays: overlays, cpu: cpu) }
|
||||
return try .readSource(at: checkedURL(mainPath), overlays: overlays, cpu: cpu)
|
||||
}
|
||||
}
|
||||
|
||||
struct AssemblyRecovery: Codable, Sendable {
|
||||
var version = 1
|
||||
var documents: [AssemblyWorkspaceDocument]
|
||||
var active: UUID
|
||||
|
||||
func write(to url: URL) throws {
|
||||
let data = try JSONEncoder().encode(self)
|
||||
guard data.count <= 64 * 1024 * 1024 else { throw AssemblyBuildFailure("Assembly drafts exceed the 64 MB recovery limit. Save and close completed documents.") }
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try data.write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
static func read(from url: URL) throws -> Self {
|
||||
let values = try url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey])
|
||||
guard values.isRegularFile == true, let size = values.fileSize, size <= 64 * 1024 * 1024 else { throw CocoaError(.fileReadTooLarge) }
|
||||
let saved = try JSONDecoder().decode(Self.self, from: Data(contentsOf: url))
|
||||
guard saved.version == 1, saved.documents.contains(where: { $0.id == saved.active }),
|
||||
Set(saved.documents.map(\.id)).count == saved.documents.count else { throw CocoaError(.fileReadCorruptFile) }
|
||||
var bufferIDs = Set<UUID>()
|
||||
for doc in saved.documents {
|
||||
guard doc.buffers.contains(where: { $0.path == doc.selectedPath }),
|
||||
doc.buffers.contains(where: { $0.path == doc.mainPath }),
|
||||
Set(doc.buffers.map(\.path)).count == doc.buffers.count else { throw CocoaError(.fileReadCorruptFile) }
|
||||
for buffer in doc.buffers {
|
||||
try CMOCProject.validateRelativePath(buffer.path)
|
||||
guard bufferIDs.insert(buffer.id).inserted else { throw CocoaError(.fileReadCorruptFile) }
|
||||
}
|
||||
}
|
||||
return saved
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
@MainActor
|
||||
final class AssemblyDevelopmentModel: ObservableObject {
|
||||
struct SourceLine: Hashable, Codable, Sendable {
|
||||
let path: String
|
||||
let line: Int
|
||||
}
|
||||
struct Selection { let id = UUID(); let buffer: UUID; let range: NSRange }
|
||||
enum Action { case assemble, run, debug, exportBinary(URL), exportDisk(URL, String, dosBoot: Bool) }
|
||||
struct Attachment {
|
||||
let document: UUID
|
||||
let artifact: AssemblyBuildArtifact
|
||||
var expected: VCCMachineSnapshot
|
||||
var guards: [UInt16: Data]
|
||||
}
|
||||
|
||||
let machine: MachineModel
|
||||
let service: AssemblyBuildService
|
||||
private(set) var recoveryURL: URL
|
||||
private let recoveryQueue = DispatchQueue(label: "VCCPlus.AssemblyRecovery")
|
||||
private var recoveryTask: Task<Void, Never>?
|
||||
@Published private(set) var documents: [AssemblyWorkspaceDocument]
|
||||
@Published private(set) var activeID: UUID
|
||||
@Published private(set) var artifact: AssemblyBuildArtifact?
|
||||
@Published private(set) var diagnostics: [AssemblyDiagnostic] = []
|
||||
@Published var message = "Ready to assemble."
|
||||
@Published var buildLog = ""
|
||||
@Published private(set) var working = false
|
||||
@Published private(set) var cursor = 0
|
||||
@Published private(set) var selection: Selection?
|
||||
@Published private(set) var executionLine: SourceLine?
|
||||
@Published private(set) var execution = ""
|
||||
@Published private(set) var commanding = false
|
||||
@Published private(set) var attached = false
|
||||
@Published private(set) var paused = false
|
||||
@Published private(set) var displayRequest = 0
|
||||
private var cursors: [UUID: Int] = [:]
|
||||
private var fileRequest = UUID()
|
||||
private var work: Task<Void, Never>?
|
||||
private var revision = UUID()
|
||||
var workspaceRevision: UUID { revision }
|
||||
@Published private(set) var sourceRevision = UUID()
|
||||
private var connection: Attachment?
|
||||
// Remember ownership across source edits so a repeat Run can replace our own bytes immediately.
|
||||
private var owner: (document: UUID, generation: UInt64, revision: UInt64)?
|
||||
private var reading = false
|
||||
private var checking = false
|
||||
private var nextCheck = Date.distantPast
|
||||
private var index: Int { documents.firstIndex { $0.id == activeID }! }
|
||||
var document: AssemblyWorkspaceDocument { documents[index] }
|
||||
var buffer: AssemblyBuffer { document.buffers.first { $0.path == document.selectedPath }! }
|
||||
var cpu: AssemblyCPU { document.cpu }
|
||||
|
||||
init(machine: MachineModel, service: AssemblyBuildService = .init(), recoveryURL: URL? = nil) {
|
||||
self.machine = machine; self.service = service
|
||||
self.recoveryURL = recoveryURL ?? machine.developmentRunDirectory.deletingLastPathComponent().appendingPathComponent("Assembly Workspace/Drafts.json")
|
||||
let first = AssemblyWorkspaceDocument.example(title: AssemblyWorkspaceDocument.starterTitle, source: AssemblyWorkspaceDocument.starterSource, cpu: .mc6809)
|
||||
documents = [first]; activeID = first.id
|
||||
while FileManager.default.fileExists(atPath: self.recoveryURL.path) {
|
||||
do {
|
||||
let saved = try AssemblyRecovery.read(from: self.recoveryURL)
|
||||
documents = saved.documents; activeID = saved.active
|
||||
message = "Restored assembly workspace."
|
||||
break
|
||||
} catch {
|
||||
// Preserve an unreadable record at its original location. New sessions
|
||||
// use a neighboring recovery file that is discovered on the next launch.
|
||||
self.recoveryURL = self.recoveryURL.deletingPathExtension().appendingPathExtension("recovered.json")
|
||||
message = "The previous Assembly draft file could not be read. It has been preserved separately."
|
||||
}
|
||||
}
|
||||
indexLabels()
|
||||
}
|
||||
|
||||
static func lineRange(_ line: Int, text: String) -> NSRange? {
|
||||
guard line > 0 else { return nil }
|
||||
let ns = text as NSString
|
||||
var start = 0
|
||||
for _ in 1..<line {
|
||||
guard start < ns.length else { return nil }
|
||||
start = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
|
||||
}
|
||||
return ns.lineRange(for: NSRange(location: start, length: 0))
|
||||
}
|
||||
var cursorLine: Int {
|
||||
(buffer.text as NSString).substring(to: min(cursor, buffer.text.utf16.count)).components(separatedBy: "\n").count
|
||||
}
|
||||
func moveCursor(_ offset: Int) {
|
||||
let next = min(max(offset, 0), buffer.text.utf16.count)
|
||||
cursors[buffer.id] = next
|
||||
if cursor != next { cursor = next }
|
||||
}
|
||||
|
||||
func select(_ id: UUID) {
|
||||
guard id != activeID, documents.contains(where: { $0.id == id }) else { return }
|
||||
cancelPending()
|
||||
activeID = id; restoreCursor()
|
||||
artifact = connection?.document == id ? connection?.artifact : nil
|
||||
diagnostics = []; buildLog = artifact?.buildLog ?? ""
|
||||
executionLine = nil; execution = ""; attached = connection?.document == id; paused = false
|
||||
message = "Ready to assemble."; labelLocations = []; indexLabels(); scheduleRecovery(); refresh()
|
||||
}
|
||||
|
||||
func openExample(title: String, source: String, target6309: Bool) {
|
||||
append(.example(title: title, source: source, cpu: target6309 ? .hd6309 : .mc6809))
|
||||
}
|
||||
private func append(_ doc: AssemblyWorkspaceDocument) { documents.append(doc); select(doc.id) }
|
||||
func open(_ url: URL, folder: Bool) {
|
||||
Task {
|
||||
do {
|
||||
let doc = try await Task.detached { try AssemblyWorkspaceDocument.open(url, folder: folder) }.value
|
||||
if let existing = documents.first(where: { $0.directory == doc.directory && $0.mainPath == doc.mainPath && $0.isProject == doc.isProject }) {
|
||||
select(existing.id)
|
||||
} else { append(doc) }
|
||||
} catch { message = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
func closeDocument() {
|
||||
let doc = document
|
||||
if doc.buffers.contains(where: \.dirty) {
|
||||
let alert = NSAlert()
|
||||
alert.messageText = "Discard edits to \(doc.title)?"
|
||||
alert.informativeText = "Closing removes this document and its recoverable drafts."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard and Close")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||||
}
|
||||
if documents.count == 1 { openExample(title: "Untitled", source: "", target6309: false) }
|
||||
else if let next = documents.first(where: { $0.id != doc.id }) { select(next.id) }
|
||||
documents.removeAll { $0.id == doc.id }
|
||||
if let conn = connection, conn.document == doc.id { machine.clearAssembly(expected: conn.expected); connection = nil }
|
||||
scheduleRecovery()
|
||||
}
|
||||
|
||||
func edit(_ text: String) {
|
||||
guard !text.utf8.elementsEqual(buffer.text.utf8), let i = document.buffers.firstIndex(where: { $0.path == document.selectedPath }) else { return }
|
||||
let path = buffer.path, original = buffer.text
|
||||
let count = document.breakpoints.count
|
||||
documents[index].breakpoints = document.breakpoints.filter { stop in
|
||||
guard stop.path == path else { return true }
|
||||
guard let before = Self.lineRange(stop.line, text: original), let after = Self.lineRange(stop.line, text: text) else { return false }
|
||||
return (original as NSString).substring(with: before) == (text as NSString).substring(with: after)
|
||||
}
|
||||
documents[index].buffers[i].text = text
|
||||
sourceRevision = UUID()
|
||||
let removed = count - document.breakpoints.count
|
||||
let note: String
|
||||
switch removed {
|
||||
case 0: note = ""
|
||||
case 1: note = " Removed one source stop on an edited line."
|
||||
default: note = " Removed \(removed) source stops on edited lines."
|
||||
}
|
||||
invalidate("Source changed. Assemble to refresh the listing and source stops." + note)
|
||||
scheduleRecovery()
|
||||
}
|
||||
/// Commit every reviewed buffer to the same draft generation. Disk writes remain explicit Save actions.
|
||||
func replaceReviewedFiles(_ edits: [AssemblyProjectEdit], snapshot: AssemblyProjectSnapshot,
|
||||
undo: Bool = false, restoreStops: Set<SourceLine> = []) throws -> Set<SourceLine> {
|
||||
guard !working, !commanding, !edits.isEmpty else { throw AssemblyBuildFailure("workspace_busy") }
|
||||
var updated = document
|
||||
let originalStops = updated.breakpoints
|
||||
for edit in edits {
|
||||
let before = undo ? edit.after : edit.before
|
||||
let after = undo ? edit.before : edit.after
|
||||
guard snapshot.files[edit.path] == Data(before.utf8) else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
if let index = updated.buffers.firstIndex(where: { $0.path == edit.path }) {
|
||||
guard updated.buffers[index].text.utf8.elementsEqual(before.utf8) else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
updated.buffers[index].text = after
|
||||
} else {
|
||||
// An unopened file in the live snapshot has no draft overlay.
|
||||
guard !undo else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
updated.buffers.append(.init(path: edit.path, text: after, saved: before))
|
||||
}
|
||||
updated.breakpoints = updated.breakpoints.filter { stop in
|
||||
guard stop.path == edit.path else { return true }
|
||||
guard let a = Self.lineRange(stop.line, text: before), let b = Self.lineRange(stop.line, text: after) else { return false }
|
||||
return (before as NSString).substring(with: a).utf8.elementsEqual((after as NSString).substring(with: b).utf8)
|
||||
}
|
||||
}
|
||||
updated.breakpoints.formUnion(restoreStops)
|
||||
documents[index] = updated
|
||||
fileRequest = UUID()
|
||||
sourceRevision = UUID()
|
||||
restoreCursor()
|
||||
invalidate("Source changed. Assemble the reviewed project revision.")
|
||||
scheduleRecovery()
|
||||
return originalStops.subtracting(updated.breakpoints)
|
||||
}
|
||||
|
||||
func setCPU(_ target: AssemblyCPU) {
|
||||
guard cpu != target else { return }
|
||||
documents[index].cpu = target
|
||||
sourceRevision = UUID()
|
||||
invalidate("Build target changed. Assemble to refresh the listing and source stops.")
|
||||
scheduleRecovery()
|
||||
}
|
||||
private func cancelPending() {
|
||||
revision = UUID(); work?.cancel(); work = nil; working = false
|
||||
}
|
||||
func cancelBuild() { invalidate("Assembly cancelled.") }
|
||||
private func invalidate(_ reason: String) {
|
||||
cancelPending(); artifact = nil; diagnostics = []
|
||||
if let conn = connection, conn.document == activeID {
|
||||
machine.clearAssembly(expected: conn.expected); connection = nil
|
||||
}
|
||||
attached = false; paused = false; execution = ""; executionLine = nil; message = reason; indexLabels()
|
||||
}
|
||||
|
||||
func selectFile(_ path: String, line: Int? = nil) {
|
||||
let doc = document, request = UUID()
|
||||
fileRequest = request
|
||||
if doc.buffers.contains(where: { $0.path == path }) { displayFile(path, line: line); return }
|
||||
Task {
|
||||
do {
|
||||
let text = try await Task.detached {
|
||||
try CMOCProject.readText(doc.checkedURL(path), maximumBytes: CMOCProject.maximumSourceBytes)
|
||||
}.value
|
||||
guard activeID == doc.id, fileRequest == request else { return }
|
||||
if !document.buffers.contains(where: { $0.path == path }) {
|
||||
documents[index].buffers.append(.init(path: path, text: text, saved: text)); indexLabels()
|
||||
}
|
||||
displayFile(path, line: line)
|
||||
} catch { message = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private func displayFile(_ path: String, line: Int?) {
|
||||
if document.selectedPath != path {
|
||||
documents[index].selectedPath = path; restoreCursor()
|
||||
}
|
||||
if let line, let range = Self.lineRange(line, text: buffer.text) {
|
||||
moveCursor(range.location)
|
||||
selection = .init(buffer: buffer.id, range: range)
|
||||
}
|
||||
scheduleRecovery()
|
||||
}
|
||||
private func restoreCursor() {
|
||||
cursor = min(cursors[buffer.id] ?? 0, buffer.text.utf16.count)
|
||||
selection = .init(buffer: buffer.id, range: NSRange(location: cursor, length: 0))
|
||||
}
|
||||
func editSettings() {
|
||||
guard document.isProject else { return }
|
||||
let path = AssemblyProjectSnapshot.configurationFilename
|
||||
if document.paths.contains(path) || document.buffers.contains(where: { $0.path == path }) { selectFile(path); return }
|
||||
let text = "{\n \"main\": \"main.asm\"\n}\n"
|
||||
documents[index].buffers.append(.init(path: path, text: text, saved: nil))
|
||||
documents[index].paths.append(path)
|
||||
sourceRevision = UUID()
|
||||
displayFile(path, line: nil); invalidate("Edit project settings, then assemble to validate them.")
|
||||
}
|
||||
func reload() {
|
||||
let doc = document, file = buffer
|
||||
if file.dirty {
|
||||
let alert = NSAlert(); alert.messageText = "Replace edits with the saved \(file.path)?"
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Reload")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||||
}
|
||||
Task {
|
||||
do {
|
||||
let text = try await Task.detached { try CMOCProject.readText(doc.checkedURL(file.path), maximumBytes: CMOCProject.maximumSourceBytes) }.value
|
||||
guard activeID == doc.id, buffer.id == file.id, buffer.text == file.text,
|
||||
let i = document.buffers.firstIndex(where: { $0.id == file.id }) else { return }
|
||||
documents[index].buffers[i] = .init(path: file.path, text: text, saved: text)
|
||||
sourceRevision = UUID()
|
||||
invalidate("Reloaded \(file.path)."); scheduleRecovery()
|
||||
} catch { message = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private var protectedSourceURLs: [URL] {
|
||||
var urls = [recoveryURL]
|
||||
for doc in documents {
|
||||
guard let root = doc.directory else { continue }
|
||||
let paths = Set(doc.inputPaths ?? doc.paths).union(doc.buffers.map(\.path))
|
||||
urls += paths.map { root.appendingPathComponent($0) }
|
||||
}
|
||||
return urls
|
||||
}
|
||||
|
||||
func save(to copy: URL? = nil) {
|
||||
let doc = document, file = buffer
|
||||
Task {
|
||||
do {
|
||||
let url = try copy ?? doc.checkedURL(file.path)
|
||||
var protected = protectedSourceURLs
|
||||
var expected: Data?
|
||||
if copy == nil {
|
||||
// Only Save Source may replace the selected source file.
|
||||
protected.removeAll { $0.standardizedFileURL == url.standardizedFileURL }
|
||||
expected = file.saved.map { Data($0.utf8) }
|
||||
if expected == nil, FileManager.default.fileExists(atPath: url.path) {
|
||||
throw AssemblyBuildFailure("The source appeared on disk. Reload it or Save a Copy.")
|
||||
}
|
||||
}
|
||||
try await machine.writeDevelopmentFile(Data(file.text.utf8), to: url, protecting: protected,
|
||||
allowEmpty: true, replacing: expected)
|
||||
guard let d = documents.firstIndex(where: { $0.id == doc.id }),
|
||||
let i = documents[d].buffers.firstIndex(where: { $0.id == file.id }) else { return }
|
||||
if doc.directory == nil {
|
||||
documents[d].directory = try CMOCProject.physicalURL(url.deletingLastPathComponent())
|
||||
documents[d].mainPath = url.lastPathComponent; documents[d].selectedPath = url.lastPathComponent
|
||||
documents[d].buffers[i].path = url.lastPathComponent; documents[d].title = url.lastPathComponent
|
||||
documents[d].breakpoints.removeAll()
|
||||
if activeID == doc.id { invalidate("Source saved.") }
|
||||
}
|
||||
if doc.directory == nil || copy == nil { documents[d].buffers[i].saved = file.text }
|
||||
message = "Saved \(url.lastPathComponent)."; scheduleRecovery()
|
||||
} catch { message = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
@Published private(set) var labelLocations: [(String, SourceLine)] = []
|
||||
private var labelTask: Task<Void, Never>?
|
||||
private func indexLabels() {
|
||||
labelTask?.cancel()
|
||||
let doc = document, snapshot = artifact?.snapshot
|
||||
labelTask = Task {
|
||||
do { try await Task.sleep(nanoseconds: 120_000_000) } catch { return }
|
||||
let result = await Task.detached(priority: .utility) {
|
||||
let words = AssemblyReference.shared.vocabulary(target6309: doc.cpu == .hd6309)
|
||||
var sources = [String: String]()
|
||||
for (path, bytes) in snapshot?.files ?? [:] {
|
||||
let ext = URL(fileURLWithPath: path).pathExtension.lowercased()
|
||||
if ["asm", "s", "lwasm", "inc"].contains(ext) { sources[path] = String(data: bytes, encoding: .utf8) }
|
||||
}
|
||||
for file in doc.buffers where file.path == doc.mainPath || ["asm", "s", "lwasm", "inc"].contains(URL(fileURLWithPath: file.path).pathExtension.lowercased()) {
|
||||
sources[file.path] = file.text
|
||||
}
|
||||
return sources.flatMap { path, text in
|
||||
AssemblyEditorSyntax.labels(in: text, vocabulary: words).map { ($0.0, SourceLine(path: path, line: $0.1)) }
|
||||
}.sorted { ($0.0, $0.1.path, $0.1.line) < ($1.0, $1.1.path, $1.1.line) }
|
||||
}.value
|
||||
if !Task.isCancelled, activeID == doc.id { labelLocations = result }
|
||||
}
|
||||
}
|
||||
func goToDefinition() {
|
||||
let words = AssemblyReference.shared.vocabulary(target6309: cpu == .hd6309)
|
||||
guard let term = AssemblyEditorSyntax.token(in: buffer.text, offset: cursor, vocabulary: words) else {
|
||||
message = "Place the caret on a label."; return
|
||||
}
|
||||
let matches = labelLocations.filter { $0.0 == term }
|
||||
guard matches.count == 1, let match = matches.first else {
|
||||
message = matches.isEmpty ? "No label definition found for \(term)." : "Multiple definitions for \(term). Choose a location in Labels."
|
||||
return
|
||||
}
|
||||
selectFile(match.1.path, line: match.1.line)
|
||||
}
|
||||
|
||||
private func scheduleRecovery() {
|
||||
recoveryTask?.cancel()
|
||||
recoveryTask = Task {
|
||||
do { try await Task.sleep(nanoseconds: 350_000_000) } catch { return }
|
||||
let state = AssemblyRecovery(documents: documents, active: activeID), url = recoveryURL
|
||||
recoveryQueue.async {
|
||||
do { try state.write(to: url) }
|
||||
catch { Task { @MainActor in self.message = "Could not preserve assembly drafts: " + error.localizedDescription } }
|
||||
}
|
||||
}
|
||||
}
|
||||
func prepareToQuit() -> Bool {
|
||||
cancelPending(); recoveryTask?.cancel()
|
||||
let state = AssemblyRecovery(documents: documents, active: activeID)
|
||||
do { try recoveryQueue.sync { try state.write(to: recoveryURL) }; return true }
|
||||
catch {
|
||||
message = "Could not preserve assembly drafts: " + error.localizedDescription
|
||||
let alert = NSAlert(); alert.messageText = "Could not save Assembly drafts"; alert.informativeText = message
|
||||
alert.runModal(); return false
|
||||
}
|
||||
}
|
||||
|
||||
static func codeGuards(_ instructions: [AssemblyInstructionLocation]) -> [UInt16: Data] {
|
||||
Dictionary(grouping: instructions, by: \.address).compactMapValues { candidates in
|
||||
guard candidates.count == 1, let first = candidates.first, !first.bytes.isEmpty else { return nil }
|
||||
return Data(first.bytes)
|
||||
}
|
||||
}
|
||||
static func location(_ stop: SourceLine, in artifact: AssemblyBuildArtifact) -> AssemblyInstructionLocation? {
|
||||
let candidates = artifact.instructions.filter { $0.path == stop.path && $0.line == stop.line }
|
||||
guard candidates.count == 1, let candidate = candidates.first,
|
||||
artifact.instructions.filter({ $0.address == candidate.address }).count == 1 else { return nil }
|
||||
return candidate
|
||||
}
|
||||
func toggleBreakpoint() {
|
||||
guard !commanding else { return }
|
||||
let stop = SourceLine(path: buffer.path, line: cursorLine)
|
||||
if document.breakpoints.contains(stop) { documents[index].breakpoints.remove(stop) }
|
||||
else {
|
||||
guard let artifact, Self.location(stop, in: artifact) != nil else {
|
||||
message = "Assemble first and choose a line with one verified instruction. Use the listing for ambiguous or data lines."; return
|
||||
}
|
||||
documents[index].breakpoints.insert(stop)
|
||||
}
|
||||
applyStops()
|
||||
}
|
||||
func clearStops() {
|
||||
guard !commanding else { return }
|
||||
documents[index].breakpoints.removeAll(); applyStops()
|
||||
}
|
||||
private func applyStops() {
|
||||
scheduleRecovery()
|
||||
guard let conn = connection, conn.document == activeID else { return }
|
||||
let points = document.breakpoints.compactMap { Self.location($0, in: conn.artifact)?.address }
|
||||
validateForControl(conn) {
|
||||
self.machine.updateAssembly(breakpoints: points, guards: conn.guards, expected: conn.expected) { snapshot in
|
||||
self.finishCommand(snapshot, connection: conn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func perform(_ action: Action) {
|
||||
guard !commanding, !working else { return }
|
||||
let doc = document, request = UUID(), previous = artifact
|
||||
revision = request; working = true; diagnostics = []; message = "Preparing assembly inputs…"
|
||||
work = Task {
|
||||
defer { if revision == request { working = false; work = nil } }
|
||||
do {
|
||||
let snapshot = try await Task.detached { try doc.snapshot() }.value
|
||||
try check(request, doc.id)
|
||||
documents[index].inputPaths = Array(snapshot.files.keys)
|
||||
let result: AssemblyBuildArtifact
|
||||
if let previous, previous.snapshot == snapshot { result = previous }
|
||||
else {
|
||||
if let makefile = snapshot.settings.makefile {
|
||||
let alert = NSAlert(); alert.messageText = "Run this project’s Makefile?"
|
||||
alert.informativeText = "\(doc.title) will execute \(makefile), target \(snapshot.settings.target ?? "all"), with your account’s permissions. ASFLAGS supplies the selected CPU target. The recipe controls the resulting binary. Without a verified source map, use the machine debugger."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Run Make")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { throw CancellationError() }
|
||||
}
|
||||
message = "Assembling for the \(cpu.rawValue)…"
|
||||
result = try await service.build(snapshot)
|
||||
try check(request, doc.id)
|
||||
if doc.directory != nil {
|
||||
guard try await Task.detached(operation: { try doc.snapshot() }).value == snapshot else {
|
||||
throw AssemblyBuildFailure("Assembly inputs changed during the build. Assemble again.")
|
||||
}
|
||||
}
|
||||
}
|
||||
try check(request, doc.id)
|
||||
artifact = result; buildLog = result.buildLog; documents[index].paths = AssemblyWorkspaceDocument.editablePaths(snapshot)
|
||||
indexLabels(); message = "Assembled · " + Self.summary(result)
|
||||
switch action {
|
||||
case .assemble: break
|
||||
case .run, .debug:
|
||||
let debug: Bool
|
||||
if case .debug = action { debug = true } else { debug = false }
|
||||
try await launch(result, doc: doc, request: request, debug: debug)
|
||||
case .exportBinary(let url): try await write(result.binaryData, url: url, request: request, doc: doc.id)
|
||||
case .exportDisk(let url, let name, let dosBoot):
|
||||
let disk = try await service.diskImage(for: result, name: name, dosBoot: dosBoot)
|
||||
try check(request, doc.id)
|
||||
if doc.directory != nil, try await Task.detached(operation: { try doc.snapshot() }).value != snapshot {
|
||||
throw AssemblyBuildFailure("Project inputs changed during disk export. Assemble again.")
|
||||
}
|
||||
try await write(disk, url: url, request: request, doc: doc.id)
|
||||
}
|
||||
} catch {
|
||||
guard revision == request else { return }
|
||||
let failure = (error as? AssemblyBuildFailure)?.diagnostics ?? []
|
||||
let reason = error is CancellationError ? "Assembly cancelled." : error.localizedDescription
|
||||
invalidate(reason); buildLog = reason; diagnostics = failure
|
||||
}
|
||||
}
|
||||
}
|
||||
private func check(_ request: UUID, _ doc: UUID) throws {
|
||||
try Task.checkCancellation()
|
||||
guard revision == request && activeID == doc else { throw CancellationError() }
|
||||
}
|
||||
private func write(_ data: Data, url: URL, request: UUID, doc: UUID) async throws {
|
||||
try check(request, doc)
|
||||
do {
|
||||
try await machine.writeDevelopmentFile(data, to: url, protecting: protectedSourceURLs)
|
||||
} catch {
|
||||
if revision == request { message = error.localizedDescription }
|
||||
return
|
||||
}
|
||||
try check(request, doc); message = "Exported \(url.lastPathComponent)."
|
||||
}
|
||||
static func summary(_ artifact: AssemblyBuildArtifact) -> String {
|
||||
let ranges = artifact.ranges.map { String(format: "$%04X–$%04X", $0.lowerBound, $0.upperBound) }.joined(separator: ", ")
|
||||
return "Load " + ranges + String(format: " · Entry $%04X", artifact.entry)
|
||||
}
|
||||
func acceptSharedBuild(_ build: AssemblyBuildArtifact) {
|
||||
artifact = build; diagnostics = []; buildLog = build.buildLog
|
||||
message = "Assembled · " + Self.summary(build)
|
||||
indexLabels()
|
||||
}
|
||||
|
||||
func launchShared(_ build: AssemblyBuildArtifact, stillGranted: @escaping () -> Bool,
|
||||
confirm: ((String) -> Bool)? = nil) async throws -> VCCMachineSnapshot {
|
||||
guard !working, !commanding, artifact?.id == build.id, stillGranted() else {
|
||||
throw AssemblyBuildFailure("The shared build is no longer current.")
|
||||
}
|
||||
working = true
|
||||
let request = revision, priorProgram = machine.assemblyProgramRevision
|
||||
defer { if revision == request { working = false } }
|
||||
try await launch(build, doc: document, request: request, debug: false, stillGranted: stillGranted, confirm: confirm)
|
||||
guard let connection, connection.artifact.id == build.id, connection.expected.debuggerProgramRevision != priorProgram, stillGranted() else { throw AssemblyBuildFailure(message) }
|
||||
return connection.expected
|
||||
}
|
||||
|
||||
private func launch(_ artifact: AssemblyBuildArtifact, doc: AssemblyWorkspaceDocument, request: UUID, debug: Bool, stillGranted: (() -> Bool)? = nil, confirm: ((String) -> Bool)? = nil) async throws {
|
||||
let generation = machine.basicDebug.generation, program = machine.assemblyProgramRevision
|
||||
let mapping = machine.assemblyMappingFingerprint
|
||||
let sameOwner = owner?.document == doc.id && owner?.generation == generation && owner?.revision == program
|
||||
guard machine.state == .paused || machine.state == .running else {
|
||||
message = "Start a Disk BASIC, Hard Drive BASIC or CoCoSDC machine before running. The build is ready for export."; return
|
||||
}
|
||||
if let confirm, !sameOwner {
|
||||
guard confirm(Self.summary(artifact)) else { throw CancellationError() }
|
||||
} else if !sameOwner {
|
||||
let alert = NSAlert(); alert.messageText = "Load this assembly program into the CoCo?"
|
||||
alert.informativeText = Self.summary(artifact) + "\n\nLoading replaces guest program memory and takes over any active development session. Save any BASIC program or variables you want to keep."
|
||||
if stillGranted != nil {
|
||||
alert.informativeText += "\n\nWhile this program runs, the connected assistant can read the CoCo text screen and send up to 64 individual letters, digits or spaces. Its run receipt can include the last text screen when the program returns to BASIC."
|
||||
}
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: debug ? "Debug from Entry" : "Run")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { message = "Launch cancelled. The build is ready."; return }
|
||||
}
|
||||
try check(request, doc.id)
|
||||
if doc.directory != nil, try await Task.detached(operation: { try doc.snapshot() }).value != artifact.snapshot {
|
||||
throw AssemblyBuildFailure("Inputs changed before launch. Assemble again.")
|
||||
}
|
||||
try check(request, doc.id)
|
||||
guard stillGranted?() != false else { throw CancellationError() }
|
||||
let points = doc.breakpoints.compactMap { Self.location($0, in: artifact)?.address }
|
||||
guard points.count == doc.breakpoints.count else {
|
||||
message = "An armed line no longer has one executable instruction. Remove that source stop before launching."; return
|
||||
}
|
||||
let guards = Self.codeGuards(artifact.instructions)
|
||||
commanding = true
|
||||
let result: VCCMachineSnapshot? = await withCheckedContinuation { continuation in
|
||||
machine.launchAssembly(artifact.binaryData, breakpoints: points, guards: guards, pauseAtEntry: debug,
|
||||
requires6309: doc.cpu == .hd6309, expectedGeneration: generation, expectedRevision: program, expectedMapping: mapping, shared: stillGranted != nil) {
|
||||
continuation.resume(returning: $0)
|
||||
}
|
||||
}
|
||||
commanding = false
|
||||
guard let result, result.errorMessage == nil else {
|
||||
if revision == request { message = result?.errorMessage ?? machine.fileError ?? "The CoCo is busy or unavailable." }; return
|
||||
}
|
||||
owner = (doc.id, result.generation, result.debuggerProgramRevision)
|
||||
guard revision == request, activeID == doc.id else { machine.clearAssembly(expected: result); return }
|
||||
connection = .init(document: doc.id, artifact: artifact, expected: result, guards: guards)
|
||||
attached = true; paused = result.state == .paused
|
||||
message = "Loaded · " + Self.summary(artifact)
|
||||
if !debug { displayRequest += 1 }
|
||||
refresh()
|
||||
}
|
||||
|
||||
func pause() {
|
||||
guard attached, !commanding, let conn = connection, conn.document == activeID else { return }
|
||||
commanding = true
|
||||
machine.pauseAssembly(expected: conn.expected) { snapshot in
|
||||
self.finishCommand(snapshot, connection: conn)
|
||||
}
|
||||
}
|
||||
func control(step: Bool) {
|
||||
guard paused, let conn = connection, conn.document == activeID, !commanding else { return }
|
||||
validateForControl(conn) {
|
||||
self.machine.controlAssembly(step: step, expected: conn.expected) { snapshot in
|
||||
self.finishCommand(snapshot, connection: conn)
|
||||
}
|
||||
}
|
||||
}
|
||||
private func validateForControl(_ conn: Attachment, command: @escaping @MainActor () -> Void) {
|
||||
let doc = document, request = revision
|
||||
commanding = true
|
||||
Task {
|
||||
do {
|
||||
let inputs = try await Task.detached { try doc.snapshot() }.value
|
||||
guard request == revision, activeID == doc.id, connection?.artifact.id == conn.artifact.id else { commanding = false; return }
|
||||
guard inputs == conn.artifact.snapshot else { throw AssemblyBuildFailure("Project inputs changed. Run again to reconnect source debugging.") }
|
||||
command()
|
||||
} catch {
|
||||
commanding = false
|
||||
if revision == request { invalidate(error.localizedDescription) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func finishCommand(_ snapshot: VCCMachineSnapshot?, connection conn: Attachment) {
|
||||
commanding = false
|
||||
guard connection?.artifact.id == conn.artifact.id else { return }
|
||||
guard let snapshot, snapshot.errorMessage == nil else {
|
||||
invalidate(snapshot?.errorMessage ?? machine.fileError ?? "The machine changed. Run again to reconnect.")
|
||||
return
|
||||
}
|
||||
connection?.expected = snapshot
|
||||
paused = snapshot.state == .paused; refresh()
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
if let build = artifact, document.directory != nil, !checking, !working, !commanding, Date() >= nextCheck {
|
||||
nextCheck = Date().addingTimeInterval(2); checking = true
|
||||
let doc = document, request = revision
|
||||
Task {
|
||||
let copy = await Task.detached { try? doc.snapshot() }.value
|
||||
checking = false
|
||||
if revision == request, activeID == doc.id, artifact?.id == build.id, copy != build.snapshot {
|
||||
invalidate("A project input changed on disk. Reload any open changed file and assemble again.")
|
||||
}
|
||||
}
|
||||
}
|
||||
guard let conn = connection, conn.document == activeID, !reading, !commanding else { return }
|
||||
if machine.state == .running {
|
||||
guard machine.assemblyAttached, machine.basicDebug.generation == conn.expected.generation,
|
||||
machine.assemblyProgramRevision == conn.expected.debuggerProgramRevision,
|
||||
machine.assemblyMappingFingerprint == conn.expected.debuggerMappingFingerprint else {
|
||||
invalidate("The running program or memory mapping changed. Run again to reconnect."); return
|
||||
}
|
||||
if paused { paused = false }
|
||||
if executionLine != nil { executionLine = nil }
|
||||
if execution != "Running" { execution = "Running" }
|
||||
return
|
||||
}
|
||||
reading = true
|
||||
machine.readDebugger(address: 0, followPC: true, memoryAddress: 0x0400) { [weak self] capture in
|
||||
guard let self else { return }; reading = false
|
||||
guard connection?.artifact.id == conn.artifact.id, activeID == conn.document, let capture else { return }
|
||||
let snapshot = capture.machine
|
||||
guard snapshot.generation == conn.expected.generation, snapshot.debuggerProgramRevision == conn.expected.debuggerProgramRevision,
|
||||
snapshot.debuggerMappingFingerprint == conn.expected.debuggerMappingFingerprint,
|
||||
snapshot.debuggerAssemblyAttached else {
|
||||
invalidate("Machine program or memory mapping changed. Run again to reconnect source debugging."); return
|
||||
}
|
||||
connection?.expected = snapshot
|
||||
let stopped = snapshot.state == .paused
|
||||
if paused != stopped { paused = stopped }
|
||||
guard stopped else {
|
||||
if executionLine != nil { executionLine = nil }
|
||||
if execution != "Running" { execution = "Running" }; return
|
||||
}
|
||||
let memory = capture.logicalMemory, available = capture.logicalMemoryAvailable
|
||||
for (address, bytes) in conn.guards {
|
||||
let start = Int(address), end = start + bytes.count
|
||||
guard end <= memory.count, end <= available.count, available[start..<end].allSatisfy({ $0 != 0 }),
|
||||
memory[start..<end].elementsEqual(bytes) else {
|
||||
invalidate("An assembled instruction changed in mapped RAM. Use Debugger to inspect it, or run again."); return
|
||||
}
|
||||
}
|
||||
let pc = snapshot.programCounter
|
||||
let candidates = conn.artifact.instructions.filter { $0.address == pc }
|
||||
let first = candidates.count == 1 ? candidates.first : nil
|
||||
let live = capture.instructions.first
|
||||
let next: SourceLine?
|
||||
if let first, live?.address == pc, let live, Array(live.bytes) == first.bytes,
|
||||
Self.location(.init(path: first.path, line: first.line), in: conn.artifact) != nil {
|
||||
next = .init(path: first.path, line: first.line)
|
||||
} else { next = nil }
|
||||
let a = capture.registers["A"]?.uint8Value ?? capture.registers["D"].map { UInt8(truncatingIfNeeded: $0.uint16Value >> 8) }
|
||||
let cc = capture.registers["CC"]?.uint8Value
|
||||
let reg = String(format: "PC $%04X", pc) + (a.map { String(format: " · A $%02X", $0) } ?? "") + (cc.map { String(format: " · CC $%02X", $0) } ?? "")
|
||||
let status = (next.map { "Paused · \($0.path):\($0.line)" } ?? "Paused · no verified source line") + " · " + reg
|
||||
if execution != status { execution = status }
|
||||
if executionLine != next {
|
||||
executionLine = next
|
||||
if let next { selectFile(next.path, line: next.line) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct AssemblyDevelopmentView: View {
|
||||
@ObservedObject var model: AssemblyDevelopmentModel
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@StateObject private var finder = SourceFind()
|
||||
@StateObject private var pool = AssemblyEditorPool()
|
||||
@State private var details = false
|
||||
@State private var detailPane = "Listing"
|
||||
@State private var diskExport = false
|
||||
@State private var diskName = "FIRST"
|
||||
@State private var diskBoot = false
|
||||
@State private var settingsHelp = false
|
||||
private var locked: Bool { model.working || model.commanding }
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack {
|
||||
Label("Assembly Development", systemImage: "cpu").font(.title2.bold())
|
||||
Spacer()
|
||||
Button(action: reference) { Label("Quick Reference", systemImage: "book.closed") }
|
||||
.keyboardShortcut("?", modifiers: [.command, .option]).accessibilityIdentifier("assembly-reference")
|
||||
Button { openWindow(id: "debugger") } label: { Label("Debugger", systemImage: "ladybug") }
|
||||
.help("Inspect registers, flags, memory, trace and Graphics Preview")
|
||||
}.padding(.horizontal, 14).padding(.vertical, 10)
|
||||
Divider()
|
||||
HStack {
|
||||
Menu("File") {
|
||||
Button("New Source") { model.openExample(title: "Untitled", source: "", target6309: false) }
|
||||
Button(AssemblyWorkspaceDocument.starterTitle) {
|
||||
model.openExample(title: AssemblyWorkspaceDocument.starterTitle, source: AssemblyWorkspaceDocument.starterSource, target6309: false)
|
||||
}
|
||||
Divider()
|
||||
Button("Local Assistant Access…") { MCPAssembly.shared.show(model, editors: pool) }
|
||||
Button("Open Source…") { open(folder: false) }
|
||||
Button("Open Project Folder…") { open(folder: true) }
|
||||
Button("Project Settings…") { settingsHelp = true }.disabled(!model.document.isProject)
|
||||
Divider()
|
||||
Button("Save Source", action: save).keyboardShortcut("s")
|
||||
Button("Save a Copy…") { saveCopy() }
|
||||
Button("Reload from Disk") { model.reload() }.disabled(model.document.directory == nil)
|
||||
Button("Close Document") { model.closeDocument() }
|
||||
}.fixedSize().accessibilityIdentifier("assembly-file")
|
||||
Picker("Document", selection: Binding(get: { model.activeID }, set: model.select)) {
|
||||
ForEach(model.documents) { doc in
|
||||
Text(doc.title + (doc.buffers.contains(where: \.dirty) ? " •" : "")).tag(doc.id)
|
||||
}
|
||||
}.labelsHidden().accessibilityLabel("Assembly document").accessibilityIdentifier("assembly-document")
|
||||
Spacer()
|
||||
Picker("Target", selection: Binding(get: { model.cpu }, set: model.setCPU)) {
|
||||
Text("MC6809").tag(AssemblyCPU.mc6809)
|
||||
Text("HD6309").tag(AssemblyCPU.hd6309)
|
||||
}.fixedSize().accessibilityIdentifier("assembly-cpu")
|
||||
}.disabled(model.commanding).padding(.horizontal, 14).padding(.vertical, 6)
|
||||
HStack(spacing: 8) {
|
||||
Button { model.perform(.assemble) } label: { Label("Assemble", systemImage: "hammer") }
|
||||
.keyboardShortcut("b").accessibilityIdentifier("assembly-assemble").disabled(locked)
|
||||
Button { model.perform(.run) } label: { Label("Run", systemImage: "play.fill") }
|
||||
.keyboardShortcut("r").buttonStyle(.borderedProminent).accessibilityIdentifier("assembly-run").disabled(locked)
|
||||
Button { model.perform(.debug) } label: { Label("Debug from Entry", systemImage: "playpause") }
|
||||
.accessibilityIdentifier("assembly-debug-entry").disabled(locked)
|
||||
if model.working && !model.commanding {
|
||||
Button("Cancel") { model.cancelBuild() }.accessibilityIdentifier("assembly-cancel")
|
||||
}
|
||||
Spacer()
|
||||
Menu("Export") {
|
||||
Button("Export Binary…") { export(disk: false) }.accessibilityIdentifier("assembly-export-binary")
|
||||
Button("Export Disk Image…") { diskBoot = false; diskExport = true }.accessibilityIdentifier("assembly-export-disk")
|
||||
}.disabled(locked).fixedSize().accessibilityIdentifier("assembly-export")
|
||||
}.padding(.horizontal, 14).padding(.vertical, 5)
|
||||
Divider()
|
||||
HStack(spacing: 8) {
|
||||
if model.document.paths.count > 1 || model.document.isProject {
|
||||
Menu(model.buffer.path) {
|
||||
ForEach(model.document.paths, id: \.self) { path in Button(path) { model.selectFile(path) } }
|
||||
}.fixedSize().accessibilityLabel("Project files")
|
||||
} else { Label(model.buffer.path, systemImage: "doc.text") }
|
||||
Text("Line \(model.cursorLine)").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
SourceFindButton(finder: finder)
|
||||
Menu("Labels") {
|
||||
Button("Go to Definition", action: model.goToDefinition)
|
||||
Divider()
|
||||
ForEach(Array(model.labelLocations.prefix(500).enumerated()), id: \.offset) { _, item in
|
||||
Button("\(item.0) · \(item.1.path):\(item.1.line)") { model.selectFile(item.1.path, line: item.1.line) }
|
||||
}
|
||||
}.fixedSize()
|
||||
Button { pool.complete(model.buffer.id) } label: { Label("Complete", systemImage: "text.badge.plus") }
|
||||
.help("Complete at the caret (Control–Space)").accessibilityIdentifier("assembly-complete")
|
||||
Button { model.toggleBreakpoint() } label: {
|
||||
Label(model.document.breakpoints.contains(.init(path: model.buffer.path, line: model.cursorLine)) ? "Remove Stop" : "Set Stop",
|
||||
systemImage: "record.circle")
|
||||
}.disabled(locked).help("Toggle a breakpoint before this source instruction").accessibilityIdentifier("assembly-breakpoint")
|
||||
if !model.document.breakpoints.isEmpty {
|
||||
Menu("Stops (\(model.document.breakpoints.count))") {
|
||||
Button("Clear All Stops", action: model.clearStops)
|
||||
Divider()
|
||||
ForEach(model.document.breakpoints.sorted { ($0.path, $0.line) < ($1.path, $1.line) }, id: \.self) { stop in
|
||||
Button("\(stop.path):\(stop.line)") { model.selectFile(stop.path, line: stop.line) }
|
||||
}
|
||||
}.fixedSize()
|
||||
}
|
||||
}.font(.callout).padding(.horizontal, 14).padding(.vertical, 5)
|
||||
SourceFindBar(finder: finder, source: model.buffer.text, readOnly: false)
|
||||
AssemblyEditor(finder: finder, model: model, pool: pool, lookup: reference).frame(minHeight: 130)
|
||||
if model.document.title == AssemblyWorkspaceDocument.starterTitle {
|
||||
Text("Run, then press 1 for Earth or 2 for Mars in the emulator. After the greeting, you can type BASIC commands at the OK prompt.")
|
||||
.font(.callout).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.top, 6)
|
||||
} else if model.document.title == "First Program — Change a Screen Cell" {
|
||||
Text("In Disk BASIC’s 32-column display, this is POKE &H0400,&H8F. Step LDA to change A, then STA to change the first screen cell.")
|
||||
.font(.callout).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.top, 6)
|
||||
}
|
||||
HStack {
|
||||
Button("Pause", action: model.pause).disabled(!model.attached || model.paused || locked).accessibilityIdentifier("assembly-pause")
|
||||
Button("Step") { model.control(step: true) }.disabled(!model.paused || locked).accessibilityIdentifier("assembly-step")
|
||||
Button("Continue") { model.control(step: false) }.disabled(!model.paused || locked).accessibilityIdentifier("assembly-continue")
|
||||
Text(model.execution).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
.accessibilityIdentifier("assembly-execution")
|
||||
Spacer()
|
||||
}.padding(.horizontal, 14).padding(.vertical, 7)
|
||||
Divider()
|
||||
Text(model.message).font(.callout).textSelection(.enabled).accessibilityIdentifier("assembly-status")
|
||||
.padding(.horizontal, 14).padding(.top, 7)
|
||||
if !model.diagnostics.isEmpty {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, item in
|
||||
Button("\(item.path):\(item.line) \(item.message)") { model.selectFile(item.path, line: item.line) }
|
||||
.buttonStyle(.link).accessibilityIdentifier("assembly-diagnostic")
|
||||
}
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.frame(maxHeight: 74).padding(.horizontal, 14)
|
||||
}
|
||||
DisclosureGroup("Build details", isExpanded: $details) {
|
||||
Picker("Build details", selection: $detailPane) {
|
||||
ForEach(["Listing", "Symbols", "Log"], id: \.self) { Text($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 320)
|
||||
ScrollView([.vertical, .horizontal]) {
|
||||
Text(detailPane == "Log" ? model.buildLog : (detailPane == "Listing" ? model.artifact?.listing : model.artifact?.symbols) ?? "")
|
||||
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
}.frame(maxWidth: .infinity, minHeight: 45, maxHeight: 150, alignment: .topLeading)
|
||||
}.padding(.horizontal, 14).padding(.vertical, 7)
|
||||
}.frame(minWidth: 690, minHeight: 420)
|
||||
.focusedSceneValue(\.sourceFind, finder)
|
||||
.onDisappear { MCPAssembly.shared.close(for: model) }
|
||||
.onChange(of: model.displayRequest) { _, _ in
|
||||
openWindow(id: "machine")
|
||||
DispatchQueue.main.async { model.machine.focusDisplay() }
|
||||
}
|
||||
.onChange(of: model.documents.map { $0.buffers.map(\.id) }) { _, ids in pool.forget(except: Set(ids.joined())) }
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
model.refresh()
|
||||
try? await Task.sleep(nanoseconds: 350_000_000)
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $diskExport) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Text("Export Disk Image").font(.headline)
|
||||
TextField("Disk BASIC filename", text: $diskName).accessibilityIdentifier("assembly-disk-name")
|
||||
Text("Use 1–8 letters or digits, without an extension.").font(.caption).foregroundStyle(.secondary)
|
||||
Toggle("Install DOS bootloader", isOn: $diskBoot).accessibilityIdentifier("assembly-export-dos")
|
||||
if let name = BASICExportName.normalized(diskName) {
|
||||
Text(DevelopmentDiskProgram.binary(name).instructions(dos: diskBoot))
|
||||
.fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("assembly-export-commands")
|
||||
}
|
||||
HStack {
|
||||
Spacer(); Button("Cancel") { diskExport = false }
|
||||
Button("Choose Location…") {
|
||||
diskExport = false; DispatchQueue.main.async { export(disk: true) }
|
||||
}.keyboardShortcut(.defaultAction).disabled(BASICExportName.normalized(diskName) == nil)
|
||||
}
|
||||
}.padding(20).frame(width: 440)
|
||||
}
|
||||
.sheet(isPresented: $settingsHelp) {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Project Settings").font(.title2.bold())
|
||||
Text("Edit vccplus-assembly.json in the source editor. Assemble validates and uses your changes. Save writes them to the project.")
|
||||
Text("Set main to the entry source. For linked objects, add modules (additional source paths) and linkScript (the LWLINK script path).")
|
||||
Text("To run an existing Makefile, set makefile, target and binary to the recipe, target name and output path. Each fresh build asks before executing the recipe.")
|
||||
HStack {
|
||||
Spacer(); Button("Cancel") { settingsHelp = false }
|
||||
Button("Edit Settings") { settingsHelp = false; model.editSettings() }.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}.padding(20).frame(width: 460)
|
||||
}
|
||||
}
|
||||
private func reference() {
|
||||
let extended = model.cpu == .hd6309
|
||||
let term = AssemblyReference.shared.topic(in: model.buffer.text, at: model.cursor, target6309: extended)
|
||||
AssemblyReferenceSelection.shared.show(term ?? "", target6309: extended)
|
||||
openWindow(id: "assembly-reference")
|
||||
}
|
||||
private func open(folder: Bool) {
|
||||
let panel = NSOpenPanel(); panel.canChooseDirectories = folder; panel.canChooseFiles = !folder
|
||||
panel.allowsMultipleSelection = false
|
||||
if !folder { panel.allowedContentTypes = ["asm", "s", "lwasm", "inc"].compactMap { UTType(filenameExtension: $0) } }
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
||||
model.open(url, folder: folder)
|
||||
}
|
||||
private func save() { if model.document.directory == nil { saveCopy() } else { model.save() } }
|
||||
private func saveCopy() {
|
||||
let panel = NSSavePanel()
|
||||
panel.nameFieldStringValue = (model.buffer.path as NSString).lastPathComponent
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return }; model.save(to: url)
|
||||
}
|
||||
private func export(disk: Bool) {
|
||||
let panel = NSSavePanel()
|
||||
let name = BASICExportName.normalized(diskName) ?? "FIRST"
|
||||
if disk { panel.message = DevelopmentDiskProgram.binary(name).instructions(dos: diskBoot) }
|
||||
panel.nameFieldStringValue = disk ? "\(name).dsk" : (model.document.mainPath as NSString).lastPathComponent.components(separatedBy: ".").dropLast().joined(separator: ".") + ".bin"
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
||||
model.perform(disk ? .exportDisk(url, name, dosBoot: diskBoot) : .exportBinary(url))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
enum AssemblyEditorSyntax {
|
||||
enum Kind { case label, mnemonic, directive, literal, operand, comment }
|
||||
struct Token { let range: NSRange; let kind: Kind }
|
||||
private static let words = try! NSRegularExpression(pattern:
|
||||
#"(?:"[^"\r\n]*"|'[^'\r\n]*'|;[^\r\n]*|\$[0-9A-Fa-f]+|%[01]+|[A-Za-z_.@?][A-Za-z0-9_.$@?]*:?|\d+)"#)
|
||||
static func tokens(in line: String, vocabulary: Set<String>) -> [Token] {
|
||||
let ns = line as NSString
|
||||
if line.trimmingCharacters(in: .whitespaces).hasPrefix("*") {
|
||||
return [.init(range: NSRange(location: 0, length: ns.length), kind: .comment)]
|
||||
}
|
||||
var opcodeSeen = false, labelSeen = false
|
||||
return words.matches(in: line, range: NSRange(location: 0, length: ns.length)).map { match in
|
||||
let word = ns.substring(with: match.range)
|
||||
let kind: Kind
|
||||
if word.hasPrefix(";") { kind = .comment }
|
||||
else if ["\"", "'", "$", "%"].contains(where: { word.hasPrefix($0) }) || word.first?.isNumber == true { kind = .literal }
|
||||
else if !opcodeSeen && !labelSeen && (word.hasSuffix(":") || match.range.location == 0) {
|
||||
kind = .label
|
||||
labelSeen = true
|
||||
} else if !opcodeSeen {
|
||||
opcodeSeen = true
|
||||
let upper = word.uppercased()
|
||||
kind = AssemblyReference.shared.isDirective(upper) ? .directive : (vocabulary.contains(upper) ? .mnemonic : .operand)
|
||||
} else { kind = .operand }
|
||||
return Token(range: match.range, kind: kind)
|
||||
}
|
||||
}
|
||||
|
||||
static func token(in source: String, offset: Int, vocabulary: Set<String>) -> String? {
|
||||
let text = source as NSString
|
||||
let pos = min(max(0, offset), text.length)
|
||||
let line = text.lineRange(for: NSRange(location: pos, length: 0))
|
||||
let contents = text.substring(with: line) as NSString
|
||||
let local = pos - line.location
|
||||
guard let token = tokens(in: contents as String, vocabulary: vocabulary).first(where: {
|
||||
NSLocationInRange(local, $0.range) || local == NSMaxRange($0.range)
|
||||
}), [.operand, .mnemonic, .label, .directive].contains(token.kind) else { return nil }
|
||||
return contents.substring(with: token.range).trimmingCharacters(in: CharacterSet(charactersIn: ":"))
|
||||
}
|
||||
|
||||
static func labels(in text: String, vocabulary: Set<String>) -> [(String, Int)] {
|
||||
text.components(separatedBy: "\n").enumerated().compactMap { index, line in
|
||||
guard let label = tokens(in: line, vocabulary: vocabulary).first, label.kind == .label else { return nil }
|
||||
return ((line as NSString).substring(with: label.range).trimmingCharacters(in: CharacterSet(charactersIn: ":")), index + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class AssemblyTextView: NSTextView, SourceFindEditor {
|
||||
weak var sourceFind: SourceFind?
|
||||
let documentUndo = UndoManager()
|
||||
override var undoManager: UndoManager? { documentUndo }
|
||||
var lookup: (() -> Void)?
|
||||
var definition: (() -> Void)?
|
||||
var target6309 = false
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift])
|
||||
if event.keyCode == 49 && modifiers == [.control] { complete(nil); return true }
|
||||
if event.charactersIgnoringModifiers == "j", modifiers == [.command, .control] { definition?(); return true }
|
||||
return super.performKeyEquivalent(with: event)
|
||||
}
|
||||
override func menu(for event: NSEvent) -> NSMenu? {
|
||||
guard let menu = super.menu(for: event)?.copy() as? NSMenu else { return nil }
|
||||
menu.addItem(.separator())
|
||||
for (title, action) in [("Look Up in Assembly Quick Reference", #selector(lookUpInstruction)),
|
||||
("Go to Label Definition", #selector(goToLabel)),
|
||||
("Complete", #selector(complete(_:)))] {
|
||||
let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
|
||||
item.target = self
|
||||
menu.addItem(item)
|
||||
}
|
||||
return menu
|
||||
}
|
||||
@objc private func lookUpInstruction() { lookup?() }
|
||||
@objc private func goToLabel() { definition?() }
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
if sourceFind?.cancel(from: self) != true {
|
||||
_ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender)
|
||||
}
|
||||
}
|
||||
override func completions(forPartialWordRange charRange: NSRange,
|
||||
indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String]? {
|
||||
guard selectedRange().length == 0, !hasMarkedText() else { return [] }
|
||||
index?.pointee = -1
|
||||
return AssemblyReference.shared.completions(in: string, at: selectedRange().location, target6309: target6309)
|
||||
}
|
||||
override func insertCompletion(_ word: String, forPartialWordRange charRange: NSRange, movement: Int, isFinal flag: Bool) {
|
||||
guard flag, movement != NSTextMovement.cancel.rawValue, !hasMarkedText(),
|
||||
selectedRange().length == 0, NSMaxRange(charRange) == selectedRange().location,
|
||||
completions(forPartialWordRange: charRange, indexOfSelectedItem: nil)?.contains(word) == true else { return }
|
||||
breakUndoCoalescing()
|
||||
insertText(word, replacementRange: charRange)
|
||||
breakUndoCoalescing()
|
||||
undoManager?.setActionName("Complete Assembly")
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class AssemblyEditorPool: ObservableObject {
|
||||
fileprivate var editors: [UUID: AssemblyTextView] = [:]
|
||||
func complete(_ id: UUID) {
|
||||
guard let editor = editors[id] else { return }
|
||||
editor.window?.makeFirstResponder(editor); editor.complete(nil)
|
||||
}
|
||||
func canReplace(_ buffers: [AssemblyBuffer]) -> Bool {
|
||||
buffers.allSatisfy { buffer in
|
||||
guard let editor = editors[buffer.id], editor.delegate != nil else { return true }
|
||||
return !editor.hasMarkedText() && editor.string.utf8.elementsEqual(buffer.text.utf8)
|
||||
}
|
||||
}
|
||||
func replaceReviewedLine(in buffer: AssemblyBuffer, range: NSRange, with replacement: String) -> Bool {
|
||||
guard let editor = editors[buffer.id], editor.delegate != nil, !editor.hasMarkedText(),
|
||||
editor.string.utf8.elementsEqual(buffer.text.utf8) else { return false }
|
||||
editor.breakUndoCoalescing()
|
||||
editor.insertText(replacement, replacementRange: range)
|
||||
editor.breakUndoCoalescing()
|
||||
editor.documentUndo.setActionName("Assistant Assembly Edit")
|
||||
return true
|
||||
}
|
||||
func forget(except ids: Set<UUID>) { editors = editors.filter { ids.contains($0.key) } }
|
||||
}
|
||||
|
||||
struct AssemblyEditor: NSViewRepresentable {
|
||||
let finder: SourceFind
|
||||
@ObservedObject var model: AssemblyDevelopmentModel
|
||||
let pool: AssemblyEditorPool
|
||||
let lookup: () -> Void
|
||||
func makeCoordinator() -> Coordinator { Coordinator(model: model) }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSScrollView()
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.borderType = .bezelBorder
|
||||
scroll.autohidesScrollers = true
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
let doc = model.buffer
|
||||
let editor: AssemblyTextView
|
||||
let coord = context.coordinator
|
||||
if let existing = pool.editors[doc.id] { editor = existing }
|
||||
else {
|
||||
editor = AssemblyTextView(frame: .zero)
|
||||
editor.isRichText = false
|
||||
editor.isAutomaticQuoteSubstitutionEnabled = false
|
||||
editor.isAutomaticDashSubstitutionEnabled = false
|
||||
editor.isAutomaticTextReplacementEnabled = false
|
||||
editor.isAutomaticSpellingCorrectionEnabled = false
|
||||
editor.isContinuousSpellCheckingEnabled = false
|
||||
editor.allowsUndo = true
|
||||
editor.font = .monospacedSystemFont(ofSize: 13, weight: .regular)
|
||||
editor.textContainerInset = NSSize(width: 8, height: 8)
|
||||
editor.isVerticallyResizable = true; editor.autoresizingMask = [.width]
|
||||
editor.textContainer?.widthTracksTextView = true
|
||||
editor.setAccessibilityLabel("Assembly source")
|
||||
editor.setAccessibilityIdentifier("assembly-source")
|
||||
pool.editors[doc.id] = editor
|
||||
}
|
||||
finder.editor = editor
|
||||
let changedDocument = scroll.documentView !== editor
|
||||
if changedDocument {
|
||||
if let previous = scroll.documentView as? AssemblyTextView {
|
||||
previous.delegate = nil; previous.lookup = nil; previous.definition = nil
|
||||
}
|
||||
scroll.documentView = editor
|
||||
editor.frame.size.width = scroll.contentSize.width
|
||||
coord.bufferID = doc.id
|
||||
}
|
||||
coord.updating = true
|
||||
defer { coord.updating = false }
|
||||
let changedSource = !editor.string.utf8.elementsEqual(doc.text.utf8)
|
||||
let target = model.cpu == .hd6309
|
||||
let changedTarget = editor.target6309 != target
|
||||
editor.target6309 = target
|
||||
if changedSource { editor.string = doc.text; editor.documentUndo.removeAllActions() }
|
||||
editor.delegate = coord
|
||||
editor.lookup = lookup; editor.definition = model.goToDefinition
|
||||
if changedDocument || changedSource || changedTarget { coord.color(editor) }
|
||||
if let request = model.selection, request.buffer == doc.id, request.id != coord.lastSelection {
|
||||
coord.lastSelection = request.id
|
||||
let range = NSIntersectionRange(request.range, NSRange(location: 0, length: editor.string.utf16.count))
|
||||
editor.setSelectedRange(range); editor.scrollRangeToVisible(range)
|
||||
}
|
||||
let active = model.executionLine
|
||||
if changedDocument || changedSource || coord.markedLine != active {
|
||||
coord.markedLine = active
|
||||
let length = editor.string.utf16.count
|
||||
editor.layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: NSRange(location: 0, length: length))
|
||||
if let active, active.path == doc.path, let range = AssemblyDevelopmentModel.lineRange(active.line, text: doc.text) {
|
||||
editor.layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemGreen.withAlphaComponent(0.22), forCharacterRange: range)
|
||||
}
|
||||
}
|
||||
}
|
||||
static func dismantleNSView(_ scroll: NSScrollView, coordinator: Coordinator) {
|
||||
if let editor = scroll.documentView as? AssemblyTextView {
|
||||
editor.delegate = nil; editor.lookup = nil; editor.definition = nil
|
||||
}
|
||||
}
|
||||
@MainActor final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
let model: AssemblyDevelopmentModel
|
||||
var updating = false
|
||||
var bufferID: UUID?
|
||||
var lastSelection: UUID?
|
||||
var markedLine: AssemblyDevelopmentModel.SourceLine?
|
||||
init(model: AssemblyDevelopmentModel) { self.model = model }
|
||||
private var changedCharacters: NSRange?
|
||||
func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
|
||||
changedCharacters = replacementString.map { NSRange(location: affectedCharRange.location, length: $0.utf16.count) }
|
||||
return true
|
||||
}
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard !updating, let view = notification.object as? AssemblyTextView, bufferID == model.buffer.id else { return }
|
||||
model.edit(view.string)
|
||||
color(view, changed: changedCharacters)
|
||||
changedCharacters = nil
|
||||
}
|
||||
func textViewDidChangeSelection(_ notification: Notification) {
|
||||
guard !updating, let view = notification.object as? NSTextView, bufferID == model.buffer.id else { return }
|
||||
model.moveCursor(view.selectedRange().location)
|
||||
}
|
||||
fileprivate func color(_ editor: AssemblyTextView, changed: NSRange? = nil) {
|
||||
let ns = editor.string as NSString
|
||||
let layout = editor.layoutManager
|
||||
let range = changed.flatMap { NSMaxRange($0) <= ns.length ? ns.lineRange(for: $0) : nil } ?? NSRange(location: 0, length: ns.length)
|
||||
layout?.removeTemporaryAttribute(.foregroundColor, forCharacterRange: range)
|
||||
let words = AssemblyReference.shared.vocabulary(target6309: editor.target6309)
|
||||
var pos = range.location
|
||||
while pos < NSMaxRange(range) {
|
||||
let row = ns.lineRange(for: NSRange(location: pos, length: 0))
|
||||
for token in AssemblyEditorSyntax.tokens(in: ns.substring(with: row), vocabulary: words) {
|
||||
let color: NSColor
|
||||
switch token.kind {
|
||||
case .label: color = .systemPurple
|
||||
case .mnemonic: color = .systemBlue
|
||||
case .directive: color = .systemTeal
|
||||
case .literal: color = .systemOrange
|
||||
case .operand: color = .labelColor
|
||||
case .comment: color = .secondaryLabelColor
|
||||
}
|
||||
layout?.addTemporaryAttribute(.foregroundColor, value: color,
|
||||
forCharacterRange: NSRange(location: pos + token.range.location, length: token.range.length))
|
||||
}
|
||||
pos = NSMaxRange(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
enum AssemblyCPU: String, CaseIterable, Codable, Sendable {
|
||||
case mc6809 = "6809"
|
||||
case hd6309 = "6309"
|
||||
}
|
||||
|
||||
struct AssemblyProjectSnapshot: Equatable, Sendable {
|
||||
static let configurationFilename = "vccplus-assembly.json"
|
||||
|
||||
struct Settings: Codable, Equatable, Sendable {
|
||||
var main: String?
|
||||
var modules: [String]?
|
||||
var linkScript: String?
|
||||
var makefile: String?
|
||||
var target: String?
|
||||
var binary: String?
|
||||
}
|
||||
|
||||
let mainPath: String
|
||||
let files: [String: Data]
|
||||
let cpu: AssemblyCPU
|
||||
let settings: Settings
|
||||
|
||||
static func single(source: String, path: String = "main.asm", cpu: AssemblyCPU = .mc6809) -> Self {
|
||||
Self(mainPath: path, files: [path: Data(source.utf8)], cpu: cpu, settings: Settings())
|
||||
}
|
||||
|
||||
static func read(directory: URL, mainPath: String = "main.asm", overlays: [String: String] = [:],
|
||||
cpu: AssemblyCPU = .mc6809) throws -> Self {
|
||||
var files = try CMOCProject.files(in: directory)
|
||||
for (path, text) in overlays {
|
||||
try CMOCProject.validateRelativePath(path)
|
||||
files[path] = try CMOCProject.sourceBytes(text)
|
||||
}
|
||||
let settings = try files[configurationFilename].map {
|
||||
try JSONDecoder().decode(Settings.self, from: $0)
|
||||
} ?? Settings()
|
||||
let entry = settings.main ?? mainPath
|
||||
if let binary = settings.binary { files.removeValue(forKey: binary) }
|
||||
let snapshot = Self(mainPath: entry, files: files, cpu: cpu, settings: settings)
|
||||
try snapshot.validate()
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/// A loose source may live in Documents or Downloads. Only follow its literal
|
||||
/// include chain; never enumerate or copy unrelated neighboring files.
|
||||
static func readSource(at url: URL, overlays: [String: String] = [:], cpu: AssemblyCPU = .mc6809) throws -> Self {
|
||||
let root = try CMOCProject.physicalURL(url.deletingLastPathComponent()).standardizedFileURL
|
||||
let main = url.lastPathComponent
|
||||
var files: [String: Data] = [:], scanned = Set<String>(), total = 0
|
||||
var pending = [(path: main, binary: false)]
|
||||
let directive = try NSRegularExpression(pattern:
|
||||
#"(?i)^(?:[^\s*;]+\s+|\s+)(include|incl|use|lib|includebin)\s+(?:"([^"]+)"|'([^']+)'|([^\s,;]+))"#)
|
||||
while let input = pending.popLast() {
|
||||
try Task.checkCancellation()
|
||||
try CMOCProject.validateRelativePath(input.path)
|
||||
let file = root.appendingPathComponent(input.path)
|
||||
if files[input.path] == nil {
|
||||
let data: Data
|
||||
if let overlay = overlays[input.path] {
|
||||
data = try CMOCProject.sourceBytes(overlay)
|
||||
} else {
|
||||
guard file.standardizedFileURL.path == file.resolvingSymlinksInPath().standardizedFileURL.path else {
|
||||
throw AssemblyBuildFailure("Copy linked inputs into the source folder before assembling.")
|
||||
}
|
||||
guard FileManager.default.fileExists(atPath: file.path) || input.path == main else { continue }
|
||||
data = try DevelopmentBuildTools.readFile(file, limit: CMOCProject.maximumFileBytes)
|
||||
}
|
||||
total += data.count
|
||||
guard total <= CMOCProject.maximumProjectBytes, files.count < 20_000 else {
|
||||
throw AssemblyBuildFailure("The included source files exceed the project snapshot limit.")
|
||||
}
|
||||
files[input.path] = data
|
||||
}
|
||||
guard !input.binary, scanned.insert(input.path).inserted, let data = files[input.path] else { continue }
|
||||
guard data.count <= CMOCProject.maximumSourceBytes, let source = String(data: data, encoding: .utf8) else {
|
||||
throw AssemblyBuildFailure("Choose UTF-8 source files of at most 1 MB.")
|
||||
}
|
||||
for line in source.components(separatedBy: .newlines) {
|
||||
let ns = line as NSString
|
||||
guard let match = directive.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)),
|
||||
let index = (2...4).first(where: { match.range(at: $0).location != NSNotFound }) else { continue }
|
||||
let operand = ns.substring(with: match.range(at: index))
|
||||
let included = file.deletingLastPathComponent().appendingPathComponent(operand).standardizedFileURL
|
||||
guard !operand.hasPrefix("/"), included.path.hasPrefix(root.path + "/") else {
|
||||
throw AssemblyBuildFailure("Keep assembly includes inside the source folder: " + operand)
|
||||
}
|
||||
var relative = String(included.path.dropFirst(root.path.count + 1))
|
||||
// Match LWASM's search order: the including file's folder first,
|
||||
// then the root supplied by -I. A buffer may exist before saving.
|
||||
if overlays[relative] == nil && !FileManager.default.fileExists(atPath: included.path) {
|
||||
let fallback = root.appendingPathComponent(operand).standardizedFileURL
|
||||
if fallback.path.hasPrefix(root.path + "/") {
|
||||
relative = String(fallback.path.dropFirst(root.path.count + 1))
|
||||
}
|
||||
}
|
||||
pending.append((relative, ns.substring(with: match.range(at: 1)).lowercased() == "includebin"))
|
||||
}
|
||||
}
|
||||
let snapshot = Self(mainPath: main, files: files, cpu: cpu, settings: Settings())
|
||||
try snapshot.validate()
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func validate() throws {
|
||||
let modules = [mainPath] + (settings.modules ?? [])
|
||||
guard modules.count <= 128, Set(modules).count == modules.count else {
|
||||
throw AssemblyBuildFailure("Use up to 128 distinct assembly modules.")
|
||||
}
|
||||
for path in files.keys { try CMOCProject.validateRelativePath(path) }
|
||||
for path in modules + [settings.makefile, settings.linkScript].compactMap({ $0 }) {
|
||||
try CMOCProject.validateRelativePath(path)
|
||||
guard files[path] != nil else { throw AssemblyBuildFailure("The project is missing " + path) }
|
||||
}
|
||||
for module in modules {
|
||||
guard let data = files[module], data.count <= CMOCProject.maximumSourceBytes,
|
||||
!data.contains(0), String(data: data, encoding: .utf8) != nil else {
|
||||
throw AssemblyBuildFailure("Choose UTF-8 assembly modules of at most 1 MB without NUL characters.")
|
||||
}
|
||||
}
|
||||
if let makefile = settings.makefile {
|
||||
guard settings.modules == nil, settings.linkScript == nil, let binary = settings.binary,
|
||||
binary.lowercased().hasSuffix(".bin"), ![mainPath, makefile].contains(binary) else {
|
||||
throw AssemblyBuildFailure("For custom Make, set makefile, target and binary. Use modules and linkScript for native linked builds.")
|
||||
}
|
||||
try CMOCProject.validateRelativePath(binary)
|
||||
try CMOCProjectConfiguration.validateTarget(settings.target ?? "all")
|
||||
} else if settings.binary != nil || settings.target != nil {
|
||||
throw AssemblyBuildFailure("A custom binary path or target requires a Makefile.")
|
||||
}
|
||||
if !(settings.modules ?? []).isEmpty, settings.linkScript == nil {
|
||||
throw AssemblyBuildFailure("Set linkScript to a project-relative LWLINK script with a load address and entry.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
enum AssemblyReferenceCategory: String, CaseIterable {
|
||||
case instructions = "Instructions"
|
||||
case registers = "Registers & Flags"
|
||||
case addressing = "Addressing Modes"
|
||||
case directives = "LWASM Directives"
|
||||
case examples = "CoCo Examples"
|
||||
case dialect = "Dialect & Compatibility"
|
||||
}
|
||||
|
||||
enum AssemblyOperandForm {
|
||||
case inherent, value, memory, indexed, relative, immediate, pair, stack, bit, maskMemory, transfer, directive, topic
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .inherent: return "No operand"
|
||||
case .value: return "#literal · <direct · offset,X · >address"
|
||||
case .memory: return "<direct · offset,X · >address"
|
||||
case .indexed: return "offset,index"
|
||||
case .relative: return "target label"
|
||||
case .immediate: return "#mask"
|
||||
case .pair: return "source register,destination register"
|
||||
case .stack: return "register[,register…] · #mask"
|
||||
case .bit: return "A|B|CC,source bit,destination bit,direct address"
|
||||
case .maskMemory: return "#mask,address · #mask,offset,X"
|
||||
case .transfer: return "r+,r+ · r-,r- · r+,r · r,r+"
|
||||
case .directive, .topic: return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AssemblyReferenceEntry: Identifiable {
|
||||
let id: String
|
||||
let name: String
|
||||
let category: AssemblyReferenceCategory
|
||||
let only6309: Bool
|
||||
let aliases: [String]
|
||||
let form: AssemblyOperandForm
|
||||
let syntax: String
|
||||
let operation: String
|
||||
let flags: String
|
||||
let detail: String
|
||||
let links: [String]
|
||||
let citations: [String]
|
||||
let terms: [String]
|
||||
let example: String?
|
||||
|
||||
init(_ name: String, _ category: AssemblyReferenceCategory, only6309: Bool = false,
|
||||
aliases: [String] = [], form: AssemblyOperandForm = .topic, syntax: String = "",
|
||||
operation: String, flags: String = "", detail: String = "", links: [String] = [],
|
||||
citations: [String], terms: [String] = [], example: String? = nil) {
|
||||
self.name = name
|
||||
self.category = category
|
||||
self.id = "\(category).\(name.lowercased().replacingOccurrences(of: " ", with: "-"))"
|
||||
self.only6309 = only6309
|
||||
self.aliases = aliases
|
||||
self.form = form
|
||||
self.syntax = syntax.isEmpty ? form.description : syntax
|
||||
self.operation = operation
|
||||
self.flags = flags
|
||||
self.detail = detail
|
||||
self.links = links
|
||||
self.citations = citations
|
||||
self.terms = terms
|
||||
self.example = example
|
||||
}
|
||||
}
|
||||
|
||||
struct AssemblyReferenceExampleRequest: Codable, Hashable {
|
||||
var id = UUID()
|
||||
let title: String
|
||||
let source: String
|
||||
let target6309: Bool
|
||||
}
|
||||
|
||||
struct AssemblyReference {
|
||||
static let shared = AssemblyReference()
|
||||
let entries: [AssemblyReferenceEntry]
|
||||
private let byTerm: [String: AssemblyReferenceEntry]
|
||||
private let commonWords: Set<String>
|
||||
private let allWords: Set<String>
|
||||
|
||||
init() {
|
||||
entries = (Self.instructions() + Self.topics()).sorted { $0.name < $1.name }
|
||||
var index: [String: AssemblyReferenceEntry] = [:]
|
||||
var common = Set<String>(), all = Set<String>()
|
||||
for entry in entries {
|
||||
for word in [entry.name] + entry.aliases {
|
||||
index[word.uppercased()] = entry
|
||||
if entry.category == .instructions || entry.category == .directives {
|
||||
all.insert(word.uppercased())
|
||||
if !entry.only6309 { common.insert(word.uppercased()) }
|
||||
}
|
||||
}
|
||||
index[entry.id.uppercased()] = entry
|
||||
}
|
||||
byTerm = index
|
||||
commonWords = common
|
||||
allWords = all
|
||||
}
|
||||
|
||||
func entry(_ term: String) -> AssemblyReferenceEntry? { byTerm[term.uppercased()] }
|
||||
|
||||
func vocabulary(target6309: Bool) -> Set<String> { target6309 ? allWords : commonWords }
|
||||
|
||||
func search(_ query: String, target6309: Bool?, category: AssemblyReferenceCategory?) -> [AssemblyReferenceEntry] {
|
||||
let words = query.lowercased().split(whereSeparator: \.isWhitespace)
|
||||
let result = entries.filter { entry in
|
||||
guard (target6309 != false || !entry.only6309), category == nil || entry.category == category else { return false }
|
||||
let fields = [entry.name, entry.operation, entry.flags, entry.detail] + entry.aliases + entry.terms
|
||||
let haystack = fields.joined(separator: " ").lowercased()
|
||||
return words.allSatisfy { haystack.contains($0) }
|
||||
}
|
||||
if let exact = entry(query), let i = result.firstIndex(where: { $0.id == exact.id }) {
|
||||
var ranked = result
|
||||
ranked.insert(ranked.remove(at: i), at: 0)
|
||||
return ranked
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
extension AssemblyReference {
|
||||
func isDirective(_ word: String) -> Bool { entry(word)?.category == .directives }
|
||||
|
||||
private struct LineFields {
|
||||
let opcode: String
|
||||
let operand: String
|
||||
let atMnemonic: Bool
|
||||
let partial: String
|
||||
}
|
||||
|
||||
/// LWASM's first column is the optional label field. NSTextView supplies UTF-16 offsets.
|
||||
private func fields(_ source: String, _ offset: Int) -> LineFields? {
|
||||
let text = source as NSString
|
||||
guard offset >= 0, offset <= text.length else { return nil }
|
||||
let range = text.lineRange(for: NSRange(location: offset, length: 0))
|
||||
let line = text.substring(with: range) as NSString
|
||||
let caret = offset - range.location
|
||||
let before = line.substring(to: caret)
|
||||
let trimmed = before.drop(while: \.isWhitespace)
|
||||
guard !trimmed.hasPrefix("*"), !trimmed.hasPrefix(";") else { return nil }
|
||||
// Only a prefix of the operand is needed. Never suggest into a string or a comment.
|
||||
guard !before.contains(";"), !before.contains("\""), !before.contains("'") else { return nil }
|
||||
func space(_ i: Int) -> Bool { [9,10,13,32].contains(line.character(at: i)) }
|
||||
var i = 0
|
||||
if i < line.length, !space(i) {
|
||||
while i < line.length && !space(i) { i += 1 }
|
||||
if caret <= i { return nil }
|
||||
}
|
||||
while i < line.length && space(i) { i += 1 }
|
||||
let start = i
|
||||
while i < line.length && !space(i) && line.character(at: i) != 59 { i += 1 }
|
||||
let opcode = line.substring(with: NSRange(location: start, length: i - start)).uppercased()
|
||||
if caret <= i {
|
||||
let length = max(0, caret - start)
|
||||
return .init(opcode: opcode, operand: "", atMnemonic: true,
|
||||
partial: line.substring(with: NSRange(location: start, length: length)).uppercased())
|
||||
}
|
||||
let tail = (before as NSString).substring(from: i)
|
||||
.trimmingPrefixWhitespace
|
||||
// LWASM's ordinary syntax permits trailing comments after the operand, even without a semicolon.
|
||||
guard !["FCC","FCN","FCS"].contains(entry(opcode)?.name ?? ""), !tail.contains(where: \.isWhitespace), !tail.hasPrefix("*") else { return nil }
|
||||
let partial = String(tail.reversed().prefix { $0.isLetter || $0.isNumber || $0 == "_" }.reversed())
|
||||
return .init(opcode: opcode, operand: tail, atMnemonic: false, partial: partial)
|
||||
}
|
||||
|
||||
func topic(in source: String, at offset: Int, target6309: Bool) -> String? {
|
||||
guard let fields = fields(source, offset), let entry = entry(fields.opcode),
|
||||
vocabulary(target6309: target6309).contains(fields.opcode) else { return nil }
|
||||
return entry.name
|
||||
}
|
||||
|
||||
func completions(in source: String, at offset: Int, target6309: Bool) -> [String] {
|
||||
guard let fields = fields(source, offset) else { return [] }
|
||||
let words = vocabulary(target6309: target6309)
|
||||
if fields.atMnemonic {
|
||||
return words.filter { $0.hasPrefix(fields.partial) }.sorted()
|
||||
}
|
||||
guard words.contains(fields.opcode), let item = entry(fields.opcode) else { return [] }
|
||||
let parts = fields.operand.uppercased().components(separatedBy: ",")
|
||||
let candidates: [String]
|
||||
let byteRegs = ["A","B","CC","DP"] + (target6309 ? ["E","F"] : [])
|
||||
let wordRegs = ["X","Y","D","S","U","PC"] + (target6309 ? ["W","V"] : [])
|
||||
switch item.form {
|
||||
case .pair:
|
||||
guard parts.count <= 2 else { return [] }
|
||||
if parts.count == 2 && !target6309 {
|
||||
if byteRegs.contains(parts[0]) { candidates = byteRegs }
|
||||
else if wordRegs.contains(parts[0]) { candidates = wordRegs }
|
||||
else { return [] }
|
||||
} else {
|
||||
// The HD6309 register arithmetic family has unpredictable PC operands.
|
||||
let regs = byteRegs + wordRegs + (target6309 ? ["0"] : [])
|
||||
candidates = ["TFR","EXG"].contains(item.name) ? regs : regs.filter { $0 != "PC" }
|
||||
}
|
||||
case .transfer:
|
||||
guard parts.count <= 2 else { return [] }
|
||||
let regs = ["D","X","Y","U","S"]
|
||||
if parts.count == 2 {
|
||||
let sourceReg = parts[0].trimmingCharacters(in: CharacterSet(charactersIn: "+-"))
|
||||
guard regs.contains(sourceReg) else { return [] }
|
||||
}
|
||||
if fields.opcode != "TFM" { candidates = regs }
|
||||
else {
|
||||
let suffixes: [String]
|
||||
if parts.count == 1 { suffixes = ["","+","-"] }
|
||||
else if parts[0].hasSuffix("+") { suffixes = ["","+"] }
|
||||
else if parts[0].hasSuffix("-") { suffixes = ["-"] }
|
||||
else { suffixes = ["+"] }
|
||||
guard !fields.operand.hasSuffix("+"), !fields.operand.hasSuffix("-") else { return [] }
|
||||
candidates = regs.flatMap { reg in suffixes.map { reg + $0 } }
|
||||
}
|
||||
case .stack:
|
||||
guard !fields.operand.hasPrefix("#") else { return [] }
|
||||
let regs = ["A","B","D","CC","DP","PC","X","Y",item.name.hasSuffix("S") ? "U" : "S"]
|
||||
candidates = regs.filter { !parts.dropLast().contains($0) }
|
||||
case .bit:
|
||||
if parts.count == 1 { candidates = ["A","B","CC"] }
|
||||
else if parts.count == 2 || parts.count == 3 { candidates = (0...7).map(String.init) }
|
||||
else if parts.count == 4 { candidates = labels(in: source) } else { return [] }
|
||||
case .indexed, .memory, .value, .maskMemory:
|
||||
if item.form != .maskMemory && fields.operand.hasPrefix("#") {
|
||||
guard item.form == .value && parts.count == 1 else { return [] }
|
||||
}
|
||||
let index = item.form == .maskMemory ? 2 : 1
|
||||
guard parts.count <= index + 1 else { return [] }
|
||||
if parts.count == index + 1 {
|
||||
let displacement = parts[index - 1].trimmingCharacters(in: CharacterSet(charactersIn: "["))
|
||||
var regs = ["X","Y","U","S"]
|
||||
guard target6309 || !["E","F","W"].contains(displacement) else { return [] }
|
||||
let registerOffset = ["A","B","D","E","F","W"].contains(displacement)
|
||||
if !registerOffset && !displacement.isEmpty { regs.append("PCR") }
|
||||
if target6309 && !registerOffset { regs.append("W") }
|
||||
guard !fields.operand.hasSuffix("+") && !fields.operand.hasSuffix("]") else { return [] }
|
||||
if parts.last?.hasPrefix("-") == true { regs = regs.filter { $0 != "PCR" && ($0 != "W" || parts.last?.hasPrefix("--") == true) } }
|
||||
candidates = regs
|
||||
} else if parts.count == index || (item.form == .maskMemory && parts.count == 1) {
|
||||
candidates = labels(in: source)
|
||||
} else { return [] }
|
||||
case .relative:
|
||||
guard !fields.operand.hasPrefix("#"), parts.count == 1 else { return [] }
|
||||
candidates = labels(in: source)
|
||||
case .immediate: candidates = labels(in: source)
|
||||
case .directive, .topic, .inherent: return []
|
||||
}
|
||||
return candidates.filter { $0.uppercased().hasPrefix(fields.partial.uppercased()) }.sorted()
|
||||
}
|
||||
|
||||
private func labels(in source: String) -> [String] {
|
||||
var names = Set<String>()
|
||||
for line in source.split(whereSeparator: \.isNewline) {
|
||||
guard let first = line.first, first.isLetter || first == "_" else { continue }
|
||||
names.insert(String(line.prefix { $0.isLetter || $0.isNumber || $0 == "_" }))
|
||||
}
|
||||
return names.sorted()
|
||||
}
|
||||
}
|
||||
|
||||
private extension String {
|
||||
var trimmingPrefixWhitespace: String { String(drop(while: \.isWhitespace)) }
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
extension AssemblyReference {
|
||||
static func instructions() -> [AssemblyReferenceEntry] {
|
||||
var entries: [AssemblyReferenceEntry] = []
|
||||
let same = "CC is preserved."
|
||||
let nz = "N reflects the sign bit. Z marks a zero result."
|
||||
let logic = nz + " V clears. C is preserved."
|
||||
let add = nz + " V marks signed overflow. C marks unsigned carry."
|
||||
let sub = nz + " V marks signed overflow. C marks a borrow."
|
||||
func instruction(_ name: String, _ hd: Bool, _ form: AssemblyOperandForm, _ operation: String,
|
||||
_ flags: String, _ pages: String, aliases: [String] = [], detail: String = "",
|
||||
links: [String] = [], example: String? = nil) {
|
||||
let citation = "Atkinson (2009), pp. " + pages
|
||||
var citations = [citation]
|
||||
if name == "TFM" { citations.append("VCC Plus, Native Debugger, HD6309 Step") }
|
||||
if !hd { citations.append("Motorola (1981), Appendix A, " + name.trimmingCharacters(in: .decimalDigits)) }
|
||||
citations.append("Astle, LWTools 4.25, ch. 3")
|
||||
var related = links
|
||||
switch form {
|
||||
case .value, .memory, .indexed, .maskMemory: related.append("Indexed")
|
||||
case .relative: related.append("Relative")
|
||||
case .immediate: related.append("Immediate")
|
||||
case .bit: related.append("Direct")
|
||||
default: break
|
||||
}
|
||||
if !related.contains("Condition codes") { related.append("Condition codes") }
|
||||
entries.append(.init(name, .instructions, only6309: hd, aliases: aliases, form: form,
|
||||
operation: operation, flags: flags, detail: detail, links: related,
|
||||
citations: citations, example: example))
|
||||
}
|
||||
// Available registers differ across both instruction families and processors.
|
||||
for (op, portable, extra) in [
|
||||
("LD","A B D X Y U S","E F W Q"), ("ST","A B D X Y U S","E F W Q"),
|
||||
("ADD","A B D","E F W"), ("ADC","A B","D"), ("SUB","A B D","E F W"), ("SBC","A B","D"),
|
||||
("CMP","A B D X Y U S","E F W"), ("AND","A B","D"), ("OR","A B","D"),
|
||||
("EOR","A B","D"), ("BIT","A B","D")
|
||||
] {
|
||||
let base = portable.components(separatedBy: " ")
|
||||
for reg in base + extra.components(separatedBy: " ") {
|
||||
let byte = ["A","B","E","F"].contains(reg)
|
||||
let operation: String, flags: String, pages: String
|
||||
var detail = "", lesson: String?
|
||||
switch op {
|
||||
case "LD":
|
||||
operation = "Copy the operand into \(reg). Use # for a literal or read \(byte ? "one byte" : reg == "Q" ? "four bytes" : "two bytes") from the addressed memory."
|
||||
flags = logic; pages = byte ? "90" : reg == "Q" ? "94" : "91"
|
||||
if reg == "A" {
|
||||
detail = "LDA #$20 places $20 in A. LDA $0400 reads the byte at $0400. LDA ,X+ reads at X, then advances X by one. The remaining CC bits keep their values. Immediate LDA takes 2 cycles. Extended LDA takes 5 on MC6809 or HD6309 emulation mode and 4 in HD6309 native mode. Indexed timing depends on the postbyte."
|
||||
lesson = "cell"
|
||||
} else if reg == "W" {
|
||||
detail = "LDW #$1234 encodes as 10 86 12 34. E becomes $12 and F becomes $34 in either HD6309 execution mode."
|
||||
lesson = "word"
|
||||
}
|
||||
case "ST":
|
||||
operation = "Copy \(reg) to the destination address. Multi-byte stores write the high byte first."
|
||||
flags = logic; pages = byte ? "127" : reg == "Q" ? "130" : "128"
|
||||
if reg == "A" { lesson = "cell" }
|
||||
case "ADD", "ADC":
|
||||
operation = "Add the operand" + (op == "ADC" ? " and incoming carry" : "") + " to \(reg). Keep the low \(byte ? 8 : 16) bits in \(reg)."
|
||||
flags = add + (byte ? " H records carry from bit 3." : " H is preserved.")
|
||||
pages = op == "ADC" ? (byte ? "5" : "6") : (byte ? "8" : "9")
|
||||
case "SUB", "SBC", "CMP":
|
||||
operation = "Subtract the operand" + (op == "SBC" ? " and incoming borrow" : "") + " from \(reg). " + (op == "CMP" ? "Keep \(reg) intact for a later branch." : "Write the difference to \(reg).")
|
||||
flags = sub + (byte ? " H is undefined." : "")
|
||||
pages = op == "CMP" ? (byte ? "50" : "51") : op == "SBC" ? (byte ? "122" : "123") : (byte ? "131" : "132")
|
||||
if op == "CMP" { lesson = "signed" }
|
||||
default:
|
||||
let action = ["AND":"Keep bits set in both inputs.", "OR":"Set bits present in either input.",
|
||||
"EOR":"Set bits where the inputs differ.", "BIT":"Test the bits of \(reg) selected by the operand."][op]!
|
||||
operation = action + (op == "BIT" ? " Preserve both inputs." : " Combine \(reg) with the operand and save the result in \(reg).")
|
||||
flags = logic
|
||||
pages = ["AND":byte ? "12" : "14", "OR":byte ? "106" : "108",
|
||||
"EOR":byte ? "62" : "63", "BIT":byte ? "32" : "33"][op]!
|
||||
}
|
||||
instruction(op + reg, !base.contains(reg), op == "ST" ? .memory : .value,
|
||||
operation, flags, pages, detail: detail, links: [reg], example: lesson)
|
||||
}
|
||||
}
|
||||
|
||||
for (op, extra, operation, flags, pages) in [
|
||||
("ASL","D","Shift one place left and fill bit 0 with zero.",nz + " C receives the old top bit. V is N XOR C.","16–17"),
|
||||
("ASR","D","Shift right, preserving the sign bit.",nz + " C receives the old bit 0. V is preserved.","18–19"),
|
||||
("LSR","D W","Shift right, bringing zero into the top bit.","N clears. Z marks zero. C receives the old bit 0. V is preserved.","98–99"),
|
||||
("ROL","D W","Shift left, moving the old carry into bit 0.",nz + " C receives the old top bit. V is N XOR C.","116–117"),
|
||||
("ROR","D W","Shift right, moving the old carry into the top bit.",nz + " C receives the old bit 0. V is preserved.","118–119"),
|
||||
("CLR","D E F W","Write zero.","Z sets. N, V and C clear.","48–49"),
|
||||
("COM","D E F W","Invert every bit.",nz + " C sets and V clears.","53–54"),
|
||||
("NEG","D","Subtract the value from zero.",nz + " C sets for a nonzero input. V marks negation of the most negative value.","102–103"),
|
||||
("INC","D E F W","Add one.",nz + " V sets on crossing from maximum positive to minimum negative. C is preserved.","67–68"),
|
||||
("DEC","D E F W","Subtract one.",nz + " V sets on crossing from minimum negative to maximum positive. C is preserved.","57–58"),
|
||||
("TST","D E F W","Test the value while preserving it.",logic,"140–141")
|
||||
] {
|
||||
for reg in ["","A","B"] + extra.components(separatedBy: " ") {
|
||||
let hd = !["","A","B"].contains(reg)
|
||||
let destination = reg.isEmpty ? "a memory byte" : "register " + reg
|
||||
instruction(op + reg, hd, reg.isEmpty ? .memory : .inherent,
|
||||
"Operate on \(destination). " + operation, flags + (["ASL","ASR"].contains(op) && !hd ? " H is undefined." : ""), pages,
|
||||
aliases: op == "ASL" ? ["LSL" + reg] : [], example: op == "DEC" ? "count" : nil)
|
||||
}
|
||||
}
|
||||
|
||||
for (suffix, condition, page, longPage) in [
|
||||
("CC","C is clear (unsigned higher or equal after a compare)",21,71), ("CS","C is set (unsigned lower)",22,72),
|
||||
("EQ","Z is set (equal)",24,73), ("NE","Z is clear (unequal)",40,83),
|
||||
("GE","N equals V (signed greater or equal)",25,74), ("GT","Z is clear and N equals V (signed greater)",26,75),
|
||||
("LE","Z is set or N differs from V (signed less or equal)",35,78), ("LT","N differs from V (signed less)",38,81),
|
||||
("HI","C and Z are both clear (unsigned higher)",27,76), ("LS","C or Z is set (unsigned lower or equal)",37,80),
|
||||
("MI","N is set (negative)",39,82), ("PL","N is clear (nonnegative)",42,84),
|
||||
("VC","V is clear (no signed overflow)",46,88), ("VS","V is set (signed overflow)",47,89),
|
||||
("RA","always",43,85), ("RN","never",44,86), ("SR","call",45,87)
|
||||
] {
|
||||
for long in [false,true] {
|
||||
let prefix = long ? "LB" : "B"
|
||||
let action: String
|
||||
switch suffix {
|
||||
case "RA": action = "Continue at the target. A branch to its own label forms a hold loop."
|
||||
case "RN": action = "Read the displacement and continue at the next instruction."
|
||||
case "SR": action = "Push the following instruction’s address on S, then continue at the target. RTS returns to the caller."
|
||||
default: action = "Continue at the target when " + condition + ". Otherwise execute the next instruction."
|
||||
}
|
||||
let aliases = suffix == "CC" ? [prefix + "HS"] : suffix == "CS" ? [prefix + "LO"] : []
|
||||
instruction(prefix + suffix, false, .relative, action, same, String(long ? longPage : page),
|
||||
aliases: aliases, detail: "The signed \(long ? 16 : 8)-bit displacement is relative to the following instruction.",
|
||||
example: suffix == "NE" ? "count" : suffix == "SR" ? "call" : "signed")
|
||||
}
|
||||
}
|
||||
for (reg, flag) in [("X",true),("Y",true),("S",false),("U",false)] {
|
||||
instruction("LEA" + reg, false, .indexed, "Calculate an indexed address and place it in \(reg). Indirect addressing reads a pointer before producing the address.",
|
||||
flag ? "Only Z changes, to indicate a zero address." : same, "95", links: [reg])
|
||||
}
|
||||
for (op, action, flags, page) in [
|
||||
("ADDR","Add source to destination.",add,10), ("ADCR","Add source and carry to destination.",add,7),
|
||||
("SUBR","Subtract source from destination.",sub,133), ("SBCR","Subtract source and borrow from destination.",sub,124),
|
||||
("CMPR","Compare destination minus source, preserving both.",sub,52), ("ANDR","Apply bitwise AND to the destination using the source.",logic,15),
|
||||
("ORR","Apply bitwise OR to the destination using the source.",logic,109),
|
||||
("EORR","Toggle destination bits selected by the source.",logic,64)
|
||||
] {
|
||||
instruction(op, true, .pair, action, flags, String(page),
|
||||
detail: "The destination selects the width. A word source supplies its low byte to a byte destination. For a word destination A/B supply D, E/F supply W, CC is zero-extended and DP supplies the high byte. PC is undefined in this family. See Atkinson, p. 143.", links: ["W"])
|
||||
}
|
||||
for (op, action, page) in [("AIM","AND",11),("OIM","OR",105),("EIM","exclusive OR",61),("TIM","AND",139)] {
|
||||
instruction(op, true, .maskMemory, "Combine the literal mask and the addressed byte with \(action). " + (op == "TIM" ? "Use the result only to test flags." : "Write the result to that address."), logic, String(page))
|
||||
}
|
||||
for (op, action, page) in [("BAND","AND",20),("BIAND","AND with the inverted source",29),("BOR","OR",41),("BIOR","OR with the inverted source",31),("BEOR","exclusive OR",23),("BIEOR","exclusive OR with the inverted source",30),("LDBT","copy",92),("STBT","store",129)] {
|
||||
let description = op == "STBT" ? "Copy the selected register bit to the destination bit in direct-page memory." :
|
||||
"Combine the selected memory bit with the destination register bit using \(action). Only the destination bit changes."
|
||||
instruction(op, true, .bit, description, "CC can change when a destination bit in CC is selected.", String(page))
|
||||
}
|
||||
for (stack, other) in [("S","U"),("U","S")] {
|
||||
for push in [true,false] {
|
||||
let prefix = push ? "PSH" : "PUL"
|
||||
instruction(prefix + stack, false, .stack, push ? "Save selected registers on \(stack). The stack grows toward lower addresses." :
|
||||
"Restore selected registers from \(stack), advancing the stack pointer. Pulling PC transfers control.",
|
||||
push ? same : "Pulling CC replaces all its flags.", push ? "110" : "113",
|
||||
detail: "Select CC, A, B, DP, X, Y, \(other) or PC. LWASM also accepts D for A and B. Hardware determines the register order.", links: [stack], example: "call")
|
||||
instruction(prefix + stack + "W", true, .inherent, push ? "Push both bytes of W onto \(stack), subtracting two from the pointer." :
|
||||
"Pull two bytes into W from \(stack), advancing the pointer by two.",
|
||||
same, String((push ? 111 : 114) + (stack == "S" ? 0 : 1)), links: ["W",stack])
|
||||
}
|
||||
}
|
||||
instruction("TFM", true, .transfer, "Copy W bytes between addresses held in D, X, Y, U or S. Each suffix advances, retreats or holds its pointer after a byte. W counts down to zero. Without interruption the transfer costs 6 cycles plus 3 per byte.", same, "136",
|
||||
aliases: ["COPY","COPY+","COPY-","TFRP","TFRM","IMP","IMPLODE","TFRS","EXP","EXPAND","TFRR"],
|
||||
detail: "LWASM’s alternative spellings take two bare registers. COPY/COPY+/TFRP advance both, COPY-/TFRM retreat both, IMP/IMPLODE/TFRS advance the source and EXP/EXPAND/TFRR advance the destination. In VCC Plus, debugger Step finishes the block. Continue can hit a breakpoint again between bytes.",
|
||||
links: ["HD6309 modes","W"], example: "transfer")
|
||||
for (name, action, page) in [("EXG","Exchange the contents of the two registers.","65–66"),("TFR","Copy the source register to the destination.","137–138")] {
|
||||
instruction(name, false, .pair, action, "Writing CC replaces its flags.", page,
|
||||
detail: "Use equal-width registers on the MC6809. The HD6309 has additional registers and defined mixed-width behavior. Writing PC transfers control.", links: ["D","W"])
|
||||
}
|
||||
for (name, operation, flags, page) in [
|
||||
("ANDCC","Keep only CC bits selected by the mask.","Any CC bit can clear.",13),("ORCC","Set each CC bit selected by the mask.","Any CC bit can set.",107),
|
||||
("CWAI","AND CC with the mask, stack the full interrupt context on S, then wait for an eligible interrupt.","The mask updates CC. E sets for the stacked full context.",55),
|
||||
("LDMD","Write the low two mode-control bits of MD.",same,93),
|
||||
("BITMD","Test the masked trap status bits of MD. Reading a selected sticky error clears it.","Z sets if no selected error was pending.",34)
|
||||
] {
|
||||
instruction(name, name.hasSuffix("MD"), .immediate, operation, flags, String(page), links: name.hasSuffix("MD") ? ["HD6309 modes"] : [])
|
||||
}
|
||||
for (name, action, page) in [("JMP","Set PC to the effective address.",69),("JSR","Push the return address on S, then set PC to the effective address.",70)] {
|
||||
instruction(name, false, .memory, action, same, String(page), example: "call")
|
||||
}
|
||||
for (name, action, flags, page) in [
|
||||
("ABX","Add the unsigned byte in B to X.",same,4),
|
||||
("DAA","Adjust A after adding packed BCD bytes, using H and C from the addition.",nz + " C reports decimal carry. V is undefined.",56),
|
||||
("MUL","Multiply unsigned A by B and place the 16-bit product in D.","Z marks a zero product. C receives product bit 7.",100),
|
||||
("NOP","Advance to the following instruction.",same,104),
|
||||
("RTS","Pull the return address from S into PC and advance S by two.",same,121),
|
||||
("RTI","Pull CC and the return state from S. Stacked E determines whether to restore a full frame.","Restores saved CC.",120),
|
||||
("SEX","Copy B’s sign bit across A to extend B into D.",nz + " V and C are preserved.",125),
|
||||
("SEXW","Copy W’s sign bit across D to extend W into Q.",nz + " V and C are preserved.",126),
|
||||
("SYNC","Wait for an interrupt request. Even a masked request can release the wait.",same,135)
|
||||
] {
|
||||
instruction(name, name == "SEXW", .inherent, action, flags, String(page), example: name == "RTS" ? "call" : nil)
|
||||
}
|
||||
for (name, vector) in [("SWI","FFFA"),("SWI2","FFF4"),("SWI3","FFF2")] {
|
||||
instruction(name, false, .inherent, "Save a full interrupt frame on S and fetch the new PC from $\(vector).",
|
||||
"E sets." + (name == "SWI" ? " I and F set after stacking." : " I and F keep their values."), "134", links: ["HD6309 modes","RTI"])
|
||||
}
|
||||
for (name, dividend, divisor, quotient, remainder, page) in [("DIVD","D","byte","B","A",59),("DIVQ","Q","word","W","D",60)] {
|
||||
instruction(name, true, .value, "Divide signed \(dividend) by a signed \(divisor). The quotient goes in \(quotient) and the remainder in \(remainder). A zero divisor traps.",
|
||||
"For an in-range quotient, N and Z describe it, V clears, and C receives its low bit. Signed overflow sets V. Range overflow preserves the dividend and clears N, Z and C.",
|
||||
String(page), detail: name == "DIVQ" ? "VCC Plus’s retained core has differences in DIVQ overflow and carry handling. Treat these flags as processor documentation." : "", links: ["MD"])
|
||||
}
|
||||
instruction("MULD", true, .value, "Multiply signed D by a signed 16-bit operand and store the 32-bit product in Q.",nz + " V and C clear.","101", links: ["Q"])
|
||||
return entries
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
struct AssemblyReferenceLesson {
|
||||
let id: String
|
||||
let name: String
|
||||
let predict: String
|
||||
let observation: String
|
||||
let assumptions: String
|
||||
let body: String
|
||||
var hd = false
|
||||
|
||||
var source: String {
|
||||
"; " + name + "\n; " + assumptions + "\n; " + predict + "\n org $3f00\n" + body + "\n end start\n"
|
||||
}
|
||||
var testedScope: String {
|
||||
hd ? "Assembled for HD6309. Debugger outcomes checked in emulation and native modes. MC6809 assembly rejection checked." :
|
||||
"Assembled for both targets. Debugger outcomes checked on MC6809 and in HD6309 emulation and native modes."
|
||||
}
|
||||
var request: AssemblyReferenceExampleRequest { .init(title: name, source: source, target6309: hd) }
|
||||
|
||||
static let all: [Self] = [
|
||||
.init(id: "cell", name: "First Program — Change a Screen Cell",
|
||||
predict: "After the load, what is in A? At which step does the display change?",
|
||||
observation: "A becomes $8F on the first step. The next step writes $8F to the upper-left cell, the same store as POKE &H0400,&H8F.",
|
||||
assumptions: "Disk BASIC 32-column text screen at $0400. No ROM calls, direct-page operands or subroutine stack use.",
|
||||
body: "start lda #$8f\n sta $0400\nhold bra hold"),
|
||||
.init(id: "count", name: "Count and branch",
|
||||
predict: "How many times will BNE jump back after starting B at three?",
|
||||
observation: "BNE jumps twice. On the third decrement B is zero, Z sets, and the branch falls through to hold.",
|
||||
assumptions: "Observe B, Z and PC. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||||
body: "start ldb #3\nagain decb\n bne again\nhold bra hold"),
|
||||
.init(id: "call", name: "Pass a value to a subroutine",
|
||||
predict: "Where does RTS return, and what value does the caller receive?",
|
||||
observation: "JSR saves the address of the store. INCA turns 7 into 8. RTS restores PC and S. The caller writes 8 at result.",
|
||||
assumptions: "Uses writable RAM for a private stack below stacktop and an output byte at result. No ROM calls, direct-page operands or display assumptions.",
|
||||
body: "start lds #stacktop\n lda #7\n jsr plusone\n sta result\nhold bra hold\nplusone inca\n rts\nresult fcb 0\n zmb 64\nstacktop equ *"),
|
||||
.init(id: "page", name: "Draw on a hidden page",
|
||||
predict: "Will storing $AA change the text screen or the PMODE preview at $1A00?",
|
||||
observation: "In Graphics Preview select At Address, Mapped CPU, $1A00, PMODE 1, Set 0. The first byte supplies four color-index-2 pixels. The CPU writes through its current memory map. The video chip continues reading its selected buffer in physical RAM, so the text display stays as it was.",
|
||||
assumptions: "Disk BASIC text display. Uses $1A00 as writable scratch RAM. No video mode change, ROM calls, direct-page operands or subroutine stack use.",
|
||||
body: "start lda #$aa\n sta $1a00\nhold bra hold"),
|
||||
.init(id: "signed", name: "Compare signed and unsigned",
|
||||
predict: "Is $FF lower or higher than $01? Predict the next PC at BLT and BHI.",
|
||||
observation: "CMPA leaves A at $FF and produces N=1, V=0, C=0, Z=0. BLT lands at signed and BHI lands at both. $FF is signed −1 and unsigned 255.",
|
||||
assumptions: "Observe PC and CC only. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||||
body: "start lda #$ff\n cmpa #1\n blt signed\nmiss bra miss\nsigned bhi both\n bra miss\nboth bra both"),
|
||||
.init(id: "word", name: "Split a word into E and F",
|
||||
predict: "Which half of W will contain $12?",
|
||||
observation: "Step LDW. W becomes $1234, E becomes $12 and F becomes $34. Z, N and V clear.",
|
||||
assumptions: "HD6309, emulation or native mode. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||||
body: "start ldw #$1234\nhold bra hold", hd: true),
|
||||
.init(id: "transfer", name: "Copy three bytes with TFM",
|
||||
predict: "How far will X and Y advance when W starts at three?",
|
||||
observation: "One debugger Step on TFM copies $A5, $5A, $42 to target. X and Y advance by three and W ends at zero. Inspect target in mapped memory.",
|
||||
assumptions: "HD6309, either mode. Separate source and destination in RAM. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||||
body: "start ldx #table\n ldy #target\n ldw #3\n tfm x+,y+\nhold bra hold\ntable fcb $a5,$5a,$42\ntarget zmb 3", hd: true)
|
||||
]
|
||||
}
|
||||
|
||||
extension AssemblyReference {
|
||||
static let bibliography = [
|
||||
"Atkinson (2009)": "Darren Atkinson. Motorola 6809 and Hitachi 6309 Programmer’s Reference. 2009. Part I contains the instruction discussions, Part II the HD6309 mode and register notes.",
|
||||
"Motorola (1981)": "Motorola, Inc. MC6809–MC6809E 8-Bit Microprocessor Programming Manual. M6809PM (AD), original issue March 1981, reprinted May 1983. Chapters 1–2 and Appendix A.",
|
||||
"Burke (1993)": "Chris Burke. The 6309 Book: Inside the 6309 Microprocessor. Second edition. Burke & Burke, 1993.",
|
||||
"Barden (1983)": "William Barden, Jr. TRS-80 Color Computer Assembly Language Programming. Radio Shack, 1983.",
|
||||
"Tepolt (1987)": "Laurence A. Tepolt. Assembly Language Programming for the CoCo 3. TEPCO, 1987.",
|
||||
"Astle": "William Astle and LWTools contributors. LW Tool Chain. Manual accompanying LWTools 4.25, chapter 3, LWASM.",
|
||||
"VCC Plus": "VCC Plus. Native Debugger and Debugger Memory Tools. Project documentation and regression programs for Graphics Preview and whole-instruction TFM Step."
|
||||
]
|
||||
|
||||
static func topics() -> [AssemblyReferenceEntry] {
|
||||
var entries: [AssemblyReferenceEntry] = []
|
||||
let motorola = "Motorola (1981), ch. 1", addressing = "Motorola (1981), ch. 2"
|
||||
let dialect = "Astle, LWTools 4.25, ch. 3"
|
||||
for (name, purpose, hd) in [
|
||||
("A","Eight-bit accumulator. A forms the high byte of D.",false), ("B","Eight-bit accumulator. B forms the low byte of D.",false),
|
||||
("D","Sixteen-bit accumulator built from A (high) and B (low). Writing D immediately changes both halves.",false),
|
||||
("X","Sixteen-bit index register. Use X to address a table or traverse bytes.",false),
|
||||
("Y","Sixteen-bit index register. X and Y can walk independent buffers.",false),
|
||||
("U","Sixteen-bit user stack pointer, also available as an index register. PSHU and PULU use this stack.",false),
|
||||
("S","Sixteen-bit hardware stack pointer. JSR, interrupts and PSHS use memory below S. Initialize a writable stack before making a standalone call.",false),
|
||||
("PC","Program counter. Branches, jumps, calls and returns change the address of the next instruction.",false),
|
||||
("DP","Direct-page register. Its byte supplies the upper address bits of a direct operand. LWASM SETDP describes your assumption during assembly.",false),
|
||||
("E","Eight-bit accumulator and high byte of the HD6309 W register. CC.E is a separate flag.",true),
|
||||
("F","Eight-bit accumulator and low byte of W. CC.F is the fast-interrupt mask.",true),
|
||||
("W","Sixteen-bit accumulator combining E (high) and F (low). TFM uses W as a byte count.",true),
|
||||
("Q","Thirty-two-bit accumulator. From most to least significant its bytes are A, B, E, F. D is the high word and W the low word.",true),
|
||||
("V","Additional 16-bit HD6309 register used in register operations. CC.V is a separate overflow flag.",true),
|
||||
("MD","Mode register. LDMD controls execution mode and FIRQ stacking. BITMD tests the latched illegal-instruction and division-by-zero status.",true)
|
||||
] {
|
||||
entries.append(.init(name, .registers, only6309: hd, operation: purpose, links: hd ? ["HD6309 modes"] : ["Condition codes"],
|
||||
citations: [hd ? "Burke (1993), register file" : motorola]))
|
||||
}
|
||||
entries.append(.init("Condition codes", .registers, aliases: ["CC"], operation: "CC holds eight one-bit values. E marks an entire interrupt frame. F masks FIRQ, H is half carry, I masks IRQ. N is negative, Z zero, V signed overflow and C carry or borrow.",
|
||||
detail: "Branch choices depend on how the previous instruction defined these bits. For example, Z=1 after CMP means equal; C=1 after CMP means unsigned lower. An undefined bit cannot support a portable decision.", links: ["BGE","BCC","CMPA"], citations: [motorola], terms: ["flags","carry","zero","loop"], example: "signed"))
|
||||
for (name, meaning, links) in [
|
||||
("CC.C","Carry or borrow. An unsigned addition sets C when the sum exceeds the register. A comparison sets C when the unsigned left operand is lower.",["BCS","ADCA"]),
|
||||
("CC.V","Signed overflow. For example, adding one to $7F produces $80 in a byte and sets V.",["BVS","BGE"]),
|
||||
("CC.Z","Zero. Many arithmetic and load instructions set Z when the result is zero. After a compare, BEQ uses Z to test equality.",["BEQ","BNE"]),
|
||||
("CC.N","Negative. For operations that set N from the result, it copies the most significant bit. A signed comparison also needs V.",["BMI","BLT"]),
|
||||
("CC.I","Interrupt request mask. Set I to mask IRQ. Clear I to permit IRQ when the external request is active.",["ANDCC","ORCC"]),
|
||||
("CC.H","Half carry. An eight-bit addition places the carry from bit 3 here. DAA uses H to adjust a packed decimal result.",["DAA","ADDA"]),
|
||||
("CC.F","Fast interrupt request mask. Set F to mask FIRQ. A saved CC value can restore the previous mask.",["ANDCC","RTI"]),
|
||||
("CC.E","Entire state stacked. RTI checks E in the saved condition byte to choose between the short and full interrupt frames.",["RTI","SWI"])
|
||||
] {
|
||||
entries.append(.init(name, .registers, operation: meaning, links: links, citations: [motorola]))
|
||||
}
|
||||
entries.append(.init("HD6309 modes", .registers, only6309: true, operation: "The HD6309 starts in emulation mode. Many instructions take fewer cycles in native mode. LDMD #1 selects native mode with the ordinary short FIRQ frame. Mode selection is independent of the LWASM target.",
|
||||
detail: "MD bit 0 selects native mode. Bit 1 selects full FIRQ stacking. A native full-state interrupt frame includes E and F; the mode on return must agree with the frame. Cycle counts also depend on indexed postbytes, branch outcomes and transfer lengths. In VCC Plus, Step completes a TFM instruction across its byte transfers.",
|
||||
links: ["MD","LDMD","BITMD","TFM","RTI"], citations: ["Atkinson (2009), pp. 2, 120, 136, 144","Burke (1993), mode register","VCC Plus, Native Debugger, HD6309 Step"]))
|
||||
for (name, operation, syntax, terms) in [
|
||||
("Immediate","Use the following operand bytes as the value.", "LDA #$20", ["literal","#"]),
|
||||
("Direct","Join DP with the 8-bit operand to make the memory address. With DP=$12, LDA <$34 reads $1234.","LDA <$34", ["direct page","<"]),
|
||||
("Extended","Use the full 16-bit address in the instruction. LDA >$0400 reads a byte there.","LDA >$0400", [">","absolute"]),
|
||||
("Indexed","Calculate an address from a register and an offset. LDA ,X+ reads at the original X then increments X by one. Use ,X++ for a two-byte advance. Indexed operands can also use A, B or D as signed offsets.","LDA ,X+ · LDD 2,S · LDA B,Y", [",X+",",X++","auto increment","offset"]),
|
||||
("Indirect","Use square brackets to fetch a two-byte pointer at the intermediate address, then access the final address. Use a two-byte increment when walking a pointer table.","LDA [,X++] · JMP [$4000]", ["pointer","brackets"]),
|
||||
("Relative","Add a signed displacement to PC after the operand. Branch targets are labels. Indexed PC-relative data references use PCR in LWASM.","BNE again · LDA table,PCR", ["relative","PCR","loop"]),
|
||||
("Inherent","The opcode specifies the operation and its operands. INCA, for example, acts on A.","INCA", ["no operand"]),
|
||||
("HD6309 indexed","E, F and W can supply offsets for X, Y, U or S. W also supports ,W, offset,W, ,W++ and ,--W, including their indirect forms.", "LDA E,X · LDA ,W++", ["W index",",W++"])
|
||||
] {
|
||||
entries.append(.init(name, .addressing, only6309: name.hasPrefix("HD"), syntax: syntax, operation: operation, detail: name == "Extended" ? "On the CoCo 3, the address in STA >$1A00 selects a byte through the CPU memory map. The MMU chooses the physical 8 KiB block and preserves the low 13 address bits. Use Mapped CPU in the debugger to inspect that store." : "", links: ["LDA"],
|
||||
citations: (name == "Extended" ? ["Tepolt (1987), p. 20, fig. 3-4"] : []) + [name.hasPrefix("HD") ? "Atkinson (2009), p. 148" : addressing, dialect], terms: terms))
|
||||
}
|
||||
for (names, syntax, text) in [
|
||||
("ORG","ORG address","Set the address of the following output. In DECB an origin determines where a data block loads."),
|
||||
("FCB .BYTE .DB","FCB byte[,byte…]","Emit each expression as one byte. The listing shows data at the current location."),
|
||||
("FDB .WORD .DW","FDB word[,word…]","Emit 16-bit words, high byte first."), ("FQB .4BYTE .QUAD","FQB value","Emit 32-bit quantities, high byte first."),
|
||||
("FCC .ASCII .STR","FCC /text/","Emit character bytes between matching delimiters."),
|
||||
("FCN FCZ .ASCIZ .STRZ","FCN /text/","Emit a string followed by a zero byte."),
|
||||
("FCS .ASCIS .STRS","FCS /text/","Emit a string with the high bit set in its last character."),
|
||||
("RMB .BLKB .DS .RS","RMB count","Advance the location counter by a number of bytes. Use ZMB when the load image must contain zeros."),
|
||||
("RMD RMW","RMD count","Reserve 16-bit words."), ("RMQ","RMQ count","Reserve 32-bit values."),
|
||||
("ZMB BSZ FZB","ZMB count","Emit the requested number of zero bytes."), ("ZMD","ZMD count","Emit zero-filled words."),
|
||||
("ZMQ","ZMQ count","Emit zero-filled four-byte quantities."), ("EQU =","name EQU expression","Assign a fixed value to a symbol."),
|
||||
("SET","name SET expression","Assign a symbol a value that later SET statements may change."),
|
||||
("SETDP","SETDP page","Tell the assembler the assumed direct page. Guest software must establish the matching DP value."),
|
||||
("END .END","END entry","Finish the assembly and specify the DECB execution address. END itself emits no machine instruction."),
|
||||
("INCLUDE INCL LIB USE","INCLUDE filename","Read another source file at this location."),
|
||||
("INCLUDEBIN","INCLUDEBIN filename","Copy bytes from a binary file into the assembly output."),
|
||||
("ALIGN","ALIGN boundary","Advance to a boundary divisible by the supplied value."), ("FILL","FILL byte,count","Emit the given byte repeatedly."),
|
||||
("SECTION SECT .AREA","SECTION name","Begin a section in an object module. The linker determines final placement."),
|
||||
("ENDSECT ENDSECTION","ENDSECT","Finish the current object section."),
|
||||
("EXTERN EXTERNAL IMPORT","name EXTERN","Declare a name defined in another object module."),
|
||||
("EXPORT .GLOBL","EXPORT name","Expose a symbol to other object modules."),
|
||||
("MACRO MACR","name MACRO","Begin defining a sequence of source lines for later expansion."), ("ENDM","ENDM","Finish a macro definition."),
|
||||
("REORG","REORG","Restore the location associated with the previous ORG."),
|
||||
("PHASE","PHASE expression","Give following code a different logical address for labels and expressions while retaining its output placement."),
|
||||
("DEPHASE","DEPHASE","Resume the original address calculation after PHASE."),
|
||||
("FDBS","FDBS word[,word…]","Emit 16-bit values low byte first, opposite to the processor’s normal word order."),
|
||||
("INCLUDESTR","INCLUDESTR string","Treat the contents of the given string as additional assembler source."),
|
||||
("EXTDEP","name EXTDEP","Mark an external symbol as a link dependency without emitting storage for it."),
|
||||
("ERROR","ERROR message","Report an assembly error with the supplied text."),
|
||||
("WARNING MSG","WARNING message","Report a warning with the supplied text."),
|
||||
("IFEQ","IFEQ expression","Include the following block when the expression equals zero."),
|
||||
("IFNE IF","IFNE expression","Include the block when the expression is nonzero."),
|
||||
("IFLT","IFLT expression","Include the block when the expression is negative."),
|
||||
("IFLE","IFLE expression","Include the block when the expression is zero or negative."),
|
||||
("IFGT","IFGT expression","Include the block when the expression is positive."),
|
||||
("IFGE","IFGE expression","Include the block when the expression is zero or positive."),
|
||||
("IFDEF","IFDEF symbol","Test whether a symbol has already been defined."),
|
||||
("IFNDEF","IFNDEF symbol","Test whether a symbol is still undefined."),
|
||||
("IFPRAGMA IFOPT","IFPRAGMA option","Include a block according to the current pragma setting."),
|
||||
("IFSTR","IFSTR comparison,arguments","Include a block according to the specified string comparison."),
|
||||
("ELSE","ELSE","Select the alternate branch of a conditional assembly block."),
|
||||
("ENDC ENDIF","ENDC","Close the current conditional assembly block."),
|
||||
("IFP1","IFP1","Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-one assembly semantics."),
|
||||
("IFP2","IFP2","Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-two assembly semantics."),
|
||||
("STRUCT","name STRUCT","Begin a structure layout. Field labels describe offsets in its instances."),
|
||||
("ENDS ENDSTRUCT","ENDS","Close a structure definition."),
|
||||
("SETSTR","SETSTR name=string","Set an assembler string variable."),
|
||||
("DTS","DTS","Emit a textual build timestamp. Its value changes with the host clock."),
|
||||
("DTB","DTB","Emit six host-local date and time bytes."),
|
||||
("*PRAGMAPUSH","*PRAGMAPUSH","Save pragma settings on the assembler’s pragma stack."),
|
||||
("*PRAGMAPOP","*PRAGMAPOP","Restore saved pragma settings."),
|
||||
("PRAGMA *PRAGMA **PRAGMA OPT","PRAGMA option","Change a LWASM dialect option. A target-changing pragma affects subsequent assembly.")
|
||||
] {
|
||||
let words = names.components(separatedBy: " ")
|
||||
entries.append(.init(words[0], .directives, aliases: Array(words.dropFirst()), form: .directive, syntax: syntax, operation: text,
|
||||
detail: "LWASM directive. Its effects take place during assembly.", links: ["END","ORG"].filter { $0 != words[0] },
|
||||
citations: [dialect], example: ["ORG","FCB","END"].contains(words[0]) ? "call" : nil))
|
||||
}
|
||||
entries.append(.init("Assembler conveniences", .dialect, aliases: ["ASRQ","CLRQ","COMQ","LSLE","LSLF","LSLQ","LSRQ","NEGE","NEGF","NEGW","NEGQ","TSTQ"],
|
||||
operation: "LWASM can expand convenience operations into several instructions when the corresponding pragma is active. The listing gives the actual expansion. A 6809 emulation of CLRD, for example, executes CLRA and CLRB separately.",
|
||||
detail: "6809 expansions include ASLD, ASRD, CLRD, COMD, LSLD, LSRD, NEGD and TSTD. These names also identify real HD6309 operations. Additional 6309 convenience spellings include ASRQ, CLRQ, COMQ, LSLE, LSLF, LSLQ, LSRQ, NEGE, NEGF, NEGW, NEGQ and TSTQ. MC6800 compatibility is a separate optional dialect.",
|
||||
links: ["CLRD","PRAGMA"], citations: [dialect]))
|
||||
entries.append(.init("MC6800 compatibility", .dialect,
|
||||
aliases: "ABA CBA CLC CLF CLI CLIF CLV CPX DES DEX DEY INS INX INY SBA SEC SEF SEI SEIF SEV TAB TAP TBA TPA TSX TXS WAI".components(separatedBy: " "),
|
||||
operation: "These optional LWASM spellings expand to 6809 encodings with the 6800compat pragma. Expansion can require several instructions. Inspect the listing when stepping.", links: ["PRAGMA"], citations: [dialect]))
|
||||
entries.append(.init("Compatibility directives", .dialect, aliases: ["NAM","PAG","PAGE","SPC","TTL",".BANK",".MODULE"],
|
||||
operation: "LWASM accepts these listing and tool-compatibility directives without generating code.", links: ["FCB"], citations: [dialect]))
|
||||
entries.append(.init("ASM-09 dialect", .dialect, aliases: ["IFC","IFNC","EXITM","EXIT"],
|
||||
operation: "The ASM-09 compatibility dialect adds string equality and inequality conditionals and an early macro exit.", links: ["MACRO"], citations: [dialect]))
|
||||
entries.append(.init("OS-9 output directives", .dialect, aliases: ["OS9","MOD","EMOD"],
|
||||
operation: "OS9 encodes SWI2 followed by a service byte for OS-9 or object output. MOD and EMOD frame an OS-9 module. Assembly Development runs standalone Disk BASIC block images.", links: ["SWI2","END"], citations: [dialect]))
|
||||
entries.append(.init("Undocumented and emulator opcodes", .dialect, aliases: ["HCF","RHF","RESET","HALT","BREAK","LOG"], operation: "LWASM lists HCF, RHF and RESET for certain 6809 encodings. Behavior outside the documented instruction set can differ by chip. BREAK and LOG are emulator extensions. VCC Plus’s Mac decoder also excludes the optional HALT/BREAK encodings.",
|
||||
links: ["NOP"], citations: ["Atkinson (2009), p. 153",dialect,"VCC Plus, Native Debugger, disassembly"], terms: ["HCF","RHF","RESET","HALT","BREAK","LOG"]))
|
||||
for lesson in AssemblyReferenceLesson.all {
|
||||
entries.append(.init(lesson.name, .examples, only6309: lesson.hd, operation: lesson.predict,
|
||||
detail: lesson.observation + "\n\n" + lesson.assumptions,
|
||||
links: [lesson.id == "page" ? "Extended" : lesson.hd ? "W" : "LDA"], citations: (lesson.id == "page" ? ["Tepolt (1987), pp. 20 and 23, figs. 3-4 and 4-1"] : []) + [lesson.hd ? "Atkinson (2009), pp. 91, 136" : "Barden (1983), addressing and subroutines", lesson.id == "page" ? "VCC Plus, Debugger Memory Tools, hidden drawing page" : dialect],
|
||||
example: lesson.id))
|
||||
}
|
||||
return entries
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
@MainActor final class AssemblyReferenceSelection: ObservableObject {
|
||||
static let shared = AssemblyReferenceSelection()
|
||||
struct Lookup {
|
||||
let token = UUID()
|
||||
let term: String?
|
||||
let target6309: Bool
|
||||
}
|
||||
@Published private(set) var lookup: Lookup?
|
||||
func show(_ term: String?, target6309: Bool) { lookup = .init(term: term, target6309: target6309) }
|
||||
}
|
||||
|
||||
struct AssemblyReferenceView: View {
|
||||
let openExample: (AssemblyReferenceExampleRequest) -> Void
|
||||
@ObservedObject private var selection = AssemblyReferenceSelection.shared
|
||||
@FocusState private var searchFocused: Bool
|
||||
@State private var query = ""
|
||||
@State private var target6309: Bool?
|
||||
@State private var category: AssemblyReferenceCategory?
|
||||
@State private var selected: String? = AssemblyReference.shared.entry("LDA")?.id
|
||||
@State private var scrollRequest = UUID()
|
||||
@State private var bibliography = false
|
||||
@State private var citationKey = ""
|
||||
private let catalog = AssemblyReference.shared
|
||||
|
||||
var body: some View {
|
||||
let matches = catalog.search(query, target6309: target6309, category: category)
|
||||
let current = matches.first { $0.id == selected } ?? matches.first
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
TextField("Search instructions, registers, or tasks", text: $query)
|
||||
.textFieldStyle(.roundedBorder).focused($searchFocused)
|
||||
.accessibilityLabel("Search assembly reference").accessibilityIdentifier("assembly.reference.search")
|
||||
Picker("Processor", selection: $target6309) {
|
||||
Text("Both CPUs").tag(nil as Bool?)
|
||||
Text("MC6809").tag(Optional(false))
|
||||
Text("HD6309").tag(Optional(true))
|
||||
}.labelsHidden().accessibilityLabel("Processor").fixedSize().accessibilityIdentifier("assembly.reference.processor")
|
||||
Button { citationKey = ""; bibliography = true } label: { Image(systemName: "books.vertical") }
|
||||
.help("Bibliography").accessibilityLabel("Bibliography")
|
||||
}.padding(10)
|
||||
Divider()
|
||||
HSplitView {
|
||||
VStack(spacing: 0) {
|
||||
Picker("Category", selection: $category) {
|
||||
Text("All Topics").tag(nil as AssemblyReferenceCategory?)
|
||||
ForEach(AssemblyReferenceCategory.allCases, id: \.self) { Text($0.rawValue).tag(Optional($0)) }
|
||||
}.labelsHidden().accessibilityLabel("Category").accessibilityIdentifier("assembly.reference.category").padding(8)
|
||||
ScrollViewReader { proxy in
|
||||
List(matches, selection: $selected) { item in
|
||||
HStack {
|
||||
Text(item.name)
|
||||
if item.only6309 { Text("6309").font(.caption2).foregroundStyle(.secondary) }
|
||||
}.tag(item.id).id(item.id)
|
||||
}
|
||||
.accessibilityLabel("Reference topics").accessibilityIdentifier("assembly.reference.topics")
|
||||
.onChange(of: scrollRequest, initial: true) { _, _ in
|
||||
if let id = current?.id { proxy.scrollTo(id, anchor: .center) }
|
||||
}
|
||||
}
|
||||
}.frame(minWidth: 170, idealWidth: 225, maxWidth: 330)
|
||||
if let item = current {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Text(item.category.rawValue + " · " + (item.only6309 ? "HD6309" : "MC6809 and HD6309")).font(.caption).foregroundStyle(.secondary)
|
||||
Text(item.name).font(.title.bold())
|
||||
if !item.aliases.isEmpty { Text("Also spelled " + item.aliases.joined(separator: ", ")).foregroundStyle(.secondary) }
|
||||
if !item.syntax.isEmpty { Text(item.syntax).font(.system(.body, design: .monospaced)).textSelection(.enabled) }
|
||||
Text(item.operation).textSelection(.enabled)
|
||||
if !item.flags.isEmpty {
|
||||
Text("Condition codes").font(.headline)
|
||||
Text(item.flags).textSelection(.enabled)
|
||||
}
|
||||
if !item.detail.isEmpty {
|
||||
if item.category == .instructions {
|
||||
DisclosureGroup("Instruction details") { Text(item.detail).textSelection(.enabled).padding(.top, 4) }
|
||||
} else { Text(item.detail).textSelection(.enabled) }
|
||||
}
|
||||
if let id = item.example, let lesson = AssemblyReferenceLesson.all.first(where: { $0.id == id }) {
|
||||
if item.category == .examples {
|
||||
Text(lesson.testedScope).font(.caption).foregroundStyle(.secondary)
|
||||
Text(lesson.source).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
}
|
||||
Button("Open Example", systemImage: "square.and.pencil") { openExample(lesson.request) }
|
||||
.help("Open an editable copy of " + lesson.name).accessibilityIdentifier("assembly.reference.openExample")
|
||||
}
|
||||
if !item.links.isEmpty {
|
||||
Text("Related topics").font(.headline)
|
||||
ForEach(item.links.filter { catalog.entry($0).map { target6309 != false || !$0.only6309 } ?? false }, id: \.self) { link in
|
||||
Button(link) { navigate(to: link) }.buttonStyle(.link)
|
||||
}
|
||||
}
|
||||
DisclosureGroup("Sources") {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
ForEach(item.citations, id: \.self) { source in
|
||||
Button(source) {
|
||||
citationKey = AssemblyReference.bibliography.keys.first { source.hasPrefix($0) } ?? ""
|
||||
bibliography = true
|
||||
}.buttonStyle(.link)
|
||||
}
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).padding(.top, 4)
|
||||
}
|
||||
}.padding(20).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.id(item.id).accessibilityIdentifier("assembly.reference.detail")
|
||||
} else {
|
||||
ContentUnavailableView.search(text: query).frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
}.frame(minWidth: 610, minHeight: 380)
|
||||
.background {
|
||||
Button("Find in Assembly Reference") { searchFocused = true }
|
||||
.keyboardShortcut("f", modifiers: .command).hidden().accessibilityHidden(true)
|
||||
}
|
||||
.onChange(of: selection.lookup?.token, initial: true) { _, _ in
|
||||
guard let request = selection.lookup else { return }
|
||||
target6309 = request.target6309
|
||||
if let term = request.term { navigate(to: term) }
|
||||
else { query = ""; category = nil }
|
||||
}
|
||||
.onChange(of: current?.id) { _, id in selected = id }
|
||||
.sheet(isPresented: $bibliography) {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("Bibliography").font(.title.bold())
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
ForEach(AssemblyReference.bibliography.keys.sorted(), id: \.self) { key in
|
||||
Text(AssemblyReference.bibliography[key] ?? "").textSelection(.enabled).id(key)
|
||||
}
|
||||
Divider()
|
||||
Text("Color Computer Archive preserves historical publications consulted for this reference. The explanations and teaching programs here were written for VCC Plus.").foregroundStyle(.secondary)
|
||||
}
|
||||
}.onAppear { if !citationKey.isEmpty { proxy.scrollTo(citationKey, anchor: .top) } }
|
||||
}
|
||||
HStack { Spacer(); Button("Done") { bibliography = false }.keyboardShortcut(.defaultAction) }
|
||||
}.padding(22).frame(width: 520, height: 405)
|
||||
}
|
||||
}
|
||||
|
||||
private func navigate(to term: String) {
|
||||
category = nil
|
||||
if let entry = catalog.entry(term) { query = ""; selected = entry.id }
|
||||
else { query = term; selected = nil }
|
||||
scrollRequest = UUID()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Combine
|
||||
import CryptoKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
enum BASICExportKind: String, Identifiable, Sendable {
|
||||
case disk, cassette
|
||||
var id: String { rawValue }
|
||||
var fileExtension: String { self == .disk ? "dsk" : "cas" }
|
||||
var title: String { self == .disk ? "Export Disk" : "Export Cassette" }
|
||||
func instructions(name: String, dosBoot: Bool) -> String {
|
||||
self == .disk ? DevelopmentDiskProgram.basic(name).instructions(dos: dosBoot)
|
||||
: "Open the cassette and press Play. Type CLOAD\"\(name)\", then type RUN on the next line."
|
||||
}
|
||||
var symbol: String { self == .disk ? "externaldrive" : "recordingtape" }
|
||||
}
|
||||
|
||||
enum BASICExportName {
|
||||
static func normalized(_ text: String) -> String? {
|
||||
let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard (1...8).contains(value.utf8.count), value.utf8.allSatisfy({
|
||||
(65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0)
|
||||
}) else { return nil }
|
||||
return value.uppercased()
|
||||
}
|
||||
static func suggestion(for url: URL?) -> String {
|
||||
guard let url else { return "HELLO" }
|
||||
let bytes = url.deletingPathExtension().lastPathComponent.utf8.filter {
|
||||
(65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0)
|
||||
}.prefix(8)
|
||||
return bytes.isEmpty ? "HELLO" : String(decoding: bytes, as: UTF8.self).uppercased()
|
||||
}
|
||||
}
|
||||
|
||||
struct BASICEditorAction: Identifiable {
|
||||
enum Operation { case replace(source: String, undoName: String), select(NSRange) }
|
||||
let id = UUID()
|
||||
let expectedSource: String
|
||||
let operation: Operation
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class BASICDevelopmentModel: ObservableObject {
|
||||
weak var assistantEditor: BASICTextView?
|
||||
let machine: MachineModel
|
||||
let directory: URL
|
||||
let workspaceID = UUID()
|
||||
private var untitledTitle = "Untitled BASIC"
|
||||
private(set) var sourceRevision = 0
|
||||
@Published var source = BASICLanguage.sample {
|
||||
didSet {
|
||||
if !source.utf8.elementsEqual(oldValue.utf8) {
|
||||
sourceRevision += 1
|
||||
diagnostics = []; clearInspection()
|
||||
if armedSource != nil {
|
||||
armedSource = nil; stoppedLine = nil; stoppedToken = nil; runtimeErrorLine = nil; runtimeErrorCode = ""
|
||||
debugStatus = "Source changed. Breakpoints will apply on the next Run; the CoCo program is unchanged."
|
||||
detachOwnedDebug()
|
||||
}
|
||||
}
|
||||
if !restoring { scheduleRecovery() }
|
||||
}
|
||||
}
|
||||
@Published private(set) var diagnostics: [BASICLanguage.Diagnostic] = []
|
||||
@Published private(set) var editorAction: BASICEditorAction?
|
||||
@Published private(set) var fileURL: URL?
|
||||
@Published private(set) var savedSource = BASICLanguage.sample
|
||||
@Published private(set) var busy = false
|
||||
@Published var message: String?
|
||||
@Published private(set) var status = "Ready to edit. Nothing has been loaded into the CoCo."
|
||||
@Published var hint: String?
|
||||
@Published var completionRequest = UUID()
|
||||
@Published var documentID = UUID()
|
||||
@Published var editorOffset = 0
|
||||
private var fileFingerprint: String?
|
||||
private var knownGuestSource: String?
|
||||
@Published private(set) var breakpoints: Set<Int> = []
|
||||
@Published private(set) var stoppedLine: Int?
|
||||
@Published private(set) var stoppedToken: NSRange?
|
||||
@Published private(set) var stepping = false
|
||||
@Published private(set) var callerAvailable = false
|
||||
@Published private(set) var runtimeErrorLine: Int?
|
||||
@Published private(set) var runtimeErrorCode = ""
|
||||
@Published private(set) var debugStatus = "Click beside a numbered line to set a breakpoint."
|
||||
@Published private(set) var variables: [BASICVariable] = []
|
||||
@Published private(set) var inspectionAvailable = false
|
||||
@Published private(set) var inspectionStatus = "Pause at a BASIC breakpoint to inspect variables."
|
||||
@Published private(set) var watches: [String] = []
|
||||
@Published var watchEntry = ""
|
||||
@Published var watchError: String?
|
||||
private var inspectionRequest = UUID()
|
||||
private var armedSource: String?
|
||||
private var debugObservation: AnyCancellable?
|
||||
var canContinue: Bool { machine.basicWorkspaceOwner == workspaceID && canTransfer && machine.state == .paused && machine.basicDebug.attached && source == armedSource }
|
||||
var canStep: Bool { canContinue && stoppedLine != nil }
|
||||
var canStepOut: Bool { canStep && callerAvailable }
|
||||
var editorLocked: Bool { busy || stepping }
|
||||
private var recoveryTask: Task<Void, Never>?
|
||||
private var restoring = false
|
||||
var dirty: Bool { !source.utf8.elementsEqual(savedSource.utf8) }
|
||||
var title: String { fileURL?.lastPathComponent ?? untitledTitle }
|
||||
var canTransfer: Bool { !busy && !machine.busy && (machine.state == .running || machine.state == .paused) }
|
||||
struct Draft: Codable {
|
||||
var source: String
|
||||
var savedSource: String
|
||||
var filePath: String?
|
||||
var fingerprint: String?
|
||||
var watches: [String]?
|
||||
}
|
||||
init(machine: MachineModel, directory: URL, initialSource: String? = nil, title: String? = nil) {
|
||||
self.machine = machine; self.directory = directory
|
||||
if let initialSource { source = initialSource; savedSource = initialSource }
|
||||
if let title { untitledTitle = title }
|
||||
restoreRecovery()
|
||||
debugObservation = machine.$basicDebug.combineLatest(machine.$basicWorkspaceOwner).sink { [weak self] value, owner in
|
||||
guard let self else { return }
|
||||
if owner != self.workspaceID {
|
||||
if self.armedSource != nil {
|
||||
self.armedSource = nil; self.stoppedLine = nil; self.stoppedToken = nil
|
||||
self.stepping = false; self.callerAvailable = false
|
||||
self.runtimeErrorLine = nil; self.runtimeErrorCode = ""; self.clearInspection()
|
||||
self.debugStatus = "Another BASIC workspace controls the CoCo. These breakpoints apply on your next Run."
|
||||
}
|
||||
return
|
||||
}
|
||||
// @Published sends before MachineModel stores the new value.
|
||||
// Defer the read until that snapshot has been fully accepted.
|
||||
Task { [weak self] in self?.refreshInspection() }
|
||||
self.stoppedLine = self.armedSource == self.source && value.attached ? value.line : nil
|
||||
self.stoppedToken = self.stoppedLine != nil ? value.sourceRange : nil
|
||||
self.stepping = self.armedSource == self.source && value.attached && value.stepping
|
||||
self.refreshRuntimeState(value)
|
||||
if self.armedSource != nil && !value.attached {
|
||||
self.armedSource = nil
|
||||
self.debugStatus = value.status.isEmpty ? "BASIC debugging ended after the machine changed." : value.status
|
||||
} else if self.armedSource != nil {
|
||||
self.debugStatus = value.line.map { "Paused at BASIC line \($0). Continue keeps variables and open files." }
|
||||
?? (value.status.isEmpty ? "BASIC breakpoints are active." : value.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
private func detachOwnedDebug() {
|
||||
guard machine.basicWorkspaceOwner == workspaceID else { return }
|
||||
machine.basicWorkspaceOwner = nil
|
||||
machine.detachBASICDebug()
|
||||
}
|
||||
private func refreshRuntimeState(_ value: MachineModel.BASICDebugState) {
|
||||
let attached = machine.basicWorkspaceOwner == workspaceID && armedSource == source && value.attached
|
||||
callerAvailable = attached && value.canStepOut
|
||||
runtimeErrorLine = attached ? value.errorLine : nil
|
||||
runtimeErrorCode = attached ? value.errorCode : ""
|
||||
}
|
||||
func clearInspection() {
|
||||
inspectionRequest = UUID(); variables = []; inspectionAvailable = false
|
||||
inspectionStatus = "Pause at a BASIC breakpoint or completed statement to inspect variables."
|
||||
}
|
||||
func refreshInspection() {
|
||||
let stop = machine.basicDebug
|
||||
guard machine.basicWorkspaceOwner == workspaceID, armedSource == source, stop.attached, stop.paused, !stop.stepping,
|
||||
stop.line != nil || stop.atPrompt else { clearInspection(); return }
|
||||
let text = source, request = UUID(); inspectionRequest = request
|
||||
Task {
|
||||
let (values, error) = await machine.inspectBASIC(source: text, stop: stop)
|
||||
guard inspectionRequest == request, source == text, armedSource == text,
|
||||
machine.basicWorkspaceOwner == workspaceID, machine.basicDebug == stop else { return }
|
||||
variables = values ?? []; inspectionAvailable = values != nil
|
||||
inspectionStatus = error ?? (values?.isEmpty == true ? "No variables have been assigned yet." : "Read-only · BASIC uses the first two characters of a name.")
|
||||
}
|
||||
}
|
||||
func addWatch() {
|
||||
guard let watch = BASICWatch(watchEntry) else {
|
||||
watchError = "Use a variable name or numeric subscripts, such as A, NAME$ or A(2,3). Expressions are not evaluated."; return
|
||||
}
|
||||
guard watches.count < 128 || watches.contains(watch.canonical) else { watchError = "Up to 128 watches are supported."; return }
|
||||
if !watches.contains(watch.canonical) { watches.append(watch.canonical) }
|
||||
watchEntry = ""; watchError = nil; persistDraft()
|
||||
}
|
||||
func removeWatch(_ name: String) { watches.removeAll { $0 == name }; persistDraft() }
|
||||
func watchValue(_ name: String) -> String {
|
||||
inspectionAvailable ? (BASICWatch(name)?.value(in: variables) ?? "Invalid watch") : "Waiting for a BASIC stop"
|
||||
}
|
||||
static func fingerprint(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
|
||||
static func readText(_ url: URL) throws -> (String, String) {
|
||||
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
guard values.isRegularFile == true, let count = values.fileSize, count <= BASICLanguage.maximumSourceBytes else {
|
||||
throw CocoaError(.fileReadTooLarge)
|
||||
}
|
||||
let data = try Data(contentsOf: url)
|
||||
guard data.count <= BASICLanguage.maximumSourceBytes, !data.contains(0),
|
||||
let text = String(data: data, encoding: .utf8) else { throw CocoaError(.fileReadInapplicableStringEncoding) }
|
||||
return (text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n"), fingerprint(data))
|
||||
}
|
||||
private func restoreRecovery() {
|
||||
let url = directory.appendingPathComponent("Draft.json")
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return }
|
||||
do {
|
||||
let values = try url.resourceValues(forKeys: [.fileSizeKey])
|
||||
guard let count = values.fileSize, count <= BASICLanguage.maximumSourceBytes * 12 else { throw CocoaError(.fileReadTooLarge) }
|
||||
let draft = try JSONDecoder().decode(Draft.self, from: Data(contentsOf: url))
|
||||
guard draft.source.utf8.count <= BASICLanguage.maximumSourceBytes,
|
||||
draft.savedSource.utf8.count <= BASICLanguage.maximumSourceBytes else { throw CocoaError(.fileReadTooLarge) }
|
||||
restoring = true
|
||||
source = draft.source; savedSource = draft.savedSource; fileURL = draft.filePath.map { URL(fileURLWithPath: $0) }
|
||||
watches = Array((draft.watches ?? []).compactMap { BASICWatch($0)?.canonical }.prefix(128))
|
||||
fileFingerprint = draft.fingerprint; restoring = false
|
||||
status = "Restored your BASIC workspace. The CoCo has not been changed."
|
||||
} catch { message = "The saved BASIC workspace could not be restored: \(error.localizedDescription)" }
|
||||
}
|
||||
private func scheduleRecovery() {
|
||||
recoveryTask?.cancel()
|
||||
recoveryTask = Task { [weak self] in
|
||||
do { try await Task.sleep(for: .milliseconds(350)) } catch { return }
|
||||
self?.persistDraft()
|
||||
}
|
||||
}
|
||||
func persistDraft() {
|
||||
recoveryTask?.cancel()
|
||||
guard source.utf8.count <= BASICLanguage.maximumSourceBytes else { message = "BASIC source is limited to 1 MB."; return }
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let value = Draft(source: source, savedSource: savedSource, filePath: fileURL?.path, fingerprint: fileFingerprint, watches: watches)
|
||||
try JSONEncoder().encode(value).write(to: directory.appendingPathComponent("Draft.json"), options: .atomic)
|
||||
} catch { message = "Could not save the recovery draft: \(error.localizedDescription)" }
|
||||
}
|
||||
func confirmDiscard(applyDiscard: Bool = true) -> Bool {
|
||||
guard !busy else { message = "Wait for the BASIC operation to finish."; return false }
|
||||
guard dirty else { persistDraft(); return true }
|
||||
let alert = NSAlert(); alert.messageText = "Save changes to \(title)?"
|
||||
alert.informativeText = "Save your readable BASIC source on the Mac before replacing it or quitting."
|
||||
alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Discard Changes")
|
||||
switch alert.runModal() {
|
||||
case .alertFirstButtonReturn: return save()
|
||||
case .alertThirdButtonReturn:
|
||||
if applyDiscard { source = savedSource; persistDraft() }; return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
func newProgram() {
|
||||
guard !busy, confirmDiscard() else { return }
|
||||
fileURL = nil; fileFingerprint = nil; savedSource = BASICLanguage.sample; source = BASICLanguage.sample
|
||||
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
|
||||
documentID = UUID(); message = nil; hint = nil; status = "New example. Nothing has been loaded into the CoCo."; persistDraft()
|
||||
}
|
||||
func open() {
|
||||
guard !busy, confirmDiscard(applyDiscard: false) else { return }
|
||||
let panel = NSOpenPanel(); panel.title = "Open BASIC Source"; panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Choose readable, line-numbered BASIC text. Tokenized disk or cassette files are not source text."
|
||||
panel.allowedContentTypes = [.plainText, UTType(filenameExtension: "bas") ?? .plainText]
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
||||
openSource(at: url)
|
||||
}
|
||||
@discardableResult func openSource(at url: URL) -> Bool {
|
||||
guard !busy else { return false }
|
||||
do {
|
||||
let (text, hash) = try Self.readText(url)
|
||||
fileURL = url; fileFingerprint = hash; savedSource = text; source = text
|
||||
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
|
||||
documentID = UUID(); message = nil; hint = nil; status = "Opened \(url.lastPathComponent). The CoCo has not been changed."; persistDraft()
|
||||
return true
|
||||
} catch { message = "Could not open BASIC source: \(error.localizedDescription)"; return false }
|
||||
}
|
||||
@discardableResult func save(as: Bool = false) -> Bool {
|
||||
guard !busy, source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false }
|
||||
var target = fileURL
|
||||
if target == nil || `as` {
|
||||
let panel = NSSavePanel(); panel.title = "Save BASIC Source"; panel.nameFieldStringValue = fileURL?.lastPathComponent ?? "HelloCoCo.bas"
|
||||
panel.allowedContentTypes = [UTType(filenameExtension: "bas") ?? .plainText]; panel.canCreateDirectories = true
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return false }; target = url
|
||||
}
|
||||
guard let target else { return false }
|
||||
return saveSource(to: target)
|
||||
}
|
||||
@discardableResult func saveSource(to target: URL) -> Bool {
|
||||
guard !busy, source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false }
|
||||
do {
|
||||
if target == fileURL, let fingerprint = fileFingerprint {
|
||||
let existing = try? Self.readText(target).1
|
||||
if existing != fingerprint {
|
||||
let alert = NSAlert(); alert.messageText = "The BASIC source changed outside VCC Plus."
|
||||
alert.informativeText = "Replace the file with your editor text? Choose Cancel to keep both and use Save As."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Replace File")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return false }
|
||||
}
|
||||
}
|
||||
let data = Data(source.utf8); try data.write(to: target, options: .atomic)
|
||||
fileURL = target; fileFingerprint = Self.fingerprint(data); savedSource = source
|
||||
message = nil; status = "Saved \(target.lastPathComponent)."; persistDraft(); return true
|
||||
} catch { message = "Could not save BASIC source: \(error.localizedDescription)"; return false }
|
||||
}
|
||||
private var cursorBreakpointLine: Int? {
|
||||
let text = source as NSString
|
||||
guard editorOffset >= 0, editorOffset <= text.length else { return nil }
|
||||
let range = text.lineRange(for: NSRange(location: editorOffset, length: 0))
|
||||
return BASICLanguage.analyze(text.substring(with: range)).lines.first?.number
|
||||
}
|
||||
var cursorBreakpointHelp: String {
|
||||
guard let line = cursorBreakpointLine else { return "Place the insertion point on a numbered BASIC statement to set a breakpoint" }
|
||||
return BreakpointRuler.actionName(line, set: breakpoints.contains(line))
|
||||
}
|
||||
func toggleBreakpointAtCursor() {
|
||||
guard let line = cursorBreakpointLine else {
|
||||
message = "Place the insertion point on a numbered BASIC statement first."; return
|
||||
}
|
||||
toggleBreakpoint(line)
|
||||
}
|
||||
func toggleBreakpoint(_ line: Int) {
|
||||
guard !busy else { return }
|
||||
if breakpoints.contains(line) { breakpoints.remove(line) }
|
||||
else {
|
||||
let matches = BASICLanguage.analyze(source).lines.filter { $0.number == line }
|
||||
guard matches.count == 1, let entry = matches.first,
|
||||
NSMaxRange(entry.labelRange) < NSMaxRange(entry.range),
|
||||
!(source as NSString).substring(with: NSRange(location: NSMaxRange(entry.labelRange), length: NSMaxRange(entry.range) - NSMaxRange(entry.labelRange)))
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
message = "Breakpoints need a unique line number with a BASIC statement."; return
|
||||
}
|
||||
guard breakpoints.count < 1024 else { message = "At most 1024 BASIC breakpoints are supported."; return }
|
||||
breakpoints.insert(line)
|
||||
}
|
||||
updateBreakpoints()
|
||||
}
|
||||
func clearBreakpoints() {
|
||||
guard !busy else { return }; breakpoints = []; updateBreakpoints()
|
||||
}
|
||||
private func updateBreakpoints() {
|
||||
message = nil
|
||||
let text = source, points = breakpoints
|
||||
// Before the first transfer these are editor intentions only. An
|
||||
// atomic Run installs the program and its points together.
|
||||
guard canTransfer, knownGuestSource != nil, machine.basicWorkspaceOwner == workspaceID else {
|
||||
debugStatus = points.isEmpty ? "No BASIC breakpoints." : "\(points.count) breakpoint(s) will apply on Run."; return
|
||||
}
|
||||
busy = true
|
||||
Task {
|
||||
defer { busy = false }
|
||||
let configured = await machine.configureBASICBreakpoints(points, source: text)
|
||||
guard machine.basicWorkspaceOwner == workspaceID, source == text else { return }
|
||||
if configured {
|
||||
armedSource = text
|
||||
stoppedLine = machine.basicDebug.line; stoppedToken = machine.basicDebug.sourceRange
|
||||
refreshInspection()
|
||||
debugStatus = stoppedLine.map { "Paused at BASIC line \($0)." } ?? "BASIC breakpoints are active."
|
||||
} else {
|
||||
armedSource = nil; stoppedLine = nil; detachOwnedDebug()
|
||||
debugStatus = "Editor and CoCo differ. These breakpoints will apply on the next Run."
|
||||
}
|
||||
}
|
||||
}
|
||||
func stepProgram(over: Bool, out: Bool = false) {
|
||||
guard out ? canStepOut : canStep else { return }
|
||||
let text = source; busy = true; message = nil
|
||||
Task {
|
||||
defer { busy = false }
|
||||
let succeeded = out ? await machine.stepOutBASIC(source: text) : await machine.stepBASIC(source: text, over: over)
|
||||
if !succeeded {
|
||||
message = machine.fileError ?? "The BASIC stop is no longer current."
|
||||
}
|
||||
}
|
||||
}
|
||||
func cancelStep() { guard stepping else { return }; machine.pause() }
|
||||
func continueProgram() {
|
||||
guard canContinue else { return }
|
||||
let text = source; busy = true; message = nil
|
||||
Task {
|
||||
defer { busy = false }
|
||||
if !((await machine.continueBASIC(source: text))) { message = machine.fileError ?? "The BASIC stop is no longer current." }
|
||||
}
|
||||
}
|
||||
func checkSource() {
|
||||
guard !busy, editorAction == nil else { return }
|
||||
let analysis = BASICLanguage.analyze(source)
|
||||
diagnostics = analysis.diagnostics; message = nil
|
||||
status = analysis.diagnostics.isEmpty
|
||||
? "No source-structure issues found. BASIC checks statement syntax when the program runs."
|
||||
: "Source check found \(analysis.diagnostics.count) \(analysis.diagnostics.count == 1 ? "issue" : "issues"). Select an issue to show its source line."
|
||||
}
|
||||
func goToLine(_ number: Int) {
|
||||
guard !busy, editorAction == nil else { return }
|
||||
let analysis = BASICLanguage.analyze(source)
|
||||
let matches = analysis.lines.filter { $0.number == number }
|
||||
guard (0...63999).contains(number), matches.count == 1, let line = matches.first else {
|
||||
message = matches.count > 1 ? "BASIC line \(number) is duplicated. Check Source before navigating."
|
||||
: "No BASIC line \(number) exists in this source. Use a program line number, not an editor row."
|
||||
return
|
||||
}
|
||||
message = nil
|
||||
editorAction = .init(expectedSource: source, operation: .select(line.range))
|
||||
status = "BASIC line \(number)."
|
||||
}
|
||||
func selectDiagnostic(_ diagnostic: BASICLanguage.Diagnostic) {
|
||||
guard !busy, editorAction == nil, diagnostics.contains(where: { $0.id == diagnostic.id }) else { return }
|
||||
editorAction = .init(expectedSource: source, operation: .select(diagnostic.range))
|
||||
}
|
||||
func renumber(start: Int, increment: Int) {
|
||||
guard !busy, editorAction == nil else { return }
|
||||
do {
|
||||
let result = try BASICLanguage.renumber(source, start: start, step: increment)
|
||||
message = nil; diagnostics = []
|
||||
guard result.source != source else { status = "The program already uses those line numbers."; return }
|
||||
editorAction = .init(expectedSource: source, operation: .replace(source: result.source, undoName: "Renumber BASIC"))
|
||||
status = "Renumbered \(result.lineCount) lines and \(result.changedReferences) references. Undo restores the previous source."
|
||||
} catch {
|
||||
diagnostics = BASICLanguage.analyze(source).diagnostics
|
||||
message = error.localizedDescription
|
||||
}
|
||||
}
|
||||
func editorActionHandled(id: UUID, applied: Bool) {
|
||||
guard editorAction?.id == id else { return }
|
||||
if applied, case .replace(_, let name) = editorAction?.operation, name == "Renumber BASIC", !breakpoints.isEmpty {
|
||||
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
|
||||
debugStatus = "Line numbers changed. Set breakpoints on the renumbered program."
|
||||
}
|
||||
editorAction = nil
|
||||
if !applied { message = "The source or insertion point changed before the edit could be applied. Try the action again." }
|
||||
}
|
||||
private func validateSourceStructure(_ text: String) -> Bool {
|
||||
let analysis = BASICLanguage.analyze(text)
|
||||
diagnostics = analysis.diagnostics
|
||||
guard !analysis.hasErrors else {
|
||||
message = "Fix the source errors below before loading or exporting. Select an issue to show its source line."
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
var suggestedExportName: String { BASICExportName.suggestion(for: fileURL) }
|
||||
func chooseExport(_ kind: BASICExportKind, name: String, dosBoot: Bool) {
|
||||
Task { _ = await performExport(kind, name: name, dosBoot: dosBoot, destination: nil) }
|
||||
}
|
||||
/// The save panel and regression checks share one production export path.
|
||||
@discardableResult func exportImage(_ kind: BASICExportKind, name: String, dosBoot: Bool = false, to destination: URL) async -> Bool {
|
||||
await performExport(kind, name: name, dosBoot: dosBoot, destination: destination)
|
||||
}
|
||||
private func performExport(_ kind: BASICExportKind, name: String, dosBoot: Bool, destination: URL?) async -> Bool {
|
||||
guard canTransfer else { message = "Start the bundled CoCo BASIC setup before exporting."; return false }
|
||||
guard let name = BASICExportName.normalized(name) else {
|
||||
message = "Use 1–8 letters or numbers for the CoCo program name, without an extension."; return false
|
||||
}
|
||||
let text = source, sourceURL = fileURL
|
||||
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
message = "Enter a line-numbered BASIC program before exporting."; return false
|
||||
}
|
||||
guard validateSourceStructure(text) else { return false }
|
||||
busy = true; message = nil; persistDraft()
|
||||
defer { busy = false }
|
||||
guard let data = await machine.exportBASICSource(text, name: name, cassette: kind == .cassette) else {
|
||||
message = machine.fileError ?? "Could not prepare the BASIC export."; return false
|
||||
}
|
||||
var target = destination
|
||||
if target == nil {
|
||||
let panel = NSSavePanel(); panel.title = kind.title
|
||||
panel.nameFieldStringValue = name + "." + kind.fileExtension
|
||||
panel.allowedContentTypes = [UTType(filenameExtension: kind.fileExtension) ?? .data]
|
||||
panel.canCreateDirectories = true; panel.isExtensionHidden = false
|
||||
panel.message = kind.instructions(name: name, dosBoot: dosBoot)
|
||||
guard panel.runModal() == .OK, let chosen = panel.url else { return false }; target = chosen
|
||||
}
|
||||
guard let target else { return false }
|
||||
do {
|
||||
let output = kind == .disk && dosBoot ? try await DevelopmentBuildTools().bootableBASICDisk(data, name: name) : data
|
||||
try await machine.writeBASICExport(output, to: target, sourceURL: sourceURL)
|
||||
status = "Exported \(target.lastPathComponent). " + kind.instructions(name: name, dosBoot: dosBoot)
|
||||
return true
|
||||
} catch { message = "Could not export BASIC: \(error.localizedDescription)"; return false }
|
||||
}
|
||||
func transfer(run: Bool) {
|
||||
Task { _ = await performTransfer(run: run) }
|
||||
}
|
||||
|
||||
/// Both the editor and the reviewed run use the same source validation and replacement confirmation.
|
||||
func performTransfer(run: Bool, reviewIsCurrent: (() -> Bool)? = nil) async -> (VCCMachineSnapshot, String)? {
|
||||
guard canTransfer else { return nil }
|
||||
let text = source
|
||||
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { message = "Enter a line-numbered BASIC program first."; return nil }
|
||||
guard validateSourceStructure(text) else { return nil }
|
||||
busy = true; message = nil; persistDraft()
|
||||
defer { busy = false }
|
||||
let prior = reviewIsCurrent == nil ? nil : await machine.mcpMachineSnapshot()
|
||||
guard reviewIsCurrent?() != false else { return nil }
|
||||
guard let existing = await machine.readBASICSource() else { message = machine.fileError ?? "Could not inspect BASIC memory."; return nil }
|
||||
if machine.assemblyAttached || (!existing.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existing != knownGuestSource) {
|
||||
let alert = NSAlert(); alert.messageText = machine.assemblyAttached ? "Take over the assembly session with BASIC?" : "Replace the BASIC program in the CoCo?"
|
||||
alert.informativeText = "This replaces program memory and clears its variables. Mounted media and machine settings are kept. Use Read from CoCo first if you want to save that program."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: run ? "Replace and Run" : "Replace and Load")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return nil }
|
||||
}
|
||||
guard reviewIsCurrent?() != false, source == text else { return nil }
|
||||
guard let snapshot = await machine.loadBASICSource(text, run: run, breakpoints: breakpoints,
|
||||
review: prior.map { ($0, existing) }) else { message = machine.fileError ?? "BASIC transfer failed."; return nil }
|
||||
machine.basicWorkspaceOwner = workspaceID
|
||||
let loadedSource = reviewIsCurrent == nil ? await machine.readBASICSource() : snapshot.assistantLoadedSource
|
||||
guard machine.basicWorkspaceOwner == workspaceID, source == text else { return nil }
|
||||
knownGuestSource = loadedSource
|
||||
armedSource = machine.basicDebug.attached ? text : nil
|
||||
refreshRuntimeState(machine.basicDebug)
|
||||
stoppedLine = machine.basicDebug.line; stoppedToken = machine.basicDebug.sourceRange
|
||||
refreshInspection()
|
||||
if machine.basicDebug.attached {
|
||||
debugStatus = stoppedLine.map { "Paused at BASIC line \($0). Continue keeps variables and open files." }
|
||||
?? (breakpoints.isEmpty ? "No BASIC breakpoints." : "BASIC breakpoints are active.")
|
||||
} else {
|
||||
debugStatus = machine.basicDebug.status.isEmpty ? "BASIC debugging is detached." : machine.basicDebug.status
|
||||
}
|
||||
status = run ? "Loaded directly into BASIC memory and started. Use CoCo Break to stop a running program." : "Loaded directly into BASIC memory. Use LIST or RUN in the CoCo."
|
||||
return loadedSource.map { (snapshot, $0) }
|
||||
}
|
||||
func readFromCoCo() {
|
||||
guard canTransfer, confirmDiscard(applyDiscard: false) else { return }
|
||||
busy = true; message = nil
|
||||
Task {
|
||||
defer { busy = false }
|
||||
guard let text = await machine.readBASICSource() else { message = machine.fileError ?? "Could not read BASIC memory."; return }
|
||||
fileURL = nil; fileFingerprint = nil; savedSource = ""; source = text; knownGuestSource = text
|
||||
breakpoints = []; armedSource = nil; stoppedLine = nil; detachOwnedDebug()
|
||||
documentID = UUID(); hint = nil; status = "Read from CoCo memory. Save a source copy on the Mac to keep it."; persistDraft()
|
||||
}
|
||||
}
|
||||
func statusMessage(_ value: String) { status = value }
|
||||
func cursorChanged(_ offset: Int) {
|
||||
editorOffset = offset
|
||||
if let keyword = BASICReferenceContext.keyword(in: source, at: offset),
|
||||
let catalog = try? BASICReferenceCatalog.bundled.get() {
|
||||
let candidates = catalog.entries.filter { $0.keyword == keyword }
|
||||
let entry = candidates.first { $0.dialect == machine.basicReferenceDialect }
|
||||
?? candidates.first { $0.dialect == .common }
|
||||
?? candidates.first { $0.dialect == .disk }
|
||||
hint = entry?.syntax.first
|
||||
} else { hint = BASICLanguage.hint(source, at: offset) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
struct BASICDevelopmentView: View {
|
||||
@ObservedObject var model: BASICDevelopmentModel
|
||||
@StateObject private var finder = SourceFind()
|
||||
let reference: BASICReferenceModel?
|
||||
@ObservedObject private var menu: MachineMenuState
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var exportKind: BASICExportKind?
|
||||
@State private var editingSheet: BASICEditingSheet?
|
||||
@State private var diagnosticsExpanded = true
|
||||
@State private var pendingEditingAction: (() -> Void)?
|
||||
@State private var pendingExport: (kind: BASICExportKind, name: String, dosBoot: Bool)?
|
||||
init(model: BASICDevelopmentModel, reference: BASICReferenceModel? = nil) {
|
||||
self.model = model; self.reference = reference; menu = model.machine.menuState
|
||||
}
|
||||
private func quickHelp(_ keyword: String?) {
|
||||
if let keyword { reference?.show(keyword: keyword, dialect: model.machine.basicReferenceDialect) }
|
||||
openWindow(id: "basic-reference")
|
||||
}
|
||||
private var unavailable: Bool { model.busy || menu.values.busy || ![VCCMachineState.running, .paused].contains(menu.values.state) }
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "terminal").font(.largeTitle).foregroundStyle(.tint)
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("BASIC Development").font(.title2.bold())
|
||||
Text("Edit on your Mac · Run in your CoCo").font(.callout).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Button { openWindow(id: "basic-reference") } label: { Label("Reference", systemImage: "book.closed") }
|
||||
.accessibilityIdentifier("basic.reference.open")
|
||||
Button { openWindow(id: "machine") } label: { Label("Show CoCo", systemImage: "desktopcomputer") }
|
||||
.accessibilityIdentifier("basic.show-machine")
|
||||
}.padding(16)
|
||||
Divider()
|
||||
HStack(spacing: 10) {
|
||||
Button { model.newProgram() } label: { Label("New", systemImage: "doc.badge.plus") }.accessibilityIdentifier("basic.new")
|
||||
Button { model.open() } label: { Label("Open…", systemImage: "folder") }.accessibilityIdentifier("basic.open")
|
||||
Button { model.save() } label: { Label("Save", systemImage: "square.and.arrow.down") }
|
||||
.keyboardShortcut("s", modifiers: .command).accessibilityIdentifier("basic.save")
|
||||
Menu {
|
||||
Button("Save As…") { model.save(as: true) }
|
||||
Button("Local Assistant Access…", systemImage: "link") { MCPAccess.shared.show(for: model) }
|
||||
.accessibilityIdentifier("basic.assistant.access")
|
||||
Divider()
|
||||
Button("Export Disk…", systemImage: "externaldrive") { exportKind = .disk }
|
||||
.disabled(unavailable).accessibilityIdentifier("basic.export-disk")
|
||||
Button("Export Cassette…", systemImage: "recordingtape") { exportKind = .cassette }
|
||||
.disabled(unavailable).accessibilityIdentifier("basic.export-cassette")
|
||||
} label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 25).help("Show more BASIC file actions").accessibilityLabel("More file actions").accessibilityIdentifier("basic.file-actions")
|
||||
Spacer(minLength: 12)
|
||||
Button { model.readFromCoCo() } label: { Label("Read from CoCo", systemImage: "arrow.down.doc") }
|
||||
.disabled(unavailable).accessibilityIdentifier("basic.read")
|
||||
Button { model.transfer(run: false) } label: { Label("Load into CoCo", systemImage: "arrow.up.doc") }
|
||||
.disabled(unavailable).accessibilityIdentifier("basic.load")
|
||||
Button { model.transfer(run: true) } label: { Label("Run", systemImage: "play.fill") }
|
||||
.buttonStyle(.borderedProminent).disabled(unavailable).accessibilityIdentifier("basic.run")
|
||||
}.controlSize(.regular).padding(.horizontal,16).padding(.vertical,10).disabled(model.editorLocked)
|
||||
HStack {
|
||||
Label(model.title, systemImage: "doc.text").fontWeight(.medium).lineLimit(1)
|
||||
if model.dirty { Text("Edited").foregroundStyle(.secondary) }
|
||||
Spacer()
|
||||
SourceFindButton(finder: finder)
|
||||
Button { model.toggleBreakpointAtCursor() } label: { Image(systemName: "record.circle") }
|
||||
.help(model.cursorBreakpointHelp)
|
||||
.accessibilityLabel(model.cursorBreakpointHelp)
|
||||
.accessibilityIdentifier("basic.toggle-breakpoint").disabled(model.editorLocked)
|
||||
Button { model.continueProgram() } label: { Label("Continue", systemImage: "play.fill") }
|
||||
.disabled(!model.canContinue).accessibilityIdentifier("basic.continue")
|
||||
Button { model.stepProgram(over: false) } label: { Image(systemName: "arrow.down.to.line") }
|
||||
.help("Run one BASIC statement, following GOSUB into its subroutine")
|
||||
.accessibilityLabel("Step Into BASIC statement").accessibilityIdentifier("basic.step-into")
|
||||
.disabled(!model.canStep)
|
||||
Button { model.stepProgram(over: true) } label: { Image(systemName: "arrow.turn.up.right") }
|
||||
.help("Run one BASIC statement, continuing through a GOSUB unless a breakpoint is hit")
|
||||
.accessibilityLabel("Step Over BASIC subroutine").accessibilityIdentifier("basic.step-over")
|
||||
.disabled(!model.canStep)
|
||||
Button { model.stepProgram(over: false, out: true) } label: { Image(systemName: "arrow.up.to.line") }
|
||||
.help("Run until this GOSUB returns to its caller or a breakpoint is hit")
|
||||
.accessibilityLabel("Step Out of BASIC subroutine").accessibilityIdentifier("basic.step-out")
|
||||
.disabled(!model.canStepOut)
|
||||
if model.stepping {
|
||||
Button { model.cancelStep() } label: { Image(systemName: "pause.fill") }
|
||||
.help("Pause the current BASIC step").accessibilityLabel("Pause BASIC step")
|
||||
.accessibilityIdentifier("basic.pause-step")
|
||||
}
|
||||
Menu {
|
||||
Button("Clear All Breakpoints", systemImage: "record.circle") { model.clearBreakpoints() }
|
||||
.disabled(model.breakpoints.isEmpty).accessibilityIdentifier("basic.clear-breakpoints")
|
||||
Divider()
|
||||
Button("Check Source", systemImage: "checkmark.circle") { model.checkSource(); diagnosticsExpanded = true }
|
||||
.accessibilityIdentifier("basic.check-source")
|
||||
Button("Go to Line…", systemImage: "arrow.turn.down.right") { editingSheet = .goToLine }
|
||||
.accessibilityIdentifier("basic.go-to-line")
|
||||
Button("Renumber…", systemImage: "list.number") { editingSheet = .renumber }
|
||||
.accessibilityIdentifier("basic.renumber")
|
||||
} label: { Label("Editing", systemImage: "pencil.line") }
|
||||
.disabled(model.editorLocked).accessibilityIdentifier("basic.editing-actions")
|
||||
Button { model.completionRequest = UUID() } label: { Label("Complete", systemImage: "text.badge.plus") }
|
||||
.help("Complete a BASIC keyword (Control–Space)").accessibilityIdentifier("basic.complete")
|
||||
.disabled(model.editorLocked)
|
||||
}.font(.callout).padding(.horizontal,16).padding(.bottom,8)
|
||||
Divider()
|
||||
if let message = model.message {
|
||||
Label(message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange)
|
||||
.textSelection(.enabled).padding(10).frame(maxWidth:.infinity,alignment:.leading)
|
||||
.background(.orange.opacity(0.08)).accessibilityIdentifier("basic.message")
|
||||
}
|
||||
if let line = model.runtimeErrorLine {
|
||||
HStack(spacing: 10) {
|
||||
Label("BASIC \(model.runtimeErrorCode.isEmpty ? "runtime" : model.runtimeErrorCode) error on line \(line)", systemImage: "exclamationmark.circle.fill")
|
||||
.foregroundStyle(.red).accessibilityIdentifier("basic.runtime-error")
|
||||
Text("The program ended. Continue returns to the prompt.").foregroundStyle(.secondary)
|
||||
Spacer(minLength: 0)
|
||||
Button { reference?.showError(code: model.runtimeErrorCode); openWindow(id: "basic-reference") } label: {
|
||||
Image(systemName: "questionmark.circle")
|
||||
}.help("Explain this BASIC error").accessibilityLabel("Explain BASIC error")
|
||||
.accessibilityIdentifier("basic.reference.error")
|
||||
Button("Show Line \(line)") { model.goToLine(line) }
|
||||
.disabled(model.editorLocked).accessibilityIdentifier("basic.show-runtime-error")
|
||||
}.font(.callout).padding(10).background(.red.opacity(0.06))
|
||||
}
|
||||
SourceFindBar(finder: finder, source: model.source, readOnly: model.editorLocked)
|
||||
BASICSourceEditor(finder: finder, text: $model.source, readOnly: model.editorLocked, completionRequest: model.completionRequest,
|
||||
editorAction: model.editorAction, breakpoints: model.breakpoints, stoppedLine: model.stoppedLine, stoppedToken: model.stoppedToken,
|
||||
toggleBreakpoint: model.toggleBreakpoint,
|
||||
actionHandled: { id, applied in model.editorActionHandled(id: id, applied: applied) },
|
||||
cursorChanged: model.cursorChanged, assistance: { model.statusMessage($0) }, quickHelp: quickHelp,
|
||||
attach: { model.assistantEditor = $0 })
|
||||
.id(model.documentID).frame(minHeight:120).accessibilityIdentifier("basic.editor")
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: model.stoppedLine == nil ? "record.circle" : "arrow.right.circle.fill")
|
||||
.foregroundStyle(model.stoppedLine == nil ? Color.secondary : Color.orange)
|
||||
Text(model.debugStatus).font(.caption).lineLimit(2)
|
||||
.accessibilityIdentifier("basic.debug-status")
|
||||
Spacer()
|
||||
if !model.breakpoints.isEmpty {
|
||||
Text("\(model.breakpoints.count) breakpoint\(model.breakpoints.count == 1 ? "" : "s")")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}.padding(.horizontal, 12).padding(.vertical, 7)
|
||||
// Reserve the window chrome and a useful editor height before
|
||||
// allocating rows to the independently scrolling inspector.
|
||||
BASICInspectionView(model: model, valuesHeight: max(36, min(160,
|
||||
geometry.size.height - 560 - (!model.diagnostics.isEmpty && diagnosticsExpanded ? 130 : 0))))
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
DisclosureGroup(isExpanded: $diagnosticsExpanded) {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 5) {
|
||||
ForEach(model.diagnostics) { diagnostic in
|
||||
Button { model.selectDiagnostic(diagnostic) } label: {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
Image(systemName: diagnostic.severity == .error ? "exclamationmark.circle" : "exclamationmark.triangle")
|
||||
.foregroundStyle(diagnostic.severity == .error ? Color.red : Color.orange)
|
||||
Text("Row \(diagnostic.row)").monospacedDigit().fontWeight(.medium)
|
||||
Text(diagnostic.message).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.contentShape(Rectangle())
|
||||
}.buttonStyle(.plain).font(.callout).disabled(model.editorLocked)
|
||||
.accessibilityLabel("Source row \(diagnostic.row): \(diagnostic.message). Go to source.")
|
||||
.accessibilityIdentifier("basic.diagnostic.\(diagnostic.id)")
|
||||
}
|
||||
}.padding(.vertical, 6)
|
||||
}.frame(maxHeight: 100)
|
||||
} label: {
|
||||
Text("Source checks · \(model.diagnostics.count)").font(.callout.bold())
|
||||
}.padding(.horizontal, 14).padding(.vertical, 8)
|
||||
.accessibilityIdentifier("basic.diagnostics")
|
||||
}
|
||||
HStack(alignment:.top,spacing:8) {
|
||||
Image(systemName: "info.circle").foregroundStyle(.secondary)
|
||||
Text(model.hint ?? "Return continues line numbering. Tab accepts a faint keyword suggestion; Control–Space shows all matches.")
|
||||
.font(.system(.caption,design:.monospaced)).textSelection(.enabled)
|
||||
.frame(maxWidth:.infinity,alignment:.leading).accessibilityIdentifier("basic.hint")
|
||||
Button { quickHelp(BASICReferenceContext.keyword(in: model.source, at: model.editorOffset)) } label: {
|
||||
Label("Quick Help", systemImage: "questionmark.circle")
|
||||
}.keyboardShortcut("h", modifiers: [.control, .shift])
|
||||
.help("Look up the command at the insertion point (Control–Shift–H)")
|
||||
.accessibilityIdentifier("basic.reference.context")
|
||||
}.padding(10).frame(minHeight:42,alignment:.top)
|
||||
Divider()
|
||||
VStack(alignment:.leading,spacing:5) {
|
||||
HStack(alignment:.top) {
|
||||
if model.busy { ProgressView().controlSize(.small) }
|
||||
Text(model.status).font(.callout).textSelection(.enabled).accessibilityIdentifier("basic.status")
|
||||
}
|
||||
Text("Direct loading supports Disk BASIC, Hard Drive BASIC and CoCo SDC at the BASIC OK prompt. Use CoCo Break to stop before replacing a running program. Read from CoCo retrieves program text, not variables.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal:false,vertical:true)
|
||||
.accessibilityIdentifier("basic.preset-support")
|
||||
}.padding(14)
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
|
||||
}.frame(minWidth:850,minHeight:560)
|
||||
.focusedSceneValue(\.sourceFind, finder)
|
||||
.onDisappear { model.persistDraft() }
|
||||
.sheet(item: $editingSheet, onDismiss: {
|
||||
let action = pendingEditingAction; pendingEditingAction = nil; action?()
|
||||
}) { kind in
|
||||
BASICEditingOptions(kind: kind,
|
||||
goToLine: { number in
|
||||
pendingEditingAction = { model.goToLine(number) }; editingSheet = nil
|
||||
},
|
||||
renumber: { start, increment in
|
||||
pendingEditingAction = { model.renumber(start: start, increment: increment) }; editingSheet = nil
|
||||
},
|
||||
cancel: { editingSheet = nil })
|
||||
}
|
||||
.sheet(item: $exportKind, onDismiss: {
|
||||
if let request = pendingExport {
|
||||
pendingExport = nil; model.chooseExport(request.kind, name: request.name, dosBoot: request.dosBoot)
|
||||
}
|
||||
}) { kind in
|
||||
BASICExportOptions(kind: kind, initialName: model.suggestedExportName,
|
||||
confirm: { name, boot in pendingExport = (kind, name, boot); exportKind = nil },
|
||||
cancel: { exportKind = nil })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum BASICEditingSheet: String, Identifiable {
|
||||
case goToLine, renumber
|
||||
var id: String { rawValue }
|
||||
}
|
||||
|
||||
private struct BASICEditingOptions: View {
|
||||
let kind: BASICEditingSheet
|
||||
let goToLine: (Int) -> Void
|
||||
let renumber: (Int, Int) -> Void
|
||||
let cancel: () -> Void
|
||||
@State private var line = "10"
|
||||
@State private var increment = "10"
|
||||
@FocusState private var firstFieldFocused: Bool
|
||||
private var firstNumber: Int? { Int(line.trimmingCharacters(in: .whitespaces)) }
|
||||
private var step: Int? { Int(increment.trimmingCharacters(in: .whitespaces)) }
|
||||
private var valid: Bool {
|
||||
guard let firstNumber, (0...63999).contains(firstNumber) else { return false }
|
||||
return kind == .goToLine || step.map { (1...63999).contains($0) } == true
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Label(kind == .goToLine ? "Go to BASIC Line" : "Renumber Program",
|
||||
systemImage: kind == .goToLine ? "arrow.turn.down.right" : "list.number").font(.title2.bold())
|
||||
if kind == .goToLine {
|
||||
Text("Find a BASIC line number in your editor source. This does not move the running CoCo program.")
|
||||
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
TextField("BASIC line number", text: $line).textFieldStyle(.roundedBorder)
|
||||
.focused($firstFieldFocused).accessibilityIdentifier("basic.go-line-number")
|
||||
} else {
|
||||
Text("Renumber the entire editor program and update its recognized line references. Strings, comments, and DATA values stay unchanged.")
|
||||
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) {
|
||||
GridRow {
|
||||
Text("Start at")
|
||||
TextField("Starting line number", text: $line).textFieldStyle(.roundedBorder)
|
||||
.focused($firstFieldFocused).accessibilityIdentifier("basic.renumber-start")
|
||||
}
|
||||
GridRow {
|
||||
Text("Increment")
|
||||
TextField("Line number increment", text: $increment).textFieldStyle(.roundedBorder)
|
||||
.accessibilityIdentifier("basic.renumber-increment")
|
||||
}
|
||||
}
|
||||
Text("The CoCo program is not changed. You can undo this edit with ⌘Z.")
|
||||
.font(.callout).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
Text(kind == .goToLine ? "BASIC line numbers range from 0 to 63999." : "Use line numbers from 0 to 63999 and a positive increment. Source problems must be corrected before renumbering.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", action: cancel).keyboardShortcut(.cancelAction)
|
||||
Button(kind == .goToLine ? "Go to Line" : "Renumber") {
|
||||
guard let firstNumber, valid else { return }
|
||||
if kind == .goToLine { goToLine(firstNumber) }
|
||||
else if let step { renumber(firstNumber, step) }
|
||||
}.keyboardShortcut(.defaultAction).disabled(!valid)
|
||||
.accessibilityIdentifier("basic.editing-confirm")
|
||||
}
|
||||
}.padding(22).frame(width: 430).task { firstFieldFocused = true }
|
||||
}
|
||||
}
|
||||
|
||||
private struct BASICExportOptions: View {
|
||||
let kind: BASICExportKind
|
||||
let confirm: (String, Bool) -> Void
|
||||
let cancel: () -> Void
|
||||
@State private var name: String
|
||||
@State private var dosBoot = false
|
||||
@FocusState private var nameFocused: Bool
|
||||
init(kind: BASICExportKind, initialName: String, confirm: @escaping (String, Bool) -> Void, cancel: @escaping () -> Void) {
|
||||
self.kind = kind; self.confirm = confirm; self.cancel = cancel
|
||||
_name = State(initialValue: initialName)
|
||||
}
|
||||
private var validName: String? { BASICExportName.normalized(name) }
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Label(kind.title, systemImage: kind.symbol).font(.title2.bold())
|
||||
Text(kind == .disk
|
||||
? "Create a fresh 35-track Disk BASIC disk with your current editor program."
|
||||
: "Create a cassette image with your current editor program.")
|
||||
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
TextField("CoCo program name", text: $name).textFieldStyle(.roundedBorder)
|
||||
.focused($nameFocused).accessibilityIdentifier("basic.export-name")
|
||||
Text("Use 1–8 letters or numbers, without an extension. The CoCo name will be uppercase.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
if let validName {
|
||||
Label(kind == .disk ? validName + ".BAS" : validName, systemImage: "doc.text")
|
||||
.font(.system(.callout, design: .monospaced))
|
||||
}
|
||||
if kind == .disk {
|
||||
Toggle("Install DOS bootloader", isOn: $dosBoot)
|
||||
.accessibilityIdentifier("basic.export-dos")
|
||||
}
|
||||
if let validName {
|
||||
Text(kind.instructions(name: validName, dosBoot: dosBoot))
|
||||
.accessibilityIdentifier("basic.export-commands")
|
||||
.font(.callout).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", action: cancel).keyboardShortcut(.cancelAction)
|
||||
Button("Choose Location…") { if let validName { confirm(validName, dosBoot) } }
|
||||
.keyboardShortcut(.defaultAction).disabled(validName == nil)
|
||||
.accessibilityIdentifier("basic.export-location")
|
||||
}
|
||||
}.padding(22).frame(width: 430).task { nameFocused = true }
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable AppKit text editor: only explicit document changes reset Undo.
|
||||
struct BASICSourceEditor: NSViewRepresentable {
|
||||
let finder: SourceFind
|
||||
@Binding var text: String
|
||||
let readOnly: Bool
|
||||
let completionRequest: UUID
|
||||
let editorAction: BASICEditorAction?
|
||||
let breakpoints: Set<Int>
|
||||
let stoppedLine: Int?
|
||||
let stoppedToken: NSRange?
|
||||
let toggleBreakpoint: (Int) -> Void
|
||||
let actionHandled: (UUID, Bool) -> Void
|
||||
let cursorChanged: (Int) -> Void
|
||||
let assistance: (String) -> Void
|
||||
let quickHelp: (String?) -> Void
|
||||
var attach: (BASICTextView) -> Void = { _ in }
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll=NSScrollView(); scroll.hasVerticalScroller=true; scroll.hasHorizontalScroller=true; scroll.autohidesScrollers=true
|
||||
// AppKit ruler decorations must not paint into the surrounding SwiftUI
|
||||
// toolbar, inspector or footer when this representable resizes.
|
||||
scroll.wantsLayer = true; scroll.layer?.masksToBounds = true
|
||||
let editor=BASICTextView(frame:.zero)
|
||||
// Highlighting and breakpoint geometry use TextKit 1. Establish it
|
||||
// before setting up the unwrapped container, even for an empty draft.
|
||||
_ = editor.layoutManager
|
||||
attach(editor)
|
||||
editor.delegate=context.coordinator; editor.string=text; editor.allowsUndo=true; editor.isRichText=false
|
||||
editor.isAutomaticQuoteSubstitutionEnabled=false; editor.isAutomaticDashSubstitutionEnabled=false
|
||||
editor.isAutomaticTextReplacementEnabled=false; editor.isAutomaticSpellingCorrectionEnabled=false
|
||||
editor.isContinuousSpellCheckingEnabled=false; editor.isGrammarCheckingEnabled=false
|
||||
editor.isVerticallyResizable=true; editor.isHorizontallyResizable=true
|
||||
editor.minSize=NSSize(width:0,height:0); editor.maxSize=NSSize(width:CGFloat.greatestFiniteMagnitude,height:CGFloat.greatestFiniteMagnitude)
|
||||
editor.textContainer?.widthTracksTextView=false
|
||||
editor.textContainer?.containerSize=editor.maxSize
|
||||
editor.autoresizingMask = [.width]
|
||||
editor.textContainerInset=NSSize(width:16,height:14)
|
||||
editor.font = .monospacedSystemFont(ofSize:14,weight:.regular)
|
||||
editor.backgroundColor = .textBackgroundColor; editor.textColor = .textColor
|
||||
finder.editor = editor
|
||||
editor.setAccessibilityLabel("BASIC source editor")
|
||||
editor.setAccessibilityIdentifier("basic.source-text")
|
||||
editor.assistance=assistance; editor.quickHelp = quickHelp; scroll.documentView=editor
|
||||
scroll.verticalRulerView = BASICBreakpointRuler(textView: editor)
|
||||
scroll.hasVerticalRuler = true; scroll.rulersVisible = true
|
||||
editor.configureDebug(points: breakpoints, stoppedLine: stoppedLine, token: stoppedToken, toggle: toggleBreakpoint)
|
||||
context.coordinator.highlight(editor)
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll:NSScrollView,context:Context) {
|
||||
context.coordinator.parent=self
|
||||
guard let editor=scroll.documentView as? BASICTextView else { return }
|
||||
finder.editor = editor
|
||||
editor.assistance=assistance; editor.quickHelp = quickHelp; editor.isEditable = !readOnly
|
||||
editor.refreshInlineSuggestion()
|
||||
if !editor.string.utf8.elementsEqual(text.utf8) {
|
||||
editor.string=text; editor.undoManager?.removeAllActions(); context.coordinator.highlight(editor)
|
||||
}
|
||||
editor.configureDebug(points: breakpoints, stoppedLine: stoppedLine, token: stoppedToken, toggle: toggleBreakpoint)
|
||||
if let action = editorAction, context.coordinator.actionID != action.id {
|
||||
context.coordinator.actionID = action.id
|
||||
let coordinator = context.coordinator
|
||||
DispatchQueue.main.async { [weak editor, weak coordinator] in
|
||||
guard let coordinator else { return }
|
||||
let applied = editor?.applyEditorAction(action) ?? false
|
||||
coordinator.parent.actionHandled(action.id, applied)
|
||||
}
|
||||
}
|
||||
if context.coordinator.completionRequest != completionRequest {
|
||||
context.coordinator.completionRequest=completionRequest
|
||||
DispatchQueue.main.async { [weak editor] in
|
||||
guard let editor, editor.isEditable else { return }
|
||||
editor.window?.makeFirstResponder(editor); editor.complete(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@MainActor final class Coordinator: NSObject,NSTextViewDelegate {
|
||||
var parent:BASICSourceEditor
|
||||
var completionRequest:UUID
|
||||
var actionID:UUID?
|
||||
init(_ parent:BASICSourceEditor) { self.parent=parent; completionRequest=parent.completionRequest }
|
||||
func textDidChange(_ notification:Notification) {
|
||||
guard let editor=notification.object as? BASICTextView else { return }
|
||||
parent.text=editor.string; highlight(editor); reportCursor(editor)
|
||||
editor.configureDebug(points: parent.breakpoints, stoppedLine: parent.stoppedLine, token: parent.stoppedToken, toggle: parent.toggleBreakpoint)
|
||||
}
|
||||
func textViewDidChangeSelection(_ notification:Notification) {
|
||||
guard let editor=notification.object as? BASICTextView else { return }; reportCursor(editor)
|
||||
}
|
||||
func reportCursor(_ editor:NSTextView) {
|
||||
let offset=editor.selectedRange().location
|
||||
DispatchQueue.main.async { [weak self,weak editor] in
|
||||
guard let self,let editor,editor.selectedRange().location == offset else { return }; self.parent.cursorChanged(offset)
|
||||
}
|
||||
}
|
||||
func textView(_ textView:NSTextView,shouldChangeTextIn affectedCharRange:NSRange,replacementString:String?) -> Bool {
|
||||
guard let replacementString else { return true }
|
||||
let current=textView.string as NSString
|
||||
guard affectedCharRange.location <= current.length, NSMaxRange(affectedCharRange) <= current.length else { return false }
|
||||
guard current.replacingCharacters(in:affectedCharRange,with:replacementString).utf8.count <= BASICLanguage.maximumSourceBytes else {
|
||||
parent.assistance("BASIC source is limited to 1 MB."); return false
|
||||
}; return true
|
||||
}
|
||||
func highlight(_ editor:NSTextView) {
|
||||
guard let storage=editor.textStorage else { return }
|
||||
storage.beginEditing()
|
||||
let full=NSRange(location:0,length:storage.length)
|
||||
storage.addAttributes([.foregroundColor:NSColor.textColor,.font:NSFont.monospacedSystemFont(ofSize:14,weight:.regular)],range:full)
|
||||
for span in BASICLanguage.spans(editor.string) {
|
||||
let color:NSColor
|
||||
switch span.kind {
|
||||
case .keyword: color = .systemPurple
|
||||
case .number: color = .systemBlue
|
||||
case .string: color = .systemRed
|
||||
case .comment: color = .secondaryLabelColor
|
||||
case .data: color = .systemBrown
|
||||
}
|
||||
storage.addAttribute(.foregroundColor,value:color,range:span.range)
|
||||
}
|
||||
storage.endEditing()
|
||||
editor.typingAttributes=[.foregroundColor:NSColor.textColor,.font:NSFont.monospacedSystemFont(ofSize:14,weight:.regular)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Native completion with an explicit acceptance operation, so Escape and moving
|
||||
/// through candidates never alter the source or its Undo history.
|
||||
final class BASICTextView: NSTextView, SourceFindEditor {
|
||||
weak var sourceFind: SourceFind?
|
||||
var assistance:((String)->Void)?
|
||||
var quickHelp: ((String?) -> Void)?
|
||||
private var helpOffset: Int?
|
||||
override func menu(for event: NSEvent) -> NSMenu? {
|
||||
let menu = super.menu(for: event) ?? NSMenu()
|
||||
helpOffset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
|
||||
let item = NSMenuItem(title: "Quick Help for BASIC Command", action: #selector(showCommandHelp), keyEquivalent: "")
|
||||
item.target = self
|
||||
menu.insertItem(.separator(), at: 0); menu.insertItem(item, at: 0)
|
||||
return menu
|
||||
}
|
||||
@objc private func showCommandHelp() {
|
||||
quickHelp?(BASICReferenceContext.keyword(in: string, at: helpOffset ?? selectedRange().location))
|
||||
helpOffset = nil
|
||||
}
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
if event.modifierFlags.contains(.option), event.clickCount == 1 {
|
||||
let offset = characterIndexForInsertion(at: convert(event.locationInWindow, from: nil))
|
||||
if let keyword = BASICReferenceContext.keyword(in: string, at: offset) {
|
||||
quickHelp?(keyword); return
|
||||
}
|
||||
}
|
||||
super.mouseDown(with: event)
|
||||
}
|
||||
private var sourceForCompletion:String?
|
||||
private var completion:BASICLanguage.Completion?
|
||||
private var completionOffset=0
|
||||
private(set) var numberedRows: [BASICLanguage.NumberedLine] = []
|
||||
private(set) var breakpointLines: Set<Int> = []
|
||||
private var decoratedSource = ""
|
||||
private var executionLine: Int?
|
||||
private var executionToken: NSRange?
|
||||
func configureDebug(points: Set<Int>, stoppedLine: Int?, token: NSRange? = nil, toggle: @escaping (Int) -> Void) {
|
||||
let ruler = enclosingScrollView?.verticalRulerView as? BASICBreakpointRuler
|
||||
ruler?.onClick = toggle
|
||||
ruler?.active = isEditable
|
||||
ruler?.points = points
|
||||
let sourceChanged = decoratedSource != string
|
||||
let lineChanged = executionLine != stoppedLine || executionToken != token
|
||||
guard sourceChanged || lineChanged || breakpointLines != points else { return }
|
||||
decoratedSource = string; breakpointLines = points; executionLine = stoppedLine; executionToken = token
|
||||
if sourceChanged { numberedRows = BASICLanguage.analyze(string).lines }
|
||||
let full = NSRange(location: 0, length: (string as NSString).length)
|
||||
layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: full)
|
||||
if let stoppedLine, let row = numberedRows.first(where: { $0.number == stoppedLine }) {
|
||||
layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemYellow.withAlphaComponent(0.2), forCharacterRange: row.range)
|
||||
if let token, token.location >= row.range.location, NSMaxRange(token) <= NSMaxRange(row.range) {
|
||||
layoutManager?.addTemporaryAttribute(.backgroundColor, value: NSColor.systemOrange.withAlphaComponent(0.5), forCharacterRange: token)
|
||||
}
|
||||
if lineChanged { scrollRangeToVisible(token ?? row.range) }
|
||||
}
|
||||
ruler?.invalidateMarkers()
|
||||
}
|
||||
private(set) var inlineSuggestion: BASICLanguage.InlineCompletion?
|
||||
private var inlineSource = ""
|
||||
private var inlineSelection = NSRange(location: NSNotFound, length: 0)
|
||||
private var inlineDismissed = false
|
||||
|
||||
func refreshInlineSuggestion() {
|
||||
let selection = selectedRange()
|
||||
if let sourceForCompletion,
|
||||
sourceForCompletion != string || selection != NSRange(location: completionOffset, length: 0) {
|
||||
self.sourceForCompletion = nil; completion = nil
|
||||
}
|
||||
if inlineSource != string || inlineSelection != selection {
|
||||
inlineDismissed = false
|
||||
inlineSource = string; inlineSelection = selection
|
||||
}
|
||||
inlineSuggestion = isEditable && !hasMarkedText() && selection.length == 0 && !inlineDismissed && sourceForCompletion == nil
|
||||
? BASICLanguage.inlineCompletion(string, at: selection.location) : nil
|
||||
setAccessibilityHelp(inlineSuggestion.map { "Suggested keyword \($0.word). Press Tab to accept or Escape to dismiss." }
|
||||
?? "Numbered BASIC source. Return continues line numbering. Control–Space shows keyword completions.")
|
||||
needsDisplay = true
|
||||
}
|
||||
override func didChangeText() {
|
||||
super.didChangeText()
|
||||
refreshInlineSuggestion()
|
||||
}
|
||||
override func setSelectedRange(_ charRange: NSRange, affinity: NSSelectionAffinity, stillSelecting flag: Bool) {
|
||||
super.setSelectedRange(charRange, affinity: affinity, stillSelecting: flag)
|
||||
refreshInlineSuggestion()
|
||||
}
|
||||
override func becomeFirstResponder() -> Bool {
|
||||
let result = super.becomeFirstResponder(); refreshInlineSuggestion(); return result
|
||||
}
|
||||
override func resignFirstResponder() -> Bool {
|
||||
let result = super.resignFirstResponder(); needsDisplay = true; return result
|
||||
}
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
super.draw(dirtyRect)
|
||||
guard isEditable, !hasMarkedText(), window?.firstResponder === self,
|
||||
let window, let suggestion = inlineSuggestion,
|
||||
inlineSource == string, inlineSelection == selectedRange() else { return }
|
||||
// Draw separately: previews never enter text storage, saves, transfers,
|
||||
// accessibility's source value, or the Undo history.
|
||||
let screenRect = firstRect(forCharacterRange: selectedRange(), actualRange: nil)
|
||||
let rect = convert(window.convertFromScreen(screenRect), from: nil)
|
||||
(suggestion.suffix as NSString).draw(at: rect.origin, withAttributes: [
|
||||
.font: font ?? NSFont.monospacedSystemFont(ofSize: 14, weight: .regular),
|
||||
.foregroundColor: NSColor.secondaryLabelColor
|
||||
])
|
||||
}
|
||||
override func insertTab(_ sender: Any?) {
|
||||
refreshInlineSuggestion()
|
||||
guard let suggestion = inlineSuggestion else { super.insertTab(sender); return }
|
||||
breakUndoCoalescing()
|
||||
insertText(suggestion.word, replacementRange: suggestion.range)
|
||||
breakUndoCoalescing()
|
||||
undoManager?.setActionName("Complete BASIC Keyword")
|
||||
}
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
if inlineSuggestion != nil {
|
||||
inlineDismissed = true; refreshInlineSuggestion()
|
||||
} else {
|
||||
// AppKit owns a native completion popup's Escape. Cached candidates
|
||||
// alone do not mean that a popup is still handling the command.
|
||||
sourceForCompletion = nil; completion = nil
|
||||
if sourceFind?.cancel(from: self) != true {
|
||||
// cancelOperation is optional; NSTextView need not implement a
|
||||
// superclass method for this standard text command.
|
||||
_ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender)
|
||||
}
|
||||
}
|
||||
}
|
||||
override func insertNewline(_ sender: Any?) {
|
||||
guard isEditable, !hasMarkedText(), selectedRange().length == 0,
|
||||
let insertion = BASICLanguage.nextLineInsertion(string, at: selectedRange().location) else {
|
||||
super.insertNewline(sender); return
|
||||
}
|
||||
breakUndoCoalescing()
|
||||
insertText(insertion, replacementRange: selectedRange())
|
||||
breakUndoCoalescing()
|
||||
undoManager?.setActionName("Insert BASIC Line")
|
||||
}
|
||||
/// Apply an explicit source edit through AppKit so the ordinary Undo stack,
|
||||
/// source binding, selection and syntax highlighting remain synchronized.
|
||||
@discardableResult func applyEditorAction(_ action: BASICEditorAction, revealReplacementAt offset: Int? = nil) -> Bool {
|
||||
guard isEditable, !hasMarkedText(), string == action.expectedSource else { return false }
|
||||
switch action.operation {
|
||||
case .replace(let source, let undoName):
|
||||
guard source.utf8.count <= BASICLanguage.maximumSourceBytes else { return false }
|
||||
if source != string {
|
||||
breakUndoCoalescing()
|
||||
insertText(source, replacementRange: NSRange(location: 0, length: (string as NSString).length))
|
||||
breakUndoCoalescing()
|
||||
guard string == source else { return false }
|
||||
undoManager?.setActionName(undoName)
|
||||
}
|
||||
if let offset {
|
||||
setSelectedRange(NSRange(location: min(max(0, offset), (source as NSString).length), length: 0))
|
||||
}
|
||||
case .select(let range):
|
||||
let length = (string as NSString).length
|
||||
guard range.location >= 0, range.location <= length,
|
||||
range.length >= 0, range.length <= length - range.location else { return false }
|
||||
setSelectedRange(range)
|
||||
}
|
||||
scrollRangeToVisible(selectedRange())
|
||||
window?.makeFirstResponder(self)
|
||||
return true
|
||||
}
|
||||
override func complete(_ sender:Any?) {
|
||||
guard prepareCompletion() else { return }; super.complete(sender)
|
||||
}
|
||||
@discardableResult func prepareCompletion() -> Bool {
|
||||
sourceForCompletion=nil; completion=nil
|
||||
guard isEditable,!hasMarkedText(),selectedRange().length == 0,
|
||||
let next=BASICLanguage.completion(string,at:selectedRange().location) else {
|
||||
assistance?("Type the beginning of a BASIC keyword, then choose Complete."); return false
|
||||
}
|
||||
sourceForCompletion=string; completion=next; completionOffset=selectedRange().location
|
||||
refreshInlineSuggestion()
|
||||
assistance?("\(next.words.count) BASIC keyword suggestions. Return accepts; Escape cancels.")
|
||||
return true
|
||||
}
|
||||
override var rangeForUserCompletion:NSRange { sourceForCompletion == string ? completion?.range ?? NSRange(location:NSNotFound,length:0) : NSRange(location:NSNotFound,length:0) }
|
||||
override func completions(forPartialWordRange charRange:NSRange,indexOfSelectedItem index:UnsafeMutablePointer<Int>?) -> [String]? {
|
||||
guard sourceForCompletion == string, completion?.range == charRange else { return [] }
|
||||
// Highlight the first choice so Return accepts it immediately.
|
||||
// insertCompletion still refuses provisional list navigation.
|
||||
index?.pointee = 0; return completion?.words
|
||||
}
|
||||
override func insertCompletion(_ word:String,forPartialWordRange charRange:NSRange,movement:Int,isFinal flag:Bool) {
|
||||
guard flag else { return }
|
||||
defer { sourceForCompletion=nil; completion=nil; refreshInlineSuggestion() }
|
||||
guard movement != NSTextMovement.cancel.rawValue,isEditable,!hasMarkedText(),sourceForCompletion == string,
|
||||
selectedRange() == NSRange(location:completionOffset,length:0),completion?.range == charRange,
|
||||
completion?.words.contains(word) == true else { return }
|
||||
breakUndoCoalescing(); insertText(word,replacementRange:charRange); breakUndoCoalescing()
|
||||
undoManager?.setActionName("Complete BASIC Keyword")
|
||||
}
|
||||
override func performKeyEquivalent(with event:NSEvent) -> Bool {
|
||||
let modifiers=event.modifierFlags.intersection([.command,.control,.option,.shift])
|
||||
if event.keyCode == 49,modifiers == [.control] { complete(nil); return true }
|
||||
return super.performKeyEquivalent(with:event)
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual gutter plus the native toolbar action provide mouse and keyboard
|
||||
/// alternatives. Line numbers remain ordinary editable source text.
|
||||
final class BASICBreakpointRuler: BreakpointRuler {
|
||||
private weak var editor: BASICTextView?
|
||||
init(textView: BASICTextView) {
|
||||
editor = textView
|
||||
super.init(scrollView: textView.enclosingScrollView!, orientation: .verticalRuler)
|
||||
clientView = textView; ruleThickness = 30
|
||||
setAccessibilityLabel("BASIC breakpoint gutter")
|
||||
setAccessibilityHelp("Click beside a numbered statement to toggle its breakpoint. The toolbar offers the same action at the insertion point.")
|
||||
}
|
||||
required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
private func targets() -> [(Int, NSRect)] {
|
||||
guard let editor, let layout = editor.layoutManager, let container = editor.textContainer else { return [] }
|
||||
let origin = editor.textContainerOrigin
|
||||
// Horizontal scrolling must not change which rows appear in the gutter.
|
||||
let viewport = NSRect(x: 0, y: editor.visibleRect.minY - origin.y,
|
||||
width: max(1, editor.bounds.width), height: editor.visibleRect.height)
|
||||
let glyphs = layout.glyphRange(forBoundingRect: viewport, in: container)
|
||||
let visible = layout.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil)
|
||||
return editor.numberedRows.compactMap { row in
|
||||
guard NSLocationInRange(row.labelRange.location, visible) else { return nil }
|
||||
let glyph = layout.glyphIndexForCharacter(at: row.labelRange.location)
|
||||
let fragment = layout.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
|
||||
let point = convert(NSPoint(x: 0, y: fragment.midY + editor.textContainerOrigin.y), from: editor)
|
||||
return (row.number, NSRect(x: 8, y: point.y - 6, width: 12, height: 12))
|
||||
}
|
||||
}
|
||||
override var wantsDefaultClipping: Bool { true }
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
// NSRulerView's standard edge treatment can extend outside its frame.
|
||||
// This gutter has no native ruler ticks or markers: draw its own edge.
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSBezierPath(rect: bounds).addClip()
|
||||
drawHashMarksAndLabels(in: dirtyRect)
|
||||
NSColor.separatorColor.setFill()
|
||||
NSRect(x: bounds.maxX - 1, y: bounds.minY, width: 1, height: bounds.height).fill()
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
}
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
NSColor.windowBackgroundColor.setFill(); bounds.fill()
|
||||
guard let editor else { return }
|
||||
for (line, target) in targets() where target.intersects(bounds) {
|
||||
let path = NSBezierPath(ovalIn: target)
|
||||
if editor.breakpointLines.contains(line) { NSColor.systemRed.setFill(); path.fill() }
|
||||
else { NSColor.separatorColor.setStroke(); path.lineWidth = 1; path.stroke() }
|
||||
}
|
||||
}
|
||||
override func visibleRows() -> [Row] {
|
||||
targets().compactMap { line, marker in
|
||||
let hit = marker.insetBy(dx: -8, dy: -3).intersection(bounds)
|
||||
return hit.isEmpty ? nil : (line, hit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct BASICInspectionView: View {
|
||||
@ObservedObject var model: BASICDevelopmentModel
|
||||
let valuesHeight: CGFloat
|
||||
@State private var expanded = true
|
||||
@State private var showingWatches = false
|
||||
var body: some View {
|
||||
Divider()
|
||||
DisclosureGroup(isExpanded: $expanded) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Picker("Inspect", selection: $showingWatches) {
|
||||
Text("Variables").tag(false); Text("Watches").tag(true)
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(width: 210).accessibilityIdentifier("basic.inspector-tabs")
|
||||
Text(model.inspectionStatus).font(.caption).foregroundStyle(.secondary).lineLimit(2)
|
||||
.accessibilityIdentifier("basic.inspection-status")
|
||||
Spacer(minLength: 0)
|
||||
Button { model.refreshInspection() } label: { Image(systemName: "arrow.clockwise") }
|
||||
.accessibilityLabel("Refresh BASIC variables").help("Refresh values at the current BASIC stop")
|
||||
.disabled(!model.inspectionAvailable).accessibilityIdentifier("basic.refresh-variables")
|
||||
}
|
||||
if showingWatches {
|
||||
HStack {
|
||||
TextField("Variable or array element, e.g. NAME$ or A(2)", text: $model.watchEntry)
|
||||
.textFieldStyle(.roundedBorder).onSubmit { model.addWatch() }
|
||||
.accessibilityIdentifier("basic.watch-entry")
|
||||
Button { model.addWatch() } label: { Label("Add", systemImage: "plus") }
|
||||
.disabled(model.watchEntry.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
.accessibilityIdentifier("basic.add-watch")
|
||||
}
|
||||
if let error = model.watchError { Text(error).font(.caption).foregroundStyle(.orange) }
|
||||
}
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 5) {
|
||||
if showingWatches {
|
||||
if model.watches.isEmpty { Text("Watch a variable or a specific array element without changing the program.").foregroundStyle(.secondary) }
|
||||
ForEach(model.watches, id: \.self) { name in
|
||||
HStack(alignment: .top) {
|
||||
Text(name).fontWeight(.medium).frame(width: 160, alignment: .leading)
|
||||
Text(model.watchValue(name)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.accessibilityIdentifier("basic.watch-value.\(name)")
|
||||
Button { model.removeWatch(name) } label: { Image(systemName: "minus.circle") }
|
||||
.buttonStyle(.borderless).help("Remove watch \(name)").accessibilityLabel("Remove watch \(name)")
|
||||
}.font(.system(.callout, design: .monospaced))
|
||||
}
|
||||
} else if model.variables.isEmpty {
|
||||
Text(model.inspectionAvailable ? "Variables appear here as statements assign them." : "Run to a breakpoint or use Step to see current values.")
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
ForEach(model.variables) { variable in BASICVariableView(variable: variable) }
|
||||
}
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 4).padding(.horizontal, 8)
|
||||
}.frame(height: max(36, valuesHeight - (showingWatches ? 60 : 0)))
|
||||
.accessibilityIdentifier("basic.inspector-values")
|
||||
}.padding(.top, 6)
|
||||
} label: {
|
||||
Label("Variables and Watches", systemImage: "list.bullet.rectangle").font(.callout.bold())
|
||||
}.padding(.horizontal, 14).padding(.vertical, 8)
|
||||
}
|
||||
}
|
||||
private struct BASICVariableView: View {
|
||||
let variable: BASICVariable
|
||||
@State private var expanded = false
|
||||
@State private var page = 0
|
||||
private let pageSize = 32
|
||||
private var first: Int { min(page * pageSize, max(0, variable.elements.count - 1) / pageSize * pageSize) }
|
||||
var body: some View {
|
||||
if variable.dimensions.isEmpty {
|
||||
row(variable.name, variable.value)
|
||||
} else {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Button { expanded.toggle() } label: {
|
||||
HStack {
|
||||
Image(systemName: expanded ? "chevron.down" : "chevron.right").frame(width: 12)
|
||||
Text(variable.title).fontWeight(.medium).frame(width: 140, alignment: .leading)
|
||||
Text(variable.value).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.font(.system(.callout, design: .monospaced)).padding(.vertical, 3).contentShape(Rectangle())
|
||||
}.buttonStyle(.plain).accessibilityIdentifier("basic.array.\(variable.name)")
|
||||
.accessibilityLabel("Array \(variable.title)").accessibilityValue(expanded ? "Expanded" : "Collapsed")
|
||||
.help("Show array elements. Bounds are inclusive; subscripts start at zero.")
|
||||
if expanded {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
ForEach(first..<min(first + pageSize, variable.elements.count), id: \.self) { offset in
|
||||
row(variable.elementName(offset), variable.elements[offset])
|
||||
}
|
||||
if variable.elements.count > pageSize {
|
||||
HStack {
|
||||
Button("Previous", systemImage: "chevron.left") { page = max(0, page - 1) }.disabled(first == 0)
|
||||
Text("\(first + 1)–\(min(first + pageSize, variable.elements.count)) of \(variable.elements.count)").font(.caption)
|
||||
Button("Next", systemImage: "chevron.right") { page = first / pageSize + 1 }.disabled(first + pageSize >= variable.elements.count)
|
||||
}
|
||||
}
|
||||
}.padding(.leading, 20)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private func row(_ name: String, _ value: String) -> some View {
|
||||
HStack(alignment: .top) {
|
||||
Text(name).fontWeight(.medium).frame(width: 160, alignment: .leading)
|
||||
Text(value).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.accessibilityIdentifier("basic.variable-value.\(name)")
|
||||
}.font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Editor assistance only. The core's ROM-aware tokenizer remains authoritative.
|
||||
enum BASICLanguage {
|
||||
enum Kind { case keyword, number, string, comment, data }
|
||||
struct Span { let range: NSRange; let kind: Kind; let word: String }
|
||||
struct Completion: Equatable { let range: NSRange; let words: [String] }
|
||||
static let maximumSourceBytes = 1_048_576
|
||||
static let sample = DevelopmentStarterSource.planet(withExtension: "bas")
|
||||
?? "10 REM EARTH OR MARS EXAMPLE MISSING - REINSTALL VCC PLUS\n"
|
||||
// Verified command/function names for the bundled CoCo 3 + Disk BASIC
|
||||
// dictionaries. GOTO/GOSUB are conveniences for the GO + TO/SUB tokens.
|
||||
static let words: [String] = {
|
||||
let names = "FOR GOTO GOSUB GO REM IF DATA PRINT ON INPUT END NEXT DIM READ RUN RESTORE RETURN STOP POKE CONT LIST CLEAR NEW CLOAD CSAVE OPEN CLOSE LLIST SET RESET CLS MOTOR SOUND AUDIO EXEC SKIPF DEL EDIT TRON TROFF DEF LET LINE PCLS PSET PRESET SCREEN PCLEAR COLOR CIRCLE PAINT GET PUT DRAW PCOPY PMODE PLAY DLOAD RENUM TAB TO SUB THEN NOT STEP OFF ELSE USING DIR DRIVE FIELD FILES KILL LOAD LSET MERGE RENAME RSET SAVE WRITE VERIFY UNLOAD DSKINI BACKUP COPY DSKI$ DSKO$ DOS WIDTH PALETTE HSCREEN LPOKE HCLS HCOLOR HPAINT HCIRCLE HLINE HGET HPUT HBUFF HPRINT ERR BRK LOCATE HSTAT HSET HRESET HDRAW CMP RGB ATTR LPEEK BUTTON HPOINT ERNO ERLIN SIN COS TAN ATN LOG EXP SQR SGN ABS INT RND USR PEEK LEN STR$ VAL ASC CHR$ EOF JOYSTK LEFT$ RIGHT$ MID$ POINT INKEY$ MEM INSTR TIMER PPOINT STRING$ CVN FREE LOC LOF MKN$ AS AND OR FN FIX POS HEX$ VARPTR"
|
||||
let unique = Set(names.split(separator: " ").map { String($0) })
|
||||
return unique.sorted { left, right in
|
||||
if left.count == right.count { return left < right }
|
||||
return left.count > right.count
|
||||
}
|
||||
}()
|
||||
|
||||
// Command descriptions and editor hints share the offline reference.
|
||||
// The ROM-aware tokenizer remains authoritative for executable syntax.
|
||||
static let signatures: [String: String] = {
|
||||
guard let catalog = try? BASICReferenceCatalog.bundled.get() else { return [:] }
|
||||
var result: [String: String] = [:]
|
||||
for dialect in [BASICReferenceDialect.common, .disk] {
|
||||
for entry in catalog.entries where entry.dialect == dialect && result[entry.keyword] == nil {
|
||||
result[entry.keyword] = entry.syntax.first
|
||||
}
|
||||
}
|
||||
return result
|
||||
}()
|
||||
/// Quoted strings, comments and DATA values are opaque to completion.
|
||||
static func spans(_ source: String) -> [Span] {
|
||||
guard source.utf8.count <= maximumSourceBytes else { return [] }
|
||||
let u = Array(source.utf16), upper = Array(source.uppercased().utf16)
|
||||
// Case folding can change non-ASCII length. Such text is invalid for the
|
||||
// guest tokenizer but must remain harmless while being edited.
|
||||
guard upper.count == u.count else { return [] }
|
||||
let tokens = words.map { ($0, Array($0.utf16)) }
|
||||
var result: [Span] = [], i = 0
|
||||
func append(_ start: Int, _ end: Int, _ kind: Kind, _ word: String = "") {
|
||||
result.append(Span(range: NSRange(location: start, length: end-start), kind: kind, word: word))
|
||||
}
|
||||
while i < u.count {
|
||||
let start = i
|
||||
if u[i] == 34 {
|
||||
i += 1; while i < u.count && u[i] != 34 && u[i] != 10 && u[i] != 13 { i += 1 }
|
||||
if i < u.count && u[i] == 34 { i += 1 }; append(start,i,.string); continue
|
||||
}
|
||||
if u[i] == 39 {
|
||||
while i < u.count && u[i] != 10 && u[i] != 13 { i += 1 }; append(start,i,.comment); continue
|
||||
}
|
||||
if let token = tokens.first(where: { i+$0.1.count <= upper.count && upper[i..<i+$0.1.count].elementsEqual($0.1) }) {
|
||||
i += token.1.count; append(start,i,.keyword,token.0)
|
||||
if token.0 == "REM" {
|
||||
let from = i; while i < u.count && u[i] != 10 && u[i] != 13 { i += 1 }; append(from,i,.comment)
|
||||
} else if token.0 == "DATA" {
|
||||
let from = i; var quoted = false
|
||||
while i < u.count && u[i] != 10 && u[i] != 13 {
|
||||
if u[i] == 34 { quoted.toggle() }
|
||||
if u[i] == 58 && !quoted { break }; i += 1
|
||||
}; append(from,i,.data)
|
||||
}; continue
|
||||
}
|
||||
if (48...57).contains(u[i]) {
|
||||
i += 1; while i < u.count && ((48...57).contains(u[i]) || u[i] == 46) { i += 1 }
|
||||
append(start,i,.number); continue
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
return result
|
||||
}
|
||||
static func completion(_ source: String, at caret: Int) -> Completion? {
|
||||
let u = Array(source.utf16)
|
||||
guard source.utf8.count <= maximumSourceBytes, caret >= 0, caret <= u.count else { return nil }
|
||||
let tokens = spans(source)
|
||||
guard !tokens.contains(where: { span in
|
||||
switch span.kind {
|
||||
case .string, .comment, .data: return caret > span.range.location && caret <= NSMaxRange(span.range)
|
||||
default: return false
|
||||
}
|
||||
}) else { return nil }
|
||||
func word(_ c: UInt16) -> Bool { (65...90).contains(c) || (97...122).contains(c) || c == 36 }
|
||||
var start = caret, end = caret
|
||||
while start > 0 && word(u[start-1]) { start -= 1 }
|
||||
while end < u.count && word(u[end]) { end += 1 }
|
||||
guard start < caret else { return nil }
|
||||
let prefix = String(decoding: u[start..<caret], as: UTF16.self).uppercased()
|
||||
let matches = words.filter { $0.hasPrefix(prefix) }.sorted()
|
||||
guard !matches.isEmpty else { return nil }
|
||||
return Completion(range: NSRange(location:start,length:end-start),words:matches)
|
||||
}
|
||||
struct InlineCompletion: Equatable {
|
||||
let range: NSRange
|
||||
let word: String
|
||||
let suffix: String
|
||||
}
|
||||
/// Inline previews only occupy empty space at the end of a physical line.
|
||||
/// Ambiguous prefixes continue to use the explicit completion list.
|
||||
static func inlineCompletion(_ source: String, at caret: Int) -> InlineCompletion? {
|
||||
let text = source as NSString
|
||||
guard caret > 0, caret <= text.length,
|
||||
caret == text.length || [10, 13].contains(text.character(at: caret)),
|
||||
let completion = completion(source, at: caret), completion.words.count == 1,
|
||||
NSMaxRange(completion.range) == caret, completion.range.length >= 2,
|
||||
let word = completion.words.first, word.utf16.count > completion.range.length else { return nil }
|
||||
// Avoid offering a keyword for the alphabetic tail of a variable (A1PRI).
|
||||
if completion.range.location > 0 {
|
||||
let prior = text.character(at: completion.range.location - 1)
|
||||
if (48...57).contains(prior) {
|
||||
let line = text.lineRange(for: completion.range)
|
||||
let before = text.substring(with: NSRange(location: line.location, length: completion.range.location - line.location))
|
||||
guard before.allSatisfy({ $0.isNumber || $0 == " " || $0 == "\t" }) else { return nil }
|
||||
}
|
||||
}
|
||||
return InlineCompletion(range: completion.range, word: word,
|
||||
suffix: String(word.dropFirst(completion.range.length)))
|
||||
}
|
||||
|
||||
/// Return at a completed numbered line follows its preceding increment,
|
||||
/// or uses ten. Inserting between lines fits into the available numeric gap.
|
||||
static func nextLineInsertion(_ source: String, at caret: Int) -> String? {
|
||||
let text = source as NSString
|
||||
guard source.utf8.count <= maximumSourceBytes, caret > 0, caret <= text.length else { return nil }
|
||||
let range = text.lineRange(for: NSRange(location: caret, length: 0))
|
||||
var end = NSMaxRange(range)
|
||||
while end > range.location && [10, 13].contains(text.character(at: end - 1)) { end -= 1 }
|
||||
guard caret == end else { return nil }
|
||||
let analysis = analyze(source)
|
||||
guard let current = analysis.lines.first(where: { $0.range.location == range.location }),
|
||||
current.number < 63999 else { return nil }
|
||||
let bodyStart = NSMaxRange(current.labelRange)
|
||||
guard bodyStart < end,
|
||||
!text.substring(with: NSRange(location: bodyStart, length: end - bodyStart))
|
||||
.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
|
||||
let used = Set(analysis.lines.map(\.number))
|
||||
let previous = analysis.lines.last(where: { $0.range.location < range.location })
|
||||
let increment = previous.map { current.number - $0.number }.flatMap { $0 > 0 ? $0 : nil } ?? 10
|
||||
let following = analysis.lines.first(where: { $0.range.location > range.location })
|
||||
if let following, following.number <= current.number { return nil }
|
||||
let limit = min(63999, following.map { $0.number - 1 } ?? 63999)
|
||||
guard limit > current.number else { return nil }
|
||||
let gap = limit - current.number + 1
|
||||
let step = following != nil && increment >= gap ? max(1, gap / 2) : increment
|
||||
var candidate = min(current.number + step, limit)
|
||||
while candidate <= limit && used.contains(candidate) { candidate += 1 }
|
||||
if candidate > limit {
|
||||
candidate = current.number + 1
|
||||
while candidate <= limit && used.contains(candidate) { candidate += 1 }
|
||||
}
|
||||
guard candidate <= limit else { return nil }
|
||||
let newline = source.contains("\r\n") ? "\r\n" : source.contains("\r") && !source.contains("\n") ? "\r" : "\n"
|
||||
return newline + String(candidate) + " "
|
||||
}
|
||||
static func hint(_ source: String, at caret: Int) -> String? {
|
||||
let text = source as NSString
|
||||
guard caret >= 0, caret <= text.length, source.utf8.count <= maximumSourceBytes else { return nil }
|
||||
let line = text.lineRange(for: NSRange(location:caret,length:0))
|
||||
let prior = spans(source).filter { $0.range.location >= line.location && NSMaxRange($0.range) <= caret && $0.kind == .keyword }
|
||||
// These tokens continue the enclosing statement rather than introducing
|
||||
// a new signature. They still have independently browsable help entries.
|
||||
let fragments: Set<String> = ["TO", "STEP", "THEN", "ELSE", "AS", "AND", "OR", "NOT"]
|
||||
return prior.reversed().filter { !fragments.contains($0.word) }.compactMap { signatures[$0.word] }.first
|
||||
}
|
||||
}
|
||||
|
||||
extension BASICLanguage {
|
||||
enum Severity { case error, warning }
|
||||
struct Diagnostic: Identifiable, Equatable {
|
||||
let row: Int
|
||||
let range: NSRange
|
||||
let message: String
|
||||
let severity: Severity
|
||||
var id: String { "\(row):\(range.location):\(message)" }
|
||||
}
|
||||
struct NumberedLine {
|
||||
let row: Int, number: Int
|
||||
let range: NSRange, labelRange: NSRange
|
||||
}
|
||||
struct Analysis {
|
||||
let lines: [NumberedLine]
|
||||
let diagnostics: [Diagnostic]
|
||||
var hasErrors: Bool { diagnostics.contains { $0.severity == .error } }
|
||||
}
|
||||
struct RenumberResult { let source: String; let lineCount: Int; let changedReferences: Int }
|
||||
struct AssistanceError: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
private struct Reference { let range: NSRange; let target: Int }
|
||||
private struct Inspection { var lines: [NumberedLine] = []; var diagnostics: [Diagnostic] = []; var references: [Reference] = [] }
|
||||
private struct Atom {
|
||||
let text: String, range: NSRange
|
||||
let numeric: Bool
|
||||
}
|
||||
// Exact command-before-function ordering from CoCo 3/Disk BASIC. This is
|
||||
// deliberately separate from completion's longest-spelling-first list.
|
||||
// An unmatched identifier consumes its alphanumeric tail, so XGOTO is a
|
||||
// variable, while FORI=1TO5 contains FOR and TO. Function names stay atomic.
|
||||
private static let scanWords = ("FOR GO REM ' ELSE IF DATA PRINT ON INPUT END NEXT DIM READ RUN RESTORE RETURN STOP POKE CONT LIST CLEAR NEW CLOAD CSAVE OPEN CLOSE LLIST SET RESET CLS MOTOR SOUND AUDIO EXEC SKIPF TAB( TO SUB THEN NOT STEP OFF + - * / ^ AND OR > = < DEL EDIT TRON TROFF DEF LET LINE PCLS PSET PRESET SCREEN PCLEAR COLOR CIRCLE PAINT GET PUT DRAW PCOPY PMODE PLAY DLOAD RENUM FN USING DIR DRIVE FIELD FILES KILL LOAD LSET MERGE RENAME RSET SAVE WRITE VERIFY UNLOAD DSKINI BACKUP COPY DSKI$ DSKO$ DOS WIDTH PALETTE HSCREEN LPOKE HCLS HCOLOR HPAINT HCIRCLE HLINE HGET HPUT HBUFF HPRINT ERR BRK LOCATE HSTAT HSET HRESET HDRAW CMP RGB ATTR SGN INT ABS USR RND SIN PEEK LEN STR$ VAL ASC CHR$ EOF JOYSTK LEFT$ RIGHT$ MID$ POINT INKEY$ MEM ATN COS TAN EXP FIX LOG POS SQR HEX$ VARPTR INSTR TIMER PPOINT STRING$ CVN FREE LOC LOF MKN$ AS LPEEK BUTTON HPOINT ERNO ERLIN").split(separator: " ").map { (String($0), Array($0.utf16)) }
|
||||
private static let scanWordsByFirst = Dictionary(grouping: scanWords, by: { $0.1[0] })
|
||||
private static func isDigit(_ c: UInt16) -> Bool { (48...57).contains(c) }
|
||||
private static func isAlpha(_ c: UInt16) -> Bool { (65...90).contains(c) || (97...122).contains(c) }
|
||||
private static func scan(_ units: [UInt16], from: Int, to: Int) -> [Atom] {
|
||||
var result: [Atom] = [], i = from
|
||||
func add(_ text: String, _ start: Int, _ end: Int, numeric: Bool = false) {
|
||||
result.append(.init(text: text, range: NSRange(location:start,length:end-start), numeric:numeric))
|
||||
}
|
||||
while i < to {
|
||||
let begin = i, c = units[i]
|
||||
if c == 32 || c == 9 { i += 1; continue }
|
||||
if c == 34 {
|
||||
i += 1; while i < to && units[i] != 34 { i += 1 }
|
||||
if i < to { i += 1 }; add("<string>",begin,i); continue
|
||||
}
|
||||
if c == 39 { break }
|
||||
if isDigit(c) {
|
||||
i += 1; while i < to && isDigit(units[i]) { i += 1 }
|
||||
add(String(decoding:units[begin..<i],as:UTF16.self),begin,i,numeric:true); continue
|
||||
}
|
||||
if let word = scanWordsByFirst[c >= 97 && c <= 122 ? c-32 : c]?.first(where: { word in
|
||||
i+word.1.count <= to && zip(units[i..<i+word.1.count],word.1).allSatisfy { raw, target in
|
||||
(raw >= 97 && raw <= 122 ? raw-32 : raw) == target
|
||||
}
|
||||
}) {
|
||||
i += word.1.count
|
||||
if word.0 == "REM" { break }
|
||||
add(word.0,begin,i)
|
||||
if word.0 == "DATA" {
|
||||
var quoted = false
|
||||
while i < to {
|
||||
if units[i] == 34 { quoted.toggle() }
|
||||
if units[i] == 58 && !quoted { break }; i += 1
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
i += 1
|
||||
if isAlpha(c) {
|
||||
while i < to && (isAlpha(units[i]) || isDigit(units[i])) { i += 1 }
|
||||
// $ belongs to the variable name, never a reference operand.
|
||||
if i < to && units[i] == 36 { i += 1 }
|
||||
}
|
||||
add(String(decoding:units[begin..<i],as:UTF16.self).uppercased(),begin,i)
|
||||
}
|
||||
return result
|
||||
}
|
||||
private static func inspect(_ source: String) -> Inspection {
|
||||
var output = Inspection()
|
||||
let units = Array(source.utf16)
|
||||
func report(_ row: Int, _ range: NSRange, _ text: String, _ severity: Severity = .error) {
|
||||
output.diagnostics.append(.init(row:row,range:range,message:text,severity:severity))
|
||||
}
|
||||
guard source.utf8.count <= maximumSourceBytes else {
|
||||
report(1,NSRange(location:0,length:0),"The source exceeds the 1 MiB editor limit."); return output
|
||||
}
|
||||
var at = 0, row = 0, bodies: [(NumberedLine,Int,Int)] = [], seen: Set<Int> = []
|
||||
while at < units.count {
|
||||
row += 1; let begin = at
|
||||
while at < units.count && units[at] != 10 && units[at] != 13 { at += 1 }
|
||||
let end = at
|
||||
if at < units.count { let newline = units[at]; at += 1; if newline == 13 && at < units.count && units[at] == 10 { at += 1 } }
|
||||
var first = begin
|
||||
while first < end && (units[first] == 32 || units[first] == 9) { first += 1 }
|
||||
if first == end { continue }
|
||||
if let invalid = (begin..<end).first(where: { units[$0] != 9 && (units[$0] < 32 || units[$0] > 126) }) {
|
||||
report(row,(source as NSString).rangeOfComposedCharacterSequence(at:invalid),"Use printable ASCII characters (tabs are allowed).")
|
||||
}
|
||||
if end-first > 249 { report(row,NSRange(location:first,length:end-first),"BASIC input lines may contain at most 249 characters.") }
|
||||
guard isDigit(units[first]) else { report(row,NSRange(location:first,length:end-first),"Begin this line with a BASIC line number."); continue }
|
||||
var after = first; while after < end && isDigit(units[after]) { after += 1 }
|
||||
let label = NSRange(location:first,length:after-first)
|
||||
guard let number = Int(String(decoding:units[first..<after],as:UTF16.self)), number <= 63999 else {
|
||||
report(row,label,"Line numbers must be between 0 and 63999."); continue
|
||||
}
|
||||
let line = NumberedLine(row:row,number:number,range:NSRange(location:begin,length:end-begin),labelRange:label)
|
||||
output.lines.append(line)
|
||||
if !seen.insert(number).inserted { report(row,label,"Line \(number) is defined more than once.") }
|
||||
while after < end && (units[after] == 32 || units[after] == 9) { after += 1 }
|
||||
if after == end { report(row,label,"A bare number deletes a BASIC line; add a statement or remove this row before renumbering.",.warning) }
|
||||
else { bodies.append((line,after,end)) }
|
||||
}
|
||||
let defined = Set(bodies.map { $0.0.number }), sorted = defined.sorted()
|
||||
func lowerBound(_ value: Int) -> Int {
|
||||
var lo=0, hi=sorted.count
|
||||
while lo<hi { let mid=(lo+hi)/2; if sorted[mid]<value { lo=mid+1 } else { hi=mid } }
|
||||
return lo
|
||||
}
|
||||
for (line,begin,end) in bodies {
|
||||
let atoms = scan(units,from:begin,to:end)
|
||||
var i = 0, on = false, trap = false
|
||||
func boundary(_ index: Int) -> Bool { index >= atoms.count || [":","ELSE"].contains(atoms[index].text) }
|
||||
func unsupported(_ atom: Atom) { report(line.row,atom.range,"Renumber cannot safely interpret this line-number operand; use a literal line number.",.warning) }
|
||||
func reference(_ index: Int, disableZero: Bool = false) {
|
||||
let atom = atoms[index]
|
||||
guard let target = Int(atom.text), target <= 63999 else { report(line.row,atom.range,"Referenced line number is outside 0–63999."); return }
|
||||
if disableZero && target == 0 { return } // ON ERR/BRK GOTO 0 disables the trap.
|
||||
if !defined.contains(target) { report(line.row,atom.range,"Referenced line \(target) is not present in this program.",.warning) }
|
||||
output.references.append(.init(range:atom.range,target:target))
|
||||
}
|
||||
while i < atoms.count {
|
||||
let atom = atoms[i], word = atom.text
|
||||
if word == ":" || word == "THEN" || word == "ELSE" { on = false; trap = false }
|
||||
if word == "ON" { on = true; trap = i+1 < atoms.count && ["ERR","BRK"].contains(atoms[i+1].text) }
|
||||
if word == "RENUM" { report(line.row,atom.range,"This program renumbers itself with RENUM; automatic editor renumbering is unsafe.",.warning) }
|
||||
if word == "GO" {
|
||||
var operand = i+1
|
||||
guard operand < atoms.count && ["TO","SUB"].contains(atoms[operand].text) else { unsupported(atom); i += 1; continue }
|
||||
operand += 1
|
||||
var count = 0
|
||||
while operand < atoms.count && atoms[operand].numeric {
|
||||
reference(operand,disableZero:trap); count += 1; operand += 1
|
||||
if on && !trap && operand < atoms.count && atoms[operand].text == "," { operand += 1; continue }
|
||||
break
|
||||
}
|
||||
if count == 0 || !boundary(operand) || (operand > 0 && atoms[operand-1].text == ",") { unsupported(atom) }
|
||||
on = false; trap = false; i = max(i+1,operand); continue
|
||||
}
|
||||
if ["THEN","ELSE","RUN","EDIT"].contains(word) {
|
||||
let operand = i+1
|
||||
if operand < atoms.count && atoms[operand].numeric {
|
||||
reference(operand)
|
||||
if !boundary(operand+1) { unsupported(atom) }
|
||||
i = operand+1; continue
|
||||
} else if word == "EDIT" || (word == "RUN" && !boundary(operand) && atoms[operand].text != "<string>") { unsupported(atom) }
|
||||
}
|
||||
if ["LIST","LLIST","DEL"].contains(word) {
|
||||
var p = i+1, lowerIndex: Int?, upperIndex: Int?, ranged = false
|
||||
if p < atoms.count && atoms[p].numeric { lowerIndex=p; p += 1 }
|
||||
if p < atoms.count && atoms[p].text == "-" {
|
||||
ranged=true; p += 1
|
||||
if p < atoms.count && atoms[p].numeric { upperIndex=p; p += 1 }
|
||||
}
|
||||
if !boundary(p) { unsupported(atom) }
|
||||
else if lowerIndex != nil || upperIndex != nil {
|
||||
let low = lowerIndex.map { Int(atoms[$0].text) ?? 64000 } ?? 0
|
||||
let high = upperIndex.map { Int(atoms[$0].text) ?? 64000 } ?? (ranged ? 63999 : low)
|
||||
if low > 63999 || high > 63999 { report(line.row,atom.range,"Line range is outside 0–63999.") }
|
||||
else {
|
||||
// Bounds need not name a real line. Preserve the set
|
||||
// of included lines, not just exact endpoint matches.
|
||||
let firstIndex=lowerBound(low), afterLast=lowerBound(high+1)
|
||||
if firstIndex < afterLast {
|
||||
let first=sorted[firstIndex], last=sorted[afterLast-1]
|
||||
if let index=lowerIndex { output.references.append(.init(range:atoms[index].range,target:first)) }
|
||||
if let index=upperIndex { output.references.append(.init(range:atoms[index].range,target:last)) }
|
||||
} else { report(line.row,atom.range,"This line range selects no program lines; review it before renumbering.",.warning) }
|
||||
}
|
||||
}
|
||||
i = max(i+1,p); continue
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
static func analyze(_ source: String) -> Analysis {
|
||||
let result = inspect(source)
|
||||
return Analysis(lines:result.lines,diagnostics:result.diagnostics)
|
||||
}
|
||||
static func lineRange(for number: Int, in source: String) -> NSRange? {
|
||||
let matches = analyze(source).lines.filter { $0.number == number }
|
||||
return matches.count == 1 ? matches.first?.range : nil
|
||||
}
|
||||
/// Numeric program order determines numbering; physical rows, blank lines,
|
||||
/// comments, string/data literals and newline style remain unchanged.
|
||||
static func renumber(_ source: String, start: Int = 10, step: Int = 10) throws -> RenumberResult {
|
||||
guard (0...63999).contains(start), (1...63999).contains(step) else {
|
||||
throw AssistanceError(message:"Choose a start from 0 to 63999 and a positive increment up to 63999.")
|
||||
}
|
||||
let result = inspect(source)
|
||||
if let issue = result.diagnostics.first { throw AssistanceError(message:"Row \(issue.row): \(issue.message)") }
|
||||
let ordered = result.lines.sorted { $0.number < $1.number }
|
||||
guard ordered.count <= 1 || ordered.count-1 <= (63999-start)/step else { throw AssistanceError(message:"The new line numbers would exceed 63999.") }
|
||||
let mapping = Dictionary(uniqueKeysWithValues:ordered.enumerated().map { ($0.element.number,start+$0.offset*step) })
|
||||
var edits = result.lines.map { ($0.labelRange,String(mapping[$0.number]!)) }
|
||||
var changed = 0
|
||||
for ref in result.references {
|
||||
guard let target = mapping[ref.target] else { throw AssistanceError(message:"Referenced line \(ref.target) is missing.") }
|
||||
if (source as NSString).substring(with:ref.range) != String(target) { changed += 1 }
|
||||
edits.append((ref.range,String(target)))
|
||||
}
|
||||
let updated = NSMutableString(string:source)
|
||||
for (range,text) in edits.sorted(by: { $0.0.location > $1.0.location }) { updated.replaceCharacters(in:range,with:text) }
|
||||
let newSource = updated as String
|
||||
// Wider line numbers can make a previously valid line too long.
|
||||
if let issue=analyze(newSource).diagnostics.first(where: { $0.severity == .error }) { throw AssistanceError(message:"Renumbering would make row \(issue.row) invalid: \(issue.message)") }
|
||||
return .init(source:newSource,lineCount:ordered.count,changedReferences:changed)
|
||||
}
|
||||
}
|
||||
|
||||
// Values are copied from a stopped interpreter. Watches never call BASIC.
|
||||
struct BASICVariable: Identifiable, Equatable, Sendable {
|
||||
let name: String
|
||||
let kind: String
|
||||
let value: String
|
||||
let address: Int
|
||||
let dimensions: [Int]
|
||||
let elements: [String]
|
||||
var id: String { name + (dimensions.isEmpty ? "" : "()") }
|
||||
var title: String { dimensions.isEmpty ? name : name + "(" + dimensions.map { String($0 - 1) }.joined(separator: ",") + ")" }
|
||||
init?(_ row: [String: Any]) {
|
||||
guard let name = row["name"] as? String, let kind = row["kind"] as? String,
|
||||
let value = row["value"] as? String, let address = row["address"] as? Int,
|
||||
let dimensions = row["dimensions"] as? [Int], let elements = row["elements"] as? [String] else { return nil }
|
||||
self.name = name; self.kind = kind; self.value = value; self.address = address
|
||||
self.dimensions = dimensions; self.elements = elements
|
||||
}
|
||||
func elementName(_ offset: Int) -> String {
|
||||
var remainder = offset
|
||||
let indices = dimensions.map { length -> String in
|
||||
defer { remainder /= length }; return String(remainder % length)
|
||||
}
|
||||
return name + "(" + indices.joined(separator: ",") + ")"
|
||||
}
|
||||
}
|
||||
struct BASICWatch: Equatable, Sendable {
|
||||
let name: String
|
||||
let indices: [Int]?
|
||||
var canonical: String { name + (indices.map { "(" + $0.map(String.init).joined(separator: ",") + ")" } ?? "") }
|
||||
init?(_ text: String) {
|
||||
// Deliberately no expressions, functions, assignments or device access.
|
||||
let compact = text.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
|
||||
guard compact.count <= 256, let match = compact.range(of: #"^[A-Z][A-Z0-9]*\$?(\( *[0-9]+ *(, *[0-9]+ *)*\))?$"#, options: .regularExpression) else { return nil }
|
||||
guard match == compact.startIndex..<compact.endIndex else { return nil }
|
||||
let parts = compact.split(separator: "(", maxSplits: 1)
|
||||
let identifier = String(parts[0]), string = identifier.hasSuffix("$")
|
||||
guard !BASICLanguage.words.contains(where: { identifier.hasPrefix($0) }) else { return nil }
|
||||
name = String((string ? String(identifier.dropLast()) : identifier).prefix(2)) + (string ? "$" : "")
|
||||
if parts.count == 2 {
|
||||
let values = parts[1].dropLast().split(separator: ",").map { Int($0.trimmingCharacters(in: .whitespaces)) }
|
||||
guard !values.isEmpty, values.allSatisfy({ $0 != nil && $0! <= 32767 }) else { return nil }
|
||||
indices = values.compactMap { $0 }
|
||||
} else { indices = nil }
|
||||
}
|
||||
func value(in variables: [BASICVariable]) -> String {
|
||||
guard let variable = variables.first(where: { $0.name == name && $0.dimensions.isEmpty == (indices == nil) }) else {
|
||||
return indices == nil ? "Not assigned" : "Not dimensioned"
|
||||
}
|
||||
guard let indices else { return variable.value }
|
||||
guard indices.count == variable.dimensions.count else { return "Wrong number of subscripts" }
|
||||
var offset = 0, stride = 1
|
||||
for (index, length) in zip(indices, variable.dimensions) {
|
||||
guard index >= 0, index < length else { return "Subscript out of range" }
|
||||
offset += index * stride; stride *= length
|
||||
}
|
||||
guard offset < variable.elements.count else { return "Unavailable" }
|
||||
return variable.elements[offset]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// The ROM family which supplies a command. Common includes CoCo 3 Super Extended BASIC.
|
||||
enum BASICReferenceDialect: String, Codable, CaseIterable, Sendable {
|
||||
case common, disk, rgbdos, sdcdos
|
||||
|
||||
var displayName: String {
|
||||
switch self {
|
||||
case .common: return "Common BASIC"
|
||||
case .disk: return "Disk BASIC"
|
||||
case .rgbdos: return "RGB-DOS"
|
||||
case .sdcdos: return "SDC-DOS"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum BASICReferenceWork: String, Codable, CaseIterable, Sendable {
|
||||
case basicGuide, diskGuide, rgbdos, sdcGuide
|
||||
|
||||
var citation: String {
|
||||
switch self {
|
||||
case .basicGuide: return "Tandy Corporation. Tandy Color Computer 3 BASIC Quick Reference Guide. 1986."
|
||||
case .diskGuide: return "Color Computer Disk BASIC Quick Reference Guide. InterTAN Canada Ltd., 1987."
|
||||
case .rgbdos: return "Krupski, Roger, Joe Scinta, Greg Miller, and Colin J. Stearman. RGB-DOS. Ken-Ton Electronics."
|
||||
case .sdcGuide: return "Lindner, tim, producer. CoCo SDC User Guide. Fourth version, February 2023. Based on Brian Blake’s original manual."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BASICReferenceEntry: Codable, Identifiable, Sendable {
|
||||
let id: String
|
||||
let keyword: String
|
||||
let title: String
|
||||
let category: String
|
||||
let dialect: BASICReferenceDialect
|
||||
let summary: String
|
||||
let syntax: [String]
|
||||
let parameters: [String]
|
||||
/// A short command fragment, which may need setup or input. Not an executable test.
|
||||
let sample: String
|
||||
let exampleID: String?
|
||||
let related: [String]
|
||||
let notes: [String]
|
||||
let source: BASICReferenceWork
|
||||
let sourcePage: String?
|
||||
|
||||
var citation: String {
|
||||
guard let location = sourcePage, !location.isEmpty else { return source.citation }
|
||||
guard location.first?.isNumber == true else { return source.citation + " " + location + "." }
|
||||
let plural = location.contains("-") || location.contains(",")
|
||||
return source.citation + (plural ? " pp. " : " p. ") + location.replacingOccurrences(of: "-", with: "–") + "."
|
||||
}
|
||||
}
|
||||
|
||||
struct BASICReferenceExample: Codable, Identifiable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let summary: String
|
||||
/// Complete, numbered source that is opened in the editor, never implicitly run.
|
||||
let source: String
|
||||
let expectedOutput: String
|
||||
let dialect: BASICReferenceDialect
|
||||
}
|
||||
|
||||
struct BASICReferenceCatalog: Codable, Sendable {
|
||||
let entries: [BASICReferenceEntry]
|
||||
let examples: [BASICReferenceExample]
|
||||
|
||||
enum CatalogError: LocalizedError {
|
||||
case missingResource
|
||||
case invalidContent(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingResource:
|
||||
return "The BASIC Quick Reference is missing from this app. Reinstall a complete copy of VCC Plus."
|
||||
case .invalidContent(let detail):
|
||||
return "The BASIC Quick Reference could not be read: \(detail)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func load(from url: URL) throws -> BASICReferenceCatalog {
|
||||
let catalog = try JSONDecoder().decode(Self.self, from: Data(contentsOf: url))
|
||||
try catalog.validate()
|
||||
return catalog
|
||||
}
|
||||
|
||||
/// Preserve failures so the reference window can explain a damaged installation.
|
||||
static let bundled: Result<BASICReferenceCatalog, Error> = Result {
|
||||
let bundles = [Bundle.main, Bundle(for: BASICReferenceBundleMarker.self)]
|
||||
guard let url = bundles.compactMap({ $0.url(forResource: "BASICReference", withExtension: "json") }).first else {
|
||||
throw CatalogError.missingResource
|
||||
}
|
||||
return try load(from: url)
|
||||
}
|
||||
|
||||
private func validate() throws {
|
||||
guard !entries.isEmpty else { throw CatalogError.invalidContent("there are no reference entries.") }
|
||||
let entryIDs = Set(entries.map(\.id))
|
||||
let exampleIDs = Set(examples.map(\.id))
|
||||
guard entryIDs.count == entries.count, exampleIDs.count == examples.count else {
|
||||
throw CatalogError.invalidContent("an entry or example identifier is duplicated.")
|
||||
}
|
||||
for entry in entries {
|
||||
guard !entry.id.isEmpty, !entry.keyword.isEmpty, !entry.title.isEmpty,
|
||||
!entry.category.isEmpty, !entry.summary.isEmpty, !entry.syntax.isEmpty,
|
||||
!entry.syntax.contains(where: \.isEmpty) else {
|
||||
throw CatalogError.invalidContent("entry \(entry.id) is incomplete.")
|
||||
}
|
||||
guard entry.related.allSatisfy(entryIDs.contains),
|
||||
entry.exampleID.map(exampleIDs.contains) ?? true else {
|
||||
throw CatalogError.invalidContent("entry \(entry.id) has an unresolved reference.")
|
||||
}
|
||||
}
|
||||
for example in examples {
|
||||
guard !example.id.isEmpty, !example.title.isEmpty, !example.summary.isEmpty,
|
||||
!example.source.isEmpty, !example.expectedOutput.isEmpty else {
|
||||
throw CatalogError.invalidContent("example \(example.id) is incomplete.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class BASICReferenceBundleMarker: NSObject {}
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Resolves explicit Quick Help requests without interpreting or changing a
|
||||
/// program. Offsets use NSTextView's UTF-16 convention, just like editor spans.
|
||||
enum BASICReferenceContext {
|
||||
private struct Token {
|
||||
var keyword: String
|
||||
var range: NSRange
|
||||
}
|
||||
|
||||
static func keyword(in source: String, at offset: Int) -> String? {
|
||||
let text = source as NSString
|
||||
guard source.utf8.count <= BASICLanguage.maximumSourceBytes,
|
||||
offset >= 0, offset <= text.length, text.length > 0 else { return nil }
|
||||
let spans = BASICLanguage.spans(source)
|
||||
let opaque = spans.filter { [.string, .comment, .data].contains($0.kind) }
|
||||
// In literals, comments and DATA values, words are data rather than
|
||||
// commands. An unfinished literal at EOF remains opaque at its end.
|
||||
for span in opaque {
|
||||
if NSLocationInRange(offset, span.range) { return nil }
|
||||
if span.range.length > 0 && offset == text.length && offset == NSMaxRange(span.range) {
|
||||
if span.kind != .string || text.character(at: text.length - 1) != 34 { return nil }
|
||||
}
|
||||
}
|
||||
let line = text.lineRange(for: NSRange(location: offset, length: 0))
|
||||
let units = Array(source.utf16)
|
||||
func isOpaque(_ at: Int) -> Bool { opaque.contains { NSLocationInRange(at, $0.range) } }
|
||||
func whitespace(_ at: Int) -> Bool { units[at] == 32 || units[at] == 9 }
|
||||
var start = line.location, end = NSMaxRange(line)
|
||||
while end > start && [10, 13].contains(units[end - 1]) { end -= 1 }
|
||||
guard start < end else { return nil }
|
||||
for at in start..<min(offset, end) where units[at] == 58 && !isOpaque(at) { start = at + 1 }
|
||||
if offset < end, units[offset] == 58, !isOpaque(offset) { return nil }
|
||||
if offset < end {
|
||||
for at in offset..<end where units[at] == 58 && !isOpaque(at) { end = at; break }
|
||||
}
|
||||
var tokens = spans.filter { $0.kind == .keyword && $0.range.location >= start && $0.range.location < end }
|
||||
.map { Token(keyword: $0.word, range: $0.range) }
|
||||
// Several public command spellings are composed from shorter ROM
|
||||
// tokens. Keep their reference entries distinct from their prefixes.
|
||||
var merged: [Token] = [], index = 0
|
||||
let pairs = ["GO TO": "GOTO", "GO SUB": "GOSUB", "LINE INPUT": "LINE INPUT",
|
||||
"DEF FN": "DEF FN", "ON ERR": "ON ERR", "PRINT USING": "PRINT USING"]
|
||||
while index < tokens.count {
|
||||
var token = tokens[index]
|
||||
if index + 1 < tokens.count {
|
||||
let next = tokens[index + 1], gap = NSMaxRange(token.range)..<tokens[index + 1].range.location
|
||||
if gap.allSatisfy(whitespace), let combined = pairs[token.keyword + " " + next.keyword] {
|
||||
token.keyword = combined; token.range.length = NSMaxRange(next.range) - token.range.location
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
let after = NSMaxRange(token.range)
|
||||
if ["LOAD", "SAVE", "CLOAD", "CSAVE"].contains(token.keyword), after < end,
|
||||
units[after] == 77 || units[after] == 109 {
|
||||
token.keyword += "M"; token.range.length += 1
|
||||
}
|
||||
if token.keyword == "PRINT" {
|
||||
var at = after
|
||||
while at < end && whitespace(at) { at += 1 }
|
||||
if at < end && units[at] == 64 {
|
||||
token.keyword = "PRINT@"; token.range.length = at + 1 - token.range.location
|
||||
}
|
||||
}
|
||||
merged.append(token); index += 1
|
||||
}
|
||||
tokens = merged
|
||||
if let exact = tokens.first(where: { NSLocationInRange(offset, $0.range) }) { return exact.keyword }
|
||||
if let left = tokens.first(where: { NSMaxRange($0.range) == offset }) { return left.keyword }
|
||||
// THEN and ELSE can introduce another statement without a colon. If
|
||||
// the branch contains only a destination line, retain the IF topic.
|
||||
var statementStart = start
|
||||
if let branch = tokens.last(where: { ["THEN", "ELSE"].contains($0.keyword) && NSMaxRange($0.range) < offset }) {
|
||||
var following = NSMaxRange(branch.range)
|
||||
while following < end && whitespace(following) { following += 1 }
|
||||
if following < end && !(48...57).contains(units[following]) { statementStart = following }
|
||||
}
|
||||
while statementStart < end && whitespace(statementStart) { statementStart += 1 }
|
||||
if statementStart == line.location || text.substring(with: NSRange(location: line.location, length: statementStart - line.location)).allSatisfy({ $0 == " " || $0 == "\t" }) {
|
||||
while statementStart < end && (48...57).contains(units[statementStart]) { statementStart += 1 }
|
||||
while statementStart < end && whitespace(statementStart) { statementStart += 1 }
|
||||
}
|
||||
guard offset >= statementStart else { return nil }
|
||||
if let first = tokens.first(where: { $0.range.location >= statementStart }), first.range.location == statementStart { return first.keyword }
|
||||
// Assignment statements can omit LET; an argument position within one
|
||||
// still has a useful help topic. A function name itself wins above.
|
||||
let prefix = text.substring(with: NSRange(location: statementStart, length: min(offset, end) - statementStart))
|
||||
return prefix.contains("=") ? "LET" : nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
extension MachineModel {
|
||||
var basicReferenceDialect: BASICReferenceDialect? {
|
||||
switch usageProfile {
|
||||
case .diskBasic: return .disk
|
||||
case .hardDriveBasic: return .rgbdos
|
||||
case .cocoSDC: return .sdcdos
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BASICReferenceHost: View {
|
||||
let result: Result<BASICReferenceModel, Error>
|
||||
@ObservedObject var machine: MachineModel
|
||||
let showManualTopic: (BASICReferenceEntry) -> Void
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
var body: some View {
|
||||
switch result {
|
||||
case .success(let reference):
|
||||
BASICReferenceView(model: reference, activeDialect: machine.basicReferenceDialect) { entry in
|
||||
showManualTopic(entry)
|
||||
openWindow(id: "manual-library")
|
||||
} openExample: { example in
|
||||
openWindow(id: "basic-example", value: example.id)
|
||||
}
|
||||
case .failure(let error):
|
||||
ContentUnavailableView {
|
||||
Label("BASIC Reference Unavailable", systemImage: "book.closed")
|
||||
} description: {
|
||||
Text("The bundled reference could not be read. \(error.localizedDescription)")
|
||||
}.frame(minWidth: 580, minHeight: 400)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// A deliberate lookup changes the selected topic. The editor never drives this
|
||||
/// model continuously, so a reference stays put while the user reads and types.
|
||||
@MainActor
|
||||
final class BASICReferenceModel: ObservableObject {
|
||||
let catalog: BASICReferenceCatalog
|
||||
@Published var selectedID: String?
|
||||
@Published var search = "" { didSet { reconcileSelection() } }
|
||||
@Published var category: String? { didSet { reconcileSelection() } }
|
||||
|
||||
init(catalog: BASICReferenceCatalog) {
|
||||
self.catalog = catalog
|
||||
selectedID = catalog.entries.first(where: { $0.id == "PRINT" })?.id ?? catalog.entries.first?.id
|
||||
}
|
||||
|
||||
var categories: [String] { Set(catalog.entries.map(\.category)).sorted() }
|
||||
var filteredEntries: [BASICReferenceEntry] {
|
||||
let terms = search.split(whereSeparator: \.isWhitespace).map(String.init)
|
||||
return catalog.entries.filter { entry in
|
||||
guard category == nil || category == entry.category else { return false }
|
||||
let searchable = [entry.title, entry.keyword, entry.summary, entry.category, entry.dialect.displayName].joined(separator: " ")
|
||||
return terms.allSatisfy { searchable.localizedCaseInsensitiveContains($0) }
|
||||
}.sorted {
|
||||
let comparison = $0.title.localizedStandardCompare($1.title)
|
||||
return comparison == .orderedSame ? $0.id < $1.id : comparison == .orderedAscending
|
||||
}
|
||||
}
|
||||
var selectedEntry: BASICReferenceEntry? { entry(id: selectedID) }
|
||||
func entry(id: String?) -> BASICReferenceEntry? {
|
||||
guard let id else { return nil }
|
||||
return catalog.entries.first { $0.id == id }
|
||||
}
|
||||
func example(for entry: BASICReferenceEntry) -> BASICReferenceExample? {
|
||||
guard let id = entry.exampleID else { return nil }
|
||||
return catalog.examples.first { $0.id == id }
|
||||
}
|
||||
func relatedEntry(_ identifier: String) -> BASICReferenceEntry? {
|
||||
entry(id: identifier) ?? catalog.entries.first { $0.keyword.caseInsensitiveCompare(identifier) == .orderedSame }
|
||||
}
|
||||
func select(_ entry: BASICReferenceEntry) {
|
||||
search = ""; category = nil; selectedID = entry.id
|
||||
}
|
||||
func show(keyword: String, dialect: BASICReferenceDialect? = nil) {
|
||||
let key = keyword.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
|
||||
let candidates = catalog.entries.filter { $0.keyword.uppercased() == key || $0.id.uppercased() == key }
|
||||
let match = candidates.first { $0.dialect == dialect }
|
||||
?? candidates.first { $0.dialect == .common }
|
||||
?? candidates.first { $0.dialect == .disk }
|
||||
?? candidates.first
|
||||
if let match { select(match) }
|
||||
else { category = nil; search = key }
|
||||
}
|
||||
func showError(code: String) {
|
||||
let key = code.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
|
||||
if let match = entry(id: "ERROR." + key) { select(match) }
|
||||
else { show(keyword: key) }
|
||||
}
|
||||
private func reconcileSelection() {
|
||||
let entries = filteredEntries
|
||||
if !entries.contains(where: { $0.id == selectedID }) { selectedID = entries.first?.id }
|
||||
}
|
||||
}
|
||||
|
||||
struct BASICReferenceView: View {
|
||||
@ObservedObject var model: BASICReferenceModel
|
||||
let activeDialect: BASICReferenceDialect?
|
||||
let openManualTopic: (BASICReferenceEntry) -> Void
|
||||
let openExample: (BASICReferenceExample) -> Void
|
||||
@FocusState private var searchFocused: Bool
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "book.closed").font(.largeTitle).foregroundStyle(.tint)
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("BASIC Quick Reference").font(.title2.bold())
|
||||
Text("Commands, examples and help for your CoCo").font(.callout).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer(minLength: 12)
|
||||
if let activeDialect {
|
||||
Label(activeDialect.displayName, systemImage: "desktopcomputer")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
.accessibilityIdentifier("basic.reference.active-dialect")
|
||||
}
|
||||
}.padding(16)
|
||||
Divider()
|
||||
HSplitView {
|
||||
navigation.frame(minWidth: 210, idealWidth: 250, maxWidth: 330)
|
||||
Group {
|
||||
if let entry = model.selectedEntry {
|
||||
ScrollView {
|
||||
entryDetail(entry).padding(22).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.id(entry.id).accessibilityIdentifier("basic.reference.detail")
|
||||
} else {
|
||||
ContentUnavailableView {
|
||||
Label(model.catalog.entries.isEmpty ? "Reference unavailable" : "No matching commands", systemImage: "magnifyingglass")
|
||||
} description: {
|
||||
Text(model.catalog.entries.isEmpty ? "The local reference could not be loaded." : "Try a command name or choose a different category.")
|
||||
} actions: {
|
||||
if !model.catalog.entries.isEmpty {
|
||||
Button("Clear Filters") { model.search = ""; model.category = nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
}.frame(minWidth: 460, maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
Divider()
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "internaldrive")
|
||||
Text("Available offline")
|
||||
Spacer()
|
||||
Text("Examples open in the editor. Run them when you’re ready.")
|
||||
}.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.vertical, 9)
|
||||
}.frame(minWidth: 780, minHeight: 540)
|
||||
.background {
|
||||
Button("Find in BASIC Reference") { searchFocused = true }
|
||||
.keyboardShortcut("f", modifiers: .command).hidden().accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
|
||||
private var navigation: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
|
||||
TextField("Find a command", text: $model.search)
|
||||
.textFieldStyle(.plain).focused($searchFocused)
|
||||
.accessibilityLabel("Search BASIC reference").accessibilityIdentifier("basic.reference.search")
|
||||
if !model.search.isEmpty {
|
||||
Button { model.search = "" } label: { Image(systemName: "xmark.circle.fill") }
|
||||
.buttonStyle(.plain).foregroundStyle(.secondary).help("Clear reference search").accessibilityLabel("Clear reference search")
|
||||
}
|
||||
}.padding(8).background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 7))
|
||||
.padding(.horizontal, 12).padding(.top, 12)
|
||||
Picker("Category", selection: $model.category) {
|
||||
Text("All Topics").tag(String?.none)
|
||||
ForEach(model.categories, id: \.self) { Text($0).tag(Optional($0)) }
|
||||
}.padding(.horizontal, 12).accessibilityIdentifier("basic.reference.category")
|
||||
List(selection: $model.selectedID) {
|
||||
ForEach(model.filteredEntries) { entry in
|
||||
HStack(alignment: .top, spacing: 9) {
|
||||
Image(systemName: symbol(for: entry)).foregroundStyle(.secondary).frame(width: 18)
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(entry.title).font(.callout.weight(.medium))
|
||||
Text(entry.dialect.displayName).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}.padding(.vertical, 3).tag(entry.id)
|
||||
.accessibilityIdentifier("basic.reference.topic." + entry.id)
|
||||
}
|
||||
}.listStyle(.sidebar).accessibilityIdentifier("basic.reference.list")
|
||||
Text("\(model.filteredEntries.count) topics").font(.caption).foregroundStyle(.secondary)
|
||||
.padding(.horizontal, 14).padding(.bottom, 10)
|
||||
}
|
||||
}
|
||||
|
||||
private func entryDetail(_ entry: BASICReferenceEntry) -> some View {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
VStack(alignment: .leading, spacing: 9) {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
Text(entry.title).font(.system(.title, design: .monospaced).bold())
|
||||
.accessibilityIdentifier("basic.reference.title")
|
||||
Spacer(minLength: 8)
|
||||
}
|
||||
HStack(spacing: 8) {
|
||||
Label(entry.category, systemImage: symbol(for: entry))
|
||||
Text("·")
|
||||
Text(entry.dialect.displayName)
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
Text(entry.summary).textSelection(.enabled)
|
||||
Button("Read in BASIC Manual", systemImage: "book.pages") { openManualTopic(entry) }
|
||||
.accessibilityIdentifier("basic.reference.manual")
|
||||
}
|
||||
if !entry.syntax.isEmpty {
|
||||
section("Syntax") { code(entry.syntax.joined(separator: "\n")) }
|
||||
}
|
||||
if !entry.parameters.isEmpty {
|
||||
section("Parameters") {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
ForEach(Array(entry.parameters.enumerated()), id: \.offset) { _, parameter in
|
||||
Text(parameter).font(.callout).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !entry.sample.isEmpty {
|
||||
section("Example syntax") { code(entry.sample) }
|
||||
}
|
||||
if let example = model.example(for: entry) {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label(example.title, systemImage: "play.rectangle").font(.headline)
|
||||
Text(example.summary).font(.callout).textSelection(.enabled)
|
||||
if !example.expectedOutput.isEmpty {
|
||||
Text("Expected result: " + example.expectedOutput).font(.callout).foregroundStyle(.secondary)
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
Button { openExample(example) } label: { Label("Open Example", systemImage: "doc.badge.plus") }
|
||||
.accessibilityIdentifier("basic.reference.example")
|
||||
Text("Opens a separate program; does not run it.").font(.caption).foregroundStyle(.secondary)
|
||||
}.padding(14).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(Color.accentColor.opacity(0.07), in: RoundedRectangle(cornerRadius: 9))
|
||||
}
|
||||
if !entry.notes.isEmpty {
|
||||
section("Good to know") {
|
||||
VStack(alignment: .leading, spacing: 9) {
|
||||
ForEach(Array(entry.notes.enumerated()), id: \.offset) { _, note in
|
||||
Text(note).font(.callout).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let related = entry.related.compactMap(model.relatedEntry)
|
||||
if !related.isEmpty {
|
||||
section("Related topics") {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
ForEach(related) { relatedEntry in
|
||||
Button { model.select(relatedEntry) } label: {
|
||||
Label(relatedEntry.title, systemImage: "arrow.turn.down.right")
|
||||
}.buttonStyle(.link).accessibilityIdentifier("basic.reference.related." + relatedEntry.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Divider()
|
||||
DisclosureGroup {
|
||||
VStack(alignment: .leading, spacing: 7) {
|
||||
Text(entry.citation).textSelection(.enabled)
|
||||
Text("Historical manuals preserved by Color Computer Archive. Explanations and examples written for VCC Plus.")
|
||||
.foregroundStyle(.secondary)
|
||||
}.font(.caption).padding(.top, 7)
|
||||
} label: {
|
||||
Label("Bibliographic reference", systemImage: "books.vertical").font(.callout)
|
||||
}.accessibilityIdentifier("basic.reference.attribution")
|
||||
}
|
||||
}
|
||||
|
||||
private func section<Content: View>(_ title: String, @ViewBuilder content: () -> Content) -> some View {
|
||||
VStack(alignment: .leading, spacing: 9) {
|
||||
Text(title).font(.headline)
|
||||
content()
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
private func code(_ text: String) -> some View {
|
||||
Text(text).font(.system(.body, design: .monospaced)).textSelection(.enabled)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.padding(12).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 7))
|
||||
}
|
||||
private func symbol(for entry: BASICReferenceEntry) -> String {
|
||||
let category = entry.category.lowercased()
|
||||
if entry.id.hasPrefix("ERROR.") || category.contains("error") { return "exclamationmark.circle" }
|
||||
if category.contains("graphic") || category.contains("display") || category.contains("screen") { return "paintpalette" }
|
||||
if category.contains("sound") || category.contains("music") { return "speaker.wave.2" }
|
||||
if category.contains("disk") || category.contains("file") || category.contains("storage") { return "externaldrive" }
|
||||
if category.contains("cassette") { return "recordingtape" }
|
||||
if category.contains("string") || category.contains("text") { return "textformat" }
|
||||
if category.contains("math") || category.contains("number") { return "function" }
|
||||
if category.contains("flow") || category.contains("control") { return "arrow.triangle.branch" }
|
||||
if category.contains("memory") { return "memorychip" }
|
||||
return "terminal"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
enum BinaryFile {
|
||||
static let limit = 1024 * 1024 // Matches BinaryImage::maxBytes; structural parsing belongs to the core.
|
||||
enum Failure: LocalizedError {
|
||||
case notFile, size
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .notFile: return "Choose a regular CoCo .bin file."
|
||||
case .size: return "Choose a nonempty CoCo .bin file, up to 1 MiB."
|
||||
}
|
||||
}
|
||||
}
|
||||
static func read(_ url: URL) throws -> Data {
|
||||
let resolved = url.resolvingSymlinksInPath()
|
||||
guard url.pathExtension.lowercased() == "bin",
|
||||
try resolved.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile }
|
||||
let file = try FileHandle(forReadingFrom: resolved)
|
||||
defer { try? file.close() }
|
||||
let data = try file.read(upToCount: limit + 1) ?? Data()
|
||||
guard !data.isEmpty, data.count <= limit else { throw Failure.size }
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// A build-produced declaration of unpacked code placement. Hashes bind this
|
||||
/// declaration to one retained build; object relocation replay and live physical
|
||||
/// RAM comparisons provide the independent byte checks before debugging.
|
||||
struct CMOCBankedDebugLayout: Sendable {
|
||||
struct File: Decodable, Sendable { let path: String; let sha256: String }
|
||||
struct Page: Decodable, Equatable, Sendable { let logicalPage: Int; let physicalPage: Int }
|
||||
struct CodeGuard: Equatable, Sendable { let address: UInt16; let bytes: [UInt8] }
|
||||
struct Framebuffer: Decodable, Equatable, Sendable {
|
||||
let id: String
|
||||
let physicalAddress: Int
|
||||
let mode: String
|
||||
var canvasBytes: Int? = nil
|
||||
var workerFields: [String: Any] {
|
||||
var fields: [String: Any] = ["id": id, "physical_address": physicalAddress, "mode": mode]
|
||||
if let canvasBytes { fields["canvas_bytes"] = canvasBytes }
|
||||
return fields
|
||||
}
|
||||
}
|
||||
struct Image: Decodable, Sendable {
|
||||
let path: String
|
||||
let logicalAddress: Int
|
||||
let offset: Int?
|
||||
let length: Int?
|
||||
}
|
||||
struct Module: Sendable {
|
||||
let id: String
|
||||
let sections: [String]
|
||||
let codeSections: [String]
|
||||
let logicalAddress: Int
|
||||
let bytes: [UInt8]
|
||||
let pages: [Page]
|
||||
let codeGuards: [CodeGuard]
|
||||
func physicalAddress(_ logical: Int) -> UInt32? {
|
||||
guard (0..<65536).contains(logical),
|
||||
let page = pages.first(where: { $0.logicalPage == logical / 8192 }) else { return nil }
|
||||
return UInt32(page.physicalPage * 8192 + logical % 8192)
|
||||
}
|
||||
func isMapped(physicalPages: [Int]) -> Bool {
|
||||
physicalPages.count == 8 && pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage }
|
||||
}
|
||||
}
|
||||
private struct ModuleRecord: Decodable {
|
||||
let id: String; let sections: [String]; let codeSections: [String]; let image: Image?; let pages: [Page]
|
||||
}
|
||||
private struct Manifest: Decodable {
|
||||
let version: Int; let entryPoint: Int
|
||||
let binary: File; let disk: File?; let linkMap: File
|
||||
let sources: [String: String]; let artifacts: [String: String]
|
||||
let modules: [ModuleRecord]
|
||||
let framebuffers: [Framebuffer]?
|
||||
}
|
||||
let entryPoint: UInt16
|
||||
let binarySHA256: String
|
||||
let linkMap: Data
|
||||
let sourceHashes: [String: String]
|
||||
let artifactHashes: [String: String]
|
||||
let modules: [Module]
|
||||
var framebuffers: [Framebuffer] = []
|
||||
func module(forSection name: String) -> Module? { modules.first { $0.sections.contains(name) } }
|
||||
func module(id: String) -> Module? { modules.first { $0.id == id } }
|
||||
|
||||
static func parse(data: Data, directory: URL, sources: [String: Data], binary: Data,
|
||||
binaryPath: String, diskPath: String? = nil, allowedOutputs: [String]) throws -> Self {
|
||||
func fail(_ text: String) -> CMOCSourceMap.Failure { .invalid("banked manifest: " + text) }
|
||||
guard data.count <= 1024 * 1024 else { throw fail("manifest exceeds 1 MB.") }
|
||||
// Bound recursive decoding before handing untrusted JSON to Decodable.
|
||||
var pending: [(Any, Int)] = [(try JSONSerialization.jsonObject(with: data), 0)], nodes = 0
|
||||
while let (value, depth) = pending.popLast() {
|
||||
nodes += 1
|
||||
guard depth <= 16, nodes <= 30000 else { throw fail("manifest nesting or record limit exceeded.") }
|
||||
if let values = value as? [String: Any] { pending += values.values.map { ($0, depth + 1) } }
|
||||
if let values = value as? [Any] { pending += values.map { ($0, depth + 1) } }
|
||||
}
|
||||
let manifest = try JSONDecoder().decode(Manifest.self, from: data)
|
||||
guard manifest.version == 1, (0..<65536).contains(manifest.entryPoint),
|
||||
!manifest.modules.isEmpty, manifest.modules.count <= 256,
|
||||
manifest.artifacts.count <= 8192, sources.count <= 4096 else { throw fail("unsupported version or record count.") }
|
||||
func path(_ value: String) throws {
|
||||
guard !value.isEmpty, value.utf8.count <= 4096, !value.hasPrefix("/"), !value.contains("\\"),
|
||||
!value.contains("\0"), !value.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }),
|
||||
(value as NSString).standardizingPath == value else { throw fail("paths must be canonical project-relative identities.") }
|
||||
}
|
||||
func hash(_ value: String) throws {
|
||||
guard value.count == 64, value.allSatisfy({ $0.isASCII && ($0.isNumber || ("a"..."f").contains(String($0))) }) else { throw fail("invalid SHA-256.") }
|
||||
}
|
||||
let root = directory.resolvingSymlinksInPath().standardizedFileURL
|
||||
let outputs = Set(allowedOutputs)
|
||||
var loaded: [String: Data] = [:], total = 0
|
||||
func read(_ name: String, digest: String) throws -> Data {
|
||||
try path(name); try hash(digest)
|
||||
guard outputs.contains(name) else { throw fail("an artifact was not retained as a declared build output.") }
|
||||
if let data = loaded[name] {
|
||||
guard CMOCSourceMap.sha256(data) == digest else { throw fail("conflicting artifact hashes.") }; return data
|
||||
}
|
||||
let url = root.appendingPathComponent(name)
|
||||
guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact paths must not traverse symbolic links.") }
|
||||
let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 8 * 1024 * 1024 else { throw fail("artifact is not a bounded regular file.") }
|
||||
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
||||
let value = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data()
|
||||
total += value.count
|
||||
guard value.count <= 8 * 1024 * 1024, total <= 128 * 1024 * 1024,
|
||||
CMOCSourceMap.sha256(value) == digest else { throw fail("artifact changed or exceeds verification limits.") }
|
||||
loaded[name] = value; return value
|
||||
}
|
||||
guard manifest.sources == sources.mapValues(CMOCSourceMap.sha256) else { throw fail("source snapshot differs from the manifest.") }
|
||||
for (name, digest) in manifest.sources { try path(name); try hash(digest) }
|
||||
guard manifest.binary.path == binaryPath, CMOCSourceMap.sha256(binary) == manifest.binary.sha256 else { throw fail("delivered executable differs from the manifest.") }
|
||||
_ = try read(manifest.binary.path, digest: manifest.binary.sha256)
|
||||
if let disk = manifest.disk {
|
||||
guard disk.path == diskPath else { throw fail("delivered disk identity differs from the manifest.") }
|
||||
_ = try read(disk.path, digest: disk.sha256)
|
||||
} else if diskPath != nil { throw fail("delivered disk is missing from the manifest.") }
|
||||
let linkMap = try read(manifest.linkMap.path, digest: manifest.linkMap.sha256)
|
||||
guard let mapText = String(data: linkMap, encoding: .utf8), !mapText.contains("\0") else { throw fail("invalid linker-map encoding.") }
|
||||
let sectionPattern = try NSRegularExpression(pattern: #"^Section: ([^\s]+) \((.+)\) load at ([0-9A-Fa-f]{4}), length ([0-9A-Fa-f]{4})$"#)
|
||||
var placements: [(name: String, address: Int, length: Int)] = []
|
||||
let rows = mapText.components(separatedBy: .newlines)
|
||||
guard rows.count <= 100000, rows.allSatisfy({ $0.utf8.count <= 8192 }) else { throw fail("linker map exceeds limits.") }
|
||||
for row in rows {
|
||||
let ns = row as NSString
|
||||
guard let match = sectionPattern.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) else {
|
||||
if row.hasPrefix("Section:") { throw fail("unsupported section placement.") }; continue
|
||||
}
|
||||
placements.append((ns.substring(with: match.range(at: 1)),
|
||||
Int(ns.substring(with: match.range(at: 3)), radix: 16)!, Int(ns.substring(with: match.range(at: 4)), radix: 16)!))
|
||||
}
|
||||
for (name, digest) in manifest.artifacts { _ = try read(name, digest: digest) }
|
||||
var modules: [Module] = [], ids = Set<String>(), sections = Set<String>()
|
||||
var physical: [UInt32: String] = [:]
|
||||
for record in manifest.modules {
|
||||
guard !record.id.isEmpty, record.id.count <= 128, ids.insert(record.id).inserted,
|
||||
!record.sections.isEmpty, record.sections.count <= 256,
|
||||
Set(record.codeSections).count == record.codeSections.count,
|
||||
Set(record.codeSections).isSubset(of: Set(record.sections)),
|
||||
!record.pages.isEmpty, record.pages.count <= 8 else { throw fail("invalid or repeated module identity.") }
|
||||
for section in record.sections {
|
||||
guard !section.isEmpty, section.count <= 256, !section.contains(where: \.isWhitespace), sections.insert(section).inserted else { throw fail("section has ambiguous module ownership.") }
|
||||
}
|
||||
guard Set(record.pages.map(\.logicalPage)).count == record.pages.count,
|
||||
record.pages.allSatisfy({ (0..<8).contains($0.logicalPage) && (0..<1024).contains($0.physicalPage) }) else {
|
||||
throw fail("module image or page layout is invalid.")
|
||||
}
|
||||
let logicalAddress: Int, moduleBytes: [UInt8]
|
||||
if let declaredImage = record.image {
|
||||
guard let digest = manifest.artifacts[declaredImage.path] else { throw fail("module image is missing from the artifact evidence.") }
|
||||
let image = try read(declaredImage.path, digest: digest)
|
||||
let offset = declaredImage.offset ?? 0
|
||||
guard offset >= 0, offset <= image.count else { throw fail("module image range is invalid.") }
|
||||
let length = declaredImage.length ?? (image.count - offset)
|
||||
guard length > 0, length <= image.count - offset,
|
||||
declaredImage.logicalAddress >= 0, declaredImage.logicalAddress < 65536,
|
||||
length <= 65536 - declaredImage.logicalAddress else { throw fail("module image range is invalid.") }
|
||||
logicalAddress = declaredImage.logicalAddress
|
||||
moduleBytes = Array(image[offset..<(offset + length)])
|
||||
} else {
|
||||
guard record.codeSections.isEmpty else {
|
||||
throw fail("module \(record.id): executable codeSections require a module image.")
|
||||
}
|
||||
// Pure BSS owns real physical storage but has no initialized
|
||||
// bytes. Relocation verification still rejects any initialized
|
||||
// object section whose bytes are absent from this empty image.
|
||||
logicalAddress = placements.first { record.sections.contains($0.name) }?.address ?? 0
|
||||
moduleBytes = []
|
||||
}
|
||||
var guards: [CodeGuard] = [], occupiedCode = Set<Int>()
|
||||
for section in record.codeSections {
|
||||
let matching = placements.filter { $0.name == section }
|
||||
guard !matching.isEmpty else { throw fail("an executable section is missing from the linker map.") }
|
||||
for placement in matching where placement.length > 0 {
|
||||
let start = placement.address - logicalAddress
|
||||
guard start >= 0, start <= moduleBytes.count, placement.length <= moduleBytes.count - start else { throw fail("executable section leaves its module image.") }
|
||||
for address in placement.address..<(placement.address + placement.length) {
|
||||
guard occupiedCode.insert(address).inserted else { throw fail("executable section placements overlap inside a module.") }
|
||||
}
|
||||
guards.append(CodeGuard(address: UInt16(placement.address), bytes: Array(moduleBytes[start..<(start + placement.length)])))
|
||||
}
|
||||
}
|
||||
let module = Module(id: record.id, sections: record.sections, codeSections: record.codeSections,
|
||||
logicalAddress: logicalAddress, bytes: moduleBytes, pages: record.pages,
|
||||
codeGuards: guards.sorted { $0.address < $1.address })
|
||||
var imagePhysical = Set<UInt32>()
|
||||
for logical in module.logicalAddress..<(module.logicalAddress + moduleBytes.count) {
|
||||
guard let address = module.physicalAddress(logical), imagePhysical.insert(address).inserted,
|
||||
physical[address] == nil || physical[address] == module.id else {
|
||||
throw fail("module images overlap physical RAM or lack a page identity.")
|
||||
}
|
||||
physical[address] = module.id
|
||||
}
|
||||
// BSS has no image bytes, but its storage must still have one
|
||||
// physical owner. Initialized non-code data follows the same rule.
|
||||
for section in record.sections where !record.codeSections.contains(section) {
|
||||
let matching = placements.filter { $0.name == section }
|
||||
guard !matching.isEmpty else { throw fail("a data section is missing from the linker map.") }
|
||||
for placement in matching where placement.length > 0 {
|
||||
for logical in placement.address..<(placement.address + placement.length) {
|
||||
guard let address = module.physicalAddress(logical),
|
||||
physical[address] == nil || physical[address] == module.id else {
|
||||
throw fail("module storage overlaps another module's physical RAM or lacks a page identity.")
|
||||
}
|
||||
physical[address] = module.id
|
||||
}
|
||||
}
|
||||
}
|
||||
modules.append(module)
|
||||
}
|
||||
// A compressed transport can enter through its loader, outside every
|
||||
// eventual source module. Bind this entry to the delivered DECB trailer.
|
||||
guard try CMOCSourceMap.decbEntryPoint(binary) == UInt16(manifest.entryPoint) else { throw fail("entry point differs from the delivered executable.") }
|
||||
let buffers = manifest.framebuffers ?? []
|
||||
let modes = Set(["sg4", "pmode0", "pmode1", "pmode2", "pmode3", "pmode4", "hscreen1", "hscreen2", "hscreen3", "hscreen4", "current_gime"])
|
||||
guard buffers.count <= 4, Set(buffers.map(\.id)).count == buffers.count,
|
||||
buffers.allSatisfy({ buffer in
|
||||
buffer.id != "displayed" && (1...64).contains(buffer.id.utf8.count) &&
|
||||
buffer.id.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 95 || $0 == 45 }) &&
|
||||
(0..<(8 * 1024 * 1024)).contains(buffer.physicalAddress) && modes.contains(buffer.mode) && {
|
||||
if buffer.mode == "current_gime" {
|
||||
guard let size = buffer.canvasBytes, (8192...(8 * 1024 * 1024)).contains(size),
|
||||
size & (size - 1) == 0, buffer.physicalAddress % size == 0,
|
||||
buffer.physicalAddress <= 8 * 1024 * 1024 - size else { return false }
|
||||
return true
|
||||
}
|
||||
return buffer.canvasBytes == nil
|
||||
}()
|
||||
}) else { throw fail("invalid framebuffer declaration.") }
|
||||
let canvases = buffers.filter { $0.mode == "current_gime" }
|
||||
for (index, canvas) in canvases.enumerated() {
|
||||
let range = canvas.physicalAddress..<(canvas.physicalAddress + canvas.canvasBytes!)
|
||||
guard canvases.dropFirst(index + 1).allSatisfy({ other in
|
||||
!range.overlaps(other.physicalAddress..<(other.physicalAddress + other.canvasBytes!))
|
||||
}) else { throw fail("overlapping current GIME canvases.") }
|
||||
}
|
||||
return Self(entryPoint: UInt16(manifest.entryPoint), binarySHA256: manifest.binary.sha256,
|
||||
linkMap: linkMap, sourceHashes: manifest.sources, artifactHashes: manifest.artifacts,
|
||||
modules: modules, framebuffers: buffers)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
/// Completed, owned build snapshots only. Working caches and development disks
|
||||
/// are deliberately outside this inventory. Cleanup is explicit and recoverable.
|
||||
final class CMOCBuildHistory: @unchecked Sendable {
|
||||
struct Entry: Identifiable, Sendable {
|
||||
let id: UUID
|
||||
let directory: URL
|
||||
let createdAt: Date
|
||||
let configurationName: String
|
||||
let action: String
|
||||
let byteCount: Int64
|
||||
let hasBinary: Bool
|
||||
let hasDisk: Bool
|
||||
let protectionReason: String?
|
||||
}
|
||||
struct Removal: Sendable {
|
||||
var removedIDs: Set<UUID> = []
|
||||
var retained: [UUID: String] = [:]
|
||||
}
|
||||
private struct Record: Codable {
|
||||
let version: Int
|
||||
let id: UUID
|
||||
let project: String
|
||||
let createdAt: Date
|
||||
let configurationName: String
|
||||
let action: String
|
||||
let hasBinary: Bool
|
||||
let hasDisk: Bool
|
||||
let byteCount: Int64
|
||||
let hashes: [String: String]
|
||||
}
|
||||
static let manifestName = ".vccplus-build-history.json"
|
||||
static let leaseName = ".vccplus-build-history.lock"
|
||||
private let root: URL
|
||||
private let lock = NSLock()
|
||||
private var leases: [UUID: Int32] = [:]
|
||||
private let trash: @Sendable (URL) throws -> Void
|
||||
|
||||
init(root: URL, trash: @escaping @Sendable (URL) throws -> Void = { url in
|
||||
try FileManager.default.trashItem(at: url, resultingItemURL: nil)
|
||||
}) {
|
||||
self.root = root.standardizedFileURL.resolvingSymlinksInPath()
|
||||
self.trash = trash
|
||||
}
|
||||
deinit { for descriptor in leases.values { close(descriptor) } }
|
||||
|
||||
func record(_ artifact: CMOCBuildArtifact, project: URL) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
let directory = try checkedDirectory(artifact.id)
|
||||
guard try CMOCProject.physicalURL(artifact.directory) == directory else { throw failure("Build result is outside its owned history folder.") }
|
||||
let manager = FileManager.default
|
||||
for name in [Self.manifestName, Self.leaseName] {
|
||||
guard !manager.fileExists(atPath: directory.appendingPathComponent(name).path) else {
|
||||
throw failure("The build recipe used a reserved history filename: \(name)")
|
||||
}
|
||||
}
|
||||
let files = try contents(directory)
|
||||
let descriptor = open(directory.appendingPathComponent(Self.leaseName).path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)
|
||||
guard descriptor >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
var retained = false
|
||||
defer { if !retained { close(descriptor); try? manager.removeItem(at: directory.appendingPathComponent(Self.leaseName)) } }
|
||||
guard flock(descriptor, LOCK_SH | LOCK_NB) == 0 else { throw failure("The new build could not be protected from cleanup.") }
|
||||
let record = Record(version: 1, id: artifact.id, project: canonicalProject(project), createdAt: Date(),
|
||||
configurationName: artifact.configurationName, action: artifact.action.rawValue,
|
||||
hasBinary: artifact.hasBinary, hasDisk: artifact.hasDisk,
|
||||
byteCount: files.values.reduce(Int64(0)) { $0 + Int64($1.count) }, hashes: files.mapValues(CMOCProject.sha256))
|
||||
let temporary = directory.appendingPathComponent(".vccplus-history-" + UUID().uuidString)
|
||||
defer { try? manager.removeItem(at: temporary) }
|
||||
try JSONEncoder().encode(record).write(to: temporary, options: .withoutOverwriting)
|
||||
guard renamex_np(temporary.path, directory.appendingPathComponent(Self.manifestName).path, UInt32(RENAME_EXCL)) == 0 else {
|
||||
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
|
||||
}
|
||||
leases[artifact.id] = descriptor; retained = true
|
||||
}
|
||||
|
||||
func entries(project: URL, protectedIDs: Set<UUID> = []) throws -> [Entry] {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard FileManager.default.fileExists(atPath: root.path) else { return [] }
|
||||
let canonical = canonicalProject(project)
|
||||
return try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil).compactMap { url in
|
||||
guard let id = UUID(uuidString: url.lastPathComponent), let record = try? read(id), record.project == canonical else { return nil }
|
||||
guard let directory = try? checkedDirectory(id) else { return nil }
|
||||
let reason: String?
|
||||
if protectedIDs.contains(id) { reason = "Protected build or assigned media" }
|
||||
else if let invalid = validationProblem(record, directory: directory) { reason = invalid }
|
||||
else if leases[id] == nil, !leaseAvailable(directory) { reason = "In use by another app session" }
|
||||
else { reason = nil }
|
||||
return Entry(id: id, directory: directory, createdAt: record.createdAt,
|
||||
configurationName: record.configurationName, action: record.action, byteCount: record.byteCount,
|
||||
hasBinary: record.hasBinary, hasDisk: record.hasDisk, protectionReason: reason)
|
||||
}.sorted { $0.createdAt == $1.createdAt ? $0.id.uuidString < $1.id.uuidString : $0.createdAt > $1.createdAt }
|
||||
}
|
||||
|
||||
func remove(ids: Set<UUID>, project: URL, protectedIDs: Set<UUID>) throws -> Removal {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
var result = Removal()
|
||||
let canonical = canonicalProject(project)
|
||||
for id in ids {
|
||||
do {
|
||||
guard !protectedIDs.contains(id) else { throw failure("Protected build or assigned media") }
|
||||
let record = try read(id), directory = try checkedDirectory(id)
|
||||
guard record.project == canonical else { throw failure("This build belongs to a different project.") }
|
||||
let owned = leases[id]
|
||||
let descriptor = owned ?? open(directory.appendingPathComponent(Self.leaseName).path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard descriptor >= 0 else { throw failure("Build ownership could not be verified.") }
|
||||
defer {
|
||||
if let owned, leases[id] != nil { _ = flock(owned, LOCK_SH) }
|
||||
if owned == nil { close(descriptor) }
|
||||
}
|
||||
guard validLease(descriptor, directory: directory) else { throw failure("Build ownership file changed; kept for recovery") }
|
||||
guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { throw failure("In use by another app session") }
|
||||
if let problem = validationProblem(record, directory: directory) { throw failure(problem) }
|
||||
// Trash retains a recovery path even if a file was edited in the
|
||||
// brief interval after validation. Never remove a run disk here.
|
||||
try trash(directory)
|
||||
if let owned { leases.removeValue(forKey: id); close(owned) }
|
||||
result.removedIDs.insert(id)
|
||||
} catch { result.retained[id] = error.localizedDescription }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private func canonicalProject(_ project: URL) -> String { project.standardizedFileURL.resolvingSymlinksInPath().path }
|
||||
private func failure(_ message: String) -> CMOCBuildError { .message(message) }
|
||||
private func checkedDirectory(_ id: UUID) throws -> URL {
|
||||
let rootValues = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard rootValues.isDirectory == true, rootValues.isSymbolicLink != true else { throw failure("Build history folder ownership could not be verified.") }
|
||||
let canonicalRoot = try CMOCProject.physicalURL(root)
|
||||
let directory = canonicalRoot.appendingPathComponent(id.uuidString)
|
||||
let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard values.isDirectory == true, values.isSymbolicLink != true,
|
||||
try CMOCProject.physicalURL(directory).deletingLastPathComponent() == canonicalRoot else {
|
||||
throw failure("Build folder ownership could not be verified.")
|
||||
}
|
||||
return directory
|
||||
}
|
||||
private func read(_ id: UUID) throws -> Record {
|
||||
let directory = try checkedDirectory(id), url = directory.appendingPathComponent(Self.manifestName)
|
||||
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard values.isRegularFile == true, values.isSymbolicLink != true,
|
||||
let size = values.fileSize, size > 0, size <= 8 * 1024 * 1024 else { throw failure("Build history is missing or invalid.") }
|
||||
let record = try JSONDecoder().decode(Record.self, from: Data(contentsOf: url))
|
||||
guard record.version == 1, record.id == id, record.hashes.count <= 20_000,
|
||||
record.byteCount >= 0, record.byteCount <= Int64(CMOCProject.maximumProjectBytes),
|
||||
record.configurationName.count <= 1024, CMOCBuildAction(rawValue: record.action) != nil,
|
||||
record.project.hasPrefix("/"), record.project.count <= 4096 else { throw failure("Build history is missing or invalid.") }
|
||||
for path in record.hashes.keys { try CMOCProject.validateRelativePath(path) }
|
||||
return record
|
||||
}
|
||||
private func leaseAvailable(_ directory: URL) -> Bool {
|
||||
let descriptor = open(directory.appendingPathComponent(Self.leaseName).path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard descriptor >= 0 else { return false }
|
||||
defer { close(descriptor) }
|
||||
return validLease(descriptor, directory: directory) && flock(descriptor, LOCK_EX | LOCK_NB) == 0
|
||||
}
|
||||
private func validLease(_ descriptor: Int32, directory: URL) -> Bool {
|
||||
var held = stat(), current = stat()
|
||||
guard fstat(descriptor, &held) == 0,
|
||||
lstat(directory.appendingPathComponent(Self.leaseName).path, ¤t) == 0 else { return false }
|
||||
return (current.st_mode & S_IFMT) == S_IFREG && current.st_size == 0 &&
|
||||
held.st_dev == current.st_dev && held.st_ino == current.st_ino
|
||||
}
|
||||
private func validationProblem(_ record: Record, directory: URL) -> String? {
|
||||
do {
|
||||
if let descriptor = leases[record.id], !validLease(descriptor, directory: directory) {
|
||||
return "Build ownership file changed; kept for recovery"
|
||||
}
|
||||
let files = try contents(directory)
|
||||
guard files.mapValues(CMOCProject.sha256) == record.hashes else {
|
||||
return "Files changed since this build; kept for recovery"
|
||||
}
|
||||
return nil
|
||||
} catch { return "Files are missing, linked or unreadable; kept for recovery" }
|
||||
}
|
||||
/// Unlike project enumeration, this includes hidden/user-added files. Any
|
||||
/// changed, added or missing file makes a completed snapshot ineligible.
|
||||
private func contents(_ directory: URL) throws -> [String: Data] {
|
||||
var enumerationError: Error?
|
||||
guard let enumerator = FileManager.default.enumerator(at: directory,
|
||||
includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey],
|
||||
errorHandler: { _, error in enumerationError = error; return false }) else { throw failure("Build files could not be inspected.") }
|
||||
var files: [String: Data] = [:], total = 0
|
||||
while let url = enumerator.nextObject() as? URL {
|
||||
let relative = String(url.path.dropFirst(directory.path.count + 1))
|
||||
if relative == Self.manifestName || relative == Self.leaseName { continue }
|
||||
try CMOCProject.validateRelativePath(relative)
|
||||
let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard values.isSymbolicLink != true else { throw failure("Linked build file") }
|
||||
if values.isDirectory == true { continue }
|
||||
// Finder may add this bookkeeping when revealing build products.
|
||||
// It is not a user source or media change. Links still fail above.
|
||||
if url.lastPathComponent == ".DS_Store" { continue }
|
||||
guard values.isRegularFile == true, let size = values.fileSize, size <= CMOCProject.maximumFileBytes,
|
||||
files.count < 20_000, total + size <= CMOCProject.maximumProjectBytes else { throw failure("Build files exceed inspection limits.") }
|
||||
let data = try Data(contentsOf: url)
|
||||
guard data.count <= CMOCProject.maximumFileBytes, total + data.count <= CMOCProject.maximumProjectBytes else { throw failure("Build files changed during inspection.") }
|
||||
total += data.count; files[relative] = data
|
||||
}
|
||||
if let enumerationError { throw enumerationError }
|
||||
return files
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Conservative unwinding of CMOC's unoptimized, preserved-U calling convention.
|
||||
/// Never scans arbitrary stack words for plausible code addresses. An unknown
|
||||
/// boundary ends the chain instead of silently skipping an intervening frame.
|
||||
struct CMOCCallStack: Sendable {
|
||||
struct Frame: Identifiable, Sendable {
|
||||
let id: Int
|
||||
let functionName: String
|
||||
let sourcePath: String
|
||||
let sourceLine: Int?
|
||||
/// Current PC for frame zero; the actual calling instruction for callers.
|
||||
let pc: UInt16
|
||||
let u: UInt16
|
||||
let localsInspectable: Bool
|
||||
}
|
||||
let frames: [Frame]
|
||||
/// Why the verified chain ended. This is not necessarily the program root.
|
||||
let termination: String
|
||||
|
||||
static func capture(metadata: CMOCVariableDebug, pc: UInt16, u: UInt16, s: UInt16,
|
||||
memory: Data, available: Data, maximumFrames: Int = 64) -> Self {
|
||||
guard memory.count == 65536, available.count == 65536 else {
|
||||
return Self(frames: [], termination: "A complete paused memory snapshot is required.")
|
||||
}
|
||||
guard metadata.sourceMap.verifiesRuntime(memory: memory, available: available) else {
|
||||
return Self(frames: [], termination: "Executable bytes changed or became unavailable; reconnect the build before inspecting its call stack.")
|
||||
}
|
||||
func readable(_ start: Int, _ count: Int) -> Bool {
|
||||
start >= 0 && count >= 0 && start <= 0xfe00 - count &&
|
||||
available[start..<(start + count)].allSatisfy { $0 != 0 }
|
||||
}
|
||||
var verifiedBytes: [Int: UInt8] = [:]
|
||||
for instruction in metadata.sourceMap.instructions {
|
||||
let at = Int(instruction.address)
|
||||
guard readable(at, instruction.bytes.count),
|
||||
Array(memory[at..<(at + instruction.bytes.count)]) == instruction.bytes else {
|
||||
return Self(frames: [], termination: "Executable bytes changed or became unavailable; reconnect the build before inspecting its call stack.")
|
||||
}
|
||||
for (offset, byte) in instruction.bytes.enumerated() { verifiedBytes[at + offset] = byte }
|
||||
}
|
||||
func bytes(_ at: Int, _ expected: [UInt8]) -> Bool {
|
||||
readable(at, expected.count) && expected.enumerated().allSatisfy { verifiedBytes[at + $0.offset] == $0.element }
|
||||
}
|
||||
func word(_ at: Int) -> Int { Int(memory[at]) * 256 + Int(memory[at + 1]) }
|
||||
func function(at address: Int) -> CMOCVariableDebug.Function? {
|
||||
let matches = metadata.functions.filter {
|
||||
let epilogueSize = bytes($0.end, [0x32, 0xc4, 0x35, 0xc0]) ? 4 :
|
||||
(bytes($0.end, [0x32, 0xc4, 0x35, 0x40, 0x3b]) ? 5 : 0)
|
||||
return $0.entry <= address && address < $0.end + epilogueSize
|
||||
}
|
||||
return matches.count == 1 ? matches[0] : nil
|
||||
}
|
||||
func supported(_ function: CMOCVariableDebug.Function) -> Bool {
|
||||
// CMOC FunctionDef emits PSHS U; LEAU ,S before local allocation,
|
||||
// then LEAS ,U; PULS U,PC after its metadata end label. ISR epilogues
|
||||
// use PULS U; RTI and are intentionally not treated as normal calls.
|
||||
function.frame && bytes(function.entry, [0x34, 0x40, 0x33, 0xe4]) &&
|
||||
bytes(function.end, [0x32, 0xc4, 0x35, 0xc0])
|
||||
}
|
||||
func target(of instruction: CMOCProjectSourceMap.Instruction) -> Int? {
|
||||
let b = instruction.bytes, next = Int(instruction.address) + b.count
|
||||
if b.count == 3 && b[0] == 0x17 { // LBSR, signed relative displacement
|
||||
return (next + Int(Int16(bitPattern: UInt16(b[1]) << 8 | UInt16(b[2])))) & 0xffff
|
||||
}
|
||||
if b.count == 2 && b[0] == 0x8d { return (next + Int(Int8(bitPattern: b[1]))) & 0xffff }
|
||||
if b.count == 3 && b[0] == 0xbd { return Int(b[1]) * 256 + Int(b[2]) }
|
||||
// JSR n,PCR is statically resolvable; register/indirect calls aren't.
|
||||
if b.count == 3 && b[0] == 0xad && b[1] == 0x8c { return (next + Int(Int8(bitPattern: b[2]))) & 0xffff }
|
||||
if b.count == 4 && b[0] == 0xad && b[1] == 0x8d {
|
||||
return (next + Int(Int16(bitPattern: UInt16(b[2]) << 8 | UInt16(b[3])))) & 0xffff
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var frames: [Frame] = [], currentPC = Int(pc), frameU = Int(u), visited = Set<Int>()
|
||||
var stackFloor = Int(s)
|
||||
let limit = min(max(maximumFrames, 1), 128)
|
||||
while frames.count < limit {
|
||||
guard let current = function(at: currentPC) else {
|
||||
return Self(frames: frames, termination: "The next location is outside an unambiguous verified C function; the remaining stack is unavailable.")
|
||||
}
|
||||
let location = metadata.sourceMap.location(at: UInt16(currentPC))
|
||||
let inBody = current.body <= currentPC && currentPC < current.end && location != nil
|
||||
let validStorage = readable(frameU, 4) && stackFloor <= frameU && !visited.contains(frameU)
|
||||
let inspectable = supported(current) && inBody && validStorage
|
||||
frames.append(Frame(id: frames.count, functionName: current.name, sourcePath: location?.path ?? current.sourcePath,
|
||||
sourceLine: location?.line, pc: UInt16(currentPC), u: UInt16(frameU), localsInspectable: inspectable))
|
||||
guard supported(current) else {
|
||||
return Self(frames: frames, termination: "This frame uses optimized, interrupt, assembly, or other unsupported stack code. Its locals and remaining callers are unavailable.")
|
||||
}
|
||||
guard inBody else {
|
||||
return Self(frames: frames, termination: "Stopped in a function prologue, epilogue, or unmapped instruction; its frame pointer cannot be assumed valid yet.")
|
||||
}
|
||||
guard validStorage else {
|
||||
return Self(frames: frames, termination: "The frame pointer is outside readable stack memory or repeats an earlier frame; unwinding stopped.")
|
||||
}
|
||||
visited.insert(frameU)
|
||||
let olderU = word(frameU), returnPC = word(frameU + 2)
|
||||
let calls = metadata.sourceMap.instructions.filter {
|
||||
Int($0.address) + $0.bytes.count == returnPC && target(of: $0) == current.entry
|
||||
}
|
||||
guard calls.count == 1, let call = calls.first,
|
||||
let caller = function(at: Int(call.address)), caller.body <= Int(call.address), Int(call.address) < caller.end else {
|
||||
return Self(frames: frames, termination: "The caller is outside verified C code or its call target cannot be proved. Runtime, indirect-call and unknown boundaries stop unwinding here.")
|
||||
}
|
||||
guard olderU >= frameU + 4, readable(olderU, 4), !visited.contains(olderU) else {
|
||||
return Self(frames: frames, termination: "The saved caller frame pointer is invalid, unavailable or non-increasing; unwinding stopped.")
|
||||
}
|
||||
stackFloor = frameU + 4
|
||||
frameU = olderU
|
||||
currentPC = Int(call.address)
|
||||
}
|
||||
return Self(frames: frames, termination: "The call stack reached its \(limit)-frame inspection limit; additional callers are not shown.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Read-only lexical assistance. Queries never compile, execute Make, evaluate
|
||||
/// macros, or rebuild the project index. All coordinates are native UTF-16.
|
||||
enum CMOCCompletion {
|
||||
struct Candidate: Identifiable, Equatable, Sendable {
|
||||
var id: String { name }
|
||||
let name: String
|
||||
let detail: String
|
||||
let conditional: Bool
|
||||
let replacementRange: NSRange
|
||||
let insertion: String
|
||||
}
|
||||
struct ParameterHint: Identifiable, Equatable, Sendable {
|
||||
var id: String { sourcePath + ":" + signature }
|
||||
let signature: String
|
||||
let name: String
|
||||
let parameters: [String]
|
||||
let activeParameter: Int
|
||||
let conditional: Bool
|
||||
let sourcePath: String
|
||||
}
|
||||
private static let keywords = ["asm", "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "interrupt", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"]
|
||||
private static let controls: Set<String> = ["if", "for", "while", "switch", "sizeof", "return", "else", "do", "asm", "__asm"]
|
||||
private static let typeWords: Set<String> = ["void", "char", "short", "int", "long", "float", "double", "unsigned", "signed", "struct", "union", "enum", "typedef"]
|
||||
|
||||
static func suggestions(index: CMOCProjectIndex, path: String, text: String, offset: Int, limit: Int = 80) -> [Candidate] {
|
||||
guard ["c", "h"].contains((path as NSString).pathExtension.lowercased()),
|
||||
text.utf8.count <= CMOCProjectIndex.maximumFileBytes else { return [] }
|
||||
let units = Array(text.utf16)
|
||||
guard offset >= 0, offset <= units.count, let scan = scan(units, to: offset), !scan.suppressed else { return [] }
|
||||
var start = offset, end = offset
|
||||
while start > 0 && identifierPart(units[start - 1]) { start -= 1 }
|
||||
while end < units.count && identifierPart(units[end]) { end += 1 }
|
||||
if start < end && !identifierStart(units[start]) { return [] }
|
||||
let prefix = String(decoding: units[start..<offset], as: UTF16.self)
|
||||
guard prefix.utf16.count <= 256 else { return [] }
|
||||
let preceding = scan.tokens.last { $0.offset < start }
|
||||
guard preceding?.text != ".", preceding?.text != "->" else { return [] }
|
||||
let range = NSRange(location: start, length: end - start)
|
||||
let revision = Revision(original: index.documents[path], current: units, offset: offset)
|
||||
let symbols = index.completionSymbols(from: path, offset: revision.offset, prefix: prefix, includeLocals: revision.safeScopes)
|
||||
.filter { $0.path != path || revision.keeps($0) }
|
||||
var seen: Set<String> = [], candidates: [Candidate] = []
|
||||
let maximum = min(max(1, limit), 200)
|
||||
for symbol in symbols {
|
||||
guard seen.insert(symbol.name).inserted else { continue }
|
||||
let uncertain = symbol.conditional || !revision.safeScopes || (symbol.path == path && revision.changed)
|
||||
candidates.append(.init(name: symbol.name,
|
||||
detail: symbol.kind.rawValue + " · " + symbol.signature + " · " + symbol.path,
|
||||
conditional: uncertain, replacementRange: range, insertion: symbol.name))
|
||||
if candidates.count >= maximum { return candidates }
|
||||
}
|
||||
for keyword in keywords where keyword.hasPrefix(prefix) && seen.insert(keyword).inserted {
|
||||
candidates.append(.init(name: keyword, detail: "C keyword", conditional: false, replacementRange: range, insertion: keyword))
|
||||
if candidates.count >= maximum { break }
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
static func parameterHints(index: CMOCProjectIndex, path: String, text: String, offset: Int) -> [ParameterHint] {
|
||||
guard ["c", "h"].contains((path as NSString).pathExtension.lowercased()),
|
||||
text.utf8.count <= CMOCProjectIndex.maximumFileBytes else { return [] }
|
||||
let units = Array(text.utf16)
|
||||
guard offset >= 0, offset <= units.count, let scanned = scan(units, to: offset), !scanned.suppressed || scanned.literal else { return [] }
|
||||
struct Frame { let delimiter: String; let name: String?; let tokenIndex: Int; var argument: Int }
|
||||
let tokens = scanned.tokens
|
||||
var stack: [Frame] = []
|
||||
for (i, token) in tokens.enumerated() {
|
||||
switch token.text {
|
||||
case "(", "[", "{":
|
||||
guard stack.count < 128 else { return [] }
|
||||
let previous = i > 0 ? tokens[i - 1] : nil
|
||||
let member = i > 1 && [".", "->"].contains(tokens[i - 2].text)
|
||||
let name = token.text == "(" && previous?.identifier == true && !controls.contains(previous!.text) && !member ? previous!.text : nil
|
||||
stack.append(.init(delimiter: token.text, name: name, tokenIndex: i, argument: 0))
|
||||
case ")", "]", "}":
|
||||
let expected = token.text == ")" ? "(" : token.text == "]" ? "[" : "{"
|
||||
guard stack.last?.delimiter == expected else { return [] }
|
||||
stack.removeLast()
|
||||
case ",":
|
||||
if stack.last?.name != nil { stack[stack.count - 1].argument += 1 }
|
||||
default: break
|
||||
}
|
||||
}
|
||||
guard let call = stack.last(where: { $0.name != nil }), let name = call.name else { return [] }
|
||||
let nameToken = tokens[call.tokenIndex - 1]
|
||||
let revision = Revision(original: index.documents[path], current: units, offset: nameToken.offset)
|
||||
// An indexed declaration, or a newly typed obvious declaration, is not
|
||||
// a call. Function pointers and member calls are deliberately omitted.
|
||||
if index.symbols.contains(where: { $0.path == path && $0.name == name && $0.offsetUTF16 == revision.offset && $0.kind == .function }) { return [] }
|
||||
let statementStart = tokens[..<(call.tokenIndex - 1)].lastIndex(where: { [";", "{", "}"].contains($0.text) }).map { $0 + 1 } ?? 0
|
||||
let prefix = tokens[statementStart..<(call.tokenIndex - 1)].map(\.text)
|
||||
if !prefix.contains("="), !prefix.contains(where: { controls.contains($0) }), !prefix.contains("(") {
|
||||
if prefix.contains(where: { typeWords.contains($0) }) || (!prefix.isEmpty && prefix.allSatisfy { $0 == "*" || $0.utf16.first.map(identifierStart) == true }) { return [] }
|
||||
}
|
||||
let matches = index.completionSymbols(from: path, offset: revision.offset, prefix: name, includeLocals: revision.safeScopes)
|
||||
.filter { $0.name == name && ($0.path != path || revision.keeps($0)) }
|
||||
// A local object shadows a global function even when its type happens
|
||||
// to be a function pointer. Do not invent its callable signature.
|
||||
guard !matches.contains(where: { $0.kind != .function && $0.kind != .macro }) else { return [] }
|
||||
var seen: Set<String> = [], result: [ParameterHint] = []
|
||||
for symbol in matches where symbol.kind == .function || symbol.kind == .macro {
|
||||
guard let parameters = parameters(in: symbol.signature, name: name), seen.insert(symbol.signature).inserted else { continue }
|
||||
result.append(.init(signature: symbol.signature, name: name, parameters: parameters, activeParameter: call.argument,
|
||||
conditional: symbol.conditional || symbol.kind == .macro || !revision.safeScopes || (symbol.path == path && revision.changed), sourcePath: symbol.path))
|
||||
if result.count == 8 { break }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private struct Revision {
|
||||
let offset: Int, changed: Bool, safeScopes: Bool
|
||||
let changedRange: Range<Int>
|
||||
init(original: String?, current: [UInt16], offset: Int) {
|
||||
guard let original else { self.offset = 0; changed = true; safeScopes = false; changedRange = 0..<Int.max; return }
|
||||
let old = Array(original.utf16)
|
||||
var prefix = 0
|
||||
while prefix < min(old.count, current.count), old[prefix] == current[prefix] { prefix += 1 }
|
||||
var suffix = 0
|
||||
while suffix < min(old.count - prefix, current.count - prefix), old[old.count - suffix - 1] == current[current.count - suffix - 1] { suffix += 1 }
|
||||
changed = prefix != old.count || prefix != current.count
|
||||
changedRange = prefix..<(old.count - suffix)
|
||||
if offset <= prefix { self.offset = offset }
|
||||
else if offset >= current.count - suffix { self.offset = offset + old.count - current.count }
|
||||
else { self.offset = prefix }
|
||||
safeScopes = !changed || (old[changedRange].allSatisfy(CMOCCompletion.identifierPart) && current[prefix..<(current.count - suffix)].allSatisfy(CMOCCompletion.identifierPart))
|
||||
}
|
||||
func keeps(_ symbol: CMOCProjectIndex.Symbol) -> Bool {
|
||||
let token = symbol.offsetUTF16..<(symbol.offsetUTF16 + symbol.lengthUTF16)
|
||||
return !token.overlaps(changedRange) && !(changedRange.isEmpty && token.contains(changedRange.lowerBound))
|
||||
}
|
||||
}
|
||||
private struct Token {
|
||||
let text: String, offset: Int
|
||||
var identifier: Bool { text.utf16.first.map(CMOCCompletion.identifierStart) == true }
|
||||
}
|
||||
private struct Scan { let tokens: [Token]; let suppressed: Bool; var literal = false }
|
||||
/// Scans only the prefix before the caret, retaining delimiters but treating
|
||||
/// literals/comments/directives as opaque. Continued lines remain opaque.
|
||||
private static func scan(_ units: [UInt16], to end: Int) -> Scan? {
|
||||
var tokens: [Token] = [], i = 0, lineStart = true
|
||||
while i < end {
|
||||
if tokens.count >= CMOCProjectIndex.maximumTokens || (i % 1024 == 0 && Task.isCancelled) { return nil }
|
||||
let c = units[i], next = i + 1 < end ? units[i + 1] : 0
|
||||
if c == 10 || c == 13 { lineStart = true; i += 1; continue }
|
||||
if c == 32 || c == 9 { i += 1; continue }
|
||||
if (lineStart && c == 35) || (c == 47 && next == 47) {
|
||||
i += 1
|
||||
while i < end {
|
||||
if units[i] == 10 {
|
||||
let previous = i > 0 && units[i - 1] == 13 ? i - 2 : i - 1
|
||||
if previous < 0 || units[previous] != 92 { break }
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
if i == end { return .init(tokens: tokens, suppressed: true) }
|
||||
continue
|
||||
}
|
||||
if c == 47 && next == 42 {
|
||||
i += 2; var closed = false
|
||||
while i < end {
|
||||
if units[i] == 42, i + 1 < end, units[i + 1] == 47 { i += 2; closed = true; break }
|
||||
if units[i] == 10 { lineStart = true }; i += 1
|
||||
}
|
||||
if !closed { return .init(tokens: tokens, suppressed: true) }; continue
|
||||
}
|
||||
lineStart = false
|
||||
if c == 34 || c == 39 {
|
||||
let quote = c; i += 1; var closed = false
|
||||
while i < end {
|
||||
if units[i] == 92 { i += min(2, end - i); continue }
|
||||
if units[i] == quote { i += 1; closed = true; break }
|
||||
i += 1
|
||||
}
|
||||
if !closed { return .init(tokens: tokens, suppressed: true, literal: true) }; continue
|
||||
}
|
||||
let start = i; i += 1
|
||||
if identifierPart(c) { while i < end && identifierPart(units[i]) { i += 1 } }
|
||||
else if c == 45 && next == 62 { i += 1 }
|
||||
tokens.append(.init(text: String(decoding: units[start..<i], as: UTF16.self), offset: start))
|
||||
}
|
||||
return .init(tokens: tokens, suppressed: false)
|
||||
}
|
||||
private static func identifierStart(_ c: UInt16) -> Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) }
|
||||
private static func identifierPart(_ c: UInt16) -> Bool { identifierStart(c) || (48...57).contains(c) }
|
||||
private static func parameters(in signature: String, name: String) -> [String]? {
|
||||
if signature.hasPrefix("#define ") && !signature.hasPrefix("#define " + name + "(") { return nil }
|
||||
let declaration = signature.hasPrefix("#define ") ? String(signature.dropFirst(8)) : signature
|
||||
let units = Array(declaration.utf16)
|
||||
guard let scan = scan(units, to: units.count), !scan.suppressed else { return nil }
|
||||
let tokens = scan.tokens
|
||||
guard let nameIndex = tokens.indices.first(where: { tokens[$0].text == name && $0 + 1 < tokens.count && tokens[$0 + 1].text == "(" }) else { return nil }
|
||||
var depth = 0, parts: [[String]] = [[]]
|
||||
for token in tokens[(nameIndex + 2)...] {
|
||||
if token.text == ")", depth == 0 {
|
||||
let parameters = parts.map { $0.joined(separator: " ").replacingOccurrences(of: ". . .", with: "...") }
|
||||
return parameters == [""] || parameters == ["void"] ? [] : parameters
|
||||
}
|
||||
if token.text == ",", depth == 0 { parts.append([]); continue }
|
||||
if ["(", "[", "{"].contains(token.text) { depth += 1 }
|
||||
if [")", "]", "}"].contains(token.text) { depth -= 1; if depth < 0 { return nil } }
|
||||
parts[parts.count - 1].append(token.text)
|
||||
}
|
||||
return nil // The index bounds display signatures; never guess truncated parameters.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
|
||||
/// AppKit supplies the native completion list and keyboard behavior. Suggestions
|
||||
/// never provisionally rewrite source: only a final, still-valid choice is an
|
||||
/// editor operation, preserving the normal document Undo manager.
|
||||
class CMOCCompletionTextView: NSTextView, SourceFindEditor {
|
||||
weak var sourceFind: SourceFind?
|
||||
var completionProvider: ((String, Int) -> [CMOCCompletion.Candidate])?
|
||||
var completionStatus: ((String) -> Void)?
|
||||
var parameterHintAction: (() -> Void)?
|
||||
var assistanceFocusLost: (() -> Void)?
|
||||
private var completionSource: String?
|
||||
private var completionRange = NSRange(location: NSNotFound, length: 0)
|
||||
private var completionOffset = 0
|
||||
private var completionCandidates: [CMOCCompletion.Candidate] = []
|
||||
|
||||
@discardableResult func prepareCompletion() -> Bool {
|
||||
invalidateCompletion()
|
||||
guard isEditable else { completionStatus?("Completion is available in editable C sources."); return false }
|
||||
guard !hasMarkedText() else { completionStatus?("Finish the current text composition before completing an identifier."); return false }
|
||||
guard selectedRange().length == 0 else { completionStatus?("Place the insertion point inside or after an identifier to complete it."); return false }
|
||||
guard let completionProvider else { completionStatus?("Source completion is not ready for this editor."); return false }
|
||||
let source = string, offset = selectedRange().location
|
||||
let candidates = completionProvider(source, offset)
|
||||
guard let first = candidates.first, first.replacementRange.location != NSNotFound,
|
||||
NSMaxRange(first.replacementRange) <= (source as NSString).length else {
|
||||
completionStatus?("No completion candidates here. Suggestions use the project’s source index.")
|
||||
return false
|
||||
}
|
||||
completionSource = source; completionRange = first.replacementRange; completionOffset = offset
|
||||
completionCandidates = candidates.filter { $0.replacementRange == first.replacementRange }
|
||||
let uncertain = completionCandidates.contains { $0.conditional }
|
||||
completionStatus?("\(completionCandidates.count) source-based suggestions" + (uncertain ? " · Some candidates depend on build settings or scope." : "."))
|
||||
return true
|
||||
}
|
||||
func invalidateCompletion() {
|
||||
completionSource = nil; completionRange = NSRange(location: NSNotFound, length: 0)
|
||||
completionCandidates = []
|
||||
}
|
||||
override func complete(_ sender: Any?) {
|
||||
guard prepareCompletion() else { return }
|
||||
super.complete(sender)
|
||||
}
|
||||
override var rangeForUserCompletion: NSRange {
|
||||
completionSource == string ? completionRange : NSRange(location: NSNotFound, length: 0)
|
||||
}
|
||||
override func completions(forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String]? {
|
||||
guard isEditable, completionSource == string, charRange == completionRange else { return [] }
|
||||
index?.pointee = -1
|
||||
return completionCandidates.map(\.insertion)
|
||||
}
|
||||
override func insertCompletion(_ word: String, forPartialWordRange charRange: NSRange, movement: Int, isFinal flag: Bool) {
|
||||
// The native list asks to preview candidates as the selection moves.
|
||||
// Keeping these out of the document also keeps them out of draft recovery.
|
||||
guard flag else { return }
|
||||
defer { invalidateCompletion() }
|
||||
guard movement != NSTextMovement.cancel.rawValue, isEditable, !hasMarkedText(), completionSource == string,
|
||||
selectedRange() == NSRange(location: completionOffset, length: 0),
|
||||
charRange == completionRange,
|
||||
completionCandidates.contains(where: { $0.insertion == word }),
|
||||
completionRange.location != NSNotFound, NSMaxRange(completionRange) <= (string as NSString).length else { return }
|
||||
breakUndoCoalescing()
|
||||
insertText(word, replacementRange: completionRange)
|
||||
breakUndoCoalescing()
|
||||
undoManager?.setActionName("Complete Identifier")
|
||||
}
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
invalidateCompletion()
|
||||
if sourceFind?.cancel(from: self) != true {
|
||||
_ = nextResponder?.tryToPerform(#selector(NSResponder.cancelOperation(_:)), with: sender)
|
||||
}
|
||||
}
|
||||
override func resignFirstResponder() -> Bool {
|
||||
let resigned = super.resignFirstResponder()
|
||||
if resigned { invalidateCompletion(); assistanceFocusLost?() }
|
||||
return resigned
|
||||
}
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
let modifiers = event.modifierFlags.intersection([.command, .control, .option, .shift])
|
||||
if event.keyCode == 49, modifiers == [.control] { complete(nil); return true }
|
||||
if event.keyCode == 49, modifiers == [.control, .shift] { parameterHintAction?(); return true }
|
||||
return super.performKeyEquivalent(with: event)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,175 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
|
||||
enum CMOCEditorAction: String, CaseIterable {
|
||||
case indent = "Indent", outdent = "Outdent", comment = "Toggle Line Comment", match = "Go to Matching Bracket"
|
||||
}
|
||||
|
||||
/// Small source edits, not a formatter. Coordinates and selections use UTF-16.
|
||||
enum CMOCEditing {
|
||||
struct Edit { let range: NSRange; let text: String; let selection: NSRange }
|
||||
static func lineEdit(_ text: String, selection: NSRange, action: CMOCEditorAction) -> Edit? {
|
||||
let source = text as NSString
|
||||
guard selection.location <= source.length, selection.length <= source.length - selection.location,
|
||||
text.utf8.count <= 1_048_576, action != .match else { return nil }
|
||||
let first = source.lineRange(for: NSRange(location: selection.location, length: 0)).location
|
||||
let last = selection.length == 0 ? selection.location : NSMaxRange(selection) - 1
|
||||
let end = NSMaxRange(source.lineRange(for: NSRange(location: last, length: 0)))
|
||||
let range = NSRange(location: first, length: end - first)
|
||||
let original = source.substring(with: range) as NSString
|
||||
var lines: [(offset: Int, text: String)] = [], cursor = 0
|
||||
repeat {
|
||||
let line = original.lineRange(for: NSRange(location: cursor, length: 0))
|
||||
lines.append((cursor, original.substring(with: line)))
|
||||
cursor = NSMaxRange(line)
|
||||
} while cursor < original.length
|
||||
let uncomment = action == .comment && lines.filter { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||||
.allSatisfy { $0.text.trimmingCharacters(in: .whitespaces).hasPrefix("//") }
|
||||
var output = "", caret = selection.location - first
|
||||
for line in lines {
|
||||
let units = Array(line.text.utf16)
|
||||
let leading = units.prefix { $0 == 32 || $0 == 9 }.count
|
||||
let blank = line.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
var at = 0, remove = 0, insert = ""
|
||||
switch action {
|
||||
case .indent: insert = " "
|
||||
case .outdent: remove = units.first == 9 ? 1 : units.prefix { $0 == 32 }.prefix(4).count
|
||||
case .comment:
|
||||
if !blank { at = leading; if uncomment {
|
||||
remove = 2 + ((leading + 2 < units.count && units[leading + 2] == 32) ? 1 : 0)
|
||||
} else { insert = "// " } }
|
||||
case .match: break
|
||||
}
|
||||
if selection.length == 0, line.offset + at <= selection.location - first {
|
||||
caret += insert.utf16.count - min(remove, max(0, selection.location - first - line.offset - at))
|
||||
}
|
||||
output += (line.text as NSString).replacingCharacters(in: NSRange(location: at, length: remove), with: insert)
|
||||
}
|
||||
guard output != original as String else { return nil }
|
||||
let selected = selection.length == 0 ? NSRange(location: first + caret, length: 0) : NSRange(location: first, length: output.utf16.count)
|
||||
return .init(range: range, text: output, selection: selected)
|
||||
}
|
||||
/// Pair only C code delimiters; literals, comments and directives are opaque.
|
||||
static func bracketPairs(_ text: String) -> [Int: Int] {
|
||||
guard text.utf8.count <= 1_048_576 else { return [:] }
|
||||
let u = Array(text.utf16); var i = 0, stack: [(UInt16, Int)] = [], pairs: [Int: Int] = [:], lineStart = true
|
||||
while i < u.count {
|
||||
let c = u[i], next: UInt16 = i + 1 < u.count ? u[i + 1] : 0
|
||||
if c == 10 || c == 13 { lineStart = true; i += 1; continue }
|
||||
if c == 32 || c == 9 { i += 1; continue }
|
||||
if (lineStart && c == 35) || (c == 47 && next == 47) {
|
||||
while i < u.count {
|
||||
if u[i] == 10 {
|
||||
let previous = i > 0 && u[i - 1] == 13 ? i - 2 : i - 1
|
||||
if previous < 0 || u[previous] != 92 { break }
|
||||
}
|
||||
i += 1
|
||||
}; continue
|
||||
}
|
||||
if c == 47 && next == 42 {
|
||||
i += 2
|
||||
while i < u.count {
|
||||
if u[i] == 42 && i + 1 < u.count && u[i + 1] == 47 { i += 2; break }
|
||||
if u[i] == 10 { lineStart = true }; i += 1
|
||||
}; continue
|
||||
}
|
||||
lineStart = false
|
||||
if c == 34 || c == 39 {
|
||||
let quote = c; i += 1
|
||||
while i < u.count {
|
||||
if u[i] == 92 { i += min(2, u.count - i); continue }
|
||||
if u[i] == quote { i += 1; break }; i += 1
|
||||
}; continue
|
||||
}
|
||||
if [UInt16(40), 91, 123].contains(c) {
|
||||
guard stack.count < 512 else { return [:] }; stack.append((c, i))
|
||||
} else if [UInt16(41), 93, 125].contains(c) {
|
||||
let expected: UInt16 = c == 41 ? 40 : c == 93 ? 91 : 123
|
||||
if let top = stack.last, top.0 == expected { pairs[top.1] = i; pairs[i] = top.1; stack.removeLast() }
|
||||
else { stack.removeAll() }
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
static func newline(_ text: String, selection: NSRange) -> String {
|
||||
let s = text as NSString
|
||||
guard selection.location <= s.length else { return "\n" }
|
||||
let range = s.lineRange(for: NSRange(location: selection.location, length: 0))
|
||||
let before = s.substring(with: NSRange(location: range.location, length: selection.location - range.location))
|
||||
let indent = String(before.prefix { $0 == " " || $0 == "\t" })
|
||||
let trimmed = before.trimmingCharacters(in: .whitespaces)
|
||||
// A temporary closing brace lets the same lexer recognize an unmatched
|
||||
// opening brace without mistaking a brace in a literal/comment for code.
|
||||
let prefix = s.substring(to: selection.location).trimmingCharacters(in: .whitespaces)
|
||||
let opensBlock = trimmed.hasSuffix("{") && bracketPairs(prefix + "}")[prefix.utf16.count] == prefix.utf16.count - 1
|
||||
let ending = text.contains("\r\n") ? "\r\n" : "\n"
|
||||
return ending + indent + (opensBlock ? (indent.contains("\t") ? "\t" : " ") : "")
|
||||
}
|
||||
}
|
||||
|
||||
class CMOCEditingTextView: CMOCCompletionTextView {
|
||||
var sourceEditingEnabled = true
|
||||
private var pairedText: String?
|
||||
private var pairs: [Int: Int] = [:]
|
||||
private var highlighted: [Int] = []
|
||||
func refreshBracketHighlight() {
|
||||
guard let layoutManager else { return }
|
||||
// Edits can shift old temporary ranges; clear this editor's bracket
|
||||
// overlay before painting the new pair. Execution-line color lives in
|
||||
// text storage and is unaffected.
|
||||
layoutManager.removeTemporaryAttribute(.backgroundColor, forCharacterRange: NSRange(location: 0, length: (string as NSString).length))
|
||||
highlighted = []
|
||||
guard sourceEditingEnabled, !hasMarkedText(), selectedRange().length == 0 else { return }
|
||||
if pairedText != string { pairedText = string; pairs = CMOCEditing.bracketPairs(string) }
|
||||
let caret = selectedRange().location
|
||||
guard let origin = pairs[caret] != nil ? caret : (caret > 0 && pairs[caret - 1] != nil ? caret - 1 : nil), let mate = pairs[origin] else { return }
|
||||
highlighted = [origin, mate]
|
||||
for offset in highlighted {
|
||||
layoutManager.addTemporaryAttribute(.backgroundColor, value: NSColor.controlAccentColor.withAlphaComponent(0.3), forCharacterRange: NSRange(location: offset, length: 1))
|
||||
}
|
||||
}
|
||||
@objc func indentSource(_ sender: Any?) { performSourceAction(.indent) }
|
||||
@objc func outdentSource(_ sender: Any?) { performSourceAction(.outdent) }
|
||||
@objc func toggleSourceComment(_ sender: Any?) { performSourceAction(.comment) }
|
||||
@objc func matchSourceBracket(_ sender: Any?) { performSourceAction(.match) }
|
||||
func performSourceAction(_ action: CMOCEditorAction) {
|
||||
guard sourceEditingEnabled, !hasMarkedText(), selectedRanges.count == 1 else { return }
|
||||
invalidateCompletion()
|
||||
if action == .match {
|
||||
refreshBracketHighlight()
|
||||
if highlighted.count == 2 {
|
||||
let target = highlighted[1]
|
||||
setSelectedRange(NSRange(location: target, length: 0)); scrollRangeToVisible(NSRange(location: target, length: 1))
|
||||
} else { completionStatus?("Place the insertion point beside a matched code bracket: ( ), [ ] or { }.") }
|
||||
return
|
||||
}
|
||||
guard isEditable, let edit = CMOCEditing.lineEdit(string, selection: selectedRange(), action: action) else { return }
|
||||
breakUndoCoalescing(); insertText(edit.text, replacementRange: edit.range)
|
||||
setSelectedRange(edit.selection); breakUndoCoalescing(); undoManager?.setActionName(action.rawValue)
|
||||
refreshBracketHighlight()
|
||||
}
|
||||
override func insertTab(_ sender: Any?) {
|
||||
guard sourceEditingEnabled, isEditable, !hasMarkedText() else { super.insertTab(sender); return }
|
||||
if selectedRange().length > 0 { performSourceAction(.indent) }
|
||||
else { insertText(" ", replacementRange: selectedRange()) }
|
||||
}
|
||||
override func insertBacktab(_ sender: Any?) {
|
||||
if sourceEditingEnabled { performSourceAction(.outdent) } else { super.insertBacktab(sender) }
|
||||
}
|
||||
override func insertNewline(_ sender: Any?) {
|
||||
guard sourceEditingEnabled, isEditable, !hasMarkedText() else { super.insertNewline(sender); return }
|
||||
let value = CMOCEditing.newline(string, selection: selectedRange())
|
||||
breakUndoCoalescing(); insertText(value, replacementRange: selectedRange()); breakUndoCoalescing()
|
||||
}
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
guard sourceEditingEnabled else { return super.performKeyEquivalent(with: event) }
|
||||
let flags = event.modifierFlags.intersection([.command, .control, .shift, .option])
|
||||
let key = event.charactersIgnoringModifiers
|
||||
if flags == [.command], key == "/" { performSourceAction(.comment); return true }
|
||||
if flags == [.control], key == "]" { performSourceAction(.indent); return true }
|
||||
if flags == [.control], key == "[" { performSourceAction(.outdent); return true }
|
||||
if flags == [.control], key?.lowercased() == "m" { performSourceAction(.match); return true }
|
||||
return super.performKeyEquivalent(with: event)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Read-only inputs for browsing. Never invokes Make or a compiler to discover
|
||||
/// flags, and never follows project links into unrelated folders.
|
||||
struct CMOCIndexInputs: Sendable {
|
||||
static let libraryPrefix = "@toolchain/include/"
|
||||
static let maximumBytes = 16 * 1024 * 1024
|
||||
static let maximumFiles = 1024
|
||||
var documents: [String: String] = [:]
|
||||
var referencePaths: Set<String> = []
|
||||
var generatedPaths: Set<String> = []
|
||||
var issues: [String] = []
|
||||
var defines: [String] = []
|
||||
var includePaths: [String] = []
|
||||
var configurationUncertain = true
|
||||
|
||||
static func load(project: CMOCProject, toolchain: URL, configurationName: String,
|
||||
overlays: [String: String], generated: [String: Data]) throws -> Self {
|
||||
var result = Self(), total = 0
|
||||
func issue(_ message: String) { if result.issues.count < 16 { result.issues.append(message) } }
|
||||
func accept(_ text: String, path: String) {
|
||||
guard !text.contains("\0"), text.utf8.count <= CMOCProject.maximumSourceBytes else {
|
||||
issue("Skipped oversized or non-text file: \(path)"); return
|
||||
}
|
||||
let oldSize = result.documents[path]?.utf8.count ?? 0
|
||||
guard (result.documents[path] != nil || result.documents.count < maximumFiles),
|
||||
total - oldSize + text.utf8.count <= maximumBytes else {
|
||||
issue("Index limited to \(maximumFiles) files and 16 MB of text."); return
|
||||
}
|
||||
total += text.utf8.count - oldSize; result.documents[path] = text
|
||||
}
|
||||
// An edited configuration is a browsing hint only, never a build command.
|
||||
var configuration = project.configuration
|
||||
if let text = overlays[CMOCProject.configurationFilename] ?? (try? project.readText(relativePath: CMOCProject.configurationFilename)) {
|
||||
do { configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(text.utf8)).validated() }
|
||||
catch { issue("Project settings contain errors; using the last accepted browsing settings.") }
|
||||
}
|
||||
let generatedOutputs = Set(configuration.makefileSettings?.generatedResources.flatMap(\.outputs) ?? [])
|
||||
let root = try CMOCProject.physicalURL(project.directory)
|
||||
var readError: Error?
|
||||
let keys: Set<URLResourceKey> = [.isRegularFileKey, .isSymbolicLinkKey, .isDirectoryKey, .fileSizeKey]
|
||||
let excluded: Set<String> = [".git", ".svn", ".build", ".vccplus-build", ".DS_Store"]
|
||||
guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: Array(keys),
|
||||
errorHandler: { _, error in readError = error; return false }) else {
|
||||
throw CMOCBuildError.message("The project could not be read for navigation.")
|
||||
}
|
||||
var urls: [(String, URL)] = []
|
||||
var visited = 0
|
||||
while let url = enumerator.nextObject() as? URL {
|
||||
try Task.checkCancellation(); visited += 1
|
||||
guard visited <= 20_000 else { issue("Project navigation stopped after 20,000 entries."); break }
|
||||
if excluded.contains(url.lastPathComponent) { enumerator.skipDescendants(); continue }
|
||||
let path = String(url.path.dropFirst(root.path.count + 1))
|
||||
if path.hasPrefix(libraryPrefix) { enumerator.skipDescendants(); issue("Reserved library-reference path omitted from project: \(path)"); continue }
|
||||
let values = try url.resourceValues(forKeys: keys)
|
||||
if values.isSymbolicLink == true { enumerator.skipDescendants(); issue("Linked file or folder omitted: \(path)"); continue }
|
||||
if values.isDirectory == true { continue }
|
||||
guard values.isRegularFile == true, CMOCProject.isEditable(path), !generatedOutputs.contains(path) else { continue }
|
||||
guard let size = values.fileSize, size <= CMOCProject.maximumSourceBytes else { issue("Oversized text file omitted: \(path)"); continue }
|
||||
urls.append((path, url))
|
||||
}
|
||||
if let readError { issue("Some project files could not be read: " + readError.localizedDescription) }
|
||||
for (path, _) in urls.sorted(by: { $0.0 < $1.0 }) {
|
||||
try Task.checkCancellation()
|
||||
if let overlay = overlays[path] { accept(overlay, path: path); continue }
|
||||
do { accept(try project.readText(relativePath: path), path: path) }
|
||||
catch { issue("Unreadable text file omitted: \(path)") }
|
||||
if result.documents.count >= maximumFiles || total >= maximumBytes { issue("Project text limit reached; some files are not indexed."); break }
|
||||
}
|
||||
for (path, text) in overlays.sorted(by: { $0.key < $1.key }) {
|
||||
try Task.checkCancellation()
|
||||
guard !path.hasPrefix(libraryPrefix), CMOCProject.isEditable(path) else { continue }
|
||||
_ = try project.fileURL(relativePath: path)
|
||||
accept(text, path: path)
|
||||
}
|
||||
for (path, data) in generated.sorted(by: { $0.key < $1.key }) where result.documents[path] == nil && ["c", "h"].contains((path as NSString).pathExtension.lowercased()) {
|
||||
try Task.checkCancellation()
|
||||
try CMOCProject.validateRelativePath(path)
|
||||
guard data.count <= CMOCProject.maximumSourceBytes, let text = String(data: data, encoding: .utf8) else { continue }
|
||||
accept(text, path: path); if result.documents[path] != nil { result.generatedPaths.insert(path) }
|
||||
}
|
||||
if !result.generatedPaths.isEmpty { issue("Generated sources are read-only snapshots from the last successful build.") }
|
||||
|
||||
if let recipe = configuration.makefileSettings {
|
||||
result.includePaths = recipe.includePaths
|
||||
result.defines = recipe.defines
|
||||
// Trust flags only when the current Makefile exactly matches the
|
||||
// generated recipe, and selected Make assignments cannot alter it.
|
||||
let expected = try? recipe.generateMakefile(makefileName: configuration.makefile)
|
||||
let current = result.documents[configuration.makefile]
|
||||
let assignments = configuration.configurations.first(where: { $0.name == configurationName })?.makeArguments ?? []
|
||||
result.configurationUncertain = expected == nil || current != expected || assignments.contains { !$0.hasPrefix("VCC_CONFIGURATION=") }
|
||||
var coco = true, unsignedChar = false, noRelocate = false
|
||||
var floatingPointMacro: String?
|
||||
var undefined: Set<String> = []
|
||||
for option in recipe.compilerOptions {
|
||||
if option.hasPrefix("-D"), option.count > 2 { result.defines.append(String(option.dropFirst(2))) }
|
||||
else if option.hasPrefix("-I"), option.count > 2 {
|
||||
let path = String(option.dropFirst(2))
|
||||
if (try? project.fileURL(relativePath: path)) != nil { result.includePaths.append(path) }
|
||||
else { issue("External include path is not browsed: \(path)"); result.configurationUncertain = true }
|
||||
} else if option == "-funsigned-char" { unsignedChar = true }
|
||||
else if option == "-fsigned-char" { unsignedChar = false }
|
||||
else if option == "--native-float" { floatingPointMacro = "_CMOC_NATIVE_FLOAT_=1" }
|
||||
else if option == "--mc6839" { floatingPointMacro = "_CMOC_MC6839_=1" }
|
||||
else if option == "--no-relocate" { noRelocate = true }
|
||||
else if option.hasPrefix("-U"), option.count > 2 { undefined.insert(String(option.dropFirst(2))); result.configurationUncertain = true }
|
||||
else if option == "--coco" { coco = true }
|
||||
else if ["--os9", "--vectrex", "--dragon", "--usim", "--thommo", "--void-target"].contains(option) { coco = false; result.configurationUncertain = true }
|
||||
else if !["-O0", "-O1", "-O2", "-fno-omit-frame-pointer", "--intermediate", "--deps"].contains(option) { result.configurationUncertain = true }
|
||||
}
|
||||
// CMOC resolves mode switches in argument order, then emits its
|
||||
// builtin definitions before all user -D arguments. Preserve that
|
||||
// order so explicit user values can override a builtin value.
|
||||
var builtins: [String] = []
|
||||
if coco { builtins.append("_COCO_BASIC_=1") }
|
||||
if unsignedChar { builtins.append("_CMOC_unsigned_char_=1") }
|
||||
if noRelocate { builtins.append("_CMOC_NO_RELOCATE_=1") }
|
||||
if let floatingPointMacro { builtins.append(floatingPointMacro) }
|
||||
result.defines.insert(contentsOf: builtins, at: 0)
|
||||
result.defines.removeAll { undefined.contains(String($0.prefix { $0 != "=" })) }
|
||||
}
|
||||
if result.configurationUncertain { issue("Custom Make flags are not evaluated; conditional definitions are browsing candidates, not compiler-verified bindings.") }
|
||||
if let data = try? Data(contentsOf: toolchain.appendingPathComponent("manifest.json")),
|
||||
let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let version = manifest["cmoc"] as? String {
|
||||
let components = version.split(separator: ".").compactMap { Int($0) }
|
||||
if components.count == 3 { result.defines.insert("_CMOC_VERSION_=\(components[0] * 1000000 + components[1] * 1000 + components[2])", at: 0) }
|
||||
}
|
||||
let undefined = Set((configuration.makefileSettings?.compilerOptions ?? []).filter { $0.hasPrefix("-U") && $0.count > 2 }.map { String($0.dropFirst(2)) })
|
||||
result.defines.removeAll { undefined.contains(String($0.prefix { $0 != "=" })) }
|
||||
let requestedHeaders = toolchain.appendingPathComponent("share/cmoc/include")
|
||||
if (try? requestedHeaders.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true {
|
||||
issue("Linked library include folder is not browsed."); return result
|
||||
}
|
||||
guard let headers = try? CMOCProject.physicalURL(requestedHeaders) else {
|
||||
issue("Bundled library headers are unavailable; project navigation remains available."); return result
|
||||
}
|
||||
let compatibility = configuration.makefileSettings?.libraries.contains("vcccompat") == true ||
|
||||
configuration.bundledLibraries.contains { $0.library == "vcccompat" }
|
||||
if compatibility { result.includePaths.append("@toolchain/include/vcc/compat") }
|
||||
result.includePaths.append("@toolchain/include")
|
||||
if let libraryFiles = FileManager.default.enumerator(at: headers, includingPropertiesForKeys: Array(keys), errorHandler: { _, _ in false }) {
|
||||
var count = 0
|
||||
while let url = libraryFiles.nextObject() as? URL {
|
||||
try Task.checkCancellation(); count += 1
|
||||
guard count <= 4096 else { issue("Library header scan reached its limit."); break }
|
||||
let values = try url.resourceValues(forKeys: keys)
|
||||
if values.isSymbolicLink == true { libraryFiles.skipDescendants(); continue }
|
||||
if !compatibility, url == headers.appendingPathComponent("vcc/compat", isDirectory: true) {
|
||||
libraryFiles.skipDescendants(); continue
|
||||
}
|
||||
guard values.isRegularFile == true, url.pathExtension.lowercased() == "h" else { continue }
|
||||
let path = libraryPrefix + String(url.path.dropFirst(headers.path.count + 1))
|
||||
guard (values.fileSize ?? Int.max) <= CMOCProject.maximumSourceBytes,
|
||||
let text = try? CMOCProject.readText(url, maximumBytes: CMOCProject.maximumSourceBytes) else { issue("Library header omitted: \(path)"); continue }
|
||||
accept(text, path: path)
|
||||
if result.documents[path] != nil { result.referencePaths.insert(path) }
|
||||
}
|
||||
} else { issue("Bundled library headers are unavailable; project navigation remains available.") }
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Read-only evidence from an owned, paused run. This deliberately has no caller
|
||||
/// supplied memory address: the only newly disclosed storage is [S, S + 64).
|
||||
enum CMOCOwnedCallContext {
|
||||
static func capture(map: CMOCProjectSourceMap, metadata: CMOCVariableDebug?,
|
||||
pc: UInt16, s: UInt16, u: UInt16, memory: Data, available: Data,
|
||||
physicalPages: [Int: Int], sharedPaths: Set<String>) -> [String: Any] {
|
||||
func unavailable(_ reason: String) -> [String: Any] {
|
||||
["status": "unavailable", "reason": reason]
|
||||
}
|
||||
guard memory.count == 65536, available.count == 65536 else {
|
||||
return unavailable("A complete immutable memory and availability snapshot is required.")
|
||||
}
|
||||
let start = Int(s), limit = start + 64
|
||||
guard limit <= 0xfe00 else { return unavailable("The actual S window crosses protected memory or wraps.") }
|
||||
func ram(_ address: Int, _ count: Int) -> Bool {
|
||||
guard address >= 0, count > 0, address <= 0xfe00 - count else { return false }
|
||||
return (address / 8192...(address + count - 1) / 8192).allSatisfy {
|
||||
physicalPages[$0].map { (0..<1024).contains($0) } == true
|
||||
}
|
||||
}
|
||||
func readable(_ address: Int, _ count: Int) -> Bool {
|
||||
ram(address, count) && available[address..<(address + count)].allSatisfy { $0 != 0 }
|
||||
}
|
||||
guard readable(start, 64) else {
|
||||
return unavailable("Every byte of the actual S window must be available RAM with a physical mapping.")
|
||||
}
|
||||
let selected = map.projected(physicalPages: physicalPages, memory: memory, available: available)
|
||||
guard selected.verifiesRuntime(memory: memory, available: available), readable(Int(pc), 1) else {
|
||||
return unavailable("The current executable bytes or RAM mapping could not be verified.")
|
||||
}
|
||||
// Metadata must identify this same retained build. Use the supplied map's
|
||||
// current bank projection, never a metadata object's stale projection.
|
||||
let debug: CMOCVariableDebug?
|
||||
if let metadata,
|
||||
metadata.sourceMap.binarySHA256 == map.binarySHA256,
|
||||
metadata.sourceMap.linkMapSHA256 == map.linkMapSHA256,
|
||||
metadata.sourceMap.sourceHashes == map.sourceHashes,
|
||||
metadata.sourceMap.objectHashes == map.objectHashes,
|
||||
metadata.sourceMap.listingHashes == map.listingHashes {
|
||||
debug = CMOCVariableDebug(functions: metadata.functions, variables: metadata.variables,
|
||||
sourceMap: map).projected(physicalPages: physicalPages, memory: memory, available: available)
|
||||
} else { debug = nil }
|
||||
let function = debug?.entryFunction(containing: pc)
|
||||
let instruction = selected.instruction(at: pc)
|
||||
let mappedSource = instruction.map {
|
||||
sharedPaths.contains($0.sourcePath) && !$0.bytes.isEmpty && readable(Int(pc), $0.bytes.count) &&
|
||||
Array(memory[Int(pc)..<(Int(pc) + $0.bytes.count)]) == $0.bytes
|
||||
} == true
|
||||
let functionSource = function.map { sharedPaths.contains($0.sourcePath) } == true
|
||||
let executableSource = selected.executableLocation(at: pc, memory: memory, available: available, sharedPaths: sharedPaths) != nil
|
||||
guard mappedSource || functionSource || executableSource else {
|
||||
return unavailable("The current PC has no verified executable identity in shared source.")
|
||||
}
|
||||
|
||||
var spans: [[String: Any]] = [], cursor = start
|
||||
while cursor < limit {
|
||||
let end = min(limit, (cursor / 8192 + 1) * 8192)
|
||||
spans.append(["logical_address": cursor, "physical_address": physicalPages[cursor / 8192]! * 8192 + cursor % 8192,
|
||||
"count": end - cursor])
|
||||
cursor = end
|
||||
}
|
||||
let words = stride(from: 0, to: 64, by: 2).map { offset -> [String: Any] in
|
||||
["offset": offset, "address": start + offset,
|
||||
"value": Int(memory[start + offset]) * 256 + Int(memory[start + offset + 1])]
|
||||
}
|
||||
var result: [String: Any] = [
|
||||
"status": "available",
|
||||
"stack_window": ["address": start, "count": 64, "bytes": Array(memory[start..<limit]),
|
||||
"words_be": words, "physical_spans": spans, "interpretation": "uninterpreted"],
|
||||
"caller": unavailable("No proven normal C call frame is available at this stop."),
|
||||
"arguments": unavailable("Typed arguments require a verified normal CMOC frame and direct caller.")
|
||||
]
|
||||
guard let debug, let function, functionSource else { return result }
|
||||
|
||||
// These bytes must belong to verified executable guards, not merely be
|
||||
// coincidentally present in writable RAM. No stack scanning is involved.
|
||||
func guarded(_ address: Int, _ bytes: [UInt8], moduleID: String?) -> Bool {
|
||||
guard readable(address, bytes.count) else { return false }
|
||||
let guards: [(Int, [UInt8])]
|
||||
if let layout = selected.bankedLayout {
|
||||
guard let moduleID, selected.activeModuleIDs?.contains(moduleID) == true,
|
||||
let module = layout.module(id: moduleID) else { return false }
|
||||
guards = module.codeGuards.map { (Int($0.address), $0.bytes) }
|
||||
} else {
|
||||
guard moduleID == nil else { return false }
|
||||
guards = selected.flatCodeGuards.map { (Int($0.address), $0.bytes) }
|
||||
}
|
||||
return bytes.enumerated().allSatisfy { offset, byte in
|
||||
let location = address + offset
|
||||
return memory[location] == byte && guards.contains { begin, data in
|
||||
location >= begin && location - begin < data.count && data[location - begin] == byte
|
||||
}
|
||||
}
|
||||
}
|
||||
func normal(_ f: CMOCVariableDebug.Function) -> Bool {
|
||||
f.frame && f.entry >= 0 && f.body >= f.entry + 4 && f.body < f.end && f.end <= 0xfe00 - 4 &&
|
||||
guarded(f.entry, [0x34, 0x40, 0x33, 0xe4], moduleID: f.moduleID) &&
|
||||
guarded(f.end, [0x32, 0xc4, 0x35, 0xc0], moduleID: f.moduleID)
|
||||
}
|
||||
guard normal(function) else { return result }
|
||||
let frameBase: Int, returnAddress: Int, phase: String
|
||||
if Int(pc) == function.entry {
|
||||
frameBase = start - 2 // U after the proven, as-yet unexecuted PSHS U.
|
||||
returnAddress = start; phase = "function_entry"
|
||||
} else if Int(pc) >= function.body, Int(pc) < function.end, mappedSource,
|
||||
Int(u) >= start, Int(u) <= limit - 4 {
|
||||
frameBase = Int(u); returnAddress = frameBase + 2; phase = "mapped_body"
|
||||
} else { return result }
|
||||
// Only these two bytes, already inside the raw window, identify a
|
||||
// potential caller. Never search other stack words for return addresses.
|
||||
let returnPC = Int(memory[returnAddress]) * 256 + Int(memory[returnAddress + 1])
|
||||
func target(_ i: CMOCProjectSourceMap.Instruction) -> Int? {
|
||||
let b = i.bytes, address = Int(i.address)
|
||||
switch b.count {
|
||||
case 2 where b[0] == 0x8d: return (address + 2 + Int(Int8(bitPattern: b[1]))) & 0xffff
|
||||
case 3 where b[0] == 0x17:
|
||||
return (address + 3 + Int(Int16(bitPattern: UInt16(b[1]) << 8 | UInt16(b[2])))) & 0xffff
|
||||
case 3 where b[0] == 0xbd: return Int(b[1]) * 256 + Int(b[2])
|
||||
case 3 where b[0] == 0xad && b[1] == 0x8c:
|
||||
return (address + 3 + Int(Int8(bitPattern: b[2]))) & 0xffff
|
||||
case 4 where b[0] == 0xad && b[1] == 0x8d:
|
||||
return (address + 4 + Int(Int16(bitPattern: UInt16(b[2]) << 8 | UInt16(b[3])))) & 0xffff
|
||||
default: return nil // Indirect, tail, interrupt and guessed calls are unsupported.
|
||||
}
|
||||
}
|
||||
let calls = selected.instructions.filter {
|
||||
Int($0.address) + $0.bytes.count == returnPC && target($0) == function.entry
|
||||
}
|
||||
guard calls.count == 1, let call = calls.first, sharedPaths.contains(call.sourcePath),
|
||||
guarded(Int(call.address), call.bytes, moduleID: call.moduleID),
|
||||
let caller = debug.entryFunction(containing: call.address), normal(caller),
|
||||
sharedPaths.contains(caller.sourcePath), caller.moduleID == call.moduleID,
|
||||
caller.name.utf8.count <= 1024, caller.sourcePath.utf8.count <= 4096,
|
||||
Int(call.address) >= caller.body else { return result }
|
||||
result["caller"] = ["status": "available", "function": caller.name, "source_path": caller.sourcePath,
|
||||
"source_line": call.sourceLine, "call_address": Int(call.address), "return_address": returnPC,
|
||||
"evidence": "unique_verified_direct_call", "callee_phase": phase]
|
||||
|
||||
let parameters = debug.variables.filter {
|
||||
$0.sourcePath == function.sourcePath && sharedPaths.contains($0.sourcePath) &&
|
||||
$0.moduleID == function.moduleID && ($0.scopeModuleID == nil || $0.scopeModuleID == function.moduleID) &&
|
||||
!$0.isStatic && $0.address == nil && $0.scope == (function.body..<function.end) && ($0.offset ?? 0) >= 4
|
||||
}.sorted { ($0.offset ?? 0) < ($1.offset ?? 0) }
|
||||
var items: [[String: Any]] = [], occupied = Set<Int>(), names = Set<String>()
|
||||
for (index, parameter) in parameters.prefix(32).enumerated() {
|
||||
guard let offset = parameter.offset, offset <= 32767,
|
||||
!parameter.name.isEmpty, parameter.name.utf8.count <= 1024,
|
||||
parameters.filter({ $0.name == parameter.name }).count == 1,
|
||||
names.insert(parameter.name).inserted else { continue }
|
||||
let address = frameBase + offset, type = parameter.type
|
||||
guard type.kind == "integer", [1, 2, 4].contains(type.size), type.name.utf8.count <= 1024, let signed = type.signed,
|
||||
address >= start, address <= limit - type.size,
|
||||
!parameters.enumerated().contains(where: { otherIndex, other in
|
||||
guard otherIndex != index, let otherOffset = other.offset,
|
||||
otherOffset <= 32767, other.type.size > 0, other.type.size <= 65536 else { return false }
|
||||
return offset < otherOffset + other.type.size && otherOffset < offset + type.size
|
||||
}),
|
||||
(address..<(address + type.size)).allSatisfy({ !occupied.contains($0) }) else { continue }
|
||||
var value: Int64 = 0
|
||||
for byte in memory[address..<(address + type.size)] { value = value * 256 + Int64(byte) }
|
||||
if signed && memory[address] & 0x80 != 0 { value -= Int64(1) << (type.size * 8) }
|
||||
occupied.formUnion(address..<(address + type.size))
|
||||
items.append(["name": parameter.name, "type": type.name, "address": address, "frame_offset": offset,
|
||||
"byte_count": type.size, "value": value, "evidence": "compiler_location_and_normal_cmoc_abi"])
|
||||
}
|
||||
result["arguments"] = ["status": items.isEmpty ? "unavailable" : "available", "items": items,
|
||||
"reason": "Only compiler-located integer parameters wholly inside the actual S window are interpreted; other values remain unavailable.",
|
||||
"all_recorded_parameters_available": !parameters.isEmpty && items.count == parameters.count,
|
||||
"recorded_parameter_count": parameters.count]
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// A bounded, non-executing lexical index. This is navigation assistance, not a
|
||||
/// compiler AST: macro expansion, arbitrary Make recipes and expression types
|
||||
/// are deliberately not guessed. Conditional candidates remain visibly marked.
|
||||
struct CMOCProjectIndex: Sendable {
|
||||
enum Kind: String, Sendable { case function = "Function", variable = "Variable", type = "Type", macro = "Macro", parameter = "Parameter", member = "Member", enumerator = "Enumerator" }
|
||||
struct Symbol: Identifiable, Hashable, Sendable {
|
||||
var id: String { "\(path):\(offsetUTF16):\(kind.rawValue)" }
|
||||
let path: String
|
||||
let name: String
|
||||
let line: Int
|
||||
let column: Int
|
||||
let kind: Kind
|
||||
let signature: String
|
||||
let isDefinition: Bool
|
||||
let isStatic: Bool
|
||||
let conditional: Bool
|
||||
let scope: String?
|
||||
let offsetUTF16: Int
|
||||
let lengthUTF16: Int
|
||||
fileprivate let scopeStart: Int
|
||||
fileprivate let scopeEnd: Int
|
||||
}
|
||||
struct Match: Identifiable, Hashable, Sendable {
|
||||
var id: String { "\(path):\(offsetUTF16):\(lengthUTF16)" }
|
||||
let path: String
|
||||
let line: Int
|
||||
let column: Int
|
||||
let lengthUTF16: Int
|
||||
let preview: String
|
||||
let offsetUTF16: Int
|
||||
}
|
||||
struct SearchResults: Sendable { let matches: [Match]; let truncated: Bool }
|
||||
static let maximumFiles = 1024
|
||||
static let maximumFileBytes = 1_048_576
|
||||
static let maximumTotalBytes = 16 * 1_048_576
|
||||
static let maximumTokens = 150_000
|
||||
static let maximumSymbols = 20_000
|
||||
let documents: [String: String]
|
||||
let symbols: [Symbol]
|
||||
let issues: [String]
|
||||
private let tokens: [String: [Token]]
|
||||
private struct Include: Sendable { let name: String; let quoted: Bool }
|
||||
private enum Directive: Sendable {
|
||||
case include(Include), define(String), undef(String)
|
||||
}
|
||||
private struct Step: Sendable {
|
||||
let directive: Directive
|
||||
let offset: Int
|
||||
let conditional: Bool
|
||||
}
|
||||
private let steps: [String: [Step]]
|
||||
private let guarded: Set<String>
|
||||
private let undefinedNames: Set<String>
|
||||
private let includePaths: [String]
|
||||
|
||||
init(documents input: [String: String], defines: [String] = [], includePaths: [String] = [], configurationUncertain: Bool = false) {
|
||||
var accepted: [String: String] = [:], notes: [String] = [], total = 0
|
||||
for path in input.keys.sorted() {
|
||||
if Task.isCancelled { notes.append("Index cancelled."); break }
|
||||
guard let text = input[path] else { continue }
|
||||
let size = text.utf8.count
|
||||
guard accepted.count < Self.maximumFiles, size <= Self.maximumFileBytes,
|
||||
total + size <= Self.maximumTotalBytes, !text.contains("\0") else {
|
||||
notes.append("Index omitted \(path): file/count/size limit or non-text contents."); continue
|
||||
}
|
||||
accepted[path] = text; total += size
|
||||
}
|
||||
var parsed: [String: [Token]] = [:], all: [Symbol] = [], links: [String: [Step]] = [:]
|
||||
var guards: [String: String] = [:], undefinedNames: Set<String> = []
|
||||
for path in accepted.keys.sorted() where ["c", "h"].contains((path as NSString).pathExtension.lowercased()) {
|
||||
if Task.isCancelled { notes.append("Index cancelled."); break }
|
||||
let source = accepted[path]!
|
||||
let preparation = Self.prepare(source, path: path, defines: defines, uncertain: configurationUncertain)
|
||||
let lexed = Self.lex(preparation.text, conditionalLines: preparation.conditionalLines)
|
||||
parsed[path] = lexed.tokens
|
||||
links[path] = preparation.steps
|
||||
guards[path] = preparation.guardName
|
||||
for step in preparation.steps {
|
||||
if case .undef(let name) = step.directive { undefinedNames.insert(name) }
|
||||
}
|
||||
if lexed.truncated { notes.append("Symbol scan stopped at \(Self.maximumTokens) tokens in \(path).") }
|
||||
var parser = Parser(path: path, source: source, tokens: lexed.tokens)
|
||||
parser.parse()
|
||||
if parser.limited { notes.append("Declaration scan reached its nesting or symbol limit in \(path).") }
|
||||
let additions = preparation.macros + parser.symbols
|
||||
let remaining = max(0, Self.maximumSymbols - all.count)
|
||||
all += additions.prefix(remaining)
|
||||
if additions.count > remaining { notes.append("Symbol limit reached; some declarations in \(path) were omitted.") }
|
||||
}
|
||||
if configurationUncertain { notes.append("Custom build flags are not evaluated. Definitions are lexical candidates; conditional branches may differ from the compiled program.") }
|
||||
self.documents = accepted; self.symbols = all.sorted { ($0.path, $0.offsetUTF16) < ($1.path, $1.offsetUTF16) }
|
||||
self.issues = Array(notes.prefix(32)); self.tokens = parsed; self.steps = links
|
||||
self.guarded = Set(guards.compactMap { undefinedNames.contains($0.value) ? nil : $0.key })
|
||||
self.undefinedNames = undefinedNames; self.includePaths = Array(includePaths.prefix(128))
|
||||
}
|
||||
func outline(path: String) -> [Symbol] { symbols.filter { $0.path == path && $0.scope == nil && $0.kind != .parameter && $0.kind != .member } }
|
||||
func token(atUTF16Offset offset: Int, in path: String) -> String? {
|
||||
guard let values = tokens[path], let token = values.first(where: { $0.identifier && $0.offset <= offset && offset < $0.offset + $0.text.utf16.count }) ?? values.last(where: { $0.identifier && $0.offset + $0.text.utf16.count == offset }) else { return nil }
|
||||
return token.text
|
||||
}
|
||||
/// Locals are visible only after their declaration and inside their lexical
|
||||
/// block. Member access has no inferred C type: return member candidates,
|
||||
/// never accidentally substitute a same-named global.
|
||||
func definitions(named name: String, from path: String, line: Int, column: Int) -> [Symbol] {
|
||||
guard !name.isEmpty, name.utf8.count <= 256 else { return [] }
|
||||
let offset = Self.offset(line: line, column: column, text: documents[path] ?? "")
|
||||
let fileTokens = tokens[path] ?? []
|
||||
let targetIndex = fileTokens.firstIndex { $0.text == name && $0.offset <= offset && offset < $0.offset + $0.text.utf16.count }
|
||||
?? fileTokens.lastIndex { $0.text == name && $0.offset + $0.text.utf16.count == offset }
|
||||
let preceding = targetIndex.flatMap { $0 > 0 ? fileTokens[$0 - 1] : nil }
|
||||
?? fileTokens.last { $0.offset < offset && $0.offset + $0.text.utf16.count <= offset }
|
||||
let member = preceding?.text == "." || preceding?.text == "->"
|
||||
let matches = symbols.filter { $0.name == name }
|
||||
if member { return matches.filter { $0.kind == .member }.map { $0.withConditional() } }
|
||||
let local = matches.filter { $0.path == path && $0.scope != nil && $0.kind != .member && $0.offsetUTF16 <= offset && $0.scopeStart <= offset && offset <= $0.scopeEnd }
|
||||
if let narrowest = local.map(\.scopeStart).max() { return local.filter { $0.scopeStart == narrowest }.sorted { $0.offsetUTF16 > $1.offsetUTF16 } }
|
||||
let visible = visibleFiles(from: path)
|
||||
let overrides = macroOverrides(from: path, offset: offset, names: [name])
|
||||
let globals = matches.filter { overrides.keeps($0) }.filter { $0.scope == nil && (!$0.isStatic || $0.path == path || visible.contains($0.path)) }
|
||||
let sameFile = globals.filter { $0.path == path && $0.isDefinition }
|
||||
if overrides.uncertain.contains(name) {
|
||||
return globals.filter { visible.contains($0.path) }.sorted { $0.kind != .macro && $1.kind == .macro }.map { $0.withConditional() }
|
||||
}
|
||||
if !sameFile.isEmpty { return sameFile }
|
||||
let visibleDefinitions = globals.filter { visible.contains($0.path) && $0.isDefinition }
|
||||
if !visibleDefinitions.isEmpty { return visibleDefinitions }
|
||||
// External definitions may reside in a different translation unit. Keep
|
||||
// duplicate external definitions visible instead of choosing by filename.
|
||||
let definitions = globals.filter { $0.isDefinition && !$0.isStatic && ($0.kind == .function || $0.kind == .variable) }
|
||||
if !definitions.isEmpty { return definitions }
|
||||
let declarations = globals.filter { visible.contains($0.path) || $0.path == path }
|
||||
return declarations.isEmpty ? globals.map { $0.withConditional() } : declarations
|
||||
}
|
||||
/// Completion is intentionally narrower than definition navigation: only
|
||||
/// declarations in this source and literal included headers participate.
|
||||
func completionSymbols(from path: String, offset: Int, prefix: String, includeLocals: Bool = true) -> [Symbol] {
|
||||
let visible = visibleFiles(from: path)
|
||||
var result = symbols.filter { symbol in
|
||||
guard symbol.name.hasPrefix(prefix), visible.contains(symbol.path), symbol.kind != .member else { return false }
|
||||
if symbol.path == path && symbol.offsetUTF16 > offset { return false }
|
||||
if symbol.scope != nil {
|
||||
return includeLocals && symbol.path == path && symbol.scopeStart <= offset && offset <= symbol.scopeEnd
|
||||
}
|
||||
return true
|
||||
}
|
||||
let overrides = macroOverrides(from: path, offset: offset, names: Set(result.lazy.filter { $0.kind == .macro }.map(\.name)))
|
||||
result = result.filter { overrides.keeps($0) }.map { overrides.uncertain.contains($0.name) ? $0.withConditional() : $0 }
|
||||
let locals = Dictionary(grouping: result.filter { $0.scope != nil }, by: \.name)
|
||||
result.removeAll { symbol in
|
||||
guard let scoped = locals[symbol.name], let innermost = scoped.map(\.scopeStart).max() else { return false }
|
||||
return symbol.scope == nil || symbol.scopeStart != innermost
|
||||
}
|
||||
return result.sorted {
|
||||
let a = ($0.scope == nil ? 1 : 0, $0.kind == .macro && overrides.uncertain.contains($0.name) ? 1 : 0, $0.path == path ? 0 : 1, $0.name, $0.path, $0.offsetUTF16)
|
||||
let b = ($1.scope == nil ? 1 : 0, $1.kind == .macro && overrides.uncertain.contains($1.name) ? 1 : 0, $1.path == path ? 0 : 1, $1.name, $1.path, $1.offsetUTF16)
|
||||
return a < b
|
||||
}
|
||||
}
|
||||
func search(query: String, caseSensitive: Bool = false, limit: Int = 500, paths: Set<String>? = nil) -> SearchResults {
|
||||
let limit = max(1, min(2000, limit))
|
||||
guard !query.isEmpty, query.utf16.count <= 1024 else { return .init(matches: [], truncated: false) }
|
||||
var found: [Match] = []
|
||||
for path in documents.keys.sorted() where paths == nil || paths!.contains(path) {
|
||||
if Task.isCancelled { return .init(matches: found, truncated: true) }
|
||||
let text = documents[path]! as NSString
|
||||
var start = 0
|
||||
while start < text.length {
|
||||
if Task.isCancelled { return .init(matches: found, truncated: true) }
|
||||
let range = text.range(of: query, options: caseSensitive ? [.literal] : [.literal, .caseInsensitive], range: NSRange(location: start, length: text.length - start))
|
||||
guard range.location != NSNotFound, range.length > 0 else { break }
|
||||
if found.count >= limit { return .init(matches: found, truncated: true) }
|
||||
let before = text.substring(to: range.location) as NSString
|
||||
let lineRange = text.lineRange(for: NSRange(location: range.location, length: 0))
|
||||
let preview = (text.substring(with: lineRange) as NSString).substring(to: min(240, lineRange.length)).trimmingCharacters(in: .newlines)
|
||||
found.append(.init(path: path, line: before.components(separatedBy: "\n").count,
|
||||
column: range.location - lineRange.location + 1, lengthUTF16: range.length, preview: preview, offsetUTF16: range.location))
|
||||
start = range.location + range.length
|
||||
}
|
||||
}
|
||||
return .init(matches: found, truncated: false)
|
||||
}
|
||||
private func visibleFiles(from path: String) -> Set<String> {
|
||||
var visible: Set<String> = [path], pending = [path]
|
||||
while let file = pending.popLast(), visible.count <= Self.maximumFiles {
|
||||
for step in steps[file] ?? [] {
|
||||
if case .include(let include) = step.directive, let target = resolve(include, in: file),
|
||||
visible.insert(target).inserted { pending.append(target) }
|
||||
}
|
||||
}
|
||||
return visible
|
||||
}
|
||||
private func resolve(_ include: Include, in file: String) -> String? {
|
||||
let parent = (file as NSString).deletingLastPathComponent
|
||||
let local = parent.isEmpty ? include.name : parent + "/" + include.name
|
||||
let names = (include.quoted ? [local] : []) + includePaths.map { $0.isEmpty ? include.name : $0 + "/" + include.name }
|
||||
return names.lazy.map { ($0 as NSString).standardizingPath }.first { documents[$0] != nil }
|
||||
}
|
||||
|
||||
private struct MacroOverrides {
|
||||
var live: [String: Set<String>] = [:]
|
||||
var undefined: Set<String> = []
|
||||
var uncertain: Set<String> = []
|
||||
func keeps(_ symbol: Symbol) -> Bool {
|
||||
guard undefined.contains(symbol.name) else { return true }
|
||||
let macros = live[symbol.name] ?? []
|
||||
if symbol.kind == .macro { return macros.contains(symbol.id) }
|
||||
return symbol.kind != .function || macros.isEmpty || uncertain.contains(symbol.name)
|
||||
}
|
||||
}
|
||||
/// Resolve only names with an explicit #undef. Replay literal directives in
|
||||
/// include order up to the caret; unknown branches keep alternative candidates.
|
||||
private func macroOverrides(from path: String, offset: Int, names: Set<String>) -> MacroOverrides {
|
||||
let relevant = names.intersection(undefinedNames)
|
||||
guard !relevant.isEmpty else { return MacroOverrides() }
|
||||
var state = MacroOverrides(), confirmed: Set<String> = [], ancestors: Set<String> = []
|
||||
var budget = Self.maximumTokens
|
||||
func scan(_ file: String, through limit: Int, certain: Bool) {
|
||||
guard budget > 0, !confirmed.contains(file), !ancestors.contains(file) else { return }
|
||||
guard ancestors.count < 64, !Task.isCancelled else { budget = 0; return }
|
||||
ancestors.insert(file)
|
||||
defer { ancestors.remove(file) }
|
||||
if guarded.contains(file), certain { confirmed.insert(file) }
|
||||
for step in steps[file] ?? [] {
|
||||
guard step.offset <= limit, budget > 0 else { break }
|
||||
budget -= 1
|
||||
let definite = certain && !step.conditional
|
||||
switch step.directive {
|
||||
case .include(let include):
|
||||
if let nested = resolve(include, in: file) { scan(nested, through: Int.max, certain: definite) }
|
||||
case .define(let name) where relevant.contains(name):
|
||||
let id = "\(file):\(step.offset):\(Kind.macro.rawValue)"
|
||||
if definite {
|
||||
state.live[name] = [id]
|
||||
state.uncertain.remove(name)
|
||||
} else {
|
||||
state.live[name, default: []].insert(id)
|
||||
if state.undefined.contains(name) { state.uncertain.insert(name) }
|
||||
}
|
||||
case .undef(let name) where relevant.contains(name):
|
||||
state.undefined.insert(name)
|
||||
if definite {
|
||||
state.live[name] = []
|
||||
state.uncertain.remove(name)
|
||||
} else if state.live[name]?.isEmpty == false { state.uncertain.insert(name) }
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
scan(path, through: offset, certain: true)
|
||||
return budget > 0 ? state : MacroOverrides()
|
||||
}
|
||||
private static func offset(line: Int, column: Int, text: String) -> Int {
|
||||
let lines = text.components(separatedBy: "\n")
|
||||
guard line > 0, line <= lines.count else { return 0 }
|
||||
return lines.prefix(line - 1).reduce(0) { $0 + $1.utf16.count + 1 } + max(0, min(column - 1, lines[line - 1].utf16.count))
|
||||
}
|
||||
private struct Token: Sendable {
|
||||
let text: String, offset: Int, line: Int, column: Int, conditional: Bool
|
||||
var identifier: Bool { guard let first = text.utf8.first else { return false }; return Self.identifierStart(first) }
|
||||
static func identifierStart(_ c: UInt8) -> Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) }
|
||||
}
|
||||
private static func lex(_ text: String, conditionalLines: Set<Int>) -> (tokens: [Token], truncated: Bool) {
|
||||
let bytes = Array(text.utf16); var result: [Token] = [], i = 0, line = 1, column = 1
|
||||
func idStart(_ c: UInt16) -> Bool { c == 95 || (65...90).contains(c) || (97...122).contains(c) }
|
||||
func advance() { if bytes[i] == 10 { line += 1; column = 1 } else { column += 1 }; i += 1 }
|
||||
while i < bytes.count {
|
||||
if result.count >= maximumTokens || (i % 1024 == 0 && Task.isCancelled) { return (result, true) }
|
||||
let c = bytes[i]
|
||||
if c == 32 || c == 9 || c == 13 || c == 10 { advance(); continue }
|
||||
if c == 34 || c == 39 {
|
||||
let quote = c; advance()
|
||||
while i < bytes.count { if bytes[i] == 92 { advance(); if i < bytes.count { advance() }; continue }; if bytes[i] == quote { advance(); break }; advance() }
|
||||
continue
|
||||
}
|
||||
let start = i, startLine = line, startColumn = column
|
||||
if idStart(c) || (48...57).contains(c) {
|
||||
advance(); while i < bytes.count && (idStart(bytes[i]) || (48...57).contains(bytes[i])) { advance() }
|
||||
} else {
|
||||
advance()
|
||||
if i < bytes.count && ((c == 45 && bytes[i] == 62) || (c == 38 && bytes[i] == 38) || (c == 124 && bytes[i] == 124) || (c == 61 && bytes[i] == 61) || (c == 33 && bytes[i] == 61)) { advance() }
|
||||
}
|
||||
result.append(.init(text: String(decoding: bytes[start..<i], as: UTF16.self), offset: start, line: startLine, column: startColumn, conditional: conditionalLines.contains(startLine)))
|
||||
}
|
||||
return (result, false)
|
||||
}
|
||||
private enum Truth { case yes, no, unknown
|
||||
var inverted: Self { self == .yes ? .no : self == .no ? .yes : .unknown }
|
||||
func and(_ other: Self) -> Self { self == .no || other == .no ? .no : self == .yes && other == .yes ? .yes : .unknown }
|
||||
func or(_ other: Self) -> Self { self == .yes || other == .yes ? .yes : self == .no && other == .no ? .no : .unknown }
|
||||
}
|
||||
private struct Preparation { var text: String; var conditionalLines: Set<Int>; var macros: [Symbol]; var steps: [Step]; var guardName: String? }
|
||||
private static func prepare(_ text: String, path: String, defines: [String], uncertain: Bool) -> Preparation {
|
||||
// Blank comments while retaining all UTF-16 coordinates and quoted text.
|
||||
var units = Array(text.utf16), i = 0, quote: UInt16?, block = false, lineComment = false
|
||||
var currentLine = 1, literalContinuationLines: Set<Int> = [], lineCommentEscape = false
|
||||
while i < units.count {
|
||||
let c = units[i], next = i + 1 < units.count ? units[i + 1] : 0
|
||||
if c == 10 { currentLine += 1; if quote != nil { literalContinuationLines.insert(currentLine) } }
|
||||
if block {
|
||||
if c == 42 && next == 47 { units[i] = 32; units[i + 1] = 32; i += 2; block = false; continue }
|
||||
if c != 10 && c != 13 { units[i] = 32 }; i += 1; continue
|
||||
}
|
||||
if lineComment {
|
||||
if c == 10 { lineComment = lineCommentEscape; lineCommentEscape = false }
|
||||
else if c != 13 { lineCommentEscape = c == 92; units[i] = 32 }
|
||||
i += 1; continue
|
||||
}
|
||||
if let q = quote { if c == 92 {
|
||||
if next == 10 { currentLine += 1; literalContinuationLines.insert(currentLine) }
|
||||
i += min(2, units.count - i); continue
|
||||
}; if c == q { quote = nil }; i += 1; continue }
|
||||
if c == 34 || c == 39 { quote = c; i += 1; continue }
|
||||
if c == 47 && next == 42 { units[i] = 32; units[i+1] = 32; i += 2; block = true; continue }
|
||||
if c == 47 && next == 47 { units[i] = 32; units[i+1] = 32; i += 2; lineComment = true; continue }
|
||||
i += 1
|
||||
}
|
||||
let clean = String(decoding: units, as: UTF16.self).components(separatedBy: "\n")
|
||||
// A conventional outer include guard makes a second literal include inert.
|
||||
let nonempty = clean.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
|
||||
let guardName = nonempty.first.flatMap { $0.hasPrefix("#ifndef ") ? String($0.dropFirst(8)) : nil }
|
||||
var guarded = guardName.map { nonempty.dropFirst().first == "#define " + $0 && nonempty.last == "#endif" } ?? false
|
||||
let lastContent = clean.lastIndex { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||||
var macros: [String: String] = [:]
|
||||
for define in defines.prefix(256) { let pieces = define.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false); if let name = pieces.first { macros[String(name)] = pieces.count > 1 ? String(pieces[1]) : "1" } }
|
||||
var conditional: Set<Int> = [], symbols: [Symbol] = [], steps: [Step] = [], output: [String] = [], offset = 0
|
||||
var active = Truth.yes, stack: [(parent: Truth, taken: Truth)] = [], unknownMacros: Set<String> = [], included = false, continuing = false
|
||||
func condition(_ expression: String) -> Truth {
|
||||
evaluateCondition(expression, macros: macros, unknownMacros: unknownMacros, unknownAbsent: uncertain || included)
|
||||
}
|
||||
for (number, line) in clean.enumerated() {
|
||||
if Task.isCancelled { break }
|
||||
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let blank = String(repeating: " ", count: line.utf16.count)
|
||||
defer { offset += line.utf16.count + 1 }
|
||||
if continuing { continuing = trimmed.hasSuffix("\\"); output.append(blank); continue }
|
||||
guard trimmed.hasPrefix("#"), !literalContinuationLines.contains(number + 1) else {
|
||||
output.append(active == .no ? blank : line)
|
||||
if active == .unknown { conditional.insert(number + 1) }; continue
|
||||
}
|
||||
continuing = trimmed.hasSuffix("\\")
|
||||
output.append(blank)
|
||||
let directive = trimmed.dropFirst().trimmingCharacters(in: .whitespaces)
|
||||
let command = String(directive.prefix { $0.isLetter }), argument = String(directive.dropFirst(directive.prefix { $0.isLetter }.count)).trimmingCharacters(in: .whitespaces)
|
||||
if stack.count == 1, command == "elif" || command == "else" || (command == "endif" && number != lastContent) {
|
||||
guarded = false
|
||||
}
|
||||
switch command {
|
||||
case "if", "ifdef", "ifndef":
|
||||
let test = command == "if" ? condition(argument) : condition("defined(\(argument))")
|
||||
let value = command == "ifndef" ? test.inverted : test
|
||||
stack.append((active, value)); active = active.and(value)
|
||||
case "elif":
|
||||
if let frame = stack.popLast() { let test = condition(argument); active = frame.parent.and(frame.taken.inverted).and(test); stack.append((frame.parent, frame.taken.or(test))) }
|
||||
case "else": if let frame = stack.last { active = frame.parent.and(frame.taken.inverted); stack[stack.count - 1].taken = .yes }
|
||||
case "endif": if let frame = stack.popLast() { active = frame.parent }
|
||||
case "include" where active != .no:
|
||||
if let first = argument.first, first == "\"" || first == "<", let end = argument.dropFirst().firstIndex(of: first == "\"" ? "\"" : ">") { steps.append(.init(directive: .include(.init(name: String(argument[argument.index(after: argument.startIndex)..<end]), quoted: first == "\"")), offset: offset, conditional: active == .unknown)) }
|
||||
included = true
|
||||
case "define" where active != .no:
|
||||
let name = String(argument.prefix { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_") })
|
||||
guard !name.isEmpty else { continue }
|
||||
let range = (line as NSString).range(of: name, range: NSRange(location: max(0, (line as NSString).range(of: "define").location + 6), length: max(0, (line as NSString).length - ((line as NSString).range(of: "define").location + 6))))
|
||||
let start = range.location == NSNotFound ? 0 : range.location
|
||||
steps.append(.init(directive: .define(name), offset: offset + start, conditional: active == .unknown))
|
||||
symbols.append(.init(path: path, name: name, line: number + 1, column: start + 1, kind: .macro,
|
||||
signature: String(trimmed.prefix(220)), isDefinition: true, isStatic: true, conditional: active == .unknown,
|
||||
scope: nil, offsetUTF16: offset + start, lengthUTF16: name.utf16.count, scopeStart: 0, scopeEnd: Int.max))
|
||||
if active == .unknown { unknownMacros.insert(name) } else { macros[name] = String(argument.dropFirst(name.count)).trimmingCharacters(in: .whitespaces); unknownMacros.remove(name) }
|
||||
case "undef" where active != .no:
|
||||
steps.append(.init(directive: .undef(argument), offset: offset, conditional: active == .unknown))
|
||||
if active == .unknown { unknownMacros.insert(argument) } else { macros.removeValue(forKey: argument); unknownMacros.remove(argument) }
|
||||
default: break
|
||||
}
|
||||
}
|
||||
return .init(text: output.joined(separator: "\n"), conditionalLines: conditional, macros: symbols, steps: steps, guardName: guarded ? guardName : nil)
|
||||
}
|
||||
private static func evaluateCondition(_ expression: String, macros: [String: String], unknownMacros: Set<String>, unknownAbsent: Bool, depth: Int = 0) -> Truth {
|
||||
guard depth < 32, expression.utf16.count <= 8192 else { return .unknown }
|
||||
let expr = expression.trimmingCharacters(in: .whitespaces)
|
||||
if expr.hasPrefix("(") && expr.hasSuffix(")") {
|
||||
var depth = 0, wraps = true
|
||||
for (i, c) in expr.enumerated() { if c == "(" { depth += 1 }; if c == ")" { depth -= 1 }; if depth == 0 && i < expr.count - 1 { wraps = false } }
|
||||
if wraps { return evaluateCondition(String(expr.dropFirst().dropLast()), macros: macros, unknownMacros: unknownMacros, unknownAbsent: unknownAbsent, depth: depth + 1) }
|
||||
}
|
||||
for op in ["||", "&&"] {
|
||||
let chars = Array(expr), operatorChars = Array(op); var depth = 0
|
||||
if chars.count >= 2 { for i in 0..<(chars.count - 1) { if chars[i] == "(" { depth += 1 }; if chars[i] == ")" { depth -= 1 }; if depth == 0 && chars[i] == operatorChars[0] && chars[i+1] == operatorChars[1] {
|
||||
let left = evaluateCondition(String(chars[..<i]), macros: macros, unknownMacros: unknownMacros, unknownAbsent: unknownAbsent, depth: depth + 1)
|
||||
let right = evaluateCondition(String(chars[(i+2)...]), macros: macros, unknownMacros: unknownMacros, unknownAbsent: unknownAbsent, depth: depth + 1)
|
||||
return op == "&&" ? left.and(right) : left.or(right)
|
||||
} } }
|
||||
}
|
||||
if expr.hasPrefix("!") { return evaluateCondition(String(expr.dropFirst()), macros: macros, unknownMacros: unknownMacros, unknownAbsent: unknownAbsent, depth: depth + 1).inverted }
|
||||
if expr.hasPrefix("defined") {
|
||||
let name = expr.dropFirst(7).trimmingCharacters(in: CharacterSet.whitespaces.union(CharacterSet(charactersIn: "()")))
|
||||
if unknownMacros.contains(name) { return .unknown }
|
||||
return macros[name] != nil ? .yes : unknownAbsent ? .unknown : .no
|
||||
}
|
||||
if let number = Int(expr) { return number == 0 ? .no : .yes }
|
||||
if expr.hasPrefix("0x"), let number = Int(expr.dropFirst(2), radix: 16) { return number == 0 ? .no : .yes }
|
||||
if unknownMacros.contains(expr) { return .unknown }
|
||||
if let value = macros[expr], let number = Int(value) { return number == 0 ? .no : .yes }
|
||||
// Arithmetic, function macros, included definitions and custom flags are
|
||||
// intentionally uncertain; never hide a potentially compiled branch.
|
||||
return .unknown
|
||||
}
|
||||
private struct Parser {
|
||||
let path: String, source: String
|
||||
let tokens: [Token]
|
||||
var symbols: [Symbol] = []
|
||||
var limited = false
|
||||
var types: Set<String> = ["void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "byte", "word", "size_t", "ptrdiff_t"]
|
||||
private let qualifiers: Set<String> = ["const", "volatile", "extern", "static", "register", "auto", "typedef", "inline", "interrupt", "__interrupt", "__norts__", "__norts", "__asm__", "asm", "__asm"]
|
||||
private let controls: Set<String> = ["return", "if", "else", "while", "do", "for", "switch", "case", "break", "continue", "goto", "sizeof"]
|
||||
mutating func parse() { parseRange(0..<tokens.count, scope: nil, scopeStart: 0, scopeEnd: Int.max, member: false, depth: 0) }
|
||||
private func matching(_ index: Int, limit: Int) -> Int? {
|
||||
let pairs = ["(": ")", "[": "]", "{": "}"]
|
||||
guard let close = pairs[tokens[index].text] else { return nil }
|
||||
var level = 0
|
||||
for i in index..<limit {
|
||||
if tokens[i].text == tokens[index].text { level += 1 }
|
||||
if tokens[i].text == close { level -= 1; if level == 0 { return i } }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
private mutating func add(_ token: Token, kind: Kind, declaration: [Token], definition: Bool = true, scope: String?, scopeStart: Int, scopeEnd: Int, conditional: Bool? = nil) {
|
||||
guard symbols.count < CMOCProjectIndex.maximumSymbols else { limited = true; return }
|
||||
symbols.append(.init(path: path, name: token.text, line: token.line, column: token.column, kind: kind,
|
||||
signature: String(declaration.map(\.text).joined(separator: " ").prefix(220)), isDefinition: definition,
|
||||
isStatic: declaration.contains { $0.text == "static" }, conditional: conditional ?? declaration.contains(where: \.conditional),
|
||||
scope: scope, offsetUTF16: token.offset, lengthUTF16: token.text.utf16.count, scopeStart: scopeStart, scopeEnd: scopeEnd))
|
||||
}
|
||||
private func split(_ values: [Token], at separator: String) -> [[Token]] {
|
||||
var result: [[Token]] = [], current: [Token] = [], parens = 0, brackets = 0, braces = 0
|
||||
for token in values {
|
||||
if token.text == separator && parens == 0 && brackets == 0 && braces == 0 { result.append(current); current = []; continue }
|
||||
current.append(token)
|
||||
switch token.text { case "(": parens += 1; case ")": parens -= 1; case "[": brackets += 1; case "]": brackets -= 1; case "{": braces += 1; case "}": braces -= 1; default: break }
|
||||
}
|
||||
if !current.isEmpty { result.append(current) }; return result
|
||||
}
|
||||
private func declaratorStart(_ declaration: [Token]) -> Int? {
|
||||
guard let first = declaration.first, first.identifier, !controls.contains(first.text) else { return nil }
|
||||
var i = 0, consumed = false
|
||||
while i < declaration.count {
|
||||
let name = declaration[i].text
|
||||
if qualifiers.contains(name) || types.contains(name) { consumed = true; i += 1; continue }
|
||||
if ["struct", "union", "enum"].contains(name) {
|
||||
consumed = true; i += 1
|
||||
if i < declaration.count && declaration[i].identifier { i += 1 }
|
||||
continue
|
||||
}
|
||||
if !consumed && declaration[i].identifier && i + 1 < declaration.count && (declaration[i+1].identifier || declaration[i+1].text == "*") {
|
||||
// A named type from another header is plausible, but it is
|
||||
// only a lexical declaration, never semantic type resolution.
|
||||
consumed = true; i += 1; continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return consumed && i < declaration.count ? i : nil
|
||||
}
|
||||
private func declarator(_ values: [Token]) -> (name: Token, function: Bool, parameters: [Token])? {
|
||||
guard let nameIndex = values.firstIndex(where: { $0.identifier && !qualifiers.contains($0.text) }) else { return nil }
|
||||
let name = values[nameIndex]
|
||||
if nameIndex + 1 < values.count, values[nameIndex+1].text == "(" {
|
||||
var depth = 0
|
||||
for i in (nameIndex+1)..<values.count {
|
||||
if values[i].text == "(" { depth += 1 }
|
||||
if values[i].text == ")" { depth -= 1; if depth == 0 { return (name, true, Array(values[(nameIndex+2)..<i])) } }
|
||||
}
|
||||
}
|
||||
return (name, false, [])
|
||||
}
|
||||
private mutating func declarations(_ declaration: [Token], scope: String?, scopeStart: Int, scopeEnd: Int, member: Bool, parameter: Bool = false) {
|
||||
guard let start = declaratorStart(declaration) else { return }
|
||||
let isTypedef = declaration.contains { $0.text == "typedef" }
|
||||
let external = declaration.contains { $0.text == "extern" }
|
||||
for part in split(Array(declaration[start...]), at: ",") {
|
||||
let noInitializer = split(part, at: "=").first ?? part
|
||||
guard let value = declarator(noInitializer) else { continue }
|
||||
let kind: Kind = isTypedef ? .type : parameter ? .parameter : member ? .member : value.function ? .function : .variable
|
||||
add(value.name, kind: kind, declaration: declaration, definition: isTypedef || (!value.function && !external),
|
||||
scope: scope, scopeStart: scopeStart, scopeEnd: scopeEnd)
|
||||
if isTypedef { types.insert(value.name.text) }
|
||||
}
|
||||
}
|
||||
private mutating func parseRange(_ range: Range<Int>, scope: String?, scopeStart: Int, scopeEnd: Int, member: Bool, depth: Int) {
|
||||
guard depth < 64 else { limited = true; return }
|
||||
var begin = range.lowerBound, i = begin
|
||||
while i < range.upperBound {
|
||||
if Task.isCancelled { return }
|
||||
let text = tokens[i].text
|
||||
if text == "(" || text == "[" {
|
||||
if let close = matching(i, limit: range.upperBound) {
|
||||
if text == "(", i > begin, tokens[i-1].text == "for", let scope,
|
||||
let separator = tokens[(i+1)..<close].firstIndex(where: { $0.text == ";" }) {
|
||||
let body = close + 1
|
||||
let end = body < range.upperBound && tokens[body].text == "{" ? matching(body, limit: range.upperBound)
|
||||
: tokens[body..<range.upperBound].firstIndex(where: { $0.text == ";" })
|
||||
if let end { declarations(Array(tokens[(i+1)..<separator]), scope: scope, scopeStart: tokens[i].offset,
|
||||
scopeEnd: tokens[end].offset, member: false) }
|
||||
}
|
||||
i = close + 1; continue
|
||||
}
|
||||
return
|
||||
}
|
||||
if text == ";" {
|
||||
declarations(Array(tokens[begin..<i]), scope: scope, scopeStart: scopeStart, scopeEnd: scopeEnd, member: member)
|
||||
i += 1; begin = i; continue
|
||||
}
|
||||
if text == "{" {
|
||||
guard let close = matching(i, limit: range.upperBound) else { return }
|
||||
let header = Array(tokens[begin..<i])
|
||||
let value = declaratorStart(header).flatMap { declarator(Array(header[$0...])) }
|
||||
let isInitializer = header.contains { $0.text == "=" }
|
||||
if scope == nil, !isInitializer, let value, value.function {
|
||||
add(value.name, kind: .function, declaration: header, scope: nil, scopeStart: 0, scopeEnd: Int.max)
|
||||
let function = value.name.text
|
||||
for parameter in split(value.parameters, at: ",") {
|
||||
declarations(parameter, scope: function, scopeStart: tokens[i].offset, scopeEnd: tokens[close].offset, member: false, parameter: true)
|
||||
}
|
||||
if !header.contains(where: { ["asm", "__asm"].contains($0.text) }) {
|
||||
parseRange((i+1)..<close, scope: function, scopeStart: tokens[i].offset, scopeEnd: tokens[close].offset, member: false, depth: depth+1)
|
||||
}
|
||||
i = close + 1; begin = i; continue
|
||||
}
|
||||
if !isInitializer, let tagIndex = header.firstIndex(where: { ["struct", "union", "enum"].contains($0.text) }) {
|
||||
let tag = tagIndex + 1 < header.count && header[tagIndex+1].identifier ? header[tagIndex+1] : nil
|
||||
if let tag { add(tag, kind: .type, declaration: header, scope: scope, scopeStart: scopeStart, scopeEnd: scopeEnd) }
|
||||
if header[tagIndex].text == "enum" {
|
||||
for item in split(Array(tokens[(i+1)..<close]), at: ",") {
|
||||
if let name = item.first, name.identifier { add(name, kind: .enumerator, declaration: item, scope: scope, scopeStart: scopeStart, scopeEnd: scopeEnd) }
|
||||
}
|
||||
} else {
|
||||
parseRange((i+1)..<close, scope: tag?.text ?? "anonymous aggregate", scopeStart: tokens[i].offset, scopeEnd: tokens[close].offset, member: true, depth: depth+1)
|
||||
}
|
||||
var end = close + 1
|
||||
while end < range.upperBound && tokens[end].text != ";" { end += 1 }
|
||||
var prefix = header
|
||||
// An anonymous aggregate needs a synthetic type token so
|
||||
// its trailing name is not consumed as a tag.
|
||||
if tag == nil { prefix.append(Token(text: "__anonymous_type", offset: tokens[i].offset, line: tokens[i].line, column: tokens[i].column, conditional: tokens[i].conditional)) }
|
||||
declarations(prefix + Array(tokens[(close+1)..<end]), scope: scope, scopeStart: scopeStart, scopeEnd: scopeEnd, member: member)
|
||||
i = min(end + 1, range.upperBound); begin = i; continue
|
||||
}
|
||||
if isInitializer {
|
||||
// Keep declaration text around the initializer, but skip
|
||||
// its braces so initializer identifiers aren't symbols.
|
||||
var end = close + 1
|
||||
while end < range.upperBound && tokens[end].text != ";" { end += 1 }
|
||||
declarations(header + Array(tokens[(close+1)..<end]), scope: scope, scopeStart: scopeStart, scopeEnd: scopeEnd, member: member)
|
||||
i = min(end+1, range.upperBound); begin = i; continue
|
||||
}
|
||||
// CMOC assembly bodies contain assembler labels/directives,
|
||||
// not C declarations; never index them as C locals.
|
||||
if !header.contains(where: { ["asm", "__asm"].contains($0.text) }) {
|
||||
parseRange((i+1)..<close, scope: scope ?? "block", scopeStart: tokens[i].offset, scopeEnd: tokens[close].offset, member: member, depth: depth+1)
|
||||
}
|
||||
i = close + 1; begin = i; continue
|
||||
}
|
||||
if text == ":", begin < tokens.count,
|
||||
(i == begin + 1 && tokens[begin].identifier) || ["case", "default"].contains(tokens[begin].text) { begin = i + 1 }
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private extension CMOCProjectIndex.Symbol {
|
||||
func withConditional() -> Self {
|
||||
.init(path: path, name: name, line: line, column: column, kind: kind, signature: signature,
|
||||
isDefinition: isDefinition, isStatic: isStatic, conditional: true, scope: scope,
|
||||
offsetUTF16: offsetUTF16, lengthUTF16: lengthUTF16, scopeStart: scopeStart, scopeEnd: scopeEnd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// One bounded, content-based description of project inputs. Excluded directory
|
||||
/// rows explain an entire subtree without reading or hashing its generated data.
|
||||
struct CMOCProjectInputManifest: Equatable, Sendable {
|
||||
struct Entry: Codable, Equatable, Sendable {
|
||||
let path: String
|
||||
let role: String
|
||||
let reason: String
|
||||
let included: Bool
|
||||
let affectsRevision: Bool
|
||||
let affectsBuild: Bool
|
||||
let sha256: String?
|
||||
let executable: Bool
|
||||
var permissions: Int? = nil
|
||||
var publicFields: [String: Any] {
|
||||
["path": path, "role": role, "reason": reason, "included": included,
|
||||
"affects_revision": affectsRevision, "affects_build": affectsBuild,
|
||||
"sha256": sha256 as Any? ?? NSNull(), "executable": executable,
|
||||
"permissions": permissions as Any? ?? NSNull()]
|
||||
}
|
||||
var control: Bool { ["recipe", "project_settings", "generator", "support", "pending_support_root", "executable"].contains(role) }
|
||||
}
|
||||
struct Change: Equatable, Sendable {
|
||||
let path: String
|
||||
let previous: Entry?
|
||||
let current: Entry?
|
||||
var requiresReview: Bool {
|
||||
guard let previous, let current else { return true }
|
||||
return previous.included != current.included || previous.role != current.role ||
|
||||
previous.executable != current.executable || previous.control || current.control
|
||||
}
|
||||
var publicFields: [String: Any] {
|
||||
["path": path, "previous": previous?.publicFields as Any? ?? NSNull(),
|
||||
"current": current?.publicFields as Any? ?? NSNull(), "requires_review": requiresReview]
|
||||
}
|
||||
}
|
||||
let configuration: CMOCProjectConfiguration
|
||||
let files: [String: Data]
|
||||
let permissions: [String: Int]
|
||||
let modificationDates: [String: Date]
|
||||
let overlayPaths: Set<String>
|
||||
let support: CMOCBuildSupportSnapshot
|
||||
let entries: [Entry]
|
||||
var sharedPaths: [String] { files.keys.filter(CMOCProject.isEditable).sorted() }
|
||||
var identity: String {
|
||||
let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]
|
||||
let rows = entries.filter(\.included)
|
||||
// Configuration is a value already validated at capture. Encoding these
|
||||
// Codable values cannot depend on disk timestamps or dictionary order.
|
||||
let data = (try? encoder.encode(rows)) ?? Data()
|
||||
let config = (try? encoder.encode(configuration)) ?? Data()
|
||||
return CMOCProject.sha256(data + config)
|
||||
}
|
||||
static func == (lhs: Self, rhs: Self) -> Bool { lhs.identity == rhs.identity }
|
||||
/// Restricted assistant recipes use only reviewed C/header inputs (or the
|
||||
/// fixed Hello Disk set), not the user's arbitrary Make resources/helpers.
|
||||
func restricting(to paths: Set<String>) -> Self {
|
||||
Self(configuration: configuration, files: files.filter { paths.contains($0.key) },
|
||||
permissions: permissions.filter { paths.contains($0.key) },
|
||||
modificationDates: modificationDates.filter { paths.contains($0.key) },
|
||||
overlayPaths: overlayPaths.intersection(paths), support: .init(files: [:], permissions: [:]),
|
||||
entries: entries.map { entry in
|
||||
guard entry.included, !paths.contains(entry.path) else { return entry }
|
||||
return Entry(path: entry.path, role: "excluded_scope", reason: "Not used by the approved restricted recipe.",
|
||||
included: false, affectsRevision: false, affectsBuild: false, sha256: nil, executable: false)
|
||||
})
|
||||
}
|
||||
func changes(from old: Self) -> [Change] {
|
||||
let before = Dictionary(uniqueKeysWithValues: old.entries.map { ($0.path, $0) })
|
||||
let after = Dictionary(uniqueKeysWithValues: entries.map { ($0.path, $0) })
|
||||
return Set(before.keys).union(after.keys).sorted().compactMap { path in
|
||||
let lhs = before[path], rhs = after[path]
|
||||
guard lhs?.included == true || rhs?.included == true, lhs != rhs else { return nil }
|
||||
return Change(path: path, previous: lhs, current: rhs)
|
||||
}
|
||||
}
|
||||
|
||||
static func capture(project: CMOCProject, overlays: [String: String] = [:],
|
||||
approvedSupportDirectories: [String]? = nil,
|
||||
readConfigurationFile: Bool = true, retainHostExecutables: Bool = false) throws -> Self {
|
||||
let fm = FileManager.default
|
||||
let root = try CMOCProject.physicalURL(project.directory)
|
||||
var configuration = project.configuration
|
||||
let settingsURL = try project.fileURL(relativePath: CMOCProject.configurationFilename)
|
||||
if readConfigurationFile, let text = overlays[CMOCProject.configurationFilename] {
|
||||
configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(text.utf8))
|
||||
} else if readConfigurationFile, fm.fileExists(atPath: settingsURL.path) {
|
||||
let attributes = try fm.attributesOfItem(atPath: settingsURL.path)
|
||||
guard ((attributes[.size] as? NSNumber)?.intValue ?? Int.max) <= CMOCProject.maximumFileBytes else {
|
||||
throw CMOCBuildError.message("Project settings exceed the input limit.")
|
||||
}
|
||||
configuration = try JSONDecoder().decode(CMOCProjectConfiguration.self, from: Data(contentsOf: settingsURL))
|
||||
}
|
||||
configuration = try configuration.validated()
|
||||
let effective = CMOCProject(directory: project.directory, configuration: configuration)
|
||||
let recipe = configuration.makefileSettings
|
||||
let generatedOutputs = Set(recipe?.generatedResources.flatMap(\.outputs) ?? [])
|
||||
var products = generatedOutputs.union(configuration.playtestDisks)
|
||||
for path in [configuration.binary, configuration.diskImage, configuration.debugManifest].compactMap({ $0 }) {
|
||||
products.insert(path)
|
||||
}
|
||||
if let binary = configuration.binary {
|
||||
let stem = (binary as NSString).deletingPathExtension
|
||||
for ext in ["map", "link"] { products.insert(stem + "." + ext) }
|
||||
}
|
||||
let explicitSources = Set((recipe?.sources ?? []) + [configuration.entrySource])
|
||||
let explicitResources = Set(configuration.resourceInputs + (recipe?.generatedResources.flatMap(\.inputs) ?? []) + (recipe?.diskFiles ?? []))
|
||||
.subtracting(products)
|
||||
let explicitGenerated = Set(configuration.generatedInputs)
|
||||
let explicit = explicitSources.union(explicitResources).union(explicitGenerated)
|
||||
.union([configuration.makefile, CMOCProject.configurationFilename])
|
||||
let includeDirectories = recipe?.includePaths ?? []
|
||||
let hard = Set([".git", ".svn", ".hg", ".ds_store"])
|
||||
let incidental = Set(["captures", "screenshots", "evidence", "receipts", "logs", "test-results", "tmp", "temp", ".cache", ".build", ".vccplus-build"])
|
||||
func within(_ path: String, _ directory: String) -> Bool { path == directory || path.hasPrefix(directory + "/") }
|
||||
func explicitlyNeeded(_ path: String, directory: Bool) -> Bool {
|
||||
explicit.contains(path) || (directory && explicit.contains(where: { $0.hasPrefix(path + "/") })) ||
|
||||
includeDirectories.contains(where: { within(path, $0) || (directory && within($0, path)) })
|
||||
}
|
||||
var enumerationError: Error?
|
||||
guard let enumerator = fm.enumerator(at: root,
|
||||
includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey],
|
||||
options: [], errorHandler: { _, error in enumerationError = error; return false }) else {
|
||||
throw CMOCBuildError.message("The project folder could not be read.")
|
||||
}
|
||||
var candidates: [String: URL] = [:], excluded: [Entry] = [], names = Set<String>()
|
||||
func exclusion(_ path: String, _ role: String, _ reason: String) {
|
||||
excluded.append(Entry(path: path, role: role, reason: reason, included: false,
|
||||
affectsRevision: false, affectsBuild: false, sha256: nil, executable: false))
|
||||
}
|
||||
while let url = enumerator.nextObject() as? URL {
|
||||
let path = String(url.path.dropFirst(root.path.count + 1))
|
||||
try CMOCProject.validateRelativePath(path)
|
||||
guard names.insert(path.lowercased()).inserted, names.count <= 20_000 else {
|
||||
throw CMOCBuildError.message("Project input names are ambiguous or exceed the 20,000-entry limit.")
|
||||
}
|
||||
let value = try url.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey, .isSymbolicLinkKey])
|
||||
if hard.contains(url.lastPathComponent.lowercased()) {
|
||||
enumerator.skipDescendants(); exclusion(path, "excluded", "Version-control or platform metadata; subtree excluded."); continue
|
||||
}
|
||||
guard value.isSymbolicLink != true else {
|
||||
throw CMOCBuildError.message("Project inputs cannot traverse symbolic links: \(path)")
|
||||
}
|
||||
let directory = value.isDirectory == true
|
||||
let soft = path.split(separator: "/").contains(where: { incidental.contains($0.lowercased()) }) ||
|
||||
configuration.outputDirectories.contains(where: { within(path, $0) })
|
||||
if soft && !explicitlyNeeded(path, directory: directory) {
|
||||
enumerator.skipDescendants(); exclusion(path, "excluded_output", "Incidental or declared output directory; subtree excluded."); continue
|
||||
}
|
||||
if directory { continue }
|
||||
guard value.isRegularFile == true else { throw CMOCBuildError.message("Unsupported project input: \(path)") }
|
||||
candidates[path] = url
|
||||
}
|
||||
if let enumerationError { throw enumerationError }
|
||||
for path in explicitResources.union(explicitGenerated) {
|
||||
guard candidates[path] != nil else { throw CMOCBuildError.message("Missing declared project input: \(path)") }
|
||||
}
|
||||
var files: [String: Data] = [:], permissions: [String: Int] = [:], dates: [String: Date] = [:]
|
||||
var entries = excluded, total = 0
|
||||
let keys = Set(candidates.keys.map { $0.lowercased() })
|
||||
for path in candidates.keys.sorted() {
|
||||
let key = path.lowercased(), ext = (key as NSString).pathExtension
|
||||
let stem = (key as NSString).deletingPathExtension
|
||||
let declared = explicit.contains(path) || includeDirectories.contains(where: { within(path, $0) })
|
||||
if products.contains(path) {
|
||||
exclusion(path, "generated_output", "Declared build output; captured in the resulting artifact, not the input revision."); continue
|
||||
}
|
||||
if !declared && (["o", "d", "lst", "map", "link", "log"].contains(ext) ||
|
||||
(ext == "s" && (keys.contains(stem + ".c") || keys.contains(stem + ".o") || keys.contains(stem + ".lst"))) ||
|
||||
(ext == "bin" && (keys.contains(stem + ".c") || keys.contains(stem + ".asm"))) ||
|
||||
key.hasSuffix("-receipt.json") || key.hasSuffix(".receipt.json") ||
|
||||
(recipe != nil && key.hasPrefix("obj/vcc-dos-boot/"))) {
|
||||
exclusion(path, "compiler_output", "Conventional compiler product, log or receipt; declare it explicitly if it is an input."); continue
|
||||
}
|
||||
let url = candidates[path]!
|
||||
let attributes = try fm.attributesOfItem(atPath: url.path)
|
||||
let mode = (attributes[.posixPermissions] as? NSNumber)?.intValue ?? 0o644
|
||||
let originalSize = (attributes[.size] as? NSNumber)?.intValue ?? Int.max
|
||||
guard originalSize <= CMOCProject.maximumFileBytes else { throw CMOCBuildError.message("Project input exceeds the 64 MB file limit: \(path)") }
|
||||
let data = try overlays[path].map(CMOCProject.sourceBytes) ?? Data(contentsOf: url)
|
||||
// A locally compiled host executable is an output, unless explicitly
|
||||
// retained as a reviewed tool/resource. CoCo binaries are unaffected.
|
||||
let magic = Array(data.prefix(4))
|
||||
let hostExecutable = [[0x7f,0x45,0x4c,0x46], [0xcf,0xfa,0xed,0xfe], [0xce,0xfa,0xed,0xfe],
|
||||
[0xfe,0xed,0xfa,0xcf], [0xfe,0xed,0xfa,0xce], [0xca,0xfe,0xba,0xbe]].contains(magic.map(Int.init))
|
||||
if hostExecutable && !declared && !retainHostExecutables {
|
||||
exclusion(path, "host_build_output", "Compiled host executable; declare it explicitly to retain it as a build input."); continue
|
||||
}
|
||||
total += data.count
|
||||
guard data.count <= CMOCProject.maximumFileBytes, total <= CMOCProject.maximumProjectBytes else {
|
||||
throw CMOCBuildError.message("Project inputs exceed the 512 MB snapshot limit.")
|
||||
}
|
||||
files[path] = data; permissions[path] = mode & 0o777
|
||||
dates[path] = attributes[.modificationDate] as? Date
|
||||
let role: String
|
||||
if path == CMOCProject.configurationFilename { role = "project_settings" }
|
||||
else if path == configuration.makefile || ["makefile", "gnumakefile"].contains((key as NSString).lastPathComponent) || ext == "mk" { role = "recipe" }
|
||||
else if ["pl", "py", "sh", "rb"].contains(ext) { role = "generator" }
|
||||
else if mode & 0o111 != 0 { role = "executable" }
|
||||
else if explicitGenerated.contains(path) { role = "generated_input" }
|
||||
else if ["h", "inc"].contains(ext) { role = "header" }
|
||||
else if CMOCProject.isSource(path) { role = "source" }
|
||||
else { role = "resource" }
|
||||
entries.append(Entry(path: path, role: role,
|
||||
reason: declared ? "Explicitly declared source, include, resource or generated input." : "Project input inside the approved root.",
|
||||
included: true, affectsRevision: true, affectsBuild: true, sha256: CMOCProject.sha256(data), executable: mode & 0o111 != 0,
|
||||
permissions: ["recipe", "project_settings", "generator", "executable"].contains(role) ? mode & 0o777 : nil))
|
||||
}
|
||||
// Exclusions collected during file classification were appended after
|
||||
// the traversal rows. Include them without duplicating existing rows.
|
||||
let seen = Set(entries.map(\.path))
|
||||
entries += excluded.filter { !seen.contains($0.path) }
|
||||
var supportProject = effective
|
||||
if let approvedSupportDirectories {
|
||||
let approved = Set(approvedSupportDirectories)
|
||||
supportProject.configuration.buildSupportDirectories = configuration.buildSupportDirectories.filter(approved.contains)
|
||||
for path in configuration.buildSupportDirectories where !approved.contains(path) {
|
||||
// New sibling roots require native approval BEFORE enumeration,
|
||||
// hashing or copying. Only their already-declared names are public.
|
||||
entries.append(Entry(path: path, role: "pending_support_root",
|
||||
reason: "New build-support root; contents remain unread until native approval authorizes the whole root.",
|
||||
included: true, affectsRevision: true, affectsBuild: true, sha256: nil, executable: false))
|
||||
}
|
||||
}
|
||||
let support = try supportProject.supportSnapshot()
|
||||
guard files.count + support.files.count <= 20_000,
|
||||
total + support.files.values.reduce(0, { $0 + $1.count }) <= CMOCProject.maximumProjectBytes else {
|
||||
throw CMOCBuildError.message("Project and approved support inputs exceed snapshot limits.")
|
||||
}
|
||||
for (path, data) in support.files {
|
||||
entries.append(Entry(path: path, role: "support", reason: "Explicitly approved build-support root.", included: true,
|
||||
affectsRevision: true, affectsBuild: true, sha256: CMOCProject.sha256(data), executable: (support.permissions[path] ?? 0) & 0o111 != 0,
|
||||
permissions: (support.permissions[path] ?? 0) & 0o777))
|
||||
}
|
||||
return Self(configuration: configuration, files: files, permissions: permissions, modificationDates: dates,
|
||||
overlayPaths: Set(overlays.keys).intersection(files.keys), support: support, entries: entries.sorted { $0.path < $1.path })
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,359 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Types and storage locations emitted by the compiler, bound to the exact
|
||||
/// source/object/listing/link-map/executable set already verified by the IDE.
|
||||
struct CMOCVariableDebug: Sendable {
|
||||
final class CType: Decodable, Sendable {
|
||||
struct Member: Decodable, Sendable {
|
||||
let name: String
|
||||
let offset: Int
|
||||
let type: CType
|
||||
}
|
||||
let name: String
|
||||
let kind: String
|
||||
let size: Int
|
||||
let signed: Bool?
|
||||
let count: Int?
|
||||
let element: CType?
|
||||
let members: [Member]?
|
||||
let floatingFormat: String?
|
||||
init(name: String, kind: String, size: Int, signed: Bool? = nil,
|
||||
count: Int? = nil, element: CType? = nil, members: [Member]? = nil, floatingFormat: String? = nil) {
|
||||
self.name = name; self.kind = kind; self.size = size; self.signed = signed
|
||||
self.count = count; self.element = element; self.members = members
|
||||
self.floatingFormat = floatingFormat
|
||||
}
|
||||
static var integer: CType { CType(name: "int", kind: "integer", size: 2, signed: true) }
|
||||
}
|
||||
struct Function: Sendable {
|
||||
let name: String
|
||||
let sourcePath: String
|
||||
let entry: Int
|
||||
let body: Int
|
||||
let end: Int
|
||||
let frame: Bool
|
||||
var moduleID: String? = nil
|
||||
var sourceLine: Int? = nil
|
||||
}
|
||||
struct Variable: Sendable {
|
||||
let name: String
|
||||
let sourcePath: String
|
||||
let line: Int
|
||||
let type: CType
|
||||
let address: Int?
|
||||
let offset: Int?
|
||||
let scope: Range<Int>?
|
||||
let isStatic: Bool
|
||||
var moduleID: String? = nil
|
||||
var scopeModuleID: String? = nil
|
||||
}
|
||||
let functions: [Function]
|
||||
let variables: [Variable]
|
||||
let sourceMap: CMOCProjectSourceMap
|
||||
|
||||
/// A compiler function record alone is not a C breakpoint location: pure
|
||||
/// assembly functions can have type metadata without any mapped C statement.
|
||||
/// Keep the advertised names and the actual stop selection on one path.
|
||||
func breakpointInstruction(named name: String) -> CMOCProjectSourceMap.Instruction? {
|
||||
let matches = functions.filter { $0.name == name }
|
||||
guard matches.count == 1, let function = matches.first else { return nil }
|
||||
return sourceMap.instructions.lazy.filter {
|
||||
$0.moduleID == function.moduleID && Int($0.address) >= function.body && Int($0.address) < function.end
|
||||
}.min { $0.address < $1.address }
|
||||
}
|
||||
|
||||
var breakpointFunctionNames: [String] {
|
||||
Set(functions.map(\.name)).filter { breakpointInstruction(named: $0) != nil }.sorted()
|
||||
}
|
||||
|
||||
/// Function-entry stops describe a verified executable symbol, including
|
||||
/// assembly functions and C prologues. They never imply a mapped C line.
|
||||
func entryFunction(named name: String) -> Function? {
|
||||
let matches = functions.filter { $0.name == name }
|
||||
guard matches.count == 1, let function = matches.first, verifiesEntry(function) else { return nil }
|
||||
return function
|
||||
}
|
||||
|
||||
var functionEntryNames: [String] {
|
||||
Set(functions.map(\.name)).filter { entryFunction(named: $0) != nil }.sorted()
|
||||
}
|
||||
|
||||
/// A live containing-function claim requires an explicit bank projection.
|
||||
/// PC may be in a verified prologue before the first mapped C statement.
|
||||
func entryFunction(containing address: UInt16) -> Function? {
|
||||
guard sourceMap.activeModuleIDs != nil || (sourceMap.bankedLayout == nil && !sourceMap.flatCodeGuards.isEmpty) else { return nil }
|
||||
let matches = functions.filter {
|
||||
Int(address) >= $0.entry && Int(address) < $0.end && verifiesEntry($0)
|
||||
}
|
||||
return matches.count == 1 ? matches.first : nil
|
||||
}
|
||||
|
||||
private func verifiesEntry(_ function: Function) -> Bool {
|
||||
guard !function.name.isEmpty, !function.sourcePath.isEmpty,
|
||||
function.entry >= 0, function.end > function.entry, function.end <= 0xfe00 else { return false }
|
||||
if sourceMap.bankedLayout == nil {
|
||||
guard function.moduleID == nil else { return false }
|
||||
var covered = function.entry
|
||||
for code in sourceMap.flatCodeGuards.sorted(by: { $0.address < $1.address }) {
|
||||
let begin = Int(code.address), end = begin + code.bytes.count
|
||||
if end <= covered { continue }
|
||||
guard begin <= covered else { return false }
|
||||
covered = end
|
||||
if covered >= function.end { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
guard
|
||||
let identity = function.moduleID, let module = sourceMap.bankedLayout?.module(id: identity),
|
||||
!module.codeSections.isEmpty,
|
||||
!module.pages.isEmpty, module.pages.count <= 8,
|
||||
Set(module.pages.map(\.logicalPage)).count == module.pages.count,
|
||||
module.pages.allSatisfy({ (0..<8).contains($0.logicalPage) && (0..<1024).contains($0.physicalPage) }) else { return false }
|
||||
if let active = sourceMap.activeModuleIDs, !active.contains(identity) { return false }
|
||||
for page in function.entry / 8192...(function.end - 1) / 8192 {
|
||||
guard module.pages.contains(where: { $0.logicalPage == page }) else { return false }
|
||||
}
|
||||
var covered = function.entry
|
||||
for code in module.codeGuards.sorted(by: { $0.address < $1.address }) {
|
||||
let begin = Int(code.address), end = begin + code.bytes.count
|
||||
if end <= covered { continue }
|
||||
guard begin <= covered else { return false }
|
||||
covered = end
|
||||
if covered >= function.end { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func projected(physicalPages: [Int: Int]) -> Self {
|
||||
projected(sourceMap: sourceMap.projected(physicalPages: physicalPages))
|
||||
}
|
||||
|
||||
func projected(physicalPages: [Int: Int], memory: Data, available: Data) -> Self {
|
||||
projected(sourceMap: sourceMap.projected(physicalPages: physicalPages, memory: memory, available: available))
|
||||
}
|
||||
|
||||
private func projected(sourceMap selected: CMOCProjectSourceMap) -> Self {
|
||||
guard let active = selected.activeModuleIDs else { return self }
|
||||
return Self(functions: functions.filter { $0.moduleID.map(active.contains) == true },
|
||||
variables: variables.filter { variable in
|
||||
variable.moduleID.map(active.contains) == true &&
|
||||
(variable.scopeModuleID == nil || variable.scopeModuleID.map(active.contains) == true)
|
||||
}, sourceMap: selected)
|
||||
}
|
||||
|
||||
enum Failure: LocalizedError {
|
||||
case invalid(String)
|
||||
var errorDescription: String? { if case .invalid(let text) = self { return "C variables unavailable: " + text }; return nil }
|
||||
}
|
||||
private struct Record: Decodable {
|
||||
let kind: String
|
||||
let name: String
|
||||
let location: String
|
||||
let type: CType?
|
||||
let symbol: String?
|
||||
let begin: String
|
||||
let end: String
|
||||
let frame: Bool?
|
||||
let offset: Int?
|
||||
let `static`: Bool?
|
||||
}
|
||||
static func parse(artifact: CMOCBuildArtifact, verifiedMap: CMOCProjectSourceMap) throws -> Self {
|
||||
func fail(_ message: String) -> Failure { .invalid(message) }
|
||||
guard verifiedMap.matches(sources: artifact.sources, binary: artifact.binaryData) else {
|
||||
throw fail("source or executable changed since verification. Rebuild before debugging.")
|
||||
}
|
||||
let linkData = try verifiedMap.bankedLayout?.linkMap ?? Data(contentsOf: artifact.mapURL)
|
||||
guard CMOCSourceMap.sha256(linkData) == verifiedMap.linkMapSHA256,
|
||||
let linkText = String(data: linkData, encoding: .utf8) else { throw fail("linker map changed since verification.") }
|
||||
func canonical(_ name: String) -> String {
|
||||
// NSString standardization can collapse /private/var to /var only
|
||||
// while the path exists. Strip the frozen physical build prefix
|
||||
// first, so keeping/reusing/deleting the incremental cache cannot
|
||||
// change the identity of the same retained compiler location.
|
||||
let physicalPrefix = artifact.compilationDirectory.path + "/"
|
||||
var name = name
|
||||
if name.hasPrefix(physicalPrefix) {
|
||||
name.removeFirst(physicalPrefix.count)
|
||||
} else {
|
||||
name = (name as NSString).standardizingPath
|
||||
let aliasPrefix = (artifact.compilationDirectory.path as NSString).standardizingPath + "/"
|
||||
if name.hasPrefix(aliasPrefix) { name.removeFirst(aliasPrefix.count) }
|
||||
}
|
||||
while name.hasPrefix("./") { name.removeFirst(2) }
|
||||
return name
|
||||
}
|
||||
let symbolPattern = try NSRegularExpression(pattern: #"^Symbol: (.+) \((.+)\) = ([0-9A-Fa-f]{4})$"#)
|
||||
var symbols: [String: [String: Int]] = [:]
|
||||
for line in linkText.components(separatedBy: .newlines) {
|
||||
let ns = line as NSString
|
||||
guard let match = symbolPattern.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)) else { continue }
|
||||
let name = ns.substring(with: match.range(at: 1)), object = canonical(ns.substring(with: match.range(at: 2)))
|
||||
guard let address = Int(ns.substring(with: match.range(at: 3)), radix: 16), symbols[object]?[name] == nil else {
|
||||
throw fail("duplicate or malformed linker symbol.")
|
||||
}
|
||||
symbols[object, default: [:]][name] = address
|
||||
}
|
||||
func location(_ raw: String) throws -> (String, Int) {
|
||||
guard let colon = raw.lastIndex(of: ":"), let line = Int(raw[raw.index(after: colon)...]), line > 0 else {
|
||||
throw fail("invalid compiler source location.")
|
||||
}
|
||||
let path = canonical(String(raw[..<colon]))
|
||||
guard let source = artifact.sources[path], let text = String(data: source, encoding: .utf8),
|
||||
line <= text.components(separatedBy: .newlines).count else { throw fail("compiler location is outside the verified source snapshot.") }
|
||||
return (path, line)
|
||||
}
|
||||
func validate(_ type: CType, depth: Int = 0) throws {
|
||||
guard depth <= 12, type.name.count <= 4096, (0...65535).contains(type.size) else { throw fail("invalid type metadata.") }
|
||||
switch type.kind {
|
||||
case "integer": guard [1, 2, 4].contains(type.size), type.signed != nil else { throw fail("unsupported integer layout.") }
|
||||
case "pointer": guard type.size == 2, let element = type.element else { throw fail("unsupported pointer layout.") }; try validate(element, depth: depth + 1)
|
||||
case "array":
|
||||
guard let count = type.count, (0...65535).contains(count), let element = type.element else { throw fail("invalid array layout.") }
|
||||
try validate(element, depth: depth + 1)
|
||||
guard count * element.size == type.size else { throw fail("invalid array size.") }
|
||||
case "aggregate":
|
||||
guard let members = type.members, members.count <= 1024, Set(members.map(\.name)).count == members.count else { throw fail("invalid aggregate layout.") }
|
||||
for member in members {
|
||||
try validate(member.type, depth: depth + 1)
|
||||
guard member.offset >= 0, member.offset <= type.size,
|
||||
member.type.size <= type.size - member.offset else { throw fail("member leaves its aggregate.") }
|
||||
}
|
||||
case "floating":
|
||||
guard (type.floatingFormat?.count ?? 0) <= 128 else { throw fail("invalid floating-point format metadata.") }
|
||||
// Unknown or legacy formats remain individually unavailable.
|
||||
// Known tags must agree with the declared storage layout.
|
||||
if let format = type.floatingFormat,
|
||||
let size = ["coco-basic-40": 5, "ieee754-binary32-be": 4][format], size != type.size {
|
||||
throw fail("floating-point format disagrees with its storage size.")
|
||||
}
|
||||
case "unsupported": break
|
||||
default: throw fail("unknown type metadata version.")
|
||||
}
|
||||
}
|
||||
var functions: [Function] = [], variables: [Variable] = []
|
||||
for object in verifiedMap.objectHashes.keys.sorted() {
|
||||
guard let listingHash = verifiedMap.listingHashes[object],
|
||||
listingHash != CMOCSourceMap.sha256(Data()) else { continue }
|
||||
let listingPath = String(object.dropLast(2)) + ".lst"
|
||||
let listing = try Data(contentsOf: artifact.fileURL(listingPath))
|
||||
let bytes = try Data(contentsOf: artifact.fileURL(object))
|
||||
guard CMOCSourceMap.sha256(listing) == verifiedMap.listingHashes[object],
|
||||
CMOCSourceMap.sha256(bytes) == verifiedMap.objectHashes[object],
|
||||
let text = String(data: listing, encoding: .utf8) else { throw fail("compiler artifacts changed since verification.") }
|
||||
// LWASM retains at most 2,048 input bytes per line. Large compiler
|
||||
// type records therefore lose their tail in the listing. Recover
|
||||
// only from the immutable, source-hashed assembly from this build,
|
||||
// and bind every recovered record to the corresponding listing row.
|
||||
func metadataRows(_ text: String) -> [(payload: String, prefixBytes: Int)] {
|
||||
text.components(separatedBy: .newlines).compactMap { row in
|
||||
guard let marker = row.range(of: "* VCCDBG1 ") else { return nil }
|
||||
return (String(row[marker.upperBound...]), row[..<marker.upperBound].utf8.count)
|
||||
}
|
||||
}
|
||||
let listedRows = metadataRows(text)
|
||||
var payloads = listedRows.map(\.payload)
|
||||
let assemblyPath = String(object.dropLast(2)) + ".s"
|
||||
if let expected = verifiedMap.sourceHashes[assemblyPath] {
|
||||
guard let frozen = artifact.sources[assemblyPath], CMOCSourceMap.sha256(frozen) == expected else {
|
||||
throw fail("\(assemblyPath): compiler assembly is outside the verified source snapshot.")
|
||||
}
|
||||
let assembly = try CMOCProject.readText(artifact.fileURL(assemblyPath), maximumBytes: CMOCProject.maximumFileBytes)
|
||||
guard CMOCSourceMap.sha256(Data(assembly.utf8)) == expected else {
|
||||
throw fail("\(assemblyPath): compiler assembly changed since verification.")
|
||||
}
|
||||
let completeRows = metadataRows(assembly)
|
||||
guard completeRows.count == listedRows.count else {
|
||||
throw fail("\(assemblyPath): compiler metadata record count differs from the verified listing.")
|
||||
}
|
||||
for (complete, listed) in zip(completeRows, listedRows) {
|
||||
let exact = complete.payload == listed.payload
|
||||
let truncated = complete.prefixBytes < 2048 &&
|
||||
listed.payload.utf8.count == 2048 - complete.prefixBytes &&
|
||||
complete.payload.utf8.count > listed.payload.utf8.count &&
|
||||
complete.payload.hasPrefix(listed.payload)
|
||||
guard exact || truncated else {
|
||||
throw fail("\(assemblyPath): compiler metadata record differs from the verified listing.")
|
||||
}
|
||||
}
|
||||
payloads = completeRows.map(\.payload)
|
||||
}
|
||||
let objectSymbols = try CMOCSourceMap.resolvedObjectSymbols(object: bytes, objectName: object,
|
||||
objectAliases: [artifact.compilationDirectory.appendingPathComponent(object).path], linkMap: linkData)
|
||||
let symbolModules = try verifiedMap.bankedLayout.map { try CMOCSourceMap.resolvedObjectSymbolModules(object: bytes, layout: $0) } ?? [:]
|
||||
func module(_ symbol: String) throws -> String? {
|
||||
guard verifiedMap.bankedLayout != nil else { return nil }
|
||||
guard let id = symbolModules[symbol] else { throw fail("compiler storage label has no verified banked placement.") }
|
||||
return id
|
||||
}
|
||||
func visible(_ id: String?) -> Bool {
|
||||
guard let active = verifiedMap.activeModuleIDs else { return true }
|
||||
return id.map(active.contains) == true
|
||||
}
|
||||
func address(_ name: String) throws -> Int {
|
||||
guard let result = symbols[canonical(object)]?[name], objectSymbols[name] == result else {
|
||||
throw fail("compiler storage label disagrees with its object symbol table.")
|
||||
}
|
||||
return result
|
||||
}
|
||||
for (recordIndex, payload) in payloads.enumerated() {
|
||||
guard payload.utf8.count < 512 * 1024, functions.count + variables.count < 20000 else { throw fail("debug metadata exceeds its limits.") }
|
||||
let payloadData = Data(payload.utf8)
|
||||
// Bound nesting before recursive Decodable type construction.
|
||||
let decodedJSON: Any
|
||||
do { decodedJSON = try JSONSerialization.jsonObject(with: payloadData) }
|
||||
catch {
|
||||
throw fail("\(listingPath), metadata record \(recordIndex + 1): invalid or truncated JSON; retain hash-verified compiler assembly for complete type records.")
|
||||
}
|
||||
var pending: [(Any, Int)] = [(decodedJSON, 0)]
|
||||
var nodes = 0
|
||||
while let (node, depth) = pending.popLast() {
|
||||
nodes += 1
|
||||
guard depth <= 24, nodes <= 10000 else { throw fail("debug type nesting exceeds its limits.") }
|
||||
if let dictionary = node as? [String: Any] { pending += dictionary.values.map { ($0, depth + 1) } }
|
||||
else if let array = node as? [Any] { pending += array.map { ($0, depth + 1) } }
|
||||
}
|
||||
let record: Record
|
||||
do { record = try JSONDecoder().decode(Record.self, from: payloadData) }
|
||||
catch {
|
||||
throw fail("\(listingPath), metadata record \(recordIndex + 1): unsupported compiler metadata format (\(String(describing: error))).")
|
||||
}
|
||||
let (path, line) = try location(record.location)
|
||||
guard !record.name.isEmpty, record.name.count < 1024 else { throw fail("invalid variable or function name.") }
|
||||
if record.kind == "function" {
|
||||
guard let symbol = record.symbol else { throw fail("function has no entry symbol.") }
|
||||
let entry = try address(symbol), body = try address(record.begin), end = try address(record.end)
|
||||
guard entry <= body, body <= end else { throw fail("invalid function range.") }
|
||||
let identity = try module(symbol)
|
||||
guard try module(record.begin) == identity, try module(record.end) == identity else { throw fail("function spans incompatible module placements.") }
|
||||
if visible(identity) {
|
||||
functions.append(Function(name: record.name, sourcePath: path, entry: entry, body: body, end: end, frame: record.frame == true, moduleID: identity, sourceLine: line))
|
||||
}
|
||||
} else if record.kind == "variable" {
|
||||
guard let type = record.type, (record.offset == nil) != (record.symbol == nil) else { throw fail("variable has ambiguous storage.") }
|
||||
try validate(type)
|
||||
let storage = try record.symbol.map(address)
|
||||
if let storage, storage + type.size > 65536 { throw fail("variable leaves logical memory.") }
|
||||
if let offset = record.offset, !(-32768...32767).contains(offset) { throw fail("invalid stack offset.") }
|
||||
var scope: Range<Int>?
|
||||
let identity = try record.symbol.map(module) ?? (record.begin.isEmpty ? nil : module(record.begin))
|
||||
var scopeIdentity: String?
|
||||
if !record.begin.isEmpty || !record.end.isEmpty {
|
||||
let begin = try address(record.begin), end = try address(record.end)
|
||||
guard begin <= end else { throw fail("invalid lexical scope.") }
|
||||
guard try module(record.begin) == module(record.end) else { throw fail("lexical scope spans incompatible module placements.") }
|
||||
scopeIdentity = try module(record.begin)
|
||||
scope = begin..<end
|
||||
} else if record.offset != nil { throw fail("local variable has no lexical scope.") }
|
||||
if visible(identity) && (scopeIdentity == nil || visible(scopeIdentity)) {
|
||||
variables.append(Variable(name: record.name, sourcePath: path, line: line, type: type, address: storage,
|
||||
offset: record.offset, scope: scope, isStatic: record.static == true,
|
||||
moduleID: identity, scopeModuleID: scopeIdentity))
|
||||
}
|
||||
} else { throw fail("unknown compiler metadata record.") }
|
||||
}
|
||||
}
|
||||
guard !functions.isEmpty else { throw fail("rebuild with the VCC Plus compiler to include C debug metadata.") }
|
||||
return Self(functions: functions, variables: variables, sourceMap: verifiedMap)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Read-only watches over one atomic, side-effect-free debugger snapshot.
|
||||
/// This is a deliberately bounded expression evaluator, not guest execution.
|
||||
struct CMOCWatchEvaluator {
|
||||
struct Context {
|
||||
let pc: UInt16
|
||||
let u: UInt16
|
||||
let memory: Data
|
||||
let available: Data
|
||||
init(pc: UInt16, u: UInt16, memory: Data, available: Data) {
|
||||
self.pc = pc; self.u = u
|
||||
// Foundation's NSData bridge may share mutable backing even when
|
||||
// the Swift value is let-bound. Verification is cached, so own the
|
||||
// snapshot bytes rather than relying on that bridge's copy-on-write.
|
||||
func owned(_ data: Data) -> Data {
|
||||
data.withUnsafeBytes { bytes in
|
||||
bytes.isEmpty ? Data() : Data(bytes: bytes.baseAddress!, count: bytes.count)
|
||||
}
|
||||
}
|
||||
self.memory = owned(memory); self.available = owned(available)
|
||||
}
|
||||
}
|
||||
struct Value: Identifiable {
|
||||
var id: String { name }
|
||||
let name: String
|
||||
let typeName: String
|
||||
let value: String
|
||||
let address: UInt16?
|
||||
let error: String?
|
||||
}
|
||||
enum Root: Hashable { case variable(String), watch(String) }
|
||||
enum Component: Hashable { case index(Int), member(String), pointee }
|
||||
struct TreePath: Hashable {
|
||||
let root: Root
|
||||
let components: [Component]
|
||||
init(root: Root, components: [Component] = []) { self.root = root; self.components = components }
|
||||
func appending(_ component: Component) -> TreePath { TreePath(root: root, components: components + [component]) }
|
||||
}
|
||||
struct TreeNode: Identifiable {
|
||||
var id: TreePath { path }
|
||||
let path: TreePath
|
||||
let name: String
|
||||
let typeName: String
|
||||
let value: String
|
||||
let address: UInt16?
|
||||
let error: String?
|
||||
let childCount: Int
|
||||
}
|
||||
struct TreePage {
|
||||
let nodes: [TreeNode]
|
||||
let totalCount: Int
|
||||
let nextOffset: Int?
|
||||
let error: String?
|
||||
}
|
||||
private final class VerificationCache { var result: Result<Void, Error>? }
|
||||
// Copies share only immutable snapshot provenance. Each newly captured
|
||||
// evaluator gets a new cache; expanding 32 children must not rescan all code
|
||||
// 32 times. Frame availability is checked separately on every root resolve.
|
||||
private let verificationCache = VerificationCache()
|
||||
private struct Problem: Error { let message: String; init(_ message: String) { self.message = message } }
|
||||
private struct Operand {
|
||||
let type: CMOCVariableDebug.CType
|
||||
let address: Int?
|
||||
let immediate: Int64?
|
||||
}
|
||||
let metadata: CMOCVariableDebug
|
||||
let context: Context
|
||||
var frameLocalsAvailable = true
|
||||
private var function: CMOCVariableDebug.Function? {
|
||||
metadata.functions.first { $0.body <= Int(context.pc) && Int(context.pc) < $0.end }
|
||||
}
|
||||
// A verified assembly entry/prologue establishes file identity without
|
||||
// establishing a C frame. Keep stack-local eligibility on the body above.
|
||||
private var fileScopeFunction: CMOCVariableDebug.Function? {
|
||||
function ?? metadata.entryFunction(containing: context.pc)
|
||||
}
|
||||
private func verified() throws {
|
||||
if let result = verificationCache.result { return try result.get() }
|
||||
do {
|
||||
try verifySnapshot()
|
||||
verificationCache.result = .success(())
|
||||
} catch {
|
||||
verificationCache.result = .failure(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private func verifySnapshot() throws {
|
||||
guard context.memory.count == 65536, context.available.count == 65536 else { throw Problem("A complete paused memory snapshot is required.") }
|
||||
guard metadata.sourceMap.verifiesRuntime(memory: context.memory, available: context.available) else {
|
||||
throw Problem("The running code no longer matches this build, or its memory is unavailable.")
|
||||
}
|
||||
}
|
||||
private func candidates(named name: String? = nil) -> [CMOCVariableDebug.Variable] {
|
||||
let location = metadata.sourceMap.location(at: context.pc)
|
||||
return metadata.variables.filter { variable in
|
||||
if let name, variable.name != name { return false }
|
||||
if let scope = variable.scope {
|
||||
guard scope.contains(Int(context.pc)), function != nil else { return false }
|
||||
// A block's stack reservation precedes its declarations. Do not
|
||||
// expose a later declaration (or shadow an outer name) early.
|
||||
if variable.offset != nil, let location, location.path == variable.sourcePath,
|
||||
location.line < variable.line { return false }
|
||||
} else if variable.isStatic, variable.sourcePath != fileScopeFunction?.sourcePath { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
private func resolve(_ name: String) throws -> CMOCVariableDebug.Variable {
|
||||
let matches = candidates(named: name)
|
||||
let locals = matches.filter { $0.scope != nil }.sorted { $0.scope!.count < $1.scope!.count }
|
||||
if let first = locals.first {
|
||||
guard locals.count == 1 || locals[1].scope != first.scope else { throw Problem("The name ‘\(name)’ is ambiguous in this scope.") }
|
||||
return first
|
||||
}
|
||||
let sameFile = matches.filter { $0.sourcePath == fileScopeFunction?.sourcePath }
|
||||
let globals = sameFile.isEmpty ? matches : sameFile
|
||||
guard globals.count == 1, let variable = globals.first else {
|
||||
throw Problem(globals.isEmpty ? "‘\(name)’ is not available in the current C scope." : "The name ‘\(name)’ is ambiguous; stop in its source file.")
|
||||
}
|
||||
return variable
|
||||
}
|
||||
private func operand(_ variable: CMOCVariableDebug.Variable) throws -> Operand {
|
||||
if let address = variable.address { return Operand(type: variable.type, address: address, immediate: nil) }
|
||||
guard frameLocalsAvailable else {
|
||||
throw Problem("This frame’s local storage cannot be verified. Pause inside a supported unoptimized function body with a preserved frame pointer.")
|
||||
}
|
||||
guard let offset = variable.offset, function?.frame == true else {
|
||||
throw Problem("Local variables require an unoptimized, preserved frame pointer. Rebuild with -O0 -fno-omit-frame-pointer and pause inside the function body.")
|
||||
}
|
||||
let address = Int(context.u) + offset
|
||||
guard address >= 0, address + variable.type.size <= 65536 else { throw Problem("The variable's stack storage is outside logical memory.") }
|
||||
return Operand(type: variable.type, address: address, immediate: nil)
|
||||
}
|
||||
private func bytes(at address: Int, count: Int) throws -> [UInt8] {
|
||||
guard address >= 0, count >= 0, address <= 65536 - count,
|
||||
!(address..<(address + count)).contains(where: { context.available[$0] == 0 }) else {
|
||||
throw Problem("This memory is unavailable for inspection (including hardware I/O).")
|
||||
}
|
||||
return Array(context.memory[address..<(address + count)])
|
||||
}
|
||||
private func integer(_ value: Operand) throws -> Int64 {
|
||||
if let immediate = value.immediate { return immediate }
|
||||
if value.type.kind == "floating" {
|
||||
throw Problem("Floating-point values can be inspected, but floating-point watch arithmetic is not supported.")
|
||||
}
|
||||
guard ["integer", "pointer"].contains(value.type.kind), let address = value.address else {
|
||||
throw Problem("This operation requires an integer or pointer value.")
|
||||
}
|
||||
let data = try bytes(at: address, count: value.type.size)
|
||||
var result: Int64 = 0
|
||||
for byte in data { result = (result << 8) | Int64(byte) }
|
||||
if value.type.kind == "integer", value.type.signed == true, let first = data.first, first & 0x80 != 0 {
|
||||
result -= Int64(1) << (data.count * 8)
|
||||
}
|
||||
return result
|
||||
}
|
||||
private func floating(_ operand: Operand) throws -> String {
|
||||
guard let format = operand.type.floatingFormat else {
|
||||
throw Problem("This build does not identify its floating-point format. Rebuild with the current VCC Plus compiler.")
|
||||
}
|
||||
let expectedSize: Int
|
||||
switch format {
|
||||
case "coco-basic-40": expectedSize = 5
|
||||
case "ieee754-binary32-be": expectedSize = 4
|
||||
default: throw Problem("Unsupported floating-point format ‘\(format)’; inspect its bytes in Memory.")
|
||||
}
|
||||
guard operand.type.size == expectedSize, let address = operand.address else {
|
||||
throw Problem("The floating-point storage does not match its compiler-described format.")
|
||||
}
|
||||
let data = try bytes(at: address, count: expectedSize)
|
||||
let value: Double
|
||||
if format == "coco-basic-40" {
|
||||
// CMOC RealConstantExpr::getRepresentation and Color BASIC's packed
|
||||
// format: exponent byte, sign bit, 31 fraction bits; hidden leading 1.
|
||||
// Exponent zero represents zero regardless of the remaining bytes.
|
||||
if data[0] == 0 { return "0" }
|
||||
let fraction = (UInt32(data[1] & 0x7f) << 24) | (UInt32(data[2]) << 16)
|
||||
| (UInt32(data[3]) << 8) | UInt32(data[4])
|
||||
let magnitude = ldexp(1 + Double(fraction) / 2147483648, Int32(data[0]) - 129)
|
||||
value = data[1] & 0x80 == 0 ? magnitude : -magnitude
|
||||
} else {
|
||||
// Decode the target byte order explicitly, independent of host CPU.
|
||||
let bits = data.reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
|
||||
value = Double(Float(bitPattern: bits))
|
||||
}
|
||||
if value.isNaN { return "NaN" }
|
||||
if value.isInfinite { return value.sign == .minus ? "-Infinity" : "Infinity" }
|
||||
if value == 0 { return value.sign == .minus ? "-0" : "0" }
|
||||
// Enough significant decimal digits to distinguish adjacent target
|
||||
// values (32-bit significand for BASIC, 24-bit for IEEE binary32).
|
||||
return String(format: expectedSize == 5 ? "%.11g" : "%.9g",
|
||||
locale: Locale(identifier: "en_US_POSIX"), value)
|
||||
}
|
||||
private func describe(_ operand: Operand, depth: Int = 0) throws -> String {
|
||||
let type = operand.type
|
||||
switch type.kind {
|
||||
case "integer": return String(try integer(operand))
|
||||
case "pointer": return String(format: "$%04llX", try integer(operand))
|
||||
case "array":
|
||||
guard let address = operand.address, let element = type.element, let count = type.count else { throw Problem("Array layout is unavailable.") }
|
||||
if depth >= 2 { return "[\(count) elements]" }
|
||||
let values = try (0..<min(count, 8)).map { index in
|
||||
try describe(Operand(type: element, address: address + index * element.size, immediate: nil), depth: depth + 1)
|
||||
}
|
||||
return "[" + values.joined(separator: ", ") + (count > 8 ? ", …]" : "]")
|
||||
case "aggregate":
|
||||
guard let address = operand.address, let members = type.members else { throw Problem("Aggregate layout is unavailable.") }
|
||||
if depth >= 2 { return "{…}" }
|
||||
let values = try members.prefix(4).map { member in
|
||||
member.name + " = " + (try describe(Operand(type: member.type, address: address + member.offset, immediate: nil), depth: depth + 1))
|
||||
}
|
||||
return "{" + values.joined(separator: ", ") + (members.count > 4 ? ", …}" : "}")
|
||||
case "floating": return try floating(operand)
|
||||
default: throw Problem("This compiler type is not supported by the watch evaluator.")
|
||||
}
|
||||
}
|
||||
func visibleVariables() -> [Value] {
|
||||
let names = Set(candidates().map(\.name)).sorted()
|
||||
let verificationError: Error?
|
||||
do { try verified(); verificationError = nil } catch { verificationError = error }
|
||||
return names.map { name in
|
||||
do {
|
||||
if let verificationError { throw verificationError }
|
||||
let variable = try resolve(name), value = try operand(variable)
|
||||
return Value(name: name, typeName: value.type.name, value: try describe(value),
|
||||
address: value.address.flatMap(UInt16.init(exactly:)), error: nil)
|
||||
} catch {
|
||||
let type = (try? resolve(name))?.type.name ?? ""
|
||||
return Value(name: name, typeName: type, value: "Unavailable", address: nil, error: message(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
func evaluate(_ expression: String) -> Value {
|
||||
do {
|
||||
try verified()
|
||||
var parser = try Parser(expression)
|
||||
let tree = try parser.parse()
|
||||
let result = try evaluate(tree, depth: 0)
|
||||
return Value(name: expression, typeName: result.type.name, value: try describe(result),
|
||||
address: result.address.flatMap(UInt16.init(exactly:)), error: nil)
|
||||
} catch { return Value(name: expression, typeName: "", value: "Unavailable", address: nil, error: message(error)) }
|
||||
}
|
||||
// Lazy tree access resolves typed paths from the current root and frame.
|
||||
// No stored node is a capability to read an address from an older snapshot.
|
||||
func variableRootPaths() -> [TreePath] {
|
||||
Set(candidates().map(\.name)).sorted().map { TreePath(root: .variable($0)) }
|
||||
}
|
||||
func variableRoots() -> [TreeNode] { variableRootPaths().map { treeNode(at: $0) } }
|
||||
func variableTreeRoots() -> [TreeNode] { variableRoots() }
|
||||
func watchRoot(_ expression: String) -> TreeNode { treeNode(at: .init(root: .watch(expression))) }
|
||||
func watchTreeRoot(_ expression: String) -> TreeNode { watchRoot(expression) }
|
||||
func treeNode(at path: TreePath) -> TreeNode {
|
||||
do {
|
||||
try verified()
|
||||
return try makeTreeNode(path: path, operand: treeOperand(at: path))
|
||||
} catch { return treeError(path, error) }
|
||||
}
|
||||
func children(of path: TreePath, offset: Int = 0) -> TreePage {
|
||||
do {
|
||||
try verified()
|
||||
guard path.components.count < 12 else { throw Problem("The 12-level inspection limit has been reached.") }
|
||||
let parent = try treeOperand(at: path)
|
||||
let total = treeChildCount(parent.type)
|
||||
guard offset >= 0, offset <= total else { throw Problem("This child page is outside the declared bounds.") }
|
||||
let end = min(total, offset + 32)
|
||||
let nodes = (offset..<end).map { index -> TreeNode in
|
||||
let component: Component
|
||||
switch parent.type.kind {
|
||||
case "array": component = .index(index)
|
||||
case "aggregate": component = .member(parent.type.members![index].name)
|
||||
default: component = .pointee
|
||||
}
|
||||
let child = path.appending(component)
|
||||
do { return try makeTreeNode(path: child, operand: treeOperand(at: child)) }
|
||||
catch { return treeError(child, error) }
|
||||
}
|
||||
return TreePage(nodes: nodes, totalCount: total, nextOffset: end < total ? end : nil, error: nil)
|
||||
} catch { return TreePage(nodes: [], totalCount: 0, nextOffset: nil, error: message(error)) }
|
||||
}
|
||||
private func treeName(_ path: TreePath) -> String {
|
||||
if let last = path.components.last {
|
||||
switch last { case .index(let i): return "[\(i)]"; case .member(let name): return name; case .pointee: return "Pointee" }
|
||||
}
|
||||
switch path.root { case .variable(let name), .watch(let name): return name }
|
||||
}
|
||||
private func treeError(_ path: TreePath, _ error: Error) -> TreeNode {
|
||||
TreeNode(path: path, name: treeName(path), typeName: "", value: "Unavailable", address: nil,
|
||||
error: message(error), childCount: 0)
|
||||
}
|
||||
private func treeChildCount(_ type: CMOCVariableDebug.CType) -> Int {
|
||||
switch type.kind {
|
||||
case "array": return min(max(type.count ?? 0, 0), 65535)
|
||||
case "aggregate": return min(type.members?.count ?? 0, 1024)
|
||||
case "pointer": return 1 // Explicit expansion explains null/unknown targets.
|
||||
default: return 0
|
||||
}
|
||||
}
|
||||
private func makeTreeNode(path: TreePath, operand: Operand) throws -> TreeNode {
|
||||
let type = operand.type
|
||||
let count = treeChildCount(type)
|
||||
let summary: String
|
||||
// Aggregate rows do not read children. An unavailable member cannot
|
||||
// prevent expansion of its inspectable siblings.
|
||||
do {
|
||||
switch type.kind {
|
||||
case "array": summary = "[\(count) elements]"
|
||||
case "aggregate": summary = "{\(count) members}"
|
||||
default: summary = try describe(operand)
|
||||
}
|
||||
} catch {
|
||||
return TreeNode(path: path, name: treeName(path), typeName: type.name, value: "Unavailable",
|
||||
address: operand.address.flatMap(UInt16.init(exactly:)), error: message(error), childCount: 0)
|
||||
}
|
||||
let atLimit = path.components.count >= 12 && count > 0
|
||||
return TreeNode(path: path, name: treeName(path), typeName: type.name, value: summary,
|
||||
address: operand.address.flatMap(UInt16.init(exactly:)),
|
||||
error: atLimit ? "The 12-level inspection limit has been reached." : nil,
|
||||
childCount: atLimit ? 0 : count)
|
||||
}
|
||||
private struct TreeVisit: Hashable {
|
||||
let address: Int
|
||||
let name: String
|
||||
let kind: String
|
||||
let size: Int
|
||||
}
|
||||
private func treeOperand(at path: TreePath) throws -> Operand {
|
||||
guard path.components.count <= 12 else { throw Problem("The 12-level inspection limit has been reached.") }
|
||||
var value: Operand
|
||||
switch path.root {
|
||||
case .variable(let name): value = try operand(resolve(name))
|
||||
case .watch(let expression):
|
||||
var parser = try Parser(expression)
|
||||
value = try evaluate(parser.parse(), depth: 0)
|
||||
}
|
||||
var visited = Set<TreeVisit>()
|
||||
func visit(_ operand: Operand) -> TreeVisit? {
|
||||
operand.address.map { TreeVisit(address: $0, name: operand.type.name, kind: operand.type.kind, size: operand.type.size) }
|
||||
}
|
||||
if let root = visit(value) { visited.insert(root) }
|
||||
for component in path.components {
|
||||
switch component {
|
||||
case .index(let index):
|
||||
guard value.type.kind == "array", let count = value.type.count, let element = value.type.element,
|
||||
let first = value.address, index >= 0, index < count, element.size > 0 else {
|
||||
throw Problem("Array index is outside its declared bounds or its element layout is unavailable.")
|
||||
}
|
||||
let (displacement, overflow) = index.multipliedReportingOverflow(by: element.size)
|
||||
let (address, additionOverflow) = first.addingReportingOverflow(displacement)
|
||||
guard !overflow, !additionOverflow, address >= 0, element.size <= 65536,
|
||||
address <= 65536 - element.size else { throw Problem("Indexed address is outside logical memory.") }
|
||||
value = Operand(type: element, address: address, immediate: nil)
|
||||
case .member(let name):
|
||||
guard value.type.kind == "aggregate", let first = value.address,
|
||||
let member = value.type.members?.first(where: { $0.name == name }) else {
|
||||
throw Problem("No inspectable member named ‘\(name)’.")
|
||||
}
|
||||
let (address, overflow) = first.addingReportingOverflow(member.offset)
|
||||
guard !overflow, address >= 0, member.type.size >= 0, member.type.size <= 65536,
|
||||
address <= 65536 - member.type.size else { throw Problem("Member address is outside logical memory.") }
|
||||
value = Operand(type: member.type, address: address, immediate: nil)
|
||||
case .pointee:
|
||||
value = try dereference(value)
|
||||
if let next = visit(value), visited.contains(next) { throw Problem("Pointer cycle: this object already appears in the expanded path.") }
|
||||
}
|
||||
if let next = visit(value) { visited.insert(next) }
|
||||
}
|
||||
return value
|
||||
}
|
||||
private func message(_ error: Error) -> String { (error as? Problem)?.message ?? error.localizedDescription }
|
||||
private indirect enum Expr {
|
||||
case identifier(String), number(Int64), unary(String, Expr), binary(String, Expr, Expr), index(Expr, Expr), member(Expr, String, Bool)
|
||||
}
|
||||
private func evaluate(_ expression: Expr, depth: Int) throws -> Operand {
|
||||
guard depth <= 32 else { throw Problem("Watch expression is too deeply nested.") }
|
||||
func eval(_ value: Expr) throws -> Operand { try evaluate(value, depth: depth + 1) }
|
||||
func literal(_ value: Int64) -> Operand { Operand(type: .init(name: "watch integer (64-bit)", kind: "integer", size: 8, signed: true), address: nil, immediate: value) }
|
||||
switch expression {
|
||||
case .identifier(let name): return try operand(resolve(name))
|
||||
case .number(let value): return literal(value)
|
||||
case .unary(let operation, let expression):
|
||||
let value = try eval(expression)
|
||||
if operation == "&" {
|
||||
guard let address = value.address else { throw Problem("Address-of requires stored data.") }
|
||||
return Operand(type: .init(name: value.type.name + " *", kind: "pointer", size: 2, element: value.type), address: nil, immediate: Int64(address))
|
||||
}
|
||||
if operation == "*" { return try dereference(value) }
|
||||
let number = try integer(value)
|
||||
switch operation {
|
||||
case "+": return literal(number)
|
||||
case "-": guard number != Int64.min else { throw Problem("Integer overflow in watch.") }; return literal(-number)
|
||||
case "~": return literal(~number)
|
||||
case "!": return literal(number == 0 ? 1 : 0)
|
||||
default: throw Problem("Unsupported unary operation.")
|
||||
}
|
||||
case .index(let target, let index):
|
||||
let base = try eval(target), number = try integer(eval(index))
|
||||
let element: CMOCVariableDebug.CType, address: Int64
|
||||
if base.type.kind == "array", let next = base.type.element, let first = base.address, let count = base.type.count {
|
||||
guard number >= 0, number < count else { throw Problem("Array index is outside its declared bounds.") }
|
||||
element = next; address = Int64(first)
|
||||
} else if base.type.kind == "pointer", let next = base.type.element {
|
||||
element = next; address = try integer(base)
|
||||
} else { throw Problem("Indexing requires an array or pointer.") }
|
||||
guard element.size > 0, number >= -65536, number <= 65536 else { throw Problem("Invalid element size or index.") }
|
||||
let result = address + number * Int64(element.size)
|
||||
guard result >= 0, result + Int64(element.size) <= 65536 else { throw Problem("Indexed address is outside logical memory.") }
|
||||
return Operand(type: element, address: Int(result), immediate: nil)
|
||||
case .member(let target, let name, let pointer):
|
||||
let source = try eval(target), base = try pointer ? dereference(source) : source
|
||||
guard base.type.kind == "aggregate", let address = base.address,
|
||||
let member = base.type.members?.first(where: { $0.name == name }) else { throw Problem("No inspectable member named ‘\(name)’.") }
|
||||
return Operand(type: member.type, address: address + member.offset, immediate: nil)
|
||||
case .binary(let operation, let left, let right):
|
||||
let lhs = try eval(left)
|
||||
let a = try integer(lhs)
|
||||
if operation == "&&", a == 0 { return literal(0) }
|
||||
if operation == "||", a != 0 { return literal(1) }
|
||||
let rhs = try eval(right), b = try integer(rhs)
|
||||
if lhs.type.kind == "pointer", ["+", "-"].contains(operation), rhs.type.kind == "integer", let element = lhs.type.element {
|
||||
guard element.size > 0, b >= -65536, b <= 65536 else { throw Problem("Invalid pointer arithmetic.") }
|
||||
let address = a + (operation == "+" ? b : -b) * Int64(element.size)
|
||||
guard (0...65535).contains(address) else { throw Problem("Pointer arithmetic leaves logical memory.") }
|
||||
return Operand(type: lhs.type, address: nil, immediate: address)
|
||||
}
|
||||
switch operation {
|
||||
case "+": let (r,o) = a.addingReportingOverflow(b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r)
|
||||
case "-": let (r,o) = a.subtractingReportingOverflow(b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r)
|
||||
case "*": let (r,o) = a.multipliedReportingOverflow(by: b); guard !o else { throw Problem("Integer overflow in watch.") }; return literal(r)
|
||||
case "/", "%": guard b != 0, !(a == Int64.min && b == -1) else { throw Problem("Invalid division in watch.") }; return literal(operation == "/" ? a / b : a % b)
|
||||
case "&": return literal(a & b)
|
||||
case "|": return literal(a | b)
|
||||
case "^": return literal(a ^ b)
|
||||
case "<<", ">>":
|
||||
guard (0...31).contains(b) else { throw Problem("Shift count must be between 0 and 31.") }
|
||||
if operation == ">>" { return literal(a >> b) }
|
||||
let (shifted, overflow) = a.multipliedReportingOverflow(by: Int64(1) << b)
|
||||
guard !overflow else { throw Problem("Integer overflow in watch.") }; return literal(shifted)
|
||||
case "==": return literal(a == b ? 1 : 0)
|
||||
case "!=": return literal(a != b ? 1 : 0)
|
||||
case "<": return literal(a < b ? 1 : 0)
|
||||
case "<=": return literal(a <= b ? 1 : 0)
|
||||
case ">": return literal(a > b ? 1 : 0)
|
||||
case ">=": return literal(a >= b ? 1 : 0)
|
||||
case "&&": return literal(a != 0 && b != 0 ? 1 : 0)
|
||||
case "||": return literal(a != 0 || b != 0 ? 1 : 0)
|
||||
default: throw Problem("Unsupported binary operation.")
|
||||
}
|
||||
}
|
||||
}
|
||||
private func dereference(_ value: Operand) throws -> Operand {
|
||||
guard value.type.kind == "pointer", let element = value.type.element, element.size > 0 else { throw Problem("Dereference requires a pointer to a known data type.") }
|
||||
let address = try integer(value)
|
||||
guard address > 0, address + Int64(element.size) <= 65536 else { throw Problem("Null or out-of-range pointer.") }
|
||||
return Operand(type: element, address: Int(address), immediate: nil)
|
||||
}
|
||||
private struct Parser {
|
||||
var tokens: [String] = []
|
||||
var index = 0
|
||||
init(_ text: String) throws {
|
||||
guard text.utf8.count <= 1024 else { throw Problem("Watch expression is too long.") }
|
||||
let chars = Array(text)
|
||||
var i = 0
|
||||
while i < chars.count {
|
||||
let c = chars[i]
|
||||
if c.isWhitespace { i += 1; continue }
|
||||
if c.isASCII && (c.isLetter || c == "_" || c.isNumber) {
|
||||
let begin = i; i += 1
|
||||
while i < chars.count, chars[i].isASCII && (chars[i].isLetter || chars[i].isNumber || chars[i] == "_") { i += 1 }
|
||||
tokens.append(String(chars[begin..<i])); continue
|
||||
}
|
||||
let pair = i + 1 < chars.count ? String(chars[i...i+1]) : ""
|
||||
guard pair != "++", pair != "--" else { throw Problem("Increment and decrement would modify guest data and are not supported.") }
|
||||
if ["->", "==", "!=", "<=", ">=", "&&", "||", "<<", ">>"].contains(pair) { tokens.append(pair); i += 2; continue }
|
||||
guard "()+-*/%&|^~!<>[].".contains(c) else { throw Problem("Only read-only expressions are supported; assignments and function calls are unavailable.") }
|
||||
tokens.append(String(c)); i += 1
|
||||
}
|
||||
guard !tokens.isEmpty, tokens.count <= 128 else { throw Problem("Enter a variable or a short read-only expression.") }
|
||||
}
|
||||
mutating func parse() throws -> Expr {
|
||||
let result = try binary(minimum: 0, depth: 0)
|
||||
guard index == tokens.count else { throw Problem("Unsupported expression syntax. Function calls and assignments are not evaluated.") }
|
||||
return result
|
||||
}
|
||||
func precedence(_ token: String) -> Int? {
|
||||
switch token {
|
||||
case "||": return 0
|
||||
case "&&": return 1
|
||||
case "|": return 2
|
||||
case "^": return 3
|
||||
case "&": return 4
|
||||
case "==", "!=": return 5
|
||||
case "<", "<=", ">", ">=": return 6
|
||||
case "<<", ">>": return 7
|
||||
case "+", "-": return 8
|
||||
case "*", "/", "%": return 9
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
mutating func binary(minimum: Int, depth: Int) throws -> Expr {
|
||||
guard depth <= 32 else { throw Problem("Watch expression is too deeply nested.") }
|
||||
var left = try unary(depth: depth + 1)
|
||||
while index < tokens.count, let p = precedence(tokens[index]), p >= minimum {
|
||||
let operation = tokens[index]; index += 1
|
||||
left = .binary(operation, left, try binary(minimum: p + 1, depth: depth + 1))
|
||||
}
|
||||
return left
|
||||
}
|
||||
mutating func unary(depth: Int) throws -> Expr {
|
||||
guard depth <= 32, index < tokens.count else { throw Problem("Incomplete or overly nested watch expression.") }
|
||||
let token = tokens[index]; index += 1
|
||||
if ["*", "&", "+", "-", "~", "!"].contains(token) { return .unary(token, try unary(depth: depth + 1)) }
|
||||
var result: Expr
|
||||
if token == "(" {
|
||||
result = try binary(minimum: 0, depth: depth + 1); try expect(")")
|
||||
} else if token.first?.isNumber == true {
|
||||
let number: Int64?
|
||||
if token.lowercased().hasPrefix("0x") { number = Int64(token.dropFirst(2), radix: 16) }
|
||||
else { number = Int64(token, radix: 10) }
|
||||
guard let number else { throw Problem("Invalid integer literal.") }; result = .number(number)
|
||||
} else if token.first?.isLetter == true || token.first == "_" { result = .identifier(token) }
|
||||
else { throw Problem("Expected a variable, number or parenthesized expression.") }
|
||||
while index < tokens.count {
|
||||
if tokens[index] == "[" {
|
||||
index += 1; let subscriptValue = try binary(minimum: 0, depth: depth + 1); try expect("]")
|
||||
result = .index(result, subscriptValue)
|
||||
} else if [".", "->"].contains(tokens[index]) {
|
||||
let pointer = tokens[index] == "->"; index += 1
|
||||
guard index < tokens.count, tokens[index].first?.isLetter == true || tokens[index].first == "_" else { throw Problem("Expected a member name.") }
|
||||
result = .member(result, tokens[index], pointer); index += 1
|
||||
} else { break }
|
||||
}
|
||||
return result
|
||||
}
|
||||
mutating func expect(_ token: String) throws {
|
||||
guard index < tokens.count, tokens[index] == token else { throw Problem("Expected ‘\(token)’.") }; index += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
/// Recovery copies only. This store never writes to the project or guest media.
|
||||
/// Each editor session owns one file per project, so two apps cannot overwrite
|
||||
/// one another's drafts. Restore into a new session before discarding an old copy.
|
||||
final class CMOCWorkspaceRecovery: @unchecked Sendable {
|
||||
struct Draft: Codable, Equatable, Sendable {
|
||||
let path: String
|
||||
let text: String
|
||||
let savedText: String
|
||||
let savedHash: String
|
||||
init(path: String, text: String, savedText: String, savedHash: String) {
|
||||
self.path = path; self.text = text; self.savedText = savedText; self.savedHash = savedHash
|
||||
}
|
||||
}
|
||||
struct Record: Identifiable, Sendable {
|
||||
let id: UUID
|
||||
let projectPath: String
|
||||
let modifiedAt: Date
|
||||
let drafts: [Draft]
|
||||
let isFromRunningSession: Bool
|
||||
fileprivate let file: URL
|
||||
fileprivate let digest: String
|
||||
fileprivate let processID: Int32
|
||||
}
|
||||
struct Scan: Sendable {
|
||||
let records: [Record]
|
||||
let issues: [String]
|
||||
}
|
||||
private struct Envelope: Codable {
|
||||
let version: Int
|
||||
let sessionID: UUID
|
||||
let processID: Int32
|
||||
let projectPath: String
|
||||
let modifiedAt: Date
|
||||
let drafts: [Draft]
|
||||
}
|
||||
static let maximumDrafts = 128
|
||||
static let maximumTextBytes = 16 * 1024 * 1024
|
||||
static let maximumRecordBytes = 64 * 1024 * 1024
|
||||
static let maximumScanRecords = 64
|
||||
static let maximumScanTextBytes = 64 * 1024 * 1024
|
||||
let root: URL
|
||||
let sessionID: UUID
|
||||
private let processID: Int32
|
||||
private let canonicalRoot: URL
|
||||
private let lock = NSLock()
|
||||
|
||||
init(root: URL, sessionID: UUID = UUID(), processID: Int32 = getpid()) {
|
||||
self.root = root.standardizedFileURL
|
||||
self.canonicalRoot = root.standardizedFileURL.resolvingSymlinksInPath()
|
||||
self.sessionID = sessionID; self.processID = processID
|
||||
}
|
||||
private func failure(_ message: String) -> CMOCBuildError {
|
||||
.message("Draft recovery: " + message)
|
||||
}
|
||||
private func projectPath(_ directory: URL) -> String {
|
||||
directory.standardizedFileURL.resolvingSymlinksInPath().path
|
||||
}
|
||||
private func kind(_ url: URL) throws -> FileAttributeType? {
|
||||
do { return try FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType }
|
||||
catch let error as NSError where error.domain == NSCocoaErrorDomain && [NSFileReadNoSuchFileError, NSFileNoSuchFileError].contains(error.code) { return nil }
|
||||
}
|
||||
private func folder(for project: String, create: Bool) throws -> URL? {
|
||||
guard root.resolvingSymlinksInPath().path == canonicalRoot.path else { throw failure("The recovery folder location changed. Copies were left untouched.") }
|
||||
if let type = try kind(root) {
|
||||
guard type == .typeDirectory else { throw failure("The recovery folder must be a real directory, not a link.") }
|
||||
} else if create {
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
} else { return nil }
|
||||
let directory = root.appendingPathComponent(CMOCProject.sha256(Data(project.utf8)), isDirectory: true)
|
||||
if let type = try kind(directory) {
|
||||
guard type == .typeDirectory else { throw failure("A project recovery folder is a link or is not a directory.") }
|
||||
} else if create {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
} else { return nil }
|
||||
return directory
|
||||
}
|
||||
private func validate(_ drafts: [Draft]) throws {
|
||||
guard drafts.count <= Self.maximumDrafts,
|
||||
Set(drafts.map { $0.path.lowercased() }).count == drafts.count else {
|
||||
throw failure("Too many drafts or duplicate draft paths. Existing copies were kept.")
|
||||
}
|
||||
var total = 0
|
||||
for draft in drafts {
|
||||
try CMOCProject.validateRelativePath(draft.path)
|
||||
let text = try CMOCProject.sourceBytes(draft.text), saved = try CMOCProject.sourceBytes(draft.savedText)
|
||||
guard CMOCProject.sha256(saved) == draft.savedHash else { throw failure("The saved-file identity for \(draft.path) is inconsistent.") }
|
||||
total += text.count + saved.count
|
||||
guard total <= Self.maximumTextBytes else { throw failure("Drafts exceed the 16 MB recovery limit. Save your edits to the project.") }
|
||||
}
|
||||
}
|
||||
private func read(_ url: URL) throws -> Data {
|
||||
let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW)
|
||||
guard descriptor >= 0 else { throw failure("Cannot safely read \(url.lastPathComponent).") }
|
||||
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var info = stat()
|
||||
guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG,
|
||||
info.st_size >= 0, info.st_size <= Int64(Self.maximumRecordBytes) else {
|
||||
throw failure("\(url.lastPathComponent) is not a bounded regular recovery file.")
|
||||
}
|
||||
let data = try handle.read(upToCount: Self.maximumRecordBytes + 1) ?? Data()
|
||||
guard data.count <= Self.maximumRecordBytes else { throw failure("The recovery file grew beyond its size limit.") }
|
||||
return data
|
||||
}
|
||||
private func alive(_ pid: Int32) -> Bool {
|
||||
guard pid > 0 else { return false }
|
||||
return kill(pid, 0) == 0 || errno == EPERM
|
||||
}
|
||||
private func record(_ file: URL, project: String) throws -> Record {
|
||||
let data = try read(file)
|
||||
let envelope: Envelope
|
||||
do { envelope = try JSONDecoder().decode(Envelope.self, from: data) }
|
||||
catch { throw failure("\(file.lastPathComponent) is damaged or has an unsupported structure. The file was kept.") }
|
||||
guard envelope.version == 1, envelope.processID > 0, envelope.projectPath == project,
|
||||
file.lastPathComponent == envelope.sessionID.uuidString + ".json",
|
||||
envelope.modifiedAt.timeIntervalSince1970.isFinite else {
|
||||
throw failure("\(file.lastPathComponent) has an invalid recovery identity. The file was kept.")
|
||||
}
|
||||
try validate(envelope.drafts)
|
||||
return Record(id: envelope.sessionID, projectPath: project, modifiedAt: envelope.modifiedAt,
|
||||
drafts: envelope.drafts, isFromRunningSession: envelope.sessionID != sessionID && alive(envelope.processID),
|
||||
file: file, digest: CMOCProject.sha256(data), processID: envelope.processID)
|
||||
}
|
||||
func save(projectDirectory: URL, drafts: [Draft]) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
try validate(drafts)
|
||||
let project = projectPath(projectDirectory)
|
||||
guard let directory = try folder(for: project, create: !drafts.isEmpty) else { return }
|
||||
let file = directory.appendingPathComponent(sessionID.uuidString + ".json")
|
||||
if let type = try kind(file), type != .typeRegular { throw failure("The session recovery file is not a regular file. It was kept.") }
|
||||
if drafts.isEmpty {
|
||||
if try kind(file) != nil { try FileManager.default.removeItem(at: file) }
|
||||
return
|
||||
}
|
||||
let envelope = Envelope(version: 1, sessionID: sessionID, processID: processID, projectPath: project,
|
||||
modifiedAt: Date(), drafts: drafts)
|
||||
let data = try JSONEncoder().encode(envelope)
|
||||
guard data.count <= Self.maximumRecordBytes else { throw failure("The encoded recovery copy exceeds its size limit. Existing copies were kept.") }
|
||||
try data.write(to: file, options: .atomic)
|
||||
}
|
||||
func scan(projectDirectory: URL) throws -> Scan {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
let project = projectPath(projectDirectory)
|
||||
guard let directory = try folder(for: project, create: false) else { return Scan(records: [], issues: []) }
|
||||
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
|
||||
guard files.count <= 1024 else { throw failure("Too many recovery files to inspect safely. Copies were left untouched.") }
|
||||
var records: [Record] = [], issues: [String] = []
|
||||
var totalTextBytes = 0
|
||||
for file in files.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) where file.pathExtension == "json" {
|
||||
guard records.count < Self.maximumScanRecords else {
|
||||
issues.append("Draft recovery: More than 64 saved sessions are present. Export or discard reviewed copies, then refresh to inspect the remaining sessions. All copies were kept.")
|
||||
break
|
||||
}
|
||||
do {
|
||||
let recovered = try record(file, project: project)
|
||||
let bytes = recovered.drafts.reduce(0) { $0 + $1.text.utf8.count + $1.savedText.utf8.count }
|
||||
guard totalTextBytes + bytes <= Self.maximumScanTextBytes else {
|
||||
issues.append("Draft recovery: Saved sessions exceed the 64 MB review limit. Export or discard reviewed copies, then refresh to inspect the remaining sessions. All copies were kept.")
|
||||
break
|
||||
}
|
||||
totalTextBytes += bytes; records.append(recovered)
|
||||
} catch { issues.append(error.localizedDescription) }
|
||||
}
|
||||
return Scan(records: records.sorted { $0.modifiedAt > $1.modifiedAt }, issues: issues)
|
||||
}
|
||||
func records(projectDirectory: URL) throws -> [Record] {
|
||||
let result = try scan(projectDirectory: projectDirectory)
|
||||
guard result.issues.isEmpty else { throw failure(result.issues.joined(separator: "\n")) }
|
||||
return result.records
|
||||
}
|
||||
func discard(_ record: Record) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let directory = try folder(for: record.projectPath, create: false),
|
||||
directory.appendingPathComponent(record.id.uuidString + ".json").resolvingSymlinksInPath().path == record.file.resolvingSymlinksInPath().path else {
|
||||
throw failure("The recovery record no longer belongs to this store.")
|
||||
}
|
||||
let current = try self.record(record.file, project: record.projectPath)
|
||||
guard current.digest == record.digest else { throw failure("This recovery copy changed after it was shown. Review it again before discarding.") }
|
||||
guard !current.isFromRunningSession else { throw failure("Another running editor session owns this recovery copy.") }
|
||||
try FileManager.default.removeItem(at: record.file)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
struct CartridgeControlsView: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var expandedSlots = Set<Int>()
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
SecondaryHeader(title: "Cartridges", badge: "mpi")
|
||||
Picker("Cartridge connection", selection: Binding(get: { machine.cartridgeAssignments.multiPak }, set: machine.setMultiPak)) {
|
||||
Text("Single cartridge").tag(false)
|
||||
Text("Multi-Pak").tag(true)
|
||||
}.pickerStyle(.segmented).accessibilityIdentifier("cartridge-connection")
|
||||
Label("Changes restart the CoCo and clear the working program. Floppy and hard disks are retained; SDC mounts return to startup.cfg.", systemImage: "arrow.counterclockwise")
|
||||
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}.padding(20)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
if machine.cartridgeAssignments.multiPak {
|
||||
ForEach(1...4, id: \.self) { slot in row(slot) }
|
||||
} else { row(0) }
|
||||
if !machine.cartridgeRestoreErrors.isEmpty {
|
||||
SecondaryAction(title: "Retry Unavailable Files", systemImage: "arrow.clockwise", action: machine.retryRememberedCartridges)
|
||||
}
|
||||
if let error = machine.diskSettingsError {
|
||||
Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).textSelection(.enabled)
|
||||
if machine.diskSettingsNeedsSave {
|
||||
SecondaryAction(title: "Retry Saving Settings", systemImage: "arrow.clockwise", action: machine.saveDiskAssignments)
|
||||
}
|
||||
}
|
||||
if let error = machine.fileError ?? machine.error {
|
||||
Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).textSelection(.enabled)
|
||||
}
|
||||
SecondaryHelp(title: "About cartridge connections") {
|
||||
Text("The single-cartridge assignment is retained while Multi-Pak is enabled. Each controller or sound device can occupy one Multi-Pak slot; choosing it elsewhere moves it. Software can route ROM and I/O ports independently of the startup slot.")
|
||||
}
|
||||
}.padding(20)
|
||||
}
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
if machine.cartridgeAssignments.multiPak {
|
||||
HStack(spacing: 16) {
|
||||
Text("Startup slot").fontWeight(.medium)
|
||||
Picker("Startup slot", selection: Binding(get: { machine.cartridgeAssignments.physicalSlot }, set: machine.selectPhysicalSlot)) {
|
||||
ForEach(1...4, id: \.self) { Text("Slot \($0)").tag($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 330)
|
||||
.accessibilityIdentifier("cartridge-startup-slot")
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
HStack {
|
||||
Label("Live routing", systemImage: "arrow.triangle.branch")
|
||||
Text("ROM: Slot \(machine.romSlot) · I/O ports: Slot \(machine.ioSlot)").monospacedDigit()
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
.accessibilityIdentifier("cartridge-live-routing")
|
||||
}
|
||||
MediaExecutionFooter(machine: machine, note: "After a change, press Run to continue.")
|
||||
}.padding(20)
|
||||
}.frame(minWidth: 680, minHeight: 440)
|
||||
.disabled(machine.busy || machine.diskSaving || machine.diskBusy || machine.state == .closed)
|
||||
}
|
||||
|
||||
private func row(_ slot: Int) -> some View {
|
||||
let assignment = machine.cartridgeAssignments.slots[slot]
|
||||
return SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack(alignment: .center, spacing: 14) {
|
||||
Text(slot == 0 ? "ROM" : "\(slot)")
|
||||
.font(.system(.body, design: .monospaced).weight(.semibold))
|
||||
.frame(width: 38, height: 38)
|
||||
.background(Color.accentColor.opacity(0.12), in: RoundedRectangle(cornerRadius: 7))
|
||||
.accessibilityLabel(slot == 0 ? "Single cartridge" : "Slot \(slot)")
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(title(assignment.kind)).fontWeight(.semibold)
|
||||
Text(summary(slot)).font(.caption).foregroundStyle(.secondary)
|
||||
.lineLimit(2).truncationMode(.middle)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
deviceMenu(slot)
|
||||
contextualAction(slot)
|
||||
}
|
||||
if let warning = readiness(slot) {
|
||||
Label(warning, systemImage: "exclamationmark.circle")
|
||||
.font(.callout).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if let error = machine.cartridgeRestoreErrors[slot] {
|
||||
Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled)
|
||||
SecondaryAction(title: "Retry Files", systemImage: "arrow.clockwise", action: machine.retryRememberedCartridges)
|
||||
.accessibilityLabel("Retry unavailable files for slot \(slot)")
|
||||
}
|
||||
if assignment.kind != .empty {
|
||||
DisclosureGroup(isExpanded: Binding(get: { expandedSlots.contains(slot) }, set: { value in
|
||||
if value { expandedSlots.insert(slot) } else { expandedSlots.remove(slot) }
|
||||
})) {
|
||||
details(slot).padding(.top, 10)
|
||||
} label: { Label("Details", systemImage: "info.circle").font(.callout).accessibilityLabel("Details for slot \(slot)") }
|
||||
}
|
||||
}
|
||||
}.modifier(MediaDropTarget(machine: machine, destination: .cartridge(slot)))
|
||||
}
|
||||
|
||||
private func title(_ kind: CartridgeAssignments.Kind) -> String {
|
||||
switch kind {
|
||||
case .empty: return "Empty slot"
|
||||
case .rom: return "ROM cartridge"
|
||||
case .floppy: return "Floppy controller (FD-502)"
|
||||
case .hardDisk: return "Hard-disk controller"
|
||||
case .ramDisk: return "RAM disk (512 KB)"
|
||||
case .orchestra90: return "Orchestra-90"
|
||||
case .speechSound: return "Speech/Sound Cartridge"
|
||||
case .sdc: return "CoCo SDC"
|
||||
}
|
||||
}
|
||||
private func summary(_ slot: Int) -> String {
|
||||
let assignment = machine.cartridgeAssignments.slots[slot]
|
||||
switch assignment.kind {
|
||||
case .empty: return "Choose a device or drop a ROM file here"
|
||||
case .rom: return assignment.url?.lastPathComponent ?? "No ROM selected"
|
||||
case .floppy: return "FD0–FD3 · Mounted: \(machine.disks.filter(\.mounted).count)"
|
||||
case .hardDisk: return "HD0–HD1 · Mounted: \(machine.hardDisks.filter(\.mounted).count)"
|
||||
case .ramDisk: return "Volatile storage for supporting software"
|
||||
case .orchestra90: return assignment.url?.lastPathComponent ?? "Stereo sound only · No program ROM"
|
||||
case .sdc: return assignment.sdcFolderURL.map { "SD card: " + $0.lastPathComponent } ?? "Choose an SD card folder and SDC-DOS ROM"
|
||||
case .speechSound:
|
||||
return assignment.url != nil && assignment.speechROMURL != nil ? "Speech and music · Two chip ROMs selected" : "Two internal chip ROMs required"
|
||||
}
|
||||
}
|
||||
private func readiness(_ slot: Int) -> String? {
|
||||
let assignment = machine.cartridgeAssignments.slots[slot]
|
||||
if assignment.kind == .rom && machine.cartridgeNames[slot].isEmpty { return "ROM unavailable — choose a replacement or retry." }
|
||||
if assignment.kind == .floppy && !machine.diskEnabled { return "Choose a disk ROM in Floppy Disks to enable this controller." }
|
||||
if assignment.kind == .sdc && (assignment.url == nil || assignment.sdcFolderURL == nil) {
|
||||
return "Inactive — choose an SDC-DOS ROM and SD card folder in Details."
|
||||
}
|
||||
if assignment.kind == .speechSound && (assignment.url == nil || assignment.speechROMURL == nil) {
|
||||
return "Inactive — choose both ROMs to enable speech and music."
|
||||
}
|
||||
return nil
|
||||
}
|
||||
private func deviceMenu(_ slot: Int) -> some View {
|
||||
let current = machine.cartridgeAssignments.slots[slot].kind
|
||||
return Menu {
|
||||
Button { machine.openCartridgeROM(slot) } label: {
|
||||
Label("ROM Cartridge…", systemImage: current == .rom ? "checkmark" : "folder")
|
||||
}.accessibilityLabel("Choose ROM for slot \(slot)")
|
||||
ForEach([CartridgeAssignments.Kind.floppy, .hardDisk, .ramDisk, .orchestra90, .speechSound, .sdc], id: \.rawValue) { kind in
|
||||
Button { machine.requestCartridge(kind, slot: slot) } label: {
|
||||
Label(menuTitle(kind, slot: slot), systemImage: current == kind ? "checkmark" : symbol(kind))
|
||||
}.disabled(current == kind).accessibilityLabel("Use \(kind == .floppy ? "floppy controller" : kind == .hardDisk ? "hard disk" : kind == .ramDisk ? "RAM disk" : kind == .orchestra90 ? "Orchestra-90" : kind == .sdc ? "CoCo SDC" : "Speech/Sound") in slot \(slot)")
|
||||
}
|
||||
Divider()
|
||||
Button { machine.requestCartridge(.empty, slot: slot) } label: {
|
||||
Label("Remove Cartridge", systemImage: "minus.circle")
|
||||
}.disabled(current == .empty).accessibilityLabel("Remove cartridge from slot \(slot)")
|
||||
} label: { Label("Device", systemImage: "slider.horizontal.3") }
|
||||
.menuStyle(.borderlessButton).fixedSize().padding(.horizontal, 10).padding(.vertical, 6)
|
||||
.background(.quaternary.opacity(0.6), in: RoundedRectangle(cornerRadius: 6))
|
||||
.accessibilityIdentifier("cartridge-device-\(slot)")
|
||||
}
|
||||
private func menuTitle(_ kind: CartridgeAssignments.Kind, slot: Int) -> String {
|
||||
var result = title(kind)
|
||||
if slot > 0, let previous = (1...4).first(where: { $0 != slot && machine.cartridgeAssignments.slots[$0].kind == kind }) {
|
||||
result += " — moves from Slot \(previous)"
|
||||
}
|
||||
return result
|
||||
}
|
||||
private func symbol(_ kind: CartridgeAssignments.Kind) -> String {
|
||||
switch kind {
|
||||
case .floppy, .hardDisk: return "externaldrive"
|
||||
case .ramDisk, .rom, .empty: return "memorychip"
|
||||
case .orchestra90: return "music.note"
|
||||
case .speechSound: return "waveform"
|
||||
case .sdc: return "sdcard"
|
||||
}
|
||||
}
|
||||
@ViewBuilder private func contextualAction(_ slot: Int) -> some View {
|
||||
switch machine.cartridgeAssignments.slots[slot].kind {
|
||||
case .rom:
|
||||
SecondaryAction(title: "Choose ROM…", systemImage: "folder") { machine.openCartridgeROM(slot) }
|
||||
.accessibilityLabel("Choose ROM for slot \(slot)")
|
||||
case .floppy:
|
||||
SecondaryAction(title: "Floppy Disks…", systemImage: "externaldrive") { openWindow(id: "disks") }
|
||||
case .hardDisk:
|
||||
SecondaryAction(title: "Hard Disks…", systemImage: "externaldrive") { openWindow(id: "hard-disks") }
|
||||
case .orchestra90:
|
||||
SecondaryAction(title: "Choose ROM…", systemImage: "folder") { machine.openCartridgeROM(slot, kind: .orchestra90) }
|
||||
.accessibilityLabel("Choose Orchestra-90 ROM for slot \(slot)")
|
||||
case .sdc:
|
||||
SecondaryAction(title: "SD Card…", systemImage: "sdcard") { expandedSlots.insert(slot) }
|
||||
.accessibilityLabel("Show CoCo SDC settings for slot \(slot)")
|
||||
case .speechSound:
|
||||
SecondaryAction(title: "ROMs…", systemImage: "memorychip") { expandedSlots.insert(slot) }
|
||||
.accessibilityLabel("Show Speech/Sound ROMs for slot \(slot)")
|
||||
case .ramDisk, .empty: EmptyView()
|
||||
}
|
||||
}
|
||||
@ViewBuilder private func details(_ slot: Int) -> some View {
|
||||
let assignment = machine.cartridgeAssignments.slots[slot]
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
switch assignment.kind {
|
||||
case .sdc:
|
||||
Text("The selected folder represents an SD card. Choose this cartridge as the startup slot to boot SDC-DOS. Changing the ROM, folder or protection restarts the CoCo.")
|
||||
romRow("SDC-DOS ROM", filename: assignment.url?.lastPathComponent, button: "Choose ROM…", label: "Choose SDC-DOS ROM for slot \(slot)") { machine.openCartridgeROM(slot, kind: .sdc) }
|
||||
romRow("SD card folder", filename: assignment.sdcFolderURL?.path, button: "Choose Folder…", label: "Choose SD card folder for slot \(slot)") { machine.openSDCFolder(slot) }
|
||||
if let folder = assignment.sdcFolderURL {
|
||||
Button { NSWorkspace.shared.activateFileViewerSelecting([folder]) } label: { Label("Show SD Card Folder in Finder", systemImage: "folder") }
|
||||
}
|
||||
Toggle("Protect SD card files (read-only)", isOn: Binding(get: { assignment.sdcReadOnly ?? true }, set: { machine.setSDCReadOnly($0, slot: slot) }))
|
||||
.accessibilityIdentifier("sdc-protected-\(slot)")
|
||||
Text((assignment.sdcReadOnly ?? true) ? "Files are protected from guest writes and file-management commands." : "Guest writes save directly. File-management commands can create, rename or delete files in this folder.")
|
||||
if (machine.cartridgeAssignments.multiPak ? slot > 0 : slot == 0), !machine.cartridgeNames[slot].isEmpty {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text("Current folder: \(machine.sdcDirectory.isEmpty ? "/" : machine.sdcDirectory)").textSelection(.enabled)
|
||||
ForEach(0..<2) { drive in
|
||||
Text("SDC\(drive): \(machine.sdcDriveNames.indices.contains(drive) && !machine.sdcDriveNames[drive].isEmpty ? machine.sdcDriveNames[drive] : "No image mounted")")
|
||||
}
|
||||
Text("Transfers · Read \(machine.sdcReadCount) · Written \(machine.sdcWriteCount)")
|
||||
.monospacedDigit().accessibilityIdentifier("sdc-transfer-counts")
|
||||
if let error = machine.sdcError, !error.isEmpty {
|
||||
Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.orange).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
SecondaryHelp(title: "Using an SD card folder") {
|
||||
Text("Keep extracted collections together with their original filenames and directories. In SDC-DOS, DRIVE 0,\"NAME.DSK\" mounts an image; DIR lists its BASIC files. Follow the software's launch instructions. SDC0–SDC1 are independent of FD0–FD3 and HD0–HD1.")
|
||||
Text("Double Dragon: select the folder containing DDRAGON1.DSK through DDRAGON9.DSK, use 2 MB RAM, then enter DRIVE 0,\"DDRAGON1.DSK\" followed by RUN \"AUTOEXEC:0\". The game selects its later disks. Arrow keys move; Z starts and punches, X kicks, C jumps.")
|
||||
Text("Profiles remember the folder, ROM and protection. Guest-selected mounts and current directory return to startup.cfg on restart. In System view, click the CoCo SDC cartridge or its slot for SD card controls. The transfer light reflects actual reads and writes.")
|
||||
}
|
||||
case .speechSound:
|
||||
Text("Speech and music for supporting programs. This cartridge has no boot program; keep your disk controller as the startup slot.")
|
||||
romRow("PIC firmware", filename: assignment.url?.lastPathComponent, button: "Choose PIC Firmware…", label: "Choose PIC firmware for slot \(slot)") { machine.openSpeechROM(slot, speech: false) }
|
||||
romRow("Speech ROM", filename: assignment.speechROMURL?.lastPathComponent, button: "Choose Speech ROM…", label: "Choose speech ROM for slot \(slot)") { machine.openSpeechROM(slot, speech: true) }
|
||||
Text("Sound, volume and mute use the normal Mac audio controls.")
|
||||
case .orchestra90:
|
||||
Text("Stereo playback works without a ROM in supporting software. The optional 8 KiB ROM adds the music program; choose its startup slot to boot it.")
|
||||
Text(assignment.url.map { "Program ROM: \($0.lastPathComponent)" } ?? "No program ROM — stereo sound only").textSelection(.enabled)
|
||||
if assignment.url != nil {
|
||||
SecondaryAction(title: "Remove ROM…", systemImage: "minus.circle") { machine.requestOrchestraWithoutROM(slot) }
|
||||
.accessibilityLabel("Remove Orchestra-90 ROM from slot \(slot)")
|
||||
}
|
||||
if assignment.url != nil && machine.cartridgeRestoreErrors[slot] == nil {
|
||||
Text("William Tell demo: press a key at startup, then type S and Return to score. Wait for the cursor, then P and Return to play. Escape sends CoCo Break to stop.")
|
||||
}
|
||||
case .ramDisk:
|
||||
Text("Requires RAM-disk-aware software; this is not a Disk BASIC drive. Resets retain data. Loading a profile, quitting, or removing the last RAM-disk assignment discards its contents. Profiles remember the device, not its data. This layout uses conventional controls.")
|
||||
case .floppy:
|
||||
Text("One FD-502 controller provides FD0–FD3. The selected disk ROM and mounted media are managed in Floppy Disks. Moving this controller retains its disks.")
|
||||
case .hardDisk:
|
||||
Text("This controller provides HD0 and HD1 and has no boot ROM. Use a compatible disk ROM or OS-9 boot disk. Moving it retains mounted images.")
|
||||
case .rom:
|
||||
Text("ROM file: \(assignment.url?.path ?? "Not selected")").textSelection(.enabled)
|
||||
Text("Choosing another ROM restarts the CoCo. Removing this assignment does not delete its file.")
|
||||
case .empty: EmptyView()
|
||||
}
|
||||
}.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
private func romRow(_ title: String, filename: String?, button: String, label: String, action: @escaping () -> Void) -> some View {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(title).fontWeight(.medium)
|
||||
Text(filename ?? "Not selected").lineLimit(1).truncationMode(.middle)
|
||||
}
|
||||
Spacer()
|
||||
SecondaryAction(title: button, systemImage: "folder", action: action).accessibilityLabel(label)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import Combine
|
||||
|
||||
struct CassetteControlsView: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
@State private var tapeSeek: Double = 0
|
||||
@State private var seeking = false
|
||||
private let refresh = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
SecondaryHeader(title: "Cassette", badge: "cassette").padding(20)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "recordingtape").font(.system(size: 26)).foregroundStyle(.secondary)
|
||||
.accessibilityHidden(true)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(machine.tapeName).font(.headline).lineLimit(1).truncationMode(.middle)
|
||||
Text(machine.tapeTransportDescription).font(.callout).foregroundStyle(.secondary)
|
||||
.accessibilityIdentifier("cassette-transport-status")
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
SecondaryAction(title: "Insert…", systemImage: "folder", action: machine.openTape)
|
||||
.disabled(machine.tapeDirty).accessibilityIdentifier("cassette-insert")
|
||||
}
|
||||
HStack(spacing: 12) {
|
||||
Spacer(minLength: 0)
|
||||
CassetteTransportButton(title: "Rewind", symbol: "backward.end.fill") { machine.tapeAction(2) }
|
||||
.disabled(!machine.tapeMounted).accessibilityIdentifier("cassette-rewind")
|
||||
CassetteTransportButton(title: "Play", symbol: "play.fill", prominent: machine.tapeMode == 0) { machine.tapeAction(1) }
|
||||
.disabled(!machine.tapeMounted || machine.tapeMode == 2).accessibilityIdentifier("cassette-play")
|
||||
CassetteTransportButton(title: "Stop", symbol: "stop.fill", prominent: machine.tapeMode != 0) { machine.tapeAction(0) }
|
||||
.disabled(!machine.tapeMounted).accessibilityIdentifier("cassette-stop")
|
||||
CassetteTransportButton(title: "Eject", symbol: "eject.fill") { machine.tapeAction(3) }
|
||||
.disabled(!machine.tapeMounted || machine.tapeDirty).accessibilityIdentifier("cassette-eject")
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
VStack(spacing: 4) {
|
||||
Slider(value: $tapeSeek, in: 0...Double(max(1, machine.tapeLength)), onEditingChanged: { editing in
|
||||
seeking = editing
|
||||
if !editing { machine.seekTape(tapeSeek) }
|
||||
}).accessibilityLabel("Tape position").disabled(!machine.tapeMounted || machine.tapeMode == 2)
|
||||
HStack {
|
||||
Text("Tape position")
|
||||
Spacer()
|
||||
Text("\(machine.tapePosition) / \(machine.tapeLength) \(machine.tapeWAV ? "samples" : "bytes")")
|
||||
.monospacedDigit()
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Menu {
|
||||
Button("CAS") { machine.tapeAction(4) }
|
||||
Button("WAV") { machine.tapeAction(5) }
|
||||
} label: { Label("New Recording", systemImage: "record.circle") }
|
||||
.fixedSize().disabled(machine.tapeDirty).accessibilityIdentifier("cassette-new-recording")
|
||||
SecondaryAction(title: "Export Tape…", systemImage: "square.and.arrow.up", action: machine.exportTape)
|
||||
.disabled(!machine.tapeMounted).accessibilityIdentifier("cassette-export")
|
||||
Spacer()
|
||||
Toggle("Fast CAS", isOn: Binding(get: { machine.tapeFast }, set: machine.setFastTape))
|
||||
.disabled(machine.tapeMode != 0)
|
||||
.help("Accelerate supported CAS loads. Change this while the transport is stopped.")
|
||||
}
|
||||
recordingNotice
|
||||
}
|
||||
}.disabled(machine.busy || machine.state == .closed)
|
||||
HStack(spacing: 12) {
|
||||
Label("App sound", systemImage: "speaker.wave.2")
|
||||
Toggle("Sound", isOn: Binding(get: { machine.audioEnabled }, set: machine.setAudio))
|
||||
.labelsHidden().accessibilityLabel("Sound")
|
||||
Slider(value: $machine.volume, in: 0...1, onEditingChanged: { editing in
|
||||
if !editing { machine.setAudio(machine.audioEnabled) }
|
||||
}).frame(maxWidth: 220).accessibilityLabel("Volume")
|
||||
Text(machine.volume == 0 ? "Muted" : "\(Int((machine.volume * 100).rounded()))%")
|
||||
.monospacedDigit().frame(width: 45, alignment: .leading).foregroundStyle(.secondary)
|
||||
Spacer(minLength: 0)
|
||||
Text("All CoCo audio").font(.caption).foregroundStyle(.secondary)
|
||||
}.disabled(machine.busy)
|
||||
SecondaryHelp(title: "Recording and tape options") {
|
||||
Text("New Recording creates an in-memory CAS or WAV tape and replaces the inserted tape. Export writes a Mac file. An unsaved recording must be exported or explicitly discarded before replacement.")
|
||||
Text("Position counts bytes for CAS and samples for WAV. Rewind returns to the beginning; the position slider can seek when transport rules permit. Cue/fast-forward and independent tape pause are not available.")
|
||||
Text("Fast CAS accelerates supported ROM load routines. Volume and Sound affect all emulator audio, including cartridges, not just the tape.")
|
||||
}
|
||||
if let error = machine.fileError ?? machine.error { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||||
}.padding(20)
|
||||
}.modifier(MediaDropTarget(machine: machine, destination: .cassette))
|
||||
Divider()
|
||||
HStack(alignment: .top, spacing: 10) {
|
||||
Image(systemName: "info.circle").foregroundStyle(.secondary)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text("Play readies the tape. The CoCo starts its motor.").font(.callout)
|
||||
Text("Closing this window preserves transport and unsaved recordings.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}.padding(20)
|
||||
}.frame(minWidth: 680, minHeight: 460)
|
||||
.onReceive(refresh) { _ in machine.poll() }
|
||||
.onAppear { tapeSeek = Double(machine.tapePosition) }
|
||||
.onChange(of: machine.tapePosition) { _, position in if !seeking { tapeSeek = Double(position) } }
|
||||
.onChange(of: machine.tapeLength) { _, _ in if !seeking { tapeSeek = Double(machine.tapePosition) } }
|
||||
}
|
||||
|
||||
private var recordingNotice: some View {
|
||||
HStack {
|
||||
Label(machine.tapeDirty || machine.tapeMode == 2 ? "Recording needs export to keep it" : "Recordings are saved only when you export them", systemImage: machine.tapeDirty || machine.tapeMode == 2 ? "exclamationmark.circle" : "info.circle")
|
||||
.foregroundStyle(machine.tapeDirty || machine.tapeMode == 2 ? Color.orange : Color.secondary)
|
||||
.font(.caption).fixedSize(horizontal: false, vertical: true)
|
||||
Spacer(minLength: 8)
|
||||
if machine.tapeDirty || machine.tapeMode == 2 {
|
||||
SecondaryAction(title: "Discard…", systemImage: "minus.circle", action: machine.discardTape)
|
||||
.accessibilityIdentifier("cassette-discard")
|
||||
}
|
||||
}.frame(minHeight: 24).accessibilityIdentifier("cassette-recording-status")
|
||||
}
|
||||
}
|
||||
|
||||
private struct CassetteTransportButton: View {
|
||||
let title: String
|
||||
let symbol: String
|
||||
var prominent = false
|
||||
let action: () -> Void
|
||||
private var label: some View {
|
||||
VStack(spacing: 6) {
|
||||
Image(systemName: symbol).font(.system(size: 19, weight: .medium)).frame(height: 23)
|
||||
Text(title).font(.callout).fontWeight(.medium)
|
||||
}.frame(width: 72, height: 54)
|
||||
}
|
||||
var body: some View {
|
||||
Group {
|
||||
if prominent { Button(action: action) { label }.buttonStyle(.borderedProminent) }
|
||||
else { Button(action: action) { label }.buttonStyle(.bordered) }
|
||||
}.accessibilityLabel(title)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
// Layout reference: keyboardLayout.cpp, copyright 2015 Joseph Forgione.
|
||||
// Matrix positions follow the retained keyboardLayout.cpp. Host key codes are
|
||||
// used for physical CoCo positions and nonprinting keys. Natural/Compact
|
||||
// printable characters follow the current Mac layout, translated to CoCo chords.
|
||||
enum KeyboardMode: String, Codable, CaseIterable {
|
||||
case natural = "Natural", coco = "CoCo", compact = "Compact"
|
||||
}
|
||||
struct CocoKeyboard {
|
||||
var mode: KeyboardMode = .natural { didSet { if mode != oldValue { releaseAll() } } }
|
||||
static let shift = UInt64(1) << 55
|
||||
static let control = UInt64(1) << 52
|
||||
static let alt = UInt64(1) << 51
|
||||
private var held: [UInt16: UInt64] = [:]
|
||||
private var shiftSensitive: Set<UInt16> = []
|
||||
private var shifted = false, controlled = false, option = false
|
||||
var mask: UInt64 {
|
||||
let chords = held.values.reduce(0, |)
|
||||
// Natural punctuation can differ from the Mac's physical Shift state.
|
||||
let shiftAlone = held.isEmpty && shifted ? Self.shift : 0
|
||||
return chords | shiftAlone | (controlled ? Self.control : 0) | (option ? Self.alt : 0)
|
||||
}
|
||||
mutating func modifiers(shift: Bool, control: Bool, alt: Bool) {
|
||||
shifted = shift; controlled = control; option = alt
|
||||
for code in shiftSensitive {
|
||||
if let chord = held[code] { held[code] = (chord & ~Self.shift) | (shift ? Self.shift : 0) }
|
||||
}
|
||||
}
|
||||
mutating func press(code: UInt16, characters: String) {
|
||||
// Ignore host repeat; the guest implements repeat from held keys.
|
||||
guard held[code] == nil else { return }
|
||||
if code == 57 {
|
||||
held[code] = UInt64(1) << 32 | (mode == .coco ? Self.shift : Self.control)
|
||||
return
|
||||
}
|
||||
if mode == .compact && (code == 48 || (code == 50 && !shifted)) {
|
||||
held[code] = UInt64(1) << (code == 48 ? 49 : 50) | (shifted ? Self.shift : 0)
|
||||
shiftSensitive.insert(code); return
|
||||
}
|
||||
if mode == .coco {
|
||||
// Physical US CoCo positions, independent of the host layout.
|
||||
let physical: [UInt16: Int] = [0:1,11:2,8:3,2:4,14:5,3:6,5:7,4:8,
|
||||
34:9,38:10,40:11,37:12,46:13,45:14,31:15,35:16,12:17,15:18,
|
||||
1:19,17:20,32:21,9:22,13:23,7:24,16:25,6:26,49:31,
|
||||
29:32,18:33,19:34,20:35,21:36,23:37,22:38,26:39,28:40,25:41,
|
||||
27:42,41:43,43:44,24:45,47:46,44:47,50:0]
|
||||
if let bit = physical[code] {
|
||||
held[code] = UInt64(1) << bit | (shifted ? Self.shift : 0)
|
||||
shiftSensitive.insert(code); return
|
||||
}
|
||||
}
|
||||
let navigation: [UInt16: UInt64] = [119: UInt64(1) << 30 | Self.shift,
|
||||
83: UInt64(1) << 30 | Self.shift, 117: UInt64(1) << 29 | Self.control,
|
||||
65: UInt64(1) << 29 | Self.control, 114: UInt64(1) << 30 | Self.control,
|
||||
82: UInt64(1) << 30 | Self.control, 116: UInt64(1) << 27 | Self.shift,
|
||||
92: UInt64(1) << 27 | Self.shift, 121: UInt64(1) << 28 | Self.shift,
|
||||
85: UInt64(1) << 28 | Self.shift]
|
||||
if let chord = navigation[code] {
|
||||
held[code] = mode == .coco && (code == 119 || code == 83) ? UInt64(1) << 50 : chord
|
||||
return
|
||||
}
|
||||
let special: [UInt16: Int] = [36: 48, 76: 48, 53: 50, 51: 29,
|
||||
123: 29, 124: 30, 125: 28, 126: 27, 115: 49, 122: 53, 120: 54, 111: 50, 89: 49, 91: 27, 84: 28, 86: 29, 88: 30]
|
||||
if let bit = special[code] {
|
||||
held[code] = UInt64(1) << bit | (shifted ? Self.shift : 0)
|
||||
shiftSensitive.insert(code)
|
||||
} else if let chord = Self.chord(for: characters) {
|
||||
held[code] = chord
|
||||
if let c = characters.utf8.first, (65...90).contains(c) || (97...122).contains(c) {
|
||||
held[code] = (chord & ~Self.shift) | (shifted ? Self.shift : 0)
|
||||
shiftSensitive.insert(code)
|
||||
}
|
||||
}
|
||||
}
|
||||
mutating func release(code: UInt16) { held.removeValue(forKey: code); shiftSensitive.remove(code) }
|
||||
mutating func releaseAll() { held.removeAll(); shiftSensitive.removeAll(); shifted = false; controlled = false; option = false }
|
||||
static func chord(for text: String) -> UInt64? {
|
||||
guard text.utf8.count == 1, let c = text.utf8.first else { return nil }
|
||||
// BASIC defaults to uppercase; physical letters are unshifted unless
|
||||
// the Mac event is uppercase. Shifted letters remain available to games/OS-9.
|
||||
if (65...90).contains(c) { return UInt64(1) << (c - 64) | shift }
|
||||
if (97...122).contains(c) { return UInt64(1) << (c - 96) }
|
||||
if c == 64 { return 1 }
|
||||
if c == 32 { return UInt64(1) << 31 }
|
||||
if (48...55).contains(c) { return UInt64(1) << (32 + c - 48) }
|
||||
if (56...57).contains(c) { return UInt64(1) << (40 + c - 56) }
|
||||
let base = Array(":;,-./".utf8)
|
||||
if let index = base.firstIndex(of: c) { return UInt64(1) << (42 + index) }
|
||||
let shifted = Array("!\"#$%&'()*+<=>?".utf8)
|
||||
let positions = [33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]
|
||||
if let index = shifted.firstIndex(of: c) { return UInt64(1) << positions[index] | shift }
|
||||
// Extended CoCo characters use Control combinations in the natural map.
|
||||
let extended: [UInt8: Int] = [91: 40, 93: 41, 92: 47, 94: 39, 95: 45, 123: 44, 125: 46, 124: 33, 126: 35]
|
||||
if let bit = extended[c] { return UInt64(1) << bit | control }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Clipboard input is translated independently of the selected physical keymap
|
||||
// and joystick bindings. Validate the entire payload before sending any keys.
|
||||
struct CocoPaste {
|
||||
enum Mode { case text, mergeBASIC, newBASIC }
|
||||
struct Failure: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
let chords: [UInt64]
|
||||
init(_ source: String, mode: Mode) throws {
|
||||
guard source.utf8.count <= 65536 else { throw Failure(message: "Paste is limited to 64 KiB of text.") }
|
||||
let normalized = source.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\n\r", with: "\n").replacingOccurrences(of: "\r", with: "\n")
|
||||
.replacingOccurrences(of: "\t", with: " ")
|
||||
var text = normalized
|
||||
if mode != .text {
|
||||
var lines: [String] = []
|
||||
for raw in normalized.split(separator: "\n", omittingEmptySubsequences: false) {
|
||||
let line = raw.trimmingCharacters(in: .whitespaces)
|
||||
if line.isEmpty { continue }
|
||||
let digits = line.prefix(while: { $0 >= "0" && $0 <= "9" })
|
||||
guard let number = Int(digits), number <= 63999 else {
|
||||
throw Failure(message: "Every BASIC line must begin with a line number from 0 to 63999. Paste commands with Paste Text instead.")
|
||||
}
|
||||
guard line.utf8.count <= 249 else {
|
||||
throw Failure(message: "BASIC line \(number) exceeds the safe 249-character paste limit. Shorten it before pasting; nothing has been sent.")
|
||||
}
|
||||
lines.append(line + "\n")
|
||||
}
|
||||
guard !lines.isEmpty else { throw Failure(message: "The clipboard contains no numbered BASIC lines.") }
|
||||
text = (mode == .newBASIC ? "NEW\n" : "") + lines.joined()
|
||||
}
|
||||
var keys: [UInt64] = []
|
||||
for character in text {
|
||||
if character == "\n" { keys.append(UInt64(1) << 48) }
|
||||
else if let chord = CocoKeyboard.chord(for: String(character)) { keys.append(chord) }
|
||||
else { throw Failure(message: "The CoCo keyboard cannot type “\(character)”. Replace that character before pasting; nothing has been sent.") }
|
||||
}
|
||||
guard !keys.isEmpty, keys.count <= 65536 else { throw Failure(message: "Paste must contain 1 to 65536 keystrokes.") }
|
||||
chords = keys
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Darwin
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
/// VCC Plus alone owns catalog loading, install receipts, downloads and caches.
|
||||
/// The transport authenticates its caller before reaching this disk-only API.
|
||||
@MainActor
|
||||
final class CompanionLibraryAuthority {
|
||||
private let model: SoftwareLibraryModel
|
||||
init(model: SoftwareLibraryModel) { self.model = model }
|
||||
|
||||
func handle(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
|
||||
await model.load()
|
||||
// Another native window may already be loading this same model.
|
||||
for _ in 0..<200 where model.loading {
|
||||
try Task.checkCancellation()
|
||||
try await Task.sleep(nanoseconds: 50_000_000)
|
||||
}
|
||||
guard let catalog = model.catalog else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") }
|
||||
let disks = catalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1)
|
||||
func release() throws -> SoftwareLibraryRelease {
|
||||
guard let id = request.releaseID, let value = disks.releases.first(where: { $0.id == id }) else {
|
||||
throw failure("Choose a disk edition from VCC Plus's catalog.")
|
||||
}
|
||||
return value
|
||||
}
|
||||
switch request.operation {
|
||||
case .snapshot:
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .setFavorite:
|
||||
guard let id = request.titleID, let enabled = request.enabled,
|
||||
disks.titles.contains(where: { $0.id == id }) else { throw failure("This disk title is unavailable.") }
|
||||
if model.state.isFavorite(id) != enabled { model.state.toggleFavorite(id) }
|
||||
await model.state.flush()
|
||||
if let message = model.state.saveError { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .setPreferredRelease:
|
||||
let selected = try release()
|
||||
guard request.titleID == selected.titleID else { throw failure("This disk edition does not belong to the selected title.") }
|
||||
model.state.selectRelease(selected.id, for: selected.titleID)
|
||||
await model.state.flush()
|
||||
if let message = model.state.saveError { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .install:
|
||||
let selected = try release()
|
||||
guard model.installingReleaseID == nil || model.installingReleaseID == selected.id else {
|
||||
throw failure("VCC Plus is already installing another title. Let it finish or cancel it there.")
|
||||
}
|
||||
guard !model.launchBusy, !model.hasPendingLaunch else { throw failure("Finish the current VCC Plus library action first.") }
|
||||
if model.installingReleaseID == nil && model.state.installedReleases[selected.id] == nil { model.install(selected) }
|
||||
return try await installStatus(selected, catalog: disks)
|
||||
case .installStatus:
|
||||
return try await installStatus(release(), catalog: disks)
|
||||
case .cancelInstallation:
|
||||
let selected = try release()
|
||||
if model.installingReleaseID == selected.id { model.cancelInstallation() }
|
||||
return .init(snapshot: snapshot(disks), isInstalling: model.installingReleaseID == selected.id)
|
||||
case .removeInstallation:
|
||||
let selected = try release()
|
||||
await model.removeInstallation(selected.id)
|
||||
if let message = model.installationErrors[selected.id] { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .diskMembers, .exportDisk:
|
||||
let selected = try release()
|
||||
let receipt = try await installedReceipt(selected)
|
||||
let candidates = receipt.relativeFiles.filter(Self.diskMember).map { CompanionLibraryDisk(path: $0, mediaType: "disk") }
|
||||
.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
|
||||
guard !candidates.isEmpty else { throw failure("This installation contains no supported floppy disk images.") }
|
||||
if request.operation == .diskMembers { return .init(snapshot: snapshot(disks), receipt: receipt, disks: candidates) }
|
||||
guard let member = request.memberPath, candidates.contains(where: { $0.path == member }) else {
|
||||
throw failure("Choose a disk file from this installation.")
|
||||
}
|
||||
let destination = model.state.directory.appendingPathComponent("CompanionDisks", isDirectory: true)
|
||||
let exported = try await Task.detached(priority: .userInitiated) {
|
||||
try Self.exportDisk(receipt: receipt, member: member, destination: destination)
|
||||
}.value
|
||||
return .init(exportedDiskURL: exported)
|
||||
case .thumbnail, .manual:
|
||||
guard let id = request.assetID,
|
||||
let asset = disks.releases.lazy.flatMap({ release in
|
||||
release.assets + (release.ownedGame == nil ? [] : [release.primaryManualAsset].compactMap { $0 })
|
||||
}).first(where: { $0.id == id }) else {
|
||||
throw failure("This supporting asset is unavailable for the disk library.")
|
||||
}
|
||||
if request.operation == .thumbnail {
|
||||
let data = try await SoftwareLibraryArtworkCache.shared.thumbnail(for: asset, directory: model.artworkDirectory)
|
||||
return .init(assetData: data)
|
||||
}
|
||||
guard asset.isManual else { throw failure("Choose a manual or instructions asset.") }
|
||||
let local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset,
|
||||
directory: model.state.directory.appendingPathComponent("Manuals", isDirectory: true))
|
||||
return .init(assetFileURL: local)
|
||||
}
|
||||
}
|
||||
|
||||
private func failure(_ message: String) -> CompanionLibraryFailure { .init(message: message) }
|
||||
private func snapshot(_ catalog: SoftwareLibraryCatalog) -> CompanionLibrarySnapshot {
|
||||
let titleIDs = Set(catalog.titles.map(\.id)), releaseIDs = Set(catalog.releases.map(\.id))
|
||||
return .init(catalog: catalog,
|
||||
favorites: model.state.favoriteTitleIDs.intersection(titleIDs),
|
||||
preferredReleaseIDs: model.state.preferredReleaseIDs.filter { titleIDs.contains($0.key) && releaseIDs.contains($0.value) },
|
||||
installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) })
|
||||
}
|
||||
private func installedReceipt(_ release: SoftwareLibraryRelease) async throws -> SoftwareLibraryInstallationReceipt {
|
||||
let receipts = try await model.installer.recoverInstallations()
|
||||
guard let receipt = receipts.first(where: { $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 }) else {
|
||||
throw failure("Install this disk edition in VCC Plus first.")
|
||||
}
|
||||
return receipt
|
||||
}
|
||||
private func installStatus(_ release: SoftwareLibraryRelease, catalog: SoftwareLibraryCatalog) async throws -> CompanionLibraryResponse {
|
||||
if let message = model.installationErrors[release.id] { throw failure(message) }
|
||||
let active = model.installingReleaseID == release.id
|
||||
return .init(snapshot: snapshot(catalog), progress: active ? model.installProgress : nil,
|
||||
isInstalling: active)
|
||||
}
|
||||
nonisolated static func diskMember(_ path: String) -> Bool {
|
||||
!path.isEmpty && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":")
|
||||
&& !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
|
||||
&& path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." }
|
||||
&& ["dsk", "os9"].contains((path as NSString).pathExtension.lowercased())
|
||||
}
|
||||
/// Every handoff gets a new writable copy. Verified originals and the
|
||||
/// emulator's working image are never handed to the real CoCo for writing.
|
||||
nonisolated private static func exportDisk(receipt: SoftwareLibraryInstallationReceipt, member: String, destination: URL) throws -> URL {
|
||||
guard diskMember(member), receipt.relativeFiles.contains(member) else { throw CompanionLibraryFailure(message: "Invalid disk member.") }
|
||||
let root = receipt.workingDirectory.standardizedFileURL
|
||||
var source = root
|
||||
for component in member.split(separator: "/") {
|
||||
source.appendPathComponent(String(component))
|
||||
let values = try source.resourceValues(forKeys: [.isSymbolicLinkKey])
|
||||
guard values.isSymbolicLink != true else { throw CompanionLibraryFailure(message: "The disk path contains a symbolic link.") }
|
||||
}
|
||||
guard source.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else {
|
||||
throw CompanionLibraryFailure(message: "The disk path leaves its installation.")
|
||||
}
|
||||
let descriptor = open(source.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard descriptor >= 0 else { throw CompanionLibraryFailure(message: "The installed disk could not be read.") }
|
||||
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var info = stat()
|
||||
guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG,
|
||||
info.st_size > 0, info.st_size <= 16 * 1024 * 1024 else {
|
||||
throw CompanionLibraryFailure(message: "Choose a floppy image within the 16 MiB limit.")
|
||||
}
|
||||
let data = try handle.read(upToCount: 16 * 1024 * 1024 + 1) ?? Data()
|
||||
guard data.count == Int(info.st_size) else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") }
|
||||
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
let folder = destination.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
do {
|
||||
let copy = folder.appendingPathComponent(source.lastPathComponent)
|
||||
try data.write(to: copy, options: .atomic)
|
||||
return copy
|
||||
} catch { try? FileManager.default.removeItem(at: folder); throw error }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,97 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// The companion receives immutable disk-only data, never a database handle.
|
||||
protocol CompanionLibraryAccess: Sendable {
|
||||
func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse
|
||||
}
|
||||
|
||||
struct CompanionLibraryRequest: Codable, Sendable {
|
||||
enum Operation: String, Codable, Sendable {
|
||||
case snapshot, setFavorite, setPreferredRelease, install, installStatus
|
||||
case cancelInstallation, removeInstallation, diskMembers, exportDisk, thumbnail, manual
|
||||
}
|
||||
var operation: Operation
|
||||
var requestID = UUID()
|
||||
var releaseID: String? = nil
|
||||
var titleID: String? = nil
|
||||
var memberPath: String? = nil
|
||||
var assetID: String? = nil
|
||||
var enabled: Bool? = nil
|
||||
// Missing in old clients: do not send project titles to an Archive-only UI.
|
||||
var ownedTitlesVersion: Int? = 1
|
||||
}
|
||||
|
||||
struct CompanionLibraryResponse: Codable, Sendable {
|
||||
var snapshot: CompanionLibrarySnapshot? = nil
|
||||
var progress: SoftwareLibraryInstallProgress? = nil
|
||||
var receipt: SoftwareLibraryInstallationReceipt? = nil
|
||||
var disks: [CompanionLibraryDisk]? = nil
|
||||
var exportedDiskURL: URL? = nil
|
||||
var assetData: Data? = nil
|
||||
var assetFileURL: URL? = nil
|
||||
var isInstalling: Bool = false
|
||||
var errorMessage: String? = nil
|
||||
}
|
||||
|
||||
struct CompanionLibrarySnapshot: Codable, Sendable {
|
||||
let catalog: SoftwareLibraryCatalog
|
||||
let favorites: Set<String>
|
||||
let preferredReleaseIDs: [String: String]
|
||||
let installations: [SoftwareLibraryState.Installation]
|
||||
}
|
||||
|
||||
struct CompanionLibraryDisk: Codable, Identifiable, Equatable, Sendable {
|
||||
let path: String
|
||||
let mediaType: String
|
||||
var id: String { path }
|
||||
}
|
||||
|
||||
struct SoftwareLibraryInstallProgress: Codable, Sendable {
|
||||
enum Stage: String, Codable, Sendable { case downloading, verifying, extracting, preparing, complete }
|
||||
let stage: Stage
|
||||
let receivedBytes: Int64
|
||||
let totalBytes: Int64
|
||||
var fraction: Double? { totalBytes > 0 ? min(1, max(0, Double(receivedBytes) / Double(totalBytes))) : nil }
|
||||
}
|
||||
|
||||
struct SoftwareLibraryInstallationReceipt: Codable, Sendable {
|
||||
let releaseID: String
|
||||
let packageSHA256: String
|
||||
let installedAt: Date
|
||||
let workingDirectory: URL
|
||||
let relativeFiles: [String]
|
||||
}
|
||||
|
||||
struct CompanionLibraryFailure: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
private struct CompanionLibraryAccessKey: EnvironmentKey {
|
||||
static let defaultValue: (any CompanionLibraryAccess)? = nil
|
||||
}
|
||||
extension EnvironmentValues {
|
||||
var companionLibraryAccess: (any CompanionLibraryAccess)? {
|
||||
get { self[CompanionLibraryAccessKey.self] }
|
||||
set { self[CompanionLibraryAccessKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
extension SoftwareLibraryCatalog {
|
||||
/// Filter both releases and their containing title: alternate cartridge/tape
|
||||
/// editions never leak through the edition picker in a disk-only client.
|
||||
var companionDisksOnly: Self {
|
||||
companionDisks(includingOwnedTitles: true)
|
||||
}
|
||||
func companionDisks(includingOwnedTitles: Bool) -> Self {
|
||||
Self(titles: titles.compactMap { title in
|
||||
let releases = title.releases.filter {
|
||||
$0.mediaType == "disk" && (includingOwnedTitles || $0.metadata["owned_game"] == .null)
|
||||
}
|
||||
return releases.isEmpty ? nil : SoftwareLibraryTitle(id: title.id, name: title.name,
|
||||
identityStatus: title.identityStatus, releases: releases)
|
||||
}, metadata: metadata)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
enum ProfileFailure: LocalizedError {
|
||||
case message(String)
|
||||
var errorDescription: String? { if case .message(let text) = self { return text }; return nil }
|
||||
}
|
||||
|
||||
// Profiles contain configuration and local file references only, never ROM,
|
||||
// disk, tape, RAM, or execution-state bytes. Version changes require migration.
|
||||
struct ConfigurationProfile: Codable, Equatable, Identifiable {
|
||||
var version = 1
|
||||
var id = UUID()
|
||||
var name: String
|
||||
var machine = MachineSettings()
|
||||
var videoOutput = 1
|
||||
var sound = true
|
||||
var volume = 0.5
|
||||
var systemROM: URL?
|
||||
var media = DiskAssignments()
|
||||
var input = InputSettings()
|
||||
var cassette: URL?
|
||||
var fastCassette = false
|
||||
var bootNitros9: Bool? // Missing in older profiles means ordinary BASIC startup.
|
||||
|
||||
enum Reference: Hashable {
|
||||
case systemROM, floppyROM, cartridge(Int), speechROM(Int), sdcFolder(Int), floppy(Int), hardDisk(Int), cassette
|
||||
var label: String {
|
||||
switch self {
|
||||
case .systemROM: return "System ROM"
|
||||
case .floppyROM: return "Floppy ROM"
|
||||
case .sdcFolder(let slot): return "SD card folder — \(slot == 0 ? "single cartridge" : "Multi-Pak slot \(slot)")"
|
||||
case .speechROM(let slot): return "Speech ROM — \(slot == 0 ? "single cartridge" : "Multi-Pak slot \(slot)")"
|
||||
case .cartridge(let slot): return slot == 0 ? "Single cartridge" : "Multi-Pak slot \(slot)"
|
||||
case .floppy(let drive): return "Floppy drive \(drive)"
|
||||
case .hardDisk(let drive): return "Hard disk \(drive)"
|
||||
case .cassette: return "Cassette"
|
||||
}
|
||||
}
|
||||
}
|
||||
var references: [(key: Reference, url: URL)] {
|
||||
var result: [(Reference, URL)] = []
|
||||
if let systemROM { result.append((.systemROM, systemROM)) }
|
||||
if let url = media.rom { result.append((.floppyROM, url)) }
|
||||
for (i, slot) in (media.cartridges?.slots ?? []).enumerated() {
|
||||
if let url = slot.url { result.append((.cartridge(i), url)) }
|
||||
if let url = slot.speechROMURL { result.append((.speechROM(i), url)) }
|
||||
if let url = slot.sdcFolderURL { result.append((.sdcFolder(i), url)) }
|
||||
}
|
||||
for (i, drive) in media.drives.enumerated() { if let drive { result.append((.floppy(i), drive.url)) } }
|
||||
for (i, drive) in (media.hardDisks?.drives ?? []).enumerated() { if let drive { result.append((.hardDisk(i), drive.url)) } }
|
||||
if let cassette { result.append((.cassette, cassette)) }
|
||||
return result
|
||||
}
|
||||
mutating func replace(_ reference: Reference, with url: URL) {
|
||||
switch reference {
|
||||
case .systemROM: systemROM = url
|
||||
case .floppyROM: media.rom = url
|
||||
case .cartridge(let i): media.cartridges?.slots[i].url = url
|
||||
case .speechROM(let i): media.cartridges?.slots[i].speechROMURL = url
|
||||
case .sdcFolder(let i): media.cartridges?.slots[i].sdcFolderURL = url
|
||||
case .floppy(let i): media.drives[i]?.url = url
|
||||
case .hardDisk(let i): media.hardDisks?.drives[i]?.url = url
|
||||
case .cassette: cassette = url
|
||||
}
|
||||
}
|
||||
func validate() throws {
|
||||
guard version == 1, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, name.count <= 100,
|
||||
!name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }),
|
||||
machine.valid, (0...2).contains(videoOutput), volume.isFinite, (0...1).contains(volume) else {
|
||||
throw ProfileFailure.message("Invalid profile settings or unsupported profile version.")
|
||||
}
|
||||
try media.validate(); _ = try input.validated()
|
||||
guard references.allSatisfy({ _, url in
|
||||
url.isFileURL && url.path.hasPrefix("/") && url.path.count <= 8192 &&
|
||||
(url.host == nil || url.host == "" || url.host == "localhost") && url.query == nil && url.fragment == nil
|
||||
}) else { throw ProfileFailure.message("Profiles must reference local files. Choose replacement files on this Mac.") }
|
||||
}
|
||||
}
|
||||
|
||||
struct ProfileStore {
|
||||
static let maxBytes = 65536
|
||||
let directory: URL
|
||||
static let standard = Self(directory: AppIdentity.supportDirectory.appendingPathComponent("Profiles", isDirectory: true))
|
||||
func file(_ id: UUID) -> URL { directory.appendingPathComponent(id.uuidString).appendingPathExtension("vccprofile") }
|
||||
static func read(_ url: URL) throws -> ConfigurationProfile {
|
||||
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
||||
let data = try handle.read(upToCount: maxBytes + 1) ?? Data()
|
||||
guard data.count <= maxBytes else { throw ProfileFailure.message("The profile exceeds 64 KB.") }
|
||||
let profile = try JSONDecoder().decode(ConfigurationProfile.self, from: data)
|
||||
try profile.validate(); return profile
|
||||
}
|
||||
static func write(_ profile: ConfigurationProfile, to url: URL) throws {
|
||||
try profile.validate()
|
||||
let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
let data = try encoder.encode(profile)
|
||||
guard data.count <= maxBytes else { throw ProfileFailure.message("The profile exceeds 64 KB.") }
|
||||
try data.write(to: url, options: .atomic)
|
||||
}
|
||||
func load() throws -> [ConfigurationProfile] {
|
||||
guard FileManager.default.fileExists(atPath: directory.path) else { return [] }
|
||||
let urls = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
|
||||
.filter { $0.pathExtension == "vccprofile" }
|
||||
guard urls.count <= 128 else { throw ProfileFailure.message("The profile library supports up to 128 profiles.") }
|
||||
return try urls.map { url in
|
||||
let value = try Self.read(url)
|
||||
guard url.lastPathComponent == file(value.id).lastPathComponent else {
|
||||
throw ProfileFailure.message("A profile's identifier does not match its library filename: \(url.lastPathComponent)")
|
||||
}
|
||||
return value
|
||||
}.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
|
||||
}
|
||||
func save(_ value: ConfigurationProfile) throws {
|
||||
try value.validate()
|
||||
let existing = try load()
|
||||
guard !existing.contains(where: { $0.id != value.id && $0.name.caseInsensitiveCompare(value.name) == .orderedSame }) else {
|
||||
throw ProfileFailure.message("A profile with that name already exists. Choose another name or update the existing profile.")
|
||||
}
|
||||
guard existing.count < 128 || existing.contains(where: { $0.id == value.id }) else {
|
||||
throw ProfileFailure.message("The profile library supports up to 128 profiles.")
|
||||
}
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try Self.write(value, to: file(value.id))
|
||||
}
|
||||
func delete(_ id: UUID) throws { try FileManager.default.removeItem(at: file(id)) }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class ProfileLibrary: ObservableObject {
|
||||
@Published private(set) var profiles: [ConfigurationProfile] = []
|
||||
@Published var error: String?
|
||||
private let store: ProfileStore
|
||||
init(store: ProfileStore = .standard) { self.store = store; reload() }
|
||||
func reload() { do { profiles = try store.load(); error = nil } catch { self.error = error.localizedDescription } }
|
||||
@discardableResult func save(_ profile: ConfigurationProfile) -> Bool {
|
||||
do { try store.save(profile); reload(); return error == nil }
|
||||
catch { self.error = error.localizedDescription; return false }
|
||||
}
|
||||
func delete(_ id: UUID) { do { try store.delete(id); reload() } catch { self.error = error.localizedDescription } }
|
||||
}
|
||||
|
||||
struct PreparedProfile {
|
||||
let profile: ConfigurationProfile
|
||||
var systemROM: Data?
|
||||
var diskROM: Data?
|
||||
var cartridges = Array(repeating: Data(), count: 5)
|
||||
var floppies: [DiskFiles.Image?] = Array(repeating: nil, count: 4)
|
||||
var hardDisks: [HardDiskFiles.Image?] = Array(repeating: nil, count: 2)
|
||||
var cassette: Data?
|
||||
static func read(_ profile: ConfigurationProfile) throws -> Self {
|
||||
try profile.validate()
|
||||
var result = Self(profile: profile)
|
||||
var failures: [String] = []
|
||||
for (key, url) in profile.references {
|
||||
do {
|
||||
switch key {
|
||||
case .systemROM: result.systemROM = try ROMImage.read(url)
|
||||
case .floppyROM: result.diskROM = try DiskFiles.readROM(url)
|
||||
case .cartridge(let i):
|
||||
result.cartridges[i] = try DiskFiles.readCartridgeAssignment(profile.media.cartridges!.slots[i])
|
||||
case .sdcFolder:
|
||||
try DiskFiles.validateSDCFolder(url)
|
||||
case .speechROM(let i):
|
||||
result.cartridges[i] = try DiskFiles.readCartridgeAssignment(profile.media.cartridges!.slots[i])
|
||||
case .floppy(let i):
|
||||
let image = try DiskFiles.readImage(url)
|
||||
guard !image.data.isEmpty else { throw ProfileFailure.message("The floppy image is empty.") }
|
||||
result.floppies[i] = image
|
||||
case .hardDisk(let i): result.hardDisks[i] = try HardDiskFiles.readImage(url)
|
||||
case .cassette: result.cassette = try TapeImage.read(url)
|
||||
}
|
||||
} catch { failures.append("\(key.label): \(url.path)\n\(error.localizedDescription)") }
|
||||
}
|
||||
guard failures.isEmpty else { throw ProfileFailure.message("Profile files need attention. Use Replace… to select their locations.\n\n" + failures.joined(separator: "\n\n")) }
|
||||
return result
|
||||
}
|
||||
func request() -> VCCMachineProfile {
|
||||
let request = VCCMachineProfile(), p = profile, layout = p.media.cartridges ?? CartridgeAssignments()
|
||||
let hard = p.media.hardDisks ?? HardDiskAssignments()
|
||||
request.use6309 = p.machine.use6309; request.ram = p.machine.ram; request.overclock = p.machine.overclock
|
||||
request.frameInterval = p.machine.frameInterval; request.fastForward = p.machine.fastForward
|
||||
request.videoOutput = p.videoOutput; request.sound = p.sound; request.volume = Float(p.volume)
|
||||
request.systemROM = systemROM; request.diskROM = diskROM; request.diskROMName = p.media.rom?.lastPathComponent ?? ""
|
||||
request.multiPak = layout.multiPak; request.physicalSlot = layout.physicalSlot
|
||||
request.kinds = layout.slots.map { NSNumber(value: $0.kind.rawValue) }; request.cartridgeROMs = cartridges
|
||||
request.cartridgeNames = layout.slots.map { $0.url?.lastPathComponent ?? "" }
|
||||
request.sdcFolders = layout.slots.map { $0.sdcFolderURL?.path ?? "" }
|
||||
request.sdcReadOnly = layout.slots.map { NSNumber(value: $0.sdcReadOnly ?? true) }
|
||||
request.images = floppies.map { $0?.data ?? Data() } + hardDisks.map { $0?.data ?? Data() }
|
||||
request.imageNames = (p.media.drives + hard.drives).map { $0?.url.lastPathComponent ?? "" }
|
||||
request.readOnly = floppies.map { NSNumber(value: $0?.readOnly ?? false) } + hardDisks.map { NSNumber(value: $0?.readOnly ?? false) }
|
||||
request.protectedImages = (p.media.drives + hard.drives).map { NSNumber(value: $0?.writeProtected ?? false) }
|
||||
request.clockEnabled = hard.clockEnabled; request.clockReadOnly = hard.clockReadOnly
|
||||
request.cassette = cassette; request.cassetteWAV = p.cassette?.pathExtension.lowercased() == "wav"
|
||||
request.fastCassette = p.fastCassette
|
||||
return request
|
||||
}
|
||||
}
|
||||
|
||||
// A derived, read-only companion to v1 profiles, not unversioned file metadata.
|
||||
// It describes connected hardware; it never promises an arbitrary image boots.
|
||||
struct ProfileGuidance {
|
||||
let title: String
|
||||
let coverage: String
|
||||
let explanation: String
|
||||
init(_ profile: ConfigurationProfile) {
|
||||
let layout = profile.media.cartridges ?? CartridgeAssignments()
|
||||
let slots = layout.multiPak ? Array(layout.slots.dropFirst()) : [layout.slots[0]]
|
||||
let floppy = slots.contains { $0.kind == .floppy }
|
||||
let hard = slots.contains { $0.kind == .hardDisk }
|
||||
let rom = slots.contains { $0.kind == .rom }
|
||||
let orchestra = slots.contains { $0.kind == .orchestra90 }
|
||||
let ramDisk = slots.contains { $0.kind == .ramDisk }
|
||||
let sdc = slots.contains { $0.kind == .sdc }
|
||||
coverage = ramDisk ? "Custom configuration: conventional controls for RAM disk" : layout.multiPak ? "System view: Multi-Pak layout" : slots[0].kind == .empty ? "System view: computer, cassette and input" : "Custom configuration: conventional display for direct-connected hardware"
|
||||
if sdc {
|
||||
title = "CoCo SDC"
|
||||
explanation = "The selected Mac folder represents an SD card. SDC-DOS lets supporting software browse and mount images from it. Select the SDC startup slot, then use DRIVE 0,\"NAME.DSK\" to mount an image. Read-only protection is on by default; when disabled, guest writes and file-management commands change files in that folder. Profiles remember the folder and ROM, not mounted-image or program state."
|
||||
} else if ramDisk {
|
||||
title = "Volatile RAM disk"
|
||||
explanation = "The 512 KB RAM disk needs supporting software, not a boot ROM. It is not a Disk BASIC drive. Resets retain its contents; loading a profile, quitting, or removing its last assignment discards them. Profiles remember the assignment only. Existing floppy and hard-disk media remain separate."
|
||||
} else if slots.contains(where: { $0.kind == .speechSound }) {
|
||||
title = "Speech/Sound Cartridge"
|
||||
explanation = "Supporting CoCo programs send speech and music commands to this cartridge. It needs both internal chip ROMs, but has no boot program; leave your disk controller as the startup slot. Sound and volume use the normal Mac controls. Profiles retain the ROM locations, not playback state."
|
||||
} else if orchestra {
|
||||
title = "Orchestra-90 stereo sound"
|
||||
explanation = "Supporting software can play stereo through Orchestra-90 without a ROM. An optional 8 KiB ROM adds its music program; select that slot as the startup slot to boot it. Sound and volume use the normal Mac audio controls. The ROM location is remembered, but profiles do not save music or playback state."
|
||||
} else if hard {
|
||||
title = "Expanded storage"
|
||||
explanation = "The floppy and virtual hard-disk controllers are separate devices. A compatible disk ROM or OS-9 boot disk is needed; attaching a VHD does not boot it."
|
||||
} else if floppy {
|
||||
title = "Floppy software"
|
||||
explanation = "The FD-502-based controller serves FD0–FD3. With a compatible Disk BASIC ROM, DIR lists the selected disk. Follow that software's loading or boot instructions; insertion alone does not run it."
|
||||
} else if rom {
|
||||
title = "Cartridge software"
|
||||
explanation = "The cartridge is program ROM, not a disk image. In Multi-Pak mode, the startup slot chooses the initial cartridge; software can change live routing. Loading this profile restarts and leaves the machine paused."
|
||||
} else {
|
||||
title = "BASIC and cassette"
|
||||
explanation = "Choose a compatible system ROM, then Run. For tape loading, Play prepares the recorder and CLOAD in BASIC starts the computer-controlled transfer. After recording with CSAVE, export the tape to keep its file."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import GameController
|
||||
import IOKit.hid
|
||||
|
||||
struct ControllerReading: Identifiable, Equatable {
|
||||
let id: String, name: String
|
||||
var x = 0.0, y = 0.0, rx = 0.0, ry = 0.0
|
||||
var buttons: UInt32 = 0
|
||||
func sample(_ settings: PortSettings) -> JoystickSample {
|
||||
JoystickSample(x: JoystickSample.axis(settings.rightStick ? rx : x, deadZone: settings.deadZone),
|
||||
y: JoystickSample.axis(settings.rightStick ? ry : y, deadZone: settings.deadZone),
|
||||
buttons: (buttons & (1 << (settings.fire1 - 1)) != 0 ? 1 : 0)
|
||||
| (buttons & (1 << (settings.fire2 - 1)) != 0 ? 2 : 0))
|
||||
}
|
||||
}
|
||||
|
||||
// GameController handles macOS-supported pads (including PlayStation/Xbox).
|
||||
// Native HID covers standard USB joysticks/gamepads such as the F310 in D mode.
|
||||
// Never seize devices, match keyboards/mice, or install a system driver.
|
||||
@MainActor
|
||||
final class ControllerDevices {
|
||||
private let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone))
|
||||
private var devices: [IOHIDDevice] = []
|
||||
private var elements: [String: [IOHIDElement]] = [:]
|
||||
private var controllerIDs: [ObjectIdentifier: (base: String, ordinal: Int)] = [:]
|
||||
private var nextRefresh = Date.distantPast
|
||||
init() {
|
||||
let matches = [4, 5].map { [kIOHIDDeviceUsagePageKey: 1, kIOHIDDeviceUsageKey: $0] }
|
||||
IOHIDManagerSetDeviceMatchingMultiple(manager, matches as CFArray)
|
||||
IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
||||
IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone))
|
||||
GCController.shouldMonitorBackgroundEvents = false
|
||||
}
|
||||
deinit {
|
||||
IOHIDManagerUnscheduleFromRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
||||
IOHIDManagerClose(manager, IOOptionBits(kIOHIDOptionsTypeNone))
|
||||
}
|
||||
private func property(_ device: IOHIDDevice, _ key: String) -> String {
|
||||
IOHIDDeviceGetProperty(device, key as CFString).map { String(describing: $0) } ?? ""
|
||||
}
|
||||
private func identity(_ device: IOHIDDevice) -> String {
|
||||
let serial = property(device, kIOHIDSerialNumberKey)
|
||||
return "hid:\(property(device, kIOHIDVendorIDKey)):\(property(device, kIOHIDProductIDKey)):\(serial.isEmpty ? property(device, kIOHIDLocationIDKey) : serial)"
|
||||
}
|
||||
func read() -> [ControllerReading] {
|
||||
if Date() >= nextRefresh {
|
||||
devices = (IOHIDManagerCopyDevices(manager) as? Set<IOHIDDevice> ?? []).filter { !GCController.supportsHIDDevice($0) }
|
||||
elements.removeAll()
|
||||
for device in devices {
|
||||
elements[identity(device)] = IOHIDDeviceCopyMatchingElements(device, nil, 0) as? [IOHIDElement] ?? []
|
||||
}
|
||||
nextRefresh = Date().addingTimeInterval(0.5)
|
||||
}
|
||||
var readings: [ControllerReading] = []
|
||||
let controllers = GCController.controllers()
|
||||
let connected = Set(controllers.map(ObjectIdentifier.init))
|
||||
controllerIDs = controllerIDs.filter { connected.contains($0.key) }
|
||||
for controller in controllers {
|
||||
guard let pad = controller.extendedGamepad else { continue }
|
||||
let name = controller.vendorName ?? "Game controller"
|
||||
let base = "gc:\(name):\(controller.productCategory)"
|
||||
let identity = ObjectIdentifier(controller)
|
||||
if controllerIDs[identity] == nil {
|
||||
let used = Set(controllerIDs.values.filter { $0.base == base }.map(\.ordinal))
|
||||
var ordinal = 0
|
||||
while used.contains(ordinal) { ordinal += 1 }
|
||||
controllerIDs[identity] = (base, ordinal)
|
||||
}
|
||||
let ordinal = controllerIDs[identity]!.ordinal
|
||||
var value = ControllerReading(id: "\(base):\(ordinal)", name: name + (ordinal == 0 ? "" : " \(ordinal + 1)"))
|
||||
let direction = pad.dpad.xAxis.value != 0 || pad.dpad.yAxis.value != 0 ? pad.dpad : pad.leftThumbstick
|
||||
value.x = Double(direction.xAxis.value); value.y = -Double(direction.yAxis.value)
|
||||
value.rx = Double(pad.rightThumbstick.xAxis.value); value.ry = -Double(pad.rightThumbstick.yAxis.value)
|
||||
let buttons: [GCControllerButtonInput?] = [pad.buttonA,pad.buttonB,pad.buttonX,pad.buttonY,
|
||||
pad.leftShoulder,pad.rightShoulder,pad.leftTrigger,pad.rightTrigger,
|
||||
pad.buttonOptions,pad.buttonMenu,pad.leftThumbstickButton,pad.rightThumbstickButton]
|
||||
for (index, button) in buttons.enumerated() where button?.isPressed == true { value.buttons |= 1 << index }
|
||||
readings.append(value)
|
||||
}
|
||||
for device in devices {
|
||||
var value = ControllerReading(id: identity(device), name: property(device, kIOHIDProductKey))
|
||||
var hasValue = false
|
||||
var hat: Int?
|
||||
var axes: [UInt32: Double] = [:]
|
||||
for element in elements[value.id] ?? [] {
|
||||
let type = IOHIDElementGetType(element)
|
||||
guard (1...3).contains(type.rawValue) else { continue }
|
||||
let page = IOHIDElementGetUsagePage(element), usage = IOHIDElementGetUsage(element)
|
||||
guard page == 1 || page == 9 else { continue }
|
||||
let raw: IOHIDValue? = withUnsafeTemporaryAllocation(of: Unmanaged<IOHIDValue>.self, capacity: 1) { buffer in
|
||||
guard IOHIDDeviceGetValue(device, element, buffer.baseAddress!) == kIOReturnSuccess else { return nil }
|
||||
return buffer[0].takeUnretainedValue()
|
||||
}
|
||||
guard let raw else { continue }
|
||||
hasValue = true
|
||||
let integer = IOHIDValueGetIntegerValue(raw)
|
||||
if page == 9, (1...16).contains(usage), integer != 0 { value.buttons |= 1 << (usage - 1) }
|
||||
if page == 1 {
|
||||
let low = IOHIDElementGetLogicalMin(element), high = IOHIDElementGetLogicalMax(element)
|
||||
guard high > low else { continue }
|
||||
let normalized = min(1, max(-1, 2 * Double(integer - low) / Double(high - low) - 1))
|
||||
switch usage {
|
||||
case 0x30...0x35: axes[usage] = normalized
|
||||
case 0x39: if (low...high).contains(integer), high - low == 7 { hat = integer - low }
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
value.x = axes[0x30] ?? 0; value.y = axes[0x31] ?? 0
|
||||
value.rx = axes[0x33] ?? axes[0x32] ?? 0; value.ry = axes[0x34] ?? axes[0x35] ?? 0
|
||||
if let hat {
|
||||
value.x = [1,2,3].contains(hat) ? 1 : ([5,6,7].contains(hat) ? -1 : 0)
|
||||
value.y = [7,0,1].contains(hat) ? -1 : ([3,4,5].contains(hat) ? 1 : 0)
|
||||
}
|
||||
// A removed device may remain in our half-second inventory cache.
|
||||
if hasValue { readings.append(value) }
|
||||
}
|
||||
return readings.sorted { $0.id < $1.id }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Immutable LWASM listing. Source filenames are descriptive metadata only;
|
||||
/// importing a listing never opens those paths or loads its bytes into the CPU.
|
||||
struct DebugSourceListing: Sendable {
|
||||
struct Line: Identifiable, Sendable {
|
||||
let id: Int
|
||||
let text: String
|
||||
let sourceFile: String?
|
||||
let sourceLine: Int?
|
||||
let address: UInt16?
|
||||
let bytes: [UInt8]
|
||||
var location: String {
|
||||
guard let sourceLine else { return "Listing line \(id + 1)" }
|
||||
return "\(sourceFile ?? "Source"):\(sourceLine)"
|
||||
}
|
||||
}
|
||||
enum ImportError: LocalizedError {
|
||||
case tooLarge, encoding, format, notFile, relocatable
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .tooLarge: return "Use a listing smaller than 8 MB, with at most 50,000 lines and 4,096 characters per line."
|
||||
case .encoding: return "The listing must be UTF-8 or BOM-marked UTF-16 text."
|
||||
case .format: return "No addressed LWASM byte lines were found. Generate a listing with LWASM --list and use final logical CPU addresses."
|
||||
case .notFile: return "Choose a regular listing file."
|
||||
case .relocatable: return "This listing uses relocatable sections. Its addresses need a linker map before they can match CPU addresses. Open a final absolute LWASM listing; CMOC/link-map integration is planned separately."
|
||||
}
|
||||
}
|
||||
}
|
||||
static let maximumBytes = 8 * 1024 * 1024
|
||||
let name: String
|
||||
let lines: [Line]
|
||||
let byAddress: [UInt16: [Int]]
|
||||
var addressedLineCount: Int { byAddress.values.reduce(0) { $0 + $1.count } }
|
||||
|
||||
static func read(_ url: URL) throws -> Self {
|
||||
let access = url.startAccessingSecurityScopedResource()
|
||||
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
||||
guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw ImportError.notFile }
|
||||
let file = try FileHandle(forReadingFrom: url)
|
||||
defer { try? file.close() }
|
||||
let data = try file.read(upToCount: maximumBytes + 1) ?? Data()
|
||||
return try parse(data, name: url.lastPathComponent)
|
||||
}
|
||||
|
||||
static func parse(_ data: Data, name: String) throws -> Self {
|
||||
guard data.count <= maximumBytes else { throw ImportError.tooLarge }
|
||||
let encoding: String.Encoding = data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) ? .utf16 : .utf8
|
||||
guard var text = String(data: data, encoding: encoding), !text.contains("\0") else { throw ImportError.encoding }
|
||||
if text.hasPrefix("\u{feff}") { text.removeFirst() }
|
||||
text = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
|
||||
let rawLines = text.split(separator: "\n", omittingEmptySubsequences: false)
|
||||
guard rawLines.count <= 50_000 else { throw ImportError.tooLarge }
|
||||
// LWASM list.c: address/marker + 16 byte digits + space, followed by
|
||||
// (17-column filename):line or --list-nofiles' decimal line number.
|
||||
// Cycle-count columns stay in the displayed text, without interpretation.
|
||||
let metadata = try NSRegularExpression(pattern: #"^(?:\((.{0,17})\):([0-9]{5,})|([0-9]{5,})) (.*)$"#)
|
||||
let section = try NSRegularExpression(pattern: #"(?i)^\s*(?:[a-z_.$@?][a-z0-9_.$@?]*\s+)?(?:section|endsection)\b"#)
|
||||
var lines: [Line] = []
|
||||
var addresses: [UInt16: [Int]] = [:]
|
||||
for (index, raw) in rawLines.enumerated() {
|
||||
guard raw.count <= 4096 else { throw ImportError.tooLarge }
|
||||
let string = String(raw), octets = Array(string.utf8)
|
||||
var sourceFile: String?, sourceLine: Int?, address: UInt16?
|
||||
var sourceText = string, bytes: [UInt8] = []
|
||||
if octets.count >= 22, octets[21] == 32 {
|
||||
let remainder = String(decoding: octets.dropFirst(22), as: UTF8.self)
|
||||
let ns = remainder as NSString
|
||||
if let match = metadata.firstMatch(in: remainder, range: NSRange(location: 0, length: ns.length)) {
|
||||
func group(_ i: Int) -> String? { match.range(at: i).location == NSNotFound ? nil : ns.substring(with: match.range(at: i)) }
|
||||
sourceFile = group(1)?.trimmingCharacters(in: .whitespaces)
|
||||
sourceLine = (group(2) ?? group(3)).flatMap(Int.init)
|
||||
sourceText = group(4) ?? ""
|
||||
if section.firstMatch(in: sourceText, range: NSRange(sourceText.startIndex..., in: sourceText)) != nil {
|
||||
throw ImportError.relocatable
|
||||
}
|
||||
let digits = String(decoding: octets[5..<21], as: UTF8.self).trimmingCharacters(in: .whitespaces)
|
||||
// A space denotes a logical address. '.' (OS-9 data) and
|
||||
// 's' (structure offset) are not CPU-code associations.
|
||||
if octets[4] == 32, digits.count > 0, digits.count % 2 == 0,
|
||||
digits.allSatisfy({ $0.isASCII && $0.isHexDigit }),
|
||||
octets.prefix(4).allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }),
|
||||
let value = UInt16(String(decoding: octets.prefix(4), as: UTF8.self), radix: 16) {
|
||||
address = value
|
||||
let chars = Array(digits)
|
||||
bytes = stride(from: 0, to: chars.count, by: 2).compactMap { UInt8(String(chars[$0...($0 + 1)]), radix: 16) }
|
||||
addresses[value, default: []].append(index)
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.append(Line(id: index, text: sourceText, sourceFile: sourceFile, sourceLine: sourceLine, address: address, bytes: bytes))
|
||||
}
|
||||
guard !addresses.isEmpty else { throw ImportError.format }
|
||||
return Self(name: name, lines: lines, byAddress: addresses)
|
||||
}
|
||||
|
||||
func line(at address: UInt16, preferring selected: Int?) -> Int? {
|
||||
guard let candidates = byAddress[address] else { return nil }
|
||||
return selected.flatMap { candidates.contains($0) ? $0 : nil } ?? candidates.first
|
||||
}
|
||||
|
||||
func find(_ query: String, after selected: Int?) -> Int? {
|
||||
guard !query.isEmpty else { return nil }
|
||||
let start = selected.map { ($0 + 1) % lines.count } ?? 0
|
||||
for offset in 0..<lines.count {
|
||||
let index = (start + offset) % lines.count
|
||||
let line = lines[index]
|
||||
if line.text.localizedCaseInsensitiveContains(query) || line.location.localizedCaseInsensitiveContains(query) { return index }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
struct DebugSourceView: View {
|
||||
@ObservedObject var debugger: DebuggerModel
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack {
|
||||
Button(action: open) { Label("Open Listing…", systemImage: "folder") }.disabled(debugger.listingLoading)
|
||||
.accessibilityIdentifier("debugger-source-open")
|
||||
if let listing = debugger.listing {
|
||||
Text(listing.name).lineLimit(1).truncationMode(.middle).help(listing.name)
|
||||
Spacer(minLength: 4)
|
||||
Button(action: debugger.unloadListing) { Label("Close", systemImage: "xmark") }.accessibilityIdentifier("debugger-source-close")
|
||||
Toggle("Follow PC", isOn: $debugger.sourceFollowPC).toggleStyle(.checkbox)
|
||||
.accessibilityIdentifier("debugger-source-follow")
|
||||
} else { Spacer(); if debugger.listingLoading { ProgressView().controlSize(.small) } }
|
||||
}.padding(10)
|
||||
Divider()
|
||||
if let listing = debugger.listing {
|
||||
HStack {
|
||||
TextField("Find source text or filename", text: $debugger.sourceSearch)
|
||||
.textFieldStyle(.roundedBorder).onSubmit { debugger.findSource() }
|
||||
.accessibilityLabel("Find source text or filename").accessibilityIdentifier("debugger-source-search")
|
||||
Button(action: debugger.findSource) { Label("Find Next", systemImage: "magnifyingglass") }.accessibilityIdentifier("debugger-source-find")
|
||||
Text("\(listing.addressedLineCount) addressed lines").font(.caption).foregroundStyle(.secondary)
|
||||
}.padding(.horizontal, 10).padding(.vertical, 6)
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView([.horizontal, .vertical]) {
|
||||
LazyVStack(alignment: .leading, spacing: 0) {
|
||||
ForEach(listing.lines) { line in row(line).id(line.id) }
|
||||
}.padding(.vertical, 4)
|
||||
}.accessibilityIdentifier("debugger-source-lines")
|
||||
.onChange(of: debugger.visibleSourceLine) { _, index in if let index { proxy.scrollTo(index, anchor: .center) } }
|
||||
.onChange(of: debugger.listing?.name) { _, _ in if let index = debugger.visibleSourceLine { proxy.scrollTo(index, anchor: .center) } }
|
||||
.onAppear { if let index = debugger.visibleSourceLine { proxy.scrollTo(index, anchor: .center) } }
|
||||
}
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
if let index = debugger.visibleSourceLine, listing.lines.indices.contains(index) {
|
||||
let line = listing.lines[index]
|
||||
Text(line.location).font(.caption).accessibilityIdentifier("debugger-source-location")
|
||||
if let address = line.address, (listing.byAddress[address]?.count ?? 0) > 1 {
|
||||
Text("Several listing lines share this address. Select the intended line; the breakpoint applies to every execution at that CPU address.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
} else if debugger.sourceFollowPC {
|
||||
Text("No source line at PC $\(DebuggerModel.hex(debugger.programCounter)).").font(.caption)
|
||||
.accessibilityIdentifier("debugger-source-no-match")
|
||||
}
|
||||
Text("Logical CPU addresses · Load the matching program separately.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
.help("Listing bytes are not verified against current memory. Use a final absolute listing for the loaded program and its current MMU mapping.")
|
||||
}.padding(8)
|
||||
} else {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Label("Open a source listing", systemImage: "doc.text.magnifyingglass").font(.headline)
|
||||
Text("Open a LWASM .lst or text listing generated with --list. View source, follow exact PC addresses, search, and share breakpoints with disassembly.")
|
||||
Text("A listing is debugging information. Opening it does not load a program or change the machine.").foregroundStyle(.secondary)
|
||||
}.padding(16).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
}
|
||||
if let message = debugger.sourceMessage {
|
||||
Text(message).font(.caption).foregroundStyle(.orange).padding(8)
|
||||
.accessibilityIdentifier("debugger-source-message")
|
||||
}
|
||||
}.background(Color(nsColor: .textBackgroundColor))
|
||||
}
|
||||
|
||||
private func row(_ line: DebugSourceListing.Line) -> some View {
|
||||
let isPC = line.id == debugger.currentSourceLine
|
||||
let selected = line.id == debugger.visibleSourceLine
|
||||
return HStack(spacing: 8) {
|
||||
if let address = line.address {
|
||||
let action = "\(debugger.allBreakpoints.contains(address) ? "Remove" : "Set") breakpoint at \(DebuggerModel.hex(address)), listing line \(line.id + 1)"
|
||||
Button { debugger.toggleBreakpoint(at: address) } label: {
|
||||
Image(systemName: debugger.breakpoints.contains(address) ? "circle.fill" : debugger.disabledBreakpoints.contains(address) ? "circle.dashed" : "circle")
|
||||
.foregroundStyle(debugger.breakpoints.contains(address) ? Color.red : Color.secondary)
|
||||
.frame(width: 22, height: 24)
|
||||
}.buttonStyle(.plain).disabled(!debugger.commandsAvailable)
|
||||
.help(action).accessibilityLabel(action)
|
||||
.accessibilityIdentifier("debugger-source-breakpoint-\(line.id)")
|
||||
} else { Color.clear.frame(width: 22, height: 24) }
|
||||
Text(String(line.id + 1)).foregroundStyle(.secondary).frame(width: 42, alignment: .trailing)
|
||||
Button {
|
||||
debugger.selectSourceLine(line.id)
|
||||
} label: {
|
||||
HStack(spacing: 8) {
|
||||
Text(line.address.map { DebuggerModel.hex($0) } ?? "—").frame(width: 42, alignment: .leading)
|
||||
Image(systemName: "arrow.right").opacity(isPC ? 1 : 0).frame(width: 12)
|
||||
Text(line.text.isEmpty ? " " : line.text).fixedSize(horizontal: true, vertical: false)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())
|
||||
}.buttonStyle(.plain).accessibilityIdentifier("debugger-source-line-\(line.id)")
|
||||
}.font(.system(size: 12, design: .monospaced)).padding(.horizontal, 8)
|
||||
.background(selected ? Color.accentColor.opacity(0.16) : Color.clear)
|
||||
.contextMenu {
|
||||
if let address = line.address {
|
||||
Button("Show Disassembly") { debugger.showDisassembly(at: address) }
|
||||
Button("Show in Memory") { debugger.showMemory(at: address) }
|
||||
Button("Set PC Here") { debugger.setPC(to: address) }.disabled(!debugger.canEdit)
|
||||
Button(debugger.allBreakpoints.contains(address) ? "Remove Breakpoint" : "Add Breakpoint") { debugger.toggleBreakpoint(at: address) }
|
||||
.disabled(!debugger.commandsAvailable)
|
||||
if debugger.allBreakpoints.contains(address) {
|
||||
Button(debugger.breakpoints.contains(address) ? "Disable Breakpoint" : "Enable Breakpoint") {
|
||||
debugger.setBreakpoint(address, enabled: !debugger.breakpoints.contains(address))
|
||||
}.disabled(!debugger.commandsAvailable)
|
||||
}
|
||||
}
|
||||
Button("Copy Source Line") {
|
||||
NSPasteboard.general.clearContents(); NSPasteboard.general.setString(line.text, forType: .string)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func open() {
|
||||
let panel = NSOpenPanel(); panel.title = "Open LWASM Source Listing"
|
||||
panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||||
// Allow .lst and text listings regardless of their Finder type association.
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
Task { await debugger.loadListing(url) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// A window-owned inspector of the shared machine. It never owns another CPU
|
||||
/// and only asks for immutable captures on the machine's existing serial queue.
|
||||
@MainActor
|
||||
final class DebuggerModel: ObservableObject {
|
||||
let machine: MachineModel
|
||||
@Published private(set) var snapshot: VCCDebuggerSnapshot?
|
||||
@Published private(set) var changedRegisters: Set<String> = []
|
||||
@Published var followPC = true
|
||||
enum CodePane: String, CaseIterable { case disassembly = "Disassembly", source = "Source" }
|
||||
@Published var codePane = CodePane.disassembly
|
||||
@Published private(set) var listing: DebugSourceListing?
|
||||
@Published private(set) var listingLoading = false
|
||||
@Published var sourceFollowPC = true
|
||||
@Published var selectedSourceLine: Int?
|
||||
@Published var sourceSearch = ""
|
||||
@Published var sourceMessage: String?
|
||||
private var listingRequest = UUID()
|
||||
@Published var addressText = "8000"
|
||||
enum MemorySpace: String, CaseIterable { case mapped = "Mapped CPU", physical = "Physical RAM" }
|
||||
enum MemoryPane: String, CaseIterable { case memory = "Memory", mmu = "MMU" }
|
||||
@Published var memoryPane = MemoryPane.memory
|
||||
@Published private(set) var memorySpace = MemorySpace.mapped
|
||||
@Published var memoryAddressText = "0000"
|
||||
@Published var physicalAddressText = "000000"
|
||||
@Published var pcText = ""
|
||||
@Published var breakpointText = ""
|
||||
@Published var editAddressText = ""
|
||||
@Published var editByteText = ""
|
||||
@Published var validationMessage: String?
|
||||
@Published private(set) var commandPending = false
|
||||
private var address: UInt16 = 0x8000
|
||||
@Published private(set) var highlightedByte: UInt32?
|
||||
private var memoryAddress: UInt16 = 0
|
||||
private var physicalAddress: UInt32 = 0
|
||||
private var readRequest: UUID?
|
||||
|
||||
init(machine: MachineModel) { self.machine = machine }
|
||||
|
||||
var paused: Bool { machine.state == .paused }
|
||||
var loaded: Bool { machine.state == .paused || machine.state == .running }
|
||||
var commandsAvailable: Bool { loaded && !machine.busy && !machine.diskSaving && !commandPending }
|
||||
var canEdit: Bool { commandsAvailable && paused }
|
||||
var breakpoints: [UInt16] { snapshot?.breakpoints.map { $0.uint16Value } ?? [] }
|
||||
var disabledBreakpoints: [UInt16] { snapshot?.disabledBreakpoints.map { $0.uint16Value } ?? [] }
|
||||
var allBreakpoints: [UInt16] { (breakpoints + disabledBreakpoints).sorted() }
|
||||
var programCounter: UInt16 { snapshot?.registers["PC"]?.uint16Value ?? 0 }
|
||||
var currentSourceLine: Int? { listing?.line(at: programCounter, preferring: selectedSourceLine) }
|
||||
var visibleSourceLine: Int? { sourceFollowPC ? currentSourceLine : selectedSourceLine }
|
||||
|
||||
func loadListing(_ url: URL) async {
|
||||
let request = UUID(); listingRequest = request; listingLoading = true; sourceMessage = nil
|
||||
let result = await Task.detached(priority: .userInitiated) { Result { try DebugSourceListing.read(url) } }.value
|
||||
guard listingRequest == request else { return }
|
||||
listingLoading = false
|
||||
switch result {
|
||||
case .success(let listing):
|
||||
self.listing = listing; selectedSourceLine = nil; sourceFollowPC = true; codePane = .source
|
||||
case .failure(let error): sourceMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func unloadListing() {
|
||||
listingRequest = UUID(); listingLoading = false; listing = nil; selectedSourceLine = nil; sourceMessage = nil
|
||||
// Source breakpoints are the shared logical-address breakpoints. Closing
|
||||
// a document must not silently remove a user's execution controls.
|
||||
}
|
||||
|
||||
func selectSourceLine(_ index: Int) {
|
||||
guard listing?.lines.indices.contains(index) == true else { return }
|
||||
selectedSourceLine = index; sourceFollowPC = false; sourceMessage = nil
|
||||
}
|
||||
|
||||
func findSource() {
|
||||
guard let listing else { return }
|
||||
guard let index = listing.find(sourceSearch, after: selectedSourceLine) else {
|
||||
sourceMessage = sourceSearch.isEmpty ? "Enter text to find in the listing." : "No matching source line."; return
|
||||
}
|
||||
selectSourceLine(index)
|
||||
}
|
||||
|
||||
func showDisassembly(at address: UInt16) {
|
||||
addressText = Self.hex(address); goToAddress(); codePane = .disassembly
|
||||
}
|
||||
var physical: Bool { memorySpace == .physical }
|
||||
var memory: [UInt8] { snapshot.map { Array(physical ? $0.physicalMemory : $0.memory) } ?? [] }
|
||||
var memoryAvailable: [UInt8] { physical ? Array(repeating: 1, count: memory.count) : snapshot.map { Array($0.memoryAvailable) } ?? [] }
|
||||
var displayedMemoryAddress: UInt32 { snapshot.map { physical ? $0.physicalAddress : UInt32($0.memoryAddress) } ?? 0 }
|
||||
var installedRAM: UInt32 { snapshot?.mmu.ramByteCount ?? 0 }
|
||||
var memoryAddressWidth: Int { physical ? 6 : 4 }
|
||||
var canEditMemory: Bool { canEdit && !physical }
|
||||
var canPreviousMemory: Bool { (physical ? physicalAddress : UInt32(memoryAddress)) > 0 }
|
||||
var canNextMemory: Bool {
|
||||
physical ? physicalAddress + 256 < installedRAM : UInt32(memoryAddress) + 256 < 65536
|
||||
}
|
||||
func memoryLocation(offset: Int) -> UInt32 {
|
||||
let address = displayedMemoryAddress + UInt32(offset)
|
||||
return physical ? address : address & 0xffff
|
||||
}
|
||||
|
||||
// A leading $ or 0x is accepted; all debugger addresses and byte values
|
||||
// are explicitly hexadecimal. Reject overflow instead of truncating it.
|
||||
static func hexadecimal(_ text: String, maximum: UInt32 = 0xffff) -> UInt16? {
|
||||
guard let value = hexadecimalAddress(text, maximum: min(maximum, 0xffff)) else { return nil }
|
||||
return UInt16(value)
|
||||
}
|
||||
|
||||
static func hexadecimalAddress(_ text: String, maximum: UInt32) -> UInt32? {
|
||||
var value = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if value.hasPrefix("$") { value.removeFirst() }
|
||||
else if value.lowercased().hasPrefix("0x") { value.removeFirst(2) }
|
||||
guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isHexDigit }),
|
||||
let parsed = UInt32(value, radix: 16), parsed <= maximum else { return nil }
|
||||
return parsed
|
||||
}
|
||||
|
||||
static func hex<T: BinaryInteger>(_ value: T, width: Int = 4) -> String {
|
||||
String(format: "%0*X", width, UInt32(truncatingIfNeeded: value))
|
||||
}
|
||||
|
||||
func poll() async {
|
||||
defer {
|
||||
// A queued immutable read can finish after the window disappears.
|
||||
// Discard that result, and permit a fresh capture on reopening.
|
||||
readRequest = nil
|
||||
commandPending = false
|
||||
}
|
||||
while !Task.isCancelled {
|
||||
refresh()
|
||||
do { try await Task.sleep(nanoseconds: 200_000_000) }
|
||||
catch { return }
|
||||
}
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
guard !commandPending else { return }
|
||||
capture()
|
||||
}
|
||||
|
||||
private func capture(releasesCommand: Bool = false) {
|
||||
guard readRequest == nil, !machine.busy else {
|
||||
if releasesCommand { commandPending = false }
|
||||
return
|
||||
}
|
||||
let request = UUID()
|
||||
readRequest = request
|
||||
let requestedPhysicalAddress = physicalAddress
|
||||
let requestedPhysicalMemory = physical
|
||||
machine.readDebugger(address: address, followPC: followPC, memoryAddress: memoryAddress,
|
||||
physicalAddress: requestedPhysicalAddress, physicalMemory: requestedPhysicalMemory) { [weak self] capture in
|
||||
guard let self, self.readRequest == request else { return }
|
||||
self.readRequest = nil
|
||||
if releasesCommand { self.commandPending = false }
|
||||
guard let capture else { return }
|
||||
let registers = capture.registers
|
||||
if let previous = self.snapshot, previous.machine.generation == capture.machine.generation {
|
||||
let changes = Set(registers.compactMap { key, value in
|
||||
previous.registers[key] != value ? key : nil
|
||||
})
|
||||
// Preserve the last instruction's highlights while paused;
|
||||
// repeated inspection is not another instruction.
|
||||
if !changes.isEmpty { self.changedRegisters = changes }
|
||||
} else { self.changedRegisters = [] }
|
||||
self.snapshot = capture
|
||||
// The bridge clamps an old physical location after a RAM-size
|
||||
// change. Preserve an unfinished text draft; only explicit Go
|
||||
// normalizes it to the newly accepted location.
|
||||
if requestedPhysicalMemory && self.physicalAddress == requestedPhysicalAddress {
|
||||
self.physicalAddress = capture.physicalAddress
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func perform(_ operation: (@escaping () -> Void) -> Void) {
|
||||
commandPending = true
|
||||
operation { [weak self] in
|
||||
guard let self else { return }
|
||||
// Do not accept a pre-command read or enable another breakpoint
|
||||
// mutation until its authoritative post-command list arrives.
|
||||
self.readRequest = nil
|
||||
self.capture(releasesCommand: true)
|
||||
}
|
||||
}
|
||||
|
||||
func toggleExecution() {
|
||||
guard commandsAvailable else { return }
|
||||
validationMessage = nil
|
||||
if machine.state == .running { perform(machine.debuggerPause) }
|
||||
else { perform(machine.debuggerContinue) }
|
||||
}
|
||||
|
||||
func step() {
|
||||
guard canEdit else { return }
|
||||
validationMessage = nil
|
||||
changedRegisters = []
|
||||
perform(machine.debuggerStep)
|
||||
}
|
||||
|
||||
func goToAddress() {
|
||||
guard let value = Self.hexadecimal(addressText) else {
|
||||
validationMessage = "Enter a hexadecimal address from 0000 to FFFF."; return
|
||||
}
|
||||
address = value; addressText = Self.hex(value); followPC = false
|
||||
validationMessage = nil; refresh()
|
||||
}
|
||||
|
||||
func setMemorySpace(_ space: MemorySpace) {
|
||||
highlightedByte = nil; memorySpace = space; validationMessage = nil; refresh()
|
||||
}
|
||||
|
||||
func showPhysicalMemory(at value: UInt32) {
|
||||
guard value < installedRAM else {
|
||||
validationMessage = "That physical address is outside installed RAM."; return
|
||||
}
|
||||
highlightedByte = nil
|
||||
physicalAddress = value & ~UInt32(15)
|
||||
physicalAddressText = Self.hex(physicalAddress, width: 6)
|
||||
memorySpace = .physical; memoryPane = .memory
|
||||
validationMessage = nil; refresh()
|
||||
}
|
||||
|
||||
func pageMemory(forward: Bool) {
|
||||
guard forward ? canNextMemory : canPreviousMemory else { return }
|
||||
if physical {
|
||||
showPhysicalMemory(at: forward ? physicalAddress + 256 : physicalAddress >= 256 ? physicalAddress - 256 : 0)
|
||||
} else {
|
||||
showMemory(at: forward ? memoryAddress + 256 : memoryAddress >= 256 ? memoryAddress - 256 : 0)
|
||||
}
|
||||
}
|
||||
|
||||
func showMemory(at value: UInt16) {
|
||||
memorySpace = .mapped; memoryPane = .memory
|
||||
highlightedByte = nil
|
||||
memoryAddress = value & 0xfff0
|
||||
memoryAddressText = Self.hex(memoryAddress)
|
||||
validationMessage = nil; refresh()
|
||||
}
|
||||
|
||||
func revealGraphicsByte(_ address: UInt32, physical: Bool) {
|
||||
if physical { showPhysicalMemory(at: address) }
|
||||
else if let logical = UInt16(exactly: address) { showMemory(at: logical) }
|
||||
highlightedByte = address
|
||||
}
|
||||
|
||||
func goToMemory() {
|
||||
if physical {
|
||||
guard installedRAM > 0, let value = Self.hexadecimalAddress(physicalAddressText, maximum: installedRAM - 1) else {
|
||||
validationMessage = "Enter a physical RAM address from 000000 to \(Self.hex(installedRAM > 0 ? installedRAM - 1 : 0, width: 6))."; return
|
||||
}
|
||||
showPhysicalMemory(at: value); return
|
||||
}
|
||||
guard let value = Self.hexadecimal(memoryAddressText) else {
|
||||
validationMessage = "Enter a hexadecimal memory address from 0000 to FFFF."; return
|
||||
}
|
||||
showMemory(at: value)
|
||||
}
|
||||
|
||||
func setPC() {
|
||||
guard canEdit else { return }
|
||||
guard let value = Self.hexadecimal(pcText) else {
|
||||
validationMessage = "Enter the new program counter in hexadecimal, from 0000 to FFFF."; return
|
||||
}
|
||||
setPC(to: value)
|
||||
}
|
||||
|
||||
func setPC(to value: UInt16) {
|
||||
guard canEdit else { return }
|
||||
validationMessage = nil; pcText = Self.hex(value)
|
||||
perform { machine.debuggerSetPC(value, completion: $0) }
|
||||
}
|
||||
|
||||
func addBreakpoint() {
|
||||
guard let value = Self.hexadecimal(breakpointText) else {
|
||||
validationMessage = "Enter a hexadecimal breakpoint address from 0000 to FFFF."; return
|
||||
}
|
||||
configureBreakpoints(Array(Set(breakpoints + [value])).sorted(), disabled: disabledBreakpoints.filter { $0 != value })
|
||||
}
|
||||
|
||||
func toggleBreakpoint(at value: UInt16) {
|
||||
if allBreakpoints.contains(value) {
|
||||
configureBreakpoints(breakpoints.filter { $0 != value }, disabled: disabledBreakpoints.filter { $0 != value })
|
||||
} else { configureBreakpoints((breakpoints + [value]).sorted(), disabled: disabledBreakpoints) }
|
||||
}
|
||||
|
||||
func setBreakpoint(_ value: UInt16, enabled: Bool) {
|
||||
guard allBreakpoints.contains(value) else { return }
|
||||
configureBreakpoints(enabled ? Array(Set(breakpoints + [value])).sorted() : breakpoints.filter { $0 != value },
|
||||
disabled: enabled ? disabledBreakpoints.filter { $0 != value } : Array(Set(disabledBreakpoints + [value])).sorted())
|
||||
}
|
||||
|
||||
func removeAllBreakpoints() { configureBreakpoints([], disabled: []) }
|
||||
|
||||
private func configureBreakpoints(_ addresses: [UInt16], disabled: [UInt16]) {
|
||||
guard commandsAvailable else { return }
|
||||
validationMessage = nil
|
||||
perform { machine.debuggerConfigureBreakpoints(addresses.map { NSNumber(value: $0) }, disabled: disabled.map { NSNumber(value: $0) }, completion: $0) }
|
||||
}
|
||||
|
||||
func selectByte(offset: Int) {
|
||||
guard !physical, let snapshot, offset >= 0, offset < memory.count, offset < memoryAvailable.count,
|
||||
memoryAvailable[offset] != 0 else { return }
|
||||
highlightedByte = memoryLocation(offset: offset)
|
||||
editAddressText = Self.hex(snapshot.memoryAddress &+ UInt16(offset))
|
||||
editByteText = Self.hex(UInt16(memory[offset]), width: 2)
|
||||
}
|
||||
|
||||
func writeByte() {
|
||||
guard canEditMemory else { return }
|
||||
guard let target = Self.hexadecimal(editAddressText),
|
||||
let byte = Self.hexadecimal(editByteText, maximum: 0xff) else {
|
||||
validationMessage = "Enter a hexadecimal address (0000–FFFF) and byte (00–FF)."; return
|
||||
}
|
||||
validationMessage = nil
|
||||
perform { machine.debuggerWriteMemory(address: target, data: Data([UInt8(byte)]), completion: $0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
struct DebuggerView: View {
|
||||
// The machine publishes at display cadence. Rendering this inspector is
|
||||
// driven by its own bounded snapshot stream and local editing state.
|
||||
private let machine: MachineModel
|
||||
@StateObject private var debugger: DebuggerModel
|
||||
@StateObject private var memoryTools: MemoryToolsModel
|
||||
@StateObject private var graphics = GraphicsPreviewModel()
|
||||
@StateObject private var trace: TraceModel
|
||||
private enum Workspace: String, CaseIterable { case inspector = "Inspector", memory = "Memory Tools", graphics = "Graphics Preview", trace = "Trace" }
|
||||
@State private var workspace = Workspace.inspector
|
||||
|
||||
init(machine: MachineModel) {
|
||||
self.machine = machine
|
||||
_debugger = StateObject(wrappedValue: DebuggerModel(machine: machine))
|
||||
_memoryTools = StateObject(wrappedValue: MemoryToolsModel(machine: machine))
|
||||
_trace = StateObject(wrappedValue: TraceModel(machine: machine))
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
executionToolbar
|
||||
Divider()
|
||||
if debugger.loaded {
|
||||
HStack {
|
||||
Picker("Debugger workspace", selection: $workspace) {
|
||||
ForEach(Workspace.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(width: 460)
|
||||
.accessibilityIdentifier("debugger-workspace")
|
||||
Spacer()
|
||||
}.padding(.horizontal, 12).padding(.vertical, 6)
|
||||
Divider()
|
||||
if workspace == .memory { MemoryToolsView(model: memoryTools) }
|
||||
else if workspace == .graphics {
|
||||
GraphicsPreviewView(model: graphics, machine: machine) { address, physical in
|
||||
debugger.revealGraphicsByte(address, physical: physical)
|
||||
workspace = .inspector
|
||||
}
|
||||
}
|
||||
else if workspace == .trace { TraceView(model: trace) }
|
||||
else {
|
||||
HSplitView {
|
||||
VSplitView {
|
||||
codeInspector.frame(minHeight: debugger.codePane == .source ? 340 : 220)
|
||||
// Keep the combined minimum stable when Source needs
|
||||
// more room, rather than overflowing a restored window.
|
||||
memoryInspector.frame(minHeight: debugger.codePane == .source ? 145 : 265,
|
||||
idealHeight: debugger.codePane == .source ? 180 : 310)
|
||||
}.frame(minWidth: 590, idealWidth: 740)
|
||||
inspector.frame(minWidth: 265, idealWidth: 285, maxWidth: 360)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: "ladybug").font(.system(size: 36)).foregroundStyle(.secondary)
|
||||
Text("Load a machine to begin debugging").font(.title2)
|
||||
Text("Open a system ROM or choose a system profile in the main window.")
|
||||
.foregroundStyle(.secondary)
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
Divider()
|
||||
statusBar
|
||||
}
|
||||
.frame(minWidth: 920, minHeight: 640)
|
||||
.task { await debugger.poll() }
|
||||
.onChange(of: debugger.followPC) { _, _ in debugger.refresh() }
|
||||
}
|
||||
|
||||
private var codeInspector: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Picker("Code view", selection: $debugger.codePane) {
|
||||
ForEach(DebuggerModel.CodePane.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(width: 225)
|
||||
.accessibilityIdentifier("debugger-code-pane")
|
||||
Spacer(minLength: 8)
|
||||
if debugger.codePane == .disassembly { disassemblyNavigation }
|
||||
}.padding(.horizontal, 12).padding(.vertical, 6)
|
||||
Divider()
|
||||
if debugger.codePane == .source { DebugSourceView(debugger: debugger) }
|
||||
else { disassembly }
|
||||
}
|
||||
}
|
||||
|
||||
private var executionToolbar: some View {
|
||||
HStack(spacing: 14) {
|
||||
Label(machine.state == .running ? "Running" : debugger.loaded ? "Paused" : "No machine",
|
||||
systemImage: machine.state == .running ? "play.circle.fill" : "pause.circle")
|
||||
.foregroundStyle(machine.state == .running ? Color.green : Color.secondary)
|
||||
.frame(width: 100, alignment: .leading)
|
||||
.accessibilityIdentifier("debugger-state")
|
||||
Button(action: debugger.toggleExecution) {
|
||||
Label(machine.state == .running ? "Pause" : "Continue",
|
||||
systemImage: machine.state == .running ? "pause.fill" : "play.fill")
|
||||
}.disabled(!debugger.commandsAvailable).accessibilityIdentifier("debugger-run")
|
||||
Button(action: debugger.step) { Label("Step", systemImage: "arrow.right.to.line") }
|
||||
.disabled(!debugger.canEdit || (workspace == .graphics && !graphics.readyToStep(machine: machine)))
|
||||
.accessibilityIdentifier("debugger-step")
|
||||
.help("Execute one instruction, then remain paused.")
|
||||
Divider().frame(height: 22)
|
||||
Text(machine.use6309 ? "HD6309" : "MC6809").font(.system(.body, design: .monospaced))
|
||||
Spacer()
|
||||
Text("PC").foregroundStyle(.secondary)
|
||||
Text("$" + DebuggerModel.hex(debugger.programCounter))
|
||||
.font(.system(.body, design: .monospaced)).textSelection(.enabled)
|
||||
.accessibilityIdentifier("debugger-pc")
|
||||
TextField("New PC", text: $debugger.pcText).frame(width: 80)
|
||||
.font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder)
|
||||
.onSubmit { debugger.setPC() }.disabled(!debugger.canEdit)
|
||||
.accessibilityLabel("New program counter in hexadecimal")
|
||||
.accessibilityIdentifier("debugger-pc-entry")
|
||||
Button("Set PC", action: debugger.setPC).disabled(!debugger.canEdit)
|
||||
.accessibilityIdentifier("debugger-set-pc")
|
||||
.help("Change the next instruction address without resetting the machine.")
|
||||
}.padding(.horizontal, 16).padding(.vertical, 9)
|
||||
}
|
||||
|
||||
private var disassemblyNavigation: some View {
|
||||
HStack(spacing: 6) {
|
||||
TextField("Address", text: $debugger.addressText).frame(width: 80)
|
||||
.font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder)
|
||||
.onSubmit { debugger.goToAddress() }
|
||||
.accessibilityLabel("Disassembly address in hexadecimal")
|
||||
.accessibilityIdentifier("debugger-address")
|
||||
Button("Go", action: debugger.goToAddress).accessibilityIdentifier("debugger-go")
|
||||
Toggle("Follow PC", isOn: $debugger.followPC).toggleStyle(.checkbox)
|
||||
.accessibilityIdentifier("debugger-follow-pc")
|
||||
}
|
||||
}
|
||||
|
||||
private var disassembly: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 10) {
|
||||
Text("").frame(width: 22)
|
||||
Text("Address").frame(width: 65, alignment: .leading)
|
||||
Text("Bytes").frame(width: 132, alignment: .leading)
|
||||
Text("Instruction").frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 12).padding(.vertical, 5)
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 0) {
|
||||
if let snapshot = debugger.snapshot {
|
||||
ForEach(Array(snapshot.instructions.enumerated()), id: \.offset) { _, instruction in
|
||||
instructionRow(instruction)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.accessibilityIdentifier("debugger-disassembly")
|
||||
}.background(Color(nsColor: .textBackgroundColor))
|
||||
}
|
||||
|
||||
private func instructionRow(_ instruction: VCCDebugInstruction) -> some View {
|
||||
let isPC = instruction.address == debugger.programCounter
|
||||
let breakpoint = debugger.allBreakpoints.contains(instruction.address)
|
||||
let enabled = debugger.breakpoints.contains(instruction.address)
|
||||
return HStack(spacing: 10) {
|
||||
Button { debugger.toggleBreakpoint(at: instruction.address) } label: {
|
||||
Image(systemName: enabled ? "circle.fill" : breakpoint ? "circle.dashed" : "circle")
|
||||
.foregroundStyle(enabled ? Color.red : Color.secondary.opacity(0.6))
|
||||
.frame(width: 22, height: 24).contentShape(Rectangle())
|
||||
}.buttonStyle(.plain).disabled(!debugger.commandsAvailable)
|
||||
.help("\(breakpoint ? "Remove" : "Add") breakpoint at \(DebuggerModel.hex(instruction.address))").accessibilityLabel("\(breakpoint ? "Remove" : "Add") breakpoint at \(DebuggerModel.hex(instruction.address))")
|
||||
.accessibilityIdentifier("debugger-breakpoint-\(DebuggerModel.hex(instruction.address))")
|
||||
Text(DebuggerModel.hex(instruction.address)).frame(width: 65, alignment: .leading)
|
||||
Text(instruction.bytes.map { String(format: "%02X", $0) }.joined(separator: " "))
|
||||
.foregroundStyle(.secondary).frame(width: 132, alignment: .leading)
|
||||
Text(instruction.mnemonic).fontWeight(isPC ? .semibold : .regular)
|
||||
.frame(width: 62, alignment: .leading)
|
||||
Text(instruction.operand).frame(maxWidth: .infinity, alignment: .leading)
|
||||
if isPC { Image(systemName: "arrow.left").foregroundStyle(Color.accentColor).accessibilityLabel("Current instruction") }
|
||||
}
|
||||
.font(.system(size: 12, design: .monospaced)).padding(.horizontal, 12)
|
||||
.background(isPC ? Color.accentColor.opacity(0.12) : Color.clear)
|
||||
.contentShape(Rectangle())
|
||||
.contextMenu {
|
||||
Button(breakpoint ? "Remove Breakpoint" : "Add Breakpoint") { debugger.toggleBreakpoint(at: instruction.address) }
|
||||
.disabled(!debugger.commandsAvailable)
|
||||
if breakpoint {
|
||||
Button(enabled ? "Disable Breakpoint" : "Enable Breakpoint") { debugger.setBreakpoint(instruction.address, enabled: !enabled) }
|
||||
.disabled(!debugger.commandsAvailable)
|
||||
}
|
||||
Button("Show in Memory") { debugger.showMemory(at: instruction.address) }
|
||||
Button("Set PC Here") { debugger.setPC(to: instruction.address) }.disabled(!debugger.canEdit)
|
||||
Button("Copy Instruction") {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString("\(DebuggerModel.hex(instruction.address)) \(instruction.mnemonic) \(instruction.operand)", forType: .string)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var memoryInspector: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Picker("Memory inspector", selection: $debugger.memoryPane) {
|
||||
ForEach(DebuggerModel.MemoryPane.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(width: 180)
|
||||
.accessibilityIdentifier("debugger-memory-pane")
|
||||
Spacer()
|
||||
if debugger.memoryPane == .memory {
|
||||
Button {
|
||||
graphics.inspectAddress(debugger.highlightedByte ?? debugger.displayedMemoryAddress, physical: debugger.physical)
|
||||
workspace = .graphics
|
||||
} label: { Label("Preview as Graphics", systemImage: "rectangle.on.rectangle") }
|
||||
.accessibilityIdentifier("debugger-preview-memory")
|
||||
}
|
||||
if debugger.installedRAM > 0 {
|
||||
Text("\(debugger.installedRAM / 1024) KB installed").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}.padding(.horizontal, 12).padding(.vertical, 6)
|
||||
Divider()
|
||||
if debugger.memoryPane == .memory { memory } else { mmu }
|
||||
}
|
||||
}
|
||||
|
||||
private var memory: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 8) {
|
||||
Picker("Address space", selection: Binding(get: { debugger.memorySpace }, set: debugger.setMemorySpace)) {
|
||||
ForEach(DebuggerModel.MemorySpace.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.labelsHidden().frame(width: 150).accessibilityIdentifier("debugger-memory-space")
|
||||
.help("Mapped CPU follows the current MMU and ROM overlays. Physical RAM shows installed RAM directly.")
|
||||
Spacer()
|
||||
Button { debugger.pageMemory(forward: false) } label: { Image(systemName: "chevron.left") }
|
||||
.disabled(!debugger.canPreviousMemory).help("Show the previous block of memory").accessibilityLabel("Previous memory block")
|
||||
.accessibilityIdentifier("debugger-memory-previous")
|
||||
Button { debugger.pageMemory(forward: true) } label: { Image(systemName: "chevron.right") }
|
||||
.disabled(!debugger.canNextMemory).help("Show the next block of memory").accessibilityLabel("Next memory block")
|
||||
.accessibilityIdentifier("debugger-memory-next")
|
||||
TextField("Address", text: Binding(get: {
|
||||
debugger.physical ? debugger.physicalAddressText : debugger.memoryAddressText
|
||||
}, set: {
|
||||
if debugger.physical { debugger.physicalAddressText = $0 } else { debugger.memoryAddressText = $0 }
|
||||
})).frame(width: 86)
|
||||
.font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder)
|
||||
.onSubmit { debugger.goToMemory() }
|
||||
.accessibilityLabel(debugger.physical ? "Physical RAM address in hexadecimal" : "Memory address in hexadecimal")
|
||||
.accessibilityIdentifier("debugger-memory-address")
|
||||
Button("Go", action: debugger.goToMemory).accessibilityIdentifier("debugger-memory-go")
|
||||
}.padding(12)
|
||||
Divider()
|
||||
ScrollView([.vertical, .horizontal]) {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
HStack(spacing: 3) {
|
||||
Text("Address").frame(width: 58, alignment: .leading)
|
||||
ForEach(0..<16) { Text(String(format: "%02X", $0)).frame(width: 24) }
|
||||
Text("ASCII").frame(width: 128, alignment: .leading)
|
||||
}.foregroundStyle(.secondary).padding(.bottom, 4)
|
||||
ForEach(0..<((debugger.memory.count + 15) / 16), id: \.self) { row in
|
||||
memoryRow(row)
|
||||
}
|
||||
}.font(.system(size: 11, design: .monospaced)).padding(12)
|
||||
}.accessibilityIdentifier("debugger-memory")
|
||||
Divider()
|
||||
if debugger.physical {
|
||||
Text("Physical RAM is read-only here. ROM overlays and I/O are excluded; the bytes may differ from the CPU's view.")
|
||||
.font(.caption).foregroundStyle(.secondary).padding(10)
|
||||
.accessibilityIdentifier("debugger-physical-read-only")
|
||||
} else {
|
||||
HStack(spacing: 8) {
|
||||
Text("Edit RAM").font(.caption).foregroundStyle(.secondary)
|
||||
TextField("Address", text: $debugger.editAddressText).frame(width: 75)
|
||||
.accessibilityLabel("RAM edit address in hexadecimal").accessibilityIdentifier("debugger-edit-address")
|
||||
TextField("Byte", text: $debugger.editByteText).frame(width: 48)
|
||||
.accessibilityLabel("RAM byte in hexadecimal").accessibilityIdentifier("debugger-edit-byte")
|
||||
.onSubmit { debugger.writeByte() }
|
||||
Button(action: debugger.writeByte) { Label("Write", systemImage: "pencil") }.accessibilityIdentifier("debugger-write-memory")
|
||||
Spacer()
|
||||
Text("I/O: — · RAM edits require Pause").font(.caption).foregroundStyle(.secondary)
|
||||
}.textFieldStyle(.roundedBorder).disabled(!debugger.canEditMemory).padding(10)
|
||||
}
|
||||
}.background(Color(nsColor: .textBackgroundColor))
|
||||
}
|
||||
|
||||
private var mmu: some View {
|
||||
ScrollView {
|
||||
if let state = debugger.snapshot?.mmu {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack {
|
||||
Label(state.enabled ? "MMU enabled" : "MMU disabled", systemImage: "memorychip")
|
||||
.font(.headline).accessibilityIdentifier("debugger-mmu-enabled")
|
||||
Spacer()
|
||||
Text("Task \(state.activeTask) selected").font(.caption)
|
||||
.accessibilityIdentifier("debugger-mmu-task")
|
||||
DebuggerHelpButton(title: "MMU mapping", text: "Each row maps an 8 KB CPU window. Task columns show programmed banks. Effective read shows the current selection, including fixed banks while MMU is disabled. RAM backing buttons inspect physical bytes, including RAM hidden by ROM overlays.")
|
||||
}
|
||||
Text("All-RAM: \(state.allRAM ? "on" : "off") · ROM map: \(state.romMap) · Bank prefix: $\(DebuggerModel.hex(state.prefix, width: 3))")
|
||||
.font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
|
||||
.help("The prefix supplies high bits for future bank-register writes; changing it does not rewrite existing bank selections.")
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 10) {
|
||||
Text("CPU range").frame(width: 88, alignment: .leading)
|
||||
Text("Task 0").frame(width: 58, alignment: .leading)
|
||||
.fontWeight(state.enabled && state.activeTask == 0 ? .bold : .regular)
|
||||
Text("Task 1").frame(width: 58, alignment: .leading)
|
||||
.fontWeight(state.enabled && state.activeTask == 1 ? .bold : .regular)
|
||||
Text("Effective read").frame(width: 175, alignment: .leading)
|
||||
Text("RAM backing").frame(width: 90, alignment: .leading)
|
||||
}.font(.caption).foregroundStyle(.secondary).padding(.bottom, 5)
|
||||
ForEach(Array(state.effective.enumerated()), id: \.offset) { index, mapping in
|
||||
mmuRow(index, mapping: mapping, state: state)
|
||||
}
|
||||
}
|
||||
Divider()
|
||||
Text(state.ramVectors
|
||||
? "FE00–FEFF: fixed RAM at $\(DebuggerModel.hex(state.vectorRAMAddress, width: 6)) (RAM vectors on)."
|
||||
: "FE00–FEFF follows the final bank's mapping (RAM vectors off).")
|
||||
.accessibilityIdentifier("debugger-mmu-vectors")
|
||||
Text("FF00–FFEF: device I/O. FFF0–FFFF: system ROM vectors at $7FF0–$7FFF.")
|
||||
Text("Disassembly and breakpoints continue to use logical CPU addresses.")
|
||||
.foregroundStyle(.secondary)
|
||||
}.font(.caption).padding(12).frame(minWidth: 540, maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}.background(Color(nsColor: .textBackgroundColor))
|
||||
}
|
||||
|
||||
private func mmuRow(_ index: Int, mapping: VCCMemoryMapping, state: VCCMMUSnapshot) -> some View {
|
||||
let start = index * 8192
|
||||
let source = mapping.source == 0 ? "RAM" : mapping.source == 1 ? "System ROM" : "Cartridge ROM"
|
||||
let offset = mapping.source == 0 ? "" : " $" + DebuggerModel.hex(mapping.sourceAddress)
|
||||
return HStack(spacing: 10) {
|
||||
Text("\(DebuggerModel.hex(start))–\(DebuggerModel.hex(start + 8191))")
|
||||
.frame(width: 88, alignment: .leading)
|
||||
Text(state.task0.count > index ? DebuggerModel.hex(state.task0[index].uint16Value, width: 3) : "—")
|
||||
.frame(width: 58, alignment: .leading)
|
||||
.foregroundStyle(state.enabled && state.activeTask == 0 ? Color.accentColor : Color.secondary)
|
||||
Text(state.task1.count > index ? DebuggerModel.hex(state.task1[index].uint16Value, width: 3) : "—")
|
||||
.frame(width: 58, alignment: .leading)
|
||||
.foregroundStyle(state.enabled && state.activeTask == 1 ? Color.accentColor : Color.secondary)
|
||||
Text("[\(DebuggerModel.hex(mapping.page, width: 3))] \(source)\(offset)")
|
||||
.frame(width: 175, alignment: .leading).fixedSize(horizontal: false, vertical: true)
|
||||
.accessibilityIdentifier("debugger-mmu-source-\(index)")
|
||||
Button("$" + DebuggerModel.hex(mapping.ramAddress, width: 6)) { debugger.showPhysicalMemory(at: mapping.ramAddress) }
|
||||
.buttonStyle(.link).frame(width: 90, alignment: .leading)
|
||||
.accessibilityLabel("Inspect RAM backing for CPU \(DebuggerModel.hex(start)) at \(DebuggerModel.hex(mapping.ramAddress, width: 6))")
|
||||
.accessibilityIdentifier("debugger-mmu-ram-\(index)")
|
||||
}.font(.system(size: 11, design: .monospaced)).padding(.vertical, 4)
|
||||
}
|
||||
|
||||
private func memoryRow(_ row: Int) -> some View {
|
||||
let bytes = debugger.memory
|
||||
let available = debugger.memoryAvailable
|
||||
let start = row * 16
|
||||
let address = debugger.memoryLocation(offset: start)
|
||||
let ascii = (start..<min(start + 16, bytes.count)).map { index -> String in
|
||||
guard index < available.count, available[index] != 0 else { return "—" }
|
||||
let byte = bytes[index]
|
||||
return byte >= 32 && byte <= 126 ? String(UnicodeScalar(byte)) : "."
|
||||
}.joined()
|
||||
return HStack(spacing: 3) {
|
||||
Text(DebuggerModel.hex(address, width: debugger.memoryAddressWidth)).foregroundStyle(.secondary).frame(width: 58, alignment: .leading)
|
||||
ForEach(0..<16) { column in
|
||||
let index = start + column
|
||||
let readable = index < bytes.count && index < available.count && available[index] != 0
|
||||
let value = readable ? String(format: "%02X", bytes[index]) : "—"
|
||||
let location = DebuggerModel.hex(debugger.memoryLocation(offset: index), width: debugger.memoryAddressWidth)
|
||||
Group {
|
||||
if debugger.physical {
|
||||
// A selectable Text with a custom accessibility label can
|
||||
// recurse through NSTextView's value/label bridge on macOS.
|
||||
// Static bytes remain readable by VoiceOver without that
|
||||
// extra text-editor accessibility node.
|
||||
Text(value).foregroundStyle(.primary).frame(width: 24, height: 18)
|
||||
.accessibilityLabel("Physical RAM \(location), \(value)")
|
||||
} else {
|
||||
Button { debugger.selectByte(offset: index) } label: {
|
||||
Text(value).frame(width: 24, height: 18).contentShape(Rectangle())
|
||||
}.buttonStyle(.plain).disabled(!readable)
|
||||
.accessibilityLabel("Memory \(location), \(readable ? value : "unavailable")")
|
||||
}
|
||||
}
|
||||
.background(debugger.highlightedByte == debugger.memoryLocation(offset: index) && readable ? Color.accentColor.opacity(0.24) : Color.clear, in: RoundedRectangle(cornerRadius: 3))
|
||||
}
|
||||
Text(ascii).foregroundStyle(.secondary).frame(width: 128, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private var inspector: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
HStack {
|
||||
Label("Registers", systemImage: "cpu").font(.headline)
|
||||
Spacer()
|
||||
DebuggerHelpButton(title: "Registers", text: "Changed registers are highlighted after execution. Addresses and register values are hexadecimal.")
|
||||
}
|
||||
Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 7) {
|
||||
ForEach(registerNames, id: \.self) { name in
|
||||
let value = debugger.snapshot?.registers[name]?.uint16Value ?? 0
|
||||
let changed = debugger.changedRegisters.contains(name)
|
||||
GridRow {
|
||||
Text(name).foregroundStyle(.secondary).frame(width: 30, alignment: .leading)
|
||||
Text("$" + DebuggerModel.hex(value, width: ["A", "B", "E", "F", "DP", "CC", "MD"].contains(name) ? 2 : 4))
|
||||
.foregroundStyle(changed ? Color.accentColor : Color.primary)
|
||||
.fontWeight(changed ? .semibold : .regular)
|
||||
.textSelection(.enabled).accessibilityIdentifier("debugger-register-\(name)")
|
||||
if changed { Image(systemName: "arrow.triangle.2.circlepath").font(.caption2).foregroundStyle(Color.accentColor).accessibilityLabel("Changed") }
|
||||
}
|
||||
}
|
||||
}.font(.system(.body, design: .monospaced))
|
||||
flags
|
||||
Divider()
|
||||
breakpointInspector
|
||||
}.padding(16)
|
||||
}.background(Color(nsColor: .controlBackgroundColor))
|
||||
}
|
||||
|
||||
private var registerNames: [String] {
|
||||
machine.use6309 ? ["A", "B", "E", "F", "X", "Y", "U", "S", "V", "PC", "DP", "CC", "MD"] : ["A", "B", "X", "Y", "U", "S", "PC", "DP", "CC"]
|
||||
}
|
||||
|
||||
private var flags: some View {
|
||||
let cc = debugger.snapshot?.registers["CC"]?.uint8Value ?? 0
|
||||
let names = ["E", "F", "H", "I", "N", "Z", "V", "C"]
|
||||
let descriptions = ["Entire state saved", "FIRQ masked", "Half carry", "IRQ masked", "Negative", "Zero", "Overflow", "Carry"]
|
||||
return VStack(alignment: .leading, spacing: 5) {
|
||||
Text("Condition Codes").font(.caption).foregroundStyle(.secondary)
|
||||
HStack(spacing: 4) {
|
||||
ForEach(0..<8) { index in
|
||||
let active = cc & (1 << (7 - index)) != 0
|
||||
Text(names[index]).font(.system(.caption, design: .monospaced)).fontWeight(active ? .bold : .regular)
|
||||
.frame(width: 23, height: 23)
|
||||
.background(active ? Color.accentColor.opacity(0.18) : Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 4))
|
||||
.foregroundStyle(active ? Color.accentColor : Color.secondary)
|
||||
.help(descriptions[index] + (active ? ": set" : ": clear"))
|
||||
.accessibilityLabel(descriptions[index] + (active ? ", set" : ", clear"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var breakpointInspector: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack {
|
||||
Label("Breakpoints", systemImage: "circle.fill").font(.headline)
|
||||
Spacer()
|
||||
Text("\(debugger.allBreakpoints.count)").foregroundStyle(.secondary)
|
||||
DebuggerHelpButton(title: "Breakpoints", text: "Click a circle beside an instruction, or enter an address. Execution pauses before that instruction. Uncheck to disable without removing. Breakpoints use logical CPU addresses and belong to this session.")
|
||||
}
|
||||
HStack {
|
||||
TextField("Hex address", text: $debugger.breakpointText)
|
||||
.textFieldStyle(.roundedBorder).font(.system(.body, design: .monospaced))
|
||||
.onSubmit { debugger.addBreakpoint() }
|
||||
.accessibilityLabel("New breakpoint address in hexadecimal")
|
||||
.accessibilityIdentifier("debugger-breakpoint-address")
|
||||
Button(action: debugger.addBreakpoint) { Label("Add", systemImage: "plus") }.accessibilityIdentifier("debugger-add-breakpoint")
|
||||
}.disabled(!debugger.commandsAvailable)
|
||||
if debugger.allBreakpoints.isEmpty {
|
||||
Text("Click a circle beside an instruction, or enter an address. Execution pauses before that instruction.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(debugger.allBreakpoints, id: \.self) { address in
|
||||
let action = "\(debugger.breakpoints.contains(address) ? "Disable" : "Enable") breakpoint at \(DebuggerModel.hex(address))"
|
||||
HStack {
|
||||
Toggle("Enabled", isOn: Binding(get: { debugger.breakpoints.contains(address) }, set: { debugger.setBreakpoint(address, enabled: $0) }))
|
||||
.toggleStyle(.checkbox).labelsHidden().disabled(!debugger.commandsAvailable)
|
||||
.help(action).accessibilityLabel(action)
|
||||
.accessibilityIdentifier("debugger-breakpoint-enabled-\(DebuggerModel.hex(address))")
|
||||
Button("$" + DebuggerModel.hex(address)) {
|
||||
debugger.showDisassembly(at: address)
|
||||
}.buttonStyle(.plain).font(.system(.body, design: .monospaced))
|
||||
Spacer()
|
||||
Button { debugger.toggleBreakpoint(at: address) } label: { Image(systemName: "minus.circle") }
|
||||
.buttonStyle(.plain).disabled(!debugger.commandsAvailable)
|
||||
.help("Remove breakpoint at \(DebuggerModel.hex(address))").accessibilityLabel("Remove breakpoint at \(DebuggerModel.hex(address))")
|
||||
}
|
||||
}
|
||||
if !debugger.allBreakpoints.isEmpty {
|
||||
Button(action: debugger.removeAllBreakpoints) { Label("Remove All", systemImage: "minus.circle") }.disabled(!debugger.commandsAvailable)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var statusBar: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 12) {
|
||||
if let error = debugger.validationMessage ?? machine.error {
|
||||
Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange)
|
||||
Text(error).foregroundStyle(.primary).textSelection(.enabled)
|
||||
.accessibilityIdentifier("debugger-error")
|
||||
} else {
|
||||
Text(debugger.snapshot?.stopReason.isEmpty == false ? debugger.snapshot!.stopReason : "Inspection preserves the running machine. Pause to step or edit RAM.")
|
||||
.foregroundStyle(.secondary).accessibilityIdentifier("debugger-status")
|
||||
}
|
||||
Spacer(minLength: 12)
|
||||
if let snapshot = debugger.snapshot {
|
||||
Text("\(snapshot.machine.cycles.formatted()) cycles").monospacedDigit().foregroundStyle(.secondary)
|
||||
}
|
||||
}.font(.caption).padding(.horizontal, 14).padding(.vertical, 10)
|
||||
}
|
||||
}
|
||||
|
||||
// A native, keyboard-accessible help popover keeps panel toolbars compact.
|
||||
// Its local presentation state is independent of live machine snapshots.
|
||||
struct DebuggerHelpButton: View {
|
||||
let title: String
|
||||
let text: String
|
||||
@State private var presented = false
|
||||
var body: some View {
|
||||
Button { presented.toggle() } label: {
|
||||
Image(systemName: "questionmark.circle").frame(width: 22, height: 22)
|
||||
}.buttonStyle(.plain).foregroundStyle(.secondary)
|
||||
.accessibilityLabel(title + " help").help(title + " help")
|
||||
.popover(isPresented: $presented) {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(title).font(.headline)
|
||||
Text(text).fixedSize(horizontal: false, vertical: true)
|
||||
}.padding(18).frame(width: 340)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Load the editable lesson from the same source shipped in the example tree.
|
||||
final class DevelopmentStarterSource {
|
||||
static func planet(withExtension ext: String) -> String? {
|
||||
for bundle in [Bundle.main, Bundle(for: DevelopmentStarterSource.self)] {
|
||||
if let file = bundle.url(forResource: "planet", withExtension: ext),
|
||||
let source = try? String(contentsOf: file, encoding: .utf8) {
|
||||
return source
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
// File references only. Guest writes and ROM contents never enter preferences.
|
||||
struct DiskAssignments: Codable, Equatable, Sendable {
|
||||
struct Drive: Codable, Equatable, Sendable {
|
||||
var url: URL
|
||||
var writeProtected: Bool
|
||||
var temporary: Bool = false
|
||||
init(url: URL, writeProtected: Bool, temporary: Bool = false) {
|
||||
self.url = url; self.writeProtected = writeProtected; self.temporary = temporary
|
||||
}
|
||||
private enum CodingKeys: String, CodingKey { case url, writeProtected, temporary }
|
||||
init(from decoder: Decoder) throws {
|
||||
let values = try decoder.container(keyedBy: CodingKeys.self)
|
||||
url = try values.decode(URL.self, forKey: .url)
|
||||
writeProtected = try values.decode(Bool.self, forKey: .writeProtected)
|
||||
temporary = try values.decodeIfPresent(Bool.self, forKey: .temporary) ?? false
|
||||
}
|
||||
}
|
||||
var hardDisks: HardDiskAssignments?
|
||||
var cartridges: CartridgeAssignments?
|
||||
var version = 1
|
||||
var rom: URL?
|
||||
var drives: [Drive?] = Array(repeating: nil, count: 4)
|
||||
|
||||
func validate() throws {
|
||||
try cartridges?.validate()
|
||||
try hardDisks?.validate()
|
||||
guard version == 1, drives.count == 4,
|
||||
rom != nil || drives.allSatisfy({ $0 == nil }),
|
||||
([rom] + drives.map { $0?.url }).compactMap({ $0 }).allSatisfy({
|
||||
$0.isFileURL && $0.host.map { $0.isEmpty || $0 == "localhost" } != false && $0.path.hasPrefix("/")
|
||||
}) else { throw DiskAssignmentStore.Failure.invalid }
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskAssignmentStore: Sendable {
|
||||
let url: URL
|
||||
static var standard: Self {
|
||||
Self(url: AppIdentity.supportDirectory
|
||||
.appendingPathComponent("DiskAssignments.json"))
|
||||
}
|
||||
enum Failure: LocalizedError {
|
||||
case invalid
|
||||
var errorDescription: String? { "The remembered disk settings are damaged or use an unsupported version. Select the disk files again." }
|
||||
}
|
||||
func load() throws -> DiskAssignments {
|
||||
let file: FileHandle
|
||||
do { file = try FileHandle(forReadingFrom: url) }
|
||||
catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {
|
||||
return DiskAssignments()
|
||||
}
|
||||
defer { try? file.close() }
|
||||
let bytes = try file.read(upToCount: 65537) ?? Data()
|
||||
guard bytes.count <= 65536 else { throw Failure.invalid }
|
||||
let value = try JSONDecoder().decode(DiskAssignments.self, from: bytes)
|
||||
try value.validate()
|
||||
return value
|
||||
}
|
||||
func save(_ value: DiskAssignments) throws {
|
||||
try value.validate()
|
||||
let bytes = try JSONEncoder().encode(value)
|
||||
guard bytes.count <= 65536 else { throw Failure.invalid }
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try bytes.write(to: url, options: .atomic)
|
||||
}
|
||||
}
|
||||
|
||||
// Stored in the same atomic preferences file as the disk setup. Slot zero is
|
||||
// the single-cartridge configuration; slots 1...4 survive switching modes.
|
||||
struct CartridgeAssignments: Codable, Equatable, Sendable {
|
||||
enum Kind: Int, Codable, Sendable { case empty = 0, rom = 1, floppy = 2, hardDisk = 3, ramDisk = 4, orchestra90 = 5, speechSound = 6, sdc = 7 }
|
||||
struct Slot: Codable, Equatable, Sendable {
|
||||
var kind: Kind = .empty
|
||||
var url: URL?
|
||||
var speechROMURL: URL? // SSC speech chip; url holds its PIC firmware.
|
||||
var sdcFolderURL: URL? // Local folder representing the SD card; never copied into a profile.
|
||||
var sdcReadOnly: Bool? // Older profiles default to protected storage.
|
||||
}
|
||||
var multiPak = false
|
||||
var mpiConfigured = false
|
||||
var physicalSlot = 4
|
||||
var slots = Array(repeating: Slot(), count: 5)
|
||||
private static func localReference(_ url: URL?) -> Bool {
|
||||
guard let url else { return true }
|
||||
guard url.isFileURL, url.path.hasPrefix("/"), url.query == nil, url.fragment == nil else { return false }
|
||||
return url.host == nil || url.host == "" || url.host == "localhost"
|
||||
}
|
||||
private static func validSlot(_ slot: Slot) -> Bool {
|
||||
if slot.kind == .sdc {
|
||||
guard slot.speechROMURL == nil else { return false }
|
||||
return localReference(slot.url) && localReference(slot.sdcFolderURL)
|
||||
}
|
||||
guard slot.sdcFolderURL == nil, slot.sdcReadOnly == nil else { return false }
|
||||
if slot.kind == .speechSound { return localReference(slot.url) && localReference(slot.speechROMURL) }
|
||||
guard slot.speechROMURL == nil else { return false }
|
||||
if slot.kind == .orchestra90 { return localReference(slot.url) }
|
||||
if slot.kind == .rom { return slot.url != nil && localReference(slot.url) }
|
||||
return slot.url == nil
|
||||
}
|
||||
func validate() throws {
|
||||
guard slots.count == 5, (1...4).contains(physicalSlot), slots.allSatisfy(Self.validSlot) else {
|
||||
throw DiskAssignmentStore.Failure.invalid
|
||||
}
|
||||
for kind: Kind in [.floppy, .hardDisk, .ramDisk, .orchestra90, .speechSound, .sdc] {
|
||||
guard slots.dropFirst().filter({ $0.kind == kind }).count <= 1 else {
|
||||
throw DiskAssignmentStore.Failure.invalid
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct HardDiskAssignments: Codable, Equatable, Sendable {
|
||||
var drives: [DiskAssignments.Drive?] = Array(repeating: nil, count: 2)
|
||||
var clockEnabled = true
|
||||
var clockReadOnly = true
|
||||
func validate() throws {
|
||||
guard drives.count == 2 else { throw DiskAssignmentStore.Failure.invalid }
|
||||
for entry in drives {
|
||||
guard let drive = entry else { continue }
|
||||
let url: URL = drive.url
|
||||
guard url.isFileURL, url.path.hasPrefix("/") else {
|
||||
throw DiskAssignmentStore.Failure.invalid
|
||||
}
|
||||
if let host = url.host, !host.isEmpty, host != "localhost" {
|
||||
throw DiskAssignmentStore.Failure.invalid
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import Combine
|
||||
|
||||
struct DiskControlsView: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var controllerExpanded = false
|
||||
private let refresh = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
SecondaryHeader(title: "Floppy Disks", badge: "floppy")
|
||||
SecondaryAction(title: "Open Disk Image…", systemImage: "folder") { DiskImageEditorCoordinator.shared.open(machine: machine) }
|
||||
.accessibilityIdentifier("disk-editor-open-image")
|
||||
}.padding(20)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
connection
|
||||
if machine.diskEnabled {
|
||||
ForEach(Array(machine.disks.enumerated()), id: \.offset) { index, disk in
|
||||
DiskDriveRow(machine: machine, index: index, disk: disk)
|
||||
}
|
||||
}
|
||||
if !machine.diskRestoreErrors.isEmpty {
|
||||
ForEach(machine.diskRestoreErrors.keys.sorted(), id: \.self) { key in
|
||||
Text(machine.diskRestoreErrors[key] ?? "").foregroundStyle(.red).textSelection(.enabled)
|
||||
}
|
||||
SecondaryAction(title: "Retry Remembered Disks", systemImage: "arrow.clockwise", action: machine.retryRememberedDisks)
|
||||
Text("Reconnect the files and retry, or choose replacements. Eject forgets an unavailable drive assignment.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
DisclosureGroup(isExpanded: $controllerExpanded) {
|
||||
controllerDetails.padding(.top, 12)
|
||||
} label: {
|
||||
Label("Controller Details", systemImage: "slider.horizontal.3").font(.callout).fontWeight(.medium)
|
||||
}.accessibilityIdentifier("floppy-controller-details")
|
||||
SecondaryHelp(title: "About floppy disks") {
|
||||
Text("The FD-502 opens DSK, JVC, OS-9, DMK and VDK images. Save As preserves the mounted format.")
|
||||
Text("Writable disks save automatically. Temporary changes stay in memory until Save As. Drive assignments are remembered.")
|
||||
Text("A new blank disk must be formatted by the CoCo. For a 35-track disk in FD0, type DSKINI0 in BASIC. Then choose Save As to create its Mac file and enable automatic saving.")
|
||||
Text("Changing media or save mode pauses emulation. Automatic saves keep emulation running.")
|
||||
}
|
||||
if let error = machine.diskSettingsError {
|
||||
Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).textSelection(.enabled)
|
||||
if machine.diskSettingsNeedsSave { SecondaryAction(title: "Retry Saving", systemImage: "arrow.clockwise", action: machine.saveDiskAssignments) }
|
||||
}
|
||||
if let error = machine.fileError ?? machine.error { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||||
}.padding(20)
|
||||
}
|
||||
Divider()
|
||||
MediaExecutionFooter(machine: machine, note: "Media changes pause the CoCo; press Run to continue.").padding(20)
|
||||
}.frame(minWidth: 700, minHeight: 420)
|
||||
.disabled(machine.busy || machine.diskSaving || machine.diskEditorLocked || machine.state == .closed)
|
||||
.onReceive(refresh) { _ in machine.poll() }
|
||||
}
|
||||
|
||||
@ViewBuilder private var connection: some View {
|
||||
if !machine.diskEnabled {
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label("Choose a disk ROM to enable the FD-502 controller", systemImage: "info.circle")
|
||||
SecondaryAction(title: "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM).disabled(machine.diskBusy)
|
||||
}
|
||||
}
|
||||
} else if !machine.diskConnected {
|
||||
Label("Controller disconnected · Mounted disks are retained", systemImage: "exclamationmark.circle")
|
||||
.font(.callout).foregroundStyle(.orange)
|
||||
SecondaryAction(title: "Configure Cartridges…", systemImage: "slider.horizontal.3") { openWindow(id: "cartridges") }
|
||||
} else {
|
||||
HStack {
|
||||
Label("FD-502 connected", systemImage: "cable.connector")
|
||||
Spacer()
|
||||
Text(machine.diskSaving ? "Saving automatically…" : "Writable disks save automatically")
|
||||
}.font(.caption).foregroundStyle(.secondary).frame(minHeight: 18)
|
||||
}
|
||||
}
|
||||
private var controllerDetails: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("Disk ROM").fontWeight(.medium)
|
||||
Text(machine.diskEnabled ? machine.diskROMName : "Not selected").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
SecondaryAction(title: machine.diskEnabled ? "Change Disk ROM…" : "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM)
|
||||
.disabled(machine.diskBusy)
|
||||
}
|
||||
if machine.diskEnabled {
|
||||
HStack {
|
||||
Text(machine.diskBusy ? "Disk operation in progress" : "Controller ready")
|
||||
Text(machine.diskMotor ? "Motor on" : "Motor off")
|
||||
Spacer()
|
||||
if machine.diskSelectedDrive >= 0 {
|
||||
Text("FD\(machine.diskSelectedDrive) · Track \(machine.diskTrack) · Sector \(machine.diskSector)")
|
||||
.monospacedDigit()
|
||||
}
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
SecondaryAction(title: "Disable Controller…", systemImage: "minus.circle", action: machine.disableDisks)
|
||||
.disabled(machine.dirtyDisks || machine.diskBusy)
|
||||
.accessibilityLabel("Disable floppy controller")
|
||||
Text("Disabling ejects all four disks and cold-restarts the CoCo. Save or discard pending changes first.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
} else if !machine.diskRestoreErrors.isEmpty {
|
||||
SecondaryAction(title: "Forget Remembered Setup…", systemImage: "minus.circle", action: machine.forgetUnavailableDisks)
|
||||
}
|
||||
}.font(.callout)
|
||||
}
|
||||
}
|
||||
|
||||
private struct DiskDriveRow: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
let index: Int
|
||||
let disk: VCCDiskSnapshot
|
||||
@State private var options = false
|
||||
private struct CopySource: Identifiable {
|
||||
let id = UUID()
|
||||
let name: String
|
||||
let epoch: UInt64
|
||||
}
|
||||
@State private var copySource: CopySource?
|
||||
private var assigned: Bool { disk.mounted || machine.diskAssignments.drives[index] != nil }
|
||||
private var manualSave: Bool {
|
||||
disk.dirty && (machine.diskTemporary[index] || machine.diskAssignments.drives[index] == nil || disk.writeProtected || disk.sourceReadOnly)
|
||||
}
|
||||
private var mode: String {
|
||||
if disk.writeProtected { return "Write protected" }
|
||||
if machine.diskTemporary[index] { return "Temporary changes" }
|
||||
return machine.diskAssignments.drives[index] == nil ? "No backing file · Use Save As" : "Saves automatically"
|
||||
}
|
||||
var body: some View {
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack(spacing: 14) {
|
||||
MediaDriveIdentity(name: "FD\(index)", mounted: disk.mounted)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(disk.mounted ? disk.name : machine.diskAssignments.drives[index]?.url.lastPathComponent ?? "No disk inserted")
|
||||
.fontWeight(.semibold).lineLimit(1).truncationMode(.middle)
|
||||
Text(disk.mounted ? "\(disk.tracks) tracks · \(disk.sides) \(disk.sides == 1 ? "side" : "sides") · \(mode)" : assigned ? "Unavailable — reconnect or replace the file" : "Insert an image or create a blank disk")
|
||||
.font(.caption).foregroundStyle(assigned && !disk.mounted ? Color.orange : Color.secondary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
SecondaryAction(title: assigned ? "Replace…" : "Insert…", systemImage: "folder") { machine.openDisk(index) }
|
||||
.disabled(disk.dirty).accessibilityLabel("Insert disk in drive \(index)")
|
||||
if assigned {
|
||||
if disk.mounted {
|
||||
SecondaryAction(title: "Edit…", systemImage: "pencil") { DiskImageEditorCoordinator.shared.edit(index, machine: machine) }
|
||||
.accessibilityIdentifier("floppy-edit-\(index)").accessibilityLabel("Edit…")
|
||||
.help("Edit files inside the disk. The CoCo stays paused and locked until the editor closes.")
|
||||
}
|
||||
SecondaryAction(title: "Eject", systemImage: "eject") { machine.ejectDisk(index) }
|
||||
.disabled(disk.dirty).accessibilityLabel("Eject disk from drive \(index)")
|
||||
} else {
|
||||
newDiskMenu
|
||||
}
|
||||
}
|
||||
if disk.mounted {
|
||||
HStack {
|
||||
DisclosureGroup(isExpanded: $options) { EmptyView() } label: { Text("Disk options").font(.callout) }
|
||||
.accessibilityIdentifier("floppy-options-\(index)")
|
||||
Spacer()
|
||||
actions
|
||||
}
|
||||
if options {
|
||||
HStack(spacing: 24) {
|
||||
Toggle("Write protected", isOn: Binding(get: { disk.writeProtected }, set: { machine.protectDisk(index, $0) }))
|
||||
.disabled(disk.sourceReadOnly || disk.formatWriteProtected).accessibilityLabel("Write protect drive \(index)")
|
||||
.help(disk.formatWriteProtected ? "Write protection is stored in the disk image header." : disk.sourceReadOnly ? "The source file is read-only. Reopen a writable copy to enable writes." : "Prevent the CoCo from changing this disk.")
|
||||
Toggle("Temporary changes", isOn: Binding(get: { machine.diskTemporary[index] }, set: { machine.setDiskTemporary(index, $0) }))
|
||||
.accessibilityLabel("Temporary changes in drive \(index)")
|
||||
Spacer(minLength: 0)
|
||||
}.font(.callout)
|
||||
Text("Temporary changes stay in memory. Turning this off saves pending changes to the assigned writable file. Save As chooses a file and retains this mode.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if manualSave {
|
||||
HStack {
|
||||
Label("Unsaved changes · Save As to keep them", systemImage: "exclamationmark.circle").foregroundStyle(.orange)
|
||||
Spacer()
|
||||
SecondaryAction(title: "Save As…", systemImage: "square.and.arrow.up") { machine.exportDisk(index) }
|
||||
.accessibilityLabel("Save disk from drive \(index) as")
|
||||
}.font(.callout).frame(minHeight: 24)
|
||||
}
|
||||
}
|
||||
if let error = machine.diskSaveErrors[index] {
|
||||
Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled)
|
||||
SecondaryAction(title: "Retry Save", systemImage: "arrow.clockwise") { machine.retryDiskSave(index) }
|
||||
.disabled(machine.diskTemporary[index] || disk.writeProtected).accessibilityLabel("Retry saving drive \(index)")
|
||||
}
|
||||
}
|
||||
}.modifier(MediaDropTarget(machine: machine, destination: .floppy(index)))
|
||||
.sheet(item: $copySource) { source in
|
||||
VCCDriveWireTransferView(machine: machine, drive: index, sourceName: source.name, sourceEpoch: source.epoch)
|
||||
}
|
||||
.disabled(machine.diskBusy)
|
||||
}
|
||||
private var newDiskMenu: some View {
|
||||
Menu {
|
||||
Button("Standard DSK") { machine.createDisk(index) }
|
||||
Button("DMK Track Image") { machine.createDisk(index, format: .trackDMK) }
|
||||
Button("VDK Disk Image") { machine.createDisk(index, format: .sectorVDK) }
|
||||
} label: {
|
||||
Label("New Disk", systemImage: "doc.badge.plus")
|
||||
}
|
||||
.fixedSize().disabled(disk.dirty).accessibilityLabel("New disk in drive \(index)")
|
||||
.accessibilityIdentifier("floppy-new-\(index)")
|
||||
}
|
||||
private var actions: some View {
|
||||
Menu {
|
||||
Button { machine.exportDisk(index) } label: { Label("Save As…", systemImage: "square.and.arrow.up") }
|
||||
.disabled(!disk.mounted).accessibilityLabel("Save disk from drive \(index) as")
|
||||
Button {
|
||||
copySource = CopySource(name: disk.name, epoch: machine.inputEpoch)
|
||||
} label: { Label("Send a Copy to DriveWire…", systemImage: "paperplane") }
|
||||
.disabled(!disk.mounted || machine.busy || machine.diskSaving || machine.diskEditorLocked)
|
||||
.accessibilityIdentifier("floppy-send-copy-\(index)")
|
||||
.help("Send an independent copy of the current disk, including changes in memory, to a running DriveWire session.")
|
||||
newDiskMenu
|
||||
if manualSave || machine.diskSaveErrors[index] != nil {
|
||||
Divider()
|
||||
Button { machine.discardDisk(index) } label: { Label("Discard Changes and Eject…", systemImage: "eject") }
|
||||
.accessibilityLabel("Discard changes in drive \(index)")
|
||||
}
|
||||
} label: { Label("Actions", systemImage: "ellipsis.circle") }
|
||||
.fixedSize().accessibilityIdentifier("floppy-actions-\(index)")
|
||||
}
|
||||
}
|
||||
|
||||
// Shared presentation only; drive and execution commands remain in MachineModel.
|
||||
struct MediaDriveIdentity: View {
|
||||
let name: String
|
||||
let mounted: Bool
|
||||
var body: some View {
|
||||
Text(name).font(.system(.body, design: .monospaced).weight(.semibold))
|
||||
.frame(width: 42, height: 42)
|
||||
.background(mounted ? Color.accentColor.opacity(0.12) : Color.secondary.opacity(0.10), in: RoundedRectangle(cornerRadius: 7))
|
||||
}
|
||||
}
|
||||
|
||||
struct MediaExecutionFooter: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
let note: String
|
||||
var body: some View {
|
||||
HStack(spacing: 12) {
|
||||
SecondaryAction(title: machine.state == .running ? "Pause" : "Run", systemImage: machine.state == .running ? "pause.fill" : "play.fill") {
|
||||
if machine.state == .running { machine.pause() } else { machine.resume() }
|
||||
}.disabled(machine.diskEditorLocked || machine.state == .empty || machine.state == .closed)
|
||||
Text(note).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
Spacer(minLength: 0)
|
||||
Text(machine.executionDescription).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
private let diskEditorMoveType = NSPasteboard.PasteboardType("com.brianholman.vccplus.disk-editor-files")
|
||||
|
||||
/// Bounded diagnostics live only in the isolated UI-test app's own fixture folder.
|
||||
enum DiskEditorPromiseDiagnostics {
|
||||
#if VCC_UI_TESTING
|
||||
private static let lock = NSLock()
|
||||
#endif
|
||||
static func record(_ phase: String) {
|
||||
#if VCC_UI_TESTING
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let path = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_PROMISE_TRACE"] else { return }
|
||||
let url = URL(fileURLWithPath: path)
|
||||
let line = Data((phase + "\n").utf8)
|
||||
if !FileManager.default.fileExists(atPath: path) { _ = FileManager.default.createFile(atPath: path, contents: nil) }
|
||||
guard let handle = try? FileHandle(forWritingTo: url) else { return }
|
||||
defer { try? handle.close() }
|
||||
guard let end = try? handle.seekToEnd(), end < 16_384 else { return }
|
||||
try? handle.write(contentsOf: line)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if VCC_UI_TESTING
|
||||
/// Observe actual mouse delivery without changing native drag eligibility.
|
||||
private final class DiskEditorNativeTableView: NSTableView {
|
||||
var dragTrace: ((String) -> Void)?
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
dragTrace?("mouse-down row=\(row(at: convert(event.locationInWindow, from: nil))) key=\(window?.isKeyWindow ?? false)")
|
||||
super.mouseDown(with: event)
|
||||
}
|
||||
override func canDragRows(with rowIndexes: IndexSet, at mouseDownPoint: NSPoint) -> Bool {
|
||||
let allowed = super.canDragRows(with: rowIndexes, at: mouseDownPoint)
|
||||
dragTrace?("can-drag native=\(allowed) rows=\(rowIndexes)")
|
||||
return allowed
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Native table supplies Finder multi-file promises and accepts ordinary host
|
||||
/// file URLs. Directory navigation stays inside the validated image namespace.
|
||||
struct DiskEditorFileTable: NSViewRepresentable {
|
||||
@ObservedObject var model: DiskImageEditorModel
|
||||
func makeCoordinator() -> Coordinator { Coordinator(model) }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
#if VCC_UI_TESTING
|
||||
let table = DiskEditorNativeTableView()
|
||||
#else
|
||||
let table = NSTableView()
|
||||
#endif
|
||||
table.identifier = NSUserInterfaceItemIdentifier("disk-editor-files")
|
||||
table.setAccessibilityIdentifier("disk-editor-files"); table.allowsMultipleSelection = true
|
||||
table.usesAlternatingRowBackgroundColors = true; table.rowHeight = 25
|
||||
table.delegate = context.coordinator; table.dataSource = context.coordinator
|
||||
table.target = context.coordinator; table.doubleAction = #selector(Coordinator.activate)
|
||||
let coordinator = context.coordinator
|
||||
#if VCC_UI_TESTING
|
||||
table.dragTrace = { [weak coordinator] in coordinator?.trace($0) }
|
||||
#endif
|
||||
table.registerForDraggedTypes([diskEditorMoveType, .fileURL]); table.setDraggingSourceOperationMask(.copy, forLocal: false)
|
||||
table.setDraggingSourceOperationMask(model.os9 ? .move : .copy, forLocal: true)
|
||||
let menu = NSMenu(); menu.delegate = context.coordinator; menu.autoenablesItems = false; table.menu = menu
|
||||
context.coordinator.table = table; context.coordinator.configureColumns()
|
||||
let scroll = NSScrollView(); scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true; scroll.documentView = table
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
context.coordinator.model = model; context.coordinator.update()
|
||||
}
|
||||
@MainActor final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate, NSMenuDelegate {
|
||||
var model: DiskImageEditorModel
|
||||
weak var table: NSTableView?
|
||||
var rows: [DiskEditorEntry] = []
|
||||
var last: [DiskEditorEntry] = []
|
||||
var os9: Bool?
|
||||
private var restoringSelection = false
|
||||
private var dragRequest: DiskEditorMoveRequest?
|
||||
#if VCC_UI_TESTING
|
||||
private var dragTraceCount = 0
|
||||
private var dragTraceLines: [String] = []
|
||||
#endif
|
||||
fileprivate func trace(_ message: @autoclosure () -> String) {
|
||||
#if VCC_UI_TESTING
|
||||
guard dragTraceCount < 250 else { return }; dragTraceCount += 1
|
||||
let line = message()
|
||||
dragTraceLines.append(line)
|
||||
if dragTraceLines.count > 40 { dragTraceLines.removeFirst() }
|
||||
let text = "DiskEditorDrag VCC_UI_TESTING\n" + dragTraceLines.joined(separator: "\n")
|
||||
table?.setAccessibilityHelp(text)
|
||||
table?.setAccessibilityValue(text)
|
||||
NSLog("DiskEditorDrag %@", line)
|
||||
#endif
|
||||
}
|
||||
init(_ model: DiskImageEditorModel) { self.model = model }
|
||||
func configureColumns() {
|
||||
guard let table else { return }
|
||||
for column in table.tableColumns { table.removeTableColumn(column) }
|
||||
let definitions: [(String, CGFloat)] = model.os9
|
||||
? [("Name", 250), ("Size", 95), ("Type", 120), ("Attributes", 110), ("Owner", 80), ("Modified", 150)]
|
||||
: [("Name", 290), ("Size", 110), ("File Type", 200), ("Encoding", 120)]
|
||||
for (title, width) in definitions {
|
||||
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(title)); column.title = title; column.width = width; column.minWidth = title == "Name" ? 160 : 70
|
||||
column.sortDescriptorPrototype = NSSortDescriptor(key: title, ascending: true); table.addTableColumn(column)
|
||||
}
|
||||
table.sortDescriptors = [NSSortDescriptor(key: "Name", ascending: true)]; os9 = model.os9
|
||||
trace("configure os9=\(model.os9) local-mask=\(model.os9 ? "move" : "copy")")
|
||||
}
|
||||
func update() {
|
||||
table?.setDraggingSourceOperationMask(model.os9 ? .move : .copy, forLocal: true)
|
||||
if os9 != model.os9 { configureColumns() }
|
||||
guard last != model.contents.entries else { return }
|
||||
last = model.contents.entries; reload()
|
||||
}
|
||||
func reload() {
|
||||
guard let table else { return }
|
||||
restoringSelection = true
|
||||
defer { restoringSelection = false }
|
||||
let descriptor = table.sortDescriptors.first, key = descriptor?.key ?? "Name", ascending = descriptor?.ascending ?? true
|
||||
rows = model.contents.entries.sorted {
|
||||
let result: ComparisonResult
|
||||
if key == "Size" { result = $0.size == $1.size ? .orderedSame : $0.size < $1.size ? .orderedAscending : .orderedDescending }
|
||||
else if key == "Modified" { result = $0.modified == $1.modified ? .orderedSame : $0.modified < $1.modified ? .orderedAscending : .orderedDescending }
|
||||
else { result = value($0, key).localizedStandardCompare(value($1, key)) }
|
||||
return ascending ? result == .orderedAscending : result == .orderedDescending
|
||||
}
|
||||
// Reloading emits a selection notification. Preserve the selection
|
||||
// before that callback can clear the model's authoritative IDs.
|
||||
let selectedIDs = model.selection
|
||||
table.reloadData()
|
||||
let selection = IndexSet(rows.indices.filter { selectedIDs.contains(rows[$0].id) })
|
||||
table.selectRowIndexes(selection, byExtendingSelection: false)
|
||||
}
|
||||
func numberOfRows(in tableView: NSTableView) -> Int { rows.count }
|
||||
func value(_ entry: DiskEditorEntry, _ key: String) -> String {
|
||||
switch key {
|
||||
case "Name": return entry.name
|
||||
case "Size": return entry.directory ? "—" : ByteCountFormatter.string(fromByteCount: entry.size, countStyle: .file)
|
||||
case "Type", "File Type": return entry.type
|
||||
case "Encoding": return entry.encoding
|
||||
case "Attributes": return entry.attributes
|
||||
case "Owner": return "\(entry.group).\(entry.owner)"
|
||||
case "Modified": return entry.modified > 0 ? Date(timeIntervalSince1970: entry.modified).formatted(date: .abbreviated, time: .shortened) : "—"
|
||||
default: return ""
|
||||
}
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
guard rows.indices.contains(row), let column = tableColumn else { return nil }
|
||||
let entry = rows[row], text = value(entry, column.identifier.rawValue)
|
||||
let cell = NSTableCellView(); let label = NSTextField(labelWithString: text)
|
||||
label.lineBreakMode = .byTruncatingMiddle; label.translatesAutoresizingMaskIntoConstraints = false
|
||||
label.font = column.identifier.rawValue == "Size" ? .monospacedDigitSystemFont(ofSize: 13, weight: .regular) : .systemFont(ofSize: 13)
|
||||
if column.identifier.rawValue == "Size" { label.alignment = .right }
|
||||
cell.textField = label; cell.addSubview(label)
|
||||
if column.identifier.rawValue == "Name" {
|
||||
let icon = NSImageView(image: NSImage(systemSymbolName: entry.directory ? "folder" : "doc", accessibilityDescription: nil) ?? NSImage())
|
||||
icon.translatesAutoresizingMaskIntoConstraints = false; cell.addSubview(icon)
|
||||
NSLayoutConstraint.activate([icon.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5), icon.widthAnchor.constraint(equalToConstant: 17), icon.centerYAnchor.constraint(equalTo: cell.centerYAnchor), label.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6)])
|
||||
} else { label.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 5).isActive = true }
|
||||
NSLayoutConstraint.activate([label.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -7), label.centerYAnchor.constraint(equalTo: cell.centerYAnchor)])
|
||||
return cell
|
||||
}
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
guard !restoringSelection, let table else { return }
|
||||
let selected = Set(table.selectedRowIndexes.compactMap { rows.indices.contains($0) ? rows[$0].id : nil })
|
||||
if model.selection != selected { model.selection = selected }
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { reload() }
|
||||
@objc func activate() {
|
||||
guard !model.busy, let table, rows.indices.contains(table.clickedRow) else { return }
|
||||
model.activate([rows[table.clickedRow].id])
|
||||
}
|
||||
func menuNeedsUpdate(_ menu: NSMenu) {
|
||||
if let table, rows.indices.contains(table.clickedRow), !table.selectedRowIndexes.contains(table.clickedRow) {
|
||||
table.selectRowIndexes(IndexSet(integer: table.clickedRow), byExtendingSelection: false)
|
||||
}
|
||||
menu.removeAllItems()
|
||||
let move = NSMenuItem(title: "Move To…", action: #selector(moveSelected), keyEquivalent: "")
|
||||
move.target = self; move.isEnabled = model.canMove; menu.addItem(move)
|
||||
}
|
||||
@objc private func moveSelected() { model.moveTo() }
|
||||
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
|
||||
trace("writer row=\(row) busy=\(model.busy) os9=\(model.os9) selected=\(tableView.selectedRowIndexes)")
|
||||
guard !model.busy, rows.indices.contains(row), !rows[row].directory else { return nil }
|
||||
if !(dragRequest.map { model.moveSourceIsCurrent($0) } ?? false) {
|
||||
let indexes = tableView.selectedRowIndexes.contains(row) ? tableView.selectedRowIndexes : IndexSet(integer: row)
|
||||
dragRequest = model.moveRequest(for: indexes.compactMap { rows.indices.contains($0) ? rows[$0] : nil })
|
||||
}
|
||||
let payload = dragRequest.flatMap { try? JSONEncoder().encode(DiskEditorDragPayload($0)) }
|
||||
trace("writer request=\(dragRequest?.id.uuidString ?? "none") files=\(dragRequest?.files.count ?? 0) payload=\(payload?.count ?? 0)")
|
||||
return DiskEditorFilePromise.make(bytes: model.contents.bytes, entry: rows[row], machine: model.machine, sourceURL: model.sourceURL, movePayload: payload, volumeID: model.contents.volumeID)
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {
|
||||
let paths = rowIndexes.compactMap { rows.indices.contains($0) ? rows[$0].path : nil }
|
||||
// The advertised payload was frozen when AppKit asked for writers,
|
||||
// before it negotiates destination types. Do not add a type here.
|
||||
if dragRequest?.files.map(\.path) != paths { dragRequest = nil }
|
||||
trace("begin rows=\(rowIndexes) request=\(dragRequest?.id.uuidString ?? "none") types=\(session.draggingPasteboard.types?.map(\.rawValue) ?? [])")
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
|
||||
trace("ended operation=\(operation.rawValue)")
|
||||
dragRequest = nil
|
||||
}
|
||||
private func ownedMove(_ info: NSDraggingInfo) -> DiskEditorMoveRequest? {
|
||||
guard let source = info.draggingSource as? NSTableView else { trace("refuse source-not-table class=\(info.draggingSource.map { String(describing: type(of: $0)) } ?? "nil")"); return nil }
|
||||
guard source === table else { trace("refuse different-table"); return nil }
|
||||
guard let request = dragRequest else { trace("refuse no-request"); return nil }
|
||||
guard model.moveSourceIsCurrent(request) else { trace("refuse stale-source"); return nil }
|
||||
guard let data = info.draggingPasteboard.data(forType: diskEditorMoveType), data.count <= DiskEditorIO.limit else { trace("refuse missing-or-oversized-payload"); return nil }
|
||||
guard let payload = try? JSONDecoder().decode(DiskEditorDragPayload.self, from: data), payload == DiskEditorDragPayload(request) else { trace("refuse mismatched-payload"); return nil }
|
||||
return request
|
||||
}
|
||||
private func destination(in table: NSTableView, for info: NSDraggingInfo) -> (path: String, row: Int)? {
|
||||
// proposedRow describes an insertion boundary, which can be the row
|
||||
// after the folder under the pointer. Folder moves target the row
|
||||
// actually under the pointer, then explicitly use an on-row drop.
|
||||
let row = table.row(at: table.convert(info.draggingLocation, from: nil))
|
||||
if rows.indices.contains(row) { return rows[row].directory ? (rows[row].path, row) : nil }
|
||||
return (model.path, -1)
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation operation: NSTableView.DropOperation) -> NSDragOperation {
|
||||
trace("validate proposed=\(row) operation=\(operation.rawValue) hovered=\(tableView.row(at: tableView.convert(info.draggingLocation, from: nil))) source=\(info.draggingSource.map { String(describing: type(of: $0)) } ?? "nil") types=\(info.draggingPasteboard.types?.map(\.rawValue) ?? [])")
|
||||
guard !model.busy else { return [] }
|
||||
if info.draggingSource is NSTableView || info.draggingPasteboard.availableType(from: [diskEditorMoveType]) != nil {
|
||||
guard let request = ownedMove(info) else { return [] }
|
||||
guard let target = destination(in: tableView, for: info) else { trace("refuse target-not-folder"); return [] }
|
||||
guard target.path.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { trace("refuse same-folder"); return [] }
|
||||
trace("validate move target-row=\(target.row)")
|
||||
tableView.setDropRow(target.row, dropOperation: .on)
|
||||
return .move
|
||||
}
|
||||
tableView.setDropRow(-1, dropOperation: .on); return .copy
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation operation: NSTableView.DropOperation) -> Bool {
|
||||
trace("accept proposed=\(row) operation=\(operation.rawValue)")
|
||||
guard !model.busy else { return false }
|
||||
if info.draggingSource is NSTableView || info.draggingPasteboard.availableType(from: [diskEditorMoveType]) != nil {
|
||||
guard let request = ownedMove(info), let target = destination(in: tableView, for: info), target.path.caseInsensitiveCompare(request.sourcePath) != .orderedSame else { trace("accept refused"); return false }
|
||||
trace("accept move files=\(request.files.count) target-row=\(target.row)")
|
||||
model.move(request, to: target.path); return true
|
||||
}
|
||||
guard let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty else { return false }
|
||||
model.proposeImport(urls); return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum DiskEditorFilePromise {
|
||||
@MainActor static func make(bytes: Data, entry: DiskEditorEntry, machine: any DiskEditorHost, sourceURL: URL?, movePayload: Data? = nil, volumeID: String? = nil) -> NSFilePromiseProvider {
|
||||
let delegate = DiskEditorPromiseDelegate(bytes: bytes, entry: entry, machine: machine, sourceURL: sourceURL, volumeID: volumeID)
|
||||
// Keep ordinary exports on the plain provider. The owned subtype uses
|
||||
// only the designated initializer. Both providers have weak delegates;
|
||||
// documented strong userInfo keeps the immutable snapshot alive.
|
||||
let provider: NSFilePromiseProvider
|
||||
if let movePayload {
|
||||
let owned = DiskEditorOwnedFilePromise(payload: movePayload)
|
||||
owned.fileType = UTType.data.identifier; owned.delegate = delegate; provider = owned
|
||||
} else { provider = NSFilePromiseProvider(fileType: UTType.data.identifier, delegate: delegate) }
|
||||
provider.userInfo = delegate
|
||||
return provider
|
||||
}
|
||||
}
|
||||
/// Advertise the owned move identity before AppKit starts type negotiation.
|
||||
/// Use NSFilePromiseProvider's designated init(), never its convenience init
|
||||
/// which would dispatch back to an unimplemented Swift subclass initializer.
|
||||
private final class DiskEditorOwnedFilePromise: NSFilePromiseProvider {
|
||||
private let payload: Data
|
||||
init(payload: Data) { self.payload = payload; super.init() }
|
||||
override func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] {
|
||||
super.writableTypes(for: pasteboard) + [diskEditorMoveType]
|
||||
}
|
||||
override func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? {
|
||||
type == diskEditorMoveType ? payload : super.pasteboardPropertyList(forType: type)
|
||||
}
|
||||
override func writingOptions(forType type: NSPasteboard.PasteboardType, pasteboard: NSPasteboard) -> NSPasteboard.WritingOptions {
|
||||
type == diskEditorMoveType ? [] : super.writingOptions(forType: type, pasteboard: pasteboard)
|
||||
}
|
||||
}
|
||||
/// Finder can request every selected row concurrently. Chain the complete
|
||||
/// async jobs, rather than only their delegate callbacks, so the shared machine
|
||||
/// guard and snapshot reader are used by one promise at a time.
|
||||
private actor DiskEditorPromiseExports {
|
||||
static let shared = DiskEditorPromiseExports()
|
||||
private var tail: Task<Void, Never>?
|
||||
func write(snapshot: Data, entryPath: String, machine: any DiskEditorHost, source: URL?, destination: URL, volumeID: String?) async throws {
|
||||
let previous = tail
|
||||
let job = Task {
|
||||
await previous?.value
|
||||
DiskEditorPromiseDiagnostics.record("promise snapshot read begin")
|
||||
let reader = try DiskImageEditorStore(data: snapshot, selectedVolumeID: volumeID)
|
||||
let data = try await reader.read(entryPath)
|
||||
DiskEditorPromiseDiagnostics.record("promise snapshot read complete; await machine export")
|
||||
try await machine.savePromisedDiskEditorExport(data, to: destination, protecting: source)
|
||||
}
|
||||
tail = Task { _ = try? await job.value }
|
||||
try await job.value
|
||||
}
|
||||
}
|
||||
private final class DiskEditorPromiseDelegate: NSObject, NSFilePromiseProviderDelegate {
|
||||
let bytes: Data, entry: DiskEditorEntry
|
||||
let volumeID: String?
|
||||
let machine: any DiskEditorHost, sourceURL: URL?
|
||||
private let queue: OperationQueue = { let q = OperationQueue(); q.maxConcurrentOperationCount = 1; return q }()
|
||||
init(bytes: Data, entry: DiskEditorEntry, machine: any DiskEditorHost, sourceURL: URL?, volumeID: String?) { self.bytes = bytes; self.entry = entry; self.machine = machine; self.sourceURL = sourceURL; self.volumeID = volumeID }
|
||||
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String { DiskEditorPromiseDiagnostics.record("promise filename"); return entry.name }
|
||||
func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue { queue }
|
||||
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) {
|
||||
// A Finder promise may be fulfilled after another edit or after closing
|
||||
// this window. Its immutable snapshot is the version the user dragged.
|
||||
DiskEditorPromiseDiagnostics.record("promise write entered")
|
||||
let snapshot = bytes, entryPath = entry.path, machine = machine, source = sourceURL, selectedVolume = volumeID
|
||||
Task.detached {
|
||||
do {
|
||||
try await DiskEditorPromiseExports.shared.write(snapshot: snapshot, entryPath: entryPath,
|
||||
machine: machine, source: source, destination: url, volumeID: selectedVolume)
|
||||
DiskEditorPromiseDiagnostics.record("promise export complete")
|
||||
completionHandler(nil)
|
||||
} catch { DiskEditorPromiseDiagnostics.record("promise export error"); completionHandler(error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// An immutable copy of a mounted disk; mutations belong to the editor only.
|
||||
struct DiskEditorSession: Sendable {
|
||||
let id: UUID
|
||||
let token: UInt64
|
||||
let drive: Int
|
||||
let name: String
|
||||
let data: Data
|
||||
let canApply: Bool
|
||||
let sourceURL: URL?
|
||||
let temporary: Bool
|
||||
let applyRestriction: String?
|
||||
let hardDisk: Bool
|
||||
|
||||
init(id: UUID, token: UInt64, drive: Int, name: String, data: Data, canApply: Bool,
|
||||
sourceURL: URL?, temporary: Bool, applyRestriction: String?, hardDisk: Bool = false) {
|
||||
self.id = id; self.token = token; self.drive = drive; self.name = name; self.data = data
|
||||
self.canApply = canApply; self.sourceURL = sourceURL; self.temporary = temporary
|
||||
self.applyRestriction = applyRestriction; self.hardDisk = hardDisk
|
||||
}
|
||||
var driveLabel: String { "\(hardDisk ? "HD" : "FD")\(drive)" }
|
||||
}
|
||||
|
||||
|
||||
/// The editor owns its working copy and native interface. Each application owns
|
||||
/// media identity, guest exclusion, restart policy and the final atomic commit.
|
||||
@MainActor
|
||||
protocol DiskEditorHost: AnyObject {
|
||||
func beginDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession
|
||||
func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession
|
||||
func cancelDiskEditor(_ session: DiskEditorSession) async throws
|
||||
func applyDiskEditor(_ session: DiskEditorSession, data: Data, restartConfirmed: Bool) async throws
|
||||
func saveDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws
|
||||
func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws
|
||||
func savePromisedDiskEditorExport(_ data: Data, to url: URL, protecting sourceURL: URL?) async throws
|
||||
func saveOfflineDiskEditor(_ data: Data, to url: URL, replacing original: Data) async throws
|
||||
func mountedEditorDrive(for url: URL) -> Int?
|
||||
func mountedHardDiskEditorDrive(for url: URL) -> Int?
|
||||
func diskEditorSourceIsAssigned(_ url: URL) -> Bool
|
||||
func diskEditorPresentation(for session: DiskEditorSession?) -> DiskEditorPresentation
|
||||
}
|
||||
|
||||
struct DiskEditorPresentation {
|
||||
let context: String
|
||||
let applyHint: String
|
||||
let applyButtonTitle: String
|
||||
let applyConfirmationTitle: String
|
||||
let applyConfirmationMessage: String
|
||||
let applyConfirmationAction: String
|
||||
let closeNotice: String
|
||||
}
|
||||
|
||||
extension DiskEditorHost {
|
||||
func beginHardDiskEditor(inDrive drive: Int) async throws -> DiskEditorSession {
|
||||
throw DiskEditorFailure.message("Hard-disk editing is unavailable in this application.")
|
||||
}
|
||||
func mountedHardDiskEditorDrive(for url: URL) -> Int? { nil }
|
||||
func saveDiskEditorImageCopy(_ data: Data, to url: URL, protecting sourceURL: URL?, replacing expected: Data?, requireNew: Bool) async throws {
|
||||
try await saveDiskEditorExport(data, to: url, protecting: sourceURL, replacing: expected, requireNew: requireNew)
|
||||
}
|
||||
func diskEditorPresentation(for session: DiskEditorSession?) -> DiskEditorPresentation {
|
||||
DiskEditorPresentation(
|
||||
context: session.map { "\($0.driveLabel) · CoCo paused and locked" } ?? "Unmounted image · CoCo unchanged",
|
||||
applyHint: session == nil ? "Edits remain in a private copy until saved." : "Applying changes requires a CoCo restart.",
|
||||
applyButtonTitle: session.map { "Apply to \($0.driveLabel)…" } ?? "Save Changes…",
|
||||
applyConfirmationTitle: session == nil ? "Save changes to this disk image?" : "Apply disk changes and restart the CoCo?",
|
||||
applyConfirmationMessage: session == nil ? "The original image will be replaced only if its bytes have not changed outside the editor." : "Restarting clears the running guest program and its memory so it cannot reuse old filesystem information. Mounted media and edited disk bytes are retained. Save any program or recording you need before applying.",
|
||||
applyConfirmationAction: session == nil ? "Save Changes" : "Restart and Apply",
|
||||
closeNotice: "Apply your disk changes, save an edited copy, or close the Disk Image Editor. The machine remains paused while its disk is locked.")
|
||||
}
|
||||
}
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
extension MachineModel: DiskEditorHost { }
|
||||
#endif
|
||||
|
||||
/// Editor-local limits keep the shared source independent of emulator ROM and
|
||||
/// cartridge helpers. The reader is the same bounded import reader as the editor.
|
||||
enum DiskEditorIO {
|
||||
static let limit = 16 * 1024 * 1024
|
||||
static let imageLimit = 512 * 1024 * 1024
|
||||
static let extensions = ["dsk", "jvc", "os9", "dmk", "vdk", "vhd", "img"]
|
||||
|
||||
/// Run off the main actor. Both apps use this exact identity/compare/write
|
||||
/// implementation; application-specific media command guards remain outside.
|
||||
static func write(_ bytes: Data, to url: URL, protecting references: [URL],
|
||||
allowEmpty: Bool = false, replacing expected: Data? = nil,
|
||||
requireNew: Bool = false, coordinated: Bool = true, maximum: Int = limit) throws {
|
||||
try validateExport(bytes, to: url, allowEmpty: allowEmpty, maximum: maximum)
|
||||
if !coordinated {
|
||||
try writeValidated(bytes, to: url, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew, maximum: maximum)
|
||||
return
|
||||
}
|
||||
var coordinationError: NSError?
|
||||
var writeError: Error?
|
||||
DiskEditorPromiseDiagnostics.record("development export before coordinate")
|
||||
NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in
|
||||
DiskEditorPromiseDiagnostics.record("development export inside coordinate")
|
||||
do { try writeValidated(bytes, to: target, protecting: references, allowEmpty: allowEmpty, replacing: expected, requireNew: requireNew, maximum: maximum) }
|
||||
catch { writeError = error }
|
||||
}
|
||||
if let error = coordinationError ?? writeError as NSError? { throw error }
|
||||
}
|
||||
private static func validateExport(_ bytes: Data, to url: URL, allowEmpty: Bool, maximum: Int) throws {
|
||||
guard url.isFileURL, (allowEmpty || !bytes.isEmpty), bytes.count <= maximum else {
|
||||
throw DiskEditorFailure.message("Choose a regular file within the \(maximum / (1024 * 1024)) MiB export limit.")
|
||||
}
|
||||
}
|
||||
private static func writeValidated(_ bytes: Data, to url: URL, protecting references: [URL],
|
||||
allowEmpty: Bool, replacing expected: Data?, requireNew: Bool, maximum: Int) throws {
|
||||
try validateExport(bytes, to: url, allowEmpty: allowEmpty, maximum: maximum)
|
||||
let path = url.standardizedFileURL.resolvingSymlinksInPath().path
|
||||
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
|
||||
if let attributes, attributes[.type] as? FileAttributeType != .typeRegular {
|
||||
throw DiskEditorFailure.message("Choose a regular disk image or disk ROM file.")
|
||||
}
|
||||
if attributes != nil, !FileManager.default.isWritableFile(atPath: url.path) {
|
||||
throw DiskEditorFailure.message("The disk file is no longer writable. Restore write access and retry, or use Save As.")
|
||||
}
|
||||
let inode = attributes?[.systemFileNumber] as? NSNumber
|
||||
let volume = attributes?[.systemNumber] as? NSNumber
|
||||
for reference in references {
|
||||
let resolved = reference.standardizedFileURL.resolvingSymlinksInPath()
|
||||
let other = try? FileManager.default.attributesOfItem(atPath: resolved.path)
|
||||
let sameIdentity = inode != nil && volume != nil &&
|
||||
inode == other?[.systemFileNumber] as? NSNumber && volume == other?[.systemNumber] as? NSNumber
|
||||
let inside = other?[.type] as? FileAttributeType == .typeDirectory && path.hasPrefix(resolved.path + "/")
|
||||
if path == resolved.path || sameIdentity || inside {
|
||||
throw DiskEditorFailure.message("Choose a separate file outside your assigned media and source document. To replace a mounted disk or cassette, eject it first using its normal media controls.")
|
||||
}
|
||||
}
|
||||
if let expected {
|
||||
guard attributes != nil, try DiskImageEditorStore.hostBytes(url, maximum: maximum) == expected else {
|
||||
throw DiskEditorFailure.message("This source file changed on disk. Reload it or save a separate copy.")
|
||||
}
|
||||
}
|
||||
try bytes.write(to: url, options: requireNew ? .withoutOverwriting : .atomic)
|
||||
}
|
||||
struct Image: Sendable { let data: Data; let readOnly: Bool }
|
||||
static func readImage(_ url: URL) throws -> Image {
|
||||
guard extensions.contains(url.pathExtension.lowercased()) else {
|
||||
throw DiskEditorFailure.message("Choose a DSK, JVC, OS-9, DMK, VDK, raw VHD or IMG disk image.")
|
||||
}
|
||||
let bytes = try DiskImageEditorStore.hostBytes(url, maximum: imageLimit)
|
||||
return Image(data: bytes, readOnly: !FileManager.default.isWritableFile(atPath: url.path))
|
||||
}
|
||||
}
|
||||
|
||||
enum DiskEditorFailure: LocalizedError {
|
||||
case message(String)
|
||||
var errorDescription: String? { switch self { case .message(let text): text } }
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
enum DiskFiles {
|
||||
static let extensions = ["dsk", "jvc", "os9", "dmk", "vdk"]
|
||||
static let limit = 16 * 1024 * 1024
|
||||
struct Image: Sendable { let data: Data; let readOnly: Bool }
|
||||
enum Failure: LocalizedError {
|
||||
case notFile, tooLarge, extensionType, romSize, changed, readOnly, cartridgeROM, orchestraROM
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .orchestraROM: return "Choose an 8 KiB Orchestra-90 ROM. The stereo sound hardware can also be used without a ROM."
|
||||
case .cartridgeROM: return "Choose a raw cartridge ROM (1 byte to 256 KiB), not a Windows DLL or a disk image."
|
||||
case .notFile: return "Choose a regular disk image or disk ROM file."
|
||||
case .tooLarge: return "Disk images must be no larger than 16 MiB."
|
||||
case .extensionType: return "Choose a DSK, JVC, OS-9, DMK or VDK floppy disk image."
|
||||
case .romSize: return "Choose an 8 or 16 KiB disk ROM, such as disk11.rom. The CoCo 3 system ROM is selected separately."
|
||||
case .changed: return "The disk file changed outside this drive. Use Save As to keep your changes in a separate file, or reinsert the disk."
|
||||
case .readOnly: return "The disk file is no longer writable. Restore write access and retry, or use Save As."
|
||||
}
|
||||
}
|
||||
}
|
||||
private static func read(_ url: URL, limit: Int) throws -> Data {
|
||||
guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile }
|
||||
let file = try FileHandle(forReadingFrom: url)
|
||||
defer { try? file.close() }
|
||||
var bytes = Data()
|
||||
while bytes.count <= limit {
|
||||
guard let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - bytes.count)), !chunk.isEmpty else { break }
|
||||
bytes.append(chunk)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
static func readROM(_ url: URL) throws -> Data {
|
||||
let bytes = try read(url, limit: 16384)
|
||||
guard bytes.count == 8192 || bytes.count == 16384 else { throw Failure.romSize }
|
||||
return bytes
|
||||
}
|
||||
static func readCartridgeROM(_ url: URL) throws -> Data {
|
||||
guard !extensions.contains(url.pathExtension.lowercased()), !["dll", "exe"].contains(url.pathExtension.lowercased()) else { throw Failure.cartridgeROM }
|
||||
let bytes = try read(url, limit: 262144)
|
||||
guard !bytes.isEmpty, bytes.count <= 262144, !bytes.starts(with: [0x4d, 0x5a]) else { throw Failure.cartridgeROM }
|
||||
return bytes
|
||||
}
|
||||
static func readOrchestraROM(_ url: URL) throws -> Data {
|
||||
let bytes = try readCartridgeROM(url)
|
||||
guard bytes.count == 8192 else { throw Failure.orchestraROM }
|
||||
return bytes
|
||||
}
|
||||
static func readSpeechChipROM(_ url: URL, speech: Bool) throws -> Data {
|
||||
let size = speech ? 2048 : 4096
|
||||
let bytes = try read(url, limit: size)
|
||||
guard bytes.count == size else {
|
||||
throw ProfileFailure.message(speech ? "Choose the 2 KiB SP0256-AL2 speech ROM." : "Choose the 4 KiB PIC7040 firmware ROM.")
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
static func readSDCROM(_ url: URL) throws -> Data {
|
||||
let bytes = try readCartridgeROM(url)
|
||||
guard bytes.count == 8192 || bytes.count == 16384 else {
|
||||
throw ProfileFailure.message("Choose an 8 or 16 KiB SDC-DOS ROM. The CoCo system ROM and FD-502 disk ROM are separate.")
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
static func validateSDCFolder(_ url: URL) throws {
|
||||
guard url.isFileURL, try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true,
|
||||
FileManager.default.isReadableFile(atPath: url.path) else {
|
||||
throw ProfileFailure.message("The SD card folder is unavailable. Reconnect it or choose its new location in Cartridges.")
|
||||
}
|
||||
}
|
||||
static func readCartridgeAssignment(_ slot: CartridgeAssignments.Slot) throws -> Data {
|
||||
if slot.kind == .sdc {
|
||||
guard let rom = slot.url, let folder = slot.sdcFolderURL else {
|
||||
throw ProfileFailure.message("CoCo SDC needs an SDC-DOS ROM and an SD card folder. Choose both in Cartridges.")
|
||||
}
|
||||
try validateSDCFolder(folder)
|
||||
return try readSDCROM(rom)
|
||||
}
|
||||
if slot.kind == .speechSound {
|
||||
guard let pic = slot.url, let speech = slot.speechROMURL else {
|
||||
throw ProfileFailure.message("Speech/Sound needs both its PIC firmware and speech ROM. Choose both files in Cartridges.")
|
||||
}
|
||||
return try readSpeechChipROM(pic, speech: false) + readSpeechChipROM(speech, speech: true)
|
||||
}
|
||||
guard let url = slot.url else { return Data() }
|
||||
return try slot.kind == .orchestra90 ? readOrchestraROM(url) : readCartridgeROM(url)
|
||||
}
|
||||
static func readImage(_ url: URL) throws -> Image {
|
||||
guard extensions.contains(url.pathExtension.lowercased()) else { throw Failure.extensionType }
|
||||
let bytes = try read(url, limit: limit)
|
||||
guard bytes.count <= limit else { throw Failure.tooLarge }
|
||||
return Image(data: bytes, readOnly: !FileManager.default.isWritableFile(atPath: url.path))
|
||||
}
|
||||
/// A separate BASIC export must not bypass mounted-media write protection,
|
||||
/// pending saves, temporary changes or source-document conflict handling.
|
||||
static func exportBASIC(_ bytes: Data, to url: URL, protecting references: [URL]) throws {
|
||||
try writeDevelopmentFile(bytes, to: url, protecting: references)
|
||||
}
|
||||
|
||||
static func writeDevelopmentFile(_ bytes: Data, to url: URL, protecting references: [URL],
|
||||
allowEmpty: Bool = false, replacing expected: Data? = nil,
|
||||
requireNew: Bool = false) throws {
|
||||
try DiskEditorIO.write(bytes, to: url, protecting: references, allowEmpty: allowEmpty,
|
||||
replacing: expected, requireNew: requireNew)
|
||||
}
|
||||
/// File promises already own destination coordination through completion.
|
||||
static func writeReceivedFilePromise(_ bytes: Data, to url: URL, protecting references: [URL]) throws {
|
||||
try DiskEditorIO.write(bytes, to: url, protecting: references, allowEmpty: true,
|
||||
requireNew: true, coordinated: false)
|
||||
}
|
||||
static func export(_ bytes: Data, to url: URL) throws {
|
||||
try bytes.write(to: url, options: .atomic)
|
||||
}
|
||||
// Coordinate with cooperating document apps and compare with the last bytes
|
||||
// we read/wrote. Never recreate a missing source or overwrite external edits.
|
||||
static func saveAutomatically(_ bytes: Data, to url: URL, expected: Data) throws {
|
||||
var coordinationError: NSError?
|
||||
var writeError: Error?
|
||||
NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in
|
||||
do {
|
||||
// The selected .dsk may be a symlink to a differently named file.
|
||||
let current = try read(target, limit: limit)
|
||||
guard current.count <= limit else { throw Failure.tooLarge }
|
||||
guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly }
|
||||
guard current == expected else { throw Failure.changed }
|
||||
try export(bytes, to: target)
|
||||
} catch { writeError = error }
|
||||
}
|
||||
if let error = coordinationError { throw error }
|
||||
if let error = writeError { throw error }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Combine
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct DiskEditorEntry: Identifiable, Hashable, Sendable {
|
||||
let name: String, path: String, type: String, encoding: String, attributes: String
|
||||
let size: Int64, modified: TimeInterval
|
||||
let directory: Bool
|
||||
let owner: Int, group: Int, permissions: Int
|
||||
var id: String { path }
|
||||
init(_ value: [String: Any]) {
|
||||
name = value["name"] as? String ?? ""; path = value["path"] as? String ?? name
|
||||
type = value["type"] as? String ?? ""; encoding = value["encoding"] as? String ?? ""
|
||||
attributes = value["attributes"] as? String ?? ""
|
||||
size = (value["size"] as? NSNumber)?.int64Value ?? 0
|
||||
modified = (value["modified"] as? NSNumber)?.doubleValue ?? 0
|
||||
directory = value["is_directory"] as? Bool ?? false
|
||||
owner = (value["owner"] as? NSNumber)?.intValue ?? 0
|
||||
group = (value["group"] as? NSNumber)?.intValue ?? 0
|
||||
permissions = (value["permissions"] as? NSNumber)?.intValue ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskEditorVolume: Identifiable, Hashable, Sendable {
|
||||
let id: String, name: String, format: String
|
||||
let offset: Int64, byteCount: Int64
|
||||
init(_ value: [String: Any]) {
|
||||
id = value["id"] as? String ?? ""; name = value["name"] as? String ?? "Volume"
|
||||
format = value["format"] as? String ?? ""
|
||||
offset = (value["offset_bytes"] as? NSNumber)?.int64Value ?? 0
|
||||
byteCount = (value["byte_count"] as? NSNumber)?.int64Value ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskEditorContents: Sendable {
|
||||
let entries: [DiskEditorEntry]
|
||||
let bytes: Data
|
||||
let format: String
|
||||
let capacity: Int64?, used: Int64?, free: Int64?
|
||||
let preservedBytes: Int64
|
||||
let volumes: [DiskEditorVolume]
|
||||
let volumeID: String
|
||||
}
|
||||
|
||||
/// Retained C libraries and working-image I/O never run on the main actor.
|
||||
actor DiskImageEditorStore {
|
||||
let directory: URL
|
||||
private let image: URL
|
||||
private let volume: URL
|
||||
private var volumeID: String
|
||||
init(data: Data, selectedVolumeID: String? = nil) throws {
|
||||
guard !data.isEmpty, data.count <= DiskEditorIO.imageLimit else { throw DiskEditorFailure.message("Choose a disk image within the 512 MiB limit.") }
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCDiskEditor-" + UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
directory = folder; image = folder.appendingPathComponent("Working.dsk")
|
||||
volume = folder.appendingPathComponent("Volume.dsk"); volumeID = ""
|
||||
do {
|
||||
try data.write(to: image, options: .atomic)
|
||||
let discovered = try VCCDiskImageEditorBackend.discoverVolumes(at: image).map(DiskEditorVolume.init)
|
||||
guard let chosen = selectedVolumeID ?? discovered.first?.id,
|
||||
discovered.contains(where: { $0.id == chosen }) else { throw DiskEditorFailure.message("The selected volume is unavailable in this image.") }
|
||||
volumeID = chosen
|
||||
try VCCDiskImageEditorBackend.extractVolume(chosen, imageURL: image, outputURL: volume)
|
||||
}
|
||||
catch { try? FileManager.default.removeItem(at: folder); throw error }
|
||||
}
|
||||
deinit {
|
||||
let folder = directory
|
||||
Task.detached { try? FileManager.default.removeItem(at: folder) }
|
||||
}
|
||||
func contents(at path: String) throws -> DiskEditorContents {
|
||||
let info = try VCCDiskImageEditorBackend.inspectImage(at: volume)
|
||||
let rows = try VCCDiskImageEditorBackend.listDirectory(path, imageURL: volume)
|
||||
let volumes = try VCCDiskImageEditorBackend.discoverVolumes(at: image).map(DiskEditorVolume.init)
|
||||
let bytes = try Data(contentsOf: image)
|
||||
let selectedSize = volumes.first(where: { $0.id == volumeID })?.byteCount ?? 0
|
||||
return DiskEditorContents(entries: rows.map(DiskEditorEntry.init), bytes: bytes,
|
||||
format: info["format"] as? String ?? "",
|
||||
capacity: (info["capacity_bytes"] as? NSNumber)?.int64Value,
|
||||
used: (info["used_bytes"] as? NSNumber)?.int64Value,
|
||||
free: (info["free_bytes"] as? NSNumber)?.int64Value,
|
||||
preservedBytes: Int64(bytes.count) - selectedSize, volumes: volumes, volumeID: volumeID)
|
||||
}
|
||||
func selectVolume(_ id: String) throws -> DiskEditorContents {
|
||||
let previous = volumeID
|
||||
do {
|
||||
try VCCDiskImageEditorBackend.extractVolume(id, imageURL: image, outputURL: volume)
|
||||
volumeID = id
|
||||
return try contents(at: "")
|
||||
} catch {
|
||||
try? VCCDiskImageEditorBackend.extractVolume(previous, imageURL: image, outputURL: volume)
|
||||
volumeID = previous
|
||||
throw error
|
||||
}
|
||||
}
|
||||
func restore(_ bytes: Data, path: String) throws -> DiskEditorContents {
|
||||
let before = try Data(contentsOf: image)
|
||||
do {
|
||||
try bytes.write(to: image, options: .atomic)
|
||||
try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume)
|
||||
return try contents(at: path)
|
||||
} catch {
|
||||
try before.write(to: image, options: .atomic)
|
||||
try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
enum Change: Sendable {
|
||||
case importFiles([URL], type: Int, ascii: Bool, replace: Bool)
|
||||
case folder(String)
|
||||
case rename(String, String)
|
||||
case delete([DiskEditorEntry])
|
||||
case os9Metadata(String, permissions: Int, ownerUser: Int, ownerGroup: Int)
|
||||
case moveFiles([String], String)
|
||||
}
|
||||
func change(_ change: Change, path: String) throws -> DiskEditorContents {
|
||||
let before = try Data(contentsOf: image)
|
||||
do {
|
||||
switch change {
|
||||
case let .importFiles(urls, type, ascii, replace):
|
||||
for url in urls {
|
||||
let data = try Self.hostBytes(url)
|
||||
try VCCDiskImageEditorBackend.importData(data, named: url.lastPathComponent, directory: path,
|
||||
imageURL: volume, fileType: type, ascii: ascii, replace: replace)
|
||||
}
|
||||
case let .folder(name): try VCCDiskImageEditorBackend.makeDirectory(name, in: path, imageURL: volume)
|
||||
case let .rename(old, name): try VCCDiskImageEditorBackend.renameEntry(old, to: name, imageURL: volume)
|
||||
case let .delete(entries):
|
||||
for entry in entries { try VCCDiskImageEditorBackend.deleteEntry(entry.path, directory: entry.directory, imageURL: volume) }
|
||||
case let .os9Metadata(path, permissions, user, group):
|
||||
try VCCDiskImageEditorBackend.setOS9Metadata(for: path, imageURL: volume, ownerUser: user, ownerGroup: group, permissions: permissions)
|
||||
case let .moveFiles(files, destination):
|
||||
try VCCDiskImageEditorBackend.moveFiles(files, toDirectory: destination, imageURL: volume)
|
||||
}
|
||||
try VCCDiskImageEditorBackend.replaceVolume(volumeID, imageURL: image, volumeURL: volume)
|
||||
return try contents(at: path)
|
||||
} catch {
|
||||
// ToolShed edits only the expendable working image. A short write
|
||||
// or full disk must not leave even this session half-mutated.
|
||||
try before.write(to: image, options: .atomic)
|
||||
try VCCDiskImageEditorBackend.extractVolume(volumeID, imageURL: image, outputURL: volume)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
func read(_ path: String) throws -> Data { try VCCDiskImageEditorBackend.readFile(path, imageURL: volume) }
|
||||
func info(_ path: String) throws -> String { try VCCDiskImageEditorBackend.identifyFile(path, imageURL: volume) }
|
||||
static func hostBytes(_ url: URL, maximum: Int = DiskEditorIO.limit) throws -> Data {
|
||||
guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw DiskEditorFailure.message("Import regular files, not folders.") }
|
||||
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
||||
var data = Data()
|
||||
while let chunk = try handle.read(upToCount: min(65536, maximum + 1 - data.count)), !chunk.isEmpty {
|
||||
data.append(chunk)
|
||||
guard data.count <= maximum else { throw DiskEditorFailure.message("This file exceeds the \(maximum / (1024 * 1024)) MiB limit.") }
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskEditorImportRequest: Identifiable {
|
||||
let id = UUID()
|
||||
let urls: [URL]
|
||||
var type: Int = 3
|
||||
var ascii = true
|
||||
}
|
||||
struct DiskEditorNameRequest: Identifiable {
|
||||
let id = UUID()
|
||||
let entry: DiskEditorEntry?
|
||||
var name: String
|
||||
}
|
||||
struct DiskEditorInformation: Identifiable {
|
||||
let id = UUID()
|
||||
let entry: DiskEditorEntry
|
||||
let details: String
|
||||
}
|
||||
struct DiskEditorMoveRequest: Identifiable, Sendable {
|
||||
let id = UUID()
|
||||
let editorID: UUID, revision: UUID, sessionID: UUID
|
||||
let sourcePath: String
|
||||
let files: [DiskEditorEntry]
|
||||
let bytes: Data
|
||||
}
|
||||
struct DiskEditorDragPayload: Codable, Equatable {
|
||||
let editorID: UUID, revision: UUID, sessionID: UUID
|
||||
let sourcePath: String, files: [String]
|
||||
init(_ request: DiskEditorMoveRequest) {
|
||||
editorID = request.editorID; revision = request.revision; sessionID = request.sessionID
|
||||
sourcePath = request.sourcePath; files = request.files.map(\.path)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class DiskImageEditorModel: ObservableObject {
|
||||
let editorID = UUID()
|
||||
private(set) var revision = UUID()
|
||||
let store: DiskImageEditorStore
|
||||
let machine: any DiskEditorHost
|
||||
let session: DiskEditorSession?
|
||||
let sourceURL: URL?
|
||||
let name: String
|
||||
let original: Data
|
||||
let sourceReadOnly: Bool
|
||||
weak var window: NSWindow?
|
||||
@Published private(set) var contents: DiskEditorContents
|
||||
@Published var selection = Set<String>()
|
||||
@Published private(set) var path = ""
|
||||
@Published private(set) var busy = false
|
||||
@Published var error: String?
|
||||
@Published var notice: String?
|
||||
@Published var importing: DiskEditorImportRequest?
|
||||
@Published var naming: DiskEditorNameRequest?
|
||||
@Published var information: DiskEditorInformation?
|
||||
@Published var moving: DiskEditorMoveRequest?
|
||||
@Published private(set) var undoStates: [Data] = []
|
||||
@Published private(set) var redoStates: [Data] = []
|
||||
private var backPaths: [String] = []
|
||||
var onFinished: (() -> Void)?
|
||||
var changed: Bool { contents.bytes != original }
|
||||
var selected: [DiskEditorEntry] { contents.entries.filter { selection.contains($0.id) } }
|
||||
var os9: Bool { contents.format == "os9" }
|
||||
var canApply: Bool { session?.canApply ?? !sourceReadOnly }
|
||||
var presentation: DiskEditorPresentation { machine.diskEditorPresentation(for: session) }
|
||||
var displayPath: String { "/" + path }
|
||||
var canBack: Bool { !backPaths.isEmpty }
|
||||
var canMove: Bool { os9 && !busy && !selected.isEmpty && selected.count <= 4096 && selected.allSatisfy { !$0.directory } }
|
||||
|
||||
init(store: DiskImageEditorStore, machine: any DiskEditorHost, session: DiskEditorSession?, sourceURL: URL?,
|
||||
name: String, original: Data, contents: DiskEditorContents, sourceReadOnly: Bool) {
|
||||
self.store = store; self.machine = machine; self.session = session; self.sourceURL = sourceURL
|
||||
self.name = name; self.original = original; self.contents = contents; self.sourceReadOnly = sourceReadOnly
|
||||
}
|
||||
private func accept(_ value: DiskEditorContents) {
|
||||
if value.bytes != contents.bytes { revision = UUID() }
|
||||
contents = value; selection.formIntersection(Set(value.entries.map(\.id)))
|
||||
}
|
||||
func moveRequest(for files: [DiskEditorEntry]) -> DiskEditorMoveRequest? {
|
||||
guard os9, !busy, !files.isEmpty, files.count <= 4096, files.allSatisfy({ !$0.directory && contents.entries.contains($0) }),
|
||||
Set(files.map(\.id)).count == files.count else { return nil }
|
||||
return DiskEditorMoveRequest(editorID: editorID, revision: revision, sessionID: session?.id ?? editorID,
|
||||
sourcePath: path, files: files, bytes: contents.bytes)
|
||||
}
|
||||
func moveSourceIsCurrent(_ request: DiskEditorMoveRequest) -> Bool {
|
||||
os9 && request.editorID == editorID && request.revision == revision && request.sessionID == (session?.id ?? editorID) &&
|
||||
request.sourcePath == path && request.bytes == contents.bytes && request.files.allSatisfy { !$0.directory && contents.entries.contains($0) }
|
||||
}
|
||||
func moveTo() {
|
||||
guard let request = moveRequest(for: selected) else { return }
|
||||
error = nil
|
||||
moving = request
|
||||
}
|
||||
func moveDestination(_ request: DiskEditorMoveRequest, path destination: String) async throws -> DiskEditorContents {
|
||||
guard moveSourceIsCurrent(request), !busy else { throw DiskEditorFailure.message("The disk or source folder changed. Close Move To and select the files again.") }
|
||||
let result = try await store.contents(at: destination)
|
||||
try Task.checkCancellation()
|
||||
guard moveSourceIsCurrent(request), !busy, result.bytes == request.bytes else {
|
||||
throw DiskEditorFailure.message("The disk changed while choosing a folder. Close Move To and select the files again.")
|
||||
}
|
||||
return result
|
||||
}
|
||||
func move(_ request: DiskEditorMoveRequest, to destination: String, expectedDestination: DiskEditorContents? = nil) {
|
||||
guard !busy else { return }
|
||||
guard moveSourceIsCurrent(request) else { error = "The dragged files or disk changed. Select the files again before moving them."; return }
|
||||
guard destination.caseInsensitiveCompare(request.sourcePath) != .orderedSame else {
|
||||
error = "These files are already in this folder. Choose a different destination."; return
|
||||
}
|
||||
work {
|
||||
let target = try await self.store.contents(at: destination)
|
||||
guard self.moveSourceIsCurrent(request), target.bytes == request.bytes,
|
||||
expectedDestination.map({ $0.bytes == target.bytes && $0.entries == target.entries }) ?? true else {
|
||||
throw DiskEditorFailure.message("The disk or destination changed. Choose the destination again.")
|
||||
}
|
||||
let names = Set(target.entries.map { $0.name.lowercased() })
|
||||
if let collision = request.files.first(where: { names.contains($0.name.lowercased()) }) {
|
||||
throw DiskEditorFailure.message("The destination already contains \(collision.name). Rename it or choose another folder; moving never overwrites files.")
|
||||
}
|
||||
try await self.commit(.moveFiles(request.files.map(\.path), destination))
|
||||
self.moving = nil
|
||||
self.notice = "Moved \(request.files.count) \(request.files.count == 1 ? "file" : "files") to /\(destination). Undo is available."
|
||||
}
|
||||
}
|
||||
private func work(_ operation: @escaping () async throws -> Void) {
|
||||
guard !busy else { return }; busy = true; error = nil; notice = nil
|
||||
Task { do { try await operation() } catch { self.error = error.localizedDescription }; self.busy = false }
|
||||
}
|
||||
func selectVolume(_ id: String) {
|
||||
guard !busy, id != contents.volumeID else { return }
|
||||
work {
|
||||
let value = try await self.store.selectVolume(id)
|
||||
self.revision = UUID(); self.path = ""; self.backPaths = []; self.selection = []
|
||||
self.moving = nil; self.information = nil; self.naming = nil; self.importing = nil
|
||||
self.accept(value)
|
||||
}
|
||||
}
|
||||
func refresh() {
|
||||
work { self.accept(try await self.store.contents(at: self.path)) }
|
||||
}
|
||||
func navigate(_ next: String, remember: Bool = true) {
|
||||
work {
|
||||
let value = try await self.store.contents(at: next)
|
||||
if remember { self.backPaths.append(self.path) }
|
||||
self.path = next; self.selection = []; self.accept(value)
|
||||
}
|
||||
}
|
||||
func back() { guard let next = backPaths.popLast() else { return }; navigate(next, remember: false) }
|
||||
func up() { navigate(path.split(separator: "/").dropLast().joined(separator: "/")) }
|
||||
func activate(_ ids: Set<String>) {
|
||||
selection = ids
|
||||
guard let entry = selected.first, selected.count == 1 else { return }
|
||||
if entry.directory { navigate(entry.path) } else { export() }
|
||||
}
|
||||
func change(_ change: DiskImageEditorStore.Change) {
|
||||
work { try await self.commit(change) }
|
||||
}
|
||||
private func commit(_ change: DiskImageEditorStore.Change) async throws {
|
||||
let before = contents.bytes
|
||||
let value = try await store.change(change, path: path)
|
||||
if value.bytes != before {
|
||||
undoStates.append(before); redoStates.removeAll()
|
||||
while undoStates.count > 1 && (undoStates.count > 32 || undoStates.reduce(0, { $0 + $1.count }) > 64 * 1024 * 1024) { undoStates.removeFirst() }
|
||||
}
|
||||
accept(value)
|
||||
}
|
||||
private func confirm(_ alert: NSAlert, accepting response: NSApplication.ModalResponse = .alertFirstButtonReturn) async -> Bool {
|
||||
guard let window else { return false }
|
||||
return await withCheckedContinuation { continuation in
|
||||
alert.beginSheetModal(for: window) { continuation.resume(returning: $0 == response) }
|
||||
}
|
||||
}
|
||||
func undo() {
|
||||
guard !busy, let bytes = undoStates.last else { return }
|
||||
let current = contents.bytes
|
||||
work {
|
||||
let value = try await self.restoreNavigable(bytes)
|
||||
self.undoStates.removeLast(); self.redoStates.append(current); self.accept(value)
|
||||
}
|
||||
}
|
||||
func redo() {
|
||||
guard !busy, let bytes = redoStates.last else { return }
|
||||
let current = contents.bytes
|
||||
work {
|
||||
let value = try await self.restoreNavigable(bytes)
|
||||
self.redoStates.removeLast(); self.undoStates.append(current); self.accept(value)
|
||||
}
|
||||
}
|
||||
private func restoreNavigable(_ bytes: Data) async throws -> DiskEditorContents {
|
||||
// Undoing creation of the currently open folder returns to the root.
|
||||
do { return try await store.restore(bytes, path: path) }
|
||||
catch {
|
||||
let value = try await store.restore(bytes, path: "")
|
||||
path = ""; backPaths = []; return value
|
||||
}
|
||||
}
|
||||
func chooseImport() {
|
||||
let panel = NSOpenPanel(); panel.title = "Import Files into Disk Image"; panel.canChooseDirectories = false; panel.allowsMultipleSelection = true
|
||||
guard let window else { return }
|
||||
panel.beginSheetModal(for: window) { response in
|
||||
guard response == .OK else { return }
|
||||
Task { @MainActor in self.proposeImport(panel.urls) }
|
||||
}
|
||||
}
|
||||
func proposeImport(_ urls: [URL]) {
|
||||
guard !busy, !urls.isEmpty else { return }
|
||||
guard urls.count <= 72 else { error = "Import at most 72 files at once."; return }
|
||||
var request = DiskEditorImportRequest(urls: urls)
|
||||
let ext = urls.first?.pathExtension.lowercased() ?? ""
|
||||
request.type = ext == "bas" ? 0 : ext == "dat" ? 1 : ["txt", "asc"].contains(ext) ? 3 : 2
|
||||
request.ascii = ["bas", "txt", "asc"].contains(ext)
|
||||
importing = request
|
||||
}
|
||||
func importNeedsReplacement(_ urls: [URL]) -> Bool {
|
||||
// Both filesystem readers compare ASCII names without casing; use the
|
||||
// same identity when deciding whether replacement consent is needed.
|
||||
let names = Set(contents.entries.map { $0.name.lowercased() })
|
||||
return urls.contains { names.contains($0.lastPathComponent.lowercased()) }
|
||||
}
|
||||
func confirmImport(_ request: DiskEditorImportRequest) {
|
||||
importing = nil
|
||||
let collisions = importNeedsReplacement(request.urls)
|
||||
work {
|
||||
if collisions {
|
||||
let alert = NSAlert(); alert.messageText = "Replace existing files?"; alert.informativeText = "The selected names already exist in this directory. Replacement changes only the editor's working copy until you apply it."
|
||||
alert.addButton(withTitle: "Replace"); alert.addButton(withTitle: "Cancel")
|
||||
guard await self.confirm(alert) else { return }
|
||||
}
|
||||
try await self.commit(.importFiles(request.urls, type: request.type, ascii: request.ascii, replace: collisions))
|
||||
}
|
||||
}
|
||||
func newFolder() { naming = DiskEditorNameRequest(entry: nil, name: "") }
|
||||
func rename() { guard selected.count == 1, let entry = selected.first else { return }; naming = DiskEditorNameRequest(entry: entry, name: entry.name) }
|
||||
func confirmName(_ request: DiskEditorNameRequest) {
|
||||
naming = nil
|
||||
if let entry = request.entry { change(.rename(entry.path, request.name)) } else { change(.folder(request.name)) }
|
||||
}
|
||||
func delete() {
|
||||
let entries = selected; guard !entries.isEmpty else { return }
|
||||
let alert = NSAlert(); alert.messageText = entries.count == 1 ? "Delete \(entries[0].name)?" : "Delete \(entries.count) entries?"
|
||||
alert.informativeText = "This changes the working copy. Undo is available until the editor closes. Nonempty folders must be emptied first."
|
||||
alert.addButton(withTitle: "Delete"); alert.addButton(withTitle: "Cancel")
|
||||
work {
|
||||
guard await self.confirm(alert) else { return }
|
||||
try await self.commit(.delete(entries))
|
||||
}
|
||||
}
|
||||
func showInfo() {
|
||||
guard selected.count == 1, let entry = selected.first else { return }
|
||||
work {
|
||||
var text = "\(entry.name)\n\(entry.type)\n\(ByteCountFormatter.string(fromByteCount: entry.size, countStyle: .file))"
|
||||
if !entry.directory && self.os9 {
|
||||
do {
|
||||
let data = try await self.store.read(entry.path)
|
||||
if data.starts(with: [0x87, 0xcd]) || data.starts(with: [0x4a, 0xfc]) {
|
||||
do { text += "\n\n" + (try await self.store.info(entry.path)) }
|
||||
catch { text += "\n\nModule information unavailable: " + error.localizedDescription }
|
||||
}
|
||||
} catch { text += "\n\nContent inspection unavailable: " + error.localizedDescription }
|
||||
}
|
||||
self.information = DiskEditorInformation(entry: entry, details: text)
|
||||
}
|
||||
}
|
||||
func applyInformation(_ info: DiskEditorInformation, permissions: Int, ownerUser: Int, ownerGroup: Int) {
|
||||
guard os9, (0...127).contains(permissions), (0...255).contains(ownerUser), (0...255).contains(ownerGroup) else {
|
||||
error = "Choose valid OS-9 access flags and group/user values from 0 to 255."; return
|
||||
}
|
||||
guard contents.entries.first(where: { $0.id == info.entry.id }) == info.entry else {
|
||||
error = "This entry changed. Close File Information and open it again before saving."; return
|
||||
}
|
||||
work {
|
||||
try await self.commit(.os9Metadata(info.entry.path, permissions: permissions, ownerUser: ownerUser, ownerGroup: ownerGroup))
|
||||
self.information = nil
|
||||
}
|
||||
}
|
||||
func export() {
|
||||
let files = selected.filter { !$0.directory }; guard !files.isEmpty, let window else { return }
|
||||
let snapshot = contents.bytes, volumeID = contents.volumeID
|
||||
if files.count == 1 {
|
||||
let panel = NSSavePanel(); panel.title = "Export Disk File"; panel.nameFieldStringValue = files[0].name
|
||||
panel.beginSheetModal(for: window) { response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
Task { @MainActor in self.export(files, targets: [url], snapshot: snapshot, volumeID: volumeID) }
|
||||
}
|
||||
} else {
|
||||
let panel = NSOpenPanel(); panel.title = "Choose Export Folder"; panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true
|
||||
panel.beginSheetModal(for: window) { response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
Task { @MainActor in self.export(files, targets: files.map { url.appendingPathComponent($0.name) }, snapshot: snapshot, volumeID: volumeID, confirmReplacement: true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func export(_ entries: [DiskEditorEntry], targets: [URL], snapshot: Data, volumeID: String, confirmReplacement: Bool = false) {
|
||||
work {
|
||||
let existing = try await Task.detached { try targets.map { url -> Data? in
|
||||
if FileManager.default.fileExists(atPath: url.path) { return try DiskImageEditorStore.hostBytes(url) }
|
||||
return nil
|
||||
} }.value
|
||||
if confirmReplacement && existing.contains(where: { $0 != nil }) {
|
||||
let alert = NSAlert(); alert.messageText = "Replace exported files?"
|
||||
alert.informativeText = "Some filenames already exist in the selected folder. Replace those files with the selected disk files?"
|
||||
alert.addButton(withTitle: "Replace"); alert.addButton(withTitle: "Cancel")
|
||||
guard await self.confirm(alert) else { return }
|
||||
}
|
||||
let reader = try await Task.detached { try DiskImageEditorStore(data: snapshot, selectedVolumeID: volumeID) }.value
|
||||
for (index, pair) in zip(entries, targets).enumerated() {
|
||||
let (entry, target) = pair
|
||||
let data = try await reader.read(entry.path)
|
||||
try await self.machine.saveDiskEditorExport(data, to: target, protecting: self.sourceURL,
|
||||
replacing: existing[index], requireNew: existing[index] == nil)
|
||||
}
|
||||
self.notice = "Exported \(entries.count) \(entries.count == 1 ? "file" : "files")."
|
||||
}
|
||||
}
|
||||
func saveCopy() {
|
||||
guard let window else { return }
|
||||
let panel = NSSavePanel(); panel.title = "Save Edited Disk Copy"; let ext = sourceURL?.pathExtension.lowercased() ?? (session?.hardDisk == true ? "vhd" : "dsk")
|
||||
panel.nameFieldStringValue = ((name as NSString).deletingPathExtension) + " Edited." + ext
|
||||
panel.allowedContentTypes = [UTType(filenameExtension: ext) ?? .data]
|
||||
panel.beginSheetModal(for: window) { response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
Task { @MainActor in
|
||||
self.work {
|
||||
let existing = try await Task.detached { () -> Data? in
|
||||
if FileManager.default.fileExists(atPath: url.path) { return try DiskImageEditorStore.hostBytes(url, maximum: DiskEditorIO.imageLimit) }
|
||||
return nil
|
||||
}.value
|
||||
try await self.saveCopy(to: url, replacing: existing)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func saveCopy(to url: URL, replacing expected: Data?) async throws {
|
||||
let data = contents.bytes
|
||||
try await machine.saveDiskEditorImageCopy(data, to: url, protecting: sourceURL,
|
||||
replacing: expected, requireNew: expected == nil)
|
||||
notice = "Saved edited copy. The original disk is unchanged."
|
||||
}
|
||||
func apply() {
|
||||
guard !busy, changed, canApply else { return }
|
||||
let alert = NSAlert()
|
||||
alert.messageText = presentation.applyConfirmationTitle
|
||||
alert.informativeText = presentation.applyConfirmationMessage
|
||||
alert.addButton(withTitle: presentation.applyConfirmationAction); alert.addButton(withTitle: "Cancel")
|
||||
work {
|
||||
guard await self.confirm(alert) else { return }
|
||||
if let session = self.session {
|
||||
try await self.machine.applyDiskEditor(session, data: self.contents.bytes, restartConfirmed: true)
|
||||
} else {
|
||||
guard let source = self.sourceURL else { throw DiskEditorFailure.message("The source image is unavailable. Save an edited copy instead.") }
|
||||
try await self.machine.saveOfflineDiskEditor(self.contents.bytes, to: source, replacing: self.original)
|
||||
}
|
||||
self.onFinished?()
|
||||
}
|
||||
}
|
||||
func close() {
|
||||
guard !busy else { return }
|
||||
work {
|
||||
if self.changed {
|
||||
let alert = NSAlert(); alert.messageText = "Discard unapplied disk edits?"
|
||||
alert.informativeText = "The original disk is unchanged. Any separately exported files or edited copy you saved are kept."
|
||||
alert.addButton(withTitle: "Keep Editing"); alert.addButton(withTitle: "Discard Changes")
|
||||
guard await self.confirm(alert, accepting: .alertSecondButtonReturn) else { return }
|
||||
}
|
||||
if let session = self.session { try await self.machine.cancelDiskEditor(session) }
|
||||
self.onFinished?()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class DiskImageEditorCoordinator: NSObject, NSWindowDelegate {
|
||||
static let shared = DiskImageEditorCoordinator()
|
||||
private var editor: DiskImageEditorModel?
|
||||
private var window: NSWindow?
|
||||
private var opening = false
|
||||
func edit(_ drive: Int, machine: any DiskEditorHost) {
|
||||
guard !opening, editor == nil else { window?.makeKeyAndOrderFront(nil); return }
|
||||
opening = true
|
||||
Task {
|
||||
var acquired: DiskEditorSession?
|
||||
do {
|
||||
let session = try await machine.beginDiskEditor(inDrive: drive); acquired = session
|
||||
try await present(data: session.data, name: session.name, source: session.sourceURL, session: session, machine: machine, sourceReadOnly: !session.canApply)
|
||||
} catch {
|
||||
if let acquired { try? await machine.cancelDiskEditor(acquired) }
|
||||
showError(error)
|
||||
}
|
||||
opening = false
|
||||
}
|
||||
}
|
||||
func editHardDisk(_ drive: Int, machine: any DiskEditorHost) {
|
||||
guard !opening, editor == nil else { window?.makeKeyAndOrderFront(nil); return }
|
||||
opening = true
|
||||
Task {
|
||||
var acquired: DiskEditorSession?
|
||||
do {
|
||||
let session = try await machine.beginHardDiskEditor(inDrive: drive); acquired = session
|
||||
try await present(data: session.data, name: session.name, source: session.sourceURL, session: session, machine: machine, sourceReadOnly: !session.canApply)
|
||||
} catch {
|
||||
if let acquired { try? await machine.cancelDiskEditor(acquired) }
|
||||
showError(error)
|
||||
}
|
||||
opening = false
|
||||
}
|
||||
}
|
||||
func open(machine: any DiskEditorHost) {
|
||||
guard editor == nil, !opening else { window?.makeKeyAndOrderFront(nil); return }
|
||||
let panel = NSOpenPanel(); panel.title = "Open Disk Image for Editing"; panel.allowedContentTypes = DiskEditorIO.extensions.compactMap { UTType(filenameExtension: $0) }
|
||||
panel.canChooseDirectories = false
|
||||
panel.begin { response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
Task { @MainActor in self.open(url, machine: machine) }
|
||||
}
|
||||
}
|
||||
func open(_ url: URL, machine: any DiskEditorHost) {
|
||||
guard editor == nil, !opening else { window?.makeKeyAndOrderFront(nil); return }
|
||||
if let drive = machine.mountedEditorDrive(for: url) { edit(drive, machine: machine); return }
|
||||
if let drive = machine.mountedHardDiskEditorDrive(for: url) { editHardDisk(drive, machine: machine); return }
|
||||
guard !machine.diskEditorSourceIsAssigned(url) else {
|
||||
showError(DiskEditorFailure.message("This image is assigned to another device or an SD card folder. Eject or remove that assignment before opening it in Disk Image Editor."))
|
||||
return
|
||||
}
|
||||
opening = true
|
||||
Task {
|
||||
do {
|
||||
let image = try await Task.detached { try DiskEditorIO.readImage(url) }.value
|
||||
try await present(data: image.data, name: url.lastPathComponent, source: url, session: nil, machine: machine, sourceReadOnly: image.readOnly)
|
||||
} catch { showError(error) }
|
||||
opening = false
|
||||
}
|
||||
}
|
||||
private func present(data: Data, name: String, source: URL?, session: DiskEditorSession?, machine: any DiskEditorHost, sourceReadOnly: Bool) async throws {
|
||||
let store = try await Task.detached { try DiskImageEditorStore(data: data) }.value
|
||||
let contents = try await store.contents(at: "")
|
||||
let model = DiskImageEditorModel(store: store, machine: machine, session: session, sourceURL: source, name: name, original: data, contents: contents, sourceReadOnly: sourceReadOnly)
|
||||
var size = NSSize(width: 1050, height: 700)
|
||||
#if VCC_UI_TESTING
|
||||
// Exercise the real compact layout without relying on a synthetic
|
||||
// WindowServer edge-drag gesture. Never enabled in the normal app.
|
||||
if CommandLine.arguments.contains("--disk-editor-compact-fixture") { size = NSSize(width: 760, height: 448) }
|
||||
#endif
|
||||
let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
|
||||
window.title = "Disk Image Editor"; window.subtitle = name; window.isReleasedWhenClosed = false; window.delegate = self
|
||||
let content = NSHostingView(rootView: DiskImageEditorView(model: model))
|
||||
// This AppKit window owns its minimum size. Inferred hosting constraints
|
||||
// must not pin the initial table dimensions and prevent shrinking.
|
||||
content.sizingOptions = []
|
||||
window.contentView = content; window.minSize = NSSize(width: 760, height: 480)
|
||||
model.window = window
|
||||
model.onFinished = { [weak self, weak window] in window?.delegate = nil; window?.close(); self?.window = nil; self?.editor = nil }
|
||||
self.window = window; editor = model; window.center(); window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
func windowShouldClose(_ sender: NSWindow) -> Bool { editor?.close(); return false }
|
||||
func prepareToQuit() -> Bool {
|
||||
guard editor != nil || opening else { return true }
|
||||
window?.makeKeyAndOrderFront(nil)
|
||||
let alert = NSAlert(); alert.messageText = "Finish disk editing before quitting"
|
||||
alert.informativeText = editor?.presentation.closeNotice ?? "Finish opening the Disk Image Editor before quitting."
|
||||
alert.addButton(withTitle: "Return to Editor")
|
||||
if let window { alert.beginSheetModal(for: window) } else { alert.runModal() }
|
||||
return false
|
||||
}
|
||||
private func showError(_ error: Error) {
|
||||
let alert = NSAlert(); alert.messageText = "Cannot open Disk Image Editor"; alert.informativeText = error.localizedDescription
|
||||
if let parent = NSApp.keyWindow ?? NSApp.mainWindow { alert.beginSheetModal(for: parent) } else { alert.runModal() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
struct DiskImageEditorView: View {
|
||||
@ObservedObject var model: DiskImageEditorModel
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
actionBar
|
||||
Divider()
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Label(model.name, systemImage: "externaldrive").font(.headline)
|
||||
if model.contents.volumes.count > 1 {
|
||||
Picker("Volume", selection: Binding(get: { model.contents.volumeID }, set: { model.selectVolume($0) })) {
|
||||
ForEach(model.contents.volumes) { volume in Text(volume.name).tag(volume.id) }
|
||||
}.frame(maxWidth: 420).disabled(model.busy)
|
||||
.accessibilityIdentifier("disk-editor-volume")
|
||||
.help("Choose a filesystem within this image. Other volumes and unrecognized regions stay unchanged.")
|
||||
}
|
||||
Text(model.displayPath).font(.callout.monospaced()).foregroundStyle(.secondary)
|
||||
.accessibilityIdentifier("disk-editor-path")
|
||||
if model.session != nil {
|
||||
Label(model.presentation.context, systemImage: "lock.fill")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
} else { Text(model.presentation.context).font(.caption).foregroundStyle(.secondary) }
|
||||
if model.contents.preservedBytes > 0 {
|
||||
Text("Outside selected volume: \(space(model.contents.preservedBytes)) · Preserved unchanged")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
.accessibilityIdentifier("disk-editor-preserved-data")
|
||||
.help("Other volumes and extra data are preserved. Total, Used and Free describe only the selected filesystem.")
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
if model.changed { Text("Unapplied changes").font(.caption).foregroundStyle(.secondary) }
|
||||
if model.busy { ProgressView().controlSize(.small).accessibilityLabel("Working with disk image") }
|
||||
}.padding(16)
|
||||
Divider()
|
||||
DiskEditorFileTable(model: model).accessibilityIdentifier("disk-editor-files")
|
||||
if let error = model.error {
|
||||
HStack(alignment: .top) {
|
||||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red).textSelection(.enabled)
|
||||
Spacer(); Button("Dismiss") { model.error = nil }
|
||||
}.font(.callout).padding(12).accessibilityIdentifier("disk-editor-error")
|
||||
} else if let notice = model.notice { Text(notice).font(.callout).frame(maxWidth: .infinity, alignment: .leading).padding(12) }
|
||||
Divider()
|
||||
HStack {
|
||||
Text(model.os9 ? "OS-9 RBF" : "Disk BASIC")
|
||||
Text("· \(model.contents.entries.count) \(model.contents.entries.count == 1 ? "entry" : "entries")")
|
||||
Spacer()
|
||||
Text("Total \(space(model.contents.capacity)) Used \(space(model.contents.used)) Free \(space(model.contents.free))")
|
||||
.monospacedDigit().accessibilityIdentifier("disk-editor-space")
|
||||
.help(model.os9 ? "Volume capacity and allocated/free space from the OS-9 allocation bitmap." : "Allocatable file space from the Disk BASIC granule map. The reserved directory track is excluded.")
|
||||
}.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16).padding(.vertical, 10)
|
||||
Divider()
|
||||
HStack {
|
||||
if !model.canApply {
|
||||
Label(model.session?.applyRestriction ?? "The original is read-only. Save an edited copy to keep changes.", systemImage: "lock")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
} else {
|
||||
Text(model.presentation.applyHint)
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Button("Close") { model.close() }.accessibilityIdentifier("disk-editor-close")
|
||||
Button("Save Edited Copy…") { model.saveCopy() }.accessibilityIdentifier("disk-editor-save-copy")
|
||||
Button(model.presentation.applyButtonTitle) { model.apply() }
|
||||
.disabled(!model.changed || !model.canApply).accessibilityIdentifier("disk-editor-apply")
|
||||
}.padding(14).disabled(model.busy)
|
||||
}
|
||||
.frame(minWidth: 760, minHeight: 440)
|
||||
.sheet(item: $model.importing) { request in DiskEditorImportSheet(model: model, request: request) }
|
||||
.sheet(item: $model.naming) { request in DiskEditorNameSheet(model: model, request: request) }
|
||||
.sheet(item: $model.information) { information in DiskEditorInformationSheet(model: model, information: information) }
|
||||
.sheet(item: $model.moving) { request in DiskEditorMoveSheet(model: model, request: request) }
|
||||
}
|
||||
// This window is hosted directly in AppKit. Keep its actions in the content
|
||||
// rather than relying on a SwiftUI scene to install an NSToolbar.
|
||||
private var actionBar: some View {
|
||||
HStack(spacing: 8) {
|
||||
HStack(spacing: 4) {
|
||||
action("Back", "chevron.left", "disk-editor-back", disabled: !model.canBack) { model.back() }
|
||||
action("Up", "arrow.up", "disk-editor-up", disabled: model.path.isEmpty) { model.up() }
|
||||
action("Refresh", "arrow.clockwise", "disk-editor-refresh") { model.refresh() }
|
||||
}
|
||||
Divider().frame(height: 22)
|
||||
HStack(spacing: 4) {
|
||||
action("Import", "square.and.arrow.down", "disk-editor-import") { model.chooseImport() }
|
||||
action("Export", "square.and.arrow.up", "disk-editor-export", disabled: !model.selected.contains(where: { !$0.directory })) { model.export() }
|
||||
action("New Folder", "folder.badge.plus", "disk-editor-new-folder", disabled: !model.os9) { model.newFolder() }
|
||||
action("Rename", "pencil", "disk-editor-rename", disabled: model.selected.count != 1) { model.rename() }
|
||||
action("Move To…", "folder", "disk-editor-move", disabled: !model.canMove) { model.moveTo() }
|
||||
.help("Move selected regular files to another folder in this OS-9 image.")
|
||||
action("Delete", "trash", "disk-editor-delete", disabled: model.selected.isEmpty) { model.delete() }
|
||||
action("Info", "info.circle", "disk-editor-info", disabled: model.selected.count != 1) { model.showInfo() }
|
||||
}
|
||||
Spacer(minLength: 12)
|
||||
HStack(spacing: 4) {
|
||||
Button { model.undo() } label: { Label("Undo", systemImage: "arrow.uturn.backward") }
|
||||
.keyboardShortcut("z", modifiers: .command).help("Undo disk edit").accessibilityIdentifier("disk-editor-undo")
|
||||
.accessibilityLabel("Undo")
|
||||
.disabled(model.busy || model.undoStates.isEmpty)
|
||||
Button { model.redo() } label: { Label("Redo", systemImage: "arrow.uturn.forward") }
|
||||
.keyboardShortcut("z", modifiers: [.command, .shift]).help("Redo disk edit").accessibilityIdentifier("disk-editor-redo")
|
||||
.accessibilityLabel("Redo")
|
||||
.disabled(model.busy || model.redoStates.isEmpty)
|
||||
}
|
||||
}.labelStyle(.iconOnly).buttonStyle(.bordered).padding(.horizontal, 14).padding(.vertical, 10)
|
||||
}
|
||||
private func space(_ value: Int64?) -> String {
|
||||
guard let value else { return "Unavailable" }
|
||||
return ByteCountFormatter.string(fromByteCount: value, countStyle: .file)
|
||||
}
|
||||
private func action(_ name: String, _ symbol: String, _ id: String, disabled: Bool = false, perform: @escaping () -> Void) -> some View {
|
||||
Button(action: perform) { Label(name, systemImage: symbol) }.help(name)
|
||||
.accessibilityLabel(name).accessibilityIdentifier(id).disabled(model.busy || disabled)
|
||||
}
|
||||
}
|
||||
|
||||
private struct DiskEditorMoveSheet: View {
|
||||
@ObservedObject var model: DiskImageEditorModel
|
||||
let request: DiskEditorMoveRequest
|
||||
@State private var destination: String
|
||||
@State private var selectedFolder: String?
|
||||
@State private var contents: DiskEditorContents?
|
||||
@State private var loading = true
|
||||
@State private var error: String?
|
||||
init(model: DiskImageEditorModel, request: DiskEditorMoveRequest) {
|
||||
self.model = model; self.request = request
|
||||
_destination = State(initialValue: request.sourcePath)
|
||||
}
|
||||
private func open(_ path: String) { destination = path; selectedFolder = nil; model.error = nil }
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Text("Move \(request.files.count == 1 ? request.files[0].name : "\(request.files.count) files")").font(.headline)
|
||||
Text("Choose a folder inside this OS-9 image. Existing files are never replaced.")
|
||||
.font(.callout).foregroundStyle(.secondary)
|
||||
HStack {
|
||||
Button("Root", systemImage: "externaldrive") { open("") }.accessibilityIdentifier("disk-editor-move-root")
|
||||
Button("Up", systemImage: "arrow.up") { open(destination.split(separator: "/").dropLast().joined(separator: "/")) }
|
||||
.disabled(destination.isEmpty).keyboardShortcut(.upArrow, modifiers: .command).accessibilityIdentifier("disk-editor-move-up")
|
||||
Text("/" + destination).font(.callout.monospaced()).lineLimit(1).truncationMode(.middle).help("/" + destination)
|
||||
.accessibilityLabel("Destination folder").accessibilityValue("/" + destination).accessibilityIdentifier("disk-editor-move-path")
|
||||
Spacer()
|
||||
if loading { ProgressView().controlSize(.small) }
|
||||
}
|
||||
List(selection: $selectedFolder) {
|
||||
ForEach(contents?.entries.filter(\.directory) ?? []) { folder in
|
||||
Label(folder.name, systemImage: "folder").frame(maxWidth: .infinity, alignment: .leading)
|
||||
.contentShape(Rectangle()).tag(folder.path)
|
||||
.accessibilityIdentifier("disk-editor-move-folder-" + folder.path)
|
||||
.onTapGesture(count: 2) { open(folder.path) }
|
||||
}
|
||||
}.accessibilityLabel("Folders in destination directory").accessibilityIdentifier("disk-editor-move-folders")
|
||||
if let message = error ?? model.error {
|
||||
Label(message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.red)
|
||||
.fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("disk-editor-move-error")
|
||||
}
|
||||
HStack {
|
||||
Button("Open Folder") { if let path = selectedFolder { open(path) } }
|
||||
.disabled(loading || selectedFolder == nil).keyboardShortcut(.downArrow, modifiers: .command)
|
||||
.accessibilityIdentifier("disk-editor-move-open")
|
||||
Spacer()
|
||||
Button("Cancel") { model.moving = nil }.keyboardShortcut(.cancelAction).accessibilityIdentifier("disk-editor-move-cancel")
|
||||
Button("Move Here") { model.move(request, to: destination, expectedDestination: contents) }
|
||||
.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-move-confirm")
|
||||
.disabled(loading || contents == nil || destination.caseInsensitiveCompare(request.sourcePath) == .orderedSame || !model.moveSourceIsCurrent(request))
|
||||
}
|
||||
}.padding(20).frame(width: 540, height: 420).disabled(model.busy)
|
||||
.task(id: destination + "/" + model.revision.uuidString) {
|
||||
loading = true; contents = nil; error = nil
|
||||
do { contents = try await model.moveDestination(request, path: destination) }
|
||||
catch { if !Task.isCancelled { self.error = error.localizedDescription } }
|
||||
if !Task.isCancelled { loading = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DiskEditorInformationSheet: View {
|
||||
@ObservedObject var model: DiskImageEditorModel
|
||||
let information: DiskEditorInformation
|
||||
@State private var permissions: Int
|
||||
@State private var ownerUser: String
|
||||
@State private var ownerGroup: String
|
||||
|
||||
init(model: DiskImageEditorModel, information: DiskEditorInformation) {
|
||||
self.model = model
|
||||
self.information = information
|
||||
_permissions = State(initialValue: information.entry.permissions & 0x7f)
|
||||
_ownerUser = State(initialValue: String(information.entry.owner))
|
||||
_ownerGroup = State(initialValue: String(information.entry.group))
|
||||
}
|
||||
private func ownerID(_ text: String) -> Int? {
|
||||
guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }),
|
||||
let value = Int(text), (0...255).contains(value) else { return nil }
|
||||
return value
|
||||
}
|
||||
private var valid: Bool { ownerID(ownerUser) != nil && ownerID(ownerGroup) != nil }
|
||||
private var changed: Bool {
|
||||
permissions != (information.entry.permissions & 0x7f) ||
|
||||
ownerID(ownerUser) != information.entry.owner || ownerID(ownerGroup) != information.entry.group
|
||||
}
|
||||
private func access(_ title: String, bit: Int, id: String) -> some View {
|
||||
Toggle(title, isOn: Binding(get: { permissions & bit != 0 }, set: { enabled in
|
||||
if enabled { permissions |= bit } else { permissions &= ~bit }
|
||||
})).toggleStyle(.checkbox).accessibilityIdentifier(id)
|
||||
.accessibilityLabel(bit <= 4 ? "Owner \(title)" : bit <= 32 ? "Public \(title)" : title)
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("File Information").font(.headline)
|
||||
Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) {
|
||||
GridRow { Text("Name").foregroundStyle(.secondary); Text(information.entry.name).textSelection(.enabled) }
|
||||
GridRow { Text("Path").foregroundStyle(.secondary); Text("/" + information.entry.path).textSelection(.enabled) }
|
||||
GridRow { Text("Entry type").foregroundStyle(.secondary); Text(information.entry.directory ? "Directory" : "File").accessibilityIdentifier("disk-editor-info-directory") }
|
||||
GridRow { Text("Type").foregroundStyle(.secondary); Text(information.entry.type) }
|
||||
GridRow { Text("Size").foregroundStyle(.secondary); Text("\(information.entry.size) bytes").monospacedDigit() }
|
||||
}
|
||||
if model.os9 {
|
||||
GroupBox("OS-9 Access") {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 10) {
|
||||
GridRow {
|
||||
Text("Owner")
|
||||
access("Read", bit: 1, id: "disk-editor-info-owner-read")
|
||||
access("Write", bit: 2, id: "disk-editor-info-owner-write")
|
||||
access("Execute", bit: 4, id: "disk-editor-info-owner-execute")
|
||||
}
|
||||
GridRow {
|
||||
Text("Public")
|
||||
access("Read", bit: 8, id: "disk-editor-info-public-read")
|
||||
access("Write", bit: 16, id: "disk-editor-info-public-write")
|
||||
access("Execute", bit: 32, id: "disk-editor-info-public-execute")
|
||||
}
|
||||
}.padding(8)
|
||||
access("Single access (non-shareable)", bit: 64, id: "disk-editor-info-single-access")
|
||||
.help("Allows only one opener at a time; this is the OS-9 single-access attribute.")
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 8)
|
||||
}
|
||||
}
|
||||
GroupBox("OS-9 Ownership") {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 10) {
|
||||
Text("Group ID")
|
||||
TextField("Group ID", text: $ownerGroup).frame(width: 70).accessibilityIdentifier("disk-editor-info-owner-group")
|
||||
Spacer()
|
||||
Text("User ID")
|
||||
TextField("User ID", text: $ownerUser).frame(width: 70).accessibilityIdentifier("disk-editor-info-owner-user")
|
||||
}.textFieldStyle(.roundedBorder).padding(8)
|
||||
if let group = ownerID(ownerGroup), let user = ownerID(ownerUser) {
|
||||
Text("Owner ID: \(group * 256 + user)").monospacedDigit().font(.callout)
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8)
|
||||
.accessibilityIdentifier("disk-editor-info-owner-id")
|
||||
}
|
||||
Text("OS-9 stores one owner ID. The Owner column shows its high and low bytes as group.user; enter each from 0 to 255.")
|
||||
.font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 8)
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
Label("Group ID and User ID must each be a whole number from 0 to 255.", systemImage: "exclamationmark.triangle")
|
||||
.font(.callout).foregroundStyle(.red).accessibilityIdentifier("disk-editor-info-validation")
|
||||
}
|
||||
}
|
||||
ScrollView {
|
||||
Text(information.details).font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.frame(minHeight: 90, maxHeight: .infinity).accessibilityIdentifier("disk-editor-info-details")
|
||||
if let error = model.error {
|
||||
Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.red)
|
||||
.fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("disk-editor-info-error")
|
||||
}
|
||||
HStack {
|
||||
if model.os9 {
|
||||
Text("Changes stay in the editor until the disk image is applied or saved.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
Spacer()
|
||||
Button("Cancel") { model.information = nil }.keyboardShortcut(.cancelAction).accessibilityIdentifier("disk-editor-info-cancel")
|
||||
Button("Save Changes") {
|
||||
guard let user = ownerID(ownerUser), let group = ownerID(ownerGroup) else { return }
|
||||
model.applyInformation(information, permissions: permissions, ownerUser: user, ownerGroup: group)
|
||||
}.keyboardShortcut(.defaultAction).disabled(!valid || !changed).accessibilityIdentifier("disk-editor-info-save")
|
||||
} else {
|
||||
Spacer()
|
||||
Button("Done") { model.information = nil }.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-info-done")
|
||||
}
|
||||
}
|
||||
}.padding(20).frame(width: 590, height: model.os9 ? 660 : 440).disabled(model.busy)
|
||||
}
|
||||
}
|
||||
|
||||
private struct DiskEditorImportSheet: View {
|
||||
@ObservedObject var model: DiskImageEditorModel
|
||||
@State var request: DiskEditorImportRequest
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("Import into \(model.displayPath)").font(.headline)
|
||||
Text(request.urls.map(\.lastPathComponent).joined(separator: "\n")).lineLimit(6).textSelection(.enabled)
|
||||
if !model.os9 {
|
||||
Picker("File Type", selection: $request.type) {
|
||||
Text("BASIC program").tag(0); Text("BASIC data").tag(1); Text("Machine language").tag(2); Text("Text").tag(3)
|
||||
}.accessibilityIdentifier("disk-editor-import-type")
|
||||
Picker("Encoding", selection: $request.ascii) { Text("ASCII").tag(true); Text("Binary / Tokenized").tag(false) }
|
||||
.accessibilityIdentifier("disk-editor-import-encoding")
|
||||
Text("Bytes are copied unchanged. Choose Binary / Tokenized for a tokenized BASIC program. These settings apply to every selected file.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
HStack {
|
||||
Spacer(); Button("Cancel") { model.importing = nil }.keyboardShortcut(.cancelAction)
|
||||
Button("Import") { model.confirmImport(request) }.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-import-confirm")
|
||||
}
|
||||
}.padding(22).frame(width: 470)
|
||||
}
|
||||
}
|
||||
|
||||
private struct DiskEditorNameSheet: View {
|
||||
@ObservedObject var model: DiskImageEditorModel
|
||||
@State var request: DiskEditorNameRequest
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text(request.entry == nil ? "New Folder" : "Rename Entry").font(.headline)
|
||||
TextField("Name", text: $request.name).accessibilityIdentifier("disk-editor-name")
|
||||
if !model.os9 { Text("Disk BASIC names use up to 8 characters plus a 3-character extension.").font(.caption).foregroundStyle(.secondary) }
|
||||
HStack {
|
||||
Spacer(); Button("Cancel") { model.naming = nil }.keyboardShortcut(.cancelAction)
|
||||
Button(request.entry == nil ? "Create Folder" : "Rename") { model.confirmName(request) }
|
||||
.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-name-confirm")
|
||||
.disabled(request.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}.padding(22).frame(width: 420)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
struct RasterVertex { float4 position [[position]]; float2 uv; };
|
||||
vertex RasterVertex vccVertex(uint index [[vertex_id]]) {
|
||||
const float2 positions[] = {float2(-1,-1), float2(3,-1), float2(-1,3)};
|
||||
const float2 coords[] = {float2(0,1), float2(2,1), float2(0,-1)};
|
||||
return {float4(positions[index],0,1), coords[index]};
|
||||
}
|
||||
fragment float4 vccFragment(RasterVertex input [[stage_in]], texture2d<float> frame [[texture(0)]], constant float4& region [[buffer(0)]], constant float2& effects [[buffer(1)]]) {
|
||||
constexpr sampler nearest(coord::normalized, address::clamp_to_edge, filter::nearest);
|
||||
// Fractional viewport edges can cover a fragment center just outside the
|
||||
// picture. Clamp to active texel centers so no guest-border pixel leaks in.
|
||||
const float2 halfTexel = 0.5 / float2(frame.get_width(), frame.get_height());
|
||||
const float2 uv = clamp(region.xy + input.uv * region.zw,
|
||||
region.xy + halfTexel, region.xy + region.zw - halfTexel);
|
||||
constexpr sampler smooth(coord::normalized, address::clamp_to_edge, filter::linear);
|
||||
float3 color = effects.x > 0.5 ? frame.sample(smooth, uv).rgb : frame.sample(nearest, uv).rgb;
|
||||
const uint row = uint(floor((uv.y - region.y) * frame.get_height()));
|
||||
if (row & 1) color *= 1.0 - effects.y;
|
||||
return float4(color, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import MetalKit
|
||||
|
||||
struct EmulatorDisplay: NSViewRepresentable {
|
||||
@ObservedObject var machine: MachineModel
|
||||
@ObservedObject private var preferences: DisplayPreferences
|
||||
var presentationToken = "display"
|
||||
init(machine: MachineModel, presentationToken: String = "display") {
|
||||
self.machine = machine; self.presentationToken = presentationToken
|
||||
self.preferences = machine.displayPreferences
|
||||
}
|
||||
func makeNSView(context: Context) -> KeyboardDisplay {
|
||||
let view = KeyboardDisplay(frame: .zero, device: MTLCreateSystemDefaultDevice())
|
||||
view.machine = machine
|
||||
view.input = machine.input
|
||||
machine.input.acceptsInput = { [weak view] in
|
||||
guard let view else { return false }
|
||||
return view.inputEnabled && view.window?.isKeyWindow == true && view.window?.firstResponder === view
|
||||
}
|
||||
view.keyChanged = { [weak machine] in machine?.setKeyboard($0) }
|
||||
view.displayFailed = { [weak machine] message in
|
||||
DispatchQueue.main.async { machine?.displayError = message }
|
||||
}
|
||||
view.configure()
|
||||
return view
|
||||
}
|
||||
func updateNSView(_ view: KeyboardDisplay, context: Context) {
|
||||
if view.presentationToken != presentationToken {
|
||||
let restoreFocus = !view.presentationToken.isEmpty && view.window?.isKeyWindow == true
|
||||
view.releaseKeys(); view.presentationToken = presentationToken
|
||||
if restoreFocus { DispatchQueue.main.async { view.window?.makeFirstResponder(view) } }
|
||||
}
|
||||
view.style = preferences.style
|
||||
view.pixels = machine.pixels
|
||||
#if VCC_UI_TESTING
|
||||
view.setAccessibilityValue(machine.uiTestSession + ",\(view.uiTestKeyDowns),\(machine.videoOutput.rawValue)")
|
||||
#endif
|
||||
view.activeVideoRect = machine.activeVideoRect
|
||||
view.synchronizeInput()
|
||||
view.inputEnabled = machine.state == .running && !machine.busy
|
||||
if view.inputEpoch != machine.inputEpoch {
|
||||
view.inputEpoch = machine.inputEpoch; view.releaseKeys()
|
||||
}
|
||||
if view.focusRequest != machine.focusRequest {
|
||||
view.focusRequest = machine.focusRequest
|
||||
DispatchQueue.main.async { view.window?.makeFirstResponder(view) }
|
||||
}
|
||||
view.requestFrame()
|
||||
}
|
||||
static func dismantleNSView(_ view: KeyboardDisplay, coordinator: ()) { view.releaseKeys() }
|
||||
}
|
||||
|
||||
final class KeyboardDisplay: MTKView, MTKViewDelegate, NSUserInterfaceValidations {
|
||||
weak var machine: MachineModel?
|
||||
@objc func copy(_ sender: Any?) { machine?.copyScreenText() }
|
||||
@objc func paste(_ sender: Any?) { machine?.pasteClipboard() }
|
||||
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
|
||||
if item.action == #selector(paste(_:)) { return machine?.canPaste == true }
|
||||
if item.action == #selector(copy(_:)) { return machine.map { !$0.busy && ($0.state == .running || $0.state == .paused) } ?? false }
|
||||
return false
|
||||
}
|
||||
|
||||
#if VCC_UI_TESTING
|
||||
private(set) var uiTestKeyDowns: UInt64 = 0
|
||||
#endif
|
||||
var presentationToken = ""
|
||||
var pixels: Data?
|
||||
var activeVideoRect = VideoGeometry.fullFrame
|
||||
var style = DisplayStyle()
|
||||
var inputEnabled = false {
|
||||
didSet { if !inputEnabled && oldValue { releaseKeys() } }
|
||||
}
|
||||
var inputEpoch: UInt64 = 0, focusRequest: UInt64 = 0
|
||||
var keyChanged: ((UInt64) -> Void)?
|
||||
var displayFailed: ((String) -> Void)?
|
||||
var input: InputHub?
|
||||
private var settingsEpoch: UInt64 = .max
|
||||
private var tracking: NSTrackingArea?
|
||||
private var capsRelease: DispatchWorkItem?
|
||||
private var keyboard = CocoKeyboard()
|
||||
func synchronizeInput() {
|
||||
if settingsEpoch != input?.epoch {
|
||||
settingsEpoch = input?.epoch ?? 0
|
||||
releaseKeys(); keyboard.mode = input?.settings.keyboard ?? .natural
|
||||
}
|
||||
}
|
||||
private var renderer: MetalRenderer?
|
||||
private var frameRequested = false
|
||||
private(set) var submittedFrames: UInt64 = 0
|
||||
|
||||
// SwiftUI can keep a Metal view layer-backed without servicing AppKit's
|
||||
// needsDisplay invalidation. In that state Core Animation stretches the last
|
||||
// presented drawable as the view resizes, even while the guest keeps running.
|
||||
// Drive MTKView's explicit draw path instead; coalesce updates on the main
|
||||
// queue so drawing never reenters a SwiftUI update or drawable-size callback.
|
||||
func requestFrame() {
|
||||
guard !frameRequested else { return }
|
||||
frameRequested = true
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else { return }
|
||||
self.frameRequested = false
|
||||
guard self.window?.isVisible == true, !self.isHiddenOrHasHiddenAncestor,
|
||||
self.bounds.width > 0, self.bounds.height > 0 else { return }
|
||||
self.draw()
|
||||
}
|
||||
}
|
||||
override func layout() { super.layout(); requestFrame() }
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); requestFrame() }
|
||||
override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties(); requestFrame() }
|
||||
private var focusObservers: [NSObjectProtocol] = []
|
||||
override var acceptsFirstResponder: Bool { true }
|
||||
override func accessibilityFrame() -> NSRect {
|
||||
guard let window else { return super.accessibilityFrame() }
|
||||
return window.convertToScreen(convert(bounds, to: nil))
|
||||
}
|
||||
func configure() {
|
||||
colorPixelFormat = .bgra8Unorm
|
||||
isPaused = true; enableSetNeedsDisplay = false; framebufferOnly = true
|
||||
autoResizeDrawable = true; delegate = self
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityEnabled(true)
|
||||
setAccessibilityRole(.group)
|
||||
setAccessibilityRoleDescription("Emulator display")
|
||||
setAccessibilityLabel("CoCo display")
|
||||
setAccessibilityIdentifier("coco-display")
|
||||
setAccessibilityHelp("Click here or press Option-Command-K to type into the CoCo. Option-Command-U returns to Mac controls. Escape is Break, Home is Clear. Guest graphics are not available as accessible text.")
|
||||
do {
|
||||
guard let device else { throw MetalRenderer.Failure.unavailable }
|
||||
renderer = try MetalRenderer(device: device, library: MetalRenderer.library(device: device, bundle: Bundle(for: KeyboardDisplay.self)))
|
||||
} catch { displayFailed?(error.localizedDescription) }
|
||||
focusObservers.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification,
|
||||
object: nil, queue: .main) { [weak self] _ in self?.releaseKeys() })
|
||||
focusObservers.append(NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification,
|
||||
object: nil, queue: .main) { [weak self] note in
|
||||
if let window = note.object as? NSWindow, window === self?.window { self?.releaseKeys() }
|
||||
})
|
||||
}
|
||||
deinit { for observer in focusObservers { NotificationCenter.default.removeObserver(observer) } }
|
||||
override func updateTrackingAreas() {
|
||||
super.updateTrackingAreas()
|
||||
if let tracking { removeTrackingArea(tracking) }
|
||||
let area = NSTrackingArea(rect: bounds, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)
|
||||
addTrackingArea(area); tracking = area
|
||||
}
|
||||
private func moveMouse(_ event: NSEvent) {
|
||||
guard inputEnabled, window?.firstResponder === self else { return }
|
||||
let point = convert(event.locationInWindow, from:nil)
|
||||
guard let normalized = VideoGeometry.mouse(point,in:bounds.size,source:activeVideoRect,scaling:style.scaling,drawableSize:drawableSize) else {
|
||||
input?.mouseLeave(); return
|
||||
}
|
||||
input?.mouseMove(x:normalized.x,y:normalized.y)
|
||||
}
|
||||
override func mouseMoved(with event: NSEvent) { moveMouse(event) }
|
||||
override func mouseDragged(with event: NSEvent) { moveMouse(event) }
|
||||
override func rightMouseDragged(with event: NSEvent) { moveMouse(event) }
|
||||
override func mouseExited(with event: NSEvent) { input?.mouseLeave() }
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
window?.makeFirstResponder(self); moveMouse(event)
|
||||
if inputEnabled { input?.mouseButton(0, down: true) }
|
||||
}
|
||||
override func mouseUp(with event: NSEvent) { input?.mouseButton(0, down: false) }
|
||||
override func rightMouseDown(with event: NSEvent) {
|
||||
window?.makeFirstResponder(self); moveMouse(event)
|
||||
if inputEnabled { input?.mouseButton(1, down: true) }
|
||||
}
|
||||
override func rightMouseUp(with event: NSEvent) { input?.mouseButton(1, down: false) }
|
||||
override func resignFirstResponder() -> Bool { releaseKeys(); return super.resignFirstResponder() }
|
||||
func releaseKeys() { capsRelease?.cancel(); keyboard.releaseAll(); keyChanged?(0); input?.release() }
|
||||
private func updateModifiers(_ event: NSEvent) {
|
||||
keyboard.modifiers(shift: event.modifierFlags.contains(.shift),
|
||||
control: event.modifierFlags.contains(.control), alt: event.modifierFlags.contains(.option))
|
||||
}
|
||||
override func flagsChanged(with event: NSEvent) {
|
||||
guard inputEnabled, !event.modifierFlags.contains(.command) else { releaseKeys(); return }
|
||||
synchronizeInput(); updateModifiers(event)
|
||||
if event.keyCode == 57 {
|
||||
keyboard.press(code: 57, characters: "")
|
||||
capsRelease?.cancel()
|
||||
let release = DispatchWorkItem { [weak self] in
|
||||
guard let self else { return }; self.keyboard.release(code: 57); self.keyChanged?(self.keyboard.mask)
|
||||
}
|
||||
capsRelease = release; DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: release)
|
||||
}
|
||||
keyChanged?(keyboard.mask)
|
||||
}
|
||||
override func keyDown(with event: NSEvent) {
|
||||
guard inputEnabled, !event.modifierFlags.contains(.command) else { releaseKeys(); super.keyDown(with: event); return }
|
||||
guard !event.isARepeat else { return }
|
||||
synchronizeInput()
|
||||
if input?.key(event.keyCode, down: true) == true { return }
|
||||
updateModifiers(event)
|
||||
let modified = event.modifierFlags.intersection([.control, .option]).isEmpty
|
||||
? event.characters : event.charactersIgnoringModifiers
|
||||
keyboard.press(code: event.keyCode, characters: modified ?? "")
|
||||
#if VCC_UI_TESTING
|
||||
if keyboard.mask != 0 { uiTestKeyDowns += 1 }
|
||||
#endif
|
||||
keyChanged?(keyboard.mask)
|
||||
}
|
||||
override func keyUp(with event: NSEvent) {
|
||||
_ = input?.key(event.keyCode, down: false)
|
||||
keyboard.release(code: event.keyCode); keyChanged?(keyboard.mask)
|
||||
}
|
||||
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { requestFrame() }
|
||||
func draw(in view: MTKView) {
|
||||
guard let renderer, let drawable = currentDrawable else { return }
|
||||
do {
|
||||
let scale = bounds.width > 0 ? CGFloat(drawable.texture.width)/bounds.width : 1
|
||||
if try renderer.encode(pixels:pixels,target:drawable.texture,drawable:drawable,activeArea:activeVideoRect,inset:VideoGeometry.border*scale,style:style) != nil {
|
||||
submittedFrames &+= 1
|
||||
}
|
||||
}
|
||||
catch { displayFailed?(error.localizedDescription) }
|
||||
}
|
||||
}
|
||||
|
||||
// Shared with native menus; observes only user-driven appearance changes.
|
||||
struct DisplayAppearanceControls: View {
|
||||
@ObservedObject var preferences: DisplayPreferences
|
||||
var body: some View {
|
||||
Picker("Scaling", selection: $preferences.style.scaling) {
|
||||
ForEach(DisplayScaling.allCases, id: \.self) { Text($0.label).tag($0) }
|
||||
}.accessibilityIdentifier("display-scaling")
|
||||
Toggle("Scanlines", isOn: $preferences.style.scanlines).accessibilityIdentifier("display-scanlines")
|
||||
}
|
||||
}
|
||||
|
||||
struct DisplayControlsView: View {
|
||||
let machine: MachineModel
|
||||
@ObservedObject private var menu: MachineMenuState
|
||||
init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState }
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
SecondaryHeader(title: "Display Settings", symbol: "display", subtitle: "Adjust the picture without restarting your CoCo.")
|
||||
SecondaryCard {
|
||||
Label("Video Signal", systemImage: "cable.connector").font(.headline)
|
||||
Picker("Video Signal", selection: Binding(get: { menu.values.videoOutput }, set: machine.setVideoOutput)) {
|
||||
ForEach(DisplayOutput.allCases, id: \.self) { Text($0.label).tag($0) }
|
||||
}.disabled(menu.values.busy || menu.values.state == .closed)
|
||||
Text("Composite TV reproduces the artifact colors used by many CoCo games. RGB provides a direct monitor signal.")
|
||||
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Appearance", systemImage: "slider.horizontal.3").font(.headline)
|
||||
DisplayAppearanceControls(preferences: machine.displayPreferences)
|
||||
SecondaryHelp(title: "How scaling works") {
|
||||
Text("Sharp and Smooth use the largest picture that fits while preserving its proportions. Integer Pixels keeps exact whole-pixel multiples and can leave a large dark-green border, including inside the expanded monitor. Choose Sharp — Fit Window to use more of the screen. If even 1× cannot fit, Integer Pixels fits proportionally instead. Scanlines fade out at small sizes to keep the picture readable.")
|
||||
Text("These choices are remembered for this Mac and apply to Display, System and the expanded monitor. They do not change machine profiles.")
|
||||
}.accessibilityIdentifier("display-scaling-help")
|
||||
SecondaryAction(title: "Reset Display Appearance", systemImage: "arrow.counterclockwise") {
|
||||
machine.displayPreferences.style = DisplayStyle()
|
||||
}
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Screenshot", systemImage: "camera").font(.headline)
|
||||
Text("Save the active picture as a PNG at native resolution, without the surrounding window or display effects.")
|
||||
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
SecondaryAction(title: "Save CoCo Screen…", systemImage: "square.and.arrow.up", action: machine.saveScreenshot)
|
||||
.disabled(menu.values.busy || !(menu.values.state == .running || menu.values.state == .paused))
|
||||
}
|
||||
}.padding(24).frame(maxWidth: 600, alignment: .leading)
|
||||
}.frame(minWidth: 520, minHeight: 500)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Combine
|
||||
|
||||
@MainActor
|
||||
final class GraphicsPreviewModel: ObservableObject {
|
||||
enum Source: String, CaseIterable { case current = "Current Video Page", address = "At Address" }
|
||||
enum Mode: Int, CaseIterable {
|
||||
case sg4, pmode0, pmode1, pmode2, pmode3, pmode4, hscreen1, hscreen2, hscreen3, hscreen4
|
||||
var label: String {
|
||||
if self == .sg4 { return "Text / SG4" }
|
||||
if rawValue <= Self.pmode4.rawValue { return "PMODE \(rawValue - 1)" }
|
||||
return "HSCREEN \(rawValue - 5)"
|
||||
}
|
||||
var supportsColorSet: Bool { rawValue >= Self.pmode0.rawValue && rawValue <= Self.pmode4.rawValue }
|
||||
}
|
||||
struct Request: Equatable {
|
||||
var source = Source.current
|
||||
var physical = false
|
||||
var address: UInt32 = 0x0e00
|
||||
var mode = Mode.pmode1
|
||||
var alternate = false
|
||||
}
|
||||
struct Pixel: Equatable { var x = 0; var y = 0 }
|
||||
struct Frame {
|
||||
let capture: VCCDebugGraphicsCapture
|
||||
let image: CGImage
|
||||
let highlights: CGImage?
|
||||
let changes: Int?
|
||||
}
|
||||
@Published var request = Request()
|
||||
@Published var addressText = "0E00"
|
||||
@Published var addressError: String?
|
||||
@Published private(set) var frame: Frame?
|
||||
@Published private(set) var error: String?
|
||||
@Published var selection = Pixel()
|
||||
private var epoch: UInt64 = 0
|
||||
|
||||
func readyToStep(machine: MachineModel) -> Bool {
|
||||
if error != nil { return true }
|
||||
guard let snapshot = frame?.capture.machine else { return false }
|
||||
return snapshot.state == .paused && snapshot.generation == machine.basicDebug.generation &&
|
||||
snapshot.cycles == machine.basicDebug.cycles
|
||||
}
|
||||
|
||||
func inspectAddress(_ address: UInt32, physical: Bool) {
|
||||
addressText = DebuggerModel.hex(address, width: physical ? 6 : 4)
|
||||
addressError = nil
|
||||
request.physical = physical
|
||||
request.address = address
|
||||
request.source = .address
|
||||
}
|
||||
|
||||
func applyAddress() {
|
||||
guard let value = DebuggerModel.hexadecimalAddress(addressText, maximum: request.physical ? 0x7fffff : 0xffff) else {
|
||||
addressError = request.physical ? "Enter a physical address from $000000 to $7FFFFF." : "Enter a CPU address from $0000 to $FFFF."
|
||||
return
|
||||
}
|
||||
inspectAddress(value, physical: request.physical)
|
||||
}
|
||||
|
||||
private static func image(_ rgba: Data, width: Int, height: Int) -> CGImage? {
|
||||
guard width > 0, height > 0, rgba.count == width * height * 4,
|
||||
let provider = CGDataProvider(data: rgba as CFData) else { return nil }
|
||||
return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32,
|
||||
bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
// A translucent overlay preserves the colors underneath. Work is bounded
|
||||
// by one native raster and is only performed for an observed single step.
|
||||
static func differences(_ before: Data, _ after: Data) -> (Data, Int) {
|
||||
guard before.count == after.count, after.count.isMultiple(of: 4) else { return (Data(), 0) }
|
||||
var mask = Data(count: after.count)
|
||||
var changes = 0
|
||||
before.withUnsafeBytes { (old: UnsafeRawBufferPointer) in
|
||||
after.withUnsafeBytes { (new: UnsafeRawBufferPointer) in
|
||||
mask.withUnsafeMutableBytes { (out: UnsafeMutableRawBufferPointer) in
|
||||
for i in stride(from: 0, to: new.count, by: 4) {
|
||||
if old[i] != new[i] || old[i+1] != new[i+1] || old[i+2] != new[i+2] || old[i+3] != new[i+3] {
|
||||
out[i] = 255; out[i+1] = 94; out[i+2] = 190; out[i+3] = 210
|
||||
changes += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return (mask, changes)
|
||||
}
|
||||
|
||||
func poll(machine: MachineModel) async {
|
||||
let intent = request
|
||||
epoch &+= 1
|
||||
let token = epoch
|
||||
frame = nil
|
||||
error = nil
|
||||
var lastRead: (epoch: UInt64, snapshot: VCCMachineSnapshot)?
|
||||
while !Task.isCancelled, token == epoch, intent == request {
|
||||
// Repeated polling of an unchanged paused machine needs no extra
|
||||
// bitmap. Commands increment inputEpoch, including paused RAM edits.
|
||||
if machine.canQuickLoad, machine.state == .running || lastRead?.snapshot.state != .paused ||
|
||||
lastRead?.epoch != machine.inputEpoch || lastRead?.snapshot.cycles != machine.basicDebug.cycles ||
|
||||
lastRead?.snapshot.generation != machine.basicDebug.generation {
|
||||
let inputEpoch = machine.inputEpoch
|
||||
let sample = await machine.readGraphicsPreview(currentPage: intent.source == .current,
|
||||
address: intent.address, physical: intent.physical, mode: intent.mode.rawValue,
|
||||
alternatePalette: intent.mode.supportsColorSet && intent.alternate)
|
||||
guard !Task.isCancelled, epoch == token, request == intent else { return }
|
||||
if let sample, inputEpoch == machine.inputEpoch, sample.machine.generation == machine.basicDebug.generation {
|
||||
lastRead = (inputEpoch, sample.machine)
|
||||
accept(sample, step: machine.lastDebuggerStep)
|
||||
}
|
||||
}
|
||||
do { try await Task.sleep(for: .milliseconds(250)) } catch { return }
|
||||
}
|
||||
}
|
||||
|
||||
private func accept(_ sample: VCCDebugGraphicsCapture, step: (generation: UInt64, before: UInt64, after: UInt64)?) {
|
||||
if let message = sample.errorMessage {
|
||||
error = message; frame = nil
|
||||
return
|
||||
}
|
||||
guard let bitmap = Self.image(sample.rgba, width: sample.width, height: sample.height) else {
|
||||
error = "This page could not be rendered."; frame = nil
|
||||
return
|
||||
}
|
||||
var highlights: CGImage?
|
||||
var changes: Int?
|
||||
if let previous = frame, let step, previous.capture.machine.state == .paused, sample.machine.state == .paused,
|
||||
sample.machine.generation == step.generation, sample.machine.cycles == step.after,
|
||||
previous.capture.machine.cycles == step.before, sample.hasSameLayout(as: previous.capture) {
|
||||
let (mask, count) = Self.differences(previous.capture.rgba, sample.rgba)
|
||||
changes = count
|
||||
if count > 0 { highlights = Self.image(mask, width: sample.width, height: sample.height) }
|
||||
}
|
||||
if selection.x >= sample.width || selection.y >= sample.height { selection = Pixel() }
|
||||
error = nil
|
||||
frame = Frame(capture: sample, image: bitmap, highlights: highlights, changes: changes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
struct GraphicsPreviewView: View {
|
||||
@ObservedObject var model: GraphicsPreviewModel
|
||||
let machine: MachineModel
|
||||
let showMemory: (UInt32, Bool) -> Void
|
||||
@State private var zoom = 0
|
||||
@State private var showChanges = true
|
||||
@State private var pixelX = "0"
|
||||
@State private var pixelY = "0"
|
||||
@State private var pointError: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Picker("Preview source", selection: $model.request.source) {
|
||||
ForEach(GraphicsPreviewModel.Source.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(width: 250)
|
||||
.accessibilityIdentifier("graphics-source")
|
||||
Spacer()
|
||||
Picker("Zoom", selection: $zoom) {
|
||||
Text("Fit").tag(0)
|
||||
ForEach([1, 2, 3, 4], id: \.self) { Text("\($0)×").tag($0) }
|
||||
}.frame(width: 120).accessibilityIdentifier("graphics-zoom")
|
||||
}.padding(.horizontal, 16).padding(.vertical, 10)
|
||||
if model.request.source == .address { addressControls }
|
||||
Divider()
|
||||
if let frame = model.frame {
|
||||
HStack(spacing: 0) {
|
||||
viewport(frame)
|
||||
Divider()
|
||||
inspector(frame).frame(width: 220)
|
||||
}
|
||||
} else {
|
||||
VStack(spacing: 10) {
|
||||
if let error = model.error {
|
||||
Image(systemName: "rectangle.slash").font(.title).foregroundStyle(.secondary)
|
||||
Text(error).multilineTextAlignment(.center)
|
||||
} else { ProgressView().controlSize(.small).accessibilityLabel("Reading graphics memory") }
|
||||
}.padding().frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
.task(id: model.request) { await model.poll(machine: machine) }
|
||||
.onChange(of: model.selection, initial: true) { _, point in
|
||||
pixelX = String(point.x); pixelY = String(point.y); pointError = nil
|
||||
}
|
||||
}
|
||||
|
||||
private var addressControls: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(spacing: 10) {
|
||||
Picker("Address space", selection: $model.request.physical) {
|
||||
Text("Mapped CPU").tag(false)
|
||||
Text("Physical RAM").tag(true)
|
||||
}.labelsHidden().fixedSize().accessibilityIdentifier("graphics-space")
|
||||
TextField("Hex address", text: $model.addressText).frame(width: 82)
|
||||
.textFieldStyle(.roundedBorder).font(.system(.body, design: .monospaced))
|
||||
.onSubmit { model.applyAddress() }.accessibilityLabel("Start address in hexadecimal")
|
||||
.accessibilityIdentifier("graphics-address")
|
||||
Button("Go", action: model.applyAddress).accessibilityIdentifier("graphics-go")
|
||||
Divider().frame(height: 18)
|
||||
Picker("Mode", selection: $model.request.mode) {
|
||||
ForEach(GraphicsPreviewModel.Mode.allCases, id: \.self) { Text($0.label).tag($0) }
|
||||
}.frame(width: 160).accessibilityIdentifier("graphics-mode")
|
||||
if model.request.mode.supportsColorSet {
|
||||
Picker("Colors", selection: $model.request.alternate) {
|
||||
Text("Set 0").tag(false)
|
||||
Text("Set 1").tag(true)
|
||||
}.frame(width: 130).accessibilityIdentifier("graphics-palette")
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
if let error = model.addressError {
|
||||
Text(error).font(.caption).foregroundStyle(.red)
|
||||
}
|
||||
}.padding(.horizontal, 16).padding(.bottom, 10)
|
||||
}
|
||||
|
||||
private func viewport(_ frame: GraphicsPreviewModel.Frame) -> some View {
|
||||
GeometryReader { bounds in
|
||||
let width = CGFloat(frame.capture.width), height = CGFloat(frame.capture.height)
|
||||
let availableScale = min(max(1, bounds.size.width - 24) / width, max(1, bounds.size.height - 24) / height)
|
||||
let fit = availableScale >= 1 ? floor(availableScale) : availableScale
|
||||
let scale = zoom == 0 ? fit : CGFloat(zoom)
|
||||
ScrollView([.horizontal, .vertical]) {
|
||||
ZStack(alignment: .topLeading) {
|
||||
Image(decorative: frame.image, scale: 1).interpolation(.none).resizable()
|
||||
if showChanges, let mask = frame.highlights {
|
||||
Image(decorative: mask, scale: 1).interpolation(.none).resizable()
|
||||
}
|
||||
let size = max(7, scale)
|
||||
Rectangle().strokeBorder(.white, lineWidth: 2)
|
||||
.overlay(Rectangle().strokeBorder(.black, lineWidth: 1))
|
||||
.frame(width: size, height: size)
|
||||
.position(x: (CGFloat(model.selection.x)+0.5)*scale, y: (CGFloat(model.selection.y)+0.5)*scale)
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
.frame(width: width*scale, height: height*scale).clipped()
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { point in
|
||||
model.selection = .init(x: min(Int(width)-1, max(0, Int(point.x / scale))),
|
||||
y: min(Int(height)-1, max(0, Int(point.y / scale))))
|
||||
}
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel("Graphics memory image, \(frame.capture.width) by \(frame.capture.height) pixels")
|
||||
.accessibilityHint("Use the X and Y fields in Pixel Inspector to select a pixel.")
|
||||
.accessibilityIdentifier("graphics-raster")
|
||||
.padding(12)
|
||||
.frame(minWidth: bounds.size.width, minHeight: bounds.size.height)
|
||||
}.background(Color(nsColor: .underPageBackgroundColor))
|
||||
}
|
||||
}
|
||||
|
||||
private func inspector(_ frame: GraphicsPreviewModel.Frame) -> some View {
|
||||
let capture = frame.capture
|
||||
let width = capture.physical ? 6 : 4
|
||||
let pixel = capture.pixel(x: model.selection.x, y: model.selection.y)
|
||||
return ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text(capture.modeName).font(.headline)
|
||||
Text("\(capture.width) × \(capture.height) pixels")
|
||||
Text((capture.physical ? "Physical RAM" : "Mapped CPU") + " · $" + DebuggerModel.hex(capture.address, width: width))
|
||||
.font(.caption).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
Divider()
|
||||
Label("Pixel Inspector", systemImage: "scope").font(.headline)
|
||||
HStack(spacing: 6) {
|
||||
Text("X")
|
||||
TextField("X", text: $pixelX).accessibilityIdentifier("graphics-x")
|
||||
Text("Y")
|
||||
TextField("Y", text: $pixelY).accessibilityIdentifier("graphics-y")
|
||||
Button { select(capture) } label: { Image(systemName: "return") }
|
||||
.help("Inspect the pixel at the entered X and Y coordinates").accessibilityLabel("Inspect pixel").accessibilityIdentifier("graphics-inspect")
|
||||
}.textFieldStyle(.roundedBorder).onSubmit { select(capture) }
|
||||
if let pointError { Text(pointError).font(.caption).foregroundStyle(.red) }
|
||||
if let pixel {
|
||||
Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 7) {
|
||||
GridRow {
|
||||
Text("Address")
|
||||
Text("$" + DebuggerModel.hex(pixel.address, width: width)).accessibilityIdentifier("graphics-byte-address")
|
||||
}
|
||||
if pixel.available {
|
||||
GridRow { Text("Byte"); Text("$" + DebuggerModel.hex(pixel.value, width: 2)) }
|
||||
GridRow { Text("Bit mask"); Text("$" + DebuggerModel.hex(pixel.mask, width: 2)) }
|
||||
}
|
||||
}.monospacedDigit().textSelection(.enabled)
|
||||
if !pixel.available { Text("This byte is unavailable.").font(.caption).foregroundStyle(.secondary) }
|
||||
if let address = pixel.attributeAddress, let value = pixel.attributeValue {
|
||||
Text("Attribute $\(DebuggerModel.hex(value.uint8Value, width: 2)) at $\(DebuggerModel.hex(address.uint32Value, width: width))")
|
||||
.font(.caption).textSelection(.enabled)
|
||||
}
|
||||
Button { showMemory(pixel.address, capture.physical) } label: {
|
||||
Label("Show Byte in Memory", systemImage: "memorychip")
|
||||
}.disabled(!pixel.available).accessibilityIdentifier("graphics-reveal")
|
||||
}
|
||||
Divider()
|
||||
Toggle("Highlight step changes", isOn: $showChanges).toggleStyle(.checkbox)
|
||||
if let changes = frame.changes {
|
||||
Text("\(changes.formatted()) \(changes == 1 ? "pixel" : "pixels") changed")
|
||||
.font(.caption).foregroundStyle(.secondary).accessibilityIdentifier("graphics-changes")
|
||||
}
|
||||
}.padding(16).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private func select(_ capture: VCCDebugGraphicsCapture) {
|
||||
guard let x = Int(pixelX), let y = Int(pixelY), (0..<capture.width).contains(x), (0..<capture.height).contains(y) else {
|
||||
pointError = "X ranges from 0 to \(capture.width-1) and Y from 0 to \(capture.height-1)."
|
||||
return
|
||||
}
|
||||
pointError = nil
|
||||
model.selection = .init(x: x, y: y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
struct HardDiskControlsView: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var newSizeKiB = 132480
|
||||
@State private var newDisk: NewHardDiskRequest?
|
||||
@State private var clockExpanded = false
|
||||
@State private var detailsExpanded = false
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
SecondaryHeader(title: "Virtual Hard Disks", badge: "hard").padding(20)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
if !machine.hardDiskConnected {
|
||||
Label("Controller disconnected · Mounted images are retained", systemImage: "exclamationmark.circle")
|
||||
.font(.callout).foregroundStyle(.orange)
|
||||
SecondaryAction(title: "Cartridges…", systemImage: "slider.horizontal.3") { openWindow(id: "cartridges") }
|
||||
} else {
|
||||
HStack {
|
||||
Label("Hard-disk controller connected", systemImage: "cable.connector")
|
||||
Spacer()
|
||||
Text(machine.diskSaving ? "Saving automatically…" : "Writable images save automatically")
|
||||
}.font(.caption).foregroundStyle(.secondary).frame(minHeight: 18)
|
||||
}
|
||||
ForEach(Array(machine.hardDisks.enumerated()), id: \.offset) { index, disk in
|
||||
HardDiskDriveRow(machine: machine, index: index, disk: disk) { newDisk = NewHardDiskRequest(id: index) }
|
||||
}
|
||||
if !machine.hardRestoreErrors.isEmpty {
|
||||
SecondaryAction(title: "Retry Unavailable Hard Disks", systemImage: "arrow.clockwise", action: machine.retryHardDisks)
|
||||
}
|
||||
DisclosureGroup(isExpanded: $clockExpanded) {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Toggle("Clock enabled", isOn: Binding(get: { machine.hardSettings.clockEnabled }, set: { machine.setHardClock(enabled: $0, readOnly: machine.hardSettings.clockReadOnly) }))
|
||||
Toggle("Allow guest to set the virtual clock", isOn: Binding(get: { !machine.hardSettings.clockReadOnly }, set: { machine.setHardClock(enabled: machine.hardSettings.clockEnabled, readOnly: !$0) }))
|
||||
.disabled(!machine.hardSettings.clockEnabled)
|
||||
Text("Starts from Mac local time. Guest changes affect only this session's emulated clock, not your Mac clock.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}.padding(.top, 10)
|
||||
} label: {
|
||||
Label("Virtual clock", systemImage: "clock").font(.callout).fontWeight(.medium)
|
||||
Text(machine.hardSettings.clockEnabled ? "Enabled" : "Disabled").font(.caption).foregroundStyle(.secondary)
|
||||
}.accessibilityIdentifier("hard-disk-clock")
|
||||
DisclosureGroup(isExpanded: $detailsExpanded) {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Text("Selected HD\(machine.hardSelectedDrive) · Sector \(machine.hardSector) · Status \(machine.hardStatus)")
|
||||
.monospacedDigit().accessibilityIdentifier("hard-disk-diagnostics")
|
||||
Text("Raw VHD, OS9 and IMG sector images are supported. This device has no boot ROM: use a compatible disk ROM or OS-9 boot disk.")
|
||||
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}.font(.callout).padding(.top, 10)
|
||||
} label: { Label("Controller Details", systemImage: "slider.horizontal.3").font(.callout).fontWeight(.medium) }
|
||||
.accessibilityIdentifier("hard-disk-controller-details")
|
||||
SecondaryHelp(title: "About hard-disk images") {
|
||||
Text("Writable images save automatically. Temporary changes stay in memory until Save As. Drive choices are remembered.")
|
||||
Text("New images are blank. Format or partition them with guest software, then choose Save As to create the Mac file. Creating a disk does not install an operating system.")
|
||||
Text("Edit opens the Disk Image Editor for OS-9 volumes and numbered HDB-DOS disks. The CoCo stays paused and locked until editing finishes; applying edits requires an explicit restart.")
|
||||
Text("Discard and Eject loses only unsaved in-memory changes. Earlier automatic saves cannot be undone.")
|
||||
}
|
||||
if let error = machine.diskSettingsError {
|
||||
Text(error).foregroundStyle(.red).textSelection(.enabled)
|
||||
if machine.diskSettingsNeedsSave { SecondaryAction(title: "Retry Saving Settings", systemImage: "arrow.clockwise", action: machine.saveDiskAssignments) }
|
||||
}
|
||||
if let error = machine.fileError ?? machine.error { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||||
}.padding(20)
|
||||
}
|
||||
Divider()
|
||||
MediaExecutionFooter(machine: machine, note: "Media and clock changes pause the CoCo; press Run to continue.").padding(20)
|
||||
}.frame(minWidth: 700, minHeight: 450)
|
||||
.disabled(machine.busy || machine.diskSaving || machine.diskEditorLocked || machine.state == .closed)
|
||||
.sheet(item: $newDisk) { request in
|
||||
NewHardDiskSheet(machine: machine, drive: request.id, initialSize: newSizeKiB) { size in
|
||||
newSizeKiB = size
|
||||
machine.createHardDisk(request.id, sizeKiB: size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct NewHardDiskRequest: Identifiable { let id: Int }
|
||||
|
||||
private struct NewHardDiskSheet: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
let drive: Int
|
||||
let create: (Int) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var size: String
|
||||
init(machine: MachineModel, drive: Int, initialSize: Int, create: @escaping (Int) -> Void) {
|
||||
self.machine = machine; self.drive = drive; self.create = create
|
||||
_size = State(initialValue: String(initialSize))
|
||||
}
|
||||
private var parsedSize: Int? {
|
||||
let value = size.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isNumber }), let number = Int(value), (1...524288).contains(number) else { return nil }
|
||||
return number
|
||||
}
|
||||
private var canCreate: Bool {
|
||||
parsedSize != nil && !machine.busy && !machine.diskSaving && machine.state != .closed
|
||||
&& machine.hardDisks.indices.contains(drive) && !machine.hardDisks[drive].dirty
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Label("New disk in HD\(drive)", systemImage: "doc.badge.plus").font(.title2)
|
||||
Text("Creates a blank in-memory image in this drive. Any currently mounted image is replaced; its Mac file is kept.")
|
||||
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
HStack {
|
||||
Text("Capacity (KiB)")
|
||||
TextField("132480", text: $size).frame(width: 130)
|
||||
.accessibilityLabel("New hard disk size in KiB").accessibilityIdentifier("new-hard-disk-size")
|
||||
Text("1–524,288 KiB").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Text(parsedSize == nil ? "Enter a whole number from 1 through 524288." : "132480 KiB is the conventional VCC image size.")
|
||||
.font(.caption).foregroundStyle(parsedSize == nil ? Color.orange : Color.secondary)
|
||||
.frame(minHeight: 16, alignment: .leading)
|
||||
Label("Format or partition the disk in the CoCo, then use Save As to keep it. No operating system is installed.", systemImage: "info.circle")
|
||||
.font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
|
||||
Button { if let value = parsedSize, canCreate { dismiss(); create(value) } } label: { Label("Create Disk", systemImage: "doc.badge.plus") }
|
||||
.keyboardShortcut(.defaultAction).disabled(!canCreate)
|
||||
.accessibilityIdentifier("create-hard-disk-confirm")
|
||||
}
|
||||
}.padding(24).frame(width: 470)
|
||||
}
|
||||
}
|
||||
|
||||
private struct HardDiskDriveRow: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
let index: Int
|
||||
let disk: VCCDiskSnapshot
|
||||
let newDisk: () -> Void
|
||||
@State private var options = false
|
||||
private var assigned: Bool { disk.mounted || machine.hardSettings.drives[index] != nil }
|
||||
private var manualSave: Bool {
|
||||
disk.dirty && (machine.hardTemporary[index] || machine.hardSettings.drives[index] == nil || disk.writeProtected || disk.sourceReadOnly)
|
||||
}
|
||||
private var mode: String {
|
||||
if disk.writeProtected { return "Write protected" }
|
||||
if machine.hardTemporary[index] { return "Temporary changes" }
|
||||
return machine.hardSettings.drives[index] == nil ? "No backing file · Use Save As" : "Saves automatically"
|
||||
}
|
||||
private var capacity: String {
|
||||
let bytes = Double(disk.byteCount)
|
||||
return bytes >= 1048576 ? String(format: "%.1f MiB", bytes / 1048576) : String(format: "%.0f KiB", bytes / 1024)
|
||||
}
|
||||
var body: some View {
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack(spacing: 14) {
|
||||
MediaDriveIdentity(name: "HD\(index)", mounted: disk.mounted)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(disk.mounted ? disk.name : machine.hardSettings.drives[index]?.url.lastPathComponent ?? "No disk inserted")
|
||||
.fontWeight(.semibold).lineLimit(1).truncationMode(.middle)
|
||||
Text(disk.mounted ? "\(capacity) · \(mode)" : assigned ? "Unavailable — reconnect or replace the file" : "Insert an image or create a blank disk")
|
||||
.font(.caption).foregroundStyle(assigned && !disk.mounted ? Color.orange : Color.secondary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
SecondaryAction(title: assigned ? "Replace…" : "Insert…", systemImage: "folder") { machine.openHardDisk(index) }
|
||||
.disabled(disk.dirty).accessibilityLabel("Insert hard disk \(index)")
|
||||
if disk.mounted {
|
||||
SecondaryAction(title: "Edit…", systemImage: "pencil") {
|
||||
DiskImageEditorCoordinator.shared.editHardDisk(index, machine: machine)
|
||||
}.accessibilityLabel("Edit hard disk \(index)").accessibilityIdentifier("hard-disk-edit-\(index)")
|
||||
.disabled(machine.diskEditorLocked)
|
||||
}
|
||||
if assigned {
|
||||
SecondaryAction(title: "Eject", systemImage: "eject") { machine.ejectHardDisk(index) }
|
||||
.disabled(disk.dirty).accessibilityLabel("Eject hard disk \(index)")
|
||||
} else {
|
||||
SecondaryAction(title: "New…", systemImage: "doc.badge.plus", action: newDisk)
|
||||
.disabled(disk.dirty).accessibilityLabel("New hard disk \(index)")
|
||||
}
|
||||
}
|
||||
if disk.mounted {
|
||||
HStack {
|
||||
DisclosureGroup(isExpanded: $options) { EmptyView() } label: { Text("Disk options").font(.callout) }
|
||||
.accessibilityIdentifier("hard-disk-options-\(index)")
|
||||
Spacer()
|
||||
actions
|
||||
}
|
||||
if options {
|
||||
HStack(spacing: 24) {
|
||||
Toggle("Write protected", isOn: Binding(get: { disk.writeProtected }, set: { machine.setHardProtection(index, $0) }))
|
||||
.disabled(disk.sourceReadOnly).accessibilityLabel("Write protect hard disk \(index)")
|
||||
.help(disk.sourceReadOnly ? "The source file is read-only. Reopen a writable copy to enable writes." : "Prevent the CoCo from changing this image.")
|
||||
Toggle("Temporary changes", isOn: Binding(get: { machine.hardTemporary[index] }, set: { machine.setHardTemporary(index, $0) }))
|
||||
.accessibilityLabel("Temporary changes in hard disk \(index)")
|
||||
Spacer(minLength: 0)
|
||||
}.font(.callout)
|
||||
Text("\(disk.byteCount / 256) sectors · Temporary changes stay in memory. Turning this off allows pending changes to save. Save As retains this mode.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if manualSave {
|
||||
HStack {
|
||||
Label("Unsaved changes · Save As to keep them", systemImage: "exclamationmark.circle").foregroundStyle(.orange)
|
||||
Spacer()
|
||||
SecondaryAction(title: "Save As…", systemImage: "square.and.arrow.up") { machine.exportHardDisk(index) }
|
||||
.accessibilityLabel("Save hard disk \(index) as")
|
||||
}.font(.callout).frame(minHeight: 24)
|
||||
}
|
||||
}
|
||||
if let error = machine.hardRestoreErrors[index] { Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled) }
|
||||
if let error = machine.hardSaveErrors[index] {
|
||||
Text(error).font(.callout).foregroundStyle(.red).textSelection(.enabled)
|
||||
SecondaryAction(title: "Retry Save", systemImage: "arrow.clockwise") { machine.retryHardSave(index) }
|
||||
.disabled(disk.writeProtected || machine.hardTemporary[index]).accessibilityLabel("Retry saving hard disk \(index)")
|
||||
}
|
||||
}
|
||||
}.modifier(MediaDropTarget(machine: machine, destination: .hardDisk(index)))
|
||||
}
|
||||
private var actions: some View {
|
||||
Menu {
|
||||
Button { machine.exportHardDisk(index) } label: { Label("Save As…", systemImage: "square.and.arrow.up") }
|
||||
.disabled(!disk.mounted).accessibilityLabel("Save hard disk \(index) as")
|
||||
Button(action: newDisk) { Label("New Disk…", systemImage: "doc.badge.plus") }
|
||||
.disabled(disk.dirty).accessibilityLabel("New hard disk \(index)")
|
||||
if manualSave || machine.hardSaveErrors[index] != nil {
|
||||
Divider()
|
||||
Button { machine.ejectHardDisk(index, discard: true) } label: { Label("Discard Changes and Eject…", systemImage: "eject") }
|
||||
.accessibilityLabel("Discard hard disk \(index) changes")
|
||||
}
|
||||
} label: { Label("Actions", systemImage: "ellipsis.circle") }
|
||||
.fixedSize().accessibilityIdentifier("hard-disk-actions-\(index)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
enum HardDiskFiles {
|
||||
static let limit = 512 * 1024 * 1024
|
||||
struct Image: Sendable { let data: Data; let readOnly: Bool; let digest: String }
|
||||
enum Failure: LocalizedError {
|
||||
case format, changed, readOnly, patch
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .format: return "Choose a raw VHD, OS9 or IMG file containing whole 256-byte sectors, from 256 bytes to 512 MiB. PC virtual-machine VHD containers are not supported."
|
||||
case .changed: return "The hard disk changed outside this drive. Use Save As to keep your changes separately, or reinsert the image."
|
||||
case .readOnly: return "The hard disk file is no longer writable. Restore write access and retry, or use Save As."
|
||||
case .patch: return "Invalid hard disk save snapshot. Your in-memory changes are retained."
|
||||
}
|
||||
}
|
||||
}
|
||||
private struct Stamp: Equatable {
|
||||
let size: UInt64, inode: UInt64
|
||||
let modified: Date
|
||||
}
|
||||
private static func stamp(_ url: URL) throws -> Stamp {
|
||||
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
|
||||
guard attributes[.type] as? FileAttributeType == .typeRegular,
|
||||
let size = attributes[.size] as? NSNumber, let inode = attributes[.systemFileNumber] as? NSNumber,
|
||||
let modified = attributes[.modificationDate] as? Date,
|
||||
size.uint64Value > 0, size.uint64Value <= limit, size.uint64Value % 256 == 0 else { throw Failure.format }
|
||||
return Stamp(size: size.uint64Value, inode: inode.uint64Value, modified: modified)
|
||||
}
|
||||
static func digest(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
|
||||
private static func digestFile(_ url: URL) throws -> String {
|
||||
let file = try FileHandle(forReadingFrom: url); defer { try? file.close() }
|
||||
var hash = SHA256(); var count = 0
|
||||
while let data = try file.read(upToCount: 1024 * 1024), !data.isEmpty {
|
||||
count += data.count; guard count <= limit else { throw Failure.format }; hash.update(data: data)
|
||||
}
|
||||
return hash.finalize().map { String(format: "%02x", $0) }.joined()
|
||||
}
|
||||
static func readImage(_ selected: URL) throws -> Image {
|
||||
guard ["vhd", "os9", "img"].contains(selected.pathExtension.lowercased()) else { throw Failure.format }
|
||||
let url = selected.resolvingSymlinksInPath(); let before = try stamp(url)
|
||||
let file = try FileHandle(forReadingFrom: url); defer { try? file.close() }
|
||||
var data = Data(); data.reserveCapacity(Int(before.size))
|
||||
while let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - data.count)), !chunk.isEmpty {
|
||||
data.append(chunk); guard data.count <= limit else { throw Failure.format }
|
||||
}
|
||||
guard data.count == before.size, before == (try stamp(url)) else { throw Failure.changed }
|
||||
// Microsoft VHD uses a footer; these extensions mean raw sector images here.
|
||||
if data.count >= 512 && data.suffix(512).starts(with: Data("conectix".utf8)) { throw Failure.format }
|
||||
return Image(data: data, readOnly: !FileManager.default.isWritableFile(atPath: url.path), digest: digest(data))
|
||||
}
|
||||
static func export(_ data: Data, to url: URL) throws -> String {
|
||||
guard !data.isEmpty, data.count <= limit, data.count % 256 == 0 else { throw Failure.format }
|
||||
try data.write(to: url, options: .atomic); return digest(data)
|
||||
}
|
||||
// Copy-on-write filesystem copies keep normal saves small on APFS. Hash the
|
||||
// entire source to detect external edits, apply only captured dirty sectors,
|
||||
// then atomically replace it. No host file I/O runs on the emulation queue.
|
||||
static func saveAutomatically(_ patches: Data, length: Int, to url: URL, expected: String) throws -> String {
|
||||
guard length > 0, length <= limit, length % 256 == 0, patches.count % 260 == 0 else { throw Failure.patch }
|
||||
var coordinationError: NSError?, writeError: Error?, result: String?
|
||||
NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in
|
||||
let temporary = target.deletingLastPathComponent().appendingPathComponent(".vcc-\(UUID().uuidString).tmp")
|
||||
defer { try? FileManager.default.removeItem(at: temporary) }
|
||||
do {
|
||||
let before = try stamp(target)
|
||||
guard length >= before.size else { throw Failure.patch }
|
||||
guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly }
|
||||
try FileManager.default.copyItem(at: target, to: temporary)
|
||||
guard try digestFile(temporary) == expected else { throw Failure.changed }
|
||||
let file = try FileHandle(forWritingTo: temporary)
|
||||
do {
|
||||
try file.truncate(atOffset: UInt64(length))
|
||||
for offset in stride(from: 0, to: patches.count, by: 260) {
|
||||
let sector = (0..<4).reduce(UInt32(0)) { $0 | (UInt32(patches[offset + $1]) << (8 * $1)) }
|
||||
let position = UInt64(sector) * 256
|
||||
guard position + 256 <= length else { throw Failure.patch }
|
||||
try file.seek(toOffset: position); try file.write(contentsOf: patches[(offset + 4)..<(offset + 260)])
|
||||
}
|
||||
try file.synchronize(); try file.close()
|
||||
} catch { try? file.close(); throw error }
|
||||
let next = try digestFile(temporary)
|
||||
guard before == (try stamp(target)) else { throw Failure.changed }
|
||||
guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly }
|
||||
_ = try FileManager.default.replaceItemAt(target, withItemAt: temporary)
|
||||
result = next
|
||||
} catch { writeError = error }
|
||||
}
|
||||
if let error = coordinationError { throw error }
|
||||
if let error = writeError { throw error }
|
||||
guard let result else { throw Failure.patch }; return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
// Guest events only. A brief hold makes transfers between UI polls visible;
|
||||
// pausing consumes counters and clears the hold immediately.
|
||||
struct ActivityTracker {
|
||||
enum State: String { case empty, loaded, read, write }
|
||||
private var previous: (UInt64, UInt64)?
|
||||
private var until: Double = 0
|
||||
private var held = State.loaded
|
||||
mutating func update(reads: UInt64, writes: UInt64, mounted: Bool, running: Bool, now: Double) -> State {
|
||||
defer { previous = (reads, writes) }
|
||||
guard mounted, running else { until = 0; held = .loaded; return mounted ? .loaded : .empty }
|
||||
if let previous, reads < previous.0 || writes < previous.1 { until = 0; held = .loaded }
|
||||
else if let previous, writes > previous.1 { held = .write; until = now + 0.16 }
|
||||
else if let previous, reads > previous.0 {
|
||||
if held != .write || now >= until { held = .read; until = now + 0.16 }
|
||||
}
|
||||
return now < until ? held : .loaded
|
||||
}
|
||||
}
|
||||
|
||||
struct HardwareState: Equatable {
|
||||
var values: [String: String] = ["scene":"on", "mpi":"off", "ram":"512kb", "cpu":"6809", "startup":"4", "floppy":"off", "hard":"off", "floppyCase":"off", "hardCase":"off", "tape":"empty", "tapeActivity":"empty", "printerPower":"off", "printerPaper":"blank", "sdcActivity":"empty"]
|
||||
var custom = false
|
||||
var activities = Array(repeating: ActivityTracker.State.empty, count: 7)
|
||||
static let ramKeys = ["128kb", "512kb", "2mb", "8mb"]
|
||||
init() {
|
||||
for n in 1...4 { values["slot\(n)"] = "empty" }
|
||||
for id in ["fd0","fd1","fd2","fd3","hd0","hd1"] { values[id] = "empty"; values[id + "Activity"] = "empty" }
|
||||
}
|
||||
init(snapshot: VCCMachineSnapshot, activities: [ActivityTracker.State], sdcActivity: ActivityTracker.State = .empty) {
|
||||
self.init(); self.activities = activities
|
||||
values["cpu"] = snapshot.use6309 ? "6309" : "6809"
|
||||
values["ram"] = Self.ramKeys[min(3, Int(snapshot.ramConfiguration))]
|
||||
values["mpi"] = snapshot.multiPakEnabled ? "on" : "off"
|
||||
values["startup"] = String(snapshot.physicalSlot)
|
||||
values["floppy"] = snapshot.diskConnected ? "on" : "off"
|
||||
values["hard"] = snapshot.hardDiskConnected ? "on" : "off"
|
||||
values["floppyCase"] = snapshot.diskConnected || snapshot.hardDiskConnected ? "on" : "off"
|
||||
values["hardCase"] = values["floppyCase"]
|
||||
custom = !snapshot.multiPakEnabled && snapshot.cartridgeKinds.first?.intValue != 0
|
||||
|| snapshot.multiPakEnabled && snapshot.cartridgeKinds.dropFirst().contains { $0.intValue == 4 }
|
||||
for n in 1...4 {
|
||||
let kind = snapshot.cartridgeKinds[n].intValue
|
||||
let available = !snapshot.cartridgeNames[n].isEmpty
|
||||
values["slot\(n)"] = available && (0...7).contains(kind) ? ["empty","rom","floppy","hard","empty","orchestra","speech","sdc"][kind] : "empty"
|
||||
}
|
||||
for (i, disk) in (snapshot.disks + snapshot.hardDisks).enumerated() {
|
||||
let id = i < 4 ? "fd\(i)" : "hd\(i-4)"
|
||||
values[id] = disk.mounted ? "loaded" : "empty"
|
||||
values[id + "Activity"] = activities[i].rawValue
|
||||
}
|
||||
values["sdcActivity"] = sdcActivity.rawValue
|
||||
values["printerPower"] = snapshot.printerEnabled ? "on" : "off"
|
||||
values["printerPaper"] = snapshot.printerByteCount > 0 ? "printed" : "blank"
|
||||
values["tape"] = snapshot.tapeMounted ? "loaded" : "empty"
|
||||
values["tapeActivity"] = activities[6].rawValue
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PresentationSettings: ObservableObject {
|
||||
enum Mode: String { case display, system }
|
||||
@Published var mode: Mode { didSet { defaults.set(mode.rawValue, forKey: "interface.presentation") } }
|
||||
@Published var expanded: Bool { didSet { defaults.set(expanded, forKey: "interface.expanded") } }
|
||||
@Published var showConnections: Bool { didSet { defaults.set(showConnections, forKey: "interface.connections") } }
|
||||
@Published var showClickableAreas: Bool { didSet { defaults.set(showClickableAreas, forKey: "interface.clickableAreas") } }
|
||||
@Published private(set) var controlsFocusRequest: UInt64 = 0
|
||||
// UI history is independent of saved machine profiles and Restore Defaults.
|
||||
func shouldIntroduce(_ profile: SystemProfile) -> Bool {
|
||||
!defaults.bool(forKey: "interface.usageGuide.seen." + profile.rawValue)
|
||||
}
|
||||
func didShowGuide(_ profile: SystemProfile) {
|
||||
defaults.set(true, forKey: "interface.usageGuide.seen." + profile.rawValue)
|
||||
}
|
||||
let windows: WindowPlacements
|
||||
func focusControls() { controlsFocusRequest += 1 }
|
||||
private let defaults: UserDefaults
|
||||
init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
windows = WindowPlacements(defaults: defaults)
|
||||
expanded = defaults.bool(forKey: "interface.expanded")
|
||||
showConnections = defaults.bool(forKey: "interface.connections")
|
||||
showClickableAreas = defaults.object(forKey: "interface.clickableAreas") == nil
|
||||
? true : defaults.bool(forKey: "interface.clickableAreas")
|
||||
mode = Mode(rawValue: defaults.string(forKey: "interface.presentation") ?? "") ?? .system
|
||||
}
|
||||
}
|
||||
|
||||
// Pure, absolute geometry: return never inverts an accumulated transform.
|
||||
struct SystemGeometry {
|
||||
static let canvas = CGRect(x: -120, y: 0, width: 960, height: 457)
|
||||
// The approved PNG includes transparent margins and its soft shelf shadow.
|
||||
// Keep its 2:1 aspect ratio; the separate target follows the visible object.
|
||||
static let libraryArtwork = CGRect(x: 420, y: 0, width: 304, height: 152)
|
||||
static let monitor = CGRect(x: 48, y: 4, width: 285, height: 256)
|
||||
static let screen = CGRect(x: 90, y: 44.5, width: 202, height: 151.1)
|
||||
let scene: CGRect
|
||||
let monitor: CGRect
|
||||
let screen: CGRect
|
||||
init(size: CGSize, system: Bool, expanded: Bool, contentBounds: CGRect = Self.canvas) {
|
||||
let scale = min(size.width / 960, size.height / 457)
|
||||
// Translate the shared scene, monitor and controls together. Keep the
|
||||
// full-scene scale so removing the tower does not enlarge the hardware.
|
||||
let offset = system ? (Self.canvas.midX - contentBounds.midX) * scale : 0
|
||||
scene = CGRect(x: (size.width - 960 * scale) / 2 + offset, y: (size.height - 457 * scale) / 2, width: 960 * scale, height: 457 * scale)
|
||||
if !system {
|
||||
monitor = .zero
|
||||
// Metal fits the current active raster, including wider CoCo 3 modes.
|
||||
screen = CGRect(origin:.zero,size:size)
|
||||
} else {
|
||||
let m: CGRect
|
||||
if expanded {
|
||||
let s = min((size.width - 24) / Self.monitor.width, (size.height - 16) / Self.monitor.height)
|
||||
m = CGRect(x: (size.width-Self.monitor.width*s)/2, y: (size.height-Self.monitor.height*s)/2, width: Self.monitor.width*s, height: Self.monitor.height*s)
|
||||
} else {
|
||||
m = CGRect(x: scene.minX+(Self.monitor.minX+120)*scale, y: scene.minY+Self.monitor.minY*scale, width: Self.monitor.width*scale, height: Self.monitor.height*scale)
|
||||
}
|
||||
monitor = m
|
||||
let s = m.width / Self.monitor.width
|
||||
screen = CGRect(x: m.minX+(Self.screen.minX-Self.monitor.minX)*s, y: m.minY+(Self.screen.minY-Self.monitor.minY)*s, width: Self.screen.width*s, height: Self.screen.height*s)
|
||||
}
|
||||
}
|
||||
func monitorRect(_ r: CGRect) -> CGRect {
|
||||
let s = monitor.width / Self.monitor.width
|
||||
return CGRect(x: monitor.minX + (r.minX - Self.monitor.minX) * s,
|
||||
y: monitor.minY + (r.minY - Self.monitor.minY) * s, width: r.width * s, height: r.height * s)
|
||||
}
|
||||
func rect(_ r: CGRect) -> CGRect {
|
||||
let s = scene.width/960
|
||||
return CGRect(x: scene.minX+(r.minX+120)*s, y: scene.minY+r.minY*s, width: r.width*s, height: r.height*s)
|
||||
}
|
||||
}
|
||||
|
||||
struct ArtworkLayer: Decodable {
|
||||
let file: String
|
||||
let bounds: [Double]
|
||||
let when: [String:String]
|
||||
let part: String
|
||||
var rect: CGRect { CGRect(x: bounds[0], y: bounds[1], width: bounds[2], height: bounds[3]) }
|
||||
func visible(_ values: [String:String]) -> Bool { when.allSatisfy { values[$0.key] == $0.value } }
|
||||
}
|
||||
|
||||
private final class ArtworkBundleMarker: NSObject {}
|
||||
|
||||
@MainActor
|
||||
final class HardwareArtwork {
|
||||
static let shared = HardwareArtwork()
|
||||
let layers: [ArtworkLayer]
|
||||
private var images: [String:NSImage] = [:]
|
||||
let directory: URL?
|
||||
init(bundle: Bundle? = nil) {
|
||||
let bundle = bundle ?? Bundle(for: ArtworkBundleMarker.self)
|
||||
directory = bundle.url(forResource: "Hardware", withExtension: nil)
|
||||
if let directory, let data = try? Data(contentsOf: directory.appendingPathComponent("layers.json")),
|
||||
let decoded = try? JSONDecoder().decode([ArtworkLayer].self, from: data) { layers = decoded }
|
||||
else { layers = [] }
|
||||
}
|
||||
func layoutBounds(_ values: [String:String]) -> CGRect {
|
||||
guard values["floppyCase"] != "on", values["hardCase"] != "on" else { return SystemGeometry.canvas }
|
||||
let visible = layers.filter { $0.visible(values) }.map(\.rect)
|
||||
return visible.reduce(SystemTarget.library.rect) { $0.union($1) }
|
||||
}
|
||||
func cartridgeHitRect(slot: Int, values: [String:String]) -> CGRect? {
|
||||
func bounds(_ n: Int) -> CGRect? {
|
||||
let matching = layers.filter { $0.when["mpi"] == "on" && $0.when["slot\(n)"] == values["slot\(n)"] && $0.when.keys.allSatisfy { $0 == "mpi" || $0 == "slot\(n)" } }
|
||||
return matching.map(\.rect).reduce(nil) { (r: CGRect?, next) in r.map { $0.union(next) } ?? next }
|
||||
}
|
||||
guard var rect = bounds(slot) else { return nil }
|
||||
for n in 1..<slot {
|
||||
if let front = bounds(n), front.intersects(rect) {
|
||||
rect.size.height = max(0, min(rect.maxY, front.minY) - rect.minY)
|
||||
}
|
||||
}
|
||||
rect.size.height = max(0, min(rect.maxY, SystemTarget.slot(slot).rect.minY) - rect.minY)
|
||||
return rect.height >= 8 ? rect.insetBy(dx: 1, dy: 1) : nil
|
||||
}
|
||||
func image(_ name: String) -> NSImage? {
|
||||
if let image = images[name] { return image }
|
||||
guard let directory, let image = NSImage(contentsOf: directory.appendingPathComponent(name)) else { return nil }
|
||||
images[name] = image; return image
|
||||
}
|
||||
}
|
||||
|
||||
struct HardwareBadge: View {
|
||||
let name: String
|
||||
let label: String
|
||||
var body: some View {
|
||||
Group {
|
||||
if let image = HardwareArtwork.shared.image(name + ".pdf") { Image(nsImage: image).resizable().scaledToFit() }
|
||||
else { Text(label) }
|
||||
}.accessibilityElement(children: .ignore).accessibilityLabel(label)
|
||||
}
|
||||
}
|
||||
|
||||
// Each cropped asset has a persistent native layer. Video polls never redraw
|
||||
// artwork; I/O changes only hide/show small pre-rendered layers. Resizing
|
||||
// regenerates the visible layers at the window's current backing scale.
|
||||
struct HardwareCanvas: NSViewRepresentable {
|
||||
let values: [String:String]
|
||||
let part: String
|
||||
func makeNSView(context: Context) -> LayeredHardwareView { LayeredHardwareView(part: part) }
|
||||
func updateNSView(_ view: LayeredHardwareView, context: Context) { view.apply(values) }
|
||||
}
|
||||
final class LayeredHardwareView: NSView {
|
||||
override var isFlipped: Bool { true }
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
private let assets: [ArtworkLayer]
|
||||
private var artworkLayers: [CALayer] = []
|
||||
private var values: [String:String] = [:]
|
||||
private var renderedSizes: [CGSize]
|
||||
private let part: String
|
||||
private(set) var rasterizations = 0
|
||||
init(part: String) {
|
||||
self.part = part
|
||||
assets = HardwareArtwork.shared.layers.filter { $0.part == part }
|
||||
renderedSizes = Array(repeating: .zero, count: assets.count)
|
||||
super.init(frame: .zero)
|
||||
wantsLayer = true; layer?.isGeometryFlipped = true
|
||||
setAccessibilityElement(false)
|
||||
for _ in assets {
|
||||
let child = CALayer(); child.isHidden = true
|
||||
layer?.addSublayer(child); artworkLayers.append(child)
|
||||
}
|
||||
}
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
func apply(_ next: [String:String]) {
|
||||
guard values != next else { return }; values = next; needsLayout = true
|
||||
}
|
||||
override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties(); renderedSizes = Array(repeating: .zero, count: assets.count); needsLayout = true }
|
||||
override func layout() {
|
||||
super.layout()
|
||||
let canvas = part == "monitor" ? SystemGeometry.monitor : SystemGeometry.canvas
|
||||
let scale = min(bounds.width/canvas.width, bounds.height/canvas.height)
|
||||
guard scale > 0 else { return }
|
||||
let backing = window?.backingScaleFactor ?? 2
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
for i in assets.indices {
|
||||
let asset = assets[i], child = artworkLayers[i], r = asset.rect
|
||||
child.isHidden = !asset.visible(values)
|
||||
let disconnected = (asset.when["floppyCase"] != nil && values["floppy"] != "on") ||
|
||||
(asset.when["hardCase"] != nil && values["hard"] != "on")
|
||||
child.opacity = disconnected ? 0.42 : 1
|
||||
child.frame = CGRect(x:(r.minX-canvas.minX)*scale,y:(r.minY-canvas.minY)*scale,width:r.width*scale,height:r.height*scale)
|
||||
guard !child.isHidden else { continue }
|
||||
let size = CGSize(width: ceil(r.width*scale*backing), height: ceil(r.height*scale*backing))
|
||||
if renderedSizes[i] != size, let image = HardwareArtwork.shared.image(asset.file) {
|
||||
let rep = NSBitmapImageRep(bitmapDataPlanes:nil,pixelsWide:max(1,Int(size.width)),pixelsHigh:max(1,Int(size.height)),bitsPerSample:8,samplesPerPixel:4,hasAlpha:true,isPlanar:false,colorSpaceName:.deviceRGB,bytesPerRow:0,bitsPerPixel:0)!
|
||||
NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep:rep)
|
||||
image.draw(in:CGRect(origin:.zero,size:size),from:.zero,operation:.sourceOver,fraction:1,respectFlipped:false,hints:nil)
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
child.contents = rep.cgImage; child.contentsScale = backing
|
||||
renderedSizes[i] = size; rasterizations += 1
|
||||
}
|
||||
}
|
||||
CATransaction.commit()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>VCCCompanionProtocolVersion</key>
|
||||
<integer>1</integer>
|
||||
<key>CFBundleName</key>
|
||||
<string>VCC Plus OSS</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>AppIcon</string>
|
||||
<key>UTExportedTypeDeclarations</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>com.brianholman.vccplus.mac.configuration-profile</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>VCC Plus Configuration Profile</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>public.json</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>vccprofile</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
<key>UTImportedTypeDeclarations</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>org.vcc.mac.configuration-profile</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>Legacy VCC Configuration Profile</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array><string>public.json</string></array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict><key>public.filename-extension</key><array><string>vccprofile</string></array></dict>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>CoCo media</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>dsk</string>
|
||||
<string>jvc</string>
|
||||
<string>dmk</string>
|
||||
<string>vdk</string>
|
||||
<string>os9</string>
|
||||
<string>vhd</string>
|
||||
<string>img</string>
|
||||
<string>cas</string>
|
||||
<string>wav</string>
|
||||
<string>rom</string>
|
||||
<string>ccc</string>
|
||||
<string>pak</string>
|
||||
<string>bin</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,158 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
struct InputControlsView: View {
|
||||
@ObservedObject var input: InputHub
|
||||
@State private var expandedPort: Int?
|
||||
@State private var showControllerTest = false
|
||||
private var keyboardDescription: String {
|
||||
switch input.settings.keyboard {
|
||||
case .natural: return "Follows the characters you type on your Mac."
|
||||
case .coco: return "Uses physical US CoCo key positions."
|
||||
case .compact: return "Adds Tab for Clear and the grave key for Break."
|
||||
}
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
SecondaryHeader(title: "Keyboard and Joysticks", badge: "joystick", subtitle: "Changes apply immediately and are remembered.")
|
||||
.padding(20)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
SecondaryCard {
|
||||
Label("Keyboard", systemImage: "keyboard").font(.headline)
|
||||
Picker("Keyboard mode", selection: $input.settings.keyboard) {
|
||||
ForEach(KeyboardMode.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.accessibilityIdentifier("input-keyboard")
|
||||
Text(keyboardDescription + " Command shortcuts stay with the Mac.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
HStack {
|
||||
Label("CoCo joystick ports", systemImage: "gamecontroller").font(.headline)
|
||||
Spacer()
|
||||
Button(action: input.swap) { Label("Swap assignments", systemImage: "arrow.left.arrow.right") }
|
||||
.accessibilityIdentifier("input-swap")
|
||||
.help("Swap the right and left CoCo port assignments, including their options.")
|
||||
}
|
||||
// Display left before right; hardware port 0 remains the right joystick.
|
||||
ForEach([1, 0], id: \.self) { port in portCard(port) }
|
||||
SecondaryCard {
|
||||
DisclosureGroup(isExpanded: $showControllerTest) {
|
||||
controllerTest.padding(.top, 8)
|
||||
} label: {
|
||||
HStack {
|
||||
Label("Controller Test", systemImage: "gamecontroller").font(.headline)
|
||||
Spacer()
|
||||
Text(input.devices.isEmpty ? "None connected" : "\(input.devices.count) connected")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
SecondaryHelp(title: "Using keyboard, mouse and controller input") {
|
||||
Text("Click the CoCo display to play. Keyboard joystick keys are reserved for the selected port. Mouse movement uses the display area; left and right clicks are Fire 1 and Fire 2.")
|
||||
Text("For Logitech F310, use the underside D switch and reconnect USB. Standard gamepads use the left stick or D-pad. Controller Test shows button numbers as you press them; select those numbers for Fire 1 and Fire 2.")
|
||||
Text("A remembered disconnected controller stays assigned and sends neutral input until it reconnects.")
|
||||
}
|
||||
if let error = input.error {
|
||||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}.padding(20)
|
||||
}
|
||||
}.frame(minWidth: 620, minHeight: 540)
|
||||
}
|
||||
private func buttons(_ value: UInt32) -> String {
|
||||
let pressed = (1...16).filter { value & (1 << ($0 - 1)) != 0 }.map(String.init)
|
||||
return pressed.isEmpty ? "none" : pressed.joined(separator: ", ")
|
||||
}
|
||||
private func portSummary(_ port: Int) -> String {
|
||||
let config = input.settings[port]
|
||||
switch config.source {
|
||||
case .none: return "No input assigned"
|
||||
case .keyboard: return config.keys.rawValue + " · " + config.interface.label
|
||||
case .mouse: return "Display pointer · " + config.interface.label
|
||||
case .controller:
|
||||
let name = config.device.isEmpty ? "Choose a controller in Options" :
|
||||
input.devices.first { $0.id == config.device }?.name ?? "Remembered controller — disconnected"
|
||||
return name + " · " + config.interface.label
|
||||
}
|
||||
}
|
||||
private func portCard(_ port: Int) -> some View {
|
||||
let config = Binding<PortSettings>(get: { input.settings[port] }, set: { input.settings[port] = $0 })
|
||||
return SecondaryCard {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(port == 0 ? "Right CoCo joystick" : "Left CoCo joystick").font(.headline)
|
||||
Text(port == 0 ? "JOYSTK 0–1" : "JOYSTK 2–3").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Picker("Input source", selection: config.source) {
|
||||
ForEach(JoystickSource.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.labelsHidden().frame(width: 180).accessibilityLabel(port == 0 ? "Right joystick input source" : "Left joystick input source")
|
||||
.accessibilityIdentifier("input-source-\(port)")
|
||||
}
|
||||
Text(portSummary(port)).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
if config.wrappedValue.source != .none {
|
||||
DisclosureGroup(isExpanded: Binding(get: { expandedPort == port }, set: { expandedPort = $0 ? port : nil })) {
|
||||
portOptions(port, config: config).padding(.top, 8)
|
||||
} label: { Label("Options", systemImage: "slider.horizontal.3") }
|
||||
.accessibilityIdentifier("input-options-\(port)")
|
||||
Text("X: \(input.preview[port].x >> 8) Y: \(input.preview[port].y >> 8) Fire 1: \(input.preview[port].buttons & 1 == 0 ? "up" : "down") Fire 2: \(input.preview[port].buttons & 2 == 0 ? "up" : "down")")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.accessibilityIdentifier("input-port-preview-\(port)")
|
||||
}
|
||||
}.onChange(of: input.settings[port].source) { _, new in
|
||||
if new != .none { expandedPort = port }
|
||||
else if expandedPort == port { expandedPort = nil }
|
||||
}
|
||||
}
|
||||
@ViewBuilder private func portOptions(_ port: Int, config: Binding<PortSettings>) -> some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
if config.wrappedValue.source == .keyboard {
|
||||
Picker("Keys", selection: config.keys) {
|
||||
ForEach(JoystickKeys.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}
|
||||
}
|
||||
if config.wrappedValue.source == .controller {
|
||||
Picker("Controller", selection: config.device) {
|
||||
Text("Choose a controller").tag("")
|
||||
if !config.wrappedValue.device.isEmpty && !input.devices.contains(where: { $0.id == config.wrappedValue.device }) {
|
||||
Text("Remembered controller — disconnected").tag(config.wrappedValue.device)
|
||||
}
|
||||
ForEach(input.devices) { Text($0.name).tag($0.id) }
|
||||
}.accessibilityIdentifier("input-controller-\(port)")
|
||||
Toggle("Use right stick", isOn: config.rightStick)
|
||||
HStack {
|
||||
Picker("Fire 1", selection: config.fire1) { ForEach(1...16, id: \.self) { Text("Button \($0)").tag($0) } }
|
||||
Picker("Fire 2", selection: config.fire2) { ForEach(1...16, id: \.self) { Text("Button \($0)").tag($0) } }
|
||||
}
|
||||
HStack {
|
||||
Text("Dead zone")
|
||||
Slider(value: config.deadZone, in: 0...0.5).accessibilityLabel("\(port == 0 ? "Right" : "Left") joystick dead zone")
|
||||
Text("\(Int(config.wrappedValue.deadZone * 100))%").monospacedDigit().frame(width: 38, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
Picker("CoCo interface", selection: config.interface) {
|
||||
ForEach(JoystickInterface.allCases, id: \.self) { Text($0.label).tag($0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private var controllerTest: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
if input.devices.isEmpty {
|
||||
Text("Connect a supported controller to see its sticks and button numbers.").foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(input.devices) { device in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(device.name).font(.headline)
|
||||
Text("Left: \(String(format: "% .2f", device.x)), \(String(format: "% .2f", device.y))\nRight: \(String(format: "% .2f", device.rx)), \(String(format: "% .2f", device.ry))\nButtons: \(buttons(device.buttons))")
|
||||
.font(.system(.caption, design: .monospaced)).fixedSize(horizontal: false, vertical: true)
|
||||
.accessibilityLabel("Controller preview: \(device.name), X \(device.x), Y \(device.y), buttons \(buttons(device.buttons))")
|
||||
.accessibilityIdentifier("controller-preview-\(device.id)")
|
||||
}
|
||||
}
|
||||
Text("Move either stick and press buttons to identify them. This preview does not change either port assignment.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Combine
|
||||
|
||||
/// Cached host observations, kept separate from core acknowledgement. This DTO
|
||||
/// permits authored diagnostics tests without opening HID devices or polling.
|
||||
struct InputDiagnosticObservation {
|
||||
var preview: [JoystickSample]?
|
||||
var submitted: [JoystickSample]?
|
||||
var submittedInterfaces: [JoystickInterface]?
|
||||
var applicationActive: Bool?
|
||||
var displayAcceptsInput: Bool?
|
||||
var pollAgeMilliseconds: Int?
|
||||
var submissionAgeMilliseconds: Int?
|
||||
var settingsError = false
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class InputHub: ObservableObject {
|
||||
@Published var settings: InputSettings { didSet {
|
||||
guard settings != oldValue else { return }
|
||||
release(); epoch &+= 1
|
||||
do { try store.save(settings); error = nil } catch { self.error = "Could not save input settings: \(error.localizedDescription)" }
|
||||
} }
|
||||
@Published private(set) var devices: [ControllerReading] = []
|
||||
@Published private(set) var preview = [JoystickSample(), JoystickSample()]
|
||||
@Published private(set) var error: String?
|
||||
private(set) var epoch: UInt64 = 0
|
||||
var acceptsInput: () -> Bool = { false }
|
||||
private let store: InputSettingsStore
|
||||
private let controller: VCCMachineController
|
||||
private let hardware: ControllerDevices
|
||||
private var timer: Timer?
|
||||
private var routing = InputRouting()
|
||||
private var last: [JoystickSample] = []
|
||||
private var lastActive = false
|
||||
private var lastPollUptime: TimeInterval?
|
||||
private var lastSubmissionUptime: TimeInterval?
|
||||
private var lastApplicationActive: Bool?
|
||||
private var lastDisplayAcceptsInput: Bool?
|
||||
private var submitted: [JoystickSample]?
|
||||
private var submittedInterfaces: [JoystickInterface]?
|
||||
init(controller: VCCMachineController, store: InputSettingsStore = .standard) {
|
||||
self.controller = controller; self.store = store; hardware = ControllerDevices()
|
||||
do { settings = try store.load() } catch {
|
||||
settings = InputSettings(); self.error = "Could not read input settings: \(error.localizedDescription)"
|
||||
}
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.poll() }
|
||||
}
|
||||
#if VCC_UI_TESTING
|
||||
// Keep the authored preview moving even during native menu tracking.
|
||||
if let timer { RunLoop.main.add(timer, forMode: .common) }
|
||||
#endif
|
||||
}
|
||||
deinit { timer?.invalidate() }
|
||||
func swap() { var next = settings; next.right = settings.left; next.left = settings.right; settings = next }
|
||||
func key(_ code: UInt16, down: Bool) -> Bool {
|
||||
routing.key(code, down: down, settings: settings)
|
||||
}
|
||||
func mouseMove(x: Double, y: Double) {
|
||||
guard x.isFinite, y.isFinite else { return }
|
||||
routing.mouse.x = Int(min(1, max(0, x)) * 16383)
|
||||
routing.mouse.y = Int(min(1, max(0, y)) * 16383)
|
||||
}
|
||||
func mouseLeave() { routing.mouse = JoystickSample() }
|
||||
func mouseButton(_ button: Int, down: Bool) {
|
||||
guard (0...1).contains(button) else { return }
|
||||
if down { routing.mouse.buttons |= 1 << button } else { routing.mouse.buttons &= ~(1 << button) }
|
||||
}
|
||||
func release() {
|
||||
routing.release(); last = []
|
||||
lastPollUptime = nil; lastApplicationActive = nil; lastDisplayAcceptsInput = nil
|
||||
submit([JoystickSample(), JoystickSample()])
|
||||
}
|
||||
private func poll() {
|
||||
#if VCC_UI_TESTING
|
||||
// Exercise the real preview/selection views with changing input even
|
||||
// when no physical controller is attached to the test Mac.
|
||||
let phase = ProcessInfo.processInfo.systemUptime
|
||||
let readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller",
|
||||
x: sin(phase), y: cos(phase), rx: sin(phase * 2), ry: cos(phase * 2))]
|
||||
#else
|
||||
let readings = hardware.read()
|
||||
#endif
|
||||
if devices != readings { devices = readings }
|
||||
let displayAcceptsInput = acceptsInput(), applicationActive = NSApp.isActive
|
||||
let active = displayAcceptsInput && applicationActive
|
||||
lastPollUptime = ProcessInfo.processInfo.systemUptime
|
||||
lastApplicationActive = applicationActive; lastDisplayAcceptsInput = displayAcceptsInput
|
||||
if active != lastActive { last = []; lastActive = active }
|
||||
let delivered = routing.delivery(settings: settings, devices: readings, active: active)
|
||||
let samples = routing.samples(settings: settings, devices: readings)
|
||||
if preview != samples { preview = samples }
|
||||
if delivered != last {
|
||||
last = delivered
|
||||
submit(delivered)
|
||||
}
|
||||
}
|
||||
private func submit(_ samples: [JoystickSample]) {
|
||||
submitted = samples; submittedInterfaces = (0..<2).map { settings[$0].interface }
|
||||
lastSubmissionUptime = ProcessInfo.processInfo.systemUptime
|
||||
for port in 0..<2 {
|
||||
controller.setJoystick(UInt(port), x: UInt(samples[port].x), y: UInt(samples[port].y),
|
||||
buttons: UInt(samples[port].buttons), mode: UInt(settings[port].interface.rawValue))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads cached native observations and a caller-supplied immutable machine
|
||||
/// snapshot. It never polls HID, changes focus/settings, or queues input.
|
||||
func diagnostics(machine: VCCMachineSnapshot) -> [String: Any] {
|
||||
let now = ProcessInfo.processInfo.systemUptime
|
||||
func age(_ time: TimeInterval?) -> Int? { time.map { Int(max(0, now - $0) * 1000) } }
|
||||
return Self.diagnostics(settings: settings, devices: devices,
|
||||
observation: InputDiagnosticObservation(preview: lastPollUptime == nil ? nil : preview,
|
||||
submitted: submitted, submittedInterfaces: submittedInterfaces,
|
||||
applicationActive: lastApplicationActive, displayAcceptsInput: lastDisplayAcceptsInput,
|
||||
pollAgeMilliseconds: age(lastPollUptime), submissionAgeMilliseconds: age(lastSubmissionUptime),
|
||||
settingsError: error != nil), machine: machine)
|
||||
}
|
||||
|
||||
static func unavailableDiagnostics(machine: VCCMachineSnapshot) -> [String: Any] {
|
||||
var result = diagnostics(settings: InputSettings(), devices: [], observation: InputDiagnosticObservation(), machine: machine)
|
||||
result["configuration_available"] = false; result["settings_error"] = NSNull()
|
||||
if let ports = result["ports"] as? [[String: Any]] {
|
||||
result["ports"] = ports.map { value -> [String: Any] in
|
||||
var port = value
|
||||
port["source"] = "unknown"
|
||||
for key in ["interface", "dead_zone", "controller_connected", "controller_mapping", "keyboard_binding"] { port[key] = NSNull() }
|
||||
return port
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
static func diagnostics(settings: InputSettings, devices: [ControllerReading],
|
||||
observation: InputDiagnosticObservation, machine: VCCMachineSnapshot) -> [String: Any] {
|
||||
func interface(_ mode: Int) -> String {
|
||||
switch mode { case 0: return "standard"; case 1: return "software"; case 2: return "tandy"; case 3: return "coco_max"; default: return "unknown" }
|
||||
}
|
||||
func source(_ value: JoystickSource) -> String {
|
||||
switch value { case .none: return "none"; case .keyboard: return "keyboard"; case .mouse: return "mouse"; case .controller: return "controller" }
|
||||
}
|
||||
func buttons(_ value: Int) -> [String] { [(value & 1) != 0 ? "fire1" : nil, (value & 2) != 0 ? "fire2" : nil].compactMap { $0 } }
|
||||
func sample(_ value: JoystickSample, mode: Int) -> [String: Any] {
|
||||
["x": value.x, "y": value.y, "buttons": buttons(value.buttons), "interface": interface(mode)]
|
||||
}
|
||||
let available = machine.state == .running || machine.state == .paused
|
||||
let focusActive: Bool? = observation.applicationActive.flatMap { app in observation.displayAcceptsInput.map { app && $0 } }
|
||||
let ports: [[String: Any]] = (0..<2).map { port in
|
||||
let config = settings[port]
|
||||
let preview: Any = observation.preview.flatMap { values in
|
||||
values.indices.contains(port) ? sample(values[port], mode: config.interface.rawValue) : nil
|
||||
} ?? NSNull()
|
||||
let submitted: Any = observation.submitted.flatMap { values in
|
||||
guard values.indices.contains(port), let modes = observation.submittedInterfaces, modes.indices.contains(port) else { return nil }
|
||||
return sample(values[port], mode: modes[port].rawValue)
|
||||
} ?? NSNull()
|
||||
let actual: Any
|
||||
if available, machine.joystickInputs.indices.contains(port) {
|
||||
let value = machine.joystickInputs[port]
|
||||
actual = sample(JoystickSample(x: Int(value.x), y: Int(value.y), buttons: Int(value.buttons)), mode: Int(value.mode))
|
||||
} else { actual = NSNull() }
|
||||
return ["port": port == 0 ? "right" : "left", "source": source(config.source),
|
||||
"interface": interface(config.interface.rawValue), "dead_zone": config.deadZone,
|
||||
"controller_connected": config.source == .controller ? devices.contains { $0.id == config.device } as Any : NSNull(),
|
||||
"controller_mapping": config.source == .controller
|
||||
? ["stick": config.rightStick ? "right" : "left", "fire1_button": config.fire1, "fire2_button": config.fire2] as Any : NSNull(),
|
||||
"keyboard_binding": config.source == .keyboard ? config.keys.rawValue as Any : NSNull(),
|
||||
"preview": preview, "submitted": submitted, "actual": actual]
|
||||
}
|
||||
return ["source": "shared_machine", "axis_min": 0, "axis_max": 16383, "axis_center": 8191,
|
||||
"x_direction": "right", "y_direction": "down", "configuration_available": true, "settings_error": observation.settingsError,
|
||||
"host_observation": ["age_ms": observation.pollAgeMilliseconds as Any? ?? NSNull(),
|
||||
"application_active": observation.applicationActive as Any? ?? NSNull(),
|
||||
"display_accepts_input": observation.displayAcceptsInput as Any? ?? NSNull(),
|
||||
"active": focusActive as Any? ?? NSNull()],
|
||||
"submission_age_ms": observation.submissionAgeMilliseconds as Any? ?? NSNull(),
|
||||
"submission_is_delivery_confirmation": false,
|
||||
"machine_observation": ["available": available, "generation": machine.generation,
|
||||
"frame": machine.frames, "cycles": machine.cycles,
|
||||
"keyboard_held": available ? machine.keyboardInputHeld as Any : NSNull()],
|
||||
"ports": ports]
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
enum JoystickSource: String, Codable, CaseIterable {
|
||||
case none = "None", keyboard = "Keyboard", mouse = "Mouse", controller = "Controller"
|
||||
}
|
||||
enum JoystickInterface: Int, Codable, CaseIterable {
|
||||
case standard = 0, software = 1, tandy = 2, cocoMax = 3
|
||||
var label: String { ["Standard", "Software high resolution", "Tandy high resolution", "CoCoMax"][rawValue] }
|
||||
}
|
||||
enum JoystickKeys: String, Codable, CaseIterable {
|
||||
case arrows = "Arrows + Z / X", wasd = "W A S D + F / G", keypad = "Keypad 8 2 4 6 + 0 / ."
|
||||
// up, down, left, right, fire 1, fire 2
|
||||
var codes: [UInt16] {
|
||||
switch self {
|
||||
case .arrows: return [126,125,123,124,6,7]
|
||||
case .wasd: return [13,1,0,2,3,5]
|
||||
case .keypad: return [91,84,86,88,82,65]
|
||||
}
|
||||
}
|
||||
}
|
||||
struct PortSettings: Codable, Equatable {
|
||||
var source: JoystickSource = .none
|
||||
var interface: JoystickInterface = .standard
|
||||
var keys: JoystickKeys = .arrows
|
||||
var device = ""
|
||||
var rightStick = false
|
||||
var fire1 = 1, fire2 = 2
|
||||
var deadZone = 0.15
|
||||
}
|
||||
struct InputSettings: Codable, Equatable {
|
||||
var keyboard: KeyboardMode = .natural
|
||||
var right = PortSettings(), left = PortSettings(keys: .wasd)
|
||||
subscript(port: Int) -> PortSettings {
|
||||
get { port == 0 ? right : left }
|
||||
set { if port == 0 { right = newValue } else { left = newValue } }
|
||||
}
|
||||
func validated() throws -> Self {
|
||||
for p in [right, left] {
|
||||
guard p.deadZone.isFinite, (0...0.5).contains(p.deadZone),
|
||||
(1...16).contains(p.fire1), (1...16).contains(p.fire2), p.device.count < 1024 else {
|
||||
throw CocoaError(.coderReadCorrupt)
|
||||
}
|
||||
}
|
||||
return self
|
||||
}
|
||||
}
|
||||
struct InputSettingsStore {
|
||||
let url: URL
|
||||
static let standard = InputSettingsStore(url: AppIdentity.supportDirectory.appendingPathComponent("InputSettings.json"))
|
||||
func load() throws -> InputSettings {
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return InputSettings() }
|
||||
return try JSONDecoder().decode(InputSettings.self, from: Data(contentsOf: url)).validated()
|
||||
}
|
||||
func save(_ value: InputSettings) throws {
|
||||
_ = try value.validated()
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(value).write(to: url, options: .atomic)
|
||||
}
|
||||
}
|
||||
struct JoystickSample: Equatable {
|
||||
var x = 8191, y = 8191, buttons = 0
|
||||
static func axis(_ value: Double, deadZone: Double) -> Int {
|
||||
guard value.isFinite else { return 8191 }
|
||||
let v = min(1, max(-1, value)), dead = min(0.5, max(0, deadZone))
|
||||
if abs(v) <= dead { return 8191 }
|
||||
let adjusted = (abs(v) - dead) / (1 - dead) * (v < 0 ? -1 : 1)
|
||||
return Int(((adjusted + 1) * 8191.5).rounded())
|
||||
}
|
||||
static func keyboard(_ held: Set<UInt16>, keys: JoystickKeys) -> Self {
|
||||
let down = keys.codes.map { held.contains($0) }
|
||||
func axis(_ low: Bool, _ high: Bool) -> Int { low == high ? 8191 : (low ? 0 : 16383) }
|
||||
return Self(x: axis(down[2], down[3]), y: axis(down[0], down[1]), buttons: (down[4] ? 1 : 0) | (down[5] ? 2 : 0))
|
||||
}
|
||||
}
|
||||
|
||||
// Device-independent host state. Focus loss drops held keys/buttons; a missing
|
||||
// remembered controller always yields neutral input, never another device.
|
||||
struct InputRouting {
|
||||
private(set) var held: Set<UInt16> = []
|
||||
var mouse = JoystickSample()
|
||||
mutating func key(_ code: UInt16, down: Bool, settings: InputSettings) -> Bool {
|
||||
let reserved = [settings.right, settings.left].contains { $0.source == .keyboard && $0.keys.codes.contains(code) }
|
||||
if down && reserved { held.insert(code) } else { held.remove(code) }
|
||||
return reserved
|
||||
}
|
||||
mutating func release() { held.removeAll(); mouse = JoystickSample() }
|
||||
func samples(settings: InputSettings, devices: [ControllerReading]) -> [JoystickSample] {
|
||||
(0..<2).map { port in
|
||||
let config = settings[port]
|
||||
switch config.source {
|
||||
case .none: return JoystickSample()
|
||||
case .keyboard: return .keyboard(held, keys: config.keys)
|
||||
case .mouse: return mouse
|
||||
case .controller: return devices.first { $0.id == config.device }?.sample(config) ?? JoystickSample()
|
||||
}
|
||||
}
|
||||
}
|
||||
mutating func delivery(settings: InputSettings, devices: [ControllerReading], active: Bool) -> [JoystickSample] {
|
||||
guard active else { release(); return [JoystickSample(), JoystickSample()] }
|
||||
return samples(settings: settings, devices: devices)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#if DEBUG
|
||||
import Foundation
|
||||
|
||||
// Opt-in native UI validation. Uses a fresh temporary directory, an isolated
|
||||
// preference suite and authored media. Never reads the user's assignments.
|
||||
// An explicit --orchestra-listening SYSTEM_ROM ORCHESTRA_ROM invocation can
|
||||
// replace only those two fixture ROMs for a manual listening check.
|
||||
// --speech-listening SYSTEM_ROM PIC_ROM SPEECH_ROM similarly opts into real
|
||||
// chip ROMs for an isolated, bounded speech check.
|
||||
// --sdc-validation SYSTEM_ROM SDC_ROM CARD_FOLDER [--sdc-6309] boots protected
|
||||
// real SDC media at BASIC without typing commands. --sdc-fixture uses authored
|
||||
// media only. Both modes run exclusively inside this isolated context.
|
||||
@MainActor
|
||||
final class InterfaceValidation {
|
||||
let directory: URL
|
||||
let defaults: UserDefaults
|
||||
private let controller = VCCMachineController()
|
||||
private var measurement: Task<Void, Never>?
|
||||
private let suite: String
|
||||
init() throws {
|
||||
directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString)
|
||||
suite = "VCCInterfaceUI-" + UUID().uuidString
|
||||
defaults = UserDefaults(suiteName: suite)!
|
||||
// Ordinary interaction tests represent a returning user; the dedicated
|
||||
// first-use test exercises a fresh guide history through real commands.
|
||||
if !CommandLine.arguments.contains("--first-guide-fixture") {
|
||||
let presentation = PresentationSettings(defaults: defaults)
|
||||
for profile in SystemProfile.allCases { presentation.didShowGuide(profile) }
|
||||
}
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
// Synthetic system-profile payload: never read private bundled ROMs in UI tests.
|
||||
let kit = directory.appendingPathComponent("Authored StarterKit")
|
||||
try FileManager.default.createDirectory(at: kit, withIntermediateDirectories: true)
|
||||
var rom = Data(repeating: 0x12, count: 32768)
|
||||
rom[0] = 0x20; rom[1] = 0xfe; rom[32766] = 0x80; rom[32767] = 0
|
||||
try rom.write(to: kit.appendingPathComponent("coco3.rom"))
|
||||
for name in ["disk11.rom", "rgbdos.rom", "sdcdos.rom"] {
|
||||
try Data(repeating: 0,count:8192).write(to:kit.appendingPathComponent(name))
|
||||
}
|
||||
// Explicit real-ROM acceptance uses only copies in this disposable kit.
|
||||
// Library startup prefers the kit, so it must match the selected test ROMs.
|
||||
if let system = ProcessInfo.processInfo.environment["VCC_BASIC_SYSTEM_ROM"],
|
||||
let disk = ProcessInfo.processInfo.environment["VCC_BASIC_DISK_ROM"] {
|
||||
let systemBytes = try ROMImage.read(URL(fileURLWithPath: system))
|
||||
let diskBytes = try DiskFiles.readROM(URL(fileURLWithPath: disk))
|
||||
try systemBytes.write(to: kit.appendingPathComponent("coco3.rom"))
|
||||
try diskBytes.write(to: kit.appendingPathComponent("disk11.rom"))
|
||||
}
|
||||
for name in ["Hello World.dsk", "Hello Hard Disk.dsk", "Blank Disk.dsk"] {
|
||||
try Data(repeating: 0,count:161280).write(to:kit.appendingPathComponent(name))
|
||||
}
|
||||
if let resource = Bundle.main.url(forResource: "Blank OS9 Header", withExtension: "bin") {
|
||||
try FileManager.default.copyItem(at: resource, to: kit.appendingPathComponent("Blank OS9 Header.bin"))
|
||||
}
|
||||
try Data([0x55,0x55,0x3c]).write(to:kit.appendingPathComponent("Hello World.cas"))
|
||||
}
|
||||
func makeModel() -> MachineModel {
|
||||
MachineModel(diskStore: .init(url: directory.appendingPathComponent("assignments.json")), controller: controller, displayDefaults: defaults,
|
||||
inputStore: .init(url: directory.appendingPathComponent("input.json")),
|
||||
startupStore: .init(directory:directory,kit:.init(directory:directory.appendingPathComponent("Authored StarterKit"))))
|
||||
}
|
||||
func install(in model: MachineModel) async throws {
|
||||
for _ in 0..<500 { if !model.busy { break }; try await Task.sleep(nanoseconds: 10_000_000) }
|
||||
if CommandLine.arguments.contains("--first-guide-fixture") { return }
|
||||
var profile = ConfigurationProfile(name: "Interface validation")
|
||||
func file(_ name: String, _ bytes: Data) throws -> URL {
|
||||
let url = directory.appendingPathComponent(name); try bytes.write(to: url); return url
|
||||
}
|
||||
profile.media.rom = try file("Authored controller.rom", Data(repeating: 0, count: 8192))
|
||||
profile.media.drives[0] = .init(url: try file("Authored FD0.dsk", Data(repeating: 0, count: 161280)), writeProtected: true, temporary: false)
|
||||
#if VCC_UI_TESTING
|
||||
if ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_HARD"] != "1", let image = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_IMAGE"] {
|
||||
// Explicit authored input for the isolated UI target only. The editor
|
||||
// works on this private copy, never on the fixture's source image.
|
||||
let input = try DiskFiles.readImage(URL(fileURLWithPath: image))
|
||||
let mounted = try file("Authored FD0.dsk", input.data)
|
||||
profile.media.drives[0] = .init(url: mounted, writeProtected: false, temporary: false)
|
||||
if let receipt = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_RECEIPT"] {
|
||||
try JSONSerialization.data(withJSONObject: ["mounted_image": mounted.path, "byte_count": input.data.count])
|
||||
.write(to: URL(fileURLWithPath: receipt), options: .atomic)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
var hard = HardDiskAssignments()
|
||||
hard.drives[0] = .init(url: try file("Authored HD0.vhd", Data(repeating: 0, count: 4096)), writeProtected: true, temporary: false)
|
||||
#if VCC_UI_TESTING
|
||||
if ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_HARD"] == "1",
|
||||
let image = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_IMAGE"] {
|
||||
let input = try DiskEditorIO.readImage(URL(fileURLWithPath: image))
|
||||
let mounted = try file("Authored HD0.vhd", input.data)
|
||||
hard.drives[0] = .init(url: mounted, writeProtected: false, temporary: false)
|
||||
hard.drives[1] = .init(url: try file("Authored HD1.vhd", input.data), writeProtected: false, temporary: false)
|
||||
if let receipt = ProcessInfo.processInfo.environment["VCC_DISK_EDITOR_TEST_RECEIPT"] {
|
||||
try JSONSerialization.data(withJSONObject: ["mounted_image": mounted.path, "byte_count": input.data.count])
|
||||
.write(to: URL(fileURLWithPath: receipt), options: .atomic)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
profile.media.hardDisks = hard
|
||||
let rom = try file("Authored cartridge.ccc", Data(repeating: 0x12, count: 8192))
|
||||
var cartridges = CartridgeAssignments(); cartridges.multiPak = true; cartridges.mpiConfigured = true
|
||||
cartridges.slots[1] = .init(kind: .rom, url: rom); cartridges.slots[2] = .init(kind: .rom, url: rom)
|
||||
cartridges.slots[3].kind = .hardDisk; cartridges.slots[4].kind = .floppy
|
||||
profile.media.cartridges = cartridges
|
||||
profile.cassette = try file("Authored tape.cas", Data([0x55, 0x55, 0x3c]))
|
||||
profile.sound = false
|
||||
#if VCC_UI_TESTING
|
||||
profile.sound = true; profile.volume = 0
|
||||
#endif
|
||||
#if VCC_UI_TESTING
|
||||
if CommandLine.arguments.contains("--shell-permission-fixture") {
|
||||
// Poll DWINIT until the test enables networking, then issue a single
|
||||
// real Becker channel request. This fixture never sends a shell command.
|
||||
var code: [UInt8] = [0x1a, 0x50] // ORCC: mask interrupts
|
||||
let poll = code.count
|
||||
func send(_ bytes: [UInt8]) {
|
||||
for byte in bytes { code += [0x86, byte, 0xb7, 0xff, 0x42] } // LDA immediate, STA Becker
|
||||
}
|
||||
send([0x5a, 0])
|
||||
code += [0xb6, 0xff, 0x41, 0x27] // LDA status, BEQ poll
|
||||
code.append(UInt8(bitPattern: Int8(poll - code.count - 1)))
|
||||
code += [0xb6, 0xff, 0x42] // consume DWINIT result
|
||||
let request = Array("tcp connect macshell 2323\r".utf8)
|
||||
send([0x45, 0, 0x64, 0, UInt8(request.count)] + request)
|
||||
code += [0x20, 0xfe]
|
||||
var rom = Data(repeating: 0x12, count: 32768)
|
||||
rom.replaceSubrange(0..<code.count, with: code)
|
||||
rom[32766] = 0x80; rom[32767] = 0
|
||||
profile.systemROM = try file("Shell Permission Test.rom", rom)
|
||||
profile.media.cartridges?.physicalSlot = 4
|
||||
await model.loadProfile(profile)
|
||||
if let error = model.profileError { throw ProfileFailure.message(error) }
|
||||
model.resume(); return
|
||||
}
|
||||
if CommandLine.arguments.contains("--library-play-fixture") {
|
||||
// Return-to-setup must reference a real authored ROM file. The normal
|
||||
// diagnostic loader intentionally clears systemROMURL, so it cannot
|
||||
// represent the saved, restartable configuration this test requires.
|
||||
profile.systemROM = directory.appendingPathComponent("Authored StarterKit/coco3.rom")
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume()
|
||||
print("Library play validation fixture: \(directory.path)")
|
||||
return
|
||||
}
|
||||
#endif
|
||||
// Explicit local ROM inputs, isolated preferences and authored media.
|
||||
if let system = ProcessInfo.processInfo.environment["VCC_BASIC_SYSTEM_ROM"],
|
||||
let disk = ProcessInfo.processInfo.environment["VCC_BASIC_DISK_ROM"] {
|
||||
profile.systemROM = URL(fileURLWithPath: system)
|
||||
profile.media.rom = URL(fileURLWithPath: disk)
|
||||
profile.machine.use6309 = CommandLine.arguments.contains("--basic-6309")
|
||||
profile.input = InputSettings()
|
||||
profile.sound = false
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume()
|
||||
return
|
||||
}
|
||||
// Optional real-ROM cartridge check. Still uses this fixture's isolated
|
||||
// stores; never mutates the supplied cartridge or normal app settings.
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--cartridge-validation") {
|
||||
guard CommandLine.arguments.count > index + 2 else {
|
||||
throw ProfileFailure.message("Supply system ROM and cartridge paths.")
|
||||
}
|
||||
var cartridgeProfile = ConfigurationProfile(name: "Authored cartridge validation setup")
|
||||
cartridgeProfile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index + 1])
|
||||
cartridgeProfile.machine.use6309 = CommandLine.arguments.contains("--cartridge-6309")
|
||||
cartridgeProfile.input = InputSettings()
|
||||
var layout = CartridgeAssignments()
|
||||
layout.multiPak = true; layout.mpiConfigured = true; layout.physicalSlot = 4
|
||||
layout.slots[4] = .init(kind: .rom, url: URL(fileURLWithPath: CommandLine.arguments[index + 2]))
|
||||
cartridgeProfile.media.cartridges = layout
|
||||
cartridgeProfile.sound = false
|
||||
await model.loadProfile(cartridgeProfile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume()
|
||||
print("Cartridge validation fixture: \(directory.path)")
|
||||
return
|
||||
}
|
||||
let realSDC = CommandLine.arguments.firstIndex(of: "--sdc-validation")
|
||||
if realSDC != nil || CommandLine.arguments.contains("--sdc-fixture") {
|
||||
#if !VCC_UI_TESTING
|
||||
guard CommandLine.arguments.contains("--interface-validation") else {
|
||||
throw ProfileFailure.message("SDC validation requires --interface-validation to isolate settings and media.")
|
||||
}
|
||||
#endif
|
||||
var sdcProfile = ConfigurationProfile(name: realSDC == nil ? "Authored SDC validation" : "SDC compatibility validation")
|
||||
sdcProfile.machine.ram = 2 // 2 MB: the Double Dragon build's requirement.
|
||||
sdcProfile.machine.use6309 = CommandLine.arguments.contains("--sdc-6309")
|
||||
sdcProfile.input = InputSettings() // No joystick key capture; the game uses CoCo keys.
|
||||
sdcProfile.sound = true; sdcProfile.volume = realSDC == nil ? 0 : 0.3
|
||||
let card: URL, sdcROM: URL
|
||||
if let index = realSDC {
|
||||
guard CommandLine.arguments.count > index + 3 else {
|
||||
throw ProfileFailure.message("Supply system ROM, SDC-DOS ROM and SD card folder paths.")
|
||||
}
|
||||
sdcProfile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index + 1])
|
||||
sdcROM = URL(fileURLWithPath: CommandLine.arguments[index + 2])
|
||||
card = URL(fileURLWithPath: CommandLine.arguments[index + 3], isDirectory: true)
|
||||
} else {
|
||||
card = directory.appendingPathComponent("Authored SD Card", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: card, withIntermediateDirectories: true)
|
||||
try Data(repeating: 0, count: 161280).write(to: card.appendingPathComponent("ONE.DSK"))
|
||||
try Data("0=ONE.DSK\n".utf8).write(to: card.appendingPathComponent("startup.cfg"))
|
||||
sdcROM = try file("Authored SDC-DOS.rom", Data(repeating: 0x12, count: 16384))
|
||||
}
|
||||
var sdcLayout = CartridgeAssignments()
|
||||
sdcLayout.multiPak = true; sdcLayout.mpiConfigured = true; sdcLayout.physicalSlot = 4
|
||||
// Optional isolated artwork check at each real Multi-Pak depth.
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--sdc-slot"),
|
||||
CommandLine.arguments.count > index + 1,
|
||||
let slot = Int(CommandLine.arguments[index + 1]), (1...4).contains(slot) {
|
||||
sdcLayout.physicalSlot = slot
|
||||
}
|
||||
sdcLayout.slots[sdcLayout.physicalSlot] = .init(kind: .sdc, url: sdcROM, sdcFolderURL: card, sdcReadOnly: true)
|
||||
sdcProfile.media.cartridges = sdcLayout
|
||||
await model.loadProfile(sdcProfile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
if realSDC == nil {
|
||||
model.loadDiagnostic()
|
||||
for _ in 0..<500 { if !model.busy { break }; try await Task.sleep(nanoseconds: 10_000_000) }
|
||||
}
|
||||
model.resume()
|
||||
print("SDC validation fixture: \(directory.path); protected card: \(card.path)")
|
||||
return
|
||||
}
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--audio-game-listening") {
|
||||
guard CommandLine.arguments.count > index + 2 else { throw ProfileFailure.message("Supply a ROM directory and DOS-boot disk image.") }
|
||||
let roms = URL(fileURLWithPath: CommandLine.arguments[index + 1], isDirectory: true)
|
||||
let input = try DiskFiles.readImage(URL(fileURLWithPath: CommandLine.arguments[index + 2]))
|
||||
profile.systemROM = roms.appendingPathComponent("coco3.rom")
|
||||
profile.media.rom = roms.appendingPathComponent("disk11.rom")
|
||||
profile.media.drives[0] = .init(url: try file("Audio validation copy.dsk", input.data), writeProtected: false, temporary: true)
|
||||
var layout = CartridgeAssignments(); layout.multiPak = true; layout.mpiConfigured = true; layout.physicalSlot = 4
|
||||
layout.slots[1] = .init(kind: .speechSound, url: roms.appendingPathComponent("pic-7040-510.bin"), speechROMURL: roms.appendingPathComponent("sp0256-al2.bin"))
|
||||
layout.slots[2] = .init(kind: .orchestra90, url: roms.appendingPathComponent("orch90.rom"))
|
||||
layout.slots[4].kind = .floppy; profile.media.cartridges = layout
|
||||
profile.sound = true; profile.volume = 0.25
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume()
|
||||
measurement = Task { @MainActor in
|
||||
do {
|
||||
try await Task.sleep(nanoseconds: 3_000_000_000)
|
||||
for bit in [4, 15, 19, 48] { // DOS through the normal keyboard
|
||||
controller.setKeyboardMask(UInt64(1) << bit)
|
||||
try await Task.sleep(nanoseconds: 100_000_000)
|
||||
controller.setKeyboardMask(0)
|
||||
try await Task.sleep(nanoseconds: 150_000_000)
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 35_000_000_000)
|
||||
let before = await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } }
|
||||
try await Task.sleep(nanoseconds: 3_000_000_000)
|
||||
let after = await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } }
|
||||
#if VCC_UI_TESTING
|
||||
if let path = ProcessInfo.processInfo.environment["VCC_AUDIO_GAME_RECEIPT"] {
|
||||
let receipt: [String: Any] = ["frames_before": before.frames, "frames_after": after.frames,
|
||||
"consumed_before": before.audioConsumed, "consumed_after": after.audioConsumed,
|
||||
"signal_before": before.audioSignalSamples, "signal_after": after.audioSignalSamples,
|
||||
"starts_before": before.audioStarts, "starts_after": after.audioStarts,
|
||||
"audio_enabled": after.audioEnabled, "volume": model.volume,
|
||||
"tape_position": after.tapePosition]
|
||||
try JSONSerialization.data(withJSONObject: receipt).write(to: URL(fileURLWithPath: path), options: .atomic)
|
||||
}
|
||||
#endif
|
||||
model.pause()
|
||||
} catch { controller.setKeyboardMask(0); model.pause() }
|
||||
}
|
||||
return
|
||||
}
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--speech-listening") {
|
||||
guard CommandLine.arguments.count > index + 3 else { throw ProfileFailure.message("Supply system, PIC and speech ROM paths.") }
|
||||
profile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index+1])
|
||||
profile.media.cartridges?.slots[1] = .init(kind: .speechSound,
|
||||
url: URL(fileURLWithPath: CommandLine.arguments[index+2]),
|
||||
speechROMURL: URL(fileURLWithPath: CommandLine.arguments[index+3]))
|
||||
// Use the real system BASIC; the authored floppy ROM is not bootable.
|
||||
profile.media.cartridges?.physicalSlot = 2
|
||||
profile.media.cartridges?.slots[2] = .init()
|
||||
profile.sound = true; profile.volume = 0.4
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume()
|
||||
measurement = Task { @MainActor in
|
||||
do {
|
||||
try await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
let bytes = Array("HELLO FROM YOUR COLOR COMPUTER. \r".utf8)
|
||||
let end = 0x3040 + bytes.count
|
||||
// The authored guest routes the real cartridge SND input.
|
||||
var code: [UInt8] = [0xb6,0xff,0x01,0x84,0xf7,0xb7,0xff,0x01,
|
||||
0xb6,0xff,0x03,0x8a,0x08,0xb7,0xff,0x03,
|
||||
0xb6,0xff,0x23,0x8a,0x08,0xb7,0xff,0x23,0x8e,0x30,0x40,0x8c,UInt8(end >> 8),UInt8(end & 255),0x27,12,
|
||||
0xe6,0x80,0xb6,0xff,0x7e,0x2a,0xfb,0xf7,0xff,0x7e,0x20,0xef,0x20,0xfe]
|
||||
code += Array(repeating: 0x12, count: 64-code.count); code += bytes
|
||||
let binary = Data([0,0,UInt8(code.count),0x30,0] + code + [0xff,0,0,0x30,0])
|
||||
await withCheckedContinuation { done in controller.quickLoadBinary(binary) { _ in done.resume() } }
|
||||
try await Task.sleep(nanoseconds: 12_000_000_000)
|
||||
model.pause()
|
||||
} catch { model.pause() }
|
||||
}
|
||||
return
|
||||
}
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--orchestra-listening") {
|
||||
guard CommandLine.arguments.count > index + 2 else { throw ProfileFailure.message("Supply system and Orchestra-90 ROM paths for the listening check.") }
|
||||
profile.systemROM = URL(fileURLWithPath: CommandLine.arguments[index+1])
|
||||
profile.media.cartridges?.slots[1] = .init(kind: .orchestra90, url: URL(fileURLWithPath: CommandLine.arguments[index+2]))
|
||||
profile.media.cartridges?.physicalSlot = 1
|
||||
profile.sound = true; profile.volume = 0.25
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume()
|
||||
measurement = Task { @MainActor in
|
||||
do {
|
||||
@MainActor func key(_ bit: Int) async throws {
|
||||
controller.setKeyboardMask(UInt64(1) << bit)
|
||||
try await Task.sleep(nanoseconds: 100_000_000)
|
||||
controller.setKeyboardMask(0)
|
||||
try await Task.sleep(nanoseconds: 150_000_000)
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 3_000_000_000)
|
||||
try await key(31) // Copyright screen: any key.
|
||||
try await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
try await key(19); try await key(48) // S, Return: score.
|
||||
try await Task.sleep(nanoseconds: 5_000_000_000)
|
||||
try await key(16); try await key(48) // P, Return: play.
|
||||
NSLog("Orchestra-90 listening check: William Tell playback requested at 25%% volume.")
|
||||
try await Task.sleep(nanoseconds: 75_000_000_000)
|
||||
model.pause()
|
||||
} catch { controller.setKeyboardMask(0) }
|
||||
}
|
||||
return
|
||||
}
|
||||
// Opt-in authored printer fixture: guest instructions drive the real PIA
|
||||
// output path. No injected host bytes and no private system ROM needed.
|
||||
if CommandLine.arguments.contains("--printer-fixture") {
|
||||
var code: [UInt8] = [0x1a, 0x50, 0x86, 0, 0xb7, 0xff, 0x21,
|
||||
0x86, 0xff, 0xb7, 0xff, 0x20, 0x86, 4, 0xb7, 0xff, 0x21]
|
||||
let start = UInt16(0x8000 + code.count)
|
||||
for byte in "HELLO FROM PRINTER\r10 PRINT \"HELLO WORLD\"\r".utf8 {
|
||||
for bit in [UInt8(0)] + (0..<8).map({ (byte >> $0) & 1 }) + [UInt8(1)] {
|
||||
code += [0x86, bit << 1, 0xb7, 0xff, 0x20]
|
||||
}
|
||||
}
|
||||
code += [0x8e, 0xff, 0xff, 0x30, 0x1f, 0x26, 0xfc, 0x7e, UInt8(start >> 8), UInt8(start & 255)]
|
||||
var rom = Data(repeating: 0x12, count: 32768)
|
||||
rom.replaceSubrange(0..<code.count, with: code)
|
||||
rom[32766] = 0x80; rom[32767] = 0
|
||||
profile.systemROM = try file("Authored Printer.rom", rom)
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.resume(); return
|
||||
}
|
||||
await model.loadProfile(profile)
|
||||
guard model.profileError == nil else { throw ProfileFailure.message(model.profileError!) }
|
||||
model.loadDiagnostic()
|
||||
for _ in 0..<500 { if !model.busy { break }; try await Task.sleep(nanoseconds: 10_000_000) }
|
||||
model.resume()
|
||||
print("Interface validation fixture: \(directory.path)")
|
||||
}
|
||||
// Optional two-minute live UI measurement: actual audio consumption, muted
|
||||
// gain, three presentations, no ROMs and no writes outside this fixture.
|
||||
func measure(_ model: MachineModel, presentation: PresentationSettings) {
|
||||
guard CommandLine.arguments.contains("--interface-measure") else { return }
|
||||
measurement = Task { @MainActor in
|
||||
model.volume = 0; model.setAudio(true)
|
||||
do {
|
||||
try await Task.sleep(nanoseconds: 5_000_000_000)
|
||||
@MainActor func sample() async -> VCCMachineSnapshot {
|
||||
await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } }
|
||||
}
|
||||
let baseline = await sample(), start = ProcessInfo.processInfo.systemUptime
|
||||
var rows: [[String: Any]] = []
|
||||
for second in 1...120 {
|
||||
try await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
let current = await sample()
|
||||
rows.append(["elapsed": ProcessInfo.processInfo.systemUptime-start,
|
||||
"frames": current.frames-baseline.frames,
|
||||
"consumed": current.audioConsumed-baseline.audioConsumed,
|
||||
"submitted": current.audioSubmitted-baseline.audioSubmitted,
|
||||
"underruns": current.audioUnderruns-baseline.audioUnderruns,
|
||||
"overruns": current.audioOverruns-baseline.audioOverruns,
|
||||
"starts": current.audioStarts-baseline.audioStarts,
|
||||
"generationChanged": current.generation != baseline.generation,
|
||||
"error": current.errorMessage ?? ""])
|
||||
if second % 20 == 0 {
|
||||
presentation.mode = second % 60 == 0 ? .display : .system
|
||||
presentation.expanded = second % 60 == 40
|
||||
}
|
||||
let data = try JSONSerialization.data(withJSONObject: rows, options: [.prettyPrinted, .sortedKeys])
|
||||
try data.write(to: directory.appendingPathComponent("measurement.json"), options: .atomic)
|
||||
}
|
||||
model.pause()
|
||||
} catch is CancellationError { }
|
||||
catch { NSLog("Interface measurement failed: %@", error.localizedDescription) }
|
||||
}
|
||||
}
|
||||
func cleanUp() {
|
||||
measurement?.cancel()
|
||||
defaults.removePersistentDomain(forName: suite)
|
||||
try? FileManager.default.removeItem(at: directory)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,649 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import Combine
|
||||
import Darwin
|
||||
|
||||
fileprivate struct BASICEditProposal: Identifiable {
|
||||
let id = UUID().uuidString
|
||||
let requestID: String, revision: Int, line: Int?, before: String, after: String
|
||||
var status = "pending"
|
||||
var appliedRevision: Int?
|
||||
var subject: String { line.map { "BASIC line " + String($0) } ?? "Complete BASIC listing" }
|
||||
|
||||
func range(in source: String) -> NSRange? {
|
||||
if let line { return BASICLanguage.lineRange(for: line, in: source) }
|
||||
return NSRange(location: 0, length: (source as NSString).length)
|
||||
}
|
||||
|
||||
var result: [String: Any] {
|
||||
var result: [String: Any] = ["proposal_id": id, "revision": revision, "status": status]
|
||||
if let line { result["line_number"] = line } else { result["kind"] = "listing" }
|
||||
if let appliedRevision { result["applied_revision"] = appliedRevision }
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class MCPAccess: ObservableObject {
|
||||
static let shared = MCPAccess()
|
||||
fileprivate weak var selected: BASICDevelopmentModel?
|
||||
@Published fileprivate(set) var activeTitle: String?
|
||||
@Published fileprivate(set) var message: String?
|
||||
private var listener: MCPTransport?
|
||||
private var pendingGrant = UUID()
|
||||
private weak var pendingModel: BASICDevelopmentModel?
|
||||
private weak var panelModel: BASICDevelopmentModel?
|
||||
private var token = ""
|
||||
private var sessionID = ""
|
||||
private var documentID: UUID?
|
||||
fileprivate var grantFile: MCPGrantFile?
|
||||
private var documentChange: AnyCancellable?
|
||||
private var panel: NSPanel?
|
||||
private let guest = MCPBASICRun()
|
||||
@Published fileprivate var canPropose = false
|
||||
@Published fileprivate var current: BASICEditProposal?
|
||||
private var history: [String: BASICEditProposal] = [:]
|
||||
private var reviewWindow: NSPanel?
|
||||
private var fixtureLabel: String?
|
||||
private var regressionFixture = false
|
||||
#if DEBUG
|
||||
private var fixtureEditor: NSWindow?
|
||||
#endif
|
||||
#if DEBUG
|
||||
private var fixturePoll: Task<Void, Never>?
|
||||
#endif
|
||||
|
||||
func show(for model: BASICDevelopmentModel) {
|
||||
panel?.close()
|
||||
let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 550, height: 510),
|
||||
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
||||
window.title = "Connect to ChatGPT or Another Assistant"
|
||||
window.isReleasedWhenClosed = false
|
||||
window.contentMinSize = NSSize(width: 360, height: 230)
|
||||
let content = NSHostingView(rootView: ScrollView { MCPAccessView(access: self, model: model) })
|
||||
content.sizingOptions = []
|
||||
window.contentView = content
|
||||
window.center()
|
||||
panel = window
|
||||
panelModel = model
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
fileprivate func chooseGrant(for model: BASICDevelopmentModel, proposals: Bool) {
|
||||
guard let owner = panel, panelModel === model, owner.isVisible,
|
||||
!owner.isMiniaturized, owner.attachedSheet == nil else { return }
|
||||
let draft = model.documentID, connection = sessionID, generation = pendingGrant
|
||||
let picker = NSSavePanel()
|
||||
picker.nameFieldStringValue = "VCC Plus OSS Connection.json"
|
||||
picker.title = proposals ? "Save Review and Run Connection" : "Save Read-Only Connection"
|
||||
picker.message = "Choose a new local file. Give it only to assistants you trust to read this program."
|
||||
picker.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in
|
||||
Task { @MainActor [weak self, weak owner, weak model] in
|
||||
guard let self, let owner, let model else { return }
|
||||
@MainActor func currentPresentation() -> Bool {
|
||||
self.panel === owner && self.panelModel === model && owner.isVisible &&
|
||||
!owner.isMiniaturized && model.documentID == draft
|
||||
}
|
||||
guard currentPresentation(), self.sessionID == connection, self.pendingGrant == generation else { return }
|
||||
defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } }
|
||||
guard response == .OK, let url = picker.url else { return }
|
||||
do { try await self.grant(model, at: url, proposals: proposals, presentationIsCurrent: currentPresentation) }
|
||||
catch is CancellationError { }
|
||||
catch {
|
||||
if currentPresentation() { self.message = "Could not create a new connection file. " + error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func grant(_ model: BASICDevelopmentModel, at url: URL, proposals: Bool = false,
|
||||
presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws {
|
||||
let ticket = UUID()
|
||||
pendingGrant = ticket
|
||||
pendingModel = model
|
||||
defer { if pendingGrant == ticket { pendingModel = nil } }
|
||||
let draft = model.documentID
|
||||
let id = UUID().uuidString
|
||||
let secret = UUID().uuidString + UUID().uuidString
|
||||
let callback: MCPTransport.Handler = { [weak self] request in
|
||||
guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) }
|
||||
return await self.reply(to: request, session: id)
|
||||
}
|
||||
let (server, file) = try await Task.detached(priority: .userInitiated) {
|
||||
let server = try MCPTransport(handler: callback)
|
||||
let data = try JSONSerialization.data(withJSONObject: ["socket": server.unixPath, "port": Int(server.port),
|
||||
"version": 1, "toolset": 3, "token": secret, "canPropose": proposals])
|
||||
return (server, try MCPGrantFile(create: url, data: data))
|
||||
}.value
|
||||
guard ticket == pendingGrant, model.documentID == draft, presentationIsCurrent?() != false else {
|
||||
Task.detached { server.stop(); file.remove() }
|
||||
throw CancellationError()
|
||||
}
|
||||
revoke()
|
||||
selected = model
|
||||
sessionID = id
|
||||
token = secret
|
||||
documentID = model.documentID
|
||||
grantFile = file
|
||||
listener = server
|
||||
canPropose = proposals
|
||||
activeTitle = model.title
|
||||
message = nil
|
||||
documentChange = model.$documentID.dropFirst().sink { [weak self] _ in _ = self?.revoke() }
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func revoke() -> Task<Void, Never> {
|
||||
pendingGrant = UUID()
|
||||
pendingModel = nil
|
||||
token = ""
|
||||
canPropose = false
|
||||
current = nil
|
||||
history.removeAll()
|
||||
guest.reset()
|
||||
reviewWindow?.orderOut(nil)
|
||||
reviewWindow = nil
|
||||
selected = nil
|
||||
documentID = nil
|
||||
sessionID = ""
|
||||
documentChange = nil
|
||||
activeTitle = nil
|
||||
let old = listener, file = grantFile
|
||||
listener = nil
|
||||
grantFile = nil
|
||||
return Task.detached {
|
||||
old?.stop()
|
||||
file?.remove()
|
||||
}
|
||||
}
|
||||
|
||||
func closing(_ model: BASICDevelopmentModel) {
|
||||
if selected === model || pendingModel === model { revoke() }
|
||||
if panelModel === model {
|
||||
panel?.close()
|
||||
panel = nil
|
||||
panelModel = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func reply(to data: Data, session: String) async -> Data {
|
||||
func pack(_ value: [String: Any]) -> Data {
|
||||
(try? JSONSerialization.data(withJSONObject: value)) ?? Data(#"{"error":"encoding_error"}"#.utf8)
|
||||
}
|
||||
guard let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
let supplied = request["token"] as? String, sessionID == session,
|
||||
!token.isEmpty, supplied == token, let model = selected, model.documentID == documentID
|
||||
else { return pack(["error": "access_denied"]) }
|
||||
guard request["version"] as? Int == 1 else { return pack(["error": "version_mismatch"]) }
|
||||
guard let args = request["arguments"] as? [String: Any] else { return pack(["error": "invalid_arguments"]) }
|
||||
let id = model.documentID.uuidString
|
||||
let result: [String: Any]
|
||||
switch request["tool"] as? String {
|
||||
case "get_capabilities" where args.isEmpty:
|
||||
result = ["tools": ["get_capabilities", "get_machine_status", "read_source", "search_help", "read_topic"] + (canPropose ? ["propose_edit", "propose_listing", "get_proposal", "get_run", "read_screen_text", "send_keys", "get_debug_snapshot", "read_debug_memory"] : []),
|
||||
"version": 1, "input_diagnostics": true, "session_id": session, "title": model.title, "document_id": id,
|
||||
"app": "VCC Plus OSS", "build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"]
|
||||
case "get_machine_status" where args.isEmpty:
|
||||
let observed = await model.machine.mcpReadinessSnapshot()
|
||||
guard sessionID == session, selected === model, model.documentID == documentID else { return pack(["error": "access_denied"]) }
|
||||
refreshProposal(model)
|
||||
var blockers: [String] = []
|
||||
if !canPropose { blockers.append("Save a review and run connection to start a shared program.") }
|
||||
if current?.status != "applied" || current?.appliedRevision != model.sourceRevision {
|
||||
blockers.append("Apply a proposal for the current BASIC draft.")
|
||||
}
|
||||
if model.editorLocked || model.machine.busy || guest.busy { blockers.append("Wait for the current operation to finish.") }
|
||||
result = MCPMachineStatus.result(observed, workspace: .basic, buildBlockers: nil, runBlockers: blockers,
|
||||
profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed))
|
||||
case "read_source" where args.count == 1:
|
||||
guard args["document_id"] as? String == id else { return pack(["error": "access_denied"]) }
|
||||
guard model.source.utf8.count <= 65536 else { return pack(["error": "source_too_large"]) }
|
||||
result = ["document_id": id, "text": model.source, "revision": model.sourceRevision, "title": model.title]
|
||||
case let name? where name == "propose_edit" || name == "propose_listing":
|
||||
guard canPropose else { return pack(["error": "access_denied"]) }
|
||||
return pack(propose(args, model: model, wholeListing: name == "propose_listing"))
|
||||
case "get_proposal":
|
||||
guard canPropose else { return pack(["error": "access_denied"]) }
|
||||
guard args.count == 1, let id = args["proposal_id"] as? String, let proposal = history[id] else {
|
||||
return pack(["error": "unknown_proposal"])
|
||||
}
|
||||
refreshProposal(model)
|
||||
return pack(["result": (history[id] ?? proposal).result])
|
||||
case let name? where ["get_run", "get_debug_snapshot", "read_debug_memory", "read_screen_text", "send_keys"].contains(name):
|
||||
guard canPropose else { return pack(["error": "access_denied"]) }
|
||||
let reply = await guest.handle(tool: name, arguments: args, model: model)
|
||||
guard sessionID == session, selected === model, model.documentID == documentID else { return pack(["error": "access_denied"]) }
|
||||
return pack(reply)
|
||||
case let tool? where tool == "search_help" || tool == "read_topic":
|
||||
let response = await MCPHelpIndex.toolResult(tool, arguments: args)
|
||||
guard sessionID == session, selected === model, documentID == model.documentID else {
|
||||
return pack(["error": "access_denied"])
|
||||
}
|
||||
return pack(response)
|
||||
default:
|
||||
return pack(["error": "invalid_arguments"])
|
||||
}
|
||||
guard sessionID == session, selected === model, documentID == model.documentID else {
|
||||
return pack(["error": "access_denied"])
|
||||
}
|
||||
return pack(["result": result])
|
||||
}
|
||||
|
||||
private func update(_ proposal: BASICEditProposal) {
|
||||
current = proposal
|
||||
history[proposal.id] = proposal
|
||||
}
|
||||
|
||||
fileprivate func refreshProposal(_ model: BASICDevelopmentModel) {
|
||||
guard var proposal = current else { return }
|
||||
if proposal.status == "pending", proposal.revision != model.sourceRevision {
|
||||
proposal.status = "stale"
|
||||
update(proposal)
|
||||
}
|
||||
}
|
||||
|
||||
private func propose(_ args: [String: Any], model: BASICDevelopmentModel, wholeListing: Bool) -> [String: Any] {
|
||||
guard args["document_id"] as? String == model.documentID.uuidString else { return ["error": "access_denied"] }
|
||||
func integer(_ key: String) -> Int? {
|
||||
guard let number = args[key] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
||||
!["d", "f"].contains(String(cString: number.objCType)) else { return nil }
|
||||
return Int(exactly: number)
|
||||
}
|
||||
guard let revision = integer("revision"), revision >= 0,
|
||||
let requestID = args["request_id"] as? String, (1...128).contains(requestID.utf8.count)
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
let line: Int?
|
||||
let replacement: String
|
||||
if wholeListing {
|
||||
guard args.count == 4, let listing = args["source"] as? String,
|
||||
(1...12 * 1024).contains(listing.utf8.count) else { return ["error": "invalid_arguments"] }
|
||||
let lines = listing.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
|
||||
guard lines.allSatisfy({ $0.utf8.count <= 249 && $0.utf8.allSatisfy { $0 == 9 || (32...126).contains($0) } })
|
||||
else { return ["error": "invalid_listing"] }
|
||||
let analysis = BASICLanguage.analyze(listing)
|
||||
guard !analysis.hasErrors, !analysis.lines.isEmpty else { return ["error": "invalid_listing"] }
|
||||
line = nil
|
||||
replacement = listing
|
||||
} else {
|
||||
guard args.count == 5, let number = integer("line_number"), let text = args["replacement"] as? String,
|
||||
(1...249).contains(text.utf8.count), text.utf8.allSatisfy({ $0 == 9 || (32...126).contains($0) }),
|
||||
BASICLanguage.lineRange(for: number, in: text) != nil else { return ["error": "invalid_arguments"] }
|
||||
line = number
|
||||
replacement = text
|
||||
}
|
||||
refreshProposal(model)
|
||||
if let retry = history.values.first(where: { $0.requestID == requestID }) {
|
||||
guard retry.revision == revision, retry.line == line, retry.after == replacement else { return ["error": "request_id_conflict"] }
|
||||
return ["result": retry.result]
|
||||
}
|
||||
guard revision == model.sourceRevision else { return ["error": "stale_revision"] }
|
||||
guard current?.status != "pending" else { return ["error": "review_pending"] }
|
||||
guard history.count < 128 else { return ["error": "session_proposal_limit"] }
|
||||
guard model.source.utf8.count <= 65536 else { return ["error": "source_too_large"] }
|
||||
let before: String
|
||||
if let line {
|
||||
guard let range = BASICLanguage.lineRange(for: line, in: model.source) else { return ["error": "line_not_found"] }
|
||||
before = (model.source as NSString).substring(with: range)
|
||||
} else {
|
||||
before = model.source
|
||||
}
|
||||
guard before != replacement else { return ["error": wholeListing ? "unchanged_listing" : "unchanged_line"] }
|
||||
let proposal = BASICEditProposal(requestID: requestID, revision: revision, line: line, before: before, after: replacement)
|
||||
update(proposal)
|
||||
showReview(model)
|
||||
return ["result": proposal.result]
|
||||
}
|
||||
|
||||
fileprivate func showReview(_ model: BASICDevelopmentModel) {
|
||||
guard selected === model, current != nil else { return }
|
||||
if let reviewWindow {
|
||||
if !regressionFixture { reviewWindow.makeKeyAndOrderFront(nil) }
|
||||
return
|
||||
}
|
||||
let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 595, height: 340),
|
||||
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
||||
window.title = fixtureLabel.map { "Review BASIC Edit — " + $0 } ?? "Review BASIC Edit"
|
||||
window.isReleasedWhenClosed = false
|
||||
window.contentMinSize = NSSize(width: 440, height: 280)
|
||||
let content = NSHostingView(rootView: ScrollView { MCPReviewView(access: self, model: model, guest: guest) })
|
||||
content.sizingOptions = []
|
||||
window.contentView = content
|
||||
window.center()
|
||||
reviewWindow = window
|
||||
if !regressionFixture {
|
||||
#if DEBUG
|
||||
if let label = fixtureLabel, let bounds = window.screen?.visibleFrame {
|
||||
let side: CGFloat = label.lowercased().contains("ollama") ? 1 : -1
|
||||
let offset = max(0, min(bounds.width / 4, (bounds.width - window.frame.width) / 2))
|
||||
window.setFrameOrigin(NSPoint(x: bounds.midX - window.frame.width / 2 + side * offset, y: window.frame.minY))
|
||||
}
|
||||
#endif
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
NSApp.requestUserAttention(.informationalRequest)
|
||||
}
|
||||
#if DEBUG
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--mcp-validation-dir"), CommandLine.arguments.indices.contains(index + 1) {
|
||||
let directory = URL(fileURLWithPath: CommandLine.arguments[index + 1])
|
||||
try? Data(String(window.windowNumber).utf8).write(to: directory.appendingPathComponent("review-window-id"))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
fileprivate func decide(_ id: String, model: BASICDevelopmentModel, apply: Bool) {
|
||||
guard var proposal = current, proposal.id == id, proposal.status == "pending" else { return }
|
||||
guard selected === model, model.documentID == documentID, model.sourceRevision == proposal.revision else {
|
||||
proposal.status = "stale"; update(proposal); return
|
||||
}
|
||||
guard apply else { proposal.status = "cancelled"; update(proposal); return }
|
||||
guard !model.editorLocked, let range = proposal.range(in: model.source),
|
||||
let editor = model.assistantEditor, editor.window != nil, let manager = editor.undoManager else {
|
||||
message = "Open the BASIC source editor and finish any active edit before applying."; return
|
||||
}
|
||||
let source = model.source as NSString
|
||||
guard source.substring(with: range) == proposal.before else { proposal.status = "stale"; update(proposal); return }
|
||||
let revised = source.replacingCharacters(in: range, with: proposal.after)
|
||||
// Remote decisions can arrive in the same AppKit event group. Give each
|
||||
// approved replacement a top-level Undo without absorbing earlier typing.
|
||||
let automaticGroups = manager.groupsByEvent
|
||||
guard !manager.isUndoing, !manager.isRedoing, manager.groupingLevel <= (automaticGroups ? 1 : 0)
|
||||
else { message = "Finish the current editor operation before applying."; return }
|
||||
editor.breakUndoCoalescing()
|
||||
if manager.groupingLevel == 1 { manager.endUndoGrouping() }
|
||||
manager.groupsByEvent = false
|
||||
manager.beginUndoGrouping()
|
||||
defer {
|
||||
manager.endUndoGrouping()
|
||||
manager.groupsByEvent = automaticGroups
|
||||
}
|
||||
let action = BASICEditorAction(expectedSource: model.source, operation: .replace(source: revised, undoName: "Assistant BASIC Edit"))
|
||||
guard editor.applyEditorAction(action, revealReplacementAt: range.location),
|
||||
model.source == revised else { message = "The source editor could not apply this edit."; return }
|
||||
proposal.status = "applied"
|
||||
proposal.appliedRevision = model.sourceRevision
|
||||
message = nil
|
||||
update(proposal)
|
||||
}
|
||||
|
||||
fileprivate func undo(_ id: String, model: BASICDevelopmentModel) {
|
||||
guard var proposal = current, proposal.id == id, proposal.status == "applied", selected === model,
|
||||
documentID == model.documentID, proposal.appliedRevision == model.sourceRevision,
|
||||
!model.editorLocked, let editor = model.assistantEditor, let manager = editor.undoManager,
|
||||
manager.canUndo, manager.undoActionName == "Assistant BASIC Edit" else { return }
|
||||
manager.undo()
|
||||
guard let range = proposal.range(in: model.source),
|
||||
(model.source as NSString).substring(with: range) == proposal.before else { return }
|
||||
proposal.status = "undone"; update(proposal)
|
||||
}
|
||||
|
||||
fileprivate func run(_ id: String, model: BASICDevelopmentModel, both: Bool) {
|
||||
guard let proposal = current, proposal.id == id, proposal.status == "applied", !guest.busy,
|
||||
selected === model, documentID == model.documentID, proposal.appliedRevision == model.sourceRevision else { return }
|
||||
guard !both || Self.isRevisedPlanetExample(model.source) else { return }
|
||||
let owner = sessionID
|
||||
Task { [self, model] in
|
||||
await guest.start(model: model, bothChoices: both, isCurrent: { [weak self, weak model] in
|
||||
guard let self, let model else { return false }
|
||||
return self.sessionID == owner && self.selected === model && self.documentID == model.documentID
|
||||
&& self.current?.id == id && self.current?.status == "applied" && proposal.appliedRevision == model.sourceRevision
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate static func isRevisedPlanetExample(_ source: String) -> Bool {
|
||||
let before = "90 PALETTE 6,37:M$=\"Hello Cold Red Dot World!\""
|
||||
let after = "90 PALETTE 6,37:M$=\"Bring a warm coat!\""
|
||||
let starter = BASICLanguage.sample
|
||||
guard starter.contains(before) else { return false }
|
||||
let revised = starter.replacingOccurrences(of: before, with: after)
|
||||
return revised.split(whereSeparator: \.isNewline) == source.split(whereSeparator: \.isNewline)
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
private func captureFixtureContent(_ window: NSWindow, to file: URL) {
|
||||
guard let content = window.contentView else { return }
|
||||
content.layoutSubtreeIfNeeded()
|
||||
content.displayIfNeeded()
|
||||
guard let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) else { return }
|
||||
content.cacheDisplay(in: content.bounds, to: bitmap)
|
||||
try? bitmap.representation(using: .png, properties: [:])?.write(to: file)
|
||||
}
|
||||
|
||||
/// Available only after the app delegate has created an isolated interface-validation machine.
|
||||
func validate(model: BASICDevelopmentModel, other: BASICDevelopmentModel, in directory: URL) async throws {
|
||||
var info = stat()
|
||||
guard lstat(directory.path, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR, info.st_uid == geteuid(),
|
||||
info.st_mode & 0o077 == 0 else { throw POSIXError(.EACCES) }
|
||||
let args = CommandLine.arguments
|
||||
let review = args.firstIndex(of: "--mcp-edit-review").flatMap { args.indices.contains($0 + 1) ? args[$0 + 1] : nil }
|
||||
let regression = review != nil && args.contains("--mcp-review-regression")
|
||||
regressionFixture = regression
|
||||
if regression {
|
||||
try Data().write(to: directory.appendingPathComponent("regression-fixture"), options: .withoutOverwriting)
|
||||
}
|
||||
if let review {
|
||||
fixtureLabel = review
|
||||
if let i = args.firstIndex(of: "--mcp-rom-dir"), args.indices.contains(i + 1) {
|
||||
try await MCPBASICRun.bootFixture(model.machine, romDirectory: URL(fileURLWithPath: args[i + 1]))
|
||||
}
|
||||
model.source = regression && args.contains("--mcp-blank-draft") ? "" : BASICLanguage.sample
|
||||
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1050, height: 720),
|
||||
styleMask: [.titled, .resizable, .miniaturizable], backing: .buffered, defer: false)
|
||||
window.title = "BASIC Development — " + review
|
||||
let content = NSHostingView(rootView: BASICDevelopmentView(model: model))
|
||||
content.sizingOptions = []
|
||||
window.contentView = content
|
||||
window.center()
|
||||
fixtureEditor = window
|
||||
if regression { window.orderBack(nil) } else { window.orderFront(nil) }
|
||||
content.layoutSubtreeIfNeeded()
|
||||
} else {
|
||||
model.source = "10 REM MCP LOCAL PROOF\n20 PRINT 6*7\n"
|
||||
}
|
||||
other.source = "10 REM PRIVATE UNSHARED EXAMPLE\n"
|
||||
let path = directory.appendingPathComponent("grant.json")
|
||||
try Data(other.documentID.uuidString.utf8).write(to: directory.appendingPathComponent("other-id"), options: .withoutOverwriting)
|
||||
try await grant(model, at: path, proposals: review != nil)
|
||||
if review == nil { show(for: model) }
|
||||
if let id = panel?.windowNumber, id > 0 {
|
||||
try Data(String(id).utf8).write(to: directory.appendingPathComponent("panel-window-id"), options: .withoutOverwriting)
|
||||
if CommandLine.arguments.contains("--mcp-capture-panel") {
|
||||
if let panel { captureFixtureContent(panel, to: directory.appendingPathComponent("access.png")) }
|
||||
}
|
||||
}
|
||||
fixturePoll = Task { @MainActor [weak self] in
|
||||
func consume(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 }
|
||||
func mark(_ name: String) { try? Data().write(to: directory.appendingPathComponent(name)) }
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: 200_000_000)
|
||||
guard let self, !Task.isCancelled else { return }
|
||||
if consume("revoke") { await self.revoke().value; mark("revoked") }
|
||||
if (review == nil || regression), consume("edit") { model.source += review == nil ? "30 REM UPDATED DRAFT\n" : "9000 REM UPDATED DRAFT\n"; mark("edited") }
|
||||
if consume("reconnect") {
|
||||
do { try await self.grant(model, at: path, proposals: review != nil); mark("reconnected") }
|
||||
catch { NSLog("MCP fixture reconnection failed: %@", error.localizedDescription) }
|
||||
}
|
||||
if regression, let proposal = self.current {
|
||||
if consume("apply") { self.decide(proposal.id, model: model, apply: true); mark("applied") }
|
||||
if consume("cancel") { self.decide(proposal.id, model: model, apply: false); mark("cancelled") }
|
||||
if consume("undo") { self.undo(proposal.id, model: model); mark("undone") }
|
||||
if consume("save-reopen"), proposal.status == "applied" {
|
||||
let target = directory.appendingPathComponent("Reviewed.bas")
|
||||
let reopened = BASICDevelopmentModel(machine: model.machine, directory: directory.appendingPathComponent("Reopened Workspace"))
|
||||
if !FileManager.default.fileExists(atPath: target.path), model.saveSource(to: target),
|
||||
reopened.openSource(at: target), reopened.source == model.source, !reopened.dirty {
|
||||
mark("saved-and-reopened")
|
||||
}
|
||||
}
|
||||
if consume("run-both") { self.run(proposal.id, model: model, both: true); mark("run-started") }
|
||||
if consume("run") { self.run(proposal.id, model: model, both: false); mark("run-started") }
|
||||
if consume("capture-review"), let window = self.reviewWindow {
|
||||
window.orderFront(nil)
|
||||
try? await Task.sleep(for: .milliseconds(350))
|
||||
self.captureFixtureContent(window, to: directory.appendingPathComponent("review.png"))
|
||||
window.orderOut(nil)
|
||||
}
|
||||
if consume("capture-result"), self.guest.receipt != nil, let window = self.reviewWindow {
|
||||
window.setContentSize(NSSize(width: 640, height: 480))
|
||||
window.orderFront(nil)
|
||||
try? await Task.sleep(for: .milliseconds(400))
|
||||
let capture = Process()
|
||||
capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
|
||||
capture.arguments = ["-x", "-o", "-l", String(window.windowNumber), directory.appendingPathComponent("verified.png").path]
|
||||
capture.terminationHandler = { _ in Task { @MainActor in window.orderOut(nil) } }
|
||||
do { try capture.run() } catch { window.orderOut(nil) }
|
||||
}
|
||||
}
|
||||
if consume("quit") {
|
||||
await self.revoke().value
|
||||
if review == nil || regression { model.source = model.savedSource }
|
||||
other.source = other.savedSource
|
||||
// AppKit's termination loop must be entered from a run-loop event,
|
||||
// so the main actor remains available to finish asynchronous shutdown.
|
||||
NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
struct MCPGrantFile {
|
||||
let url: URL
|
||||
let device: dev_t
|
||||
let inode: ino_t
|
||||
|
||||
init(create url: URL, data: Data) throws {
|
||||
let fd = open(url.path, O_CREAT | O_WRONLY | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)
|
||||
guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
var info = stat()
|
||||
do {
|
||||
guard fstat(fd, &info) == 0 else { throw POSIXError(.EIO) }
|
||||
try file.write(contentsOf: data)
|
||||
try file.close()
|
||||
} catch {
|
||||
unlink(url.path)
|
||||
throw error
|
||||
}
|
||||
self.url = url
|
||||
device = info.st_dev
|
||||
inode = info.st_ino
|
||||
}
|
||||
|
||||
func remove() {
|
||||
var info = stat()
|
||||
if lstat(url.path, &info) == 0 && info.st_dev == device && info.st_ino == inode { unlink(url.path) }
|
||||
}
|
||||
}
|
||||
|
||||
private struct MCPAccessView: View {
|
||||
@ObservedObject var access: MCPAccess
|
||||
@ObservedObject var model: BASICDevelopmentModel
|
||||
@State private var proposals = false
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Label(model.title, systemImage: "doc.text").font(.headline)
|
||||
Text("A local assistant with the connection file can read this BASIC draft, including unsaved edits, search the installed manuals, and check the guest processor and mounted drive status. Its model provider may receive that text.")
|
||||
|
||||
if let name = access.activeTitle, access.selected !== model {
|
||||
Label("Another BASIC editor is sharing \(name).", systemImage: "link")
|
||||
Button("Revoke That Connection") { access.revoke() }
|
||||
} else if let name = access.activeTitle {
|
||||
Label("Sharing: \(name)", systemImage: "link").accessibilityIdentifier("mcp.access.active")
|
||||
if let file = access.grantFile {
|
||||
MCPChatGPTSetup(grantURL: file.url, firstPrompt: "Use VCC Plus to identify my shared BASIC draft and read its source. Tell me its title and what the program does.")
|
||||
}
|
||||
if access.canPropose {
|
||||
Text("Edits require native review. Starting a reviewed run permits bounded guest input and inspection of its screen, debugger registers, watches and program memory.")
|
||||
if access.current != nil { Button("Show Edit Review…") { access.showReview(model) } }
|
||||
}
|
||||
Button("Revoke Access") { access.revoke() }.accessibilityIdentifier("mcp.access.revoke")
|
||||
} else {
|
||||
Toggle("Allow proposed edits and controls for runs I start", isOn: $proposals)
|
||||
Button(proposals ? "Save Review and Run Connection…" : "Save Read-Only Connection…") {
|
||||
access.chooseGrant(for: model, proposals: proposals)
|
||||
}.accessibilityIdentifier("mcp.access.grant")
|
||||
}
|
||||
if let message = access.message { Text(message).foregroundStyle(.secondary) }
|
||||
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MCPReviewView: View {
|
||||
@ObservedObject var access: MCPAccess
|
||||
@ObservedObject var model: BASICDevelopmentModel
|
||||
@ObservedObject var guest: MCPBASICRun
|
||||
|
||||
var body: some View {
|
||||
if let p = access.current {
|
||||
VStack(alignment: .leading, spacing: 13) {
|
||||
Label(model.title, systemImage: "doc.text").font(.headline)
|
||||
if let revision = p.appliedRevision {
|
||||
Text("\(p.subject) · Reviewed revision \(p.revision) → applied revision \(revision)").foregroundStyle(.secondary)
|
||||
} else {
|
||||
Text("\(p.subject) · Draft revision \(p.revision)").foregroundStyle(.secondary)
|
||||
}
|
||||
line(p.appliedRevision == nil ? "Current" : "Before", p.before, color: .red, listing: p.line == nil)
|
||||
line(p.appliedRevision == nil ? "Proposed" : "Applied", p.after, color: .green, listing: p.line == nil)
|
||||
switch p.status {
|
||||
case "pending":
|
||||
HStack {
|
||||
Button("Cancel Edit") { access.decide(p.id, model: model, apply: false) }
|
||||
Button("Apply Edit") { access.decide(p.id, model: model, apply: true) }.buttonStyle(.borderedProminent)
|
||||
}
|
||||
case "applied":
|
||||
Text("Applied to the BASIC draft.").font(.headline)
|
||||
HStack {
|
||||
Button("Undo Edit") { access.undo(p.id, model: model) }
|
||||
Button("Run") { access.run(p.id, model: model, both: false) }
|
||||
if MCPAccess.isRevisedPlanetExample(model.source) {
|
||||
Button("Run Both Choices") { access.run(p.id, model: model, both: true) }
|
||||
.help("Verify the Earth and revised Mars greetings, their backgrounds, and a fresh PRINT 7 command.")
|
||||
}
|
||||
}.disabled(guest.busy || p.appliedRevision != model.sourceRevision)
|
||||
if !guest.status.isEmpty { Text(guest.status).textSelection(.enabled) }
|
||||
if let branches = guest.receipt?["branches"] as? [[String: Any]] {
|
||||
ForEach(branches.indices, id: \.self) { index in
|
||||
let branch = branches[index]
|
||||
if let rgb = branch["background_rgb"] as? String, let value = UInt32(rgb.dropFirst(), radix: 16),
|
||||
let text = branch["greeting"] as? String {
|
||||
HStack(spacing: 8) {
|
||||
RoundedRectangle(cornerRadius: 3)
|
||||
.fill(Color(red: Double(value >> 16 & 255) / 255, green: Double(value >> 8 & 255) / 255, blue: Double(value & 255) / 255))
|
||||
.frame(width: 18, height: 18).accessibilityHidden(true)
|
||||
Text(branch["key"] as? String == "2" ? "Mars" : "Earth").fontWeight(.semibold)
|
||||
Text(text.trimmingCharacters(in: .whitespaces))
|
||||
Text(rgb).font(.system(.caption, design: .monospaced))
|
||||
}.textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
if let message = model.message { Text(message).foregroundStyle(.secondary) }
|
||||
case "stale": Text("The draft changed. Ask the assistant to read it again and propose a fresh edit.")
|
||||
case "undone": Text("Edit undone.")
|
||||
default: Text("Edit cancelled.")
|
||||
}
|
||||
if let message = access.message { Text(message).foregroundStyle(.secondary) }
|
||||
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.onChange(of: model.sourceRevision) { _, _ in access.refreshProposal(model) }
|
||||
}
|
||||
}
|
||||
|
||||
private func line(_ label: String, _ text: String, color: Color, listing: Bool) -> some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(label).font(.caption.weight(.semibold))
|
||||
if listing && text.isEmpty {
|
||||
Text("Empty draft").foregroundStyle(.secondary)
|
||||
} else if listing && text.components(separatedBy: .newlines).count > 5 {
|
||||
ScrollView {
|
||||
Text(verbatim: text).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.font(.system(.body, design: .monospaced)).textSelection(.enabled)
|
||||
}.frame(height: 110)
|
||||
} else {
|
||||
Text(verbatim: text).font(.system(.body, design: .monospaced)).textSelection(.enabled)
|
||||
}
|
||||
}.padding(9).frame(maxWidth: .infinity, alignment: .leading).background(color.opacity(0.10), in: RoundedRectangle(cornerRadius: 5))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// A separate grant with its own listener and no reference to a workspace or emulator.
|
||||
@MainActor
|
||||
final class MCPArchiveAccess: ObservableObject {
|
||||
static let shared = MCPArchiveAccess(catalog: .shared)
|
||||
private let catalog: ArchiveLibraryCatalog
|
||||
private var listener: MCPTransport?
|
||||
private var secret: String?
|
||||
private var pending: UUID?
|
||||
private var panel: NSPanel?
|
||||
@Published private(set) var grantFile: MCPGrantFile?
|
||||
@Published fileprivate var message: String?
|
||||
|
||||
init(catalog: ArchiveLibraryCatalog) { self.catalog = catalog }
|
||||
|
||||
func show() {
|
||||
if let panel {
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 540, height: 380),
|
||||
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
||||
window.title = "Archive Search Connection"
|
||||
window.isReleasedWhenClosed = false
|
||||
window.contentMinSize = NSSize(width: 360, height: 230)
|
||||
let content = NSHostingView(rootView: ScrollView { MCPArchiveAccessView(access: self) })
|
||||
content.sizingOptions = []
|
||||
window.contentView = content
|
||||
window.center()
|
||||
panel = window
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
fileprivate func chooseGrant() {
|
||||
let picker = NSSavePanel()
|
||||
picker.nameFieldStringValue = "VCC Plus OSS Archive Search.json"
|
||||
picker.title = "Save Archive Search Connection"
|
||||
picker.message = "Choose a new file for the assistant that will search the Archive."
|
||||
guard picker.runModal() == .OK, let url = picker.url else { return }
|
||||
Task {
|
||||
do { try await connect(at: url) }
|
||||
catch is CancellationError {}
|
||||
catch { message = "Could not save the connection. " + error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
func connect(at url: URL) async throws {
|
||||
let ticket = UUID()
|
||||
pending = ticket
|
||||
defer { if pending == ticket { pending = nil } }
|
||||
let token = UUID().uuidString + UUID().uuidString
|
||||
let handler: MCPTransport.Handler = { [weak self] bytes in
|
||||
guard let self else { return Self.denied }
|
||||
return await self.reply(to: bytes, connection: token)
|
||||
}
|
||||
let (server, file) = try await Task.detached(priority: .userInitiated) {
|
||||
let server = try MCPTransport(handler: handler)
|
||||
let bytes = try JSONSerialization.data(withJSONObject: ["kind": "archive", "version": 2, "token": token,
|
||||
"socket": server.unixPath, "port": Int(server.port)])
|
||||
return (server, try MCPGrantFile(create: url, data: bytes))
|
||||
}.value
|
||||
guard pending == ticket else {
|
||||
await Task.detached { server.stop(); file.remove() }.value
|
||||
throw CancellationError()
|
||||
}
|
||||
revoke()
|
||||
listener = server
|
||||
secret = token
|
||||
grantFile = file
|
||||
message = nil
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func revoke() -> Task<Void, Never> {
|
||||
pending = nil
|
||||
secret = nil
|
||||
let old = listener, file = grantFile
|
||||
listener = nil
|
||||
grantFile = nil
|
||||
message = nil
|
||||
return Task.detached { old?.stop(); file?.remove() }
|
||||
}
|
||||
|
||||
private nonisolated static let denied = Data(#"{"error":"access_denied"}"#.utf8)
|
||||
|
||||
private func reply(to data: Data, connection: String) async -> Data {
|
||||
guard let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
secret == connection, request["token"] as? String == connection else { return Self.denied }
|
||||
let response: [String: Any]
|
||||
if Self.integer(request["version"]) != 1 {
|
||||
response = ["error": "version_mismatch"]
|
||||
} else if let tool = request["tool"] as? String, let args = request["arguments"] as? [String: Any] {
|
||||
do { response = try await perform(tool, args) }
|
||||
catch ArchiveLibraryError.input(let message) { response = ["error": message] }
|
||||
catch { response = ["error": "archive_index_unavailable"] }
|
||||
} else {
|
||||
response = ["error": "invalid_arguments"]
|
||||
}
|
||||
// The user can revoke or replace the grant while SQLite serves an asynchronous query.
|
||||
guard secret == connection else { return Self.denied }
|
||||
return (try? JSONSerialization.data(withJSONObject: response)) ?? Data(#"{"error":"encoding_error"}"#.utf8)
|
||||
}
|
||||
|
||||
private func perform(_ tool: String, _ args: [String: Any]) async throws -> [String: Any] {
|
||||
switch tool {
|
||||
case "search_archive":
|
||||
guard Set(args.keys).isSubset(of: ["query", "category", "limit", "offset"]),
|
||||
let query = args["query"] as? String, !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
query.unicodeScalars.count <= 256,
|
||||
let limit = Self.integer(args["limit"] ?? 10), (1...50).contains(limit),
|
||||
let offset = Self.integer(args["offset"] ?? 0), (0...250_000).contains(offset)
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
let category = args["category"] as? String
|
||||
if args["category"] != nil {
|
||||
guard let category, !category.isEmpty, category.unicodeScalars.count <= 512 else {
|
||||
return ["error": "invalid_arguments"]
|
||||
}
|
||||
}
|
||||
let hits = try await catalog.search(query: query, collection: category, limit: limit, offset: offset)
|
||||
var result: [String: Any] = ["results": hits.map(Self.publicCitation), "offset": offset]
|
||||
if hits.count == limit && offset + limit <= 250_000 { result["next_offset"] = offset + limit }
|
||||
return ["result": result]
|
||||
case "get_archive_citation":
|
||||
guard args.count == 1, let id = args["citation_id"] as? String, !id.isEmpty, id.utf8.count <= 128
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
guard let hit = try await catalog.citation(id: id) else { return ["error": "citation_unavailable"] }
|
||||
return ["result": Self.publicCitation(hit)]
|
||||
default:
|
||||
return ["error": "access_denied"]
|
||||
}
|
||||
}
|
||||
|
||||
private static func integer(_ value: Any?) -> Int? {
|
||||
guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
||||
!CFNumberIsFloatType(number) else { return nil }
|
||||
return Int(number.stringValue)
|
||||
}
|
||||
|
||||
private static func publicCitation(_ hit: ArchiveHit) -> [String: Any] {
|
||||
var value: [String: Any] = ["citation_id": hit.id, "document_sha256": hit.document.id,
|
||||
"title": hit.document.title, "collection": hit.document.collection, "citation": hit.citation,
|
||||
"source_url": hit.sourceURL.absoluteString, "locator": hit.locator, "ocr": hit.ocr]
|
||||
if let page = hit.page { value["pdf_page"] = page }
|
||||
if let member = hit.document.memberPath { value["member_path"] = member }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
private struct MCPArchiveAccessView: View {
|
||||
@ObservedObject var access: MCPArchiveAccess
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Connect a local assistant to search the Archive and look up citations. Its model provider may receive your queries and the public references it finds.").fixedSize(horizontal: false, vertical: true)
|
||||
if let file = access.grantFile {
|
||||
Label("Archive search is available to this connection.", systemImage: "link")
|
||||
Button("Revoke Archive Access") { access.revoke() }
|
||||
Divider()
|
||||
MCPChatGPTSetup(grantURL: file.url, firstPrompt: "Use Archive Search to find a reference to JOYSTK and give me its original source and page.")
|
||||
} else {
|
||||
Button("Save Archive Search Connection…") { access.chooseGrant() }
|
||||
}
|
||||
if let message = access.message { Text(message).font(.callout).textSelection(.enabled) }
|
||||
}.padding().frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,741 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Combine
|
||||
import SwiftUI
|
||||
|
||||
struct AssemblyProjectEdit {
|
||||
let path: String
|
||||
let before: String
|
||||
let after: String
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class AssemblyAccessWindowDelegate: NSObject, NSWindowDelegate {
|
||||
let didClose: @MainActor (NSWindow) -> Void
|
||||
init(didClose: @escaping @MainActor (NSWindow) -> Void) { self.didClose = didClose; super.init() }
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
if let window = notification.object as? NSWindow { didClose(window) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection is bound to one native assembly document and its original source-file set.
|
||||
@MainActor
|
||||
final class MCPAssembly: ObservableObject {
|
||||
static let shared = MCPAssembly()
|
||||
static let tools = ["get_capabilities", "get_machine_status", "get_debug_snapshot", "read_debug_memory", "search_help", "read_topic", "read_project_file", "build_project", "get_build", "propose_fix", "propose_project_edits", "get_proposal", "get_run", "read_screen_text", "send_keys"]
|
||||
private weak var model: AssemblyDevelopmentModel?
|
||||
private weak var editors: AssemblyEditorPool?
|
||||
private var transport: MCPTransport?
|
||||
private var file: MCPGrantFile?
|
||||
fileprivate var grantURL: URL? { file?.url }
|
||||
private var scope = UUID()
|
||||
private var token = ""
|
||||
private var documentID: UUID?
|
||||
private var files: Set<String> = []
|
||||
private var last: AssemblyProjectSnapshot?
|
||||
private var lastSourceRevision: UUID?
|
||||
private var revision = 0
|
||||
private var selection: AnyCancellable?
|
||||
private var editObservation: AnyCancellable?
|
||||
private var window: NSPanel?
|
||||
private var windowPresentation = UUID()
|
||||
private lazy var windowDelegate = AssemblyAccessWindowDelegate { [weak self] closing in
|
||||
guard let self, self.window === closing else { return }
|
||||
self.windowPresentation = UUID()
|
||||
}
|
||||
private var buildTask: Task<Void, Never>?
|
||||
private var requests: [String: (tool: String, args: NSDictionary, id: String)] = [:]
|
||||
private var latestBuildID: String?
|
||||
private var builds: [String: [String: Any]] = [:]
|
||||
private var proposals: [String: [String: Any]] = [:]
|
||||
private var built: (id: String, revision: Int, artifact: AssemblyBuildArtifact)?
|
||||
private var inspection: MCPDebuggerInspection?
|
||||
private var runIO: MCPCompiledRunIO?
|
||||
private var run: (id: String, revision: Int, build: String, machine: VCCMachineSnapshot)? {
|
||||
willSet { runIO?.invalidate(); runIO = nil }
|
||||
}
|
||||
private var runMessage = "No run started."
|
||||
@Published private(set) var connected = false
|
||||
@Published private(set) var canRun = false
|
||||
@Published private(set) var status = ""
|
||||
@Published private(set) var proposal: Proposal?
|
||||
|
||||
struct Proposal: Identifiable {
|
||||
enum Content {
|
||||
case line(path: String, number: Int, before: String, after: String)
|
||||
case files([AssemblyProjectEdit])
|
||||
}
|
||||
let id: String
|
||||
let revision: Int
|
||||
let content: Content
|
||||
}
|
||||
private struct AppliedFiles {
|
||||
let proposal: Proposal
|
||||
let revision: Int
|
||||
let removedStops: Set<AssemblyDevelopmentModel.SourceLine>
|
||||
}
|
||||
@Published private var appliedFiles: AppliedFiles?
|
||||
fileprivate var runnableBuildID: String? { canRun ? built?.id : nil }
|
||||
fileprivate var undoableProposalID: String? { proposal == nil ? appliedFiles?.proposal.id : nil }
|
||||
|
||||
func show(_ model: AssemblyDevelopmentModel, editors: AssemblyEditorPool) {
|
||||
windowPresentation = UUID()
|
||||
if self.model !== model { revoke() }
|
||||
self.model = model
|
||||
self.editors = editors
|
||||
let panel = window ?? NSPanel(contentRect: NSRect(x: 0, y: 0, width: 670, height: 460),
|
||||
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
||||
panel.title = "Assembly Assistant Access"
|
||||
panel.isReleasedWhenClosed = false
|
||||
panel.delegate = windowDelegate
|
||||
panel.contentView = NSHostingView(rootView: AssemblyAccessView(access: self, model: model))
|
||||
if window == nil { panel.center() }
|
||||
window = panel
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
func close(for model: AssemblyDevelopmentModel) {
|
||||
guard self.model === model else { return }
|
||||
revoke()
|
||||
window?.close()
|
||||
window = nil
|
||||
}
|
||||
|
||||
fileprivate func choose(_ model: AssemblyDevelopmentModel) {
|
||||
guard let owner = window, self.model === model, owner.isVisible,
|
||||
!owner.isMiniaturized, owner.attachedSheet == nil else { return }
|
||||
let document = model.activeID, generation = scope, presentation = windowPresentation
|
||||
let panel = NSSavePanel()
|
||||
panel.title = "Save Assembly Connection"
|
||||
panel.nameFieldStringValue = "VCC Plus OSS Assembly Connection.json"
|
||||
panel.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in
|
||||
Task { @MainActor [weak self, weak owner, weak model] in
|
||||
guard let self, let owner, let model else { return }
|
||||
@MainActor func currentPresentation() -> Bool {
|
||||
self.windowPresentation == presentation && self.window === owner && self.model === model && owner.isVisible &&
|
||||
!owner.isMiniaturized && model.activeID == document
|
||||
}
|
||||
guard currentPresentation(), self.scope == generation else { return }
|
||||
defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } }
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
do { try await self.connect(model, to: url, presentationIsCurrent: currentPresentation) }
|
||||
catch is CancellationError { }
|
||||
catch { if currentPresentation() { self.status = error.localizedDescription } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func revoke() {
|
||||
inspection = nil
|
||||
scope = UUID(); token = ""; connected = false; documentID = nil; selection = nil; editObservation = nil
|
||||
requests.removeAll(); builds.removeAll(); latestBuildID = nil; proposals.removeAll()
|
||||
buildTask?.cancel(); buildTask = nil
|
||||
proposal = nil; appliedFiles = nil; built = nil; last = nil; run = nil; runMessage = "No run started."
|
||||
canRun = false; status = ""; files.removeAll(); revision = 0
|
||||
let old = transport, oldFile = file
|
||||
transport = nil; file = nil
|
||||
Task.detached { old?.stop(); oldFile?.remove() }
|
||||
}
|
||||
|
||||
private static func sourcePaths(_ snapshot: AssemblyProjectSnapshot) throws -> Set<String> {
|
||||
guard snapshot.settings.makefile == nil, snapshot.settings.linkScript == nil,
|
||||
(snapshot.settings.modules ?? []).isEmpty else {
|
||||
throw AssemblyBuildFailure("Share a native direct-assembly project. Linked projects and Make recipes require the local workspace.")
|
||||
}
|
||||
let paths = Set(snapshot.files.keys.filter { $0 != AssemblyProjectSnapshot.configurationFilename })
|
||||
let extensions = ["asm", "s", "inc", "lwasm", "a09"]
|
||||
guard paths.contains(snapshot.mainPath), paths.count <= 32, snapshot.files.values.reduce(0, { $0 + $1.count }) <= 512 * 1024,
|
||||
paths.allSatisfy({ path in
|
||||
guard extensions.contains((path as NSString).pathExtension.lowercased()), let data = snapshot.files[path] else { return false }
|
||||
return data.count <= 64 * 1024 && !data.contains(0) && String(data: data, encoding: .utf8) != nil
|
||||
}) else { throw AssemblyBuildFailure("Share a project containing up to 32 UTF-8 assembly or include files, 64 KiB per file.") }
|
||||
return paths
|
||||
}
|
||||
|
||||
func connect(_ model: AssemblyDevelopmentModel, to url: URL,
|
||||
presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws {
|
||||
revoke(); self.model = model
|
||||
let ticket = scope, doc = model.document, version = model.workspaceRevision
|
||||
let snapshot = try await Task.detached { try doc.snapshot() }.value
|
||||
guard scope == ticket, model.activeID == doc.id, model.workspaceRevision == version,
|
||||
presentationIsCurrent?() != false else { throw CancellationError() }
|
||||
let paths = try Self.sourcePaths(snapshot)
|
||||
let key = UUID().uuidString + UUID().uuidString
|
||||
let handler: MCPTransport.Handler = { [weak self] bytes in
|
||||
guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) }
|
||||
return await self.reply(bytes, ticket: ticket)
|
||||
}
|
||||
let pair = try await Task.detached {
|
||||
let server = try MCPTransport(handler: handler)
|
||||
let info: [String: Any] = ["kind": "assembly", "toolset": 3, "socket": server.unixPath, "port": Int(server.port), "version": 1, "token": key]
|
||||
return (server, try MCPGrantFile(create: url, data: JSONSerialization.data(withJSONObject: info)))
|
||||
}.value
|
||||
guard scope == ticket, model.activeID == doc.id, model.workspaceRevision == version,
|
||||
presentationIsCurrent?() != false else {
|
||||
Task.detached { pair.0.stop(); pair.1.remove() }
|
||||
throw CancellationError()
|
||||
}
|
||||
last = snapshot; lastSourceRevision = model.sourceRevision; files = paths; revision = 1
|
||||
documentID = doc.id; token = key; transport = pair.0; file = pair.1
|
||||
connected = true; status = "Sharing " + doc.title
|
||||
editObservation = model.$sourceRevision.dropFirst().sink { [weak self] _ in self?.runIO?.invalidate() }
|
||||
selection = model.$activeID.dropFirst().sink { [weak self] _ in self?.revoke() }
|
||||
}
|
||||
|
||||
private func snapshot(_ model: AssemblyDevelopmentModel, ticket: UUID, retry: Bool = true) async throws -> AssemblyProjectSnapshot {
|
||||
let doc = model.document, version = model.workspaceRevision
|
||||
let value = try await Task.detached { try doc.snapshot() }.value
|
||||
guard scope == ticket, model.activeID == documentID, doc.id == documentID else { throw AssemblyBuildFailure("access_denied") }
|
||||
if model.workspaceRevision != version {
|
||||
guard retry else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
return try await snapshot(model, ticket: ticket, retry: false)
|
||||
}
|
||||
guard try Self.sourcePaths(value) == files else { throw AssemblyBuildFailure("Shared files changed. Export a new connection.") }
|
||||
if last != value || lastSourceRevision != model.sourceRevision {
|
||||
lastSourceRevision = model.sourceRevision
|
||||
revision += 1; last = value; canRun = false; run = nil; runMessage = "No run started."
|
||||
appliedFiles = nil
|
||||
if let p = proposal { proposals[p.id]?["status"] = "stale"; proposal = nil }
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
private func reply(_ data: Data, ticket: UUID) async -> Data {
|
||||
func pack(_ value: [String: Any]) -> Data { (try? JSONSerialization.data(withJSONObject: value)) ?? Data(#"{"error":"encoding_error"}"#.utf8) }
|
||||
guard connected, ticket == scope, let model, model.activeID == documentID,
|
||||
let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
let supplied = request["token"] as? String, supplied == token else { return pack(["error": "access_denied"]) }
|
||||
guard request["version"] as? Int == 1, let args = request["arguments"] as? [String: Any],
|
||||
let tool = request["tool"] as? String else { return pack(["error": "invalid_arguments"]) }
|
||||
func currentGrant() -> Bool {
|
||||
connected && scope == ticket && self.model === model && model.activeID == documentID
|
||||
}
|
||||
if tool == "search_help" || tool == "read_topic" {
|
||||
let reply = await MCPHelpIndex.toolResult(tool, arguments: args)
|
||||
guard currentGrant() else { return pack(["error": "access_denied"]) }
|
||||
return pack(reply)
|
||||
}
|
||||
do {
|
||||
let result = try await perform(tool, args, model: model, ticket: ticket)
|
||||
guard currentGrant() else { return pack(["error": "access_denied"]) }
|
||||
return pack(["result": result])
|
||||
} catch { return pack(["error": currentGrant() ? error.localizedDescription : "access_denied"]) }
|
||||
}
|
||||
|
||||
private func perform(_ tool: String, _ args: [String: Any], model: AssemblyDevelopmentModel, ticket: UUID) async throws -> [String: Any] {
|
||||
let snapshot = try await snapshot(model, ticket: ticket)
|
||||
guard connected, scope == ticket, self.model === model, model.activeID == documentID else { throw AssemblyBuildFailure("access_denied") }
|
||||
let id = model.activeID.uuidString
|
||||
if tool == "get_capabilities", args.isEmpty {
|
||||
return ["version": 1, "input_diagnostics": true, "kind": "assembly", "language": "assembly", "session_id": scope.uuidString,
|
||||
"project_id": id, "revision": revision, "entry": snapshot.mainPath, "target": snapshot.cpu.rawValue,
|
||||
"files": files.sorted(), "tools": Self.tools]
|
||||
}
|
||||
if tool == "get_machine_status", args.isEmpty {
|
||||
let observed = await model.machine.mcpReadinessSnapshot()
|
||||
var build = await MCPMachineStatus.missingToolBlockers(in: model.service.tools.toolchain, requiring: ["lwasm"])
|
||||
var run: [String] = []
|
||||
if requests.count >= 64 { build.append("Reconnect to start another build.") }
|
||||
if buildTask != nil || model.working || model.commanding { build.append("Wait for the current build or editor command.") }
|
||||
if !canRun || built?.artifact.snapshot != snapshot { run.append("Assemble the current project revision.") }
|
||||
if proposal != nil { run.append("Review the pending assembly edit.") }
|
||||
if model.machine.busy || model.working || model.commanding { run.append("Wait for the current machine or editor operation.") }
|
||||
return MCPMachineStatus.result(observed, workspace: .assembly(needs6309: snapshot.cpu == .hd6309),
|
||||
buildBlockers: build, runBlockers: run, lastBuild: latestBuildID.flatMap(buildRecord),
|
||||
profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed))
|
||||
}
|
||||
if tool == "get_build" {
|
||||
guard args.count == 1, let key = args["build_id"] as? String else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
guard let record = buildRecord(key) else { throw AssemblyBuildFailure("unknown_build") }
|
||||
return record
|
||||
}
|
||||
if tool == "get_proposal" {
|
||||
guard args.count == 1, let key = args["proposal_id"] as? String else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
guard let record = proposals[key] else { throw AssemblyBuildFailure("unknown_proposal") }
|
||||
return record
|
||||
}
|
||||
if tool == "read_screen_text" || tool == "send_keys" {
|
||||
guard let run, let built, let runIO, run.revision == revision, run.build == built.id,
|
||||
model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
|
||||
let epoch = model.workspaceRevision
|
||||
let result = try await runIO.reply(tool, arguments: args)
|
||||
guard connected, scope == ticket, self.runIO === runIO, model.activeID == documentID,
|
||||
model.workspaceRevision == epoch, revision == run.revision,
|
||||
model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
|
||||
return result
|
||||
}
|
||||
if tool == "get_debug_snapshot" || tool == "read_debug_memory" {
|
||||
guard let run, let built, run.id == args["run_id"] as? String, run.revision == revision,
|
||||
run.build == built.id, model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
|
||||
if tool == "get_debug_snapshot" {
|
||||
guard args.count == 1 else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
return try await runResult(model, ticket: ticket, inspect: true)
|
||||
}
|
||||
let epoch = model.workspaceRevision
|
||||
let now = await model.machine.mcpMachineSnapshot()
|
||||
guard scope == ticket, self.run?.id == run.id, model.activeID == documentID, model.workspaceRevision == epoch,
|
||||
revision == run.revision, model.artifact?.id == built.artifact.id,
|
||||
now.debuggerAssemblyAttached, MCPDebuggerInspection.sameProgram(now, run.machine),
|
||||
let inspection else { throw AssemblyBuildFailure("stale_snapshot") }
|
||||
return try inspection.reply(tool: tool, arguments: args)
|
||||
}
|
||||
guard args["project_id"] as? String == id else { throw AssemblyBuildFailure("access_denied") }
|
||||
if tool == "read_project_file" {
|
||||
guard args.count == 2, let path = args["path"] as? String, files.contains(path), let data = snapshot.files[path] else {
|
||||
throw AssemblyBuildFailure("path_not_shared")
|
||||
}
|
||||
return ["project_id": id, "revision": revision, "path": path, "text": String(decoding: data, as: UTF8.self)]
|
||||
}
|
||||
guard let requestedRevision = integer(args["revision"]) else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
if tool == "get_run", args.count == 2 {
|
||||
guard requestedRevision == revision else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
return try await runResult(model, ticket: ticket)
|
||||
}
|
||||
guard ["build_project", "propose_fix", "propose_project_edits"].contains(tool) else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
guard let requestID = args["request_id"] as? String, (1...(tool == "propose_project_edits" ? 128 : 64)).contains(requestID.utf8.count)
|
||||
else { throw AssemblyBuildFailure("invalid_request_id") }
|
||||
if tool == "propose_fix", integer(args["line_number"]) == nil { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
if let previous = requests[requestID] {
|
||||
guard previous.tool == tool, previous.args.isEqual(to: args) else { throw AssemblyBuildFailure("request_conflict") }
|
||||
if let record = buildRecord(previous.id) ?? proposals[previous.id] { return record }
|
||||
}
|
||||
guard requestedRevision == revision else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
guard requests.count < 64 else { throw AssemblyBuildFailure("session_request_limit") }
|
||||
let key = UUID().uuidString
|
||||
if tool == "build_project", args.count == 3 {
|
||||
guard buildTask == nil, !model.working, !model.commanding else { throw AssemblyBuildFailure("build_busy") }
|
||||
let number = revision, workspaceRevision = model.workspaceRevision
|
||||
let record: [String: Any] = ["build_id": key, "project_id": id, "revision": number, "status": "building", "diagnostics": []]
|
||||
latestBuildID = key
|
||||
builds[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key)
|
||||
built = nil; run = nil; canRun = false; runMessage = "No run started."
|
||||
buildTask = Task { [weak self] in
|
||||
await self?.build(model, inputs: snapshot, revision: number, id: key, ticket: ticket, workspaceRevision: workspaceRevision)
|
||||
}
|
||||
return record
|
||||
}
|
||||
if tool == "propose_project_edits" {
|
||||
guard args.count == 4, proposal == nil else { throw AssemblyBuildFailure("invalid_proposal") }
|
||||
let edits = try Self.projectEdits(args["edits"], snapshot: snapshot, shared: files)
|
||||
let record: [String: Any] = ["proposal_id": key, "revision": revision, "status": "pending",
|
||||
"kind": "project_edits", "files": edits.map(\.path)]
|
||||
proposals[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key)
|
||||
proposal = Proposal(id: key, revision: revision, content: .files(edits))
|
||||
status = "Review the proposed assembly files."
|
||||
if let window {
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
if !NSApp.isActive { NSApp.requestUserAttention(.informationalRequest) }
|
||||
}
|
||||
return record
|
||||
}
|
||||
guard tool == "propose_fix", args.count == 6, proposal == nil, let path = args["path"] as? String, files.contains(path),
|
||||
let line = args["line_number"] as? Int, line > 0, let replacement = args["replacement"] as? String,
|
||||
replacement.utf8.count <= 1024, !replacement.contains(where: { $0.isNewline || $0 == "\0" }),
|
||||
let data = snapshot.files[path] else { throw AssemblyBuildFailure("invalid_proposal") }
|
||||
let source = String(decoding: data, as: UTF8.self)
|
||||
guard let range = Self.contentRange(line, source), range.length <= 4096 else { throw AssemblyBuildFailure("invalid_line") }
|
||||
let before = (source as NSString).substring(with: range)
|
||||
guard before != replacement else { throw AssemblyBuildFailure("unchanged_line") }
|
||||
let growth = replacement.utf8.count - before.utf8.count
|
||||
guard data.count + growth <= 64 * 1024,
|
||||
snapshot.files.values.reduce(0, { $0 + $1.count }) + growth <= 512 * 1024 else {
|
||||
throw AssemblyBuildFailure("project_too_large")
|
||||
}
|
||||
let record: [String: Any] = ["proposal_id": key, "revision": revision, "path": path, "line_number": line, "status": "pending"]
|
||||
proposals[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key)
|
||||
proposal = Proposal(id: key, revision: revision, content: .line(path: path, number: line, before: before, after: replacement))
|
||||
status = "Review the proposed assembly change."
|
||||
return record
|
||||
}
|
||||
|
||||
static func projectEdits(_ value: Any?, snapshot: AssemblyProjectSnapshot, shared: Set<String>) throws -> [AssemblyProjectEdit] {
|
||||
guard let rows = value as? [[String: Any]], (1...8).contains(rows.count) else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
var paths = Set<String>(), edits: [AssemblyProjectEdit] = []
|
||||
var bytes = 0, total = snapshot.files.values.reduce(0) { $0 + $1.count }
|
||||
for row in rows {
|
||||
guard row.count == 2, let path = row["path"] as? String, let source = row["source"] as? String,
|
||||
paths.insert(path).inserted, !source.utf8.contains(0) else { throw AssemblyBuildFailure("invalid_arguments") }
|
||||
guard shared.contains(path), let data = snapshot.files[path], let before = String(data: data, encoding: .utf8) else {
|
||||
throw AssemblyBuildFailure("access_denied")
|
||||
}
|
||||
guard !source.utf8.elementsEqual(before.utf8) else { throw AssemblyBuildFailure("unchanged_file") }
|
||||
let size = source.utf8.count
|
||||
bytes += size; total += size - data.count
|
||||
guard bytes <= 16 * 1024 else { throw AssemblyBuildFailure("patch_too_large") }
|
||||
edits.append(AssemblyProjectEdit(path: path, before: before, after: source))
|
||||
}
|
||||
guard total <= 512 * 1024 else { throw AssemblyBuildFailure("project_too_large") }
|
||||
return edits.sorted { $0.path < $1.path }
|
||||
}
|
||||
|
||||
private func integer(_ value: Any?) -> Int? {
|
||||
guard let n = value as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(),
|
||||
!["f", "d"].contains(String(cString: n.objCType)) else { return nil }
|
||||
return Int(exactly: n)
|
||||
}
|
||||
|
||||
private func buildRecord(_ id: String) -> [String: Any]? {
|
||||
guard var record = builds[id] else { return nil }
|
||||
if record["revision"] as? Int != revision { record["status"] = "stale" }
|
||||
return record
|
||||
}
|
||||
|
||||
private func build(_ model: AssemblyDevelopmentModel, inputs: AssemblyProjectSnapshot, revision number: Int,
|
||||
id: String, ticket: UUID, workspaceRevision: UUID) async {
|
||||
defer { if ticket == scope { buildTask = nil } }
|
||||
do {
|
||||
let artifact = try await model.service.build(inputs)
|
||||
guard try await snapshot(model, ticket: ticket) == inputs, revision == number, ticket == scope,
|
||||
workspaceRevision == model.workspaceRevision else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
builds[id]?["status"] = "succeeded"
|
||||
builds[id]?["entry"] = Int(artifact.entry)
|
||||
builds[id]?["target"] = inputs.cpu.rawValue
|
||||
builds[id]?["instruction_count"] = artifact.instructions.count
|
||||
builds[id]?["ranges"] = artifact.ranges.map { [Int($0.lowerBound), Int($0.upperBound)] }
|
||||
built = (id, number, artifact); canRun = true
|
||||
model.acceptSharedBuild(artifact)
|
||||
status = "Assembled for " + inputs.cpu.rawValue + ". " + AssemblyDevelopmentModel.summary(artifact)
|
||||
} catch {
|
||||
guard scope == ticket else { return }
|
||||
builds[id]?["status"] = revision == number ? "failed" : "stale"
|
||||
builds[id]?["diagnostics"] = (error as? AssemblyBuildFailure)?.diagnostics.prefix(32).map {
|
||||
["path": $0.path, "line": $0.line, "message": String($0.message.prefix(512))] as [String: Any]
|
||||
} ?? []
|
||||
builds[id]?["message"] = String(error.localizedDescription.prefix(2048))
|
||||
status = String(error.localizedDescription.prefix(512))
|
||||
}
|
||||
}
|
||||
|
||||
private static func contentRange(_ line: Int, _ source: String) -> NSRange? {
|
||||
let text = source as NSString
|
||||
guard let span = AssemblyDevelopmentModel.lineRange(line, text: source), span.location < text.length else { return nil }
|
||||
var end = 0
|
||||
text.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: span.location, length: 0))
|
||||
return NSRange(location: span.location, length: end - span.location)
|
||||
}
|
||||
|
||||
func decide(_ id: String, apply: Bool) async {
|
||||
guard let p = proposal, p.id == id, let model else { return }
|
||||
if !apply { proposals[p.id]?["status"] = "cancelled"; proposal = nil; return }
|
||||
do {
|
||||
let value = try await snapshot(model, ticket: scope)
|
||||
guard proposal?.id == p.id, revision == p.revision, !model.working, !model.commanding else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
guard connected, model.activeID == documentID, model.sourceRevision == lastSourceRevision else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
if case let .files(edits) = p.content {
|
||||
let removed = try replaceFiles(edits, model: model, value: value)
|
||||
appliedFiles = AppliedFiles(proposal: p, revision: revision, removedStops: removed)
|
||||
proposal = nil; proposals[p.id]?["status"] = "applied"; proposals[p.id]?["applied_revision"] = revision
|
||||
status = "Applied all reviewed files to the assembly draft."
|
||||
return
|
||||
}
|
||||
guard case let .line(path, line, before, after) = p.content else { return }
|
||||
guard model.buffer.path == path, value.files[path] == Data(model.buffer.text.utf8) else {
|
||||
model.selectFile(path, line: line)
|
||||
status = "Review the selected source file, then apply the change."
|
||||
return
|
||||
}
|
||||
guard let range = Self.contentRange(line, model.buffer.text), (model.buffer.text as NSString).substring(with: range) == before else {
|
||||
throw AssemblyBuildFailure("revision_conflict")
|
||||
}
|
||||
let expected = (model.buffer.text as NSString).replacingCharacters(in: range, with: after)
|
||||
let accepted = editors?.replaceReviewedLine(in: model.buffer, range: range, with: after) ?? false
|
||||
guard accepted, model.buffer.text == expected else { throw AssemblyBuildFailure("Open the assembly editor before applying the proposal.") }
|
||||
proposal = nil; proposals[p.id]?["status"] = "applied"
|
||||
_ = try await snapshot(model, ticket: scope)
|
||||
proposals[p.id]?["applied_revision"] = revision
|
||||
status = "Applied the edit. Build the revised assembly source."
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
private func replaceFiles(_ edits: [AssemblyProjectEdit], model: AssemblyDevelopmentModel, value: AssemblyProjectSnapshot,
|
||||
undo: Bool = false, restore: Set<AssemblyDevelopmentModel.SourceLine> = []) throws -> Set<AssemblyDevelopmentModel.SourceLine> {
|
||||
let paths = Set(edits.map(\.path))
|
||||
guard editors?.canReplace(model.document.buffers.filter { paths.contains($0.path) }) != false else {
|
||||
throw AssemblyBuildFailure("Finish the current editor input before applying this review.")
|
||||
}
|
||||
let removed = try model.replaceReviewedFiles(edits, snapshot: value, undo: undo, restoreStops: restore)
|
||||
var files = value.files
|
||||
for edit in edits { files[edit.path] = Data((undo ? edit.before : edit.after).utf8) }
|
||||
last = AssemblyProjectSnapshot(mainPath: value.mainPath, files: files, cpu: value.cpu, settings: value.settings)
|
||||
lastSourceRevision = model.sourceRevision; revision += 1
|
||||
built = nil; canRun = false; run = nil; runMessage = "No run started."
|
||||
return removed
|
||||
}
|
||||
|
||||
func undoFiles(_ id: String) async {
|
||||
guard let applied = appliedFiles, applied.proposal.id == id, let model, case let .files(edits) = applied.proposal.content else { return }
|
||||
do {
|
||||
let value = try await snapshot(model, ticket: scope)
|
||||
guard connected, model.activeID == documentID, appliedFiles?.proposal.id == applied.proposal.id, proposal == nil,
|
||||
revision == applied.revision, model.sourceRevision == lastSourceRevision else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
_ = try replaceFiles(edits, model: model, value: value, undo: true, restore: applied.removedStops)
|
||||
proposals[applied.proposal.id]?["status"] = "undone"; appliedFiles = nil
|
||||
status = "Undid all reviewed assembly changes."
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
func startRun(_ id: String, confirm: ((String) -> Bool)? = nil) async {
|
||||
guard canRun, proposal == nil, let model, let built, built.id == id, !model.working, !model.commanding else { return }
|
||||
let ticket = scope
|
||||
do {
|
||||
guard try await snapshot(model, ticket: ticket) == built.artifact.snapshot, self.built?.id == built.id,
|
||||
proposal == nil, revision == built.revision else { throw AssemblyBuildFailure("revision_conflict") }
|
||||
run = nil; runMessage = "Starting"
|
||||
let launched = try await model.launchShared(built.artifact, stillGranted: { [weak self] in
|
||||
self?.scope == ticket && self?.built?.id == built.id && self?.revision == built.revision &&
|
||||
self?.proposal == nil && self?.model?.activeID == self?.documentID
|
||||
}, confirm: confirm)
|
||||
guard scope == ticket else { return }
|
||||
let runID = UUID().uuidString
|
||||
run = (runID, built.revision, built.id, launched)
|
||||
runIO = MCPCompiledRunIO(machine: model.machine, runID: runID, expected: launched, assembly: true)
|
||||
runMessage = "started"; status = "Assembly program loaded."
|
||||
} catch { if scope == ticket { runMessage = error.localizedDescription; status = runMessage } }
|
||||
}
|
||||
|
||||
private func runResult(_ model: AssemblyDevelopmentModel, ticket: UUID, inspect: Bool = false) async throws -> [String: Any] {
|
||||
guard let run, let built, run.revision == revision, run.build == built.id else {
|
||||
return ["status": runMessage, "revision": revision]
|
||||
}
|
||||
let workspaceRevision = model.workspaceRevision
|
||||
let capture: VCCDebuggerSnapshot? = await withCheckedContinuation { c in
|
||||
model.machine.readDebugger(address: 0, followPC: true, memoryAddress: 0x0400) { c.resume(returning: $0) }
|
||||
}
|
||||
guard let capture, scope == ticket, revision == run.revision, self.run?.id == run.id,
|
||||
model.activeID == documentID, workspaceRevision == model.workspaceRevision,
|
||||
model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
|
||||
let current = capture.machine
|
||||
guard current.generation == run.machine.generation, current.debuggerProgramRevision == run.machine.debuggerProgramRevision,
|
||||
current.debuggerMappingFingerprint == run.machine.debuggerMappingFingerprint, current.debuggerAssemblyAttached
|
||||
else { throw AssemblyBuildFailure("stale_run") }
|
||||
var result: [String: Any] = ["run_id": run.id, "build_id": built.id, "revision": revision, "target": built.artifact.snapshot.cpu.rawValue,
|
||||
"processor": current.use6309 ? "HD6309" : "MC6809", "status": current.state == .paused ? "paused" : "running"]
|
||||
if current.assistantCompiledReturned {
|
||||
if inspect { throw AssemblyBuildFailure("run_finished") }
|
||||
result["status"] = "finished"
|
||||
if let runIO {
|
||||
if let text = try await runIO.finalScreenText() { result["final_screen_text"] = text }
|
||||
guard scope == ticket, self.runIO === runIO, self.run?.id == run.id,
|
||||
model.activeID == documentID, workspaceRevision == model.workspaceRevision else {
|
||||
throw AssemblyBuildFailure("stale_run")
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
guard current.state == .paused else {
|
||||
if inspect { throw AssemblyBuildFailure("pause_required") }
|
||||
return result
|
||||
}
|
||||
let guards = AssemblyDevelopmentModel.codeGuards(built.artifact.instructions)
|
||||
for (address, bytes) in guards {
|
||||
let range = Int(address)..<(Int(address) + bytes.count)
|
||||
guard range.upperBound <= capture.logicalMemory.count, range.upperBound <= capture.logicalMemoryAvailable.count,
|
||||
capture.logicalMemoryAvailable[range].allSatisfy({ $0 != 0 }), capture.logicalMemory[range].elementsEqual(bytes)
|
||||
else { throw AssemblyBuildFailure("stale_run") }
|
||||
}
|
||||
let pc = current.programCounter
|
||||
let candidates = built.artifact.instructions.filter { $0.address == pc }
|
||||
var sourceStop: [String: Any]?
|
||||
if candidates.count == 1, let mapped = candidates.first, files.contains(mapped.path),
|
||||
AssemblyDevelopmentModel.location(.init(path: mapped.path, line: mapped.line), in: built.artifact) != nil,
|
||||
let instruction = capture.instructions.first, instruction.address == pc, Array(instruction.bytes) == mapped.bytes {
|
||||
sourceStop = ["path": mapped.path, "line": mapped.line, "address": Int(pc), "instruction_bytes": mapped.bytes.map(Int.init)]
|
||||
}
|
||||
if inspect {
|
||||
var ranges = built.artifact.instructions.filter { files.contains($0.path) && guards[$0.address] != nil }.map {
|
||||
Int($0.address)..<(Int($0.address) + $0.bytes.count)
|
||||
}
|
||||
ranges.append(0x0400..<0x0401)
|
||||
let snapshot = try MCPDebuggerInspection(runID: run.id, capture: capture,
|
||||
scope: ["project_id": model.activeID.uuidString, "build_id": built.id, "revision": revision],
|
||||
sourceStop: sourceStop, watches: [], watchStatus: "Assembly has no source-level variable watches.", ranges: ranges)
|
||||
inspection = snapshot
|
||||
return snapshot.fields
|
||||
}
|
||||
guard let sourceStop else { return result }
|
||||
result["source_stop"] = sourceStop
|
||||
var registers = ["pc": Int(pc)]
|
||||
if let a = capture.registers["A"] { registers["a"] = a.intValue }
|
||||
if let e = capture.registers["E"] { registers["e"] = e.intValue }
|
||||
result["registers"] = registers
|
||||
if capture.logicalMemoryAvailable.count > 0x0400, capture.logicalMemoryAvailable[0x0400] != 0 {
|
||||
result["text_ram_0400"] = Int(capture.logicalMemory[0x0400])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// A fresh, explicitly isolated synthetic project. Only the regression variant accepts test decisions.
|
||||
func startFixture(_ model: AssemblyDevelopmentModel, directory: URL, romDirectory: URL) async throws {
|
||||
guard CommandLine.arguments.contains("--interface-validation"),
|
||||
try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty
|
||||
else { throw AssemblyBuildFailure("Use an empty isolated assembly validation directory.") }
|
||||
try await MCPBASICRun.bootFixture(model.machine, romDirectory: romDirectory)
|
||||
let project = directory.appendingPathComponent("Assembly")
|
||||
try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false)
|
||||
let enhanced = CommandLine.arguments.contains("--mcp-assembly-hd6309")
|
||||
let source = """
|
||||
org $3f00
|
||||
include "value.inc"
|
||||
start \(enhanced ? "lde" : "lda") #VALUE
|
||||
\(enhanced ? "adde" : "adda") #1
|
||||
\(enhanced ? "ste" : "sta") $0400
|
||||
done rts
|
||||
end start
|
||||
|
||||
"""
|
||||
try Data(source.utf8).write(to: project.appendingPathComponent("main.asm"), options: .withoutOverwriting)
|
||||
try Data("VALUE equ 1\n".utf8).write(to: project.appendingPathComponent("value.inc"), options: .withoutOverwriting)
|
||||
model.open(project, folder: true)
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||
while model.document.directory?.lastPathComponent != project.lastPathComponent, ContinuousClock.now < deadline {
|
||||
try await Task.sleep(for: .milliseconds(30))
|
||||
}
|
||||
let physicalProject = try CMOCProject.physicalURL(project)
|
||||
guard model.document.directory?.path == physicalProject.path else { throw AssemblyBuildFailure("The synthetic assembly workspace failed to open.") }
|
||||
model.setCPU(enhanced ? .hd6309 : .mc6809)
|
||||
try await connect(model, to: directory.appendingPathComponent("grant.json"))
|
||||
guard CommandLine.arguments.contains("--mcp-assembly-regression") else { return }
|
||||
let editorPool = AssemblyEditorPool()
|
||||
editors = editorPool
|
||||
let editorWindow = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 620, height: 320),
|
||||
styleMask: [.titled], backing: .buffered, defer: false)
|
||||
editorWindow.title = "Assembly Development — Regression"
|
||||
let editor = NSHostingView(rootView: AssemblyEditor(finder: SourceFind(), model: model, pool: editorPool, lookup: {}))
|
||||
editor.sizingOptions = []
|
||||
editorWindow.contentView = editor
|
||||
editorWindow.orderBack(nil)
|
||||
editor.layoutSubtreeIfNeeded()
|
||||
try Data().write(to: directory.appendingPathComponent("assembly-regression-fixture"), options: .withoutOverwriting)
|
||||
let ticket = scope
|
||||
Task {
|
||||
defer { editorWindow.orderOut(nil) }
|
||||
func consume(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 }
|
||||
while scope == ticket {
|
||||
try? await Task.sleep(for: .milliseconds(100))
|
||||
if consume("apply"), let id = proposal?.id { await decide(id, apply: true) }
|
||||
if consume("undo-files"), let id = undoableProposalID { await undoFiles(id) }
|
||||
if consume("cancel-project-edits"), let id = proposal?.id { await decide(id, apply: false) }
|
||||
if consume("stale-review-click") {
|
||||
// A click captured from a retired native review must never operate on its replacement.
|
||||
await decide("retired-review", apply: true)
|
||||
await decide("retired-review", apply: false)
|
||||
await undoFiles("retired-review")
|
||||
try? Data().write(to: directory.appendingPathComponent("checked-stale-click"))
|
||||
}
|
||||
if consume("capture-review"), proposal != nil {
|
||||
show(model, editors: editorPool)
|
||||
try? await Task.sleep(for: .milliseconds(250))
|
||||
if let panel = window {
|
||||
let capture = Process()
|
||||
capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
|
||||
capture.arguments = ["-x", "-o", "-l", String(panel.windowNumber), directory.appendingPathComponent("review.png").path]
|
||||
capture.terminationHandler = { _ in Task { @MainActor in panel.orderOut(nil) } }
|
||||
do { try capture.run() } catch { panel.orderOut(nil) }
|
||||
}
|
||||
}
|
||||
if consume("stale-run-click") {
|
||||
await startRun("retired-build", confirm: { _ in true })
|
||||
try? Data().write(to: directory.appendingPathComponent("checked-stale-run"))
|
||||
}
|
||||
if consume("play"), let id = runnableBuildID { await startRun(id, confirm: { _ in true }) }
|
||||
if consume("run"), let id = runnableBuildID {
|
||||
if !model.document.breakpoints.contains(.init(path: "main.asm", line: 6)),
|
||||
let span = AssemblyDevelopmentModel.lineRange(6, text: model.buffer.text) {
|
||||
model.moveCursor(span.location); model.toggleBreakpoint()
|
||||
}
|
||||
await startRun(id, confirm: { _ in true })
|
||||
}
|
||||
if consume("quit") {
|
||||
revoke()
|
||||
NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private struct AssemblyAccessView: View {
|
||||
@ObservedObject var access: MCPAssembly
|
||||
@ObservedObject var model: AssemblyDevelopmentModel
|
||||
@State private var expandedFiles = Set<String>()
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label(model.document.title, systemImage: "cpu").font(.headline)
|
||||
if access.connected {
|
||||
if let proposal = access.proposal {
|
||||
switch proposal.content {
|
||||
case let .line(path, number, before, after):
|
||||
Text("\(path), line \(number)").bold()
|
||||
comparison(before: before, after: after)
|
||||
reviewButtons(proposal.id, multiple: false)
|
||||
case .files(let edits):
|
||||
Text(edits.count == 1 ? "Review 1 assembly file" : "Review \(edits.count) assembly files").font(.headline)
|
||||
reviewButtons(proposal.id, multiple: true)
|
||||
ForEach(edits, id: \.path) { edit in
|
||||
DisclosureGroup(edit.path, isExpanded: Binding(
|
||||
get: { expandedFiles.contains(edit.path) },
|
||||
set: { if $0 { expandedFiles.insert(edit.path) } else { expandedFiles.remove(edit.path) } }
|
||||
)) {
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
sourceColumn("Current", edit.before)
|
||||
Divider()
|
||||
sourceColumn("Proposed", edit.after)
|
||||
}.padding(.vertical, 4)
|
||||
}
|
||||
}
|
||||
.onAppear { if let first = edits.first { expandedFiles = [first.path] } }
|
||||
.id(proposal.id)
|
||||
}
|
||||
}
|
||||
if let id = access.undoableProposalID {
|
||||
Button("Undo All Changes") { Task { await access.undoFiles(id) } }
|
||||
}
|
||||
if let url = access.grantURL {
|
||||
MCPChatGPTSetup(grantURL: url, firstPrompt: "Identify my shared VCC Plus assembly project and target processor. Read the entry source file and describe what the CoCo program does.")
|
||||
}
|
||||
HStack {
|
||||
Button("Copy MCP Helper Path") {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-mcp").path, forType: .string)
|
||||
}
|
||||
Button("Revoke Connection") { access.revoke() }
|
||||
}
|
||||
let buildID = access.runnableBuildID
|
||||
Button("Run Shared Build…") {
|
||||
if let buildID { Task { await access.startRun(buildID) } }
|
||||
}.disabled(buildID == nil || access.proposal != nil || model.commanding || model.working)
|
||||
} else {
|
||||
Text("Share this document’s assembly files with a client that can build them and propose edits. You approve edits and start runs. The client can read the guest text screen and send one letter, digit or space at a time during your run. It can check machine and media status. At a verified source stop it can inspect registers, shared program memory and the text byte at $0400. The client’s model provider may receive those results.")
|
||||
Button("Save Assembly Connection…") { access.choose(model) }
|
||||
}
|
||||
if !access.status.isEmpty { Text(access.status).foregroundStyle(.secondary).textSelection(.enabled) }
|
||||
}.padding().frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
private func sourceColumn(_ title: String, _ source: String) -> some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(title).font(.caption).foregroundStyle(.secondary)
|
||||
ScrollView(.horizontal) {
|
||||
Text(verbatim: source).font(.callout.monospaced()).textSelection(.enabled)
|
||||
.fixedSize(horizontal: true, vertical: true)
|
||||
}
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
@ViewBuilder private func comparison(before: String, after: String) -> some View {
|
||||
Text("Current").font(.caption)
|
||||
Text(before).font(.body.monospaced()).textSelection(.enabled)
|
||||
Text("Proposed").font(.caption)
|
||||
Text(after).font(.body.monospaced()).textSelection(.enabled)
|
||||
}
|
||||
private func reviewButtons(_ id: String, multiple: Bool) -> some View {
|
||||
HStack {
|
||||
Button(multiple ? "Apply All Changes" : "Apply Edit") { Task { await access.decide(id, apply: true) } }
|
||||
Button(multiple ? "Cancel Changes" : "Cancel Edit") { Task { await access.decide(id, apply: false) } }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
enum MCPGuestKey {
|
||||
static let limit = 64
|
||||
|
||||
static func accepts(_ keys: String) -> Bool {
|
||||
guard keys.utf8.count == 1, let byte = keys.utf8.first else { return false }
|
||||
return byte == 32 || (48...57).contains(byte) || (65...90).contains(byte) || (97...122).contains(byte)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class MCPBASICRun: ObservableObject {
|
||||
@Published private(set) var status = ""
|
||||
@Published private(set) var busy = false
|
||||
@Published private(set) var runID: String?
|
||||
@Published private(set) var receipt: [String: Any]?
|
||||
|
||||
private struct Run {
|
||||
let id: String
|
||||
let document: UUID
|
||||
let revision: Int
|
||||
let snapshot: VCCMachineSnapshot
|
||||
let guestSource: String
|
||||
}
|
||||
private var inspection: MCPDebuggerInspection?
|
||||
private var run: Run?
|
||||
private weak var machine: MachineModel?
|
||||
private var sourceChanges: AnyCancellable?
|
||||
private var requestedDocument: UUID?
|
||||
private var requestedRevision: Int?
|
||||
private var generation = UUID()
|
||||
private var sending = false
|
||||
private var sent: [String: String] = [:]
|
||||
private var verifiedPrompt = false
|
||||
private var currentApproval: (() -> Bool)?
|
||||
|
||||
func reset() {
|
||||
if let run { machine?.cancelMCPInput(runID: run.id) }
|
||||
generation = UUID()
|
||||
run = nil
|
||||
inspection = nil
|
||||
runID = nil
|
||||
receipt = nil
|
||||
requestedDocument = nil
|
||||
requestedRevision = nil
|
||||
sourceChanges = nil
|
||||
currentApproval = nil
|
||||
busy = false
|
||||
sending = false
|
||||
verifiedPrompt = false
|
||||
sent.removeAll()
|
||||
status = ""
|
||||
}
|
||||
|
||||
func start(model: BASICDevelopmentModel, bothChoices: Bool, isCurrent: @escaping () -> Bool) async {
|
||||
guard !busy, !sending, isCurrent() else { return }
|
||||
reset()
|
||||
busy = true
|
||||
machine = model.machine
|
||||
currentApproval = isCurrent
|
||||
sourceChanges = model.$source.dropFirst().sink { [weak self] _ in self?.reset() }
|
||||
let ticket = generation, document = model.documentID, revision = model.sourceRevision
|
||||
requestedDocument = document
|
||||
requestedRevision = revision
|
||||
let current = { self.generation == ticket && document == model.documentID && revision == model.sourceRevision && isCurrent() }
|
||||
defer { if generation == ticket { busy = false } }
|
||||
do {
|
||||
var branches: [[String: Any]] = []
|
||||
for key in bothChoices ? ["2", "1"] : [""] {
|
||||
try require(current(), "The approved revision or connection changed.")
|
||||
status = "Starting the reviewed BASIC program…"
|
||||
guard let (snapshot, guestSource) = await model.performTransfer(run: true, reviewIsCurrent: current) else {
|
||||
throw ProfileFailure.message(model.message ?? "The BASIC workspace could not start this run.")
|
||||
}
|
||||
try require(current() && model.machine.basicWorkspaceOwner == model.workspaceID, "The BASIC workspace changed.")
|
||||
let started = Run(id: UUID().uuidString, document: document, revision: revision, snapshot: snapshot, guestSource: guestSource)
|
||||
run = started
|
||||
runID = started.id
|
||||
sent.removeAll()
|
||||
verifiedPrompt = false
|
||||
if bothChoices {
|
||||
status = key == "2" ? "Checking Mars in the CoCo…" : "Checking Earth in the CoCo…"
|
||||
branches.append(try await checkChoice(key, model: model, run: started))
|
||||
}
|
||||
}
|
||||
try require(current(), "The approved revision or connection changed.")
|
||||
if bothChoices {
|
||||
let mismatches = branches.filter { $0["color_matches"] as? Bool == false }
|
||||
receipt = ["document_id": document.uuidString, "revision": revision, "branches": branches,
|
||||
"verified": mismatches.isEmpty, "behavior_verified": true]
|
||||
verifiedPrompt = true
|
||||
if let first = mismatches.first {
|
||||
status = "Both greetings and PRINT 7 verified. Choice " + (first["key"] as? String ?? "") +
|
||||
" displayed " + (first["background_rgb"] as? String ?? "") + " instead of the expected " +
|
||||
(first["expected_color"] as? String ?? "") + " background."
|
||||
} else { status = "Verified both choices and PRINT 7." }
|
||||
} else { status = "BASIC started. The client can read the guest screen and send a single letter, digit or space at a time." }
|
||||
} catch {
|
||||
if generation == ticket {
|
||||
status += " " + error.localizedDescription
|
||||
run = nil
|
||||
runID = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func require(_ condition: Bool, _ reason: String) throws {
|
||||
guard condition else { throw ProfileFailure.message(reason) }
|
||||
}
|
||||
|
||||
private func validate(_ model: BASICDevelopmentModel, _ expected: Run) throws {
|
||||
try require(run?.id == expected.id && currentApproval?() == true && model.documentID == expected.document
|
||||
&& model.sourceRevision == expected.revision && model.machine.basicWorkspaceOwner == model.workspaceID,
|
||||
"The run or reviewed document has changed.")
|
||||
}
|
||||
|
||||
private func screen(_ model: BASICDevelopmentModel, _ expected: Run) async throws -> [String: Any] {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(1))
|
||||
while true {
|
||||
try validate(model, expected)
|
||||
do {
|
||||
let result = try await model.machine.mcpScreen(expected: expected.snapshot, source: expected.guestSource)
|
||||
try validate(model, expected)
|
||||
return result
|
||||
} catch {
|
||||
// WIDTH can temporarily switch out BASIC's RAM while redrawing.
|
||||
guard error.localizedDescription == "Direct BASIC access requires the normal BASIC memory map",
|
||||
ContinuousClock.now < deadline else { throw error }
|
||||
try await Task.sleep(for: .milliseconds(45))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func type(_ keys: String, model: BASICDevelopmentModel, run: Run) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||
while true {
|
||||
try validate(model, run)
|
||||
do {
|
||||
try await model.machine.mcpPaste(keys, runID: run.id, direct: keys == "PRINT 7\n",
|
||||
expected: run.snapshot, source: run.guestSource)
|
||||
try validate(model, run)
|
||||
return
|
||||
} catch {
|
||||
// Both refusals occur before the controller queues any keys. A ROM
|
||||
// interrupt or GIME text update may temporarily obscure direct mode.
|
||||
let beforeTyping = ["Direct BASIC access requires the normal BASIC memory map",
|
||||
"The guest is not at the expected BASIC input state."]
|
||||
guard beforeTyping.contains(error.localizedDescription), ContinuousClock.now < deadline else { throw error }
|
||||
try await Task.sleep(for: .milliseconds(45))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func wait(_ reason: String, model: BASICDevelopmentModel, run: Run,
|
||||
until: ([String: Any], [String]) -> Bool) async throws -> [String: Any] {
|
||||
let clock = ContinuousClock()
|
||||
let end = clock.now.advanced(by: .seconds(6))
|
||||
var last = ""
|
||||
var state = ""
|
||||
while clock.now < end {
|
||||
let result = try await screen(model, run)
|
||||
last = result["text"] as? String ?? ""
|
||||
state = "frame \(result["frame"] ?? "?"), paste \(result["paste_remaining"] ?? "?"), direct input \(result["direct_prompt"] ?? "?")"
|
||||
if until(result, last.components(separatedBy: "\n")) { return result }
|
||||
try await Task.sleep(for: .milliseconds(75))
|
||||
}
|
||||
throw ProfileFailure.message("Timed out waiting for " + reason + " (" + state + "). Guest screen: " + String(last.suffix(350)))
|
||||
}
|
||||
|
||||
private static func hasMenu(_ lines: [String]) -> Bool {
|
||||
let shown = lines.map { $0.trimmingCharacters(in: .whitespaces).lowercased() }.filter { !$0.isEmpty }
|
||||
guard shown.count >= 2 else { return false }
|
||||
let first = shown[shown.count - 2], second = shown[shown.count - 1]
|
||||
return first.hasPrefix("1") && first.contains("earth") && second.hasPrefix("2") && second.contains("mars")
|
||||
}
|
||||
|
||||
private func checkChoice(_ key: String, model: BASICDevelopmentModel, run: Run) async throws -> [String: Any] {
|
||||
let menu = try await wait("the 40-column choice menu", model: model, run: run) { s, lines in
|
||||
s["columns"] as? Int == 40 && Self.hasMenu(lines) && s["direct_prompt"] as? Bool == false
|
||||
}
|
||||
try await type("3", model: model, run: run)
|
||||
let menuFrame = menu["frame"] as? UInt64 ?? 0
|
||||
let ignored = try await wait("the menu after the unrelated key", model: model, run: run) { s, _ in
|
||||
Self.hasMenu((s["text"] as? String ?? "").components(separatedBy: "\n")) && s["direct_prompt"] as? Bool == false &&
|
||||
s["paste_remaining"] as? Int == 0 && (s["frame"] as? UInt64 ?? 0) >= menuFrame + 10
|
||||
}
|
||||
try await type(key, model: model, run: run)
|
||||
let greeting = key == "1" ? "Hello Nice Blue Dot World!" : "Bring a warm coat!"
|
||||
let output = try await wait("the greeting and BASIC prompt", model: model, run: run) { s, lines in
|
||||
s["direct_prompt"] as? Bool == true && s["paste_remaining"] as? Int == 0 &&
|
||||
lines.contains { $0.trimmingCharacters(in: .whitespaces) == "OK" }
|
||||
}
|
||||
let text = output["text"] as? String ?? ""
|
||||
let lines = text.components(separatedBy: "\n")
|
||||
guard let row = lines.firstIndex(where: { $0.trimmingCharacters(in: .whitespaces) == greeting }) else {
|
||||
throw ProfileFailure.message("Expected “" + greeting + "” for choice " + key + ". Guest screen: " + text)
|
||||
}
|
||||
guard let sample = (output["colors"] as? [[String: Int]])?.first(where: { $0["row"] == row }),
|
||||
let rgb = sample["rgb"] else {
|
||||
throw ProfileFailure.message("The greeting has no measurable text-cell background.")
|
||||
}
|
||||
let red = (rgb >> 16) & 255, green = (rgb >> 8) & 255, blue = rgb & 255
|
||||
// Require a strongly dominant primary. Composite palette 37 renders amber
|
||||
// (#FFBF39); its largest component is red, which alone cannot verify red.
|
||||
let dominant = key == "1" ? blue : red
|
||||
let others = key == "1" ? max(red, green) : max(green, blue)
|
||||
let correct = dominant >= 32 && dominant >= 2 * others
|
||||
try require(sample["palette_value"] == (key == "1" ? 10 : 37), "The greeting used an unexpected GIME palette value.")
|
||||
try await type("PRINT 7\n", model: model, run: run)
|
||||
let prompt = try await wait("the result of PRINT 7", model: model, run: run) { s, rows in
|
||||
let compact = rows.map { $0.trimmingCharacters(in: .whitespaces).uppercased() }.filter { !$0.isEmpty }
|
||||
return compact.suffix(3) == ["PRINT 7", "7", "OK"] && s["direct_prompt"] as? Bool == true && s["paste_remaining"] as? Int == 0
|
||||
}
|
||||
return ["key": key, "run_id": run.id, "invalid_key": "3", "invalid_screen": ignored["text"] ?? "",
|
||||
"screen": text, "greeting": lines[row], "color_matches": correct, "expected_color": key == "1" ? "blue" : "red", "background_rgb": String(format: "#%06X", rgb), "cell": sample,
|
||||
"frame": output["frame"] ?? 0, "signal": output["signal"] ?? 0, "columns": output["columns"] ?? 0,
|
||||
"processor": run.snapshot.use6309 ? "HD6309" : "MC6809", "command_screen": prompt["text"] ?? ""]
|
||||
}
|
||||
|
||||
private func debug(_ tool: String, _ args: [String: Any], model: BASICDevelopmentModel, run: Run) async throws -> [String: Any] {
|
||||
// The BASIC bridge verifies exact detokenized source plus run identity.
|
||||
let observed = try await model.machine.checkReviewedBASIC(run.snapshot, source: run.guestSource)
|
||||
try validate(model, run)
|
||||
guard MCPDebuggerInspection.sameProgram(observed, run.snapshot) else { throw ProfileFailure.message("stale_run") }
|
||||
if tool == "get_debug_snapshot" {
|
||||
guard args.count == 1 else { throw ProfileFailure.message("invalid_arguments") }
|
||||
let captured = try await MCPDebuggerInspection.capture(model.machine)
|
||||
let state = captured.machine
|
||||
guard MCPDebuggerInspection.sameProgram(state, run.snapshot) else { throw ProfileFailure.message("stale_run") }
|
||||
guard state.state == .paused else { throw ProfileFailure.message("pause_required") }
|
||||
let stop = model.machine.basicDebug
|
||||
var watches: [[String: String]] = [], watchStatus = "Pause at a supported BASIC statement to inspect watches."
|
||||
var mapped: [String: Any]?
|
||||
if state.basicDebugAttached && !state.basicStepping && state.basicStoppedLine >= 0 {
|
||||
mapped = ["line": state.basicStoppedLine, "address": Int(state.programCounter)]
|
||||
let (variables, error) = await model.machine.inspectBASIC(source: model.source, stop: stop)
|
||||
if let variables {
|
||||
watches = model.watches.compactMap { name in BASICWatch(name).map { ["name": name, "value": $0.value(in: variables)] } }
|
||||
watchStatus = "available"
|
||||
} else { watchStatus = error ?? "BASIC variable memory is unavailable." }
|
||||
}
|
||||
let bytes = captured.logicalMemory, available = captured.logicalMemoryAvailable
|
||||
guard bytes.count >= 0x1d, available.count >= 0x1d, available[0x19..<0x1d].allSatisfy({ $0 != 0 }) else {
|
||||
throw ProfileFailure.message("memory_unavailable")
|
||||
}
|
||||
let start = Int(bytes[0x19]) * 256 + Int(bytes[0x1a]), end = Int(bytes[0x1b]) * 256 + Int(bytes[0x1c])
|
||||
// A second source check binds the parsed interpreter pointers and watches to the same paused stop.
|
||||
let now = try await model.machine.checkReviewedBASIC(run.snapshot, source: run.guestSource)
|
||||
try validate(model, run)
|
||||
guard MCPDebuggerInspection.sameProgram(now, state), now.state == .paused, now.cycles == state.cycles,
|
||||
end >= start else { throw ProfileFailure.message("stale_snapshot") }
|
||||
inspection = try MCPDebuggerInspection(runID: run.id, capture: captured,
|
||||
scope: ["document_id": run.document.uuidString, "revision": run.revision],
|
||||
sourceStop: mapped, watches: watches, watchStatus: watchStatus, ranges: [start..<end])
|
||||
}
|
||||
guard let inspection else { throw ProfileFailure.message("no_snapshot") }
|
||||
return try inspection.reply(tool: tool, arguments: args)
|
||||
}
|
||||
|
||||
func handle(tool: String, arguments: [String: Any], model: BASICDevelopmentModel) async -> [String: Any] {
|
||||
if tool == "get_run" {
|
||||
guard let requestedDocument, let requestedRevision else { return ["error": "no_run"] }
|
||||
guard currentApproval?() == true, model.documentID == requestedDocument, model.sourceRevision == requestedRevision,
|
||||
arguments.count == 2, arguments["document_id"] as? String == requestedDocument.uuidString,
|
||||
arguments["revision"] as? Int == requestedRevision else { return ["error": "revision_conflict"] }
|
||||
var result: [String: Any] = ["document_id": requestedDocument.uuidString, "revision": requestedRevision,
|
||||
"busy": busy, "status": status, "run_id": runID as Any? ?? NSNull()]
|
||||
if let receipt { result["receipt"] = receipt }
|
||||
return ["result": result]
|
||||
}
|
||||
guard let run else { return ["error": "no_run"] }
|
||||
do {
|
||||
try validate(model, run)
|
||||
guard arguments["run_id"] as? String == run.id else { return ["error": "stale_run"] }
|
||||
if tool == "get_debug_snapshot" || tool == "read_debug_memory" {
|
||||
return ["result": try await debug(tool, arguments, model: model, run: run)]
|
||||
}
|
||||
if tool == "read_screen_text", arguments.count == 1 {
|
||||
var observation = try await screen(model, run)
|
||||
observation["run_id"] = run.id
|
||||
observation["revision"] = run.revision
|
||||
return ["result": observation]
|
||||
}
|
||||
guard tool == "send_keys", arguments.count == 3, let request = arguments["request_id"] as? String,
|
||||
(1...64).contains(request.utf8.count), let keys = arguments["keys"] as? String,
|
||||
MCPGuestKey.accepts(keys) || keys == "PRINT 7\n"
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
let accepted = ["result": ["run_id": run.id, "request_id": request, "accepted": true] as [String: Any]]
|
||||
if let previous = sent[request] { return previous == keys ? accepted : ["error": "request_conflict"] }
|
||||
guard sent.count < MCPGuestKey.limit else { return ["error": "input_limit_reached"] }
|
||||
guard !busy, !sending, !verifiedPrompt else { return ["error": "input_unavailable"] }
|
||||
sending = true
|
||||
defer { if self.run?.id == run.id { sending = false } }
|
||||
try await type(keys, model: model, run: run)
|
||||
sent[request] = keys
|
||||
verifiedPrompt = keys == "PRINT 7\n"
|
||||
return accepted
|
||||
} catch { return ["error": error.localizedDescription] }
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
static func bootFixture(_ machine: MachineModel, romDirectory: URL,
|
||||
use6309: Bool = CommandLine.arguments.contains("--basic-6309"),
|
||||
composite: Bool = CommandLine.arguments.contains("--mcp-composite")) async throws {
|
||||
var profile = ConfigurationProfile(name: "Isolated BASIC review")
|
||||
profile.systemROM = romDirectory.appendingPathComponent("coco3.rom")
|
||||
profile.media.rom = romDirectory.appendingPathComponent("disk11.rom")
|
||||
var layout = CartridgeAssignments()
|
||||
layout.slots[0].kind = .floppy
|
||||
profile.media.cartridges = layout
|
||||
profile.sound = false
|
||||
profile.videoOutput = composite ? 1 : 0
|
||||
profile.machine.use6309 = use6309
|
||||
await machine.loadProfile(profile)
|
||||
if let issue = machine.profileError { throw ProfileFailure.message(issue) }
|
||||
machine.resume()
|
||||
try await machine.waitForMCPFixturePrompt()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,167 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
enum MCPCMOCGuest {
|
||||
struct DebugInfo {
|
||||
let map: CMOCProjectSourceMap
|
||||
let variables: CMOCVariableDebug?
|
||||
|
||||
init(_ build: CMOCBuildArtifact) throws {
|
||||
map = try CMOCProjectSourceMap.parse(artifact: build)
|
||||
guard map.matches(sources: build.sources, binary: build.binaryData) else {
|
||||
throw ProfileFailure.message("The C source and binary differ from their source map.")
|
||||
}
|
||||
variables = try? CMOCVariableDebug.parse(artifact: build, verifiedMap: map)
|
||||
}
|
||||
}
|
||||
|
||||
typealias SaveStop = @MainActor (VCCDebuggerSnapshot, DebugInfo, CMOCProjectSourceMap.Instruction) throws -> Void
|
||||
|
||||
static func run(model: CMOCDevelopmentModel, build: CMOCBuildArtifact,
|
||||
isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> [String: Any] {
|
||||
let (info, point, disk, expectedOutput) = try await Task.detached {
|
||||
let info = try DebugInfo(build)
|
||||
guard let disk = build.diskURL,
|
||||
let entry = build.sources["main.c"].flatMap({ String(data: $0, encoding: .utf8) }),
|
||||
let line = entry.components(separatedBy: "\n").firstIndex(where: { $0.contains("printf(\"DISK RESULT:") }),
|
||||
let point = info.map.instructions.first(where: { $0.sourcePath == "main.c" && $0.sourceLine == line + 1 }) else {
|
||||
throw ProfileFailure.message("The Hello Disk source stop could not be matched to this binary.")
|
||||
}
|
||||
let wordPath = "assets/words.txt"
|
||||
let wordData = try Data(contentsOf: build.fileURL(wordPath))
|
||||
guard CMOCProject.sha256(wordData) == build.fileHashes[wordPath],
|
||||
let words = String(data: wordData, encoding: .utf8)?.split(whereSeparator: \.isNewline) else {
|
||||
throw ProfileFailure.message("The word list changed after this disk was built.")
|
||||
}
|
||||
let lines = ["HELLO FROM A MULTI-FILE PROJECT", "WORDS READ FROM THE FLOPPY:"] + words.map(String.init) +
|
||||
["", "DISK RESULT: 0", "GENERATED WORD COUNT: \(words.count)"]
|
||||
return (info, point, try Data(contentsOf: disk), lines.joined(separator: "\n"))
|
||||
}.value
|
||||
let machine = model.machine
|
||||
let initial = await machine.mcpMachineSnapshot()
|
||||
let name = "Hello Disk " + UUID().uuidString + ".dsk"
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(25))
|
||||
do {
|
||||
let launched = try await launchAtStop(model, build: build, info: info, point: point, disk: disk, name: name,
|
||||
initial: initial, deadline: deadline, isCurrent: isCurrent, saveStop: saveStop)
|
||||
let continued = await machine.continueReviewedC(launched, name: name, stop: point.address, bytes: Data(point.bytes))
|
||||
if let error = continued.errorMessage { throw ProfileFailure.message(error) }
|
||||
while ContinuousClock.now < deadline {
|
||||
let (screen, now) = await machine.reviewedCOutput()
|
||||
guard isCurrent(), now.generation == launched.generation, now.debuggerProgramRevision == launched.debuggerProgramRevision,
|
||||
now.disks.first?.name == name else { throw CancellationError() }
|
||||
if let screen, let output = screen.range(of: expectedOutput + "\n", options: .backwards),
|
||||
now.disks[0].readEvents > initial.disks[0].readEvents {
|
||||
let receipt: [String: Any] = ["screen": String(screen[output]).trimmingCharacters(in: .newlines), "cpu": now.use6309 ? "6309" : "6809",
|
||||
"source_stop": ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address),
|
||||
"bytes": point.bytes.map { Int($0) }],
|
||||
"disk_read_events": now.disks[0].readEvents - initial.disks[0].readEvents,
|
||||
"disk_write_protected": now.disks[0].writeProtected, "artifact_id": build.id.uuidString]
|
||||
await machine.ejectReviewedCDisk(name)
|
||||
return receipt
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(50))
|
||||
}
|
||||
throw ProfileFailure.message("Hello Disk did not display its successful disk result and generated word count.")
|
||||
} catch {
|
||||
await machine.ejectReviewedCDisk(name)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
static func runOrdinary(model: CMOCDevelopmentModel, build: CMOCBuildArtifact, play: Bool = false,
|
||||
isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> [String: Any] {
|
||||
let (info, point) = try await Task.detached {
|
||||
let info = try DebugInfo(build)
|
||||
guard info.map.bankedLayout == nil else {
|
||||
throw ProfileFailure.message("This packed build requires its declared disk launch. Use the C workspace's Disk & Run, or grant disposable playtests for assistant execution.")
|
||||
}
|
||||
guard let main = info.variables?.functions.first(where: { $0.name == "main" && $0.sourcePath == build.entrySourcePath }),
|
||||
let point = info.map.instructions.first(where: {
|
||||
$0.sourcePath == main.sourcePath && main.body <= Int($0.address) && Int($0.address) < main.end
|
||||
}) else { throw ProfileFailure.message("Build the Debug configuration with a mapped main function to run this shared project.") }
|
||||
return (info, point)
|
||||
}.value
|
||||
let initial = await model.machine.mcpMachineSnapshot()
|
||||
let state = try await launchAtStop(model, build: build, info: info, point: point, disk: nil, name: "",
|
||||
initial: initial, deadline: .now.advanced(by: .seconds(25)),
|
||||
isCurrent: isCurrent, saveStop: saveStop)
|
||||
if play {
|
||||
guard isCurrent() else { throw CancellationError() }
|
||||
let continued = await model.machine.continueReviewedC(state, name: "", stop: point.address, bytes: Data(point.bytes))
|
||||
if let error = continued.errorMessage { throw ProfileFailure.message(error) }
|
||||
}
|
||||
return ["artifact_id": build.id.uuidString, "status": play ? "continued_from_main" : "paused", "cpu": state.use6309 ? "6309" : "6809",
|
||||
"source_stop": ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address),
|
||||
"bytes": point.bytes.map(Int.init)] as [String: Any]]
|
||||
}
|
||||
|
||||
private static func launchAtStop(_ model: CMOCDevelopmentModel, build: CMOCBuildArtifact, info: DebugInfo,
|
||||
point: CMOCProjectSourceMap.Instruction, disk: Data?, name: String,
|
||||
initial: VCCMachineSnapshot, deadline: ContinuousClock.Instant,
|
||||
isCurrent: @escaping @MainActor () -> Bool, saveStop: SaveStop) async throws -> VCCMachineSnapshot {
|
||||
let machine = model.machine
|
||||
var launched: VCCMachineSnapshot
|
||||
repeat {
|
||||
guard isCurrent() else { throw CancellationError() }
|
||||
launched = await machine.startReviewedC(build.binaryData, disk: disk, name: name, stop: point.address, expected: initial)
|
||||
if launched.errorMessage == nil { break }
|
||||
if launched.errorMessage == "occupied_basic_program" { throw ProfileFailure.message(MCPMachineStatus.occupiedBASICGuidance) }
|
||||
guard launched.errorMessage == "Waiting for an empty Disk BASIC prompt.", ContinuousClock.now < deadline else {
|
||||
throw ProfileFailure.message(launched.errorMessage ?? "The CoCo could not start the reviewed binary.")
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(60))
|
||||
} while true
|
||||
var stopped = launched
|
||||
while stopped.state != .paused && ContinuousClock.now < deadline {
|
||||
guard isCurrent(), stopped.generation == launched.generation,
|
||||
stopped.debuggerProgramRevision == launched.debuggerProgramRevision else { throw CancellationError() }
|
||||
try await Task.sleep(for: .milliseconds(50))
|
||||
stopped = await machine.mcpMachineSnapshot()
|
||||
}
|
||||
let capture = try await MCPDebuggerInspection.capture(machine)
|
||||
guard isCurrent(), MCPDebuggerInspection.sameProgram(capture.machine, launched),
|
||||
capture.machine.state == .paused, capture.machine.programCounter == point.address,
|
||||
capture.machine.debuggerDevelopmentAttached, disk == nil || capture.machine.disks.first?.name == name,
|
||||
capture.instructions.first?.bytes == Data(point.bytes) else {
|
||||
throw ProfileFailure.message("The reviewed binary did not reach its verified C source stop.")
|
||||
}
|
||||
try saveStop(capture, info, point)
|
||||
return capture.machine
|
||||
}
|
||||
|
||||
static func inspection(runID: String, revision: Int, projectID: String, build: CMOCBuildArtifact,
|
||||
capture: VCCDebuggerSnapshot, info: DebugInfo, point: CMOCProjectSourceMap.Instruction,
|
||||
watches: [String], sharedPaths: Set<String>) throws -> MCPDebuggerInspection {
|
||||
guard sharedPaths.contains(point.sourcePath) else { throw ProfileFailure.message("path_not_shared") }
|
||||
let memory = capture.logicalMemory, available = capture.logicalMemoryAvailable
|
||||
let ranges: [Range<Int>] = try info.map.instructions.compactMap { instruction in
|
||||
let range = Int(instruction.address)..<(Int(instruction.address) + instruction.bytes.count)
|
||||
guard range.upperBound <= min(memory.count, available.count), available[range].allSatisfy({ $0 != 0 }),
|
||||
memory[range].elementsEqual(instruction.bytes) else { throw ProfileFailure.message("stale_run") }
|
||||
return sharedPaths.contains(instruction.sourcePath) ? range : nil
|
||||
}
|
||||
var rows: [[String: String]] = [], status = "C watch metadata is unavailable for this build."
|
||||
if let metadata = info.variables, let u = capture.registers["U"]?.uint16Value, let s = capture.registers["S"]?.uint16Value {
|
||||
status = "available"
|
||||
let frame = CMOCCallStack.capture(metadata: metadata, pc: point.address, u: u, s: s, memory: memory,
|
||||
available: available, maximumFrames: 1).frames.first
|
||||
let evaluator = CMOCWatchEvaluator(metadata: metadata, context: .init(pc: point.address, u: u, memory: memory, available: available),
|
||||
frameLocalsAvailable: frame?.localsInspectable == true)
|
||||
rows = watches.map { name in
|
||||
// Only a locally configured named variable can cross the grant. Arbitrary dereferences can name unrelated memory.
|
||||
guard name.range(of: #"^[A-Za-z_][A-Za-z_0-9]*$"#, options: .regularExpression) != nil else {
|
||||
return ["name": name, "unavailable": "Only named C variables are shared."]
|
||||
}
|
||||
let value = evaluator.evaluate(name)
|
||||
if let error = value.error { return ["name": name, "unavailable": error] }
|
||||
return ["name": name, "type": value.typeName, "value": value.value]
|
||||
}
|
||||
}
|
||||
return try MCPDebuggerInspection(runID: runID, capture: capture,
|
||||
scope: ["project_id": projectID, "revision": revision, "artifact_id": build.id.uuidString, "observation": "captured_source_stop"],
|
||||
sourceStop: ["path": point.sourcePath, "line": point.sourceLine, "address": Int(point.address), "instruction_bytes": point.bytes.map(Int.init)],
|
||||
watches: rows, watchStatus: status, ranges: ranges)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// A grant fixes the input names and build recipe at consent time. An ordinary
|
||||
/// project contributes C and headers only; its Make recipes and options never run.
|
||||
struct MCPCMOCProject: Equatable, Sendable {
|
||||
static let diskPaths = ["assets/words.txt", "include/hello.h", "main.c", "src/disk.c", "src/display.c"]
|
||||
static let diskControls = ["Makefile", "tools/build-data.pl", CMOCProject.configurationFilename]
|
||||
static let libraryHeaders = ["cmoc.h", "coco.h", "decbfile.h", "stdarg.h", "assert.h", "setjmp.h", "disk.h", "lores.h", "gimeterm.h"]
|
||||
let paths: [String]
|
||||
let entry: String
|
||||
let helloDisk: Bool
|
||||
let customMake: Bool
|
||||
let configuration: CMOCProjectConfiguration
|
||||
|
||||
init(project: CMOCProject, files: [String], customMake: Bool = false) throws {
|
||||
self.customMake = customMake
|
||||
configuration = try project.configuration.validated()
|
||||
let available = Set(files)
|
||||
helloDisk = !customMake && Set(Self.diskPaths + Self.diskControls).isSubset(of: available)
|
||||
if customMake {
|
||||
entry = project.configuration.entrySource
|
||||
paths = available.filter { CMOCProject.isEditable($0) }.sorted()
|
||||
guard paths.contains(entry), paths.contains(configuration.makefile), paths.count <= 1024,
|
||||
Set(paths.map { $0.lowercased() }).count == paths.count else {
|
||||
throw CMOCBuildError.message("unsupported_project_sources: choose a project with at most 1,024 distinct shared text files")
|
||||
}
|
||||
for path in paths { try CMOCProject.validateRelativePath(path) }
|
||||
} else if helloDisk {
|
||||
paths = Self.diskPaths
|
||||
entry = "main.c"
|
||||
} else {
|
||||
entry = project.configuration.entrySource
|
||||
paths = available.filter { $0.hasSuffix(".c") || $0.hasSuffix(".h") }.sorted()
|
||||
guard paths.contains(entry), entry.hasSuffix(".c"), paths.count <= 64,
|
||||
Set(paths.map { $0.lowercased() }).count == paths.count,
|
||||
paths.allSatisfy(Self.validPath) else { throw CMOCBuildError.message("unsupported_project_sources") }
|
||||
}
|
||||
}
|
||||
|
||||
private static func validPath(_ path: String) -> Bool {
|
||||
guard path.utf8.count <= 200, !path.hasPrefix("obj/"), !path.hasPrefix("generated/") else { return false }
|
||||
return path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { part in
|
||||
guard let first = part.first, first.isASCII, first.isLetter || first == "_" || first.isNumber else { return false }
|
||||
return part.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || "_.-".contains($0)) }
|
||||
}
|
||||
}
|
||||
|
||||
// Remove C comments before classifying directives. Quoted strings and
|
||||
// character literals stay intact; comments cannot hide a leading #include.
|
||||
private static let lexicalTokens = try! NSRegularExpression(pattern: ##"(?s)/\*.*?(?:\*/|\z)|//[^\r\n]*|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'"##)
|
||||
private static func uncomment(_ source: String) -> String {
|
||||
let text = source as NSString
|
||||
let result = NSMutableString(capacity: text.length)
|
||||
var start = 0
|
||||
for token in lexicalTokens.matches(in: source, range: NSRange(location: 0, length: text.length)) {
|
||||
let value = text.substring(with: token.range)
|
||||
guard value.hasPrefix("/") else { continue }
|
||||
result.append(text.substring(with: NSRange(location: start, length: token.range.location - start)))
|
||||
result.append(" " + String(value.filter { $0.isNewline }))
|
||||
start = NSMaxRange(token.range)
|
||||
}
|
||||
result.append(text.substring(from: start))
|
||||
return result as String
|
||||
}
|
||||
|
||||
func validate(_ source: String, path: String, trusted: Set<String>? = nil) throws {
|
||||
guard source.utf8.count <= (customMake ? CMOCProject.maximumSourceBytes : 65536), !source.utf8.contains(0) else {
|
||||
throw CMOCBuildError.message("file_too_large: " + path)
|
||||
}
|
||||
if customMake { return } // The user explicitly approved this project's Make recipe and compiler inputs.
|
||||
var rejectedLine = 1
|
||||
// Locate the first construct outside the restricted C-source mode.
|
||||
if let range = source.range(of: #"(?m)^.*(?:\basm\b|__asm|_Pragma|__has_include|_CMOC_CONCAT|%:|\?\?|##|#\s*(?:pragma|line|error|warning)).*$"#, options: .regularExpression) {
|
||||
rejectedLine = source[..<range.lowerBound].filter { $0 == "\n" }.count + 1
|
||||
}
|
||||
func rejection(_ line: Int) -> CMOCBuildError {
|
||||
.message("unsupported_source_directive: \(path):\(line): This construct is outside the restricted C connection. For your own Make project, select Use Project Makefile in Assistant Access.")
|
||||
}
|
||||
let denied = rejection(rejectedLine)
|
||||
guard !source.contains("%:"), !source.contains("??"), !source.contains("##"),
|
||||
source.utf8.allSatisfy({ $0 == 9 || $0 == 10 || $0 == 13 || $0 >= 32 }),
|
||||
source.range(of: #"\\[ \t]*(?:\r|\n|$)|\\[uU][0-9a-fA-F]"#, options: .regularExpression) == nil,
|
||||
source.range(of: #"\b(asm|__asm_?_?|_Pragma|__has_include(?:_next)?|_CMOC_CONCAT2?)\b"#, options: .regularExpression) == nil else { throw denied }
|
||||
if let trusted {
|
||||
guard source.components(separatedBy: .newlines).allSatisfy({ !$0.contains("#") || trusted.contains($0) }) else { throw denied }
|
||||
return
|
||||
}
|
||||
for (index, line) in Self.uncomment(source).components(separatedBy: .newlines).enumerated() {
|
||||
let denied = rejection(index + 1)
|
||||
let directive = line.trimmingCharacters(in: .whitespaces)
|
||||
guard directive.hasPrefix("#") else { continue }
|
||||
let body = directive.dropFirst().trimmingCharacters(in: .whitespaces)
|
||||
let nameEnd = body.firstIndex(where: { !$0.isLetter && $0 != "_" }) ?? body.endIndex
|
||||
let keyword = String(body[..<nameEnd])
|
||||
let arg = body[nameEnd...].trimmingCharacters(in: .whitespaces)
|
||||
switch keyword {
|
||||
case "ifndef", "ifdef", "undef":
|
||||
guard keyword != "undef" || !arg.hasPrefix("_") else { throw denied }
|
||||
guard arg.range(of: #"^[A-Za-z_]\w*$"#, options: .regularExpression) != nil else { throw denied }
|
||||
continue
|
||||
case "else", "endif":
|
||||
guard arg.isEmpty else { throw denied }
|
||||
continue
|
||||
case "define", "if", "elif":
|
||||
// Fixed includes below; no stringification, token concatenation,
|
||||
// injected directives or changes to compiler predefined macros.
|
||||
guard !arg.isEmpty, !arg.contains("#"), keyword != "define" || !arg.hasPrefix("_") else { throw denied }
|
||||
continue
|
||||
case "include": break
|
||||
default: throw denied
|
||||
}
|
||||
guard arg.count >= 3, let first = arg.first, let last = arg.last else { throw denied }
|
||||
let name = String(arg.dropFirst().dropLast())
|
||||
if first == "<", last == ">", Self.libraryHeaders.contains(name) { continue }
|
||||
let parent = (path as NSString).deletingLastPathComponent
|
||||
guard first == "\"", last == "\"", Self.validPath(name), name.hasSuffix(".h"),
|
||||
paths.contains(name) || paths.contains("include/" + name) || paths.contains(parent + "/" + name) else { throw denied }
|
||||
}
|
||||
}
|
||||
|
||||
func snapshotProject(at directory: URL, inputs: [String: String], buildInputs: [String: Data]? = nil,
|
||||
support: CMOCBuildSupportSnapshot? = nil, permissions: [String: Int] = [:],
|
||||
modificationDates: [String: Date] = [:], overlayPaths: Set<String> = []) throws -> CMOCProject {
|
||||
if customMake {
|
||||
guard var files = buildInputs else { throw CMOCBuildError.message("missing_project_source") }
|
||||
for (path, text) in inputs { files[path] = try CMOCProject.sourceBytes(text) }
|
||||
let fm = FileManager.default
|
||||
try fm.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
for (path, bytes) in files {
|
||||
try CMOCProject.validateRelativePath(path)
|
||||
let url = directory.appendingPathComponent(path)
|
||||
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try bytes.write(to: url, options: .withoutOverwriting)
|
||||
if let mode = permissions[path] { try fm.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) }
|
||||
if !overlayPaths.contains(path), let date = modificationDates[path] {
|
||||
try fm.setAttributes([.modificationDate: date], ofItemAtPath: url.path)
|
||||
}
|
||||
}
|
||||
for relative in configuration.buildSupportDirectories {
|
||||
try fm.createDirectory(at: directory.appendingPathComponent(relative).standardizedFileURL, withIntermediateDirectories: true)
|
||||
}
|
||||
if let support {
|
||||
for (path, bytes) in support.files {
|
||||
guard configuration.buildSupportDirectories.contains(where: { path.hasPrefix($0 + "/") }) else {
|
||||
throw CMOCBuildError.message("unapproved_build_support")
|
||||
}
|
||||
let url = directory.appendingPathComponent(path).standardizedFileURL
|
||||
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try bytes.write(to: url, options: .withoutOverwriting)
|
||||
if let mode = support.permissions[path] { try fm.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) }
|
||||
}
|
||||
}
|
||||
return try CMOCProject.open(at: directory)
|
||||
}
|
||||
if helloDisk { return try CMOCProject.createHelloDisk(at: directory) }
|
||||
var recipe = CMOCMakefileSettings()
|
||||
recipe.sources = paths.filter { $0.hasSuffix(".c") }
|
||||
recipe.compilerOptions = ["-I."] // Allow a nested source to include a shared header at the project root.
|
||||
recipe.includePaths = paths.contains(where: { $0.hasPrefix("include/") }) ? ["include"] : []
|
||||
var configuration = CMOCProjectConfiguration()
|
||||
configuration.entrySource = entry
|
||||
configuration.makefileSettings = recipe
|
||||
configuration.buildTarget = "build"
|
||||
let fm = FileManager.default
|
||||
try fm.createDirectory(at: directory, withIntermediateDirectories: false)
|
||||
for path in paths {
|
||||
guard let source = inputs[path] else { throw CMOCBuildError.message("missing_project_source") }
|
||||
let url = directory.appendingPathComponent(path)
|
||||
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try Data(source.utf8).write(to: url, options: .withoutOverwriting)
|
||||
}
|
||||
try Data(recipe.generateMakefile().utf8).write(to: directory.appendingPathComponent("Makefile"))
|
||||
try JSONEncoder().encode(configuration).write(to: directory.appendingPathComponent(CMOCProject.configurationFilename))
|
||||
return try CMOCProject.open(at: directory)
|
||||
}
|
||||
}
|
||||
|
||||
struct MCPCMOCEdit: Equatable {
|
||||
let path: String
|
||||
let before: String
|
||||
let after: String
|
||||
}
|
||||
|
||||
/// Frozen inputs for an explicitly approved Make build. Binary resources are
|
||||
/// build inputs but are not exposed as assistant-readable text.
|
||||
struct MCPCMOCMakeInputs: Equatable, Sendable {
|
||||
let makefile: String
|
||||
let files: [String: Data]
|
||||
let permissions: [String: Int]
|
||||
var modificationDates: [String: Date] = [:]
|
||||
var overlayPaths: Set<String> = []
|
||||
let support: CMOCBuildSupportSnapshot
|
||||
|
||||
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
// Modification times are Make scheduling hints, not source revisions.
|
||||
// Overlay membership can change on Save without changing any bytes.
|
||||
lhs.makefile == rhs.makefile && lhs.files == rhs.files && lhs.permissions == rhs.permissions && lhs.support == rhs.support
|
||||
}
|
||||
|
||||
var recipeID: String {
|
||||
let controls = files.filter { path, _ in
|
||||
let name = (path as NSString).lastPathComponent
|
||||
return path == makefile || (permissions[path] ?? 0) & 0o111 != 0
|
||||
|| ["Makefile", "makefile", "GNUmakefile", CMOCProject.configurationFilename].contains(name)
|
||||
|| ["mk", "pl", "py", "sh", "rb"].contains((path as NSString).pathExtension.lowercased())
|
||||
}.mapValues(CMOCProject.sha256)
|
||||
let rows = controls.merging(support.hashes) { first, _ in first }.sorted { $0.key < $1.key }
|
||||
return CMOCProject.sha256(Data(rows.map { "\($0.key):\($0.value):\(permissions[$0.key] ?? 0)" }.joined(separator: "\n").utf8))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
import Security
|
||||
import SwiftUI
|
||||
|
||||
/// Only the helper path and the grant filename go into the desktop client's configuration.
|
||||
struct MCPChatGPTConnection {
|
||||
let grantURL: URL
|
||||
let helper: URL
|
||||
let name: String
|
||||
|
||||
init(grantURL: URL, helper: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-mcp")) {
|
||||
self.grantURL = grantURL
|
||||
self.helper = helper
|
||||
// Per-file names let BASIC, C and assembly grants coexist. Re-exporting to the same path reuses the entry.
|
||||
let suffix = SHA256.hash(data: Data(grantURL.path.utf8)).prefix(6).map { String(format: "%02x", $0) }.joined()
|
||||
name = "vcc-plus-oss-" + suffix
|
||||
}
|
||||
|
||||
var arguments: [String] { ["--grant", grantURL.path] }
|
||||
|
||||
enum Registration { case missing, matches, disabled, conflict }
|
||||
|
||||
enum SetupError: LocalizedError {
|
||||
case manualSetup, installApp, grantUnavailable, cliFailed, timeout
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .manualSetup: return "Use the manual steps for this version of ChatGPT."
|
||||
case .installApp: return "Copy VCC Plus OSS into Applications and open that copy before adding it to ChatGPT."
|
||||
case .grantUnavailable: return "Save a new connection file in VCC Plus before connecting."
|
||||
case .cliFailed: return "ChatGPT could not confirm its MCP settings. Check the entry in Settings → MCP servers."
|
||||
case .timeout: return "ChatGPT took too long to respond. Check the entry in Settings → MCP servers."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func cli(in app: URL?) throws -> URL {
|
||||
guard let app else { throw SetupError.manualSetup }
|
||||
let cli = app.appendingPathComponent("Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex")
|
||||
var code: SecStaticCode?
|
||||
var requirement: SecRequirement?
|
||||
guard FileManager.default.isExecutableFile(atPath: cli.path),
|
||||
SecStaticCodeCreateWithPath(cli as CFURL, [], &code) == errSecSuccess, let code,
|
||||
SecRequirementCreateWithString(#"anchor apple generic and identifier "codex" and certificate leaf[subject.OU] = "2DC432GLL2""# as CFString, [], &requirement) == errSecSuccess,
|
||||
let requirement, SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess else { throw SetupError.manualSetup }
|
||||
return cli
|
||||
}
|
||||
|
||||
private func command(_ cli: URL, _ args: [String]) throws -> (Int32, Data) {
|
||||
let process = Process()
|
||||
let pipe = Pipe()
|
||||
process.executableURL = cli
|
||||
process.arguments = args
|
||||
// Resolve user-level ChatGPT settings, independent of any trusted project in the app launch directory.
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: "/", isDirectory: true)
|
||||
process.standardInput = FileHandle.nullDevice
|
||||
process.standardOutput = pipe
|
||||
process.standardError = pipe
|
||||
try process.run()
|
||||
let terminate = DispatchWorkItem { if process.isRunning { process.terminate() } }
|
||||
let forceStop = DispatchWorkItem { if process.isRunning { kill(process.processIdentifier, SIGKILL) } }
|
||||
DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: terminate)
|
||||
DispatchQueue.global().asyncAfter(deadline: .now() + 12, execute: forceStop)
|
||||
defer { terminate.cancel(); forceStop.cancel() }
|
||||
let output = pipe.fileHandleForReading.readDataToEndOfFile()
|
||||
process.waitUntilExit()
|
||||
guard process.terminationReason == .exit else { throw SetupError.timeout }
|
||||
return (process.terminationStatus, output)
|
||||
}
|
||||
|
||||
func registration(cli: URL) throws -> Registration {
|
||||
let (status, bytes) = try command(cli, ["mcp", "get", "--json", name])
|
||||
let lines = String(decoding: bytes, as: UTF8.self).components(separatedBy: .newlines)
|
||||
if status != 0 {
|
||||
guard lines.contains("Error: No MCP server named '\(name)' found.") else { throw SetupError.cliFailed }
|
||||
return .missing
|
||||
}
|
||||
// The CLI can emit a startup warning on stderr before printing its JSON record.
|
||||
guard let start = lines.firstIndex(where: { $0.first == "{" }),
|
||||
let entry = (try? JSONSerialization.jsonObject(with: Data(lines[start...].joined(separator: "\n").utf8))) as? [String: Any],
|
||||
entry["name"] as? String == name, let transport = entry["transport"] as? [String: Any] else { throw SetupError.cliFailed }
|
||||
guard transport["type"] as? String == "stdio", transport["command"] as? String == helper.path,
|
||||
transport["args"] as? [String] == arguments else { return .conflict }
|
||||
return entry["enabled"] as? Bool == true ? .matches : .disabled
|
||||
}
|
||||
|
||||
func configure(app: URL?, add: Bool) throws -> String {
|
||||
let cli = try Self.cli(in: app)
|
||||
guard FileManager.default.isReadableFile(atPath: grantURL.path) else { throw SetupError.grantUnavailable }
|
||||
let volume = try helper.resourceValues(forKeys: [.volumeIsReadOnlyKey])
|
||||
guard FileManager.default.isExecutableFile(atPath: helper.path),
|
||||
!(helper.path.hasPrefix("/Volumes/") && volume.volumeIsReadOnly == true), !helper.path.contains("/AppTranslocation/") else { throw SetupError.installApp }
|
||||
switch try registration(cli: cli) {
|
||||
case .matches: return "This connection is saved in ChatGPT. Restart ChatGPT if needed, then type /mcp to check the live connection."
|
||||
case .disabled: return "This connection is saved but disabled. Enable it in ChatGPT Settings → MCP servers."
|
||||
case .conflict: return "ChatGPT already uses this server name for another connection. Choose a different name in manual setup."
|
||||
case .missing:
|
||||
guard add else { return "This connection has not been added to ChatGPT yet." }
|
||||
}
|
||||
let (status, _) = try command(cli, ["mcp", "add", name, "--", helper.path] + arguments)
|
||||
guard status == 0, try registration(cli: cli) == .matches else { throw SetupError.cliFailed }
|
||||
return "Added to ChatGPT. In Settings → MCP servers, select Restart. Start a local chat and type /mcp to check the live connection."
|
||||
}
|
||||
}
|
||||
|
||||
/// The editable starter is a runtime resource also used by Book 12. Connection details are composed at
|
||||
/// copy time so an edited draft cannot retain a previous connection's grant path.
|
||||
struct MCPProjectSetupPrompt {
|
||||
static let resourcePath = "PROJECT_SETUP_PREAMBLE.txt"
|
||||
let starter: String
|
||||
var text: String
|
||||
|
||||
enum PromptError: LocalizedError {
|
||||
case unavailable, empty
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .unavailable: return "The project setup starter could not be read from this app’s runtime resources."
|
||||
case .empty: return "The project setup prompt is empty. Enter your instructions or reset to the starter."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(starter: String) throws {
|
||||
guard !starter.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw PromptError.empty }
|
||||
self.starter = starter
|
||||
text = starter
|
||||
}
|
||||
|
||||
static func load(runtimeTemplates: URL?) throws -> Self {
|
||||
guard let runtimeTemplates,
|
||||
let text = try? String(contentsOf: runtimeTemplates.appendingPathComponent(resourcePath), encoding: .utf8) else {
|
||||
throw PromptError.unavailable
|
||||
}
|
||||
return try Self(starter: text)
|
||||
}
|
||||
|
||||
var canCopy: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||||
|
||||
mutating func reset() { text = starter }
|
||||
|
||||
func connectionDetails(_ connection: MCPChatGPTConnection) throws -> String {
|
||||
// Encode paths as data, including any embedded whitespace or quotation marks.
|
||||
// Never open the grant file: its token and other contents stay on this Mac.
|
||||
let details: [String: Any] = ["name": connection.name, "command": connection.helper.path,
|
||||
"arguments": connection.arguments]
|
||||
let bytes = try JSONSerialization.data(withJSONObject: details, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
|
||||
return String(decoding: bytes, as: UTF8.self)
|
||||
}
|
||||
|
||||
func rendered(connection: MCPChatGPTConnection, firstPrompt: String) throws -> String {
|
||||
guard canCopy else { throw PromptError.empty }
|
||||
return """
|
||||
\(text.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
|
||||
VCC Plus connection details (configuration only; verify tool discovery and a successful request separately):
|
||||
\(try connectionDetails(connection))
|
||||
|
||||
First read-only check after discovering this connection’s tools:
|
||||
\(firstPrompt)
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
struct MCPChatGPTSetup: View {
|
||||
let grantURL: URL
|
||||
let firstPrompt: String
|
||||
@State private var message = ""
|
||||
@State private var working = false
|
||||
@State private var expanded = false
|
||||
@State private var projectPrompt: MCPProjectSetupPrompt?
|
||||
@State private var promptMessage = ""
|
||||
@State private var editingPrompt = false
|
||||
|
||||
private func configure(add: Bool) {
|
||||
guard !working else { return }
|
||||
let setup = MCPChatGPTConnection(grantURL: grantURL)
|
||||
let app = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.openai.codex")
|
||||
working = true
|
||||
Task { @MainActor in
|
||||
let result = await Task.detached(priority: .userInitiated) {
|
||||
do { return try setup.configure(app: app, add: add) }
|
||||
catch { return error.localizedDescription }
|
||||
}.value
|
||||
message = result
|
||||
working = false
|
||||
}
|
||||
}
|
||||
|
||||
private func copy(_ value: String) {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(value, forType: .string)
|
||||
}
|
||||
|
||||
private func copyProjectPrompt() {
|
||||
guard let projectPrompt else { return }
|
||||
do {
|
||||
let value = try projectPrompt.rendered(connection: MCPChatGPTConnection(grantURL: grantURL), firstPrompt: firstPrompt)
|
||||
copy(value)
|
||||
promptMessage = "Project setup prompt copied."
|
||||
} catch {
|
||||
promptMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor private func loadProjectPrompt() async {
|
||||
guard projectPrompt == nil else { return }
|
||||
let templates = Bundle.main.url(forResource: "RuntimeTemplates", withExtension: nil)
|
||||
let result = await Task.detached(priority: .userInitiated) {
|
||||
Result { try MCPProjectSetupPrompt.load(runtimeTemplates: templates) }
|
||||
}.value
|
||||
guard !Task.isCancelled, projectPrompt == nil else { return }
|
||||
switch result {
|
||||
case .success(let prompt): projectPrompt = prompt
|
||||
case .failure(let error): promptMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private var projectPromptEditor: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Project Setup Prompt").font(.title2)
|
||||
Text("Edit the starter for your project. It authorizes setup only within the permissions you exported. Copying does not change your connections.")
|
||||
.foregroundStyle(.secondary)
|
||||
TextEditor(text: Binding(get: { projectPrompt?.text ?? "" }, set: { projectPrompt?.text = $0; promptMessage = "" }))
|
||||
.font(.body.monospaced())
|
||||
.scrollContentBackground(.hidden)
|
||||
.padding(6)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 6))
|
||||
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary))
|
||||
.accessibilityLabel("Project setup instructions")
|
||||
.accessibilityIdentifier("mcp.projectSetup.instructions")
|
||||
Text("The current connection name, helper path and saved connection path are appended when you copy. Connection file contents are never included.")
|
||||
.font(.callout).foregroundStyle(.secondary)
|
||||
if let projectPrompt,
|
||||
let details = try? projectPrompt.connectionDetails(MCPChatGPTConnection(grantURL: grantURL)) {
|
||||
DisclosureGroup("Included connection details") {
|
||||
ScrollView {
|
||||
Text(details).font(.callout.monospaced()).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.frame(maxHeight: 100)
|
||||
}
|
||||
}
|
||||
if !promptMessage.isEmpty { Text(promptMessage).font(.callout).textSelection(.enabled) }
|
||||
HStack {
|
||||
Button("Reset to Starter") { projectPrompt?.reset(); promptMessage = "" }
|
||||
.accessibilityIdentifier("mcp.projectSetup.reset")
|
||||
Spacer()
|
||||
Button("Done") { editingPrompt = false }.keyboardShortcut(.cancelAction)
|
||||
Button("Copy Project Setup Prompt") { copyProjectPrompt() }
|
||||
.disabled(projectPrompt?.canCopy != true)
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.accessibilityIdentifier("mcp.projectSetup.editorCopy")
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(minWidth: 520, idealWidth: 640, minHeight: 400, idealHeight: 540)
|
||||
}
|
||||
|
||||
private func field(_ label: String, _ value: String) -> some View {
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
Text(label).frame(width: 85, alignment: .leading)
|
||||
Text(value).font(.callout.monospaced()).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||
Button { copy(value) } label: { Image(systemName: "doc.on.doc") }.accessibilityLabel("Copy " + label)
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
let setup = MCPChatGPTConnection(grantURL: grantURL)
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("ChatGPT for Mac").font(.headline)
|
||||
HStack {
|
||||
Button("Add to ChatGPT") { configure(add: true) }
|
||||
Button("Check Setup") { configure(add: false) }
|
||||
Button("Copy First Prompt") { copy(firstPrompt) }
|
||||
}.disabled(working)
|
||||
HStack {
|
||||
Button("Copy Project Setup Prompt") { copyProjectPrompt() }
|
||||
.disabled(projectPrompt?.canCopy != true)
|
||||
.accessibilityIdentifier("mcp.projectSetup.copy")
|
||||
Button("Edit…") { editingPrompt = true }
|
||||
.disabled(projectPrompt == nil)
|
||||
.accessibilityLabel("Edit project setup prompt")
|
||||
.accessibilityIdentifier("mcp.projectSetup.edit")
|
||||
}
|
||||
Text("An editable starter that authorizes setup within your exported permissions. Copying does not change your connections.")
|
||||
.font(.callout).foregroundStyle(.secondary)
|
||||
if !promptMessage.isEmpty { Text(promptMessage).font(.callout).textSelection(.enabled) }
|
||||
if working { ProgressView().controlSize(.small) }
|
||||
if !message.isEmpty { Text(message).font(.callout).textSelection(.enabled) }
|
||||
DisclosureGroup("Manual setup", isExpanded: $expanded) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("In ChatGPT Settings → MCP servers, choose Add server and select STDIO. Enter each argument separately.")
|
||||
field("Name", setup.name)
|
||||
field("Command", setup.helper.path)
|
||||
field("Argument 1", setup.arguments[0])
|
||||
field("Argument 2", setup.arguments[1])
|
||||
Text("Save, select Restart in ChatGPT, and type /mcp in a local chat. Paste the first prompt to try VCC Plus.")
|
||||
Link("ChatGPT MCP instructions", destination: URL(string: "https://learn.chatgpt.com/docs/extend/mcp")!)
|
||||
}.padding(.top, 4)
|
||||
}
|
||||
}
|
||||
.task { await loadProjectPrompt() }
|
||||
.sheet(isPresented: $editingPrompt) { projectPromptEditor }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Input receipts belong to one native launch and cannot be reused after its grant is retired.
|
||||
@MainActor
|
||||
final class MCPCompiledRunIO {
|
||||
private let machine: MachineModel
|
||||
private let runID: String
|
||||
private let expected: VCCMachineSnapshot
|
||||
private let assembly: Bool
|
||||
private let lease = VCCCompiledRunLease()
|
||||
private var accepted: [String: String] = [:]
|
||||
private var sending = false
|
||||
|
||||
init(machine: MachineModel, runID: String, expected: VCCMachineSnapshot, assembly: Bool) {
|
||||
self.machine = machine
|
||||
self.runID = runID
|
||||
self.expected = expected
|
||||
self.assembly = assembly
|
||||
}
|
||||
|
||||
func invalidate() {
|
||||
lease.invalidate()
|
||||
machine.cancelMCPInput(runID: runID)
|
||||
}
|
||||
|
||||
func finalScreenText() async throws -> String? {
|
||||
let result = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected,
|
||||
assembly: assembly, key: nil, readScreen: false, finalScreen: true)
|
||||
guard lease.isValid else { throw ProfileFailure.message("stale_run") }
|
||||
return result["text"] as? String
|
||||
}
|
||||
|
||||
func reply(_ tool: String, arguments: [String: Any]) async throws -> [String: Any] {
|
||||
guard lease.isValid, arguments["run_id"] as? String == runID else { throw ProfileFailure.message("stale_run") }
|
||||
if tool == "read_screen_text", arguments.count == 1 {
|
||||
let result = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected,
|
||||
assembly: assembly, key: nil, readScreen: true)
|
||||
guard lease.isValid else { throw ProfileFailure.message("stale_run") }
|
||||
return result
|
||||
}
|
||||
guard tool == "send_keys", arguments.count == 3,
|
||||
let request = arguments["request_id"] as? String, (1...64).contains(request.utf8.count),
|
||||
let keys = arguments["keys"] as? String, MCPGuestKey.accepts(keys),
|
||||
let chord = CocoKeyboard.chord(for: keys) else { throw ProfileFailure.message("invalid_arguments") }
|
||||
let prior = accepted[request]
|
||||
if let prior, prior != keys { throw ProfileFailure.message("request_conflict") }
|
||||
guard !sending else { throw ProfileFailure.message("input_busy") }
|
||||
guard prior != nil || accepted.count < MCPGuestKey.limit else { throw ProfileFailure.message("input_limit_reached") }
|
||||
sending = true
|
||||
defer { sending = false }
|
||||
// Revalidate even cached receipts. Only the first accepted request submits a chord.
|
||||
_ = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected, assembly: assembly,
|
||||
key: prior == nil ? NSNumber(value: chord) : nil, readScreen: false)
|
||||
guard lease.isValid else { throw ProfileFailure.message("stale_run") }
|
||||
accepted[request] = keys
|
||||
return ["run_id": runID, "request_id": request, "accepted": true]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// One immutable observation of an explicitly shared program. Only the permitted
|
||||
/// ranges are retained. Memory requests never perform another guest bus read.
|
||||
struct MCPDebuggerInspection {
|
||||
let runID: String
|
||||
let id = UUID().uuidString
|
||||
let machine: VCCMachineSnapshot
|
||||
private let memory: [(range: Range<Int>, bytes: Data)]
|
||||
let fields: [String: Any]
|
||||
|
||||
init(runID: String, capture: VCCDebuggerSnapshot, scope: [String: Any],
|
||||
sourceStop: [String: Any]?, watches: [[String: String]], watchStatus: String,
|
||||
ranges: [Range<Int>]) throws {
|
||||
let state = capture.machine
|
||||
guard state.state == .paused, state.assistantDeviceBlockers.isEmpty else {
|
||||
throw ProfileFailure.message("pause_required")
|
||||
}
|
||||
self.runID = runID
|
||||
machine = state
|
||||
let data = capture.logicalMemory, available = capture.logicalMemoryAvailable
|
||||
var permitted = IndexSet()
|
||||
for range in ranges where range.lowerBound >= 0 && range.upperBound <= min(0xff00, data.count, available.count) {
|
||||
permitted.insert(integersIn: range)
|
||||
}
|
||||
for address in Array(permitted) where available[address] == 0 { permitted.remove(address) }
|
||||
memory = permitted.rangeView.map { ($0, data.subdata(in: $0)) }
|
||||
var fields = scope
|
||||
fields["run_id"] = runID
|
||||
fields["snapshot_id"] = id
|
||||
fields["status"] = "paused"
|
||||
fields["processor"] = state.use6309 ? "HD6309" : "MC6809"
|
||||
fields["registers"] = capture.registers.reduce(into: [String: Int]()) { $0[$1.key.lowercased()] = $1.value.intValue }
|
||||
fields["source_stop"] = sourceStop as Any? ?? NSNull()
|
||||
fields["watches"] = watches
|
||||
fields["watch_status"] = watchStatus
|
||||
fields["memory_ranges"] = memory.map { ["address": $0.range.lowerBound, "count": $0.range.count] }
|
||||
self.fields = fields
|
||||
}
|
||||
|
||||
static func sameProgram(_ state: VCCMachineSnapshot, _ expected: VCCMachineSnapshot) -> Bool {
|
||||
state.assistantDeviceBlockers.isEmpty && state.generation == expected.generation &&
|
||||
state.debuggerProgramRevision == expected.debuggerProgramRevision &&
|
||||
state.debuggerMappingFingerprint == expected.debuggerMappingFingerprint && state.use6309 == expected.use6309
|
||||
}
|
||||
|
||||
func reply(tool: String, arguments: [String: Any]) throws -> [String: Any] {
|
||||
guard arguments["run_id"] as? String == runID else { throw ProfileFailure.message("stale_run") }
|
||||
if tool == "get_debug_snapshot", arguments.count == 1 { return fields }
|
||||
guard tool == "read_debug_memory", arguments.count == 4,
|
||||
let requested = arguments["snapshot_id"] as? String, let address = Self.integer(arguments["address"]),
|
||||
let count = Self.integer(arguments["count"]), (0...65535).contains(address), (1...256).contains(count),
|
||||
address + count <= 65536 else { throw ProfileFailure.message("invalid_arguments") }
|
||||
guard requested == id else { throw ProfileFailure.message("stale_snapshot") }
|
||||
guard let block = memory.first(where: { $0.range.contains(address) && address + count <= $0.range.upperBound }) else {
|
||||
throw ProfileFailure.message("memory_unavailable")
|
||||
}
|
||||
let offset = address - block.range.lowerBound
|
||||
return ["run_id": runID, "snapshot_id": id, "address": address, "count": count,
|
||||
"bytes": block.bytes[offset..<(offset + count)].map(Int.init)]
|
||||
}
|
||||
|
||||
private static func integer(_ value: Any?) -> Int? {
|
||||
guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
||||
!["f", "d"].contains(String(cString: number.objCType)) else { return nil }
|
||||
return Int(exactly: number)
|
||||
}
|
||||
|
||||
@MainActor static func capture(_ machine: MachineModel) async throws -> VCCDebuggerSnapshot {
|
||||
let snapshot: VCCDebuggerSnapshot? = await withCheckedContinuation { continuation in
|
||||
machine.readDebugger(address: 0, followPC: true, memoryAddress: 0) { continuation.resume(returning: $0) }
|
||||
}
|
||||
guard let snapshot else { throw ProfileFailure.message("debugger_busy") }
|
||||
return snapshot
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
// Decode the installed reader's generated JSON payload as data, never executable JavaScript.
|
||||
actor MCPHelpIndex {
|
||||
static let shared = MCPHelpIndex()
|
||||
struct Topic {
|
||||
let id, title, text: String
|
||||
}
|
||||
private struct Book: Decodable {
|
||||
struct Chapter: Decodable {
|
||||
struct Section: Decodable { let id, title: String; let passages: [String] }
|
||||
let page: String
|
||||
let sections: [Section]
|
||||
}
|
||||
let directory: String
|
||||
let chapters: [Chapter]
|
||||
}
|
||||
private let root: URL?
|
||||
private var cached: [Topic]?
|
||||
|
||||
init(root: URL? = Bundle.main.url(forResource: "ManualLibrary", withExtension: nil)) {
|
||||
self.root = root
|
||||
}
|
||||
|
||||
private func topics() throws -> [Topic] {
|
||||
if let cached { return cached }
|
||||
guard let root else { throw CocoaError(.fileNoSuchFile) }
|
||||
let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
|
||||
let books = [root.appendingPathComponent("book-index.js")] + contents.map { $0.appendingPathComponent("book-index.js") }.filter { FileManager.default.fileExists(atPath: $0.path) }
|
||||
var topics: [Topic] = []
|
||||
for file in books {
|
||||
let index = try String(contentsOf: file, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let prefix = "(globalThis.manualBooks ??= []).push("
|
||||
guard index.hasPrefix(prefix), index.hasSuffix(");") else { throw CocoaError(.fileReadCorruptFile) }
|
||||
let payload = index.dropFirst(prefix.count).dropLast(2)
|
||||
let book = try JSONDecoder().decode(Book.self, from: Data(payload.utf8))
|
||||
for chapter in book.chapters {
|
||||
for section in chapter.sections {
|
||||
topics.append(Topic(id: "\(book.directory)/\(chapter.page)#\(section.id)",
|
||||
title: section.title, text: section.passages.joined(separator: "\n\n")))
|
||||
}
|
||||
}
|
||||
}
|
||||
cached = topics.sorted { $0.id < $1.id }
|
||||
return cached!
|
||||
}
|
||||
|
||||
func search(_ query: String) throws -> [Topic] {
|
||||
let words = query.lowercased().split(whereSeparator: \.isWhitespace).map(String.init)
|
||||
guard !words.isEmpty else { return [] }
|
||||
return try topics().compactMap { t -> (Int, Topic)? in
|
||||
let title = t.title.lowercased(), body = t.text.lowercased()
|
||||
guard words.allSatisfy({ title.contains($0) || body.contains($0) }) else { return nil }
|
||||
return (words.filter { title.contains($0) }.count + (title == query.lowercased() ? 10 : 0), t)
|
||||
}.sorted { lhs, rhs in
|
||||
lhs.0 == rhs.0 ? lhs.1.id < rhs.1.id : lhs.0 > rhs.0
|
||||
}.prefix(8).map { $0.1 }
|
||||
}
|
||||
func read(_ id: String) throws -> Topic? { try topics().first { $0.id == id } }
|
||||
|
||||
@MainActor
|
||||
static func toolResult(_ name: String, arguments args: [String: Any]) async -> [String: Any] {
|
||||
do {
|
||||
switch name {
|
||||
case "search_help":
|
||||
guard args.count == 1, let query = args["query"] as? String, (1...160).contains(query.utf8.count),
|
||||
!query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return ["error": "invalid_arguments"] }
|
||||
let topics = try await shared.search(query)
|
||||
return ["result": ["hits": topics.map { ["topic_id": $0.id, "title": $0.title, "excerpt": String($0.text.prefix(240))] }]]
|
||||
case "read_topic":
|
||||
guard args.count == 1, let id = args["topic_id"] as? String, (1...512).contains(id.utf8.count)
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
guard let topic = try await shared.read(id) else { return ["error": "not_found"] }
|
||||
var text = String(decoding: topic.text.utf8.prefix(12 * 1024), as: UTF8.self)
|
||||
while text.utf8.count > 12 * 1024 { text.removeLast() }
|
||||
return ["result": ["topic_id": id, "title": topic.title, "text": text, "truncated": text != topic.text]]
|
||||
default: return ["error": "invalid_arguments"]
|
||||
}
|
||||
} catch { return ["error": "manual_unavailable"] }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
/// Read-only observations of the shared development setup; host paths and guest contents stay private.
|
||||
enum MCPMachineStatus {
|
||||
enum Workspace { case basic, cmoc(needsFloppy: Bool), assembly(needs6309: Bool) }
|
||||
static let occupiedBASICGuidance = "A program is in CoCo BASIC memory. In BASIC Development, save any open draft, choose Read from CoCo, then Save As… to keep the guest listing. When you are ready to clear its program and variables, type NEW at the CoCo’s OK prompt and retry the C run."
|
||||
|
||||
static func missingToolBlockers(in toolchain: URL, requiring names: [String]) async -> [String] {
|
||||
await Task.detached {
|
||||
let bin = toolchain.appendingPathComponent("bin")
|
||||
return names.filter { !FileManager.default.isExecutableFile(atPath: bin.appendingPathComponent($0).path) }
|
||||
.map { "Install the bundled development tool " + $0 + "." }
|
||||
}.value
|
||||
}
|
||||
|
||||
static func result(_ machine: VCCMachineSnapshot, workspace: Workspace,
|
||||
buildBlockers: [String]?, runBlockers: [String],
|
||||
lastBuild: [String: Any]? = nil, profile: SystemProfile? = nil, input: [String: Any]? = nil) -> [String: Any] {
|
||||
var reasons = runBlockers + machine.assistantDeviceBlockers
|
||||
let state: String
|
||||
switch machine.state {
|
||||
case .running: state = "running"
|
||||
case .paused: state = "paused"
|
||||
case .empty: state = "empty"
|
||||
case .closed: state = "closed"
|
||||
@unknown default: state = "unknown"
|
||||
}
|
||||
if machine.state != .running && machine.state != .paused {
|
||||
reasons.append("Start the CoCo before running the shared program.")
|
||||
}
|
||||
switch workspace {
|
||||
case .assembly(let needs6309):
|
||||
if needs6309 && !machine.use6309 { reasons.append("Use an HD6309 guest or assemble for MC6809.") }
|
||||
case .cmoc(let needsFloppy):
|
||||
if needsFloppy && machine.disks.first?.mounted != false { reasons.append("Use an empty floppy drive 0 before starting Hello Disk.") }
|
||||
if machine.basicDebugAttached || (machine.debuggerDevelopmentAttached && !machine.assistantCompiledReturned) || machine.debuggerAssemblyAttached || machine.pasteRemaining > 0 {
|
||||
reasons.append("Finish the active debugging or paste session.")
|
||||
}
|
||||
if machine.assistantEmptyBASIC?.boolValue == false { reasons.append(occupiedBASICGuidance) }
|
||||
fallthrough
|
||||
case .basic:
|
||||
if machine.assistantDirectPrompt?.boolValue != true {
|
||||
reasons.append(machine.assistantDirectPrompt == nil ? "Use a supported BASIC system and memory map." : "Wait at the BASIC OK prompt.")
|
||||
}
|
||||
}
|
||||
func drives(_ disks: [VCCDiskSnapshot]) -> [[String: Any]] {
|
||||
disks.enumerated().map { index, disk in
|
||||
["drive": index, "mounted": disk.mounted, "write_protected": disk.writeProtected]
|
||||
}
|
||||
}
|
||||
var build: [String: Any] = ["applicable": false]
|
||||
if let buildBlockers {
|
||||
build = ["applicable": true, "available": buildBlockers.isEmpty, "blockers": buildBlockers]
|
||||
if let lastBuild {
|
||||
build["last_build"] = lastBuild.filter { ["build_id", "revision", "status"].contains($0.key) }
|
||||
}
|
||||
}
|
||||
var result: [String: Any] = [
|
||||
"processor": machine.use6309 ? "HD6309" : "MC6809", "state": state,
|
||||
"system_profile": (profile?.name as Any?) ?? NSNull(),
|
||||
"video_output": DisplayOutput(rawValue: machine.videoOutput)?.label ?? "unknown",
|
||||
"memory": MachineSettings.memoryLabels.indices.contains(Int(machine.ramConfiguration))
|
||||
? MachineSettings.memoryLabels[Int(machine.ramConfiguration)] : "unknown",
|
||||
"floppy_drives": drives(machine.disks), "hard_drives": drives(machine.hardDisks),
|
||||
"cassette_mounted": machine.tapeMounted, "cassette_recording": machine.tapeMode == 2,
|
||||
"drivewire_enabled": machine.driveWireEnabled,
|
||||
"basic_direct_prompt": (machine.assistantDirectPrompt as Any?) ?? NSNull(),
|
||||
"basic_program_loaded": (machine.assistantEmptyBASIC.map { !$0.boolValue } as Any?) ?? NSNull(),
|
||||
"build": build,
|
||||
"run": ["blockers": reasons, "ready_for_native_run": reasons.isEmpty] as [String: Any]
|
||||
]
|
||||
if let input { result["input"] = input }
|
||||
return result
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,137 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
/// One request per connection. Peers cannot hold the main thread or the emulator queue.
|
||||
final class MCPTransport {
|
||||
typealias Handler = @Sendable (Data) async -> Data
|
||||
let unixPath: String
|
||||
let port: UInt16
|
||||
private let directory: URL
|
||||
private let queue = DispatchQueue(label: "vcc.mcp.accept")
|
||||
private let slots = DispatchSemaphore(value: 8)
|
||||
private var listeners: [DispatchSourceRead] = []
|
||||
|
||||
private static func checked(_ rc: Int32) throws -> Int32 {
|
||||
guard rc >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
||||
return rc
|
||||
}
|
||||
|
||||
init(handler: @escaping Handler) throws {
|
||||
directory = URL(fileURLWithPath: "/private/tmp/vcc-mcp-" + UUID().uuidString)
|
||||
unixPath = directory.appendingPathComponent("host.sock").path
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
var sockets: [Int32] = []
|
||||
do {
|
||||
let uds = try Self.checked(socket(AF_UNIX, SOCK_STREAM, 0))
|
||||
sockets.append(uds)
|
||||
var un = sockaddr_un()
|
||||
un.sun_family = sa_family_t(AF_UNIX)
|
||||
let path = Array(unixPath.utf8CString)
|
||||
guard path.count <= MemoryLayout.size(ofValue: un.sun_path) else { throw POSIXError(.ENAMETOOLONG) }
|
||||
withUnsafeMutableBytes(of: &un.sun_path) { dest in
|
||||
path.withUnsafeBytes { dest.copyBytes(from: $0) }
|
||||
}
|
||||
un.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
|
||||
try Self.bindSocket(uds, &un)
|
||||
let tcp = try Self.checked(socket(AF_INET, SOCK_STREAM, 0))
|
||||
sockets.append(tcp)
|
||||
var addr = sockaddr_in()
|
||||
addr.sin_family = sa_family_t(AF_INET)
|
||||
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
||||
addr.sin_addr.s_addr = inet_addr("127.0.0.1")
|
||||
try Self.bindSocket(tcp, &addr)
|
||||
var size = socklen_t(MemoryLayout<sockaddr_in>.size)
|
||||
_ = try Self.checked(withUnsafeMutablePointer(to: &addr) {
|
||||
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(tcp, $0, &size) }
|
||||
})
|
||||
port = UInt16(bigEndian: addr.sin_port)
|
||||
for fd in sockets {
|
||||
_ = try Self.checked(fcntl(fd, F_SETFL, O_NONBLOCK))
|
||||
_ = try Self.checked(fcntl(fd, F_SETFD, FD_CLOEXEC))
|
||||
_ = try Self.checked(listen(fd, 8))
|
||||
}
|
||||
for fd in sockets {
|
||||
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue)
|
||||
source.setEventHandler { [slots] in
|
||||
let peer = accept(fd, nil, nil)
|
||||
guard peer >= 0 else { return }
|
||||
guard slots.wait(timeout: .now()) == .success else { close(peer); return }
|
||||
// Spawn a bounded worker; synchronous socket IO never runs on Swift's executor.
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
func finish() { close(peer); slots.signal() }
|
||||
if fd == uds {
|
||||
var uid: uid_t = 0, gid: gid_t = 0
|
||||
guard getpeereid(peer, &uid, &gid) == 0, uid == geteuid() else { finish(); return }
|
||||
}
|
||||
var yes: Int32 = 1
|
||||
var timeout = timeval(tv_sec: 3, tv_usec: 0)
|
||||
guard fcntl(peer, F_SETFD, FD_CLOEXEC) == 0, fcntl(peer, F_SETFL, 0) == 0,
|
||||
setsockopt(peer, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout.size(ofValue: yes))) == 0,
|
||||
setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0,
|
||||
setsockopt(peer, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) == 0,
|
||||
let request = Self.readLine(peer) else { finish(); return }
|
||||
Task {
|
||||
let response = await handler(request)
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
Self.writeResponse(response, to: peer)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
source.setCancelHandler { close(fd) }
|
||||
listeners.append(source)
|
||||
source.resume()
|
||||
}
|
||||
} catch {
|
||||
for fd in sockets { close(fd) }
|
||||
try? FileManager.default.removeItem(at: directory)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private static func bindSocket<T>(_ fd: Int32, _ addr: inout T) throws {
|
||||
_ = try checked(withUnsafePointer(to: &addr) {
|
||||
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout<T>.size)) }
|
||||
})
|
||||
}
|
||||
|
||||
private static func readLine(_ fd: Int32) -> Data? {
|
||||
let deadline = DispatchTime.now() + .seconds(5)
|
||||
let limit = 48 * 1024
|
||||
var data = Data(), buffer = [UInt8](repeating: 0, count: 1024)
|
||||
while data.count < limit && DispatchTime.now() < deadline {
|
||||
let size = recv(fd, &buffer, min(limit - data.count, buffer.count), 0)
|
||||
guard size > 0 else { return nil }
|
||||
let bytes = buffer.prefix(size)
|
||||
if let lf = bytes.firstIndex(of: 10) {
|
||||
data.append(contentsOf: bytes[..<lf])
|
||||
return data
|
||||
}
|
||||
data.append(contentsOf: bytes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func writeResponse(_ data: Data, to fd: Int32) {
|
||||
let deadline = DispatchTime.now() + .seconds(5)
|
||||
(data + Data([10])).withUnsafeBytes { bytes in
|
||||
guard let base = bytes.baseAddress else { return }
|
||||
var offset = 0
|
||||
while offset < bytes.count && DispatchTime.now() < deadline {
|
||||
let n = send(fd, base + offset, bytes.count - offset, 0)
|
||||
guard n > 0 else { return }
|
||||
offset += n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stop() {
|
||||
for listener in listeners { listener.cancel() }
|
||||
listeners.removeAll()
|
||||
try? FileManager.default.removeItem(at: directory)
|
||||
}
|
||||
deinit { stop() }
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import Combine
|
||||
|
||||
extension MachineModel {
|
||||
var executionDescription: String {
|
||||
state == .running ? (settings.fastForward ? "Fast-forward · Sound silenced" : "Running") : state == .paused ? "Paused" : state == .closed ? "Stopped" : "Ready"
|
||||
}
|
||||
var tapeTransportDescription: String {
|
||||
if tapeMode == 2 { return tapeMotor ? "Recording — export to save" : "Recording ready — waiting for the computer" }
|
||||
if tapeMode == 1 { return tapeMotor ? "Playing" : "Ready — waiting for the computer" }
|
||||
return tapeMounted ? "Tape stopped" : "No tape inserted"
|
||||
}
|
||||
var needsMediaAttention: Bool {
|
||||
mediaNeedsManualSave || !cartridgeRestoreErrors.isEmpty || !diskRestoreErrors.isEmpty || !diskSaveErrors.isEmpty ||
|
||||
!hardRestoreErrors.isEmpty || !hardSaveErrors.isEmpty || diskSettingsError != nil
|
||||
}
|
||||
func requestColdReset() {
|
||||
let alert = NSAlert(); alert.messageText = "Cold restart the CoCo?"
|
||||
alert.informativeText = "This clears RAM and your working program. Mounted media and their changes are retained."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Cold Restart")
|
||||
if alert.runModal() == .alertSecondButtonReturn { reset() }
|
||||
}
|
||||
func requestOrchestraWithoutROM(_ slot: Int) {
|
||||
guard !busy, !diskSaving, (0..<5).contains(slot) else { return }
|
||||
let alert = NSAlert(); alert.messageText = "Remove the Orchestra-90 ROM and restart?"
|
||||
alert.informativeText = "This clears the working program in RAM. Orchestra-90 stays connected for stereo playback by supporting software. The ROM file and mounted disks are kept."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Remove ROM and Restart")
|
||||
if alert.runModal() == .alertSecondButtonReturn { assignCartridge(.orchestra90, slot: slot, useBundledROM: false) }
|
||||
}
|
||||
func requestCartridge(_ kind: CartridgeAssignments.Kind, slot: Int) {
|
||||
let old = cartridgeAssignments.slots[slot]
|
||||
guard old.kind != kind else { return }
|
||||
let alert = NSAlert(); alert.messageText = "Change \(slot == 0 ? "the cartridge" : "slot \(slot)") and restart?"
|
||||
alert.informativeText = "This clears the working program in RAM. \(old.kind == .empty ? "" : "The current slot assignment will be replaced. ")A controller already in another Multi-Pak slot moves here. Mounted disks and their changes are retained."
|
||||
if old.kind == .ramDisk {
|
||||
alert.informativeText += " RAM disk data is volatile and is lost when its last assignment is removed."
|
||||
}
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Change and Restart")
|
||||
if alert.runModal() == .alertSecondButtonReturn { assignCartridge(kind, slot: slot) }
|
||||
}
|
||||
}
|
||||
|
||||
struct MachineView: View {
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@ObservedObject var machine: MachineModel
|
||||
@ObservedObject var presentation: PresentationSettings
|
||||
let showManualHome: () -> Void
|
||||
@State private var help = false
|
||||
@FocusState private var controlsFocused: Bool
|
||||
private let refresh = Timer.publish(every: 1.0 / 30, on: .main, in: .common).autoconnect()
|
||||
private var system: Bool { presentation.mode == .system && !machine.hardware.custom }
|
||||
var body: some View {
|
||||
VStack(spacing: 12) {
|
||||
HStack {
|
||||
Button { openWindow(id: "machine-settings") } label: {
|
||||
HardwareBadge(name: "coco-" + HardwareState.ramKeys[machine.settings.ram], label: "Color Computer 3, \(MachineSettings.memoryLabels[machine.settings.ram])")
|
||||
.frame(maxWidth: 440, maxHeight: 42)
|
||||
}.buttonStyle(.plain).help("Open Machine Settings for processor and memory")
|
||||
Spacer(minLength: 24)
|
||||
Button { openWindow(id: "machine-settings") } label: {
|
||||
HardwareBadge(name: machine.use6309 ? "hitachi" : "motorola", label: machine.use6309 ? "Hitachi 6309" : "Motorola 6809").frame(width: 44, height: 44)
|
||||
}.buttonStyle(.plain).help("Open Machine Settings for processor and memory")
|
||||
}
|
||||
Divider()
|
||||
toolbar
|
||||
if presentation.mode == .system && machine.hardware.custom {
|
||||
HStack {
|
||||
Label("Custom configuration", systemImage: "info.circle").fontWeight(.medium)
|
||||
Text("This hardware layout uses conventional controls; your setup is unchanged.").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Button("Cartridges…") { openWindow(id: "cartridges") }
|
||||
}.font(.callout)
|
||||
}
|
||||
MachineStage(machine: machine, presentation: presentation, system: system) {
|
||||
showManualHome()
|
||||
openWindow(id: "manual-library")
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(system ? Color(red: 0.945, green: 0.933, blue: 0.904) : Color(red: 0.10, green: 0.14, blue: 0.12))
|
||||
.clipShape(RoundedRectangle(cornerRadius: 8))
|
||||
.modifier(MediaDropTarget(machine: machine))
|
||||
status
|
||||
if let error = machine.displayError ?? machine.fileError ?? machine.error ?? machine.profileError {
|
||||
Text(error).foregroundStyle(.red).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.lineLimit(3).help(error)
|
||||
}
|
||||
if machine.needsMediaAttention {
|
||||
HStack {
|
||||
Label(machine.tapeDirty || machine.tapeMode == 2 ? "Tape recording needs export" : "Media needs attention", systemImage: "exclamationmark.circle")
|
||||
.foregroundStyle(.orange)
|
||||
Button("Cassette…") { openWindow(id: "cassette") }
|
||||
Button("Floppies…") { openWindow(id: "disks") }
|
||||
Button("Hard Disks…") { openWindow(id: "hard-disks") }
|
||||
Button("Cartridges…") { openWindow(id: "cartridges") }
|
||||
Spacer()
|
||||
}.font(.callout)
|
||||
}
|
||||
}.padding(20).frame(minWidth: 940, minHeight: 590)
|
||||
.task(id: machine.guideRequest) {
|
||||
guard let request = machine.guideRequest,
|
||||
presentation.shouldIntroduce(request.profile) else { return }
|
||||
// Bring the existing emulator forward after a successful profile load.
|
||||
// Allow its window and popover anchor to attach before presenting help.
|
||||
openWindow(id: "machine")
|
||||
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
|
||||
guard !machine.busy, machine.guideRequest == request,
|
||||
machine.usageProfile == request.profile else { return }
|
||||
help = true
|
||||
}
|
||||
.onChange(of: presentation.controlsFocusRequest) { _, _ in controlsFocused = true }
|
||||
.background(MacShellPermissionPresenter(machine: machine).frame(width: 0, height: 0).accessibilityHidden(true))
|
||||
.onReceive(refresh) { _ in machine.poll() }
|
||||
.onReceive(NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.willSleepNotification)) { _ in machine.pause() }
|
||||
// Changing presentation never invokes pause, reset, reload or a media command.
|
||||
}
|
||||
private var toolbar: some View {
|
||||
HStack(spacing: 10) {
|
||||
Button { openWindow(id: "profiles") } label: {
|
||||
Label(machine.profileName.map { $0 + (machine.profileModified ? " • Modified" : "") } ?? "Profiles", systemImage: "circle.grid.2x2")
|
||||
.lineLimit(1).frame(maxWidth: 170, alignment: .leading)
|
||||
}.focusable().focused($controlsFocused).accessibilityIdentifier("profiles-button")
|
||||
.onKeyPress(.space) { openWindow(id: "profiles"); return .handled }
|
||||
.help("Review and load saved setups. A profile saves settings, not the running program.")
|
||||
Button {
|
||||
if machine.state == .running { machine.pause() } else { machine.resume() }
|
||||
} label: { Label(machine.state == .running ? "Pause" : "Run", systemImage: machine.state == .running ? "pause.fill" : "play.fill") }
|
||||
.buttonStyle(.borderedProminent).disabled(machine.busy || machine.diskEditorLocked || machine.state == .empty || machine.state == .closed)
|
||||
.accessibilityIdentifier("execution")
|
||||
MachineRestartMenu(machine: machine).equatable()
|
||||
MediaActionsMenu()
|
||||
MachineSettingsMenu(machine: machine).equatable()
|
||||
Spacer(minLength: 0)
|
||||
Picker("Presentation", selection: $presentation.mode) {
|
||||
Label("Display", systemImage: "display").tag(PresentationSettings.Mode.display)
|
||||
Label("System", systemImage: "shippingbox").tag(PresentationSettings.Mode.system)
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(width: 194).accessibilityIdentifier("presentation")
|
||||
.help("Change the presentation without changing the running machine")
|
||||
}.controlSize(.large)
|
||||
}
|
||||
private var status: some View {
|
||||
HStack(spacing: 12) {
|
||||
if machine.pasteRemaining > 0 {
|
||||
Button("Cancel Paste (\(machine.pasteRemaining) left)") { machine.cancelPaste() }
|
||||
.monospacedDigit().frame(width: 210, alignment: .leading)
|
||||
.help("Stop typing. Text already entered in the CoCo is retained.")
|
||||
}
|
||||
Label(machine.executionDescription, systemImage: machine.state == .running ? "play.circle.fill" : "pause.circle")
|
||||
.foregroundStyle(.secondary).fixedSize()
|
||||
Divider().frame(height: 18)
|
||||
ScrollView(.horizontal) {
|
||||
HStack(spacing: 16) {
|
||||
ForEach(Array(machine.disks.enumerated()), id: \.offset) { i, disk in
|
||||
if disk.mounted { Button("FD\(i) \(disk.name)") { openWindow(id: "disks") }.help(disk.name) }
|
||||
}
|
||||
ForEach(Array(machine.hardDisks.enumerated()), id: \.offset) { i, disk in
|
||||
if disk.mounted { Button("HD\(i) \(disk.name)") { openWindow(id: "hard-disks") }.help(disk.name) }
|
||||
}
|
||||
if machine.tapeMounted {
|
||||
Button("Tape \(machine.tapeName)\(machine.tapeDirty || machine.tapeMode == 2 ? " — Unsaved" : "")") { openWindow(id: "cassette") }
|
||||
.help(machine.tapeTransportDescription)
|
||||
}
|
||||
}.buttonStyle(.link).lineLimit(1)
|
||||
}.scrollIndicators(.hidden)
|
||||
if system {
|
||||
Button { presentation.expanded.toggle() } label: {
|
||||
Label(presentation.expanded ? "Return to system" : "Expand monitor", systemImage: presentation.expanded ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right")
|
||||
}.accessibilityIdentifier("expand-monitor").fixedSize()
|
||||
}
|
||||
Button { help.toggle() } label: { Image(systemName: "info.circle") }.help("Show the guide for this CoCo setup").accessibilityLabel("Using the CoCo")
|
||||
.popover(isPresented: $help) {
|
||||
CoCoUsageHelp(profile: machine.usageProfile,
|
||||
floppyMounted: machine.disks.contains { $0.mounted },
|
||||
hardMounted: machine.hardDiskConnected && machine.hardDisks.first?.mounted == true,
|
||||
tapeMounted: machine.tapeMounted).equatable()
|
||||
.onAppear {
|
||||
if let profile = machine.usageProfile { presentation.didShowGuide(profile) }
|
||||
}
|
||||
.onChange(of: machine.usageProfile) { _, profile in
|
||||
if let profile { presentation.didShowGuide(profile) }
|
||||
}
|
||||
}
|
||||
}.font(.callout)
|
||||
}
|
||||
}
|
||||
|
||||
struct MediaActionsMenu: View {
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
var body: some View {
|
||||
Menu {
|
||||
Button { openWindow(id: "software-library") } label: { Label("Software Library…", systemImage: "books.vertical") }
|
||||
Divider()
|
||||
Button("Floppy Disks…") { openWindow(id: "disks") }
|
||||
Button("Virtual Hard Disks…") { openWindow(id: "hard-disks") }
|
||||
Button("Cassette…") { openWindow(id: "cassette") }
|
||||
Button("Printer Output…") { openWindow(id: "printer") }
|
||||
Button("Cartridges…") { openWindow(id: "cartridges") }
|
||||
} label: { Label("Media", systemImage: "externaldrive") }.fixedSize()
|
||||
}
|
||||
}
|
||||
|
||||
// Polling redraws the enclosing MachineView. These explicit equality boundaries
|
||||
// keep tracking native menus intact; their own deduplicated observation still
|
||||
// updates genuine command state (including changes made from the menu bar).
|
||||
struct MachineSettingsMenu: View, Equatable {
|
||||
let machine: MachineModel
|
||||
@ObservedObject private var menu: MachineMenuState
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState }
|
||||
static func == (lhs: Self, rhs: Self) -> Bool { lhs.machine === rhs.machine }
|
||||
var body: some View {
|
||||
Menu {
|
||||
Button("Machine Settings…") { openWindow(id: "machine-settings") }
|
||||
Button("Display Settings…") { openWindow(id: "display-settings") }
|
||||
Button("Cartridges and Multi-Pak…") { openWindow(id: "cartridges") }
|
||||
Button("Keyboard and Joysticks…") { openWindow(id: "input") }
|
||||
Divider()
|
||||
Picker("Video Signal", selection: Binding(get: { menu.values.videoOutput }, set: machine.setVideoOutput)) {
|
||||
ForEach(DisplayOutput.allCases, id: \.rawValue) { Text($0.label).tag($0) }
|
||||
}
|
||||
Toggle("Sound", isOn: Binding(get: { menu.values.audioEnabled }, set: machine.setAudio))
|
||||
Button("Sound and Cassette…") { openWindow(id: "cassette") }
|
||||
Divider()
|
||||
Button("Open System ROM…", action: machine.openROM)
|
||||
if machine.hasBundledROMs {
|
||||
Button("Restore App Defaults…") { machine.confirmRestoreAppDefaults() }
|
||||
Divider()
|
||||
Button("Restore Bundled System ROM…") { machine.restoreBundledROM(system: true) }
|
||||
Button("Restore Bundled Disk ROM…") { machine.restoreBundledROM(system: false) }
|
||||
}
|
||||
Button("Load Binary…", action: machine.openBinary).disabled(!menu.values.canQuickLoad)
|
||||
Button("Run Diagnostic", action: machine.loadDiagnostic)
|
||||
} label: { Label("Settings", systemImage: "slider.horizontal.3") }
|
||||
.fixedSize().disabled(menu.values.busy)
|
||||
}
|
||||
}
|
||||
|
||||
struct MachineRestartMenu: View, Equatable {
|
||||
let machine: MachineModel
|
||||
@ObservedObject private var menu: MachineMenuState
|
||||
init(machine: MachineModel) { self.machine = machine; self.menu = machine.menuState }
|
||||
static func == (lhs: Self, rhs: Self) -> Bool { lhs.machine === rhs.machine }
|
||||
var body: some View {
|
||||
Menu {
|
||||
Button("Soft Reset — Retain RAM", action: machine.softReset)
|
||||
Button("Cold Restart — Clear RAM…", action: machine.requestColdReset)
|
||||
} label: { Label("Restart", systemImage: "arrow.counterclockwise") }
|
||||
.disabled(menu.values.busy || menu.values.state == .empty || menu.values.state == .closed).fixedSize()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Value-only content keeps the open help stable during frame/activity refreshes.
|
||||
private struct CoCoUsageHelp: View, Equatable {
|
||||
let profile: SystemProfile?
|
||||
let floppyMounted: Bool
|
||||
let hardMounted: Bool
|
||||
let tapeMounted: Bool
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Label("Using your CoCo", systemImage: "book.closed").font(.headline)
|
||||
if let profile { Text(profile.name).font(.subheadline.bold()) }
|
||||
Text("Click the live display to type. Escape is Break; Home is Clear.")
|
||||
if profile == .cocoSDC {
|
||||
SDCUsageGuide()
|
||||
} else if profile == .nitros9 {
|
||||
Nitros9UsageGuide()
|
||||
} else if profile == .hardDriveBasic {
|
||||
if hardMounted {
|
||||
instruction("Hard disk", "DIR 0", "Lists virtual volume 0 on HD0. RGBDOS selects hard-disk volumes at startup.")
|
||||
} else {
|
||||
Text("No image is mounted in HD0. Open Media → Virtual Hard Disks to insert one, or use the floppies below.")
|
||||
}
|
||||
instruction("Floppy drives", "DRIVE OFF\nDIR 0", "Lists FD0. Use DIR 1, DIR 2 or DIR 3 for the other floppies. OFF changes the drive mapping; it does not eject your images.")
|
||||
instruction("Return to the hard disk", "DRIVE ON\nDIR 0", "Returns drive numbers to the hard disk's virtual volumes.")
|
||||
} else if profile == .diskBasic {
|
||||
instruction("Floppy drives", "DIR 0", "Lists FD0. Use DIR 1, DIR 2 or DIR 3 for the other floppies.")
|
||||
} else {
|
||||
Text("This is a custom setup. Disk and boot commands depend on its ROM and software; follow their instructions.")
|
||||
}
|
||||
if profile != nil && profile != .nitros9 && (floppyMounted || (profile == .hardDriveBasic && hardMounted)) {
|
||||
instruction("Hello World example", "LOAD \"HELLO:0\"\nRUN", "On fresh starter media, HELLO asks where you live. Press 1 for Earth or 2 for Mars.")
|
||||
}
|
||||
if tapeMounted {
|
||||
instruction("Cassette in BASIC", "CLOAD \"HELLO\"\nRUN", "For the starter tape, open Media → Cassette and press Play first.")
|
||||
}
|
||||
Text("Save disk programs or record and export a tape to keep your work. Profiles save settings and file locations, not the running program.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).padding(20)
|
||||
}.frame(width: 420).frame(maxHeight: 580)
|
||||
.background(Color(nsColor: .windowBackgroundColor))
|
||||
}
|
||||
private func instruction(_ title: String, _ commands: String, _ explanation: String) -> some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(title).font(.subheadline.bold())
|
||||
Text(commands).font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
Text(explanation).font(.callout).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared by the system-profile details and live help; the archive remains a
|
||||
// private input, and links provide the full catalogue without copying it.
|
||||
struct Nitros9UsageGuide: View {
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Getting around OS-9").font(.headline)
|
||||
Text("Loading this profile automatically types DOS 255 at the RGBDOS prompt. Wait for the OS-9 shell prompt before typing. These are OS-9 commands, not BASIC commands.").font(.callout)
|
||||
section("System disk · HD0", "dir /dd\ndir /dd/games\ndir /dd/apps", "The boot disk is /dd, also accessible as /h0. Use chd to change your working directory; chx changes where commands are found.")
|
||||
section("Shared data disk · HD1", "dir /h1\nchd /h1\necho Hello from OS-9 >hello\nlist hello", "This is the OS-9 area of your Hard Drive BASIC disk. Its BASIC volumes are separate; the existing HELLO program is preserved. Return with chd /dd.")
|
||||
section("Explore files", "dir /dd/sources\ndir /dd/grfx\ndir /dd/sound\nlist /dd/docs.txt", "dir lists files; list reads text. The archive includes software, source, pictures and sound. Programs may have their own startup instructions.")
|
||||
section("Command help", "help\nhelp dir", "Use the installed help and the archive notes for more detail.")
|
||||
section("Return to BASIC", "DOS 255", "Choose Restart → Cold Restart — Clear RAM…, then select 6 (EXIT TO BASIC) and press Return at the archive menu. At BASIC, type DOS 255 to boot OS-9 again. In BASIC, DIR 1 lists archive volume 1; DRIVE OFF switches drive numbers 0–3 to the floppies, and DRIVE ON restores hard-disk mapping.")
|
||||
DriveWireNetworkingHelp()
|
||||
Text("The archive also describes DriveWire disks, MIDI and Glenside IDE hardware. VCC Plus uses its native virtual hard disks for this profile.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
Link("Archive contents and original notes", destination: URL(string: "https://colorcomputerarchive.com/repo/Virtual%20Hard%20Drives/NitrOS-9%20L2%20V3.3.0/Virtual%20Hard%20Drive.txt")!)
|
||||
}
|
||||
}
|
||||
private func section(_ title: String, _ command: String, _ detail: String) -> some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(title).font(.subheadline.bold())
|
||||
Text(command).font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
Text(detail).font(.callout).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DriveWireNetworkingHelp: View {
|
||||
var body: some View {
|
||||
SecondaryHelp(title: "Connect from NitrOS-9") {
|
||||
Text("A fresh NitrOS-9 system disk loads its networking drivers at boot. At the OS-9 shell, enter the host name and port of your TCP service or BBS.")
|
||||
Text("telnet HOST PORT")
|
||||
.font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
.accessibilityIdentifier("drivewire-guest-commands")
|
||||
Text("Use 127.0.0.1 for a service running on this Mac. If you turned networking off, you can enable it again in Machine Settings.")
|
||||
Text("For your Mac’s own command line, enter telnet macshell 2323 and respond to the permission request in VCC Plus. Type exit to return to OS-9.")
|
||||
Text("Use clear to clear the CoCo screen. Hold Option while pressing an arrow key to move. In vi, press i to insert and Escape to finish inserting.")
|
||||
Text("Using an older system disk? In Configuration Profiles, select NitrOS-9 and choose Create Fresh Starter Media… for a separate disk with the drivers installed. To keep using the older disk, load its bundled drivers using the instructions below.")
|
||||
SecondaryHelp(title: "Load drivers on an older disk") {
|
||||
Text("Use an unused filename for the combined drivers. Create the file once, then load it after each boot.")
|
||||
Text("""
|
||||
chd /dd/boot_with_beckerdw
|
||||
merge dwio scdwv n n1 >/dd/dwnet
|
||||
attr /dd/dwnet e
|
||||
chd /dd
|
||||
load /dd/dwnet
|
||||
""").font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared by system-profile details and firmware-aware live help.
|
||||
struct SDCUsageGuide: View {
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Your SD card is a local Mac folder. On first use, the CoCo SDC system profile supplies a writable copy of HELLO.DSK and a startup.cfg that mounts it in drive 0. Your changes are kept when you reload the profile.")
|
||||
Text("List and run the supplied example").font(.subheadline.bold())
|
||||
Text("DIR 0\nLOAD \"HELLO:0\"\nRUN").font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
Text("DIR lists files on the mounted disk. On a fresh card, HELLO asks you to press 1 for Earth or 2 for Mars.")
|
||||
Text("Mount the starter disk again").font(.subheadline.bold())
|
||||
Text("DRIVE 0,\"/HELLO.DSK\"").font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
Text("Use this if another image is mounted. The leading / starts at your SD card folder's root. To mount another image, use its path instead.")
|
||||
Text("Find your files on the Mac").font(.subheadline.bold())
|
||||
Text("Click the SDC cartridge or open Cartridge → Cartridges, then Show SD Card Folder in Finder. You can add extracted disk images there. The app keeps the bundled original; saves go directly to your local copy. Finish disk operations before changing files in Finder.")
|
||||
Text("startup.cfg controls startup mounts. Changes to that file are preserved. Fresh Media Copy creates a separate clean card. This guide applies to the supplied SDC-DOS ROM; your chosen card may contain different files.").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A guest cannot bring the app or a window to the front. The prompt waits for
|
||||
// an active emulator/settings window and yields to existing sheets and panels.
|
||||
struct MacShellPermissionPresenter: NSViewRepresentable {
|
||||
@ObservedObject var machine: MachineModel
|
||||
func makeCoordinator() -> Presenter { Presenter() }
|
||||
func makeNSView(context: Context) -> NSView {
|
||||
let anchor = NSView()
|
||||
anchor.setAccessibilityElement(false)
|
||||
return anchor
|
||||
}
|
||||
func updateNSView(_ anchor: NSView, context: Context) {
|
||||
let presenter = context.coordinator
|
||||
DispatchQueue.main.async { [weak anchor] in presenter.update(in: anchor?.window, machine: machine) }
|
||||
}
|
||||
static func dismantleNSView(_ anchor: NSView, coordinator: Presenter) { coordinator.dismiss() }
|
||||
|
||||
@MainActor final class Presenter {
|
||||
private var alert: NSAlert?
|
||||
private var presented: MachineModel.MacShellRequest?
|
||||
|
||||
func dismiss() {
|
||||
presented = nil
|
||||
guard let alert else { return }
|
||||
self.alert = nil
|
||||
alert.window.sheetParent?.endSheet(alert.window, returnCode: .abort)
|
||||
}
|
||||
|
||||
func update(in owner: NSWindow?, machine: MachineModel) {
|
||||
let request = machine.macShellRequest
|
||||
if alert != nil {
|
||||
if presented != request { dismiss() }
|
||||
return
|
||||
}
|
||||
guard let request, let owner, NSApp.isActive, owner.isKeyWindow, owner.isVisible,
|
||||
!owner.isMiniaturized, owner.attachedSheet == nil, NSApp.modalWindow == nil,
|
||||
!(NSApp.keyWindow is NSPanel) else { return }
|
||||
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = "Allow this CoCo program to use your Mac shell?"
|
||||
alert.informativeText = "The guest requested macshell. It can run commands as your Mac user, starting in your home folder, and read or change files your account and VCC Plus can access."
|
||||
alert.addButton(withTitle: "Deny").keyEquivalent = "\r"
|
||||
alert.addButton(withTitle: "Allow")
|
||||
if request.disk != nil {
|
||||
alert.showsSuppressionButton = true
|
||||
alert.suppressionButton?.title = "Remember for any program running with this NitrOS-9 setup"
|
||||
alert.suppressionButton?.state = .off
|
||||
}
|
||||
self.alert = alert
|
||||
presented = request
|
||||
alert.beginSheetModal(for: owner) { [weak self, weak machine, weak alert] result in
|
||||
guard let self, let machine, let alert, self.alert === alert else { return }
|
||||
self.alert = nil; self.presented = nil
|
||||
machine.decideMacShell(request, allow: result == .alertSecondButtonReturn,
|
||||
remember: alert.suppressionButton?.state == .on)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Combine
|
||||
import SwiftUI
|
||||
|
||||
// SwiftUI rebuilds native menu groups when an observed Commands object changes.
|
||||
// Keep frame, audio and media-status polling out of that observation: rebuilding
|
||||
// the system View menu while it is tracking can dismiss it before selection.
|
||||
@MainActor
|
||||
final class MachineMenuState: ObservableObject {
|
||||
struct Values: Equatable {
|
||||
var busy: Bool
|
||||
var diskSaving: Bool
|
||||
var state: VCCMachineState
|
||||
var videoOutput: DisplayOutput
|
||||
var fastForward: Bool
|
||||
var audioEnabled: Bool
|
||||
var diskConnected: Bool
|
||||
var hardDiskConnected: Bool
|
||||
var pasting: Bool = false
|
||||
var canPaste: Bool { !busy && state == .running && !pasting }
|
||||
var canQuickLoad: Bool { !busy && !diskSaving && (state == .running || state == .paused) }
|
||||
}
|
||||
@Published private(set) var values: Values
|
||||
private var observation: AnyCancellable?
|
||||
|
||||
init(machine: MachineModel) {
|
||||
values = Values(busy: machine.busy || machine.diskEditorLocked, diskSaving: machine.diskSaving, state: machine.state,
|
||||
videoOutput: machine.videoOutput, fastForward: machine.settings.fastForward, audioEnabled: machine.audioEnabled,
|
||||
diskConnected: machine.diskConnected, hardDiskConnected: machine.hardDiskConnected, pasting: machine.pasteRemaining > 0)
|
||||
let effectiveBusy = Publishers.CombineLatest(machine.$busy, machine.$diskEditorLocked).map { $0 || $1 }.removeDuplicates()
|
||||
observation = Publishers.CombineLatest4(effectiveBusy, machine.$diskSaving, machine.$state, machine.$videoOutput)
|
||||
.combineLatest(machine.$settings.map(\.fastForward), machine.$diskConnected, machine.$hardDiskConnected)
|
||||
.combineLatest(machine.$audioEnabled, machine.$pasteRemaining.map { $0 > 0 }.removeDuplicates())
|
||||
.map { controlsAndDevices, audioEnabled, pasting in
|
||||
let (controls, fastForward, diskConnected, hardDiskConnected) = controlsAndDevices
|
||||
return Values(busy: controls.0, diskSaving: controls.1, state: controls.2, videoOutput: controls.3,
|
||||
fastForward: fastForward, audioEnabled: audioEnabled, diskConnected: diskConnected, hardDiskConnected: hardDiskConnected, pasting: pasting)
|
||||
}
|
||||
.removeDuplicates()
|
||||
.sink { [weak self] value in
|
||||
// The model and its published setters belong to the main actor.
|
||||
guard let self, self.values != value else { return }
|
||||
self.values = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the emulator command available in its menu throughout the app. Only
|
||||
/// the active emulator window owns its keyboard equivalent.
|
||||
struct FastForwardMenuItem: View {
|
||||
let machine: MachineModel
|
||||
let values: MachineMenuState.Values
|
||||
let emulatorFocused: Bool
|
||||
|
||||
var body: some View {
|
||||
Toggle("Fast-forward", isOn: Binding(get: { values.fastForward }, set: machine.setFastForward))
|
||||
.keyboardShortcut(emulatorFocused ? KeyboardShortcut("f", modifiers: [.command, .shift]) : nil)
|
||||
.disabled(values.busy || values.diskSaving || values.state == .closed)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
struct MachineSettings: Codable, Equatable {
|
||||
var use6309 = false
|
||||
var ram = 1
|
||||
var overclock = 1
|
||||
var frameInterval = 1
|
||||
var fastForward = false
|
||||
static let preferenceKey = "machineSettings.v1"
|
||||
static let memoryLabels = ["128 KB", "512 KB", "2 MB", "8 MB"]
|
||||
var valid: Bool { (0...3).contains(ram) && (1...16).contains(overclock) && (1...6).contains(frameInterval) }
|
||||
func needsRestart(comparedTo previous: Self) -> Bool { use6309 != previous.use6309 || ram != previous.ram }
|
||||
static func remembered(in defaults: UserDefaults) -> Self {
|
||||
guard let data = defaults.data(forKey: preferenceKey),
|
||||
let value = try? JSONDecoder().decode(Self.self, from: data), value.valid else { return Self() }
|
||||
return value
|
||||
}
|
||||
func save(in defaults: UserDefaults) {
|
||||
guard valid, let data = try? JSONEncoder().encode(self) else { return }
|
||||
defaults.set(data, forKey: Self.preferenceKey)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
|
||||
struct MachineSettingsView: View {
|
||||
@ObservedObject var machine: MachineModel
|
||||
@State private var draft = MachineSettings()
|
||||
@State private var confirmRestart = false
|
||||
private var restartRequired: Bool {
|
||||
(machine.state == .running || machine.state == .paused) && draft.needsRestart(comparedTo: machine.settings)
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
SecondaryHeader(title: "Machine Settings", symbol: "cpu", subtitle: "Review changes, then apply them to the CoCo.")
|
||||
.padding(20)
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
SecondaryCard {
|
||||
Label("Hardware", systemImage: "cpu").font(.headline)
|
||||
Picker("Processor", selection: $draft.use6309) {
|
||||
Text("Motorola 6809").tag(false)
|
||||
Text("Hitachi 6309").tag(true)
|
||||
}.accessibilityIdentifier("machine-processor")
|
||||
Picker("Memory", selection: $draft.ram) {
|
||||
ForEach(0..<4) { Text(MachineSettings.memoryLabels[$0]).tag($0) }
|
||||
}.accessibilityIdentifier("machine-memory")
|
||||
Label("Hardware changes restart the CoCo and clear RAM. Mounted media stays attached.", systemImage: "arrow.counterclockwise")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Performance", systemImage: "speedometer").font(.headline)
|
||||
Stepper("CPU overclock: \(draft.overclock)×", value: $draft.overclock, in: 1...16)
|
||||
.monospacedDigit()
|
||||
Toggle("Fast-forward", isOn: $draft.fastForward)
|
||||
Text("Fast-forward temporarily silences playback. Disk and cassette operations continue.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
Divider()
|
||||
Picker("Present frames", selection: $draft.frameInterval) {
|
||||
Text("Every frame").tag(1)
|
||||
ForEach(2...6, id: \.self) { Text("Every \($0) frames").tag($0) }
|
||||
}.accessibilityIdentifier("machine-frame-interval")
|
||||
SecondaryHelp(title: "About speed and display timing") {
|
||||
Text("1× is normal. Overclock increases CPU speed when software selects double-speed mode. Video and device timing stay unchanged.")
|
||||
Text("Fast-forward runs faster than real time as this Mac allows. Presenting fewer frames reduces display updates only; CPU, video timing, sound and devices still run every frame.")
|
||||
}
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Networking", systemImage: "network").font(.headline)
|
||||
Toggle("Enable DriveWire networking", isOn: Binding(
|
||||
get: { machine.driveWireEnabled }, set: machine.setDriveWireNetworking))
|
||||
.accessibilityIdentifier("machine-drivewire-networking")
|
||||
Text("Lets compatible NitrOS-9 programs open outbound TCP connections through the FD-502 Becker port. Networking defaults on for the built-in NitrOS-9 profile. Your choice here applies across profiles. Turning it off closes connections immediately.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
DriveWireNetworkingHelp()
|
||||
Divider()
|
||||
Label("Mac shell", systemImage: "terminal").font(.subheadline.bold())
|
||||
Text("At the OS-9 prompt, enter telnet macshell 2323 to request access to your Mac command line. Programs in the guest can then run commands with your Mac account’s permissions. Type exit to return to OS-9.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
if machine.macShellStatus == "idle" {
|
||||
Button("Start Mac Shell Session", action: machine.startMacShellSession)
|
||||
.disabled(!machine.driveWireEnabled || machine.busy)
|
||||
} else {
|
||||
Text(machine.macShellStatus == "ready" ? "Ready for one guest connection." :
|
||||
machine.macShellStatus == "requested" ? "Waiting for your permission." : "Mac shell session connected.")
|
||||
.font(.callout)
|
||||
Button("Stop Mac Shell Session", action: machine.stopMacShellSession)
|
||||
}
|
||||
if machine.hasRememberedMacShellPermission {
|
||||
Button("Forget Mac Shell Permission", action: machine.forgetMacShellPermission)
|
||||
}
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Recovery", systemImage: "arrow.counterclockwise").font(.headline)
|
||||
Text(machine.hasBundledROMs ? "Restore the complete standard setup, including ROMs and media assignments. This is separate from editing the hardware above." : "Bundled defaults are unavailable in this source build. Choose your own ROMs, or add the private development ROMs.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
Button { machine.confirmRestoreAppDefaults { draft = machine.settings } } label: {
|
||||
Label("Restore App Defaults…", systemImage: "arrow.counterclockwise")
|
||||
}.disabled(!machine.hasBundledROMs)
|
||||
}
|
||||
}.padding(20)
|
||||
}
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
if let error = machine.profileError ?? machine.fileError ?? machine.error {
|
||||
Text(error).foregroundStyle(.red).font(.callout).textSelection(.enabled)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
HStack {
|
||||
Button { draft = MachineSettings() } label: {
|
||||
Label("Hardware Defaults", systemImage: "arrow.counterclockwise")
|
||||
}.help("Reset this form's draft only. Choose Apply to change the machine.")
|
||||
Spacer()
|
||||
Button { draft = machine.settings } label: { Label("Revert", systemImage: "arrow.uturn.backward") }
|
||||
.disabled(draft == machine.settings)
|
||||
Button {
|
||||
if restartRequired { confirmRestart = true }
|
||||
else { machine.applyMachineSettings(draft) }
|
||||
} label: {
|
||||
Label(restartRequired ? "Apply and Restart…" : "Apply",
|
||||
systemImage: restartRequired ? "arrow.clockwise" : "checkmark")
|
||||
}.keyboardShortcut(.defaultAction).disabled(draft == machine.settings || !draft.valid)
|
||||
}
|
||||
Text("Hardware Defaults edits this draft. Applied settings are remembered for the next launch.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}.padding(16)
|
||||
}
|
||||
.background(MacShellPermissionPresenter(machine: machine))
|
||||
.frame(minWidth: 540, minHeight: 520)
|
||||
.disabled(machine.busy || machine.diskSaving || machine.state == .closed)
|
||||
.onAppear { draft = machine.settings }
|
||||
.onChange(of: machine.settings) { old, new in if draft == old { draft = new } }
|
||||
.alert("Cold-restart the machine?", isPresented: $confirmRestart) {
|
||||
Button("Cancel", role: .cancel) { }
|
||||
Button("Apply and Restart", role: .destructive) { machine.applyMachineSettings(draft) }
|
||||
} message: {
|
||||
Text("Programs and other contents of RAM will be cleared. Mounted disks, cartridges, and cassette contents are retained. The machine will keep its current running or paused state.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Combine
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
struct ManualLibraryContent {
|
||||
let root: URL
|
||||
|
||||
init(root: URL) {
|
||||
// WebKit checks its read grant against the exact path used by a citation.
|
||||
self.root = root.standardizedFileURL.resolvingSymlinksInPath()
|
||||
}
|
||||
|
||||
static var bundled: Self? {
|
||||
Bundle.main.url(forResource: "ManualLibrary", withExtension: nil).map { Self(root: $0) }
|
||||
}
|
||||
|
||||
var home: URL { root.appendingPathComponent("index.html") }
|
||||
|
||||
func allowsExternalReference(_ url: URL) -> Bool {
|
||||
guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { return false }
|
||||
let existing = ["https://colorcomputerarchive.com/", "https://learn.chatgpt.com/docs/extend/mcp?surface=app",
|
||||
"https://learn.chatgpt.com/docs/extend/mcp?surface=cli",
|
||||
"https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz",
|
||||
"https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz/src/branch/main/CHATGPT_PROMPT.md",
|
||||
"https://www.fla-shop.com/svg/usa/", "https://creativecommons.org/licenses/by/4.0/"]
|
||||
if existing.contains(url.absoluteString) { return true }
|
||||
let provenance = root.appendingPathComponent("toolchain-reference/provenance.json")
|
||||
guard relativePath(for: provenance) != nil,
|
||||
let data = try? Data(contentsOf: provenance),
|
||||
let record = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let references = record["externalReferences"] as? [String] else { return false }
|
||||
return references.contains(url.absoluteString)
|
||||
}
|
||||
|
||||
func relativePath(for url: URL) -> String? {
|
||||
guard url.isFileURL, url.host?.isEmpty != false else { return nil }
|
||||
let base = root.standardizedFileURL.resolvingSymlinksInPath().pathComponents
|
||||
let file = url.standardizedFileURL.resolvingSymlinksInPath()
|
||||
let parts = file.pathComponents
|
||||
guard parts.count > base.count, parts.starts(with: base),
|
||||
(try? file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
|
||||
else { return nil }
|
||||
return parts.dropFirst(base.count).joined(separator: "/")
|
||||
}
|
||||
|
||||
func basicTopicURL(for entry: BASICReferenceEntry) -> URL? {
|
||||
let page: String
|
||||
let anchor: String
|
||||
if entry.id.hasPrefix("ERROR.") {
|
||||
page = "errors.html"
|
||||
anchor = "err-" + entry.keyword.lowercased().replacingOccurrences(of: "/0", with: "div-zero")
|
||||
} else {
|
||||
page = "reference.html"
|
||||
anchor = "term-" + entry.id.lowercased()
|
||||
.replacingOccurrences(of: ".", with: "-")
|
||||
.replacingOccurrences(of: "$", with: "-string")
|
||||
.replacingOccurrences(of: "@", with: "-at")
|
||||
}
|
||||
let url = root.appendingPathComponent("programming-in-coco-basic").appendingPathComponent(page)
|
||||
var destination = URLComponents(url: url, resolvingAgainstBaseURL: false)
|
||||
destination?.fragment = anchor
|
||||
return destination?.url
|
||||
}
|
||||
|
||||
// Only files in a book's designated practice areas offer a writable copy.
|
||||
func copyTitle(for relativePath: String) -> String? {
|
||||
let parts = relativePath.split(separator: "/")
|
||||
guard parts.count == 3 else { return nil }
|
||||
let url = root.appendingPathComponent(relativePath)
|
||||
guard self.relativePath(for: url) == relativePath else { return nil }
|
||||
if parts[0] == "toolchain-reference", parts[1] == "sources",
|
||||
["markdown", "sgml"].contains(url.pathExtension.lowercased()) || url.lastPathComponent == "lwtools-manual.html.txt" {
|
||||
return "Save Original Manual Source"
|
||||
}
|
||||
if parts[0] == "toolchain-reference", parts[1] == "sources",
|
||||
["cmoc-help.txt", "lwasm-help.txt", "lwlink-help.txt"].contains(url.lastPathComponent) {
|
||||
return "Save Command-Line Help"
|
||||
}
|
||||
switch (parts[1], url.pathExtension.lowercased()) {
|
||||
case ("media", "dsk"): return "Save Practice Disk"
|
||||
case ("media", "cas"): return "Save Practice Cassette"
|
||||
case ("examples", "asm"), ("examples", "a"): return "Save Assembly Example"
|
||||
case ("examples", "b09"): return "Save BASIC09 Example"
|
||||
case ("examples", "c"): return "Save C Example"
|
||||
case ("examples", "zip"): return "Save Example Project"
|
||||
case ("examples", "txt"): return "Save Example Text"
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
func exampleURL(for relativePath: String) -> URL? {
|
||||
let parts = relativePath.components(separatedBy: "/")
|
||||
guard parts.count == 3, parts[1] == "examples" else { return nil }
|
||||
let url = root.appendingPathComponent(relativePath)
|
||||
guard url.pathExtension.lowercased() == "bas",
|
||||
self.relativePath(for: url) == relativePath else { return nil }
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
|
||||
let webView: WKWebView
|
||||
let content: ManualLibraryContent?
|
||||
lazy var pageFind = ManualPageFind(webView: webView)
|
||||
private var searchNavigation: WKNavigation?
|
||||
var openExample: ((String) -> Void)?
|
||||
@Published private(set) var canGoBack = false
|
||||
@Published private(set) var canGoForward = false
|
||||
@Published private(set) var error: String?
|
||||
|
||||
init(content: ManualLibraryContent? = .bundled) {
|
||||
self.content = content
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
webView = WKWebView(frame: .zero, configuration: configuration)
|
||||
super.init()
|
||||
webView.navigationDelegate = self
|
||||
webView.allowsBackForwardNavigationGestures = true
|
||||
webView.publisher(for: \.canGoBack).receive(on: RunLoop.main).assign(to: &$canGoBack)
|
||||
webView.publisher(for: \.canGoForward).receive(on: RunLoop.main).assign(to: &$canGoForward)
|
||||
}
|
||||
|
||||
func showHome() {
|
||||
loadPage(content?.home)
|
||||
}
|
||||
|
||||
func showLibrarySearch() {
|
||||
pageFind.close()
|
||||
if let url = webView.url, content?.relativePath(for: url) == "index.html", !webView.isLoading {
|
||||
focusLibrarySearch()
|
||||
} else {
|
||||
searchNavigation = loadPage(content?.home)
|
||||
}
|
||||
}
|
||||
|
||||
private func focusLibrarySearch() {
|
||||
webView.window?.makeFirstResponder(webView)
|
||||
webView.evaluateJavaScript("""
|
||||
document.getElementById('search').scrollIntoView();
|
||||
var input = document.getElementById('manual-query');
|
||||
input.focus({preventScroll: true});
|
||||
input.select();
|
||||
""", in: nil, in: .defaultClient, completionHandler: nil)
|
||||
}
|
||||
|
||||
func showBASICTopic(_ entry: BASICReferenceEntry) {
|
||||
loadPage(content?.basicTopicURL(for: entry))
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func loadPage(_ url: URL?) -> WKNavigation? {
|
||||
guard let content, let url, content.relativePath(for: url) != nil else {
|
||||
error = "This page is missing from the bundled Manual Library."
|
||||
return nil
|
||||
}
|
||||
error = nil
|
||||
return webView.loadFileURL(url, allowingReadAccessTo: content.root)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
|
||||
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
|
||||
guard let url = action.request.url, action.targetFrame?.isMainFrame != false else {
|
||||
decisionHandler(.cancel)
|
||||
return
|
||||
}
|
||||
if let path = content?.relativePath(for: url) {
|
||||
let fileExtension = url.pathExtension.lowercased()
|
||||
if let saveTitle = content?.copyTitle(for: path) {
|
||||
decisionHandler(.cancel)
|
||||
if action.navigationType == .linkActivated {
|
||||
let panel = NSSavePanel()
|
||||
panel.nameFieldStringValue = url.lastPathComponent
|
||||
panel.title = saveTitle
|
||||
panel.begin { [weak self] response in
|
||||
guard response == .OK, let destination = panel.url else { return }
|
||||
do {
|
||||
try Data(contentsOf: url).write(to: destination, options: .atomic)
|
||||
} catch {
|
||||
self?.error = "The practice file could not be saved. " + error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if fileExtension == "bas" {
|
||||
decisionHandler(.cancel)
|
||||
if action.navigationType == .linkActivated, content?.exampleURL(for: path) != nil {
|
||||
openExample?(path)
|
||||
}
|
||||
return
|
||||
}
|
||||
decisionHandler(.allow)
|
||||
return
|
||||
}
|
||||
decisionHandler(.cancel)
|
||||
if action.navigationType == .linkActivated {
|
||||
if content?.allowsExternalReference(url) == true {
|
||||
if !NSWorkspace.shared.open(url) { error = "The reference could not open in your browser." }
|
||||
} else {
|
||||
error = "This link does not lead to an available page in the bundled Manual Library."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
|
||||
pageFind.pageChanged()
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
error = nil
|
||||
if let searchNavigation, navigation === searchNavigation {
|
||||
self.searchNavigation = nil
|
||||
focusLibrarySearch()
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
||||
showLoadFailure(error)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||
showLoadFailure(error)
|
||||
}
|
||||
|
||||
private func showLoadFailure(_ failure: Error) {
|
||||
let reason = failure as NSError
|
||||
guard !(reason.domain == NSURLErrorDomain && reason.code == NSURLErrorCancelled) else { return }
|
||||
error = "The manual page could not open. " + failure.localizedDescription
|
||||
}
|
||||
|
||||
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||||
error = "The manual reader stopped responding. Choose Library Home to reopen it."
|
||||
}
|
||||
}
|
||||
|
||||
private struct ManualWebPage: NSViewRepresentable {
|
||||
let reader: ManualReader
|
||||
let openExample: (String) -> Void
|
||||
|
||||
func makeNSView(context: Context) -> WKWebView { reader.webView }
|
||||
|
||||
func updateNSView(_ webView: WKWebView, context: Context) { reader.openExample = openExample }
|
||||
}
|
||||
|
||||
struct ManualLibraryView: View {
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@ObservedObject var reader: ManualReader
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
if let error = reader.error {
|
||||
Label(error, systemImage: "exclamationmark.triangle")
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(10)
|
||||
Divider()
|
||||
}
|
||||
ManualPageFindBar(finder: reader.pageFind)
|
||||
ManualWebPage(reader: reader) { path in
|
||||
openWindow(id: "basic-example", value: "manual/" + path)
|
||||
}
|
||||
}
|
||||
.focusedSceneValue(\.manualPageFind, reader.pageFind)
|
||||
.toolbar {
|
||||
ToolbarItemGroup(placement: .primaryAction) {
|
||||
Button("Find on This Page", systemImage: "magnifyingglass") { reader.pageFind.show() }
|
||||
.help("Find on this page (⌘F)").accessibilityIdentifier("manual.find")
|
||||
|
||||
Button {
|
||||
reader.showLibrarySearch()
|
||||
} label: {
|
||||
Label("Ask the Manuals", systemImage: "books.vertical").labelStyle(.titleAndIcon)
|
||||
}
|
||||
.help("Search all manuals by keyword")
|
||||
.accessibilityIdentifier("manual.ask")
|
||||
}
|
||||
ToolbarItemGroup(placement: .navigation) {
|
||||
Button("Back", systemImage: "chevron.backward") { reader.webView.goBack() }
|
||||
.help("Back").disabled(!reader.canGoBack)
|
||||
.accessibilityIdentifier("manual.back")
|
||||
Button("Forward", systemImage: "chevron.forward") { reader.webView.goForward() }
|
||||
.help("Forward").disabled(!reader.canGoForward)
|
||||
.accessibilityIdentifier("manual.forward")
|
||||
Button("Library Home", systemImage: "books.vertical") { reader.showHome() }
|
||||
.help("Library Home").accessibilityIdentifier("manual.home")
|
||||
}
|
||||
}
|
||||
.frame(minWidth: 420, minHeight: 340)
|
||||
.onAppear {
|
||||
if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.showHome() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
/// Find within the displayed HTML, including words split by inline formatting.
|
||||
/// DOM Ranges preserve links, source listings and the page's original markup.
|
||||
@MainActor
|
||||
final class ManualPageFind: ObservableObject {
|
||||
private weak var webView: WKWebView?
|
||||
@Published private(set) var visible = false
|
||||
@Published private(set) var focusRequest = 0
|
||||
@Published var query = "" { didSet { if query != oldValue { refresh() } } }
|
||||
@Published private(set) var count = 0
|
||||
@Published private(set) var position = 0
|
||||
@Published private(set) var searching = false
|
||||
private var revision = 0
|
||||
private var requested = 0
|
||||
|
||||
init(webView: WKWebView) { self.webView = webView }
|
||||
|
||||
func show() {
|
||||
if !visible {
|
||||
visible = true
|
||||
refresh()
|
||||
}
|
||||
focusRequest += 1
|
||||
}
|
||||
|
||||
func close() {
|
||||
guard visible else { return }
|
||||
visible = false
|
||||
clear()
|
||||
if let webView { webView.window?.makeFirstResponder(webView) }
|
||||
}
|
||||
|
||||
func pageChanged() {
|
||||
// An in-flight reply belongs to the document which produced it.
|
||||
visible = false
|
||||
clear()
|
||||
}
|
||||
|
||||
private func clear() {
|
||||
revision += 1
|
||||
requested = 0
|
||||
count = 0
|
||||
position = 0
|
||||
searching = false
|
||||
webView?.callAsyncJavaScript(Self.script, arguments: ["query": "", "index": 0],
|
||||
in: nil, in: .defaultClient, completionHandler: nil)
|
||||
}
|
||||
|
||||
func move(backward: Bool = false) {
|
||||
guard visible else { show(); return }
|
||||
guard count > 0 else { return }
|
||||
requested = (requested + (backward ? count - 1 : 1)) % count
|
||||
run()
|
||||
}
|
||||
|
||||
private func refresh() {
|
||||
requested = 0
|
||||
count = 0
|
||||
position = 0
|
||||
if visible { run() }
|
||||
}
|
||||
|
||||
private func run() {
|
||||
guard let webView else { return }
|
||||
revision += 1
|
||||
let expected = revision
|
||||
searching = true
|
||||
webView.callAsyncJavaScript(Self.script, arguments: ["query": query, "index": requested],
|
||||
in: nil, in: .defaultClient) { [weak self] result in
|
||||
guard let self, revision == expected else { return }
|
||||
let values = (try? result.get()) as? [Int]
|
||||
count = values?.first ?? 0
|
||||
position = values?.last ?? 0
|
||||
searching = false
|
||||
}
|
||||
}
|
||||
|
||||
// Each WebKit document owns its match ranges in an isolated content world.
|
||||
// Group adjacent inline nodes so a phrase can span a link or a bold word,
|
||||
// while keeping headings, paragraphs, table cells and code blocks distinct.
|
||||
private static let script = #"""
|
||||
const term = query.trim();
|
||||
let state = globalThis.vccPageFind;
|
||||
if (!term) {
|
||||
CSS.highlights?.delete('vcc-page-find');
|
||||
if (state?.selected) getSelection()?.removeAllRanges();
|
||||
delete globalThis.vccPageFind;
|
||||
return [0, 0];
|
||||
}
|
||||
if (state?.term !== term) {
|
||||
CSS.highlights?.delete('vcc-page-find');
|
||||
if (state?.selected) getSelection()?.removeAllRanges();
|
||||
state = {term, ranges: []};
|
||||
globalThis.vccPageFind = state;
|
||||
const root = document.querySelector('article.lesson') || document.querySelector('main') || document.body;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const pattern = term.split(/\s+/).map(word => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s+');
|
||||
const re = new RegExp(pattern, 'giu');
|
||||
let group, text = '', nodes = [];
|
||||
function collect() {
|
||||
let start = 0;
|
||||
for (const match of text.matchAll(re)) {
|
||||
const last = match.index + match[0].length;
|
||||
while (start + 1 < nodes.length && nodes[start + 1].offset <= match.index) start++;
|
||||
let end = start;
|
||||
while (end + 1 < nodes.length && nodes[end + 1].offset < last) end++;
|
||||
const range = document.createRange();
|
||||
range.setStart(nodes[start].node, match.index - nodes[start].offset);
|
||||
range.setEnd(nodes[end].node, last - nodes[end].offset);
|
||||
state.ranges.push(range);
|
||||
}
|
||||
nodes = [];
|
||||
text = '';
|
||||
}
|
||||
while (walker.nextNode()) {
|
||||
const node = walker.currentNode, parent = node.parentElement;
|
||||
if (!parent || parent.closest('script, style, noscript, [hidden], [aria-hidden="true"]')) continue;
|
||||
const block = parent.closest('p, h1, h2, h3, h4, li, dt, dd, td, th, pre, figcaption, summary, nav, label, button, section, article, div') || root;
|
||||
if (block !== group) { collect(); group = block; }
|
||||
nodes.push({node, offset:text.length});
|
||||
text += node.data;
|
||||
}
|
||||
collect();
|
||||
}
|
||||
if (!state.ranges.length) return [0, 0];
|
||||
const active = index % state.ranges.length;
|
||||
const range = state.ranges[active];
|
||||
const element = range.startContainer.parentElement;
|
||||
for (let p = element; p; p = p.parentElement) {
|
||||
if (p.tagName === 'DETAILS') p.open = true;
|
||||
}
|
||||
if (CSS.highlights && typeof Highlight === 'function') {
|
||||
CSS.highlights.set('vcc-page-find', new Highlight(range));
|
||||
} else {
|
||||
const selection = getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
state.selected = true;
|
||||
}
|
||||
element.scrollIntoView({block:'nearest', inline:'nearest'});
|
||||
const rect = range.getBoundingClientRect();
|
||||
if (rect.top < 72 || rect.bottom > innerHeight) scrollBy(0, rect.top - innerHeight / 2);
|
||||
return [state.ranges.length, active + 1];
|
||||
"""#
|
||||
}
|
||||
|
||||
private struct ManualPageFindKey: FocusedValueKey { typealias Value = ManualPageFind }
|
||||
extension FocusedValues {
|
||||
var manualPageFind: ManualPageFind? {
|
||||
get { self[ManualPageFindKey.self] }
|
||||
set { self[ManualPageFindKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
struct ManualPageFindBar: View {
|
||||
@ObservedObject var finder: ManualPageFind
|
||||
@FocusState private var focused: Bool
|
||||
|
||||
var body: some View {
|
||||
if finder.visible {
|
||||
HStack(spacing: 8) {
|
||||
TextField("Find on This Page", text: $finder.query)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.focused($focused)
|
||||
.onSubmit { finder.move() }
|
||||
.accessibilityIdentifier("manual.find.field")
|
||||
if !finder.query.isEmpty && !finder.searching {
|
||||
Text(finder.count == 0 ? "No matches" : "\(finder.position) of \(finder.count)")
|
||||
.font(.caption).foregroundStyle(.secondary).monospacedDigit()
|
||||
.accessibilityIdentifier("manual.find.status")
|
||||
}
|
||||
Button { finder.move(backward: true) } label: { Image(systemName: "chevron.up") }
|
||||
.disabled(finder.count == 0).accessibilityLabel("Find Previous")
|
||||
.help("Find previous occurrence (⇧⌘G)")
|
||||
Button { finder.move() } label: { Image(systemName: "chevron.down") }
|
||||
.disabled(finder.count == 0).accessibilityLabel("Find Next")
|
||||
.help("Find next occurrence (⌘G)")
|
||||
Button("Done") { finder.close() }.keyboardShortcut(.escape, modifiers: [])
|
||||
}
|
||||
.padding(.horizontal, 10).padding(.vertical, 5).background(.bar)
|
||||
.onAppear { focused = true }
|
||||
.onChange(of: finder.focusRequest) { focused = true }
|
||||
.onExitCommand { finder.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct MediaDropTarget: ViewModifier {
|
||||
let machine: MachineModel
|
||||
var destination: MediaDestination?
|
||||
@State private var targeted = false
|
||||
func body(content: Content) -> some View {
|
||||
content.overlay { if targeted { RoundedRectangle(cornerRadius: 10).strokeBorder(Color.accentColor, lineWidth: 3).allowsHitTesting(false) } }
|
||||
.onDrop(of: [UTType.fileURL], isTargeted: $targeted) { providers in
|
||||
guard providers.count == 1, let provider = providers.first else {
|
||||
machine.reportMediaError("Drop one media file at a time so its destination is explicit."); return false
|
||||
}
|
||||
guard !machine.busy, !machine.diskSaving else { return false }
|
||||
provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, _ in
|
||||
let url: URL?
|
||||
if let value = item as? URL { url = value }
|
||||
else if let data = item as? Data { url = URL(dataRepresentation: data, relativeTo: nil) }
|
||||
else { url = nil }
|
||||
Task { @MainActor in
|
||||
guard let url, url.isFileURL else { machine.reportMediaError("Drop a local media file from Finder."); return }
|
||||
machine.offerMedia(url, preferred: destination)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RecentMediaCommands: View {
|
||||
let machine: MachineModel
|
||||
@ObservedObject var recent: RecentMedia
|
||||
@ObservedObject var menu: MachineMenuState
|
||||
var body: some View {
|
||||
Menu("Open Recent Media") {
|
||||
if recent.entries.isEmpty { Text("No Recent Media") }
|
||||
ForEach(recent.entries) { entry in
|
||||
Button(entry.label) { machine.offerMedia(entry.url, preferred: entry.destination, fromHistory: true) }
|
||||
.help(entry.url.path).disabled(menu.values.busy || menu.values.diskSaving)
|
||||
}
|
||||
Divider()
|
||||
Button("Clear Recent Media") { recent.clear() }.disabled(recent.entries.isEmpty)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
@MainActor
|
||||
final class MemoryToolsModel: ObservableObject {
|
||||
enum Space: String, CaseIterable { case mapped = "Mapped CPU", physical = "Physical RAM" }
|
||||
struct Row: Identifiable {
|
||||
let id: Int
|
||||
let location: UInt32
|
||||
let logicalAddress: UInt16
|
||||
let bytes: String
|
||||
let mnemonic: String
|
||||
let operand: String
|
||||
}
|
||||
let machine: MachineModel
|
||||
@Published var space = Space.physical
|
||||
@Published var startText = "000000"
|
||||
@Published var endText = "0000FF"
|
||||
@Published var logicalText = "0000"
|
||||
@Published var os9 = false
|
||||
@Published private(set) var pending = false
|
||||
@Published private(set) var rows: [Row] = []
|
||||
@Published private(set) var caption = "Capture memory to inspect it. The machine keeps its current running or paused state."
|
||||
@Published var error: String?
|
||||
@Published var saveMessage: String?
|
||||
private(set) var capturedPhysical = true
|
||||
private var subscriptions: Set<AnyCancellable> = []
|
||||
init(machine: MachineModel) {
|
||||
self.machine = machine
|
||||
// Observe only command availability and RAM capacity, not the 60 Hz
|
||||
// display publisher. A profile change must update range validation even
|
||||
// while this tab retains an older, explicitly labeled capture.
|
||||
let changes: [AnyPublisher<Void, Never>] = [
|
||||
machine.$state.removeDuplicates().map { _ in () }.eraseToAnyPublisher(),
|
||||
machine.$busy.removeDuplicates().map { _ in () }.eraseToAnyPublisher(),
|
||||
machine.$diskSaving.removeDuplicates().map { _ in () }.eraseToAnyPublisher(),
|
||||
machine.$settings.map(\.ram).removeDuplicates().map { _ in () }.eraseToAnyPublisher()
|
||||
]
|
||||
Publishers.MergeMany(changes).sink { [weak self] in self?.objectWillChange.send() }.store(in: &subscriptions)
|
||||
}
|
||||
var available: Bool { !pending && !machine.busy && !machine.diskSaving && (machine.state == .paused || machine.state == .running) }
|
||||
var capacity: UInt32 { space == .mapped ? 65536 : [0x20000, 0x80000, 0x200000, 0x800000][min(3, max(0, machine.settings.ram))] }
|
||||
|
||||
static func range(start: String, end: String, capacity: UInt32) -> (UInt32, UInt32)? {
|
||||
guard capacity > 0,
|
||||
let first = DebuggerModel.hexadecimalAddress(start, maximum: capacity - 1),
|
||||
let last = DebuggerModel.hexadecimalAddress(end, maximum: capacity - 1), last >= first else { return nil }
|
||||
return (first, last - first + 1)
|
||||
}
|
||||
|
||||
private func capture(decode: Bool) async -> VCCDebugMemoryCapture? {
|
||||
guard available else { return nil }
|
||||
guard let (start, length) = Self.range(start: startText, end: endText, capacity: capacity) else {
|
||||
error = "Enter an inclusive hexadecimal range within 000000–\(DebuggerModel.hex(capacity - 1, width: 6)). The end must not precede the start."; return nil
|
||||
}
|
||||
let physical = space == .physical
|
||||
guard let logical = decode && physical ? DebuggerModel.hexadecimal(logicalText) : 0 else {
|
||||
error = "Enter a logical origin from 0000 to FFFF."; return nil
|
||||
}
|
||||
let interpretOS9 = os9
|
||||
pending = true; error = nil; saveMessage = nil
|
||||
defer { pending = false }
|
||||
let capture: VCCDebugMemoryCapture? = await withCheckedContinuation { continuation in
|
||||
machine.readDebuggerMemory(address: start, count: decode ? min(length, 4096) : length,
|
||||
physical: physical, logicalAddress: logical, os9: interpretOS9, decode: decode) { continuation.resume(returning: $0) }
|
||||
}
|
||||
guard let capture else { error = "The machine is busy. Try again when its current operation finishes."; return nil }
|
||||
guard capture.machine.errorMessage == nil else { error = capture.machine.errorMessage; return nil }
|
||||
if decode {
|
||||
capturedPhysical = physical
|
||||
rows = capture.instructions.enumerated().map { index, instruction in
|
||||
Row(id: index, location: capture.address + capture.instructionOffsets[index].uint32Value,
|
||||
logicalAddress: instruction.address,
|
||||
bytes: instruction.bytes.map { String(format: "%02X", $0) }.joined(separator: " "),
|
||||
mnemonic: instruction.mnemonic, operand: instruction.operand)
|
||||
}
|
||||
caption = "\(physical ? "Physical RAM" : "Mapped CPU") capture at \(capture.machine.cycles.formatted()) cycles · \(rows.count) rows · \(capture.machine.use6309 ? "HD6309" : "MC6809")\(physical ? " · \(capture.capacity / 1024) KB captured RAM space" : "")\(interpretOS9 ? " · OS-9 interpretation" : "")"
|
||||
}
|
||||
return capture
|
||||
}
|
||||
|
||||
func decode() async { _ = await capture(decode: true) }
|
||||
|
||||
func exportBytes() async -> Data? {
|
||||
guard let result = await capture(decode: false) else { return nil }
|
||||
guard !result.bytes.isEmpty, result.available.count == result.bytes.count,
|
||||
result.available.allSatisfy({ $0 != 0 }) else {
|
||||
error = "This range contains I/O that cannot be read without side effects. Choose a range excluding it, or export physical RAM. No file was written."
|
||||
return nil
|
||||
}
|
||||
return result.bytes
|
||||
}
|
||||
|
||||
func save(_ data: Data, to url: URL) async {
|
||||
pending = true; error = nil
|
||||
defer { pending = false }
|
||||
do {
|
||||
try await Task.detached {
|
||||
let access = url.startAccessingSecurityScopedResource()
|
||||
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
||||
try data.write(to: url, options: .atomic)
|
||||
}.value
|
||||
saveMessage = "Saved \(data.count.formatted()) raw bytes to \(url.lastPathComponent)."
|
||||
} catch { self.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct MemoryToolsView: View {
|
||||
@ObservedObject var model: MemoryToolsModel
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Picker("Address space", selection: $model.space) {
|
||||
ForEach(MemoryToolsModel.Space.allCases, id: \.self) { Text($0.rawValue).tag($0) }
|
||||
}.frame(width: 240).accessibilityIdentifier("memory-tools-space")
|
||||
Spacer()
|
||||
Text("All addresses are hexadecimal").font(.caption).foregroundStyle(.secondary)
|
||||
DebuggerHelpButton(title: "Memory capture and export", text: "Physical addresses identify RAM locations, not CPU execution addresses. The assumed CPU origin controls relative branch targets. Captures are read-only; Disassemble shows up to 128 rows. Export writes the entire selected range as raw bytes, without a LOADM header.")
|
||||
}
|
||||
HStack(spacing: 12) {
|
||||
entry("Start", text: $model.startText, id: "memory-tools-start")
|
||||
entry("End (inclusive)", text: $model.endText, id: "memory-tools-end")
|
||||
if model.space == .physical { entry("Assumed CPU origin", text: $model.logicalText, id: "memory-tools-origin") }
|
||||
}
|
||||
HStack {
|
||||
Toggle("Interpret OS-9 calls and module headers", isOn: $model.os9)
|
||||
.toggleStyle(.checkbox).accessibilityIdentifier("memory-tools-os9")
|
||||
Spacer()
|
||||
Button { Task { await model.decode() } } label: { Label("Disassemble", systemImage: "list.bullet.rectangle") }.disabled(!model.available)
|
||||
.accessibilityIdentifier("memory-tools-decode")
|
||||
Button(action: export) { Label("Export Binary…", systemImage: "square.and.arrow.up") }.disabled(!model.available)
|
||||
.accessibilityIdentifier("memory-tools-export")
|
||||
}
|
||||
Divider()
|
||||
Text(model.caption).font(.caption).foregroundStyle(.secondary)
|
||||
.accessibilityIdentifier("memory-tools-caption")
|
||||
ScrollView([.horizontal, .vertical]) {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
HStack(spacing: 12) {
|
||||
Text("Location").frame(width: 75, alignment: .leading)
|
||||
Text("CPU").frame(width: 45, alignment: .leading)
|
||||
Text("Bytes").frame(width: 160, alignment: .leading)
|
||||
Text("Instruction / annotation")
|
||||
}.foregroundStyle(.secondary)
|
||||
ForEach(model.rows) { row in
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
Text(DebuggerModel.hex(row.location, width: model.capturedPhysical ? 6 : 4)).frame(width: 75, alignment: .leading)
|
||||
Text(DebuggerModel.hex(row.logicalAddress)).frame(width: 45, alignment: .leading)
|
||||
Text(row.bytes.isEmpty ? "—" : row.bytes).frame(width: 160, alignment: .leading)
|
||||
Text(row.mnemonic).frame(width: 60, alignment: .leading)
|
||||
Text(row.operand)
|
||||
}.accessibilityElement(children: .combine)
|
||||
.accessibilityIdentifier("memory-tools-row-\(row.id)")
|
||||
.contextMenu {
|
||||
Button("Copy Row") {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString("\(DebuggerModel.hex(row.location, width: 6)) \(row.bytes) \(row.mnemonic) \(row.operand)", forType: .string)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.font(.system(size: 12, design: .monospaced)).padding(8)
|
||||
}.frame(minHeight: 180).background(Color(nsColor: .textBackgroundColor), in: RoundedRectangle(cornerRadius: 6))
|
||||
if let error = model.error {
|
||||
Text(error).foregroundStyle(.red).font(.caption).fixedSize(horizontal: false, vertical: true)
|
||||
.accessibilityIdentifier("memory-tools-error")
|
||||
}
|
||||
if let message = model.saveMessage {
|
||||
Text(message).font(.caption).accessibilityIdentifier("memory-tools-saved")
|
||||
}
|
||||
if model.pending { ProgressView().controlSize(.small) }
|
||||
}.padding(16).frame(minWidth: 760, idealWidth: 900, minHeight: 420, idealHeight: 600)
|
||||
}
|
||||
|
||||
private func entry(_ label: String, text: Binding<String>, id: String) -> some View {
|
||||
HStack {
|
||||
Text(label)
|
||||
TextField(label, text: text).labelsHidden().textFieldStyle(.roundedBorder)
|
||||
.font(.system(.body, design: .monospaced)).frame(width: 90)
|
||||
.accessibilityLabel(label + " in hexadecimal").accessibilityIdentifier(id)
|
||||
}
|
||||
}
|
||||
private func export() {
|
||||
Task {
|
||||
guard let bytes = await model.exportBytes() else { return }
|
||||
let panel = NSSavePanel()
|
||||
panel.title = "Export Raw Memory"
|
||||
panel.nameFieldStringValue = "memory.raw"
|
||||
panel.allowedContentTypes = [.data]
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
Task { await model.save(bytes, to: url) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import MetalKit
|
||||
import Combine
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
enum DisplayScaling: String, CaseIterable {
|
||||
case sharp, smooth, integer
|
||||
var label: String {
|
||||
switch self {
|
||||
case .sharp: return "Sharp — Fit Window"
|
||||
case .smooth: return "Smooth — Fit Window"
|
||||
case .integer: return "Integer Pixels"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DisplayStyle: Equatable {
|
||||
var scaling: DisplayScaling = .smooth
|
||||
var scanlines = false
|
||||
}
|
||||
|
||||
// Host presentation preferences deliberately stay outside machine profiles.
|
||||
// Separate observation prevents emulator polls from rebuilding open controls.
|
||||
@MainActor
|
||||
final class DisplayPreferences: ObservableObject {
|
||||
@Published var style: DisplayStyle { didSet {
|
||||
defaults.set(style.scaling.rawValue, forKey: "displayScaling")
|
||||
defaults.set(style.scanlines, forKey: "displayScanlines")
|
||||
} }
|
||||
private let defaults: UserDefaults
|
||||
init(defaults: UserDefaults) {
|
||||
self.defaults = defaults
|
||||
style = DisplayStyle(scaling: DisplayScaling(rawValue: defaults.string(forKey: "displayScaling") ?? "") ?? .smooth,
|
||||
scanlines: defaults.bool(forKey: "displayScanlines"))
|
||||
}
|
||||
}
|
||||
|
||||
// Immutable pixels and their matching active bounds, captured together before
|
||||
// the save panel opens. Encoding and file writing need no emulator commands.
|
||||
struct ScreenCapture: Sendable {
|
||||
let pixels: Data
|
||||
let area: CGRect
|
||||
enum Failure: LocalizedError {
|
||||
case noFrame, encoding
|
||||
var errorDescription: String? { self == .noFrame ? "No CoCo picture is available to save yet." : "The CoCo picture could not be encoded as a PNG." }
|
||||
}
|
||||
init(pixels: Data?, area: CGRect) throws {
|
||||
guard let pixels, pixels.count == 640 * 480 * 4 else { throw Failure.noFrame }
|
||||
self.pixels = pixels; self.area = VideoGeometry.validated(area).integral
|
||||
}
|
||||
func png() throws -> Data {
|
||||
let width = Int(area.width), height = Int(area.height)
|
||||
var rgba = Data(count: width * height * 4)
|
||||
rgba.withUnsafeMutableBytes { output in
|
||||
pixels.withUnsafeBytes { input in
|
||||
let src = input.bindMemory(to: UInt8.self), dst = output.bindMemory(to: UInt8.self)
|
||||
for y in 0..<height { for x in 0..<width {
|
||||
let i = ((Int(area.minY) + y) * 640 + Int(area.minX) + x) * 4
|
||||
let o = (y * width + x) * 4
|
||||
dst[o] = src[i+2]; dst[o+1] = src[i+1]; dst[o+2] = src[i]; dst[o+3] = 255
|
||||
} }
|
||||
}
|
||||
}
|
||||
guard let provider = CGDataProvider(data: rgba as CFData),
|
||||
let color = CGColorSpace(name: CGColorSpace.sRGB),
|
||||
let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32,
|
||||
bytesPerRow: width * 4, space: color, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) else { throw Failure.encoding }
|
||||
let data = NSMutableData()
|
||||
guard let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { throw Failure.encoding }
|
||||
CGImageDestinationAddImage(destination, image, nil)
|
||||
guard CGImageDestinationFinalize(destination) else { throw Failure.encoding }
|
||||
return data as Data
|
||||
}
|
||||
func save(to url: URL) throws { try png().write(to: url, options: .atomic) }
|
||||
}
|
||||
|
||||
// One layout calculation for Metal and mouse joysticks. Preserve the source
|
||||
// raster's proportions, with a small logical-point green inset on every edge.
|
||||
struct VideoGeometry {
|
||||
static let fullFrame = CGRect(x:0,y:0,width:640,height:480)
|
||||
static let border: CGFloat = 4
|
||||
static let surround = MTLClearColorMake(0.10, 0.14, 0.12, 1)
|
||||
static func validated(_ rect: CGRect) -> CGRect {
|
||||
guard [rect.origin.x,rect.origin.y,rect.width,rect.height].allSatisfy({ $0.isFinite }),
|
||||
rect.width > 0, rect.height > 0 else { return fullFrame }
|
||||
let clipped = rect.intersection(fullFrame)
|
||||
return clipped.isNull || clipped.isEmpty ? fullFrame : clipped
|
||||
}
|
||||
static func picture(in size: CGSize, source: CGRect, inset: CGFloat = border, scaling: DisplayScaling = .sharp) -> CGRect {
|
||||
let source = validated(source)
|
||||
let available = CGSize(width:max(0,size.width-2*inset),height:max(0,size.height-2*inset))
|
||||
let fit = min(available.width/source.width,available.height/source.height)
|
||||
let scale = scaling == .integer && fit >= 1 ? floor(fit) : fit
|
||||
let width = source.width*scale, height = source.height*scale
|
||||
let x = (size.width-width)/2, y = (size.height-height)/2
|
||||
return CGRect(x:scaling == .integer && fit >= 1 ? floor(x) : x,
|
||||
y:scaling == .integer && fit >= 1 ? floor(y) : y,width:width,height:height)
|
||||
}
|
||||
static func mouse(_ point: CGPoint, in size: CGSize, source: CGRect,
|
||||
scaling: DisplayScaling = .sharp, backing: CGFloat = 1,
|
||||
drawableSize: CGSize? = nil) -> CGPoint? {
|
||||
guard size.width > 0, size.height > 0 else { return nil }
|
||||
let physical = drawableSize ?? CGSize(width:size.width*max(1,backing),height:size.height*max(1,backing))
|
||||
guard physical.width > 0, physical.height > 0 else { return nil }
|
||||
// Use the actual drawable dimensions: fractional SwiftUI layouts can
|
||||
// round backing pixels differently from bounds * screen scale.
|
||||
let r = picture(in:physical,source:source,inset:border*physical.width/size.width,scaling:scaling)
|
||||
// Metal's viewport starts at the top; AppKit mouse coordinates at bottom.
|
||||
let pixel = CGPoint(x:point.x*physical.width/size.width,y:(size.height-point.y)*physical.height/size.height)
|
||||
guard r.width > 0, r.height > 0, r.contains(pixel) else { return nil }
|
||||
return CGPoint(x:(pixel.x-r.minX)/r.width,y:(pixel.y-r.minY)/r.height)
|
||||
}
|
||||
}
|
||||
|
||||
// All CPU-side access is on the main thread. Each submission owns its upload
|
||||
// texture until the GPU finishes; no texture is overwritten while in flight.
|
||||
final class MetalRenderer {
|
||||
let device: MTLDevice
|
||||
private let queue: MTLCommandQueue
|
||||
private let pipeline: MTLRenderPipelineState
|
||||
private let inFlight = DispatchSemaphore(value: 3)
|
||||
enum Failure: LocalizedError {
|
||||
case unavailable, shaders, resources
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .unavailable: return "Metal is unavailable on this Mac."
|
||||
case .shaders: return "The app’s display shaders could not be loaded. Rebuild the app in Xcode."
|
||||
case .resources: return "The Mac could not allocate the display resources."
|
||||
}
|
||||
}
|
||||
}
|
||||
static func library(device: MTLDevice, bundle: Bundle) throws -> MTLLibrary {
|
||||
guard let url = bundle.url(forResource: "DisplayShader", withExtension: "txt") else { throw Failure.shaders }
|
||||
return try device.makeLibrary(source: String(contentsOf: url, encoding: .utf8), options: nil)
|
||||
}
|
||||
init(device: MTLDevice, library: MTLLibrary) throws {
|
||||
self.device = device
|
||||
guard let queue = device.makeCommandQueue() else { throw Failure.resources }
|
||||
self.queue = queue
|
||||
let descriptor = MTLRenderPipelineDescriptor()
|
||||
descriptor.vertexFunction = library.makeFunction(name: "vccVertex")
|
||||
descriptor.fragmentFunction = library.makeFunction(name: "vccFragment")
|
||||
guard descriptor.vertexFunction != nil, descriptor.fragmentFunction != nil else { throw Failure.shaders }
|
||||
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
|
||||
pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
|
||||
}
|
||||
func encode(pixels: Data?, target: MTLTexture, drawable: CAMetalDrawable? = nil, activeArea: CGRect = VideoGeometry.fullFrame, inset: CGFloat = VideoGeometry.border, style: DisplayStyle = DisplayStyle()) throws -> MTLCommandBuffer? {
|
||||
guard inFlight.wait(timeout: .now()) == .success else { return nil }
|
||||
var submitted = false
|
||||
defer { if !submitted { inFlight.signal() } }
|
||||
guard let command = queue.makeCommandBuffer() else { throw Failure.resources }
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = target
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
pass.colorAttachments[0].clearColor = VideoGeometry.surround
|
||||
var source: MTLTexture?
|
||||
if let pixels, pixels.count == 640 * 480 * 4 {
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm,
|
||||
width: 640, height: 480, mipmapped: false)
|
||||
descriptor.storageMode = device.hasUnifiedMemory ? .shared : .managed; descriptor.usage = .shaderRead
|
||||
guard let texture = device.makeTexture(descriptor: descriptor) else { throw Failure.resources }
|
||||
pixels.withUnsafeBytes { data in
|
||||
texture.replace(region: MTLRegionMake2D(0, 0, 640, 480), mipmapLevel: 0,
|
||||
withBytes: data.baseAddress!, bytesPerRow: 640 * 4)
|
||||
}
|
||||
source = texture
|
||||
}
|
||||
guard let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { throw Failure.resources }
|
||||
if let source, CGFloat(target.width) > 2*inset, CGFloat(target.height) > 2*inset {
|
||||
let crop = VideoGeometry.validated(activeArea)
|
||||
let r = VideoGeometry.picture(in:CGSize(width:target.width,height:target.height),source:crop,inset:inset,scaling:style.scaling)
|
||||
encoder.setViewport(MTLViewport(originX:Double(r.minX),originY:Double(r.minY),width:Double(r.width),height:Double(r.height),znear:0,zfar:1))
|
||||
var region = SIMD4<Float>(Float(crop.minX/640),Float(crop.minY/480),Float(crop.width/640),Float(crop.height/480))
|
||||
encoder.setFragmentBytes(®ion,length:MemoryLayout<SIMD4<Float>>.stride,index:0)
|
||||
// Fade out at small sizes, where scanlines would alias or hide rows.
|
||||
let strength: Float = style.scanlines ? 0.25 * Float(min(1,max(0,r.height/crop.height-1))) : 0
|
||||
var effects = SIMD2<Float>(style.scaling == .smooth ? 1 : 0, strength)
|
||||
encoder.setFragmentBytes(&effects,length:MemoryLayout<SIMD2<Float>>.stride,index:1)
|
||||
encoder.setRenderPipelineState(pipeline)
|
||||
encoder.setFragmentTexture(source, index: 0)
|
||||
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
|
||||
}
|
||||
encoder.endEncoding()
|
||||
if let drawable { command.present(drawable) }
|
||||
let semaphore = inFlight
|
||||
command.addCompletedHandler { _ in semaphore.signal() }
|
||||
command.commit(); submitted = true
|
||||
return command
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import Combine
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
// Text is an interpretation of the captured bytes, never their replacement.
|
||||
// Classic BASIC can send seven data bits; its stop bit appears as bit 7 in
|
||||
// the original VCC write-sampled decoder. Raw export always keeps that bit.
|
||||
enum PrinterText {
|
||||
static let previewLimit = 65_536
|
||||
static func decode(_ data: Data, sevenBit: Bool) -> String {
|
||||
var result = ""
|
||||
result.reserveCapacity(data.count)
|
||||
var carriageReturn = false
|
||||
for raw in data {
|
||||
let byte = sevenBit ? raw & 0x7f : raw
|
||||
if byte == 10 && carriageReturn { carriageReturn = false; continue }
|
||||
carriageReturn = byte == 13
|
||||
switch byte {
|
||||
case 13, 10: result.append("\n")
|
||||
case 9: result.append("\t")
|
||||
case 32...126: result.append(Character(UnicodeScalar(byte)))
|
||||
case 12: result.append("\n⟨FF⟩\n")
|
||||
case 27: result.append("⟨ESC⟩")
|
||||
default: result.append(String(format: "⟨%02X⟩", Int(byte)))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
static func export(_ bytes: Data, raw: Bool, sevenBit: Bool) -> Data {
|
||||
raw ? bytes : Data(decode(bytes, sevenBit: sevenBit).utf8)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PrinterModel: ObservableObject {
|
||||
@Published private(set) var enabled = false
|
||||
@Published private(set) var byteCount = 0
|
||||
@Published private(set) var dropped: UInt64 = 0
|
||||
@Published private(set) var preview = ""
|
||||
@Published private(set) var busy = false
|
||||
@Published private(set) var saving = false
|
||||
@Published private(set) var unsaved = false
|
||||
@Published var sevenBit = true { didSet { updatePreview() } }
|
||||
@Published var followOutput = true
|
||||
@Published var error: String?
|
||||
private let controller: VCCMachineController
|
||||
private var revision: UInt64 = 0
|
||||
private var savedRevision: UInt64 = 0
|
||||
private var loadedRevision: UInt64 = .max
|
||||
private var fetching = false
|
||||
private var bytes = Data()
|
||||
var previewIsTruncated: Bool { byteCount > PrinterText.previewLimit }
|
||||
init(controller: VCCMachineController) { self.controller = controller }
|
||||
|
||||
// Called by the existing machine poll. No per-frame byte copies or view
|
||||
// invalidation: output is fetched only after its revision actually changes.
|
||||
func observe(_ snapshot: VCCMachineSnapshot) {
|
||||
if enabled != snapshot.printerEnabled { enabled = snapshot.printerEnabled }
|
||||
if byteCount != Int(snapshot.printerByteCount) { byteCount = Int(snapshot.printerByteCount) }
|
||||
if dropped != snapshot.printerDroppedBytes { dropped = snapshot.printerDroppedBytes }
|
||||
revision = snapshot.printerRevision
|
||||
let dirty = byteCount > 0 && revision != savedRevision
|
||||
if unsaved != dirty { unsaved = dirty }
|
||||
refreshIfNeeded()
|
||||
}
|
||||
private func refreshIfNeeded() {
|
||||
guard !fetching, loadedRevision != revision else { return }
|
||||
fetching = true
|
||||
controller.printerOutput { [weak self] output, snapshot in
|
||||
MainActor.assumeIsolated {
|
||||
guard let self else { return }
|
||||
self.fetching = false
|
||||
self.bytes = output.bytes; self.loadedRevision = output.revision
|
||||
self.updatePreview(); self.observe(snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
private func updatePreview() {
|
||||
let text = PrinterText.decode(Data(bytes.suffix(PrinterText.previewLimit)), sevenBit: sevenBit)
|
||||
if preview != text { preview = text }
|
||||
}
|
||||
func setCapture(_ value: Bool) {
|
||||
guard !busy else { return }
|
||||
busy = true; error = nil
|
||||
controller.setPrinterEnabled(value) { [weak self] snapshot in
|
||||
MainActor.assumeIsolated {
|
||||
self?.observe(snapshot); self?.busy = false; self?.error = snapshot.errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
func clear() {
|
||||
guard !busy, !saving else { return }
|
||||
let alert = NSAlert()
|
||||
alert.messageText = "Clear printer output?"
|
||||
alert.informativeText = "This removes the captured output from this session. Save Text or Export Raw Bytes first to keep it. Capture will stop; the CoCo keeps running."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Clear Output")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return }
|
||||
busy = true; error = nil
|
||||
// Both commands are queued in order, so a guest write cannot refill the
|
||||
// cleared capture between the clear acknowledgement and the next poll.
|
||||
controller.setPrinterEnabled(false) { _ in }
|
||||
controller.clearPrinterOutput { [weak self] snapshot in
|
||||
MainActor.assumeIsolated {
|
||||
guard let self else { return }
|
||||
self.savedRevision = snapshot.printerRevision
|
||||
self.observe(snapshot); self.busy = false; self.error = snapshot.errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
private func capture(_ completion: @escaping (VCCPrinterOutput) -> Void) {
|
||||
controller.printerOutput { [weak self] output, snapshot in
|
||||
MainActor.assumeIsolated { self?.observe(snapshot); completion(output) }
|
||||
}
|
||||
}
|
||||
func copy() {
|
||||
let sevenBit = sevenBit
|
||||
capture { output in
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(PrinterText.decode(output.bytes, sevenBit: sevenBit), forType: .string)
|
||||
}
|
||||
}
|
||||
func save(raw: Bool) {
|
||||
guard !saving else { return }
|
||||
saving = true; error = nil
|
||||
let sevenBit = sevenBit
|
||||
capture { [weak self] output in
|
||||
guard let self else { return }
|
||||
let data = PrinterText.export(output.bytes, raw: raw, sevenBit: sevenBit)
|
||||
let panel = NSSavePanel()
|
||||
panel.title = raw ? "Export Raw Printer Bytes" : "Save Printer Text"
|
||||
panel.message = "Saves the output captured when you chose this command. New output continues collecting separately."
|
||||
panel.nameFieldStringValue = raw ? "CoCo Printer Output.bin" : "CoCo Printer Output.txt"
|
||||
panel.allowedContentTypes = raw ? [.data] : [.plainText]
|
||||
panel.canCreateDirectories = true
|
||||
panel.begin { [weak self] response in
|
||||
guard let self else { return }
|
||||
guard response == .OK, let url = panel.url else { self.saving = false; return }
|
||||
Task { @MainActor in
|
||||
defer { self.saving = false }
|
||||
do {
|
||||
try await Task.detached(priority: .userInitiated) { try data.write(to: url, options: .atomic) }.value
|
||||
self.savedRevision = output.revision
|
||||
self.unsaved = self.byteCount > 0 && self.revision != self.savedRevision
|
||||
} catch { self.error = "Could not save printer output: \(error.localizedDescription)" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func printOutput() {
|
||||
let window = NSApp.keyWindow
|
||||
let sevenBit = sevenBit
|
||||
capture { output in
|
||||
let info = NSPrintInfo.shared.copy() as! NSPrintInfo
|
||||
info.topMargin = 36; info.bottomMargin = 36; info.leftMargin = 36; info.rightMargin = 36
|
||||
info.horizontalPagination = .fit; info.verticalPagination = .automatic
|
||||
info.isVerticallyCentered = false
|
||||
let width = max(100, info.paperSize.width - info.leftMargin - info.rightMargin)
|
||||
let text = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: 1))
|
||||
text.isVerticallyResizable = true
|
||||
text.textContainer?.containerSize = NSSize(width: width, height: .greatestFiniteMagnitude)
|
||||
text.textContainer?.widthTracksTextView = true
|
||||
text.font = .monospacedSystemFont(ofSize: 10, weight: .regular)
|
||||
text.textColor = .black; text.backgroundColor = .white
|
||||
text.string = PrinterText.decode(output.bytes, sevenBit: sevenBit)
|
||||
if let container = text.textContainer, let layout = text.layoutManager {
|
||||
layout.ensureLayout(for: container)
|
||||
text.setFrameSize(NSSize(width: width, height: max(1, layout.usedRect(for: container).height + 12)))
|
||||
}
|
||||
let operation = NSPrintOperation(view: text, printInfo: info)
|
||||
operation.jobTitle = "CoCo Printer Output"
|
||||
if let window { operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil) }
|
||||
else { operation.run() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PrinterOutputView: View {
|
||||
@ObservedObject var printer: PrinterModel
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
SecondaryHeader(title: "Tandy Thermal Printer TP-10", badge: "printer",
|
||||
subtitle: "Printer output from the CoCo’s serial port").padding(20)
|
||||
Divider()
|
||||
HStack(spacing: 12) {
|
||||
Button { printer.setCapture(!printer.enabled) } label: {
|
||||
Label(printer.enabled ? "Stop Capture" : "Start Capture", systemImage: printer.enabled ? "stop.fill" : "record.circle")
|
||||
}.disabled(printer.busy).accessibilityIdentifier("printer-capture")
|
||||
Spacer()
|
||||
SecondaryAction(title: "Copy", systemImage: "doc.on.doc", action: printer.copy)
|
||||
SecondaryAction(title: "Save Text…", systemImage: "square.and.arrow.up") { printer.save(raw: false) }
|
||||
.disabled(printer.saving).accessibilityIdentifier("printer-save-text")
|
||||
SecondaryAction(title: "Print…", systemImage: "printer", action: printer.printOutput)
|
||||
.accessibilityIdentifier("printer-print")
|
||||
}.padding(16)
|
||||
PrinterTextView(text: printer.preview, follow: printer.followOutput)
|
||||
.overlay(alignment: .topLeading) {
|
||||
if printer.byteCount == 0 {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text(printer.enabled ? "Waiting for printer output…" : "Ready to capture printer output").font(.headline)
|
||||
Text("Start Capture, then use PRINT #-2, \"HELLO WORLD\" or LLIST in CoCo BASIC.")
|
||||
.font(.callout).foregroundStyle(.secondary)
|
||||
}.padding(20).allowsHitTesting(false)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
HStack {
|
||||
Label(printer.enabled ? "Capturing" : "Capture stopped", systemImage: printer.enabled ? "record.circle" : "stop.circle")
|
||||
Text("\(printer.byteCount.formatted()) bytes\(printer.unsaved ? " · Not saved" : "")")
|
||||
.accessibilityIdentifier("printer-output-status")
|
||||
Spacer()
|
||||
Toggle("Follow Output", isOn: $printer.followOutput)
|
||||
}.font(.caption).padding(.horizontal, 16).padding(.vertical, 10)
|
||||
if printer.previewIsTruncated {
|
||||
Text("Showing the latest 64 KiB. Copy, Save and Print include all captured output.")
|
||||
.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16)
|
||||
}
|
||||
if printer.dropped > 0 {
|
||||
Label("Capture is full (1 MiB). \(printer.dropped.formatted()) additional bytes were not retained. Stop, save and clear to start a new capture.", systemImage: "exclamationmark.triangle")
|
||||
.font(.callout).foregroundStyle(.orange).padding(.horizontal, 16)
|
||||
}
|
||||
if let error = printer.error { Text(error).foregroundStyle(.red).textSelection(.enabled).padding(.horizontal, 16) }
|
||||
Divider()
|
||||
HStack {
|
||||
Toggle("7-bit BASIC Text", isOn: $printer.sevenBit)
|
||||
.help("Ignore the high bit for text only. Raw export always preserves every captured byte.")
|
||||
Spacer()
|
||||
SecondaryAction(title: "Export Raw Bytes…", systemImage: "doc.badge.gearshape") { printer.save(raw: true) }
|
||||
.disabled(printer.saving).accessibilityIdentifier("printer-save-raw")
|
||||
SecondaryAction(title: "Clear…", systemImage: "trash", action: printer.clear)
|
||||
.disabled(printer.busy || printer.saving || printer.byteCount == 0).accessibilityIdentifier("printer-clear")
|
||||
}.padding(16)
|
||||
SecondaryHelp(title: "Using printer output") {
|
||||
Text("Start capture before printing. Closing this window keeps capture and output; quitting requires saving or discarding unsaved output. Clear stops capture without restarting the CoCo.")
|
||||
Text("Text converts carriage returns to new lines. Control codes appear as ⟨ESC⟩, ⟨FF⟩ or hexadecimal markers. This is a text capture, not TP-10 graphics emulation. Raw export is unchanged.")
|
||||
Text("The serial output shares a PIA register with other CoCo hardware. Capture only while printing; other software can generate unrelated data. For DriveWire TCP connections, use the FD-502 Becker port in Machine Settings.")
|
||||
}.padding(.horizontal, 20).padding(.bottom, 16)
|
||||
}.frame(minWidth: 720, minHeight: 540)
|
||||
}
|
||||
}
|
||||
|
||||
// An existing selection and scroll position survive every live refresh. The
|
||||
// native read-only text view provides keyboard selection, Copy and VoiceOver.
|
||||
private struct PrinterTextView: NSViewRepresentable {
|
||||
let text: String
|
||||
let follow: Bool
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSScrollView()
|
||||
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true
|
||||
scroll.borderType = .bezelBorder
|
||||
let view = NSTextView(frame: scroll.contentView.bounds)
|
||||
view.isEditable = false; view.isSelectable = true
|
||||
view.font = .monospacedSystemFont(ofSize: 13, weight: .regular)
|
||||
view.textContainerInset = NSSize(width: 12, height: 12)
|
||||
view.isVerticallyResizable = true; view.isHorizontallyResizable = true
|
||||
view.autoresizingMask = [.width]
|
||||
view.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||
view.textContainer?.containerSize = view.maxSize
|
||||
view.textContainer?.widthTracksTextView = false
|
||||
view.setAccessibilityLabel("Captured printer output")
|
||||
view.setAccessibilityIdentifier("printer-text")
|
||||
scroll.documentView = view
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let view = scroll.documentView as? NSTextView, view.string != text else { return }
|
||||
let range = view.selectedRange(), origin = scroll.contentView.bounds.origin
|
||||
view.string = text
|
||||
let length = (text as NSString).length
|
||||
let start = min(range.location, length)
|
||||
view.setSelectedRange(NSRange(location: start, length: min(range.length, length - start)))
|
||||
if follow { view.scrollRangeToVisible(NSRange(location: length, length: 0)) }
|
||||
else { scroll.contentView.scroll(to: origin); scroll.reflectScrolledClipView(scroll.contentView) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct ProfileControlsView: View {
|
||||
private static let profileType = UTType(exportedAs: "com.brianholman.vccplus.mac.configuration-profile", conformingTo: .json)
|
||||
private static let legacyProfileType = UTType(importedAs: "org.vcc.mac.configuration-profile", conformingTo: .json)
|
||||
@ObservedObject var machine: MachineModel
|
||||
@StateObject private var library: ProfileLibrary
|
||||
init(machine: MachineModel, store: ProfileStore = .standard) {
|
||||
self.machine = machine
|
||||
_library = StateObject(wrappedValue: ProfileLibrary(store: store))
|
||||
}
|
||||
@State private var selection: String? = SystemProfile.diskBasic.id
|
||||
@State private var working = false
|
||||
private var selected: ConfigurationProfile? { library.profiles.first { $0.id.uuidString == selection } }
|
||||
private var selectedSystem: SystemProfile? { SystemProfile.allCases.first { $0.id == selection } }
|
||||
private var unavailable: Bool { working || machine.busy || machine.state == .closed }
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
SecondaryHeader(title: "Configuration Profiles", symbol: "square.grid.2x2", subtitle: "Named setups and file locations — not saved machine snapshots.")
|
||||
HStack {
|
||||
Button(action: saveCurrent) { Label("Save Current As…", systemImage: "doc.badge.plus") }
|
||||
Button(action: importProfile) { Label("Import…", systemImage: "folder") }
|
||||
Spacer()
|
||||
Button(action: library.reload) { Label("Refresh", systemImage: "arrow.clockwise") }
|
||||
}.disabled(unavailable)
|
||||
}.padding(20)
|
||||
Divider()
|
||||
HSplitView {
|
||||
List(selection: $selection) {
|
||||
Section("System Profiles") {
|
||||
ForEach(SystemProfile.allCases) { profile in
|
||||
Label(profile.name, systemImage: "lock.fill").tag(profile.id)
|
||||
.accessibilityIdentifier(profile.id)
|
||||
}
|
||||
}
|
||||
Section("My Profiles") {
|
||||
ForEach(library.profiles) { profile in
|
||||
Label(profile.name, systemImage: "doc.text").tag(profile.id.uuidString)
|
||||
}
|
||||
}
|
||||
}.listStyle(.sidebar).frame(minWidth: 175, idealWidth: 220, maxWidth: 280)
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
if let kind = selectedSystem { systemDetails(kind) }
|
||||
else if let profile = selected { personalDetails(profile) }
|
||||
else {
|
||||
Label("Select a profile", systemImage: "square.grid.2x2").font(.title2)
|
||||
Text(library.profiles.isEmpty ? "Save your current setup to create the first personal profile." : "Select a profile to review its setup and files.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).padding(20)
|
||||
}.frame(minWidth: 380)
|
||||
}.frame(minHeight: 260).disabled(unavailable)
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
if let error = library.error ?? machine.profileError {
|
||||
ScrollView {
|
||||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.frame(maxHeight: 100)
|
||||
}
|
||||
HStack(spacing: 12) {
|
||||
if working || machine.busy { ProgressView().controlSize(.small) }
|
||||
if let name = machine.profileName {
|
||||
Text("Last loaded: \(name)").font(.caption).foregroundStyle(.secondary)
|
||||
.lineLimit(1).truncationMode(.middle)
|
||||
.help("Later changes do not update the saved profile automatically.")
|
||||
} else {
|
||||
Text(selectedSystem != nil ? "System profiles are read-only." : "Load replaces the current setup and clears RAM.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
if selected != nil { personalActions.disabled(unavailable) }
|
||||
Button(action: loadSelected) { Label("Load…", systemImage: "arrow.clockwise") }
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(unavailable || (selected == nil && selectedSystem == nil) ||
|
||||
selectedSystem.map { machine.systemProfileUnavailableReason($0) != nil } == true)
|
||||
}
|
||||
}.padding(16)
|
||||
}.frame(minWidth: 740, minHeight: 540)
|
||||
}
|
||||
@ViewBuilder private var personalActions: some View {
|
||||
if let profile = selected {
|
||||
ProfileActionsMenu(profileID: profile.id, update: updateSelected, rename: renameSelected,
|
||||
export: exportSelected, delete: deleteSelected).equatable()
|
||||
}
|
||||
}
|
||||
private func systemDetails(_ kind: SystemProfile) -> some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Label(kind.name, systemImage: "lock.fill").font(.title2.bold())
|
||||
Text(kind.summary).foregroundStyle(.secondary)
|
||||
}
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label("Setup", systemImage: "cpu").font(.headline)
|
||||
Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) {
|
||||
summaryRow("Hardware", "Motorola 6809 · 512 KB")
|
||||
summaryRow("Video", "Composite TV")
|
||||
summaryRow("Startup", kind == .cocoSDC ? "Slot 4 · SDC-DOS" : kind == .diskBasic ? "Slot 4 · Disk BASIC" : "Slot 4 · RGBDOS")
|
||||
Divider().gridCellColumns(2).gridCellUnsizedAxes(.horizontal).padding(.vertical, 4)
|
||||
if kind == .cocoSDC {
|
||||
summaryRow("SD card", "Local writable folder · CoCo SDC")
|
||||
summaryRow("SDC0", "HELLO.DSK · mounted at startup")
|
||||
} else { summaryRow("FD0", "Hello World floppy") }
|
||||
if kind == .hardDriveBasic || kind == .nitros9 {
|
||||
summaryRow("HD0", kind == .nitros9 ? "NitrOS-9 system disk" : "Hello World hard disk")
|
||||
}
|
||||
if kind == .nitros9 { summaryRow("HD1", "Shared Hard Drive BASIC disk") }
|
||||
if kind == .diskBasic { summaryRow("Cassette", "Hello World · stopped") }
|
||||
}
|
||||
SecondaryHelp(title: "Setup details") { Text(kind.explanation) }
|
||||
}
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Label(kind == .nitros9 ? "Load restarts and automatically boots NitrOS-9." : "Load restarts BASIC with an empty program. Examples do not run automatically.", systemImage: "arrow.clockwise")
|
||||
.font(.callout).fixedSize(horizontal: false, vertical: true)
|
||||
Text(kind == .nitros9 ? "Existing data is kept. An empty shared OS-9 area is initialized with a backup." : kind == .diskBasic ? "Your writable media is preserved. This is the same setup as Restore App Defaults." : "Your writable media is preserved.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if let reason = machine.systemProfileUnavailableReason(kind) {
|
||||
Label(reason, systemImage: "exclamationmark.triangle").foregroundStyle(.orange)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label("Make it yours", systemImage: "doc.on.doc").font(.headline)
|
||||
ViewThatFits(in: .horizontal) {
|
||||
HStack(alignment: .top, spacing: 16) {
|
||||
copyChoice(kind, freshMedia: false).frame(width: 180, alignment: .leading)
|
||||
copyChoice(kind, freshMedia: true).frame(width: 230, alignment: .leading)
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
copyChoice(kind, freshMedia: false)
|
||||
copyChoice(kind, freshMedia: true)
|
||||
}
|
||||
}
|
||||
Text("Both create an editable personal profile. Existing files and the current session stay unchanged; load the new profile when ready.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
SecondaryHelp(title: kind == .nitros9 ? "Using NitrOS-9" : "Try the examples") {
|
||||
if kind == .nitros9 { Nitros9UsageGuide() }
|
||||
else if kind == .cocoSDC { SDCUsageGuide() }
|
||||
else { Text(kind.instructions).textSelection(.enabled) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func summaryRow(_ title: String, _ value: String) -> some View {
|
||||
GridRow(alignment: .firstTextBaseline) {
|
||||
Text(title).foregroundStyle(.secondary)
|
||||
Text(value).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
private func copyChoice(_ kind: SystemProfile, freshMedia: Bool) -> some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Button { copySystem(kind, freshMedia: freshMedia) } label: {
|
||||
Label(freshMedia ? "Create Fresh Starter Media…" : "Save as My Profile…",
|
||||
systemImage: freshMedia ? "doc.badge.plus" : "doc.on.doc")
|
||||
}.fixedSize().accessibilityIdentifier(freshMedia ? "fresh-system-media" : "copy-system-profile")
|
||||
.disabled(machine.systemProfileUnavailableReason(kind) != nil)
|
||||
Text(freshMedia ? "New, clean media copies." : "The same working media files.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
private func personalDetails(_ profile: ConfigurationProfile) -> some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Label(profile.name, systemImage: "doc.text").font(.title2.bold())
|
||||
Text(ProfileGuidance(profile).title).foregroundStyle(.secondary)
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Setup", systemImage: "cpu").font(.headline)
|
||||
Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) {
|
||||
summaryRow("Processor", profile.machine.use6309 ? "Hitachi 6309" : "Motorola 6809")
|
||||
summaryRow("Memory", MachineSettings.memoryLabels[profile.machine.ram])
|
||||
summaryRow("CPU overclock", "\(profile.machine.overclock)×")
|
||||
summaryRow("Pacing", profile.machine.fastForward ? "Fast-forward · playback silenced" : "Normal")
|
||||
summaryRow("Cartridges", profile.media.cartridges?.multiPak == true ? "Multi-Pak" : "Single cartridge")
|
||||
}
|
||||
Text(ProfileGuidance(profile).coverage).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
if profile.systemROM == nil {
|
||||
Label("No system ROM assigned. Choose one after loading this setup.", systemImage: "exclamationmark.triangle")
|
||||
.foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if profile.bootNitros9 == true {
|
||||
Label("After Run, this profile automatically boots NitrOS-9 with DOS 255. Cold Restart opens the archive menu; select 6 (EXIT TO BASIC) and press Return.", systemImage: "info.circle")
|
||||
.font(.callout).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
SecondaryCard {
|
||||
Label("Files", systemImage: "folder").font(.headline)
|
||||
if profile.references.isEmpty { Text("No files assigned.").foregroundStyle(.secondary) }
|
||||
ForEach(profile.references, id: \.key) { reference in
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(reference.key.label).font(.caption).foregroundStyle(.secondary)
|
||||
Text(reference.url.lastPathComponent).lineLimit(1).truncationMode(.middle)
|
||||
Text(reference.url.path).font(.caption).foregroundStyle(.secondary)
|
||||
.lineLimit(1).truncationMode(.middle).textSelection(.enabled).help(reference.url.path)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Button { replace(reference.key, in: profile) } label: { Label("Replace…", systemImage: "folder") }
|
||||
.accessibilityLabel("Replace \(reference.key.label)")
|
||||
}
|
||||
}
|
||||
Text("Replace updates this saved profile's file location. Load the profile to apply it; files are not copied.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
SecondaryHelp(title: "About this configuration") {
|
||||
Text(ProfileGuidance(profile).explanation).fixedSize(horizontal: false, vertical: true)
|
||||
Text("Later changes do not update the saved profile automatically. Use Actions → Update from Current to replace its saved setup.")
|
||||
}
|
||||
}
|
||||
}
|
||||
private func namePrompt(_ title: String, initial: String) -> String? {
|
||||
let alert = NSAlert(); alert.messageText = title
|
||||
let field = NSTextField(string: initial); field.frame = NSRect(x: 0, y: 0, width: 320, height: 24)
|
||||
field.setAccessibilityIdentifier("profile-name")
|
||||
alert.accessoryView = field; alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel")
|
||||
alert.window.initialFirstResponder = field
|
||||
guard alert.runModal() == .alertFirstButtonReturn else { return nil }
|
||||
return field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
private func confirm(_ title: String, detail: String, action: String) -> Bool {
|
||||
let alert = NSAlert(); alert.messageText = title; alert.informativeText = detail
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: action)
|
||||
return alert.runModal() == .alertSecondButtonReturn
|
||||
}
|
||||
private func saveCurrent() {
|
||||
guard let name = namePrompt("Save Current Setup as Profile", initial: "") else { return }
|
||||
capture(name: name, id: nil)
|
||||
}
|
||||
private func capture(name: String, id: UUID?) {
|
||||
working = true
|
||||
Task { @MainActor in
|
||||
defer { working = false }
|
||||
do {
|
||||
let profile = try await machine.captureProfile(name: name, replacing: id)
|
||||
if library.save(profile) { selection = profile.id.uuidString }
|
||||
} catch { library.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private func copySystem(_ kind: SystemProfile, freshMedia: Bool) {
|
||||
guard let name = namePrompt(freshMedia ? "Name Setup with Fresh Starter Media" : "Save System Setup as My Profile",
|
||||
initial: "My " + kind.name), !name.isEmpty else { return }
|
||||
do { try ConfigurationProfile(name: name).validate() }
|
||||
catch { library.error = error.localizedDescription; return }
|
||||
// Check names before allocating a fresh hard disk. Never overwrite a profile.
|
||||
guard !library.profiles.contains(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else {
|
||||
library.error = "A profile with that name already exists. Choose another name."; return
|
||||
}
|
||||
working = true; library.error = nil
|
||||
Task { @MainActor in
|
||||
defer { working = false }
|
||||
do {
|
||||
var profile = try await machine.makeSystemProfile(kind, freshMedia: freshMedia)
|
||||
profile.name = name
|
||||
if library.save(profile) { selection = profile.id.uuidString }
|
||||
} catch { library.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private func loadSelected() {
|
||||
if let kind = selectedSystem {
|
||||
guard confirm("Load “\(kind.name)”?", detail: (kind == .nitros9 ? "This restarts and boots NitrOS-9. Empty OS-9 space on the shared data disk is initialized with a backup. " : "This restarts BASIC with the system setup. ") + " Current RAM and RAM disk contents are cleared. Writable disks are saved first; unsaved temporary disks or recordings block the switch. Existing starter media is reused, never erased. Neither example loads or runs automatically.", action: "Load Profile") else { return }
|
||||
library.error = nil; working = true
|
||||
Task { @MainActor in _ = await machine.loadSystemProfile(kind); working = false }
|
||||
return
|
||||
}
|
||||
guard let profile = selected,
|
||||
confirm("Load “\(profile.name)”?", detail: "This clears the current machine's RAM and RAM disk contents and replaces its setup and media. Writable disk changes will be saved first; unsaved temporary images or recordings block the switch. The new machine starts paused. Profiles are not saved-game snapshots." + (profile.bootNitros9 == true ? " Pressing Run will automatically boot NitrOS-9." : ""), action: "Load Profile") else { return }
|
||||
library.error = nil; working = true
|
||||
Task { @MainActor in await machine.loadProfile(profile); working = false }
|
||||
}
|
||||
private func updateSelected() {
|
||||
guard let profile = selected,
|
||||
confirm("Update “\(profile.name)” from the current setup?", detail: "This replaces the saved configuration and file assignments. It does not copy media contents or alter their files.", action: "Update Profile") else { return }
|
||||
capture(name: profile.name, id: profile.id)
|
||||
}
|
||||
private func renameSelected() {
|
||||
guard var profile = selected, let name = namePrompt("Rename Profile", initial: profile.name) else { return }
|
||||
profile.name = name; library.save(profile)
|
||||
}
|
||||
private func deleteSelected() {
|
||||
guard let profile = selected,
|
||||
confirm("Delete “\(profile.name)” from Profiles?", detail: "Its ROMs and media files are kept. The current machine is unchanged.", action: "Delete Profile") else { return }
|
||||
library.delete(profile.id); if library.error == nil { selection = nil }
|
||||
}
|
||||
private func replace(_ reference: ConfigurationProfile.Reference, in original: ConfigurationProfile) {
|
||||
let panel = NSOpenPanel(); panel.title = "Replace \(reference.label)"
|
||||
if case .sdcFolder = reference { panel.canChooseDirectories = true; panel.canChooseFiles = false }
|
||||
else { panel.canChooseDirectories = false; panel.canChooseFiles = true }
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
var profile = original; profile.replace(reference, with: url); library.save(profile)
|
||||
}
|
||||
}
|
||||
private func importProfile() {
|
||||
let panel = NSOpenPanel(); panel.title = "Import Configuration Profile"
|
||||
panel.allowedContentTypes = [Self.profileType, Self.legacyProfileType, .json]
|
||||
panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
do {
|
||||
var profile = try ProfileStore.read(url); profile.id = UUID()
|
||||
guard let name = namePrompt("Name Imported Profile", initial: profile.name) else { return }
|
||||
profile.name = name
|
||||
if library.save(profile) { selection = profile.id.uuidString }
|
||||
} catch { library.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private func exportSelected() {
|
||||
guard let profile = selected else { return }
|
||||
let panel = NSSavePanel(); panel.title = "Export Configuration Profile"
|
||||
panel.allowedContentTypes = [Self.profileType]
|
||||
panel.nameFieldStringValue = profile.name.replacingOccurrences(of: "/", with: "-") + ".vccprofile"
|
||||
panel.message = "The file includes local file paths and controller identifiers, but no ROM or media contents."
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
do { try ProfileStore.write(profile, to: url); library.error = nil }
|
||||
catch { library.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Frame/status updates must not replace an open menu. The selected profile is
|
||||
// its identity; commands still read the authoritative library and machine state.
|
||||
private struct ProfileActionsMenu: View, Equatable {
|
||||
let profileID: UUID
|
||||
let update: () -> Void
|
||||
let rename: () -> Void
|
||||
let export: () -> Void
|
||||
let delete: () -> Void
|
||||
static func == (lhs: Self, rhs: Self) -> Bool { lhs.profileID == rhs.profileID }
|
||||
var body: some View {
|
||||
Menu {
|
||||
Button(action: update) { Label("Update from Current…", systemImage: "arrow.triangle.2.circlepath") }
|
||||
Button(action: rename) { Label("Rename…", systemImage: "pencil") }
|
||||
Button(action: export) { Label("Export…", systemImage: "square.and.arrow.up") }
|
||||
Divider()
|
||||
Button(role: .destructive, action: delete) { Label("Delete…", systemImage: "trash") }
|
||||
} label: { Label("Actions", systemImage: "ellipsis.circle") }
|
||||
.fixedSize().accessibilityIdentifier("profile-actions")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
|
||||
enum ROMImage {
|
||||
enum Failure: LocalizedError {
|
||||
case notFile, size, resetVector
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .notFile: return "Choose a regular CoCo 3 ROM file."
|
||||
case .size: return "Choose a 32 KiB CoCo 3 system ROM. This file has a different size."
|
||||
case .resetVector: return "This file does not have a valid CoCo 3 ROM reset address."
|
||||
}
|
||||
}
|
||||
}
|
||||
static func validate(_ bytes: Data) throws {
|
||||
guard bytes.count == 32768 else { throw Failure.size }
|
||||
let start = Int(bytes[bytes.startIndex + 32766]) * 256 + Int(bytes[bytes.startIndex + 32767])
|
||||
guard (0x8000...0xfeff).contains(start) else { throw Failure.resetVector }
|
||||
}
|
||||
static func read(_ url: URL) throws -> Data {
|
||||
guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw Failure.notFile }
|
||||
let file = try FileHandle(forReadingFrom: url)
|
||||
defer { try? file.close() }
|
||||
// Read at most the allowed size plus one byte, even for huge input files.
|
||||
let bytes = try file.read(upToCount: 32769) ?? Data()
|
||||
try validate(bytes)
|
||||
return bytes
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user