311 lines
18 KiB
Swift
311 lines
18 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
import CryptoKit
|
|
|
|
enum AppIdentity {
|
|
static let bundleID = "com.brianholman.vccplus.oss.mac"
|
|
// VCC Plus starts independently; no automatic import of legacy settings.
|
|
static var supportDirectory: URL {
|
|
supportDirectory(in: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0])
|
|
}
|
|
static func supportDirectory(in parent: URL) -> URL {
|
|
parent.appendingPathComponent(bundleID, isDirectory: true)
|
|
}
|
|
}
|
|
|
|
// Built-in definitions are separate from the editable profile library.
|
|
enum SystemProfile: String, CaseIterable, Identifiable, Sendable {
|
|
case diskBasic, hardDriveBasic, cocoSDC, nitros9
|
|
var id: String { "system-" + rawValue }
|
|
var name: String {
|
|
switch self { case .diskBasic: return "Disk BASIC"; case .hardDriveBasic: return "Hard Drive BASIC"; case .nitros9: return "NitrOS-9 L2 V3.3.0"; case .cocoSDC: return "CoCo SDC" }
|
|
}
|
|
var diskROMName: String { self == .cocoSDC ? "sdcdos.rom" : self == .diskBasic ? "disk11.rom" : "rgbdos.rom" }
|
|
var summary: String {
|
|
switch self {
|
|
case .cocoSDC: return "Local SD card folder with Hello World mounted in drive 0"
|
|
case .diskBasic: return "Default disk and cassette loaded"
|
|
case .hardDriveBasic: return "Default hard disk and floppy loaded"
|
|
case .nitros9: return "Automatic OS-9 boot, with shared data disk in HD1"
|
|
}
|
|
}
|
|
var explanation: String {
|
|
switch self {
|
|
case .cocoSDC: return "6809, 512 KB, composite video, and CoCo SDC in Multi-Pak startup slot 4. A writable local SD card folder contains HELLO.DSK. Its startup.cfg mounts that disk as SDC0; the example does not load or run automatically. No floppy or hard-disk controller is needed."
|
|
case .diskBasic: return "The app's default setup: 6809, 512 KB, composite video, and the floppy controller in Multi-Pak slot 4. The Hello World floppy and stopped cassette are ready."
|
|
case .hardDriveBasic: return "6809, 512 KB, composite video, RGBDOS in Multi-Pak slot 4, and the hard-disk controller in slot 1. HD0 has 256 initialized BASIC volumes; volume 0 contains HELLO. FD0 holds the shared Hello World floppy. The cassette is ejected."
|
|
case .nitros9: return "6809, 512 KB, composite video, RGBDOS in slot 4 and the hard-disk controller in slot 1. HD0 holds the NitrOS-9 archive; HD1 is the same working disk used by Hard Drive BASIC. FD0 holds the shared Hello World floppy. Loading boots NitrOS-9 automatically."
|
|
}
|
|
}
|
|
var instructions: String {
|
|
switch self {
|
|
case .cocoSDC: return "Type DIR 0, then LOAD \"HELLO:0\" and RUN. To mount the starter disk again, type DRIVE 0,\"/HELLO.DSK\". Open the SD card folder in Finder from Cartridge Settings to add other images. Your local files are preserved when this profile is loaded again."
|
|
case .diskBasic: return "Disk: type LOAD\"HELLO\", then RUN. Tape: press Play in Cassette, type CLOAD\"HELLO\", then RUN."
|
|
case .hardDriveBasic: return "Hard disk: type LOAD\"HELLO\", then RUN. For the floppy, type DRIVE OFF before LOAD\"HELLO\". DRIVE ON returns to the hard disk. BASIC's drive numbers are virtual volumes within HD0, not the app's HD0/HD1 devices."
|
|
case .nitros9: return "At the OS-9 prompt, use dir /dd and dir /h1. Change folders with chd; list text files with list. The main window's Using your CoCo guide includes commands and archive links. Cold Restart opens the archive menu; select 6 (EXIT TO BASIC) and press Return. At BASIC, type DOS 255 to boot again."
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
// Optional private payload for development and distribution. ROMs never enter Git.
|
|
struct StarterKit: Sendable {
|
|
let directory: URL
|
|
static var bundled: Self? {
|
|
Bundle.main.url(forResource: "StarterKit", withExtension: nil).map { Self(directory: $0) }
|
|
}
|
|
private func romResource(_ name: String, in support: URL) throws -> (Data, URL) {
|
|
let source = directory.appendingPathComponent(name)
|
|
let bytes: Data
|
|
if name == "coco3.rom" { bytes = try ROMImage.read(source) }
|
|
else if name == "pic-7040-510.bin" { bytes = try DiskFiles.readSpeechChipROM(source, speech: false) }
|
|
else if name == "sp0256-al2.bin" { bytes = try DiskFiles.readSpeechChipROM(source, speech: true) }
|
|
else if name == "orch90.rom" { bytes = try DiskFiles.readOrchestraROM(source) }
|
|
else if name == "sdcdos.rom" { bytes = try DiskFiles.readSDCROM(source) }
|
|
else { bytes = try DiskFiles.readROM(source) }
|
|
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
|
// Content-addressed copies keep saved profiles valid when the .app moves
|
|
// or is upgraded. Never modify the signed bundle or an existing ROM.
|
|
return (bytes, support.appendingPathComponent("Bundled ROMs/\(digest)/\(name)"))
|
|
}
|
|
// Read-only identity lookup for contextual help; no seeding or preference changes.
|
|
func cachedROMURL(_ name: String, in support: URL) throws -> URL {
|
|
try romResource(name, in: support).1
|
|
}
|
|
func rom(_ name: String, in support: URL) throws -> URL {
|
|
let (bytes, target) = try romResource(name, in: support)
|
|
if FileManager.default.fileExists(atPath: target.path) {
|
|
guard try Data(contentsOf: target) == bytes else { throw StartupStore.Failure.changedROM }
|
|
} else {
|
|
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
try bytes.write(to: target, options: .withoutOverwriting)
|
|
}
|
|
return target
|
|
}
|
|
func seed(_ name: String, in support: URL) throws -> URL {
|
|
let source = directory.appendingPathComponent(name)
|
|
let target = support.appendingPathComponent("Starter Media/\(name)")
|
|
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
if !FileManager.default.fileExists(atPath: target.path) {
|
|
try FileManager.default.copyItem(at: source, to: target)
|
|
}
|
|
return target
|
|
}
|
|
// Publish a complete card on first use. Existing cards, including files a
|
|
// user has edited or deliberately removed, are never reseeded or replaced.
|
|
func seedSDCCard(in support: URL) throws -> URL {
|
|
let target = support.appendingPathComponent("Starter Media/CoCo SDC", isDirectory: true)
|
|
if FileManager.default.fileExists(atPath: target.path) {
|
|
try DiskFiles.validateSDCFolder(target)
|
|
return target
|
|
}
|
|
let parent = target.deletingLastPathComponent()
|
|
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
|
|
let temporary = parent.appendingPathComponent(".sdc-starter-" + UUID().uuidString, isDirectory: true)
|
|
try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: false)
|
|
defer { try? FileManager.default.removeItem(at: temporary) }
|
|
try FileManager.default.copyItem(at: directory.appendingPathComponent("Hello World.dsk"),
|
|
to: temporary.appendingPathComponent("HELLO.DSK"))
|
|
try Data("0=HELLO.DSK\n".utf8).write(to: temporary.appendingPathComponent("startup.cfg"), options: .withoutOverwriting)
|
|
try FileManager.default.moveItem(at: temporary, to: target)
|
|
return target
|
|
}
|
|
// Two small authored volumes expand into the conventional RGBDOS layout.
|
|
// An authored empty OS-9 filesystem precedes the BASIC volumes. No OS is bundled here.
|
|
func os9Header() throws -> Data {
|
|
let bytes = try Data(contentsOf: directory.appendingPathComponent("Blank OS9 Header.bin"))
|
|
guard bytes.count == 8192, bytes.prefix(3) == Data([5, 160, 0]) else {
|
|
throw ProfileFailure.message("The bundled empty OS-9 template is invalid. Existing media has been kept.")
|
|
}
|
|
return bytes
|
|
}
|
|
func seedHardDisk(in support: URL) throws -> URL {
|
|
let target = support.appendingPathComponent("Starter Media/Hello World.vhd")
|
|
if FileManager.default.fileExists(atPath: target.path) { return target }
|
|
let hello = try Data(contentsOf: directory.appendingPathComponent("Hello Hard Disk.dsk"))
|
|
let blank = try Data(contentsOf: directory.appendingPathComponent("Blank Disk.dsk"))
|
|
guard hello.count == 161280, blank.count == 161280 else { throw StartupStore.Failure.invalid }
|
|
let parent = target.deletingLastPathComponent()
|
|
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
|
|
let temporary = parent.appendingPathComponent(".hard-starter-" + UUID().uuidString)
|
|
try Data().write(to: temporary, options: .withoutOverwriting)
|
|
defer { try? FileManager.default.removeItem(at: temporary) }
|
|
let file = try FileHandle(forWritingTo: temporary)
|
|
do {
|
|
try file.write(contentsOf: os9Header())
|
|
try file.truncate(atOffset: 0x5a000 * 256)
|
|
try file.seekToEnd()
|
|
try file.write(contentsOf: hello)
|
|
for _ in 1..<256 { try file.write(contentsOf: blank) }
|
|
try file.synchronize(); try file.close()
|
|
} catch { try? file.close(); throw error }
|
|
// moveItem refuses to replace an existing working copy.
|
|
try FileManager.default.moveItem(at: temporary, to: target)
|
|
return target
|
|
}
|
|
}
|
|
|
|
struct StartupStore: Sendable {
|
|
struct Selection: Codable, Equatable {
|
|
var version = 1
|
|
var systemROM: URL?
|
|
var cassette: URL?
|
|
var bootNitros9: Bool?
|
|
// Only the built-in preset selection may establish this local startup provenance.
|
|
// Older selections and imported personal profiles have no network default.
|
|
var builtInNitros9: Bool?
|
|
func validate() throws {
|
|
guard version == 1 else { throw Failure.invalid }
|
|
let references: [URL] = [systemROM, cassette].compactMap { $0 }
|
|
for reference in references {
|
|
let host = reference.host ?? ""
|
|
guard reference.isFileURL, host.isEmpty || host == "localhost", reference.path.hasPrefix("/") else { throw Failure.invalid }
|
|
}
|
|
}
|
|
}
|
|
enum Failure: LocalizedError {
|
|
case invalid, changedROM, unavailable
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .unavailable: return "Bundled app defaults are unavailable in this build. Add the private development ROMs or choose your own system and disk ROMs."
|
|
case .invalid: return "The remembered startup selections are damaged. Choose your system ROM and cassette again. Existing media has been kept."
|
|
case .changedROM: return "A cached bundled ROM was changed. Choose a valid system or disk ROM; existing files have been kept."
|
|
}
|
|
}
|
|
}
|
|
let directory: URL
|
|
let kit: StarterKit?
|
|
var url: URL { directory.appendingPathComponent("Startup.json") }
|
|
func read() throws -> Selection? {
|
|
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
|
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
|
let data = try handle.read(upToCount: 65537) ?? Data()
|
|
guard data.count <= 65536 else { throw Failure.invalid }
|
|
let value = try JSONDecoder().decode(Selection.self, from: data)
|
|
try value.validate(); return value
|
|
}
|
|
func save(_ selection: Selection) throws {
|
|
try selection.validate()
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
try JSONEncoder().encode(selection).write(to: url, options: .atomic)
|
|
}
|
|
// Used by both first launch and explicit recovery. Seed only absent example
|
|
// files; restoring configuration must never overwrite a user's saved work.
|
|
func appDefaults() throws -> ConfigurationProfile { try systemProfile(.diskBasic) }
|
|
|
|
func unavailableReason(for kind: SystemProfile) -> String? {
|
|
guard let kit else { return Failure.unavailable.localizedDescription }
|
|
let names = ["coco3.rom", "Hello World.dsk"] + (kind == .cocoSDC ? ["sdcdos.rom"] : kind == .diskBasic
|
|
? ["disk11.rom", "Hello World.cas"] : ["rgbdos.rom", "Blank Disk.dsk", "Hello Hard Disk.dsk", "Blank OS9 Header.bin"])
|
|
+ (kind == .nitros9 ? ["NitrOS-9 L2 V3.3.0.vhd"] : [])
|
|
let missing = names.filter { !FileManager.default.fileExists(atPath: kit.directory.appendingPathComponent($0).path) }
|
|
return missing.isEmpty ? nil : "This build is missing starter resources: " + missing.joined(separator: ", ")
|
|
}
|
|
|
|
func systemProfile(_ kind: SystemProfile, freshMedia: Bool = false) throws -> ConfigurationProfile {
|
|
guard let kit else { throw Failure.unavailable }
|
|
if let reason = unavailableReason(for: kind) { throw ProfileFailure.message(reason) }
|
|
let support = freshMedia ? directory.appendingPathComponent("Starter Media Copies/" + UUID().uuidString) : directory
|
|
do {
|
|
var profile = ConfigurationProfile(name: kind.name)
|
|
profile.systemROM = try kit.rom("coco3.rom", in: directory)
|
|
var cartridges = CartridgeAssignments()
|
|
cartridges.multiPak = true; cartridges.mpiConfigured = true; cartridges.physicalSlot = 4
|
|
if kind == .cocoSDC {
|
|
cartridges.slots[4] = .init(kind: .sdc, url: try kit.rom("sdcdos.rom", in: directory),
|
|
sdcFolderURL: try kit.seedSDCCard(in: support), sdcReadOnly: false)
|
|
} else {
|
|
profile.media.rom = try kit.rom(kind.diskROMName, in: directory)
|
|
profile.media.drives[0] = .init(url: try kit.seed("Hello World.dsk", in: support), writeProtected: false)
|
|
cartridges.slots[4].kind = .floppy
|
|
}
|
|
var hard = HardDiskAssignments()
|
|
if kind == .hardDriveBasic || kind == .nitros9 {
|
|
cartridges.slots[1].kind = .hardDisk
|
|
let shared = try kit.seedHardDisk(in: support)
|
|
hard.drives[kind == .nitros9 ? 1 : 0] = .init(url: shared, writeProtected: false)
|
|
if kind == .nitros9 {
|
|
hard.drives[0] = .init(url: try kit.seed("NitrOS-9 L2 V3.3.0.vhd", in: support), writeProtected: false)
|
|
profile.bootNitros9 = true
|
|
}
|
|
} else if kind == .diskBasic {
|
|
profile.cassette = try kit.seed("Hello World.cas", in: support)
|
|
}
|
|
profile.media.cartridges = cartridges; profile.media.hardDisks = hard
|
|
try profile.validate()
|
|
return profile
|
|
} catch {
|
|
if freshMedia { try? FileManager.default.removeItem(at: support) }
|
|
throw error
|
|
}
|
|
}
|
|
|
|
// Only the app-owned shared data disk is eligible. Arbitrary imported HD1
|
|
// images are never formatted. Nonzero partitions are always preserved.
|
|
func initializeSharedOS9(for profile: ConfigurationProfile) throws -> Bool {
|
|
guard profile.bootNitros9 == true, let kit,
|
|
let drive = profile.media.hardDisks?.drives[1], !drive.writeProtected, !drive.temporary else { return false }
|
|
let target = drive.url.standardizedFileURL
|
|
let expected = directory.appendingPathComponent("Starter Media/Hello World.vhd").standardizedFileURL
|
|
guard target == expected else { return false } // Fresh copies were formatted when seeded.
|
|
guard try target.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { return false }
|
|
let image = try HardDiskFiles.readImage(target)
|
|
guard !image.readOnly, image.data.count == 135659520 else {
|
|
throw ProfileFailure.message("The shared data disk cannot be initialized. Its contents were kept; check its size and write access.")
|
|
}
|
|
guard image.data.prefix(0x5a000 * 256).allSatisfy({ $0 == 0 }) else { return false }
|
|
let header = try kit.os9Header()
|
|
let backup = target.deletingLastPathComponent().appendingPathComponent("Before OS9 initialization " + UUID().uuidString + ".vhd")
|
|
try FileManager.default.copyItem(at: target, to: backup)
|
|
guard try HardDiskFiles.readImage(backup).digest == image.digest else { throw HardDiskFiles.Failure.changed }
|
|
var patches = Data()
|
|
for sector in 0..<(header.count / 256) {
|
|
var number = UInt32(sector).littleEndian
|
|
withUnsafeBytes(of: &number) { patches.append(contentsOf: $0) }
|
|
patches.append(header[(sector * 256)..<((sector + 1) * 256)])
|
|
}
|
|
_ = try HardDiskFiles.saveAutomatically(patches, length: image.data.count, to: target, expected: image.digest)
|
|
return true
|
|
}
|
|
|
|
func prepare(diskStore: DiskAssignmentStore) throws -> Selection? {
|
|
if let existing = try read() { return existing }
|
|
guard let kit else { return nil }
|
|
var selection = Selection(systemROM: try kit.rom("coco3.rom", in: directory))
|
|
// Migrate existing installs without changing their topology or media.
|
|
// A completed marker prevents later ejections/deletions being reseeded.
|
|
if !FileManager.default.fileExists(atPath: diskStore.url.path) {
|
|
let profile = try appDefaults()
|
|
selection.cassette = profile.cassette
|
|
try diskStore.save(profile.media)
|
|
}
|
|
try save(selection)
|
|
return selection
|
|
}
|
|
}
|
|
|
|
// Explicit native release QA uses the production startup path in an isolated
|
|
// temporary home for VCC's files. Normal launches never enter this mode.
|
|
@MainActor
|
|
final class StartupValidationContext {
|
|
let directory: URL
|
|
let defaults: UserDefaults
|
|
private let suite: String
|
|
init() throws {
|
|
guard StarterKit.bundled != nil else { throw StartupStore.Failure.invalid }
|
|
directory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCStartupValidation-" + UUID().uuidString)
|
|
suite = "VCCStartupValidation-" + UUID().uuidString
|
|
defaults = UserDefaults(suiteName: suite)!
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
NSLog("VCC startup validation files: %@", directory.path)
|
|
}
|
|
func model() -> MachineModel {
|
|
MachineModel(diskStore: .init(url: directory.appendingPathComponent("DiskAssignments.json")), displayDefaults: defaults,
|
|
inputStore: .init(url: directory.appendingPathComponent("Input.json")), startupStore: .init(directory: directory, kit: .bundled))
|
|
}
|
|
func cleanUp() {
|
|
defaults.removePersistentDomain(forName: suite)
|
|
try? FileManager.default.removeItem(at: directory)
|
|
}
|
|
}
|