628 lines
34 KiB
Swift
628 lines
34 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import SwiftUI
|
||
import PDFKit
|
||
import Compression
|
||
|
||
struct ArchiveAssetReceipt: Sendable {
|
||
let url: URL
|
||
let sha256: String
|
||
let bytes: Int64
|
||
let fileExtension: String
|
||
let memberRange: ArchiveMemberRange?
|
||
|
||
init?(document: ArchiveDocument) {
|
||
let sha = document.id
|
||
guard sha.utf8.count == 64, sha.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { return nil }
|
||
if document.format == "pdf" {
|
||
guard let url = document.deliveryURL, let bytes = document.deliveryBytes,
|
||
bytes > 0, bytes <= 4 * 1024 * 1024 * 1024, Self.acceptsPDF(url) else { return nil }
|
||
self.url = url
|
||
self.bytes = bytes
|
||
fileExtension = "pdf"
|
||
memberRange = nil
|
||
} else {
|
||
guard let bytes = document.sourceBytes, bytes > 0, bytes <= 128 * 1024 * 1024,
|
||
Self.acceptsSource(document.sourceURL) else { return nil }
|
||
let ext: String
|
||
if let member = document.memberPath {
|
||
guard let range = document.memberRange, (0...1_073_741_824).contains(range.archiveBytes),
|
||
range.offset >= 0, range.compressedBytes > 0, range.compressedBytes <= range.archiveBytes,
|
||
range.offset <= range.archiveBytes - range.compressedBytes,
|
||
range.method == 8 || (range.method == 0 && range.compressedBytes == bytes),
|
||
document.sourceURL.pathExtension.lowercased() == "zip" else { return nil }
|
||
ext = (member as NSString).pathExtension.lowercased()
|
||
memberRange = range
|
||
} else {
|
||
ext = document.sourceURL.pathExtension.lowercased()
|
||
memberRange = nil
|
||
}
|
||
switch document.format {
|
||
case "image" where ["jpg","jpeg","gif","png","tif","tiff"].contains(ext): break
|
||
case "text" where ["txt","bas"].contains(ext): break
|
||
default: return nil
|
||
}
|
||
url = document.sourceURL
|
||
self.bytes = bytes
|
||
fileExtension = ext
|
||
}
|
||
sha256 = sha
|
||
}
|
||
|
||
private static func acceptsPDF(_ url: URL) -> Bool {
|
||
SoftwareLibraryInstaller.acceptsDownloadURL(url) && url.path.hasPrefix("/dl/software/CoCoLibrary/Documents/")
|
||
&& url.pathExtension.lowercased() == "pdf"
|
||
}
|
||
|
||
private static func acceptsSource(_ url: URL) -> Bool {
|
||
url.scheme == "https" && url.host == "colorcomputerarchive.com" && url.user == nil && url.password == nil
|
||
&& (url.port == nil || url.port == 443) && url.query == nil && url.fragment == nil
|
||
&& url.path.hasPrefix("/repo/Documents/") && !url.pathComponents.contains("..") && !url.pathComponents.contains(".")
|
||
&& !url.path.contains("\\") && !url.path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
|
||
}
|
||
|
||
func acceptsResponseURL(_ url: URL) -> Bool {
|
||
fileExtension == "pdf" ? Self.acceptsPDF(url) : Self.acceptsSource(url)
|
||
}
|
||
|
||
var rangeHeader: String? {
|
||
memberRange.map { "bytes=\($0.offset)-\($0.offset + $0.compressedBytes - 1)" }
|
||
}
|
||
|
||
/// Servers may return the complete ZIP instead of honoring a byte-range request.
|
||
func responseSize(_ response: HTTPURLResponse) -> Int64? {
|
||
guard let final = response.url, acceptsResponseURL(final) else { return nil }
|
||
guard let range = memberRange else { return response.statusCode == 200 ? bytes : nil }
|
||
if response.statusCode == 200 { return range.archiveBytes }
|
||
let header = "bytes \(range.offset)-\(range.offset + range.compressedBytes - 1)/\(range.archiveBytes)"
|
||
return response.statusCode == 206 && response.value(forHTTPHeaderField: "Content-Range") == header ? range.compressedBytes : nil
|
||
}
|
||
}
|
||
|
||
private enum ArchiveReaderError: LocalizedError {
|
||
case changed, unavailable, location, space, download, page
|
||
var errorDescription: String? {
|
||
switch self {
|
||
case .changed: return "The downloaded file does not match the edition in the Archive index."
|
||
case .unavailable: return "This edition is available at the Archive source."
|
||
case .location: return "The Archive file could not be cached. Check the free space and permissions."
|
||
case .space: return "There is not enough free space to cache this Archive file."
|
||
case .download: return "The Archive file could not be downloaded. Check your connection and try again."
|
||
case .page: return "This PDF could not be opened at the cited page. Use the Archive source to inspect the original."
|
||
}
|
||
}
|
||
}
|
||
|
||
enum ArchiveReadProgress: Sendable {
|
||
case checking, downloading(Int64, Int64), verifying
|
||
}
|
||
|
||
actor ArchiveAssetCache {
|
||
#if VCC_UI_TESTING
|
||
static let shared: ArchiveAssetCache = {
|
||
let directory = ProcessInfo.processInfo.environment["VCC_ARCHIVE_TEST_CACHE"].map { URL(fileURLWithPath: $0, isDirectory: true) }
|
||
?? FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveUITest-" + UUID().uuidString, isDirectory: true)
|
||
return ArchiveAssetCache(directory: directory)
|
||
}()
|
||
#else
|
||
static let shared = ArchiveAssetCache()
|
||
#endif
|
||
private let directory: URL?
|
||
private let configuration: URLSessionConfiguration
|
||
|
||
init(directory: URL? = nil, configuration: URLSessionConfiguration? = nil) {
|
||
self.directory = directory
|
||
if let configuration {
|
||
self.configuration = configuration
|
||
} else {
|
||
let config = URLSessionConfiguration.ephemeral
|
||
config.timeoutIntervalForRequest = 45
|
||
config.timeoutIntervalForResource = 3600
|
||
config.urlCache = nil
|
||
self.configuration = config
|
||
}
|
||
}
|
||
|
||
func localCopy(_ receipt: ArchiveAssetReceipt, progress: @escaping @Sendable (ArchiveReadProgress) -> Void) async throws -> URL {
|
||
try Task.checkCancellation()
|
||
let fm = FileManager.default
|
||
let directory = self.directory ?? AppIdentity.supportDirectory.appendingPathComponent(
|
||
receipt.fileExtension == "pdf" ? "ArchiveLibrary/PDFs" : "ArchiveLibrary/Assets", isDirectory: true)
|
||
try fm.createDirectory(at: directory, withIntermediateDirectories: true)
|
||
let info = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||
guard info.isDirectory == true, info.isSymbolicLink != true else { throw ArchiveReaderError.location }
|
||
let target = directory.appendingPathComponent(receipt.sha256 + "." + receipt.fileExtension)
|
||
progress(.checking)
|
||
if let attributes = try? fm.attributesOfItem(atPath: target.path) {
|
||
guard attributes[.type] as? FileAttributeType == .typeRegular else { throw ArchiveReaderError.location }
|
||
if (attributes[.size] as? NSNumber)?.int64Value == receipt.bytes,
|
||
try SoftwareLibraryManualCache.fingerprint(target) == receipt.sha256 { return target }
|
||
}
|
||
let transferBytes = receipt.memberRange?.compressedBytes ?? receipt.bytes
|
||
let disk = try fm.attributesOfFileSystem(forPath: directory.path)
|
||
let free = (disk[.systemFreeSize] as? NSNumber)?.int64Value
|
||
let reserved: Int64 = 32 * 1024 * 1024 + (receipt.memberRange == nil ? 0 : receipt.bytes)
|
||
if let free, free < transferBytes + reserved { throw ArchiveReaderError.space }
|
||
var request = URLRequest(url: receipt.url)
|
||
request.setValue("VCCPlus/ArchiveLibrary", forHTTPHeaderField: "User-Agent")
|
||
request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
|
||
request.setValue(receipt.rangeHeader, forHTTPHeaderField: "Range")
|
||
let temporary = directory.appendingPathComponent(UUID().uuidString + ".download")
|
||
defer { try? fm.removeItem(at: temporary) }
|
||
let observer = ArchiveAssetTransfer(receipt: receipt, available: free.map { $0 - reserved }, destination: temporary, progress: progress)
|
||
progress(.downloading(0, transferBytes))
|
||
let http = try await observer.download(request, configuration: configuration)
|
||
try Task.checkCancellation()
|
||
progress(.verifying)
|
||
// Only atomically replace the cached edition after its final bytes have been verified.
|
||
let staged = directory.appendingPathComponent(UUID().uuidString + ".partial")
|
||
defer { try? fm.removeItem(at: staged) }
|
||
if let range = receipt.memberRange {
|
||
try Self.unpack(range, from: temporary, offset: http.statusCode == 206 ? 0 : range.offset, to: staged, bytes: receipt.bytes)
|
||
} else {
|
||
try fm.moveItem(at: temporary, to: staged)
|
||
}
|
||
guard try SoftwareLibraryManualCache.fingerprint(staged) == receipt.sha256 else { throw ArchiveReaderError.changed }
|
||
try Task.checkCancellation()
|
||
if fm.fileExists(atPath: target.path) {
|
||
guard try fm.attributesOfItem(atPath: target.path)[.type] as? FileAttributeType == .typeRegular else { throw ArchiveReaderError.location }
|
||
_ = try fm.replaceItemAt(target, withItemAt: staged)
|
||
} else { try fm.moveItem(at: staged, to: target) }
|
||
return target
|
||
}
|
||
|
||
/// No archive paths become local filenames. Decode only the indexed member body
|
||
/// and cap both compressed input and output, including the full-ZIP HTTP 200 path.
|
||
private static func unpack(_ range: ArchiveMemberRange, from source: URL, offset: Int64, to output: URL, bytes: Int64) throws {
|
||
let input = try FileHandle(forReadingFrom: source)
|
||
defer { try? input.close() }
|
||
try input.seek(toOffset: UInt64(offset))
|
||
try Data().write(to: output, options: .withoutOverwriting)
|
||
let writer = try FileHandle(forWritingTo: output)
|
||
defer { try? writer.close() }
|
||
var written: Int64 = 0
|
||
func write(_ chunk: Data?) throws {
|
||
try Task.checkCancellation()
|
||
guard let chunk else { return }
|
||
written += Int64(chunk.count)
|
||
guard written <= bytes else { throw ArchiveReaderError.changed }
|
||
try writer.write(contentsOf: chunk)
|
||
}
|
||
let decoder = range.method == 8 ? try OutputFilter(.decompress, using: .zlib, writingTo: write) : nil
|
||
var remaining = range.compressedBytes
|
||
while remaining > 0 {
|
||
try Task.checkCancellation()
|
||
guard let chunk = try input.read(upToCount: Int(min(remaining, 65536))), !chunk.isEmpty else { throw ArchiveReaderError.changed }
|
||
remaining -= Int64(chunk.count)
|
||
if let decoder { try decoder.write(chunk) } else { try write(chunk) }
|
||
}
|
||
try decoder?.finalize()
|
||
guard written == bytes else { throw ArchiveReaderError.changed }
|
||
}
|
||
}
|
||
|
||
private final class ArchiveAssetTransfer: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
|
||
private let receipt: ArchiveAssetReceipt
|
||
private let available: Int64?
|
||
private let destination: URL
|
||
private let progress: @Sendable (ArchiveReadProgress) -> Void
|
||
private let lock = NSLock() // Synchronizes task registration, cancellation, and completion.
|
||
private var continuation: CheckedContinuation<HTTPURLResponse, Error>?
|
||
// Foundation invokes the callbacks below on this session's serial delegate queue.
|
||
private var rejection: ArchiveReaderError?
|
||
private var lastReport: UInt64 = 0
|
||
private var response: HTTPURLResponse?
|
||
|
||
init(receipt: ArchiveAssetReceipt, available: Int64?, destination: URL, progress: @escaping @Sendable (ArchiveReadProgress) -> Void) {
|
||
self.receipt = receipt
|
||
self.available = available
|
||
self.destination = destination
|
||
self.progress = progress
|
||
}
|
||
|
||
func download(_ request: URLRequest, configuration: URLSessionConfiguration) async throws -> HTTPURLResponse {
|
||
// The async download(for:) helper does not forward incremental download
|
||
// callbacks. An explicit delegate task also lets us enforce the byte cap in flight.
|
||
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
|
||
defer { session.invalidateAndCancel() }
|
||
let task = session.downloadTask(with: request)
|
||
let result = try await withTaskCancellationHandler {
|
||
try await withCheckedThrowingContinuation { (reply: CheckedContinuation<HTTPURLResponse, Error>) in
|
||
lock.withLock {
|
||
guard !Task.isCancelled else { reply.resume(throwing: CancellationError()); return }
|
||
continuation = reply
|
||
task.resume()
|
||
}
|
||
}
|
||
} onCancel: {
|
||
if self.lock.withLock({ self.continuation != nil }) { task.cancel() }
|
||
}
|
||
try Task.checkCancellation()
|
||
return result
|
||
}
|
||
|
||
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
||
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
|
||
guard let url = request.url, receipt.acceptsResponseURL(url) else { completionHandler(nil); return }
|
||
var redirected = request
|
||
redirected.setValue(receipt.rangeHeader, forHTTPHeaderField: "Range")
|
||
redirected.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
|
||
completionHandler(redirected)
|
||
}
|
||
|
||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
|
||
guard rejection == nil, let http = downloadTask.response as? HTTPURLResponse, let expected = receipt.responseSize(http) else {
|
||
rejection = rejection ?? .download
|
||
return
|
||
}
|
||
guard available.map({ expected <= $0 }) ?? true else { rejection = .space; return }
|
||
do {
|
||
guard (try location.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) == expected else {
|
||
rejection = .changed
|
||
return
|
||
}
|
||
// Foundation removes its temporary file when this delegate method returns.
|
||
try FileManager.default.moveItem(at: location, to: destination)
|
||
response = http
|
||
} catch { rejection = .location }
|
||
}
|
||
|
||
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
||
let reply = lock.withLock {
|
||
let reply = continuation
|
||
continuation = nil
|
||
return reply
|
||
}
|
||
if let rejection { reply?.resume(throwing: rejection) }
|
||
else if (error as? URLError)?.code == .cancelled { reply?.resume(throwing: CancellationError()) }
|
||
else if error == nil, let response { reply?.resume(returning: response) }
|
||
else { reply?.resume(throwing: ArchiveReaderError.download) }
|
||
}
|
||
|
||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
|
||
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||
guard let response = downloadTask.response as? HTTPURLResponse, let expected = receipt.responseSize(response) else {
|
||
rejection = .download
|
||
downloadTask.cancel()
|
||
return
|
||
}
|
||
guard totalBytesWritten <= expected, totalBytesExpectedToWrite <= expected else {
|
||
rejection = .changed
|
||
downloadTask.cancel()
|
||
return
|
||
}
|
||
if let available, expected > available {
|
||
rejection = .space
|
||
downloadTask.cancel()
|
||
return
|
||
}
|
||
let now = DispatchTime.now().uptimeNanoseconds
|
||
guard lastReport == 0 || now - lastReport >= 120_000_000 || totalBytesWritten == expected else { return }
|
||
lastReport = now
|
||
progress(.downloading(totalBytesWritten, expected))
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
final class ArchiveReaderModel: ObservableObject {
|
||
let view = PDFView()
|
||
@Published private(set) var referenceID: String?
|
||
@Published private(set) var document: PDFDocument?
|
||
@Published private(set) var preview: ArchiveInlineContent?
|
||
@Published private(set) var sectionLabel: String?
|
||
@Published private(set) var cancelled = false
|
||
@Published private(set) var progress: ArchiveReadProgress?
|
||
@Published private(set) var error: String?
|
||
@Published private(set) var page = 1
|
||
@Published var find = "" { didSet { if find != oldValue { resetFind() } } }
|
||
@Published private(set) var findMessage: String?
|
||
@Published private(set) var isFinding = false
|
||
private var request: Task<Void, Never>?
|
||
private var findTask: Task<Void, Never>?
|
||
private var findRequestID = UUID()
|
||
private var requestID = UUID()
|
||
private var localURL: URL?
|
||
private var lastMatch: (page: Int, range: NSRange)?
|
||
private var pendingPage = 1
|
||
let remembersPage: Bool
|
||
private let cache: ArchiveAssetCache
|
||
private let catalog: ArchiveLibraryCatalog
|
||
|
||
init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared) {
|
||
self.remembersPage = remembersPage
|
||
self.cache = cache
|
||
self.catalog = catalog
|
||
view.displayMode = .singlePageContinuous
|
||
view.autoScales = true
|
||
view.displaysPageBreaks = true
|
||
view.setAccessibilityLabel("Archive PDF")
|
||
}
|
||
func stop() {
|
||
requestID = UUID(); request?.cancel(); request = nil; progress = nil
|
||
resetFind()
|
||
}
|
||
func reset() {
|
||
stop()
|
||
document = nil; view.document = nil; preview = nil; sectionLabel = nil
|
||
referenceID = nil; error = nil; localURL = nil; page = 1; find = ""; cancelled = false
|
||
}
|
||
func cancel() {
|
||
stop()
|
||
cancelled = true
|
||
}
|
||
func retry(_ record: ArchiveDocument) {
|
||
open(record, page: pendingPage)
|
||
}
|
||
private func rememberPage() {
|
||
if remembersPage, let referenceID { UserDefaults.standard.set(page, forKey: "archive-library.page." + referenceID) }
|
||
}
|
||
static func savedPage(for id: String) -> Int { max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) }
|
||
func updatePage() {
|
||
guard let document, let current = view.currentPage, current.document === document else { return }
|
||
let index = document.index(for: current)
|
||
guard index >= 0, index < document.pageCount else { return }
|
||
page = index + 1
|
||
rememberPage()
|
||
}
|
||
func go(to number: Int) {
|
||
guard let document, number > 0, number <= document.pageCount, let target = document.page(at: number - 1) else { return }
|
||
view.go(to: target); updatePage()
|
||
}
|
||
func open(_ record: ArchiveDocument, page number: Int) {
|
||
if referenceID == record.id {
|
||
if document != nil { go(to: number); return }
|
||
if preview != nil && page == number { return }
|
||
if progress != nil && (record.format == "pdf" || number == pendingPage) {
|
||
pendingPage = number
|
||
return
|
||
}
|
||
}
|
||
reset()
|
||
referenceID = record.id
|
||
pendingPage = number
|
||
let identity = requestID
|
||
progress = .checking
|
||
request = Task {
|
||
do {
|
||
switch record.format {
|
||
case "pdf", "image", "text":
|
||
guard let receipt = ArchiveAssetReceipt(document: record) else { throw ArchiveReaderError.unavailable }
|
||
let url = try await cache.localCopy(receipt) { event in
|
||
Task { @MainActor in
|
||
guard self.requestID == identity, self.progress != nil else { return }
|
||
self.progress = event
|
||
}
|
||
}
|
||
try Task.checkCancellation()
|
||
if record.format == "pdf" {
|
||
let parsed = await Task.detached(priority: .userInitiated) { PDFDocument(url: url) }.value
|
||
try Task.checkCancellation()
|
||
let target = pendingPage
|
||
guard let parsed, !parsed.isLocked, target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page }
|
||
localURL = url; document = parsed; view.document = parsed; view.autoScales = true; go(to: target)
|
||
} else {
|
||
let content = try await ArchivePreviewDecoder.shared.read(url, format: record.format, number: number)
|
||
try Task.checkCancellation()
|
||
page = number; preview = content; rememberPage()
|
||
}
|
||
default:
|
||
guard let section = try await catalog.readerSection(documentID: record.id, number: number) else {
|
||
throw ArchiveReaderError.unavailable
|
||
}
|
||
try Task.checkCancellation()
|
||
page = section.number; sectionLabel = section.label
|
||
preview = record.format == "office-xls" ? .worksheet(section.text) : .text(section.text)
|
||
rememberPage()
|
||
}
|
||
progress = nil
|
||
} catch {
|
||
guard requestID == identity else { return }
|
||
progress = nil
|
||
if !Task.isCancelled { self.error = error.localizedDescription }
|
||
}
|
||
}
|
||
}
|
||
private func resetFind() {
|
||
findRequestID = UUID(); findTask?.cancel(); findTask = nil; isFinding = false; findMessage = nil; lastMatch = nil
|
||
}
|
||
func findNext() {
|
||
guard let localURL, let document, !isFinding, !find.isEmpty else { return }
|
||
let text = find, current = page
|
||
let start = lastMatch.flatMap { $0.page == page ? NSMaxRange($0.range) : nil } ?? 0
|
||
let identity = UUID(); findRequestID = identity; isFinding = true; findMessage = nil
|
||
findTask = Task {
|
||
let result = await Self.nextMatch(in: localURL, text: text, page: current, start: start)
|
||
guard !Task.isCancelled, findRequestID == identity, self.document === document else { return }
|
||
isFinding = false
|
||
guard let (number, range) = result, let target = document.page(at: number - 1), let selection = target.selection(for: range) else {
|
||
findMessage = "No matching text in the PDF’s text layer."; return
|
||
}
|
||
view.setCurrentSelection(selection, animate: false); view.go(to: selection); updatePage(); lastMatch = (number, range)
|
||
}
|
||
}
|
||
private nonisolated static func nextMatch(in url: URL, text: String, page: Int, start: Int) async -> (Int, NSRange)? {
|
||
guard let doc = PDFDocument(url: url), doc.pageCount > 0, page > 0, page <= doc.pageCount else { return nil }
|
||
for offset in 0...doc.pageCount {
|
||
if Task.isCancelled { return nil }
|
||
let index = (page - 1 + offset) % doc.pageCount
|
||
let match: NSRange? = autoreleasepool {
|
||
guard let raw = doc.page(at: index)?.string as NSString? else { return nil }
|
||
let lower = offset == 0 ? min(start, raw.length) : 0
|
||
let upper = offset == doc.pageCount ? min(start, raw.length) : raw.length
|
||
let range = raw.range(of: text, options: [.caseInsensitive], range: NSRange(location: lower, length: upper - lower))
|
||
return range.location == NSNotFound ? nil : range
|
||
}
|
||
if let match { return (index + 1, match) }
|
||
}
|
||
return nil
|
||
}
|
||
}
|
||
|
||
private struct ArchivePDFSurface: NSViewRepresentable {
|
||
let view: PDFView
|
||
func makeNSView(context: Context) -> PDFView { view }
|
||
func updateNSView(_ nsView: PDFView, context: Context) {}
|
||
}
|
||
|
||
struct ArchiveReaderPane: View {
|
||
let record: ArchiveDocument
|
||
let hit: ArchiveHit?
|
||
@ObservedObject var reader: ArchiveReaderModel
|
||
let requestedPage: Int
|
||
let catalog: ArchiveLibraryCatalog
|
||
@Environment(\.openWindow) private var openWindow
|
||
@State private var examples: [ArchiveExample] = []
|
||
@State private var exampleError: String?
|
||
@State private var loadedExampleKey: String?
|
||
@State private var copies: String?
|
||
@State private var pageField = "1"
|
||
@FocusState private var findFocused: Bool
|
||
|
||
private var isCurrent: Bool { reader.referenceID == record.id }
|
||
private var loaded: Bool { isCurrent && reader.document != nil }
|
||
private var visiblePage: Int? {
|
||
guard record.format == "pdf" else { return nil }
|
||
return loaded ? reader.page : (hit?.page ?? requestedPage)
|
||
}
|
||
private var exampleKey: String { record.id + "/" + String(visiblePage ?? 0) }
|
||
private var atHit: Bool {
|
||
guard let hit else { return false }
|
||
if loaded || (isCurrent && reader.preview != nil) { return hit.locationNumber == reader.page }
|
||
return true
|
||
}
|
||
private var source: URL {
|
||
if atHit, let hit { return hit.sourceURL }
|
||
guard record.memberPath == nil, record.sourceURL.pathExtension.lowercased() == "pdf", let visiblePage,
|
||
var parts = URLComponents(url: record.sourceURL, resolvingAgainstBaseURL: false) else { return record.sourceURL }
|
||
parts.fragment = "page=\(visiblePage)"; return parts.url ?? record.sourceURL
|
||
}
|
||
private var citation: String {
|
||
if atHit, let hit { return hit.citation }
|
||
return record.cite(visiblePage.map { "PDF page \($0)" } ?? (isCurrent ? reader.sectionLabel : nil), at: source)
|
||
}
|
||
var body: some View {
|
||
VStack(alignment: .leading, spacing: 0) {
|
||
VStack(alignment: .leading, spacing: 5) {
|
||
Text(record.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary)
|
||
Text(record.title).font(.title3.weight(.semibold)).lineLimit(3).textSelection(.enabled)
|
||
if let member = record.memberPath { Text("ZIP member · " + member).font(.caption).textSelection(.enabled) }
|
||
if atHit, let hit { Label(hit.locator + (hit.ocr ? " · OCR match" : ""), systemImage: "text.magnifyingglass").font(.caption).foregroundStyle(.secondary) }
|
||
if loadedExampleKey == exampleKey, !examples.isEmpty { exampleActions }
|
||
if let exampleError { Text(exampleError).font(.caption).foregroundStyle(.secondary) }
|
||
}.padding(12)
|
||
Divider()
|
||
if loaded, let pdf = reader.document {
|
||
VStack(spacing: 7) {
|
||
HStack {
|
||
Button { reader.go(to: reader.page - 1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous PDF page").disabled(reader.page <= 1)
|
||
TextField("Page", text: $pageField).frame(width: 46).accessibilityLabel("PDF page number").onSubmit {
|
||
if let n = Int(pageField) { reader.go(to: min(max(n, 1), pdf.pageCount)) }; pageField = String(reader.page)
|
||
}
|
||
Text("of \(pdf.pageCount)").foregroundStyle(.secondary)
|
||
Button { reader.go(to: reader.page + 1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next PDF page").disabled(reader.page >= pdf.pageCount)
|
||
Spacer()
|
||
Button { reader.view.zoomOut(nil) } label: { Image(systemName: "minus.magnifyingglass") }.accessibilityLabel("Zoom out")
|
||
Button { reader.view.zoomIn(nil) } label: { Image(systemName: "plus.magnifyingglass") }.accessibilityLabel("Zoom in")
|
||
Button("Fit") { reader.view.autoScales = true }.accessibilityLabel("Fit page")
|
||
}
|
||
HStack {
|
||
Button { findFocused = true } label: { Image(systemName: "magnifyingglass") }
|
||
.buttonStyle(.borderless).keyboardShortcut("f").accessibilityLabel("Focus Find in PDF")
|
||
TextField("Find in PDF", text: $reader.find).focused($findFocused).onSubmit { reader.findNext() }.accessibilityIdentifier("archive-pdf-find")
|
||
if reader.isFinding { ProgressView().controlSize(.small) }
|
||
Button("Find Next") { reader.findNext() }.keyboardShortcut("g").disabled(reader.find.isEmpty || reader.isFinding)
|
||
}
|
||
if let message = reader.findMessage { Text(message).font(.caption).foregroundStyle(.secondary) }
|
||
}.padding(8)
|
||
ArchivePDFSurface(view: reader.view).id(ObjectIdentifier(reader.view)).accessibilityIdentifier("archive-pdf-surface")
|
||
.onReceive(NotificationCenter.default.publisher(for: .PDFViewPageChanged, object: reader.view)) { _ in reader.updatePage() }
|
||
} else if isCurrent, let preview = reader.preview {
|
||
if let count = record.pageCount, count > 1 {
|
||
HStack {
|
||
Button { reader.open(record, page: reader.page - 1) } label: { Image(systemName: "chevron.left") }
|
||
.accessibilityLabel("Previous section").disabled(reader.page <= 1)
|
||
TextField("Section", text: $pageField).frame(width: 44).accessibilityLabel("Section number").onSubmit {
|
||
if let n = Int(pageField) { reader.open(record, page: min(max(n, 1), count)) }
|
||
pageField = String(reader.page)
|
||
}
|
||
Text("of \(count)")
|
||
Button { reader.open(record, page: reader.page + 1) } label: { Image(systemName: "chevron.right") }
|
||
.accessibilityLabel("Next section").disabled(reader.page >= count)
|
||
if let label = reader.sectionLabel { Text(label).lineLimit(2).help(label) }
|
||
Spacer(minLength: 0)
|
||
}.padding(8)
|
||
}
|
||
ArchiveInlinePreview(content: preview, title: record.title)
|
||
.id(record.id + "/" + String(reader.page))
|
||
} else {
|
||
VStack(spacing: 12) {
|
||
if isCurrent, let progress = reader.progress {
|
||
switch progress {
|
||
case .checking: ProgressView("Opening document…")
|
||
case .verifying: ProgressView("Verifying download…")
|
||
case .downloading(let done, let total):
|
||
ProgressView(value: Double(done), total: Double(total)) { Text("Downloading…") }
|
||
Text(ByteCountFormatter.string(fromByteCount: done, countStyle: .file) + " of " + ByteCountFormatter.string(fromByteCount: total, countStyle: .file)).font(.caption).monospacedDigit()
|
||
}
|
||
Button("Cancel") { reader.cancel() }
|
||
} else if isCurrent, reader.error != nil || reader.cancelled {
|
||
Text(reader.error ?? "Loading cancelled.").multilineTextAlignment(.center)
|
||
Button("Try Again") { reader.retry(record) }
|
||
} else {
|
||
ProgressView("Opening document…")
|
||
}
|
||
}.padding(16).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||
}
|
||
Divider()
|
||
HStack {
|
||
VStack(alignment: .leading, spacing: 3) {
|
||
Text("Color Computer Archive").font(.caption).foregroundStyle(.secondary)
|
||
Link("Archive source", destination: source)
|
||
}
|
||
Spacer()
|
||
if let copies { Text(copies).font(.caption).foregroundStyle(.secondary) }
|
||
Button("Copy Citation") { copy(citation, success: "Citation copied") }.accessibilityIdentifier("archive-copy-citation")
|
||
}.padding(10)
|
||
}
|
||
.onChange(of: reader.page, initial: true) { _, value in pageField = String(value) }
|
||
.task(id: hit?.id ?? record.id) {
|
||
guard !Task.isCancelled else { return }
|
||
reader.open(record, page: requestedPage)
|
||
}
|
||
.task(id: exampleKey) {
|
||
examples = []; loadedExampleKey = nil; exampleError = nil; copies = nil
|
||
guard let page = visiblePage else { return }
|
||
do {
|
||
let entries = try await catalog.examples(documentID: record.id, page: page)
|
||
try Task.checkCancellation()
|
||
examples = entries; loadedExampleKey = exampleKey
|
||
} catch { if !Task.isCancelled { exampleError = "Example information could not be read." } }
|
||
}
|
||
}
|
||
@ViewBuilder private var exampleActions: some View {
|
||
if let first = examples.first, examples.count == 1 {
|
||
HStack {
|
||
Button(first.kind == "snippet" ? "Copy Snippet" : "Copy Example") { copy(first.source, success: "Source copied") }
|
||
.help(first.title + " · " + first.author + "\n" + first.provenance)
|
||
if first.kind == "basic_program" { Button("Open in BASIC Editor") { openExample(first) } }
|
||
Menu { Text(first.title); Text(first.language); Text(first.author); Text(first.provenance) } label: { Image(systemName: "info.circle") }
|
||
.menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Example source information")
|
||
}
|
||
} else {
|
||
Menu("Examples on this page") {
|
||
ForEach(examples) { item in
|
||
Menu(item.title) {
|
||
Button(item.kind == "snippet" ? "Copy Snippet" : "Copy Example") { copy(item.source, success: "Source copied") }
|
||
if item.kind == "basic_program" { Button("Open in BASIC Editor") { openExample(item) } }
|
||
Divider(); Text(item.author); Text(item.language); Text(item.provenance)
|
||
}
|
||
}
|
||
}.fixedSize().accessibilityIdentifier("archive-examples")
|
||
}
|
||
}
|
||
private func openExample(_ item: ArchiveExample) { openWindow(id: "basic-example", value: "archive/" + item.sourceSHA256) }
|
||
private func copy(_ text: String, success: String) {
|
||
let pasteboard = NSPasteboard.general
|
||
pasteboard.clearContents(); copies = pasteboard.setString(text, forType: .string) ? success : "Copy failed"
|
||
}
|
||
}
|