// 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 = SoftwareManualPDFView() private var task: Task? private var directory: URL? private var companion: (any CompanionLibraryAccess)? #if !VCC_COMPANION_CLIENT var continuity: LibraryContinuityStore? private var savedPosition: LibraryReadingPosition? #endif private var positionTracking: [NSObjectProtocol] = [] private var lastPositionSave = Date.distantPast @Published private(set) var readingReady = false func open(_ asset: SoftwareLibraryAsset, directory: URL, companion: (any CompanionLibraryAccess)? = nil) { let retained = self.asset?.id == asset.id && (document != nil || text != nil) if retained && (readingReady || pdfView.whenLaidOut != nil) { return } saveReadingPosition(force: true) stopPositionTracking() #if !VCC_COMPANION_CLIENT savedPosition = companion == nil ? continuity?.reading(for: "software-manual:" + asset.id) : nil #endif if retained { return } 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 } 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(_ number: Int? = nil) { guard let document else { return } page = min(max(number ?? 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." } } private func stopPositionTracking() { if readingReady { readingReady = false } pdfView.whenLaidOut = nil for token in positionTracking { NotificationCenter.default.removeObserver(token) } positionTracking = [] } func restoreReadingPosition() { guard !readingReady, let asset else { return } if let document { pdfView.whenLaidOut = { [weak self] in guard let self, self.document === document, self.pdfView.document === document else { return } self.pdfView.autoScales = true var number = 1 #if !VCC_COMPANION_CLIENT if let saved = self.savedPosition { number = min(max(1, saved.page), document.pageCount) if saved.autoScales == false, let zoom = saved.zoom { self.pdfView.autoScales = false self.pdfView.scaleFactor = min(10, max(0.1, zoom)) } } #endif self.pdfView.layoutDocumentView() self.goToPage(number) #if !VCC_COMPANION_CLIENT if let saved = self.savedPosition, let target = document.page(at: number - 1) { let bounds = target.bounds(for: self.pdfView.displayBox) let point = CGPoint(x: bounds.minX + bounds.width * saved.horizontalOffset, y: bounds.minY + bounds.height * saved.offset) self.pdfView.go(to: PDFDestination(page: target, at: point)) } #endif self.trackReadingPosition() } pdfView.needsLayout = true } else if text != nil { DispatchQueue.main.async { [weak self] in guard let self, self.asset?.id == asset.id, self.text != nil, let clip = self.textView.enclosingScrollView?.contentView else { return } #if !VCC_COMPANION_CLIENT if let saved = self.savedPosition { 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 self.trackReadingPosition() } } } private func trackReadingPosition() { guard !readingReady else { return } readingReady = true 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?.updateReadingPosition(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?.updateReadingPosition() } }) } } private func updateReadingPosition(force: Bool = false) { guard readingReady else { return } if let document, let current = pdfView.currentDestination?.page, current.document === document { let index = document.index(for: current) if (0..= 1 else { return } var position = LibraryReadingPosition(documentID: asset.id, page: page) if let document { guard let destination = pdfView.currentDestination, let current = destination.page, current.document === document else { return } let index = document.index(for: current) let bounds = current.bounds(for: pdfView.displayBox) let point = destination.point let scale = pdfView.scaleFactor guard bounds.minX.isFinite, bounds.minY.isFinite, bounds.width.isFinite, bounds.height.isFinite, bounds.width > 0, bounds.height > 0, point.x.isFinite, point.y.isFinite, scale.isFinite, scale > 0, (0..= 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) }.disabled(!model.readingReady).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).id(model.asset?.id).accessibilityIdentifier("manual-pdf").onAppear { model.restoreReadingPosition() } } } else if model.text != nil { ManualText(view: model.textView).id(model.asset?.id).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) .onDisappear { model.cancel() } } } // PDFKit chooses its fit scale from the attached view's viewport. Its document and // scale notifications before that layout do not represent a reading position. final class SoftwareManualPDFView: PDFView { var whenLaidOut: (() -> Void)? override func layout() { super.layout() guard whenLaidOut != nil, window != nil, !bounds.isEmpty else { return } DispatchQueue.main.async { [weak self] in guard let self, self.window != nil, !self.bounds.isEmpty else { return } let restore = self.whenLaidOut self.whenLaidOut = nil restore?() } } } 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) { } }