Sync source edition with VCC Plus 3.7.0 build 63
This commit is contained in:
1 parent
c652a5276d
commit
b2ecec4d87
86 files changed
+10519
-472
No files matched your search
@@ -140,12 +140,14 @@ enum ArchiveInlineContent: Sendable {
|
||||
struct ArchiveInlinePreview: View {
|
||||
let content: ArchiveInlineContent
|
||||
let title: String
|
||||
var position: LibraryReadingPosition? = nil
|
||||
var onPositionChange: (Double, Double, Double?) -> Void = { _,_,_ in }
|
||||
|
||||
var body: some View {
|
||||
switch content {
|
||||
case .image(let image): ArchiveInlineImage(image: image, title: title)
|
||||
case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title)
|
||||
case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title)
|
||||
case .image(let image): ArchiveInlineImage(image: image, title: title, position: position, onPositionChange: onPositionChange)
|
||||
case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title, position: position, onPositionChange: onPositionChange)
|
||||
case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title, position: position, onPositionChange: onPositionChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,8 +155,14 @@ struct ArchiveInlinePreview: View {
|
||||
private struct ArchiveInlineImage: View {
|
||||
let image: CGImage
|
||||
let title: String
|
||||
@State private var zoom = 0
|
||||
let position: LibraryReadingPosition?
|
||||
let onPositionChange: (Double, Double, Double?) -> Void
|
||||
@State private var zoom: Int
|
||||
|
||||
init(image: CGImage, title: String, position: LibraryReadingPosition?, onPositionChange: @escaping (Double, Double, Double?) -> Void) {
|
||||
self.image = image; self.title = title; self.position = position; self.onPositionChange = onPositionChange
|
||||
_zoom = State(initialValue: min(5,max(0,Int(log2(position?.zoom ?? 1)))))
|
||||
}
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
@@ -166,18 +174,77 @@ private struct ArchiveInlineImage: View {
|
||||
Spacer()
|
||||
}.padding(6)
|
||||
Divider()
|
||||
GeometryReader { geometry in
|
||||
let width = CGFloat(image.width), height = CGFloat(image.height)
|
||||
let fit = min(1, min(geometry.size.width / width, geometry.size.height / height))
|
||||
let scale = fit * pow(2.0, CGFloat(zoom))
|
||||
ScrollView([.horizontal, .vertical]) {
|
||||
Image(image, scale: 1, label: Text(title))
|
||||
.resizable()
|
||||
.frame(width: width * scale, height: height * scale)
|
||||
.accessibilityIdentifier("archive-inline-image")
|
||||
.frame(minWidth: geometry.size.width, minHeight: geometry.size.height)
|
||||
}
|
||||
ArchiveImageSurface(image: image, title: title, zoom: zoom, initialPosition: position, onPositionChange: onPositionChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ArchiveImageSurface: NSViewRepresentable {
|
||||
let image: CGImage
|
||||
let title: String
|
||||
let zoom: Int
|
||||
let initialPosition: LibraryReadingPosition?
|
||||
let onPositionChange: (Double, Double, Double?) -> Void
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSScrollView()
|
||||
scroll.hasHorizontalScroller = true; scroll.hasVerticalScroller = true
|
||||
let imageView = NSImageView()
|
||||
imageView.image = NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height))
|
||||
imageView.imageScaling = .scaleAxesIndependently
|
||||
imageView.setAccessibilityLabel(title)
|
||||
imageView.setAccessibilityIdentifier("archive-inline-image")
|
||||
let container = NSView()
|
||||
container.addSubview(imageView)
|
||||
scroll.documentView = container
|
||||
context.coordinator.imageView = imageView
|
||||
context.coordinator.scroll = scroll
|
||||
scroll.contentView.postsBoundsChangedNotifications = true
|
||||
context.coordinator.observer = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scroll.contentView, queue: .main) { [weak coordinator = context.coordinator] _ in coordinator?.changed() }
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
let coordinator = context.coordinator
|
||||
coordinator.onPositionChange = onPositionChange; coordinator.imageSize = NSSize(width: image.width, height: image.height)
|
||||
coordinator.initialPosition = initialPosition; coordinator.zoom = zoom
|
||||
DispatchQueue.main.async { [weak coordinator] in coordinator?.layout() }
|
||||
}
|
||||
final class Coordinator {
|
||||
weak var scroll: NSScrollView?
|
||||
weak var imageView: NSImageView?
|
||||
var observer: NSObjectProtocol?
|
||||
var imageSize = NSSize.zero
|
||||
var initialPosition: LibraryReadingPosition?
|
||||
var zoom = 0
|
||||
var restored = false
|
||||
var layingOut = false
|
||||
var viewport = NSSize.zero
|
||||
var onPositionChange: (Double,Double,Double?) -> Void = { _,_,_ in }
|
||||
deinit { if let observer { NotificationCenter.default.removeObserver(observer) } }
|
||||
func layout() {
|
||||
guard let scroll, let image = scroll.documentView, imageSize.width > 0,
|
||||
scroll.contentSize.width > 0, scroll.contentSize.height > 0 else { return }
|
||||
layingOut = true
|
||||
viewport = scroll.contentSize
|
||||
let fit = min(1,min(scroll.contentSize.width/imageSize.width,scroll.contentSize.height/imageSize.height))
|
||||
let picture = NSSize(width:imageSize.width*fit*pow(2,Double(zoom)),height:imageSize.height*fit*pow(2,Double(zoom)))
|
||||
let size = NSSize(width:max(scroll.contentSize.width,picture.width),height:max(scroll.contentSize.height,picture.height))
|
||||
image.setFrameSize(size)
|
||||
imageView?.frame = NSRect(x:(size.width-picture.width)/2,y:(size.height-picture.height)/2,width:picture.width,height:picture.height)
|
||||
if !restored {
|
||||
restored = true
|
||||
let target = NSPoint(x:(initialPosition?.horizontalOffset ?? 0)*max(0,size.width-scroll.contentSize.width),y:(initialPosition?.offset ?? 0)*max(0,size.height-scroll.contentSize.height))
|
||||
scroll.contentView.scroll(to: target); scroll.reflectScrolledClipView(scroll.contentView)
|
||||
}
|
||||
layingOut = false
|
||||
changed()
|
||||
}
|
||||
func changed() {
|
||||
guard !layingOut, let scroll, let image = scroll.documentView else { return }
|
||||
if viewport != scroll.contentSize { layout(); return }
|
||||
let x = scroll.contentView.bounds.minX/max(1,image.bounds.width-scroll.contentSize.width)
|
||||
let y = scroll.contentView.bounds.minY/max(1,image.bounds.height-scroll.contentSize.height)
|
||||
onPositionChange(min(1,max(0,y)),min(1,max(0,x)),pow(2,Double(zoom)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -186,9 +253,15 @@ private struct ArchiveInlineText: NSViewRepresentable {
|
||||
let text: String
|
||||
let worksheet: Bool
|
||||
let title: String
|
||||
let position: LibraryReadingPosition?
|
||||
let onPositionChange: (Double, Double, Double?) -> Void
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSTextView.scrollableTextView()
|
||||
scroll.contentView.postsBoundsChangedNotifications = true
|
||||
context.coordinator.scroll = scroll
|
||||
context.coordinator.observer = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scroll.contentView, queue: .main) { [weak coordinator = context.coordinator] _ in coordinator?.changed() }
|
||||
guard let view = scroll.documentView as? NSTextView else { return scroll }
|
||||
view.isEditable = false
|
||||
view.isSelectable = true
|
||||
@@ -205,6 +278,7 @@ private struct ArchiveInlineText: NSViewRepresentable {
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let view = scroll.documentView as? NSTextView else { return }
|
||||
context.coordinator.onPositionChange = onPositionChange
|
||||
view.setAccessibilityLabel(title)
|
||||
guard view.string != text else { return }
|
||||
view.string = text
|
||||
@@ -234,7 +308,24 @@ private struct ArchiveInlineText: NSViewRepresentable {
|
||||
view.textStorage?.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: (text as NSString).length))
|
||||
}
|
||||
view.setSelectedRange(NSRange(location: 0, length: 0))
|
||||
scroll.contentView.scroll(to: .zero)
|
||||
scroll.reflectScrolledClipView(scroll.contentView)
|
||||
let initial = position
|
||||
DispatchQueue.main.async { [weak scroll] in
|
||||
guard let scroll, let view = scroll.documentView as? NSTextView else { return }
|
||||
view.layoutManager?.ensureLayout(for: view.textContainer!)
|
||||
let point = NSPoint(x:(initial?.horizontalOffset ?? 0)*max(0,view.bounds.width-scroll.contentSize.width),y:(initial?.offset ?? 0)*max(0,view.bounds.height-scroll.contentSize.height))
|
||||
scroll.contentView.scroll(to: point); scroll.reflectScrolledClipView(scroll.contentView)
|
||||
}
|
||||
}
|
||||
final class Coordinator {
|
||||
weak var scroll: NSScrollView?
|
||||
var observer: NSObjectProtocol?
|
||||
var onPositionChange: (Double,Double,Double?) -> Void = { _,_,_ in }
|
||||
deinit { if let observer { NotificationCenter.default.removeObserver(observer) } }
|
||||
func changed() {
|
||||
guard let scroll, let view = scroll.documentView else { return }
|
||||
let y = scroll.contentView.bounds.minY/max(1,view.bounds.height-scroll.contentSize.height)
|
||||
let x = scroll.contentView.bounds.minX/max(1,view.bounds.width-scroll.contentSize.width)
|
||||
onPositionChange(min(1,max(0,y)),min(1,max(0,x)),nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,25 @@ actor ArchiveLibraryCatalog {
|
||||
return try rows.map(document)
|
||||
}
|
||||
|
||||
func document(id: String) throws -> ArchiveDocument? {
|
||||
guard Self.isSHA(id) else { return nil }
|
||||
return try database().rows("SELECT * FROM document WHERE sha256=? LIMIT 1", [id]).first.map(document)
|
||||
}
|
||||
|
||||
/// Locate the exact title in the same deterministic order used by Browse.
|
||||
/// Deep links must not depend on the title happening to be in its first batch.
|
||||
func browseOffset(documentID: String, collection: String?, batchSize: Int) throws -> Int? {
|
||||
guard (1...50).contains(batchSize), let target = try document(id: documentID) else { return nil }
|
||||
let filter = try scope(collection)
|
||||
let rows = try database().rows("""
|
||||
SELECT count(*) AS amount FROM document d WHERE 1=1 \(filter.sql)
|
||||
AND (d.title COLLATE NOCASE < ? COLLATE NOCASE OR
|
||||
(d.title COLLATE NOCASE = ? COLLATE NOCASE AND d.sha256 < ?))
|
||||
""", filter.values + [target.title, target.title, target.id])
|
||||
guard let amount = rows.first?["amount"].flatMap(Int.init), amount <= 250_000 else { return nil }
|
||||
return (amount / batchSize) * batchSize
|
||||
}
|
||||
|
||||
private static let compounds = ["module directory", "width 80", "width 40", "disk basic", "extended basic"]
|
||||
|
||||
private func match(_ query: String) throws -> String {
|
||||
|
||||
@@ -313,6 +313,7 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
@Published private(set) var progress: ArchiveReadProgress?
|
||||
@Published private(set) var error: String?
|
||||
@Published private(set) var page = 1
|
||||
@Published private(set) var inlineNavigationRevision = 0
|
||||
@Published var find = "" { didSet { if find != oldValue { resetFind() } } }
|
||||
@Published private(set) var findMessage: String?
|
||||
@Published private(set) var isFinding = false
|
||||
@@ -323,12 +324,17 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
private var localURL: URL?
|
||||
private var lastMatch: (page: Int, range: NSRange)?
|
||||
private var pendingPage = 1
|
||||
private var resumePending = false
|
||||
private var lastCheckpoint = Date.distantPast
|
||||
private var tracking: [NSObjectProtocol] = []
|
||||
private let continuity: LibraryContinuityStore?
|
||||
let remembersPage: Bool
|
||||
private let cache: ArchiveAssetCache
|
||||
private let catalog: ArchiveLibraryCatalog
|
||||
|
||||
init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared) {
|
||||
init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared, continuity: LibraryContinuityStore? = nil) {
|
||||
self.remembersPage = remembersPage
|
||||
self.continuity = remembersPage ? (continuity ?? .shared) : nil
|
||||
self.cache = cache
|
||||
self.catalog = catalog
|
||||
view.displayMode = .singlePageContinuous
|
||||
@@ -336,7 +342,9 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
view.displaysPageBreaks = true
|
||||
view.setAccessibilityLabel("Archive PDF")
|
||||
}
|
||||
deinit { for token in tracking { NotificationCenter.default.removeObserver(token) } }
|
||||
func stop() {
|
||||
rememberPage(force: true)
|
||||
requestID = UUID(); request?.cancel(); request = nil; progress = nil
|
||||
resetFind()
|
||||
}
|
||||
@@ -350,12 +358,55 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
cancelled = true
|
||||
}
|
||||
func retry(_ record: ArchiveDocument) {
|
||||
open(record, page: pendingPage)
|
||||
open(record, page: pendingPage, resumePosition: resumePending)
|
||||
}
|
||||
private func rememberPage() {
|
||||
if remembersPage, let referenceID { UserDefaults.standard.set(page, forKey: "archive-library.page." + referenceID) }
|
||||
private func rememberPage(force: Bool = false) {
|
||||
guard let continuity, let referenceID, document != nil || preview != nil,
|
||||
force || Date().timeIntervalSince(lastCheckpoint) >= 1 else { return }
|
||||
lastCheckpoint = Date()
|
||||
var position = continuity.reading(for: "archive:" + referenceID) ?? LibraryReadingPosition(documentID: referenceID)
|
||||
position.page = page
|
||||
if let document, let destination = view.currentDestination, let destinationPage = destination.page {
|
||||
let bounds = destinationPage.bounds(for: view.displayBox)
|
||||
let index = document.index(for: destinationPage)
|
||||
if index >= 0, index < document.pageCount { position.page = index + 1 }
|
||||
if bounds.height > 0 { position.offset = min(1,max(0,(destination.point.y-bounds.minY)/bounds.height)) }
|
||||
if bounds.width > 0 { position.horizontalOffset = min(1,max(0,(destination.point.x-bounds.minX)/bounds.width)) }
|
||||
position.zoom = view.scaleFactor; position.autoScales = view.autoScales
|
||||
}
|
||||
continuity.setReading(position, for: "archive:" + referenceID)
|
||||
}
|
||||
static func savedPage(for id: String) -> Int {
|
||||
LibraryContinuityStore.shared.reading(for: "archive:" + id)?.page ?? max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1)
|
||||
}
|
||||
func savedPage(for id: String) -> Int {
|
||||
continuity?.reading(for: "archive:" + id)?.page ?? max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1)
|
||||
}
|
||||
var inlinePosition: LibraryReadingPosition? {
|
||||
guard let referenceID, let value = continuity?.reading(for: "archive:" + referenceID), value.page == page else { return nil }
|
||||
return value
|
||||
}
|
||||
func updateInlinePosition(offset: Double, horizontal: Double = 0, zoom: Double? = nil) {
|
||||
guard let continuity, let referenceID else { return }
|
||||
var position = LibraryReadingPosition(documentID: referenceID, page: page, offset: min(1,max(0,offset)), horizontalOffset: min(1,max(0,horizontal)), zoom: zoom)
|
||||
position.autoScales = nil
|
||||
continuity.setReading(position, for: "archive:" + referenceID)
|
||||
}
|
||||
private func trackPDFPosition() {
|
||||
for token in tracking { NotificationCenter.default.removeObserver(token) }
|
||||
tracking = []
|
||||
for name in [Notification.Name.PDFViewPageChanged, .PDFViewScaleChanged] {
|
||||
tracking.append(NotificationCenter.default.addObserver(forName: name, object: view, queue: .main) { [weak self] _ in
|
||||
Task { @MainActor [weak self] in self?.updatePage() }
|
||||
})
|
||||
}
|
||||
if let clip = view.documentView?.enclosingScrollView?.contentView {
|
||||
clip.postsBoundsChangedNotifications = true
|
||||
tracking.append(NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: clip, queue: .main) { [weak self] _ in
|
||||
Task { @MainActor [weak self] in self?.rememberPage() }
|
||||
})
|
||||
}
|
||||
}
|
||||
static func savedPage(for id: String) -> Int { max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) }
|
||||
func updatePage() {
|
||||
guard let document, let current = view.currentPage, current.document === document else { return }
|
||||
let index = document.index(for: current)
|
||||
@@ -367,18 +418,32 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
guard let document, number > 0, number <= document.pageCount, let target = document.page(at: number - 1) else { return }
|
||||
view.go(to: target); updatePage()
|
||||
}
|
||||
func open(_ record: ArchiveDocument, page number: Int) {
|
||||
func open(_ record: ArchiveDocument, page requestedNumber: Int, resumePosition: Bool = false) {
|
||||
let number = resumePosition ? min(max(requestedNumber,1),record.pageCount ?? max(requestedNumber,1)) : requestedNumber
|
||||
if referenceID == record.id {
|
||||
if document != nil { go(to: number); return }
|
||||
if preview != nil && page == number { return }
|
||||
if document != nil {
|
||||
if !resumePosition || page != number { go(to: number) }
|
||||
return
|
||||
}
|
||||
if preview != nil && page == number {
|
||||
if !resumePosition {
|
||||
continuity?.setReading(LibraryReadingPosition(documentID: record.id, page: number), for: "archive:" + record.id)
|
||||
// A deliberate same-section citation starts at that section,
|
||||
// rather than keeping an already visible image/text viewport.
|
||||
inlineNavigationRevision += 1
|
||||
}
|
||||
return
|
||||
}
|
||||
if progress != nil && (record.format == "pdf" || number == pendingPage) {
|
||||
pendingPage = number
|
||||
resumePending = resumePosition
|
||||
return
|
||||
}
|
||||
}
|
||||
reset()
|
||||
referenceID = record.id
|
||||
pendingPage = number
|
||||
pendingPage = number; resumePending = resumePosition
|
||||
let saved = resumePosition ? continuity?.reading(for: "archive:" + record.id) : nil
|
||||
let identity = requestID
|
||||
progress = .checking
|
||||
request = Task {
|
||||
@@ -396,13 +461,22 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
if record.format == "pdf" {
|
||||
let parsed = await Task.detached(priority: .userInitiated) { PDFDocument(url: url) }.value
|
||||
try Task.checkCancellation()
|
||||
let target = pendingPage
|
||||
guard let parsed, !parsed.isLocked, target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page }
|
||||
guard let parsed, !parsed.isLocked, parsed.pageCount > 0 else { throw ArchiveReaderError.page }
|
||||
let target = resumePending ? min(max(pendingPage,1),parsed.pageCount) : pendingPage
|
||||
guard target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page }
|
||||
localURL = url; document = parsed; view.document = parsed; view.autoScales = true; go(to: target)
|
||||
if resumePending, let saved, saved.page == target, let page = parsed.page(at: target-1) {
|
||||
if saved.autoScales == false, let zoom = saved.zoom { view.autoScales = false; view.scaleFactor = CGFloat(zoom) }
|
||||
let bounds = page.bounds(for: view.displayBox)
|
||||
view.go(to: PDFDestination(page: page, at: NSPoint(x: bounds.minX + saved.horizontalOffset*bounds.width, y: bounds.minY + saved.offset*bounds.height)))
|
||||
}
|
||||
trackPDFPosition(); rememberPage(force: true)
|
||||
} else {
|
||||
let content = try await ArchivePreviewDecoder.shared.read(url, format: record.format, number: number)
|
||||
try Task.checkCancellation()
|
||||
page = number; preview = content; rememberPage()
|
||||
page = number; preview = content
|
||||
if !resumePending { continuity?.setReading(LibraryReadingPosition(documentID: record.id, page: number), for: "archive:" + record.id) }
|
||||
rememberPage(force: true)
|
||||
}
|
||||
default:
|
||||
guard let section = try await catalog.readerSection(documentID: record.id, number: number) else {
|
||||
@@ -411,7 +485,8 @@ final class ArchiveReaderModel: ObservableObject {
|
||||
try Task.checkCancellation()
|
||||
page = section.number; sectionLabel = section.label
|
||||
preview = record.format == "office-xls" ? .worksheet(section.text) : .text(section.text)
|
||||
rememberPage()
|
||||
if !resumePending { continuity?.setReading(LibraryReadingPosition(documentID: record.id, page: page), for: "archive:" + record.id) }
|
||||
rememberPage(force: true)
|
||||
}
|
||||
progress = nil
|
||||
} catch {
|
||||
@@ -469,6 +544,7 @@ struct ArchiveReaderPane: View {
|
||||
@ObservedObject var reader: ArchiveReaderModel
|
||||
let requestedPage: Int
|
||||
let catalog: ArchiveLibraryCatalog
|
||||
var resumesPosition = false
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var examples: [ArchiveExample] = []
|
||||
@State private var exampleError: String?
|
||||
@@ -551,8 +627,13 @@ struct ArchiveReaderPane: View {
|
||||
Spacer(minLength: 0)
|
||||
}.padding(8)
|
||||
}
|
||||
ArchiveInlinePreview(content: preview, title: record.title)
|
||||
.id(record.id + "/" + String(reader.page))
|
||||
let revision = reader.inlineNavigationRevision
|
||||
ArchiveInlinePreview(content: preview, title: record.title, position: reader.inlinePosition,
|
||||
onPositionChange: { y,x,zoom in
|
||||
guard reader.inlineNavigationRevision == revision else { return }
|
||||
reader.updateInlinePosition(offset: y, horizontal: x, zoom: zoom)
|
||||
})
|
||||
.id(record.id + "/" + String(reader.page) + "/" + String(revision))
|
||||
} else {
|
||||
VStack(spacing: 12) {
|
||||
if isCurrent, let progress = reader.progress {
|
||||
@@ -586,7 +667,7 @@ struct ArchiveReaderPane: View {
|
||||
.onChange(of: reader.page, initial: true) { _, value in pageField = String(value) }
|
||||
.task(id: hit?.id ?? record.id) {
|
||||
guard !Task.isCancelled else { return }
|
||||
reader.open(record, page: requestedPage)
|
||||
reader.open(record, page: requestedPage, resumePosition: resumesPosition)
|
||||
}
|
||||
.task(id: exampleKey) {
|
||||
examples = []; loadedExampleKey = nil; exampleError = nil; copies = nil
|
||||
|
||||
@@ -38,11 +38,26 @@ final class ArchiveLibraryQuery: ObservableObject {
|
||||
init(_ text: String = "") { self.text = text }
|
||||
}
|
||||
|
||||
private struct ArchiveVisibleRows: PreferenceKey {
|
||||
static let defaultValue: [String: CGFloat] = [:]
|
||||
static func reduce(value: inout [String: CGFloat], nextValue: () -> [String: CGFloat]) { value.merge(nextValue(), uniquingKeysWith: { _, last in last }) }
|
||||
}
|
||||
|
||||
struct ArchiveLibraryView: View {
|
||||
@AppStorage("archive-library.collection") private var collection = ""
|
||||
@AppStorage("archive-library.browse-selection") private var browseID: String?
|
||||
@AppStorage("archive-library.browse-offset") private var browseOffset = 0
|
||||
@AppStorage("archive-library.scope") private var localScope = false
|
||||
@State private var collection = ""
|
||||
@State private var browseID: String?
|
||||
@State private var browseOffset = 0
|
||||
@State private var localScope = false
|
||||
@ObservedObject private var navigation = ArchiveLibraryNavigation.shared
|
||||
private let continuity: LibraryContinuityStore
|
||||
@State private var browseTopID: String?
|
||||
@State private var searchTopID: String?
|
||||
@State private var restoreBrowseTop: String?
|
||||
@State private var restoreSearchTop: String?
|
||||
@State private var restoringSearchSelection = false
|
||||
@State private var navigationDocument: ArchiveDocument?
|
||||
@State private var navigationPage: Int?
|
||||
@State private var navigationError: String?
|
||||
@State private var collections: [ArchiveCollection] = []
|
||||
@State private var documents: [ArchiveDocument] = []
|
||||
@State private var hits: [ArchiveHit] = []
|
||||
@@ -66,20 +81,49 @@ struct ArchiveLibraryView: View {
|
||||
private let batch = 35
|
||||
private let catalog: ArchiveLibraryCatalog
|
||||
|
||||
init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil) {
|
||||
self.catalog = catalog
|
||||
_browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog))
|
||||
_archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery())
|
||||
_searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: false, catalog: catalog))
|
||||
init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil,
|
||||
continuity suppliedContinuity: LibraryContinuityStore? = nil) {
|
||||
let continuity = suppliedContinuity ?? .shared
|
||||
self.catalog = catalog; self.continuity = continuity
|
||||
let saved = continuity.browse(for: "archive-main")
|
||||
let defaults = UserDefaults.standard
|
||||
_collection = State(initialValue: saved?.scope ?? defaults.string(forKey: "archive-library.collection") ?? "")
|
||||
_browseID = State(initialValue: saved?.filters["browseID"] ?? defaults.string(forKey: "archive-library.browse-selection"))
|
||||
_browseOffset = State(initialValue: saved?.pageOffset ?? max(0, defaults.integer(forKey: "archive-library.browse-offset")))
|
||||
_localScope = State(initialValue: saved?.filters["localScope"].map { $0 == "true" } ?? defaults.bool(forKey: "archive-library.scope"))
|
||||
_searchID = State(initialValue: saved?.filters["searchID"])
|
||||
_searchOffset = State(initialValue: Int(saved?.filters["searchOffset"] ?? "0") ?? 0)
|
||||
_searchFolder = State(initialValue: saved?.filters["searchFolder"])
|
||||
_searchBrowseCollection = State(initialValue: saved?.filters["searchBrowseCollection"])
|
||||
_browseTopID = State(initialValue: saved?.filters["browseTop"])
|
||||
_searchTopID = State(initialValue: saved?.filters["searchTop"])
|
||||
_restoreBrowseTop = State(initialValue: saved?.filters["browseTop"])
|
||||
_restoreSearchTop = State(initialValue: saved?.filters["searchTop"])
|
||||
_restoringSearchSelection = State(initialValue: saved?.filters["searchID"] != nil)
|
||||
_browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog, continuity: continuity))
|
||||
_archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery(saved?.query ?? ""))
|
||||
_searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: true, catalog: catalog, continuity: continuity))
|
||||
}
|
||||
|
||||
private var query: String { archiveQuery.text }
|
||||
private var searching: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||||
private var browseDocument: ArchiveDocument? { documents.first { $0.id == browseID } }
|
||||
private var browseDocument: ArchiveDocument? { navigationDocument.flatMap { $0.id == browseID ? $0 : nil } ?? documents.first { $0.id == browseID } }
|
||||
private var hit: ArchiveHit? { hits.first { $0.id == searchID } }
|
||||
private var selected: ArchiveDocument? { searching ? hit?.document : browseDocument }
|
||||
private var reader: ArchiveReaderModel { searching ? searchReader : browseReader }
|
||||
private var requestedPage: Int { searching ? (hit?.locationNumber ?? 1) : browseID.map(ArchiveReaderModel.savedPage) ?? 1 }
|
||||
private var requestedPage: Int {
|
||||
if searching { return restoringSearchSelection ? hit.map { searchReader.savedPage(for: $0.document.id) } ?? 1 : hit?.locationNumber ?? 1 }
|
||||
return navigationPage ?? browseID.map { browseReader.savedPage(for: $0) } ?? 1
|
||||
}
|
||||
private var browseState: LibraryBrowseState {
|
||||
var state = LibraryBrowseState()
|
||||
state.scope = collection; state.query = query; state.selectedID = searching ? searchID : browseID; state.pageOffset = browseOffset
|
||||
state.filters = ["localScope": String(localScope), "searchOffset": String(searchOffset)]
|
||||
for (key,value) in [("browseID",browseID),("searchID",searchID),("searchFolder",searchFolder),("searchBrowseCollection",searchBrowseCollection),("browseTop",browseTopID),("searchTop",searchTopID)] {
|
||||
if let value { state.filters[key] = value }
|
||||
}
|
||||
return state
|
||||
}
|
||||
private var sidebarPath: String { searching ? (searchFolder ?? collection) : collection }
|
||||
private var scopePath: String? {
|
||||
if searching, let searchFolder, !searchFolder.isEmpty { return searchFolder }
|
||||
@@ -106,29 +150,51 @@ struct ArchiveLibraryView: View {
|
||||
}
|
||||
.frame(minWidth: 430, minHeight: 320)
|
||||
.task(id: retry) {
|
||||
do { let paths = try await catalog.collections(); try Task.checkCancellation(); collections = ArchiveCollection.tree(paths) }
|
||||
do {
|
||||
let paths = try await catalog.collections(); try Task.checkCancellation()
|
||||
collections = ArchiveCollection.tree(paths)
|
||||
let valid = Set(paths.flatMap { path -> [String] in
|
||||
let parts = path.split(separator: "/")
|
||||
guard !parts.isEmpty else { return [] }
|
||||
return (1...parts.count).map { parts.prefix($0).joined(separator: "/") }
|
||||
})
|
||||
if !collection.isEmpty, !valid.contains(collection) {
|
||||
collection = ""; browseID = nil; browseOffset = 0
|
||||
}
|
||||
}
|
||||
catch { if !Task.isCancelled { browseError = error.localizedDescription } }
|
||||
}
|
||||
.task(id: ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)) { await loadBrowse() }
|
||||
.task(id: key) { await loadSearch(key) }
|
||||
.task(id: navigation.request?.id) { if let request = navigation.request { await openRequested(request) } }
|
||||
.onChange(of: browseState) { _, value in continuity.setBrowse(value, for: "archive-main") }
|
||||
.onChange(of: query) { old, new in
|
||||
navigationError = nil
|
||||
if old.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !new.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
searchBrowseCollection = browseDocument?.collection
|
||||
if browseReader.progress != nil { browseReader.stop() }
|
||||
}
|
||||
restoringSearchSelection = false; restoreSearchTop = nil
|
||||
searchID = nil; searchOffset = 0; compactReader = false; searchReader.reset()
|
||||
if !searching { searchBrowseCollection = nil; searchFolder = nil }
|
||||
}
|
||||
.onChange(of: localScope) { _, _ in searchOffset = 0; searchID = nil; compactReader = false; searchReader.reset() }
|
||||
.onChange(of: browseID) { _, id in
|
||||
navigationError = nil
|
||||
if id != navigationDocument?.id { navigationDocument = nil; navigationPage = nil }
|
||||
if id == nil { browseReader.reset() }
|
||||
else if !searching { compactReader = true }
|
||||
}
|
||||
.onChange(of: searchID) { _, id in
|
||||
navigationError = nil
|
||||
// Initial restoration sets State before observation starts. A later
|
||||
// selection change (including keyboard arrows) is an explicit hit.
|
||||
if id != nil { restoringSearchSelection = false }
|
||||
if id == nil { searchReader.reset() }
|
||||
else if searching { compactReader = true }
|
||||
}
|
||||
.onDisappear { browseReader.stop(); searchReader.stop() }
|
||||
.onDisappear { continuity.setBrowse(browseState, for: "archive-main"); continuity.checkpoint(); browseReader.stop(); searchReader.stop() }
|
||||
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in continuity.setBrowse(browseState, for: "archive-main"); continuity.checkpoint() }
|
||||
}
|
||||
|
||||
private func header(narrow: Bool, sidebar side: Bool) -> some View {
|
||||
@@ -176,7 +242,7 @@ struct ArchiveLibraryView: View {
|
||||
}
|
||||
|
||||
private func chooseCollection(_ path: String) {
|
||||
showCollections = false
|
||||
showCollections = false; navigationError = nil; navigationDocument = nil; navigationPage = nil; restoreBrowseTop = nil; restoreSearchTop = nil
|
||||
if searching {
|
||||
if path != sidebarPath { searchID = nil; searchReader.reset() }
|
||||
searchFolder = path; searchOffset = 0; localScope = !path.isEmpty; compactReader = false
|
||||
@@ -215,17 +281,25 @@ struct ArchiveLibraryView: View {
|
||||
}
|
||||
|
||||
private var browseList: some View {
|
||||
ScrollViewReader { proxy in
|
||||
List(selection: $browseID) {
|
||||
ForEach(documents) { doc in
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(doc.title).lineLimit(2)
|
||||
Text(doc.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
}.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id)
|
||||
}.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id).id(doc.id)
|
||||
.background(GeometryReader { value in Color.clear.preference(key: ArchiveVisibleRows.self, value: [doc.id: value.frame(in: .named("archive-browse")).minY]) })
|
||||
.simultaneousGesture(TapGesture().onEnded { browseID = doc.id; compactReader = true })
|
||||
}
|
||||
}.accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list")
|
||||
}.coordinateSpace(name: "archive-browse")
|
||||
.onPreferenceChange(ArchiveVisibleRows.self) { rows in if !searching { browseTopID = topRow(rows) } }
|
||||
.onChange(of: documents.map(\.id)) { _, ids in
|
||||
if let target = restoreBrowseTop, ids.contains(target) { proxy.scrollTo(target, anchor: .top); restoreBrowseTop = nil }
|
||||
}
|
||||
.accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list")
|
||||
.onKeyPress(.return, action: readSelectedWithKeyboard)
|
||||
.overlay { if documents.isEmpty, !browseBusy { ContentUnavailableView("No documents in this collection", systemImage: "books.vertical") } }
|
||||
}
|
||||
}
|
||||
|
||||
private var groups: [ArchiveResultGroup] {
|
||||
@@ -237,27 +311,64 @@ struct ArchiveLibraryView: View {
|
||||
return ordered
|
||||
}
|
||||
private var resultsList: some View {
|
||||
ScrollViewReader { proxy in
|
||||
List(selection: $searchID) {
|
||||
ForEach(groups) { group in
|
||||
Section {
|
||||
ForEach(group.hits) { result in
|
||||
HStack { Text(result.locator); if result.ocr { Text("OCR").font(.caption).foregroundStyle(.secondary) } }
|
||||
.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id)
|
||||
.simultaneousGesture(TapGesture().onEnded { searchID = result.id; compactReader = true })
|
||||
.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id).id(result.id)
|
||||
.background(GeometryReader { value in Color.clear.preference(key: ArchiveVisibleRows.self, value: [result.id: value.frame(in: .named("archive-search")).minY]) })
|
||||
.simultaneousGesture(TapGesture().onEnded { restoringSearchSelection = false; restoreSearchTop = nil; searchID = result.id; compactReader = true })
|
||||
}
|
||||
} header: { Text(group.document.title).lineLimit(3).textCase(nil) }
|
||||
}
|
||||
}.accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list")
|
||||
}.coordinateSpace(name: "archive-search")
|
||||
.onPreferenceChange(ArchiveVisibleRows.self) { rows in if searching { searchTopID = topRow(rows) } }
|
||||
.onChange(of: hits.map(\.id)) { _, ids in
|
||||
if let target = restoreSearchTop, ids.contains(target) { proxy.scrollTo(target, anchor: .top); restoreSearchTop = nil }
|
||||
}
|
||||
.accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list")
|
||||
.onKeyPress(.return, action: readSelectedWithKeyboard)
|
||||
.overlay { if hits.isEmpty, !searchBusy { ContentUnavailableView("No matching pages", systemImage: "magnifyingglass") } }
|
||||
}
|
||||
}
|
||||
private func topRow(_ positions: [String: CGFloat]) -> String? {
|
||||
positions.filter { $0.value <= 0 }.max(by: { $0.value < $1.value })?.key ?? positions.min(by: { $0.value < $1.value })?.key
|
||||
}
|
||||
|
||||
@ViewBuilder private var detail: some View {
|
||||
if let selected {
|
||||
ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog)
|
||||
if let navigationError {
|
||||
ContentUnavailableView("Reference unavailable", systemImage: "book.closed", description: Text(navigationError))
|
||||
} else if let selected {
|
||||
ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog, resumesPosition: searching ? restoringSearchSelection : navigationPage == nil)
|
||||
} else { ContentUnavailableView("Choose a document", systemImage: "book.pages", description: Text("Browse a collection or search the Archive.")) }
|
||||
}
|
||||
private func openRequested(_ request: ArchiveLibraryOpenRequest) async {
|
||||
do {
|
||||
guard let record = try await catalog.document(id: request.documentID),
|
||||
request.expectedSHA256 == nil || request.expectedSHA256 == record.id,
|
||||
request.location.map({ $0 > 0 && $0 <= (record.pageCount ?? 1_000_000) }) != false else {
|
||||
throw ArchiveLibraryError.input("This reference no longer matches the installed Archive index. The software selection has not changed.")
|
||||
}
|
||||
guard let offset = try await catalog.browseOffset(documentID: record.id, collection: record.collection, batchSize: batch) else {
|
||||
throw ArchiveLibraryError.input("The reference could not be located in the installed Archive collection.")
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
guard navigation.request?.id == request.id else { return }
|
||||
navigationError = nil; archiveQuery.text = ""; collection = record.collection; browseOffset = offset
|
||||
navigationDocument = record; navigationPage = request.location; browseID = record.id
|
||||
restoreBrowseTop = record.id; compactReader = true
|
||||
browseReader.open(record, page: request.location ?? browseReader.savedPage(for: record.id), resumePosition: request.location == nil)
|
||||
navigation.consumed(request.id)
|
||||
} catch {
|
||||
guard !Task.isCancelled, navigation.request?.id == request.id else { return }
|
||||
navigationError = error.localizedDescription; compactReader = true; navigation.consumed(request.id)
|
||||
}
|
||||
}
|
||||
private func moveBatch(_ direction: Int) {
|
||||
navigationError = nil; navigationDocument = nil; navigationPage = nil; restoringSearchSelection = false
|
||||
restoreBrowseTop = nil; restoreSearchTop = nil
|
||||
if searching { searchOffset = max(0, searchOffset + direction * batch); searchID = nil }
|
||||
else { browseOffset = max(0, browseOffset + direction * batch); browseID = nil }
|
||||
}
|
||||
@@ -274,6 +385,7 @@ struct ArchiveLibraryView: View {
|
||||
let rows = try await catalog.browse(collection: collection.isEmpty ? nil : collection, limit: batch + 1, offset: browseOffset)
|
||||
try Task.checkCancellation()
|
||||
guard request == ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry) else { return }
|
||||
if rows.isEmpty, browseOffset > 0 { browseOffset = 0; browseID = nil; browseBusy = false; return }
|
||||
documents = Array(rows.prefix(batch)); browseMore = rows.count > batch
|
||||
if !documents.contains(where: { $0.id == browseID }) { browseID = nil }
|
||||
browseBusy = false
|
||||
|
||||
@@ -5,6 +5,14 @@ import Foundation
|
||||
/// declaration to one retained build; object relocation replay and live physical
|
||||
/// RAM comparisons provide the independent byte checks before debugging.
|
||||
struct CMOCBankedDebugLayout: Sendable {
|
||||
struct OverlayIdentity: Codable, Equatable, Hashable, Sendable {
|
||||
let group: String
|
||||
let owner: String
|
||||
}
|
||||
struct OverlayGroup: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let owners: [String]
|
||||
}
|
||||
struct File: Decodable, Sendable { let path: String; let sha256: String }
|
||||
struct Page: Decodable, Equatable, Sendable { let logicalPage: Int; let physicalPage: Int }
|
||||
struct CodeGuard: Equatable, Sendable { let address: UInt16; let bytes: [UInt8] }
|
||||
@@ -33,6 +41,7 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
let bytes: [UInt8]
|
||||
let pages: [Page]
|
||||
let codeGuards: [CodeGuard]
|
||||
var overlay: OverlayIdentity? = nil
|
||||
func physicalAddress(_ logical: Int) -> UInt32? {
|
||||
guard (0..<65536).contains(logical),
|
||||
let page = pages.first(where: { $0.logicalPage == logical / 8192 }) else { return nil }
|
||||
@@ -44,6 +53,7 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
}
|
||||
private struct ModuleRecord: Decodable {
|
||||
let id: String; let sections: [String]; let codeSections: [String]; let image: Image?; let pages: [Page]
|
||||
let overlay: OverlayIdentity?
|
||||
}
|
||||
private struct Manifest: Decodable {
|
||||
let version: Int; let entryPoint: Int
|
||||
@@ -51,6 +61,7 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
let sources: [String: String]; let artifacts: [String: String]
|
||||
let modules: [ModuleRecord]
|
||||
let framebuffers: [Framebuffer]?
|
||||
let overlayGroups: [OverlayGroup]?
|
||||
}
|
||||
let entryPoint: UInt16
|
||||
let binarySHA256: String
|
||||
@@ -59,15 +70,21 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
let artifactHashes: [String: String]
|
||||
let modules: [Module]
|
||||
var framebuffers: [Framebuffer] = []
|
||||
var overlayGroups: [OverlayGroup] = []
|
||||
func module(forSection name: String) -> Module? { modules.first { $0.sections.contains(name) } }
|
||||
func module(id: String) -> Module? { modules.first { $0.id == id } }
|
||||
func permitsPhysicalOverlap(between first: String, and second: String) -> Bool {
|
||||
guard first != second, let a = module(id: first)?.overlay, let b = module(id: second)?.overlay else { return false }
|
||||
return a.group == b.group && a.owner != b.owner
|
||||
}
|
||||
|
||||
static func parse(data: Data, directory: URL, sources: [String: Data], binary: Data,
|
||||
binaryPath: String, diskPath: String? = nil, allowedOutputs: [String]) throws -> Self {
|
||||
func fail(_ text: String) -> CMOCSourceMap.Failure { .invalid("banked manifest: " + text) }
|
||||
guard data.count <= 1024 * 1024 else { throw fail("manifest exceeds 1 MB.") }
|
||||
// Bound recursive decoding before handing untrusted JSON to Decodable.
|
||||
var pending: [(Any, Int)] = [(try JSONSerialization.jsonObject(with: data), 0)], nodes = 0
|
||||
let raw = try JSONSerialization.jsonObject(with: data)
|
||||
var pending: [(Any, Int)] = [(raw, 0)], nodes = 0
|
||||
while let (value, depth) = pending.popLast() {
|
||||
nodes += 1
|
||||
guard depth <= 16, nodes <= 30000 else { throw fail("manifest nesting or record limit exceeded.") }
|
||||
@@ -75,9 +92,31 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
if let values = value as? [Any] { pending += values.map { ($0, depth + 1) } }
|
||||
}
|
||||
let manifest = try JSONDecoder().decode(Manifest.self, from: data)
|
||||
guard manifest.version == 1, (0..<65536).contains(manifest.entryPoint),
|
||||
guard [1, 2].contains(manifest.version), (0..<65536).contains(manifest.entryPoint),
|
||||
!manifest.modules.isEmpty, manifest.modules.count <= 256,
|
||||
manifest.artifacts.count <= 8192, sources.count <= 4096 else { throw fail("unsupported version or record count.") }
|
||||
let groups = manifest.overlayGroups ?? []
|
||||
if manifest.version == 1 {
|
||||
let object = raw as? [String: Any]
|
||||
let records = object?["modules"] as? [[String: Any]] ?? []
|
||||
guard object?["overlayGroups"] == nil, records.allSatisfy({ $0["overlay"] == nil }) else {
|
||||
throw fail("overlay declarations require manifest version 2.")
|
||||
}
|
||||
} else if manifest.overlayGroups == nil {
|
||||
throw fail("version 2 requires an explicit overlayGroups array.")
|
||||
}
|
||||
guard groups.count <= 64, groups.reduce(0, { $0 + $1.owners.count }) <= 256 else {
|
||||
throw fail("overlay group or owner count exceeds limits.")
|
||||
}
|
||||
func validIdentity(_ value: String) -> Bool { !value.isEmpty && value.utf8.count <= 128 && !value.contains("\0") }
|
||||
var declaredOwners: [String: Set<String>] = [:]
|
||||
for group in groups {
|
||||
guard validIdentity(group.id), declaredOwners[group.id] == nil, group.owners.count >= 2,
|
||||
group.owners.allSatisfy(validIdentity), Set(group.owners).count == group.owners.count else {
|
||||
throw fail("overlay groups require unique bounded identities and at least two distinct owners.")
|
||||
}
|
||||
declaredOwners[group.id] = Set(group.owners)
|
||||
}
|
||||
func path(_ value: String) throws {
|
||||
guard !value.isEmpty, value.utf8.count <= 4096, !value.hasPrefix("/"), !value.contains("\\"),
|
||||
!value.contains("\0"), !value.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }),
|
||||
@@ -96,14 +135,23 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
guard CMOCSourceMap.sha256(data) == digest else { throw fail("conflicting artifact hashes.") }; return data
|
||||
}
|
||||
let url = root.appendingPathComponent(name)
|
||||
guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact paths must not traverse symbolic links.") }
|
||||
guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact \(name) must not traverse symbolic links.") }
|
||||
let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 8 * 1024 * 1024 else { throw fail("artifact is not a bounded regular file.") }
|
||||
guard info.isRegularFile == true, info.isSymbolicLink != true, let size = info.fileSize else {
|
||||
throw fail("artifact \(name) is not a regular file with a known size.")
|
||||
}
|
||||
let limit = CMOCSourceMap.evidenceByteLimit(for: name)
|
||||
guard size <= limit else { throw fail("artifact \(name) is \(size) bytes; its verification limit is \(limit) bytes.") }
|
||||
guard size <= CMOCSourceMap.maximumVerificationBytes - total else {
|
||||
throw fail("artifact \(name) would bring retained evidence to \(total + size) bytes; the aggregate limit is \(CMOCSourceMap.maximumVerificationBytes) bytes.")
|
||||
}
|
||||
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
||||
let value = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data()
|
||||
let value = try handle.read(upToCount: limit + 1) ?? Data()
|
||||
guard value.count == size, value.count <= limit else {
|
||||
throw fail("artifact \(name) changed size while reading (observed \(value.count) bytes; expected \(size), limit \(limit)).")
|
||||
}
|
||||
guard CMOCSourceMap.sha256(value) == digest else { throw fail("artifact \(name) SHA-256 differs from the retained build manifest.") }
|
||||
total += value.count
|
||||
guard value.count <= 8 * 1024 * 1024, total <= 128 * 1024 * 1024,
|
||||
CMOCSourceMap.sha256(value) == digest else { throw fail("artifact changed or exceeds verification limits.") }
|
||||
loaded[name] = value; return value
|
||||
}
|
||||
guard manifest.sources == sources.mapValues(CMOCSourceMap.sha256) else { throw fail("source snapshot differs from the manifest.") }
|
||||
@@ -130,13 +178,27 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
}
|
||||
for (name, digest) in manifest.artifacts { _ = try read(name, digest: digest) }
|
||||
var modules: [Module] = [], ids = Set<String>(), sections = Set<String>()
|
||||
var physical: [UInt32: String] = [:]
|
||||
var physical: [UInt32: Set<String>] = [:]
|
||||
var overlayByModule: [String: OverlayIdentity] = [:]
|
||||
func mayShare(_ address: UInt32, module: String, overlay: OverlayIdentity?) -> Bool {
|
||||
(physical[address] ?? []).allSatisfy { previous in
|
||||
if previous == module { return true }
|
||||
guard let overlay, let other = overlayByModule[previous] else { return false }
|
||||
return overlay.group == other.group && overlay.owner != other.owner
|
||||
}
|
||||
}
|
||||
for record in manifest.modules {
|
||||
guard !record.id.isEmpty, record.id.count <= 128, ids.insert(record.id).inserted,
|
||||
!record.sections.isEmpty, record.sections.count <= 256,
|
||||
Set(record.codeSections).count == record.codeSections.count,
|
||||
Set(record.codeSections).isSubset(of: Set(record.sections)),
|
||||
!record.pages.isEmpty, record.pages.count <= 8 else { throw fail("invalid or repeated module identity.") }
|
||||
if let overlay = record.overlay {
|
||||
guard declaredOwners[overlay.group]?.contains(overlay.owner) == true else {
|
||||
throw fail("module \(record.id) names an undeclared overlay group or owner.")
|
||||
}
|
||||
overlayByModule[record.id] = overlay
|
||||
}
|
||||
for section in record.sections {
|
||||
guard !section.isEmpty, section.count <= 256, !section.contains(where: \.isWhitespace), sections.insert(section).inserted else { throw fail("section has ambiguous module ownership.") }
|
||||
}
|
||||
@@ -181,14 +243,14 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
}
|
||||
let module = Module(id: record.id, sections: record.sections, codeSections: record.codeSections,
|
||||
logicalAddress: logicalAddress, bytes: moduleBytes, pages: record.pages,
|
||||
codeGuards: guards.sorted { $0.address < $1.address })
|
||||
codeGuards: guards.sorted { $0.address < $1.address }, overlay: record.overlay)
|
||||
var imagePhysical = Set<UInt32>()
|
||||
for logical in module.logicalAddress..<(module.logicalAddress + moduleBytes.count) {
|
||||
guard let address = module.physicalAddress(logical), imagePhysical.insert(address).inserted,
|
||||
physical[address] == nil || physical[address] == module.id else {
|
||||
mayShare(address, module: module.id, overlay: module.overlay) else {
|
||||
throw fail("module images overlap physical RAM or lack a page identity.")
|
||||
}
|
||||
physical[address] = module.id
|
||||
physical[address, default: []].insert(module.id)
|
||||
}
|
||||
// BSS has no image bytes, but its storage must still have one
|
||||
// physical owner. Initialized non-code data follows the same rule.
|
||||
@@ -198,15 +260,23 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
for placement in matching where placement.length > 0 {
|
||||
for logical in placement.address..<(placement.address + placement.length) {
|
||||
guard let address = module.physicalAddress(logical),
|
||||
physical[address] == nil || physical[address] == module.id else {
|
||||
mayShare(address, module: module.id, overlay: module.overlay) else {
|
||||
throw fail("module storage overlaps another module's physical RAM or lacks a page identity.")
|
||||
}
|
||||
physical[address] = module.id
|
||||
physical[address, default: []].insert(module.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
modules.append(module)
|
||||
}
|
||||
for group in groups {
|
||||
for owner in group.owners {
|
||||
let members = modules.filter { $0.overlay == OverlayIdentity(group: group.id, owner: owner) }
|
||||
guard !members.isEmpty, members.contains(where: { !$0.codeGuards.isEmpty }) else {
|
||||
throw fail("overlay owner \(group.id)/\(owner) needs at least one code-bearing module.")
|
||||
}
|
||||
}
|
||||
}
|
||||
// A compressed transport can enter through its loader, outside every
|
||||
// eventual source module. Bind this entry to the delivered DECB trailer.
|
||||
guard try CMOCSourceMap.decbEntryPoint(binary) == UInt16(manifest.entryPoint) else { throw fail("entry point differs from the delivered executable.") }
|
||||
@@ -235,6 +305,6 @@ struct CMOCBankedDebugLayout: Sendable {
|
||||
}
|
||||
return Self(entryPoint: UInt16(manifest.entryPoint), binarySHA256: manifest.binary.sha256,
|
||||
linkMap: linkMap, sourceHashes: manifest.sources, artifactHashes: manifest.artifacts,
|
||||
modules: modules, framebuffers: buffers)
|
||||
modules: modules, framebuffers: buffers, overlayGroups: groups)
|
||||
}
|
||||
}
|
||||
@@ -1510,6 +1510,7 @@ final class CMOCDevelopmentModel: ObservableObject {
|
||||
pausedDebugSnapshot = snapshot; pausedInputEpoch = epoch
|
||||
let sameStop = previousEpoch == epoch && previousSnapshot?.machine.programCounter == address &&
|
||||
previousSnapshot?.machine.debuggerMappingFingerprint == snapshot.machine.debuggerMappingFingerprint &&
|
||||
previousSnapshot?.machine.debuggerResidencyFingerprint == snapshot.machine.debuggerResidencyFingerprint &&
|
||||
previousSnapshot?.registers["U"] == snapshot.registers["U"] &&
|
||||
previousSnapshot?.registers["S"] == snapshot.registers["S"] &&
|
||||
previousSnapshot?.logicalMemory == snapshot.logicalMemory &&
|
||||
|
||||
@@ -20,6 +20,10 @@ struct CMOCSourceMap: Sendable {
|
||||
return (items, values.count, items.count != values.count)
|
||||
}
|
||||
|
||||
struct EvidenceAddress: Hashable {
|
||||
let module: String?
|
||||
let physical: UInt32
|
||||
}
|
||||
struct Instruction: Equatable, Sendable {
|
||||
let sourceLine: Int // one-based C source line
|
||||
let address: UInt16
|
||||
@@ -52,6 +56,19 @@ struct CMOCSourceMap: Sendable {
|
||||
Self.sha256(source) == provenance.sourceSHA256 && Self.sha256(binary) == provenance.binarySHA256
|
||||
}
|
||||
static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
|
||||
// Generated assembly may contain full compiler type records and data tables;
|
||||
// it has a larger byte budget than object/listing/map/executable evidence.
|
||||
// Banked verification retains one aggregate cap across unique files.
|
||||
static let maximumVerificationBytes = 128 * 1024 * 1024
|
||||
static func evidenceByteLimit(for path: String) -> Int {
|
||||
(path as NSString).pathExtension.lowercased() == "s" ? 32 * 1024 * 1024 : 8 * 1024 * 1024
|
||||
}
|
||||
static func validateEvidenceSize(_ count: Int, path: String) throws {
|
||||
let limit = evidenceByteLimit(for: path)
|
||||
guard count <= limit else {
|
||||
throw Failure.invalid("artifact \(path) is \(count) bytes; its verification limit is \(limit) bytes.")
|
||||
}
|
||||
}
|
||||
static func decbEntryPoint(_ data: Data) throws -> UInt16 { try BinaryImage(data).entry }
|
||||
|
||||
/// The caller must build all artifacts together from an immutable source
|
||||
@@ -61,8 +78,9 @@ struct CMOCSourceMap: Sendable {
|
||||
sourceAliases: [String] = [], objectAliases: [String] = [],
|
||||
strictIdentities: Bool = false, allowEmpty: Bool = false,
|
||||
bankedLayout: CMOCBankedDebugLayout? = nil) throws -> Self {
|
||||
for data in [source, listing, object, linkMap, binary] {
|
||||
guard data.count <= 8 * 1024 * 1024 else { throw Failure.invalid("an artifact exceeds 8 MB.") }
|
||||
for (name, data) in [(sourceName, source), (String(objectName.dropLast(2)) + ".lst", listing),
|
||||
(objectName, object), ("linker map", linkMap), ("executable", binary)] {
|
||||
try validateEvidenceSize(data.count, path: name)
|
||||
}
|
||||
guard let sourceText = String(data: source, encoding: .utf8), !sourceText.contains("\0"),
|
||||
!sourceName.isEmpty, !objectName.isEmpty else { throw Failure.invalid("invalid source identity or encoding.") }
|
||||
@@ -75,7 +93,7 @@ struct CMOCSourceMap: Sendable {
|
||||
let linePattern = try NSRegularExpression(pattern: #"^\* Line (.+):([0-9]+)(?::.*)?$"#)
|
||||
let functionPattern = try NSRegularExpression(pattern: #"^\* FUNCTION .+: defined at (.+):([0-9]+)$"#)
|
||||
var sectionName: String?, sourceLine: Int?, instructions: [Instruction] = []
|
||||
var seenAddresses = Set<UInt32>()
|
||||
var seenAddresses = Set<EvidenceAddress>()
|
||||
for text in listingLines {
|
||||
let octets = Array(text.utf8)
|
||||
guard octets.count >= 22, octets[21] == 32 else { continue }
|
||||
@@ -121,7 +139,8 @@ struct CMOCSourceMap: Sendable {
|
||||
}
|
||||
let address = UInt16(section.base + offset)
|
||||
let identity = bankedLayout?.module(forSection: sectionName)?.physicalAddress(Int(address)) ?? UInt32(address)
|
||||
guard seenAddresses.insert(identity).inserted else { throw Failure.invalid("duplicate instruction addresses in the listing.") }
|
||||
let qualified = EvidenceAddress(module: bankedLayout?.module(forSection: sectionName)?.id, physical: identity)
|
||||
guard seenAddresses.insert(qualified).inserted else { throw Failure.invalid("duplicate instruction addresses in the listing module.") }
|
||||
instructions.append(Instruction(sourceLine: sourceLine, address: address,
|
||||
bytes: Array(final[offset..<(offset + originalBytes.count)]), assembly: trimmed,
|
||||
moduleID: bankedLayout?.module(forSection: sectionName)?.id,
|
||||
@@ -715,7 +734,7 @@ struct CMOCProjectSourceMap: Sendable {
|
||||
throw CMOCSourceMap.Failure.invalid("source identities must be canonical project-relative paths.")
|
||||
}
|
||||
}
|
||||
var instructions: [Instruction] = [], addresses = Set<UInt32>(), occupied = Set<UInt32>()
|
||||
var instructions: [Instruction] = [], addresses = Set<CMOCSourceMap.EvidenceAddress>(), occupied = Set<CMOCSourceMap.EvidenceAddress>()
|
||||
var entry: UInt16?, objectHashes: [String: String] = [:], listingHashes: [String: String] = [:]
|
||||
var executableSymbols: [ExecutableSymbol] = [], flatCodeGuards: [CodeGuard] = []
|
||||
let marker = try NSRegularExpression(pattern: #"\* (?:Line (.+):([0-9]+)(?::.*)?|FUNCTION .+: defined at (.+):([0-9]+))$"#)
|
||||
@@ -763,13 +782,15 @@ struct CMOCProjectSourceMap: Sendable {
|
||||
if let entry, entry != map.entryPoint { throw CMOCSourceMap.Failure.invalid("inconsistent entry points.") }
|
||||
entry = map.entryPoint
|
||||
for item in map.instructions {
|
||||
guard addresses.insert(item.physicalAddress ?? UInt32(item.address)).inserted else {
|
||||
let startIdentity = CMOCSourceMap.EvidenceAddress(module: item.moduleID, physical: item.physicalAddress ?? UInt32(item.address))
|
||||
guard addresses.insert(startIdentity).inserted else {
|
||||
throw CMOCSourceMap.Failure.invalid("two source locations claim the same instruction address.")
|
||||
}
|
||||
for index in item.bytes.indices {
|
||||
let address = Int(item.address) + index
|
||||
let identity = item.moduleID.flatMap { bankedLayout?.module(id: $0)?.physicalAddress(address) } ?? UInt32(address)
|
||||
guard address < 65536, occupied.insert(identity).inserted else {
|
||||
let qualified = CMOCSourceMap.EvidenceAddress(module: item.moduleID, physical: identity)
|
||||
guard address < 65536, occupied.insert(qualified).inserted else {
|
||||
throw CMOCSourceMap.Failure.invalid("overlapping source instruction ranges.")
|
||||
}
|
||||
}
|
||||
@@ -824,7 +845,7 @@ extension CMOCProjectSourceMap {
|
||||
func projected(physicalPages: [Int: Int]) -> Self {
|
||||
guard let bankedLayout else { return self }
|
||||
let active = Set(bankedLayout.modules.filter { module in
|
||||
module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage }
|
||||
module.overlay == nil && module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage }
|
||||
}.map(\.id))
|
||||
return projected(activeModuleIDs: active)
|
||||
}
|
||||
@@ -835,13 +856,30 @@ extension CMOCProjectSourceMap {
|
||||
func projected(physicalPages: [Int: Int], memory: Data, available: Data) -> Self {
|
||||
guard let bankedLayout else { return self }
|
||||
guard memory.count == 65536, available.count == 65536 else { return projected(activeModuleIDs: []) }
|
||||
func mapped(_ module: CMOCBankedDebugLayout.Module) -> Bool {
|
||||
module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage }
|
||||
}
|
||||
func codeMatches(_ module: CMOCBankedDebugLayout.Module) -> Bool {
|
||||
mapped(module) && module.codeGuards.allSatisfy { guardRange in
|
||||
let start = Int(guardRange.address), end = start + guardRange.bytes.count
|
||||
return end <= memory.count && available[start..<end].allSatisfy { $0 != 0 } &&
|
||||
Array(memory[start..<end]) == guardRange.bytes
|
||||
}
|
||||
}
|
||||
var selectedOwners = Set<CMOCBankedDebugLayout.OverlayIdentity>()
|
||||
for group in bankedLayout.overlayGroups {
|
||||
let matches = group.owners.filter { owner in
|
||||
let identity = CMOCBankedDebugLayout.OverlayIdentity(group: group.id, owner: owner)
|
||||
let code = bankedLayout.modules.filter { $0.overlay == identity && !$0.codeGuards.isEmpty }
|
||||
return !code.isEmpty && code.allSatisfy(codeMatches)
|
||||
}
|
||||
if matches.count == 1 {
|
||||
selectedOwners.insert(.init(group: group.id, owner: matches[0]))
|
||||
}
|
||||
}
|
||||
let active = Set(bankedLayout.modules.filter { module in
|
||||
module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } &&
|
||||
module.codeGuards.allSatisfy { guardRange in
|
||||
let start = Int(guardRange.address), end = start + guardRange.bytes.count
|
||||
return end <= memory.count && available[start..<end].allSatisfy { $0 != 0 } &&
|
||||
Array(memory[start..<end]) == guardRange.bytes
|
||||
}
|
||||
if let overlay = module.overlay { return selectedOwners.contains(overlay) && mapped(module) }
|
||||
return codeMatches(module)
|
||||
}.map(\.id))
|
||||
return projected(activeModuleIDs: active)
|
||||
}
|
||||
@@ -958,6 +996,7 @@ struct CMOCPublicDebugEvidence {
|
||||
var fields: [String: Any] = ["status": metadata == nil ? "source_only" : "verified",
|
||||
"source_map": "verified", "variables": metadata == nil ? "unavailable" : "verified",
|
||||
"banked": map.bankedLayout != nil, "binary_sha256": map.binarySHA256,
|
||||
"supported_manifest_versions": [1, 2], "module_catalog_scope": "verified_static_declarations_not_residency",
|
||||
"entry_point": Int(map.entryPoint), "link_map_sha256": map.linkMapSHA256,
|
||||
"c_frame_locals": "unavailable", "c_frame_locals_reason": "Owned entry/instruction stops do not establish a C frame; optimized-out or unknown layouts are not guessed.",
|
||||
"owned_stop_evidence": map.bankedLayout != nil ? "declared_banked_modules" : map.flatCodeGuards.isEmpty ? "unavailable" : "verified_flat_code"]
|
||||
@@ -994,8 +1033,11 @@ struct CMOCPublicDebugEvidence {
|
||||
catalog("globals", globalDeclarations(metadata: metadata, sharedPaths: sharedPaths))
|
||||
catalog("modules", map.bankedLayout?.modules.map(\.id) ?? [])
|
||||
catalog("module_details", map.bankedLayout?.modules.map { module in
|
||||
["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] }] as [String: Any]
|
||||
var row: [String: Any] = ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] }]
|
||||
if let overlay = module.overlay { row["overlay"] = ["group": overlay.group, "owner": overlay.owner] }
|
||||
return row
|
||||
} ?? [])
|
||||
catalog("overlay_groups", map.bankedLayout?.overlayGroups.map { ["id": $0.id, "owners": $0.owners] as [String: Any] } ?? [])
|
||||
catalog("framebuffers", map.bankedLayout?.framebuffers.map(\.workerFields) ?? [])
|
||||
fields["function_metadata_count"] = functions.count
|
||||
return fields
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
import Darwin
|
||||
import Combine
|
||||
|
||||
enum CoCoCaptureFiles {
|
||||
static func folder(_ folder: URL) throws {
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
guard FileManager.default.isWritableFile(atPath: folder.path) else { throw CoCoRecordingError.message("The capture folder is not writable. Choose another folder in Capture Settings.") }
|
||||
}
|
||||
/// Atomic same-volume rename with no replacement, including simultaneous captures.
|
||||
static func promote(_ temporary: URL, folder: URL, name: String, extension ext: String) throws -> URL {
|
||||
for n in 0..<10_000 {
|
||||
let target = folder.appendingPathComponent(name + (n == 0 ? "" : "-\(n)")).appendingPathExtension(ext)
|
||||
if renamex_np(temporary.path, target.path, UInt32(RENAME_EXCL)) == 0 { return target }
|
||||
if errno != EEXIST { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
|
||||
}
|
||||
throw CoCoRecordingError.message("A unique capture filename could not be reserved.")
|
||||
}
|
||||
static func stamp(_ date: Date = Date()) -> String {
|
||||
let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd HH-mm-ss"
|
||||
return f.string(from: date)
|
||||
}
|
||||
static func save(_ capture: ScreenCapture, folder: URL) throws -> URL {
|
||||
try self.folder(folder)
|
||||
let temp = folder.appendingPathComponent(".vcc-screen-\(UUID().uuidString).png")
|
||||
defer { try? FileManager.default.removeItem(at: temp) }
|
||||
try capture.save(to: temp)
|
||||
return try promote(temp, folder: folder, name: "VCC Plus Screen " + stamp(), extension: "png")
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor final class CoCoCapturePreferences: ObservableObject {
|
||||
enum Destination: String { case desktop, documents, other }
|
||||
@Published private(set) var folder: URL
|
||||
@Published private(set) var preparingDestination = false
|
||||
@Published private(set) var timerSeconds: Int
|
||||
@Published var includeVideoAudio: Bool { didSet { defaults.set(includeVideoAudio, forKey: "capture.video.includeAudio") } }
|
||||
var screenshots: URL { folder }
|
||||
var recordings: URL { folder }
|
||||
private let defaults: UserDefaults
|
||||
private let fallbackRoot: URL?
|
||||
private let makeBookmark: @Sendable (URL) throws -> Data
|
||||
private var selectionRevision: UInt64 = 0
|
||||
private var scopes: [URL] = []
|
||||
var desktop: URL { fallbackRoot ?? FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0] }
|
||||
var documents: URL { fallbackRoot?.appendingPathComponent("Documents", isDirectory: true) ?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] }
|
||||
var destination: Destination {
|
||||
if folder.standardizedFileURL == desktop.standardizedFileURL { return .desktop }
|
||||
if folder.standardizedFileURL == documents.standardizedFileURL { return .documents }
|
||||
return .other
|
||||
}
|
||||
init(defaults: UserDefaults, fallbackRoot: URL? = nil,
|
||||
makeBookmark: @escaping @Sendable (URL) throws -> Data = { url in
|
||||
try url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
|
||||
}) {
|
||||
self.defaults = defaults; self.fallbackRoot = fallbackRoot; self.makeBookmark = makeBookmark
|
||||
let desktop = fallbackRoot ?? FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0]
|
||||
let documents = fallbackRoot?.appendingPathComponent("Documents", isDirectory: true)
|
||||
?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
let stored = defaults.string(forKey: "capture.destination").flatMap(Destination.init(rawValue:))
|
||||
let timer = defaults.integer(forKey: "capture.timer.seconds")
|
||||
timerSeconds = [0, 5, 10].contains(timer) ? timer : 0
|
||||
includeVideoAudio = defaults.object(forKey: "capture.video.includeAudio") as? Bool ?? true
|
||||
if stored == .desktop || stored == .documents {
|
||||
// Built-in choices are logical locations, not security bookmarks.
|
||||
// Neither selection nor restore touches a cloud-backed directory.
|
||||
folder = stored == .documents ? documents : desktop
|
||||
} else {
|
||||
func resolve(_ key: String) -> URL? {
|
||||
guard let data = defaults.data(forKey: key) else { return nil }
|
||||
var stale = false
|
||||
guard let url = try? URL(resolvingBookmarkData: data, options: [.withSecurityScope, .withoutUI],
|
||||
relativeTo: nil, bookmarkDataIsStale: &stale), url.isFileURL else { return nil }
|
||||
return url
|
||||
}
|
||||
let shared = resolve("capture.folder.shared")
|
||||
var legacy: (url: URL, bookmark: Data)?
|
||||
if shared == nil {
|
||||
for key in ["capture.folder.screenshots", "capture.folder.recordings"] {
|
||||
if let url = resolve(key), let bookmark = defaults.data(forKey: key) {
|
||||
legacy = (url, bookmark); break
|
||||
}
|
||||
}
|
||||
}
|
||||
folder = shared ?? legacy?.url ?? desktop
|
||||
if let legacy { defaults.set(legacy.bookmark, forKey: "capture.folder.shared") }
|
||||
if folder.standardizedFileURL == desktop.standardizedFileURL {
|
||||
if shared != nil || legacy != nil { defaults.set(Destination.desktop.rawValue, forKey: "capture.destination") }
|
||||
} else if folder.standardizedFileURL == documents.standardizedFileURL {
|
||||
defaults.set(Destination.documents.rawValue, forKey: "capture.destination")
|
||||
} else if shared != nil || legacy != nil {
|
||||
defaults.set(Destination.other.rawValue, forKey: "capture.destination")
|
||||
if folder.startAccessingSecurityScopedResource() { scopes.append(folder) }
|
||||
}
|
||||
}
|
||||
}
|
||||
func setTimerSeconds(_ seconds: Int) {
|
||||
guard [0, 5, 10].contains(seconds) else { return }
|
||||
timerSeconds = seconds; defaults.set(seconds, forKey: "capture.timer.seconds")
|
||||
}
|
||||
private func beginChoice() -> UInt64 {
|
||||
selectionRevision &+= 1; preparingDestination = false
|
||||
return selectionRevision
|
||||
}
|
||||
func setFolder(_ url: URL) async throws {
|
||||
try await prepareFolder(url, revision: beginChoice())
|
||||
}
|
||||
private func prepareFolder(_ url: URL, revision: UInt64) async throws {
|
||||
guard url.isFileURL else { throw CoCoRecordingError.message("Choose a local capture folder.") }
|
||||
guard revision == selectionRevision else { throw CancellationError() }
|
||||
// Selecting a built-in through Other Location has the same logical
|
||||
// semantics and never creates an unnecessary security bookmark.
|
||||
if url.standardizedFileURL == desktop.standardizedFileURL { setDestination(.desktop); return }
|
||||
if url.standardizedFileURL == documents.standardizedFileURL { setDestination(.documents); return }
|
||||
preparingDestination = true
|
||||
let makeBookmark = makeBookmark
|
||||
do {
|
||||
let grant = try await Task.detached(priority: .userInitiated) {
|
||||
let data = try makeBookmark(url)
|
||||
return (data, url.startAccessingSecurityScopedResource())
|
||||
}.value
|
||||
guard revision == selectionRevision else {
|
||||
if grant.1 { Task.detached(priority: .utility) { url.stopAccessingSecurityScopedResource() } }
|
||||
throw CancellationError()
|
||||
}
|
||||
// Keep old grants while an in-flight movie still owns its folder.
|
||||
if grant.1 { scopes.append(url) }
|
||||
defaults.set(grant.0, forKey: "capture.folder.shared")
|
||||
defaults.set(Destination.other.rawValue, forKey: "capture.destination")
|
||||
folder = url; preparingDestination = false
|
||||
} catch {
|
||||
guard revision == selectionRevision else { throw CancellationError() }
|
||||
preparingDestination = false; throw error
|
||||
}
|
||||
}
|
||||
func setDestination(_ value: Destination) {
|
||||
if value == .other { choose(); return }
|
||||
_ = beginChoice()
|
||||
folder = value == .desktop ? desktop : documents
|
||||
defaults.set(value.rawValue, forKey: "capture.destination")
|
||||
}
|
||||
func choose() {
|
||||
let revision = beginChoice()
|
||||
let panel = NSOpenPanel(); panel.title = "Save Screenshots and Videos To"
|
||||
panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true
|
||||
panel.directoryURL = folder
|
||||
panel.begin { [weak self] response in
|
||||
guard let self, revision == self.selectionRevision, response == .OK, let url = panel.url else { return }
|
||||
Task {
|
||||
do { try await self.prepareFolder(url, revision: revision) }
|
||||
catch is CancellationError { }
|
||||
catch { NSAlert(error: error).runModal() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CoCoRecordingRecovery: Codable, Identifiable {
|
||||
let id: UUID
|
||||
let created: Date
|
||||
let directory: URL
|
||||
var working: URL { directory.appendingPathComponent("Working.mov") }
|
||||
}
|
||||
private struct CoCoRecoveryDocument: Codable {
|
||||
var version = 1
|
||||
var recordings: [CoCoRecordingRecovery]
|
||||
}
|
||||
|
||||
/// Owns recording transport independently of AppKit's modal/main run loop.
|
||||
/// UI progress is observational: it never clocks or drains the movie pipeline.
|
||||
private actor CoCoRecordingSession {
|
||||
struct Completion: Sendable { let movie: URL?; let error: String? }
|
||||
private let controller: VCCMachineController
|
||||
private let encoder: CoCoVideoEncoder
|
||||
private let includeAudio: Bool
|
||||
private let folder: URL
|
||||
private let failed: @Sendable (String) -> Void
|
||||
private let replies = DispatchQueue(label: "com.brianholman.vccplus.capture-replies", qos: .userInitiated)
|
||||
private var pump: Task<Void, Never>?
|
||||
private var finalization: Task<Completion, Never>?
|
||||
private var capacityCheck: Task<Void, Never>?
|
||||
private var failureMessage: String?
|
||||
private var started = false
|
||||
|
||||
init(controller: VCCMachineController, encoder: CoCoVideoEncoder, includeAudio: Bool, folder: URL,
|
||||
failed: @escaping @Sendable (String) -> Void) {
|
||||
self.controller = controller; self.encoder = encoder; self.includeAudio = includeAudio
|
||||
self.folder = folder; self.failed = failed
|
||||
}
|
||||
func start() async throws -> TimeInterval {
|
||||
let snapshot = await withCheckedContinuation { continuation in
|
||||
controller.beginVideoCapture(replyQueue: replies) { continuation.resume(returning: $0) }
|
||||
}
|
||||
if let message = snapshot.errorMessage { throw CoCoRecordingError.message(message) }
|
||||
started = true
|
||||
let origin = ProcessInfo.processInfo.systemUptime
|
||||
encoder.failure = { [weak self] message in Task { await self?.fail(message) } }
|
||||
pump = Task { [weak self] in guard let self else { return }; await self.run() }
|
||||
return origin
|
||||
}
|
||||
private func packets(finish: Bool) async -> ([CoCoVideoFrame], String?) {
|
||||
let includeAudio = includeAudio
|
||||
return await withCheckedContinuation { continuation in
|
||||
controller.takeVideoCapture(finish: finish, replyQueue: replies) { packets, error in
|
||||
continuation.resume(returning: (packets.map {
|
||||
CoCoCaptureCoordinator.videoFrame(pixels: $0.pixels, area: $0.activeArea,
|
||||
audio: $0.samples, sampleOffset: Int64($0.sampleOffset), includeAudio: includeAudio)
|
||||
}, error))
|
||||
}
|
||||
}
|
||||
}
|
||||
private func run() async {
|
||||
var nextCapacityCheck: TimeInterval = 0
|
||||
while !Task.isCancelled {
|
||||
let result = await packets(finish: false)
|
||||
// Cancellation cannot discard bytes already drained by this pull.
|
||||
encoder.append(result.0)
|
||||
if let message = result.1 { fail(message); return }
|
||||
guard !Task.isCancelled else { return }
|
||||
let now = ProcessInfo.processInfo.systemUptime
|
||||
if now >= nextCapacityCheck {
|
||||
nextCapacityCheck = now + 5; checkCapacity()
|
||||
}
|
||||
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
|
||||
}
|
||||
}
|
||||
private func checkCapacity() {
|
||||
guard capacityCheck == nil, finalization == nil else { return }
|
||||
let folder = folder
|
||||
capacityCheck = Task { [weak self] in
|
||||
let free = await Task.detached(priority: .utility) {
|
||||
try? folder.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage
|
||||
}.value
|
||||
await self?.acceptCapacity(free)
|
||||
}
|
||||
}
|
||||
private func acceptCapacity(_ free: Int64?) {
|
||||
capacityCheck = nil
|
||||
guard finalization == nil, let free, free < 256 * 1024 * 1024 else { return }
|
||||
fail("Recording stopped because the destination is low on space. The working movie is retained.")
|
||||
}
|
||||
private func fail(_ message: String) {
|
||||
guard failureMessage == nil else { return }
|
||||
failureMessage = message
|
||||
_ = beginFinalization()
|
||||
failed(message)
|
||||
}
|
||||
private func beginFinalization() -> Task<Completion, Never> {
|
||||
if let finalization { return finalization }
|
||||
let draining = pump; pump = nil; draining?.cancel()
|
||||
let final = Task { [self] in
|
||||
// One owner waits for the in-flight pull, takes the final tail and
|
||||
// finishes the writer. User Stop and failures share this result.
|
||||
await draining?.value
|
||||
if started {
|
||||
let tail = await packets(finish: true)
|
||||
encoder.append(tail.0)
|
||||
if failureMessage == nil { failureMessage = tail.1 }
|
||||
}
|
||||
let result: Result<URL, Error> = await withCheckedContinuation { continuation in
|
||||
encoder.finish { continuation.resume(returning: $0) }
|
||||
}
|
||||
switch result {
|
||||
case .success(let url): return Completion(movie: url, error: failureMessage)
|
||||
case .failure(let error): return Completion(movie: nil, error: failureMessage ?? error.localizedDescription)
|
||||
}
|
||||
}
|
||||
finalization = final
|
||||
return final
|
||||
}
|
||||
func finish(failure: String? = nil) async -> Completion {
|
||||
if let failure { fail(failure) }
|
||||
return await beginFinalization().value
|
||||
}
|
||||
func currentFailure() -> String? { failureMessage }
|
||||
}
|
||||
|
||||
@MainActor final class CoCoCaptureCoordinator: ObservableObject {
|
||||
enum State: Equatable { case idle, starting, recording, finishing }
|
||||
@Published private(set) var state: State = .idle
|
||||
@Published private(set) var countdown: Int?
|
||||
@Published private(set) var elapsed: TimeInterval = 0
|
||||
@Published private(set) var saving = false
|
||||
@Published var error: String?
|
||||
@Published private(set) var saved: URL?
|
||||
@Published private(set) var recoveries: [CoCoRecordingRecovery] = []
|
||||
@Published var settingsShown = false
|
||||
let preferences: CoCoCapturePreferences
|
||||
private weak var machine: MachineModel?
|
||||
private let controller: VCCMachineController
|
||||
private var countdownTask: Task<Void, Never>?
|
||||
private var recordingTask: Task<Void, Never>?
|
||||
private var pendingImage: ScreenCapture?
|
||||
private var session: CoCoRecordingSession?
|
||||
private var recovery: CoCoRecordingRecovery?
|
||||
private var start = ProcessInfo.processInfo.systemUptime
|
||||
private var recoveryURL: URL
|
||||
private var canWriteRecovery = true
|
||||
private let feedback: (CoCoCaptureFeedback.Cue) -> Void
|
||||
var active: Bool { state != .idle }
|
||||
var recording: Bool { state == .recording }
|
||||
lazy var menuState = CoCoCaptureMenuState(self)
|
||||
|
||||
init(machine: MachineModel, controller: VCCMachineController, defaults: UserDefaults, directory: URL,
|
||||
feedback: ((CoCoCaptureFeedback.Cue) -> Void)? = nil) {
|
||||
self.machine = machine; self.controller = controller
|
||||
self.feedback = feedback ?? CoCoCaptureFeedback.play
|
||||
#if VCC_UI_TESTING
|
||||
let root = ProcessInfo.processInfo.environment["VCC_CAPTURE_TEST_DIRECTORY"].map { URL(fileURLWithPath: $0, isDirectory: true) } ?? directory.appendingPathComponent("Captures")
|
||||
preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||||
#else
|
||||
preferences = CoCoCapturePreferences(defaults: defaults)
|
||||
#endif
|
||||
recoveryURL = directory.appendingPathComponent("CaptureRecovery.json")
|
||||
if let data = try? Data(contentsOf: recoveryURL) {
|
||||
do {
|
||||
guard data.count <= 1_048_576 else { throw CoCoRecordingError.message("The recording recovery record is too large.") }
|
||||
let document = try JSONDecoder().decode(CoCoRecoveryDocument.self, from: data)
|
||||
guard document.version == 1 else { throw CoCoRecordingError.message("A newer recording recovery version has been preserved.") }
|
||||
let records = document.recordings
|
||||
guard records.allSatisfy({ $0.directory.isFileURL && $0.directory.lastPathComponent == ".vcc-recording-" + $0.id.uuidString }) else {
|
||||
throw CoCoRecordingError.message("The recording recovery record is invalid.")
|
||||
}
|
||||
recoveries = records
|
||||
} catch { self.error = "Recording recovery data was preserved but could not be read: \(error.localizedDescription)"; canWriteRecovery = false }
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera is the action; selecting menu options only changes preferences.
|
||||
func capture() {
|
||||
if preferences.timerSeconds == 0 { captureNow() } else { delay(preferences.timerSeconds) }
|
||||
}
|
||||
func captureNow() {
|
||||
guard !saving, pendingImage == nil, countdown == nil, let machine else { return }
|
||||
do {
|
||||
pendingImage = try ScreenCapture(pixels: machine.pixels, area: machine.activeVideoRect)
|
||||
feedback(.screenshot)
|
||||
savePending()
|
||||
}
|
||||
catch { self.error = error.localizedDescription }
|
||||
}
|
||||
private func savePending() {
|
||||
guard let image = pendingImage else { return }
|
||||
saving = true; error = nil
|
||||
let folder = preferences.screenshots
|
||||
Task {
|
||||
defer { saving = false }
|
||||
do {
|
||||
saved = try await Task.detached(priority: .userInitiated) { try CoCoCaptureFiles.save(image, folder: folder) }.value
|
||||
pendingImage = nil
|
||||
} catch { self.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
func saveImageAs() {
|
||||
guard let image = pendingImage, !saving else { return }
|
||||
let panel = NSSavePanel(); panel.title = "Save Captured CoCo Screen"; panel.allowedContentTypes = [.png]
|
||||
panel.nameFieldStringValue = "VCC Plus Screen " + CoCoCaptureFiles.stamp() + ".png"
|
||||
panel.begin { [weak self] result in
|
||||
guard let self, result == .OK, let url = panel.url else { return }
|
||||
self.saving = true
|
||||
Task { [self] in
|
||||
defer { self.saving = false }
|
||||
do {
|
||||
try await Task.detached { try image.save(to: url) }.value
|
||||
self.pendingImage = nil; self.saved = url; self.error = nil
|
||||
} catch { self.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
func discardImage() { guard !saving else { return }; pendingImage = nil; error = nil }
|
||||
var hasPendingImage: Bool { pendingImage != nil }
|
||||
func delay(_ seconds: Int) {
|
||||
guard [5, 10].contains(seconds), !saving, pendingImage == nil else { return }
|
||||
cancelCountdown(); countdown = seconds
|
||||
countdownTask = Task { [weak self] in
|
||||
for remaining in stride(from: seconds, through: 1, by: -1) {
|
||||
guard let self, !Task.isCancelled else { return }; countdown = remaining
|
||||
do { try await Task.sleep(for: .seconds(1)) } catch { return }
|
||||
}
|
||||
guard let self, !Task.isCancelled else { return }; countdown = nil; captureNow()
|
||||
}
|
||||
}
|
||||
func cancelCountdown() { countdownTask?.cancel(); countdownTask = nil; countdown = nil }
|
||||
|
||||
func startRecording() {
|
||||
guard state == .idle, let machine, machine.pixels != nil else { return }
|
||||
if machine.settings.fastForward {
|
||||
error = "Turn off fast-forward before recording video. No machine setting has been changed."; return
|
||||
}
|
||||
guard canWriteRecovery else { error = "Resolve the preserved recording recovery record before starting another movie."; return }
|
||||
state = .starting; error = nil
|
||||
let includeAudio = preferences.includeVideoAudio
|
||||
let folder = preferences.recordings
|
||||
Task { [self] in
|
||||
do {
|
||||
let entry = CoCoRecordingRecovery(id: UUID(), created: Date(), directory: folder.appendingPathComponent(".vcc-recording-" + UUID().uuidString))
|
||||
// Directory identity is tied to its recovery ID; never clean a user folder.
|
||||
let record = CoCoRecordingRecovery(id: entry.id, created: entry.created,
|
||||
directory: folder.appendingPathComponent(".vcc-recording-" + entry.id.uuidString, isDirectory: true))
|
||||
let newEncoder = try await Task.detached { try CoCoCaptureFiles.folder(record.directory); return try CoCoVideoEncoder(workingURL: record.working) }.value
|
||||
let backend = CoCoRecordingSession(controller: controller, encoder: newEncoder,
|
||||
includeAudio: includeAudio, folder: folder) { [weak self] message in
|
||||
Task { @MainActor in
|
||||
guard let self, self.recovery?.id == record.id else { return }
|
||||
self.error = message
|
||||
await self.stopRecording(failed: true)
|
||||
}
|
||||
}
|
||||
session = backend
|
||||
recovery = record; recoveries.append(record); try await persistRecovery()
|
||||
let origin = try await backend.start()
|
||||
state = .recording; start = origin; elapsed = ProcessInfo.processInfo.systemUptime - origin
|
||||
let startupFailure = await backend.currentFailure()
|
||||
// A failure notification can finish this session while the
|
||||
// status query suspends us. Never publish a stale success cue
|
||||
// or resurrect its progress task after that finalization.
|
||||
guard recovery?.id == record.id, state == .recording else { return }
|
||||
if let startupFailure {
|
||||
error = startupFailure; await stopRecording(failed: true); return
|
||||
}
|
||||
feedback(.recordingStarted)
|
||||
recordingTask = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
guard let self, state == .recording else { return }
|
||||
elapsed = ProcessInfo.processInfo.systemUptime - start
|
||||
do { try await Task.sleep(for: .milliseconds(250)) } catch { return }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
// Even a failed bridge start may own a writer. Recovery and
|
||||
// quit must wait until that writer has finished its last work.
|
||||
state = .finishing
|
||||
if let session { _ = await session.finish(failure: self.error) }
|
||||
session = nil; recovery = nil; state = .idle
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Keep the recording clock and packet duration unchanged for silent video.
|
||||
/// Only emulated PCM is selected here; host shutter/start cues never enter it.
|
||||
nonisolated static func videoFrame(pixels: Data, area: CGRect, audio: Data, sampleOffset: Int64, includeAudio: Bool) -> CoCoVideoFrame {
|
||||
CoCoVideoFrame(pixels: pixels, area: area, audio: includeAudio ? audio : Data(count: audio.count), sampleOffset: sampleOffset)
|
||||
}
|
||||
func stopRecording(failed: Bool = false) async {
|
||||
guard state == .recording, let session, let record = recovery else { return }
|
||||
state = .finishing
|
||||
recordingTask?.cancel(); recordingTask = nil
|
||||
let result = await session.finish(failure: failed ? (error ?? "Recording stopped with an error. The working movie is retained.") : nil)
|
||||
if let message = result.error { error = message }
|
||||
do {
|
||||
if !failed, result.error == nil, let movie = result.movie {
|
||||
try await complete(record, movie: movie, folder: record.directory.deletingLastPathComponent())
|
||||
}
|
||||
} catch { self.error = error.localizedDescription }
|
||||
self.session = nil; recovery = nil; state = .idle
|
||||
}
|
||||
func recover(_ record: CoCoRecordingRecovery) {
|
||||
guard state == .idle else { return }; state = .finishing; error = nil
|
||||
Task {
|
||||
defer { state = .idle }
|
||||
do { try await complete(record, movie: record.working, folder: preferences.recordings) }
|
||||
catch { self.error = "Recovery did not complete. Retained files are unchanged. \(error.localizedDescription)" }
|
||||
}
|
||||
}
|
||||
private func complete(_ record: CoCoRecordingRecovery, movie: URL, folder: URL) async throws {
|
||||
let final = try await Task.detached(priority: .userInitiated) {
|
||||
try CoCoCaptureFiles.folder(folder)
|
||||
let temp = folder.appendingPathComponent(".vcc-finish-" + UUID().uuidString + ".mp4")
|
||||
do {
|
||||
try await CoCoVideoEncoder.exportMP4(from: movie, to: temp)
|
||||
return try CoCoCaptureFiles.promote(temp, folder: folder, name: "VCC Plus Video " + CoCoCaptureFiles.stamp(record.created), extension: "mp4")
|
||||
} catch { try? FileManager.default.removeItem(at: temp); throw error }
|
||||
}.value
|
||||
saved = final
|
||||
recoveries.removeAll { $0.id == record.id }; try await persistRecovery()
|
||||
// Only this verified owned working file/directory is removed.
|
||||
try? FileManager.default.removeItem(at: record.working)
|
||||
_ = rmdir(record.directory.path) // Never remove unexpected files added to it.
|
||||
}
|
||||
private func persistRecovery() async throws {
|
||||
guard canWriteRecovery else { throw CoCoRecordingError.message("Recovery data is read-only until repaired.") }
|
||||
let records = recoveries, url = recoveryURL
|
||||
try await Task.detached(priority: .utility) {
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(CoCoRecoveryDocument(recordings: records)).write(to: url, options: .atomic)
|
||||
}.value
|
||||
}
|
||||
func stopBeforeReplacingMachine() async -> Bool {
|
||||
cancelCountdown()
|
||||
guard active else { return true }
|
||||
guard state == .recording else { error = "Wait for the recording to finish."; return false }
|
||||
let alert = NSAlert(); alert.messageText = "Stop and save the CoCo movie first?"
|
||||
alert.informativeText = "Changing the machine ends this recording. Existing media safeguards still apply."
|
||||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Stop and Continue")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return false }
|
||||
let id = recovery?.id
|
||||
await stopRecording(); return state == .idle && !recoveries.contains { $0.id == id }
|
||||
}
|
||||
}
|
||||
|
||||
/// Native menus observe transitions, not per-frame/elapsed-time notifications.
|
||||
@MainActor final class CoCoCaptureMenuState: ObservableObject {
|
||||
@Published private(set) var state: CoCoCaptureCoordinator.State
|
||||
@Published private(set) var countdown = false
|
||||
private var tokens: Set<AnyCancellable> = []
|
||||
init(_ capture: CoCoCaptureCoordinator) {
|
||||
state = capture.state
|
||||
capture.$state.removeDuplicates().sink { [weak self] in self?.state = $0 }.store(in: &tokens)
|
||||
capture.$countdown.map { $0 != nil }.removeDuplicates().sink { [weak self] in self?.countdown = $0 }.store(in: &tokens)
|
||||
}
|
||||
}
|
||||
|
||||
struct CoCoCaptureControls: View {
|
||||
@ObservedObject var capture: CoCoCaptureCoordinator
|
||||
@ObservedObject var machine: MachineModel
|
||||
@ObservedObject private var preferences: CoCoCapturePreferences
|
||||
init(capture: CoCoCaptureCoordinator, machine: MachineModel) {
|
||||
self.capture = capture; self.machine = machine; preferences = capture.preferences
|
||||
}
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
var body: some View {
|
||||
HStack(spacing: 4) {
|
||||
Button { capture.capture() } label: { Image(systemName: "camera").frame(width: 28, height: 28) }
|
||||
.help(preferences.timerSeconds == 0 ? "Capture CoCo Screen" : "Capture CoCo Screen after \(preferences.timerSeconds) seconds").accessibilityLabel("Capture CoCo Screen")
|
||||
.accessibilityIdentifier("capture-now")
|
||||
.disabled(machine.pixels == nil || capture.countdown != nil || capture.saving || capture.hasPendingImage)
|
||||
Menu {
|
||||
CoCoCaptureOptions(preferences: preferences)
|
||||
if capture.countdown != nil { Button("Cancel Capture", action: capture.cancelCountdown) }
|
||||
Divider(); Button("Capture Settings…") { capture.settingsShown = true }
|
||||
} label: { Image(systemName: "chevron.down").frame(width: 14, height: 28) }
|
||||
.menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Screenshot and video options")
|
||||
.accessibilityLabel("Screenshot and video options").accessibilityIdentifier("capture-options")
|
||||
Button {
|
||||
if capture.recording { Task { await capture.stopRecording() } } else { capture.startRecording() }
|
||||
} label: {
|
||||
Image(systemName: capture.recording ? "stop.circle.fill" : "video")
|
||||
.foregroundStyle(capture.recording ? Color.red : Color.primary)
|
||||
.symbolEffect(.pulse, options: .repeating, isActive: capture.recording && !reduceMotion)
|
||||
.frame(width: 28, height: 28)
|
||||
}.help(capture.recording ? "Stop Recording" : (preferences.includeVideoAudio ? "Record CoCo Video with CoCo audio, even when local playback is muted" : "Record CoCo Video without audio"))
|
||||
.accessibilityLabel(capture.recording ? "Stop Recording" : "Record CoCo Video")
|
||||
.accessibilityIdentifier("capture-record")
|
||||
.disabled((!capture.recording && machine.pixels == nil) || capture.state == .starting || capture.state == .finishing)
|
||||
if let seconds = capture.countdown {
|
||||
Button("\(seconds)s · Cancel", action: capture.cancelCountdown).font(.caption).help("Cancel Capture")
|
||||
.accessibilityIdentifier("capture-countdown-cancel")
|
||||
} else if capture.active {
|
||||
Text(capture.state == .finishing ? "Finishing…" : String(format: "%02d:%02d", Int(capture.elapsed)/60, Int(capture.elapsed)%60))
|
||||
.font(.caption.monospacedDigit()).frame(minWidth: 42)
|
||||
}
|
||||
if capture.error != nil || !capture.recoveries.isEmpty && !capture.active {
|
||||
Button { capture.settingsShown = true } label: { Image(systemName: "exclamationmark.circle").foregroundStyle(.orange) }
|
||||
.help(capture.error ?? "Retained recording available — open Capture Settings")
|
||||
.accessibilityLabel("Capture status and recovery")
|
||||
} else if let saved = capture.saved {
|
||||
Button { NSWorkspace.shared.activateFileViewerSelecting([saved]) } label: { Image(systemName: "checkmark.circle") }
|
||||
.help("Saved \(saved.lastPathComponent) — Show in Finder").accessibilityLabel("Show saved capture in Finder")
|
||||
}
|
||||
}.buttonStyle(.borderless)
|
||||
.sheet(isPresented: $capture.settingsShown) { CoCoCaptureSettings(capture: capture, preferences: capture.preferences) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One shared options view keeps the header menu and settings sheet consistent.
|
||||
struct CoCoCaptureOptions: View {
|
||||
@ObservedObject var preferences: CoCoCapturePreferences
|
||||
var body: some View {
|
||||
Section("Save Screenshots and Videos To") {
|
||||
Toggle("Desktop", isOn: Binding(get: { preferences.destination == .desktop }, set: { _ in preferences.setDestination(.desktop) }))
|
||||
.accessibilityIdentifier("capture-destination-desktop")
|
||||
Toggle("Documents", isOn: Binding(get: { preferences.destination == .documents }, set: { _ in preferences.setDestination(.documents) }))
|
||||
.accessibilityIdentifier("capture-destination-documents")
|
||||
Button(action: preferences.choose) {
|
||||
if preferences.destination == .other { Label("Other Location…", systemImage: "checkmark") }
|
||||
else { Text("Other Location…") }
|
||||
}.accessibilityIdentifier("capture-destination-other")
|
||||
if preferences.destination == .other { Text(preferences.folder.lastPathComponent).font(.caption) }
|
||||
}
|
||||
Picker("Screenshot Timer", selection: Binding(get: { preferences.timerSeconds }, set: preferences.setTimerSeconds)) {
|
||||
Text("None").tag(0)
|
||||
Text("5 Seconds").tag(5)
|
||||
Text("10 Seconds").tag(10)
|
||||
}.pickerStyle(.inline).accessibilityIdentifier("capture-timer")
|
||||
Toggle("Include CoCo Audio in Video", isOn: $preferences.includeVideoAudio)
|
||||
.accessibilityIdentifier("capture-video-audio")
|
||||
}
|
||||
}
|
||||
|
||||
struct CoCoCaptureSettings: View {
|
||||
@ObservedObject var capture: CoCoCaptureCoordinator
|
||||
@ObservedObject var preferences: CoCoCapturePreferences
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("CoCo Capture").font(.title2.bold())
|
||||
Text("Captures include only the CoCo picture. System artwork, Mac windows and the desktop are excluded. Include CoCo Audio in Video controls the movie’s sound, even when local playback is muted. Shutter and recording-start cues are never recorded.")
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Save Screenshots and Videos To").font(.headline)
|
||||
Picker("Save to", selection: Binding(get: { preferences.destination }, set: preferences.setDestination)) {
|
||||
Text("Desktop").tag(CoCoCapturePreferences.Destination.desktop)
|
||||
Text("Documents").tag(CoCoCapturePreferences.Destination.documents)
|
||||
Text("Other Location…").tag(CoCoCapturePreferences.Destination.other)
|
||||
}.accessibilityIdentifier("capture-settings-destination")
|
||||
Text(preferences.folder.path).font(.caption).textSelection(.enabled).lineLimit(2)
|
||||
if preferences.preparingDestination {
|
||||
Label("Preparing capture folder…", systemImage: "hourglass").font(.caption)
|
||||
.accessibilityIdentifier("capture-settings-preparing-folder")
|
||||
}
|
||||
HStack { Button("Other Location…", action: preferences.choose); Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: preferences.folder.path) } }
|
||||
Picker("Screenshot Timer", selection: Binding(get: { preferences.timerSeconds }, set: preferences.setTimerSeconds)) {
|
||||
Text("None").tag(0); Text("5 Seconds").tag(5); Text("10 Seconds").tag(10)
|
||||
}.accessibilityIdentifier("capture-settings-timer")
|
||||
Toggle("Include CoCo Audio in Video", isOn: $preferences.includeVideoAudio)
|
||||
.accessibilityIdentifier("capture-settings-video-audio")
|
||||
Text("The camera button uses the selected timer. Video recording starts immediately. Audio choices apply to the next recording.")
|
||||
.font(.caption).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if !capture.recoveries.isEmpty {
|
||||
Divider(); Text("Retained Recordings").font(.headline)
|
||||
ForEach(capture.recoveries) { record in
|
||||
HStack { Text(record.created.formatted()); Button("Recover MP4") { capture.recover(record) }.disabled(capture.active)
|
||||
Button("Show Files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: record.directory.path) } }
|
||||
}
|
||||
Text("Interrupted movies may contain only completed fragments. Working files remain until a verified MP4 is saved.").font(.caption)
|
||||
}
|
||||
if let error = capture.error { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||||
if capture.hasPendingImage {
|
||||
HStack { Button("Save Captured Image As…", action: capture.saveImageAs); Button("Discard Captured Image", action: capture.discardImage) }.disabled(capture.saving)
|
||||
}
|
||||
HStack { Spacer(); Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) }
|
||||
}.padding(24).frame(width: 520)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
|
||||
/// Host feedback has no connection to the emulator's generated PCM or either
|
||||
/// video/playtest capture path. No microphone or system-output recording is used.
|
||||
@MainActor enum CoCoCaptureFeedback {
|
||||
enum Cue: Equatable { case screenshot, recordingStarted }
|
||||
|
||||
private static let shutter = sound("screenshot")
|
||||
private static let recording = sound("recording-start")
|
||||
|
||||
private static func sound(_ name: String) -> NSSound? {
|
||||
guard let url = Bundle.main.url(forResource: name, withExtension: "wav", subdirectory: "CaptureSounds") else { return nil }
|
||||
return NSSound(contentsOf: url, byReference: false)
|
||||
}
|
||||
|
||||
static func play(_ cue: Cue) {
|
||||
let sound = cue == .screenshot ? shutter : recording
|
||||
sound?.stop()
|
||||
sound?.play()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import CoreGraphics
|
||||
import CoreVideo
|
||||
import AudioToolbox
|
||||
|
||||
/// Only emulator pixels and generated stereo PCM enter this boundary. There is
|
||||
/// deliberately no host-window, microphone, or screen-recording API here.
|
||||
struct CoCoVideoFrame: Sendable {
|
||||
var pixels: Data
|
||||
var area: CGRect
|
||||
var audio: Data // packed, interleaved Float32 stereo, 44,100 sample frames/sec
|
||||
var sampleOffset: Int64
|
||||
}
|
||||
|
||||
enum CoCoRecordingError: LocalizedError {
|
||||
case message(String)
|
||||
var errorDescription: String? { if case let .message(s) = self { return s }; return nil }
|
||||
}
|
||||
|
||||
/// Serial, bounded writer. Working MOV fragments remain available after a
|
||||
/// failure; only a verified MP4 completion permits their owner to clean up.
|
||||
final class CoCoVideoEncoder: @unchecked Sendable {
|
||||
static let width = 1280, height = 960
|
||||
static let rate: Int32 = 44_100
|
||||
let workingURL: URL
|
||||
private let queue = DispatchQueue(label: "com.brianholman.vccplus.video-encoder", qos: .userInitiated)
|
||||
private let writer: AVAssetWriter
|
||||
private let video: AVAssetWriterInput
|
||||
private let audio: AVAssetWriterInput
|
||||
private let adaptor: AVAssetWriterInputPixelBufferAdaptor
|
||||
private var audioFormat: CMAudioFormatDescription?
|
||||
private var images: [(Data, CGRect, Int64)] = []
|
||||
private var sounds: [(Data, Int64)] = []
|
||||
private var queuedSamples = 0
|
||||
private var lastVideoTick: Int64 = -1
|
||||
private var previousPicture: (Data, CGRect)?
|
||||
private var lastAudioEnd: Int64 = 0
|
||||
private var finalSample: Int64 = 0
|
||||
private var finishing = false, draining = false, failed = false
|
||||
private var finishReplies: [(Result<URL, Error>) -> Void] = []
|
||||
private var finishResult: Result<URL, Error>?
|
||||
private var closingWriter = false
|
||||
private var failureError: Error?
|
||||
private let ingressLock = NSLock()
|
||||
private var accepting = true
|
||||
private var retainedFrames = 0, retainedSamples = 0
|
||||
var failure: (@Sendable (String) -> Void)?
|
||||
/// Read-only AVFoundation lifecycle evidence; a finish reply promises this
|
||||
/// terminal state, including when a failed movie is retained for recovery.
|
||||
var writerIsTerminal: Bool { [.completed, .failed, .cancelled].contains(writer.status) }
|
||||
|
||||
init(workingURL: URL) throws {
|
||||
self.workingURL = workingURL
|
||||
writer = try AVAssetWriter(outputURL: workingURL, fileType: .mov)
|
||||
writer.movieFragmentInterval = CMTime(seconds: 10, preferredTimescale: 600)
|
||||
writer.initialMovieFragmentInterval = CMTime(seconds: 1, preferredTimescale: 600)
|
||||
video = AVAssetWriterInput(mediaType: .video, outputSettings: [
|
||||
AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: Self.width,
|
||||
AVVideoHeightKey: Self.height, AVVideoCompressionPropertiesKey: [
|
||||
AVVideoAverageBitRateKey: 4_000_000, AVVideoExpectedSourceFrameRateKey: 60,
|
||||
AVVideoMaxKeyFrameIntervalKey: 60, AVVideoAllowFrameReorderingKey: false]])
|
||||
audio = AVAssetWriterInput(mediaType: .audio, outputSettings: [
|
||||
AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 48_000,
|
||||
AVNumberOfChannelsKey: 2, AVEncoderBitRateKey: 160_000])
|
||||
video.expectsMediaDataInRealTime = true; audio.expectsMediaDataInRealTime = true
|
||||
adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: video,
|
||||
sourcePixelBufferAttributes: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
|
||||
kCVPixelBufferWidthKey as String: Self.width, kCVPixelBufferHeightKey as String: Self.height,
|
||||
kCVPixelBufferCGImageCompatibilityKey as String: true,
|
||||
kCVPixelBufferCGBitmapContextCompatibilityKey as String: true])
|
||||
guard writer.canAdd(video), writer.canAdd(audio) else { throw CoCoRecordingError.message("The native video/audio encoder is unavailable.") }
|
||||
writer.add(video); writer.add(audio)
|
||||
var format = AudioStreamBasicDescription(mSampleRate: Double(Self.rate), mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: 8, mFramesPerPacket: 1, mBytesPerFrame: 8, mChannelsPerFrame: 2,
|
||||
mBitsPerChannel: 32, mReserved: 0)
|
||||
guard CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &format,
|
||||
layoutSize: 0, layout: nil, magicCookieSize: 0, magicCookie: nil,
|
||||
extensions: nil, formatDescriptionOut: &audioFormat) == noErr,
|
||||
writer.startWriting() else { throw writer.error ?? CoCoRecordingError.message("The recording could not start.") }
|
||||
writer.startSession(atSourceTime: .zero)
|
||||
}
|
||||
|
||||
func append(_ frames: [CoCoVideoFrame]) {
|
||||
let samples = frames.reduce(0) { $0 + $1.audio.count / 8 }
|
||||
ingressLock.lock()
|
||||
guard accepting else { ingressLock.unlock(); return }
|
||||
guard retainedFrames + frames.count <= 12, retainedSamples + samples <= Int(Self.rate) * 2 else {
|
||||
accepting = false; ingressLock.unlock()
|
||||
queue.async { [self] in fail(CoCoRecordingError.message("The recorder reached its bounded input limit. The working movie has been retained.")) }
|
||||
return
|
||||
}
|
||||
retainedFrames += frames.count; retainedSamples += samples
|
||||
ingressLock.unlock()
|
||||
queue.async { [self] in
|
||||
guard !failed, !finishing else { return }
|
||||
do {
|
||||
for frame in frames {
|
||||
guard frame.pixels.count == 640 * 480 * 4, frame.audio.count % 8 == 0,
|
||||
frame.sampleOffset >= lastAudioEnd else {
|
||||
throw CoCoRecordingError.message("The recording input lost its frame/audio ordering.")
|
||||
}
|
||||
let gap = frame.sampleOffset - lastAudioEnd
|
||||
guard gap <= Int64(Self.rate) * 2 else { throw CoCoRecordingError.message("The recording input was interrupted. The working movie has been retained.") }
|
||||
if gap > 0 {
|
||||
ingressLock.lock()
|
||||
let allowed = retainedSamples + Int(gap) <= Int(Self.rate) * 2
|
||||
if allowed { retainedSamples += Int(gap) }
|
||||
ingressLock.unlock()
|
||||
guard allowed else { throw CoCoRecordingError.message("The recorder reached its bounded audio limit.") }
|
||||
sounds.append((Data(count: Int(gap) * 8), lastAudioEnd)); queuedSamples += Int(gap)
|
||||
}
|
||||
if !frame.audio.isEmpty { sounds.append((frame.audio, frame.sampleOffset)); queuedSamples += frame.audio.count / 8 }
|
||||
lastAudioEnd = frame.sampleOffset + Int64(frame.audio.count / 8)
|
||||
finalSample = max(finalSample, lastAudioEnd)
|
||||
let tick = frame.sampleOffset * 60 / Int64(Self.rate)
|
||||
if tick > lastVideoTick {
|
||||
let duplicates = Int(tick - lastVideoTick - 1)
|
||||
if duplicates > 0 {
|
||||
ingressLock.lock()
|
||||
let allowed = retainedFrames + duplicates <= 12
|
||||
if allowed { retainedFrames += duplicates }
|
||||
ingressLock.unlock()
|
||||
guard allowed else { throw CoCoRecordingError.message("The recording frame clock was interrupted. The working movie is retained.") }
|
||||
let held = previousPicture ?? (frame.pixels, frame.area)
|
||||
for t in (lastVideoTick + 1)..<tick { images.append((held.0, held.1, t)) }
|
||||
}
|
||||
images.append((frame.pixels, frame.area, tick)); lastVideoTick = tick
|
||||
previousPicture = (frame.pixels, frame.area)
|
||||
}
|
||||
else { release(frames: 1, samples: 0) }
|
||||
guard images.count <= 12, queuedSamples <= Int(Self.rate) * 2 else {
|
||||
throw CoCoRecordingError.message("The video encoder could not keep up. The working movie has been retained.")
|
||||
}
|
||||
}
|
||||
drain()
|
||||
} catch { fail(error) }
|
||||
}
|
||||
}
|
||||
|
||||
func finish(_ completion: @escaping (Result<URL, Error>) -> Void) {
|
||||
ingressLock.lock(); accepting = false; ingressLock.unlock()
|
||||
queue.async { [self] in
|
||||
if let finishResult { completion(finishResult); return }
|
||||
finishReplies.append(completion)
|
||||
guard !finishing, !failed else { return }
|
||||
finishing = true; drain()
|
||||
}
|
||||
}
|
||||
|
||||
/// A disposable producer advances faster than wall time. Its own worker may
|
||||
/// await this acknowledgement rather than overflowing the unchanged bounded
|
||||
/// ingress queue. The application recorder continues using nonblocking append.
|
||||
func whenDrained(_ completion: @escaping @Sendable (Result<Void, Error>) -> Void) {
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + 10
|
||||
func check() {
|
||||
queue.async { [self] in
|
||||
if failed { completion(.failure(writer.error ?? CoCoRecordingError.message("The video writer stopped."))); return }
|
||||
ingressLock.lock()
|
||||
let empty = retainedFrames == 0 && retainedSamples == 0
|
||||
ingressLock.unlock()
|
||||
if empty { completion(.success(())) }
|
||||
else if ProcessInfo.processInfo.systemUptime >= deadline {
|
||||
let error = CoCoRecordingError.message("The video writer did not drain within its deadline.")
|
||||
fail(error); completion(.failure(error))
|
||||
} else { queue.asyncAfter(deadline: .now() + .milliseconds(5), execute: check) }
|
||||
}
|
||||
}
|
||||
check()
|
||||
}
|
||||
|
||||
private func drain() {
|
||||
guard !failed else { return }
|
||||
do {
|
||||
while !images.isEmpty && video.isReadyForMoreMediaData {
|
||||
let image = images.removeFirst()
|
||||
let pixel = try Self.pixelBuffer(image.0, area: image.1, pool: adaptor.pixelBufferPool)
|
||||
guard adaptor.append(pixel, withPresentationTime: CMTime(value: image.2, timescale: 60)) else {
|
||||
throw writer.error ?? CoCoRecordingError.message("A video frame could not be written.")
|
||||
}
|
||||
release(frames: 1, samples: 0)
|
||||
}
|
||||
while !sounds.isEmpty && audio.isReadyForMoreMediaData {
|
||||
let sound = sounds.removeFirst(); queuedSamples -= sound.0.count / 8
|
||||
let sample = try audioSample(sound.0, offset: sound.1)
|
||||
guard audio.append(sample) else { throw writer.error ?? CoCoRecordingError.message("CoCo sound could not be written.") }
|
||||
release(frames: 0, samples: sound.0.count / 8)
|
||||
}
|
||||
if writer.status == .failed { throw writer.error ?? CoCoRecordingError.message("The movie writer stopped.") }
|
||||
if images.isEmpty && sounds.isEmpty {
|
||||
if finishing, !closingWriter {
|
||||
closingWriter = true
|
||||
writer.endSession(atSourceTime: CMTime(value: max(finalSample, 735), timescale: Self.rate))
|
||||
video.markAsFinished(); audio.markAsFinished()
|
||||
writer.finishWriting { [self] in
|
||||
queue.async { [self] in
|
||||
if let failureError { finishAll(.failure(failureError)) }
|
||||
else if writer.status == .completed { finishAll(.success(workingURL)) }
|
||||
else { finishAll(.failure(writer.error ?? CoCoRecordingError.message("The working movie could not be finalized."))) }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if !draining {
|
||||
draining = true
|
||||
queue.asyncAfter(deadline: .now() + .milliseconds(5)) { [self] in draining = false; drain() }
|
||||
}
|
||||
} catch { fail(error) }
|
||||
}
|
||||
|
||||
private func fail(_ error: Error) {
|
||||
guard !failed else { return }; failed = true
|
||||
failureError = error
|
||||
ingressLock.lock(); accepting = false; retainedFrames = 0; retainedSamples = 0; ingressLock.unlock()
|
||||
images.removeAll(); sounds.removeAll(); queuedSamples = 0
|
||||
// Finishing what the framework can retain is preferable to cancelling
|
||||
// and deleting fragments. Every Stop waits for that closure, including
|
||||
// Stop arriving after the failure callback or during another Stop.
|
||||
if closingWriter {
|
||||
// The existing AVFoundation callback owns the terminal result.
|
||||
} else if writer.status == .writing {
|
||||
closingWriter = true
|
||||
video.markAsFinished(); audio.markAsFinished()
|
||||
writer.finishWriting { [self] in queue.async { [self] in finishAll(.failure(error)) } }
|
||||
} else { finishAll(.failure(error)) }
|
||||
failure?(error.localizedDescription)
|
||||
}
|
||||
private func finishAll(_ result: Result<URL, Error>) {
|
||||
guard finishResult == nil else { return }
|
||||
finishResult = result
|
||||
let replies = finishReplies; finishReplies.removeAll()
|
||||
for reply in replies { reply(result) }
|
||||
}
|
||||
private func release(frames: Int, samples: Int) {
|
||||
ingressLock.lock(); retainedFrames -= frames; retainedSamples -= samples; ingressLock.unlock()
|
||||
}
|
||||
|
||||
private func audioSample(_ data: Data, offset: Int64) throws -> CMSampleBuffer {
|
||||
var block: CMBlockBuffer?
|
||||
guard CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil,
|
||||
blockLength: data.count, blockAllocator: kCFAllocatorDefault, customBlockSource: nil,
|
||||
offsetToData: 0, dataLength: data.count, flags: 0, blockBufferOut: &block) == kCMBlockBufferNoErr,
|
||||
let block else { throw CoCoRecordingError.message("Audio buffer allocation failed.") }
|
||||
let copied = data.withUnsafeBytes { CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: block, offsetIntoDestination: 0, dataLength: data.count) }
|
||||
var time = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: Self.rate),
|
||||
presentationTimeStamp: CMTime(value: offset, timescale: Self.rate), decodeTimeStamp: .invalid)
|
||||
var sample: CMSampleBuffer?
|
||||
guard copied == noErr, CMSampleBufferCreateReady(allocator: kCFAllocatorDefault,
|
||||
dataBuffer: block, formatDescription: audioFormat, sampleCount: data.count / 8,
|
||||
sampleTimingEntryCount: 1, sampleTimingArray: &time, sampleSizeEntryCount: 0,
|
||||
sampleSizeArray: nil, sampleBufferOut: &sample) == noErr, let sample else {
|
||||
throw CoCoRecordingError.message("The CoCo audio sample could not be prepared.")
|
||||
}
|
||||
return sample
|
||||
}
|
||||
|
||||
static func pixelBuffer(_ bytes: Data, area: CGRect, pool: CVPixelBufferPool?) throws -> CVPixelBuffer {
|
||||
guard bytes.count == 640 * 480 * 4 else { throw CoCoRecordingError.message("No complete CoCo picture is available.") }
|
||||
guard [area.minX, area.minY, area.width, area.height].allSatisfy(\.isFinite) else {
|
||||
throw CoCoRecordingError.message("The recording picture dimensions are invalid.")
|
||||
}
|
||||
let bounds = CGRect(x: 0, y: 0, width: 640, height: 480)
|
||||
let rect = area.intersection(bounds).integral
|
||||
guard !rect.isEmpty, !rect.isNull, let pool else { throw CoCoRecordingError.message("The recording picture dimensions are invalid.") }
|
||||
var buffer: CVPixelBuffer?
|
||||
guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &buffer) == kCVReturnSuccess, let buffer else { throw CoCoRecordingError.message("A video pixel buffer could not be allocated.") }
|
||||
CVPixelBufferLockBaseAddress(buffer, []); defer { CVPixelBufferUnlockBaseAddress(buffer, []) }
|
||||
let color = CGColorSpace(name: CGColorSpace.sRGB)!
|
||||
guard let source = CGDataProvider(data: bytes as CFData),
|
||||
let image = CGImage(width: 640, height: 480, bitsPerComponent: 8, bitsPerPixel: 32,
|
||||
bytesPerRow: 640 * 4, space: color,
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue),
|
||||
provider: source, decode: nil, shouldInterpolate: false, intent: .defaultIntent)?.cropping(to: rect),
|
||||
let context = CGContext(data: CVPixelBufferGetBaseAddress(buffer), width: width, height: height,
|
||||
bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(buffer), space: color,
|
||||
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) else {
|
||||
throw CoCoRecordingError.message("The CoCo picture could not be rendered for video.")
|
||||
}
|
||||
context.setFillColor(CGColor(gray: 0, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: width, height: height))
|
||||
let scale = min(CGFloat(width) / rect.width, CGFloat(height) / rect.height)
|
||||
let size = CGSize(width: rect.width * scale, height: rect.height * scale)
|
||||
context.interpolationQuality = .none
|
||||
context.draw(image, in: CGRect(x: (CGFloat(width)-size.width)/2, y: (CGFloat(height)-size.height)/2, width: size.width, height: size.height))
|
||||
return buffer
|
||||
}
|
||||
|
||||
static func exportMP4(from source: URL, to destination: URL) async throws {
|
||||
guard !FileManager.default.fileExists(atPath: destination.path),
|
||||
let export = AVAssetExportSession(asset: AVURLAsset(url: source), presetName: AVAssetExportPresetPassthrough),
|
||||
export.supportedFileTypes.contains(.mp4) else { throw CoCoRecordingError.message("The retained movie cannot be converted to this MP4 destination.") }
|
||||
export.outputURL = destination; export.outputFileType = .mp4
|
||||
await export.export()
|
||||
guard export.status == .completed else { throw export.error ?? CoCoRecordingError.message("MP4 completion failed; the working movie has been retained.") }
|
||||
let asset = AVURLAsset(url: destination)
|
||||
guard try await !asset.loadTracks(withMediaType: .video).isEmpty,
|
||||
try await !asset.loadTracks(withMediaType: .audio).isEmpty,
|
||||
try await asset.load(.duration).seconds > 0 else { throw CoCoRecordingError.message("The completed movie did not contain playable video and audio.") }
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,19 @@ final class CompanionLibraryAuthority {
|
||||
try Task.checkCancellation()
|
||||
try await Task.sleep(nanoseconds: 50_000_000)
|
||||
}
|
||||
guard let catalog = model.catalog else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") }
|
||||
let disks = catalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1)
|
||||
guard model.catalog != nil || !model.personalEntries.isEmpty else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") }
|
||||
let available = model.combinedCatalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1,
|
||||
includingPersonalTitles: request.personalTitlesVersion == 1)
|
||||
let privateDisks = Set(model.personalEntries.filter { entry in
|
||||
entry.files.contains { $0.kind == "disk" && Self.diskMember($0.path) }
|
||||
}.map(\.releaseID))
|
||||
// The emulator accepts additional disk containers that this real-CoCo
|
||||
// handoff cannot offer. Keep those entries in VCC Plus's own library.
|
||||
let disks = SoftwareLibraryCatalog(titles: available.titles.compactMap { title in
|
||||
let releases = title.releases.filter { !$0.isPersonal || privateDisks.contains($0.id) }
|
||||
return releases.isEmpty ? nil : .init(id: title.id, name: title.name,
|
||||
identityStatus: title.identityStatus, releases: releases)
|
||||
}, metadata: available.metadata)
|
||||
func release() throws -> SoftwareLibraryRelease {
|
||||
guard let id = request.releaseID, let value = disks.releases.first(where: { $0.id == id }) else {
|
||||
throw failure("Choose a disk edition from VCC Plus's catalog.")
|
||||
@@ -45,6 +56,7 @@ final class CompanionLibraryAuthority {
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .install:
|
||||
let selected = try release()
|
||||
if selected.isPersonal { return try await installStatus(selected, catalog: disks) }
|
||||
guard model.installingReleaseID == nil || model.installingReleaseID == selected.id else {
|
||||
throw failure("VCC Plus is already installing another title. Let it finish or cancel it there.")
|
||||
}
|
||||
@@ -59,6 +71,7 @@ final class CompanionLibraryAuthority {
|
||||
return .init(snapshot: snapshot(disks), isInstalling: model.installingReleaseID == selected.id)
|
||||
case .removeInstallation:
|
||||
let selected = try release()
|
||||
guard !selected.isPersonal else { throw failure("Manage or remove this private entry in VCC Plus's Personal Library. DriveWire disk copies are separate from its retained files.") }
|
||||
await model.removeInstallation(selected.id)
|
||||
if let message = model.installationErrors[selected.id] { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
@@ -89,6 +102,13 @@ final class CompanionLibraryAuthority {
|
||||
return .init(assetData: data)
|
||||
}
|
||||
guard asset.isManual else { throw failure("Choose a manual or instructions asset.") }
|
||||
if asset.matchStatus == "personal", let local = asset.manualURL, local.isFileURL {
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
try SoftwareLibraryLocalAsset.validate(asset, url: local,
|
||||
maximumBytes: local.pathExtension.lowercased() == "txt" ? 1024 * 1024 : 512 * 1024 * 1024)
|
||||
}.value
|
||||
return .init(assetFileURL: local)
|
||||
}
|
||||
let local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset,
|
||||
directory: model.state.directory.appendingPathComponent("Manuals", isDirectory: true))
|
||||
return .init(assetFileURL: local)
|
||||
@@ -98,12 +118,29 @@ final class CompanionLibraryAuthority {
|
||||
private func failure(_ message: String) -> CompanionLibraryFailure { .init(message: message) }
|
||||
private func snapshot(_ catalog: SoftwareLibraryCatalog) -> CompanionLibrarySnapshot {
|
||||
let titleIDs = Set(catalog.titles.map(\.id)), releaseIDs = Set(catalog.releases.map(\.id))
|
||||
let personal = model.personalEntries.filter { releaseIDs.contains($0.releaseID) }.map {
|
||||
$0.receipt(in: model.personalDirectory($0))
|
||||
}.map { SoftwareLibraryState.Installation(releaseID: $0.releaseID, packageSHA256: $0.packageSHA256,
|
||||
installedAt: $0.installedAt, workingDirectory: $0.workingDirectory) }
|
||||
return .init(catalog: catalog,
|
||||
favorites: model.state.favoriteTitleIDs.intersection(titleIDs),
|
||||
preferredReleaseIDs: model.state.preferredReleaseIDs.filter { titleIDs.contains($0.key) && releaseIDs.contains($0.value) },
|
||||
installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) })
|
||||
installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) && !$0.releaseID.hasPrefix("personal:") } + personal)
|
||||
}
|
||||
private func installedReceipt(_ release: SoftwareLibraryRelease) async throws -> SoftwareLibraryInstallationReceipt {
|
||||
if release.isPersonal {
|
||||
// Reload the store to reject entries hidden since the catalog snapshot.
|
||||
let entries = try await model.personalStore.entries()
|
||||
guard let entry = entries.first(where: {
|
||||
$0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256
|
||||
}) else { throw failure("This private disk entry is no longer available. Open Personal Library in VCC Plus.") }
|
||||
let directory = model.personalDirectory(entry)
|
||||
for location in [directory.deletingLastPathComponent(), directory, directory.appendingPathComponent("Working")] {
|
||||
let values = try location.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard values.isDirectory == true, values.isSymbolicLink != true else { throw failure("The private disk location is not a safe directory. Its retained files were preserved.") }
|
||||
}
|
||||
return entry.receipt(in: directory)
|
||||
}
|
||||
let receipts = try await model.installer.recoverInstallations()
|
||||
guard let receipt = receipts.first(where: { $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 }) else {
|
||||
throw failure("Install this disk edition in VCC Plus first.")
|
||||
@@ -111,6 +148,10 @@ final class CompanionLibraryAuthority {
|
||||
return receipt
|
||||
}
|
||||
private func installStatus(_ release: SoftwareLibraryRelease, catalog: SoftwareLibraryCatalog) async throws -> CompanionLibraryResponse {
|
||||
if release.isPersonal {
|
||||
let receipt = try await installedReceipt(release)
|
||||
return .init(snapshot: snapshot(catalog), receipt: receipt, isInstalling: false)
|
||||
}
|
||||
if let message = model.installationErrors[release.id] { throw failure(message) }
|
||||
let active = model.installingReleaseID == release.id
|
||||
return .init(snapshot: snapshot(catalog), progress: active ? model.installProgress : nil,
|
||||
@@ -127,16 +168,19 @@ final class CompanionLibraryAuthority {
|
||||
nonisolated private static func exportDisk(receipt: SoftwareLibraryInstallationReceipt, member: String, destination: URL) throws -> URL {
|
||||
guard diskMember(member), receipt.relativeFiles.contains(member) else { throw CompanionLibraryFailure(message: "Invalid disk member.") }
|
||||
let root = receipt.workingDirectory.standardizedFileURL
|
||||
var source = root
|
||||
for component in member.split(separator: "/") {
|
||||
source.appendPathComponent(String(component))
|
||||
let values = try source.resourceValues(forKeys: [.isSymbolicLinkKey])
|
||||
guard values.isSymbolicLink != true else { throw CompanionLibraryFailure(message: "The disk path contains a symbolic link.") }
|
||||
guard root.isFileURL else { throw CompanionLibraryFailure(message: "Invalid installation location.") }
|
||||
// Resolve members relative to opened directories so a swapped symlink
|
||||
// cannot redirect an intermediate path outside the working tree.
|
||||
var directory = open(root.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard directory >= 0 else { throw CompanionLibraryFailure(message: "The disk working directory could not be read safely.") }
|
||||
defer { close(directory) }
|
||||
let components = member.split(separator: "/").map(String.init)
|
||||
for component in components.dropLast() {
|
||||
let next = openat(directory, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard next >= 0 else { throw CompanionLibraryFailure(message: "The disk path contains an unavailable directory or symbolic link.") }
|
||||
close(directory); directory = next
|
||||
}
|
||||
guard source.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else {
|
||||
throw CompanionLibraryFailure(message: "The disk path leaves its installation.")
|
||||
}
|
||||
let descriptor = open(source.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
|
||||
let descriptor = openat(directory, components.last!, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard descriptor >= 0 else { throw CompanionLibraryFailure(message: "The installed disk could not be read.") }
|
||||
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
@@ -146,12 +190,21 @@ final class CompanionLibraryAuthority {
|
||||
throw CompanionLibraryFailure(message: "Choose a floppy image within the 16 MiB limit.")
|
||||
}
|
||||
let data = try handle.read(upToCount: 16 * 1024 * 1024 + 1) ?? Data()
|
||||
guard data.count == Int(info.st_size) else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") }
|
||||
var after = stat()
|
||||
guard data.count == Int(info.st_size), fstat(descriptor, &after) == 0,
|
||||
info.st_size == after.st_size, info.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec,
|
||||
info.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,
|
||||
info.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec,
|
||||
info.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") }
|
||||
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
let destinationValues = try destination.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard destinationValues.isDirectory == true, destinationValues.isSymbolicLink != true else {
|
||||
throw CompanionLibraryFailure(message: "The DriveWire disk-copy location is not a safe directory.")
|
||||
}
|
||||
let folder = destination.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
do {
|
||||
let copy = folder.appendingPathComponent(source.lastPathComponent)
|
||||
let copy = folder.appendingPathComponent(components.last!)
|
||||
try data.write(to: copy, options: .atomic)
|
||||
return copy
|
||||
} catch { try? FileManager.default.removeItem(at: folder); throw error }
|
||||
|
||||
@@ -21,6 +21,8 @@ struct CompanionLibraryRequest: Codable, Sendable {
|
||||
var enabled: Bool? = nil
|
||||
// Missing in old clients: do not send project titles to an Archive-only UI.
|
||||
var ownedTitlesVersion: Int? = 1
|
||||
// Older clients cannot identify private entries safely. Missing decodes as nil.
|
||||
var personalTitlesVersion: Int? = 1
|
||||
}
|
||||
|
||||
struct CompanionLibraryResponse: Codable, Sendable {
|
||||
@@ -83,12 +85,13 @@ extension SoftwareLibraryCatalog {
|
||||
/// Filter both releases and their containing title: alternate cartridge/tape
|
||||
/// editions never leak through the edition picker in a disk-only client.
|
||||
var companionDisksOnly: Self {
|
||||
companionDisks(includingOwnedTitles: true)
|
||||
companionDisks(includingOwnedTitles: true, includingPersonalTitles: true)
|
||||
}
|
||||
func companionDisks(includingOwnedTitles: Bool) -> Self {
|
||||
func companionDisks(includingOwnedTitles: Bool, includingPersonalTitles: Bool = false) -> Self {
|
||||
Self(titles: titles.compactMap { title in
|
||||
let releases = title.releases.filter {
|
||||
$0.mediaType == "disk" && (includingOwnedTitles || $0.metadata["owned_game"] == .null)
|
||||
(includingPersonalTitles || (!title.id.hasPrefix("personal:") && !$0.isPersonal)) &&
|
||||
$0.mediaType == "disk" && (includingOwnedTitles || $0.metadata["owned_game"] == .null)
|
||||
}
|
||||
return releases.isEmpty ? nil : SoftwareLibraryTitle(id: title.id, name: title.name,
|
||||
identityStatus: title.identityStatus, releases: releases)
|
||||
|
||||
@@ -62,7 +62,7 @@ struct DiskControlsView: View {
|
||||
SecondaryCard {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Label("Choose a disk ROM to enable the FD-502 controller", systemImage: "info.circle")
|
||||
SecondaryAction(title: "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM).disabled(machine.diskBusy)
|
||||
SecondaryAction(title: "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM)
|
||||
}
|
||||
}
|
||||
} else if !machine.diskConnected {
|
||||
@@ -86,7 +86,6 @@ struct DiskControlsView: View {
|
||||
}
|
||||
Spacer()
|
||||
SecondaryAction(title: machine.diskEnabled ? "Change Disk ROM…" : "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM)
|
||||
.disabled(machine.diskBusy)
|
||||
}
|
||||
if machine.diskEnabled {
|
||||
HStack {
|
||||
@@ -99,7 +98,7 @@ struct DiskControlsView: View {
|
||||
}
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
SecondaryAction(title: "Disable Controller…", systemImage: "minus.circle", action: machine.disableDisks)
|
||||
.disabled(machine.dirtyDisks || machine.diskBusy)
|
||||
.disabled(machine.dirtyDisks)
|
||||
.accessibilityLabel("Disable floppy controller")
|
||||
Text("Disabling ejects all four disks and cold-restarts the CoCo. Save or discard pending changes first.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
@@ -194,7 +193,10 @@ private struct DiskDriveRow: View {
|
||||
.sheet(item: $copySource) { source in
|
||||
VCCDriveWireTransferView(machine: machine, drive: index, sourceName: source.name, sourceEpoch: source.epoch)
|
||||
}
|
||||
.disabled(machine.diskBusy)
|
||||
// Guest sector transfers change busy many times per second. Keep browsing,
|
||||
// menus and controls stable; commands recheck controller idleness on its
|
||||
// serialized worker before changing media. Host-save/editor locks above
|
||||
// and each disk's unsaved/protection guards still disable unsafe actions.
|
||||
}
|
||||
private var newDiskMenu: some View {
|
||||
Menu {
|
||||
|
||||
@@ -18,9 +18,22 @@ struct InputDiagnosticObservation {
|
||||
@MainActor
|
||||
final class InputHub: ObservableObject {
|
||||
@Published var settings: InputSettings { didSet {
|
||||
guard settings != oldValue else { return }
|
||||
release(); epoch &+= 1
|
||||
do { try store.save(settings); error = nil } catch { self.error = "Could not save input settings: \(error.localizedDescription)" }
|
||||
guard !normalizingSettings else { return }
|
||||
let previousPolicy = automaticRightController
|
||||
if !applyingAutomaticSettings, settings.right != oldValue.right { automaticRightController = false }
|
||||
// Normalize this one user edit before releasing/routing/persisting it.
|
||||
// @Published can reenter this observer during normalization; only the
|
||||
// outer edit releases input, advances the epoch and persists settings.
|
||||
let assigned = settings.assigningSoleController(devices.map(\.id), automaticRight: automaticRightController)
|
||||
if settings != assigned {
|
||||
normalizingSettings = true
|
||||
settings = assigned
|
||||
normalizingSettings = false
|
||||
}
|
||||
if settings.right.source == .controller, !settings.right.device.isEmpty { automaticRightController = false }
|
||||
guard settings != oldValue || previousPolicy != automaticRightController else { return }
|
||||
if settings != oldValue { release(); epoch &+= 1 }
|
||||
saveSettings()
|
||||
} }
|
||||
@Published private(set) var devices: [ControllerReading] = []
|
||||
@Published private(set) var preview = [JoystickSample(), JoystickSample()]
|
||||
@@ -29,7 +42,11 @@ final class InputHub: ObservableObject {
|
||||
var acceptsInput: () -> Bool = { false }
|
||||
private let store: InputSettingsStore
|
||||
private let controller: VCCMachineController
|
||||
private let hardware: ControllerDevices
|
||||
private let hardware: ControllerDevices?
|
||||
private let controllerReadings: (() -> [ControllerReading])?
|
||||
private var automaticRightController = false
|
||||
private var applyingAutomaticSettings = false
|
||||
private var normalizingSettings = false
|
||||
private var timer: Timer?
|
||||
private var routing = InputRouting()
|
||||
private var last: [JoystickSample] = []
|
||||
@@ -40,20 +57,49 @@ final class InputHub: ObservableObject {
|
||||
private var lastDisplayAcceptsInput: Bool?
|
||||
private var submitted: [JoystickSample]?
|
||||
private var submittedInterfaces: [JoystickInterface]?
|
||||
init(controller: VCCMachineController, store: InputSettingsStore = .standard) {
|
||||
self.controller = controller; self.store = store; hardware = ControllerDevices()
|
||||
do { settings = try store.load() } catch {
|
||||
init(controller: VCCMachineController, store: InputSettingsStore = .standard,
|
||||
controllerReadings: (() -> [ControllerReading])? = nil, automaticallyPoll: Bool = true) {
|
||||
self.controller = controller; self.store = store
|
||||
self.controllerReadings = controllerReadings
|
||||
hardware = controllerReadings == nil ? ControllerDevices() : nil
|
||||
do {
|
||||
let saved = try store.loadState()
|
||||
settings = saved.settings; automaticRightController = saved.automaticRightController
|
||||
} catch {
|
||||
settings = InputSettings(); self.error = "Could not read input settings: \(error.localizedDescription)"
|
||||
}
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.poll() }
|
||||
}
|
||||
if automaticallyPoll {
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.poll() }
|
||||
}
|
||||
#if VCC_UI_TESTING
|
||||
// Keep the authored preview moving even during native menu tracking.
|
||||
if let timer { RunLoop.main.add(timer, forMode: .common) }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
deinit { timer?.invalidate() }
|
||||
private func saveSettings() {
|
||||
do { try store.save(settings, automaticRightController: automaticRightController); error = nil }
|
||||
catch { self.error = "Could not save input settings: \(error.localizedDescription)" }
|
||||
}
|
||||
/// Built-in reset is explicit; personal profile inputs never inherit the
|
||||
/// fresh-install controller-discovery policy from this Mac's settings store.
|
||||
func applyProfileSettings(_ value: InputSettings) { applySettings(value, automaticRight: false) }
|
||||
/// Library hints can fill unused ports without turning an unchanged fresh
|
||||
/// Right fallback into an explicit user choice.
|
||||
func applyLibrarySettings(_ value: InputSettings) {
|
||||
applySettings(value, automaticRight: automaticRightController && value.right == settings.right)
|
||||
}
|
||||
func restoreDefaultSettings() { applySettings(.freshDefaults, automaticRight: true) }
|
||||
private func applySettings(_ value: InputSettings, automaticRight: Bool) {
|
||||
let previous = settings, previousPolicy = automaticRightController
|
||||
automaticRightController = automaticRight
|
||||
applyingAutomaticSettings = true
|
||||
settings = value
|
||||
applyingAutomaticSettings = false
|
||||
if settings == previous, automaticRightController != previousPolicy { saveSettings() }
|
||||
}
|
||||
func swap() { var next = settings; next.right = settings.left; next.left = settings.right; settings = next }
|
||||
func key(_ code: UInt16, down: Bool) -> Bool {
|
||||
routing.key(code, down: down, settings: settings)
|
||||
@@ -73,17 +119,27 @@ final class InputHub: ObservableObject {
|
||||
lastPollUptime = nil; lastApplicationActive = nil; lastDisplayAcceptsInput = nil
|
||||
submit([JoystickSample(), JoystickSample()])
|
||||
}
|
||||
private func poll() {
|
||||
func poll() {
|
||||
let readings: [ControllerReading]
|
||||
if let controllerReadings { readings = controllerReadings() }
|
||||
else {
|
||||
#if VCC_UI_TESTING
|
||||
// Exercise the real preview/selection views with changing input even
|
||||
// when no physical controller is attached to the test Mac.
|
||||
let phase = ProcessInfo.processInfo.systemUptime
|
||||
let readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller",
|
||||
readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller",
|
||||
x: sin(phase), y: cos(phase), rx: sin(phase * 2), ry: cos(phase * 2))]
|
||||
#else
|
||||
let readings = hardware.read()
|
||||
readings = hardware?.read() ?? []
|
||||
#endif
|
||||
}
|
||||
if devices != readings { devices = readings }
|
||||
let assigned = settings.assigningSoleController(readings.map(\.id), automaticRight: automaticRightController)
|
||||
if assigned != settings {
|
||||
applyingAutomaticSettings = true
|
||||
settings = assigned
|
||||
applyingAutomaticSettings = false
|
||||
}
|
||||
let displayAcceptsInput = acceptsInput(), applicationActive = NSApp.isActive
|
||||
let active = displayAcceptsInput && applicationActive
|
||||
lastPollUptime = ProcessInfo.processInfo.systemUptime
|
||||
|
||||
@@ -35,6 +35,24 @@ struct InputSettings: Codable, Equatable {
|
||||
get { port == 0 ? right : left }
|
||||
set { if port == 0 { right = newValue } else { left = newValue } }
|
||||
}
|
||||
/// An unassigned Controller source can adopt an unambiguous connection.
|
||||
/// A remembered device remains authoritative even while disconnected.
|
||||
static var freshDefaults: Self {
|
||||
var value = Self(); value.right.source = .mouse
|
||||
return value
|
||||
}
|
||||
func assigningSoleController(_ deviceIDs: [String], automaticRight: Bool = false) -> Self {
|
||||
guard deviceIDs.count == 1, let device = deviceIDs.first,
|
||||
!device.isEmpty, device.count < 1024 else { return self }
|
||||
var result = self
|
||||
if automaticRight, result.right.source == .mouse, result.right.device.isEmpty {
|
||||
result.right.source = .controller
|
||||
}
|
||||
for port in 0..<2 where result[port].source == .controller && result[port].device.isEmpty {
|
||||
result[port].device = device
|
||||
}
|
||||
return result
|
||||
}
|
||||
func validated() throws -> Self {
|
||||
for p in [right, left] {
|
||||
guard p.deadZone.isFinite, (0...0.5).contains(p.deadZone),
|
||||
@@ -46,16 +64,48 @@ struct InputSettings: Codable, Equatable {
|
||||
}
|
||||
}
|
||||
struct InputSettingsStore {
|
||||
struct State {
|
||||
let settings: InputSettings
|
||||
let automaticRightController: Bool
|
||||
}
|
||||
/// Keep the existing flat settings document/profile contract. This optional
|
||||
/// store-only marker distinguishes a fresh fallback from a person's choice.
|
||||
private struct Record: Codable {
|
||||
let settings: InputSettings
|
||||
let automaticRightController: Bool
|
||||
private enum Keys: String, CodingKey { case automaticRightController }
|
||||
init(settings: InputSettings, automaticRightController: Bool) {
|
||||
self.settings = settings; self.automaticRightController = automaticRightController
|
||||
}
|
||||
init(from decoder: Decoder) throws {
|
||||
settings = try InputSettings(from: decoder)
|
||||
automaticRightController = try decoder.container(keyedBy: Keys.self)
|
||||
.decodeIfPresent(Bool.self, forKey: .automaticRightController) ?? false
|
||||
}
|
||||
func encode(to encoder: Encoder) throws {
|
||||
try settings.encode(to: encoder)
|
||||
if automaticRightController {
|
||||
var fields = encoder.container(keyedBy: Keys.self)
|
||||
try fields.encode(true, forKey: .automaticRightController)
|
||||
}
|
||||
}
|
||||
}
|
||||
let url: URL
|
||||
static let standard = InputSettingsStore(url: AppIdentity.supportDirectory.appendingPathComponent("InputSettings.json"))
|
||||
func load() throws -> InputSettings {
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return InputSettings() }
|
||||
return try JSONDecoder().decode(InputSettings.self, from: Data(contentsOf: url)).validated()
|
||||
try loadState().settings
|
||||
}
|
||||
func save(_ value: InputSettings) throws {
|
||||
func loadState() throws -> State {
|
||||
guard FileManager.default.fileExists(atPath: url.path) else {
|
||||
return State(settings: .freshDefaults, automaticRightController: true)
|
||||
}
|
||||
let record = try JSONDecoder().decode(Record.self, from: Data(contentsOf: url))
|
||||
return State(settings: try record.settings.validated(), automaticRightController: record.automaticRightController)
|
||||
}
|
||||
func save(_ value: InputSettings, automaticRightController: Bool = false) throws {
|
||||
_ = try value.validated()
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(value).write(to: url, options: .atomic)
|
||||
try JSONEncoder().encode(Record(settings: value, automaticRightController: automaticRightController)).write(to: url, options: .atomic)
|
||||
}
|
||||
}
|
||||
struct JoystickSample: Equatable {
|
||||
|
||||
@@ -18,9 +18,40 @@ final class InterfaceValidation {
|
||||
private let controller = VCCMachineController()
|
||||
private var measurement: Task<Void, Never>?
|
||||
private let suite: String
|
||||
private let retainsRelaunchFixture: Bool
|
||||
init() throws {
|
||||
#if VCC_UI_TESTING
|
||||
if let path = ProcessInfo.processInfo.environment["VCC_CONTINUITY_TEST_ROOT"] {
|
||||
let candidate = URL(fileURLWithPath: path).standardizedFileURL
|
||||
let temporary = FileManager.default.temporaryDirectory.standardizedFileURL.resolvingSymlinksInPath()
|
||||
// XCTest's runner is sandboxed and owns a different temporary root
|
||||
// from the tested app. Permit precisely that runner's tmp directory,
|
||||
// never its Documents directory or an arbitrary supplied parent.
|
||||
let userHome = URL(fileURLWithPath: NSHomeDirectoryForUser(NSUserName()) ?? NSHomeDirectory())
|
||||
let runnerTemporary = userHome.appendingPathComponent("Library/Containers/com.brianholman.vccplus.mac.uitests.xctrunner/Data/tmp")
|
||||
.standardizedFileURL.resolvingSymlinksInPath()
|
||||
let prefix = "VCCContinuityRelaunch-"
|
||||
let token = String(candidate.lastPathComponent.dropFirst(prefix.count))
|
||||
let values = try candidate.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard candidate.lastPathComponent.hasPrefix(prefix), UUID(uuidString: token) != nil,
|
||||
[temporary.path, runnerTemporary.path].contains(candidate.deletingLastPathComponent().resolvingSymlinksInPath().path),
|
||||
values.isDirectory == true, values.isSymbolicLink != true,
|
||||
try String(contentsOf: candidate.appendingPathComponent("fixture-owner"), encoding: .utf8) == token else {
|
||||
throw CocoaError(.fileReadNoPermission)
|
||||
}
|
||||
directory = candidate
|
||||
suite = prefix + token
|
||||
retainsRelaunchFixture = true
|
||||
} else {
|
||||
directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString)
|
||||
suite = "VCCInterfaceUI-" + UUID().uuidString
|
||||
retainsRelaunchFixture = false
|
||||
}
|
||||
#else
|
||||
directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString)
|
||||
suite = "VCCInterfaceUI-" + UUID().uuidString
|
||||
retainsRelaunchFixture = false
|
||||
#endif
|
||||
defaults = UserDefaults(suiteName: suite)!
|
||||
// Ordinary interaction tests represent a returning user; the dedicated
|
||||
// first-use test exercises a fresh guide history through real commands.
|
||||
@@ -51,7 +82,12 @@ final class InterfaceValidation {
|
||||
try Data(repeating: 0,count:161280).write(to:kit.appendingPathComponent(name))
|
||||
}
|
||||
if let resource = Bundle.main.url(forResource: "Blank OS9 Header", withExtension: "bin") {
|
||||
try FileManager.default.copyItem(at: resource, to: kit.appendingPathComponent("Blank OS9 Header.bin"))
|
||||
let destination = kit.appendingPathComponent("Blank OS9 Header.bin")
|
||||
if retainsRelaunchFixture && FileManager.default.fileExists(atPath: destination.path) {
|
||||
guard try Data(contentsOf: destination) == Data(contentsOf: resource) else { throw CocoaError(.fileReadCorruptFile) }
|
||||
} else {
|
||||
try FileManager.default.copyItem(at: resource, to: destination)
|
||||
}
|
||||
}
|
||||
try Data([0x55,0x55,0x3c]).write(to:kit.appendingPathComponent("Hello World.cas"))
|
||||
}
|
||||
@@ -398,6 +434,9 @@ final class InterfaceValidation {
|
||||
}
|
||||
func cleanUp() {
|
||||
measurement?.cancel()
|
||||
// Only the UI runner that owns the explicit one-test fixture removes it.
|
||||
// A second app process must be able to read the first process's state.
|
||||
guard !retainsRelaunchFixture else { return }
|
||||
defaults.removePersistentDomain(forName: suite)
|
||||
try? FileManager.default.removeItem(at: directory)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// Browsing/reading choices are personal state, not part of either shipped catalog.
|
||||
struct LibraryBrowseState: Codable, Equatable, Sendable {
|
||||
var scope = ""
|
||||
var query = ""
|
||||
var filters: [String: String] = [:]
|
||||
var selectedID: String?
|
||||
var selectedEditionID: String?
|
||||
var topVisibleID: String?
|
||||
var offset: Double = 0
|
||||
var pageOffset = 0
|
||||
}
|
||||
|
||||
struct LibraryReadingPosition: Codable, Equatable, Sendable {
|
||||
var documentID: String
|
||||
var relativePath: String? = nil
|
||||
var page = 1
|
||||
var anchor: String? = nil
|
||||
var offset: Double = 0
|
||||
var horizontalOffset: Double = 0
|
||||
var zoom: Double? = nil
|
||||
var autoScales: Bool? = nil
|
||||
var readingOrder: Int? = nil
|
||||
}
|
||||
|
||||
struct ManualBookmark: Codable, Equatable, Identifiable, Sendable {
|
||||
let id: UUID
|
||||
let bookID: String
|
||||
var bookTitle: String
|
||||
var sectionTitle: String
|
||||
var position: LibraryReadingPosition
|
||||
var label: String?
|
||||
let createdAt: Date
|
||||
var updatedAt: Date
|
||||
var locationChanged: Bool? = nil
|
||||
var displayName: String { label.flatMap { $0.isEmpty ? nil : $0 } ?? sectionTitle }
|
||||
var locationKey: String { bookID + "/" + (position.relativePath ?? "") + "#" + (position.anchor ?? "offset-\(Int(position.offset * 10_000))") }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class LibraryContinuityStore: ObservableObject {
|
||||
private(set) static var shared: LibraryContinuityStore = {
|
||||
#if VCC_UI_TESTING
|
||||
return LibraryContinuityStore(directory: FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityUITest-" + UUID().uuidString))
|
||||
#else
|
||||
if CommandLine.arguments.contains("--interface-validation") || CommandLine.arguments.contains("--validate-startup") {
|
||||
return LibraryContinuityStore(directory: FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityValidation-" + UUID().uuidString))
|
||||
}
|
||||
return LibraryContinuityStore(directory: AppIdentity.supportDirectory)
|
||||
#endif
|
||||
}()
|
||||
/// Called by the app delegate after selecting its normal or isolated support root.
|
||||
static func configureShared(directory: URL) {
|
||||
guard shared.fileURL.deletingLastPathComponent() != directory else { return }
|
||||
shared = LibraryContinuityStore(directory: directory)
|
||||
}
|
||||
private struct Document: Codable, Sendable {
|
||||
var version = 1
|
||||
var browse: [String: LibraryBrowseState] = [:]
|
||||
var reading: [String: LibraryReadingPosition] = [:]
|
||||
var bookmarks: [ManualBookmark] = []
|
||||
}
|
||||
@Published private(set) var bookmarks: [ManualBookmark] = []
|
||||
@Published private(set) var saveError: String?
|
||||
private var document = Document()
|
||||
private var maySave = true
|
||||
private var revision = 0
|
||||
private var pendingSave: Task<Void, Never>?
|
||||
private let queue = DispatchQueue(label: "com.brianholman.vccplus.library-continuity", qos: .utility)
|
||||
let fileURL: URL
|
||||
|
||||
init(directory: URL) {
|
||||
fileURL = directory.appendingPathComponent("LibraryContinuity.json")
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else { return }
|
||||
do {
|
||||
let handle = try FileHandle(forReadingFrom: fileURL)
|
||||
defer { try? handle.close() }
|
||||
let bytes = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data()
|
||||
guard bytes.count <= 8 * 1024 * 1024 else { throw Failure.invalid }
|
||||
let decoded = try JSONDecoder().decode(Document.self, from: bytes)
|
||||
guard decoded.version == 1, decoded.browse.count <= 256,
|
||||
decoded.reading.count <= 20_000, decoded.bookmarks.count <= 5_000,
|
||||
decoded.browse.allSatisfy({ Self.validID($0.key) && Self.valid($0.value) }),
|
||||
decoded.reading.allSatisfy({ Self.validID($0.key) && Self.valid($0.value) }),
|
||||
decoded.bookmarks.allSatisfy({ Self.valid($0.position) && Self.validID($0.bookID) }),
|
||||
Set(decoded.bookmarks.map(\.id)).count == decoded.bookmarks.count else { throw Failure.invalid }
|
||||
document = decoded
|
||||
bookmarks = decoded.bookmarks
|
||||
} catch {
|
||||
maySave = false
|
||||
saveError = "Saved library positions and bookmarks could not be read. The original file has been preserved at \(fileURL.path). \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
func browse(for key: String) -> LibraryBrowseState? { document.browse[key] }
|
||||
func reading(for key: String) -> LibraryReadingPosition? { document.reading[key] }
|
||||
func setBrowse(_ value: LibraryBrowseState, for key: String) {
|
||||
guard maySave, Self.validID(key), Self.valid(value), document.browse[key] != value else { return }
|
||||
document.browse[key] = value; scheduleSave()
|
||||
}
|
||||
func setReading(_ value: LibraryReadingPosition, for key: String) {
|
||||
guard maySave, Self.validID(key), Self.valid(value), document.reading[key] != value else { return }
|
||||
document.reading[key] = value; scheduleSave()
|
||||
}
|
||||
@discardableResult
|
||||
func addBookmark(bookID: String, bookTitle: String, sectionTitle: String, position: LibraryReadingPosition) -> ManualBookmark? {
|
||||
guard maySave, Self.validID(bookID), Self.valid(position), bookmarks.count < 5_000 else { return nil }
|
||||
let candidate = ManualBookmark(id: UUID(), bookID: bookID, bookTitle: String(bookTitle.prefix(512)),
|
||||
sectionTitle: String(sectionTitle.prefix(1024)), position: position, createdAt: Date(), updatedAt: Date())
|
||||
if let existing = bookmarks.first(where: { $0.locationKey == candidate.locationKey }) { return existing }
|
||||
bookmarks.append(candidate); document.bookmarks = bookmarks; scheduleSave(); return candidate
|
||||
}
|
||||
func renameBookmark(_ id: UUID, label: String) {
|
||||
guard maySave, let index = bookmarks.firstIndex(where: { $0.id == id }) else { return }
|
||||
bookmarks[index].label = String(label.trimmingCharacters(in: .whitespacesAndNewlines).prefix(512))
|
||||
bookmarks[index].updatedAt = Date(); document.bookmarks = bookmarks; scheduleSave()
|
||||
}
|
||||
func removeBookmark(_ id: UUID) {
|
||||
guard maySave else { return }
|
||||
bookmarks.removeAll { $0.id == id }; document.bookmarks = bookmarks; scheduleSave()
|
||||
}
|
||||
func markBookmarkLocationChanged(_ id: UUID, changed: Bool) {
|
||||
guard maySave, let index = bookmarks.firstIndex(where: { $0.id == id }), bookmarks[index].locationChanged != changed else { return }
|
||||
bookmarks[index].locationChanged = changed
|
||||
document.bookmarks = bookmarks; scheduleSave()
|
||||
}
|
||||
func flush() async {
|
||||
pendingSave?.cancel(); pendingSave = nil
|
||||
guard maySave else { return }
|
||||
await withCheckedContinuation { continuation in write { continuation.resume() } }
|
||||
}
|
||||
/// Queue the latest checkpoint without a main-thread or emulator wait.
|
||||
func checkpoint() {
|
||||
pendingSave?.cancel(); pendingSave = nil
|
||||
if maySave { write() }
|
||||
}
|
||||
private func scheduleSave() {
|
||||
revision += 1
|
||||
pendingSave?.cancel()
|
||||
pendingSave = Task { [weak self] in
|
||||
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
|
||||
guard let self, !Task.isCancelled else { return }
|
||||
self.write()
|
||||
}
|
||||
}
|
||||
private func write(completion: (@Sendable () -> Void)? = nil) {
|
||||
let value = document, destination = fileURL, generation = revision
|
||||
queue.async { [weak self] in
|
||||
let message: String?
|
||||
do {
|
||||
let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]
|
||||
let bytes = try encoder.encode(value)
|
||||
guard bytes.count <= 8 * 1024 * 1024 else { throw Failure.invalid }
|
||||
try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try bytes.write(to: destination, options: .atomic)
|
||||
message = nil
|
||||
} catch { message = "Library positions and bookmarks could not be saved: \(error.localizedDescription)" }
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.revision == generation else { return }
|
||||
self.saveError = message
|
||||
}
|
||||
completion?()
|
||||
}
|
||||
}
|
||||
private static func validID(_ value: String) -> Bool { !value.isEmpty && value.utf8.count <= 4096 && !value.contains("\0") }
|
||||
private static func valid(_ state: LibraryBrowseState) -> Bool {
|
||||
state.scope.utf8.count <= 4096 && state.query.count <= 256 && state.filters.count <= 32
|
||||
&& state.filters.allSatisfy { $0.key.count <= 128 && $0.value.count <= 4096 }
|
||||
&& state.offset.isFinite && state.offset >= 0 && (0...250_000).contains(state.pageOffset)
|
||||
}
|
||||
private static func valid(_ position: LibraryReadingPosition) -> Bool {
|
||||
validID(position.documentID) && position.page > 0 && position.page <= 1_000_000
|
||||
&& position.offset.isFinite && (0...1).contains(position.offset)
|
||||
&& position.horizontalOffset.isFinite && (0...1).contains(position.horizontalOffset)
|
||||
&& position.zoom.map { $0.isFinite && $0 > 0 && $0 <= 100 } != false
|
||||
&& position.relativePath.map { !$0.hasPrefix("/") && !$0.split(separator: "/").contains("..") && !$0.contains("\0") } != false
|
||||
&& position.anchor.map { $0.count <= 2048 && !$0.contains("\0") } != false
|
||||
}
|
||||
private enum Failure: LocalizedError {
|
||||
case invalid
|
||||
var errorDescription: String? { "The continuity file is damaged or uses an unsupported version." }
|
||||
}
|
||||
}
|
||||
|
||||
struct ArchiveLibraryOpenRequest: Equatable, Sendable {
|
||||
let id = UUID()
|
||||
let documentID: String
|
||||
let location: Int?
|
||||
let expectedSHA256: String?
|
||||
}
|
||||
|
||||
/// A request is retained until the Archive window appears, so opening its window
|
||||
/// and requesting an exact document do not depend on notification timing.
|
||||
@MainActor
|
||||
final class ArchiveLibraryNavigation: ObservableObject {
|
||||
static let shared = ArchiveLibraryNavigation()
|
||||
@Published private(set) var request: ArchiveLibraryOpenRequest?
|
||||
func open(documentID: String, location: Int? = nil, expectedSHA256: String? = nil) {
|
||||
request = ArchiveLibraryOpenRequest(documentID: documentID, location: location, expectedSHA256: expectedSHA256)
|
||||
}
|
||||
func consumed(_ id: UUID) { if request?.id == id { request = nil } }
|
||||
}
|
||||
@@ -607,7 +607,7 @@ final class MCPCMOC: ObservableObject {
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
do {
|
||||
let server = try MCPTransport(handler: handler)
|
||||
let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 11, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true,
|
||||
let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 12, "playtestVideo": approvedPlaytests, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true,
|
||||
"socket": server.unixPath, "port": Int(server.port), "version": 1])
|
||||
return (server, try MCPGrantFile(create: destination, data: bytes))
|
||||
} catch { try? FileManager.default.removeItem(at: dir); throw error }
|
||||
@@ -698,13 +698,15 @@ final class MCPCMOC: ObservableObject {
|
||||
if let latestRefreshID, let record = refreshRecords[latestRefreshID] { fields["refresh"] = projectRefreshFields(record) }
|
||||
result = fields
|
||||
case "get_capabilities" where args.isEmpty:
|
||||
result = ["tools": Self.tools + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "restart_playtest", "stop_playtest"] : []), "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS",
|
||||
result = ["tools": Self.tools + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "start_playtest_video", "stop_playtest_video", "read_playtest_video", "restart_playtest", "stop_playtest"] : []), "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "video_capture": playtestsApproved, "video_capture_maximum_fields": 3600, "video_capture_maximum_clips": 4, "video_capture_maximum_bytes": 64 * 1024 * 1024, "video_capture_retained_maximum_bytes": 256 * 1024 * 1024, "video_capture_chunk_maximum_bytes": 65536, "video_capture_guest_only": true, "video_capture_optional_audio": true, "video_capture_ui_cues": false, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS",
|
||||
"mutation_request_limit": MCPPlaytest.mutationRequestLimit, "stop_retention_exempt": true,
|
||||
"playtest_processors": playtestsApproved ? ["MC6809", "HD6309"] : [],
|
||||
"playtest_default_processor": "MC6809", "playtest_processor_selection": playtestsApproved,
|
||||
"app_version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown",
|
||||
"app_build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown", "project_id": id, "revision": revision,
|
||||
"entry": scope.entry, "target": "CoCo Disk BASIC", "build_recipe": scope.customMake ? "approved_make" : scope.helloDisk ? "installed_hello_disk" : "bundled_cmoc", "files": scope.paths, "headers": Self.headers, "session_id": owner.uuidString, "version": 1]
|
||||
"entry": scope.entry, "target": "CoCo Disk BASIC", "build_recipe": scope.customMake ? "approved_make" : scope.helloDisk ? "installed_hello_disk" : "bundled_cmoc", "files": scope.paths, "headers": Self.headers, "session_id": owner.uuidString, "version": 1,
|
||||
"banked_debug_manifest_versions": [1, 2], "verified_code_overlays": true,
|
||||
"overlay_residency_evidence": "complete_mapped_code_bytes"]
|
||||
if scope.customMake {
|
||||
var facts = result
|
||||
facts["recipe_id"] = approvedRecipeID
|
||||
@@ -832,7 +834,7 @@ final class MCPCMOC: ObservableObject {
|
||||
case "start_playtest":
|
||||
guard playtestsApproved else { throw problem("access_denied") }
|
||||
result = try await startPlaytest(args, model: model, owner: owner)
|
||||
case "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "restart_playtest", "stop_playtest", "exchange_playtest_media":
|
||||
case "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "start_playtest_video", "stop_playtest_video", "read_playtest_video", "restart_playtest", "stop_playtest", "exchange_playtest_media":
|
||||
if tool == "stop_playtest", playtestsApproved, args.count == 2,
|
||||
let runID = args["run_id"] as? String, let request = args["request_id"] as? String,
|
||||
(1...128).contains(request.utf8.count),
|
||||
@@ -848,7 +850,7 @@ final class MCPCMOC: ObservableObject {
|
||||
owned.artifactID == artifact.value.id.uuidString, !playtestBusy else { throw problem("stale_run") }
|
||||
playtestBusy = true
|
||||
defer { playtestBusy = false }
|
||||
if !["capture_playtest", "capture_playtest_graphics", "get_playtest_input"].contains(tool) { ownedInspection = nil }
|
||||
if !["capture_playtest", "capture_playtest_graphics", "get_playtest_input", "start_playtest_video", "stop_playtest_video", "read_playtest_video"].contains(tool) { ownedInspection = nil }
|
||||
var request = args
|
||||
if tool == "playtest_debug" {
|
||||
guard Set(args.keys).isSubset(of: ["run_id", "request_id", "action", "function", "stop_kind"]), let action = args["action"] as? String else { throw problem("invalid_arguments") }
|
||||
@@ -1070,8 +1072,12 @@ final class MCPCMOC: ObservableObject {
|
||||
modules = layout.modules.compactMap { module in
|
||||
let code = module.codeGuards
|
||||
guard !code.isEmpty else { return nil }
|
||||
return ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] },
|
||||
var definition: [String: Any] = ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] },
|
||||
"guards": code.map { ["address": Int($0.address), "bytes_base64": Data($0.bytes).base64EncodedString()] }]
|
||||
if let overlay = module.overlay {
|
||||
definition["overlay_group"] = overlay.group; definition["overlay_owner"] = overlay.owner
|
||||
}
|
||||
return definition
|
||||
}
|
||||
} else {
|
||||
flatGuards = map.flatCodeGuards.map(\.workerFields)
|
||||
@@ -1215,15 +1221,16 @@ final class MCPCMOC: ObservableObject {
|
||||
guard ownsPlaytest(owned, artifact: artifact, owner: owner),
|
||||
capture["processor"] as? String == owned.processor.rawValue,
|
||||
capture["paused"] as? Bool == true, capture["attached"] as? Bool == true,
|
||||
let clock = capture["field_clock"] as? Int else { throw problem("verified_pause_required") }
|
||||
let clock = capture["field_clock"] as? Int,
|
||||
let captureFingerprint = Self.ownedCaptureFingerprint(capture) else { throw problem("verified_pause_required") }
|
||||
if tool == "get_call_context" {
|
||||
guard callContextApproved, Set(arguments.keys) == ["run_id", "snapshot_id"],
|
||||
let previous = ownedInspection, previous.run == owned.runID,
|
||||
arguments["snapshot_id"] as? String == previous.id,
|
||||
previous.clock == clock, previous.fingerprint == Self.ownedCaptureFingerprint(capture),
|
||||
previous.clock == clock, previous.fingerprint == captureFingerprint,
|
||||
var context = previous.callContext else { throw problem("stale_or_unavailable_call_context") }
|
||||
for key in ["run_id", "snapshot_id", "artifact_id", "project_id", "revision", "processor", "requested_processor",
|
||||
"execution_mode", "md_register", "field_clock", "boot", "stop_kind", "mapping_fingerprint", "program_revision"] {
|
||||
"execution_mode", "md_register", "field_clock", "boot", "stop_kind", "mapping_fingerprint", "program_revision", "residency_fingerprint", "overlay_residency"] {
|
||||
context[key] = previous.fields[key] ?? NSNull()
|
||||
}
|
||||
return context
|
||||
@@ -1231,6 +1238,7 @@ final class MCPCMOC: ObservableObject {
|
||||
if tool == "read_debug_memory" {
|
||||
guard arguments.count == 4, let previous = ownedInspection, previous.run == owned.runID,
|
||||
previous.clock == clock, arguments["snapshot_id"] as? String == previous.id,
|
||||
previous.fingerprint == captureFingerprint,
|
||||
let address = int(arguments["address"]), let count = int(arguments["count"]),
|
||||
(1...256).contains(count), address >= 0, address <= 0xff00 - count,
|
||||
previous.ranges.contains(where: { $0.contains(address) && address + count <= $0.upperBound }) else { throw problem("stale_or_unavailable_memory") }
|
||||
@@ -1249,6 +1257,10 @@ final class MCPCMOC: ObservableObject {
|
||||
let (verifiedMap, verifiedMetadata, variableError) = try await debugMetadata(artifact)
|
||||
guard ownsPlaytest(owned, artifact: artifact, owner: owner) else { throw problem("stale_run") }
|
||||
let map = verifiedMap.projected(physicalPages: pages, memory: memory, available: available)
|
||||
if verifiedMap.bankedLayout?.overlayGroups.isEmpty == false {
|
||||
guard let residency = capture["residency_fingerprint"] as? String, UInt64(residency) != nil,
|
||||
residency != "0" else { throw problem("overlay_residency_unavailable") }
|
||||
}
|
||||
let metadata = verifiedMetadata?.projected(physicalPages: pages, memory: memory, available: available)
|
||||
let shared = Set(scope?.paths ?? [])
|
||||
let point = map.instruction(at: address).flatMap { shared.contains($0.sourcePath) ? $0 : nil }
|
||||
@@ -1328,6 +1340,16 @@ final class MCPCMOC: ObservableObject {
|
||||
"globals": globals.items, "globals_total": globals.total, "globals_truncated": globals.truncated,
|
||||
"mapping_fingerprint": capture["mapping_fingerprint"] as Any? ?? NSNull(),
|
||||
"program_revision": capture["program_revision"] as Any? ?? NSNull(),
|
||||
"residency_fingerprint": capture["residency_fingerprint"] as Any? ?? "0",
|
||||
"overlay_residency": map.bankedLayout?.overlayGroups.map { group in
|
||||
let activeOwners = Set(map.bankedLayout!.modules.compactMap { module -> String? in
|
||||
guard map.activeModuleIDs?.contains(module.id) == true, let overlay = module.overlay,
|
||||
overlay.group == group.id else { return nil }
|
||||
return overlay.owner
|
||||
})
|
||||
return ["group": group.id, "owner": activeOwners.count == 1 ? activeOwners.first! as Any : NSNull(),
|
||||
"status": activeOwners.count == 1 ? "verified" : "unavailable"] as [String: Any]
|
||||
} ?? [],
|
||||
"physical_pages": rawPages,
|
||||
"symbol_stop": symbols.count == 1 ? symbolCatalog.items.first as Any? ?? NSNull() : NSNull(),
|
||||
"symbols_at_pc": symbolCatalog.items, "symbols_at_pc_total": symbolCatalog.total, "symbols_at_pc_truncated": symbolCatalog.truncated,
|
||||
@@ -1335,11 +1357,10 @@ final class MCPCMOC: ObservableObject {
|
||||
"source_debugging": ["status": metadata == nil ? "source_only" : "verified", "source_map": "verified", "variables": metadata == nil ? "unavailable" : "verified"],
|
||||
"watch_status": metadata == nil ? String((variableError ?? "Typed C metadata is unavailable; verified code inspection remains available.").prefix(2000)) : "Verified globals; C frame locals are unavailable for owned entry and instruction stops.",
|
||||
"memory_ranges": ranges.map { ["address": $0.lowerBound, "count": $0.count] }]
|
||||
guard let fingerprint = Self.ownedCaptureFingerprint(capture) else { throw problem("invalid_worker_capture") }
|
||||
let context = callContextApproved ? CMOCOwnedCallContext.capture(map: map, metadata: metadata, pc: address,
|
||||
s: stackPointer, u: framePointer, memory: memory, available: available,
|
||||
physicalPages: pages, sharedPaths: shared) : nil
|
||||
ownedInspection = (snapshot, owned.runID, clock, memory, ranges, fields, fingerprint, context)
|
||||
ownedInspection = (snapshot, owned.runID, clock, memory, ranges, fields, captureFingerprint, context)
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -1351,6 +1372,7 @@ final class MCPCMOC: ObservableObject {
|
||||
guard keys.allSatisfy({ capture[$0] != nil }) else { return nil }
|
||||
var state = Dictionary(uniqueKeysWithValues: keys.map { ($0, capture[$0]!) })
|
||||
state["md_register"] = capture["md_register"] ?? NSNull()
|
||||
state["residency_fingerprint"] = capture["residency_fingerprint"] ?? "0"
|
||||
guard JSONSerialization.isValidJSONObject(state),
|
||||
let bytes = try? JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]) else { return nil }
|
||||
return CMOCSourceMap.sha256(bytes)
|
||||
@@ -1850,7 +1872,7 @@ private struct MCPCMOCConsent: View {
|
||||
if !host.active {
|
||||
Toggle("Allow Disposable Playtests", isOn: $host.allowPlaytests)
|
||||
if host.allowPlaytests {
|
||||
Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in the paused, idle test drive without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest and uses no microphone. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout)
|
||||
Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, record bounded MP4 gameplay clips with optional CoCo audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in the paused, idle test drive without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest. Mac windows, microphone and capture feedback cues are excluded. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout)
|
||||
}
|
||||
if host.allowPlaytests, let media = model.project?.configuration.playtestDisks, !media.isEmpty {
|
||||
Text("Additional playtest disks: " + media.joined(separator: ", ")).font(.callout).textSelection(.enabled)
|
||||
|
||||
@@ -35,6 +35,7 @@ struct MCPDebuggerInspection {
|
||||
fields["source_stop"] = sourceStop as Any? ?? NSNull()
|
||||
fields["watches"] = watches
|
||||
fields["watch_status"] = watchStatus
|
||||
fields["residency_fingerprint"] = String(state.debuggerResidencyFingerprint)
|
||||
fields["memory_ranges"] = memory.map { ["address": $0.range.lowerBound, "count": $0.range.count] }
|
||||
self.fields = fields
|
||||
}
|
||||
@@ -42,6 +43,7 @@ struct MCPDebuggerInspection {
|
||||
static func sameProgram(_ state: VCCMachineSnapshot, _ expected: VCCMachineSnapshot) -> Bool {
|
||||
state.assistantDeviceBlockers.isEmpty && state.generation == expected.generation &&
|
||||
state.debuggerProgramRevision == expected.debuggerProgramRevision &&
|
||||
state.debuggerResidencyFingerprint == expected.debuggerResidencyFingerprint &&
|
||||
state.debuggerMappingFingerprint == expected.debuggerMappingFingerprint && state.use6309 == expected.use6309
|
||||
}
|
||||
|
||||
|
||||
@@ -366,6 +366,10 @@ final class MCPPlaytest {
|
||||
static let audioFieldLimit = 120
|
||||
static let audioCaptureLimit = 16
|
||||
static let audioByteLimit = 4 * 1024 * 1024
|
||||
static let videoFieldLimit = 3600
|
||||
static let videoClipLimit = 4
|
||||
static let videoByteLimit = 64 * 1024 * 1024
|
||||
static let videoRetainedByteLimit = 256 * 1024 * 1024
|
||||
private static let maximumAudioClipBytes = 44 + 131_072 * 4
|
||||
let runID: String
|
||||
let projectID: String
|
||||
@@ -394,6 +398,88 @@ final class MCPPlaytest {
|
||||
private var audioCapturesAccepted = 0
|
||||
private var audioBytesRetained = 0
|
||||
private var stopRequestID: String?
|
||||
private var videoDirectories: [String: URL] = [:]
|
||||
private var completedVideos: [String: [String: Any]] = [:]
|
||||
private var videoBytesRetained = 0
|
||||
private var currentVideoID: String?
|
||||
private var videoIsRecording = false
|
||||
private var videoStopRequestIDs: [String: String] = [:]
|
||||
private struct VideoFileIdentity: Equatable, Sendable {
|
||||
let device: UInt64, inode: UInt64
|
||||
let size: Int
|
||||
let seconds: Int64, nanos: Int64
|
||||
init(_ info: stat) {
|
||||
device = UInt64(info.st_dev); inode = UInt64(info.st_ino); size = Int(info.st_size)
|
||||
seconds = Int64(info.st_mtimespec.tv_sec); nanos = Int64(info.st_mtimespec.tv_nsec)
|
||||
}
|
||||
}
|
||||
private var videoFileIdentities: [String: VideoFileIdentity] = [:]
|
||||
private let videoArtifactWillVerify: (@Sendable (URL) throws -> Void)?
|
||||
|
||||
private func retainVideoMetadata(_ result: [String: Any]) async throws {
|
||||
guard let metadata = (result["video"] ?? result["video_recording"]) as? [String: Any] else { return }
|
||||
videoIsRecording = metadata["status"] as? String == "recording"
|
||||
guard metadata["completed"] as? Bool == true else { return }
|
||||
guard let id = metadata["clip_id"] as? String, let directory = videoDirectories[id] else { throw Self.failure("invalid_playtest_video") }
|
||||
if completedVideos[id] != nil { return }
|
||||
let url = directory.appendingPathComponent("Clip.mp4")
|
||||
let expectedCount = (metadata["byte_count"] as? NSNumber)?.intValue
|
||||
let expectedHash = metadata["sha256"] as? String
|
||||
let willVerify = videoArtifactWillVerify
|
||||
let identity = try await Task.detached {
|
||||
try willVerify?(url)
|
||||
let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK)
|
||||
guard fd >= 0 else { throw Self.failure("invalid_playtest_video") }
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var info = stat()
|
||||
guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG,
|
||||
(1...Self.videoByteLimit).contains(Int(info.st_size)), Int(info.st_size) == expectedCount else {
|
||||
throw Self.failure("invalid_playtest_video")
|
||||
}
|
||||
let identity = VideoFileIdentity(info)
|
||||
let bytes = try handle.read(upToCount: identity.size + 1) ?? Data()
|
||||
guard bytes.count == identity.size, CMOCProject.sha256(bytes) == expectedHash,
|
||||
fstat(fd, &info) == 0, VideoFileIdentity(info) == identity else { throw Self.failure("invalid_playtest_video") }
|
||||
return identity
|
||||
}.value
|
||||
guard let count = expectedCount, videoBytesRetained <= Self.videoRetainedByteLimit - count else { throw Self.failure("playtest_video_retention_limit") }
|
||||
videoBytesRetained += count; completedVideos[id] = metadata; videoFileIdentities[id] = identity
|
||||
}
|
||||
|
||||
private func readVideo(_ arguments: [String: Any]) async throws -> [String: Any] {
|
||||
guard Set(arguments.keys).isSubset(of: ["run_id", "clip_id", "offset", "limit"]),
|
||||
let id = arguments["clip_id"] as? String, let metadata = completedVideos[id], let directory = videoDirectories[id],
|
||||
let total = (metadata["byte_count"] as? NSNumber)?.intValue,
|
||||
let identity = videoFileIdentities[id] else { throw Self.failure("playtest_video_unavailable") }
|
||||
func integer(_ value: Any?, fallback: Int, range: ClosedRange<Int>) throws -> Int {
|
||||
guard let value else { return fallback }
|
||||
guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite,
|
||||
number.doubleValue == Double(number.intValue), range.contains(number.intValue) else { throw Self.failure("invalid_arguments") }
|
||||
return number.intValue
|
||||
}
|
||||
let offset = try integer(arguments["offset"], fallback: 0, range: 0...total)
|
||||
let limit = try integer(arguments["limit"], fallback: 65536, range: 1...65536)
|
||||
let url = directory.appendingPathComponent("Clip.mp4")
|
||||
let data = try await Task.detached {
|
||||
let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK)
|
||||
guard fd >= 0 else { throw Self.failure("invalid_playtest_video") }
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var info = stat()
|
||||
guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, VideoFileIdentity(info) == identity else { throw Self.failure("invalid_playtest_video") }
|
||||
try handle.seek(toOffset: UInt64(offset))
|
||||
let count = min(limit, total - offset)
|
||||
let bytes = try handle.read(upToCount: count) ?? Data()
|
||||
guard bytes.count == count, fstat(fd, &info) == 0, VideoFileIdentity(info) == identity else { throw Self.failure("invalid_playtest_video") }
|
||||
return bytes
|
||||
}.value
|
||||
guard valid else { throw Self.failure("stale_run") }
|
||||
var result = metadata
|
||||
result["video_chunk_base64"] = data.base64EncodedString(); result["offset"] = offset
|
||||
result["next_offset"] = offset + data.count; result["eof"] = offset + data.count == total
|
||||
return scoped(result)
|
||||
}
|
||||
|
||||
private struct MediumState {
|
||||
let source: MCPPlaytestMedium
|
||||
@@ -413,11 +499,13 @@ final class MCPPlaytest {
|
||||
|
||||
private init(worker: Worker, projectID: String, revision: Int, artifactID: String, retentionDirectory: URL,
|
||||
diskProvenance: MCPPlaytestDiskStore.Provenance, resumedDiskID: String?, runID: String,
|
||||
processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?) {
|
||||
processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?,
|
||||
videoArtifactWillVerify: (@Sendable (URL) throws -> Void)?) {
|
||||
self.runID = runID
|
||||
self.worker = worker; self.projectID = projectID; self.revision = revision; self.artifactID = artifactID
|
||||
self.retentionDirectory = retentionDirectory; self.diskProvenance = diskProvenance; self.resumedDiskID = resumedDiskID
|
||||
self.processor = processor
|
||||
self.videoArtifactWillVerify = videoArtifactWillVerify
|
||||
if let media {
|
||||
self.media = Dictionary(uniqueKeysWithValues: media.map { ($0.id, MediumState(source: $0, data: $0.data)) })
|
||||
self.mediaOrder = media.map(\.id); self.mountedMediaID = media.first?.id
|
||||
@@ -429,7 +517,8 @@ final class MCPPlaytest {
|
||||
modules: [[String: Any]] = [], stopAt: UInt16? = nil, stopModule: String? = nil, flatGuards: [[String: Any]] = [], cpu: String = "6809", helperURL: URL? = nil, retentionDirectory: URL? = nil,
|
||||
diskProvenance: MCPPlaytestDiskStore.Provenance? = nil, resumedDiskID: String? = nil,
|
||||
graphicsBuffers: [[String: Any]] = [], runID: String = UUID().uuidString,
|
||||
media: [MCPPlaytestMedium]? = nil) async throws -> MCPPlaytest {
|
||||
media: [MCPPlaytestMedium]? = nil,
|
||||
videoArtifactWillVerify: (@Sendable (URL) throws -> Void)? = nil) async throws -> MCPPlaytest {
|
||||
guard let reservedID = UUID(uuidString: runID) else { throw failure("invalid_playtest_run_id") }
|
||||
guard systemROM.count == 32768, diskROM.count == 8192, !disk.isEmpty, disk.count <= 512 * 1024,
|
||||
["6809", "6309"].contains(cpu), bootCommands.utf8.count <= 256 else { throw failure("invalid_playtest_artifact") }
|
||||
@@ -472,7 +561,7 @@ final class MCPPlaytest {
|
||||
let test = MCPPlaytest(worker: worker, projectID: projectID, revision: revision, artifactID: artifactID,
|
||||
retentionDirectory: retentionDirectory ?? AppIdentity.supportDirectory.appendingPathComponent("Development Runs/Assistant Playtests"),
|
||||
diskProvenance: provenance, resumedDiskID: resumedDiskID.map { UUID(uuidString: $0)!.uuidString }, runID: reservedID.uuidString,
|
||||
processor: cpu == "6309" ? .hd6309 : .mc6809, media: media)
|
||||
processor: cpu == "6309" ? .hd6309 : .mc6809, media: media, videoArtifactWillVerify: videoArtifactWillVerify)
|
||||
var setup: [String: Any] = ["op": "init", "system_rom": systemROM.base64EncodedString(),
|
||||
"disk_rom": diskROM.base64EncodedString(), "disk": disk.base64EncodedString(),
|
||||
"boot_keys": paste.chords.map { NSNumber(value: $0) }, "modules": modules, "cpu": cpu,
|
||||
@@ -550,6 +639,10 @@ final class MCPPlaytest {
|
||||
throw Self.failure("playtest_disk_export_failed")
|
||||
}
|
||||
exportedDisk = Data(data); exportedStatus = result
|
||||
// Video is an independent artifact. A missing or corrupt movie may
|
||||
// never prevent retention of the guest's writable disk bytes.
|
||||
do { try await retainVideoMetadata(result) }
|
||||
catch { exportedStatus?["video_retention_error"] = "The video artifact could not be verified; disk retention continues." }
|
||||
}
|
||||
guard let data = exportedDisk else { throw Self.failure("playtest_disk_export_failed") }
|
||||
do {
|
||||
@@ -695,6 +788,8 @@ final class MCPPlaytest {
|
||||
do {
|
||||
result = try await worker.request(["op": "stop"])
|
||||
try receiveMediaExport(result)
|
||||
do { try await retainVideoMetadata(result) }
|
||||
catch { result["video_retention_error"] = "The video artifact could not be verified; disk retention continues." }
|
||||
} catch let error as WorkerTransportFailure {
|
||||
// A failed swap pipe cannot have advanced a paused guest.
|
||||
// Every candidate copy is already frozen in the host; retain
|
||||
@@ -771,6 +866,7 @@ final class MCPPlaytest {
|
||||
if exportedDisk != nil { return scoped(["status": "retention_pending", "disk_retained": false]) }
|
||||
let result = try await worker.request(["op": "capture"])
|
||||
guard valid else { throw Self.failure("stale_run") }
|
||||
try await retainVideoMetadata(result)
|
||||
return scoped(result)
|
||||
}
|
||||
if tool == "get_playtest_input" {
|
||||
@@ -779,8 +875,9 @@ final class MCPPlaytest {
|
||||
guard valid else { throw Self.failure("stale_run") }
|
||||
return scoped(result)
|
||||
}
|
||||
if tool == "read_playtest_video" { return try await readVideo(arguments) }
|
||||
guard let requestID = arguments["request_id"] as? String, (1...64).contains(requestID.utf8.count),
|
||||
["playtest_input", "restart_playtest", "stop_playtest", "playtest_debug", "capture_playtest_audio", "exchange_playtest_media"].contains(tool) else { throw Self.failure("invalid_arguments") }
|
||||
["playtest_input", "restart_playtest", "stop_playtest", "playtest_debug", "capture_playtest_audio", "exchange_playtest_media", "start_playtest_video", "stop_playtest_video"].contains(tool) else { throw Self.failure("invalid_arguments") }
|
||||
let signature = try JSONSerialization.data(withJSONObject: ["tool": tool, "arguments": arguments], options: [.sortedKeys])
|
||||
if let (prior, reason) = mediaFailures[requestID] {
|
||||
guard signature == prior else { throw Self.failure("request_conflict") }
|
||||
@@ -793,11 +890,15 @@ final class MCPPlaytest {
|
||||
if tool == "stop_playtest", let stopRequestID, requestID != stopRequestID {
|
||||
throw Self.failure("request_conflict: retry the original stop request_id")
|
||||
}
|
||||
if tool == "stop_playtest_video", let clip = currentVideoID,
|
||||
let prior = videoStopRequestIDs[clip], prior != requestID {
|
||||
throw Self.failure("request_conflict: retry the original video stop request_id")
|
||||
}
|
||||
guard exportedDisk == nil || tool == "stop_playtest" else { throw Self.failure("playtest_retention_pending") }
|
||||
guard !finished else { throw Self.failure("stale_run") }
|
||||
// Cleanup has its own single cached receipt and must remain possible
|
||||
// after any execution/audio budget is exhausted.
|
||||
guard tool == "stop_playtest" || mutationRequestsAccepted < Self.mutationRequestLimit || accepted[requestID] != nil else {
|
||||
guard ["stop_playtest", "stop_playtest_video"].contains(tool) || mutationRequestsAccepted < Self.mutationRequestLimit || accepted[requestID] != nil else {
|
||||
throw Self.failure("playtest_request_limit")
|
||||
}
|
||||
if tool == "exchange_playtest_media" {
|
||||
@@ -843,6 +944,31 @@ final class MCPPlaytest {
|
||||
}
|
||||
var request: [String: Any]
|
||||
switch tool {
|
||||
case "start_playtest_video":
|
||||
guard Set(arguments.keys).isSubset(of: ["run_id", "request_id", "include_audio", "max_fields"]) else { throw Self.failure("invalid_arguments") }
|
||||
guard !videoIsRecording else { throw Self.failure("playtest_video_active") }
|
||||
let includeAudio: Bool
|
||||
if let value = arguments["include_audio"] {
|
||||
guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { throw Self.failure("invalid_arguments") }
|
||||
includeAudio = number.boolValue
|
||||
} else { includeAudio = true }
|
||||
let maximum: Int
|
||||
if let value = arguments["max_fields"] {
|
||||
guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite,
|
||||
number.doubleValue == Double(number.intValue), (1...Self.videoFieldLimit).contains(number.intValue) else { throw Self.failure("invalid_arguments") }
|
||||
maximum = number.intValue
|
||||
} else { maximum = 1800 }
|
||||
guard videoDirectories.count < Self.videoClipLimit, videoBytesRetained <= Self.videoRetainedByteLimit - Self.videoByteLimit else {
|
||||
throw Self.failure("playtest_video_capture_limit")
|
||||
}
|
||||
let id = UUID().uuidString
|
||||
let directory = retentionDirectory.appendingPathComponent("Videos", isDirectory: true).appendingPathComponent(runID, isDirectory: true).appendingPathComponent(id, isDirectory: true)
|
||||
try await Task.detached { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) }.value
|
||||
videoDirectories[id] = directory; currentVideoID = id
|
||||
request = ["op": "video_start", "clip_id": id, "directory": directory.path, "include_audio": includeAudio, "max_fields": maximum]
|
||||
case "stop_playtest_video":
|
||||
guard arguments.count == 2, currentVideoID != nil else { throw Self.failure("playtest_video_unavailable") }
|
||||
request = ["op": "video_stop"]
|
||||
case "capture_playtest_audio":
|
||||
guard arguments.count == 3, let n = arguments["fields"] as? NSNumber,
|
||||
CFGetTypeID(n) != CFBooleanGetTypeID(), n.doubleValue.isFinite,
|
||||
@@ -892,6 +1018,7 @@ final class MCPPlaytest {
|
||||
}
|
||||
case "restart_playtest":
|
||||
guard arguments.count == 2 else { throw Self.failure("invalid_arguments") }
|
||||
guard !videoIsRecording else { throw Self.failure("playtest_video_active: stop the recording before restarting") }
|
||||
request = ["op": "restart"]
|
||||
default:
|
||||
guard arguments.count == 2 else { throw Self.failure("invalid_arguments") }
|
||||
@@ -900,7 +1027,8 @@ final class MCPPlaytest {
|
||||
// Reserve the identity before execution. An interrupted operation must
|
||||
// never be retried as a new input sequence with the same request ID.
|
||||
if tool == "stop_playtest" { stopRequestID = requestID }
|
||||
if tool != "stop_playtest" { mutationRequestsAccepted += 1 }
|
||||
if tool == "stop_playtest_video", let clip = currentVideoID { videoStopRequestIDs[clip] = requestID }
|
||||
if !["stop_playtest", "stop_playtest_video"].contains(tool) { mutationRequestsAccepted += 1 }
|
||||
if tool == "capture_playtest_audio" { audioCapturesAccepted += 1 }
|
||||
accepted[requestID] = (signature, scoped(["request_id": requestID, "status": "interrupted"]))
|
||||
if tool == "stop_playtest" {
|
||||
@@ -920,6 +1048,7 @@ final class MCPPlaytest {
|
||||
lastSafeMediaExport = nil
|
||||
var result = try await worker.request(request)
|
||||
guard valid else { throw Self.failure("stale_run") }
|
||||
try await retainVideoMetadata(result)
|
||||
if tool == "capture_playtest_audio" {
|
||||
guard let encoded = result["audio_wav_base64"] as? String,
|
||||
let wav = Data(base64Encoded: encoded), (44...Self.maximumAudioClipBytes).contains(wav.count),
|
||||
@@ -963,6 +1092,7 @@ final class MCPPlaytest {
|
||||
if let operation = request["op"] as? String, ["continue", "step", "stop_at"].contains(operation) { lastSafeMediaExport = nil }
|
||||
let result = try await worker.request(request)
|
||||
guard valid else { throw Self.failure("stale_run") }
|
||||
try await retainVideoMetadata(result)
|
||||
return scoped(result)
|
||||
}
|
||||
|
||||
@@ -975,6 +1105,12 @@ final class MCPPlaytest {
|
||||
result["mutation_requests_used"] = mutationRequestsAccepted
|
||||
result["remaining_mutation_requests"] = max(0, Self.mutationRequestLimit - mutationRequestsAccepted)
|
||||
result["stop_retention_exempt"] = true
|
||||
result["video_stop_retention_exempt"] = true
|
||||
result["video_clip_limit"] = Self.videoClipLimit
|
||||
result["remaining_video_clips"] = max(0, Self.videoClipLimit - videoDirectories.count)
|
||||
result["video_byte_limit"] = Self.videoByteLimit
|
||||
result["video_retained_byte_limit"] = Self.videoRetainedByteLimit
|
||||
result["remaining_video_bytes"] = max(0, Self.videoRetainedByteLimit - videoBytesRetained)
|
||||
result["audio_capture_limit"] = Self.audioCaptureLimit
|
||||
result["remaining_audio_captures"] = max(0, Self.audioCaptureLimit - audioCapturesAccepted)
|
||||
result["audio_byte_limit"] = Self.audioByteLimit
|
||||
|
||||
@@ -59,6 +59,8 @@ struct MachineView: View {
|
||||
.frame(maxWidth: 440, maxHeight: 42)
|
||||
}.buttonStyle(.plain).help("Open Machine Settings for processor and memory")
|
||||
Spacer(minLength: 24)
|
||||
CoCoCaptureControls(capture: machine.captures, machine: machine)
|
||||
Spacer(minLength: 12)
|
||||
Button { openWindow(id: "machine-settings") } label: {
|
||||
HardwareBadge(name: machine.use6309 ? "hitachi" : "motorola", label: machine.use6309 ? "Hitachi 6309" : "Motorola 6809").frame(width: 44, height: 44)
|
||||
}.buttonStyle(.plain).help("Open Machine Settings for processor and memory")
|
||||
|
||||
@@ -352,10 +352,11 @@ final class MachineModel: ObservableObject {
|
||||
private let automaticDiskWriter: @Sendable (Data, URL, Data) async throws -> Void
|
||||
private let diskStore: DiskAssignmentStore
|
||||
private let inputStore: InputSettingsStore
|
||||
private let inputControllerReadings: (() -> [ControllerReading])?
|
||||
lazy var printer = PrinterModel(controller: controller)
|
||||
private var existingInputHub: InputHub?
|
||||
lazy var input: InputHub = {
|
||||
let hub = InputHub(controller: controller, store: inputStore)
|
||||
let hub = InputHub(controller: controller, store: inputStore, controllerReadings: inputControllerReadings)
|
||||
existingInputHub = hub
|
||||
return hub
|
||||
}()
|
||||
@@ -386,10 +387,13 @@ final class MachineModel: ObservableObject {
|
||||
private var mediaPromptOpen = false
|
||||
let recentMedia: RecentMedia
|
||||
let displayPreferences: DisplayPreferences
|
||||
lazy var captures = CoCoCaptureCoordinator(machine: self, controller: controller, defaults: displayDefaults,
|
||||
directory: diskStore.url.deletingLastPathComponent())
|
||||
private var screenshotInProgress = false
|
||||
private let controller: VCCMachineController
|
||||
init(diskStore: DiskAssignmentStore = .standard, controller: VCCMachineController = VCCMachineController(),
|
||||
displayDefaults: UserDefaults = .standard, inputStore: InputSettingsStore = .standard, startupStore: StartupStore? = nil,
|
||||
inputControllerReadings: (() -> [ControllerReading])? = nil,
|
||||
restoreMediaOnLaunch: Bool = true,
|
||||
automaticHardDiskWriter: @escaping @Sendable (Data, Int, URL, String) async throws -> String = { patches, length, url, expected in
|
||||
try await Task.detached(priority: .utility) { try HardDiskFiles.saveAutomatically(patches, length: length, to: url, expected: expected) }.value
|
||||
@@ -403,6 +407,7 @@ final class MachineModel: ObservableObject {
|
||||
self.starterShellDiskURL = startupStore?.directory.resolvingSymlinksInPath()
|
||||
.appendingPathComponent("Starter Media/NitrOS-9 L2 V3.3.0.vhd").standardizedFileURL
|
||||
self.inputStore = inputStore
|
||||
self.inputControllerReadings = inputControllerReadings
|
||||
self.displayDefaults = displayDefaults
|
||||
videoOutput = DisplayOutput.remembered(in: displayDefaults)
|
||||
let rememberedSettings = MachineSettings.remembered(in: displayDefaults)
|
||||
@@ -522,7 +527,7 @@ final class MachineModel: ObservableObject {
|
||||
// Shared by both presentations. The profile transaction already pauses the
|
||||
// worker, drains automatic writes and rejects any unsaved media atomically.
|
||||
@discardableResult func restoreAppDefaults() async -> Bool {
|
||||
await loadSystemProfile(.diskBasic)
|
||||
await loadSystemProfile(.diskBasic, resetInput: true)
|
||||
}
|
||||
func systemProfileUnavailableReason(_ kind: SystemProfile) -> String? {
|
||||
guard let startupStore else { return StartupStore.Failure.unavailable.localizedDescription }
|
||||
@@ -537,11 +542,15 @@ final class MachineModel: ObservableObject {
|
||||
}.value
|
||||
}
|
||||
@discardableResult func loadSystemProfile(_ kind: SystemProfile) async -> Bool {
|
||||
await loadSystemProfile(kind, resetInput: false)
|
||||
}
|
||||
@discardableResult private func loadSystemProfile(_ kind: SystemProfile, resetInput: Bool) async -> Bool {
|
||||
guard !busy, !diskSaving, state != .closed else { return false }
|
||||
await loadProfile(preparing: { [startupStore] in
|
||||
guard let startupStore else { throw StartupStore.Failure.unavailable }
|
||||
return try await Task.detached(priority: .userInitiated) { try startupStore.systemProfile(kind) }.value
|
||||
}, startRunning: true, builtInNitros9: kind == .nitros9)
|
||||
}, startRunning: true, builtInNitros9: kind == .nitros9,
|
||||
preserveInput: !resetInput, resetInput: resetInput)
|
||||
let succeeded = profileError == nil && fileError == nil
|
||||
if succeeded { guideRequest = GuideRequest(profile: kind) }
|
||||
return succeeded
|
||||
@@ -1080,6 +1089,9 @@ final class MachineModel: ObservableObject {
|
||||
// checks active disk writes and recordings again on its serial queue.
|
||||
func applyMachineSettings(_ value: MachineSettings) {
|
||||
guard !busy, !diskSaving, state != .closed, value.valid else { return }
|
||||
if captures.active && (value.fastForward || value.use6309 != settings.use6309 || value.ram != settings.ram) {
|
||||
Task { if await captures.stopBeforeReplacingMachine() { applyMachineSettings(value) } }; return
|
||||
}
|
||||
command({ controller.configureMachine(use6309: value.use6309, ram: value.ram,
|
||||
overclock: value.overclock, frameInterval: value.frameInterval,
|
||||
fastForward: value.fastForward, completion: $0) }, onSuccess: { [self] in
|
||||
@@ -1111,6 +1123,10 @@ final class MachineModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
func installROM(_ data: Data, url: URL) {
|
||||
if captures.active {
|
||||
Task { if await captures.stopBeforeReplacingMachine() { installROM(data, url: url) } else { busy = false } }; return
|
||||
}
|
||||
captures.cancelCountdown()
|
||||
busy = true; inputEpoch += 1
|
||||
controller.loadROM(data, use6309: use6309) { [weak self] snapshot in
|
||||
MainActor.assumeIsolated {
|
||||
@@ -1761,6 +1777,9 @@ final class MachineModel: ObservableObject {
|
||||
var definition: [String: Any] = ["id": module.id, "pages": module.pages.map {
|
||||
["logicalPage": $0.logicalPage, "physicalPage": $0.physicalPage]
|
||||
}, "addresses": code.map { NSNumber(value: $0.address) }, "bytes": code.map { Data($0.bytes) }]
|
||||
if let overlay = module.overlay {
|
||||
definition["overlay_group"] = overlay.group; definition["overlay_owner"] = overlay.owner
|
||||
}
|
||||
if let pointModules {
|
||||
definition["breakpoints"] = addresses.filter { pointModules[$0]?.contains(module.id) == true }.map { NSNumber(value: $0) }
|
||||
}
|
||||
@@ -1846,6 +1865,7 @@ final class MachineModel: ObservableObject {
|
||||
debuggerCommand({ controller.debuggerStepBankedSource(mode: mode, addresses: addresses, locations: locations,
|
||||
bytes: bytes, moduleIdentifiers: moduleIdentifiers, generation: expected.generation,
|
||||
programRevision: expected.debuggerProgramRevision, mappingFingerprint: expected.debuggerMappingFingerprint,
|
||||
residencyFingerprint: expected.debuggerResidencyFingerprint,
|
||||
programCounter: expected.programCounter, completion: $0) }, completion: completion)
|
||||
return
|
||||
}
|
||||
@@ -1891,8 +1911,8 @@ final class MachineModel: ObservableObject {
|
||||
func debuggerWriteMemory(address: UInt16, data: Data, completion: @escaping () -> Void) {
|
||||
debuggerCommand({ controller.debuggerWriteMemory(address: address, data: data, completion: $0) }, completion: completion)
|
||||
}
|
||||
func softReset() { command(controller.softReset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) }
|
||||
func reset() { command(controller.reset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) }
|
||||
func softReset() { captures.cancelCountdown(); command(controller.softReset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) }
|
||||
func reset() { captures.cancelCountdown(); command(controller.reset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) }
|
||||
func poll() {
|
||||
guard !polling, !busy, state != .closed else { return }
|
||||
polling = true
|
||||
@@ -2373,8 +2393,11 @@ extension MachineModel {
|
||||
await loadProfile(preparing: { profile }, startRunning: false)
|
||||
}
|
||||
@discardableResult private func loadProfile(preparing: () async throws -> ConfigurationProfile, startRunning: Bool,
|
||||
builtInNitros9: Bool = false, afterStart: (() async throws -> Void)? = nil) async -> Bool {
|
||||
builtInNitros9: Bool = false, preserveInput: Bool = false, resetInput: Bool = false,
|
||||
libraryInputs: Bool = false,
|
||||
afterStart: (() async throws -> Void)? = nil) async -> Bool {
|
||||
guard !busy, state != .closed else { return false }
|
||||
guard await captures.stopBeforeReplacingMachine() else { return false }
|
||||
var committed = false
|
||||
guideRequest = nil
|
||||
busy = true; inputEpoch += 1; profileError = nil; fileError = nil
|
||||
@@ -2428,7 +2451,11 @@ extension MachineModel {
|
||||
}
|
||||
}
|
||||
nextHardSave = .distantPast; savedHardFlushRequests = hardFlushRequests
|
||||
volume = profile.volume; input.settings = profile.input
|
||||
volume = profile.volume
|
||||
if resetInput { input.restoreDefaultSettings() }
|
||||
else if preserveInput { input.release() }
|
||||
else if libraryInputs { input.applyLibrarySettings(profile.input) }
|
||||
else { input.applyProfileSettings(profile.input) }
|
||||
_ = await applyDriveWireDefault(builtInNitros9)
|
||||
rememberStartup()
|
||||
loadedProfileConfiguration = profileConfiguration
|
||||
@@ -2609,6 +2636,7 @@ extension MachineModel {
|
||||
let capture: ScreenCapture
|
||||
do { capture = try ScreenCapture(pixels: pixels, area: activeVideoRect) }
|
||||
catch { fileError = error.localizedDescription; return }
|
||||
CoCoCaptureFeedback.play(.screenshot)
|
||||
screenshotInProgress = true; fileError = nil
|
||||
let panel = NSSavePanel()
|
||||
panel.title = "Save CoCo Screen"
|
||||
@@ -2685,6 +2713,15 @@ extension MachineModel {
|
||||
case .diskBasic:
|
||||
profile.media.rom = try firmware("disk11.rom", fallback: diskAssignments.rom)
|
||||
layout.slots[plan.controllerSlot].kind = .floppy
|
||||
case .hardDriveBasic:
|
||||
// An arbitrary active disk ROM may be Disk BASIC rather than RGB-DOS.
|
||||
// Only recognized starter firmware can supply a missing bundled ROM;
|
||||
// editable profile names and the presence of a hard disk prove nothing.
|
||||
let knownRGBDOS = usageProfile == .hardDriveBasic || usageProfile == .nitros9
|
||||
profile.media.rom = try firmware(SystemProfile.hardDriveBasic.diskROMName,
|
||||
fallback: knownRGBDOS ? diskAssignments.rom : nil)
|
||||
layout.slots[plan.controllerSlot].kind = .floppy
|
||||
layout.slots[plan.controllerSlot == 1 ? 2 : 1].kind = .hardDisk
|
||||
case .cocoSDC:
|
||||
let priorROM = cartridgeAssignments.slots.first { $0.kind == .sdc }?.url
|
||||
layout.slots[plan.controllerSlot] = .init(kind: .sdc, url: try firmware("sdcdos.rom", fallback: priorROM),
|
||||
@@ -2692,6 +2729,7 @@ extension MachineModel {
|
||||
}
|
||||
profile.media.cartridges = layout
|
||||
profile.media.hardDisks = HardDiskAssignments()
|
||||
for (drive, url) in plan.hardDiskURLs { profile.media.hardDisks?.drives[drive] = .init(url: url, writeProtected: false) }
|
||||
for (drive, url) in plan.floppyURLs { profile.media.drives[drive] = .init(url: url, writeProtected: false) }
|
||||
profile.cassette = plan.cassetteURL; profile.fastCassette = plan.cassetteURL != nil
|
||||
profile.bootNitros9 = nil
|
||||
@@ -2720,7 +2758,7 @@ extension MachineModel {
|
||||
let applied = await loadProfile(preparing: {
|
||||
try await Task.detached(priority: .userInitiated) { try prepared.plan.validateMedia() }.value
|
||||
return prepared.profile
|
||||
}, startRunning: true, afterStart: { [self] in
|
||||
}, startRunning: true, libraryInputs: true, afterStart: { [self] in
|
||||
do {
|
||||
try Task.checkCancellation()
|
||||
if prepared.plan.cassetteURL != nil && !prepared.plan.commands.isEmpty {
|
||||
@@ -2769,7 +2807,8 @@ extension MachineModel {
|
||||
guard canLaunchLibrarySoftware else { throw ProfileFailure.message("Wait for the current machine operation to finish.") }
|
||||
_ = try await Task.detached(priority: .userInitiated) { try PreparedProfile.read(profile) }.value
|
||||
try Task.checkCancellation()
|
||||
let applied = await loadProfile(preparing: { profile }, startRunning: true, builtInNitros9: profile == libraryReturnToNitros9)
|
||||
let applied = await loadProfile(preparing: { profile }, startRunning: true, builtInNitros9: profile == libraryReturnToNitros9,
|
||||
libraryInputs: true)
|
||||
guard applied, profileError == nil else { throw ProfileFailure.message(profileError ?? "The previous setup could not be restored.") }
|
||||
libraryReturnToNitros9 = nil
|
||||
}
|
||||
|
||||
@@ -100,33 +100,157 @@ struct ManualLibraryContent {
|
||||
}
|
||||
}
|
||||
|
||||
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<UUID> = []
|
||||
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) {
|
||||
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 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 {
|
||||
@@ -151,11 +275,16 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func loadPage(_ url: URL?) -> WKNavigation? {
|
||||
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)
|
||||
}
|
||||
@@ -192,6 +321,21 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -211,6 +355,42 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
|
||||
|
||||
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()
|
||||
@@ -248,6 +428,7 @@ private struct ManualWebPage: NSViewRepresentable {
|
||||
struct ManualLibraryView: View {
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@ObservedObject var reader: ManualReader
|
||||
@State private var showsBookmarks = false
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
@@ -264,6 +445,23 @@ struct ManualLibraryView: View {
|
||||
.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")
|
||||
|
||||
@@ -288,7 +486,94 @@ struct ManualLibraryView: View {
|
||||
}
|
||||
.frame(minWidth: 420, minHeight: 340)
|
||||
.onAppear {
|
||||
if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.showHome() }
|
||||
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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,10 +122,10 @@ actor SoftwareLibraryArtworkCache {
|
||||
}
|
||||
|
||||
static func canDisplay(_ asset: SoftwareLibraryAsset) -> Bool {
|
||||
guard let url = asset.thumbnailURL, accepts(url),
|
||||
guard let url = asset.thumbnailURL, accepts(url) || (asset.matchStatus == "personal" && url.isFileURL),
|
||||
let checksum = asset.thumbnailSHA256, checksum.count == 64,
|
||||
checksum.allSatisfy({ $0.isHexDigit }),
|
||||
let size = asset.thumbnailByteSize, size > 0, size <= maximumThumbnailBytes else { return false }
|
||||
let size = asset.thumbnailByteSize, size > 0, size <= (asset.matchStatus == "personal" ? Int64(maximumSourceBytes) : Int64(maximumThumbnailBytes)) else { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -165,6 +165,11 @@ actor SoftwareLibraryArtworkCache {
|
||||
}
|
||||
|
||||
func thumbnail(for asset: SoftwareLibraryAsset, directory: URL) async throws -> Data {
|
||||
if asset.matchStatus == "personal", let url = asset.thumbnailURL, url.isFileURL {
|
||||
try SoftwareLibraryLocalAsset.validate(asset, url: url, maximumBytes: Int(Self.maximumSourceBytes))
|
||||
return try Self.downsample(Data(contentsOf: url), expectedSHA256: asset.thumbnailSHA256)
|
||||
}
|
||||
|
||||
try Task.checkCancellation()
|
||||
guard Self.canDisplay(asset), let url = asset.thumbnailURL,
|
||||
let fingerprint = asset.thumbnailSHA256 else { throw Failure.unsupported }
|
||||
@@ -241,3 +246,35 @@ private final class LibraryArtworkRedirects: NSObject, URLSessionTaskDelegate {
|
||||
completionHandler(request.url.map(SoftwareLibraryArtworkCache.accepts) == true ? request : nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// Local assets are accepted only from a namespaced private entry's Assets tree.
|
||||
/// The public catalog/cache URL allowlists remain unchanged.
|
||||
enum SoftwareLibraryLocalAsset {
|
||||
static func validate(_ asset: SoftwareLibraryAsset, url: URL, maximumBytes: Int) throws {
|
||||
guard asset.matchStatus == "personal", url.isFileURL, url.host == nil || url.host == "localhost",
|
||||
url.query == nil, url.fragment == nil, let expected = asset.sha256,
|
||||
expected.count == 64, expected.allSatisfy(\.isHexDigit), let size = asset.byteSize,
|
||||
size > 0, size <= maximumBytes else { throw SoftwareLibraryManualCache.Failure.unavailable }
|
||||
let parts = url.standardizedFileURL.pathComponents
|
||||
guard let index = parts.lastIndex(of: "PersonalLibrary"), parts.count > index + 3,
|
||||
UUID(uuidString: parts[index + 1]) != nil, parts[index + 2] == "Assets",
|
||||
asset.id.hasPrefix("personal:" + parts[index + 1].lowercased() + ":asset:") else { throw SoftwareLibraryManualCache.Failure.unavailable }
|
||||
// System parent aliases such as /var are legitimate. The private
|
||||
// library root and every component beneath it must be nonsymlink.
|
||||
var checked = URL(fileURLWithPath: NSString.path(withComponents: Array(parts.prefix(index))), isDirectory: true)
|
||||
for part in parts.dropFirst(index) {
|
||||
checked.appendPathComponent(part)
|
||||
guard try checked.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { throw SoftwareLibraryManualCache.Failure.unavailable }
|
||||
}
|
||||
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
guard values.isRegularFile == true, values.fileSize == Int(size) else { throw SoftwareLibraryManualCache.Failure.changed }
|
||||
let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }
|
||||
var hash = SHA256(), count = 0
|
||||
while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty {
|
||||
try Task.checkCancellation(); count += block.count
|
||||
guard count <= maximumBytes else { throw SoftwareLibraryManualCache.Failure.changed }
|
||||
hash.update(data: block)
|
||||
}
|
||||
guard count == Int(size), hash.finalize().map({ String(format: "%02x", $0) }).joined() == expected.lowercased() else { throw SoftwareLibraryManualCache.Failure.changed }
|
||||
}
|
||||
}
|
||||
@@ -234,6 +234,16 @@ struct SoftwareLibraryRelease: Identifiable, Codable, Sendable {
|
||||
}
|
||||
}
|
||||
try SoftwareLibraryOwnedGame.validateBrowseMetadata(metadata, optional: true)
|
||||
if metadata["related_archive"] != .null {
|
||||
guard metadata["related_archive_contract"].integer == 1, case .array(let references) = metadata["related_archive"], references.count <= 100 else {
|
||||
throw SoftwareLibraryCatalog.Failure.invalid("unsupported related Archive document contract")
|
||||
}
|
||||
let parsed = try references.map(SoftwareLibraryRelatedReference.parse)
|
||||
guard Set(parsed.map(\.id)).count == parsed.count,
|
||||
Set(parsed.map { $0.documentID + ":" + String($0.page ?? 0) }).count == parsed.count else {
|
||||
throw SoftwareLibraryCatalog.Failure.invalid("duplicate related Archive document relationship")
|
||||
}
|
||||
}
|
||||
}
|
||||
var publisher: String? { metadata["publisher"].string }
|
||||
var year: Int? { metadata["year"].integer }
|
||||
@@ -624,3 +634,46 @@ private extension Dictionary where Key == String, Value == String {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// Reviewed cross-library relationships are public metadata, never transport URLs.
|
||||
struct SoftwareLibraryRelatedReference: Identifiable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let documentID: String
|
||||
let sha256: String
|
||||
let role: String
|
||||
let page: Int?
|
||||
let spoiler: Bool
|
||||
let order: Int
|
||||
static let roles = ["Guide", "Tutorial", "Reference", "Hints", "Walkthrough", "Solution", "Map"]
|
||||
static func parse(_ json: LibraryJSON) throws -> Self {
|
||||
guard let id = json["id"].string, !id.isEmpty, id.utf8.count <= 240,
|
||||
let title = json["title"].string, !title.isEmpty, title.utf8.count <= 1000,
|
||||
let document = json["document_id"].string, document.count == 64, document.allSatisfy(\.isHexDigit),
|
||||
let sha = json["sha256"].string, sha == document,
|
||||
let role = json["role"].string, roles.contains(role),
|
||||
json["page"] == .null || (json["page"].integer ?? 0) > 0 else {
|
||||
throw SoftwareLibraryCatalog.Failure.invalid("invalid related Archive document metadata")
|
||||
}
|
||||
return .init(id: id, title: title, documentID: document, sha256: sha, role: role,
|
||||
page: json["page"].integer, spoiler: json["spoiler"] == .bool(true), order: json["order"].integer ?? 999)
|
||||
}
|
||||
}
|
||||
extension SoftwareLibraryRelease {
|
||||
var isDirectSubmission: Bool { metadata["origin"].string == "direct_submission" }
|
||||
var isArchive: Bool { ownedGame == nil && !isPersonal && !isDirectSubmission }
|
||||
var relatedArchiveReferences: [SoftwareLibraryRelatedReference] {
|
||||
guard metadata["related_archive_contract"].integer == 1 else { return [] }
|
||||
return metadata["related_archive"].array.compactMap { try? SoftwareLibraryRelatedReference.parse($0) }.sorted {
|
||||
if $0.order != $1.order { return $0.order < $1.order }
|
||||
let a = SoftwareLibraryRelatedReference.roles.firstIndex(of: $0.role) ?? 99
|
||||
let b = SoftwareLibraryRelatedReference.roles.firstIndex(of: $1.role) ?? 99
|
||||
if a != b { return a < b }
|
||||
return $0.title.localizedStandardCompare($1.title) == .orderedAscending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SoftwareLibraryRelease {
|
||||
var isPersonal: Bool { metadata["personal"] == .bool(true) && titleID.hasPrefix("personal:") }
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import CryptoKit
|
||||
/// A bounded interpretation of catalog data, not executable host instructions.
|
||||
/// Preparation reads only the installed Working tree and never changes the machine.
|
||||
struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
enum Profile: String, Sendable { case diskBasic = "disk-basic", romCartridge = "rom-cartridge", cocoSDC = "coco-sdc" }
|
||||
enum Profile: String, Sendable { case diskBasic = "disk-basic", hardDriveBasic = "hard-drive-basic", romCartridge = "rom-cartridge", cocoSDC = "coco-sdc" }
|
||||
enum CartridgeDevice: String, Sendable { case rom, orchestra90 }
|
||||
struct Candidate: Identifiable, Equatable, Sendable {
|
||||
let path: String
|
||||
@@ -37,6 +37,7 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
let controllerSlot: Int
|
||||
let cartridgeDevice: CartridgeDevice
|
||||
let floppyURLs: [Int: URL]
|
||||
let hardDiskURLs: [Int: URL]
|
||||
let cassetteURL: URL?
|
||||
let cartridgeURL: URL?
|
||||
let sdcFolderURL: URL?
|
||||
@@ -46,13 +47,14 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
let manualInstructions: String
|
||||
let compatibilityNotes: [String]
|
||||
let automaticallyStarts: Bool
|
||||
let offersPlay: Bool
|
||||
let controls: LibraryJSON
|
||||
private let curatedStartup: SoftwareLibraryOwnedGame?
|
||||
var usesCuratedStartup: Bool { curatedStartup != nil }
|
||||
|
||||
private static func supportsDisk(_ ext: String, profile: Profile) -> Bool {
|
||||
switch profile {
|
||||
case .diskBasic: return DiskFiles.extensions.contains(ext)
|
||||
case .diskBasic, .hardDriveBasic: return DiskFiles.extensions.contains(ext)
|
||||
case .cocoSDC: return ["dsk", "jvc", "os9"].contains(ext)
|
||||
case .romCartridge: return false
|
||||
}
|
||||
@@ -61,27 +63,43 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
/// Presentation only: downloaded files still undergo full preparation before
|
||||
/// a restart is offered. Missing or ambiguous startup media remains Set Up.
|
||||
static func hasAutomaticStartup(for release: SoftwareLibraryRelease) -> Bool {
|
||||
guard let profile = assignedMediaProfile(for: release) else { return false }
|
||||
return profile == .romCartridge || decodeCommands(release.setup.command)?.contains(where: startsSoftware) == true
|
||||
}
|
||||
|
||||
/// Play opens a reviewed personal setup even when loading remains manual.
|
||||
/// This does not claim that a guest program will start automatically.
|
||||
static func hasPlayAction(for release: SoftwareLibraryRelease) -> Bool {
|
||||
guard assignedMediaProfile(for: release) != nil else { return false }
|
||||
return hasAutomaticStartup(for: release) || (release.isPersonal &&
|
||||
release.setup.configuration["personal_reviewed_setup"] == .bool(true))
|
||||
}
|
||||
|
||||
private static func assignedMediaProfile(for release: SoftwareLibraryRelease) -> Profile? {
|
||||
guard let name = release.setup.configuration["profile"].string,
|
||||
let profile = Profile(rawValue: name),
|
||||
case .array(let members) = release.setup.selectedMembers,
|
||||
!members.isEmpty, members.count <= 4 else { return false }
|
||||
guard (try? recommendedCartridgeDevice(release.setup.configuration, profile: profile)) != nil else { return false }
|
||||
!members.isEmpty, members.count <= 4 else { return nil }
|
||||
guard (try? recommendedCartridgeDevice(release.setup.configuration, profile: profile)) != nil else { return nil }
|
||||
var targets = Set<String>()
|
||||
for member in members {
|
||||
guard let path = member["path"].string, validRelative(path),
|
||||
let target = member["target"].string, targets.insert(target).inserted else { return false }
|
||||
let target = member["target"].string, targets.insert(target).inserted else { return nil }
|
||||
let ext = (path as NSString).pathExtension.lowercased()
|
||||
switch profile {
|
||||
case .romCartridge:
|
||||
guard members.count == 1, target == "cartridge", ["ccc", "rom"].contains(ext) else { return false }
|
||||
guard members.count == 1, target == "cartridge", ["ccc", "rom"].contains(ext) else { return nil }
|
||||
case .hardDriveBasic:
|
||||
guard (["hard0", "hard1"].contains(target) && ["vhd", "os9", "img"].contains(ext)) ||
|
||||
(["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return nil }
|
||||
case .diskBasic:
|
||||
guard (target == "media" && ["cas", "wav"].contains(ext)) ||
|
||||
(["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return false }
|
||||
(["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return nil }
|
||||
case .cocoSDC:
|
||||
guard ["disk0", "disk1"].contains(target), Self.supportsDisk(ext, profile: profile) else { return false }
|
||||
guard ["disk0", "disk1"].contains(target), Self.supportsDisk(ext, profile: profile) else { return nil }
|
||||
}
|
||||
}
|
||||
return profile == .romCartridge || decodeCommands(release.setup.command)?.contains(where: startsSoftware) == true
|
||||
return profile
|
||||
}
|
||||
|
||||
static func prepare(release: SoftwareLibraryRelease, receipt: SoftwareLibraryInstallationReceipt,
|
||||
@@ -136,9 +154,10 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
let ext = (path as NSString).pathExtension.lowercased()
|
||||
let type: String?
|
||||
switch release.mediaType {
|
||||
case "cartridge": type = ext == "ccc" ? "cartridge" : nil
|
||||
case "cartridge": type = ["ccc", "rom"].contains(ext) ? "cartridge" : nil
|
||||
case "cassette": type = ["cas", "wav"].contains(ext) ? "cassette" : nil
|
||||
case "disk", "sdc": type = Self.supportsDisk(ext, profile: profile) ? "disk" : nil
|
||||
case "hard-disk": type = profile == .hardDriveBasic && ["vhd", "os9", "img"].contains(ext) ? "hard-disk" : nil
|
||||
default: type = nil
|
||||
}
|
||||
return type.map { Candidate(path: path, mediaType: $0) }
|
||||
@@ -150,10 +169,10 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
} else if candidates.count == 1 { choice = candidates[0] }
|
||||
else if !candidates.isEmpty { throw Failure.needsSelection(candidates) }
|
||||
else { throw Failure.unsupported("No supported startup media has been identified for this edition. Open its installed files and use the loading notes to configure it manually.") }
|
||||
selected = [(choice.mediaType == "cartridge" ? "cartridge" : choice.mediaType == "cassette" ? "media" : "disk0", choice.path)]
|
||||
selected = [(choice.mediaType == "cartridge" ? "cartridge" : choice.mediaType == "cassette" ? "media" : choice.mediaType == "hard-disk" ? "hard0" : "disk0", choice.path)]
|
||||
} else if selectedMember != nil { throw Failure.invalidRecipe("This edition already identifies its startup media.") }
|
||||
guard selected.count <= 4, Set(selected.map(\.target)).count == selected.count else { throw Failure.invalidRecipe("Conflicting startup media assignments.") }
|
||||
var floppies: [Int: URL] = [:]
|
||||
guard selected.count <= (release.isPersonal ? 8 : 4), Set(selected.map(\.target)).count == selected.count else { throw Failure.invalidRecipe("Conflicting startup media assignments.") }
|
||||
var floppies: [Int: URL] = [:], hardDisks: [Int: URL] = [:]
|
||||
var cassette: URL?, cartridge: URL?
|
||||
var selectedSDC: [Int: URL] = [:]
|
||||
for member in selected {
|
||||
@@ -166,6 +185,12 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
case "media":
|
||||
guard profile == .diskBasic, ["cas", "wav"].contains(ext) else { throw Failure.invalidRecipe("The selected file is not a supported cassette.") }
|
||||
cassette = url
|
||||
case "hard0", "hard1":
|
||||
guard profile == .hardDriveBasic, ["vhd", "os9", "img"].contains(ext), let drive = Int(member.target.suffix(1)) else {
|
||||
throw Failure.invalidRecipe("Choose a supported raw hard-disk image for HD0 or HD1.")
|
||||
}
|
||||
_ = try HardDiskFiles.readImage(url)
|
||||
hardDisks[drive] = url
|
||||
case "disk0", "disk1", "disk2", "disk3":
|
||||
guard Self.supportsDisk(ext, profile: profile),
|
||||
let drive = Int(member.target.suffix(1)) else { throw Failure.invalidRecipe("Unsupported disk assignment.") }
|
||||
@@ -197,7 +222,8 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
}
|
||||
let decoded = members.isEmpty ? nil : decodeCommands(release.setup.command)
|
||||
let canStart = cartridge != nil || (decoded?.contains(where: startsSoftware) == true)
|
||||
var commands = canStart ? (decoded ?? []) : []
|
||||
let offersPlay = canStart || Self.hasPlayAction(for: release)
|
||||
var commands = offersPlay ? (decoded ?? []) : []
|
||||
// Mounting an image is separate from executing its program. Manual SDC
|
||||
// editions still get their chosen image mounted before guidance appears.
|
||||
if sdcFolder != nil {
|
||||
@@ -205,16 +231,16 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
}
|
||||
var instructions = release.setup.instructions.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if instructions.isEmpty { instructions = "The selected media is mounted. Follow its manual or directory listing to choose a program; no startup command has been established." }
|
||||
if !canStart, let command = release.setup.command, !command.isEmpty {
|
||||
if !canStart && (!offersPlay || decoded == nil), let command = release.setup.command, !command.isEmpty {
|
||||
instructions += "\n\nThe catalog’s loading sequence needs manual entry. Review it before typing: " + command.replacingOccurrences(of: "\\r", with: " → ")
|
||||
}
|
||||
return Self(workingDirectory: root, canonicalWorkingDirectory: root.resolvingSymlinksInPath(), releaseID: release.id, title: release.metadata["title"].string ?? release.name,
|
||||
profile: profile, use6309: cpu == "6309", ramKiB: ram, ramIndex: ramIndex,
|
||||
videoOutput: video, controllerSlot: slot, cartridgeDevice: cartridgeDevice, floppyURLs: floppies, cassetteURL: cassette,
|
||||
videoOutput: video, controllerSlot: slot, cartridgeDevice: cartridgeDevice, floppyURLs: floppies, hardDiskURLs: hardDisks, cassetteURL: cassette,
|
||||
cartridgeURL: cartridge, sdcFolderURL: sdcFolder, sdcInitialImages: sdcNames,
|
||||
commands: commands, manualInstructions: instructions,
|
||||
compatibilityNotes: release.setup.compatibilityNotes + release.setup.configurationRequirements,
|
||||
automaticallyStarts: canStart, controls: release.setup.controls,
|
||||
automaticallyStarts: canStart, offersPlay: offersPlay, controls: release.setup.controls,
|
||||
curatedStartup: release.ownedGame.flatMap { $0.firstPlayColdDOS ? $0 : nil })
|
||||
}
|
||||
|
||||
@@ -241,7 +267,7 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
throw Failure.invalidRecipe("The original game disk no longer matches its verified startup recipe. Your working files are kept.")
|
||||
}
|
||||
}
|
||||
for url in Array(floppyURLs.values) + [cassetteURL, cartridgeURL].compactMap({ $0 }) {
|
||||
for url in Array(floppyURLs.values) + Array(hardDiskURLs.values) + [cassetteURL, cartridgeURL].compactMap({ $0 }) {
|
||||
guard url.path.hasPrefix(workingDirectory.path + "/") else { throw Failure.unsafeMedia(url.lastPathComponent) }
|
||||
_ = try Self.file(String(url.path.dropFirst(workingDirectory.path.count + 1)), root: workingDirectory)
|
||||
}
|
||||
@@ -323,8 +349,14 @@ struct SoftwareLibraryLaunchPlan: Sendable {
|
||||
guard let parts = statements(line) else { return false }
|
||||
let number = "(?:[0-9]+|&H[0-9A-F]+)"
|
||||
let filename = "\\\"[^\\\"\\\\]{1,64}\\\""
|
||||
// Disk BASIC's ordinary LOAD replaces the BASIC program and discards
|
||||
// the rest of that command line. RUN must be delivered on a new line.
|
||||
let programLoad = "LOAD *" + filename
|
||||
guard !parts.dropLast().contains(where: {
|
||||
$0.range(of: "^(?:" + programLoad + ")$", options: [.regularExpression, .caseInsensitive]) != nil
|
||||
}) else { return false }
|
||||
let patterns = ["(?:CLOADM?|RUN)(?: *" + filename + ")?", "LOADM *" + filename,
|
||||
"LOAD *" + filename + " *, *R", "LOAD +CHR\\$\\(42\\) *, *R",
|
||||
programLoad + "(?: *, *R)?", "LOAD +CHR\\$\\(42\\) *, *R",
|
||||
"EXEC(?: *" + number + ")?", "DOS(?: +[0-9]+)?", "DIR(?: +[0-3])?",
|
||||
"PCLEAR *[0-9]+", "CLEAR *" + number + "(?: *, *" + number + ")?",
|
||||
"POKE *" + number + " *, *" + number, "NEW"]
|
||||
|
||||
@@ -10,13 +10,14 @@ struct SoftwareLibraryLaunchPreviewView: View {
|
||||
private var setupName: String {
|
||||
switch plan.profile {
|
||||
case .diskBasic: return "Disk BASIC"
|
||||
case .hardDriveBasic: return "Hard-drive BASIC"
|
||||
case .romCartridge: return plan.cartridgeDevice == .orchestra90 ? "Orchestra-90" : "ROM Cartridge"
|
||||
case .cocoSDC: return "CoCo SDC"
|
||||
}
|
||||
}
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Label(plan.automaticallyStarts ? "Start Software" : "Set Up Software", systemImage: "play.rectangle")
|
||||
Label(plan.automaticallyStarts ? "Start Software" : plan.offersPlay ? "Play Software" : "Set Up Software", systemImage: "play.rectangle")
|
||||
.font(.title2.weight(.semibold))
|
||||
Text(plan.title).font(.title3.weight(.medium))
|
||||
ScrollView {
|
||||
@@ -42,14 +43,24 @@ struct SoftwareLibraryLaunchPreviewView: View {
|
||||
ForEach(plan.floppyURLs.keys.sorted(), id: \.self) { drive in
|
||||
LabeledContent("FD\(drive)", value: plan.floppyURLs[drive]!.lastPathComponent)
|
||||
}
|
||||
ForEach(plan.hardDiskURLs.keys.sorted(), id: \.self) { drive in
|
||||
LabeledContent("HD\(drive)", value: plan.hardDiskURLs[drive]!.lastPathComponent)
|
||||
}
|
||||
if let folder = plan.sdcFolderURL { Label("SD card folder: " + folder.lastPathComponent, systemImage: "sdcard") }
|
||||
if !plan.compatibilityNotes.isEmpty {
|
||||
Text(plan.compatibilityNotes.joined(separator: "\n\n")).font(.callout).foregroundStyle(.secondary)
|
||||
}
|
||||
if !plan.automaticallyStarts {
|
||||
Label("Manual loading", systemImage: "keyboard").font(.headline)
|
||||
if plan.offersPlay {
|
||||
Text(plan.commands.isEmpty
|
||||
? "The CoCo will run with the selected media mounted. Load the program yourself; no loading commands will be typed automatically."
|
||||
: "The CoCo will run with the selected media mounted and enter the commands below. Start the program yourself if those commands do not run it.")
|
||||
.font(.callout)
|
||||
}
|
||||
Text(plan.manualInstructions).font(.callout).textSelection(.enabled)
|
||||
} else if !plan.commands.isEmpty {
|
||||
}
|
||||
if !plan.commands.isEmpty {
|
||||
DisclosureGroup("Loading commands") {
|
||||
Text(plan.commands.joined(separator: "\n")).font(.system(.callout, design: .monospaced)).textSelection(.enabled)
|
||||
}
|
||||
@@ -64,7 +75,7 @@ struct SoftwareLibraryLaunchPreviewView: View {
|
||||
HStack {
|
||||
Button("Cancel", role: .cancel, action: cancel).keyboardShortcut(.cancelAction).accessibilityIdentifier("library-cancel-play")
|
||||
Spacer()
|
||||
Button(plan.automaticallyStarts ? "Start" : "Set Up", action: confirm)
|
||||
Button(plan.automaticallyStarts ? "Start" : plan.offersPlay ? "Play" : "Set Up", action: confirm)
|
||||
.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).accessibilityIdentifier("library-confirm-play")
|
||||
}
|
||||
}.padding(24).frame(width: 490)
|
||||
@@ -98,3 +109,33 @@ struct SoftwareLibraryMediaChoiceView: View {
|
||||
}.padding(24).frame(width: 520)
|
||||
}
|
||||
}
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
struct SoftwareLibraryPersonalPresentation: ViewModifier {
|
||||
@ObservedObject var model: SoftwareLibraryModel
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.sheet(item: $model.personalEditor, onDismiss: { model.cancelPersonalEdit() }) { entry in
|
||||
PersonalSoftwareEditor(entry: entry, unsupported: model.personalUnsupported, isImport: model.isPersonalImport,
|
||||
saving: model.personalSaving, error: model.personalError, duplicateID: model.personalDuplicateID,
|
||||
save: { model.savePersonal($0, coverPNG: $1, allowDuplicate: $2) }, openExisting: model.openExistingPersonal,
|
||||
previewCover: model.personalCoverPreview,
|
||||
cancel: model.cancelPersonalEdit)
|
||||
}
|
||||
.safeAreaInset(edge: .bottom) {
|
||||
if model.personalInspecting {
|
||||
HStack { ProgressView().controlSize(.small); Text("Preparing a private import preview…"); Spacer(); Button("Cancel", role: .cancel) { model.cancelPersonalInspection() } }.padding(10)
|
||||
} else if model.personalEditor == nil, let error = model.personalError {
|
||||
Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange)
|
||||
.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(10)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
import SwiftUI
|
||||
struct SoftwareLibraryPersonalPresentation: ViewModifier {
|
||||
let model: SoftwareLibraryModel
|
||||
func body(content: Content) -> some View { content }
|
||||
}
|
||||
#endif
|
||||
@@ -105,8 +105,15 @@ final class SoftwareLibraryManualModel: ObservableObject {
|
||||
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 {
|
||||
@@ -124,11 +131,16 @@ final class SoftwareLibraryManualModel: ObservableObject {
|
||||
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 == "txt" {
|
||||
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)
|
||||
@@ -142,7 +154,7 @@ final class SoftwareLibraryManualModel: ObservableObject {
|
||||
catch { self.error = error.localizedDescription; loading = false }
|
||||
}
|
||||
}
|
||||
func cancel() { task?.cancel(); 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 }
|
||||
@@ -156,6 +168,70 @@ final class SoftwareLibraryManualModel: ObservableObject {
|
||||
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 {
|
||||
@@ -192,10 +268,10 @@ struct SoftwareLibraryManualView: View {
|
||||
if model.document != nil {
|
||||
HStack(spacing: 0) {
|
||||
if showPages { ManualPages(view: model.pdfView).frame(width: 115) }
|
||||
ManualPDF(view: model.pdfView).accessibilityIdentifier("manual-pdf")
|
||||
ManualPDF(view: model.pdfView).accessibilityIdentifier("manual-pdf").onAppear { model.restoreReadingPosition() }
|
||||
}
|
||||
} else if model.text != nil {
|
||||
ManualText(view: model.textView).accessibilityIdentifier("manual-text")
|
||||
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 {
|
||||
@@ -211,12 +287,14 @@ struct SoftwareLibraryManualView: View {
|
||||
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) }
|
||||
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() }
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
/// Native review stays attached to its window and cannot strand shutdown on a
|
||||
@@ -49,9 +50,9 @@ struct LibraryCategory: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
struct LibraryBrowseQuery: Equatable, Sendable {
|
||||
enum Scope: String, CaseIterable { case showcase, started, all, favorites, installed }
|
||||
enum Sort: String, CaseIterable { case title = "Title", modified = "Last Modified", size = "Download Size" }
|
||||
struct LibraryBrowseQuery: Equatable, Sendable, Codable {
|
||||
enum Scope: String, CaseIterable, Codable { case showcase, started, all, favorites, installed, personal, search }
|
||||
enum Sort: String, CaseIterable, Codable { case title = "Title", modified = "Last Modified", size = "Download Size" }
|
||||
var scope: Scope = .started
|
||||
var text = ""
|
||||
var category = ""
|
||||
@@ -129,6 +130,11 @@ struct LibraryBrowseQuery: Equatable, Sendable {
|
||||
}
|
||||
func apply(to titles: [SoftwareLibraryTitle], favorites: Set<String>, installed: Set<String>) -> [LibraryBrowseRow] {
|
||||
var rows = titles.compactMap { title -> LibraryBrowseRow? in
|
||||
let personal = title.id.hasPrefix("personal:")
|
||||
if scope == .personal && !personal { return nil }
|
||||
// Getting Started and Cover Collection remain curated catalog
|
||||
// views. General browsing/search can combine local and public data.
|
||||
if personal && (scope == .started || scope == .showcase || scope == .installed) { return nil }
|
||||
if scope == .favorites && !favorites.contains(title.id) { return nil }
|
||||
let matches = title.releases.filter {
|
||||
(scope != .started || Self.isGettingStarted($0)) &&
|
||||
@@ -139,11 +145,12 @@ struct LibraryBrowseQuery: Equatable, Sendable {
|
||||
return LibraryBrowseRow(title: title, matchingReleases: matches)
|
||||
}
|
||||
rows.sort { a, b in
|
||||
if a.isPersonal != b.isPersonal { return a.isPersonal }
|
||||
let featuredGrouping = !category.isEmpty || !softwareType.isEmpty
|
||||
let aFeatured = featuredGrouping && a.categoryFeatured
|
||||
let bFeatured = featuredGrouping && b.categoryFeatured
|
||||
if aFeatured != bFeatured { return aFeatured }
|
||||
switch aFeatured ? .title : sort {
|
||||
switch a.isPersonal || aFeatured ? .title : sort {
|
||||
case .modified:
|
||||
let av = a.matchingReleases.compactMap(\.modifiedAt).max() ?? ""
|
||||
let bv = b.matchingReleases.compactMap(\.modifiedAt).max() ?? ""
|
||||
@@ -164,6 +171,7 @@ struct LibraryBrowseRow: Identifiable, Sendable {
|
||||
let title: SoftwareLibraryTitle
|
||||
let matchingReleases: [SoftwareLibraryRelease]
|
||||
var id: String { title.id }
|
||||
var isPersonal: Bool { title.id.hasPrefix("personal:") && matchingReleases.contains(where: \.isPersonal) }
|
||||
var name: String { title.name }
|
||||
var categoryFeatured: Bool { matchingReleases.contains(where: \.categoryFeatured) }
|
||||
var formats: String { Set(matchingReleases.map(\.mediaLabel)).sorted().joined(separator: ", ") }
|
||||
@@ -197,14 +205,28 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
@Published private(set) var loading = false
|
||||
@Published private(set) var filtering = false
|
||||
@Published private(set) var error: String?
|
||||
@Published var query = LibraryBrowseQuery() { didSet { if query != oldValue { filter() } } }
|
||||
@Published var selection: String?
|
||||
@Published var layout = "Shelf"
|
||||
@Published var query = LibraryBrowseQuery() { didSet { if query != oldValue { saveBrowseContext(); filter() } } }
|
||||
@Published var selection: String? { didSet { if selection != oldValue { saveBrowseContext() } } }
|
||||
@Published var layout = "Shelf" { didSet { if layout != oldValue { saveBrowseContext() } } }
|
||||
private(set) var browseTopID: String?
|
||||
private(set) var browseOffset: Double = 0
|
||||
private var restoredBrowse = false
|
||||
private var restoringBrowse = false
|
||||
let companionAccess: (any CompanionLibraryAccess)?
|
||||
private let insertCompanionDisk: ((URL) async throws -> Void)?
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
let installer: SoftwareLibraryInstaller
|
||||
let machine: MachineModel?
|
||||
private let browseContinuity: LibraryContinuityStore
|
||||
lazy var personalStore = PersonalSoftwareLibraryStore(root: state.directory.appendingPathComponent("PersonalLibrary", isDirectory: true))
|
||||
@Published private(set) var personalEntries: [PersonalSoftwareEntry] = []
|
||||
@Published var personalEditor: PersonalSoftwareEntry?
|
||||
@Published private(set) var personalInspecting = false
|
||||
@Published private(set) var personalSaving = false
|
||||
@Published private(set) var personalError: String?
|
||||
@Published private(set) var personalDuplicateID: UUID?
|
||||
private var personalDraft: PersonalSoftwareDraft?
|
||||
private var personalTask: Task<Void, Never>?
|
||||
private let sourceImporter: SoftwareLibrarySourceImporter
|
||||
private let sourceWorkspaceIdentity: (() -> UUID)?
|
||||
private let openSourceProject: ((URL, UUID, String?) async throws -> Bool)?
|
||||
@@ -239,11 +261,13 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
private var generation = 0
|
||||
private var subscriptions: Set<AnyCancellable> = []
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
init(state: SoftwareLibraryState, artworkDirectory: URL? = nil, machine: MachineModel? = nil,
|
||||
init(state: SoftwareLibraryState, continuity: LibraryContinuityStore? = nil, artworkDirectory: URL? = nil, machine: MachineModel? = nil,
|
||||
sourceWorkspaceIdentity: (() -> UUID)? = nil,
|
||||
openSourceProject: ((URL, UUID, String?) async throws -> Bool)? = nil) {
|
||||
companionAccess = nil; insertCompanionDisk = nil
|
||||
self.state = state
|
||||
browseContinuity = continuity ?? LibraryContinuityStore(directory: state.directory)
|
||||
manual.continuity = browseContinuity
|
||||
self.machine = machine
|
||||
self.sourceWorkspaceIdentity = sourceWorkspaceIdentity; self.openSourceProject = openSourceProject
|
||||
#if VCC_UI_TESTING
|
||||
@@ -277,6 +301,7 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
state = SoftwareLibraryState(companion: companion)
|
||||
artworkDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCompanionPresentation")
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
browseContinuity = LibraryContinuityStore(directory: state.directory)
|
||||
machine = nil; installer = SoftwareLibraryInstaller(root: state.directory)
|
||||
sourceWorkspaceIdentity = nil; openSourceProject = nil
|
||||
sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages"))
|
||||
@@ -373,7 +398,7 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
if isDiskCompanion { return installed ? "Insert Disk…" : "Download & Insert…" }
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if release.ownedGame?.firstPlayColdDOS == true { return installed ? "Play" : "Download & Play" }
|
||||
return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release)
|
||||
return SoftwareLibraryLaunchPlan.hasPlayAction(for: release)
|
||||
? (installed ? "Play…" : "Download & Play…") : (installed ? "Set Up…" : "Download & Set Up…")
|
||||
#else
|
||||
return "Insert Disk…"
|
||||
@@ -382,7 +407,7 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
func launchSymbol(_ release: SoftwareLibraryRelease) -> String {
|
||||
if isDiskCompanion { return "externaldrive" }
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release) ? "play.fill" : "desktopcomputer"
|
||||
return SoftwareLibraryLaunchPlan.hasPlayAction(for: release) ? "play.fill" : "desktopcomputer"
|
||||
#else
|
||||
return "externaldrive"
|
||||
#endif
|
||||
@@ -392,11 +417,17 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
machine?.focusDisplay()
|
||||
#endif
|
||||
}
|
||||
func load(from url: URL? = SoftwareLibraryCatalog.bundledURL()) async {
|
||||
func load(from url: URL? = SoftwareLibraryCatalog.bundledURL(),
|
||||
catalogLoader: @Sendable (URL) async throws -> SoftwareLibraryCatalog = { try await SoftwareLibraryCatalog.load(from: $0) }) async {
|
||||
guard catalog == nil, !loading else { return }
|
||||
// Restoration may schedule a filter before recovered installations,
|
||||
// private entries or the catalog arrive. Reconcile selection only once
|
||||
// that complete initial result is available, preserving newer user input.
|
||||
loading = true; error = nil
|
||||
restoreBrowseContext()
|
||||
defer { loading = false; filter() }
|
||||
if let companionAccess {
|
||||
defer { loading = false; recoveringInstallations = false }
|
||||
defer { recoveringInstallations = false }
|
||||
do {
|
||||
let response = try await companionAccess.libraryRequest(.init(operation: .snapshot))
|
||||
try acceptCompanion(response)
|
||||
@@ -406,21 +437,21 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
}
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
await refreshInstallations()
|
||||
await refreshPersonalEntries()
|
||||
#if VCC_UI_TESTING
|
||||
if SoftwareLibraryInstallFixture.enabled {
|
||||
catalog = SoftwareLibraryInstallFixture.catalog
|
||||
categories = LibraryCategory.tree(catalog!.categories)
|
||||
updateSoftwareTypes(catalog!)
|
||||
query.scope = .all
|
||||
filter(); loading = false; return
|
||||
filter(); return
|
||||
}
|
||||
#endif
|
||||
do {
|
||||
guard let url else { throw SoftwareLibraryCatalog.Failure.missing }
|
||||
let snapshot = try await SoftwareLibraryCatalog.load(from: url)
|
||||
let snapshot = try await catalogLoader(url)
|
||||
catalog = snapshot; categories = LibraryCategory.tree(snapshot.categories); updateSoftwareTypes(snapshot); filter()
|
||||
} catch { self.error = error.localizedDescription }
|
||||
loading = false
|
||||
#endif
|
||||
}
|
||||
private func acceptCompanion(_ response: CompanionLibraryResponse) throws {
|
||||
@@ -464,8 +495,25 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
next.scope = scope; next.category = category; next.softwareType = ""
|
||||
query = next
|
||||
}
|
||||
private func updateSoftwareTypes(_ catalog: SoftwareLibraryCatalog) {
|
||||
softwareTypes = Array(Set(catalog.titles.flatMap { title in title.releases.flatMap { LibraryBrowseQuery.types(of: $0, related: title.releases) } })).sorted()
|
||||
/// The header is a global search entry point, not an implicit filter of
|
||||
/// whichever narrow collection happened to be selected before typing.
|
||||
func setSearchText(_ text: String) {
|
||||
guard text != query.text else { return }
|
||||
if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && query.scope != .search {
|
||||
query = LibraryBrowseQuery(scope: .search, text: text, sort: query.sort)
|
||||
} else {
|
||||
var next = query
|
||||
next.text = text
|
||||
if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, next.scope == .search { next.scope = .all }
|
||||
query = next
|
||||
}
|
||||
}
|
||||
private func updateSoftwareTypes(_ catalog: SoftwareLibraryCatalog?) {
|
||||
var types = Set(catalog?.titles.flatMap { title in title.releases.flatMap { LibraryBrowseQuery.types(of: $0, related: title.releases) } } ?? [])
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if !isDiskCompanion { types.formUnion(personalEntries.map { PersonalSoftwareEntry.standardCategory($0.category) }) }
|
||||
#endif
|
||||
softwareTypes = types.sorted()
|
||||
}
|
||||
func browseType(_ type: String) {
|
||||
var next = query
|
||||
@@ -479,6 +527,13 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
query = next
|
||||
}
|
||||
func install(_ release: SoftwareLibraryRelease, playAfter: Bool = false) {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if release.isPersonal && !isDiskCompanion {
|
||||
guard playAfter, let entry = personalEntries.first(where: { $0.releaseID == release.id }), !launchBusy, !hasPendingLaunch else { return }
|
||||
personalTask = Task { await prepareLaunch(release, receipt: entry.receipt(in: await personalStore.directory(for: entry.id))) }
|
||||
return
|
||||
}
|
||||
#endif
|
||||
guard installingReleaseID == nil, !recoveringInstallations, !launchBusy, !hasPendingLaunch else { return }
|
||||
if companionAccess != nil { installCompanion(release, insertAfter: playAfter); return }
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
@@ -510,6 +565,10 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
func shutdown() async {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
personalTask?.cancel(); await personalTask?.value
|
||||
if let draft = personalDraft { await personalStore.cancel(draft.id) }
|
||||
#endif
|
||||
sourceImportTask?.cancel()
|
||||
await sourceImportTask?.value
|
||||
launchTask?.cancel()
|
||||
@@ -517,8 +576,14 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
cancelInstallation()
|
||||
await installationTask?.value
|
||||
await state.flush()
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
await browseContinuity.flush()
|
||||
#endif
|
||||
}
|
||||
func removeInstallation(_ id: String) async {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if let entry = personalEntries.first(where: { $0.releaseID == id }) { removePersonal(entry); return }
|
||||
#endif
|
||||
guard installingReleaseID == nil, !launchBusy, !hasPendingLaunch else { return }
|
||||
if let companionAccess {
|
||||
do { try acceptCompanion(try await companionAccess.libraryRequest(.init(operation: .removeInstallation, releaseID: id))) }
|
||||
@@ -687,19 +752,212 @@ final class SoftwareLibraryModel: ObservableObject {
|
||||
launchMessage = "The disk is inserted. Follow the loading instructions on your CoCo."
|
||||
} catch { if !Task.isCancelled { launchError = error.localizedDescription } }
|
||||
}
|
||||
/// A presentation/permissioned-local-connection snapshot. The prepared
|
||||
/// public catalog remains unchanged; private entries keep separate IDs.
|
||||
var combinedCatalog: SoftwareLibraryCatalog {
|
||||
var titles = catalog?.titles ?? []
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if !isDiskCompanion {
|
||||
titles += personalEntries.map { entry in
|
||||
let directory = personalDirectory(entry)
|
||||
return SoftwareLibraryTitle(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [entry.release(in: directory)])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return SoftwareLibraryCatalog(titles: titles, metadata: catalog?.metadata ?? [:])
|
||||
}
|
||||
private func filter() {
|
||||
guard let catalog else { return }
|
||||
let titles = combinedCatalog.titles
|
||||
task?.cancel(); generation += 1; let version = generation
|
||||
let query = query, favorites = state.favoriteTitleIDs, installed = Set(state.installedReleases.keys)
|
||||
let sourceTitles = titles
|
||||
filtering = true
|
||||
task = Task {
|
||||
// Debounce typing without blocking the machine's UI or audio queues.
|
||||
do { try await Task.sleep(nanoseconds: 90_000_000) } catch { return }
|
||||
let worker = Task.detached(priority: .userInitiated) { query.apply(to: catalog.titles, favorites: favorites, installed: installed) }
|
||||
let worker = Task.detached(priority: .userInitiated) { query.apply(to: sourceTitles, favorites: favorites, installed: installed) }
|
||||
let result = await worker.value
|
||||
guard !Task.isCancelled, version == generation else { return }
|
||||
rows = result; filtering = false
|
||||
if !rows.contains(where: { $0.id == selection }) { selection = rows.first?.id }
|
||||
// A failed public-catalog read is not evidence that a saved public
|
||||
// title disappeared. Keep it pending for Retry; private-only browsing
|
||||
// can still reconcile against the successfully recovered local set.
|
||||
let selectionDomainAvailable = catalog != nil || query.scope == .personal ||
|
||||
selection?.hasPrefix("personal:") == true || (selection == nil && !rows.isEmpty)
|
||||
if !loading, selectionDomainAvailable, !rows.contains(where: { $0.id == selection }) { selection = rows.first?.id }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
extension SoftwareLibraryModel {
|
||||
var personalUnsupported: [String] { personalDraft?.unsupported ?? [] }
|
||||
var isPersonalImport: Bool { personalDraft != nil }
|
||||
var canEditPersonal: Bool { !isDiskCompanion && !personalInspecting && !personalSaving }
|
||||
var selectedPersonalEntry: PersonalSoftwareEntry? { personalEntries.first { $0.titleID == selection } }
|
||||
func choosePersonalSoftware() {
|
||||
guard canEditPersonal, personalEditor == nil else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.title = "Add Personal Software"; panel.prompt = "Review Files"
|
||||
// The native panel sizes its message horizontally. Keep each line short
|
||||
// so guidance does not force an excessively wide file chooser.
|
||||
panel.message = "Choose a folder, ZIP, or CoCo media files.\nOriginals stay untouched. Nothing is uploaded or run."
|
||||
panel.canChooseFiles = true; panel.canChooseDirectories = true; panel.allowsMultipleSelection = true
|
||||
panel.begin { [weak self] response in
|
||||
guard response == .OK, !panel.urls.isEmpty, let self else { return }
|
||||
self.personalInspecting = true; self.personalError = nil
|
||||
self.personalTask = Task {
|
||||
defer { self.personalInspecting = false; self.personalTask = nil }
|
||||
do {
|
||||
let draft = try await self.personalStore.inspect(panel.urls)
|
||||
if Task.isCancelled { await self.personalStore.cancel(draft.id); throw CancellationError() }
|
||||
self.personalDraft = draft; self.personalEditor = draft.entry; self.personalDuplicateID = nil
|
||||
} catch is CancellationError { }
|
||||
catch { self.personalError = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
func cancelPersonalInspection() { if personalInspecting { personalTask?.cancel() } }
|
||||
func editPersonal(_ entry: PersonalSoftwareEntry) {
|
||||
guard canEditPersonal, personalEditor == nil else { return }
|
||||
personalDraft = nil; personalError = nil; personalDuplicateID = nil; personalEditor = entry
|
||||
}
|
||||
func savePersonal(_ entry: PersonalSoftwareEntry, coverPNG: Data? = nil, allowDuplicate: Bool) {
|
||||
guard !personalSaving else { return }
|
||||
personalSaving = true; personalError = nil; personalDuplicateID = nil
|
||||
personalTask = Task {
|
||||
defer { personalSaving = false; personalTask = nil }
|
||||
do {
|
||||
if var draft = personalDraft {
|
||||
draft.entry = entry
|
||||
_ = try await personalStore.save(draft, allowDuplicate: allowDuplicate, coverPNG: coverPNG)
|
||||
} else { try await personalStore.update(entry, coverPNG: coverPNG) }
|
||||
personalDraft = nil; personalEditor = nil
|
||||
await refreshPersonalEntries()
|
||||
query = LibraryBrowseQuery(scope: .personal); selection = entry.titleID
|
||||
installationNotice = "Your personal software is saved privately on this Mac. The CoCo has not been changed."
|
||||
} catch PersonalSoftwareLibraryStore.Failure.duplicate(let id) {
|
||||
personalDuplicateID = id
|
||||
personalError = PersonalSoftwareLibraryStore.Failure.duplicate(id).localizedDescription
|
||||
} catch { personalError = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
func cancelPersonalEdit() {
|
||||
guard !personalSaving else { return }
|
||||
let draft = personalDraft; personalEditor = nil; personalDraft = nil; personalDuplicateID = nil; personalError = nil
|
||||
if let draft { Task { await personalStore.cancel(draft.id) } }
|
||||
}
|
||||
func openExistingPersonal(_ id: UUID) {
|
||||
cancelPersonalEdit(); query = LibraryBrowseQuery(scope: .personal); selection = "personal:" + id.uuidString.lowercased()
|
||||
}
|
||||
func removePersonal(_ entry: PersonalSoftwareEntry) {
|
||||
guard !personalSaving else { return }
|
||||
personalTask = Task {
|
||||
do {
|
||||
var hidden = entry; hidden.hidden = true
|
||||
try await personalStore.update(hidden); await refreshPersonalEntries()
|
||||
installationNotice = "Removed from Personal Library. Original and working files are retained on this Mac; no space was reclaimed."
|
||||
} catch { personalError = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
func personalDirectory(_ entry: PersonalSoftwareEntry) -> URL {
|
||||
state.directory.appendingPathComponent("PersonalLibrary").appendingPathComponent(entry.id.uuidString.lowercased())
|
||||
}
|
||||
func personalCoverPreview(_ entry: PersonalSoftwareEntry) async throws -> Data? {
|
||||
let draftID = personalDraft?.entry.id == entry.id ? personalDraft?.id : nil
|
||||
return try await personalStore.previewCover(entry, draftID: draftID)
|
||||
}
|
||||
func choosePersonalCover(for entry: PersonalSoftwareEntry) {
|
||||
guard canEditPersonal, personalEditor == nil else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.title = "Choose Cover Image"; panel.prompt = "Use Image"
|
||||
panel.message = "Choose an image for this personal entry. Nothing is uploaded."
|
||||
panel.allowedContentTypes = [.image]
|
||||
panel.canChooseDirectories = false; panel.allowsMultipleSelection = false
|
||||
panel.begin { [weak self] response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
self?.replacePersonalCover(from: url, for: entry)
|
||||
}
|
||||
}
|
||||
func acceptPersonalCoverDrop(_ urls: [URL], for entry: PersonalSoftwareEntry) -> Bool {
|
||||
guard urls.count == 1, let url = urls.first, url.isFileURL,
|
||||
canEditPersonal, personalEditor == nil else { return false }
|
||||
replacePersonalCover(from: url, for: entry)
|
||||
return true
|
||||
}
|
||||
func selectPersonalCover(_ choice: PersonalSoftwareEntry.CoverChoice, for entry: PersonalSoftwareEntry) {
|
||||
changePersonalCover(entry, choice: choice, source: nil)
|
||||
}
|
||||
private func replacePersonalCover(from url: URL, for entry: PersonalSoftwareEntry) {
|
||||
changePersonalCover(entry, choice: nil, source: url)
|
||||
}
|
||||
private func changePersonalCover(_ entry: PersonalSoftwareEntry,
|
||||
choice: PersonalSoftwareEntry.CoverChoice?, source: URL?) {
|
||||
guard canEditPersonal, personalEditor == nil, selectedPersonalEntry?.id == entry.id else { return }
|
||||
personalSaving = true; personalError = nil
|
||||
personalTask = Task {
|
||||
defer { personalSaving = false; personalTask = nil }
|
||||
do {
|
||||
let png: Data?
|
||||
if let source {
|
||||
let worker = Task.detached(priority: .userInitiated) { try PersonalCoverImage.prepare(source) }
|
||||
png = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() }
|
||||
} else { png = nil }
|
||||
try Task.checkCancellation()
|
||||
guard selectedPersonalEntry?.id == entry.id,
|
||||
personalEntries.first(where: { $0.id == entry.id })?.updatedAt == entry.updatedAt else {
|
||||
throw PersonalSoftwareLibraryStore.Failure.invalid("The selected personal entry changed. Choose its cover again.")
|
||||
}
|
||||
var edited = entry
|
||||
if let choice { edited.cover = choice }
|
||||
try await personalStore.update(edited, coverPNG: png)
|
||||
await refreshPersonalEntries()
|
||||
installationNotice = "Cover image updated privately on this Mac. Your software and saved games are unchanged."
|
||||
} catch is CancellationError { }
|
||||
catch { personalError = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private func refreshPersonalEntries() async {
|
||||
do {
|
||||
personalEntries = try await personalStore.entries()
|
||||
updateSoftwareTypes(catalog)
|
||||
let warnings = await personalStore.warnings
|
||||
personalError = warnings.isEmpty ? nil : warnings.joined(separator: "\n")
|
||||
filter()
|
||||
}
|
||||
catch { personalError = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
extension SoftwareLibraryModel {
|
||||
func restoreBrowseContext() {
|
||||
guard !restoredBrowse else { return }
|
||||
restoredBrowse = true
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
guard !isDiskCompanion, let saved = browseContinuity.browse(for: "software-main"),
|
||||
let encoded = saved.filters["browse-query"], let data = encoded.data(using: .utf8),
|
||||
let restored = try? JSONDecoder().decode(LibraryBrowseQuery.self, from: data) else { return }
|
||||
restoringBrowse = true
|
||||
query = restored; selection = saved.selectedID
|
||||
layout = saved.filters["layout"] == "Table" ? "Table" : "Shelf"
|
||||
browseTopID = saved.topVisibleID; browseOffset = saved.offset
|
||||
restoringBrowse = false
|
||||
#endif
|
||||
}
|
||||
func saveBrowseContext() {
|
||||
guard restoredBrowse, !restoringBrowse else { return }
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
guard !isDiskCompanion, let encoded = try? JSONEncoder().encode(query), let json = String(data: encoded, encoding: .utf8) else { return }
|
||||
browseContinuity.setBrowse(.init(scope: query.scope.rawValue, query: query.text,
|
||||
filters: ["browse-query": json, "layout": layout], selectedID: selection,
|
||||
selectedEditionID: selectedRelease?.id, topVisibleID: browseTopID, offset: browseOffset), for: "software-main")
|
||||
#endif
|
||||
}
|
||||
func rememberBrowsePosition(id: String?, offset: Double) {
|
||||
guard browseTopID != id || abs(browseOffset - offset) > 0.01 else { return }
|
||||
browseTopID = id; browseOffset = max(0, min(offset.isFinite ? offset : 0, 1))
|
||||
saveBrowseContext()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Darwin
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// Private user data, separate from the prepared public catalog. Matching local
|
||||
/// companion clients may request verified disk entries and supporting assets.
|
||||
struct PersonalSoftwareEntry: Codable, Identifiable, Sendable {
|
||||
struct CoverFile: Codable, Equatable, Sendable {
|
||||
let path: String
|
||||
let sha256: String
|
||||
let byteSize: Int64
|
||||
}
|
||||
enum CoverChoice: Codable, Equatable, Sendable {
|
||||
case imported(String)
|
||||
case custom(CoverFile)
|
||||
case categoryIcon
|
||||
}
|
||||
static let standardCategories = SoftwareLibraryOwnedGame.categoryNames.sorted()
|
||||
static func standardCategory(_ value: String) -> String {
|
||||
standardCategories.contains(value) ? value : "Other"
|
||||
}
|
||||
struct File: Codable, Identifiable, Sendable {
|
||||
let path: String
|
||||
var kind: String
|
||||
let byteSize: Int64
|
||||
let sha256: String
|
||||
var id: String { path }
|
||||
var isMedia: Bool { ["disk", "hard-disk", "cassette", "cartridge", "binary"].contains(kind) }
|
||||
var role: String = ""
|
||||
}
|
||||
var schemaVersion = 1
|
||||
let id: UUID
|
||||
var title: String
|
||||
var author = ""
|
||||
var softwareVersion = ""
|
||||
var category = "Other"
|
||||
var notes = ""
|
||||
var profile = "disk-basic"
|
||||
var processor = "6809"
|
||||
var ramKiB = 512
|
||||
var video = "composite"
|
||||
var command = ""
|
||||
var configured = false
|
||||
var hidden = false
|
||||
var createdAt = Date()
|
||||
var updatedAt = Date()
|
||||
var files: [File]
|
||||
var sourcePackageSHA256: String? = nil
|
||||
var sourcePackageBytes: Int64? = nil
|
||||
// Older entries retain their first imported cover until explicitly changed.
|
||||
var cover: CoverChoice? = nil
|
||||
var selectedCoverFile: CoverFile? {
|
||||
switch cover {
|
||||
case .custom(let file): return file
|
||||
case .categoryIcon: return nil
|
||||
case .imported(let path):
|
||||
return files.first { $0.kind == "cover" && $0.path == path }.map { .init(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) }
|
||||
case nil:
|
||||
return files.first { $0.kind == "cover" }.map { .init(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) }
|
||||
}
|
||||
}
|
||||
var titleID: String { "personal:" + id.uuidString.lowercased() }
|
||||
var releaseID: String { titleID + ":edition" }
|
||||
var packageSHA256: String {
|
||||
let inventory = files.sorted { $0.path < $1.path }.map { "\($0.path)\n\($0.byteSize)\n\($0.sha256)" }.joined(separator: "\n")
|
||||
return SHA256.hash(data: Data(inventory.utf8)).map { String(format: "%02x", $0) }.joined()
|
||||
}
|
||||
func release(in directory: URL) -> SoftwareLibraryRelease {
|
||||
var configuration: [String: LibraryJSON] = ["profile": .string(profile), "processor": .string(processor),
|
||||
"ram_kib": .number(Double(ramKiB)), "video": .string(video), "personal_reviewed_setup": .bool(configured)]
|
||||
if !configured { configuration["personal_manual_setup"] = .bool(true) }
|
||||
let members = configured ? files.filter { $0.isMedia && !$0.role.isEmpty }.map {
|
||||
LibraryJSON.object(["path": .string($0.path), "target": .string($0.role)])
|
||||
} : []
|
||||
let selected = selectedCoverFile
|
||||
let customCover: Bool
|
||||
if case .custom = cover { customCover = true } else { customCover = false }
|
||||
let supporting = files.filter { $0.kind == "manual" }.map { CoverFile(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) }
|
||||
let assets = (supporting + [selected].compactMap { $0 }).map { file -> SoftwareLibraryAsset in
|
||||
let isCover = selected?.path == file.path
|
||||
let url = directory.appendingPathComponent("Assets").appendingPathComponent(file.path)
|
||||
var asset = SoftwareLibraryAsset(id: titleID + ":asset:" + file.path,
|
||||
name: isCover && customCover ? "Personal Cover Image" : URL(fileURLWithPath: file.path).lastPathComponent,
|
||||
kind: isCover ? "cover" : "manual", sourceURL: url, sha256: file.sha256, byteSize: file.byteSize,
|
||||
credit: author.isEmpty ? "Personal collection — private on this Mac" : author,
|
||||
matchStatus: "personal", matchReason: "Imported by this Mac's user; no public distribution permission inferred.")
|
||||
if !isCover { asset.manualURL = url }
|
||||
else { asset.thumbnailURL = url; asset.thumbnailSHA256 = file.sha256; asset.thumbnailByteSize = file.byteSize }
|
||||
return asset
|
||||
}
|
||||
return SoftwareLibraryRelease(id: releaseID, titleID: titleID, name: softwareVersion.isEmpty ? title : softwareVersion,
|
||||
category: Self.standardCategory(category), mediaType: files.first(where: \.isMedia)?.kind ?? "unknown", contentRole: "software",
|
||||
sourceURL: directory, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil,
|
||||
packageSHA256: packageSHA256, byteSize: files.reduce(0) { $0 + $1.byteSize }, languageStatus: "unknown",
|
||||
metadata: .object(["personal": .bool(true), "title": .string(title), "publisher": .string(author),
|
||||
"personal_version": .string(softwareVersion), "personal_notes": .string(notes), "system": .string("coco3"),
|
||||
"primary_browse_category": .string(Self.standardCategory(category)),
|
||||
"browse_categories": .array([.string(Self.standardCategory(category))])]),
|
||||
setup: .init(status: "manual-setup", command: configured && !command.isEmpty ? command : nil,
|
||||
instructions: notes.isEmpty ? "Private software on this Mac. Review its files and launch setup before running it." : notes,
|
||||
configuration: .object(configuration), selectedMembers: .array(members), reasons: [], validation: .object([:])),
|
||||
assets: assets, downloadURLs: [])
|
||||
}
|
||||
func receipt(in directory: URL) -> SoftwareLibraryInstallationReceipt {
|
||||
.init(releaseID: releaseID, packageSHA256: packageSHA256, installedAt: createdAt,
|
||||
workingDirectory: directory.appendingPathComponent("Working"), relativeFiles: files.map(\.path))
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded local image decoding shared by import previews and persisted cover edits.
|
||||
enum PersonalCoverImage {
|
||||
enum Failure: LocalizedError {
|
||||
case invalid
|
||||
var errorDescription: String? { "Choose a readable image no larger than 8 MiB, with dimensions at most 16,384 pixels and 64 million pixels in total. Existing library files were preserved." }
|
||||
}
|
||||
static func prepare(_ url: URL) throws -> Data {
|
||||
let access = url.startAccessingSecurityScopedResource()
|
||||
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
||||
return try prepare(sourceData(url))
|
||||
}
|
||||
fileprivate static func sourceData(_ url: URL) throws -> Data {
|
||||
guard url.isFileURL, url.host == nil || url.host == "localhost", url.query == nil, url.fragment == nil else { throw Failure.invalid }
|
||||
let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard fd >= 0 else { throw Failure.invalid }
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var before = stat(), after = stat()
|
||||
guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG,
|
||||
before.st_size > 0, before.st_size <= Int64(SoftwareLibraryArtworkCache.maximumSourceBytes) else { throw Failure.invalid }
|
||||
let data = try handle.read(upToCount: SoftwareLibraryArtworkCache.maximumSourceBytes + 1) ?? Data()
|
||||
guard data.count == Int(before.st_size), fstat(fd, &after) == 0, before.st_size == after.st_size,
|
||||
before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,
|
||||
before.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec, before.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else { throw Failure.invalid }
|
||||
return data
|
||||
}
|
||||
static func prepare(_ data: Data) throws -> Data {
|
||||
guard !data.isEmpty, data.count <= SoftwareLibraryArtworkCache.maximumSourceBytes,
|
||||
let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
|
||||
CGImageSourceGetStatus(source) == .statusComplete,
|
||||
let type = CGImageSourceGetType(source), UTType(type as String)?.conforms(to: .image) == true,
|
||||
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
|
||||
let width = properties[kCGImagePropertyPixelWidth] as? Int,
|
||||
let height = properties[kCGImagePropertyPixelHeight] as? Int,
|
||||
width > 0, height > 0, width <= 16_384, height <= 16_384,
|
||||
Int64(width) * Int64(height) <= 64_000_000 else { throw Failure.invalid }
|
||||
let normalized = try SoftwareLibraryArtworkCache.downsample(data, expectedSHA256: nil)
|
||||
guard normalized.count <= SoftwareLibraryArtworkCache.maximumThumbnailBytes,
|
||||
SoftwareLibraryArtworkCache.image(from: normalized) != nil else { throw Failure.invalid }
|
||||
return normalized
|
||||
}
|
||||
}
|
||||
|
||||
struct PersonalSoftwareDraft: Identifiable, Sendable {
|
||||
let id: UUID
|
||||
var entry: PersonalSoftwareEntry
|
||||
let unsupported: [String]
|
||||
var totalBytes: Int64 { entry.files.reduce(0) { $0 + $1.byteSize } }
|
||||
}
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
actor PersonalSoftwareLibraryStore {
|
||||
static let maximumBytes: Int64 = 1024 * 1024 * 1024
|
||||
static let maximumFiles = 20_000
|
||||
let root: URL
|
||||
private let manager = FileManager.default
|
||||
private var staged: Set<UUID> = []
|
||||
private(set) var warnings: [String] = []
|
||||
enum Failure: LocalizedError {
|
||||
case invalid(String), duplicate(UUID)
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalid(let message): return message
|
||||
case .duplicate: return "This exact set of files is already in your Personal Library. Choose Open Existing, or explicitly add a separate copy."
|
||||
}
|
||||
}
|
||||
}
|
||||
init(root: URL) { self.root = root.standardizedFileURL }
|
||||
func directory(for id: UUID) -> URL { root.appendingPathComponent(id.uuidString.lowercased(), isDirectory: true) }
|
||||
private func stage(_ id: UUID) -> URL { root.appendingPathComponent(".Staging", isDirectory: true).appendingPathComponent(id.uuidString.lowercased(), isDirectory: true) }
|
||||
private func prepareRoot() throws {
|
||||
for directory in [root, root.appendingPathComponent(".Staging")] {
|
||||
if manager.fileExists(atPath: directory.path) {
|
||||
let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard values.isDirectory == true, values.isSymbolicLink != true else { throw Failure.invalid("The private library location is not a safe directory. Existing files were preserved.") }
|
||||
} else { try manager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) }
|
||||
}
|
||||
}
|
||||
static func validRelative(_ path: String) -> Bool {
|
||||
!path.isEmpty && path.utf8.count <= 4096 && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":") &&
|
||||
!path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) &&
|
||||
path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." }
|
||||
}
|
||||
private static func fingerprint(_ url: URL, expectedSize: Int64? = nil) throws -> (Int64, String) {
|
||||
let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard fd >= 0 else { throw Failure.invalid("A selected file cannot be read safely: " + url.lastPathComponent) }
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var before = stat(), after = stat()
|
||||
guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, before.st_size >= 0,
|
||||
before.st_size <= maximumBytes else { throw Failure.invalid("Choose regular files no larger than 1 GiB.") }
|
||||
var hash = SHA256(), size: Int64 = 0
|
||||
while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty {
|
||||
try Task.checkCancellation(); size += Int64(block.count)
|
||||
guard size <= maximumBytes else { throw Failure.invalid("The selected file exceeds 1 GiB.") }
|
||||
hash.update(data: block)
|
||||
}
|
||||
guard fstat(fd, &after) == 0, before.st_ino == after.st_ino, before.st_size == after.st_size,
|
||||
before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,
|
||||
size == before.st_size, expectedSize == nil || size == expectedSize else { throw Failure.invalid("A source file changed while being copied. Please try again.") }
|
||||
return (size, hash.finalize().map { String(format: "%02x", $0) }.joined())
|
||||
}
|
||||
private static func kind(_ url: URL) throws -> String? {
|
||||
switch url.pathExtension.lowercased() {
|
||||
case "dsk", "jvc", "dmk", "vdk": _ = try DiskFiles.readImage(url); return "disk"
|
||||
case "os9":
|
||||
let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
|
||||
if size <= DiskFiles.limit { _ = try DiskFiles.readImage(url); return "disk" }
|
||||
_ = try HardDiskFiles.readImage(url); return "hard-disk"
|
||||
case "vhd", "img": _ = try HardDiskFiles.readImage(url); return "hard-disk"
|
||||
case "ccc", "rom": _ = try DiskFiles.readCartridgeROM(url); return "cartridge"
|
||||
case "cas", "wav": _ = try TapeImage.read(url); return "cassette"
|
||||
case "bin": _ = try BinaryFile.read(url); return "binary"
|
||||
case "pdf", "txt": return "manual"
|
||||
case "png", "jpg", "jpeg": return "cover"
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
func inspect(_ sources: [URL]) throws -> PersonalSoftwareDraft {
|
||||
try prepareRoot(); guard !sources.isEmpty else { throw CancellationError() }
|
||||
let id = UUID(), destination = stage(id)
|
||||
try manager.createDirectory(at: destination, withIntermediateDirectories: false)
|
||||
staged.insert(id)
|
||||
do {
|
||||
let inputs = destination.appendingPathComponent("Inputs")
|
||||
try manager.createDirectory(at: inputs, withIntermediateDirectories: false)
|
||||
var inventory: [String] = [], unsupported: [String] = [], bytes: Int64 = 0
|
||||
for source in sources {
|
||||
let access = source.startAccessingSecurityScopedResource()
|
||||
defer { if access { source.stopAccessingSecurityScopedResource() } }
|
||||
let values = try source.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey])
|
||||
guard values.isSymbolicLink != true else { throw Failure.invalid("Choose original files or folders, rather than symbolic links.") }
|
||||
if source.pathExtension.lowercased() == "zip", values.isRegularFile == true {
|
||||
guard sources.count == 1 else { throw Failure.invalid("Import one ZIP at a time, or select its extracted files as one set.") }
|
||||
let archive = destination.appendingPathComponent("Package.zip")
|
||||
let reviewed = try Self.fingerprint(source)
|
||||
try Self.copyReviewedPackage(from: source, to: archive, byteSize: reviewed.0, sha256: reviewed.1)
|
||||
let extracted = destination.appendingPathComponent("Extracted")
|
||||
inventory = try VCCLibraryArchive.extractZIP(at: archive, toNewDirectory: extracted,
|
||||
maximumExpandedBytes: UInt64(Self.maximumBytes), maximumEntries: UInt(Self.maximumFiles), shouldCancel: { Task.isCancelled })
|
||||
for path in inventory { try copy(extracted.appendingPathComponent(path), to: inputs.appendingPathComponent(path), count: &bytes) }
|
||||
} else if values.isDirectory == true {
|
||||
let selectedPath = source.resolvingSymlinksInPath().standardizedFileURL.path
|
||||
let stagingPath = destination.resolvingSymlinksInPath().standardizedFileURL.path
|
||||
guard selectedPath != stagingPath, !stagingPath.hasPrefix(selectedPath + "/") else {
|
||||
throw Failure.invalid("Select a software folder that does not contain the private library's import area.")
|
||||
}
|
||||
guard sources.count == 1 else { throw Failure.invalid("Select one coherent software folder, or choose individual files.") }
|
||||
// URL enumeration can canonicalize /var to /private/var
|
||||
// independently of the selected URL. Use the enumerator's
|
||||
// actual relative names, never trim by absolute string length.
|
||||
guard let enumerator = manager.enumerator(atPath: source.path) else { throw Failure.invalid("The selected folder cannot be read.") }
|
||||
for case let path as String in enumerator {
|
||||
try Task.checkCancellation()
|
||||
guard Self.validRelative(path) else { throw Failure.invalid("The software folder contains an unsafe relative name.") }
|
||||
let file = source.appendingPathComponent(path)
|
||||
let info = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .isDirectoryKey])
|
||||
guard info.isSymbolicLink != true else { throw Failure.invalid("The software folder contains a symbolic link: " + file.lastPathComponent) }
|
||||
if info.isDirectory == true {
|
||||
if file.lastPathComponent.hasPrefix(".") { enumerator.skipDescendants() }
|
||||
continue
|
||||
}
|
||||
if file.lastPathComponent.hasPrefix(".") { continue }
|
||||
guard info.isRegularFile == true else { throw Failure.invalid("The software folder contains an unsupported filesystem item.") }
|
||||
guard inventory.count < Self.maximumFiles else { throw Failure.invalid("The software folder contains too many files.") }
|
||||
try copy(file, to: inputs.appendingPathComponent(path), count: &bytes); inventory.append(path)
|
||||
}
|
||||
} else {
|
||||
let path = source.lastPathComponent
|
||||
guard !inventory.contains(path) else { throw Failure.invalid("Two selected files have the same name. Put them in a folder with distinct relative paths first.") }
|
||||
try copy(source, to: inputs.appendingPathComponent(path), count: &bytes); inventory.append(path)
|
||||
}
|
||||
}
|
||||
var files: [PersonalSoftwareEntry.File] = []
|
||||
for path in inventory.sorted() {
|
||||
guard Self.validRelative(path) else { throw Failure.invalid("The software contains an unsafe path.") }
|
||||
let file = inputs.appendingPathComponent(path), info = try Self.fingerprint(file)
|
||||
let kind = try Self.kind(file) ?? "supporting"
|
||||
if ["disk", "hard-disk", "cartridge", "cassette", "binary"].contains(kind), info.0 == 0 { throw Failure.invalid("A selected media file is empty: " + path) }
|
||||
if kind == "supporting" { unsupported.append(path) }
|
||||
files.append(.init(path: path, kind: kind, byteSize: info.0, sha256: info.1))
|
||||
}
|
||||
guard files.contains(where: \.isMedia) else { throw Failure.invalid("No supported CoCo media was found. Select a disk, cassette, raw cartridge, binary or software package.") }
|
||||
let name = sources[0].deletingPathExtension().lastPathComponent
|
||||
var entry = PersonalSoftwareEntry(id: id, title: name, files: files)
|
||||
let package = destination.appendingPathComponent("Package.zip")
|
||||
if manager.fileExists(atPath: package.path) {
|
||||
let identity = try Self.fingerprint(package)
|
||||
entry.sourcePackageBytes = identity.0; entry.sourcePackageSHA256 = identity.1
|
||||
}
|
||||
if let media = files.first(where: \.isMedia) {
|
||||
if media.kind == "cartridge" { entry.profile = "rom-cartridge" }
|
||||
if media.kind == "hard-disk" { entry.profile = "hard-drive-basic" }
|
||||
}
|
||||
let mediaIndices = entry.files.indices.filter { entry.files[$0].isMedia }
|
||||
if mediaIndices.count == 1, let index = mediaIndices.first, entry.files[index].kind == "disk" {
|
||||
entry.files[index].role = "disk0"
|
||||
}
|
||||
return .init(id: id, entry: entry, unsupported: unsupported)
|
||||
} catch { try? manager.removeItem(at: destination); staged.remove(id); throw error }
|
||||
}
|
||||
/// Retain exactly the bytes observed during package review. A source ZIP can
|
||||
/// change between review and copying; a coherent newer ZIP is still a change,
|
||||
/// not permission to silently import a different package.
|
||||
static func copyReviewedPackage(from source: URL, to target: URL, byteSize: Int64, sha256: String) throws {
|
||||
let manager = FileManager.default
|
||||
guard !manager.fileExists(atPath: target.path) else { throw Failure.invalid("The retained package destination already exists.") }
|
||||
try manager.copyItem(at: source, to: target)
|
||||
do {
|
||||
let retained = try fingerprint(target)
|
||||
guard retained.0 == byteSize, retained.1 == sha256 else {
|
||||
throw Failure.invalid("The source ZIP changed during copying. Select it again; existing library files were preserved.")
|
||||
}
|
||||
} catch {
|
||||
try? manager.removeItem(at: target)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private func copy(_ source: URL, to target: URL, count: inout Int64) throws {
|
||||
let relative = target.lastPathComponent
|
||||
guard Self.validRelative(relative) else { throw Failure.invalid("The selected file has an unsafe name.") }
|
||||
let before = try Self.fingerprint(source)
|
||||
count += before.0; guard count <= Self.maximumBytes else { throw Failure.invalid("One personal software set may contain at most 1 GiB.") }
|
||||
try Task.checkCancellation()
|
||||
try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
guard !manager.fileExists(atPath: target.path) else { throw Failure.invalid("Duplicate file path in this software set.") }
|
||||
try manager.copyItem(at: source, to: target)
|
||||
let after = try Self.fingerprint(target)
|
||||
guard before == after else { throw Failure.invalid("A source file changed during copying. Your source files were not modified.") }
|
||||
}
|
||||
func cancel(_ draftID: UUID) {
|
||||
guard staged.remove(draftID) != nil else { return }
|
||||
try? manager.removeItem(at: stage(draftID))
|
||||
}
|
||||
func entries(includeHidden: Bool = false) throws -> [PersonalSoftwareEntry] {
|
||||
try prepareRoot()
|
||||
var result: [PersonalSoftwareEntry] = []; warnings = []
|
||||
for folder in try manager.contentsOfDirectory(at: root, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], options: [.skipsHiddenFiles]) {
|
||||
guard UUID(uuidString: folder.lastPathComponent) != nil else { continue }
|
||||
let info = try folder.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard info.isDirectory == true, info.isSymbolicLink != true else { throw Failure.invalid("A private library entry was replaced by an unsafe filesystem item.") }
|
||||
do {
|
||||
let entry = try read(folder.appendingPathComponent("Entry.json"))
|
||||
guard entry.id.uuidString.lowercased() == folder.lastPathComponent.lowercased() else { throw Failure.invalid("A private library entry has a conflicting identity.") }
|
||||
if includeHidden || !entry.hidden { result.append(entry) }
|
||||
} catch {
|
||||
if warnings.count < 10 { warnings.append("An unavailable private entry was preserved at " + folder.path + ". " + error.localizedDescription) }
|
||||
}
|
||||
}
|
||||
return result.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
|
||||
}
|
||||
private func read(_ file: URL) throws -> PersonalSoftwareEntry {
|
||||
let info = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
|
||||
guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 4 * 1024 * 1024 else { throw Failure.invalid("A private entry cannot be read safely; its files have been preserved.") }
|
||||
var entry = try JSONDecoder().decode(PersonalSoftwareEntry.self, from: Data(contentsOf: file))
|
||||
entry.category = PersonalSoftwareEntry.standardCategory(entry.category)
|
||||
try Self.validate(entry); return entry
|
||||
}
|
||||
private static func validate(_ entry: PersonalSoftwareEntry) throws {
|
||||
guard entry.schemaVersion == 1, !entry.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
entry.title.utf8.count <= 240, entry.author.utf8.count <= 500, entry.notes.utf8.count <= 65536,
|
||||
[128, 512, 2048, 8192].contains(entry.ramKiB), ["6809", "6309"].contains(entry.processor),
|
||||
["rgb", "composite"].contains(entry.video), ["disk-basic", "rom-cartridge", "hard-drive-basic"].contains(entry.profile),
|
||||
!entry.files.isEmpty, entry.files.count <= maximumFiles, Set(entry.files.map(\.path)).count == entry.files.count,
|
||||
entry.files.contains(where: \.isMedia), entry.command.utf8.count <= 4096,
|
||||
entry.command.unicodeScalars.allSatisfy({ $0.value == 13 || $0.value == 10 || (32...126).contains($0.value) }),
|
||||
entry.files.allSatisfy({ ["disk", "hard-disk", "cartridge", "cassette", "binary", "manual", "cover", "supporting"].contains($0.kind) && validRelative($0.path) && $0.byteSize >= 0 && $0.byteSize <= maximumBytes && $0.sha256.count == 64 && $0.sha256.allSatisfy(\.isHexDigit) }) else {
|
||||
throw Failure.invalid("The personal entry is damaged, unsupported or contains invalid setup data. Its files have been preserved.")
|
||||
}
|
||||
if entry.sourcePackageSHA256 != nil || entry.sourcePackageBytes != nil {
|
||||
guard let sha = entry.sourcePackageSHA256, sha.count == 64, sha.allSatisfy(\.isHexDigit),
|
||||
let bytes = entry.sourcePackageBytes, bytes > 0, bytes <= maximumBytes else { throw Failure.invalid("The retained package identity is invalid; files were preserved.") }
|
||||
}
|
||||
switch entry.cover {
|
||||
case .imported(let path):
|
||||
guard entry.files.contains(where: { $0.kind == "cover" && $0.path == path }) else { throw Failure.invalid("Choose a cover image from this entry's imported files.") }
|
||||
case .custom(let file):
|
||||
let parts = file.path.split(separator: "/", omittingEmptySubsequences: false)
|
||||
guard validRelative(file.path), parts.count == 2, parts.first == "PersonalCovers",
|
||||
(file.path as NSString).pathExtension == "png", UUID(uuidString: URL(fileURLWithPath: file.path).deletingPathExtension().lastPathComponent) != nil,
|
||||
file.sha256.count == 64, file.sha256.allSatisfy(\.isHexDigit), file.byteSize > 0,
|
||||
file.byteSize <= Int64(SoftwareLibraryArtworkCache.maximumThumbnailBytes) else { throw Failure.invalid("The private cover descriptor is invalid. Existing files were preserved.") }
|
||||
case .categoryIcon, nil: break
|
||||
}
|
||||
let targets = entry.files.filter { !$0.role.isEmpty }.map(\.role)
|
||||
guard Set(targets).count == targets.count,
|
||||
targets.allSatisfy({ ["disk0", "disk1", "disk2", "disk3", "hard0", "hard1", "media", "cartridge"].contains($0) }) else { throw Failure.invalid("Assign each drive or media target at most once.") }
|
||||
if entry.configured {
|
||||
for file in entry.files where !file.role.isEmpty {
|
||||
let valid = (file.kind == "disk" && file.role.hasPrefix("disk") && entry.profile != "rom-cartridge") ||
|
||||
(file.kind == "hard-disk" && file.role.hasPrefix("hard") && entry.profile == "hard-drive-basic") ||
|
||||
(file.kind == "cassette" && file.role == "media" && entry.profile == "disk-basic") ||
|
||||
(file.kind == "cartridge" && file.role == "cartridge" && entry.profile == "rom-cartridge")
|
||||
guard valid else { throw Failure.invalid("A media assignment does not match this machine setup. Review the file's role and machine setup before saving.") }
|
||||
}
|
||||
}
|
||||
}
|
||||
func save(_ draft: PersonalSoftwareDraft, allowDuplicate: Bool = false, coverPNG: Data? = nil) throws -> PersonalSoftwareEntry {
|
||||
var draft = draft
|
||||
let normalizedCover = try coverPNG.map { try PersonalCoverImage.prepare($0) }
|
||||
draft.entry.category = PersonalSoftwareEntry.standardCategory(draft.entry.category)
|
||||
try Self.validate(draft.entry)
|
||||
guard staged.contains(draft.id), draft.entry.id == draft.id else { throw Failure.invalid("This import preview has expired. Select the files again.") }
|
||||
if !allowDuplicate, let existing = try entries().first(where: { $0.packageSHA256 == draft.entry.packageSHA256 }) { throw Failure.duplicate(existing.id) }
|
||||
let source = stage(draft.id), inputs = source.appendingPathComponent("Inputs")
|
||||
try requireSafePath(inputs, directory: true)
|
||||
let final = directory(for: draft.id)
|
||||
guard !manager.fileExists(atPath: final.path) else { throw Failure.invalid("A personal entry already uses this identity.") }
|
||||
let required = draft.entry.files.reduce(Int64(0)) { $0 + $1.byteSize } * 3 + 64 * 1024 * 1024
|
||||
if let free = try root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage, free < required { throw SoftwareLibraryInstaller.Failure.insufficientSpace }
|
||||
let ready = source.appendingPathComponent("Ready")
|
||||
if manager.fileExists(atPath: ready.path) { try manager.removeItem(at: ready) }
|
||||
try manager.createDirectory(at: ready, withIntermediateDirectories: false)
|
||||
do {
|
||||
for name in ["Original/Files", "Working", "Assets"] { try manager.createDirectory(at: ready.appendingPathComponent(name), withIntermediateDirectories: true) }
|
||||
for file in draft.entry.files {
|
||||
try Task.checkCancellation()
|
||||
if file.kind == "hard-disk" { _ = try HardDiskFiles.readImage(inputs.appendingPathComponent(file.path)) }
|
||||
let original = ready.appendingPathComponent("Original/Files").appendingPathComponent(file.path)
|
||||
var count: Int64 = 0
|
||||
try copy(inputs.appendingPathComponent(file.path), to: original, count: &count)
|
||||
let actual = try Self.fingerprint(original)
|
||||
guard actual.0 == file.byteSize, actual.1 == file.sha256 else { throw Failure.invalid("The staged import no longer matches its preview.") }
|
||||
// A .txt or image can also be runtime program data. Preserve
|
||||
// the coherent complete set in Working, even when an asset is
|
||||
// additionally offered in the native manual/artwork reader.
|
||||
let target = ready.appendingPathComponent("Working").appendingPathComponent(file.path)
|
||||
try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try manager.copyItem(at: original, to: target)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path)
|
||||
if ["manual", "cover"].contains(file.kind) {
|
||||
let asset = ready.appendingPathComponent("Assets").appendingPathComponent(file.path)
|
||||
try manager.createDirectory(at: asset.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try manager.copyItem(at: original, to: asset)
|
||||
}
|
||||
try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: original.path)
|
||||
}
|
||||
let package = source.appendingPathComponent("Package.zip")
|
||||
if manager.fileExists(atPath: package.path) {
|
||||
let identity = try Self.fingerprint(package)
|
||||
guard identity.0 == draft.entry.sourcePackageBytes, identity.1 == draft.entry.sourcePackageSHA256 else { throw Failure.invalid("The source ZIP no longer matches the reviewed import.") }
|
||||
let retained = ready.appendingPathComponent("Original/Package.zip")
|
||||
try manager.copyItem(at: package, to: retained)
|
||||
guard try Self.fingerprint(retained) == identity else { throw Failure.invalid("The retained source ZIP did not copy correctly.") }
|
||||
try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: retained.path)
|
||||
}
|
||||
if let normalizedCover {
|
||||
draft.entry.cover = .custom(try storeCover(normalizedCover, in: ready))
|
||||
} else if draft.entry.cover != nil {
|
||||
_ = try previewCover(draft.entry, draftID: draft.id)
|
||||
}
|
||||
try write(draft.entry, to: ready.appendingPathComponent("Entry.json"))
|
||||
try Task.checkCancellation(); try manager.moveItem(at: ready, to: final)
|
||||
cancel(draft.id)
|
||||
return draft.entry
|
||||
} catch { try? manager.removeItem(at: ready); throw error }
|
||||
}
|
||||
private func write(_ entry: PersonalSoftwareEntry, to url: URL) throws {
|
||||
let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
try encoder.encode(entry).write(to: url, options: .atomic)
|
||||
}
|
||||
func update(_ entry: PersonalSoftwareEntry, coverPNG: Data? = nil) throws {
|
||||
var entry = entry
|
||||
let normalizedCover = try coverPNG.map { try PersonalCoverImage.prepare($0) }
|
||||
entry.category = PersonalSoftwareEntry.standardCategory(entry.category)
|
||||
try Self.validate(entry)
|
||||
let directory = directory(for: entry.id)
|
||||
try requireSafePath(directory, directory: true)
|
||||
let file = directory.appendingPathComponent("Entry.json")
|
||||
let previous = try read(file)
|
||||
guard (coverPNG == nil && entry.cover == previous.cover) || previous.updatedAt == entry.updatedAt else {
|
||||
throw Failure.invalid("This private entry changed while its cover was being edited. Reopen it before saving; existing files were preserved.")
|
||||
}
|
||||
func identities(_ files: [PersonalSoftwareEntry.File]) -> [String: String] {
|
||||
Dictionary(uniqueKeysWithValues: files.map { ($0.path, $0.kind + ":" + String($0.byteSize) + ":" + $0.sha256) })
|
||||
}
|
||||
guard identities(previous.files) == identities(entry.files), previous.createdAt == entry.createdAt,
|
||||
previous.sourcePackageSHA256 == entry.sourcePackageSHA256, previous.sourcePackageBytes == entry.sourcePackageBytes else { throw Failure.invalid("Use a new import to replace media; existing working files are preserved.") }
|
||||
var added: URL?
|
||||
do {
|
||||
if let normalizedCover {
|
||||
let cover = try storeCover(normalizedCover, in: directory)
|
||||
added = directory.appendingPathComponent("Assets").appendingPathComponent(cover.path)
|
||||
entry.cover = .custom(cover)
|
||||
} else if entry.cover != nil {
|
||||
_ = try previewCover(entry, draftID: nil)
|
||||
}
|
||||
entry.updatedAt = Date(); try write(entry, to: file)
|
||||
} catch {
|
||||
if let added { try? manager.removeItem(at: added) }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview reads retained assets or this draft's staged input; it never
|
||||
/// persists a chosen replacement image or changes the media inventory.
|
||||
func previewCover(_ entry: PersonalSoftwareEntry, draftID: UUID? = nil) throws -> Data? {
|
||||
try Self.validate(entry)
|
||||
guard let cover = entry.selectedCoverFile else { return nil }
|
||||
let base: URL
|
||||
if let draftID {
|
||||
guard staged.contains(draftID), draftID == entry.id else { throw Failure.invalid("This import preview has expired. Select the files again.") }
|
||||
base = stage(draftID).appendingPathComponent("Inputs")
|
||||
} else { base = directory(for: entry.id).appendingPathComponent("Assets") }
|
||||
let source = base.appendingPathComponent(cover.path)
|
||||
try requireSafePath(source, directory: false)
|
||||
let data = try PersonalCoverImage.sourceData(source)
|
||||
guard Int64(data.count) == cover.byteSize,
|
||||
SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == cover.sha256.lowercased() else {
|
||||
throw Failure.invalid("The private cover no longer matches its saved identity. Existing files were preserved.")
|
||||
}
|
||||
return try PersonalCoverImage.prepare(data)
|
||||
}
|
||||
|
||||
private func requireSafePath(_ path: URL, directory: Bool) throws {
|
||||
let path = path.standardizedFileURL
|
||||
guard path.path == root.path || path.path.hasPrefix(root.path + "/") else { throw Failure.invalid("The private asset path leaves its library.") }
|
||||
var checked = root
|
||||
let relative = path.path.dropFirst(root.path.count).split(separator: "/")
|
||||
let rootValues = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard rootValues.isDirectory == true, rootValues.isSymbolicLink != true else { throw Failure.invalid("The private library location is not a safe directory.") }
|
||||
for (index, component) in relative.enumerated() {
|
||||
checked.appendPathComponent(String(component))
|
||||
let values = try checked.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey])
|
||||
let needsDirectory = index < relative.count - 1 || directory
|
||||
guard values.isSymbolicLink != true, needsDirectory ? values.isDirectory == true : values.isRegularFile == true else {
|
||||
throw Failure.invalid("The private asset path contains an unsafe filesystem item. Existing files were preserved.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func storeCover(_ data: Data, in directory: URL) throws -> PersonalSoftwareEntry.CoverFile {
|
||||
try requireSafePath(directory, directory: true)
|
||||
for relative in ["Assets", "Assets/PersonalCovers"] {
|
||||
let folder = directory.appendingPathComponent(relative)
|
||||
if !manager.fileExists(atPath: folder.path) { try manager.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) }
|
||||
try requireSafePath(folder, directory: true)
|
||||
}
|
||||
let path = "PersonalCovers/" + UUID().uuidString.lowercased() + ".png"
|
||||
let destination = directory.appendingPathComponent("Assets").appendingPathComponent(path)
|
||||
let fd = open(destination.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)
|
||||
guard fd >= 0 else { throw Failure.invalid("The replacement cover could not be saved safely.") }
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
do {
|
||||
try handle.write(contentsOf: data); try handle.close()
|
||||
return .init(path: path, sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), byteSize: Int64(data.count))
|
||||
} catch {
|
||||
try? handle.close(); try? manager.removeItem(at: destination); throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,556 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// Finder file drags use the native file-URL pasteboard representation. Image
|
||||
/// decoding remains in the receiving model/editor's bounded background work.
|
||||
struct PersonalCoverFileDropTarget: NSViewRepresentable {
|
||||
let enabled: Bool
|
||||
@Binding var isTargeted: Bool
|
||||
let perform: ([URL]) -> Bool
|
||||
|
||||
func makeNSView(context: Context) -> DropView {
|
||||
let view = DropView()
|
||||
view.registerForDraggedTypes([.fileURL])
|
||||
view.setAccessibilityElement(false)
|
||||
view.setAccessibilityHidden(true)
|
||||
return view
|
||||
}
|
||||
func updateNSView(_ view: DropView, context: Context) {
|
||||
view.enabled = enabled
|
||||
view.targeted = $isTargeted
|
||||
view.perform = perform
|
||||
if !enabled, isTargeted {
|
||||
DispatchQueue.main.async { [weak view] in
|
||||
guard let view, !view.enabled else { return }
|
||||
view.setTargeted(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
static func dismantleNSView(_ view: DropView, coordinator: ()) {
|
||||
view.unregisterDraggedTypes()
|
||||
view.perform = nil
|
||||
let targeted = view.targeted
|
||||
view.targeted = nil
|
||||
if targeted?.wrappedValue == true {
|
||||
DispatchQueue.main.async { targeted?.wrappedValue = false }
|
||||
}
|
||||
}
|
||||
final class DropView: NSView {
|
||||
var enabled = false
|
||||
var targeted: Binding<Bool>?
|
||||
var perform: (([URL]) -> Bool)?
|
||||
override func layout() {
|
||||
super.layout()
|
||||
#if VCC_UI_TESTING
|
||||
trace("layout frame=\(frame) window=\(String(describing: window?.frame))")
|
||||
#endif
|
||||
}
|
||||
private func trace(_ message: String) {
|
||||
#if VCC_UI_TESTING
|
||||
guard let path = ProcessInfo.processInfo.environment["VCC_COVER_DRAG_TRACE"] else { return }
|
||||
let url = URL(fileURLWithPath: path)
|
||||
var data = (try? Data(contentsOf: url)) ?? Data()
|
||||
guard data.count < 8192 else { return }
|
||||
data.append(Data((message + "\n").utf8)); try? data.write(to: url)
|
||||
#endif
|
||||
}
|
||||
|
||||
func setTargeted(_ value: Bool) {
|
||||
if targeted?.wrappedValue != value { targeted?.wrappedValue = value }
|
||||
}
|
||||
private func urls(from sender: NSDraggingInfo) -> [URL]? {
|
||||
guard enabled,
|
||||
let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self],
|
||||
options: [.urlReadingFileURLsOnly: true]) as? [URL],
|
||||
urls.count == 1, let url = urls.first, url.isFileURL,
|
||||
url.host == nil || url.host == "localhost", url.query == nil, url.fragment == nil else { return nil }
|
||||
return urls
|
||||
}
|
||||
private func operation(for sender: NSDraggingInfo) -> NSDragOperation {
|
||||
let accepts = sender.draggingSourceOperationMask.contains(.copy) && urls(from: sender) != nil
|
||||
setTargeted(accepts)
|
||||
return accepts ? .copy : []
|
||||
}
|
||||
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
|
||||
trace("entered enabled=\(enabled) frame=\(frame)")
|
||||
return operation(for: sender)
|
||||
}
|
||||
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { operation(for: sender) }
|
||||
override func draggingExited(_ sender: NSDraggingInfo?) { setTargeted(false) }
|
||||
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
|
||||
operation(for: sender) == .copy
|
||||
}
|
||||
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
|
||||
defer { setTargeted(false) }
|
||||
guard sender.draggingSourceOperationMask.contains(.copy), let urls = urls(from: sender) else { return false }
|
||||
trace("perform file-count=\(urls.count)")
|
||||
return perform?(urls) ?? false
|
||||
}
|
||||
override func concludeDragOperation(_ sender: NSDraggingInfo?) { setTargeted(false) }
|
||||
}
|
||||
}
|
||||
|
||||
#if VCC_UI_TESTING
|
||||
/// Authored UI-test source for a real AppKit file drag. It uses the same
|
||||
/// pasteboard representation as Finder and never calls a drop handler itself.
|
||||
struct PersonalCoverFileDragFixture: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> SourceView {
|
||||
let view = SourceView()
|
||||
view.setAccessibilityElement(true)
|
||||
view.isEnabled = true
|
||||
view.setAccessibilityLabel("Drag test image")
|
||||
view.setAccessibilityIdentifier("personal-cover-drag-source")
|
||||
return view
|
||||
}
|
||||
func updateNSView(_ view: SourceView, context: Context) {
|
||||
view.sourceURL = ProcessInfo.processInfo.environment["VCC_COVER_DRAG_SOURCE"].map { URL(fileURLWithPath: $0) }
|
||||
view.needsDisplay = true
|
||||
}
|
||||
final class SourceView: NSImageView, NSDraggingSource {
|
||||
var sourceURL: URL?
|
||||
override var intrinsicContentSize: NSSize { NSSize(width: 100, height: 45) }
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
super.draw(dirtyRect)
|
||||
let frame = bounds.insetBy(dx: 1, dy: 1)
|
||||
let border = NSBezierPath(roundedRect: frame, xRadius: 5, yRadius: 5)
|
||||
NSColor.controlBackgroundColor.setFill(); border.fill()
|
||||
NSColor.separatorColor.setStroke(); border.stroke()
|
||||
NSImage(systemSymbolName: "doc", accessibilityDescription: nil)?
|
||||
.draw(in: NSRect(x: bounds.midX - 8, y: 23, width: 16, height: 17))
|
||||
let paragraph = NSMutableParagraphStyle(); paragraph.alignment = .center
|
||||
("Drag test image" as NSString).draw(in: NSRect(x: 3, y: 5, width: bounds.width - 6, height: 14),
|
||||
withAttributes: [.font: NSFont.systemFont(ofSize: 10), .foregroundColor: NSColor.labelColor,
|
||||
.paragraphStyle: paragraph])
|
||||
}
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
guard let sourceURL else { return }
|
||||
let item = NSDraggingItem(pasteboardWriter: sourceURL as NSURL)
|
||||
let icon = NSImage(systemSymbolName: "doc", accessibilityDescription: nil)
|
||||
item.setDraggingFrame(NSRect(x: bounds.midX - 16, y: bounds.midY - 16, width: 32, height: 32), contents: icon)
|
||||
let session = beginDraggingSession(with: [item], event: event, source: self)
|
||||
session.animatesToStartingPositionsOnCancelOrFail = true
|
||||
}
|
||||
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
|
||||
.copy
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Guest command text must retain ASCII quotes and literal keystrokes. A native
|
||||
/// plain-text editor also keeps Return inside the draft instead of saving it.
|
||||
private struct PersonalLaunchCommandEditor: NSViewRepresentable {
|
||||
@Binding var text: String
|
||||
let isEnabled: Bool
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSTextView.scrollableTextView()
|
||||
let editor = scroll.documentView as! NSTextView
|
||||
scroll.drawsBackground = false
|
||||
editor.drawsBackground = false
|
||||
editor.isRichText = false
|
||||
editor.allowsUndo = true
|
||||
editor.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)
|
||||
editor.textColor = .labelColor
|
||||
editor.isAutomaticQuoteSubstitutionEnabled = false
|
||||
editor.isAutomaticDashSubstitutionEnabled = false
|
||||
editor.isAutomaticTextReplacementEnabled = false
|
||||
editor.isAutomaticSpellingCorrectionEnabled = false
|
||||
editor.isContinuousSpellCheckingEnabled = false
|
||||
editor.isAutomaticLinkDetectionEnabled = false
|
||||
editor.isAutomaticDataDetectionEnabled = false
|
||||
editor.isAutomaticTextCompletionEnabled = false
|
||||
editor.smartInsertDeleteEnabled = false
|
||||
editor.textContainerInset = NSSize(width: 4, height: 6)
|
||||
editor.setAccessibilityLabel("Keyboard loading commands (optional)")
|
||||
editor.setAccessibilityIdentifier("personal-launch-commands")
|
||||
editor.delegate = context.coordinator
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
let editor = scroll.documentView as! NSTextView
|
||||
context.coordinator.text = $text
|
||||
editor.isEditable = isEnabled
|
||||
if editor.string != text { editor.string = text }
|
||||
}
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var text: Binding<String>
|
||||
init(text: Binding<String>) { self.text = text }
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let editor = notification.object as? NSTextView else { return }
|
||||
text.wrappedValue = editor.string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PersonalSoftwareEditor: View {
|
||||
@State var entry: PersonalSoftwareEntry
|
||||
let unsupported: [String]
|
||||
let isImport: Bool
|
||||
let saving: Bool
|
||||
let error: String?
|
||||
let duplicateID: UUID?
|
||||
let save: (PersonalSoftwareEntry, Data?, Bool) -> Void
|
||||
let openExisting: (UUID) -> Void
|
||||
let previewCover: (PersonalSoftwareEntry) async throws -> Data?
|
||||
let cancel: () -> Void
|
||||
private let initialEntry: PersonalSoftwareEntry
|
||||
@State private var included: Set<String>
|
||||
@State private var pendingCoverData: Data?
|
||||
@State private var coverImage: NSImage?
|
||||
@State private var coverBusy = false
|
||||
@State private var coverError: String?
|
||||
@State private var coverGeneration = UUID()
|
||||
@State private var coverTask: Task<Void, Never>?
|
||||
@State private var coverImageTask: Task<Data, Error>?
|
||||
@State private var previewingImportedPath: String?
|
||||
@State private var coverPanel: NSOpenPanel?
|
||||
@State private var coverEditorActive = true
|
||||
@State private var coverDropTargeted = false
|
||||
init(entry: PersonalSoftwareEntry, unsupported: [String] = [], isImport: Bool, saving: Bool,
|
||||
error: String?, duplicateID: UUID?, save: @escaping (PersonalSoftwareEntry, Data?, Bool) -> Void,
|
||||
openExisting: @escaping (UUID) -> Void,
|
||||
previewCover: @escaping (PersonalSoftwareEntry) async throws -> Data?, cancel: @escaping () -> Void) {
|
||||
var normalized = entry
|
||||
normalized.category = PersonalSoftwareEntry.standardCategory(entry.category)
|
||||
_entry = State(initialValue: normalized); _included = State(initialValue: Set(entry.files.map(\.path)))
|
||||
self.unsupported = unsupported; self.isImport = isImport; self.saving = saving; self.error = error
|
||||
self.duplicateID = duplicateID; self.save = save; self.openExisting = openExisting
|
||||
self.previewCover = previewCover; self.cancel = cancel; self.initialEntry = entry
|
||||
}
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Label(isImport ? "Add Personal Software" : "Edit Personal Software", systemImage: "lock.rectangle.stack")
|
||||
.font(.title2.weight(.semibold))
|
||||
Spacer()
|
||||
Text("Private — On This Mac").font(.callout).foregroundStyle(.secondary)
|
||||
}.padding(20)
|
||||
Divider()
|
||||
Form {
|
||||
Section("Files & Details") {
|
||||
TextField("Title", text: $entry.title).accessibilityIdentifier("personal-title")
|
||||
TextField("Author / Publisher (optional)", text: $entry.author)
|
||||
TextField("Software version (optional)", text: $entry.softwareVersion)
|
||||
Picker("Category", selection: $entry.category) {
|
||||
ForEach(PersonalSoftwareEntry.standardCategories, id: \.self) { category in
|
||||
Text(SoftwareLibraryOwnedGame.categoryLabel(category)).tag(category)
|
||||
}
|
||||
}.pickerStyle(.menu).accessibilityIdentifier("personal-category")
|
||||
Text("Find this personal software alongside matching catalog titles when browsing categories. Your files stay private on this Mac.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
TextField("Notes / loading instructions", text: $entry.notes, axis: .vertical).lineLimit(3...8)
|
||||
Text("Your source files stay untouched. Imported originals and writable working files are kept separately in the app's private library. Nothing is uploaded.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
LabeledContent("Selected files", value: "\(included.count) · " + ByteCountFormatter.string(fromByteCount: entry.files.filter { included.contains($0.path) }.reduce(0) { $0 + $1.byteSize }, countStyle: .file))
|
||||
ForEach(Array(entry.files.indices), id: \.self) { index in
|
||||
HStack {
|
||||
if isImport {
|
||||
Toggle(isOn: Binding(get: { included.contains(entry.files[index].path) }, set: { value in
|
||||
setIncluded(entry.files[index].path, value)
|
||||
})) { Text(entry.files[index].path).lineLimit(2).textSelection(.enabled) }
|
||||
} else { Text(entry.files[index].path).lineLimit(2).textSelection(.enabled) }
|
||||
Spacer()
|
||||
if isImport, (entry.files[index].path as NSString).pathExtension.lowercased() == "os9" {
|
||||
Picker("Interpret OS-9 media", selection: Binding(get: { entry.files[index].kind }, set: {
|
||||
entry.files[index].kind = $0; entry.files[index].role = ""
|
||||
})) {
|
||||
Text("Floppy disk").tag("disk")
|
||||
Text("Hard disk").tag("hard-disk")
|
||||
}.labelsHidden().frame(width: 125).help("OS-9 files can represent floppy or hard disks. Choose how this file will be mounted.")
|
||||
} else { Text(entry.files[index].kind.capitalized).font(.caption).foregroundStyle(.secondary) }
|
||||
}
|
||||
}
|
||||
if !unsupported.isEmpty {
|
||||
Label("Supporting files are retained but not run. Nested archives and unrecognized formats are not expanded or treated as media.", systemImage: "info.circle")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
Section("Cover Image") { coverEditor }
|
||||
Section("Launch Setup") {
|
||||
Toggle("Use reviewed launch settings", isOn: $entry.configured).accessibilityIdentifier("personal-configured")
|
||||
Text("Save reviewed machine settings and media assignments to enable Play. Keyboard loading commands are optional: without them, Play opens the CoCo with its media ready for manual loading. Off keeps manual setup. Saving this entry never starts or changes the CoCo.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
Picker("Machine setup", selection: $entry.profile) {
|
||||
Text("Disk BASIC / Cassette").tag("disk-basic")
|
||||
Text("ROM Cartridge").tag("rom-cartridge")
|
||||
Text("Hard-drive BASIC").tag("hard-drive-basic")
|
||||
}
|
||||
Picker("Processor", selection: $entry.processor) { Text("MC6809").tag("6809"); Text("HD6309").tag("6309") }
|
||||
Picker("RAM", selection: $entry.ramKiB) {
|
||||
ForEach([128,512,2048,8192], id: \.self) { value in Text(value < 1024 ? "\(value) KB" : "\(value / 1024) MB").tag(value) }
|
||||
}
|
||||
Picker("Video", selection: $entry.video) { Text("Composite").tag("composite"); Text("RGB").tag("rgb") }
|
||||
ForEach(Array(entry.files.indices).filter { entry.files[$0].isMedia && included.contains(entry.files[$0].path) }, id: \.self) { index in
|
||||
Picker(entry.files[index].path, selection: $entry.files[index].role) {
|
||||
Text("Not assigned").tag("")
|
||||
ForEach(roles(entry.files[index].kind), id: \.self) { role in Text(roleLabel(role)).tag(role) }
|
||||
}.disabled(!entry.configured)
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Keyboard loading commands (optional)")
|
||||
PersonalLaunchCommandEditor(text: $entry.command, isEnabled: entry.configured)
|
||||
.frame(height: 90).padding(6)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 6))
|
||||
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.secondary.opacity(0.3)))
|
||||
}
|
||||
Text("Press Return for a new command line. For a BASIC program, enter LOAD \"PROGRAM\" on one line and RUN on the next. Commands are ordinary CoCo keyboard input; leave this blank if the loading sequence is unknown.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
if entry.configured, !entry.command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
SoftwareLibraryLaunchPlan.decodeCommands(entry.command) == nil {
|
||||
Label("These commands need manual entry and will not be typed automatically. Check the syntax and put LOAD and RUN on separate lines.", systemImage: "info.circle")
|
||||
.font(.caption).foregroundStyle(.orange)
|
||||
.accessibilityIdentifier("personal-launch-commands-manual")
|
||||
}
|
||||
}
|
||||
}.formStyle(.grouped)
|
||||
if let error {
|
||||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal,20).padding(.vertical,8)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
if saving { ProgressView().controlSize(.small); Text("Saving private copy…").font(.callout) }
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel, action: cancelEditing).keyboardShortcut(.cancelAction).disabled(saving)
|
||||
if let duplicateID {
|
||||
Button("Open Existing") { openExisting(duplicateID) }.disabled(saving)
|
||||
Button("Add Separate Copy") { submit(true) }.disabled(saving || coverBusy)
|
||||
} else {
|
||||
Button(isImport ? "Add to Personal Library" : "Save Details") { submit(false) }
|
||||
.keyboardShortcut(.defaultAction).disabled(saving || coverBusy || entry.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !entry.files.contains(where: { $0.isMedia && included.contains($0.path) }))
|
||||
.accessibilityIdentifier("personal-save")
|
||||
}
|
||||
}.padding(16)
|
||||
}.frame(minWidth: 650, idealWidth: 720, minHeight: 600)
|
||||
.onAppear {
|
||||
coverEditorActive = true
|
||||
loadCoverPreview(entry, commitChoice: false)
|
||||
}
|
||||
.onDisappear { discardPendingCover() }
|
||||
}
|
||||
private var coverEditor: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack(alignment: .top, spacing: 16) {
|
||||
coverPreview
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Picker("Cover", selection: Binding(get: { coverSelection }, set: selectCover)) {
|
||||
Text("Category Icon").tag("category")
|
||||
ForEach(entry.files.filter { $0.kind == "cover" }) { file in
|
||||
Text(file.path).tag("imported:" + file.path)
|
||||
}
|
||||
if hasExistingCustomCover { Text("Saved Custom Image").tag("custom") }
|
||||
if pendingCoverData != nil { Text("Chosen Image").tag("replacement") }
|
||||
}.pickerStyle(.menu).accessibilityIdentifier("personal-cover-selection")
|
||||
Button("Choose Image…", systemImage: "photo.badge.plus", action: chooseCoverImage)
|
||||
.disabled(saving || coverPanel != nil).accessibilityIdentifier("personal-cover-choose")
|
||||
Button("Remove Cover", systemImage: "photo.badge.minus", action: useCategoryIcon)
|
||||
.disabled(saving || (coverSelection == "category" && !coverBusy))
|
||||
.accessibilityIdentifier("personal-cover-remove")
|
||||
Text("Choose an image or drop one image file onto the preview. The image stays private on this Mac and is saved only when you save this entry.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
if let coverError {
|
||||
Label(coverError, systemImage: "exclamationmark.triangle")
|
||||
.font(.caption).foregroundStyle(.orange).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
private var coverPreview: some View {
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 9).fill(.quaternary.opacity(0.35))
|
||||
if let coverImage {
|
||||
Image(nsImage: coverImage).resizable().scaledToFit().padding(5)
|
||||
} else {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: SoftwareLibraryCategoryStyle.symbol(for: entry.category))
|
||||
.font(.system(size: 42, weight: .light))
|
||||
.foregroundStyle(SoftwareLibraryCategoryStyle.tint(for: entry.category).opacity(0.7))
|
||||
Text(SoftwareLibraryOwnedGame.categoryLabel(entry.category))
|
||||
.font(.caption.weight(.medium)).foregroundStyle(.secondary)
|
||||
}.padding(12)
|
||||
}
|
||||
if coverBusy {
|
||||
ProgressView().controlSize(.small).frame(maxHeight: .infinity, alignment: .bottom).padding(8)
|
||||
}
|
||||
}.frame(width: 150, height: 180)
|
||||
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(coverDropTargeted ? Color.accentColor : .clear, lineWidth: 3))
|
||||
.overlay {
|
||||
PersonalCoverFileDropTarget(enabled: !saving && coverEditorActive, isTargeted: $coverDropTargeted) { urls in
|
||||
guard let url = urls.first else { return false }
|
||||
prepareCoverImage(url)
|
||||
return true
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity).accessibilityHidden(true)
|
||||
}
|
||||
.accessibilityElement(children: .ignore).accessibilityLabel("Cover image preview")
|
||||
.accessibilityValue(coverBusy ? "Loading image" : coverImage == nil ? "Category icon" : "Selected image")
|
||||
.accessibilityIdentifier("personal-cover-preview")
|
||||
.help("Drop one image file here to choose a private cover image")
|
||||
}
|
||||
private var hasExistingCustomCover: Bool {
|
||||
if case .custom? = initialEntry.cover { return true }
|
||||
return false
|
||||
}
|
||||
private var coverSelection: String {
|
||||
if pendingCoverData != nil { return "replacement" }
|
||||
switch entry.cover {
|
||||
case .categoryIcon?: return "category"
|
||||
case .imported(let path)?: return "imported:" + path
|
||||
case .custom?: return "custom"
|
||||
case nil:
|
||||
return entry.files.first(where: { $0.kind == "cover" && included.contains($0.path) })
|
||||
.map { "imported:" + $0.path } ?? "category"
|
||||
}
|
||||
}
|
||||
private func selectCover(_ selection: String) {
|
||||
guard !saving, coverEditorActive, selection != coverSelection else { return }
|
||||
if selection == "category" { useCategoryIcon(); return }
|
||||
var candidate = entry
|
||||
if selection == "custom", hasExistingCustomCover { candidate.cover = initialEntry.cover }
|
||||
else if selection.hasPrefix("imported:") {
|
||||
let path = String(selection.dropFirst("imported:".count))
|
||||
guard entry.files.contains(where: { $0.kind == "cover" && $0.path == path }) else { return }
|
||||
candidate.cover = .imported(path)
|
||||
} else { return }
|
||||
loadCoverPreview(candidate, commitChoice: true)
|
||||
}
|
||||
private func loadCoverPreview(_ candidate: PersonalSoftwareEntry, commitChoice: Bool) {
|
||||
let generation = beginCoverWork()
|
||||
var snapshot = candidate
|
||||
// A selected imported image is retained with the draft even if it had
|
||||
// been unchecked in Files & Details before choosing it here.
|
||||
let selectedPath: String?
|
||||
if case .imported(let path)? = candidate.cover { selectedPath = path } else { selectedPath = nil }
|
||||
previewingImportedPath = selectedPath
|
||||
snapshot.files = snapshot.files.filter { included.contains($0.path) || $0.path == selectedPath }
|
||||
coverTask = Task { @MainActor in
|
||||
do {
|
||||
let data = try await previewCover(snapshot)
|
||||
guard coverEditorActive, entry.id == candidate.id, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
let image = data.flatMap(NSImage.init(data:))
|
||||
guard data == nil || image != nil else { throw CocoaError(.fileReadCorruptFile) }
|
||||
if commitChoice {
|
||||
entry.cover = candidate.cover
|
||||
if let selectedPath { included.insert(selectedPath) }
|
||||
pendingCoverData = nil
|
||||
}
|
||||
coverImage = image
|
||||
finishCoverWork()
|
||||
} catch {
|
||||
guard coverEditorActive, entry.id == candidate.id, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
coverError = "Could not read this cover image. " + error.localizedDescription
|
||||
finishCoverWork()
|
||||
}
|
||||
}
|
||||
}
|
||||
private func chooseCoverImage() {
|
||||
guard !saving, coverEditorActive else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.image]
|
||||
panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.allowsMultipleSelection = false
|
||||
panel.message = "Choose a private cover image for this software."
|
||||
panel.prompt = "Choose Image"
|
||||
coverPanel = panel
|
||||
panel.begin { response in
|
||||
Task { @MainActor in
|
||||
guard coverEditorActive, coverPanel === panel else { return }
|
||||
coverPanel = nil
|
||||
if response == .OK, let url = panel.url { prepareCoverImage(url) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func prepareCoverImage(_ url: URL) {
|
||||
let generation = beginCoverWork()
|
||||
let entryID = entry.id
|
||||
let worker = Task.detached(priority: .userInitiated) {
|
||||
try Task.checkCancellation()
|
||||
let data = try PersonalCoverImage.prepare(url)
|
||||
try Task.checkCancellation()
|
||||
return data
|
||||
}
|
||||
coverImageTask = worker
|
||||
coverTask = Task { @MainActor in
|
||||
do {
|
||||
let data = try await worker.value
|
||||
guard coverEditorActive, entry.id == entryID, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
guard let image = NSImage(data: data) else { throw CocoaError(.fileReadCorruptFile) }
|
||||
pendingCoverData = data
|
||||
coverImage = image
|
||||
finishCoverWork()
|
||||
} catch {
|
||||
guard coverEditorActive, entry.id == entryID, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
coverError = "Could not use this image. " + error.localizedDescription
|
||||
finishCoverWork()
|
||||
}
|
||||
}
|
||||
}
|
||||
private func beginCoverWork() -> UUID {
|
||||
stopCoverWork()
|
||||
coverBusy = true; coverError = nil
|
||||
return coverGeneration
|
||||
}
|
||||
private func finishCoverWork() {
|
||||
coverBusy = false; coverTask = nil; coverImageTask = nil; previewingImportedPath = nil
|
||||
}
|
||||
private func stopCoverWork() {
|
||||
coverGeneration = UUID()
|
||||
coverTask?.cancel(); coverTask = nil
|
||||
coverImageTask?.cancel(); coverImageTask = nil
|
||||
previewingImportedPath = nil
|
||||
coverBusy = false
|
||||
}
|
||||
private func useCategoryIcon() {
|
||||
stopCoverWork()
|
||||
entry.cover = .categoryIcon; pendingCoverData = nil; coverImage = nil; coverError = nil
|
||||
}
|
||||
private func setIncluded(_ path: String, _ value: Bool) {
|
||||
let removingSelectedCover = !value && coverSelection == "imported:" + path
|
||||
if !value, previewingImportedPath == path { stopCoverWork() }
|
||||
if value { included.insert(path) } else { included.remove(path) }
|
||||
if !value, pendingCoverData != nil, case .imported(let previousPath)? = entry.cover, previousPath == path {
|
||||
// The validated replacement is independent of this imported file.
|
||||
entry.cover = .categoryIcon
|
||||
} else if removingSelectedCover { useCategoryIcon() }
|
||||
}
|
||||
private func discardPendingCover() {
|
||||
coverEditorActive = false
|
||||
stopCoverWork()
|
||||
coverPanel?.cancel(nil); coverPanel = nil
|
||||
pendingCoverData = nil; coverDropTargeted = false
|
||||
}
|
||||
private func cancelEditing() {
|
||||
discardPendingCover()
|
||||
cancel()
|
||||
}
|
||||
private func submit(_ allowDuplicate: Bool) {
|
||||
guard !saving, !coverBusy else { return }
|
||||
var edited = entry
|
||||
edited.files = edited.files.filter { included.contains($0.path) }
|
||||
// The store validates the file inventory before installing the PNG.
|
||||
// A replaced imported cover may have been excluded from that inventory.
|
||||
if pendingCoverData != nil { edited.cover = .categoryIcon }
|
||||
edited.command = edited.command.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r")
|
||||
save(edited, pendingCoverData, allowDuplicate)
|
||||
}
|
||||
private func roles(_ kind: String) -> [String] {
|
||||
switch kind {
|
||||
case "disk": return ["disk0","disk1","disk2","disk3"]
|
||||
case "hard-disk": return ["hard0","hard1"]
|
||||
case "cassette": return ["media"]
|
||||
case "cartridge": return ["cartridge"]
|
||||
default: return []
|
||||
}
|
||||
}
|
||||
private func roleLabel(_ role: String) -> String {
|
||||
switch role { case "media": return "Cassette"; case "cartridge": return "ROM Cartridge"
|
||||
default: return role.hasPrefix("hard") ? "HD" + role.suffix(1) : "FD" + role.suffix(1) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -63,9 +63,11 @@ final class SoftwareLibraryState: ObservableObject {
|
||||
fileURL = directory.appendingPathComponent("Unused.json")
|
||||
}
|
||||
func applyRemoteSnapshot(_ snapshot: CompanionLibrarySnapshot) {
|
||||
favoriteTitleIDs = snapshot.favorites
|
||||
preferredReleaseIDs = snapshot.preferredReleaseIDs
|
||||
installedReleases = Dictionary(snapshot.installations.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, last in last })
|
||||
let visible = snapshot.catalog.companionDisksOnly
|
||||
let titles = Set(visible.titles.map(\.id)), releases = Set(visible.releases.map(\.id))
|
||||
favoriteTitleIDs = snapshot.favorites.intersection(titles)
|
||||
preferredReleaseIDs = snapshot.preferredReleaseIDs.filter { titles.contains($0.key) && releases.contains($0.value) }
|
||||
installedReleases = Dictionary(snapshot.installations.filter { releases.contains($0.releaseID) }.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, last in last })
|
||||
saveError = nil
|
||||
}
|
||||
private func sendRemote(_ request: CompanionLibraryRequest) {
|
||||
|
||||
@@ -10,6 +10,7 @@ struct SoftwareLibraryView: View {
|
||||
@State private var showAdvancedFilters = false
|
||||
@State private var confirmingReturn = false
|
||||
@State private var removingRelease: SoftwareLibraryRelease?
|
||||
@State private var personalCoverDropTargeted = false
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
header
|
||||
@@ -48,10 +49,10 @@ struct SoftwareLibraryView: View {
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
Text("Color Computer Archive software and VCC Plus-exclusive titles").font(.caption).foregroundStyle(.secondary)
|
||||
Text("Color Computer Archive, creator submissions and your private software").font(.caption).foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
if model.filtering { ProgressView().controlSize(.mini) }
|
||||
Text(model.catalog.map { "\($0.titles.count.formatted()) titles · \($0.releaseCount.formatted()) editions" } ?? "")
|
||||
Text(model.catalog.map { "Catalog: \($0.titles.count.formatted()) titles · \($0.releaseCount.formatted()) editions" } ?? "")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}.padding(.horizontal, 16).padding(.vertical, 9)
|
||||
}
|
||||
@@ -65,6 +66,7 @@ struct SoftwareLibraryView: View {
|
||||
if !model.isDiskCompanion { openWindow(id: "c-development") }
|
||||
}
|
||||
.modifier(SoftwareLibraryLaunchPresentation(model: model))
|
||||
.modifier(SoftwareLibraryPersonalPresentation(model: model))
|
||||
.environment(\.companionLibraryAccess, model.companionAccess)
|
||||
.sheet(isPresented: $showManual) {
|
||||
VStack(spacing: 0) {
|
||||
@@ -82,7 +84,7 @@ struct SoftwareLibraryView: View {
|
||||
} message: {
|
||||
Text("This restarts the CoCo with the previous hardware and media assignments. It does not restore its previous program or memory. Unsaved media must be saved first.")
|
||||
}
|
||||
.onDisappear { Task { await model.state.flush() } }
|
||||
.onDisappear { model.saveBrowseContext(); Task { await model.state.flush() } }
|
||||
.alert("Remove from Library?", isPresented: Binding(get: { removingRelease != nil }, set: { if !$0 { removingRelease = nil } }), presenting: removingRelease) { release in
|
||||
Button("Cancel", role: .cancel) { removingRelease = nil }
|
||||
Button("Remove from Library") { Task { await model.removeInstallation(release.id) }; removingRelease = nil }
|
||||
@@ -100,12 +102,13 @@ struct SoftwareLibraryView: View {
|
||||
.accessibilityIdentifier("library-return-setup")
|
||||
.disabled(model.launchBusy || model.installingReleaseID != nil)
|
||||
}
|
||||
libraryActions
|
||||
HStack(spacing: 7) {
|
||||
Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
|
||||
TextField("Search titles, authors, or keywords", text: $model.query.text)
|
||||
TextField("Search titles, authors, or keywords", text: Binding(get: { model.query.text }, set: model.setSearchText))
|
||||
.textFieldStyle(.plain).accessibilityLabel("Search software").accessibilityIdentifier("library-search")
|
||||
if !model.query.text.isEmpty {
|
||||
Button { model.query.text = "" } label: { Image(systemName: "xmark.circle.fill") }
|
||||
Button { model.setSearchText("") } label: { Image(systemName: "xmark.circle.fill") }
|
||||
.buttonStyle(.plain).help("Clear search").accessibilityLabel("Clear search")
|
||||
}
|
||||
}.padding(8).background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))
|
||||
@@ -122,6 +125,7 @@ struct SoftwareLibraryView: View {
|
||||
Text("My Library").font(.caption.weight(.semibold)).foregroundStyle(.secondary).padding(.top, 8)
|
||||
scope("Favorites", icon: "heart", scope: .favorites, id: "favorites")
|
||||
scope("Installed", icon: "internaldrive", scope: .installed, id: "installed")
|
||||
scope("Personal Library", icon: "lock.rectangle.stack", scope: .personal, id: "personal")
|
||||
}.padding(14)
|
||||
Divider()
|
||||
List {
|
||||
@@ -156,6 +160,7 @@ struct SoftwareLibraryView: View {
|
||||
}.buttonStyle(.plain).accessibilityIdentifier("library-scope-" + id)
|
||||
}
|
||||
private var heading: String {
|
||||
if model.query.scope == .search { return "Search Results" }
|
||||
if !model.query.softwareType.isEmpty { return SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType) }
|
||||
if !model.query.category.isEmpty { return model.query.category.components(separatedBy: "/").last ?? "All Software" }
|
||||
switch model.query.scope {
|
||||
@@ -164,6 +169,8 @@ struct SoftwareLibraryView: View {
|
||||
case .all: return "All Software"
|
||||
case .favorites: return "Favorites"
|
||||
case .installed: return "Installed"
|
||||
case .personal: return "Personal Library"
|
||||
case .search: return "Search Results"
|
||||
}
|
||||
}
|
||||
private var browser: some View {
|
||||
@@ -186,6 +193,14 @@ struct SoftwareLibraryView: View {
|
||||
.help("Filter and sort").accessibilityLabel("Filter and sort").accessibilityIdentifier("library-filters")
|
||||
.popover(isPresented: $showFilters, arrowEdge: .bottom) { ScrollView { filters.padding(18) }.frame(width: 370, height: showAdvancedFilters ? 460 : 340) }
|
||||
}.padding(.horizontal, 16).padding(.top, 14)
|
||||
if model.query.scope == .personal {
|
||||
addPersonalSoftwareButton(id: "library-personal-add")
|
||||
.padding(.horizontal, 16)
|
||||
if model.isDiskCompanion {
|
||||
Text("Add or edit personal software in VCC Plus. Your disk entries are available through the local connection.")
|
||||
.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16)
|
||||
}
|
||||
}
|
||||
if model.query.scope == .showcase {
|
||||
Text("Software with cover art, labels and screenshots.")
|
||||
.font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16)
|
||||
@@ -193,10 +208,8 @@ struct SoftwareLibraryView: View {
|
||||
Text("A first selection to explore your CoCo. More guided picks will join the collection.")
|
||||
.font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16)
|
||||
}
|
||||
if !model.query.category.isEmpty || !model.query.softwareType.isEmpty {
|
||||
Text(model.query.sort == .title
|
||||
? "Curated titles appear first, alphabetically, followed by the alphabetical collection."
|
||||
: "Curated titles appear first, alphabetically; the remaining titles use your selected sort.")
|
||||
if let orderingCaption {
|
||||
Text(orderingCaption)
|
||||
.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16)
|
||||
}
|
||||
if !activeFilters.isEmpty {
|
||||
@@ -206,9 +219,19 @@ struct SoftwareLibraryView: View {
|
||||
Button("Clear filters") { model.clearFilters() }.controlSize(.small)
|
||||
}.padding(.horizontal, 16)
|
||||
}
|
||||
if model.loading {
|
||||
if let error = model.error, hasPersonalResults {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Label("Catalog unavailable", systemImage: "exclamationmark.triangle")
|
||||
Text(error).font(.caption).textSelection(.enabled)
|
||||
Text("Your personal software is still available.").font(.caption)
|
||||
}.foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
|
||||
Button("Retry") { Task { await model.load() } }.disabled(model.loading)
|
||||
}.padding(.horizontal, 16).accessibilityIdentifier("library-catalog-unavailable-notice")
|
||||
}
|
||||
if model.loading && !hasPersonalResults {
|
||||
Spacer(); ProgressView("Opening the library…").frame(maxWidth: .infinity); Spacer()
|
||||
} else if let error = model.error {
|
||||
} else if let error = model.error, !hasPersonalResults {
|
||||
ContentUnavailableView { Label("Library unavailable", systemImage: "books.vertical") } description: { Text(error) } actions: {
|
||||
Button("Try Again") { Task { await model.load() } }
|
||||
}
|
||||
@@ -224,19 +247,76 @@ struct SoftwareLibraryView: View {
|
||||
model.selection = value
|
||||
}
|
||||
})) {
|
||||
TableColumn("Title", value: \.name).width(min: 140, ideal: 240)
|
||||
TableColumn("Title") { row in
|
||||
HStack(spacing: 6) {
|
||||
Text(row.name).lineLimit(2)
|
||||
.accessibilityLabel(row.name + (row.isPersonal ? ", Personal Library" : ""))
|
||||
.accessibilityIdentifier("library-table-title-" + row.id)
|
||||
if row.isPersonal { personalBadge }
|
||||
}
|
||||
.accessibilityElement(children: .contain)
|
||||
}.width(min: 140, ideal: 240)
|
||||
TableColumn("Format", value: \.formats).width(min: 65, ideal: 95)
|
||||
TableColumn("Size", value: \.size).width(55)
|
||||
}.accessibilityLabel("Software titles")
|
||||
.background(SoftwareLibraryScrollTracker(ids: model.rows.map(\.id), table: true,
|
||||
restoreID: model.browseTopID, restoreOffset: model.browseOffset, changed: model.rememberBrowsePosition))
|
||||
} else {
|
||||
ScrollView {
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 155, maximum: 215), spacing: 18)], alignment: .leading, spacing: 22) {
|
||||
ForEach(model.rows) { row in shelfCard(row) }
|
||||
LazyVStack(alignment: .leading, spacing: 18) {
|
||||
if hasPersonalAndCatalog {
|
||||
shelfHeading("Personal Library", icon: "lock.fill")
|
||||
shelfGrid(model.rows.filter(\.isPersonal))
|
||||
shelfHeading("Catalog", icon: "books.vertical")
|
||||
shelfGrid(model.rows.filter { !$0.isPersonal })
|
||||
} else {
|
||||
shelfGrid(model.rows)
|
||||
}
|
||||
}.padding(16)
|
||||
}.background(Color.primary.opacity(0.018))
|
||||
.background(SoftwareLibraryScrollTracker(ids: model.rows.map(\.id), table: false,
|
||||
restoreID: model.browseTopID, restoreOffset: model.browseOffset, changed: model.rememberBrowsePosition))
|
||||
}
|
||||
}
|
||||
}
|
||||
private var hasPersonalResults: Bool { model.rows.contains(where: \.isPersonal) }
|
||||
private var hasPersonalAndCatalog: Bool {
|
||||
hasPersonalResults && model.rows.contains { !$0.isPersonal }
|
||||
}
|
||||
private var orderingCaption: String? {
|
||||
let curatedFirst = !model.query.category.isEmpty || !model.query.softwareType.isEmpty
|
||||
if hasPersonalAndCatalog {
|
||||
if !curatedFirst {
|
||||
return model.query.sort == .title
|
||||
? "Personal titles appear first, alphabetically. Catalog titles follow alphabetically."
|
||||
: "Personal titles appear first, alphabetically. Catalog titles follow using your selected sort."
|
||||
}
|
||||
return model.query.sort == .title
|
||||
? "Personal titles appear first, alphabetically. Catalog titles follow, with curated titles first, then the alphabetical collection."
|
||||
: "Personal titles appear first, alphabetically. Catalog titles follow, with curated titles first; the remaining titles use your selected sort."
|
||||
}
|
||||
guard model.rows.contains(where: { !$0.isPersonal }), curatedFirst else { return nil }
|
||||
return model.query.sort == .title
|
||||
? "Curated titles appear first, alphabetically, followed by the alphabetical collection."
|
||||
: "Curated titles appear first, alphabetically; the remaining titles use your selected sort."
|
||||
}
|
||||
private func shelfHeading(_ title: String, icon: String) -> some View {
|
||||
Label(title, systemImage: icon).font(.headline).foregroundStyle(.secondary)
|
||||
.accessibilityAddTraits(.isHeader)
|
||||
}
|
||||
private func shelfGrid(_ rows: [LibraryBrowseRow]) -> some View {
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 155, maximum: 215), spacing: 18)], alignment: .leading, spacing: 22) {
|
||||
ForEach(rows) { row in shelfCard(row) }
|
||||
}
|
||||
}
|
||||
private var personalBadge: some View {
|
||||
Label("Personal", systemImage: "lock.fill").font(.caption2).foregroundStyle(.secondary)
|
||||
.labelStyle(.titleAndIcon)
|
||||
.fixedSize()
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel("Personal")
|
||||
.accessibilityIdentifier("library-personal-badge")
|
||||
}
|
||||
private var activeFilters: [String] {
|
||||
var labels: [String] = []
|
||||
if !model.query.softwareType.isEmpty { labels.append(SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType)) }
|
||||
@@ -251,20 +331,33 @@ struct SoftwareLibraryView: View {
|
||||
}
|
||||
private var searchIsActive: Bool { !model.query.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||||
private var narrowed: Bool { searchIsActive || !activeFilters.isEmpty || !model.query.category.isEmpty }
|
||||
private var personalLibraryIsEmpty: Bool {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
return !model.isDiskCompanion && model.query.scope == .personal && model.personalEntries.isEmpty
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
private var emptyState: some View {
|
||||
ContentUnavailableView {
|
||||
Label(!narrowed && model.query.scope == .installed ? "Your software will live here" : !narrowed && model.query.scope == .favorites ? "Keep your favorites close" : "No matching titles", systemImage: model.query.scope == .favorites ? "heart" : "books.vertical")
|
||||
Label(personalLibraryIsEmpty ? "Add your first software" : !narrowed && model.query.scope == .installed ? "Your software will live here" : !narrowed && model.query.scope == .favorites ? "Keep your favorites close" : "No matching titles", systemImage: personalLibraryIsEmpty ? "lock.rectangle.stack" : model.query.scope == .favorites ? "heart" : "books.vertical")
|
||||
} description: {
|
||||
if model.catalog?.releaseCount == 0 { Text("This development build has an empty catalog. Build with a prepared Software Library catalog to browse software.").accessibilityIdentifier("library-catalog-empty") }
|
||||
if personalLibraryIsEmpty { Text("Add a folder, ZIP, or CoCo media files to your private library on this Mac. Your originals stay untouched; nothing is uploaded or run.") }
|
||||
else if model.query.scope != .personal && model.catalog?.releaseCount == 0 { Text("This development build has an empty catalog. Build with a prepared Software Library catalog to browse software.").accessibilityIdentifier("library-catalog-empty") }
|
||||
else if narrowed { Text(searchIsActive ? "No titles match “\(model.query.text)” in this selection. Clear the search or adjust your filters." : "No titles match these filters. Try clearing them or choosing another category.") }
|
||||
else if model.query.scope == .installed { Text("Choose a title and Install Only to keep a copy on your Mac. Your running CoCo session will stay as it is.") }
|
||||
else if model.query.scope == .favorites { Text("Choose the heart beside a title to add it to your collection.") }
|
||||
else { Text("Try a different search, category, or filter.") }
|
||||
} actions: {
|
||||
if searchIsActive {
|
||||
Button("Clear Search") { model.query.text = "" }.accessibilityIdentifier("library-empty-clear-search")
|
||||
if personalLibraryIsEmpty {
|
||||
addPersonalSoftwareButton(id: "library-personal-add-first")
|
||||
.buttonStyle(.borderedProminent)
|
||||
} else {
|
||||
if searchIsActive {
|
||||
Button("Clear Search") { model.setSearchText("") }.accessibilityIdentifier("library-empty-clear-search")
|
||||
}
|
||||
Button("Browse All Titles") { model.query = LibraryBrowseQuery(scope: .all) }
|
||||
}
|
||||
Button("Browse All Titles") { model.query = LibraryBrowseQuery(scope: .all) }
|
||||
}
|
||||
}
|
||||
private var filters: some View {
|
||||
@@ -337,10 +430,13 @@ struct SoftwareLibraryView: View {
|
||||
Text(row.name).font(.callout.weight(.medium)).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)
|
||||
if model.state.isFavorite(row.id) { Image(systemName: "heart.fill").font(.caption).foregroundStyle(.pink) }
|
||||
}
|
||||
Text(row.formats).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
HStack {
|
||||
Text(row.formats).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
if row.isPersonal { personalBadge }
|
||||
}
|
||||
}.padding(4).contentShape(Rectangle())
|
||||
}.buttonStyle(.plain).accessibilityIdentifier("library-title-" + row.id)
|
||||
.accessibilityLabel(row.name + ", " + row.formats).help(row.name)
|
||||
.accessibilityLabel(row.name + (row.isPersonal ? ", Personal Library" : "") + ", " + row.formats).help(row.name)
|
||||
}
|
||||
@ViewBuilder private var detail: some View {
|
||||
if let row = model.selectedRow, let release = model.selectedRelease {
|
||||
@@ -358,11 +454,15 @@ struct SoftwareLibraryView: View {
|
||||
.accessibilityIdentifier("library-favorite")
|
||||
}
|
||||
if let error = model.state.saveError { Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) }
|
||||
SoftwareLibraryArtworkView(
|
||||
asset: release.assets.first(where: { SoftwareLibraryArtworkCache.canDisplay($0) }),
|
||||
cacheDirectory: model.artworkDirectory,
|
||||
softwareType: LibraryBrowseQuery.type(of: release, related: row.title.releases))
|
||||
.frame(maxWidth: .infinity).frame(height: 200)
|
||||
detailArtwork(release, title: row.title)
|
||||
if release.isPersonal {
|
||||
Label("Personal Library — Private on This Mac", systemImage: "lock.fill").font(.headline)
|
||||
.accessibilityIdentifier("library-personal")
|
||||
}
|
||||
if release.isDirectSubmission {
|
||||
Label("Creator-submitted software", systemImage: "person.crop.square").font(.headline)
|
||||
if let author = release.metadata["author"].string { Text("By " + author).font(.callout) }
|
||||
}
|
||||
if let owned = release.ownedGame {
|
||||
Label("VCC Plus-exclusive", systemImage: "sparkles").font(.headline)
|
||||
.accessibilityIdentifier("library-exclusive")
|
||||
@@ -408,11 +508,13 @@ struct SoftwareLibraryView: View {
|
||||
}
|
||||
}
|
||||
assetLinks(release)
|
||||
relatedReferences(release)
|
||||
DisclosureGroup("Edition & source details") { metadata(release, title: row.title).padding(.top, 10) }
|
||||
.font(.callout)
|
||||
if release.ownedGame == nil {
|
||||
if release.isArchive {
|
||||
Link(destination: release.sourceURL.deletingLastPathComponent().appendingPathComponent("", isDirectory: true)) { Label("View on Color Computer Archive", systemImage: "arrow.up.right.square") }
|
||||
}
|
||||
if release.isDirectSubmission { Link("Visit Project", destination: URL(string: release.metadata["project_url"].string ?? "") ?? release.sourceURL) }
|
||||
Text(model.isDiskCompanion
|
||||
? "Insert Disk creates a separate writable copy for DriveWire. Choose its drive slot, then follow the loading instructions on your real CoCo."
|
||||
: "Play previews the recommended setup before restarting. You can also use the Media menu to mount installed files yourself.")
|
||||
@@ -423,6 +525,59 @@ struct SoftwareLibraryView: View {
|
||||
ContentUnavailableView("Choose a title", systemImage: "book.closed", description: Text("Explore its editions, loading instructions, and manuals."))
|
||||
}
|
||||
}
|
||||
private func artwork(_ release: SoftwareLibraryRelease, title: SoftwareLibraryTitle) -> some View {
|
||||
SoftwareLibraryArtworkView(asset: release.assets.first(where: { SoftwareLibraryArtworkCache.canDisplay($0) }),
|
||||
cacheDirectory: model.artworkDirectory, softwareType: LibraryBrowseQuery.type(of: release, related: title.releases))
|
||||
.frame(maxWidth: .infinity).frame(height: 200)
|
||||
}
|
||||
@ViewBuilder private func detailArtwork(_ release: SoftwareLibraryRelease, title: SoftwareLibraryTitle) -> some View {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if !model.isDiskCompanion, let entry = model.selectedPersonalEntry {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
artwork(release, title: title)
|
||||
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(personalCoverDropTargeted ? Color.accentColor : .clear, lineWidth: 3))
|
||||
.contentShape(Rectangle())
|
||||
.overlay {
|
||||
PersonalCoverFileDropTarget(enabled: model.canEditPersonal && model.personalEditor == nil,
|
||||
isTargeted: $personalCoverDropTargeted) { urls in
|
||||
model.acceptPersonalCoverDrop(urls, for: entry)
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity).accessibilityHidden(true)
|
||||
}
|
||||
.accessibilityIdentifier("library-personal-cover")
|
||||
HStack {
|
||||
Menu {
|
||||
Button("Choose Cover Image…", systemImage: "photo") { model.choosePersonalCover(for: entry) }
|
||||
let imported = entry.files.filter { $0.kind == "cover" }
|
||||
if !imported.isEmpty {
|
||||
Menu("Use Imported Image") {
|
||||
ForEach(imported) { file in
|
||||
Button(URL(fileURLWithPath: file.path).lastPathComponent) {
|
||||
model.selectPersonalCover(.imported(file.path), for: entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Button("Remove Cover", systemImage: "photo.badge.minus") {
|
||||
model.selectPersonalCover(.categoryIcon, for: entry)
|
||||
}.disabled(!release.assets.contains(where: { SoftwareLibraryArtworkCache.canDisplay($0) }))
|
||||
} label: { Label("Cover Image", systemImage: "photo") }
|
||||
.disabled(!model.canEditPersonal || model.personalEditor != nil)
|
||||
.accessibilityIdentifier("library-personal-cover-menu")
|
||||
if model.personalSaving { ProgressView().controlSize(.small) }
|
||||
}
|
||||
Text("Drop an image onto the cover, or choose one. It stays private on this Mac.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
#if VCC_UI_TESTING
|
||||
if ProcessInfo.processInfo.environment["VCC_COVER_DRAG_SOURCE"] != nil {
|
||||
PersonalCoverFileDragFixture().frame(width: 120, height: 45)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
} else { artwork(release, title: title) }
|
||||
#else
|
||||
artwork(release, title: title)
|
||||
#endif
|
||||
}
|
||||
private func sourceCard(_ release: SoftwareLibraryRelease, owned: SoftwareLibraryOwnedGame) -> some View {
|
||||
SecondaryCard {
|
||||
Label("Learn from the source", systemImage: "curlybraces").font(.headline)
|
||||
@@ -460,6 +615,8 @@ struct SoftwareLibraryView: View {
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Button("Cancel", role: .cancel) { model.cancelInstallation() }.accessibilityIdentifier("library-cancel-install")
|
||||
} else if release.isPersonal && !model.isDiskCompanion {
|
||||
personalActions(release)
|
||||
} else if let installed = model.state.installedReleases[release.id] {
|
||||
Label("Installed", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(.green)
|
||||
.accessibilityIdentifier("library-install-status")
|
||||
@@ -467,8 +624,12 @@ struct SoftwareLibraryView: View {
|
||||
Text("Your writable media is ready. The original files are kept separately.").font(.callout)
|
||||
Button { NSWorkspace.shared.open(installed.workingDirectory) } label: { Label("Show Files in Finder", systemImage: "folder") }
|
||||
.accessibilityIdentifier("library-reveal-install")
|
||||
Button("Remove from Library…") { removingRelease = release }
|
||||
.disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil).accessibilityIdentifier("library-remove-install")
|
||||
if release.isPersonal && model.isDiskCompanion {
|
||||
Text("Manage this personal entry in VCC Plus.").font(.caption).foregroundStyle(.secondary)
|
||||
} else {
|
||||
Button("Remove from Library…") { removingRelease = release }
|
||||
.disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil).accessibilityIdentifier("library-remove-install")
|
||||
}
|
||||
} else {
|
||||
if model.canLaunch { playButton(release, installed: false) }
|
||||
Button { model.install(release) } label: { Label(model.installationErrors[release.id] == nil ? "Install Only" : "Try Again", systemImage: "arrow.down.circle") }
|
||||
@@ -534,7 +695,7 @@ struct SoftwareLibraryView: View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Label("Controls", systemImage: "gamecontroller").font(.subheadline.weight(.medium))
|
||||
ForEach(controls.keys.sorted(), id: \.self) { key in
|
||||
Text(release.setup.controlDescription(key, source: release.ownedGame == nil ? "the Archive" : "the project")).font(.callout).textSelection(.enabled)
|
||||
Text(release.setup.controlDescription(key, source: release.isPersonal ? "your setup" : release.isArchive ? "the Archive" : "the author")).font(.callout).textSelection(.enabled)
|
||||
.accessibilityIdentifier("library-controls-" + key)
|
||||
}
|
||||
}
|
||||
@@ -557,7 +718,7 @@ struct SoftwareLibraryView: View {
|
||||
.accessibilityIdentifier("library-manual-" + manual.id)
|
||||
} else {
|
||||
Link(destination: manual.sourceURL) { Label(manual.name, systemImage: "arrow.up.right.square") }
|
||||
.font(.callout).help(release.ownedGame == nil ? "Open this document on Color Computer Archive" : "Open this project document")
|
||||
.font(.callout).help(release.isArchive ? "Open this document on Color Computer Archive" : "Open this project document")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -578,18 +739,23 @@ struct SoftwareLibraryView: View {
|
||||
}
|
||||
if let publisher = release.publisher { LabeledContent("Publisher", value: publisher) }
|
||||
if let year = release.year { LabeledContent("Year", value: String(year)) }
|
||||
LabeledContent("Download", value: ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file))
|
||||
LabeledContent(release.isPersonal ? "Retained files" : "Download", value: ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file))
|
||||
if release.isDirectSubmission {
|
||||
if let author = release.metadata["author"].string { LabeledContent("Author", value: author) }
|
||||
if let license = release.metadata["license"].string { LabeledContent("License", value: license) }
|
||||
if let version = release.metadata["software_version"].string { LabeledContent("Software version", value: version) }
|
||||
}
|
||||
if let owned = release.ownedGame {
|
||||
LabeledContent("Author", value: owned.author)
|
||||
LabeledContent("License", value: owned.license)
|
||||
}
|
||||
LabeledContent(release.ownedGame == nil ? "Archive modified" : "Project modified", value: release.modifiedAt ?? "Unknown")
|
||||
if release.ownedGame == nil, release.modifiedAt != nil, release.modifiedTimezone == nil || release.modifiedTimezone == "unspecified" {
|
||||
LabeledContent(release.isArchive ? "Archive modified" : "Modified", value: release.modifiedAt ?? "Unknown")
|
||||
if release.isArchive, release.modifiedAt != nil, release.modifiedTimezone == nil || release.modifiedTimezone == "unspecified" {
|
||||
Text("Archive date; time zone not specified.").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
LabeledContent("Loading evidence", value: release.ownedGame == nil ? release.setup.statusLabel : "Project-provided loading instructions")
|
||||
LabeledContent("Loading evidence", value: release.isPersonal ? "User-provided private setup" : release.ownedGame == nil ? release.setup.statusLabel : "Project-provided loading instructions")
|
||||
Text(release.setup.validationScope.map { "VCC Plus check: " + $0.replacingOccurrences(of: "-", with: " ") } ?? "Not individually tested in VCC Plus.")
|
||||
if release.ownedGame == nil && title.releases.count > 1 && title.identityStatus == "suggested" { Text("Related editions are grouped from Archive names; their contents may differ.") }
|
||||
if release.isArchive && title.releases.count > 1 && title.identityStatus == "suggested" { Text("Related editions are grouped from Archive names; their contents may differ.") }
|
||||
if !release.videoModes.isEmpty { Text("Video: " + release.videoModes.joined(separator: ", ")) }
|
||||
if let note = release.setup.curationNote { Text(note) }
|
||||
if !release.assets.isEmpty {
|
||||
@@ -597,7 +763,8 @@ struct SoftwareLibraryView: View {
|
||||
Text("Artwork & manual sources").fontWeight(.medium)
|
||||
ForEach(release.assets) { asset in
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Link(asset.name, destination: asset.sourceURL)
|
||||
if asset.matchStatus == "personal" { Text(asset.name) }
|
||||
else { Link(asset.name, destination: asset.sourceURL) }
|
||||
Text(asset.credit).foregroundStyle(.secondary)
|
||||
if asset.matchStatus == "candidate" { Text("Suggested match from Archive names; corrections are welcome.").font(.caption).foregroundStyle(.secondary) }
|
||||
}
|
||||
@@ -621,6 +788,65 @@ struct SoftwareLibraryView: View {
|
||||
private func systemName(_ value: String) -> String {
|
||||
switch value { case "coco3": return "Color Computer 3"; case "coco1-2", "coco1/2": return "Color Computer 1/2"; case "unknown": return "Not specified"; default: return value }
|
||||
}
|
||||
@ViewBuilder private func addPersonalSoftwareButton(id: String) -> some View {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if !model.isDiskCompanion {
|
||||
Button("Add Software…", systemImage: "folder.badge.plus") { model.choosePersonalSoftware() }
|
||||
.disabled(!model.canEditPersonal || model.personalEditor != nil)
|
||||
.help("Add software to your private Personal Library")
|
||||
.accessibilityIdentifier(id)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@ViewBuilder private var libraryActions: some View {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if !model.isDiskCompanion {
|
||||
Menu {
|
||||
Button("Add Personal Software…", systemImage: "folder.badge.plus") { model.choosePersonalSoftware() }
|
||||
.disabled(!model.canEditPersonal)
|
||||
Button("Submit Software…", systemImage: "paperplane") {
|
||||
NSWorkspace.shared.open(URL(string: "https://vccplus.brianholman.com/software/submit/")!)
|
||||
}
|
||||
} label: { Image(systemName: "ellipsis.circle") }
|
||||
.help("Library Actions").accessibilityLabel("Library Actions").accessibilityIdentifier("library-actions")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@ViewBuilder private func personalActions(_ release: SoftwareLibraryRelease) -> some View {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if let entry = model.selectedPersonalEntry {
|
||||
Label("Private copy", systemImage: "lock.fill").font(.headline)
|
||||
if model.canLaunch, release.mediaType != "binary" { playButton(release, installed: true) }
|
||||
Text(release.mediaType == "binary" ? "Open the working folder, then use File → Load Binary to load this program deliberately." : "Your writable media and retained originals are kept separately. Nothing is uploaded.").font(.caption).foregroundStyle(.secondary)
|
||||
Button("Edit Details…", systemImage: "pencil") { model.editPersonal(entry) }.disabled(!model.canEditPersonal)
|
||||
Button("Show Files in Finder", systemImage: "folder") { NSWorkspace.shared.open(model.personalDirectory(entry).appendingPathComponent("Working")) }
|
||||
Button("Remove from Library…") { removingRelease = release }
|
||||
.disabled(model.launchBusy || model.hasPendingLaunch)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@ViewBuilder private func relatedReferences(_ release: SoftwareLibraryRelease) -> some View {
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
if !model.isDiskCompanion, !release.relatedArchiveReferences.isEmpty {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Guides & References").font(.headline)
|
||||
ForEach(release.relatedArchiveReferences) { reference in
|
||||
Button {
|
||||
ArchiveLibraryNavigation.shared.open(documentID: reference.documentID, location: reference.page,
|
||||
expectedSHA256: reference.sha256)
|
||||
openWindow(id: "archive-library")
|
||||
} label: {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Label(reference.title, systemImage: "doc.text.magnifyingglass")
|
||||
Text(reference.role + (reference.spoiler ? " · Contains spoilers" : "") + (reference.page.map { " · Page \($0)" } ?? ""))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}.buttonStyle(.link).help("Open in Archive Library").accessibilityIdentifier("library-reference-" + reference.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
private func profileName(_ value: String) -> String {
|
||||
switch value { case "rom-cartridge": return "ROM Cartridge"; case "disk-basic": return "Disk BASIC"; case "hard-drive-basic", "hard-basic": return "Hard Drive BASIC"; case "coco-sdc": return "CoCo SDC"; case "nitros9": return "NitrOS-9"; default: return value.replacingOccurrences(of: "-", with: " ").capitalized }
|
||||
}
|
||||
@@ -642,3 +868,101 @@ private struct SoftwareLibraryLaunchPresentation: ViewModifier {
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes the actual native clip view without taking over its delegate or
|
||||
/// sending pointer events. Restoration runs once, after content is installed.
|
||||
private struct SoftwareLibraryScrollTracker: NSViewRepresentable {
|
||||
let ids: [String]
|
||||
let table: Bool
|
||||
let restoreID: String?
|
||||
let restoreOffset: Double
|
||||
let changed: (String?, Double) -> Void
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
func makeNSView(context: Context) -> NSView { NSView() }
|
||||
func updateNSView(_ view: NSView, context: Context) {
|
||||
context.coordinator.ids = ids; context.coordinator.table = table; context.coordinator.changed = changed
|
||||
context.coordinator.restoreID = restoreID; context.coordinator.restoreOffset = restoreOffset
|
||||
context.coordinator.attach(view)
|
||||
context.coordinator.refreshRestoration()
|
||||
}
|
||||
static func dismantleNSView(_ view: NSView, coordinator: Coordinator) { coordinator.clear() }
|
||||
final class Coordinator {
|
||||
var ids: [String] = [], table = false
|
||||
var restoreID: String?, restoreOffset: Double = 0
|
||||
var changed: ((String?, Double) -> Void)?
|
||||
private var token: NSObjectProtocol?
|
||||
private weak var scroll: NSScrollView?
|
||||
private var restored = false, attaching = false
|
||||
private var attachAttempts = 0, restoreAttempts = 0
|
||||
func clear() { if let token { NotificationCenter.default.removeObserver(token) }; token = nil; scroll = nil; restored = false }
|
||||
func attach(_ marker: NSView) {
|
||||
guard scroll == nil, !attaching else { return }
|
||||
attaching = true
|
||||
DispatchQueue.main.async { [weak self, weak marker] in
|
||||
guard let self else { return }; self.attaching = false
|
||||
guard let marker, marker.window != nil else { return }
|
||||
var ancestor: NSView? = marker.superview
|
||||
let target = marker.convert(marker.bounds, to: nil)
|
||||
for _ in 0..<6 {
|
||||
guard let root = ancestor else { break }
|
||||
func descendants(_ view: NSView) -> [NSScrollView] {
|
||||
(view as? NSScrollView).map { [$0] } ?? view.subviews.flatMap(descendants)
|
||||
}
|
||||
if let match = descendants(root).first(where: { candidate in
|
||||
let frame = candidate.convert(candidate.bounds, to: nil)
|
||||
return target.width > 0 && target.height > 0 && frame.intersection(target).width > target.width * 0.8 &&
|
||||
frame.intersection(target).height > target.height * 0.8 && (!self.table || candidate.documentView is NSTableView)
|
||||
}) {
|
||||
self.scroll = match; match.contentView.postsBoundsChangedNotifications = true
|
||||
self.token = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification,
|
||||
object: match.contentView, queue: .main) { [weak self] _ in self?.record() }
|
||||
DispatchQueue.main.async { [weak self] in self?.restore() }
|
||||
return
|
||||
}
|
||||
ancestor = root.superview
|
||||
}
|
||||
if self.attachAttempts < 20 {
|
||||
self.attachAttempts += 1
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self, weak marker] in
|
||||
if let marker { self?.attach(marker) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func refreshRestoration() {
|
||||
guard !restored else { return }
|
||||
DispatchQueue.main.async { [weak self] in self?.restore() }
|
||||
}
|
||||
private func restore() {
|
||||
guard !restored, !ids.isEmpty, let scroll, let document = scroll.documentView else { return }
|
||||
if document.bounds.height <= 0 || scroll.contentView.bounds.height <= 0 || ((document as? NSTableView).map { $0.numberOfRows < ids.count } ?? false) {
|
||||
if restoreAttempts < 20 {
|
||||
restoreAttempts += 1
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in self?.restore() }
|
||||
}
|
||||
return
|
||||
}
|
||||
restored = true
|
||||
let range = max(0, document.bounds.height - scroll.contentView.bounds.height)
|
||||
var y = CGFloat(max(0, min(restoreOffset, 1))) * range
|
||||
if let table = document as? NSTableView, let id = restoreID, let index = ids.firstIndex(of: id), index < table.numberOfRows {
|
||||
let row = table.rect(ofRow: index); y = row.minY + CGFloat(restoreOffset) * row.height
|
||||
}
|
||||
scroll.contentView.scroll(to: NSPoint(x: 0, y: min(max(0,y), range))); scroll.reflectScrolledClipView(scroll.contentView)
|
||||
}
|
||||
private func record() {
|
||||
guard restored, let scroll, let document = scroll.documentView else { return }
|
||||
let y = scroll.contentView.bounds.minY
|
||||
if let table = document as? NSTableView {
|
||||
let index = table.row(at: NSPoint(x: 1, y: y))
|
||||
if ids.indices.contains(index) {
|
||||
let row = table.rect(ofRow: index)
|
||||
changed?(ids[index], Double((y - row.minY) / max(1,row.height))); return
|
||||
}
|
||||
}
|
||||
let range = max(1, document.bounds.height - scroll.contentView.bounds.height)
|
||||
changed?(nil, Double(y/range))
|
||||
}
|
||||
deinit { if let token { NotificationCenter.default.removeObserver(token) } }
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObje
|
||||
basicExamples[id] = workspace
|
||||
return workspace
|
||||
}
|
||||
lazy var softwareLibrary = SoftwareLibraryModel(state: SoftwareLibraryState(directory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary")), artworkDirectory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary/ArtworkCache"), machine: machine,
|
||||
lazy var softwareLibrary = SoftwareLibraryModel(state: SoftwareLibraryState(directory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary")), continuity: LibraryContinuityStore.shared, artworkDirectory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary/ArtworkCache"), machine: machine,
|
||||
sourceWorkspaceIdentity: { [weak self] in self?.development.assistantProjectID ?? UUID() },
|
||||
openSourceProject: { [weak self] directory, identity, configuration in
|
||||
guard let self else { return false }
|
||||
@@ -121,6 +121,7 @@ final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObje
|
||||
#endif
|
||||
}
|
||||
super.init()
|
||||
LibraryContinuityStore.configureShared(directory: profileStore.directory.deletingLastPathComponent())
|
||||
}
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
#if VCC_UI_TESTING
|
||||
@@ -239,6 +240,33 @@ final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObje
|
||||
}
|
||||
private var terminationPending = false
|
||||
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
|
||||
if machine.captures.saving {
|
||||
let alert = NSAlert(); alert.messageText = "Wait for the CoCo image to finish saving."
|
||||
alert.informativeText = "Your captured picture is still being written. Try quitting again after saving completes."
|
||||
alert.runModal()
|
||||
return .terminateCancel
|
||||
}
|
||||
if machine.captures.hasPendingImage {
|
||||
let alert = NSAlert(); alert.messageText = "A captured CoCo image has not been saved."
|
||||
alert.addButton(withTitle: "Cancel Quit"); alert.addButton(withTitle: "Save Image As…"); alert.addButton(withTitle: "Discard Image and Continue")
|
||||
let choice = alert.runModal()
|
||||
if choice == .alertSecondButtonReturn { machine.captures.saveImageAs(); return .terminateCancel }
|
||||
guard choice == .alertThirdButtonReturn else { return .terminateCancel }
|
||||
machine.captures.discardImage()
|
||||
}
|
||||
if machine.captures.active {
|
||||
guard machine.captures.recording, !terminationPending else { return .terminateCancel }
|
||||
let alert = NSAlert(); alert.messageText = "Stop and save the CoCo movie before quitting?"
|
||||
alert.addButton(withTitle: "Cancel Quit"); alert.addButton(withTitle: "Stop and Save")
|
||||
guard alert.runModal() == .alertSecondButtonReturn else { return .terminateCancel }
|
||||
terminationPending = true
|
||||
Task { @MainActor in
|
||||
await machine.captures.stopRecording()
|
||||
terminationPending = false
|
||||
if machine.captures.error == nil { sender.terminate(nil) }
|
||||
}
|
||||
return .terminateCancel
|
||||
}
|
||||
if companionLaunchDeferred {
|
||||
guard !terminationPending else { return .terminateCancel }
|
||||
terminationPending = true
|
||||
@@ -392,6 +420,7 @@ struct MachineCommands: Commands {
|
||||
@FocusedValue(\.emulatorWindow) private var emulatorWindow
|
||||
let machine: MachineModel
|
||||
@ObservedObject private var menu: MachineMenuState
|
||||
@ObservedObject private var captureMenu: CoCoCaptureMenuState
|
||||
@ObservedObject var presentation: PresentationSettings
|
||||
let connectAssistant: () -> Void
|
||||
init(machine: MachineModel, presentation: PresentationSettings, connectAssistant: @escaping () -> Void) {
|
||||
@@ -399,6 +428,7 @@ struct MachineCommands: Commands {
|
||||
self.presentation = presentation
|
||||
self.machine = machine
|
||||
self.menu = machine.menuState
|
||||
self.captureMenu = machine.captures.menuState
|
||||
}
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@CommandsBuilder
|
||||
@@ -414,6 +444,9 @@ struct MachineCommands: Commands {
|
||||
Button("Assembly Quick Reference…") { openWindow(id: "assembly-reference") }
|
||||
Button("Keyboard & Shortcuts…") { openWindow(id: "keyboard-help") }
|
||||
Button("Release History…") { openWindow(id: "release-history") }
|
||||
Button("Feedback…") {
|
||||
NSWorkspace.shared.open(URL(string: "https://vccplus.brianholman.com/feedback/?product=vcc-plus")!)
|
||||
}
|
||||
Button("Licenses & Notices…") { openWindow(id: "credits") }
|
||||
Button("About VCC Plus OSS") { openWindow(id: "about") }
|
||||
}
|
||||
@@ -479,6 +512,16 @@ struct MachineCommands: Commands {
|
||||
Button("Save CoCo Screen…", action: machine.saveScreenshot)
|
||||
.keyboardShortcut("s", modifiers: [.command, .shift])
|
||||
.disabled(menu.values.busy || !(menu.values.state == .running || menu.values.state == .paused))
|
||||
Menu("Quick CoCo Capture") {
|
||||
Button("Capture CoCo Screen", action: machine.captures.capture)
|
||||
CoCoCaptureOptions(preferences: machine.captures.preferences)
|
||||
Button("Cancel Timed Capture", action: machine.captures.cancelCountdown).disabled(!captureMenu.countdown)
|
||||
}.disabled(!(menu.values.state == .running || menu.values.state == .paused))
|
||||
Button(captureMenu.state == .recording ? "Stop CoCo Video Recording" : "Record CoCo Video") {
|
||||
if machine.captures.recording { Task { await machine.captures.stopRecording() } }
|
||||
else { machine.captures.startRecording() }
|
||||
}.disabled(captureMenu.state == .starting || captureMenu.state == .finishing || (captureMenu.state != .recording && !(menu.values.state == .running || menu.values.state == .paused)))
|
||||
Button("Capture Settings…") { openWindow(id: "machine"); machine.captures.settingsShown = true }
|
||||
}
|
||||
CommandGroup(after: .pasteboard) {
|
||||
Divider()
|
||||
|
||||
Reference in new issue
Block a user