337 lines
20 KiB
Swift
337 lines
20 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import SwiftUI
|
||
import PDFKit
|
||
import CryptoKit
|
||
|
||
/// Original PDF and plain-text bytes are verified and retained separately from disposable art.
|
||
actor SoftwareLibraryManualCache {
|
||
static let shared = SoftwareLibraryManualCache()
|
||
static let maximumBytes: Int64 = 512 * 1024 * 1024
|
||
enum Failure: LocalizedError {
|
||
case unavailable, response, changed
|
||
var errorDescription: String? {
|
||
switch self {
|
||
case .unavailable: return "This manual is not yet available in the reader."
|
||
case .response: return "The manual could not be downloaded. Please try again."
|
||
case .changed: return "The manual did not match the catalog’s saved copy. Please try again later."
|
||
}
|
||
}
|
||
}
|
||
private let session: URLSession
|
||
init(session: URLSession? = nil) {
|
||
if let session { self.session = session }
|
||
else {
|
||
let config = URLSessionConfiguration.ephemeral
|
||
config.timeoutIntervalForRequest = 30; config.timeoutIntervalForResource = 300
|
||
config.urlCache = nil
|
||
self.session = URLSession(configuration: config, delegate: ManualRedirects(), delegateQueue: nil)
|
||
}
|
||
}
|
||
static func accepts(_ url: URL) -> Bool {
|
||
url.scheme == "https" && url.host == "vccplus.brianholman.com" && url.user == nil && url.password == nil
|
||
&& (url.port == nil || url.port == 443) && url.query == nil && url.fragment == nil
|
||
&& url.path.hasPrefix("/dl/software/CoCoLibrary/Documents/Manuals/") && ["pdf", "txt"].contains(url.pathExtension.lowercased())
|
||
&& !url.pathComponents.contains("..") && !url.pathComponents.contains(".") && !url.path.contains("\\")
|
||
}
|
||
static func fingerprint(_ url: URL) throws -> String {
|
||
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
||
var hash = SHA256()
|
||
while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty {
|
||
try Task.checkCancellation(); hash.update(data: block)
|
||
}
|
||
return hash.finalize().map { String(format: "%02x", $0) }.joined()
|
||
}
|
||
func localCopy(for asset: SoftwareLibraryAsset, directory: URL) async throws -> URL {
|
||
try Task.checkCancellation()
|
||
guard asset.isManual, let url = asset.manualURL, Self.accepts(url),
|
||
let hash = asset.sha256, hash.count == 64, hash.allSatisfy({ $0.isHexDigit }),
|
||
let size = asset.byteSize, size > 0, size <= (url.pathExtension.lowercased() == "txt" ? 1024 * 1024 : Self.maximumBytes), directory.isFileURL else { throw Failure.unavailable }
|
||
let target = directory.appendingPathComponent(hash.lowercased() + "." + url.pathExtension.lowercased())
|
||
if let values = try? target.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]),
|
||
values.isRegularFile == true, values.isSymbolicLink != true, values.fileSize == Int(size),
|
||
try Self.fingerprint(target) == hash.lowercased() { return target }
|
||
var request = URLRequest(url: url); request.setValue("VCCPlus/SoftwareLibrary-Manual", forHTTPHeaderField: "User-Agent")
|
||
let (temporary, response) = try await session.download(for: request)
|
||
defer { try? FileManager.default.removeItem(at: temporary) }
|
||
try Task.checkCancellation()
|
||
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
|
||
let final = http.url, Self.accepts(final) else { throw Failure.response }
|
||
let actualSize = try temporary.resourceValues(forKeys: [.fileSizeKey]).fileSize
|
||
guard actualSize == Int(size), try Self.fingerprint(temporary) == hash.lowercased() else { throw Failure.changed }
|
||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||
guard !((try? target.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) ?? false) else { throw Failure.unavailable }
|
||
let staged = directory.appendingPathComponent(UUID().uuidString + ".partial")
|
||
defer { try? FileManager.default.removeItem(at: staged) }
|
||
try FileManager.default.copyItem(at: temporary, to: staged)
|
||
try Task.checkCancellation()
|
||
if FileManager.default.fileExists(atPath: target.path) {
|
||
_ = try FileManager.default.replaceItemAt(target, withItemAt: staged)
|
||
} else { try FileManager.default.moveItem(at: staged, to: target) }
|
||
return target
|
||
}
|
||
}
|
||
private final class ManualRedirects: NSObject, URLSessionTaskDelegate {
|
||
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
||
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
|
||
completionHandler(request.url.map(SoftwareLibraryManualCache.accepts) == true ? request : nil)
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
final class SoftwareLibraryManualModel: ObservableObject {
|
||
@Published private(set) var asset: SoftwareLibraryAsset?
|
||
@Published private(set) var loading = false
|
||
@Published private(set) var error: String?
|
||
@Published private(set) var document: PDFDocument?
|
||
@Published private(set) var text: String?
|
||
let textView = NSTextView()
|
||
static func decodeText(_ data: Data) throws -> String {
|
||
guard !data.isEmpty, data.count <= 1024 * 1024,
|
||
!data.contains(where: { $0 < 32 && ![9, 10, 12, 13, 26].contains($0) }),
|
||
let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {
|
||
throw SoftwareLibraryManualCache.Failure.response
|
||
}
|
||
return text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
|
||
.replacingOccurrences(of: "\u{0C}", with: "\n\n").replacingOccurrences(of: "\u{1A}", with: "")
|
||
}
|
||
func findInText() {
|
||
let item = NSMenuItem(); item.tag = NSTextFinder.Action.showFindInterface.rawValue
|
||
textView.performFindPanelAction(item)
|
||
}
|
||
@Published var page = 1
|
||
@Published var searchText = ""
|
||
@Published var searchMessage = ""
|
||
let pdfView = PDFView()
|
||
private var task: Task<Void, Never>?
|
||
private var directory: URL?
|
||
private var companion: (any CompanionLibraryAccess)?
|
||
#if !VCC_COMPANION_CLIENT
|
||
var continuity: LibraryContinuityStore?
|
||
#endif
|
||
private var positionTracking: [NSObjectProtocol] = []
|
||
private var lastPositionSave = Date.distantPast
|
||
private var restoringPosition = false
|
||
func open(_ asset: SoftwareLibraryAsset, directory: URL, companion: (any CompanionLibraryAccess)? = nil) {
|
||
if self.asset?.id == asset.id && (document != nil || text != nil) { return }
|
||
saveReadingPosition(force: true)
|
||
task?.cancel(); self.asset = asset; self.directory = directory; self.companion = companion
|
||
document = nil; pdfView.document = nil; text = nil; textView.string = ""; page = 1; searchText = ""; searchMessage = ""; error = nil; loading = true
|
||
task = Task {
|
||
do {
|
||
let local: URL
|
||
if let companion {
|
||
let response = try await companion.libraryRequest(.init(operation: .manual, assetID: asset.id))
|
||
if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) }
|
||
guard let shared = response.assetFileURL, shared.isFileURL,
|
||
shared.host.map({ $0.isEmpty || $0 == "localhost" }) != false,
|
||
shared.query == nil, shared.fragment == nil else { throw SoftwareLibraryManualCache.Failure.response }
|
||
try await Task.detached(priority: .userInitiated) {
|
||
let values = try shared.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||
guard values.isRegularFile == true, values.isSymbolicLink != true,
|
||
let size = values.fileSize, size > 0, size <= 64 * 1024 * 1024 else { throw SoftwareLibraryManualCache.Failure.response }
|
||
}.value
|
||
local = shared
|
||
} else if asset.matchStatus == "personal", let url = asset.manualURL, url.isFileURL {
|
||
local = try await Task.detached(priority: .userInitiated) {
|
||
try SoftwareLibraryLocalAsset.validate(asset, url: url, maximumBytes: url.pathExtension.lowercased() == "txt" ? 1024 * 1024 : 512 * 1024 * 1024)
|
||
return url
|
||
}.value
|
||
} else {
|
||
local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset, directory: directory)
|
||
}
|
||
try Task.checkCancellation()
|
||
if local.pathExtension.lowercased() == "txt" {
|
||
let bytes = try await Task.detached(priority: .userInitiated) { try Data(contentsOf: local) }.value
|
||
try Task.checkCancellation()
|
||
let decoded = try Self.decodeText(bytes)
|
||
text = decoded; textView.string = decoded
|
||
} else {
|
||
guard let loaded = PDFDocument(url: local), !loaded.isLocked, loaded.pageCount > 0 else { throw SoftwareLibraryManualCache.Failure.response }
|
||
document = loaded; pdfView.document = loaded; pdfView.autoScales = true
|
||
}
|
||
loading = false
|
||
} catch is CancellationError { }
|
||
catch { self.error = error.localizedDescription; loading = false }
|
||
}
|
||
}
|
||
func cancel() { saveReadingPosition(force: true); task?.cancel(); loading = false; stopPositionTracking() }
|
||
func retry() { if let asset, let directory { open(asset, directory: directory, companion: companion) } }
|
||
func goToPage() {
|
||
guard let document else { return }
|
||
page = min(max(page, 1), document.pageCount)
|
||
if let target = document.page(at: page - 1) { pdfView.go(to: target) }
|
||
}
|
||
func findNext() {
|
||
guard let document, !searchText.isEmpty else { return }
|
||
let selection = document.findString(searchText, fromSelection: pdfView.currentSelection, withOptions: .caseInsensitive)
|
||
?? document.findString(searchText, fromSelection: nil, withOptions: .caseInsensitive)
|
||
if let selection { pdfView.setCurrentSelection(selection, animate: false); pdfView.go(to: selection); searchMessage = "" }
|
||
else { searchMessage = "No matching text. Scanned pages may not contain searchable text." }
|
||
}
|
||
func stopPositionTracking() {
|
||
for token in positionTracking { NotificationCenter.default.removeObserver(token) }
|
||
positionTracking = []
|
||
}
|
||
func restoreReadingPosition() {
|
||
#if !VCC_COMPANION_CLIENT
|
||
guard companion == nil, let asset, let continuity else { return }
|
||
let identity = asset.id
|
||
let saved = continuity.reading(for: "software-manual:" + identity)
|
||
restoringPosition = true
|
||
DispatchQueue.main.async { [weak self] in
|
||
guard let self, self.asset?.id == identity else { return }
|
||
defer { self.restoringPosition = false; self.trackReadingPosition() }
|
||
if let saved, let document = self.document {
|
||
let index = min(max(0,saved.page-1),document.pageCount-1)
|
||
self.page = index+1
|
||
if let page = document.page(at: index) {
|
||
self.pdfView.autoScales = saved.autoScales ?? true
|
||
if saved.autoScales == false, let zoom = saved.zoom { self.pdfView.scaleFactor = min(10,max(0.1,zoom)) }
|
||
let bounds = page.bounds(for: self.pdfView.displayBox)
|
||
self.pdfView.go(to: PDFDestination(page: page, at: CGPoint(x: bounds.minX + bounds.width * saved.horizontalOffset,
|
||
y: bounds.minY + bounds.height * saved.offset)))
|
||
}
|
||
} else if let saved, let clip = self.textView.enclosingScrollView?.contentView {
|
||
let height = max(0,self.textView.bounds.height - clip.bounds.height)
|
||
clip.scroll(to: NSPoint(x: 0,y: height * saved.offset))
|
||
self.textView.enclosingScrollView?.reflectScrolledClipView(clip)
|
||
}
|
||
}
|
||
#endif
|
||
}
|
||
private func trackReadingPosition() {
|
||
stopPositionTracking()
|
||
for name in [Notification.Name.PDFViewPageChanged, .PDFViewScaleChanged] {
|
||
positionTracking.append(NotificationCenter.default.addObserver(forName: name, object: pdfView, queue: .main) { [weak self] _ in
|
||
Task { @MainActor [weak self] in self?.saveReadingPosition(force: true) }
|
||
})
|
||
}
|
||
let clip = document == nil ? textView.enclosingScrollView?.contentView : pdfView.documentView?.enclosingScrollView?.contentView
|
||
if let clip {
|
||
clip.postsBoundsChangedNotifications = true
|
||
positionTracking.append(NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: clip, queue: .main) { [weak self] _ in
|
||
Task { @MainActor [weak self] in self?.saveReadingPosition() }
|
||
})
|
||
}
|
||
}
|
||
func saveReadingPosition(force: Bool = false) {
|
||
#if !VCC_COMPANION_CLIENT
|
||
guard !restoringPosition, companion == nil, let asset, let continuity, document != nil || text != nil,
|
||
force || Date().timeIntervalSince(lastPositionSave) >= 1 else { return }
|
||
lastPositionSave = Date()
|
||
var position = LibraryReadingPosition(documentID: asset.id,page: page)
|
||
if let document, let destination = pdfView.currentDestination, let current = destination.page {
|
||
position.page = document.index(for: current)+1
|
||
let bounds = current.bounds(for: pdfView.displayBox)
|
||
position.offset = bounds.height > 0 ? min(1,max(0,(destination.point.y-bounds.minY)/bounds.height)) : 0
|
||
position.horizontalOffset = bounds.width > 0 ? min(1,max(0,(destination.point.x-bounds.minX)/bounds.width)) : 0
|
||
position.zoom = pdfView.scaleFactor; position.autoScales = pdfView.autoScales
|
||
} else if let clip = textView.enclosingScrollView?.contentView {
|
||
position.offset = min(1,max(0,clip.bounds.minY / max(1,textView.bounds.height - clip.bounds.height)))
|
||
}
|
||
continuity.setReading(position, for: "software-manual:" + asset.id)
|
||
#endif
|
||
}
|
||
}
|
||
|
||
struct SoftwareLibraryManualView: View {
|
||
@ObservedObject var model: SoftwareLibraryManualModel
|
||
@State private var showPages = false
|
||
var body: some View {
|
||
VStack(spacing: 0) {
|
||
HStack {
|
||
Label(model.asset?.name ?? "Software Manual", systemImage: "book.closed").font(.headline).lineLimit(2)
|
||
Spacer()
|
||
if model.text != nil {
|
||
Button { model.findInText() } label: { Label("Find", systemImage: "magnifyingglass") }
|
||
.accessibilityIdentifier("manual-text-find")
|
||
}
|
||
if model.document != nil {
|
||
Button { showPages.toggle() } label: { Image(systemName: "sidebar.left") }.help(showPages ? "Hide page thumbnails" : "Show page thumbnails").accessibilityLabel(showPages ? "Hide page thumbnails" : "Show page thumbnails")
|
||
Button { model.pdfView.zoomOut(nil) } label: { Image(systemName: "minus.magnifyingglass") }.help("Zoom out").accessibilityLabel("Zoom out")
|
||
Button { model.pdfView.zoomIn(nil) } label: { Image(systemName: "plus.magnifyingglass") }.help("Zoom in").accessibilityLabel("Zoom in")
|
||
Button("Fit Page") { model.pdfView.autoScales = true }.accessibilityIdentifier("manual-fit")
|
||
}
|
||
}.padding(12)
|
||
if let document = model.document {
|
||
HStack {
|
||
Button { model.pdfView.goToPreviousPage(nil) } label: { Image(systemName: "chevron.left") }.help("Previous page").accessibilityLabel("Previous page").disabled(model.page <= 1)
|
||
TextField("Page", value: $model.page, format: .number).frame(width: 45).onSubmit { model.goToPage() }.accessibilityLabel("Page number")
|
||
Text("of \(document.pageCount)").foregroundStyle(.secondary)
|
||
Button { model.pdfView.goToNextPage(nil) } label: { Image(systemName: "chevron.right") }.help("Next page").accessibilityLabel("Next page").disabled(model.page >= document.pageCount)
|
||
Spacer()
|
||
TextField("Find in manual", text: $model.searchText).frame(maxWidth: 230).onSubmit { model.findNext() }.accessibilityIdentifier("manual-search")
|
||
Button("Find Next") { model.findNext() }.disabled(model.searchText.isEmpty)
|
||
}.padding(.horizontal, 12).padding(.bottom, 10)
|
||
}
|
||
Divider()
|
||
if model.document != nil {
|
||
HStack(spacing: 0) {
|
||
if showPages { ManualPages(view: model.pdfView).frame(width: 115) }
|
||
ManualPDF(view: model.pdfView).accessibilityIdentifier("manual-pdf").onAppear { model.restoreReadingPosition() }
|
||
}
|
||
} else if model.text != nil {
|
||
ManualText(view: model.textView).accessibilityIdentifier("manual-text").onAppear { model.restoreReadingPosition() }
|
||
} else if model.loading {
|
||
VStack(spacing: 12) { ProgressView("Downloading manual…"); Button("Cancel") { model.cancel() } }.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||
} else {
|
||
VStack(spacing: 12) {
|
||
Image(systemName: "book.closed").font(.largeTitle)
|
||
Text(model.error ?? "Choose a manual from the Software Library.").multilineTextAlignment(.center)
|
||
if model.asset != nil { Button("Try Again") { model.retry() } }
|
||
}.padding().frame(maxWidth: .infinity, maxHeight: .infinity)
|
||
}
|
||
Divider()
|
||
VStack(alignment: .leading, spacing: 4) {
|
||
if !model.searchMessage.isEmpty { Text(model.searchMessage).foregroundStyle(.secondary) }
|
||
HStack {
|
||
Text(model.asset?.credit ?? "Manual preserved by Color Computer Archive").foregroundStyle(.secondary)
|
||
Spacer()
|
||
if let asset = model.asset, asset.matchStatus != "personal" { Link(asset.sourceURL.host?.lowercased() == "colorcomputerarchive.com" ? "Archive source" : "Project source", destination: asset.sourceURL) }
|
||
else if model.asset?.matchStatus == "personal" { Text("Private — On This Mac").foregroundStyle(.secondary) }
|
||
}
|
||
}.font(.caption).padding(10)
|
||
}.frame(minWidth: 620, minHeight: 480)
|
||
.onReceive(NotificationCenter.default.publisher(for: .PDFViewPageChanged, object: model.pdfView)) { _ in
|
||
if let page = model.pdfView.currentPage, let document = model.document { model.page = document.index(for: page) + 1 }
|
||
model.saveReadingPosition(force: true)
|
||
}
|
||
.onDisappear { model.cancel() }
|
||
}
|
||
}
|
||
private struct ManualPDF: NSViewRepresentable {
|
||
let view: PDFView
|
||
func makeNSView(context: Context) -> PDFView {
|
||
view.displayMode = .singlePageContinuous; view.displaysPageBreaks = true; view.backgroundColor = .windowBackgroundColor
|
||
return view
|
||
}
|
||
func updateNSView(_ nsView: PDFView, context: Context) { }
|
||
}
|
||
private struct ManualPages: NSViewRepresentable {
|
||
let view: PDFView
|
||
func makeNSView(context: Context) -> PDFThumbnailView {
|
||
let thumbnails = PDFThumbnailView(); thumbnails.pdfView = view; thumbnails.thumbnailSize = NSSize(width: 85, height: 110)
|
||
return thumbnails
|
||
}
|
||
func updateNSView(_ nsView: PDFThumbnailView, context: Context) { nsView.pdfView = view }
|
||
}
|
||
|
||
private struct ManualText: NSViewRepresentable {
|
||
let view: NSTextView
|
||
func makeNSView(context: Context) -> NSScrollView {
|
||
let scroll = NSScrollView()
|
||
scroll.hasVerticalScroller = true; scroll.autohidesScrollers = true
|
||
view.isEditable = false; view.isSelectable = true; view.isRichText = false
|
||
view.font = .monospacedSystemFont(ofSize: 14, weight: .regular)
|
||
view.textColor = .textColor; view.backgroundColor = .textBackgroundColor
|
||
view.textContainerInset = NSSize(width: 18, height: 18)
|
||
view.isVerticallyResizable = true; view.isHorizontallyResizable = false
|
||
view.autoresizingMask = [.width]; view.textContainer?.widthTracksTextView = true
|
||
view.usesFindBar = true; view.isIncrementalSearchingEnabled = true
|
||
view.setAccessibilityLabel("Readme and instructions")
|
||
scroll.documentView = view
|
||
return scroll
|
||
}
|
||
func updateNSView(_ nsView: NSScrollView, context: Context) { }
|
||
}
|