// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import Combine import SwiftUI import WebKit struct ManualLibraryContent { let root: URL init(root: URL) { // WebKit checks its read grant against the exact path used by a citation. self.root = root.standardizedFileURL.resolvingSymlinksInPath() } static var bundled: Self? { Bundle.main.url(forResource: "ManualLibrary", withExtension: nil).map { Self(root: $0) } } var home: URL { root.appendingPathComponent("index.html") } func allowsExternalReference(_ url: URL) -> Bool { guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { return false } let existing = ["https://colorcomputerarchive.com/", "https://learn.chatgpt.com/docs/extend/mcp?surface=app", "https://learn.chatgpt.com/docs/extend/mcp?surface=cli", "https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz", "https://vccplus-git.brianholman.com/VCCPlusApps/CoCoCapitalQuiz/src/branch/main/CHATGPT_PROMPT.md", "https://www.fla-shop.com/svg/usa/", "https://creativecommons.org/licenses/by/4.0/"] if existing.contains(url.absoluteString) { return true } let provenance = root.appendingPathComponent("toolchain-reference/provenance.json") guard relativePath(for: provenance) != nil, let data = try? Data(contentsOf: provenance), let record = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let references = record["externalReferences"] as? [String] else { return false } return references.contains(url.absoluteString) } func relativePath(for url: URL) -> String? { guard url.isFileURL, url.host?.isEmpty != false else { return nil } let base = root.standardizedFileURL.resolvingSymlinksInPath().pathComponents let file = url.standardizedFileURL.resolvingSymlinksInPath() let parts = file.pathComponents guard parts.count > base.count, parts.starts(with: base), (try? file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { return nil } return parts.dropFirst(base.count).joined(separator: "/") } func basicTopicURL(for entry: BASICReferenceEntry) -> URL? { let page: String let anchor: String if entry.id.hasPrefix("ERROR.") { page = "errors.html" anchor = "err-" + entry.keyword.lowercased().replacingOccurrences(of: "/0", with: "div-zero") } else { page = "reference.html" anchor = "term-" + entry.id.lowercased() .replacingOccurrences(of: ".", with: "-") .replacingOccurrences(of: "$", with: "-string") .replacingOccurrences(of: "@", with: "-at") } let url = root.appendingPathComponent("programming-in-coco-basic").appendingPathComponent(page) var destination = URLComponents(url: url, resolvingAgainstBaseURL: false) destination?.fragment = anchor return destination?.url } // Only files in a book's designated practice areas offer a writable copy. func copyTitle(for relativePath: String) -> String? { let parts = relativePath.split(separator: "/") guard parts.count == 3 else { return nil } let url = root.appendingPathComponent(relativePath) guard self.relativePath(for: url) == relativePath else { return nil } if parts[0] == "toolchain-reference", parts[1] == "sources", ["markdown", "sgml"].contains(url.pathExtension.lowercased()) || url.lastPathComponent == "lwtools-manual.html.txt" { return "Save Original Manual Source" } if parts[0] == "toolchain-reference", parts[1] == "sources", ["cmoc-help.txt", "lwasm-help.txt", "lwlink-help.txt"].contains(url.lastPathComponent) { return "Save Command-Line Help" } switch (parts[1], url.pathExtension.lowercased()) { case ("media", "dsk"): return "Save Practice Disk" case ("media", "cas"): return "Save Practice Cassette" case ("examples", "asm"), ("examples", "a"): return "Save Assembly Example" case ("examples", "b09"): return "Save BASIC09 Example" case ("examples", "c"): return "Save C Example" case ("examples", "zip"): return "Save Example Project" case ("examples", "txt"): return "Save Example Text" default: return nil } } func exampleURL(for relativePath: String) -> URL? { let parts = relativePath.components(separatedBy: "/") guard parts.count == 3, parts[1] == "examples" else { return nil } let url = root.appendingPathComponent(relativePath) guard url.pathExtension.lowercased() == "bas", self.relativePath(for: url) == relativePath else { return nil } return url } } private final class ManualContinuityBridge: NSObject, WKScriptMessageHandler { weak var reader: ManualReader? func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard message.frameInfo.isMainFrame else { return } Task { @MainActor [weak self] in self?.reader?.receivedPosition(message.body) } } } @MainActor final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate { let webView: WKWebView let content: ManualLibraryContent? lazy var pageFind = ManualPageFind(webView: webView) private var searchNavigation: WKNavigation? let continuity: LibraryContinuityStore? private let scrollBridge = ManualContinuityBridge() private var restorePosition: LibraryReadingPosition? private var navigationRevision = 0 @Published private(set) var currentBookID: String? @Published private(set) var currentBookTitle = "" @Published private(set) var currentSectionTitle = "" @Published private(set) var currentPosition: LibraryReadingPosition? @Published private(set) var bookmarkMessage: String? @Published private var changedBookmarkIDs: Set = [] private var restoringBookmarkID: UUID? var openExample: ((String) -> Void)? @Published private(set) var canGoBack = false @Published private(set) var canGoForward = false @Published private(set) var error: String? init(content: ManualLibraryContent? = .bundled, continuity: LibraryContinuityStore? = nil) { self.content = content self.continuity = continuity ?? (content?.root == ManualLibraryContent.bundled?.root ? .shared : nil) let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() webView = WKWebView(frame: .zero, configuration: configuration) super.init() scrollBridge.reader = self webView.configuration.userContentController.add(scrollBridge, name: "libraryPosition") webView.configuration.userContentController.addUserScript(WKUserScript(source: Self.positionScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)) webView.navigationDelegate = self webView.allowsBackForwardNavigationGestures = true webView.publisher(for: \.canGoBack).receive(on: RunLoop.main).assign(to: &$canGoBack) webView.publisher(for: \.canGoForward).receive(on: RunLoop.main).assign(to: &$canGoForward) } func showHome() { loadPage(content?.home) } func resume() { guard webView.url == nil else { return } if let position = continuity?.reading(for: "manual-last"), let path = position.relativePath, let content, content.relativePath(for: content.root.appendingPathComponent(path)) != nil { loadPage(content.root.appendingPathComponent(path), restore: position) } else { showHome() } } var hasCurrentBookmark: Bool { guard let book = currentBookID, let position = currentPosition else { return false } return continuity?.bookmarks.contains { $0.bookID == book && $0.position.relativePath == position.relativePath && $0.position.anchor == position.anchor && (position.anchor != nil || Int($0.position.offset * 10_000) == Int(position.offset * 10_000)) } == true } func bookmarkCurrentLocation() { guard continuity != nil, !webView.isLoading, let url = webView.url else { return } let revision = navigationRevision // The periodic scroll checkpoint deliberately runs infrequently. A // deliberate bookmark must ask the loaded page for its location now. Task { [weak self] in guard let self else { return } do { let value = try await webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()") guard navigationRevision == revision, webView.url == url, !webView.isLoading, let object = value as? [String: Any], object["href"] as? String == url.absoluteString else { return } receivedPosition(object) guard let book = currentBookID, let position = currentPosition else { return } let existing = hasCurrentBookmark _ = continuity?.addBookmark(bookID: book, bookTitle: currentBookTitle, sectionTitle: currentSectionTitle, position: position) bookmarkMessage = existing ? "This location is already bookmarked." : "Bookmark saved." } catch { guard navigationRevision == revision, webView.url == url else { return } bookmarkMessage = "This location could not be bookmarked. Try again after the page finishes loading." } } } func openBookmark(_ bookmark: ManualBookmark, fromBookStart: Bool = false) { guard let content else { return } let home = bookmark.bookID.hasPrefix("toolchain-reference:") ? "toolchain-reference/index.html" : bookmark.bookID + "/template.html" let path = fromBookStart ? home : bookmark.position.relativePath ?? "" let url = content.root.appendingPathComponent(path) guard content.relativePath(for: url) != nil else { error = "This bookmark's page is no longer in the bundled book. The bookmark has been preserved." return } loadPage(url, restore: fromBookStart ? nil : bookmark.position) restoringBookmarkID = fromBookStart ? nil : bookmark.id } func bookmarkAvailable(_ bookmark: ManualBookmark) -> Bool { guard let content, let path = bookmark.position.relativePath else { return false } return bookmark.locationChanged != true && !changedBookmarkIDs.contains(bookmark.id) && content.relativePath(for: content.root.appendingPathComponent(path)) != nil } func checkpoint() { webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()", completionHandler: nil) continuity?.checkpoint() } fileprivate func receivedPosition(_ value: Any) { guard let object = value as? [String: Any], let href = object["href"] as? String, let url = URL(string: href), let path = content?.relativePath(for: url), path == webView.url.flatMap({ content?.relativePath(for: $0) }), url.pathExtension.lowercased() == "html" else { return } let parts = path.split(separator: "/") let bookID: String? = parts.count > 1 ? (parts[0] == "toolchain-reference" ? "toolchain-reference:" + String(parts[1]) : String(parts[0])) : nil let anchor = (object["anchor"] as? String).flatMap { $0.isEmpty ? nil : $0 } let position = LibraryReadingPosition(documentID: bookID ?? "manual-home", relativePath: path, anchor: anchor, offset: min(1, max(0, (object["offset"] as? Double) ?? 0)), readingOrder: object["order"] as? Int) currentBookID = bookID currentBookTitle = object["bookTitle"] as? String ?? "Manual Library" currentSectionTitle = object["sectionTitle"] as? String ?? currentBookTitle currentPosition = position continuity?.setReading(position, for: "manual-last") continuity?.setReading(position, for: "manual-page:" + path) if let bookID { continuity?.setReading(position, for: "manual-book:" + bookID) } } private static let positionScript = #""" (() => { let timer; const sections = () => Array.from(document.querySelectorAll('article section[id],article h2[id],article h3[id]')); window.vccLibraryCheckpoint = () => { const y = window.scrollY, candidates = sections(); let target = null; for (const item of candidates) { if (item.getBoundingClientRect().top + y <= y + 12) target = item; } const start = target ? target.getBoundingClientRect().top + y : 0; const index = candidates.indexOf(target); const next = target ? candidates[index + 1] : null; const end = next ? next.getBoundingClientRect().top + y : document.documentElement.scrollHeight; const title = target?.querySelector('h2,h3,h4')?.textContent || target?.textContent || document.querySelector('h1')?.textContent || document.title; const crumb = document.querySelector('.crumb a:nth-child(2)')?.textContent; const bookTitle = location.pathname.includes('/toolchain-reference/') ? (document.querySelector('h1')?.textContent || document.title) : (crumb || document.title); const chapters = Array.from(document.querySelectorAll('.toc ol > li > a')); const chapter = chapters.findIndex(link => new URL(link.href).pathname === location.pathname); const position = {href: location.href, anchor: target?.id || '', offset: Math.min(1, Math.max(0, (y-start)/Math.max(1,end-start))), bookTitle, sectionTitle:title.slice(0,1024),order:Math.max(0,chapter)*10000+Math.max(0,index)}; window.webkit.messageHandlers.libraryPosition.postMessage(position); return position; }; window.addEventListener('scroll', () => { if (!timer) timer=setTimeout(() => { timer=null; window.vccLibraryCheckpoint(); },1000); }, {passive:true}); window.addEventListener('pagehide', window.vccLibraryCheckpoint); })(); """# func showLibrarySearch() { pageFind.close() if let url = webView.url, content?.relativePath(for: url) == "index.html", !webView.isLoading { focusLibrarySearch() } else { searchNavigation = loadPage(content?.home) } } private func focusLibrarySearch() { webView.window?.makeFirstResponder(webView) webView.evaluateJavaScript(""" document.getElementById('search').scrollIntoView(); var input = document.getElementById('manual-query'); input.focus({preventScroll: true}); input.select(); """, in: nil, in: .defaultClient, completionHandler: nil) } func showBASICTopic(_ entry: BASICReferenceEntry) { loadPage(content?.basicTopicURL(for: entry)) } @discardableResult private func loadPage(_ url: URL?, restore: LibraryReadingPosition? = nil) -> WKNavigation? { guard let content, let url, content.relativePath(for: url) != nil else { error = "This page is missing from the bundled Manual Library." return nil } checkpoint() navigationRevision += 1 restorePosition = restore restoringBookmarkID = nil currentPosition = nil error = nil return webView.loadFileURL(url, allowingReadAccessTo: content.root) } func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = action.request.url, action.targetFrame?.isMainFrame != false else { decisionHandler(.cancel) return } if let path = content?.relativePath(for: url) { let fileExtension = url.pathExtension.lowercased() if let saveTitle = content?.copyTitle(for: path) { decisionHandler(.cancel) if action.navigationType == .linkActivated { let panel = NSSavePanel() panel.nameFieldStringValue = url.lastPathComponent panel.title = saveTitle panel.begin { [weak self] response in guard response == .OK, let destination = panel.url else { return } do { try Data(contentsOf: url).write(to: destination, options: .atomic) } catch { self?.error = "The practice file could not be saved. " + error.localizedDescription } } } return } if fileExtension == "bas" { decisionHandler(.cancel) if action.navigationType == .linkActivated, content?.exampleURL(for: path) != nil { openExample?(path) } return } if action.navigationType == .linkActivated { navigationRevision += 1 restorePosition = nil if url.fragment == nil || url.fragment?.isEmpty == true { if url.lastPathComponent == "template.html", let book = path.split(separator: "/").first, let saved = continuity?.reading(for: "manual-book:" + String(book)), let savedPath = saved.relativePath, savedPath != path, let content, content.relativePath(for: content.root.appendingPathComponent(savedPath)) != nil { decisionHandler(.cancel) loadPage(content.root.appendingPathComponent(savedPath), restore: saved) return } restorePosition = continuity?.reading(for: "manual-page:" + path) } } decisionHandler(.allow) return } decisionHandler(.cancel) if action.navigationType == .linkActivated { if content?.allowsExternalReference(url) == true { if !NSWorkspace.shared.open(url) { error = "The reference could not open in your browser." } } else { error = "This link does not lead to an available page in the bundled Manual Library." } } } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { pageFind.pageChanged() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { error = nil let saved = restorePosition let restoredBookmark = restoringBookmarkID restorePosition = nil restoringBookmarkID = nil let revision = navigationRevision if let saved, saved.relativePath == webView.url.flatMap({ content?.relativePath(for: $0) }) { let argument = ["anchor": saved.anchor ?? "", "offset": saved.offset, "href": webView.url?.absoluteString ?? ""] as [String: Any] if let data = try? JSONSerialization.data(withJSONObject: argument), let json = String(data: data, encoding: .utf8) { webView.evaluateJavaScript(""" (() => { const p = \(json); if (location.href !== p.href) return null; const target = p.anchor ? document.getElementById(p.anchor) : null; if (p.anchor && !target) return false; const y = target ? target.getBoundingClientRect().top + window.scrollY : 0; const candidates = Array.from(document.querySelectorAll('article section[id],article h2[id],article h3[id]')); const next = target ? candidates[candidates.indexOf(target)+1] : null; const end = next ? next.getBoundingClientRect().top + window.scrollY : document.documentElement.scrollHeight; window.scrollTo(0,y + Math.max(0,end-y)*p.offset); window.vccLibraryCheckpoint?.(); return true; })(); """) { [weak self] result, _ in guard let self, self.navigationRevision == revision else { return } if (result as? Bool) == false { if let restoredBookmark { self.changedBookmarkIDs.insert(restoredBookmark) self.continuity?.markBookmarkLocationChanged(restoredBookmark, changed: true) } self.error = "Location changed. This saved section is no longer available; the page and bookmark have been preserved." } else if let restoredBookmark { self.changedBookmarkIDs.remove(restoredBookmark) self.continuity?.markBookmarkLocationChanged(restoredBookmark, changed: false) } } } } else { webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()", completionHandler: nil) } if let searchNavigation, navigation === searchNavigation { self.searchNavigation = nil focusLibrarySearch() } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showLoadFailure(error) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { showLoadFailure(error) } private func showLoadFailure(_ failure: Error) { let reason = failure as NSError guard !(reason.domain == NSURLErrorDomain && reason.code == NSURLErrorCancelled) else { return } error = "The manual page could not open. " + failure.localizedDescription } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { error = "The manual reader stopped responding. Choose Library Home to reopen it." } } private struct ManualWebPage: NSViewRepresentable { let reader: ManualReader let openExample: (String) -> Void func makeNSView(context: Context) -> WKWebView { reader.webView } func updateNSView(_ webView: WKWebView, context: Context) { reader.openExample = openExample } } struct ManualLibraryView: View { @Environment(\.openWindow) private var openWindow @ObservedObject var reader: ManualReader @State private var showsBookmarks = false var body: some View { VStack(spacing: 0) { if let error = reader.error { Label(error, systemImage: "exclamationmark.triangle") .frame(maxWidth: .infinity, alignment: .leading).padding(10) Divider() } ManualPageFindBar(finder: reader.pageFind) ManualWebPage(reader: reader) { path in openWindow(id: "basic-example", value: "manual/" + path) } } .focusedSceneValue(\.manualPageFind, reader.pageFind) .toolbar { ToolbarItemGroup(placement: .primaryAction) { Button { let exists = reader.hasCurrentBookmark reader.bookmarkCurrentLocation() if exists { showsBookmarks = true } } label: { Image(systemName: reader.hasCurrentBookmark ? "bookmark.fill" : "bookmark") } .disabled(reader.currentBookID == nil || reader.currentPosition == nil || reader.continuity == nil) .help("Bookmark this location").accessibilityLabel("Bookmark this location") .accessibilityIdentifier("manual.bookmark-location") Button { showsBookmarks.toggle() } label: { Image(systemName: "list.bullet") } .help("Bookmarks").accessibilityLabel("Bookmarks") .accessibilityIdentifier("manual.bookmarks") .popover(isPresented: $showsBookmarks) { if let continuity = reader.continuity { ManualBookmarksPopover(reader: reader, continuity: continuity) { showsBookmarks = false } } else { Text("Bookmarks are unavailable in this reader.").padding() } } Button("Find on This Page", systemImage: "magnifyingglass") { reader.pageFind.show() } .help("Find on this page (⌘F)").accessibilityIdentifier("manual.find") Button { reader.showLibrarySearch() } label: { Label("Ask the Manuals", systemImage: "books.vertical").labelStyle(.titleAndIcon) } .help("Search all manuals by keyword") .accessibilityIdentifier("manual.ask") } ToolbarItemGroup(placement: .navigation) { Button("Back", systemImage: "chevron.backward") { reader.webView.goBack() } .help("Back").disabled(!reader.canGoBack) .accessibilityIdentifier("manual.back") Button("Forward", systemImage: "chevron.forward") { reader.webView.goForward() } .help("Forward").disabled(!reader.canGoForward) .accessibilityIdentifier("manual.forward") Button("Library Home", systemImage: "books.vertical") { reader.showHome() } .help("Library Home").accessibilityIdentifier("manual.home") } } .frame(minWidth: 420, minHeight: 340) .onAppear { if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.resume() } } .onDisappear { reader.checkpoint() } .onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in reader.checkpoint() } } } private struct ManualBookmarksPopover: View { @ObservedObject var reader: ManualReader @ObservedObject var continuity: LibraryContinuityStore let close: () -> Void @State private var filter = "all" @State private var renameID: UUID? @State private var renameText = "" private var entries: [ManualBookmark] { continuity.bookmarks.filter { filter != "book" || $0.bookID == reader.currentBookID } .sorted { if $0.bookID != $1.bookID { return order($0.bookID) < order($1.bookID) } if let first = $0.position.readingOrder, let second = $1.position.readingOrder, first != second { return first < second } let first = ($0.position.relativePath ?? "") + "#" + ($0.position.anchor ?? "") let second = ($1.position.relativePath ?? "") + "#" + ($1.position.anchor ?? "") return first.localizedStandardCompare(second) == .orderedAscending } } private func order(_ id: String) -> String { let books = ["meet-your-color-computer", "back-at-the-coco", "software-storage-and-peripherals", "users-handbook", "programming-in-coco-basic", "your-first-6809-programs", "assembly-language-programming", "programming-in-c", "inside-the-coco-3", "working-with-os9", "nitros9-on-vcc-plus", "vibe-coding-with-chatgpt"] if let index = books.firstIndex(of: id) { return String(format: "%02d", index) } return "99-" + id } var body: some View { VStack(alignment: .leading, spacing: 10) { Text("Bookmarks").font(.headline) Picker("Bookmark scope", selection: $filter) { Text("All Books").tag("all") Text("This Book").tag("book").disabled(reader.currentBookID == nil) }.pickerStyle(.segmented).accessibilityIdentifier("manual.bookmark-scope") if let error = continuity.saveError { Text(error).font(.caption).foregroundStyle(.red) } if entries.isEmpty { VStack(alignment: .leading, spacing: 8) { Label("No bookmarks", systemImage: "bookmark").font(.headline) Text("Use Bookmark This Location while reading a manual.") .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } .frame(maxWidth: .infinity, alignment: .leading) .padding(.top, 12) Spacer(minLength: 0) } else { List { ForEach(Array(Set(entries.map(\.bookID))).sorted(by: { order($0) < order($1) }), id: \.self) { book in Section(entries.first { $0.bookID == book }?.bookTitle ?? book) { ForEach(entries.filter { $0.bookID == book }) { item in HStack { Button { reader.openBookmark(item); close() } label: { VStack(alignment: .leading) { Text(item.displayName).lineLimit(2) Text(reader.bookmarkAvailable(item) ? item.sectionTitle : "Location changed — page unavailable") .font(.caption).foregroundStyle(.secondary).lineLimit(2) }.frame(maxWidth: .infinity, alignment: .leading) }.buttonStyle(.plain) .accessibilityIdentifier("manual.bookmark-open-" + item.id.uuidString) Menu { Button("Open") { reader.openBookmark(item); close() } Button("Open Book") { reader.openBookmark(item, fromBookStart: true); close() } Button("Rename…") { renameText = item.label ?? item.sectionTitle; renameID = item.id } Button("Remove Bookmark", role: .destructive) { continuity.removeBookmark(item.id) } } label: { Image(systemName: "ellipsis.circle") } .menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Bookmark actions for " + item.displayName) .accessibilityIdentifier("manual.bookmark-actions-" + item.id.uuidString) } } } } }.listStyle(.inset) } }.padding(12).frame(width: 400, height: 420, alignment: .topLeading) .onAppear { filter = continuity.browse(for: "manual-bookmark-ui")?.filters["scope"] ?? (reader.currentBookID == nil ? "all" : "book") if reader.currentBookID == nil { filter = "all" } } .onChange(of: filter) { _, value in var state = LibraryBrowseState(); state.filters["scope"] = value; continuity.setBrowse(state, for: "manual-bookmark-ui") } .onChange(of: reader.currentBookID) { _, value in if value == nil { filter = "all" } } .alert("Rename Bookmark", isPresented: Binding(get: { renameID != nil }, set: { if !$0 { renameID = nil } })) { TextField("Bookmark name", text: $renameText) Button("Cancel", role: .cancel) { renameID = nil } Button("Save") { if let renameID { continuity.renameBookmark(renameID, label: renameText) }; renameID = nil } } } }