287 lines
21 KiB
Swift
287 lines
21 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
#if VCC_UI_TESTING
|
|
import Foundation
|
|
import CryptoKit
|
|
|
|
// Authored transport + catalog for native install checks. Compiled only into the
|
|
// isolated UI-test app. Every request is intercepted, including unknown URLs,
|
|
// so the fixture cannot accidentally reach the production download service.
|
|
enum SoftwareLibraryInstallFixture {
|
|
static var enabled: Bool { CommandLine.arguments.contains("--library-install-fixture") || playEnabled || exclusiveEnabled }
|
|
static var playEnabled: Bool { CommandLine.arguments.contains("--library-play-fixture") }
|
|
static var exclusiveEnabled: Bool { CommandLine.arguments.contains("--library-exclusive-fixture") }
|
|
static var sourceConfiguration: URLSessionConfiguration { sessionConfiguration() }
|
|
static let titleID = "authored-library-title"
|
|
static let releaseID = "authored-library-cartridge"
|
|
static let downloadURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Cartridges/Authored%20Library%20Cartridge.ccc")!
|
|
static let bytes: Data = {
|
|
var value = Data(repeating: 0x12, count: 8192)
|
|
value[0] = 0x20; value[1] = 0xfe
|
|
return value
|
|
}()
|
|
static let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
|
static var catalog: SoftwareLibraryCatalog {
|
|
if exclusiveEnabled { return exclusiveCatalog }
|
|
if playEnabled { return playCatalog }
|
|
let setup = SoftwareLibrarySetup(status: "inferred-ready", command: nil,
|
|
instructions: "Authored UI-test cartridge. Installation does not attach or run it.",
|
|
configuration: .object(["profile": .string("disk-basic"), "processor": .string("6809"), "ram_kib": .number(512)]),
|
|
selectedMembers: .array([]), reasons: [], validation: .object([:]))
|
|
let release = SoftwareLibraryRelease(id: releaseID, titleID: titleID,
|
|
name: "Authored Library Cartridge.ccc", category: "Cartridges", mediaType: "cartridge", contentRole: "software",
|
|
sourceURL: URL(string: "https://example.invalid/Authored%20Library%20Cartridge.ccc")!,
|
|
modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil,
|
|
packageSHA256: digest, byteSize: Int64(bytes.count), languageStatus: "english",
|
|
metadata: .object(["system": .string("coco3"), "publisher": .string("VCC Plus test fixture")]),
|
|
setup: setup, assets: [], downloadURLs: [downloadURL])
|
|
return SoftwareLibraryCatalog(titles: [SoftwareLibraryTitle(id: titleID,
|
|
name: "Authored Library Cartridge", identityStatus: "confirmed", releases: [release])],
|
|
metadata: ["schema_version": "1", "recipe_contract": "2", "stage": "authored-ui-fixture",
|
|
"archive_attribution": "Authored test content; no Archive software is used."])
|
|
}
|
|
static let manualReleaseID = "authored-library-manual-disk"
|
|
static let missingReleaseID = "authored-library-missing-member"
|
|
static let diskBytes = Data(repeating: 0, count: 161280)
|
|
private static func playRelease(id: String, name: String, media: String, data: Data, missing: Bool = false) -> SoftwareLibraryRelease {
|
|
let filename = name + (media == "cartridge" ? ".ccc" : ".dsk")
|
|
let source = URL(string: "https://example.invalid/")!.appendingPathComponent(filename)
|
|
let download = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Fixtures/")!.appendingPathComponent(filename)
|
|
let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
|
|
let cartridge = media == "cartridge"
|
|
var configuration: [String: LibraryJSON] = [
|
|
"profile": .string(cartridge ? "rom-cartridge" : "disk-basic"),
|
|
"processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"),
|
|
"controller_slot": .number(4), "cartridge_slot": .number(4),
|
|
"floppy_controller_enabled": .bool(!cartridge), "controls": .object([:])
|
|
]
|
|
if cartridge { configuration["launch_method"] = .string("cartridge-autostart") }
|
|
let setup = SoftwareLibrarySetup(status: cartridge ? "inferred-ready" : "manual-setup", command: nil,
|
|
instructions: cartridge ? "Authored cartridge: verifies setup and resume without a private ROM." : "Authored blank disk: mount it and use the BASIC prompt manually. No loading command is supplied.",
|
|
configuration: .object(configuration),
|
|
selectedMembers: .array([.object(["path": .string(missing ? "Missing.ccc" : filename),
|
|
"target": .string(cartridge ? "cartridge" : "disk0"),
|
|
"sha256": .string(hash), "byte_size": .number(Double(data.count))])]),
|
|
reasons: [], validation: .object([:]))
|
|
return SoftwareLibraryRelease(id: id, titleID: id, name: filename,
|
|
category: cartridge ? "Cartridges" : "Disks/Blank disks", mediaType: media, contentRole: "software",
|
|
sourceURL: source, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil,
|
|
packageSHA256: hash, byteSize: Int64(data.count), languageStatus: "english",
|
|
metadata: .object(["system": .string("CoCo 3"), "publisher": .string("VCC Plus test fixture")]),
|
|
setup: setup, assets: [], downloadURLs: [download])
|
|
}
|
|
static var playCatalog: SoftwareLibraryCatalog {
|
|
let releases = [
|
|
playRelease(id: releaseID, name: "Authored Library Cartridge", media: "cartridge", data: bytes),
|
|
playRelease(id: manualReleaseID, name: "Authored Manual Disk", media: "disk", data: diskBytes),
|
|
playRelease(id: missingReleaseID, name: "Missing Media Reference", media: "cartridge", data: bytes, missing: true)
|
|
]
|
|
return SoftwareLibraryCatalog(titles: releases.map {
|
|
SoftwareLibraryTitle(id: $0.titleID, name: $0.sourceURL.deletingPathExtension().lastPathComponent,
|
|
identityStatus: "confirmed", releases: [$0])
|
|
}, metadata: ["schema_version": "1", "recipe_contract": "2", "stage": "authored-ui-fixture"])
|
|
}
|
|
static func playData(for url: URL?) -> Data? {
|
|
guard let release = playCatalog.releases.first(where: { $0.downloadURLs.first == url }) else { return nil }
|
|
return release.mediaType == "disk" ? diskBytes : bytes
|
|
}
|
|
static func installer(root: URL) -> SoftwareLibraryInstaller {
|
|
SoftwareLibraryInstaller(root: root, session: URLSession(configuration: sessionConfiguration()))
|
|
}
|
|
static func sessionConfiguration() -> URLSessionConfiguration {
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [LibraryFixtureURLProtocol.self]
|
|
configuration.urlCache = nil
|
|
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
return configuration
|
|
}
|
|
|
|
static let exclusiveTitleID = "vccplus.fixture-orbit"
|
|
static let exclusiveReleaseID = "vccplus.fixture-orbit.1"
|
|
static let exclusiveBase = "https://vccplus.brianholman.com/dl/software/CoCoLibrary/"
|
|
static let exclusiveSourceURL = URL(string: exclusiveBase + "Sources/Exclusives/FixtureOrbit/1/FixtureOrbit-Source.zip")!
|
|
static let exclusiveDiskURL = URL(string: exclusiveBase + "Exclusives/FixtureOrbit/1/FixtureOrbit.zip")!
|
|
static let exclusiveManualURL = URL(string: exclusiveBase + "Documents/Manuals/Exclusives/FixtureOrbit/1/Manual.pdf")!
|
|
static let exclusiveArtworkURL = URL(string: exclusiveBase + "Artwork/Thumbnails/Exclusives/FixtureOrbit/1/Cover.png")!
|
|
static let exclusiveArtwork = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")!
|
|
static func checksum(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
|
|
static let exclusiveSourceBytes = storedZIP([
|
|
("FixtureOrbit/main.c", Data("/* Authored exclusive-title UI fixture. */\nint fixture_orbit;\nint main(void) { return 0; }\n".utf8)),
|
|
("FixtureOrbit/Makefile", Data("UI_SENTINEL := $(shell touch MAKE_WAS_RUN)\nbuild:\n\ttouch MAKE_WAS_RUN\n".utf8)),
|
|
("FixtureOrbit/vccplus-project.json", Data("{\"entrySource\":\"main.c\",\"makefile\":\"Makefile\",\"binary\":\"main.bin\"}".utf8)),
|
|
("FixtureOrbit/LICENSE", Data("CC0-1.0: authored VCC Plus test fixture only.\n".utf8))
|
|
])
|
|
static let exclusiveDiskPackage = storedZIP([("ORBIT.DSK", diskBytes)])
|
|
static let exclusiveManual: Data = {
|
|
let stream = "BT /F1 18 Tf 30 170 Td (Fixture Orbit Manual) Tj 0 -30 Td /F1 11 Tf (Authored offline UI-test documentation.) Tj ET\n"
|
|
let objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
|
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 220] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
|
|
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", "<< /Length \(stream.utf8.count) >>\nstream\n\(stream)endstream"]
|
|
var output = "%PDF-1.4\n", offsets = [0]
|
|
for (index, object) in objects.enumerated() {
|
|
offsets.append(output.utf8.count); output += "\(index + 1) 0 obj\n\(object)\nendobj\n"
|
|
}
|
|
let xref = output.utf8.count
|
|
output += "xref\n0 \(objects.count + 1)\n0000000000 65535 f \n"
|
|
for offset in offsets.dropFirst() { output += String(format: "%010d 00000 n \n", offset) }
|
|
output += "trailer\n<< /Size \(objects.count + 1) /Root 1 0 R >>\nstartxref\n\(xref)\n%%EOF\n"
|
|
return Data(output.utf8)
|
|
}()
|
|
private static func exclusiveFile(_ url: URL, _ data: Data) -> LibraryJSON {
|
|
.object(["url": .string(url.absoluteString), "sha256": .string(checksum(data)), "byte_size": .number(Double(data.count))])
|
|
}
|
|
static var exclusiveCatalog: SoftwareLibraryCatalog {
|
|
let diskSHA = checksum(diskBytes)
|
|
let configuration: LibraryJSON = .object(["profile": .string("disk-basic"), "processor": .string("6809"),
|
|
"ram_kib": .number(128), "video": .string("rgb"), "controller_slot": .number(4)])
|
|
let selected: LibraryJSON = .array([.object(["path": .string("ORBIT.DSK"), "target": .string("disk0")])])
|
|
let validation: LibraryJSON = .object(["scope": .string("runtime-verified"), "disk_sha256": .string(diskSHA)])
|
|
let owned: LibraryJSON = .object([
|
|
"schema_version": .number(1), "id": .string(exclusiveTitleID), "release_id": .string(exclusiveReleaseID),
|
|
"publication_status": .string("approved"), "getting_started": .bool(true), "category_featured": .bool(true),
|
|
"browse_categories": .array([.string("Educational"), .string("Games")]), "primary_browse_category": .string("Educational"),
|
|
"provenance": .object(["kind": .string("project-owned"), "collection": .string("vccplus-exclusive"),
|
|
"author": .string("Fixture Author"), "license": .string("CC0-1.0 authored fixture"), "project_url": .string("https://example.invalid/fixture-orbit/")]),
|
|
"disk_package": exclusiveFile(exclusiveDiskURL, exclusiveDiskPackage),
|
|
"disk": .object(["path": .string("ORBIT.DSK"), "sha256": .string(diskSHA), "byte_size": .number(Double(diskBytes.count))]),
|
|
"setup": .object(["configuration": configuration, "selected_members": selected, "command": .string("DOS\r"), "validation": validation]),
|
|
"first_play": .object(["mode": .string("cold-restart-dos")]),
|
|
"links": .object(["manual_online": .string("https://vccplus.brianholman.com/games/fixture-orbit/"),
|
|
"manual_pdf": exclusiveFile(exclusiveManualURL, exclusiveManual), "source_repository": .string("https://example.invalid/FixtureOrbit")]),
|
|
"source": .object(["package": exclusiveFile(exclusiveSourceURL, exclusiveSourceBytes),
|
|
"project_directory": .string("FixtureOrbit"), "configuration_file": .string("FixtureOrbit/vccplus-project.json"),
|
|
"entry_source": .string("main.c"), "license_files": .array([.string("FixtureOrbit/LICENSE")]),
|
|
"build_configuration": .string("Release")])
|
|
])
|
|
var art = SoftwareLibraryAsset(id: "fixture-orbit-cover", name: "Authored fixture cover", kind: "screenshot",
|
|
sourceURL: URL(string: "https://example.invalid/fixture-orbit/")!, sha256: checksum(exclusiveArtwork),
|
|
byteSize: Int64(exclusiveArtwork.count), credit: "Authored test fixture", matchStatus: "confirmed", matchReason: "Authored fixture")
|
|
art.thumbnailURL = exclusiveArtworkURL; art.thumbnailSHA256 = checksum(exclusiveArtwork); art.thumbnailByteSize = Int64(exclusiveArtwork.count)
|
|
let release = SoftwareLibraryRelease(id: exclusiveReleaseID, titleID: exclusiveTitleID, name: "FixtureOrbit.zip",
|
|
category: "Disks/Educational", mediaType: "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/fixture-orbit/")!,
|
|
modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: checksum(exclusiveDiskPackage),
|
|
byteSize: Int64(exclusiveDiskPackage.count), languageStatus: "english",
|
|
metadata: .object(["system": .string("CoCo 3"), "owned_game": owned]),
|
|
setup: .init(status: "spot-checked", command: "DOS\r", instructions: "Authored metadata fixture; do not use Play for this non-bootable disk.",
|
|
configuration: configuration, selectedMembers: selected, reasons: [], validation: validation),
|
|
assets: [art], downloadURLs: [exclusiveDiskURL])
|
|
return SoftwareLibraryCatalog(titles: [.init(id: exclusiveTitleID, name: "Fixture Orbit", identityStatus: "authored-ui-fixture", releases: [release])],
|
|
metadata: ["schema_version": "1", "recipe_contract": "2", "stage": "authored-exclusive-ui-fixture"])
|
|
}
|
|
/// Prepopulate only the isolated UI profile's verified passive assets. The
|
|
/// shared reader/artwork actors therefore perform no network request.
|
|
static func seedExclusiveAssets(manualDirectory: URL, artworkDirectory: URL) throws {
|
|
guard exclusiveEnabled else { return }
|
|
try FileManager.default.createDirectory(at: manualDirectory, withIntermediateDirectories: true)
|
|
try exclusiveManual.write(to: manualDirectory.appendingPathComponent(checksum(exclusiveManual) + ".pdf"), options: .atomic)
|
|
try FileManager.default.createDirectory(at: artworkDirectory, withIntermediateDirectories: true)
|
|
let art = exclusiveCatalog.releases[0].assets[0]
|
|
try exclusiveArtwork.write(to: artworkDirectory.appendingPathComponent(SoftwareLibraryArtworkCache.cacheKey(for: art) + ".png"), options: .atomic)
|
|
}
|
|
static func exclusiveData(for url: URL?) -> Data? {
|
|
guard let url else { return nil }
|
|
if url == exclusiveSourceURL { return exclusiveSourceBytes }
|
|
if url == exclusiveDiskURL { return exclusiveDiskPackage }
|
|
if url == exclusiveManualURL { return exclusiveManual }
|
|
if url == exclusiveArtworkURL { return exclusiveArtwork }
|
|
return nil
|
|
}
|
|
/// Minimal deterministic stored ZIP writer for these authored files. It
|
|
/// supplies normal regular-file attributes; production uses the safe reader.
|
|
private static func storedZIP(_ files: [(String, Data)]) -> Data {
|
|
func word(_ value: UInt32, bytes: Int) -> Data {
|
|
Data((0..<bytes).map { UInt8(truncatingIfNeeded: value >> (8 * $0)) })
|
|
}
|
|
func crc(_ bytes: Data) -> UInt32 {
|
|
var value = UInt32.max
|
|
for byte in bytes {
|
|
value ^= UInt32(byte)
|
|
for _ in 0..<8 { value = value & 1 == 1 ? (value >> 1) ^ 0xedb88320 : value >> 1 }
|
|
}
|
|
return value ^ UInt32.max
|
|
}
|
|
var output = Data(), central = Data()
|
|
for (name, data) in files {
|
|
let path = Data(name.utf8), size = UInt32(data.count), hash = crc(data), offset = UInt32(output.count)
|
|
for (value, bytes) in [(UInt32(0x04034b50), 4), (20, 2), (0, 2), (0, 2), (0, 2), (0, 2),
|
|
(hash, 4), (size, 4), (size, 4), (UInt32(path.count), 2), (0, 2)] { output.append(word(value, bytes: bytes)) }
|
|
output.append(path); output.append(data)
|
|
for (value, bytes) in [(UInt32(0x02014b50), 4), (0x0314, 2), (20, 2), (0, 2), (0, 2), (0, 2), (0, 2),
|
|
(hash, 4), (size, 4), (size, 4), (UInt32(path.count), 2), (0, 2), (0, 2), (0, 2), (0, 2),
|
|
(UInt32(0o100644) << 16, 4), (offset, 4)] { central.append(word(value, bytes: bytes)) }
|
|
central.append(path)
|
|
}
|
|
let offset = UInt32(output.count); output.append(central)
|
|
for (value, bytes) in [(UInt32(0x06054b50), 4), (0, 2), (0, 2), (UInt32(files.count), 2),
|
|
(UInt32(files.count), 2), (UInt32(central.count), 4), (offset, 4), (0, 2)] { output.append(word(value, bytes: bytes)) }
|
|
return output
|
|
}
|
|
}
|
|
|
|
private final class LibraryFixtureAttempts: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var value = 0
|
|
func next() -> Int { lock.lock(); defer { lock.unlock() }; value += 1; return value }
|
|
}
|
|
|
|
private final class LibraryFixtureURLProtocol: URLProtocol, @unchecked Sendable {
|
|
private static let attempts = LibraryFixtureAttempts()
|
|
private let lock = NSLock()
|
|
private var cancelled = false
|
|
private var pending: DispatchWorkItem?
|
|
override class func canInit(with request: URLRequest) -> Bool { true }
|
|
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
override func startLoading() {
|
|
if SoftwareLibraryInstallFixture.exclusiveEnabled {
|
|
guard let data = SoftwareLibraryInstallFixture.exclusiveData(for: request.url), let url = request.url else {
|
|
client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)); return
|
|
}
|
|
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1",
|
|
headerFields: ["Content-Type": "application/octet-stream", "Content-Length": String(data.count)])!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: data); client?.urlProtocolDidFinishLoading(self)
|
|
return
|
|
}
|
|
if SoftwareLibraryInstallFixture.playEnabled {
|
|
guard let data = SoftwareLibraryInstallFixture.playData(for: request.url), let url = request.url else {
|
|
client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)); return
|
|
}
|
|
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1",
|
|
headerFields: ["Content-Type": "application/octet-stream", "Content-Length": String(data.count)])!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: data)
|
|
client?.urlProtocolDidFinishLoading(self)
|
|
return
|
|
}
|
|
guard request.url == SoftwareLibraryInstallFixture.downloadURL else {
|
|
client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)); return
|
|
}
|
|
let attempt = Self.attempts.next()
|
|
if attempt == 1 {
|
|
let response = HTTPURLResponse(url: request.url!, statusCode: 503, httpVersion: "HTTP/1.1", headerFields: ["Content-Length": "0"])!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocolDidFinishLoading(self)
|
|
return
|
|
}
|
|
let data = SoftwareLibraryInstallFixture.bytes
|
|
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1",
|
|
headerFields: ["Content-Type": "application/octet-stream", "Content-Length": String(data.count)])!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: data.prefix(data.count / 2))
|
|
let work = DispatchWorkItem { [weak self] in
|
|
guard let self else { return }
|
|
self.lock.lock(); let cancelled = self.cancelled; self.lock.unlock()
|
|
guard !cancelled else { return }
|
|
self.client?.urlProtocol(self, didLoad: data.suffix(data.count / 2))
|
|
self.client?.urlProtocolDidFinishLoading(self)
|
|
}
|
|
lock.lock(); pending = work; let stopped = cancelled; lock.unlock()
|
|
if stopped { work.cancel(); return }
|
|
// Long enough for an actual Cancel click, then a quick retry completes.
|
|
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + (attempt == 2 ? 10 : 0.2), execute: work)
|
|
}
|
|
override func stopLoading() {
|
|
lock.lock(); cancelled = true; pending?.cancel(); pending = nil; lock.unlock()
|
|
}
|
|
}
|
|
#endif
|