295 lines
13 KiB
Swift
295 lines
13 KiB
Swift
// 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
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
|
|
let webView: WKWebView
|
|
let content: ManualLibraryContent?
|
|
lazy var pageFind = ManualPageFind(webView: webView)
|
|
private var searchNavigation: WKNavigation?
|
|
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) {
|
|
self.content = content
|
|
let configuration = WKWebViewConfiguration()
|
|
configuration.websiteDataStore = .nonPersistent()
|
|
webView = WKWebView(frame: .zero, configuration: configuration)
|
|
super.init()
|
|
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 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?) -> WKNavigation? {
|
|
guard let content, let url, content.relativePath(for: url) != nil else {
|
|
error = "This page is missing from the bundled Manual Library."
|
|
return 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
|
|
}
|
|
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
|
|
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
|
|
|
|
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("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.showHome() }
|
|
}
|
|
}
|
|
}
|