Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

@@ -0,0 +1,258 @@
// 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)?
func open(_ asset: SoftwareLibraryAsset, directory: URL, companion: (any CompanionLibraryAccess)? = nil) {
if self.asset?.id == asset.id && (document != nil || text != nil) { 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 {
local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset, directory: directory)
}
try Task.checkCancellation()
if local.pathExtension == "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() { task?.cancel(); loading = false }
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." }
}
}
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")
}
} else if model.text != nil {
ManualText(view: model.textView).accessibilityIdentifier("manual-text")
} 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 { Link(asset.matchStatus == "project-owned" ? "Project source" : "Archive source", destination: asset.sourceURL) }
}
}.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 }
}
.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) { }
}