// SPDX-License-Identifier: GPL-3.0-or-later import XCTest import PDFKit import CryptoKit @MainActor final class SoftwareLibraryManualTests: XCTestCase { private func fixture() throws -> (SoftwareLibraryAsset, Data) { let pdf = PDFDocument() for _ in 0..<2 { let image = NSImage(size: NSSize(width: 300, height: 500)) image.lockFocus(); NSColor.white.setFill(); NSRect(x: 0, y: 0, width: 300, height: 500).fill(); image.unlockFocus() pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount) } let bytes = try XCTUnwrap(pdf.dataRepresentation()) let hash = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() var asset = SoftwareLibraryAsset(id: "manual", name: "Manual", kind: "manual", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Manuals/Games/Manual.pdf")!, sha256: hash, byteSize: Int64(bytes.count), credit: "Color Computer Archive", matchStatus: "accepted", matchReason: "Reviewed") asset.manualURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/Games/Manual.pdf") return (asset, bytes) } func testImportedUppercaseTextManualUsesTextReaderWithoutNetwork() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent("PersonalManual-" + UUID().uuidString) defer { try? FileManager.default.removeItem(at: root) } let source = root.appendingPathComponent("Selected") try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) let text = Data("Authored local loading instructions\n".utf8) try text.write(to: source.appendingPathComponent("README.TXT")) try Data([0x12,0x39]).write(to: source.appendingPathComponent("GAME.ccc")) let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary")) let draft = try await store.inspect([source]), entry = try await store.save(draft) let imported = await store.directory(for: entry.id) let manual = try XCTUnwrap(entry.release(in: imported).primaryManualAsset) let model = SoftwareLibraryManualModel(); model.open(manual, directory: root.appendingPathComponent("UnusedCache")) for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 10_000_000) } XCTAssertEqual(model.text, String(decoding: text, as: UTF8.self)) XCTAssertNil(model.document); XCTAssertNil(model.error) XCTAssertEqual(try Data(contentsOf: source.appendingPathComponent("README.TXT")), text) model.cancel() } func testPlainTextDecodingPreservesInstructionsAndRejectsBinaryData() throws { XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data("Z = start\r\nX = kick\u{1A}".utf8)), "Z = start\nX = kick") XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data([0x63, 0x61, 0x66, 0xe9])), "café") XCTAssertThrowsError(try SoftwareLibraryManualModel.decodeText(Data([0, 1, 2]))) } func testPlainTextManualWorksOfflineAndCanSwitchToPDF() async throws { let bytes = Data("Double Dragon\nZ = Punch; X = kick; C = jump\nstart with Z.\n".utf8) let hash = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() var asset = SoftwareLibraryAsset(id: "readme", name: "Readme & Instructions", kind: "manual", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Disks/Games/Game.zip")!, sha256: hash, byteSize: Int64(bytes.count), credit: "ZIP readme", matchStatus: "accepted", matchReason: "Exact member") asset.manualURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/Readmes/Game/README.txt")! let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } try bytes.write(to: directory.appendingPathComponent(hash + ".txt")) let config = URLSessionConfiguration.ephemeral; config.protocolClasses = [ManualNoNetwork.self] let local = try await SoftwareLibraryManualCache(session: URLSession(configuration: config)).localCopy(for: asset, directory: directory) XCTAssertEqual(try Data(contentsOf: local), bytes) let model = SoftwareLibraryManualModel(); model.open(asset, directory: directory) for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 20_000_000) } XCTAssertEqual(model.text, String(data: bytes, encoding: .utf8)); XCTAssertNil(model.document) model.cancel(); model.open(asset, directory: directory); XCTAssertFalse(model.loading) let (pdf, pdfBytes) = try fixture() try pdfBytes.write(to: directory.appendingPathComponent(pdf.sha256! + ".pdf")) model.open(pdf, directory: directory) for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 20_000_000) } XCTAssertEqual(model.document?.pageCount, 2); XCTAssertNil(model.text) } func testTextKeyboardControlsAreDisplayedVerbatim() { let setup = SoftwareLibrarySetup(status: "spot-checked", command: nil, instructions: "", configuration: .object(["controls": .object(["keyboard": .string("Z: start/punch; X: kick; C: jump"), "note": .string("Use a joystick"), "right": .object(["suggested_input": .string("gamepad")])])]), selectedMembers: .array([]), reasons: [], validation: .object([:])) XCTAssertEqual(setup.controlDescription("keyboard"), "Z: start/punch; X: kick; C: jump") XCTAssertEqual(setup.controlDescription("note"), "Use a joystick") XCTAssertEqual(setup.controlDescription("right"), "Right joystick: controller input suggested by the Archive.") } func testManualURLsAreScopedToHostedPDFsAndText() throws { XCTAssertTrue(SoftwareLibraryManualCache.accepts(try fixture().0.manualURL!)) for address in ["https://example.com/a.pdf", "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/a.pdf?x=1", "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/a.html", "file:///tmp/a.pdf"] { XCTAssertFalse(SoftwareLibraryManualCache.accepts(URL(string: address)!)) } } func testRetainedManualWorksOfflineAndReaderPreservesPageOnReopen() async throws { let (asset, bytes) = try fixture() let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let original = directory.appendingPathComponent(asset.sha256! + ".pdf") try bytes.write(to: original) let config = URLSessionConfiguration.ephemeral; config.protocolClasses = [ManualNoNetwork.self] let local = try await SoftwareLibraryManualCache(session: URLSession(configuration: config)).localCopy(for: asset, directory: directory) XCTAssertEqual(local, original) XCTAssertEqual(try Data(contentsOf: local), bytes) let model = SoftwareLibraryManualModel(); model.open(asset, directory: directory) for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 20_000_000) } XCTAssertEqual(model.document?.pageCount, 2) model.page = 2; model.goToPage(); model.cancel() model.open(asset, directory: directory) XCTAssertEqual(model.page, 2) XCTAssertFalse(model.loading) model.page = 999; model.goToPage(); XCTAssertEqual(model.page, 2) model.page = -1; model.goToPage(); XCTAssertEqual(model.page, 1) } func testCompanionManualChecksRegularFileBeforeOpening() async throws { let (asset, bytes) = try fixture() let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let original = directory.appendingPathComponent("Manual.pdf") try bytes.write(to: original) let link = directory.appendingPathComponent("Link.pdf") try FileManager.default.createSymbolicLink(at: link, withDestinationURL: original) let empty = directory.appendingPathComponent("Empty.pdf") try Data().write(to: empty) for url in [original, directory, link, empty] { let model = SoftwareLibraryManualModel() model.open(asset, directory: directory, companion: ManualCompanion(file: url)) for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 20_000_000) } XCTAssertFalse(model.loading) if url == original { XCTAssertEqual(model.document?.pageCount, 2) XCTAssertNil(model.error) } else { XCTAssertNil(model.document) XCTAssertNotNil(model.error, "Companion manuals must reject directories, symlinks and empty files") } } XCTAssertEqual(try Data(contentsOf: original), bytes) } func testUnsupportedManualAndCancellationDoNotCreateFiles() async throws { var (asset, _) = try fixture(); asset.manualURL = URL(string: "https://example.com/a.pdf") let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let config = URLSessionConfiguration.ephemeral; config.protocolClasses = [ManualNoNetwork.self] let cache = SoftwareLibraryManualCache(session: URLSession(configuration: config)) do { _ = try await cache.localCopy(for: asset, directory: directory); XCTFail("Invalid source") } catch SoftwareLibraryManualCache.Failure.unavailable { } let task = Task { withUnsafeCurrentTask { $0?.cancel() } return try await cache.localCopy(for: asset, directory: directory) } do { _ = try await task.value; XCTFail("Cancelled") } catch is CancellationError { } XCTAssertFalse(FileManager.default.fileExists(atPath: directory.path)) } } private struct ManualCompanion: CompanionLibraryAccess { let file: URL func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse { XCTAssertEqual(request.operation, .manual) return CompanionLibraryResponse(assetFileURL: file) } } private final class ManualNoNetwork: URLProtocol { override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet)) } override func stopLoading() { } }