Sync source edition with VCC Plus 3.7.0 build 63

This commit is contained in:
Brian Holman committed 2026-11-14 01:43:46 -07:00
1 parent c652a5276d
commit b2ecec4d87
86 files changed
+10519 -472

No files matched your search

+533 -4
View File
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AppKit
import CryptoKit
import AVFoundation
// Run using the VCCUITests scheme: its separate app identity and mandatory
// authored fixture keep personal ROMs, media, profiles and sessions untouched.
@@ -11,6 +13,9 @@ final class InteractionTests: XCTestCase {
private var diskEditorFixtureFolder: URL?
private var projectSetupFixtureFolder: URL?
private var audioGameFixtureFolder: URL?
private var captureFixtureFolder: URL?
private var coverFixtureFolder: URL?
private var continuityFixtureFolder: URL?
private var originalClipboard: [NSPasteboardItem]?
private var main: XCUIElement { app.windows["VCC UI Tests"] }
private var display: XCUIElement { main.descendants(matching: .any)["coco-display"].firstMatch }
@@ -87,6 +92,27 @@ final class InteractionTests: XCTestCase {
return true
}
app.launchArguments = ["-ApplePersistenceIgnoreState", "YES", "-NSQuitAlwaysKeepsWindows", "NO"]
if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") {
try requireFullManualEdition()
let token = UUID().uuidString
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityRelaunch-" + token)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
try token.write(to: folder.appendingPathComponent("fixture-owner"), atomically: true, encoding: .utf8)
continuityFixtureFolder = folder
app.launchEnvironment["VCC_CONTINUITY_TEST_ROOT"] = folder.path
}
if name.contains("testPersonalLibraryCover") {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCoverUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
coverFixtureFolder = folder
app.launchEnvironment["VCC_COVER_DRAG_TRACE"] = folder.appendingPathComponent("drag-trace.txt").path
app.launchEnvironment["VCC_COVER_DRAG_SOURCE"] = folder.appendingPathComponent("Blue Cover.png").path
}
if name.contains("testCoCoCapture") {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCaptureUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
captureFixtureFolder = folder; app.launchEnvironment["VCC_CAPTURE_TEST_DIRECTORY"] = folder.path
}
if name.contains("CompactOS9") { app.launchArguments.append("--disk-editor-compact-fixture") }
if name.contains("testDiskImageEditor") {
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
@@ -120,17 +146,36 @@ final class InteractionTests: XCTestCase {
let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent().deletingLastPathComponent()
let store = repo.appendingPathComponent("media/knowledge-base")
let index = store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite")
// Match normal packaging: prefer the prepared local index and avoid
// touching the optional external research volume during UI setup.
let localIndex = repo.appendingPathComponent("media/app-inputs/archive-library/ArchiveLibrary.sqlite")
let index = FileManager.default.fileExists(atPath: localIndex.path) ? localIndex :
store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite")
try XCTSkipUnless(FileManager.default.fileExists(atPath: index.path), "Stage the local Archive Library index.")
let cache = FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveReader-" + UUID().uuidString)
try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: false)
archiveCache = cache
func seed(_ relative: String, as filename: String) throws {
let original = store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative)
// Stage optional retained originals before launching XCTest when
// the research store is on a removable volume. File access in
// setUp must not wait indefinitely on an unseen system prompt.
let staged = repo.appendingPathComponent(".build/archive-ui-fixtures").appendingPathComponent(relative)
let original = FileManager.default.fileExists(atPath: staged.path) ? staged :
store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative)
try XCTSkipUnless(FileManager.default.fileExists(atPath: original.path), "Stage the Archive fixture " + relative)
try FileManager.default.copyItem(at: original, to: cache.appendingPathComponent(filename))
let data = try Data(contentsOf: original)
XCTAssertEqual(SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(),
(filename as NSString).deletingPathExtension, "Retained fixture must match the indexed original")
try data.write(to: cache.appendingPathComponent(filename), options: .atomic)
}
if name.contains("testArchiveLibraryBrowsesTextAndImageInline") {
if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") {
try seed("Magazines/MOTD/MOTD 1986 04.pdf", as: "917d4da1916fd14cd89f20da6fea5474e807a16e723f05055231992e430e6d33.pdf")
try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png",
as: "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5.png")
app.launchArguments += ["-archive-library.collection", "Walkthroughs/Sierra Games"]
} else if name.contains("testArchiveLibraryRelatedReferenceFromSoftware") {
try seed("Walkthroughs/Raaka-Tu Walkthrough (Tandy).txt", as: "e55b30ce36985c0ff35ade23152828e090014bae1b8ddcadd50b02b90f72c7dc.txt")
} else if name.contains("testArchiveLibraryBrowsesTextAndImageInline") {
try seed("Walkthroughs/Sierra Games/AGI Quest I Walkthrough (Juha Terho).txt",
as: "563a8fe2ba0e251227fb05c1ac6a4bfe965bc3e124bb91547f8bae493adab68a.txt")
try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png",
@@ -200,6 +245,13 @@ final class InteractionTests: XCTestCase {
if let diskEditorFixtureFolder { try? FileManager.default.removeItem(at: diskEditorFixtureFolder) }
if let projectSetupFixtureFolder { try? FileManager.default.removeItem(at: projectSetupFixtureFolder) }
if let audioGameFixtureFolder { try? FileManager.default.removeItem(at: audioGameFixtureFolder) }
if let captureFixtureFolder { try? FileManager.default.removeItem(at: captureFixtureFolder) }
if let coverFixtureFolder { try? FileManager.default.removeItem(at: coverFixtureFolder) }
if let continuityFixtureFolder {
let suite = continuityFixtureFolder.lastPathComponent
UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
try? FileManager.default.removeItem(at: continuityFixtureFolder)
}
}
if let app, app.state != .notRunning {
if (testRun?.failureCount ?? 0) > 0 {
@@ -4550,3 +4602,480 @@ extension InteractionTests {
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
}
}
extension InteractionTests {
func testCoCoCaptureHeaderScreenshotTimerAndMovie() async throws {
let before = session()
let root = try XCTUnwrap(captureFixtureFolder)
let documents = root.appendingPathComponent("Documents", isDirectory: true)
func files(_ dir: URL, _ ext: String) -> [URL] {
((try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []).filter { $0.pathExtension == ext && !$0.lastPathComponent.hasPrefix(".") }
}
func waitFor(_ predicate: @escaping () -> Bool, seconds: TimeInterval = 12) {
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in predicate() }, object: nil)], timeout: seconds), .completed)
}
let camera = main.buttons["capture-now"], record = main.buttons["capture-record"]
let options = main.menuButtons["capture-options"]
func choose(_ label: String) {
options.click()
let item = app.menuItems[label].firstMatch
XCTAssertTrue(item.waitForExistence(timeout: 3)); item.click()
}
XCTAssertTrue(camera.waitForExistence(timeout: 5)); XCTAssertTrue(record.exists)
camera.click(); waitFor { files(root,"png").count == 1 }
let png = try XCTUnwrap(files(root,"png").first)
let picture = try XCTUnwrap(NSImage(contentsOf: png))
XCTAssertLessThanOrEqual(picture.size.width, 640); XCTAssertLessThanOrEqual(picture.size.height, 480)
XCTAssertGreaterThan(picture.size.width, 200)
choose("10 Seconds")
let cancel = main.buttons["capture-countdown-cancel"]
XCTAssertFalse(cancel.exists, "Changing the timer must not start a capture")
XCTAssertEqual(files(root,"png").count, 1)
camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3)); cancel.click()
XCTAssertFalse(cancel.exists); XCTAssertEqual(files(root,"png").count, 1)
choose("5 Seconds")
XCTAssertFalse(cancel.exists, "Only the camera performs a capture")
camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3))
waitFor({ files(root,"png").count == 2 }, seconds: 10)
choose("None")
choose("Documents")
// The chooser changes the one shared destination only on confirmation.
choose("Other Location…")
let chooser = app.windows["Save Screenshots and Videos To"]
XCTAssertTrue(chooser.waitForExistence(timeout: 4))
chooser.buttons["Cancel"].click()
camera.click(); waitFor { files(documents,"png").count == 1 }
XCTAssertEqual(files(root,"png").count, 2)
choose("Include CoCo Audio in Video")
record.click()
waitFor { record.label == "Stop Recording" }
// Take another image while video is active. Its shutter is host-only.
camera.click(); waitFor { files(documents,"png").count == 2 }
choose("Include CoCo Audio in Video") // Changes the next recording only.
let deadline = Date().addingTimeInterval(1.2)
waitFor { Date() >= deadline }
record.click()
waitFor({ files(documents,"mp4").count == 1 }, seconds: 20)
let movie = try XCTUnwrap(files(documents,"mp4").first)
XCTAssertGreaterThan(try movie.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0, 1000)
let asset = AVURLAsset(url: movie)
let tracks = try await asset.loadTracks(withMediaType: .audio)
let track = try XCTUnwrap(tracks.first)
let reader = try AVAssetReader(asset: asset)
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
reader.add(output); XCTAssertTrue(reader.startReading())
var peak: Float = 0, samples = 0
while let sample = output.copyNextSampleBuffer() {
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
var data = Data(count: CMBlockBufferGetDataLength(buffer))
XCTAssertEqual(data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) }, noErr)
data.withUnsafeBytes { raw in
for value in raw.bindMemory(to: Float.self) { peak = max(peak, abs(value)); samples += 1 }
}
}
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(samples, 0)
XCTAssertLessThan(peak, 0.00001, "Local start/shutter cues must not leak into the silent video")
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertGreaterThan(session()[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let shot = XCTAttachment(screenshot: main.screenshot()); shot.name = "Shared capture controls"; shot.lifetime = .keepAlways; add(shot)
}
}
extension InteractionTests {
func testArchiveLibraryAndManualsResumeAcrossProcessRelaunch() throws {
let fixture = try XCTUnwrap(continuityFixtureFolder)
let stateFile = fixture.appendingPathComponent("LibraryContinuity.json")
func state() -> [String: Any] {
guard let data = try? Data(contentsOf: stateFile),
let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] }
return object
}
func waitUntil(_ description: String, _ condition: @escaping () -> Bool) {
let predicate = NSPredicate { _, _ in condition() }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 12), .completed, description)
}
func reading(_ key: String) -> [String: Any] { (state()["reading"] as? [String: [String: Any]])?[key] ?? [:] }
func bookmarks() -> [[String: Any]] { state()["bookmarks"] as? [[String: Any]] ?? [] }
func capture(_ window: XCUIElement, _ title: String) {
let image = XCTAttachment(screenshot: window.screenshot()); image.name = title; image.lifetime = .keepAlways; add(image)
}
func relaunch() {
app.activate()
app.typeKey("q", modifierFlags: .command)
waitUntil("The first isolated process must quit before launching its successor") { self.app.state == .notRunning }
app.launch()
XCTAssertTrue(main.waitForExistence(timeout: 15))
waitUntil("The successor process must finish its authored machine startup") {
self.main.buttons["execution"].label == "Pause" && self.main.links["FD0 Authored FD0.dsk"].exists
}
}
menu("Media", "Software Library…")
let software = app.windows["Software Library"]
XCTAssertTrue(software.buttons["library-scope-all"].waitForExistence(timeout: 10))
software.buttons["library-scope-all"].click()
let softwareSearch = software.descendants(matching: .any)["library-search"].firstMatch
softwareSearch.click(); app.typeText("Raaka-Tu")
let game = software.buttons["library-title-486dda54b9351ac926c382f70f328aa5"]
XCTAssertTrue(game.waitForExistence(timeout: 10)); game.click()
waitUntil("Software title and search must reach the continuity file") {
let browse = (state()["browse"] as? [String: [String: Any]])?["software-main"]
return browse?["selectedID"] as? String == "486dda54b9351ac926c382f70f328aa5"
}
menu("Help", "Archive Library…")
let archive = app.windows["Archive Library"]
let map = archive.descendants(matching: .any)["archive-browse-list"].firstMatch.staticTexts["King's Quest I Map (Sierra)"]
XCTAssertTrue(map.waitForExistence(timeout: 10)); map.click()
XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10))
archive.buttons["Zoom in"].click()
let mapID = "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5"
waitUntil("Archive image zoom must be checkpointed") { (reading("archive:" + mapID)["zoom"] as? Double ?? 0) > 1 }
let mapZoom = try XCTUnwrap(reading("archive:" + mapID)["zoom"] as? Double)
capture(archive, "Archive map before process relaunch")
menu("Help", "Manual Library…")
let manual = app.windows["Manual Library"]
func follow(_ title: String) {
let link = manual.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
XCTAssertTrue(link.waitForExistence(timeout: 10), title); link.click()
}
let firstBook = "meet-your-color-computer", secondBook = "back-at-the-coco"
func readAndBookmark(_ book: String) {
let chapter = book + (book == firstBook ? "/meet-the-machine.html" : "/familiar-hardware.html")
waitUntil("The selected chapter must finish loading") {
reading("manual-last")["relativePath"] as? String == chapter && manual.buttons["manual.bookmark-location"].isEnabled
}
manual.webViews.firstMatch.scroll(byDeltaX: 0, deltaY: -600)
waitUntil("Scrolling must record a reading position") {
let position = reading("manual-book:" + book)
return (position["offset"] as? Double ?? 0) > 0.001 || position["anchor"] as? String != nil
}
let bookmark = manual.buttons["manual.bookmark-location"]
XCTAssertTrue(bookmark.isEnabled); bookmark.click()
waitUntil("A bookmark in each book must be saved") { bookmarks().contains { $0["bookID"] as? String == book } }
}
follow("Open the first book"); follow("Start reading"); readAndBookmark(firstBook)
manual.buttons["manual.home"].click()
follow("Open Back at the CoCo"); follow("Start reading"); readAndBookmark(secondBook)
let firstPosition = reading("manual-book:" + firstBook), secondPosition = reading("manual-book:" + secondBook)
let firstMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == firstBook }?["id"] as? String)
let secondMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == secondBook }?["id"] as? String)
XCTAssertEqual(bookmarks().count, 2)
capture(manual, "Second manual before process relaunch")
relaunch()
menu("Media", "Software Library…")
XCTAssertTrue(game.waitForExistence(timeout: 10))
XCTAssertEqual(softwareSearch.value as? String, "Raaka-Tu")
XCTAssertTrue(software.links["library-reference-02587e81cceaec9ac0c11fe9"].waitForExistence(timeout: 10), "The selected software detail must resume")
capture(software, "Software selection and search after process relaunch")
menu("Help", "Archive Library…")
XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10), "The selected browse image must resume")
XCTAssertTrue(archive.buttons["Fit Image"].isEnabled, "The image must retain its zoom")
XCTAssertEqual(reading("archive:" + mapID)["zoom"] as? Double, mapZoom)
let archiveSearch = archive.textFields["archive-search"]
archiveSearch.click(); app.typeText("MOTD strip buffer")
let result = archive.outlines["archive-results-list"].descendants(matching: .outlineRow).containing(.staticText, identifier: "PDF page 12").firstMatch
XCTAssertTrue(result.waitForExistence(timeout: 10)); result.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click()
let pdfPage = archive.textFields["PDF page number"]
waitUntil("The selected search result must show its cited page") { pdfPage.value as? String == "12" }
capture(archive, "Archive search before second process relaunch")
menu("Help", "Manual Library…")
waitUntil("The last active manual must resume") { reading("manual-last")["documentID"] as? String == secondBook && manual.buttons["manual.bookmark-location"].isEnabled }
XCTAssertEqual(reading("manual-last")["relativePath"] as? String, secondPosition["relativePath"] as? String)
XCTAssertEqual(reading("manual-last")["anchor"] as? String, secondPosition["anchor"] as? String)
manual.buttons["manual.bookmarks"].click()
manual.radioButtons["All Books"].click()
let firstEntry = manual.buttons["manual.bookmark-open-" + firstMark]
let secondEntry = manual.buttons["manual.bookmark-open-" + secondMark]
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertTrue(secondEntry.exists)
capture(manual, "Two-book bookmarks after process relaunch")
// This journey verifies native scope actions and persistence. Focused
// keyboard/VoiceOver operation is qualified separately; clicking a Mac
// radio button alone does not establish keyboard focus for arrow keys.
manual.radioButtons["This Book"].click()
waitUntil("This Book must show only the active book's bookmark") { !firstEntry.exists && secondEntry.exists }
manual.radioButtons["All Books"].click()
waitUntil("All Books must show both saved bookmarks") { firstEntry.exists && secondEntry.exists }
firstEntry.click()
waitUntil("Explicit bookmark navigation must win over second-book resume") { reading("manual-last")["documentID"] as? String == firstBook }
XCTAssertEqual(reading("manual-last")["anchor"] as? String, firstPosition["anchor"] as? String)
manual.buttons["manual.bookmarks"].click()
manual.radioButtons["This Book"].click()
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists)
firstEntry.click()
relaunch()
menu("Help", "Archive Library…")
XCTAssertEqual(archiveSearch.value as? String, "MOTD strip buffer")
waitUntil("The selected PDF search page must survive the second process relaunch") { pdfPage.value as? String == "12" }
capture(archive, "Archive search and cited page after process relaunch")
menu("Help", "Manual Library…")
waitUntil("The explicit first-book visit must become the new automatic resume") { reading("manual-last")["documentID"] as? String == firstBook && manual.buttons["manual.bookmark-location"].isEnabled }
manual.buttons["manual.bookmarks"].click()
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists)
manual.radioButtons["All Books"].click(); XCTAssertTrue(secondEntry.exists)
XCTAssertEqual(bookmarks().count, 2)
capture(manual, "First manual and saved bookmark filter after second relaunch")
}
func testManualLibraryBookmarksAndWindowResume() throws {
try requireFullManualEdition()
menu("Help", "Manual Library…")
let reader = app.windows["Manual Library"]
XCTAssertTrue(reader.waitForExistence(timeout: 8))
for title in ["Open the first book", "Start reading"] {
let link = reader.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
XCTAssertTrue(link.waitForExistence(timeout: 8)); link.click()
}
let bookmark = reader.buttons["manual.bookmark-location"]
let ready = NSPredicate { _, _ in bookmark.exists && bookmark.isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 8), .completed)
bookmark.click(); reader.buttons["manual.bookmarks"].click()
let entry = reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).firstMatch
XCTAssertTrue(entry.waitForExistence(timeout: 5))
reader.radioButtons["All Books"].click(); XCTAssertTrue(entry.exists)
reader.radioButtons["This Book"].click(); XCTAssertTrue(entry.exists)
let shot = XCTAttachment(screenshot: reader.screenshot()); shot.name = "Manual bookmarks — one list with filters"; shot.lifetime = .keepAlways; add(shot)
entry.click()
reader.buttons["manual.bookmark-location"].click() // recognizes the existing entry
XCTAssertTrue(entry.waitForExistence(timeout: 5))
XCTAssertEqual(reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).count, 1)
entry.click()
reader.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
menu("Help", "Manual Library…")
XCTAssertTrue(reader.buttons["manual.bookmark-location"].waitForExistence(timeout: 5))
reader.buttons["manual.bookmarks"].click(); XCTAssertTrue(entry.waitForExistence(timeout: 5))
}
func testSoftwareLibraryPersonalImportPreservesGuest() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 8))
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let source = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk")
let original = try Data(contentsOf: source)
library.buttons["library-scope-personal"].click()
let addButton = library.buttons["library-personal-add"]
let addFirst = library.buttons["library-personal-add-first"]
XCTAssertTrue(addButton.waitForExistence(timeout: 5))
XCTAssertTrue(addFirst.waitForExistence(timeout: 5))
addFirst.click()
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
app.buttons["Cancel"].click()
XCTAssertTrue(addButton.waitForExistence(timeout: 5))
addButton.click()
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(source.path); app.typeKey(.return, modifierFlags: [])
app.buttons["Review Files"].click()
let field = library.textFields["personal-title"]
XCTAssertTrue(field.waitForExistence(timeout: 8)); field.click(); app.typeKey("a", modifierFlags: .command); app.typeText("Private Library UI Example")
let category = library.popUpButtons["personal-category"]
XCTAssertTrue(category.exists); XCTAssertEqual(category.value as? String, "Other")
category.click(); app.menuItems["Games"].click()
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Add Personal Software — review before import"; shot.lifetime = .keepAlways; add(shot)
library.buttons["personal-save"].click()
let title = library.staticTexts["Private Library UI Example"].firstMatch
XCTAssertTrue(title.waitForExistence(timeout: 10))
XCTAssertTrue(library.buttons["library-scope-personal"].exists)
XCTAssertTrue(addButton.exists, "Add Software stays available after the first import")
XCTAssertFalse(addFirst.exists, "A populated library must not show the first-item invitation")
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("No such personal title 370")
let clear = library.buttons["library-empty-clear-search"]
XCTAssertTrue(clear.waitForExistence(timeout: 5))
XCTAssertFalse(addButton.exists, "The header search opens global results, outside the private-only browse scope")
XCTAssertFalse(addFirst.exists, "A filtered library is not an empty personal collection")
clear.click()
library.buttons["library-scope-getting-started"].click()
search.click(); app.typeText("Private Library UI Example")
let personalCard = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-personal:")).firstMatch
XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "Global search must find a private game from Getting Started")
XCTAssertTrue(personalCard.label.contains("Personal"))
library.buttons["Clear search"].click()
library.buttons["library-type-Games"].click()
XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "The standard Games category includes the private game")
let grouped = XCTAttachment(screenshot: library.screenshot()); grouped.name = "Unified Games — Personal Library before Catalog"; grouped.lifetime = .keepAlways; add(grouped)
library.radioButtons["Table"].click()
let table = library.outlines["Software titles"]
XCTAssertTrue(table.waitForExistence(timeout: 5))
table.scroll(byDeltaX: 0, deltaY: 1200)
let tableShot = XCTAttachment(screenshot: library.screenshot()); tableShot.name = "Unified Games — Table Personal badge"; tableShot.lifetime = .keepAlways; add(tableShot)
let firstRow = table.outlineRows.element(boundBy: 0)
let badge = firstRow.descendants(matching: .any)["library-personal-badge"].firstMatch
XCTAssertTrue(badge.waitForExistence(timeout: 5), "The first table row visibly identifies the personal entry")
XCTAssertFalse(addButton.exists, "Other categories keep personal import in Library Actions")
XCTAssertEqual(try Data(contentsOf: source), original)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testPersonalLibraryCoverChooserCancelDropAndRemovePreserveGuest() throws {
try personalCoverJourney(includeDrop: true)
}
func testPersonalLibraryCoverChooserCancelAndRemovePreserveGuest() throws {
try personalCoverJourney(includeDrop: false)
}
private func personalCoverJourney(includeDrop: Bool) throws {
let manualDrag = includeDrop && ProcessInfo.processInfo.environment["VCC_UI_MANUAL_COVER_DRAG"] == "1"
var manualFinderWindow: XCUIElement?
defer {
if let window = manualFinderWindow, window.exists,
window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists {
window.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
}
}
let before = session()
let folder = try XCTUnwrap(coverFixtureFolder)
defer { try? FileManager.default.removeItem(at: folder) }
func image(_ color: NSColor, name: String) throws -> URL {
let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 320, pixelsHigh: 200,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
color.setFill(); NSBezierPath(rect: NSRect(x: 0, y: 0, width: 320, height: 200)).fill()
NSGraphicsContext.restoreGraphicsState()
let url = folder.appendingPathComponent(name)
try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: url)
return url
}
let red = try image(.red, name: "Red Cover.png"), blue = try image(.blue, name: "Blue Cover.png")
let redBytes = try Data(contentsOf: red), blueBytes = try Data(contentsOf: blue)
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let disk = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk"), diskBytes = try Data(contentsOf: disk)
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-personal"].click()
library.buttons["library-personal-add"].click()
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(disk.path); app.typeKey(.return, modifierFlags: [])
app.buttons["Review Files"].click()
XCTAssertTrue(library.buttons["personal-save"].waitForExistence(timeout: 8)); library.buttons["personal-save"].click()
let cover = library.descendants(matching: .any)["library-personal-cover"].firstMatch
XCTAssertTrue(cover.waitForExistence(timeout: 8))
func choose(_ url: URL, prompt: String) {
XCTAssertTrue(app.buttons[prompt].waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(url.path); app.typeKey(.return, modifierFlags: [])
app.buttons[prompt].click()
}
func matches(_ element: XCUIElement, red: Bool) -> Bool {
guard element.exists, let pixels = NSBitmapImageRep(data: element.screenshot().pngRepresentation),
let color = pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2)?.usingColorSpace(.deviceRGB) else { return false }
// Native display captures carry the monitor's color transform;
// verify the authored dominant channel rather than raw PNG bytes.
return red ? color.redComponent > 0.7 && color.redComponent - max(color.greenComponent, color.blueComponent) > 0.4
: color.blueComponent > 0.7 && color.blueComponent - max(color.greenComponent, color.redComponent) > 0.4
}
func waitForColor(_ element: XCUIElement, red: Bool, timeout: TimeInterval = 15) {
let expectation = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in matches(element, red: red) }, object: nil)
let result = XCTWaiter.wait(for: [expectation], timeout: timeout)
if result != .completed {
let screenshot = element.screenshot()
let attachment = XCTAttachment(screenshot: screenshot); attachment.name = "Cover pixel assertion"; attachment.lifetime = .keepAlways; add(attachment)
if let pixels = NSBitmapImageRep(data: screenshot.pngRepresentation) {
print("Cover screenshot \(pixels.pixelsWide)x\(pixels.pixelsHigh), center \(String(describing: pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2))), frame \(element.frame)")
}
}
XCTAssertEqual(result, .completed)
}
library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Choose Cover Image…"].click()
choose(red, prompt: "Use Image"); waitForColor(cover, red: true)
library.buttons["Edit Details…"].click()
let chooseDraft = library.buttons["personal-cover-choose"]
XCTAssertTrue(chooseDraft.waitForExistence(timeout: 5))
let preview = library.descendants(matching: .any)["personal-cover-preview"].firstMatch
let form = library.sheets.firstMatch.scrollViews.firstMatch
for _ in 0..<6 where !form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame) {
form.scroll(byDeltaX: 0, deltaY: -180)
}
XCTAssertTrue(form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame), "Inspect the complete preview inside the form viewport")
chooseDraft.click(); choose(blue, prompt: "Choose Image")
waitForColor(preview, red: false)
let editorShot = XCTAttachment(screenshot: library.screenshot()); editorShot.name = "Personal cover — draft image preview"; editorShot.lifetime = .keepAlways; add(editorShot)
library.sheets.firstMatch.buttons["Cancel"].click(); waitForColor(cover, red: true)
if includeDrop {
app.activate()
// The authored native source starts an actual NSDraggingSession with
// a file URL. It never calls the destination handler or changes model
// state; the normal decoder/store/render path must produce blue pixels.
let source = library.descendants(matching: .any)["personal-cover-drag-source"].firstMatch
XCTAssertTrue(source.waitForExistence(timeout: 5))
let pasteboardGeneration = NSPasteboard(name: .drag).changeCount
if manualDrag {
let finder = XCUIApplication(bundleIdentifier: "com.apple.finder")
finder.activate(); finder.typeKey("n", modifierFlags: .command)
finder.typeKey("g", modifierFlags: [.command, .shift]); finder.typeText(folder.path); finder.typeKey(.return, modifierFlags: [])
let window = finder.windows[folder.lastPathComponent]
XCTAssertTrue(window.waitForExistence(timeout: 8))
manualFinderWindow = window
print("VCC_COVER_MANUAL_DRAG_READY: Drag Blue Cover.png from Finder onto the red cover in Software Library")
fflush(stdout)
let delivered = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
let log = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? ""
return log.contains("perform file-count=1") && matches(cover, red: false)
}, object: nil)
XCTAssertEqual(XCTWaiter.wait(for: [delivered], timeout: 180), .completed)
} else {
source.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).press(forDuration: 0.25,
thenDragTo: cover.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)), withVelocity: .slow, thenHoldForDuration: 1)
}
XCTAssertGreaterThan(NSPasteboard(name: .drag).changeCount, pasteboardGeneration)
XCTAssertTrue(NSPasteboard(name: .drag).types?.contains(.fileURL) == true)
let trace = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? "No native drag events"
print("Native cover drag: " + trace)
XCTAssertTrue(trace.contains("perform file-count=1"))
if !manualDrag { app.activate(); waitForColor(cover, red: false) }
let shot = XCTAttachment(screenshot: cover.screenshot()); shot.name = "Personal cover — native file drop replacement"; shot.lifetime = .keepAlways; add(shot)
}
if let window = manualFinderWindow, window.exists,
window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists {
window.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
manualFinderWindow = nil
app.activate()
}
library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Remove Cover"].click()
let removed = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in cover.label.hasSuffix(" category cover") }, object: nil)
XCTAssertEqual(XCTWaiter.wait(for: [removed], timeout: 10), .completed)
XCTAssertFalse(matches(cover, red: true)); XCTAssertFalse(matches(cover, red: false))
XCTAssertEqual(try Data(contentsOf: red), redBytes); XCTAssertEqual(try Data(contentsOf: blue), blueBytes)
XCTAssertEqual(try Data(contentsOf: disk), diskBytes)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testArchiveLibraryRelatedReferenceFromSoftware() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-all"].click()
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("Raaka-Tu")
let game = library.buttons["library-title-486dda54b9351ac926c382f70f328aa5"]
XCTAssertTrue(game.waitForExistence(timeout: 8)); game.click()
let referenceID = "library-reference-02587e81cceaec9ac0c11fe9"
let link = library.links[referenceID]
XCTAssertTrue(link.waitForExistence(timeout: 8))
let detail = library.scrollViews.containing(.link, identifier: referenceID).firstMatch
func guideVisible() -> Bool {
// macOS can report clipped content beneath the fixed footer as
// hittable. Require the complete link inside its actual viewport.
let frame = link.frame
return !frame.isEmpty && link.isHittable && detail.frame.insetBy(dx: 10, dy: 18).contains(frame)
}
for _ in 0..<8 where !guideVisible() { detail.scroll(byDeltaX: 0, deltaY: -250) }
XCTAssertTrue(guideVisible(), "Scroll the entire guide action clear of the fixed footer before opening it")
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Software Library — Raaka-Tu Guides & References"; shot.lifetime = .keepAlways; add(shot)
link.click()
let archive = app.windows["Archive Library"]
let text = archive.textViews["archive-inline-text"]
XCTAssertTrue(text.waitForExistence(timeout: 10)); XCTAssertGreaterThan((text.value as? String ?? "").count, 100)
XCTAssertEqual(text.label, "Raaka-Tu Walkthrough (Tandy)", "The loaded reader must identify the exact linked document")
let readerShot = XCTAttachment(screenshot: archive.screenshot()); readerShot.name = "Archive Library — linked Raaka-Tu walkthrough"; readerShot.lifetime = .keepAlways; add(readerShot)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
}