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

120 lines
6.2 KiB
Swift

// 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
}
}