260 lines
16 KiB
Swift
260 lines
16 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import XCTest
|
|
import PDFKit
|
|
import SwiftUI
|
|
import CryptoKit
|
|
|
|
@MainActor
|
|
final class SoftwareLibraryManualTests: XCTestCase {
|
|
private func fixture(id: String = "manual", pages: Int = 2, size: NSSize = NSSize(width: 300, height: 500)) throws -> (SoftwareLibraryAsset, Data) {
|
|
let pdf = PDFDocument()
|
|
for _ in 0..<pages {
|
|
let image = NSImage(size: size)
|
|
image.lockFocus(); NSColor.white.setFill(); NSRect(origin: .zero, size: size).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: id, 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 testFreshPDFStartsAtCoverAndRestoresOnlyTheSavedReadingPosition() async throws {
|
|
// At PDFKit's default scale this viewport fits more than two of the
|
|
// small pages. Its midpoint and the top of its first page can disagree.
|
|
let (asset, bytes) = try fixture(pages: 4, size: NSSize(width: 320, height: 294))
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
try bytes.write(to: root.appendingPathComponent(try XCTUnwrap(asset.sha256) + ".pdf"))
|
|
let key = "software-manual:" + asset.id
|
|
let frame = NSRect(x: 0, y: 0, width: 900, height: 850)
|
|
|
|
func waitFor(_ message: String, _ condition: () -> Bool) async throws {
|
|
let deadline = ContinuousClock.now + .seconds(8)
|
|
while !condition() {
|
|
guard ContinuousClock.now < deadline else {
|
|
XCTFail(message)
|
|
throw CocoaError(.fileReadUnknown)
|
|
}
|
|
try await Task.sleep(for: .milliseconds(10))
|
|
}
|
|
}
|
|
func attach(_ model: SoftwareLibraryManualModel) -> NSWindow {
|
|
let window = NSWindow(contentRect: frame, styleMask: [.titled], backing: .buffered, defer: false)
|
|
let host = NSHostingView(rootView: SoftwareLibraryManualView(model: model))
|
|
window.contentView = host
|
|
host.layoutSubtreeIfNeeded()
|
|
window.displayIfNeeded()
|
|
return window
|
|
}
|
|
|
|
let saved: LibraryReadingPosition
|
|
do {
|
|
let model = SoftwareLibraryManualModel()
|
|
let store = LibraryContinuityStore(directory: root)
|
|
model.continuity = store
|
|
let window = attach(model)
|
|
defer { window.contentView = nil }
|
|
XCTAssertNil(store.reading(for: key))
|
|
model.open(asset, directory: root)
|
|
try await waitFor("Fresh PDF did not fit its cover in the attached reader") {
|
|
model.pdfView.window === window && model.pdfView.autoScales &&
|
|
model.pdfView.scaleFactor > 1 && model.pdfView.currentDestination?.page != nil
|
|
}
|
|
XCTAssertEqual(model.page, 1)
|
|
let document = try XCTUnwrap(model.document)
|
|
XCTAssertTrue(model.pdfView.currentDestination?.page === document.page(at: 0))
|
|
model.goToPage(model.page + 1)
|
|
try await waitFor("Next skipped the second page") {
|
|
model.page == 2 && model.pdfView.currentDestination?.page === document.page(at: 1)
|
|
}
|
|
model.goToPage(model.page - 1)
|
|
try await waitFor("Previous did not return to the cover") {
|
|
model.page == 1 && model.pdfView.currentDestination?.page === document.page(at: 0)
|
|
}
|
|
|
|
model.pdfView.autoScales = false
|
|
model.pdfView.scaleFactor = 4
|
|
let second = try XCTUnwrap(document.page(at: 1))
|
|
model.pdfView.go(to: PDFDestination(page: second, at: CGPoint(x: 60, y: 205)))
|
|
try await waitFor("The user-selected location was not observed") { model.page == 2 }
|
|
model.cancel()
|
|
await store.flush()
|
|
saved = try XCTUnwrap(store.reading(for: key))
|
|
XCTAssertEqual(saved.page, 2)
|
|
XCTAssertEqual(saved.autoScales, false)
|
|
XCTAssertEqual(try XCTUnwrap(saved.zoom), 4, accuracy: 0.01)
|
|
XCTAssertGreaterThan(saved.offset, 0.1)
|
|
XCTAssertLessThan(saved.offset, 0.95)
|
|
}
|
|
|
|
// Closing a different reader while its PDF has loaded but the view has
|
|
// not been attached must not replace the last real position.
|
|
let unopened = SoftwareLibraryManualModel()
|
|
let previousStore = LibraryContinuityStore(directory: root)
|
|
unopened.continuity = previousStore
|
|
unopened.open(asset, directory: root)
|
|
try await waitFor("Detached PDF failed to open") { unopened.document != nil }
|
|
unopened.cancel()
|
|
XCTAssertEqual(previousStore.reading(for: key), saved)
|
|
|
|
let restored = SoftwareLibraryManualModel()
|
|
let reopenedStore = LibraryContinuityStore(directory: root)
|
|
restored.continuity = reopenedStore
|
|
XCTAssertEqual(reopenedStore.reading(for: key), saved)
|
|
let window = attach(restored)
|
|
defer { window.contentView = nil }
|
|
restored.open(asset, directory: root)
|
|
try await waitFor("Stored PDF page and zoom were lost during attachment") {
|
|
restored.page == 2 && !restored.pdfView.autoScales &&
|
|
abs(restored.pdfView.scaleFactor - 4) < 0.01
|
|
}
|
|
let (other, otherBytes) = try fixture(id: "another-manual", pages: 3)
|
|
try otherBytes.write(to: root.appendingPathComponent(try XCTUnwrap(other.sha256) + ".pdf"))
|
|
restored.open(other, directory: root)
|
|
try await waitFor("Switching manuals did not open a fitted cover") {
|
|
restored.readingReady && restored.page == 1 && restored.pdfView.autoScales
|
|
}
|
|
XCTAssertEqual(restored.document?.pageCount, 3)
|
|
let reopened = try XCTUnwrap(reopenedStore.reading(for: key))
|
|
XCTAssertEqual(reopened.page, saved.page)
|
|
XCTAssertEqual(reopened.horizontalOffset, saved.horizontalOffset, accuracy: 0.01)
|
|
XCTAssertEqual(reopened.offset, saved.offset, accuracy: 0.01)
|
|
}
|
|
|
|
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() { }
|
|
}
|