// 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? private let suite: String private let retainsRelaunchFixture: Bool init() throws { #if VCC_UI_TESTING if let path = ProcessInfo.processInfo.environment["VCC_CONTINUITY_TEST_ROOT"] { let candidate = URL(fileURLWithPath: path).standardizedFileURL let temporary = FileManager.default.temporaryDirectory.standardizedFileURL.resolvingSymlinksInPath() // XCTest's runner is sandboxed and owns a different temporary root // from the tested app. Permit precisely that runner's tmp directory, // never its Documents directory or an arbitrary supplied parent. let userHome = URL(fileURLWithPath: NSHomeDirectoryForUser(NSUserName()) ?? NSHomeDirectory()) let runnerTemporary = userHome.appendingPathComponent("Library/Containers/com.brianholman.vccplus.mac.uitests.xctrunner/Data/tmp") .standardizedFileURL.resolvingSymlinksInPath() let prefix = "VCCContinuityRelaunch-" let token = String(candidate.lastPathComponent.dropFirst(prefix.count)) let values = try candidate.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) guard candidate.lastPathComponent.hasPrefix(prefix), UUID(uuidString: token) != nil, [temporary.path, runnerTemporary.path].contains(candidate.deletingLastPathComponent().resolvingSymlinksInPath().path), values.isDirectory == true, values.isSymbolicLink != true, try String(contentsOf: candidate.appendingPathComponent("fixture-owner"), encoding: .utf8) == token else { throw CocoaError(.fileReadNoPermission) } directory = candidate suite = prefix + token retainsRelaunchFixture = true } else { directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString) suite = "VCCInterfaceUI-" + UUID().uuidString retainsRelaunchFixture = false } #else directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString) suite = "VCCInterfaceUI-" + UUID().uuidString retainsRelaunchFixture = false #endif 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") { let destination = kit.appendingPathComponent("Blank OS9 Header.bin") if retainsRelaunchFixture && FileManager.default.fileExists(atPath: destination.path) { guard try Data(contentsOf: destination) == Data(contentsOf: resource) else { throw CocoaError(.fileReadCorruptFile) } } else { try FileManager.default.copyItem(at: resource, to: destination) } } 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.. 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.. 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() // Only the UI runner that owns the explicit one-test fixture removes it. // A second app process must be able to read the first process's state. guard !retainsRelaunchFixture else { return } defaults.removePersistentDomain(forName: suite) try? FileManager.default.removeItem(at: directory) } } #endif