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()
|
||||
|
||||
@@ -60,7 +60,7 @@ typedef NS_ENUM(NSInteger, VCCDiskInsertionReset) {
|
||||
@interface VCCMachineSnapshot : NSObject
|
||||
@property(nonatomic, readonly) VCCMachineState state;
|
||||
@property(nonatomic, readonly) uint64_t generation;
|
||||
@property(nonatomic, readonly) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision;
|
||||
@property(nonatomic, readonly) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, debuggerResidencyFingerprint, assistantMediaRevision;
|
||||
@property(nonatomic, readonly) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping;
|
||||
@property(nonatomic, readonly) BOOL debuggerBankedDevelopment;
|
||||
@property(nonatomic, readonly) BOOL basicDebugAttached, assistantCompiledReturned;
|
||||
@@ -221,7 +221,21 @@ typedef void (^VCCMachineCompletion)(VCCMachineSnapshot *snapshot);
|
||||
@property(nonatomic, readonly) NSArray<VCCTraceRecord *> *records;
|
||||
@end
|
||||
|
||||
// Guest-only immutable recording input. Each audio frame is Float32 stereo at
|
||||
// 44.1 kHz. The offset is a monotonic recording timeline, not a CPU cycle count.
|
||||
@interface VCCVideoPacket : NSObject
|
||||
@property(nonatomic, readonly) NSData *pixels, *samples;
|
||||
@property(nonatomic, readonly) CGRect activeArea;
|
||||
@property(nonatomic, readonly) uint64_t sampleOffset;
|
||||
@end
|
||||
|
||||
@interface VCCMachineController : NSObject
|
||||
- (void)beginVideoCaptureWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(beginVideoCapture(completion:));
|
||||
- (void)takeVideoCapturePackets:(BOOL)finish completion:(void (^)(NSArray<VCCVideoPacket *> *, NSString * _Nullable))completion NS_SWIFT_NAME(takeVideoCapture(finish:completion:));
|
||||
// Recording data must continue draining while a native modal loop owns the UI.
|
||||
// Ordinary callers retain the main-queue completion methods above.
|
||||
- (void)beginVideoCaptureOnQueue:(dispatch_queue_t)replyQueue completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(beginVideoCapture(replyQueue:completion:));
|
||||
- (void)takeVideoCapturePackets:(BOOL)finish replyQueue:(dispatch_queue_t)replyQueue completion:(void (^)(NSArray<VCCVideoPacket *> *, NSString * _Nullable))completion NS_SWIFT_NAME(takeVideoCapture(finish:replyQueue:completion:));
|
||||
// Capture starts disabled. Toggling or clearing never pauses/resets the machine.
|
||||
// Closing a UI window has no effect; reset/profile replacement retain output.
|
||||
- (void)setPrinterEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion;
|
||||
@@ -236,7 +250,7 @@ typedef void (^VCCMachineCompletion)(VCCMachineSnapshot *snapshot);
|
||||
// mode: 0 into, 1 over, 2 out. Completion acknowledges start; poll machine state
|
||||
// for the eventual pause. pauseWithCompletion cancels a pending source step.
|
||||
- (void)debuggerStepSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepSource(mode:addresses:locations:bytes:generation:programRevision:mappingFingerprint:programCounter:completion:));
|
||||
- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes moduleIdentifiers:(NSArray<NSString *> *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepBankedSource(mode:addresses:locations:bytes:moduleIdentifiers:generation:programRevision:mappingFingerprint:programCounter:completion:));
|
||||
- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes moduleIdentifiers:(NSArray<NSString *> *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint residencyFingerprint:(uint64_t)residencyFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepBankedSource(mode:addresses:locations:bytes:moduleIdentifiers:generation:programRevision:mappingFingerprint:residencyFingerprint:programCounter:completion:));
|
||||
- (void)debuggerMemoryAtAddress:(uint32_t)address count:(uint32_t)count physical:(BOOL)physical logicalAddress:(uint16_t)logicalAddress os9:(BOOL)os9 decode:(BOOL)decode completion:(void (^)(VCCDebugMemoryCapture *))completion NS_SWIFT_NAME(debuggerMemory(address:count:physical:logicalAddress:os9:decode:completion:));
|
||||
- (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion;
|
||||
- (void)debuggerSetBreakpoints:(NSArray<NSNumber *> *)addresses completion:(VCCMachineCompletion)completion;
|
||||
|
||||
@@ -17,12 +17,21 @@
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
@interface VCCVideoPacket ()
|
||||
@property(nonatomic, readwrite, copy) NSData *pixels, *samples;
|
||||
@property(nonatomic, readwrite) CGRect activeArea;
|
||||
@property(nonatomic, readwrite) uint64_t sampleOffset;
|
||||
@end
|
||||
@implementation VCCVideoPacket
|
||||
@end
|
||||
|
||||
@interface VCCTraceRecord ()
|
||||
@property(nonatomic, readwrite) NSUInteger index;
|
||||
@property(nonatomic, readwrite) uint64_t clock, frame;
|
||||
@@ -291,7 +300,7 @@ static std::vector<uint16_t> DebugAddresses(NSArray<NSNumber*>* values, unsigned
|
||||
@property(nonatomic, readwrite) uint64_t generation, frames, cycles;
|
||||
@property(nonatomic, readwrite, copy) NSArray<VCCJoystickInputSnapshot *> *joystickInputs;
|
||||
@property(nonatomic, readwrite) BOOL keyboardInputHeld;
|
||||
@property(nonatomic, readwrite) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision;
|
||||
@property(nonatomic, readwrite) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, debuggerResidencyFingerprint, assistantMediaRevision;
|
||||
@property(nonatomic, readwrite) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping;
|
||||
@property(nonatomic, readwrite) BOOL debuggerBankedDevelopment;
|
||||
@property(nonatomic, readwrite) BOOL basicDebugAttached, assistantCompiledReturned;
|
||||
@@ -384,6 +393,11 @@ struct Worker {
|
||||
VCC::Mac::MachineSession machine;
|
||||
VCC::Mac::MacAudioOutput audio;
|
||||
bool audioEnabled = false, fastForward = false;
|
||||
bool recording = false;
|
||||
NSMutableArray<VCCVideoPacket *> *recordingPackets = nil;
|
||||
std::chrono::steady_clock::time_point recordingOrigin{}, recordingLast{};
|
||||
uint64_t recordingSample = 0;
|
||||
std::string recordingError;
|
||||
VCC::Mac::FramePacer pacer;
|
||||
VCC::Mac::AudioProgress audioProgress;
|
||||
std::chrono::steady_clock::time_point previousAudioTick{};
|
||||
@@ -500,6 +514,19 @@ std::vector<VCC::Mac::DebugBankedModule> BankedModules(NSArray<NSDictionary<NSSt
|
||||
VCC::Mac::DebugBankedModule parsed;
|
||||
parsed.identifier = identifier.UTF8String;
|
||||
parsed.guards = CodeGuards(addresses, bytes);
|
||||
id overlayGroup = module[@"overlay_group"], overlayOwner = module[@"overlay_owner"];
|
||||
if (overlayGroup || overlayOwner) {
|
||||
if (![overlayGroup isKindOfClass:NSString.class] || ![overlayOwner isKindOfClass:NSString.class] ||
|
||||
![overlayGroup length] || ![overlayOwner length] ||
|
||||
[overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128 ||
|
||||
[overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128)
|
||||
throw std::invalid_argument("Overlay modules require bounded group and owner identities");
|
||||
const char *groupText = [overlayGroup UTF8String], *ownerText = [overlayOwner UTF8String];
|
||||
if (!groupText || !ownerText || std::strlen(groupText) != [overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] ||
|
||||
std::strlen(ownerText) != [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding])
|
||||
throw std::invalid_argument("Overlay identities must not contain embedded NUL bytes");
|
||||
parsed.overlayGroup = groupText; parsed.overlayOwner = ownerText;
|
||||
}
|
||||
if (id qualified = module[@"breakpoints"]) {
|
||||
if (![qualified isKindOfClass:NSArray.class]) throw std::invalid_argument("Module breakpoints must be an array");
|
||||
for (id point in qualified)
|
||||
@@ -528,6 +555,7 @@ VCC::Mac::Snapshot AssemblyIdentity(VCCMachineSnapshot *snapshot) {
|
||||
expected.generation = snapshot.generation;
|
||||
expected.debuggerProgramRevision = snapshot.debuggerProgramRevision;
|
||||
expected.debuggerMappingFingerprint = snapshot.debuggerMappingFingerprint;
|
||||
expected.debuggerResidencyFingerprint = snapshot.debuggerResidencyFingerprint;
|
||||
expected.cpu.PC = snapshot.programCounter;
|
||||
expected.cycles = snapshot.cycles;
|
||||
return expected;
|
||||
@@ -664,6 +692,7 @@ VCCMachineSnapshot *Capture(Worker& worker) {
|
||||
if (worker.closed) result.state = VCCMachineStateClosed;
|
||||
result.generation = value.generation; result.frames = value.frames;
|
||||
result.debuggerProgramRevision = value.debuggerProgramRevision; result.debuggerMappingFingerprint = value.debuggerMappingFingerprint;
|
||||
result.debuggerResidencyFingerprint = value.debuggerResidencyFingerprint;
|
||||
result.debuggerDevelopmentAttached = value.debuggerDevelopmentAttached;
|
||||
result.debuggerBankedDevelopment = value.debuggerBankedDevelopment;
|
||||
result.debuggerAssemblyAttached = value.debuggerAssemblyAttached;
|
||||
@@ -714,6 +743,32 @@ void CheckCompiledRun(Worker& worker, VCCCompiledRunLease *lease, VCCMachineSnap
|
||||
if (!worker.machine.sharedCompiledCallActive())
|
||||
throw std::logic_error(worker.machine.sharedCompiledCallReturned() ? "run_finished" : "unverified_program_entry");
|
||||
}
|
||||
void RecordVideoPacket(Worker& worker, const std::vector<VCC::Mac::StereoSample>& samples) {
|
||||
if (!worker.recording) return;
|
||||
const auto value = worker.machine.snapshot();
|
||||
if (!value.frame || value.frame->pixels.size() != 640 * 480) return;
|
||||
if (worker.recordingPackets.count >= 8) {
|
||||
worker.recording = false;
|
||||
worker.recordingError = "Recording input stopped keeping up. The working movie has been retained; the CoCo keeps running.";
|
||||
return;
|
||||
}
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const auto elapsed = std::chrono::duration<double>(now - worker.recordingOrigin).count();
|
||||
const uint64_t position = std::max(worker.recordingSample, uint64_t(elapsed * 44100));
|
||||
const auto& frame = *value.frame;
|
||||
auto packet = [VCCVideoPacket new];
|
||||
packet.pixels = [NSData dataWithBytes:frame.pixels.data() length:frame.pixels.size() * sizeof(uint32_t)];
|
||||
packet.activeArea = CGRectMake(frame.activeArea.x, frame.activeArea.y, frame.activeArea.width, frame.activeArea.height);
|
||||
packet.samples = [NSData dataWithBytes:samples.data() length:samples.size() * sizeof(VCC::Mac::StereoSample)];
|
||||
packet.sampleOffset = position;
|
||||
worker.recordingSample = position + samples.size(); worker.recordingLast = now;
|
||||
[worker.recordingPackets addObject:packet];
|
||||
}
|
||||
std::vector<VCC::Mac::StereoSample> DrainWorkerAudio(Worker& worker) {
|
||||
auto samples = worker.machine.takeAudio();
|
||||
RecordVideoPacket(worker, samples);
|
||||
return samples;
|
||||
}
|
||||
void AdvanceWorker(Worker& worker) {
|
||||
if (worker.compiledKeyLease) {
|
||||
if (worker.machine.pasteRemaining()) {
|
||||
@@ -749,6 +804,40 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
dispatch_source_t _timer;
|
||||
std::shared_ptr<Worker> _worker;
|
||||
}
|
||||
- (void)beginVideoCaptureWithCompletion:(VCCMachineCompletion)completion {
|
||||
[self beginVideoCaptureOnQueue:dispatch_get_main_queue() completion:completion];
|
||||
}
|
||||
- (void)beginVideoCaptureOnQueue:(dispatch_queue_t)replyQueue completion:(VCCMachineCompletion)completion {
|
||||
auto worker = _worker;
|
||||
dispatch_async(_queue, ^{
|
||||
try {
|
||||
worker->error.clear();
|
||||
worker->requireNoDiskEditor();
|
||||
if (worker->closed || !worker->machine.snapshot().frame) throw std::logic_error("No CoCo picture is available to record.");
|
||||
if (worker->fastForward) throw std::logic_error("Turn off fast-forward before recording video.");
|
||||
if (worker->recording) throw std::logic_error("A CoCo movie is already recording.");
|
||||
worker->recordingPackets = [NSMutableArray new]; worker->recordingError.clear();
|
||||
worker->recordingSample = 0;
|
||||
worker->recordingOrigin = worker->recordingLast = std::chrono::steady_clock::now();
|
||||
worker->recording = true;
|
||||
} catch (const std::exception& error) { worker->error = error.what(); }
|
||||
VCCMachineSnapshot *snapshot = Capture(*worker);
|
||||
dispatch_async(replyQueue, ^{ completion(snapshot); });
|
||||
});
|
||||
}
|
||||
- (void)takeVideoCapturePackets:(BOOL)finish completion:(void (^)(NSArray<VCCVideoPacket *> *, NSString *))completion {
|
||||
[self takeVideoCapturePackets:finish replyQueue:dispatch_get_main_queue() completion:completion];
|
||||
}
|
||||
- (void)takeVideoCapturePackets:(BOOL)finish replyQueue:(dispatch_queue_t)replyQueue completion:(void (^)(NSArray<VCCVideoPacket *> *, NSString *))completion {
|
||||
auto worker = _worker;
|
||||
dispatch_async(_queue, ^{
|
||||
if (finish) worker->recording = false;
|
||||
NSArray *packets = [worker->recordingPackets copy] ?: @[];
|
||||
[worker->recordingPackets removeAllObjects];
|
||||
NSString *error = worker->recordingError.empty() ? nil : [NSString stringWithUTF8String:worker->recordingError.c_str()];
|
||||
dispatch_async(replyQueue, ^{ completion(packets, error); });
|
||||
});
|
||||
}
|
||||
- (instancetype)init {
|
||||
if ((self = [super init])) {
|
||||
_worker = std::make_shared<Worker>();
|
||||
@@ -765,6 +854,8 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
try {
|
||||
if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) {
|
||||
if (worker->audio.running()) worker->audio.stop();
|
||||
if (worker->recording && std::chrono::steady_clock::now() - worker->recordingLast >= std::chrono::microseconds(16667))
|
||||
RecordVideoPacket(*worker, std::vector<VCC::Mac::StereoSample>(735));
|
||||
worker->pacer.reset(); worker->audioProgress.reset(); return;
|
||||
}
|
||||
if (worker->fastForward) {
|
||||
@@ -772,7 +863,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
// input, pause, and automatic media saves keep getting turns.
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(8);
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
AdvanceWorker(*worker); worker->machine.takeAudio();
|
||||
AdvanceWorker(*worker); DrainWorkerAudio(*worker);
|
||||
if (std::chrono::steady_clock::now() >= deadline) break;
|
||||
}
|
||||
} else if (worker->audioEnabled) {
|
||||
@@ -784,7 +875,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
// Roughly 100 ms ahead, at most four frames per queue turn.
|
||||
// The physical audio clock paces production; guest clocks stay fixed.
|
||||
for(unsigned i=0;i<4 && worker->audio.buffer().size()<VCC::Mac::audioTargetSamples;++i) {
|
||||
AdvanceWorker(*worker); auto samples=worker->machine.takeAudio();
|
||||
AdvanceWorker(*worker); auto samples=DrainWorkerAudio(*worker);
|
||||
worker->audio.buffer().write(samples.data(), samples.size());
|
||||
if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) break;
|
||||
}
|
||||
@@ -805,7 +896,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
throw std::runtime_error("Audio output stopped consuming samples. Emulation continues without sound; turn Sound on to retry.");
|
||||
} else {
|
||||
if (worker->pacer.ready(std::chrono::steady_clock::now())) {
|
||||
AdvanceWorker(*worker); worker->machine.takeAudio();
|
||||
AdvanceWorker(*worker); DrainWorkerAudio(*worker);
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
@@ -842,6 +933,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
VCCMachineProfile* p = [profile copy];
|
||||
__block BOOL applied = NO;
|
||||
[self perform:^(Worker& worker) {
|
||||
if (worker.recording) throw std::logic_error("Stop the CoCo movie before replacing the machine profile.");
|
||||
if (worker.closed) throw std::logic_error("The machine controller has shut down");
|
||||
if (p.ram < 0 || p.ram > 3 || p.overclock < 1 || p.overclock > 16 || p.frameInterval < 1 || p.frameInterval > 6 ||
|
||||
p.videoOutput < 0 || p.videoOutput > 2 || p.physicalSlot < 1 || p.physicalSlot > 4 ||
|
||||
@@ -943,6 +1035,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
value.ram = unsigned(ram); value.overclock = unsigned(overclock); value.frameInterval = unsigned(interval);
|
||||
const auto previous = worker.machine.snapshot().configuration;
|
||||
const bool restart = previous.processor != value.processor || previous.ram != value.ram;
|
||||
if (worker.recording && (restart || fastForward)) throw std::logic_error("Stop the CoCo movie before changing CPU/RAM or enabling fast-forward.");
|
||||
if (restart) {
|
||||
if (auto* disk = worker.floppy(); disk && disk->snapshot().busy)
|
||||
throw std::logic_error("Wait for the disk operation to finish before changing CPU or memory.");
|
||||
@@ -976,6 +1069,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
- (void)loadROM:(NSData *)rom use6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion {
|
||||
NSData *owned = [rom copy];
|
||||
[self command:^(Worker& worker) {
|
||||
if (worker.recording) throw std::logic_error("Stop the CoCo movie before replacing the system ROM.");
|
||||
if (owned.length != 0x8000) throw std::invalid_argument("A 32 KiB CoCo 3 ROM image is required");
|
||||
const auto *begin = static_cast<const std::uint8_t *>(owned.bytes);
|
||||
worker.machine.load({begin, begin + owned.length}, use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809);
|
||||
@@ -1414,7 +1508,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
generation, programRevision, mappingFingerprint, programCounter);
|
||||
} completion:completion];
|
||||
}
|
||||
- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes moduleIdentifiers:(NSArray<NSString *> *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion {
|
||||
- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes moduleIdentifiers:(NSArray<NSString *> *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint residencyFingerprint:(uint64_t)residencyFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion {
|
||||
NSArray<NSNumber *> *ownedAddresses = [addresses copy], *ownedLocations = [locations copy];
|
||||
NSArray<NSData *> *ownedBytes = [[NSArray alloc] initWithArray:bytes copyItems:YES];
|
||||
NSArray<NSString *> *identifiers = [[NSArray alloc] initWithArray:moduleIdentifiers copyItems:YES];
|
||||
@@ -1433,7 +1527,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin
|
||||
instructions.push_back({parsed[i], uint32_t(location), OwnedBytes(ownedBytes[i], 8), identifiers[i].UTF8String});
|
||||
}
|
||||
worker.machine.debuggerStepSource(static_cast<VCC::Mac::SourceStepMode>(mode), instructions,
|
||||
generation, programRevision, mappingFingerprint, programCounter);
|
||||
generation, programRevision, mappingFingerprint, programCounter, 1000000, 600, residencyFingerprint);
|
||||
} completion:completion];
|
||||
}
|
||||
- (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion {
|
||||
|
||||
@@ -48,7 +48,7 @@ enum CompanionTransport {
|
||||
}
|
||||
|
||||
enum Failure: LocalizedError {
|
||||
case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut
|
||||
case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut, startupTimedOut
|
||||
case remote(String)
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
@@ -60,11 +60,36 @@ enum CompanionTransport {
|
||||
case .malformedFrame: "The companion service returned an invalid response."
|
||||
case .tooLarge: "The companion request or response exceeds the supported size."
|
||||
case .timedOut: "The companion operation timed out."
|
||||
case .startupTimedOut: "VCC Plus did not finish starting. Check for a macOS permission prompt, then try opening the Software Library again."
|
||||
case .remote(let message): message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Launch Services can return before a cold app finishes macOS startup
|
||||
/// checks. Retry only a missing listener, with a monotonic deadline and
|
||||
/// cancellation; identity/protocol/permission failures remain immediate.
|
||||
static func waitForService(timeout: TimeInterval = 45, retryInterval: TimeInterval = 0.1,
|
||||
now: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
|
||||
sleep: (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) },
|
||||
probe: (TimeInterval) async throws -> Void) async throws {
|
||||
let deadline = now() + timeout
|
||||
while true {
|
||||
try Task.checkCancellation()
|
||||
let remaining = deadline - now()
|
||||
guard remaining > 0 else { throw Failure.startupTimedOut }
|
||||
do {
|
||||
try await probe(remaining)
|
||||
try Task.checkCancellation()
|
||||
return
|
||||
} catch Failure.unavailable {
|
||||
let remaining = deadline - now()
|
||||
guard remaining > 0 else { throw Failure.startupTimedOut }
|
||||
try await sleep(min(retryInterval, remaining))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct Request: Codable {
|
||||
let version: Int
|
||||
let id: UUID
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
Capture feedback audio
|
||||
|
||||
The screenshot cue derives from “iPhone Camera Capture.wav” by pooky1:
|
||||
https://freesound.org/people/pooky1/sounds/431588/
|
||||
The recording-start cue is a trimmed excerpt of “Tape start .wav” by sophiehall3535:
|
||||
https://freesound.org/people/sophiehall3535/sounds/245927/
|
||||
Both original Freesound pages identify Creative Commons Zero (CC0 1.0):
|
||||
https://creativecommons.org/publicdomain/zero/1.0/
|
||||
VCC Plus downmixes and adjusts playback levels, fades cue edges, and removes the
|
||||
tape recording's lead-in and later sounds. These public-domain dedications are
|
||||
separate from the GPL code and the original VCC Plus artwork notice. Source,
|
||||
preparation instructions and file hashes are retained in docs/media/capture-sounds.
|
||||
|
||||
Original VCC
|
||||
|
||||
Original VCC source and Windows About artwork retain their upstream copyright and licensing notices. The complete original Windows credits are included in About and in the Original Windows VCC notice. The GNU GPL version 3 is included in full; the project permits version 3 or later.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,2 +1,4 @@
|
||||
Work with the selected VCC Plus project and its installed development tools.
|
||||
Read the project's source and build configuration before changing it. Preserve the user's documents and media. Use the connection's read-only inspection and BASIC/Assembly lookup tools to understand current state. Run a build or disposable playtest only within the connection's granted capabilities. Verify actual tool discovery and successful requests separately. Report what was checked and any unavailable evidence honestly. The source content profile includes reference lookup rather than the full manual collection. Do not bypass a missing capability through private files or guest-state injection.
|
||||
|
||||
For packed or banked projects, discover get_capabilities before choosing a debugging approach. Check banked_debug_manifest_versions and verified_code_overlays, and use available installed help for the verified physical code overlay contract. Prove the currently loaded owner from complete mapped executable bytes and fresh residency evidence; never guess ownership from an address or reuse a stale owner after replacement. Test loaders through ordinary guest execution, without debugger writes to guest memory or registers.
|
||||
@@ -3,6 +3,7 @@ import CryptoKit
|
||||
import Foundation
|
||||
import PDFKit
|
||||
import SQLite3
|
||||
import SwiftUI
|
||||
import XCTest
|
||||
|
||||
@MainActor
|
||||
@@ -40,6 +41,33 @@ final class ArchiveReaderTests: XCTestCase {
|
||||
|
||||
private struct ReaderTimeout: Error {}
|
||||
|
||||
func testSavedPDFPageAndZoomResumeButExplicitLocationWins() async throws {
|
||||
let pdf = PDFDocument()
|
||||
for color in [NSColor.white, .gray] {
|
||||
let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true }
|
||||
pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount)
|
||||
}
|
||||
let bytes = try XCTUnwrap(pdf.dataRepresentation())
|
||||
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
||||
let item = ArchiveDocument(id: digest, title: "Resume", collection: "Books",
|
||||
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Resume.pdf")!, memberPath: nil,
|
||||
pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Resume.pdf")!, deliveryBytes: Int64(bytes.count))
|
||||
try bytes.write(to: directory.appendingPathComponent(digest + ".pdf"))
|
||||
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
|
||||
store.setReading(LibraryReadingPosition(documentID: digest, page: 2, offset: 0.7, zoom: 1.75, autoScales: false), for: "archive:" + digest)
|
||||
let resumed = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store)
|
||||
defer { resumed.reset() }
|
||||
resumed.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
|
||||
resumed.open(item, page: resumed.savedPage(for: digest), resumePosition: true)
|
||||
try await waitFor { resumed.progress == nil }
|
||||
XCTAssertNil(resumed.error)
|
||||
XCTAssertEqual(resumed.page, 2)
|
||||
XCTAssertEqual(resumed.view.scaleFactor, 1.75, accuracy: 0.01)
|
||||
resumed.open(item, page: 1)
|
||||
XCTAssertEqual(resumed.page, 1)
|
||||
XCTAssertTrue(resumed.view.currentPage === resumed.document?.page(at: 0))
|
||||
}
|
||||
|
||||
func testSelectingPDFPagesReusesTheVerifiedDocumentAndOpensTheCitedPage() async throws {
|
||||
let pdf = PDFDocument()
|
||||
for color in [NSColor.white, .gray] {
|
||||
@@ -75,6 +103,36 @@ final class ArchiveReaderTests: XCTestCase {
|
||||
XCTAssertTrue(model.view.currentPage === rendered.page(at: 0))
|
||||
}
|
||||
|
||||
func testExplicitSamePageDuringPDFResumeDiscardsSavedZoomAndOffset() async throws {
|
||||
let pdf = PDFDocument()
|
||||
let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in NSColor.white.setFill(); rect.fill(); return true }
|
||||
pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: 0)
|
||||
let bytes = try XCTUnwrap(pdf.dataRepresentation())
|
||||
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
||||
let item = ArchiveDocument(id: digest, title: "Same page", collection: "Books",
|
||||
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Same.pdf")!, memberPath: nil,
|
||||
pageCount: 1, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Same.pdf")!, deliveryBytes: Int64(bytes.count))
|
||||
try bytes.write(to: directory.appendingPathComponent(digest + ".pdf"))
|
||||
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
|
||||
store.setReading(LibraryReadingPosition(documentID: digest, page: 1, offset: 0.7, horizontalOffset: 0.6, zoom: 9, autoScales: false), for: "archive:" + digest)
|
||||
let model = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store)
|
||||
defer { model.reset() }
|
||||
model.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
|
||||
model.open(item, page: 1, resumePosition: true)
|
||||
XCTAssertNotNil(model.progress)
|
||||
// Both calls occur before the load task gets its first execution turn:
|
||||
// same bytes and same page, but the second action is an explicit link.
|
||||
model.open(item, page: 1, resumePosition: false)
|
||||
try await waitFor { model.progress == nil }
|
||||
XCTAssertNil(model.error)
|
||||
XCTAssertEqual(model.page, 1)
|
||||
XCTAssertTrue(model.view.autoScales, "An explicit target must not inherit the pending resume's manual zoom")
|
||||
XCTAssertNotEqual(model.view.scaleFactor, 9)
|
||||
let position = try XCTUnwrap(store.reading(for: "archive:" + digest))
|
||||
XCTAssertNotEqual(position.offset, 0.7, "An explicit target must not restore the old within-page offset")
|
||||
XCTAssertNotEqual(position.horizontalOffset, 0.6)
|
||||
}
|
||||
|
||||
func testSelectingTextThenCachedImageReplacesThePreview() async throws {
|
||||
let model = ArchiveReaderModel(remembersPage: false, cache: cache)
|
||||
defer { model.reset() }
|
||||
@@ -108,6 +166,49 @@ final class ArchiveReaderTests: XCTestCase {
|
||||
XCTAssertNil(model.referenceID)
|
||||
}
|
||||
|
||||
func testExplicitTextNavigationOverridesInFlightAndVisibleResume() async throws {
|
||||
_ = NSApplication.shared
|
||||
let bytes = Data((0..<250).map { "Line \($0): Archive reading position fixture." }.joined(separator: "\n").utf8)
|
||||
let item = record("Resume.txt", format: "text", bytes: bytes)
|
||||
try bytes.write(to: directory.appendingPathComponent(item.id + ".txt"))
|
||||
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
|
||||
store.setReading(LibraryReadingPosition(documentID: item.id, offset: 0.65), for: "archive:" + item.id)
|
||||
let model = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store)
|
||||
defer { model.reset() }
|
||||
model.open(item, page: 1, resumePosition: true)
|
||||
model.open(item, page: 1, resumePosition: false)
|
||||
try await waitFor { model.progress == nil }
|
||||
XCTAssertNil(model.error)
|
||||
XCTAssertEqual(model.inlinePosition?.offset, 0, "Explicit intent must replace the in-flight resume's saved inline position")
|
||||
|
||||
model.updateInlinePosition(offset: 0.65)
|
||||
let host = NSHostingView(rootView: ArchiveReaderPane(record: item, hit: nil, reader: model,
|
||||
requestedPage: 1, catalog: ArchiveLibraryCatalog(url: nil), resumesPosition: true))
|
||||
host.frame = NSRect(x: 0, y: 0, width: 700, height: 500)
|
||||
func textView(_ root: NSView) -> NSTextView? {
|
||||
if let text = root as? NSTextView, text.accessibilityIdentifier() == "archive-inline-text" { return text }
|
||||
return root.subviews.lazy.compactMap { textView($0) }.first
|
||||
}
|
||||
host.layoutSubtreeIfNeeded()
|
||||
try await waitFor {
|
||||
host.layoutSubtreeIfNeeded()
|
||||
return textView(host)?.enclosingScrollView?.contentView.bounds.minY ?? 0 > 100
|
||||
}
|
||||
let resumedText = try XCTUnwrap(textView(host))
|
||||
let revision = model.inlineNavigationRevision
|
||||
model.open(item, page: 1, resumePosition: true)
|
||||
XCTAssertEqual(model.inlineNavigationRevision, revision)
|
||||
XCTAssertGreaterThan(resumedText.enclosingScrollView?.contentView.bounds.minY ?? 0, 100)
|
||||
model.open(item, page: 1, resumePosition: false)
|
||||
try await waitFor {
|
||||
host.layoutSubtreeIfNeeded()
|
||||
guard let current = textView(host), current !== resumedText else { return false }
|
||||
return (current.enclosingScrollView?.contentView.bounds.minY ?? 1) == 0
|
||||
}
|
||||
XCTAssertEqual(model.inlinePosition?.offset, 0)
|
||||
withExtendedLifetime(host) {}
|
||||
}
|
||||
|
||||
func testTextReaderPreservesLegacyEncodingsAndRemovesFloppyPadding() throws {
|
||||
let url = directory.appendingPathComponent("Letter.txt")
|
||||
let accented = "Café\n£5"
|
||||
|
||||
@@ -164,6 +164,22 @@ final class BASICReferenceTests: XCTestCase {
|
||||
XCTAssertFalse(content.allowsExternalReference(URL(fileURLWithPath: "/tmp/private.txt")))
|
||||
}
|
||||
|
||||
func testOverlayContractIsDiscoverableAndReadableThroughTheBundledMCPIndex() async throws {
|
||||
try requireFullManualEdition()
|
||||
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
|
||||
let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app")))
|
||||
let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil))
|
||||
let index = MCPHelpIndex(root: root)
|
||||
let hits = try await index.search("overlayGroups")
|
||||
let hit = try XCTUnwrap(hits.first { $0.id.hasSuffix("#verified-physical-code-overlays") })
|
||||
let read = try await index.read(hit.id)
|
||||
let topic = try XCTUnwrap(read)
|
||||
for field in ["banked_debug_manifest_versions", "verified_code_overlays", "overlayGroups", "residency_fingerprint"] {
|
||||
XCTAssertTrue(topic.text.contains(field), field)
|
||||
}
|
||||
XCTAssertLessThanOrEqual(topic.text.utf8.count, 12 * 1024, "The complete contract must fit a read_topic response")
|
||||
}
|
||||
|
||||
func testOriginalToolReferencesAreReadableThroughTheNativeMCPIndex() async throws {
|
||||
try requireFullManualEdition()
|
||||
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
|
||||
|
||||
@@ -2,51 +2,306 @@
|
||||
import XCTest
|
||||
|
||||
final class CMOCSourceMapTests: XCTestCase {
|
||||
/// Explicit opt-in diagnostic for any retained custom project's immutable
|
||||
/// build result. No project Makefile is executed and no emulator is loaded.
|
||||
func testExplicitlySuppliedBankedBuildEvidence() throws {
|
||||
private enum RetainedEvidenceFailure: Error { case missingCompilationRoot, ambiguousCompilationRoot }
|
||||
|
||||
/// Test harness recovery only. Ordinary CMOC markers survive optimized builds
|
||||
/// even when optional VCCDBG1 type records are absent. Never infer from a Mac
|
||||
/// username, output directory name or current project location.
|
||||
private func retainedCompilationDirectory(files: [String: Data], entrySource: String) throws -> URL {
|
||||
let pattern = try NSRegularExpression(pattern: #"\* (?:Line (.+):([0-9]+)(?::.*)?|FUNCTION .+: defined at (.+):([0-9]+))$"#)
|
||||
var roots = Set<String>()
|
||||
func consider(_ path: String) {
|
||||
guard path.hasPrefix("/"), path.hasSuffix("/" + entrySource) else { return }
|
||||
roots.insert(URL(fileURLWithPath: String(path.dropLast(entrySource.count))).standardizedFileURL.path)
|
||||
}
|
||||
for (name, data) in files where ["s", "lst"].contains((name as NSString).pathExtension.lowercased()) {
|
||||
guard let text = String(data: data, encoding: .utf8) else { continue }
|
||||
for row in text.components(separatedBy: .newlines) {
|
||||
if let marker = row.range(of: "* VCCDBG1 "),
|
||||
let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any],
|
||||
let location = record["location"] as? String, let colon = location.lastIndex(of: ":") {
|
||||
consider(String(location[..<colon]))
|
||||
}
|
||||
let ns = row as NSString
|
||||
if let match = pattern.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) {
|
||||
let index = match.range(at: 1).location == NSNotFound ? 3 : 1
|
||||
consider(ns.substring(with: match.range(at: index)))
|
||||
}
|
||||
}
|
||||
}
|
||||
guard !roots.isEmpty else { throw RetainedEvidenceFailure.missingCompilationRoot }
|
||||
guard roots.count == 1, let root = roots.first else { throw RetainedEvidenceFailure.ambiguousCompilationRoot }
|
||||
return URL(fileURLWithPath: root, isDirectory: true)
|
||||
}
|
||||
|
||||
private func explicitlySuppliedBankedArtifact() throws -> CMOCBuildArtifact {
|
||||
guard let path = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT"] else {
|
||||
throw XCTSkip("Supply a retained banked artifact directory for project qualification.")
|
||||
}
|
||||
let directory = URL(fileURLWithPath: path).resolvingSymlinksInPath()
|
||||
if let expected = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT_ID"] {
|
||||
XCTAssertEqual(directory.lastPathComponent, expected, "Qualification must read the explicitly selected artifact")
|
||||
}
|
||||
let project = try CMOCProject.open(at: directory)
|
||||
let files = try CMOCProject.files(in: directory)
|
||||
let sources = files.filter { CMOCProject.isSource($0.key) && String(data: $0.value, encoding: .utf8) != nil && !$0.value.contains(0) }
|
||||
let settings = project.configuration
|
||||
let entry = try XCTUnwrap(sources[settings.entrySource])
|
||||
let binaryPath = try XCTUnwrap(settings.binary)
|
||||
let binary = try XCTUnwrap(files[binaryPath])
|
||||
// Compiler source markers retain the original isolated working folder.
|
||||
// Recover it from a full, retained metadata record rather than assuming
|
||||
// it is the current output folder or a historical machine path.
|
||||
var compilationDirectory: URL?
|
||||
for (name, data) in sources where name.hasSuffix(".s") {
|
||||
guard let text = String(data: data, encoding: .utf8) else { continue }
|
||||
for row in text.components(separatedBy: .newlines) {
|
||||
guard let marker = row.range(of: "* VCCDBG1 "),
|
||||
let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any],
|
||||
let location = record["location"] as? String, let colon = location.lastIndex(of: ":") else { continue }
|
||||
let sourcePath = String(location[..<colon])
|
||||
if sourcePath.hasPrefix("/"), sourcePath.hasSuffix("/" + settings.entrySource) {
|
||||
compilationDirectory = URL(fileURLWithPath: String(sourcePath.dropLast(settings.entrySource.count)))
|
||||
break
|
||||
}
|
||||
}
|
||||
if compilationDirectory != nil { break }
|
||||
}
|
||||
let artifact = CMOCBuildArtifact(id: UUID(), directory: directory, source: String(decoding: entry, as: UTF8.self),
|
||||
let binaryPath = try XCTUnwrap(settings.binary), binary = try XCTUnwrap(files[binaryPath])
|
||||
let manifestPath = try XCTUnwrap(settings.debugManifest), manifest = try XCTUnwrap(files[manifestPath])
|
||||
print("Retained qualification identity: artifact=\(directory.lastPathComponent), manifest_sha256=\(CMOCSourceMap.sha256(manifest)), binary_sha256=\(CMOCSourceMap.sha256(binary)).")
|
||||
return CMOCBuildArtifact(id: UUID(), directory: directory, source: String(decoding: entry, as: UTF8.self),
|
||||
sourceData: entry, sourceSHA256: CMOCProject.sha256(entry), binaryData: binary, buildLog: "",
|
||||
sources: sources, compilationDirectory: try XCTUnwrap(compilationDirectory), entrySourcePath: settings.entrySource,
|
||||
binaryRelativePath: binaryPath, diskRelativePath: settings.diskImage, outputPaths: files.keys.sorted(),
|
||||
debugManifestRelativePath: settings.debugManifest)
|
||||
sources: sources, compilationDirectory: try retainedCompilationDirectory(files: files, entrySource: settings.entrySource),
|
||||
entrySourcePath: settings.entrySource, binaryRelativePath: binaryPath, diskRelativePath: settings.diskImage,
|
||||
outputPaths: files.keys.sorted(), debugManifestRelativePath: settings.debugManifest)
|
||||
}
|
||||
|
||||
/// Explicit opt-in typed Debug qualification remains strict: a verified
|
||||
/// executable does not substitute for real compiler type/function metadata.
|
||||
func testExplicitlySuppliedBankedBuildEvidence() throws {
|
||||
let artifact = try explicitlySuppliedBankedArtifact()
|
||||
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
|
||||
XCTAssertNotNil(map.bankedLayout)
|
||||
XCTAssertFalse(map.instructions.isEmpty)
|
||||
XCTAssertNotNil(map.bankedLayout); XCTAssertFalse(map.instructions.isEmpty)
|
||||
let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map)
|
||||
XCTAssertFalse(metadata.functions.isEmpty)
|
||||
print("Verified retained banked artifact: \(map.bankedLayout?.modules.count ?? 0) modules, \(map.instructions.count) instructions, \(metadata.functions.count) functions, \(metadata.variables.count) variables.")
|
||||
}
|
||||
|
||||
/// Release builds may deliberately omit type records. This separate opt-in
|
||||
/// still requires complete executable/source mapping and reports typed limits.
|
||||
func testExplicitlySuppliedBankedExecutableEvidence() throws {
|
||||
let artifact = try explicitlySuppliedBankedArtifact()
|
||||
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
|
||||
XCTAssertNotNil(map.bankedLayout); XCTAssertFalse(map.instructions.isEmpty)
|
||||
XCTAssertFalse(map.executableSymbols.isEmpty)
|
||||
let metadata: CMOCVariableDebug?, reason: String?
|
||||
do { metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map); reason = nil }
|
||||
catch { metadata = nil; reason = error.localizedDescription }
|
||||
let fields = CMOCPublicDebugEvidence.fields(map: map, metadata: metadata, variableError: reason, sharedPaths: Set(artifact.sources.keys))
|
||||
XCTAssertEqual(fields["source_map"] as? String, "verified")
|
||||
if metadata == nil {
|
||||
XCTAssertEqual(fields["status"] as? String, "source_only")
|
||||
XCTAssertEqual(fields["variables"] as? String, "unavailable")
|
||||
XCTAssertFalse(try XCTUnwrap(fields["reason"] as? String).isEmpty)
|
||||
} else { XCTAssertEqual(fields["status"] as? String, "verified") }
|
||||
print("Verified retained executable: \(map.bankedLayout?.modules.count ?? 0) modules, \(map.instructions.count) instructions, \(map.executableSymbols.count) executable symbols; typed metadata: \(reason ?? "verified").")
|
||||
}
|
||||
|
||||
func testRetainedCompilationRootUsesOrdinaryMarkersWithoutInventingTypeMetadata() throws {
|
||||
let root = "/private/tmp/authored build/project"
|
||||
let function = Data("* FUNCTION main(): defined at \(root)/src/main.c:7\n".utf8)
|
||||
XCTAssertEqual(try retainedCompilationDirectory(files: ["obj/main.s": function], entrySource: "src/main.c").path, root)
|
||||
let listing = Data("(obj/main.s):00018 * Line \(root)/src/main.c:8: inline assembly\n".utf8)
|
||||
XCTAssertEqual(try retainedCompilationDirectory(files: ["obj/main.lst": listing], entrySource: "src/main.c").path, root)
|
||||
let metadata = Data("* VCCDBG1 {\"location\":\"\(root)/src/main.c:9\"}\n".utf8)
|
||||
XCTAssertEqual(try retainedCompilationDirectory(files: ["obj/main.s": metadata], entrySource: "src/main.c").path, root)
|
||||
XCTAssertThrowsError(try retainedCompilationDirectory(files: ["obj/other.s": function], entrySource: "other.c"))
|
||||
let conflicting = function + Data("* Line /private/tmp/different/src/main.c:4\n".utf8)
|
||||
XCTAssertThrowsError(try retainedCompilationDirectory(files: ["obj/main.s": conflicting], entrySource: "src/main.c"))
|
||||
}
|
||||
|
||||
func testExplicitPhysicalOverlaysRequireExclusiveOwnersAndResidentCodeProof() throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCOverlay-" + UUID().uuidString).resolvingSymlinksInPath()
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let source = Data("void a(void) {}\nvoid b(void) {}\n".utf8)
|
||||
let packed = binary([(0x0e00, [0x12])], entry: 0x0e00)
|
||||
let names = ["a1", "a2", "b1", "b2"]
|
||||
let opcodes: [UInt8] = [0x12, 0x39, 0x13, 0x3a]
|
||||
let objectBytes = object(zip(names, opcodes).map { Section(name: $0.0, bytes: [$0.1]) })
|
||||
let listing = Data(names.enumerated().flatMap { index, name in
|
||||
[row("SECTION \(name)"), row("* Line main.c:\(index < 2 ? 1 : 2)"), row("NOP", offset: 0, bytes: [opcodes[index]]), row("ENDSECTION")]
|
||||
}.joined(separator: "\n").utf8)
|
||||
let placements = names.enumerated().map { index, name in "Section: \(name) (main.o) load at \(index % 2 == 0 ? "4000" : "5000"), length 0001" }
|
||||
let map = Data((placements + ["Section: dataA (runtime.o) load at 6000, length 0001", "Section: dataB (runtime.o) load at 6000, length 0001", "Section: bssA (runtime.o) load at 6100, length 0001", "Section: bssB (runtime.o) load at 6100, length 0001", "Section: resident (runtime.o) load at 7000, length 0001"]).joined(separator: "\n").utf8)
|
||||
var files = ["game.bin": packed, "game.map": map, "main.o": objectBytes, "main.lst": listing,
|
||||
"a1.raw": Data([opcodes[0]]), "a2.raw": Data([opcodes[1]]), "b1.raw": Data([opcodes[2]]), "b2.raw": Data([opcodes[3]]),
|
||||
"dataA.raw": Data([0x42]), "dataB.raw": Data([0x99]), "resident.raw": Data([0x39])]
|
||||
var modules: [[String: Any]] = names.enumerated().map { index, name in
|
||||
["id": name, "sections": [name], "codeSections": [name],
|
||||
"image": ["path": name + ".raw", "logicalAddress": index % 2 == 0 ? 0x4000 : 0x5000],
|
||||
"pages": [["logicalPage": 2, "physicalPage": 30]],
|
||||
"overlay": ["group": "stages", "owner": index < 2 ? "A" : "B"]]
|
||||
}
|
||||
for owner in ["A", "B"] {
|
||||
modules.append(["id": "data" + owner, "sections": ["data" + owner], "codeSections": [],
|
||||
"image": ["path": "data" + owner + ".raw", "logicalAddress": 0x6000],
|
||||
"pages": [["logicalPage": 3, "physicalPage": 31]], "overlay": ["group": "stages", "owner": owner]])
|
||||
modules.append(["id": "bss" + owner, "sections": ["bss" + owner], "codeSections": [],
|
||||
"pages": [["logicalPage": 3, "physicalPage": 31]], "overlay": ["group": "stages", "owner": owner]])
|
||||
}
|
||||
modules.append(["id": "resident", "sections": ["resident"], "codeSections": ["resident"],
|
||||
"image": ["path": "resident.raw", "logicalAddress": 0x7000], "pages": [["logicalPage": 3, "physicalPage": 31]]])
|
||||
func manifest(_ edit: (inout [String: Any]) -> Void = { _ in }) throws -> Data {
|
||||
var value: [String: Any] = ["version": 2, "entryPoint": 0x0e00,
|
||||
"binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)],
|
||||
"linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)],
|
||||
"sources": ["main.c": CMOCSourceMap.sha256(source)],
|
||||
"artifacts": files.filter { $0.key != "game.bin" && $0.key != "game.map" }.mapValues(CMOCSourceMap.sha256),
|
||||
"overlayGroups": [["id": "stages", "owners": ["A", "B"]]], "modules": modules]
|
||||
edit(&value); return try JSONSerialization.data(withJSONObject: value)
|
||||
}
|
||||
func layout(_ edit: (inout [String: Any]) -> Void = { _ in }) throws -> CMOCBankedDebugLayout {
|
||||
for (name, bytes) in files { try bytes.write(to: directory.appendingPathComponent(name)) }
|
||||
return try CMOCBankedDebugLayout.parse(data: manifest(edit), directory: directory, sources: ["main.c": source], binary: packed,
|
||||
binaryPath: "game.bin", allowedOutputs: Array(files.keys))
|
||||
}
|
||||
let verified = try layout()
|
||||
XCTAssertTrue(verified.permitsPhysicalOverlap(between: "a1", and: "b1"))
|
||||
XCTAssertFalse(verified.permitsPhysicalOverlap(between: "a1", and: "a2"))
|
||||
let mapping = try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: directory,
|
||||
units: [.init(sourcePath: "main.c", sourceName: "main.c", objectName: "main.o", listing: listing, object: objectBytes)],
|
||||
linkMap: map, binary: packed, bankedLayout: verified)
|
||||
XCTAssertEqual(mapping.instructions.count, 4, "Distinct exclusive owners may occupy the same physical instruction identity")
|
||||
XCTAssertEqual(mapping.projected(physicalPages: [2: 30, 3: 31]).activeModuleIDs, ["resident"], "Pages alone never identify an overlay owner")
|
||||
var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536)
|
||||
memory[0x4000] = opcodes[0]; memory[0x5000] = opcodes[1]; memory[0x7000] = 0x39
|
||||
func selected() -> CMOCProjectSourceMap { mapping.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available) }
|
||||
XCTAssertEqual(selected().activeModuleIDs, ["a1", "a2", "dataA", "bssA", "resident"])
|
||||
XCTAssertEqual(selected().instructions.map(\.moduleID), ["a1", "a2"])
|
||||
let typed = CMOCVariableDebug(functions: [
|
||||
.init(name: "stage", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "a1"),
|
||||
.init(name: "stage", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "b1")], variables: [
|
||||
.init(name: "stateA", sourcePath: "main.c", line: 1, type: .integer, address: 0x6100, offset: nil, scope: nil, isStatic: false, moduleID: "bssA"),
|
||||
.init(name: "stateB", sourcePath: "main.c", line: 2, type: .integer, address: 0x6100, offset: nil, scope: nil, isStatic: false, moduleID: "bssB"),
|
||||
.init(name: "wrongScope", sourcePath: "main.c", line: 1, type: .integer, address: 0x6000, offset: nil, scope: 0x4000..<0x4001, isStatic: true, moduleID: "dataA", scopeModuleID: "b1")], sourceMap: mapping)
|
||||
func typedSelection() -> CMOCVariableDebug { typed.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available) }
|
||||
XCTAssertTrue(typed.projected(physicalPages: [2: 30, 3: 31]).variables.isEmpty)
|
||||
XCTAssertEqual(typedSelection().variables.map(\.name), ["stateA"], "BSS inherits only its uniquely proven owner; lexical owner must also match")
|
||||
XCTAssertEqual(typedSelection().entryFunction(named: "stage")?.moduleID, "a1")
|
||||
memory[0x5000] = opcodes[3]
|
||||
XCTAssertEqual(selected().activeModuleIDs, ["resident"], "A half-loaded owner must not establish residency")
|
||||
XCTAssertTrue(typedSelection().functions.isEmpty); XCTAssertTrue(typedSelection().variables.isEmpty)
|
||||
memory[0x4000] = opcodes[2]
|
||||
XCTAssertEqual(selected().activeModuleIDs, ["b1", "b2", "dataB", "bssB", "resident"])
|
||||
XCTAssertEqual(typedSelection().variables.map(\.name), ["stateB"])
|
||||
XCTAssertEqual(typedSelection().entryFunction(named: "stage")?.moduleID, "b1")
|
||||
available[0x5000] = 0
|
||||
XCTAssertEqual(selected().activeModuleIDs, ["resident"], "Unavailable executable bytes never establish residency")
|
||||
XCTAssertThrowsError(try layout { $0["version"] = 1 })
|
||||
XCTAssertThrowsError(try layout { $0.removeValue(forKey: "overlayGroups") })
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
var changed = modules; changed[2]["overlay"] = ["group": "stages", "owner": "A"]; value["modules"] = changed
|
||||
}, "Same-owner physical overlap remains invalid")
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
var changed = modules; changed[2].removeValue(forKey: "overlay"); value["modules"] = changed
|
||||
}, "Ordinary resident code cannot share overlay storage")
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
value["overlayGroups"] = [["id": "stages", "owners": ["A", "B", "unused"]]]
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
var changed = modules; changed[5]["overlay"] = ["group": "stages", "owner": "C"]
|
||||
value["modules"] = changed; value["overlayGroups"] = [["id": "stages", "owners": ["A", "B", "C"]]]
|
||||
}, "A data/BSS-only owner has no immutable executable residency proof")
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
value["overlayGroups"] = [["id": "stages", "owners": ["A", "A"]]]
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
var changed = modules; changed[2]["overlay"] = ["group": "other", "owner": "C"]
|
||||
value["modules"] = changed
|
||||
value["overlayGroups"] = [["id": "stages", "owners": ["A", "B"]], ["id": "other", "owners": ["C", "D"]]]
|
||||
}, "Different overlay groups may coexist and cannot share physical storage") {
|
||||
XCTAssertTrue($0.localizedDescription.contains("module images overlap physical RAM"))
|
||||
}
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
var changed = modules; changed[0]["overlay"] = ["group": "stages", "owner": "unknown"]; value["modules"] = changed
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
value["overlayGroups"] = [["id": "stages", "owners": ["A", "B"]], ["id": "stages", "owners": ["C", "D"]]]
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
value["overlayGroups"] = [["id": String(repeating: "x", count: 129), "owners": ["A", "B"]]]
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
value["overlayGroups"] = (0..<65).map { ["id": "g\($0)", "owners": ["A", "B"]] }
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
value["overlayGroups"] = [["id": "stages", "owners": (0..<257).map { "o\($0)" }]]
|
||||
})
|
||||
XCTAssertThrowsError(try layout { value in
|
||||
// Even null metadata cannot silently downgrade to version 1.
|
||||
value["version"] = 1; value["overlayGroups"] = NSNull()
|
||||
})
|
||||
let catalog = CMOCPublicDebugEvidence.fields(map: mapping, metadata: nil, variableError: nil, sharedPaths: ["main.c"])
|
||||
XCTAssertEqual(catalog["supported_manifest_versions"] as? [Int], [1, 2])
|
||||
XCTAssertEqual(catalog["module_catalog_scope"] as? String, "verified_static_declarations_not_residency")
|
||||
XCTAssertEqual((catalog["overlay_groups"] as? [[String: Any]])?.first?["owners"] as? [String], ["A", "B"])
|
||||
XCTAssertNil(catalog["active_overlay_owners"], "Build declarations never assert runtime residency")
|
||||
files["b1.raw"] = files["a1.raw"]; files["b2.raw"] = files["a2.raw"]
|
||||
let ambiguousLayout = try layout()
|
||||
let ambiguous = CMOCProjectSourceMap(entryPoint: mapping.entryPoint, binarySHA256: mapping.binarySHA256, sourceHashes: mapping.sourceHashes,
|
||||
instructions: mapping.instructions, objectHashes: mapping.objectHashes, listingHashes: mapping.listingHashes,
|
||||
linkMapSHA256: mapping.linkMapSHA256, bankedLayout: ambiguousLayout)
|
||||
memory[0x4000] = opcodes[0]; memory[0x5000] = opcodes[1]; available[0x5000] = 1
|
||||
XCTAssertEqual(ambiguous.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available).activeModuleIDs, ["resident"],
|
||||
"Identical code signatures must not guess an owner or expose its BSS")
|
||||
}
|
||||
|
||||
func testGeneratedAssemblyEvidenceUsesTypedBudgetsAndExactIdentity() throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCEvidence-" + UUID().uuidString).resolvingSymlinksInPath()
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let source = Data("void main(void) {}\n".utf8)
|
||||
let packed = binary([(0x0e00, [0x12])], entry: 0x0e00)
|
||||
let map = Data("Section: code (main.o) load at 4000, length 0001\n".utf8)
|
||||
let raw = Data([0x39])
|
||||
for (name, data) in ["game.bin": packed, "game.map": map, "code.raw": raw] {
|
||||
try data.write(to: directory.appendingPathComponent(name))
|
||||
}
|
||||
var artifacts = ["code.raw": CMOCSourceMap.sha256(raw)]
|
||||
func parse(outputs: [String]? = nil) throws -> CMOCBankedDebugLayout {
|
||||
let value: [String: Any] = ["version": 1, "entryPoint": 0x0e00,
|
||||
"binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)],
|
||||
"linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)],
|
||||
"sources": ["main.c": CMOCSourceMap.sha256(source)], "artifacts": artifacts,
|
||||
"modules": [["id": "code", "sections": ["code"], "codeSections": ["code"],
|
||||
"image": ["path": "code.raw", "logicalAddress": 0x4000],
|
||||
"pages": [["logicalPage": 2, "physicalPage": 30]]]]]
|
||||
return try CMOCBankedDebugLayout.parse(data: JSONSerialization.data(withJSONObject: value),
|
||||
directory: directory, sources: ["main.c": source], binary: packed, binaryPath: "game.bin",
|
||||
allowedOutputs: outputs ?? (["game.bin", "game.map"] + Array(artifacts.keys)))
|
||||
}
|
||||
// A compiler can emit large type records/data while retaining small code.
|
||||
let assembly = Data(repeating: 0x3b, count: 9 * 1024 * 1024 + 17)
|
||||
let path = "generated.s", file = directory.appendingPathComponent(path)
|
||||
try assembly.write(to: file); artifacts[path] = CMOCSourceMap.sha256(assembly)
|
||||
let verified = try parse()
|
||||
XCTAssertEqual(verified.artifactHashes[path], CMOCSourceMap.sha256(assembly))
|
||||
XCTAssertEqual(verified.modules.first?.physicalAddress(0x4000), 30 * 8192)
|
||||
XCTAssertNoThrow(try CMOCSourceMap.validateEvidenceSize(assembly.count, path: path))
|
||||
XCTAssertThrowsError(try parse(outputs: ["game.bin", "game.map", "code.raw"]))
|
||||
try Data(repeating: 0x21, count: assembly.count).write(to: file)
|
||||
XCTAssertThrowsError(try parse()) { XCTAssertTrue($0.localizedDescription.contains("generated.s SHA-256")) }
|
||||
try FileManager.default.removeItem(at: file)
|
||||
try FileManager.default.createSymbolicLink(at: file, withDestinationURL: directory.appendingPathComponent("code.raw"))
|
||||
XCTAssertThrowsError(try parse()) { XCTAssertTrue($0.localizedDescription.contains("generated.s must not traverse symbolic links")) }
|
||||
try FileManager.default.removeItem(at: file)
|
||||
artifacts.removeValue(forKey: path)
|
||||
for (name, size, limit) in [("oversized.s", 32 * 1024 * 1024 + 1, 32 * 1024 * 1024),
|
||||
("oversized.lst", 8 * 1024 * 1024 + 1, 8 * 1024 * 1024)] {
|
||||
let bytes = Data(repeating: 0x3b, count: size)
|
||||
try bytes.write(to: directory.appendingPathComponent(name)); artifacts[name] = CMOCSourceMap.sha256(bytes)
|
||||
XCTAssertThrowsError(try parse()) {
|
||||
let message = $0.localizedDescription
|
||||
XCTAssertTrue(message.contains(name)); XCTAssertTrue(message.contains("\(size) bytes"))
|
||||
XCTAssertTrue(message.contains("\(limit) bytes"))
|
||||
}
|
||||
XCTAssertThrowsError(try CMOCSourceMap.validateEvidenceSize(size, path: name))
|
||||
artifacts.removeValue(forKey: name)
|
||||
try FileManager.default.removeItem(at: directory.appendingPathComponent(name))
|
||||
}
|
||||
let chunk = Data(repeating: 0x3b, count: 27 * 1024 * 1024)
|
||||
let hash = CMOCSourceMap.sha256(chunk)
|
||||
for index in 0..<5 {
|
||||
let name = "part\(index).s"
|
||||
try chunk.write(to: directory.appendingPathComponent(name)); artifacts[name] = hash
|
||||
}
|
||||
XCTAssertThrowsError(try parse()) {
|
||||
XCTAssertTrue($0.localizedDescription.contains("aggregate limit is 134217728 bytes"))
|
||||
}
|
||||
}
|
||||
|
||||
// Small LWOBJ16 records are constructed here to exercise relocation failures
|
||||
// independently of a compiler installation or personal ROM files.
|
||||
private struct Section {
|
||||
|
||||
@@ -354,6 +354,60 @@ final class CartridgePersistenceTests: XCTestCase {
|
||||
XCTAssertFalse(model.disks[0].dirty); XCTAssertTrue(model.diskConnected)
|
||||
}
|
||||
}
|
||||
@MainActor func testMediaCommandsRecheckActiveTransferWithoutChangingDisksOnBothCPUs() async throws {
|
||||
// The native controls remain available during guest I/O. Their safety
|
||||
// must come from the worker's current state, not a stale UI snapshot.
|
||||
for use6309 in [false, true] {
|
||||
let controller = VCCMachineController()
|
||||
func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
||||
await withCheckedContinuation { c in action { c.resume(returning: $0) } }
|
||||
}
|
||||
let original = Data(repeating: 0, count: 161280)
|
||||
_ = await step { controller.loadDiskROM(Data(repeating: 0, count: 8192), name: "Original ROM", completion: $0) }
|
||||
_ = await step { controller.mountDisk(original, drive: 0, name: "Original.dsk", readOnly: false, completion: $0) }
|
||||
var system = Data(repeating: 0, count: 32768)
|
||||
// Begin a write, then leave its sector data transfer incomplete.
|
||||
let code: [UInt8] = [0x86,0x29,0xb7,0xff,0x40,0x86,1,0xb7,0xff,0x4a,0x86,0xa0,0xb7,0xff,0x48,0x20,0xfe]
|
||||
system.replaceSubrange(0..<code.count, with: code); system[32766] = 0x80
|
||||
_ = await step { controller.loadROM(system, use6309: use6309, completion: $0) }
|
||||
_ = await step(controller.resume)
|
||||
var snapshot = await step(controller.snapshot)
|
||||
for _ in 0..<100 where !snapshot.diskBusy {
|
||||
try await Task.sleep(nanoseconds: 1_000_000)
|
||||
snapshot = await step(controller.snapshot)
|
||||
}
|
||||
XCTAssertTrue(snapshot.diskBusy, "CPU \(use6309 ? "6309" : "6809") must reach a real transfer")
|
||||
_ = await step(controller.pause)
|
||||
let operations: [(@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void] = [
|
||||
controller.pauseForDiskChange,
|
||||
{ controller.mountDisk(Data(repeating: 0xe5, count: 161280), drive: 0, name: "Replacement.dsk", readOnly: false, completion: $0) },
|
||||
{ controller.createDisk(inDrive: 0, format: .standard, completion: $0) },
|
||||
{ controller.ejectDisk(inDrive: 0, discard: false, completion: $0) },
|
||||
{ controller.setDiskWriteProtected(true, drive: 0, completion: $0) },
|
||||
{ controller.loadDiskROM(Data(repeating: 0x12, count: 8192), name: "Replacement ROM", completion: $0) },
|
||||
controller.disableDisks,
|
||||
]
|
||||
for operation in operations {
|
||||
snapshot = await step(operation)
|
||||
XCTAssertNotNil(snapshot.errorMessage)
|
||||
XCTAssertTrue(snapshot.diskBusy)
|
||||
XCTAssertTrue(snapshot.disks[0].mounted)
|
||||
XCTAssertEqual(snapshot.disks[0].name, "Original.dsk")
|
||||
XCTAssertFalse(snapshot.disks[0].writeProtected)
|
||||
XCTAssertEqual(snapshot.diskROMName, "Original ROM")
|
||||
}
|
||||
_ = await step(controller.reset)
|
||||
let (bytes, _, exported): (Data?, UInt64, VCCMachineSnapshot) = await withCheckedContinuation { done in
|
||||
controller.exportDisk(inDrive: 0) { done.resume(returning: ($0, $1, $2)) }
|
||||
}
|
||||
XCTAssertNil(exported.errorMessage)
|
||||
XCTAssertEqual(bytes, original, "Rejected actions must retain the original bytes")
|
||||
snapshot = await step { controller.ejectDisk(inDrive: 0, discard: false, completion: $0) }
|
||||
XCTAssertNil(snapshot.errorMessage)
|
||||
XCTAssertFalse(snapshot.disks[0].mounted, "Ejection works once the controller is idle")
|
||||
_ = await step(controller.shutdown)
|
||||
}
|
||||
}
|
||||
@MainActor func testBridgeRejectsInvalidAndBusyLayoutsWithoutReplacingSlots() async throws {
|
||||
let controller = VCCMachineController()
|
||||
func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import AVFoundation
|
||||
import AppKit
|
||||
|
||||
final class CoCoCaptureTests: XCTestCase {
|
||||
private final class HeldPullController: VCCMachineController, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var reply: (() -> Void)?
|
||||
private var holdNextPull = true
|
||||
private var finals = 0
|
||||
var heldReply: (() -> Void)? { lock.withLock { reply } }
|
||||
var finalPulls: Int { lock.withLock { finals } }
|
||||
override func takeVideoCapture(finish: Bool, replyQueue: DispatchQueue, completion: @escaping ([VCCVideoPacket], String?) -> Void) {
|
||||
if finish { lock.withLock { finals += 1 } }
|
||||
super.takeVideoCapture(finish: finish, replyQueue: replyQueue) { [self] packets, error in
|
||||
let held = lock.withLock {
|
||||
if !finish && holdNextPull {
|
||||
holdNextPull = false; reply = { completion(packets, error) }; return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !held { completion(packets, error) }
|
||||
}
|
||||
}
|
||||
func releasePull() { let value = lock.withLock { let value = reply; reply = nil; return value }; value?() }
|
||||
}
|
||||
private final class InvalidCapturePacket: VCCVideoPacket {
|
||||
private let original: VCCVideoPacket
|
||||
init(_ original: VCCVideoPacket) { self.original = original; super.init() }
|
||||
override var pixels: Data { Data() }
|
||||
override var samples: Data { original.samples }
|
||||
override var activeArea: CGRect { original.activeArea }
|
||||
override var sampleOffset: UInt64 { original.sampleOffset }
|
||||
}
|
||||
private final class FailingPullController: VCCMachineController, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var failPull = false
|
||||
private var invalidPull = false
|
||||
private var finals = 0
|
||||
var finalPulls: Int { lock.withLock { finals } }
|
||||
var failNextPull: Bool { get { lock.withLock { failPull } } set { lock.withLock { failPull = newValue } } }
|
||||
var invalidateNextPull: Bool { get { lock.withLock { invalidPull } } set { lock.withLock { invalidPull = newValue } } }
|
||||
override func takeVideoCapture(finish: Bool, replyQueue: DispatchQueue, completion: @escaping ([VCCVideoPacket], String?) -> Void) {
|
||||
if finish { lock.withLock { finals += 1 } }
|
||||
super.takeVideoCapture(finish: finish, replyQueue: replyQueue) { [self] packets, error in
|
||||
let fail = lock.withLock { let fail = !finish && failPull; if fail { failPull = false }; return fail }
|
||||
if fail {
|
||||
completion(packets, "Authored capture-consumer interruption")
|
||||
} else {
|
||||
let invalid = lock.withLock { let invalid = !finish && invalidPull && !packets.isEmpty; if invalid { invalidPull = false }; return invalid }
|
||||
if invalid { completion([InvalidCapturePacket(packets[0])] + Array(packets.dropFirst()), error) }
|
||||
else { completion(packets, error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Deliberately occupies the UI executor longer than the bridge's eight
|
||||
/// packets can buffer. This is test-only starvation, never a product wait.
|
||||
private func holdMainActor() { Thread.sleep(forTimeInterval: 0.8) }
|
||||
private final class BookmarkGate: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let release = DispatchSemaphore(value: 0)
|
||||
private var began = false
|
||||
let blocked: URL
|
||||
let fails: Bool
|
||||
init(blocked: URL, fails: Bool = false) { self.blocked = blocked; self.fails = fails }
|
||||
var started: Bool { lock.withLock { began } }
|
||||
func unblock() { release.signal() }
|
||||
func prepare(_ url: URL) throws -> Data {
|
||||
XCTAssertFalse(Thread.isMainThread, "Bookmark creation must not occupy the UI thread")
|
||||
if url == blocked {
|
||||
lock.withLock { began = true }
|
||||
guard release.wait(timeout: .now() + 5) == .success else { throw CoCoRecordingError.message("The authored bookmark gate timed out") }
|
||||
if fails { throw CocoaError(.fileReadNoSuchFile) }
|
||||
}
|
||||
return try url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
|
||||
}
|
||||
}
|
||||
/// Each lifecycle case owns its controller, defaults and media directory.
|
||||
/// Feedback is injected by the caller; these tests never play host cues.
|
||||
@MainActor private func guest(controller: VCCMachineController = VCCMachineController(), use6309: Bool = false) async throws -> (URL, UserDefaults, MachineModel) {
|
||||
let root = try folder(), suite = "CoCoCaptureLifecycle-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
addTeardownBlock { defaults.removePersistentDomain(forName: suite) }
|
||||
// Never ask the native test runner to bookmark the person's Desktop.
|
||||
// Seed the owned location before preferences initialize, on both hosts.
|
||||
defaults.set(try root.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.shared")
|
||||
let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller,
|
||||
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false)
|
||||
addTeardownBlock { await withCheckedContinuation { c in controller.shutdown { _ in c.resume() } } }
|
||||
await withCheckedContinuation { c in controller.loadDiagnostic(use6309: use6309) { _ in c.resume() } }
|
||||
await withCheckedContinuation { c in controller.resume { _ in c.resume() } }
|
||||
for _ in 0..<200 where model.pixels == nil { model.poll(); try await Task.sleep(for: .milliseconds(10)) }
|
||||
_ = try XCTUnwrap(model.pixels, "The owned authored diagnostic must publish a frame")
|
||||
return (root, defaults, model)
|
||||
}
|
||||
private func folder() throws -> URL {
|
||||
let url = FileManager.default.temporaryDirectory.appendingPathComponent("CoCoCapture-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||
addTeardownBlock { try? FileManager.default.removeItem(at: url) }
|
||||
return url
|
||||
}
|
||||
private func picture() -> Data {
|
||||
var data = Data(count: 640 * 480 * 4)
|
||||
data.withUnsafeMutableBytes { raw in
|
||||
let p = raw.bindMemory(to: UInt8.self)
|
||||
for y in 0..<480 { for x in 0..<640 {
|
||||
let n = (y * 640 + x) * 4
|
||||
// Green outside the crop, red above blue inside: catches both
|
||||
// unwanted border content and an upside-down encoded picture.
|
||||
if x < 64 || x >= 576 || y < 48 || y >= 432 { p[n+1] = 255 }
|
||||
else if y < 240 { p[n+2] = 255 } else { p[n] = 255 }
|
||||
} }
|
||||
}
|
||||
return data
|
||||
}
|
||||
func testQuickSaveCollisionIsAtomicAndRetainsOriginal() throws {
|
||||
let dir = try folder()
|
||||
let first = dir.appendingPathComponent("Example.png")
|
||||
try Data([1,2,3]).write(to: first)
|
||||
let temporary = dir.appendingPathComponent("temporary")
|
||||
try Data([4,5,6]).write(to: temporary)
|
||||
let second = try CoCoCaptureFiles.promote(temporary, folder: dir, name: "Example", extension: "png")
|
||||
XCTAssertEqual(second.lastPathComponent, "Example-1.png")
|
||||
XCTAssertEqual(try Data(contentsOf: first), Data([1,2,3]))
|
||||
XCTAssertEqual(try Data(contentsOf: second), Data([4,5,6]))
|
||||
let capture = try ScreenCapture(pixels: picture(), area: CGRect(x: 64, y: 48, width: 512, height: 384))
|
||||
let png = try CoCoCaptureFiles.save(capture, folder: dir)
|
||||
let image = try XCTUnwrap(NSImage(contentsOf: png))
|
||||
XCTAssertEqual(image.size, NSSize(width: 512, height: 384))
|
||||
}
|
||||
|
||||
func testNativeMovieCompletesMP4WithGuestOnlyCropAndStereo() async throws {
|
||||
let dir = try folder(), movie = dir.appendingPathComponent("Working.mov"), final = dir.appendingPathComponent("Final.mp4")
|
||||
let encoder = try CoCoVideoEncoder(workingURL: movie)
|
||||
let bytes = picture()
|
||||
for n in 0..<60 {
|
||||
var samples = Data(count: 735 * 8)
|
||||
samples.withUnsafeMutableBytes { raw in
|
||||
let values = raw.bindMemory(to: Float.self)
|
||||
for i in 0..<735 { values[2*i] = Float(sin(Double(n*735+i)*2 * .pi * 440 / 44100)) * 0.2; values[2*i+1] = -values[2*i] }
|
||||
}
|
||||
encoder.append([CoCoVideoFrame(pixels: bytes, area: CGRect(x: 64, y: 48, width: 512, height: 384), audio: samples, sampleOffset: Int64(n*735))])
|
||||
try await Task.sleep(for: .milliseconds(17))
|
||||
}
|
||||
let working: URL = try await withCheckedThrowingContinuation { c in encoder.finish { c.resume(with: $0) } }
|
||||
try await CoCoVideoEncoder.exportMP4(from: working, to: final)
|
||||
let asset = AVURLAsset(url: final)
|
||||
let duration = try await asset.load(.duration).seconds
|
||||
XCTAssertEqual(duration, 1, accuracy: 0.03)
|
||||
let video = try await asset.loadTracks(withMediaType: .video), audio = try await asset.loadTracks(withMediaType: .audio)
|
||||
XCTAssertEqual(video.count, 1); XCTAssertEqual(audio.count, 1)
|
||||
let dimensions = try await video[0].load(.naturalSize)
|
||||
XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960))
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
let frame = try await generator.image(at: .zero).image
|
||||
var rgba = Data(count: 1280 * 960 * 4)
|
||||
rgba.withUnsafeMutableBytes { p in
|
||||
let context = CGContext(data: p.baseAddress, width: 1280, height: 960, bitsPerComponent: 8,
|
||||
bytesPerRow: 1280 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
|
||||
context.draw(frame, in: CGRect(x: 0, y: 0, width: 1280, height: 960))
|
||||
}
|
||||
let top = (240 * 1280 + 640) * 4, bottom = (720 * 1280 + 640) * 4
|
||||
XCTAssertGreaterThan(rgba[top], 200); XCTAssertLessThan(rgba[top+1], 40); XCTAssertLessThan(rgba[top+2], 40)
|
||||
XCTAssertGreaterThan(rgba[bottom+2], 200); XCTAssertLessThan(rgba[bottom+1], 40); XCTAssertLessThan(rgba[bottom], 40)
|
||||
// Passthrough refuses overwrite, leaving an already delivered movie intact.
|
||||
let hash = try Data(contentsOf: final)
|
||||
do { try await CoCoVideoEncoder.exportMP4(from: working, to: final); XCTFail("Must not overwrite") } catch { }
|
||||
XCTAssertEqual(try Data(contentsOf: final), hash)
|
||||
}
|
||||
|
||||
@MainActor func testBridgeCaptureBothProcessorsDoesNotAdvancePausedGuest() async throws {
|
||||
for hd in [false, true] {
|
||||
let controller = VCCMachineController()
|
||||
func command(_ op: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
||||
await withCheckedContinuation { c in op { c.resume(returning: $0) } }
|
||||
}
|
||||
func packets(_ finish: Bool) async -> ([VCCVideoPacket], String?) {
|
||||
await withCheckedContinuation { c in controller.takeVideoCapture(finish: finish) { c.resume(returning: ($0,$1)) } }
|
||||
}
|
||||
_ = await command { controller.loadDiagnostic(use6309: hd, completion: $0) }
|
||||
_ = await command(controller.resume)
|
||||
var available = await command(controller.snapshot)
|
||||
for _ in 0..<50 where available.presentedFrame == 0 {
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
available = await command(controller.snapshot)
|
||||
}
|
||||
XCTAssertGreaterThan(available.presentedFrame, 0)
|
||||
let before = await command(controller.pause)
|
||||
let started = await command(controller.beginVideoCapture)
|
||||
XCTAssertNil(started.errorMessage)
|
||||
try await Task.sleep(for: .milliseconds(65))
|
||||
let capture = await packets(true)
|
||||
XCTAssertNil(capture.1); XCTAssertFalse(capture.0.isEmpty)
|
||||
for p in capture.0 {
|
||||
XCTAssertEqual(p.pixels.count, 640 * 480 * 4)
|
||||
XCTAssertTrue(p.samples.allSatisfy { $0 == 0 })
|
||||
XCTAssertGreaterThan(p.activeArea.width, 0)
|
||||
}
|
||||
let after = await command(controller.snapshot)
|
||||
XCTAssertEqual(after.generation, before.generation)
|
||||
XCTAssertEqual(after.cycles, before.cycles)
|
||||
XCTAssertEqual(after.presentedFrame, before.presentedFrame)
|
||||
XCTAssertEqual(after.audioStarts, before.audioStarts)
|
||||
XCTAssertEqual(after.use6309, hd)
|
||||
_ = await command(controller.shutdown)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func testStopWaitsForAnInFlightDrainedPacketBeforeFinalizing() async throws {
|
||||
let root = try folder(), controller = HeldPullController()
|
||||
let suite = "CoCoCaptureStop-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
defaults.set(try root.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.recordings")
|
||||
let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller,
|
||||
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false)
|
||||
func command(_ op: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async {
|
||||
_ = await withCheckedContinuation { c in op { c.resume(returning: $0) } }
|
||||
}
|
||||
await command { controller.loadDiagnostic(use6309: false, completion: $0) }
|
||||
await command(controller.resume)
|
||||
// This fixture owns its guest setup. An asynchronous remembered-media
|
||||
// restore must not race that load or supply the frame incidentally.
|
||||
for _ in 0..<100 where model.pixels == nil {
|
||||
model.poll(); try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
guard model.pixels != nil else {
|
||||
await withCheckedContinuation { c in model.shutdown { c.resume() } }
|
||||
XCTFail("The authored diagnostic guest did not produce its first frame")
|
||||
return
|
||||
}
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
capture.startRecording()
|
||||
capture.startRecording() // Repeated Start while starting cannot add another cue.
|
||||
for _ in 0..<100 where controller.heldReply == nil { try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertNotNil(controller.heldReply)
|
||||
XCTAssertEqual(cues, [.recordingStarted])
|
||||
let stopping = Task { await capture.stopRecording() }
|
||||
try await Task.sleep(for: .milliseconds(30))
|
||||
XCTAssertEqual(capture.state, .finishing)
|
||||
XCTAssertEqual(controller.finalPulls, 0, "Stop must not overtake the pull that already owns drained samples")
|
||||
await capture.stopRecording()
|
||||
XCTAssertEqual(capture.state, .finishing, "Duplicate Stop must leave the first finalization in control")
|
||||
XCTAssertEqual(controller.finalPulls, 0)
|
||||
controller.releasePull()
|
||||
await stopping.value
|
||||
XCTAssertEqual(controller.finalPulls, 1)
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
|
||||
let saved = capture.saved
|
||||
XCTAssertTrue(capture.recoveries.isEmpty)
|
||||
XCTAssertEqual(cues, [.recordingStarted], "Stop/finalization must not replay the start cue")
|
||||
await withCheckedContinuation { c in model.shutdown { c.resume() } }
|
||||
let movie = try XCTUnwrap(saved)
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: movie.path))
|
||||
}
|
||||
|
||||
@MainActor func testFailedQuickSaveRetainsImageAndRejectsReplacementUntilExplicitDiscard() async throws {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
let blocked = root.appendingPathComponent("Not a folder")
|
||||
let original = Data("existing user file".utf8)
|
||||
try original.write(to: blocked)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
// A regular file is a deterministic inaccessible-directory fixture,
|
||||
// independent of the account's administrator/write permissions.
|
||||
try await capture.preferences.setFolder(blocked)
|
||||
capture.captureNow()
|
||||
for _ in 0..<200 where capture.saving { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertFalse(capture.saving); XCTAssertNotNil(capture.error)
|
||||
XCTAssertTrue(capture.hasPendingImage); XCTAssertNil(capture.saved)
|
||||
XCTAssertEqual(cues, [.screenshot])
|
||||
try await capture.preferences.setFolder(root)
|
||||
capture.captureNow(); capture.delay(5)
|
||||
XCTAssertTrue(capture.hasPendingImage); XCTAssertNil(capture.countdown)
|
||||
XCTAssertEqual(cues, [.screenshot], "A failed image cannot be silently replaced or cue again")
|
||||
XCTAssertEqual(try Data(contentsOf: blocked), original)
|
||||
capture.discardImage()
|
||||
XCTAssertFalse(capture.hasPendingImage); XCTAssertNil(capture.error)
|
||||
capture.captureNow()
|
||||
for _ in 0..<200 where capture.saving { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertNotNil(capture.saved); XCTAssertFalse(capture.hasPendingImage)
|
||||
XCTAssertEqual(cues, [.screenshot, .screenshot])
|
||||
XCTAssertEqual(try Data(contentsOf: blocked), original)
|
||||
}
|
||||
|
||||
@MainActor func testFastForwardStartRefusesWithoutChangingMachineOrCreatingRecovery() async throws {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
await withCheckedContinuation { c in
|
||||
controller.configureMachine(use6309: false, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: true) { _ in c.resume() }
|
||||
}
|
||||
for _ in 0..<200 where !model.settings.fastForward { model.poll(); try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertTrue(model.settings.fastForward)
|
||||
let before = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
try await capture.preferences.setFolder(root)
|
||||
capture.startRecording(); capture.startRecording()
|
||||
XCTAssertEqual(capture.state, .idle)
|
||||
XCTAssertTrue(capture.error?.contains("fast-forward") == true)
|
||||
XCTAssertTrue(capture.recoveries.isEmpty); XCTAssertTrue(cues.isEmpty)
|
||||
let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
|
||||
XCTAssertTrue(after.fastForward); XCTAssertEqual(after.generation, before.generation)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("CaptureRecovery.json").path))
|
||||
}
|
||||
|
||||
@MainActor func testTenSecondCaptureExpiresWhilePausedWithoutAdvancingGuest() async throws {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
let before = await withCheckedContinuation { c in controller.pause { c.resume(returning: $0) } }
|
||||
model.poll()
|
||||
try await Task.sleep(for: .milliseconds(20))
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
try await capture.preferences.setFolder(root)
|
||||
capture.preferences.setTimerSeconds(10)
|
||||
capture.capture()
|
||||
XCTAssertEqual(capture.countdown, 10); XCTAssertTrue(cues.isEmpty)
|
||||
for _ in 0..<1_200 where capture.countdown != nil || capture.saving { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertNil(capture.countdown); XCTAssertFalse(capture.saving)
|
||||
XCTAssertEqual(cues, [.screenshot]); XCTAssertNil(capture.error)
|
||||
let image = try XCTUnwrap(NSImage(contentsOf: try XCTUnwrap(capture.saved)))
|
||||
XCTAssertEqual(image.size, NSSize(width: model.activeVideoRect.width, height: model.activeVideoRect.height))
|
||||
let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
|
||||
XCTAssertEqual(after.generation, before.generation)
|
||||
XCTAssertEqual(after.cycles, before.cycles)
|
||||
XCTAssertEqual(after.presentedFrame, before.presentedFrame)
|
||||
XCTAssertEqual(after.audioStarts, before.audioStarts)
|
||||
}
|
||||
|
||||
@MainActor func testResetsCancelScreenshotTimersButContinueTheSameRecording() async throws {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
model.captures = capture
|
||||
try await capture.preferences.setFolder(root)
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .recording)
|
||||
let record = try XCTUnwrap(capture.recoveries.first)
|
||||
for cold in [false, true] {
|
||||
capture.delay(10)
|
||||
XCTAssertEqual(capture.countdown, 10)
|
||||
if cold { model.reset() } else { model.softReset() }
|
||||
XCTAssertNil(capture.countdown)
|
||||
for _ in 0..<200 where model.busy { try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertFalse(model.busy)
|
||||
XCTAssertEqual(capture.state, .recording)
|
||||
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
|
||||
try await Task.sleep(for: .milliseconds(80))
|
||||
}
|
||||
XCTAssertEqual(cues, [.recordingStarted], "A reset neither restarts recording nor takes a delayed screenshot")
|
||||
await capture.stopRecording()
|
||||
XCTAssertNil(capture.error); XCTAssertEqual(capture.state, .idle)
|
||||
let asset = AVURLAsset(url: try XCTUnwrap(capture.saved))
|
||||
let duration = try await asset.load(.duration).seconds
|
||||
XCTAssertGreaterThan(duration, 0.12)
|
||||
XCTAssertTrue(capture.recoveries.isEmpty)
|
||||
}
|
||||
|
||||
@MainActor func testCaptureInterruptionRetainsOwnedMovieAndRecoveryAcrossRelaunch() async throws {
|
||||
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
try await capture.preferences.setFolder(root)
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .recording)
|
||||
let record = try XCTUnwrap(capture.recoveries.first)
|
||||
let unrelated = record.directory.appendingPathComponent("User note.txt"), original = Data("preserve".utf8)
|
||||
try original.write(to: unrelated)
|
||||
try await Task.sleep(for: .milliseconds(250))
|
||||
controller.failNextPull = true
|
||||
for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved)
|
||||
XCTAssertEqual(capture.error, "Authored capture-consumer interruption")
|
||||
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: record.working.path))
|
||||
XCTAssertGreaterThan(try Data(contentsOf: record.working).count, 0)
|
||||
XCTAssertEqual(cues, [.recordingStarted])
|
||||
let reopened = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
XCTAssertEqual(reopened.recoveries.map(\.id), [record.id])
|
||||
let recoveredFolder = root.appendingPathComponent("Recovered", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: recoveredFolder, withIntermediateDirectories: true)
|
||||
try await reopened.preferences.setFolder(recoveredFolder)
|
||||
reopened.recover(record)
|
||||
for _ in 0..<400 where reopened.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertNil(reopened.error); XCTAssertTrue(reopened.recoveries.isEmpty)
|
||||
let final = try XCTUnwrap(reopened.saved)
|
||||
XCTAssertEqual(final.deletingLastPathComponent().standardizedFileURL, recoveredFolder.standardizedFileURL)
|
||||
let duration = try await AVURLAsset(url: final).load(.duration).seconds
|
||||
XCTAssertGreaterThan(duration, 0.2, "Recovery must deliver preceding recorded content")
|
||||
XCTAssertEqual(try Data(contentsOf: unrelated), original, "Completion cleans only its working movie, never unexpected files")
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: record.working.path))
|
||||
XCTAssertEqual(cues, [.recordingStarted], "Recovery must not emit a new recording-start cue")
|
||||
}
|
||||
|
||||
@MainActor func testRecordingTransportSurvivesAnOccupiedMainActorOnBothProcessors() async throws {
|
||||
for hd in [false, true] {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller, use6309: hd)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .recording)
|
||||
let before = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
|
||||
holdMainActor()
|
||||
let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
|
||||
// Allow any delayed failure notification to run before assertions;
|
||||
// merely observing the old published Recording state proves little.
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error)
|
||||
XCTAssertEqual(after.generation, before.generation)
|
||||
XCTAssertEqual(after.audioStarts, before.audioStarts)
|
||||
XCTAssertGreaterThan(after.cycles, before.cycles)
|
||||
XCTAssertGreaterThan(after.presentedFrame, before.presentedFrame)
|
||||
XCTAssertEqual(after.use6309, hd)
|
||||
await capture.stopRecording()
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
|
||||
XCTAssertTrue(capture.recoveries.isEmpty)
|
||||
let asset = AVURLAsset(url: try XCTUnwrap(capture.saved))
|
||||
let duration = try await asset.load(.duration).seconds
|
||||
XCTAssertGreaterThan(duration, 0.75, "The movie must span the occupied UI interval")
|
||||
XCTAssertEqual(cues, [.recordingStarted])
|
||||
await withCheckedContinuation { c in model.shutdown { c.resume() } }
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func testCaptureFailureQuiescesAndFinalizesWhileMainActorIsOccupied() async throws {
|
||||
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { _ in })
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .recording)
|
||||
let record = try XCTUnwrap(capture.recoveries.first)
|
||||
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(200)) { controller.failNextPull = true }
|
||||
holdMainActor()
|
||||
XCTAssertEqual(controller.finalPulls, 1, "Failure must stop the source without waiting for the UI notification")
|
||||
for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved)
|
||||
XCTAssertEqual(capture.error, "Authored capture-consumer interruption")
|
||||
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
|
||||
let duration = try await AVURLAsset(url: record.working).load(.duration).seconds
|
||||
XCTAssertGreaterThan(duration, 0.1)
|
||||
XCTAssertEqual(controller.finalPulls, 1, "The later UI stop shares the same backend finalization")
|
||||
}
|
||||
|
||||
@MainActor func testEncoderFailureQuiescesSourceBeforeItsMainActorNotification() async throws {
|
||||
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { _ in })
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .recording)
|
||||
let record = try XCTUnwrap(capture.recoveries.first)
|
||||
// A malformed authored transport frame exercises the real encoder's
|
||||
// validation/failure callback; no guest memory or registers are changed.
|
||||
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(200)) { controller.invalidateNextPull = true }
|
||||
holdMainActor()
|
||||
XCTAssertEqual(controller.finalPulls, 1)
|
||||
// User Stop can arrive before the queued UI failure notification. Both
|
||||
// paths must share the already-started backend finalization.
|
||||
await capture.stopRecording()
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved)
|
||||
XCTAssertTrue(capture.error?.contains("ordering") == true)
|
||||
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
|
||||
XCTAssertEqual(controller.finalPulls, 1)
|
||||
let duration = try await AVURLAsset(url: record.working).load(.duration).seconds
|
||||
XCTAssertGreaterThan(duration, 0.1)
|
||||
}
|
||||
|
||||
@MainActor func testImmediateFailureDoesNotLatchRecordingOrStopItsSuccessor() async throws {
|
||||
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
for _ in 0..<4 {
|
||||
controller.failNextPull = true
|
||||
capture.startRecording()
|
||||
for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertEqual(capture.state, .idle, "An immediate background failure must not leave a stale Recording state")
|
||||
XCTAssertEqual(capture.error, "Authored capture-consumer interruption")
|
||||
}
|
||||
let retained = capture.recoveries.map(\.id), oldCues = cues.count
|
||||
XCTAssertEqual(retained.count, 4)
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
try await Task.sleep(for: .milliseconds(150))
|
||||
XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error)
|
||||
XCTAssertEqual(cues.count, oldCues + 1)
|
||||
await capture.stopRecording()
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
|
||||
XCTAssertNotNil(capture.saved)
|
||||
XCTAssertEqual(capture.recoveries.map(\.id), retained)
|
||||
}
|
||||
|
||||
@MainActor func testCaptureStartOwnsFreshErrorStateAndBridgeRefusalNeverCuesOnBothProcessors() async throws {
|
||||
for hd in [false, true] {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller, use6309: hd)
|
||||
let rejected = await withCheckedContinuation { c in
|
||||
controller.configureMachine(use6309: hd, ram: 99, overclock: 1, frameInterval: 1, fastForward: false) { c.resume(returning: $0) }
|
||||
}
|
||||
XCTAssertNotNil(rejected.errorMessage)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error)
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
await capture.stopRecording()
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
|
||||
XCTAssertNotNil(capture.saved); XCTAssertTrue(capture.recoveries.isEmpty)
|
||||
XCTAssertEqual(cues, [.recordingStarted])
|
||||
// The model deliberately retains its last normal-speed snapshot;
|
||||
// the owner queue independently refuses the actual fast-forward run.
|
||||
_ = await withCheckedContinuation { c in
|
||||
controller.configureMachine(use6309: hd, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: true) { c.resume(returning: $0) }
|
||||
}
|
||||
XCTAssertFalse(model.settings.fastForward)
|
||||
capture.startRecording()
|
||||
for _ in 0..<200 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertEqual(capture.state, .idle)
|
||||
XCTAssertTrue(capture.error?.contains("fast-forward") == true)
|
||||
XCTAssertEqual(cues, [.recordingStarted], "A refused bridge start must not emit a success cue")
|
||||
_ = await withCheckedContinuation { c in
|
||||
controller.configureMachine(use6309: hd, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: false) { c.resume(returning: $0) }
|
||||
}
|
||||
let probe = await withCheckedContinuation { c in controller.beginVideoCapture(replyQueue: .global(qos: .userInitiated)) { c.resume(returning: $0) } }
|
||||
XCTAssertNil(probe.errorMessage, "The rejected start must not leave an unowned capture producer active")
|
||||
let stopped: String? = await withCheckedContinuation { c in controller.takeVideoCapture(finish: true, replyQueue: .global(qos: .userInitiated)) { _, error in c.resume(returning: error) } }
|
||||
XCTAssertNil(stopped)
|
||||
await withCheckedContinuation { c in model.shutdown { c.resume() } }
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func testNewerRecoveryManifestIsPreservedAndBlocksAnotherWriter() async throws {
|
||||
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
|
||||
let manifest = root.appendingPathComponent("CaptureRecovery.json")
|
||||
let original = Data(#"{"version":2,"recordings":[],"futureMetadata":"preserve exactly"}"#.utf8)
|
||||
try original.write(to: manifest)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
try await capture.preferences.setFolder(root)
|
||||
XCTAssertNotNil(capture.error)
|
||||
capture.startRecording()
|
||||
XCTAssertEqual(capture.state, .idle); XCTAssertTrue(capture.recoveries.isEmpty)
|
||||
XCTAssertTrue(capture.error?.contains("preserved recording recovery") == true)
|
||||
XCTAssertTrue(cues.isEmpty)
|
||||
XCTAssertEqual(try Data(contentsOf: manifest), original)
|
||||
let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
|
||||
XCTAssertFalse(contents.contains { $0.lastPathComponent.hasPrefix(".vcc-recording-") })
|
||||
}
|
||||
@MainActor func testSharedDestinationDefaultsTimerAndAudioPersistWithoutMovingFiles() async throws {
|
||||
let root = try folder(), suite = "CoCoCapturePreferences-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let first = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||||
XCTAssertEqual(first.destination, .desktop)
|
||||
XCTAssertEqual(first.folder, root)
|
||||
XCTAssertEqual(first.screenshots, first.recordings)
|
||||
XCTAssertEqual(first.timerSeconds, 0); XCTAssertTrue(first.includeVideoAudio)
|
||||
XCTAssertNil(defaults.data(forKey: "capture.folder.shared"), "A logical default must not create a security bookmark before the user chooses a folder")
|
||||
let custom = root.appendingPathComponent("My Captures", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: custom, withIntermediateDirectories: true)
|
||||
let original = custom.appendingPathComponent("Existing.txt")
|
||||
try Data("keep me".utf8).write(to: original)
|
||||
try await first.setFolder(custom); first.setTimerSeconds(10); first.includeVideoAudio = false
|
||||
let chosenBookmark = try XCTUnwrap(defaults.data(forKey: "capture.folder.shared"))
|
||||
let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||||
XCTAssertEqual(reopened.folder.standardizedFileURL, custom.standardizedFileURL)
|
||||
XCTAssertEqual(reopened.screenshots, reopened.recordings)
|
||||
XCTAssertEqual(reopened.destination, .other)
|
||||
XCTAssertEqual(reopened.timerSeconds, 10); XCTAssertFalse(reopened.includeVideoAudio)
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), chosenBookmark, "Reopening preferences preserves an explicit selected-folder grant")
|
||||
reopened.setTimerSeconds(3)
|
||||
XCTAssertEqual(reopened.timerSeconds, 10, "Only None, 5 and 10 are valid timer choices")
|
||||
reopened.setDestination(.documents)
|
||||
XCTAssertEqual(reopened.folder, root.appendingPathComponent("Documents", isDirectory: true))
|
||||
XCTAssertEqual(try Data(contentsOf: original), Data("keep me".utf8))
|
||||
reopened.setDestination(.desktop)
|
||||
XCTAssertEqual(reopened.folder, root)
|
||||
defaults.set(999, forKey: "capture.timer.seconds")
|
||||
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).timerSeconds, 0)
|
||||
}
|
||||
|
||||
@MainActor func testLegacyCaptureFoldersMigrateWithExplicitScreenshotChoiceFirst() throws {
|
||||
let root = try folder(), screenshot = root.appendingPathComponent("Pictures"), video = root.appendingPathComponent("Movies")
|
||||
for path in [screenshot, video] { try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) }
|
||||
for screenshotChosen in [false, true] {
|
||||
let suite = "CoCoCaptureMigration-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let videoBookmark = try video.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
|
||||
defaults.set(videoBookmark, forKey: "capture.folder.recordings")
|
||||
if screenshotChosen {
|
||||
defaults.set(try screenshot.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.screenshots")
|
||||
}
|
||||
let migrated = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||||
let expected = screenshotChosen ? screenshot : video
|
||||
XCTAssertEqual(migrated.folder.standardizedFileURL, expected.standardizedFileURL)
|
||||
XCTAssertEqual(migrated.screenshots, migrated.recordings)
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.recordings"), videoBookmark)
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"),
|
||||
defaults.data(forKey: screenshotChosen ? "capture.folder.screenshots" : "capture.folder.recordings"),
|
||||
"Migration reuses the existing security bookmark bytes instead of requesting a new grant")
|
||||
let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||||
XCTAssertEqual(reopened.folder.standardizedFileURL, expected.standardizedFileURL)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func testBuiltInDestinationsPersistWithoutBookmarkOrDirectoryWorkAndOverrideOther() async throws {
|
||||
let root = try folder(), custom = root.appendingPathComponent("Chosen Other", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: custom, withIntermediateDirectories: true)
|
||||
let suite = "CoCoLogicalDestination-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||||
try await preferences.setFolder(custom)
|
||||
let bookmark = try XCTUnwrap(defaults.data(forKey: "capture.folder.shared"))
|
||||
let documents = root.appendingPathComponent("Documents", isDirectory: true)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path))
|
||||
preferences.setDestination(.documents)
|
||||
XCTAssertEqual(preferences.destination, .documents); XCTAssertEqual(preferences.folder, documents)
|
||||
XCTAssertEqual(defaults.string(forKey: "capture.destination"), "documents")
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), bookmark, "Keep the previous explicit grant for in-flight writers")
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path), "Selecting a logical folder must not create it on the UI thread")
|
||||
let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { _ in
|
||||
XCTFail("Logical destination restore must not make a bookmark"); return Data()
|
||||
})
|
||||
XCTAssertEqual(reopened.destination, .documents); XCTAssertEqual(reopened.folder, documents)
|
||||
reopened.setDestination(.desktop)
|
||||
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder, root)
|
||||
XCTAssertEqual(defaults.string(forKey: "capture.destination"), "desktop")
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), bookmark)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path))
|
||||
}
|
||||
|
||||
@MainActor func testLateOtherGrantCannotReplaceNewerBuiltInOrOtherChoice() async throws {
|
||||
for newerOther in [false, true] {
|
||||
let root = try folder(), first = root.appendingPathComponent("First"), second = root.appendingPathComponent("Second")
|
||||
for url in [first, second] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
|
||||
let suite = "CoCoDestinationOrder-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let gate = BookmarkGate(blocked: first)
|
||||
let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try gate.prepare($0) })
|
||||
let stale = Task { try await preferences.setFolder(first) }
|
||||
for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertTrue(gate.started); XCTAssertTrue(preferences.preparingDestination)
|
||||
if newerOther { try await preferences.setFolder(second) } else { preferences.setDestination(.documents) }
|
||||
gate.unblock()
|
||||
do { try await stale.value; XCTFail("A superseded grant must not become the selected folder") }
|
||||
catch is CancellationError { }
|
||||
let expected = newerOther ? second : root.appendingPathComponent("Documents", isDirectory: true)
|
||||
XCTAssertEqual(preferences.folder, expected); XCTAssertFalse(preferences.preparingDestination)
|
||||
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder.standardizedFileURL, expected.standardizedFileURL)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func testLateOtherFailureIsCancellationAndLegacyFallbackStillMigrates() async throws {
|
||||
let root = try folder(), first = root.appendingPathComponent("First"), legacy = root.appendingPathComponent("Legacy")
|
||||
for url in [first, legacy] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
|
||||
let suite = "CoCoDestinationFailure-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let legacyBookmark = try legacy.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
|
||||
defaults.set(Data("invalid shared bookmark".utf8), forKey: "capture.folder.shared")
|
||||
defaults.set(legacyBookmark, forKey: "capture.folder.recordings")
|
||||
let gate = BookmarkGate(blocked: first, fails: true)
|
||||
let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try gate.prepare($0) })
|
||||
XCTAssertEqual(preferences.folder.standardizedFileURL, legacy.standardizedFileURL)
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), legacyBookmark)
|
||||
let stale = Task { try await preferences.setFolder(first) }
|
||||
for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertTrue(gate.started)
|
||||
preferences.setDestination(.desktop); gate.unblock()
|
||||
do { try await stale.value; XCTFail("A superseded failed grant must be ignored") }
|
||||
catch is CancellationError { }
|
||||
XCTAssertEqual(preferences.folder, root); XCTAssertFalse(preferences.preparingDestination)
|
||||
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), legacyBookmark)
|
||||
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).destination, .desktop)
|
||||
let later = root.appendingPathComponent("Later Other")
|
||||
try FileManager.default.createDirectory(at: later, withIntermediateDirectories: true)
|
||||
let nextGate = BookmarkGate(blocked: first, fails: true)
|
||||
let next = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try nextGate.prepare($0) })
|
||||
let superseded = Task { try await next.setFolder(first) }
|
||||
for _ in 0..<200 where !nextGate.started { try await Task.sleep(for: .milliseconds(5)) }
|
||||
XCTAssertTrue(nextGate.started)
|
||||
try await next.setFolder(later); nextGate.unblock()
|
||||
do { try await superseded.value; XCTFail("An old failure must not replace a newer accepted Other folder") }
|
||||
catch is CancellationError { }
|
||||
XCTAssertEqual(next.folder, later); XCTAssertFalse(next.preparingDestination)
|
||||
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder.standardizedFileURL, later.standardizedFileURL)
|
||||
}
|
||||
|
||||
@MainActor func testTimerSelectionCancellationAndRealCaptureEmitOnlyActualCaptureCues() async throws {
|
||||
let root = try folder(), suite = "CoCoCaptureCues-" + UUID().uuidString
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let controller = VCCMachineController()
|
||||
let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller,
|
||||
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false)
|
||||
var cues: [CoCoCaptureFeedback.Cue] = []
|
||||
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
|
||||
try await capture.preferences.setFolder(root)
|
||||
capture.captureNow(); capture.startRecording()
|
||||
XCTAssertTrue(cues.isEmpty, "A missing framebuffer cannot emit a success cue")
|
||||
XCTAssertEqual(capture.state, .idle)
|
||||
await withCheckedContinuation { c in controller.loadDiagnostic(use6309: false) { _ in c.resume() } }
|
||||
await withCheckedContinuation { c in controller.resume { _ in c.resume() } }
|
||||
for _ in 0..<100 where model.pixels == nil { model.poll(); try await Task.sleep(for: .milliseconds(10)) }
|
||||
guard model.pixels != nil else {
|
||||
await withCheckedContinuation { c in model.shutdown { c.resume() } }
|
||||
return XCTFail("The diagnostic guest did not provide a picture")
|
||||
}
|
||||
capture.preferences.setTimerSeconds(10); capture.preferences.includeVideoAudio = false
|
||||
XCTAssertNil(capture.countdown); XCTAssertNil(capture.saved); XCTAssertTrue(cues.isEmpty)
|
||||
capture.capture()
|
||||
XCTAssertEqual(capture.countdown, 10); XCTAssertTrue(cues.isEmpty)
|
||||
capture.cancelCountdown()
|
||||
try await Task.sleep(for: .milliseconds(50))
|
||||
XCTAssertNil(capture.countdown); XCTAssertNil(capture.saved); XCTAssertTrue(cues.isEmpty)
|
||||
capture.preferences.setTimerSeconds(0); capture.capture(); capture.capture()
|
||||
XCTAssertEqual(cues, [.screenshot], "A duplicate click during saving must not capture or cue twice")
|
||||
for _ in 0..<100 where capture.saving { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertNotNil(capture.saved); XCTAssertFalse(capture.hasPendingImage)
|
||||
capture.preferences.setTimerSeconds(5); capture.capture()
|
||||
XCTAssertEqual(capture.countdown, 5); XCTAssertEqual(cues.count, 1)
|
||||
for _ in 0..<650 where capture.countdown != nil || capture.saving { try await Task.sleep(for: .milliseconds(10)) }
|
||||
XCTAssertNil(capture.countdown); XCTAssertFalse(capture.saving)
|
||||
XCTAssertEqual(cues, [.screenshot, .screenshot], "Only timer expiry emits the delayed capture cue")
|
||||
let pngs = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil).filter { $0.pathExtension == "png" }
|
||||
XCTAssertEqual(pngs.count, 2)
|
||||
await withCheckedContinuation { c in model.shutdown { c.resume() } }
|
||||
}
|
||||
|
||||
func testSilentVideoDecodesToSilenceWithUnchangedPictureAndTimeline() async throws {
|
||||
let root = try folder(), movie = root.appendingPathComponent("Silent.mov"), final = root.appendingPathComponent("Silent.mp4")
|
||||
let encoder = try CoCoVideoEncoder(workingURL: movie), bytes = picture()
|
||||
var source = Data(count: 735 * 8)
|
||||
source.withUnsafeMutableBytes { raw in
|
||||
let floats = raw.bindMemory(to: Float.self)
|
||||
for i in 0..<735 { floats[2*i] = 0.25; floats[2*i+1] = -0.25 }
|
||||
}
|
||||
let live = CoCoCaptureCoordinator.videoFrame(pixels: bytes, area: CGRect(x: 64, y: 48, width: 512, height: 384), audio: source, sampleOffset: 735, includeAudio: true)
|
||||
XCTAssertEqual(live.audio, source)
|
||||
for n in 0..<60 {
|
||||
let silent = CoCoCaptureCoordinator.videoFrame(pixels: bytes, area: live.area, audio: source, sampleOffset: Int64(n*735), includeAudio: false)
|
||||
XCTAssertEqual(silent.pixels, bytes); XCTAssertEqual(silent.area, live.area)
|
||||
XCTAssertEqual(silent.sampleOffset, Int64(n*735)); XCTAssertEqual(silent.audio.count, source.count)
|
||||
XCTAssertTrue(silent.audio.allSatisfy { $0 == 0 })
|
||||
encoder.append([silent]); try await Task.sleep(for: .milliseconds(17))
|
||||
}
|
||||
let working: URL = try await withCheckedThrowingContinuation { c in encoder.finish { c.resume(with: $0) } }
|
||||
try await CoCoVideoEncoder.exportMP4(from: working, to: final)
|
||||
let asset = AVURLAsset(url: final)
|
||||
let duration = try await asset.load(.duration).seconds
|
||||
XCTAssertEqual(duration, 1, accuracy: 0.03)
|
||||
let audio = try await asset.loadTracks(withMediaType: .audio), video = try await asset.loadTracks(withMediaType: .video)
|
||||
XCTAssertEqual(video.count, 1)
|
||||
let track = try XCTUnwrap(audio.first)
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
|
||||
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
|
||||
reader.add(output); XCTAssertTrue(reader.startReading())
|
||||
var peak: Float = 0, count = 0
|
||||
while let sample = output.copyNextSampleBuffer() {
|
||||
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
|
||||
var data = Data(count: CMBlockBufferGetDataLength(buffer))
|
||||
let result = data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) }
|
||||
XCTAssertEqual(result, noErr)
|
||||
data.withUnsafeBytes { raw in
|
||||
for value in raw.bindMemory(to: Float.self) { peak = max(peak, abs(value)); count += 1 }
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0)
|
||||
XCTAssertLessThan(peak, 0.00001, "The delivered MP4 must decode to silence, despite nonzero source PCM")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
final class CoCoVideoBudgetTests: XCTestCase {
|
||||
private func directory() throws -> URL {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CoCoVideoBudget-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
|
||||
addTeardownBlock { try? FileManager.default.removeItem(at: root) }
|
||||
return root
|
||||
}
|
||||
private func frames(count: Int, audioFrames: Int = 735) -> [CoCoVideoFrame] {
|
||||
let pixels = Data(repeating: 0x40, count: 640 * 480 * 4)
|
||||
return (0..<count).map { n in
|
||||
CoCoVideoFrame(pixels: pixels, area: CGRect(x:64,y:48,width:512,height:384),
|
||||
audio: Data(count: audioFrames * 8), sampleOffset: Int64(n * audioFrames))
|
||||
}
|
||||
}
|
||||
|
||||
func testOversizedIngressFailsOnceAndEveryFinishCallbackCompletesOnce() async throws {
|
||||
let root = try directory()
|
||||
let encoder = try CoCoVideoEncoder(workingURL: root.appendingPathComponent("Working.mov"))
|
||||
let failure = expectation(description: "bounded ingress reports one failure")
|
||||
failure.assertForOverFulfill = true
|
||||
encoder.failure = { message in
|
||||
XCTAssertTrue(message.localizedCaseInsensitiveContains("bounded"))
|
||||
failure.fulfill()
|
||||
}
|
||||
// A valid three-second stereo batch exceeds the recorder's public
|
||||
// two-second retention contract before it reaches the encoder queue.
|
||||
let oversized = frames(count: 1, audioFrames: 3 * 44_100)
|
||||
for _ in 0..<100 { encoder.append(oversized) }
|
||||
let first = expectation(description: "first finish returns failure")
|
||||
let second = expectation(description: "repeat finish returns failure")
|
||||
first.assertForOverFulfill = true; second.assertForOverFulfill = true
|
||||
encoder.finish { result in
|
||||
if case .success = result { XCTFail("Over-budget input must not claim a completed movie") }
|
||||
XCTAssertTrue(encoder.writerIsTerminal, "Failure completion must await AVFoundation writer closure")
|
||||
first.fulfill()
|
||||
}
|
||||
encoder.finish { result in
|
||||
if case .success = result { XCTFail("Repeated Stop must not manufacture a successful movie") }
|
||||
XCTAssertTrue(encoder.writerIsTerminal, "Duplicate Stop must share the same writer-closure barrier")
|
||||
second.fulfill()
|
||||
}
|
||||
await fulfillment(of: [failure, first, second], timeout: 8)
|
||||
}
|
||||
|
||||
func testRapidValidFrameProducerIsRejectedWithoutUnboundedQueueing() async throws {
|
||||
let root = try directory()
|
||||
let encoder = try CoCoVideoEncoder(workingURL: root.appendingPathComponent("Working.mov"))
|
||||
let failure = expectation(description: "unpaced producer reaches bounded ingress")
|
||||
failure.assertForOverFulfill = true
|
||||
encoder.failure = { message in
|
||||
XCTAssertTrue(message.localizedCaseInsensitiveContains("bounded"))
|
||||
failure.fulfill()
|
||||
}
|
||||
// This is deliberately not real-time pacing: a producer must not hide
|
||||
// thousands of otherwise valid frames inside pending dispatch blocks.
|
||||
let pixels = Data(repeating:0x60,count:640 * 480 * 4)
|
||||
let audio = Data(count:735 * 8)
|
||||
for n in 0..<2_000 {
|
||||
encoder.append([CoCoVideoFrame(pixels:pixels,area:CGRect(x:64,y:48,width:512,height:384),audio:audio,sampleOffset:Int64(n * 735))])
|
||||
}
|
||||
let stopped = expectation(description: "stop finishes after input rejection")
|
||||
stopped.assertForOverFulfill = true
|
||||
encoder.finish { result in
|
||||
if case .success = result { XCTFail("Dropped over-budget input cannot be reported as a complete recording") }
|
||||
stopped.fulfill()
|
||||
}
|
||||
await fulfillment(of:[failure,stopped],timeout:8)
|
||||
}
|
||||
|
||||
func testOrderingFailureRetainsPrecedingMovieBytesAndNeverClaimsSuccessfulCompletion() async throws {
|
||||
let root = try directory(), working = root.appendingPathComponent("Working.mov")
|
||||
let neighbor = root.appendingPathComponent("Existing.mp4"), original = Data("unrelated original".utf8)
|
||||
try original.write(to: neighbor)
|
||||
let encoder = try CoCoVideoEncoder(workingURL: working)
|
||||
let failure = expectation(description: "ordering failure is reported once")
|
||||
failure.assertForOverFulfill = true
|
||||
encoder.failure = { message in
|
||||
XCTAssertTrue(message.contains("ordering"))
|
||||
failure.fulfill()
|
||||
}
|
||||
// First establish a real encoded movie, rather than asserting that an
|
||||
// empty writer created a pathname. The next packet violates ordering.
|
||||
for frame in frames(count: 20) {
|
||||
encoder.append([frame])
|
||||
try await Task.sleep(for: .milliseconds(17))
|
||||
}
|
||||
var invalid = frames(count: 1)[0]
|
||||
invalid.sampleOffset = -1
|
||||
encoder.append([invalid])
|
||||
await fulfillment(of: [failure], timeout: 5)
|
||||
let stopped: Result<URL, Error> = await withCheckedContinuation { c in encoder.finish { c.resume(returning: $0) } }
|
||||
if case .success = stopped { XCTFail("Writer failure must not be advertised as a completed movie") }
|
||||
XCTAssertTrue(encoder.writerIsTerminal)
|
||||
let drained: Result<Void, Error> = await withCheckedContinuation { c in encoder.whenDrained { c.resume(returning: $0) } }
|
||||
if case .success = drained { XCTFail("Failed input cannot be acknowledged as a successful drain") }
|
||||
// The failure notification can precede AVFoundation's closure, but the
|
||||
// finish callback cannot. No polling/retry is permitted after finish.
|
||||
let duration = try await AVURLAsset(url: working).load(.duration).seconds
|
||||
XCTAssertGreaterThan(duration, 0.2, "A failed writer retains its preceding playable content")
|
||||
XCTAssertGreaterThan(try Data(contentsOf: working).count, 0)
|
||||
XCTAssertEqual(try Data(contentsOf: neighbor), original)
|
||||
let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
|
||||
XCTAssertEqual(Set(contents.map(\.lastPathComponent)), ["Working.mov", "Existing.mp4"])
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,66 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
final class CompanionLibraryTests: XCTestCase {
|
||||
private static func release(_ id: String, media: String = "disk") -> SoftwareLibraryRelease {
|
||||
.init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media,
|
||||
func testColdServiceReadinessCanOutlastOldSixSecondLimitWithoutDelayingReadyService() async throws {
|
||||
var uptime: TimeInterval = 100, attempts = 0, pauses = 0
|
||||
try await CompanionTransport.waitForService(now: { uptime }, sleep: { delay in
|
||||
pauses += 1; uptime += delay
|
||||
}, probe: { remaining in
|
||||
attempts += 1
|
||||
XCTAssertGreaterThan(remaining, 0); XCTAssertLessThanOrEqual(remaining, 45)
|
||||
if uptime < 123 { throw CompanionTransport.Failure.unavailable }
|
||||
})
|
||||
XCTAssertGreaterThan(uptime - 100, 22.9)
|
||||
XCTAssertGreaterThan(attempts, 60); XCTAssertEqual(pauses, attempts - 1)
|
||||
pauses = 0; attempts = 0
|
||||
try await CompanionTransport.waitForService(now: { uptime }, sleep: { _ in pauses += 1 }, probe: { _ in attempts += 1 })
|
||||
XCTAssertEqual(attempts, 1); XCTAssertEqual(pauses, 0)
|
||||
}
|
||||
|
||||
func testColdServiceReadinessHasBoundedDeadlineAndKeepsRealErrors() async throws {
|
||||
var uptime: TimeInterval = 0, pauses = 0
|
||||
do {
|
||||
try await CompanionTransport.waitForService(timeout: 0.25, now: { uptime }, sleep: { delay in
|
||||
pauses += 1; uptime += delay
|
||||
}, probe: { _ in throw CompanionTransport.Failure.unavailable })
|
||||
XCTFail("A service that never starts must time out")
|
||||
} catch CompanionTransport.Failure.startupTimedOut { }
|
||||
XCTAssertEqual(uptime, 0.25, accuracy: 0.00001); XCTAssertEqual(pauses, 3)
|
||||
for failure in [CompanionTransport.Failure.untrustedPeer, .unsafeEndpoint, .unsupportedVersion, .timedOut, .remote("Denied")] {
|
||||
pauses = 0
|
||||
do {
|
||||
try await CompanionTransport.waitForService(sleep: { _ in pauses += 1 }, probe: { _ in throw failure })
|
||||
XCTFail("A real companion error must not be retried")
|
||||
} catch { XCTAssertEqual(error.localizedDescription, failure.localizedDescription) }
|
||||
XCTAssertEqual(pauses, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testColdServiceReadinessCancelsDuringStartupWait() async throws {
|
||||
let waiting = expectation(description: "Startup is waiting for its missing listener")
|
||||
let task = Task {
|
||||
try await CompanionTransport.waitForService(sleep: { _ in
|
||||
waiting.fulfill()
|
||||
try await Task.sleep(for: .seconds(60))
|
||||
}, probe: { _ in throw CompanionTransport.Failure.unavailable })
|
||||
}
|
||||
await fulfillment(of: [waiting], timeout: 2)
|
||||
task.cancel()
|
||||
do { try await task.value; XCTFail("Cancellation must end startup polling") }
|
||||
catch is CancellationError { }
|
||||
}
|
||||
|
||||
private static func release(_ id: String, media: String = "disk", owned: Bool = false) -> SoftwareLibraryRelease {
|
||||
var metadata: [String: LibraryJSON] = ["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)]
|
||||
if owned { metadata["owned_game"] = .object([:]) }
|
||||
return .init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media,
|
||||
contentRole: "software", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Example.zip")!,
|
||||
modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil,
|
||||
packageSHA256: String(repeating: "a", count: 64), byteSize: 256, languageStatus: "unknown",
|
||||
metadata: .object(["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)]),
|
||||
metadata: .object(metadata),
|
||||
setup: .init(status: "manual-setup", command: nil, instructions: "Follow the authored instructions.",
|
||||
configuration: .object([:]), selectedMembers: .array([]), reasons: [], validation: .object([:])),
|
||||
assets: [], downloadURLs: [])
|
||||
@@ -44,6 +97,61 @@ final class CompanionLibraryTests: XCTestCase {
|
||||
XCTAssertNil(state.saveError)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: state.directory.appendingPathComponent("Unused.json").path))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testBothAppsSharePersistedFavoritesAndEditionChoicesWithoutASecondStateFile() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CompanionChoices-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let catalog = SoftwareLibraryCatalog(titles: [.init(id: "title", name: "Authored Example", identityStatus: "reviewed",
|
||||
releases: [Self.release("disk"), Self.release("second-disk")])], metadata: [:])
|
||||
let host = SoftwareLibraryModel(state: .init(directory: root))
|
||||
await host.load(from: root.appendingPathComponent("authored.sqlite"), catalogLoader: { _ in catalog })
|
||||
host.state.toggleFavorite("title")
|
||||
host.state.selectRelease("second-disk", for: "title")
|
||||
await host.state.flush()
|
||||
|
||||
let service = AuthorityLibrary(authority: .init(model: host))
|
||||
let client = SoftwareLibraryModel(companion: service) { _ in XCTFail("Changing choices must not insert media.") }
|
||||
await client.load()
|
||||
XCTAssertTrue(client.state.isFavorite("title"), "A companion opening after a VCC Plus change reads the same choices.")
|
||||
XCTAssertEqual(client.state.preferredReleaseID(for: "title"), "second-disk")
|
||||
client.state.toggleFavorite("title")
|
||||
client.state.selectRelease("disk", for: "title")
|
||||
await client.state.flush()
|
||||
XCTAssertNil(client.state.saveError)
|
||||
XCTAssertFalse(host.state.isFavorite("title"))
|
||||
XCTAssertEqual(host.state.preferredReleaseID(for: "title"), "disk")
|
||||
|
||||
// Reopening the authoritative state proves the response was persisted,
|
||||
// rather than copied only between the two current in-memory models.
|
||||
let persisted = SoftwareLibraryState(directory: root)
|
||||
XCTAssertNil(persisted.saveError)
|
||||
XCTAssertFalse(persisted.isFavorite("title"))
|
||||
XCTAssertEqual(persisted.preferredReleaseID(for: "title"), "disk")
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: client.state.directory.appendingPathComponent("Unused.json").path))
|
||||
let reopened = SoftwareLibraryModel(companion: service) { _ in XCTFail("Reopening must not insert media.") }
|
||||
await reopened.load()
|
||||
XCTAssertFalse(reopened.state.isFavorite("title"))
|
||||
XCTAssertEqual(reopened.state.preferredReleaseID(for: "title"), "disk")
|
||||
await reopened.shutdown(); await client.shutdown(); await host.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testUnavailableCompanionCanBeRetriedWithoutCreatingLocalLibraryState() async throws {
|
||||
let service = RecoveringLibrary(catalog: Self.catalog)
|
||||
let model = SoftwareLibraryModel(companion: service) { _ in XCTFail("A failed or retried browse must not insert media.") }
|
||||
await model.load()
|
||||
XCTAssertNotNil(model.error)
|
||||
XCTAssertNil(model.catalog)
|
||||
XCTAssertFalse(model.loading)
|
||||
await service.reconnect()
|
||||
await model.load()
|
||||
XCTAssertNil(model.error)
|
||||
XCTAssertEqual(model.catalog?.releases.map(\.id), ["disk"])
|
||||
XCTAssertFalse(model.loading)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: model.state.directory.appendingPathComponent("Unused.json").path))
|
||||
await model.shutdown()
|
||||
}
|
||||
@MainActor
|
||||
func testClearingFiltersAndChangingEditionCannotExposeTapeOrCartridge() async throws {
|
||||
let service = FakeLibrary(catalog: Self.catalog)
|
||||
@@ -68,6 +176,301 @@ final class CompanionLibraryTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testPersonalCapabilityIsExplicitAndOlderRequestsDecodeWithoutIt() throws {
|
||||
let current = CompanionLibraryRequest(operation: .snapshot)
|
||||
XCTAssertEqual(current.personalTitlesVersion, 1)
|
||||
let old = try JSONDecoder().decode(CompanionLibraryRequest.self, from: Data("{\"operation\":\"snapshot\",\"requestID\":\"00000000-0000-0000-0000-000000000001\"}".utf8))
|
||||
XCTAssertNil(old.personalTitlesVersion)
|
||||
XCTAssertNil(old.ownedTitlesVersion)
|
||||
let entry = PersonalSoftwareEntry(id: UUID(), title: "Private disk", files: [
|
||||
.init(path: "game.dsk", kind: "disk", byteSize: 256, sha256: String(repeating: "a", count: 64))])
|
||||
let release = entry.release(in: URL(fileURLWithPath: "/unused/PersonalLibrary/" + entry.id.uuidString.lowercased()))
|
||||
let catalog = SoftwareLibraryCatalog(titles: Self.catalog.titles + [
|
||||
.init(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [release])], metadata: [:])
|
||||
XCTAssertEqual(catalog.companionDisks(includingOwnedTitles: true).releases.map(\.id), ["disk"])
|
||||
XCTAssertEqual(Set(catalog.companionDisksOnly.releases.map(\.id)), Set(["disk", entry.releaseID]))
|
||||
let mixed = SoftwareLibraryCatalog(titles: [.init(id: "title", name: "Mixed editions", identityStatus: "reviewed",
|
||||
releases: [Self.release("disk"), Self.release("owned", owned: true), Self.release("cart", media: "cartridge")])], metadata: [:])
|
||||
XCTAssertEqual(mixed.companionDisks(includingOwnedTitles: false, includingPersonalTitles: true).releases.map(\.id), ["disk"])
|
||||
XCTAssertEqual(mixed.companionDisks(includingOwnedTitles: true).releases.map(\.id), ["disk", "owned"])
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testAuthoritySharesCurrentPersonalDiskChoicesAndIndependentWritableCopies() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionPersonal-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
|
||||
let source = root.appendingPathComponent("GAME.dsk")
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let original = try Data(contentsOf: fixture)
|
||||
try original.write(to: source)
|
||||
let manual = root.appendingPathComponent("README.txt"), instructions = Data("Private local instructions".utf8)
|
||||
try instructions.write(to: manual)
|
||||
let draft = try await model.personalStore.inspect([source, manual])
|
||||
let entry = try await model.personalStore.save(draft)
|
||||
await model.load(from: root.appendingPathComponent("authored.sqlite"), catalogLoader: { _ in Self.catalog })
|
||||
let authority = CompanionLibraryAuthority(model: model)
|
||||
let initial = try await authority.handle(.init(operation: .snapshot))
|
||||
let snapshot = try XCTUnwrap(initial.snapshot)
|
||||
XCTAssertEqual(Set(snapshot.catalog.releases.map(\.id)), Set(["disk", entry.releaseID]))
|
||||
XCTAssertEqual(snapshot.installations.map(\.releaseID), [entry.releaseID])
|
||||
XCTAssertTrue(snapshot.catalog.releases.first(where: { $0.id == entry.releaseID })!.downloadURLs.isEmpty)
|
||||
let favorite = try await authority.handle(.init(operation: .setFavorite, titleID: entry.titleID, enabled: true))
|
||||
XCTAssertTrue(favorite.snapshot!.favorites.contains(entry.titleID))
|
||||
let preferred = try await authority.handle(.init(operation: .setPreferredRelease, releaseID: entry.releaseID, titleID: entry.titleID))
|
||||
XCTAssertEqual(preferred.snapshot!.preferredReleaseIDs[entry.titleID], entry.releaseID)
|
||||
for operation in [CompanionLibraryRequest.Operation.install, .installStatus] {
|
||||
let status = try await authority.handle(.init(operation: operation, releaseID: entry.releaseID))
|
||||
XCTAssertFalse(status.isInstalling); XCTAssertEqual(status.receipt?.releaseID, entry.releaseID)
|
||||
}
|
||||
let directory = model.personalDirectory(entry), working = directory.appendingPathComponent("Working/GAME.dsk")
|
||||
var saved = original; saved[0] ^= 1; try saved.write(to: working)
|
||||
let members = try await authority.handle(.init(operation: .diskMembers, releaseID: entry.releaseID))
|
||||
XCTAssertEqual(members.disks?.map(\.path), ["GAME.dsk"])
|
||||
let export = try await authority.handle(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
|
||||
let copy = try XCTUnwrap(export.exportedDiskURL)
|
||||
XCTAssertNotEqual(copy, working); XCTAssertEqual(try Data(contentsOf: copy), saved)
|
||||
try Data([1, 2, 3]).write(to: copy)
|
||||
let second = try await authority.handle(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
|
||||
XCTAssertNotEqual(second.exportedDiskURL, copy)
|
||||
XCTAssertEqual(try Data(contentsOf: working), saved)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.dsk")), original)
|
||||
XCTAssertEqual(try Data(contentsOf: source), original)
|
||||
let asset = try XCTUnwrap(snapshot.catalog.releases.first(where: { $0.id == entry.releaseID })?.primaryManualAsset)
|
||||
let response = try await authority.handle(.init(operation: .manual, assetID: asset.id))
|
||||
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(response.assetFileURL)), instructions)
|
||||
let localManual = try XCTUnwrap(response.assetFileURL)
|
||||
try FileManager.default.removeItem(at: localManual)
|
||||
try FileManager.default.createSymbolicLink(at: localManual, withDestinationURL: manual)
|
||||
await assertFailure(authority, .init(operation: .manual, assetID: asset.id))
|
||||
await assertFailure(authority, .init(operation: .removeInstallation, releaseID: entry.releaseID))
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: working.path))
|
||||
await model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testAuthorityRefusesHiddenUnknownNondiskAndUnnegotiatedPersonalIDs() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionHidden-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let draft = try await model.personalStore.inspect([fixture])
|
||||
let visible = try await model.personalStore.save(draft)
|
||||
let duplicate = try await model.personalStore.inspect([fixture])
|
||||
var hidden = try await model.personalStore.save(duplicate, allowDuplicate: true)
|
||||
hidden.hidden = true; try await model.personalStore.update(hidden)
|
||||
let cart = root.appendingPathComponent("CART.ccc"); try Data([0x39]).write(to: cart)
|
||||
let cartDraft = try await model.personalStore.inspect([cart])
|
||||
let nondisk = try await model.personalStore.save(cartDraft)
|
||||
var unsupported: [PersonalSoftwareEntry] = []
|
||||
for ext in ["dmk", "jvc", "vdk"] {
|
||||
let file = root.appendingPathComponent("Unsupported." + ext)
|
||||
try FileManager.default.copyItem(at: fixture, to: file)
|
||||
let draft = try await model.personalStore.inspect([file])
|
||||
unsupported.append(try await model.personalStore.save(draft))
|
||||
}
|
||||
await model.load(from: fixture, catalogLoader: { _ in Self.catalog })
|
||||
let authority = CompanionLibraryAuthority(model: model)
|
||||
let current = try await authority.handle(.init(operation: .snapshot))
|
||||
XCTAssertEqual(Set(current.snapshot!.catalog.releases.map(\.id)), Set(["disk", visible.releaseID]))
|
||||
for version in [nil, 2] as [Int?] {
|
||||
let response = try await authority.handle(.init(operation: .snapshot, personalTitlesVersion: version))
|
||||
XCTAssertEqual(response.snapshot?.catalog.releases.map(\.id), ["disk"])
|
||||
XCTAssertTrue(response.snapshot!.installations.isEmpty)
|
||||
await assertFailure(authority, .init(operation: .diskMembers, releaseID: visible.releaseID, personalTitlesVersion: version))
|
||||
await assertFailure(authority, .init(operation: .setFavorite, titleID: visible.titleID, enabled: true, personalTitlesVersion: version))
|
||||
}
|
||||
for entry in [hidden, nondisk] + unsupported {
|
||||
await assertFailure(authority, .init(operation: .diskMembers, releaseID: entry.releaseID))
|
||||
await assertFailure(authority, .init(operation: .setFavorite, titleID: entry.titleID, enabled: true))
|
||||
}
|
||||
await assertFailure(authority, .init(operation: .diskMembers, releaseID: "personal:unknown:edition"))
|
||||
await assertFailure(authority, .init(operation: .setPreferredRelease, releaseID: visible.releaseID, titleID: hidden.titleID))
|
||||
await assertFailure(authority, .init(operation: .exportDisk, releaseID: visible.releaseID, memberPath: "../DECB.dsk"))
|
||||
await assertFailure(authority, .init(operation: .exportDisk, releaseID: visible.releaseID, memberPath: "missing.dsk"))
|
||||
var removed = visible; removed.hidden = true; try await model.personalStore.update(removed)
|
||||
await assertFailure(authority, .init(operation: .diskMembers, releaseID: visible.releaseID))
|
||||
await model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testAuthorityRefusesPersonalWorkingAndMemberSymlinks() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionLinks-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
|
||||
let source = root.appendingPathComponent("Set/sub"), fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
|
||||
try FileManager.default.copyItem(at: fixture, to: source.appendingPathComponent("GAME.dsk"))
|
||||
let draft = try await model.personalStore.inspect([source.deletingLastPathComponent()])
|
||||
let entry = try await model.personalStore.save(draft)
|
||||
await model.load(from: fixture, catalogLoader: { _ in Self.catalog })
|
||||
let authority = CompanionLibraryAuthority(model: model), directory = model.personalDirectory(entry)
|
||||
let working = directory.appendingPathComponent("Working"), member = working.appendingPathComponent("sub/GAME.dsk")
|
||||
let original = try Data(contentsOf: fixture)
|
||||
try FileManager.default.removeItem(at: member)
|
||||
try FileManager.default.createSymbolicLink(at: member, withDestinationURL: fixture)
|
||||
await assertFailure(authority, .init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "sub/GAME.dsk"))
|
||||
try FileManager.default.removeItem(at: working.appendingPathComponent("sub"))
|
||||
try FileManager.default.createSymbolicLink(at: working.appendingPathComponent("sub"), withDestinationURL: source)
|
||||
await assertFailure(authority, .init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "sub/GAME.dsk"))
|
||||
try FileManager.default.moveItem(at: working, to: directory.appendingPathComponent("RetainedWorking"))
|
||||
try FileManager.default.createSymbolicLink(at: working, withDestinationURL: directory.appendingPathComponent("RetainedWorking"))
|
||||
await assertFailure(authority, .init(operation: .diskMembers, releaseID: entry.releaseID))
|
||||
XCTAssertEqual(try Data(contentsOf: fixture), original)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/sub/GAME.dsk")), original)
|
||||
await model.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testCompanionModelPlaysPersonalDiskThroughActualAuthority() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionClient-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let host = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let source = root.appendingPathComponent("PRIVATE.dsk"), original = try Data(contentsOf: fixture)
|
||||
try original.write(to: source)
|
||||
let draft = try await host.personalStore.inspect([source])
|
||||
let entry = try await host.personalStore.save(draft)
|
||||
await host.load(from: fixture, catalogLoader: { _ in Self.catalog })
|
||||
let directory = host.personalDirectory(entry), working = directory.appendingPathComponent("Working/PRIVATE.dsk")
|
||||
var workingBytes = original; workingBytes[0] ^= 1
|
||||
try workingBytes.write(to: working)
|
||||
let service = AuthorityLibrary(authority: .init(model: host))
|
||||
var inserted: [URL] = []
|
||||
var insertedBytes: [Data] = []
|
||||
let client = SoftwareLibraryModel(companion: service) { url in
|
||||
inserted.append(url)
|
||||
insertedBytes.append(try Data(contentsOf: url))
|
||||
// Real DriveWire writes must affect only its separate handoff image.
|
||||
try Data([0x42, 0x43]).write(to: url)
|
||||
}
|
||||
await client.load()
|
||||
XCTAssertNil(client.error)
|
||||
let release = try XCTUnwrap(client.catalog?.releases.first(where: { $0.id == entry.releaseID }))
|
||||
XCTAssertTrue(release.isPersonal)
|
||||
XCTAssertNotNil(client.state.installedReleases[entry.releaseID])
|
||||
client.play(release)
|
||||
for _ in 0..<100 where client.installingReleaseID != nil { try await Task.sleep(nanoseconds: 20_000_000) }
|
||||
XCTAssertNil(client.installingReleaseID, "The local companion operation must complete without downloading or launching the emulator.")
|
||||
XCTAssertNil(client.installationErrors[entry.releaseID]); XCTAssertNil(client.launchError)
|
||||
XCTAssertEqual(inserted.count, 1)
|
||||
XCTAssertEqual(insertedBytes, [workingBytes])
|
||||
let copy = try XCTUnwrap(inserted.first)
|
||||
XCTAssertNotEqual(copy, working)
|
||||
XCTAssertTrue(copy.path.hasPrefix(host.state.directory.appendingPathComponent("CompanionDisks").path + "/"))
|
||||
XCTAssertEqual(try Data(contentsOf: copy), Data([0x42, 0x43]))
|
||||
XCTAssertEqual(try Data(contentsOf: working), workingBytes)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/PRIVATE.dsk")), original)
|
||||
XCTAssertEqual(try Data(contentsOf: source), original)
|
||||
let requests = await service.requests
|
||||
XCTAssertEqual(requests.map(\.operation), [.snapshot, .install, .diskMembers, .exportDisk])
|
||||
XCTAssertTrue(requests.allSatisfy { $0.personalTitlesVersion == 1 })
|
||||
await client.shutdown(); await host.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testSelectedPersonalCoverAndRemovalReachCompanionWithoutChangingDiskBytes() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionCover-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let host = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let source = root.appendingPathComponent("GAME.dsk"), original = try Data(contentsOf: fixture)
|
||||
try original.write(to: source)
|
||||
let context = try XCTUnwrap(CGContext(data: nil, width: 24, height: 36, bitsPerComponent: 8,
|
||||
bytesPerRow: 24 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
|
||||
context.setFillColor(CGColor(gray: 0.3, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 24, height: 36))
|
||||
let imageBytes = NSMutableData()
|
||||
let encoder = try XCTUnwrap(CGImageDestinationCreateWithData(imageBytes, UTType.png.identifier as CFString, 1, nil))
|
||||
CGImageDestinationAddImage(encoder, try XCTUnwrap(context.makeImage()), nil)
|
||||
XCTAssertTrue(CGImageDestinationFinalize(encoder))
|
||||
let authored = imageBytes as Data, imported = root.appendingPathComponent("Imported.png")
|
||||
try authored.write(to: imported)
|
||||
var draft = try await host.personalStore.inspect([source, imported]); draft.entry.category = "Games"
|
||||
let entry = try await host.personalStore.save(draft, coverPNG: authored)
|
||||
let directory = host.personalDirectory(entry), working = directory.appendingPathComponent("Working/GAME.dsk")
|
||||
var saved = original; saved[0] ^= 1; try saved.write(to: working)
|
||||
await host.load(from: fixture, catalogLoader: { _ in Self.catalog })
|
||||
let authority = CompanionLibraryAuthority(model: host), service = AuthorityLibrary(authority: authority)
|
||||
let client = SoftwareLibraryModel(companion: service) { _ in XCTFail("Artwork browsing must not insert media.") }
|
||||
await client.load()
|
||||
let release = try XCTUnwrap(client.catalog?.releases.first { $0.id == entry.releaseID })
|
||||
let asset = try XCTUnwrap(release.assets.first { $0.kind == "cover" })
|
||||
XCTAssertEqual(release.assets.filter { $0.kind == "cover" }.count, 1)
|
||||
XCTAssertEqual(asset.name, "Personal Cover Image")
|
||||
XCTAssertTrue(asset.id.contains(":asset:PersonalCovers/"))
|
||||
XCTAssertTrue(SoftwareLibraryArtworkCache.canDisplay(asset))
|
||||
let local = try XCTUnwrap(asset.thumbnailURL), retainedCover = try Data(contentsOf: local)
|
||||
let thumbnail = try await service.libraryRequest(.init(operation: .thumbnail, assetID: asset.id))
|
||||
let decoded = try XCTUnwrap(SoftwareLibraryArtworkCache.image(from: XCTUnwrap(thumbnail.assetData)))
|
||||
XCTAssertEqual(decoded.width, 24); XCTAssertEqual(decoded.height, 36)
|
||||
// Even an otherwise selected local asset must retain its recorded hash.
|
||||
var changed = retainedCover; changed[changed.count - 1] ^= 1; try changed.write(to: local)
|
||||
await assertFailure(authority, .init(operation: .thumbnail, assetID: asset.id))
|
||||
try retainedCover.write(to: local)
|
||||
let oldClient = try await service.libraryRequest(.init(operation: .snapshot, personalTitlesVersion: nil))
|
||||
XCTAssertFalse(oldClient.snapshot!.catalog.titles.contains { $0.id == entry.titleID })
|
||||
let beforeRemoval = try await service.libraryRequest(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
|
||||
let beforeCopy = try XCTUnwrap(beforeRemoval.exportedDiskURL)
|
||||
XCTAssertEqual(try Data(contentsOf: beforeCopy), saved)
|
||||
host.query.scope = .personal; host.selection = entry.titleID
|
||||
host.selectPersonalCover(.categoryIcon, for: entry)
|
||||
for _ in 0..<100 where host.personalSaving { try await Task.sleep(nanoseconds: 20_000_000) }
|
||||
XCTAssertFalse(host.personalSaving); XCTAssertNil(host.personalError)
|
||||
let reopened = SoftwareLibraryModel(companion: service) { _ in XCTFail("Removing artwork must not insert media.") }
|
||||
await reopened.load()
|
||||
let withoutCover = try XCTUnwrap(reopened.catalog?.releases.first { $0.id == entry.releaseID })
|
||||
XCTAssertTrue(withoutCover.assets.filter { $0.thumbnailURL != nil }.isEmpty,
|
||||
"Removal must suppress the imported image as well, leaving the category illustration.")
|
||||
XCTAssertEqual(SoftwareLibraryCategoryStyle.symbol(for: LibraryBrowseQuery.type(of: withoutCover)), "gamecontroller")
|
||||
XCTAssertEqual(withoutCover.packageSHA256, release.packageSHA256)
|
||||
await assertFailure(authority, .init(operation: .thumbnail, assetID: asset.id))
|
||||
let afterRemoval = try await service.libraryRequest(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
|
||||
let afterCopy = try XCTUnwrap(afterRemoval.exportedDiskURL)
|
||||
XCTAssertNotEqual(beforeCopy, afterCopy)
|
||||
XCTAssertEqual(try Data(contentsOf: afterCopy), saved)
|
||||
XCTAssertEqual(try Data(contentsOf: beforeCopy), saved)
|
||||
XCTAssertEqual(try Data(contentsOf: working), saved)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.dsk")), original)
|
||||
XCTAssertEqual(try Data(contentsOf: source), original)
|
||||
XCTAssertEqual(try Data(contentsOf: local), retainedCover)
|
||||
XCTAssertEqual(try Data(contentsOf: imported), authored)
|
||||
await client.shutdown(); await reopened.shutdown(); await host.shutdown()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func assertFailure(_ authority: CompanionLibraryAuthority, _ request: CompanionLibraryRequest,
|
||||
file: StaticString = #filePath, line: UInt = #line) async {
|
||||
do { _ = try await authority.handle(request); XCTFail("Expected refusal for \(request.operation)", file: file, line: line) }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private actor AuthorityLibrary: CompanionLibraryAccess {
|
||||
let authority: CompanionLibraryAuthority
|
||||
private(set) var requests: [CompanionLibraryRequest] = []
|
||||
init(authority: CompanionLibraryAuthority) { self.authority = authority }
|
||||
func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
|
||||
requests.append(request)
|
||||
return try await authority.handle(request)
|
||||
}
|
||||
}
|
||||
|
||||
private actor RecoveringLibrary: CompanionLibraryAccess {
|
||||
let catalog: SoftwareLibraryCatalog
|
||||
private var connected = false
|
||||
init(catalog: SoftwareLibraryCatalog) { self.catalog = catalog }
|
||||
func reconnect() { connected = true }
|
||||
func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
|
||||
guard connected else { throw CompanionTransport.Failure.unavailable }
|
||||
guard request.operation == .snapshot else { throw CompanionLibraryFailure(message: "Unexpected mutation in reconnect fixture.") }
|
||||
return .init(snapshot: .init(catalog: catalog, favorites: [], preferredReleaseIDs: [:], installations: []))
|
||||
}
|
||||
}
|
||||
|
||||
private actor FakeLibrary: CompanionLibraryAccess {
|
||||
let catalog: SoftwareLibraryCatalog
|
||||
var favorites = Set<String>()
|
||||
|
||||
@@ -2,6 +2,64 @@
|
||||
import XCTest
|
||||
|
||||
final class DebuggerMMUBridgeTests: XCTestCase {
|
||||
@MainActor func testOverlayBridgeQualifiesOwnerAndRequiresFreshResidencyForSourceStep() async {
|
||||
for enhanced in [false, true] {
|
||||
let controller = VCCMachineController()
|
||||
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
|
||||
_ = await command { controller.configureMachine(use6309: enhanced, ram: 1, overclock: 1, frameInterval: 1, fastForward: false, completion: $0) }
|
||||
_ = await command { controller.loadDiagnostic(use6309: enhanced, completion: $0) }
|
||||
// Initial authored code setup. Guest-driven replacement itself is
|
||||
// covered by the core and disposable-worker loader fixtures.
|
||||
let a = Data([0x12, 0x86, 0x11, 0x39]), b = Data([0x12, 0x86, 0x22, 0x39])
|
||||
_ = await command { controller.debuggerWriteMemory(address: 0x4000, data: a, completion: $0) }
|
||||
_ = await command { controller.debuggerSetPC(0x4000, completion: $0) }
|
||||
_ = await command { controller.debuggerSetBreakpoints([0x4567], completion: $0) }
|
||||
let initial = await capture(controller, includePhysical: false)
|
||||
let physical = Int(initial.mmu.effective[2].sourceAddress / 8192)
|
||||
let modules: [[String: Any]] = [("a", a), ("b", b)].map { name, bytes in
|
||||
["id": name, "pages": [["logicalPage": 2, "physicalPage": physical]],
|
||||
"addresses": [0x4000], "bytes": [bytes], "breakpoints": [],
|
||||
"overlay_group": "stage", "overlay_owner": name]
|
||||
}
|
||||
let armed = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: modules, completion: $0) }
|
||||
XCTAssertNil(armed.errorMessage); XCTAssertTrue(armed.debuggerDevelopmentAttached)
|
||||
XCTAssertNotEqual(armed.debuggerResidencyFingerprint, 0)
|
||||
var malformed = modules
|
||||
malformed[0].removeValue(forKey: "overlay_owner")
|
||||
let invalid = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: malformed, completion: $0) }
|
||||
XCTAssertNotNil(invalid.errorMessage)
|
||||
XCTAssertEqual(invalid.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint)
|
||||
for key in ["overlay_group", "overlay_owner"] {
|
||||
var definitions = modules; definitions[0][key] = "a\0truncated"
|
||||
let rejectedDefinitions = definitions
|
||||
let rejected = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: rejectedDefinitions, completion: $0) }
|
||||
XCTAssertNotNil(rejected.errorMessage)
|
||||
XCTAssertEqual(rejected.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint)
|
||||
}
|
||||
func step(_ fingerprint: UInt64) async -> VCCMachineSnapshot {
|
||||
await command {
|
||||
controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001,0x4000,0x4001], locations: [1,2,3,4],
|
||||
bytes: [Data([0x12]),Data([0x86,0x11]),Data([0x12]),Data([0x86,0x22])],
|
||||
moduleIdentifiers: ["a","a","b","b"], generation: armed.generation,
|
||||
programRevision: armed.debuggerProgramRevision, mappingFingerprint: armed.debuggerMappingFingerprint,
|
||||
residencyFingerprint: fingerprint, programCounter: 0x4000, completion: $0)
|
||||
}
|
||||
}
|
||||
let stale = await step(armed.debuggerResidencyFingerprint &+ 1)
|
||||
XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.cycles, armed.cycles)
|
||||
let started = await step(armed.debuggerResidencyFingerprint)
|
||||
XCTAssertNil(started.errorMessage)
|
||||
var stopped = started
|
||||
for _ in 0..<100 where stopped.state == .running {
|
||||
try? await Task.sleep(for: .milliseconds(5)); stopped = await command(controller.snapshot)
|
||||
}
|
||||
XCTAssertEqual(stopped.state, .paused); XCTAssertEqual(stopped.programCounter, 0x4001)
|
||||
XCTAssertEqual(stopped.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint)
|
||||
let final = await capture(controller, includePhysical: false)
|
||||
XCTAssertEqual(final.breakpoints.map(\.uint16Value), [0x4567])
|
||||
_ = await command(controller.shutdown)
|
||||
}
|
||||
}
|
||||
@MainActor func testBankedGuardBridgeFreezesModulesAndPreservesManualPoints() async {
|
||||
let controller = VCCMachineController()
|
||||
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
|
||||
@@ -41,7 +99,8 @@ final class DebuggerMMUBridgeTests: XCTestCase {
|
||||
controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001], locations: [1,2],
|
||||
bytes: [Data([0x12]),Data([0x20,0xfe])], moduleIdentifiers: ["resident","resident"],
|
||||
generation: armed.generation, programRevision: armed.debuggerProgramRevision,
|
||||
mappingFingerprint: armed.debuggerMappingFingerprint &+ 1, programCounter: 0x4000, completion: $0)
|
||||
mappingFingerprint: armed.debuggerMappingFingerprint &+ 1,
|
||||
residencyFingerprint: armed.debuggerResidencyFingerprint, programCounter: 0x4000, completion: $0)
|
||||
}
|
||||
XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.state, .paused)
|
||||
let cleared = await command(controller.debuggerClearDevelopmentBreakpoints)
|
||||
|
||||
@@ -1,7 +1,155 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import AppKit
|
||||
|
||||
final class InputTests: XCTestCase {
|
||||
private func inputStore() throws -> InputSettingsStore {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("InputSelection-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
addTeardownBlock { try? FileManager.default.removeItem(at: directory) }
|
||||
return InputSettingsStore(url: directory.appendingPathComponent("input.json"))
|
||||
}
|
||||
|
||||
func testSoleControllerPolicyPreservesOtherSourcesAndRememberedAssignments() {
|
||||
for source in JoystickSource.allCases {
|
||||
var settings = InputSettings(); settings.right.source = source
|
||||
settings.right.interface = .tandy; settings.right.rightStick = true
|
||||
settings.right.fire1 = 4; settings.right.fire2 = 8; settings.right.deadZone = 0.3
|
||||
settings.left.source = .controller; settings.left.device = "disconnected-remembered"
|
||||
XCTAssertEqual(settings.assigningSoleController([]), settings)
|
||||
XCTAssertEqual(settings.assigningSoleController(["first", "second"]), settings)
|
||||
let selected = settings.assigningSoleController(["sole"])
|
||||
var expected = settings
|
||||
if source == .controller { expected.right.device = "sole" }
|
||||
XCTAssertEqual(selected, expected)
|
||||
var remembered = settings; remembered.right.device = "previous-controller"
|
||||
XCTAssertEqual(remembered.assigningSoleController(["sole"]), remembered)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func testSelectingControllerWithSoleCachedDevicePersistsOnceAndReopens() throws {
|
||||
_ = NSApplication.shared
|
||||
let store = try inputStore()
|
||||
var settings = InputSettings(); settings.right.source = .keyboard
|
||||
settings.right.interface = .tandy; settings.right.rightStick = true
|
||||
settings.right.fire1 = 4; settings.right.fire2 = 1; settings.right.deadZone = 0.25
|
||||
try store.save(settings)
|
||||
let device = ControllerReading(id: "gc:authored:0", name: "Authored controller", rx: 1, ry: -1, buttons: 8)
|
||||
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [device] }, automaticallyPoll: false)
|
||||
hub.poll()
|
||||
XCTAssertEqual(hub.epoch, 0)
|
||||
hub.settings.right.source = .controller
|
||||
settings.right.source = .controller; settings.right.device = device.id
|
||||
XCTAssertEqual(hub.settings, settings)
|
||||
XCTAssertEqual(hub.epoch, 1, "One effective settings edit must release and persist once")
|
||||
XCTAssertEqual(try store.load(), settings)
|
||||
XCTAssertFalse(try store.loadState().automaticRightController)
|
||||
hub.poll()
|
||||
XCTAssertEqual(hub.preview[0], JoystickSample(x: 16383, y: 0, buttons: 1))
|
||||
let stamp = Date(timeIntervalSince1970: 1234)
|
||||
try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: store.url.path)
|
||||
for _ in 0..<8 { hub.poll() }
|
||||
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: store.url.path)[.modificationDate] as? Date, stamp)
|
||||
let reopened = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [device] }, automaticallyPoll: false)
|
||||
reopened.poll()
|
||||
XCTAssertEqual(reopened.settings, settings); XCTAssertEqual(reopened.epoch, 0)
|
||||
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: store.url.path)[.modificationDate] as? Date, stamp)
|
||||
}
|
||||
|
||||
@MainActor func testUnassignedControllerAdoptsLateDeviceButNeverStealsDisconnectedAssignment() throws {
|
||||
_ = NSApplication.shared
|
||||
let store = try inputStore()
|
||||
var settings = InputSettings(); settings.right.source = .controller
|
||||
try store.save(settings)
|
||||
var observed: [ControllerReading] = []
|
||||
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
|
||||
hub.poll(); XCTAssertEqual(hub.settings, settings); XCTAssertEqual(hub.epoch, 0)
|
||||
observed = [ControllerReading(id: "hid:authored:one", name: "First"), ControllerReading(id: "gc:authored:two", name: "Second")]
|
||||
hub.poll(); XCTAssertEqual(hub.settings.right.device, ""); XCTAssertEqual(hub.epoch, 0)
|
||||
observed.removeLast(); hub.poll()
|
||||
XCTAssertEqual(hub.settings.right.device, "hid:authored:one"); XCTAssertEqual(hub.epoch, 1)
|
||||
observed = [ControllerReading(id: "gc:authored:two", name: "Other", x: 1, buttons: 3)]
|
||||
hub.poll()
|
||||
XCTAssertEqual(hub.settings.right.device, "hid:authored:one")
|
||||
XCTAssertEqual(hub.preview[0], JoystickSample()); XCTAssertEqual(hub.epoch, 1)
|
||||
XCTAssertEqual(try store.load(), hub.settings)
|
||||
}
|
||||
|
||||
@MainActor func testFreshMouseFallbackSurvivesStoreRecreationThenAdoptsSoleController() throws {
|
||||
_ = NSApplication.shared
|
||||
let immediateStore = try inputStore()
|
||||
let immediate = InputHub(controller: VCCMachineController(), store: immediateStore,
|
||||
controllerReadings: { [ControllerReading(id: "connected-at-launch", name: "Sole")] }, automaticallyPoll: false)
|
||||
immediate.poll()
|
||||
XCTAssertEqual(immediate.settings.right.source, .controller)
|
||||
XCTAssertEqual(immediate.settings.right.device, "connected-at-launch")
|
||||
XCTAssertEqual(immediate.settings.left.source, .none)
|
||||
XCTAssertEqual(try immediateStore.load(), immediate.settings)
|
||||
let store = try inputStore()
|
||||
var observed: [ControllerReading] = []
|
||||
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
|
||||
XCTAssertEqual(hub.settings, .freshDefaults)
|
||||
hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse); XCTAssertEqual(hub.settings.left.source, .none)
|
||||
observed = [ControllerReading(id: "one", name: "First"), ControllerReading(id: "two", name: "Second")]
|
||||
hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse)
|
||||
hub.settings.keyboard = .compact
|
||||
XCTAssertTrue(try store.loadState().automaticRightController)
|
||||
let reopened = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
|
||||
observed.removeLast(); reopened.poll()
|
||||
XCTAssertEqual(reopened.settings.right.source, .controller); XCTAssertEqual(reopened.settings.right.device, "one")
|
||||
XCTAssertEqual(reopened.settings.keyboard, .compact); XCTAssertEqual(reopened.settings.left.source, .none)
|
||||
XCTAssertFalse(try store.loadState().automaticRightController)
|
||||
}
|
||||
|
||||
@MainActor func testLegacyExplicitSourcesAndPersonalProfileOverrideFreshAutomaticDefault() throws {
|
||||
_ = NSApplication.shared
|
||||
let sole = ControllerReading(id: "one", name: "Sole")
|
||||
for source in [JoystickSource.none, .keyboard, .mouse] {
|
||||
let store = try inputStore()
|
||||
var settings = InputSettings(); settings.right.source = source
|
||||
// Exact previous-format document has no automatic-default marker.
|
||||
try JSONEncoder().encode(settings).write(to: store.url)
|
||||
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [sole] }, automaticallyPoll: false)
|
||||
hub.poll(); XCTAssertEqual(hub.settings, settings); XCTAssertEqual(hub.epoch, 0)
|
||||
}
|
||||
let store = try inputStore()
|
||||
var observed: [ControllerReading] = []
|
||||
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
|
||||
hub.applyProfileSettings(.freshDefaults)
|
||||
XCTAssertFalse(try store.loadState().automaticRightController, "An explicit profile's Mouse source is authoritative even when it matches the fresh fallback")
|
||||
observed = [sole]; hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse)
|
||||
hub.restoreDefaultSettings(); hub.poll()
|
||||
XCTAssertEqual(hub.settings.right.source, .controller); XCTAssertEqual(hub.settings.right.device, sole.id)
|
||||
XCTAssertEqual(hub.settings.left.source, .none)
|
||||
hub.settings.right = PortSettings(source: .mouse)
|
||||
hub.poll()
|
||||
XCTAssertEqual(hub.settings.right.source, .mouse)
|
||||
XCTAssertFalse(try store.loadState().automaticRightController, "An explicit right-port edit must end fresh automatic discovery")
|
||||
}
|
||||
@MainActor func testLibraryHintsPreserveUnchangedFreshRightPolicyAcrossReload() throws {
|
||||
_ = NSApplication.shared
|
||||
let store = try inputStore()
|
||||
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [] }, automaticallyPoll: false)
|
||||
var librarySettings = hub.settings
|
||||
librarySettings.left.source = .keyboard
|
||||
hub.applyLibrarySettings(librarySettings)
|
||||
XCTAssertEqual(try store.load(), librarySettings)
|
||||
XCTAssertTrue(try store.loadState().automaticRightController)
|
||||
let reopened = InputHub(controller: VCCMachineController(), store: store,
|
||||
controllerReadings: { [ControllerReading(id: "late", name: "Sole")] }, automaticallyPoll: false)
|
||||
reopened.poll()
|
||||
XCTAssertEqual(reopened.settings.right.source, .controller)
|
||||
XCTAssertEqual(reopened.settings.right.device, "late")
|
||||
XCTAssertEqual(reopened.settings.left, librarySettings.left)
|
||||
XCTAssertFalse(try store.loadState().automaticRightController)
|
||||
// A library action must not re-enable discovery after an explicit
|
||||
// personal profile selected Mouse, even if all its values match.
|
||||
reopened.applyProfileSettings(.freshDefaults)
|
||||
reopened.applyLibrarySettings(.freshDefaults)
|
||||
reopened.poll()
|
||||
XCTAssertEqual(reopened.settings.right.source, .mouse)
|
||||
XCTAssertFalse(try store.loadState().automaticRightController)
|
||||
}
|
||||
func testKeyboardModesAndReservedNavigation() {
|
||||
var keyboard = CocoKeyboard()
|
||||
keyboard.mode = .coco
|
||||
@@ -194,7 +342,7 @@ final class InputTests: XCTestCase {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = InputSettingsStore(url: directory.appendingPathComponent("input.json"))
|
||||
XCTAssertEqual(try store.load(), InputSettings())
|
||||
XCTAssertEqual(try store.load(), .freshDefaults)
|
||||
var settings = InputSettings(); settings.keyboard = .compact
|
||||
settings.right.source = .controller; settings.right.device = "authored controller"
|
||||
settings.right.interface = .tandy; settings.left.source = .keyboard; settings.left.keys = .wasd
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
import PDFKit
|
||||
import WebKit
|
||||
import XCTest
|
||||
import SQLite3
|
||||
|
||||
@MainActor
|
||||
final class LibraryContinuityTests: XCTestCase {
|
||||
private var directory: URL!
|
||||
override func setUpWithError() throws {
|
||||
directory = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryContinuity-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
|
||||
}
|
||||
override func tearDownWithError() throws { try FileManager.default.removeItem(at: directory) }
|
||||
|
||||
func testBrowseReadingAndIndependentBookmarksRoundTripAcrossRelaunch() async throws {
|
||||
let store = LibraryContinuityStore(directory: directory)
|
||||
var browse = LibraryBrowseState()
|
||||
browse.scope = "Games"; browse.query = "adventure"; browse.selectedID = "personal:one"
|
||||
browse.filters = ["format":"disk", "sort":"name"]; browse.topVisibleID = "personal:two"
|
||||
store.setBrowse(browse, for: "software-main")
|
||||
let first = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "alpha", offset: 0.25)
|
||||
let second = LibraryReadingPosition(documentID: "book-two", relativePath: "book-two/chapter.html", anchor: "beta", offset: 0.5)
|
||||
let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Alpha", position: first))
|
||||
store.setReading(second, for: "manual-last")
|
||||
store.renameBookmark(mark.id, label: "My reference")
|
||||
await store.flush()
|
||||
let restored = LibraryContinuityStore(directory: directory)
|
||||
XCTAssertEqual(restored.browse(for: "software-main"), browse)
|
||||
XCTAssertEqual(restored.reading(for: "manual-last"), second)
|
||||
XCTAssertEqual(restored.bookmarks.first?.position, first)
|
||||
XCTAssertEqual(restored.bookmarks.first?.displayName, "My reference")
|
||||
}
|
||||
|
||||
func testDuplicateBookmarkPreservesOriginalLabelAndPosition() async throws {
|
||||
let store = LibraryContinuityStore(directory: directory)
|
||||
let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/a.html", anchor: "section", offset: 0.2)
|
||||
let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "Section", position: position))
|
||||
store.renameBookmark(mark.id, label: "Keep this")
|
||||
var moved = position; moved.offset = 0.8
|
||||
let again = store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "New heading", position: moved)
|
||||
XCTAssertEqual(again?.id, mark.id)
|
||||
XCTAssertEqual(store.bookmarks.count, 1)
|
||||
XCTAssertEqual(store.bookmarks.first?.position.offset, 0.2)
|
||||
XCTAssertEqual(store.bookmarks.first?.label, "Keep this")
|
||||
store.removeBookmark(mark.id)
|
||||
await store.flush()
|
||||
XCTAssertTrue(LibraryContinuityStore(directory: directory).bookmarks.isEmpty)
|
||||
}
|
||||
|
||||
func testNewerOrUnreadableStateIsNeverOverwritten() async throws {
|
||||
let file = directory.appendingPathComponent("LibraryContinuity.json")
|
||||
for bytes in [Data("{\"version\":999,\"browse\":{},\"reading\":{},\"bookmarks\":[]}".utf8), Data("invalid json".utf8)] {
|
||||
try bytes.write(to: file, options: .atomic)
|
||||
let store = LibraryContinuityStore(directory: directory)
|
||||
XCTAssertNotNil(store.saveError)
|
||||
store.setBrowse(LibraryBrowseState(), for: "archive-main")
|
||||
await store.flush()
|
||||
XCTAssertEqual(try Data(contentsOf: file), bytes)
|
||||
}
|
||||
}
|
||||
|
||||
func testInvalidPositionsCannotEscapeContentRootOrPersistNonfiniteValues() async throws {
|
||||
let store = LibraryContinuityStore(directory: directory)
|
||||
store.setReading(LibraryReadingPosition(documentID: "one", relativePath: "../private.html"), for: "bad-path")
|
||||
store.setReading(LibraryReadingPosition(documentID: "one", offset: .nan), for: "bad-offset")
|
||||
var browse = LibraryBrowseState(); browse.pageOffset = -1
|
||||
store.setBrowse(browse, for: "bad-browse")
|
||||
await store.flush()
|
||||
XCTAssertNil(store.reading(for: "bad-path")); XCTAssertNil(store.reading(for: "bad-offset"))
|
||||
XCTAssertNil(store.browse(for: "bad-browse"))
|
||||
}
|
||||
|
||||
func testManualScrollBookmarkAndResumeUseStableSectionInSeparateReader() async throws {
|
||||
_ = NSApplication.shared
|
||||
let contentRoot = directory.appendingPathComponent("Manuals")
|
||||
let book = contentRoot.appendingPathComponent("book-one")
|
||||
try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true)
|
||||
let page = book.appendingPathComponent("chapter.html")
|
||||
try """
|
||||
<!doctype html><html><head><title>One</title></head><body>
|
||||
<nav class="crumb"><a href="../index.html">Library</a><a href="template.html">Book One</a></nav>
|
||||
<article><h1>Chapter</h1><section id="alpha" style="height:1400px"><h2>Alpha</h2></section>
|
||||
<section id="beta" style="height:1400px"><h2>Beta</h2></section></article>
|
||||
</body></html>
|
||||
""".write(to: page, atomically: true, encoding: .utf8)
|
||||
try "<html><body>Home</body></html>".write(to: contentRoot.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
|
||||
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
|
||||
let reader = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: store)
|
||||
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
reader.webView.loadFileURL(page, allowingReadAccessTo: contentRoot)
|
||||
try await waitFor { reader.currentPosition?.relativePath == "book-one/chapter.html" }
|
||||
_ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();")
|
||||
try await waitFor { reader.currentPosition?.anchor == "beta" }
|
||||
reader.bookmarkCurrentLocation()
|
||||
try await waitFor { store.bookmarks.count == 1 }
|
||||
XCTAssertEqual(store.bookmarks.first?.sectionTitle, "Beta")
|
||||
await store.flush()
|
||||
let restoredStore = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
|
||||
let reopened = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: restoredStore)
|
||||
reopened.webView.frame = reader.webView.frame
|
||||
reopened.resume()
|
||||
try await waitFor { reopened.currentPosition?.anchor == "beta" }
|
||||
XCTAssertGreaterThan(reopened.currentPosition?.offset ?? 0, 0)
|
||||
XCTAssertEqual(reopened.currentBookTitle, "Book One")
|
||||
XCTAssertEqual(restoredStore.bookmarks.count, 1)
|
||||
}
|
||||
|
||||
func testImmediateBookmarkSamplesFreshScrollAndIgnoresSupersedingNavigation() async throws {
|
||||
_ = NSApplication.shared
|
||||
let root = directory.appendingPathComponent("Manuals")
|
||||
let book = root.appendingPathComponent("book-one")
|
||||
try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true)
|
||||
let page = book.appendingPathComponent("chapter.html")
|
||||
try """
|
||||
<!doctype html><html><head><title>One</title></head><body>
|
||||
<article><h1>Chapter</h1><section id="alpha" style="height:1400px"><h2>Alpha</h2></section>
|
||||
<section id="beta" style="height:1400px"><h2>Beta</h2></section></article>
|
||||
</body></html>
|
||||
""".write(to: page, atomically: true, encoding: .utf8)
|
||||
try "<html><body>Home</body></html>".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
|
||||
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
|
||||
let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store)
|
||||
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
reader.webView.loadFileURL(page, allowingReadAccessTo: root)
|
||||
try await waitFor { reader.currentPosition != nil }
|
||||
XCTAssertNotEqual(reader.currentPosition?.anchor, "beta")
|
||||
// Deliberately do not call the checkpoint or wait for its one-second
|
||||
// scroll timer before performing the user's bookmark action.
|
||||
_ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100)")
|
||||
reader.bookmarkCurrentLocation()
|
||||
try await waitFor { store.bookmarks.count == 1 }
|
||||
XCTAssertEqual(store.bookmarks[0].position.anchor, "beta")
|
||||
XCTAssertEqual(store.bookmarks[0].sectionTitle, "Beta")
|
||||
XCTAssertGreaterThan(store.bookmarks[0].position.offset, 0)
|
||||
|
||||
store.removeBookmark(store.bookmarks[0].id)
|
||||
reader.bookmarkCurrentLocation()
|
||||
reader.showHome()
|
||||
try await waitFor { reader.currentPosition?.relativePath == "index.html" }
|
||||
XCTAssertTrue(store.bookmarks.isEmpty, "A checkpoint from a superseded page must not create a bookmark")
|
||||
}
|
||||
|
||||
func testArchiveDeepLinkFindsExactDocumentOutsideFirstBrowseBatch() async throws {
|
||||
let database = directory.appendingPathComponent("Archive.sqlite")
|
||||
var handle: OpaquePointer?
|
||||
XCTAssertEqual(sqlite3_open(database.path, &handle), SQLITE_OK)
|
||||
defer { sqlite3_close(handle) }
|
||||
var sql = """
|
||||
PRAGMA application_id=0x56434341; PRAGMA user_version=2;
|
||||
CREATE TABLE document(id INTEGER PRIMARY KEY,sha256 TEXT,title TEXT,collection TEXT,format TEXT,source_url TEXT,page_count INTEGER,issue_year TEXT);
|
||||
"""
|
||||
for n in 0..<72 {
|
||||
let digest = String(format: "%064x", n+1)
|
||||
sql += "INSERT INTO document VALUES(\(n+1),'\(digest)','Title \(String(format: "%03d", n))','Books','text','https://colorcomputerarchive.com/repo/Documents/Books/\(n).txt',1,NULL);"
|
||||
}
|
||||
XCTAssertEqual(sqlite3_exec(handle, sql, nil, nil, nil), SQLITE_OK)
|
||||
let catalog = ArchiveLibraryCatalog(url: database)
|
||||
let digest = String(format: "%064x", 61)
|
||||
let exact = try await catalog.document(id: digest)
|
||||
XCTAssertEqual(exact?.title, "Title 060")
|
||||
let offset = try await catalog.browseOffset(documentID: digest, collection: "Books", batchSize: 35)
|
||||
XCTAssertEqual(offset, 35)
|
||||
let rows = try await catalog.browse(collection: "Books", limit: 35, offset: offset ?? 0)
|
||||
XCTAssertTrue(rows.contains { $0.id == digest })
|
||||
let malformed = try await catalog.document(id: "not-a-content-identity")
|
||||
XCTAssertNil(malformed)
|
||||
}
|
||||
|
||||
func testTwoBookReadingPositionsAndBookmarksSurviveReaderAndStoreRecreation() async throws {
|
||||
_ = NSApplication.shared
|
||||
let root = try makeTwoBookManuals()
|
||||
let state = directory.appendingPathComponent("State")
|
||||
let store = LibraryContinuityStore(directory: state)
|
||||
let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store)
|
||||
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
for book in ["book-one", "book-two"] {
|
||||
reader.webView.loadFileURL(root.appendingPathComponent(book + "/chapter.html"), allowingReadAccessTo: root)
|
||||
try await waitFor { reader.currentBookID == book }
|
||||
_ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();")
|
||||
try await waitFor { reader.currentPosition?.anchor == "beta" }
|
||||
reader.bookmarkCurrentLocation()
|
||||
try await waitFor { store.bookmarks.contains { $0.bookID == book } }
|
||||
}
|
||||
let originalBookmarks = store.bookmarks
|
||||
func assertSavedBookmarks(_ actual: [ManualBookmark], file: StaticString = #filePath, line: UInt = #line) {
|
||||
// Successful navigation may update location validation metadata;
|
||||
// the user's saved identity, label and position must stay fixed.
|
||||
XCTAssertEqual(actual.map(\.id), originalBookmarks.map(\.id), file: file, line: line)
|
||||
XCTAssertEqual(actual.map(\.position), originalBookmarks.map(\.position), file: file, line: line)
|
||||
XCTAssertEqual(actual.map(\.displayName), originalBookmarks.map(\.displayName), file: file, line: line)
|
||||
}
|
||||
let firstPosition = try XCTUnwrap(store.reading(for: "manual-book:book-one"))
|
||||
let secondPosition = try XCTUnwrap(store.reading(for: "manual-book:book-two"))
|
||||
XCTAssertNotEqual(firstPosition.relativePath, secondPosition.relativePath)
|
||||
await store.flush()
|
||||
|
||||
let recreatedStore = LibraryContinuityStore(directory: state)
|
||||
let reopened = ManualReader(content: ManualLibraryContent(root: root), continuity: recreatedStore)
|
||||
reopened.webView.frame = reader.webView.frame
|
||||
reopened.resume()
|
||||
try await waitFor { reopened.currentBookID == "book-two" && reopened.currentPosition?.anchor == "beta" }
|
||||
XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-one"), firstPosition)
|
||||
assertSavedBookmarks(recreatedStore.bookmarks)
|
||||
|
||||
// An explicit bookmark in another book wins over the last-active book.
|
||||
reopened.openBookmark(try XCTUnwrap(originalBookmarks.first { $0.bookID == "book-one" }))
|
||||
try await waitFor { reopened.currentBookID == "book-one" && reopened.currentPosition?.anchor == "beta" }
|
||||
_ = try await reopened.webView.evaluateJavaScript("window.scrollTo(0,0);window.vccLibraryCheckpoint();")
|
||||
try await waitFor { reopened.currentPosition?.anchor == nil }
|
||||
assertSavedBookmarks(recreatedStore.bookmarks)
|
||||
XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-two"), secondPosition)
|
||||
reopened.showHome()
|
||||
try await waitFor { reopened.currentPosition?.relativePath == "index.html" }
|
||||
reopened.resume()
|
||||
XCTAssertEqual(reopened.currentPosition?.relativePath, "index.html", "Explicit Library Home must not be replaced by automatic resume")
|
||||
await recreatedStore.flush()
|
||||
assertSavedBookmarks(LibraryContinuityStore(directory: state).bookmarks)
|
||||
}
|
||||
|
||||
func testUpdatedManualMissingSectionAndPagePreserveBookmarksWithoutOpeningOtherContent() async throws {
|
||||
_ = NSApplication.shared
|
||||
let root = try makeTwoBookManuals()
|
||||
let state = directory.appendingPathComponent("State")
|
||||
let store = LibraryContinuityStore(directory: state)
|
||||
let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "removed-section", offset: 0.7)
|
||||
let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Removed section", position: position))
|
||||
store.renameBookmark(mark.id, label: "Keep my reference")
|
||||
let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store)
|
||||
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
|
||||
reader.openBookmark(mark)
|
||||
try await waitFor { reader.error?.contains("Location changed") == true }
|
||||
XCTAssertEqual(reader.webView.url?.lastPathComponent, "chapter.html")
|
||||
let fallbackScroll = try await reader.webView.evaluateJavaScript("window.scrollY") as? Double
|
||||
XCTAssertEqual(fallbackScroll, 0)
|
||||
XCTAssertFalse(reader.bookmarkAvailable(try XCTUnwrap(store.bookmarks.first)))
|
||||
await store.flush()
|
||||
let preserved = try XCTUnwrap(LibraryContinuityStore(directory: state).bookmarks.first)
|
||||
XCTAssertEqual(preserved.id, mark.id)
|
||||
XCTAssertEqual(preserved.position, position)
|
||||
XCTAssertEqual(preserved.displayName, "Keep my reference")
|
||||
XCTAssertEqual(preserved.locationChanged, true)
|
||||
|
||||
reader.showHome()
|
||||
try await waitFor { reader.currentPosition?.relativePath == "index.html" }
|
||||
try FileManager.default.removeItem(at: root.appendingPathComponent("book-one/chapter.html"))
|
||||
reader.openBookmark(preserved)
|
||||
XCTAssertTrue(reader.error?.contains("page is no longer") == true)
|
||||
XCTAssertEqual(reader.currentPosition?.relativePath, "index.html")
|
||||
XCTAssertEqual(store.bookmarks.first?.position, position)
|
||||
XCTAssertEqual(store.bookmarks.count, 1)
|
||||
}
|
||||
|
||||
func testLegacyArchivePageMigratesToPersistentStateIndependentOfAssetCache() async throws {
|
||||
let pdf = PDFDocument()
|
||||
for color in [NSColor.white, .gray] {
|
||||
let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true }
|
||||
pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount)
|
||||
}
|
||||
let bytes = try XCTUnwrap(pdf.dataRepresentation())
|
||||
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
||||
let key = "archive-library.page." + digest
|
||||
let original = UserDefaults.standard.object(forKey: key)
|
||||
defer {
|
||||
if let original { UserDefaults.standard.set(original, forKey: key) }
|
||||
else { UserDefaults.standard.removeObject(forKey: key) }
|
||||
}
|
||||
UserDefaults.standard.set(2, forKey: key)
|
||||
let cached = directory.appendingPathComponent(digest + ".pdf")
|
||||
try bytes.write(to: cached)
|
||||
let state = directory.appendingPathComponent("State")
|
||||
let store = LibraryContinuityStore(directory: state)
|
||||
let reader = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: store)
|
||||
defer { reader.reset() }
|
||||
reader.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
|
||||
let item = ArchiveDocument(id: digest, title: "Migration fixture", collection: "Books",
|
||||
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Migration.pdf")!, memberPath: nil,
|
||||
pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Migration.pdf")!, deliveryBytes: Int64(bytes.count))
|
||||
reader.open(item, page: reader.savedPage(for: digest), resumePosition: true)
|
||||
try await waitFor { reader.progress == nil }
|
||||
XCTAssertNil(reader.error)
|
||||
XCTAssertEqual(reader.page, 2)
|
||||
reader.reset()
|
||||
await store.flush()
|
||||
|
||||
// Clearing an asset cache or moving away from old preferences must not
|
||||
// clear the user's newly migrated reading position.
|
||||
try FileManager.default.removeItem(at: cached)
|
||||
UserDefaults.standard.removeObject(forKey: key)
|
||||
let recreated = LibraryContinuityStore(directory: state)
|
||||
let reopened = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: recreated)
|
||||
defer { reopened.reset() }
|
||||
XCTAssertEqual(reopened.savedPage(for: digest), 2)
|
||||
XCTAssertEqual(recreated.reading(for: "archive:" + digest)?.documentID, digest)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: cached.path))
|
||||
}
|
||||
|
||||
private func makeTwoBookManuals() throws -> URL {
|
||||
let root = directory.appendingPathComponent("Manuals")
|
||||
for book in ["book-one", "book-two"] {
|
||||
let folder = root.appendingPathComponent(book)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
try """
|
||||
<!doctype html><html><head><title>\(book)</title></head><body>
|
||||
<nav class="crumb"><a href="../index.html">Library</a><a href="template.html">\(book)</a></nav>
|
||||
<article><h1>Chapter</h1><section id="alpha" style="height:1400px"><h2>Alpha</h2></section>
|
||||
<section id="beta" style="height:1400px"><h2>Beta</h2></section></article></body></html>
|
||||
""".write(to: folder.appendingPathComponent("chapter.html"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
try "<html><body>Library Home</body></html>".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
|
||||
return root
|
||||
}
|
||||
|
||||
private func waitFor(_ condition: () -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now + .seconds(8)
|
||||
while !condition() {
|
||||
guard ContinuousClock.now < deadline else { XCTFail("Reader did not reach its expected state"); throw CocoaError(.fileReadUnknown) }
|
||||
try await Task.sleep(for: .milliseconds(25))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,11 +156,14 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
do {
|
||||
try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms)
|
||||
let grant = try readGrant(grantFile)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 11)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 12)
|
||||
XCTAssertEqual(grant["playtestVideo"] as? Bool, true)
|
||||
XCTAssertEqual(grant["playtestCallContext"] as? Bool, true)
|
||||
let capabilities = try await result("get_capabilities", grant: grant)
|
||||
XCTAssertTrue((capabilities["tools"] as? [String])?.contains("get_call_context") == true)
|
||||
XCTAssertEqual(capabilities["call_context"] as? Bool, true)
|
||||
XCTAssertEqual(capabilities["banked_debug_manifest_versions"] as? [Int], [1, 2])
|
||||
XCTAssertEqual(capabilities["verified_code_overlays"] as? Bool, true)
|
||||
XCTAssertTrue((capabilities["build_actions"] as? [String])?.contains("disk") == true)
|
||||
XCTAssertTrue((capabilities["configurations"] as? [String])?.contains("Debug") == true)
|
||||
let scope: [String: Any] = ["project_id": try XCTUnwrap(capabilities["project_id"] as? String),
|
||||
@@ -176,6 +179,12 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
XCTAssertEqual(running["run_id"] as? String, run)
|
||||
let snapshot = try await result("get_debug_snapshot", ["run_id": run], grant: grant)
|
||||
let snapshotID = try XCTUnwrap(snapshot["snapshot_id"] as? String)
|
||||
XCTAssertEqual(snapshot["residency_fingerprint"] as? String, "0", "Ordinary flat runs retain their existing identity")
|
||||
let range = try XCTUnwrap((snapshot["memory_ranges"] as? [[String: Int]])?.first)
|
||||
let memoryArguments: [String: Any] = ["run_id": run, "snapshot_id": snapshotID,
|
||||
"address": try XCTUnwrap(range["address"]), "count": min(8, try XCTUnwrap(range["count"]))]
|
||||
let frozenRead = try await result("read_debug_memory", memoryArguments, grant: grant)
|
||||
XCTAssertFalse((frozenRead["bytes"] as? [Int] ?? []).isEmpty)
|
||||
let arguments: [String: Any] = ["run_id": run, "snapshot_id": snapshotID]
|
||||
let context = try await result("get_call_context", arguments, grant: grant)
|
||||
XCTAssertEqual(context["run_id"] as? String, run)
|
||||
@@ -203,6 +212,8 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
let repeated = try await result("get_call_context", arguments, grant: grant)
|
||||
XCTAssertEqual(repeated as NSDictionary, context as NSDictionary,
|
||||
"Repeated context reads preserve clock, registers, mapping and snapshot identity.")
|
||||
let memoryRead = try await result("read_debug_memory", memoryArguments, grant: grant)
|
||||
XCTAssertEqual(memoryRead as NSDictionary, frozenRead as NSDictionary)
|
||||
}
|
||||
for invalid in [arguments.merging(["run_id": "ordinary-shared-run"]) { _, new in new },
|
||||
arguments.merging(["snapshot_id": "stale-snapshot"]) { _, new in new },
|
||||
@@ -213,11 +224,78 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
_ = try await result("playtest_debug", ["run_id": run, "request_id": UUID().uuidString, "action": "step"], grant: grant)
|
||||
let staleAfterStep = try await request("get_call_context", arguments, grant: grant)
|
||||
XCTAssertNotNil(staleAfterStep["error"])
|
||||
let staleMemory = try await request("read_debug_memory", memoryArguments, grant: grant)
|
||||
XCTAssertNotNil(staleMemory["error"])
|
||||
let newer = try await result("get_debug_snapshot", ["run_id": run], grant: grant)
|
||||
let newerArguments: [String: Any] = ["run_id": run, "snapshot_id": try XCTUnwrap(newer["snapshot_id"] as? String)]
|
||||
_ = try await build(scope, grant: grant)
|
||||
let latestArtifact = try await build(scope, grant: grant)
|
||||
let staleAfterBuild = try await request("get_call_context", newerArguments, grant: grant)
|
||||
XCTAssertNotNil(staleAfterBuild["error"])
|
||||
// Exercise the real stdio public schema and authenticated app host,
|
||||
// not a fixture host returning a manufactured MP4 response.
|
||||
let helper = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("vcc-mcp")
|
||||
let clientSource = resources.deletingLastPathComponent().appendingPathComponent("Tools/MCP/test-helper.py")
|
||||
var selection = scope; selection["artifact_id"] = try XCTUnwrap(latestArtifact["artifact_id"] as? String)
|
||||
let selectionJSON = String(decoding: try JSONSerialization.data(withJSONObject: selection), as: UTF8.self)
|
||||
let movie = root.appendingPathComponent("PublicVideo.mp4")
|
||||
let script = """
|
||||
import base64,hashlib,importlib.util,json,pathlib,sys,time,uuid
|
||||
spec=importlib.util.spec_from_file_location('mcp_fixture',sys.argv[1])
|
||||
fixture=importlib.util.module_from_spec(spec);spec.loader.exec_module(fixture)
|
||||
selection=json.loads(sys.argv[4])
|
||||
with fixture.Client(sys.argv[2],sys.argv[3]) as client:
|
||||
client.handshake('2025-06-18')
|
||||
def call(name,**args):
|
||||
result=client.call(name,**args)['result']
|
||||
assert not result.get('isError'), result
|
||||
return result['structuredContent']
|
||||
run=call('start_playtest',**selection,request_id=str(uuid.uuid4()))['run_id']
|
||||
scope={k:selection[k] for k in ('project_id','revision')}
|
||||
deadline=time.monotonic()+60
|
||||
while True:
|
||||
ready=call('get_run',**scope)
|
||||
if ready['status']!='starting':
|
||||
assert ready['status']=='ready', ready
|
||||
break
|
||||
assert time.monotonic()<deadline
|
||||
time.sleep(.025)
|
||||
started=call('start_playtest_video',run_id=run,request_id='begin-public-video',include_audio=False,max_fields=60)
|
||||
advanced=call('playtest_input',run_id=run,request_id='public-video-input',steps=[{'keys':[],'fields':30}])
|
||||
stopped=call('stop_playtest_video',run_id=run,request_id='end-public-video')
|
||||
clip=stopped['video']; assert clip['completed'] and clip['fields_recorded']==30, clip
|
||||
assert stopped['field_clock']==advanced['field_clock']
|
||||
data=bytearray();offset=0
|
||||
while True:
|
||||
page=call('read_playtest_video',run_id=run,clip_id=clip['clip_id'],offset=offset,limit=65536)
|
||||
data.extend(base64.b64decode(page['video_chunk_base64'],validate=True));offset=page['next_offset']
|
||||
if page['eof']:break
|
||||
assert len(data)==clip['byte_count'] and hashlib.sha256(data).hexdigest()==clip['sha256']
|
||||
assert data[4:8]==b'ftyp'
|
||||
pathlib.Path(sys.argv[5]).write_bytes(data)
|
||||
retained=call('stop_playtest',run_id=run,request_id='public-video-cleanup')
|
||||
assert retained['disk_retained']
|
||||
print(json.dumps({'bytes':len(data),'sha256':clip['sha256'],'fields':clip['fields_recorded']}))
|
||||
"""
|
||||
let publicOutput = try await Task.detached {
|
||||
let process = Process(), pipe = Pipe()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
|
||||
process.arguments = ["python3", "-c", script, clientSource.path, helper.path, grantFile.path, selectionJSON, movie.path]
|
||||
process.standardOutput = pipe; process.standardError = pipe
|
||||
let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } }
|
||||
DispatchQueue.global().asyncAfter(deadline: .now() + 90, execute: deadline)
|
||||
defer { deadline.cancel() }
|
||||
try process.run()
|
||||
let output = try pipe.fileHandleForReading.readToEnd() ?? Data()
|
||||
process.waitUntilExit()
|
||||
guard process.terminationStatus == 0 else {
|
||||
throw NSError(domain: "MCPPublicVideo", code: Int(process.terminationStatus),
|
||||
userInfo: [NSLocalizedDescriptionKey: String(decoding: output, as: UTF8.self)])
|
||||
}
|
||||
return output
|
||||
}.value
|
||||
let publicVideo = try XCTUnwrap(JSONSerialization.jsonObject(with: publicOutput) as? [String: Any])
|
||||
XCTAssertEqual(publicVideo["fields"] as? Int, 30)
|
||||
XCTAssertEqual(publicVideo["sha256"] as? String, CMOCProject.sha256(try Data(contentsOf: movie)))
|
||||
await host.revoke().value
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: grantFile.path))
|
||||
// A fresh endpoint lets us check the revoked token itself, rather
|
||||
@@ -292,7 +370,7 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
}.value
|
||||
let observed = try XCTUnwrap(JSONSerialization.jsonObject(with: output) as? [String: Any])
|
||||
let names = try XCTUnwrap(observed["tools"] as? [String])
|
||||
XCTAssertEqual(names.count, 32)
|
||||
XCTAssertEqual(names.count, 35)
|
||||
XCTAssertTrue(names.contains("list_playtest_media")); XCTAssertTrue(names.contains("exchange_playtest_media"))
|
||||
XCTAssertEqual(Set(names), Set(try XCTUnwrap(observed["host_tools"] as? [String])))
|
||||
XCTAssertEqual(observed["media"] as? Bool, true)
|
||||
@@ -391,11 +469,12 @@ final class MCPCallContextAccessTests: XCTestCase {
|
||||
do {
|
||||
try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms)
|
||||
let grant = try readGrant(grantFile)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 11)
|
||||
XCTAssertEqual(grant["toolset"] as? Int, 12)
|
||||
XCTAssertEqual(grant["playtestVideo"] as? Bool, true)
|
||||
XCTAssertEqual(grant["playtestMedia"] as? Bool, true)
|
||||
let capabilities = try await result("get_capabilities", grant: grant)
|
||||
XCTAssertEqual(capabilities["playtest_media_exchange"] as? Bool, true)
|
||||
XCTAssertEqual((capabilities["tools"] as? [String])?.count, 32)
|
||||
XCTAssertEqual((capabilities["tools"] as? [String])?.count, 35)
|
||||
let scope: [String: Any] = ["project_id": try XCTUnwrap(capabilities["project_id"] as? String),
|
||||
"revision": try XCTUnwrap(capabilities["revision"] as? Int)]
|
||||
let artifact = try await build(scope, grant: grant)
|
||||
|
||||
@@ -183,6 +183,7 @@ extension MCPDebuggerInspectionTests {
|
||||
("pc", 0x3101), ("registers", ["PC": 0x3100, "S": 0x7002, "U": 0x7100]),
|
||||
("processor", "HD6309"), ("execution_mode", "native"), ("md_register", 1),
|
||||
("mapping_fingerprint", "mapping-2"), ("program_revision", 2), ("physical_pages", ["3": 57]),
|
||||
("residency_fingerprint", "changed-owner"),
|
||||
("logical_memory", Data(repeating: 1, count: 65536).base64EncodedString()),
|
||||
("available", Data(repeating: 0, count: 65536).base64EncodedString())] {
|
||||
var changed = base; changed[key] = value
|
||||
|
||||
@@ -1,8 +1,225 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import AVFoundation
|
||||
import Darwin
|
||||
|
||||
@MainActor
|
||||
final class MCPPlaytestTests: XCTestCase {
|
||||
func testMissingOrChangedVideoDoesNotPreventGuestDiskRetention() async throws {
|
||||
let (helper, system, diskROM) = try inputs()
|
||||
for mediaEnabled in [false, true] {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoDiskSafety-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let original = disk(), artifact = UUID().uuidString
|
||||
let baseHash = CMOCProject.sha256(original)
|
||||
let provenance = MCPPlaytestDiskStore.Provenance(projectKey: CMOCProject.sha256(Data("video-disk-safety".utf8)),
|
||||
artifactID: artifact, artifactDiskSHA256: baseHash, mediaKey: mediaEnabled ? "primary" : nil,
|
||||
mediaBaseSHA256: mediaEnabled ? baseHash : nil)
|
||||
let media: [MCPPlaytestMedium]? = mediaEnabled ? [MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact, key: "primary"),
|
||||
name: "HOME.dsk", key: "primary", baseSHA256: baseHash, data: original, provenance: provenance)] : nil
|
||||
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
|
||||
bootCommands: "10 PRINT 37\nSAVE\"TEST\"\n", projectID: "video-disk-safety", revision: 1,
|
||||
artifactID: artifact, helperURL: helper, retentionDirectory: root, diskProvenance: provenance, media: media,
|
||||
videoArtifactWillVerify: { clip in
|
||||
// Fail exactly at first host registration, after the real
|
||||
// worker finalized its MP4 and before the host reads it.
|
||||
if mediaEnabled { try Data([0,1,2,3]).write(to: clip, options: .atomic) }
|
||||
else { try FileManager.default.removeItem(at: clip) }
|
||||
})
|
||||
defer { test.invalidate() }
|
||||
let savedHash = try XCTUnwrap(test.startReceipt["disk_sha256"] as? String)
|
||||
XCTAssertNotEqual(savedHash, CMOCProject.sha256(original), "An ordinary guest SAVE must change the retained disk")
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin", "include_audio": false, "max_fields": 120])
|
||||
let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "fields", "steps": [["keys": [], "fields": 3]]])
|
||||
let video = try XCTUnwrap(input["video_recording"] as? [String: Any])
|
||||
let id = try XCTUnwrap(video["clip_id"] as? String)
|
||||
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
||||
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
||||
XCTAssertNotNil(stopped["video_retention_error"], "A separate artifact failure must remain visible")
|
||||
let retained = try XCTUnwrap(test.retainedDiskURL)
|
||||
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: retained)), savedHash)
|
||||
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) }
|
||||
}
|
||||
}
|
||||
private func videoBytes(_ test: MCPPlaytest, metadata: [String: Any]) async throws -> Data {
|
||||
let id = try XCTUnwrap(metadata["clip_id"] as? String)
|
||||
let size = try XCTUnwrap(metadata["byte_count"] as? Int)
|
||||
XCTAssertGreaterThan(size, 0); XCTAssertLessThanOrEqual(size, 64 * 1024 * 1024)
|
||||
var data = Data(), offset = 0
|
||||
while offset < size {
|
||||
let arguments: [String: Any] = ["run_id": test.runID, "clip_id": id, "offset": offset, "limit": 4096]
|
||||
let chunk = try await test.reply("read_playtest_video", arguments: arguments)
|
||||
XCTAssertEqual(chunk["clip_id"] as? String, id)
|
||||
XCTAssertEqual(chunk["offset"] as? Int, offset)
|
||||
XCTAssertEqual(chunk["byte_count"] as? Int, size)
|
||||
XCTAssertEqual(chunk["mime_type"] as? String, "video/mp4")
|
||||
XCTAssertEqual(chunk["sha256"] as? String, metadata["sha256"] as? String)
|
||||
let bytes = try XCTUnwrap((chunk["video_chunk_base64"] as? String).flatMap { Data(base64Encoded: $0) })
|
||||
XCTAssertFalse(bytes.isEmpty); XCTAssertLessThanOrEqual(bytes.count, 4096)
|
||||
guard !bytes.isEmpty else { throw ProfileFailure.message("Empty video chunk before EOF") }
|
||||
data.append(bytes); offset += bytes.count
|
||||
XCTAssertEqual(chunk["next_offset"] as? Int, offset)
|
||||
XCTAssertEqual(chunk["eof"] as? Bool, offset == size)
|
||||
let retry = try await test.reply("read_playtest_video", arguments: arguments)
|
||||
XCTAssertEqual(retry["video_chunk_base64"] as? String, chunk["video_chunk_base64"] as? String)
|
||||
}
|
||||
XCTAssertEqual(data.count, size); XCTAssertEqual(CMOCProject.sha256(data), metadata["sha256"] as? String)
|
||||
let eof = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id, "offset": size])
|
||||
XCTAssertEqual(eof["eof"] as? Bool, true); XCTAssertEqual(eof["video_chunk_base64"] as? String, "")
|
||||
return data
|
||||
}
|
||||
|
||||
private func decodedVideoAudio(_ url: URL) async throws -> (Float, Float, Int) {
|
||||
let asset = AVURLAsset(url: url)
|
||||
let tracks = try await asset.loadTracks(withMediaType: .audio)
|
||||
let track = try XCTUnwrap(tracks.first)
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
|
||||
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
|
||||
reader.add(output); XCTAssertTrue(reader.startReading())
|
||||
var minimum: Float = 1, maximum: Float = -1, count = 0
|
||||
while let sample = output.copyNextSampleBuffer() {
|
||||
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
|
||||
var data = Data(count: CMBlockBufferGetDataLength(buffer))
|
||||
XCTAssertEqual(data.withUnsafeMutableBytes {
|
||||
CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!)
|
||||
}, noErr)
|
||||
data.withUnsafeBytes { raw in
|
||||
for value in raw.bindMemory(to: Float.self) { minimum = min(minimum, value); maximum = max(maximum, value); count += 1 }
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0)
|
||||
return (minimum, maximum, count)
|
||||
}
|
||||
|
||||
func testOwnedVideoRecordsActualFieldsAudioChoiceAndRetryIdentityOnBothProcessors() async throws {
|
||||
let (helper, system, diskROM) = try inputs()
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedVideo-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: folder) }
|
||||
for cpu in ["6809", "6309"] {
|
||||
let root = folder.appendingPathComponent(cpu)
|
||||
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
|
||||
bootCommands: "10 CLS 3:PRINT \"VIDEO\"\n20 SOUND 80,255:GOTO20\nRUN\n",
|
||||
projectID: "video-fixture", revision: 1, artifactID: UUID().uuidString, cpu: cpu,
|
||||
helperURL: helper, retentionDirectory: root)
|
||||
do {
|
||||
let before = try await test.capture()
|
||||
for value: Any in [0, 3601, true, 1.5] {
|
||||
await expectDiskFailure {
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid", "max_fields": value])
|
||||
}
|
||||
}
|
||||
for value: Any in [1, "yes"] {
|
||||
await expectDiskFailure {
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid-audio", "include_audio": value])
|
||||
}
|
||||
}
|
||||
await expectDiskFailure { _ = try await test.reply("start_playtest_video", arguments: ["run_id": "foreign", "request_id": "foreign"]) }
|
||||
let afterInvalid = try await test.capture()
|
||||
XCTAssertEqual(afterInvalid["field_clock"] as? Int, before["field_clock"] as? Int)
|
||||
|
||||
for includeAudio in [true, false] {
|
||||
let key = includeAudio ? "audio" : "silent"
|
||||
let starting = try await test.capture()
|
||||
let startArgs: [String: Any] = ["run_id": test.runID, "request_id": "begin-" + key,
|
||||
"include_audio": includeAudio, "max_fields": 120]
|
||||
let started = try await test.reply("start_playtest_video", arguments: startArgs)
|
||||
XCTAssertEqual(started["field_clock"] as? Int, starting["field_clock"] as? Int, "Starting video must not execute the guest")
|
||||
let startRetry = try await test.reply("start_playtest_video", arguments: startArgs)
|
||||
XCTAssertEqual(startRetry as NSDictionary, started as NSDictionary)
|
||||
await expectDiskFailure {
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-" + key, "include_audio": !includeAudio, "max_fields": 120])
|
||||
}
|
||||
await expectDiskFailure {
|
||||
_ = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart-" + key])
|
||||
}
|
||||
let inputArgs: [String: Any] = ["run_id": test.runID, "request_id": "fields-" + key,
|
||||
"steps": [["keys": ["space"], "fields": 30], ["keys": [], "fields": 30]]]
|
||||
let input = try await test.reply("playtest_input", arguments: inputArgs)
|
||||
assertProcessor(input, cpu: cpu)
|
||||
let trace = try XCTUnwrap(input["input_trace"] as? [[String: Any]])
|
||||
XCTAssertEqual(trace.count, 2); XCTAssertEqual(trace[0]["fields_advanced"] as? Int, 30)
|
||||
XCTAssertEqual((trace[0]["input"] as? [String: Any])?["neutral"] as? Bool, false)
|
||||
XCTAssertEqual((trace[1]["input"] as? [String: Any])?["neutral"] as? Bool, true)
|
||||
let inputRetry = try await test.reply("playtest_input", arguments: inputArgs)
|
||||
XCTAssertEqual(inputRetry["field_clock"] as? Int, input["field_clock"] as? Int)
|
||||
let stopArgs: [String: Any] = ["run_id": test.runID, "request_id": "end-" + key]
|
||||
let stopped = try await test.reply("stop_playtest_video", arguments: stopArgs)
|
||||
let stopRetry = try await test.reply("stop_playtest_video", arguments: stopArgs)
|
||||
XCTAssertEqual(stopRetry as NSDictionary, stopped as NSDictionary)
|
||||
XCTAssertEqual(stopped["field_clock"] as? Int, input["field_clock"] as? Int, "Stopping video must not execute the guest")
|
||||
let video = try XCTUnwrap(stopped["video"] as? [String: Any])
|
||||
XCTAssertEqual(video["include_audio"] as? Bool, includeAudio)
|
||||
XCTAssertEqual(video["fields_recorded"] as? Int, 60)
|
||||
XCTAssertEqual(video["truncated"] as? Bool, false)
|
||||
XCTAssertEqual((video["field_end"] as? Int ?? -1) - (video["field_start"] as? Int ?? -1), 60)
|
||||
let movie = root.appendingPathComponent(key + ".mp4")
|
||||
try await videoBytes(test, metadata: video).write(to: movie)
|
||||
let asset = AVURLAsset(url: movie)
|
||||
let duration = try await asset.load(.duration).seconds
|
||||
XCTAssertEqual(duration, 1, accuracy: 0.05)
|
||||
let tracks = try await asset.loadTracks(withMediaType: .video)
|
||||
XCTAssertEqual(tracks.count, 1)
|
||||
let dimensions = try await XCTUnwrap(tracks.first).load(.naturalSize)
|
||||
XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960))
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
let frame = try await generator.image(at: .zero).image
|
||||
XCTAssertEqual(frame.width, 1280); XCTAssertEqual(frame.height, 960)
|
||||
let samples = try await decodedVideoAudio(movie)
|
||||
if includeAudio { XCTAssertGreaterThan(samples.1 - samples.0, 0.01, "A real guest SOUND program must reach the delivered MP4") }
|
||||
else { XCTAssertLessThan(max(abs(samples.0), abs(samples.1)), 0.00001, "Silent video must exclude guest audio and all UI cues") }
|
||||
if !includeAudio {
|
||||
let id = try XCTUnwrap(video["clip_id"] as? String)
|
||||
let retained = root.appendingPathComponent("Videos/\(test.runID)/\(id)/Clip.mp4")
|
||||
try FileManager.default.removeItem(at: retained)
|
||||
XCTAssertEqual(mkfifo(retained.path, 0o600), 0)
|
||||
let began = ContinuousClock.now
|
||||
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) }
|
||||
XCTAssertLessThan(began.duration(to: .now), .seconds(2), "A replaced FIFO must not block the ownership lease before validation")
|
||||
}
|
||||
let clipID = try XCTUnwrap(video["clip_id"] as? String)
|
||||
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": clipID, "offset": -1]) }
|
||||
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": UUID().uuidString]) }
|
||||
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": "foreign", "clip_id": clipID]) }
|
||||
}
|
||||
let retained = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain"])
|
||||
XCTAssertEqual(retained["disk_retained"] as? Bool, true)
|
||||
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk())
|
||||
} catch { await test.invalidate().value; throw error }
|
||||
await test.invalidate().value
|
||||
}
|
||||
}
|
||||
|
||||
func testVideoFieldBoundAndRunStopRetainCompletedClipsWithoutMoreExecution() async throws {
|
||||
let (helper, system, diskROM) = try inputs()
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoBounds-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
|
||||
bootCommands: "10 CLS:PRINT \"BOUNDED VIDEO\"\n20 GOTO20\nRUN\n", projectID: "video-bound", revision: 1,
|
||||
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: root)
|
||||
do {
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-limit", "max_fields": 2])
|
||||
let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cross-limit", "steps": [["keys": [], "fields": 5]]])
|
||||
let limited = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "end-limit"])
|
||||
let video = try XCTUnwrap(limited["video"] as? [String: Any])
|
||||
XCTAssertEqual(video["fields_recorded"] as? Int, 2); XCTAssertEqual(video["truncated"] as? Bool, true)
|
||||
XCTAssertEqual(video["reason"] as? String, "field_limit"); XCTAssertEqual(video["completed"] as? Bool, true)
|
||||
XCTAssertEqual(limited["field_clock"] as? Int, input["field_clock"] as? Int)
|
||||
_ = try await videoBytes(test, metadata: video)
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-cleanup", "include_audio": false])
|
||||
let last = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cleanup-fields", "steps": [["keys": [], "fields": 3]]])
|
||||
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain-with-video"])
|
||||
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
||||
XCTAssertEqual(stopped["field_clock"] as? Int, last["field_clock"] as? Int)
|
||||
let finalVideo = try XCTUnwrap(stopped["video"] as? [String: Any])
|
||||
XCTAssertEqual(finalVideo["fields_recorded"] as? Int, 3)
|
||||
XCTAssertEqual(finalVideo["reason"] as? String, "run_stopped"); XCTAssertEqual(finalVideo["truncated"] as? Bool, false)
|
||||
_ = try await videoBytes(test, metadata: finalVideo)
|
||||
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk())
|
||||
} catch { await test.invalidate().value; throw error }
|
||||
await test.invalidate().value
|
||||
}
|
||||
|
||||
func testPhysicalKeysCoverGameplayWithoutHostLayoutOrArbitraryText() {
|
||||
XCTAssertEqual(MCPPlaytest.chord("left"), UInt64(1) << 29)
|
||||
XCTAssertEqual(MCPPlaytest.chord("right"), UInt64(1) << 30)
|
||||
@@ -551,7 +768,11 @@ final class MCPPlaytestTests: XCTestCase {
|
||||
projectID: "request-limit-fixture", revision: 1, artifactID: UUID().uuidString,
|
||||
helperURL: helper, retentionDirectory: folder)
|
||||
defer { test.invalidate() }
|
||||
for index in 0..<MCPPlaytest.mutationRequestLimit {
|
||||
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "video-before-limit", "include_audio": false])
|
||||
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "video-fields", "steps": [["keys": [], "fields": 2]]])
|
||||
let budget = try await test.capture()
|
||||
let remaining = try XCTUnwrap(budget["remaining_mutation_requests"] as? Int)
|
||||
for index in 0..<remaining {
|
||||
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause-\(index)", "action": "pause"])
|
||||
}
|
||||
let before = try await test.capture()
|
||||
@@ -560,6 +781,18 @@ final class MCPPlaytestTests: XCTestCase {
|
||||
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "exhausted", "action": "step"])
|
||||
XCTFail("Exhausted execution ledger accepted another mutation")
|
||||
} catch { XCTAssertTrue(error.localizedDescription.contains("playtest_request_limit")) }
|
||||
let finishedVideo = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "finish-video-after-limit"])
|
||||
let clip = try XCTUnwrap(finishedVideo["video"] as? [String: Any])
|
||||
XCTAssertEqual(clip["fields_recorded"] as? Int, 2)
|
||||
_ = try await videoBytes(test, metadata: clip)
|
||||
for index in 0..<32 {
|
||||
do {
|
||||
_ = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "extra-video-stop-\(index)"])
|
||||
XCTFail("A cleanup exemption must not retain unlimited distinct stop receipts")
|
||||
} catch { XCTAssertTrue(error.localizedDescription.contains("request_conflict")) }
|
||||
}
|
||||
let sameVideoStop = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "finish-video-after-limit"])
|
||||
XCTAssertEqual(sameVideoStop as NSDictionary, finishedVideo as NSDictionary)
|
||||
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
||||
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
||||
XCTAssertEqual(stopped["stop_retention_exempt"] as? Bool, true)
|
||||
@@ -886,6 +1119,198 @@ final class MCPPlaytestTests: XCTestCase {
|
||||
if let disk = test.retainedDiskURL { try FileManager.default.removeItem(at:disk.deletingLastPathComponent()) }
|
||||
}
|
||||
|
||||
private enum PhysicalOverlayLoad { case complete, partial, corrupted }
|
||||
|
||||
/// Authored LOADM guest: real 6809 instructions copy two immutable code
|
||||
/// pieces into the same physical RAM. The ROM pair still comes from the
|
||||
/// selected build resources through inputs(); these bytes are not firmware.
|
||||
private func physicalOverlayFixture(_ mode: PhysicalOverlayLoad) throws -> (disk: Data, modules: [[String: Any]], a: Data, b: Data) {
|
||||
let a = Data([0x12, 0x86, 0x11, 0xb7, 0x50, 0x00, 0x7e, 0x11, 0x00])
|
||||
let b = mode == .complete
|
||||
? Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x7e, 0x12, 0x00])
|
||||
: Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x20, 0xf8])
|
||||
let witnessA = Data([0x12, 0x86, 0xa1, 0x39]), witnessB = Data([0x12, 0x86, 0xb2, 0x39])
|
||||
func raw(_ code: Data, _ witness: Data) -> Data {
|
||||
code + Data(repeating: 0x12, count: 0x20 - code.count) + witness
|
||||
}
|
||||
let rawA = raw(a, witnessA), rawB = raw(b, witnessB)
|
||||
func loader(_ source: UInt16, count: Int, corruptWitness: Bool = false) -> Data {
|
||||
// LDX #$4000; LDY #source; LDB #count;
|
||||
// copy: LDA ,Y+; STA ,X+; DECB; BNE copy.
|
||||
var code = Data([0x8e, 0x40, 0, 0x10, 0x8e, UInt8(source >> 8), UInt8(source & 255),
|
||||
0xc6, UInt8(count), 0xa6, 0xa0, 0xa7, 0x80, 0x5a, 0x26, 0xf9])
|
||||
if corruptWitness { code.append(contentsOf: [0x86, 0xc3, 0xb7, 0x40, 0x22]) } // Guest LDA/STA.
|
||||
code.append(contentsOf: [0x7e, 0x40, 0])
|
||||
return code
|
||||
}
|
||||
let loadA = loader(0x2000, count: rawA.count)
|
||||
let loadB = loader(0x2100, count: mode == .partial ? b.count : rawB.count, corruptWitness: mode == .corrupted)
|
||||
let blocks: [(UInt16, Data)] = [(0x1000, loadA), (0x1100, loadB), (0x1200, loadA), (0x2000, rawA), (0x2100, rawB)]
|
||||
var binary = Data()
|
||||
for (address, bytes) in blocks {
|
||||
binary.append(contentsOf: [0, UInt8(bytes.count >> 8), UInt8(bytes.count & 255), UInt8(address >> 8), UInt8(address & 255)])
|
||||
binary.append(bytes)
|
||||
}
|
||||
binary.append(contentsOf: [255, 0, 0, 0x10, 0])
|
||||
guard binary.count < 256 else { throw ProfileFailure.message("The authored overlay fixture must fit one DECB sector.") }
|
||||
var image = disk()
|
||||
image.replaceSubrange(0..<binary.count, with: binary)
|
||||
image[(17 * 18 + 1) * 256] = 0xc1
|
||||
var entry = Data(repeating: 0, count: 32)
|
||||
entry.replaceSubrange(0..<11, with: Data("PROBE BIN".utf8))
|
||||
entry[11] = 2; entry[15] = UInt8(binary.count)
|
||||
let directory = (17 * 18 + 2) * 256
|
||||
image.replaceSubrange(directory..<(directory + 32), with: entry)
|
||||
func guardBytes(_ address: Int, _ bytes: Data) -> [String: Any] {
|
||||
["address": address, "bytes_base64": bytes.base64EncodedString()]
|
||||
}
|
||||
func piece(_ id: String, owner: String, address: Int, bytes: Data) -> [String: Any] {
|
||||
["id": id, "overlay_group": "stage-code", "overlay_owner": owner,
|
||||
"pages": [["logical_page": 2, "physical_page": 58]], "guards": [guardBytes(address, bytes)]]
|
||||
}
|
||||
let modules = [
|
||||
piece("a-entry", owner: "A", address: 0x4000, bytes: a),
|
||||
piece("a-witness", owner: "A", address: 0x4020, bytes: witnessA),
|
||||
piece("b-entry", owner: "B", address: 0x4000, bytes: b),
|
||||
piece("b-witness", owner: "B", address: 0x4020, bytes: witnessB),
|
||||
["id": "loader", "pages": [["logical_page": 0, "physical_page": 56]],
|
||||
"guards": [guardBytes(0x1000, loadA), guardBytes(0x1100, loadB), guardBytes(0x1200, loadA)]]
|
||||
]
|
||||
return (image, modules, a, b)
|
||||
}
|
||||
|
||||
func testPhysicalCodeOverlayWorkerFollowsActualGuestCopiesAndRetainsDiskOnBothProcessors() async throws {
|
||||
let (helper, system, diskROM) = try inputs()
|
||||
let fixture = try physicalOverlayFixture(.complete)
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlay-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
for cpu in ["6809", "6309"] {
|
||||
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk,
|
||||
// Buffer disk operations in one BASIC command before SAVE runs,
|
||||
// so subsequent pasted characters cannot arrive during disk I/O.
|
||||
bootCommands: "10 PRINT 7\nSAVE\"MARKER\":LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-worker",
|
||||
revision: 1, artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000,
|
||||
stopModule: "a-entry", cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu))
|
||||
defer { test.invalidate() }
|
||||
if test.startReceipt["state"] as? String != "paused" {
|
||||
let screen = try await test.capture()
|
||||
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "failed-start-cleanup"])
|
||||
XCTFail("Overlay guest did not reach A: \(screen["screen_text"] ?? "no screen text"); PC \(screen["pc"] ?? "unknown")")
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(test.startReceipt["ram_kb"] as? Int, 512)
|
||||
assertProcessor(test.startReceipt, cpu: cpu)
|
||||
XCTAssertNotEqual(test.startReceipt["disk_sha256"] as? String, CMOCProject.sha256(fixture.disk), "SAVE must actually modify the disposable guest disk")
|
||||
func captured(_ expected: Data, witness: UInt8) async throws -> [String: Any] {
|
||||
let capture = try await test.debugCapture()
|
||||
assertProcessor(capture, cpu: cpu)
|
||||
XCTAssertEqual(capture["pc"] as? Int, 0x4000)
|
||||
XCTAssertEqual(capture["attached"] as? Bool, true)
|
||||
XCTAssertEqual((capture["physical_pages"] as? [String: Int])?["2"], 58)
|
||||
let memory = try XCTUnwrap((capture["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
||||
XCTAssertEqual(Data(memory[0x4000..<(0x4000 + expected.count)]), expected)
|
||||
XCTAssertEqual(memory[0x4022], witness)
|
||||
XCTAssertNotEqual(capture["residency_fingerprint"] as? String, "0")
|
||||
return capture
|
||||
}
|
||||
let first = try await captured(fixture.a, witness: 0xa1)
|
||||
let firstResidency = try XCTUnwrap(first["residency_fingerprint"] as? String)
|
||||
func stop(_ module: String, request: String) async throws {
|
||||
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": request,
|
||||
"action": "stop_at", "address": 0x4000, "module_id": module, "selection": "function_entry:" + module])
|
||||
let receipt = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": request + "-advance",
|
||||
"steps": [["keys": [], "fields": 2]]])
|
||||
XCTAssertEqual(receipt["state"] as? String, "paused")
|
||||
}
|
||||
// The entry opcode, logical address and physical page are identical.
|
||||
// Asking for B must run past A and let the guest loader install B.
|
||||
try await stop("b-entry", request: "owner-b")
|
||||
let second = try await captured(fixture.b, witness: 0xb2)
|
||||
XCTAssertNotEqual(second["residency_fingerprint"] as? String, firstResidency)
|
||||
XCTAssertEqual(second["mapping_fingerprint"] as? String, first["mapping_fingerprint"] as? String)
|
||||
XCTAssertEqual(second["program_revision"] as? Int, first["program_revision"] as? Int)
|
||||
let secondMemory = try XCTUnwrap((second["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
||||
XCTAssertEqual(secondMemory[0x5000], 0x11, "A executed its own guest STA before loading B")
|
||||
try await stop("a-entry", request: "owner-a-again")
|
||||
let third = try await captured(fixture.a, witness: 0xa1)
|
||||
XCTAssertEqual(third["residency_fingerprint"] as? String, firstResidency)
|
||||
let thirdMemory = try XCTUnwrap((third["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
||||
XCTAssertEqual(thirdMemory[0x5000], 0x22, "B executed its own guest STA before restoring A")
|
||||
let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart"])
|
||||
XCTAssertEqual(restarted["boot"] as? Int, 2)
|
||||
XCTAssertEqual(restarted["disk_sha256"] as? String, test.startReceipt["disk_sha256"] as? String)
|
||||
XCTAssertEqual(restarted["disk_original_sha256"] as? String, CMOCProject.sha256(fixture.disk))
|
||||
_ = try await captured(fixture.a, witness: 0xa1)
|
||||
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
||||
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
|
||||
let saved = try XCTUnwrap(test.retainedDiskURL)
|
||||
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: saved)), restarted["disk_sha256"] as? String)
|
||||
}
|
||||
}
|
||||
|
||||
func testPhysicalCodeOverlayWorkerRejectsPartialAndCorruptedOwnerWitnessesOnBothProcessors() async throws {
|
||||
let (helper, system, diskROM) = try inputs()
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlayPartial-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
for cpu in ["6809", "6309"] {
|
||||
for (name, mode, witness) in [("partial", PhysicalOverlayLoad.partial, UInt8(0xa1)), ("corrupted", .corrupted, UInt8(0xc3))] {
|
||||
let fixture = try physicalOverlayFixture(mode)
|
||||
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk,
|
||||
bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-invalid-worker", revision: 1,
|
||||
artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000, stopModule: "a-entry",
|
||||
cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu + "-" + name))
|
||||
defer { test.invalidate() }
|
||||
let valid = try await test.debugCapture()
|
||||
XCTAssertEqual(valid["attached"] as? Bool, true)
|
||||
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "want-b",
|
||||
"action": "stop_at", "address": 0x4000, "module_id": "b-entry", "selection": "function_entry:b-entry"])
|
||||
let advanced = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "load-invalid",
|
||||
"steps": [["keys": [], "fields": 2]]])
|
||||
XCTAssertEqual(advanced["state"] as? String, "running", "An invalid owner must not qualify B's stop")
|
||||
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause", "action": "pause"])
|
||||
let invalid = try await test.debugCapture()
|
||||
assertProcessor(invalid, cpu: cpu)
|
||||
XCTAssertEqual(invalid["attached"] as? Bool, false)
|
||||
XCTAssertEqual(invalid["mapping_fingerprint"] as? String, valid["mapping_fingerprint"] as? String)
|
||||
XCTAssertNotEqual(invalid["residency_fingerprint"] as? String, valid["residency_fingerprint"] as? String)
|
||||
let pc = try XCTUnwrap(invalid["pc"] as? Int)
|
||||
XCTAssertTrue((0x4000..<0x4008).contains(pc), "Pause observes the actual guest loop, not a manufactured PC")
|
||||
let memory = try XCTUnwrap((invalid["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
|
||||
XCTAssertEqual(Data(memory[0x4000..<(0x4000 + fixture.b.count)]), fixture.b, "B's entry alone is insufficient proof")
|
||||
XCTAssertEqual(memory[0x4022], witness, "The guest partial copy/corruption must remain visible in the full capture")
|
||||
XCTAssertEqual(memory[0x5000], 0x22)
|
||||
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPhysicalOverlayWireRejectsEmbeddedNULIdentityBeforeGuestExecution() async throws {
|
||||
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
|
||||
let helper = ProcessInfo.processInfo.environment["VCC_TEST_PLAYTEST_HELPER"].map { URL(fileURLWithPath: $0) }
|
||||
?? products.appendingPathComponent("vcc-playtest")
|
||||
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: helper.path), "Requires the built, isolated vcc-playtest helper.")
|
||||
let fixture = try physicalOverlayFixture(.complete)
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOverlayWire-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
for field in ["overlay_group", "overlay_owner"] {
|
||||
var modules = fixture.modules
|
||||
modules[0][field] = "a\0alias"
|
||||
do {
|
||||
// These deliberately unusable ROM bytes must never execute.
|
||||
// This is a wire validation check, not a firmware/CPU pass.
|
||||
let run = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768),
|
||||
diskROM: Data(repeating: 0, count: 8192), disk: fixture.disk, bootCommands: "\n",
|
||||
projectID: "overlay-wire-invalid", revision: 1, artifactID: UUID().uuidString,
|
||||
modules: modules, stopAt: 0x4000, stopModule: "a-entry", cpu: "6809", helperURL: helper,
|
||||
retentionDirectory: root.appendingPathComponent(field))
|
||||
await run.invalidate().value
|
||||
XCTFail("An embedded NUL in \(field) crossed the worker boundary")
|
||||
} catch {
|
||||
XCTAssertTrue(error.localizedDescription.contains("invalid_overlay_identity"), error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFlatOwnedStopUsesVerifiedBytesAndActualRuntimeMapping() async throws {
|
||||
let (helper, system, diskROM) = try inputs()
|
||||
// Guest instructions assign42 to a global, then loop at a verified stop.
|
||||
|
||||
@@ -93,6 +93,68 @@ final class SoftwareLibraryBrowseTests: XCTestCase {
|
||||
XCTAssertEqual(LibraryBrowseQuery.type(of: cartridge, related: [disk, music]), "Other", "Conflicting editions do not establish a type")
|
||||
XCTAssertEqual(LibraryBrowseQuery.type(of: release("demo", category: "Disks/Games/Sierra Games/Demos")), "Games")
|
||||
}
|
||||
|
||||
func testUnifiedPersonalGamesAreFirstAndAvailableToLocalDiskCompanion() {
|
||||
var entry = PersonalSoftwareEntry(id: UUID(), title: "Private Game", files: [
|
||||
.init(path: "PRIVATE.DSK", kind: "disk", byteSize: 4, sha256: String(repeating: "a", count: 64))
|
||||
])
|
||||
entry.category = "Games"
|
||||
let privateRelease = entry.release(in: directory)
|
||||
let privateTitle = SoftwareLibraryTitle(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [privateRelease])
|
||||
let publicGame = title("public-game", name: "Public Game", [release("public-edition", category: "Disks/Games")])
|
||||
let titles = [privateTitle, publicGame]
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .all, softwareType: "Games").apply(to: titles, favorites: [entry.titleID], installed: [entry.releaseID]).map(\.id), [entry.titleID, publicGame.id])
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .all, category: "Games").apply(to: [privateTitle], favorites: [], installed: []).count, 1)
|
||||
for scope in [LibraryBrowseQuery.Scope.started, .showcase, .installed] {
|
||||
XCTAssertTrue(LibraryBrowseQuery(scope: scope).apply(to: [privateTitle], favorites: [entry.titleID], installed: [entry.releaseID]).isEmpty)
|
||||
}
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .personal).apply(to: titles, favorites: [], installed: []).map(\.id), [entry.titleID])
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .favorites).apply(to: titles, favorites: [entry.titleID], installed: []).map(\.id), [entry.titleID])
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .search, text: "Private Game").apply(to: titles, favorites: [], installed: []).map(\.id), [entry.titleID])
|
||||
let companion = SoftwareLibraryCatalog(titles: titles, metadata: [:]).companionDisksOnly
|
||||
XCTAssertEqual(companion.titles.map(\.id), [privateTitle.id, publicGame.id], "The user's local companion can browse their own disks")
|
||||
}
|
||||
func testPersonalGroupIsAlphabeticalBeforeCatalogWithoutMergingSameNames() {
|
||||
func personal(_ name: String, bytes: Int64) -> SoftwareLibraryTitle {
|
||||
var entry = PersonalSoftwareEntry(id: UUID(), title: name, files: [.init(path: "GAME.dsk", kind: "disk", byteSize: bytes, sha256: String(repeating: "a", count: 64))])
|
||||
entry.category = "Games"
|
||||
return .init(id: entry.titleID, name: name, identityStatus: "personal", releases: [entry.release(in: directory)])
|
||||
}
|
||||
let privateA = personal("A Game", bytes: 10000), privateZ = personal("Z Game", bytes: 1)
|
||||
let publicA = title("public-a", name: "A Game", [release("a", bytes: 10)])
|
||||
let publicB = title("public-b", name: "B Game", [release("b", bytes: 50)])
|
||||
for sort in LibraryBrowseQuery.Sort.allCases {
|
||||
let rows = LibraryBrowseQuery(scope: .all, softwareType: "Games", sort: sort).apply(to: [publicA, privateZ, publicB, privateA], favorites: [], installed: [])
|
||||
XCTAssertEqual(Array(rows.prefix(2)).map(\.id), [privateA.id, privateZ.id])
|
||||
XCTAssertTrue(rows[0].isPersonal); XCTAssertFalse(rows[2].isPersonal)
|
||||
XCTAssertEqual(rows.count, 4, "Personal and catalog editions with the same name stay distinct")
|
||||
XCTAssertEqual(Array(rows.suffix(2)).map(\.id), sort == .size ? [publicB.id, publicA.id] : [publicA.id, publicB.id])
|
||||
}
|
||||
XCTAssertTrue(LibraryBrowseQuery(scope: .all, softwareType: "Music").apply(to: [privateA], favorites: [], installed: []).isEmpty)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testHeaderSearchEscapesEveryPriorScopeAndFacetsAndResumes() async throws {
|
||||
let support = directory.appendingPathComponent("GlobalSearch")
|
||||
let continuity = LibraryContinuityStore(directory: support)
|
||||
let model = SoftwareLibraryModel(state: .init(directory: support), continuity: continuity)
|
||||
model.restoreBrowseContext()
|
||||
for scope in LibraryBrowseQuery.Scope.allCases where scope != .search {
|
||||
model.query = .init(scope: scope, category: "Disks", softwareType: "Music", media: "cassette", evidence: "checked", sort: .modified)
|
||||
model.setSearchText("Popstar")
|
||||
XCTAssertEqual(model.query, .init(scope: .search, text: "Popstar", sort: .modified))
|
||||
}
|
||||
model.query.media = "disk"; model.setSearchText("Popstar Game")
|
||||
XCTAssertEqual(model.query.media, "disk", "Explicit filters within Search Results survive further typing")
|
||||
model.saveBrowseContext(); await continuity.flush()
|
||||
let resumed = SoftwareLibraryModel(state: .init(directory: support), continuity: LibraryContinuityStore(directory: support))
|
||||
await resumed.load(from: try database()); try await settle(resumed)
|
||||
XCTAssertEqual(resumed.query.scope, .search); XCTAssertEqual(resumed.query.text, "Popstar Game")
|
||||
XCTAssertEqual(resumed.query.media, "disk")
|
||||
model.setSearchText("")
|
||||
XCTAssertEqual(model.query.scope, .all); XCTAssertEqual(model.query.text, "")
|
||||
await model.shutdown(); await resumed.shutdown()
|
||||
}
|
||||
func testAdvancedFacetsMatchTheSameEditionAndKeepUnknownEvidenceHonest() {
|
||||
let disk = release("disk", environment: "os9", processor: "6309", hardware: ["speech-sound": "optional"], videoModes: ["SG-12"])
|
||||
let tape = release("tape", media: "cassette", environment: "basic", processor: "either", hardware: ["joystick": "unspecified"], videoModes: ["6847T1"])
|
||||
@@ -221,6 +283,87 @@ final class SoftwareLibraryBrowseTests: XCTestCase {
|
||||
await state.flush()
|
||||
}
|
||||
@MainActor
|
||||
func testColdResumeRetainsSelectionWhileCatalogRecoveryIsDelayed() async throws {
|
||||
let support = directory.appendingPathComponent("DelayedResume")
|
||||
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
|
||||
let query = LibraryBrowseQuery(scope: .all)
|
||||
let encoded = String(decoding: try JSONEncoder().encode(query), as: UTF8.self)
|
||||
continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded, "layout": "Table"], selectedID: "other"), for: "software-main")
|
||||
await continuity.flush()
|
||||
let restored = LibraryContinuityStore(directory: support)
|
||||
let model = SoftwareLibraryModel(state: state, continuity: restored), url = try database()
|
||||
let loading = Task { await model.load(from: url, catalogLoader: { url in
|
||||
try await Task.sleep(nanoseconds: 350_000_000)
|
||||
return try await SoftwareLibraryCatalog.load(from: url)
|
||||
}) }
|
||||
for _ in 0..<100 where !model.loading { try await Task.sleep(nanoseconds: 1_000_000) }
|
||||
try await Task.sleep(nanoseconds: 180_000_000) // exceeds the empty-result filter debounce
|
||||
XCTAssertTrue(model.loading)
|
||||
XCTAssertEqual(model.selection, "other")
|
||||
XCTAssertEqual(restored.browse(for: "software-main")?.selectedID, "other", "An empty interim result must not overwrite resume state")
|
||||
await loading.value; try await settle(model)
|
||||
XCTAssertEqual(model.selection, "other"); XCTAssertEqual(model.layout, "Table")
|
||||
XCTAssertEqual(model.selectedRow?.name, "Other Game")
|
||||
await model.shutdown()
|
||||
}
|
||||
@MainActor
|
||||
func testFailedCatalogReadKeepsPublicResumePendingForRetry() async throws {
|
||||
let support = directory.appendingPathComponent("FailedResume")
|
||||
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
|
||||
let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .all)), as: UTF8.self)
|
||||
continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded], selectedID: "other"), for: "software-main")
|
||||
let model = SoftwareLibraryModel(state: state, continuity: continuity), url = try database()
|
||||
await model.load(from: url, catalogLoader: { _ in throw CocoaError(.fileReadNoPermission) })
|
||||
try await settle(model)
|
||||
XCTAssertNotNil(model.error); XCTAssertNil(model.catalog)
|
||||
XCTAssertEqual(model.selection, "other")
|
||||
XCTAssertEqual(continuity.browse(for: "software-main")?.selectedID, "other")
|
||||
await model.load(from: url); try await settle(model)
|
||||
XCTAssertNil(model.error); XCTAssertEqual(model.selection, "other")
|
||||
XCTAssertEqual(model.selectedRow?.name, "Other Game")
|
||||
await model.shutdown()
|
||||
}
|
||||
@MainActor
|
||||
func testPrivateScopeRemainsUsableWhenPublicCatalogCannotLoad() async throws {
|
||||
let support = directory.appendingPathComponent("PrivateWithoutCatalog")
|
||||
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
|
||||
let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .personal)), as: UTF8.self)
|
||||
continuity.setBrowse(.init(scope: "personal", filters: ["browse-query": encoded], selectedID: "personal:missing"), for: "software-main")
|
||||
let model = SoftwareLibraryModel(state: state, continuity: continuity)
|
||||
let source = directory.appendingPathComponent("LOCAL.ccc"); try Data([0x12,0x39]).write(to: source)
|
||||
let draft = try await model.personalStore.inspect([source]), entry = try await model.personalStore.save(draft)
|
||||
await model.load(from: directory.appendingPathComponent("Unavailable.sqlite"), catalogLoader: { _ in throw CocoaError(.fileReadNoSuchFile) })
|
||||
try await settle(model)
|
||||
XCTAssertNil(model.catalog); XCTAssertNotNil(model.error)
|
||||
XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selectedRow?.id, entry.titleID)
|
||||
await model.shutdown()
|
||||
}
|
||||
@MainActor
|
||||
func testPersonalSaveDuringColdCatalogLoadWinsOverResumedPublicScope() async throws {
|
||||
let support = directory.appendingPathComponent("PersonalDuringLoad")
|
||||
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
|
||||
let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .all)), as: UTF8.self)
|
||||
continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded], selectedID: "other"), for: "software-main")
|
||||
let model = SoftwareLibraryModel(state: state, continuity: continuity), url = try database()
|
||||
let source = directory.appendingPathComponent("AUTHORED.ccc")
|
||||
try Data([0x12,0x39]).write(to: source)
|
||||
let draft = try await model.personalStore.inspect([source]), entry = try await model.personalStore.save(draft)
|
||||
let loading = Task { await model.load(from: url, catalogLoader: { url in
|
||||
try await Task.sleep(nanoseconds: 500_000_000)
|
||||
return try await SoftwareLibraryCatalog.load(from: url)
|
||||
}) }
|
||||
for _ in 0..<100 where !model.loading { try await Task.sleep(nanoseconds: 1_000_000) }
|
||||
try await Task.sleep(nanoseconds: 150_000_000)
|
||||
model.editPersonal(entry); model.savePersonal(entry, allowDuplicate: false)
|
||||
for _ in 0..<100 where model.personalSaving { try await Task.sleep(nanoseconds: 5_000_000) }
|
||||
XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selection, entry.titleID)
|
||||
await loading.value; try await settle(model)
|
||||
XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selection, entry.titleID)
|
||||
XCTAssertEqual(model.selectedRow?.id, entry.titleID)
|
||||
await model.shutdown()
|
||||
XCTAssertEqual(continuity.browse(for: "software-main")?.selectedID, entry.titleID)
|
||||
}
|
||||
@MainActor
|
||||
func testRapidQueriesAndFavoriteChangesPublishLatestResults() async throws {
|
||||
let state = SoftwareLibraryState(directory: directory.appendingPathComponent("Personal"))
|
||||
let model = SoftwareLibraryModel(state: state)
|
||||
|
||||
@@ -40,6 +40,20 @@ final class SoftwareLibraryLaunchPlanTests: XCTestCase {
|
||||
XCTAssertFalse(automatic(release(media: "hard-disk", profile: "hard-drive-basic", paths: [("hardDisk0", "GAME.vhd")], command: "DOS\r")))
|
||||
XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.vhd")], command: "DOS\r")))
|
||||
}
|
||||
func testUnconfiguredPersonalROMImportOffersRealCartridgeSetup() async throws {
|
||||
let selected = root.appendingPathComponent("AUTHORED.ROM"), bytes = Data([0x12,0x39])
|
||||
try bytes.write(to: selected)
|
||||
let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary"))
|
||||
let draft = try await store.inspect([selected]), entry = try await store.save(draft)
|
||||
XCTAssertFalse(entry.configured)
|
||||
let imported = await store.directory(for: entry.id)
|
||||
let plan = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: imported), receipt: entry.receipt(in: imported))
|
||||
XCTAssertEqual(plan.profile, .romCartridge)
|
||||
XCTAssertEqual(plan.cartridgeURL?.lastPathComponent, "AUTHORED.ROM")
|
||||
XCTAssertTrue(plan.commands.isEmpty)
|
||||
XCTAssertEqual(try Data(contentsOf: selected), bytes)
|
||||
try plan.validateMedia()
|
||||
}
|
||||
func testCartridgeAutostartsWithoutTypingAndHonorsItsStartupSlot() throws {
|
||||
try file("GAME.ccc")
|
||||
let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "GAME.ccc")], extra: ["cartridge_slot": .number(2)]), receipt: receipt(["GAME.ccc"]))
|
||||
@@ -186,4 +200,53 @@ final class SoftwareLibraryLaunchPlanTests: XCTestCase {
|
||||
XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands(command), command)
|
||||
}
|
||||
}
|
||||
|
||||
func testBasicProgramLoadThenRunUsesSeparateKeyboardLines() throws {
|
||||
for sequence in ["LOAD \"POPSTAR\"\nRUN", "load \"POPSTAR\"\r\nrun", "LOAD\"POPSTAR\"\\rRUN\\r"] {
|
||||
let commands = try XCTUnwrap(SoftwareLibraryLaunchPlan.decodeCommands(sequence))
|
||||
XCTAssertEqual(commands.count, 2)
|
||||
XCTAssertEqual(commands[0].uppercased().replacingOccurrences(of: " ", with: ""), "LOAD\"POPSTAR\"")
|
||||
XCTAssertEqual(commands[1].uppercased(), "RUN")
|
||||
}
|
||||
try file("POPSTAR.DSK")
|
||||
let item = release(paths: [("disk0", "POPSTAR.DSK")], command: "LOAD \"POPSTAR\"\nRUN", status: "manual-setup")
|
||||
XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item))
|
||||
let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: receipt(["POPSTAR.DSK"]))
|
||||
XCTAssertTrue(plan.automaticallyStarts)
|
||||
XCTAssertEqual(plan.commands, ["LOAD \"POPSTAR\"", "RUN"])
|
||||
XCTAssertEqual(plan.floppyURLs[0]?.lastPathComponent, "POPSTAR.DSK")
|
||||
XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\":RUN"), "BASIC discards the rest of the LOAD command line")
|
||||
XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\""), ["LOAD \"POPSTAR\""])
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release(paths: [("disk0", "POPSTAR.DSK")], command: "LOAD \"POPSTAR\"")))
|
||||
XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\"\nRUN\nDIR"), "No later commands may be typed into a started guest program")
|
||||
}
|
||||
@MainActor
|
||||
func testReviewedPersonalDiskOffersPlayWithoutLoadingCommands() throws {
|
||||
try file("GAME.DSK")
|
||||
var entry = PersonalSoftwareEntry(id: UUID(), title: "Reviewed personal disk", files: [
|
||||
.init(path: "GAME.DSK", kind: "disk", byteSize: 3, sha256: sha, role: "disk0")
|
||||
])
|
||||
entry.configured = true
|
||||
let item = entry.release(in: root)
|
||||
XCTAssertTrue(SoftwareLibraryLaunchPlan.hasPlayAction(for: item))
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item))
|
||||
let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: entry.receipt(in: root))
|
||||
XCTAssertTrue(plan.offersPlay); XCTAssertFalse(plan.automaticallyStarts)
|
||||
XCTAssertTrue(plan.commands.isEmpty); XCTAssertNotNil(plan.floppyURLs[0])
|
||||
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
|
||||
XCTAssertEqual(model.launchLabel(item, installed: true), "Play…")
|
||||
XCTAssertEqual(model.launchSymbol(item), "play.fill")
|
||||
entry.command = "LOAD \"GAME\""
|
||||
let loadOnly = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: root), receipt: entry.receipt(in: root))
|
||||
XCTAssertTrue(loadOnly.offersPlay); XCTAssertFalse(loadOnly.automaticallyStarts)
|
||||
XCTAssertEqual(loadOnly.commands, ["LOAD \"GAME\""])
|
||||
entry.command = "SYSTEM \"curl example.invalid\""
|
||||
let unsupported = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: root), receipt: entry.receipt(in: root))
|
||||
XCTAssertTrue(unsupported.offersPlay); XCTAssertTrue(unsupported.commands.isEmpty)
|
||||
entry.configured = false
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: root)))
|
||||
entry.configured = true; entry.files[0].role = ""
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: root)))
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: release(paths: [("disk0", "GAME.DSK")])), "Public catalog labels retain their existing behavior")
|
||||
}
|
||||
}
|
||||
@@ -36,21 +36,21 @@ final class SoftwareLibraryMachineLaunchTests: XCTestCase {
|
||||
profile.input.right.source = .controller; profile.input.right.device = "remembered-controller"
|
||||
return profile
|
||||
}
|
||||
func plan(cartridge: Bool = true, command: String? = nil, keyboardControls: Bool = false, cartridgeDevice: String = "rom") throws -> SoftwareLibraryLaunchPlan {
|
||||
func plan(cartridge: Bool = true, command: String? = nil, keyboardControls: Bool = false, cartridgeDevice: String = "rom", hardDrive: Bool = false) throws -> SoftwareLibraryLaunchPlan {
|
||||
let working = folder.appendingPathComponent(UUID().uuidString).appendingPathComponent("Working")
|
||||
try FileManager.default.createDirectory(at: working, withIntermediateDirectories: true)
|
||||
let filename = cartridge ? "Fixture.ccc" : "Fixture.dsk"
|
||||
let filename = hardDrive ? "Fixture.vhd" : cartridge ? "Fixture.ccc" : "Fixture.dsk"
|
||||
var bytes = Data(repeating: cartridge ? 0x12 : 0, count: cartridge ? 8192 : 161280)
|
||||
if cartridge { bytes[0] = 0x20; bytes[1] = 0xfe }
|
||||
try bytes.write(to: working.appendingPathComponent(filename))
|
||||
let sha = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
||||
var configuration: [String: LibraryJSON] = ["profile": .string(cartridge ? "rom-cartridge" : "disk-basic"), "processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"), "controller_slot": .number(4), "controls": .object(["right": .object(["suggested_input": .string("keyboard-joystick")])])]
|
||||
var configuration: [String: LibraryJSON] = ["profile": .string(hardDrive ? "hard-drive-basic" : cartridge ? "rom-cartridge" : "disk-basic"), "processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"), "controller_slot": .number(4), "controls": .object(["right": .object(["suggested_input": .string("keyboard-joystick")])])]
|
||||
if keyboardControls { configuration["controls"] = .object(["keyboard": .string("Arrow keys, Z, X and C")]) }
|
||||
if cartridge { configuration["launch_method"] = .string("cartridge-autostart"); configuration["cartridge_device"] = .string(cartridgeDevice) }
|
||||
let setup = SoftwareLibrarySetup(status: command == nil && !cartridge ? "manual-setup" : "inferred-ready", command: command,
|
||||
instructions: "Authored launch fixture", configuration: .object(configuration),
|
||||
selectedMembers: .array([.object(["path": .string(filename), "target": .string(cartridge ? "cartridge" : "disk0")])]), reasons: [], validation: .object([:]))
|
||||
let release = SoftwareLibraryRelease(id: "fixture", titleID: "fixture", name: "Fixture", category: cartridge ? "Cartridges" : "Disks/Games", mediaType: cartridge ? "cartridge" : "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/" + filename)!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: sha, byteSize: Int64(bytes.count), languageStatus: "english", metadata: .object(["title": .string("Authored Launch")]), setup: setup, assets: [], downloadURLs: [])
|
||||
selectedMembers: .array([.object(["path": .string(filename), "target": .string(hardDrive ? "hard0" : cartridge ? "cartridge" : "disk0")])]), reasons: [], validation: .object([:]))
|
||||
let release = SoftwareLibraryRelease(id: "fixture", titleID: "fixture", name: "Fixture", category: cartridge ? "Cartridges" : "Disks/Games", mediaType: hardDrive ? "hard-disk" : cartridge ? "cartridge" : "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/" + filename)!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: sha, byteSize: Int64(bytes.count), languageStatus: "english", metadata: .object(["title": .string("Authored Launch")]), setup: setup, assets: [], downloadURLs: [])
|
||||
let receipt = SoftwareLibraryInstallationReceipt(releaseID: release.id, packageSHA256: sha, installedAt: Date(), workingDirectory: working, relativeFiles: [filename])
|
||||
return try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt)
|
||||
}
|
||||
@@ -114,6 +114,56 @@ final class SoftwareLibraryMachineLaunchTests: XCTestCase {
|
||||
XCTAssertEqual(model.profileName, initial.name); XCTAssertTrue(after.disks[0].mounted)
|
||||
}
|
||||
}
|
||||
@MainActor func testHardDriveLibraryRejectsUnrecognizedDiskROMWithoutChangingMachine() async throws {
|
||||
let fixture = try Fixture(); defer { fixture.cleanup() }
|
||||
try await withMachine(fixture) { model, controller, initial in
|
||||
let before = await step(controller.snapshot)
|
||||
do {
|
||||
_ = try await model.prepareLibraryLaunch(fixture.plan(cartridge: false, hardDrive: true))
|
||||
XCTFail("An arbitrary Disk BASIC ROM cannot stand in for RGB-DOS")
|
||||
} catch {
|
||||
XCTAssertTrue(error.localizedDescription.contains("rgbdos.rom"))
|
||||
}
|
||||
let after = await step(controller.snapshot)
|
||||
XCTAssertEqual(after.generation, before.generation)
|
||||
XCTAssertEqual(after.state, .running)
|
||||
XCTAssertEqual(model.diskAssignments.rom, initial.media.rom)
|
||||
XCTAssertEqual(model.profileName, initial.name)
|
||||
}
|
||||
}
|
||||
@MainActor func testHardDriveLibraryUsesSuppliedRGBDOSAndRecognizedCachedFallback() async throws {
|
||||
let startup = try StartupTests.Fixture(); defer { startup.remove() }
|
||||
let fixture = try Fixture(); defer { fixture.cleanup() }
|
||||
let rgbdos = Data(repeating: 0x39, count: 8192)
|
||||
try rgbdos.write(to: startup.kit.directory.appendingPathComponent("rgbdos.rom"))
|
||||
let model = MachineModel(diskStore: startup.disks, displayDefaults: fixture.defaults,
|
||||
inputStore: .init(url: fixture.folder.appendingPathComponent("Input.json")), startupStore: startup.startup)
|
||||
do {
|
||||
try await settle(model)
|
||||
let initial = try fixture.initialProfile()
|
||||
await model.loadProfile(initial); XCTAssertNil(model.profileError)
|
||||
let plan = try fixture.plan(cartridge: false, hardDrive: true)
|
||||
let prepared = try await model.prepareLibraryLaunch(plan)
|
||||
let rom = try XCTUnwrap(prepared.profile.media.rom)
|
||||
XCTAssertNotEqual(rom, initial.media.rom)
|
||||
XCTAssertEqual(try Data(contentsOf: rom), rgbdos)
|
||||
XCTAssertEqual(prepared.profile.media.hardDisks?.drives[0]?.url, plan.hardDiskURLs[0])
|
||||
XCTAssertEqual(prepared.profile.media.cartridges?.slots[4].kind, .floppy)
|
||||
XCTAssertEqual(prepared.profile.media.cartridges?.slots[1].kind, .hardDisk)
|
||||
|
||||
// Known starter firmware remains a valid fallback after bundle moves.
|
||||
let loaded = await model.loadSystemProfile(.hardDriveBasic)
|
||||
XCTAssertTrue(loaded)
|
||||
XCTAssertEqual(model.usageProfile, .hardDriveBasic)
|
||||
try FileManager.default.removeItem(at: startup.kit.directory.appendingPathComponent("rgbdos.rom"))
|
||||
let cached = try await model.prepareLibraryLaunch(plan)
|
||||
XCTAssertEqual(cached.profile.media.rom, rom)
|
||||
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(cached.profile.media.rom)), rgbdos)
|
||||
} catch {
|
||||
await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error
|
||||
}
|
||||
await withCheckedContinuation { done in model.shutdown { done.resume() } }
|
||||
}
|
||||
@MainActor func testPreviewDoesNotChangeSessionAndStaleConfigurationCannotLaunch() async throws {
|
||||
let fixture = try Fixture(); defer { fixture.cleanup() }
|
||||
try await withMachine(fixture) { model, controller, _ in
|
||||
|
||||
@@ -18,6 +18,25 @@ final class SoftwareLibraryManualTests: XCTestCase {
|
||||
asset.manualURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/Games/Manual.pdf")
|
||||
return (asset, bytes)
|
||||
}
|
||||
func testImportedUppercaseTextManualUsesTextReaderWithoutNetwork() async throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent("PersonalManual-" + UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let source = root.appendingPathComponent("Selected")
|
||||
try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
|
||||
let text = Data("Authored local loading instructions\n".utf8)
|
||||
try text.write(to: source.appendingPathComponent("README.TXT"))
|
||||
try Data([0x12,0x39]).write(to: source.appendingPathComponent("GAME.ccc"))
|
||||
let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary"))
|
||||
let draft = try await store.inspect([source]), entry = try await store.save(draft)
|
||||
let imported = await store.directory(for: entry.id)
|
||||
let manual = try XCTUnwrap(entry.release(in: imported).primaryManualAsset)
|
||||
let model = SoftwareLibraryManualModel(); model.open(manual, directory: root.appendingPathComponent("UnusedCache"))
|
||||
for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 10_000_000) }
|
||||
XCTAssertEqual(model.text, String(decoding: text, as: UTF8.self))
|
||||
XCTAssertNil(model.document); XCTAssertNil(model.error)
|
||||
XCTAssertEqual(try Data(contentsOf: source.appendingPathComponent("README.TXT")), text)
|
||||
model.cancel()
|
||||
}
|
||||
func testPlainTextDecodingPreservesInstructionsAndRejectsBinaryData() throws {
|
||||
XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data("Z = start\r\nX = kick\u{1A}".utf8)), "Z = start\nX = kick")
|
||||
XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data([0x63, 0x61, 0x66, 0xe9])), "café")
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import CryptoKit
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
final class SoftwareLibraryPersonalTests: XCTestCase {
|
||||
private var root: URL!
|
||||
override func setUpWithError() throws {
|
||||
root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("PersonalLibraryTests-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
}
|
||||
override func tearDownWithError() throws { if let root { try? FileManager.default.removeItem(at: root) } }
|
||||
private func service() -> PersonalSoftwareLibraryStore { .init(root: root.appendingPathComponent("PersonalLibrary")) }
|
||||
private func cartridge(_ name: String = "GAME.ccc") throws -> URL {
|
||||
let source = root.appendingPathComponent(name)
|
||||
try Data([0x39,0x12,0x12,0x12]).write(to: source)
|
||||
return source
|
||||
}
|
||||
private func png(width: Int = 96, height: Int = 128, gray: CGFloat = 0.25) throws -> Data {
|
||||
let context = try XCTUnwrap(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8,
|
||||
bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
|
||||
context.setFillColor(CGColor(gray: gray, alpha: 1))
|
||||
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
|
||||
let data = NSMutableData()
|
||||
let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil))
|
||||
CGImageDestinationAddImage(destination, try XCTUnwrap(context.makeImage()), nil)
|
||||
XCTAssertTrue(CGImageDestinationFinalize(destination))
|
||||
return data as Data
|
||||
}
|
||||
func testSingleFloppyDefaultsToFD0WithoutEnablingAutomation() async throws {
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let source = root.appendingPathComponent("GAME.dsk")
|
||||
let bytes = try Data(contentsOf: fixture); try bytes.write(to: source)
|
||||
let readme = root.appendingPathComponent("README.txt"); try Data("Instructions".utf8).write(to: readme)
|
||||
let store = service(), draft = try await store.inspect([source, readme])
|
||||
XCTAssertEqual(draft.entry.files.first(where: { $0.kind == "disk" })?.role, "disk0")
|
||||
XCTAssertFalse(draft.entry.configured); XCTAssertTrue(draft.entry.command.isEmpty)
|
||||
let entry = try await store.save(draft), directory = await store.directory(for: entry.id)
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: directory)))
|
||||
let recovered = try await store.entries()
|
||||
XCTAssertEqual(recovered.first?.files.first(where: { $0.kind == "disk" })?.role, "disk0")
|
||||
XCTAssertEqual(try Data(contentsOf: source), bytes)
|
||||
}
|
||||
func testMultipleFloppiesKeepExplicitRolesAndSavedChoicesAreNotReset() async throws {
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let first = root.appendingPathComponent("FIRST.dsk"), second = root.appendingPathComponent("SECOND.dsk")
|
||||
let bytes = try Data(contentsOf: fixture); try bytes.write(to: first); try bytes.write(to: second)
|
||||
let store = service(), multiple = try await store.inspect([first, second])
|
||||
XCTAssertTrue(multiple.entry.files.allSatisfy { $0.role.isEmpty }, "Do not infer a boot disk from filename order")
|
||||
await store.cancel(multiple.id)
|
||||
let single = try await store.inspect([first]); var entry = try await store.save(single)
|
||||
entry.files[0].role = "disk2"; try await store.update(entry)
|
||||
let saved = try await store.entries()
|
||||
XCTAssertEqual(saved.first?.files[0].role, "disk2", "Defaulting applies to new imports, not saved user choices")
|
||||
XCTAssertEqual(try Data(contentsOf: second), bytes)
|
||||
}
|
||||
func testImportPreservesOriginalsAndWorkingSavesAndNeverPublishes() async throws {
|
||||
let source = try cartridge(), bytes = try Data(contentsOf: source), store = service()
|
||||
let draft = try await store.inspect([source])
|
||||
XCTAssertEqual(draft.entry.profile, "rom-cartridge")
|
||||
XCTAssertFalse(draft.entry.configured)
|
||||
let entry = try await store.save(draft)
|
||||
let directory = await store.directory(for: entry.id)
|
||||
let working = directory.appendingPathComponent("Working/GAME.ccc")
|
||||
XCTAssertEqual(try Data(contentsOf: working), bytes)
|
||||
let saved = Data([0x10,0x20,0x30]); try saved.write(to: working)
|
||||
XCTAssertEqual(try Data(contentsOf: source), bytes)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), bytes)
|
||||
let restored = try await service().entries()
|
||||
XCTAssertEqual(restored.map(\.id), [entry.id])
|
||||
XCTAssertEqual(try Data(contentsOf: working), saved)
|
||||
let release = entry.release(in: directory)
|
||||
XCTAssertTrue(release.isPersonal); XCTAssertFalse(release.isArchive)
|
||||
XCTAssertTrue(release.downloadURLs.isEmpty)
|
||||
XCTAssertTrue(release.sourceURL.isFileURL)
|
||||
let catalog = SoftwareLibraryCatalog(titles: [.init(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [release])], metadata: [:])
|
||||
XCTAssertTrue(catalog.companionDisksOnly.titles.isEmpty)
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .all).apply(to: catalog.titles, favorites: [], installed: []).map(\.id), [entry.titleID])
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .personal).apply(to: catalog.titles, favorites: [], installed: []).count,1)
|
||||
XCTAssertEqual(LibraryBrowseQuery(scope: .favorites).apply(to: catalog.titles, favorites: [entry.titleID], installed: []).count,1)
|
||||
}
|
||||
func testDuplicateRequiresExplicitSeparateCopyAndHiddenEntryStaysHidden() async throws {
|
||||
let source = try cartridge(), store = service()
|
||||
let initial = try await store.inspect([source])
|
||||
let first = try await store.save(initial)
|
||||
let duplicate = try await store.inspect([source])
|
||||
do { _ = try await store.save(duplicate); XCTFail("Expected duplicate review") }
|
||||
catch PersonalSoftwareLibraryStore.Failure.duplicate(let id) { XCTAssertEqual(id, first.id) }
|
||||
let second = try await store.save(duplicate, allowDuplicate: true)
|
||||
XCTAssertNotEqual(first.id, second.id)
|
||||
var removed = first; removed.hidden = true
|
||||
try await store.update(removed)
|
||||
let visible = try await service().entries()
|
||||
XCTAssertEqual(visible.map(\.id), [second.id])
|
||||
let retained = await store.directory(for: first.id)
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: retained.appendingPathComponent("Working/GAME.ccc").path))
|
||||
}
|
||||
func testPersonalCategoryDefaultsAndNormalizesWithoutReplacingWorkingFiles() async throws {
|
||||
let source = try cartridge(), store = service()
|
||||
var draft = try await store.inspect([source])
|
||||
XCTAssertEqual(draft.entry.category, "Other")
|
||||
draft.entry.category = "A custom category"
|
||||
var entry = try await store.save(draft)
|
||||
XCTAssertEqual(entry.category, "Other")
|
||||
let directory = await store.directory(for: entry.id)
|
||||
let working = directory.appendingPathComponent("Working/GAME.ccc")
|
||||
let bytes = Data([0x39, 0x20, 0x30]); try bytes.write(to: working)
|
||||
entry.category = "Games"; try await store.update(entry)
|
||||
var recovered = try await store.entries()
|
||||
XCTAssertEqual(recovered.first?.category, "Games")
|
||||
for category in PersonalSoftwareEntry.standardCategories {
|
||||
entry.category = category
|
||||
let release = entry.release(in: directory)
|
||||
XCTAssertEqual(LibraryBrowseQuery.type(of: release), category, "Each dropdown choice must use its actual category illustration")
|
||||
}
|
||||
// Simulate a free-form category saved by the previous development UI.
|
||||
entry.category = "An old custom category"
|
||||
try JSONEncoder().encode(entry).write(to: directory.appendingPathComponent("Entry.json"), options: .atomic)
|
||||
recovered = try await store.entries()
|
||||
XCTAssertEqual(recovered.first?.category, "Other")
|
||||
XCTAssertEqual(try Data(contentsOf: working), bytes)
|
||||
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
|
||||
}
|
||||
func testSavedReviewedBasicCommandsOfferAutomaticLaunchWithoutTouchingMedia() async throws {
|
||||
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
|
||||
let source = root.appendingPathComponent("POPSTAR.DSK")
|
||||
let bytes = try Data(contentsOf: fixture)
|
||||
try bytes.write(to: source)
|
||||
let store = service(), draft = try await store.inspect([source])
|
||||
var entry = try await store.save(draft)
|
||||
entry.configured = true; entry.video = "rgb"; entry.ramKiB = 512
|
||||
entry.files[0].role = "disk0"
|
||||
entry.command = "LOAD \"POPSTAR\"\nRUN"
|
||||
try await store.update(entry)
|
||||
let recovered = try await store.entries()
|
||||
let saved = try XCTUnwrap(recovered.first)
|
||||
let directory = await store.directory(for: saved.id)
|
||||
let release = saved.release(in: directory)
|
||||
XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release))
|
||||
let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: saved.receipt(in: directory))
|
||||
XCTAssertTrue(plan.automaticallyStarts)
|
||||
XCTAssertEqual(plan.commands, ["LOAD \"POPSTAR\"", "RUN"])
|
||||
XCTAssertEqual(plan.floppyURLs[0], directory.appendingPathComponent("Working/POPSTAR.DSK"))
|
||||
XCTAssertEqual(plan.ramKiB, 512)
|
||||
XCTAssertEqual(try Data(contentsOf: source), bytes)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/POPSTAR.DSK")), bytes)
|
||||
var manual = saved; manual.configured = false
|
||||
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: manual.release(in: directory)))
|
||||
}
|
||||
func testCancelAndSymlinkFailurePreserveSelectedFiles() async throws {
|
||||
let source = try cartridge(), store = service()
|
||||
let draft = try await store.inspect([source])
|
||||
await store.cancel(draft.id)
|
||||
let entries = try await store.entries(); XCTAssertTrue(entries.isEmpty)
|
||||
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
|
||||
let folder = root.appendingPathComponent("Set")
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
try FileManager.default.createSymbolicLink(at: folder.appendingPathComponent("GAME.ccc"), withDestinationURL: source)
|
||||
do { _ = try await store.inspect([folder]); XCTFail("Symbolic links must not be followed") } catch { }
|
||||
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
|
||||
do { _ = try await store.inspect([root]); XCTFail("A source folder must not recursively include its own import destination.") } catch { }
|
||||
}
|
||||
func testMultiFileSetMetadataEditsAndInvalidRecipePreserveMedia() async throws {
|
||||
let folder = root.appendingPathComponent("Owned Software")
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
try Data([0x39]).write(to: folder.appendingPathComponent("GAME.ccc"))
|
||||
try Data("Private instructions".utf8).write(to: folder.appendingPathComponent("README.txt"))
|
||||
let store = service(); let draft = try await store.inspect([folder])
|
||||
XCTAssertEqual(draft.entry.files.map(\.path), ["GAME.ccc", "README.txt"], "Selected-folder aliases must not become member prefixes.")
|
||||
var entry = try await store.save(draft)
|
||||
let directory = await store.directory(for: entry.id)
|
||||
let original = try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc"))
|
||||
entry.title = "My purchased game"; entry.author = "Original author"
|
||||
try await store.update(entry)
|
||||
let recovered = try await service().entries()
|
||||
XCTAssertEqual(recovered.first?.title, entry.title)
|
||||
XCTAssertEqual(recovered.first?.files.count,2)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/README.txt")), Data("Private instructions".utf8))
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), original)
|
||||
entry.command = "hello\u{1B}"
|
||||
do { try await store.update(entry); XCTFail("Control injection must fail") } catch { }
|
||||
XCTAssertEqual(try Data(contentsOf: folder.appendingPathComponent("README.txt")), Data("Private instructions".utf8))
|
||||
let release = recovered[0].release(in: directory)
|
||||
let manual = try XCTUnwrap(release.primaryManualAsset)
|
||||
try SoftwareLibraryLocalAsset.validate(manual, url: manual.manualURL!, maximumBytes: 1024*1024)
|
||||
try Data("changed".utf8).write(to: manual.manualURL!)
|
||||
XCTAssertThrowsError(try SoftwareLibraryLocalAsset.validate(manual,url:manual.manualURL!,maximumBytes:1024*1024))
|
||||
}
|
||||
func testZIPKeepsOriginalPackageAndCompleteWorkingTree() async throws {
|
||||
let archive = root.appendingPathComponent("Authored Software.zip")
|
||||
let bytes = Data(base64Encoded: "UEsDBBQAAAAAAAAAIVyFZweNAQAAAAEAAAANAAAAR2FtZS9HQU1FLmNjYzlQSwMEFAAAAAAAAAAhXFokposcAAAAHAAAAA8AAABHYW1lL1JFQURNRS50eHRBdXRob3JlZCBsb2NhbCBpbnN0cnVjdGlvbnMKUEsBAhQDFAAAAAAAAAAhXIVnB40BAAAAAQAAAA0AAAAAAAAAAAAAAKSBAAAAAEdhbWUvR0FNRS5jY2NQSwECFAMUAAAAAAAAACFcWiSmixwAAAAcAAAADwAAAAAAAAAAAAAApIEsAAAAR2FtZS9SRUFETUUudHh0UEsFBgAAAAACAAIAeAAAAHUAAAAAAA==")!
|
||||
try bytes.write(to: archive)
|
||||
let store = service()
|
||||
let owned = try await store.inspect([archive])
|
||||
let entry = try await store.save(owned)
|
||||
let directory = await store.directory(for: entry.id)
|
||||
XCTAssertEqual(entry.files.map(\.path), ["Game/GAME.ccc", "Game/README.txt"])
|
||||
XCTAssertEqual(try Data(contentsOf: archive),bytes)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Package.zip")),bytes)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/Game/README.txt")),Data("Authored local instructions\n".utf8))
|
||||
}
|
||||
func testReviewedZIPRejectsChangedValidBytesAndPreservesExistingLibrary() async throws {
|
||||
let source = root.appendingPathComponent("Authored.zip")
|
||||
let original = Data(base64Encoded: "UEsDBBQAAAAAAAAAIVyFZweNAQAAAAEAAAANAAAAR2FtZS9HQU1FLmNjYzlQSwMEFAAAAAAAAAAhXFokposcAAAAHAAAAA8AAABHYW1lL1JFQURNRS50eHRBdXRob3JlZCBsb2NhbCBpbnN0cnVjdGlvbnMKUEsBAhQDFAAAAAAAAAAhXIVnB40BAAAAAQAAAA0AAAAAAAAAAAAAAKSBAAAAAEdhbWUvR0FNRS5jY2NQSwECFAMUAAAAAAAAACFcWiSmixwAAAAcAAAADwAAAAAAAAAAAAAApIEsAAAAR2FtZS9SRUFETUUudHh0UEsFBgAAAAACAAIAeAAAAHUAAAAAAA==")!
|
||||
try original.write(to: source)
|
||||
let store = service(), reviewedHash = SHA256.hash(data: original).map { String(format: "%02x", $0) }.joined()
|
||||
let draft = try await store.inspect([source]), entry = try await store.save(draft)
|
||||
let retained = await store.directory(for: entry.id)
|
||||
// Rename ZIP member directories in both local/central headers. Sizes and
|
||||
// file CRCs remain valid: rejection must bind bytes, not just ZIP validity.
|
||||
var changed = original, offset = 0
|
||||
while let range = changed.range(of: Data("Game/".utf8), in: offset..<changed.count) {
|
||||
changed.replaceSubrange(range, with: Data("Play/".utf8)); offset = range.upperBound
|
||||
}
|
||||
XCTAssertEqual(changed.count, original.count); XCTAssertNotEqual(changed, original)
|
||||
try changed.write(to: source)
|
||||
let extracted = root.appendingPathComponent("ChangedIsValid")
|
||||
let paths = try VCCLibraryArchive.extractZIP(at: source, toNewDirectory: extracted, maximumExpandedBytes: 1024*1024, maximumEntries: 10, shouldCancel: { false })
|
||||
XCTAssertEqual(paths, ["Play/GAME.ccc", "Play/README.txt"])
|
||||
let attempted = root.appendingPathComponent("Unpublished.zip")
|
||||
XCTAssertThrowsError(try PersonalSoftwareLibraryStore.copyReviewedPackage(from: source, to: attempted,
|
||||
byteSize: Int64(original.count), sha256: reviewedHash))
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: attempted.path))
|
||||
XCTAssertEqual(try Data(contentsOf: source), changed, "Failed import must not modify the selected source")
|
||||
XCTAssertEqual(try Data(contentsOf: retained.appendingPathComponent("Original/Package.zip")), original)
|
||||
XCTAssertEqual(try Data(contentsOf: retained.appendingPathComponent("Working/Game/GAME.ccc")), Data([0x39]))
|
||||
let existing = try await store.entries(); XCTAssertEqual(existing.map(\.id), [entry.id])
|
||||
}
|
||||
func testPersonalCoverSelectionReplacementRemovalAndReloadPreserveMedia() async throws {
|
||||
let source = try cartridge(), store = service(), firstPNG = try png(), secondPNG = try png(gray: 0.75)
|
||||
let first = root.appendingPathComponent("A.png"), second = root.appendingPathComponent("B.png")
|
||||
try firstPNG.write(to: first); try secondPNG.write(to: second)
|
||||
let manual = root.appendingPathComponent("README.txt")
|
||||
try Data("Retained manual".utf8).write(to: manual)
|
||||
var draft = try await store.inspect([source, first, second, manual])
|
||||
XCTAssertNil(draft.entry.cover)
|
||||
XCTAssertEqual(draft.entry.selectedCoverFile?.path, "A.png")
|
||||
let initialPreview = try await store.previewCover(draft.entry, draftID: draft.id)
|
||||
XCTAssertEqual(initialPreview, try PersonalCoverImage.prepare(firstPNG))
|
||||
draft.entry.cover = .imported("B.png")
|
||||
let selectedPreview = try await store.previewCover(draft.entry, draftID: draft.id)
|
||||
XCTAssertEqual(selectedPreview, try PersonalCoverImage.prepare(secondPNG))
|
||||
var entry = try await store.save(draft)
|
||||
let identity = entry.packageSHA256, files = entry.files.map(\.path)
|
||||
let directory = await store.directory(for: entry.id), working = directory.appendingPathComponent("Working/GAME.ccc")
|
||||
let savedProgram = Data([0x39, 0x20]); try savedProgram.write(to: working)
|
||||
let release = entry.release(in: directory)
|
||||
XCTAssertEqual(release.assets.filter { $0.kind == "cover" }.map(\.name), ["B.png"])
|
||||
XCTAssertEqual(release.assets.filter(\.isManual).map(\.name), ["README.txt"])
|
||||
let replacement = try png(width: 1800, height: 1000)
|
||||
try await store.update(entry, coverPNG: replacement)
|
||||
var reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
|
||||
guard case .custom(let custom) = entry.cover else { return XCTFail("Replacement cover must use a separate local asset.") }
|
||||
XCTAssertTrue(custom.path.hasPrefix("PersonalCovers/"))
|
||||
let customURL = directory.appendingPathComponent("Assets").appendingPathComponent(custom.path)
|
||||
let customBytes = try Data(contentsOf: customURL)
|
||||
XCTAssertEqual(Int64(customBytes.count), custom.byteSize)
|
||||
XCTAssertEqual(custom.sha256, SHA256.hash(data: customBytes).map { String(format: "%02x", $0) }.joined())
|
||||
let image = try XCTUnwrap(SoftwareLibraryArtworkCache.image(from: customBytes))
|
||||
XCTAssertEqual(image.width, 640); XCTAssertLessThanOrEqual(image.height, 640)
|
||||
let customAsset = try XCTUnwrap(entry.release(in: directory).assets.first { $0.kind == "cover" })
|
||||
XCTAssertEqual(customAsset.name, "Personal Cover Image")
|
||||
try SoftwareLibraryLocalAsset.validate(customAsset, url: customURL, maximumBytes: 2 * 1024 * 1024)
|
||||
let customPreview = try await store.previewCover(entry)
|
||||
XCTAssertEqual(customPreview, try PersonalCoverImage.prepare(customBytes))
|
||||
try await store.update(entry, coverPNG: secondPNG)
|
||||
reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
|
||||
XCTAssertNotEqual(entry.selectedCoverFile?.path, custom.path)
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: customURL.path), "Prior cover assets remain recoverable.")
|
||||
entry.cover = .categoryIcon
|
||||
try await store.update(entry)
|
||||
reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
|
||||
XCTAssertEqual(entry.cover, .categoryIcon)
|
||||
let removedPreview = try await store.previewCover(entry)
|
||||
XCTAssertNil(removedPreview)
|
||||
XCTAssertTrue(entry.release(in: directory).assets.filter { $0.kind == "cover" }.isEmpty)
|
||||
XCTAssertEqual(entry.release(in: directory).assets.filter(\.isManual).map(\.name), ["README.txt"])
|
||||
entry.cover = .imported("A.png"); try await store.update(entry)
|
||||
reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
|
||||
XCTAssertEqual(entry.cover, .imported("A.png"))
|
||||
XCTAssertEqual(entry.packageSHA256, identity); XCTAssertEqual(entry.files.map(\.path), files)
|
||||
XCTAssertEqual(entry.receipt(in: directory).relativeFiles, files)
|
||||
XCTAssertEqual(try Data(contentsOf: working), savedProgram)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), Data([0x39,0x12,0x12,0x12]))
|
||||
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/A.png")), firstPNG)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/A.png")), firstPNG)
|
||||
XCTAssertEqual(try Data(contentsOf: first), firstPNG)
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: customURL.path))
|
||||
}
|
||||
func testPersonalCoverPendingSaveCancelAndLegacyEntryCompatibility() async throws {
|
||||
let source = try cartridge(), store = service(), image = try png()
|
||||
let art = root.appendingPathComponent("cover.png"); try image.write(to: art)
|
||||
let draft = try await store.inspect([source, art])
|
||||
let pending = try PersonalCoverImage.prepare(art)
|
||||
await store.cancel(draft.id)
|
||||
let cancelled = try await store.entries(); XCTAssertTrue(cancelled.isEmpty)
|
||||
do { _ = try await store.save(draft, coverPNG: pending); XCTFail("A canceled cover edit must not persist.") } catch { }
|
||||
XCTAssertEqual(try Data(contentsOf: art), image)
|
||||
let newDraft = try await store.inspect([source, art])
|
||||
let entry = try await store.save(newDraft, coverPNG: pending)
|
||||
guard case .custom = entry.cover else { return XCTFail("New imports can save their chosen local cover atomically.") }
|
||||
let directory = await store.directory(for: entry.id)
|
||||
XCTAssertEqual(entry.packageSHA256, newDraft.entry.packageSHA256)
|
||||
XCTAssertEqual(entry.files.map(\.path), newDraft.entry.files.map(\.path))
|
||||
// An actual pre-cover JSON record omits the optional key entirely.
|
||||
var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(entry)) as? [String: Any])
|
||||
json.removeValue(forKey: "cover")
|
||||
try JSONSerialization.data(withJSONObject: json).write(to: directory.appendingPathComponent("Entry.json"), options: .atomic)
|
||||
let restored = try await store.entries(), legacy = try XCTUnwrap(restored.first)
|
||||
XCTAssertNil(legacy.cover)
|
||||
XCTAssertEqual(legacy.release(in: directory).assets.filter { $0.kind == "cover" }.map(\.name), ["cover.png"])
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/cover.png")), image)
|
||||
}
|
||||
func testCoverInputsRejectCorruptOversizedAndUnsafeFiles() throws {
|
||||
let valid = try png(), selected = root.appendingPathComponent("selected.png")
|
||||
try valid.write(to: selected)
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(Data()))
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(Data("invalid image".utf8)))
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(Data(repeating: 0, count: 8 * 1024 * 1024 + 1)))
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(png(width: 16_385, height: 1)))
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(URL(string: "https://example.com/cover.png")!))
|
||||
let link = root.appendingPathComponent("link.png")
|
||||
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: selected)
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(link))
|
||||
XCTAssertThrowsError(try PersonalCoverImage.prepare(root))
|
||||
XCTAssertEqual(try Data(contentsOf: selected), valid)
|
||||
}
|
||||
func testCoverInvalidDescriptorsSymlinksAndStaleEditsPreserveSavedEntry() async throws {
|
||||
let source = try cartridge(), store = service(), image = try png()
|
||||
let draft = try await store.inspect([source]), entry = try await store.save(draft)
|
||||
let directory = await store.directory(for: entry.id), record = directory.appendingPathComponent("Entry.json")
|
||||
let before = try Data(contentsOf: record)
|
||||
do { try await store.update(entry, coverPNG: Data("corrupt".utf8)); XCTFail("Invalid replacement must be refused.") } catch { }
|
||||
var invalid = entry; invalid.cover = .imported("GAME.ccc")
|
||||
do { try await store.update(invalid); XCTFail("Media cannot be selected as an imported cover.") } catch { }
|
||||
for path in ["../outside.png", "PersonalCovers/../outside.png", "/outside.png", "PersonalCovers/not-a-uuid.png"] {
|
||||
invalid.cover = .custom(.init(path: path, sha256: String(repeating: "a", count: 64), byteSize: 10))
|
||||
do { try await store.update(invalid); XCTFail("Unsafe cover path must be refused: " + path) } catch { }
|
||||
}
|
||||
let assets = directory.appendingPathComponent("Assets"), outside = root.appendingPathComponent("Outside")
|
||||
try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
|
||||
try FileManager.default.createSymbolicLink(at: assets.appendingPathComponent("PersonalCovers"), withDestinationURL: outside)
|
||||
do { try await store.update(entry, coverPNG: image); XCTFail("The cover destination must not follow links.") } catch { }
|
||||
XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty)
|
||||
XCTAssertEqual(try Data(contentsOf: record), before)
|
||||
try FileManager.default.removeItem(at: assets.appendingPathComponent("PersonalCovers"))
|
||||
var external = entry; external.title = "Changed in another editor"
|
||||
try await store.update(external)
|
||||
let changed = try Data(contentsOf: record)
|
||||
do { try await store.update(entry, coverPNG: image); XCTFail("An older cover editor must not overwrite newer metadata.") } catch { }
|
||||
var staleRemoval = entry; staleRemoval.cover = .categoryIcon
|
||||
do { try await store.update(staleRemoval); XCTFail("Stale cover removal must be refused.") } catch { }
|
||||
XCTAssertEqual(try Data(contentsOf: record), changed)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: assets.appendingPathComponent("PersonalCovers").path))
|
||||
let recovered = try await store.entries(), current = try XCTUnwrap(recovered.first)
|
||||
try await store.update(current, coverPNG: image)
|
||||
let withCover = try await store.entries(), selected = try XCTUnwrap(withCover.first)
|
||||
let cover = try XCTUnwrap(selected.selectedCoverFile), coverURL = assets.appendingPathComponent(cover.path)
|
||||
let retained = try Data(contentsOf: coverURL), savedRecord = try Data(contentsOf: record)
|
||||
try FileManager.default.removeItem(at: coverURL)
|
||||
try FileManager.default.createSymbolicLink(at: coverURL, withDestinationURL: source)
|
||||
do { _ = try await store.previewCover(selected); XCTFail("Preview must refuse a linked asset.") } catch { }
|
||||
do { try await store.update(selected); XCTFail("Saving a linked selected asset must be refused.") } catch { }
|
||||
XCTAssertEqual(try Data(contentsOf: record), savedRecord)
|
||||
try FileManager.default.removeItem(at: coverURL); try retained.write(to: coverURL)
|
||||
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/GAME.ccc")), Data([0x39,0x12,0x12,0x12]))
|
||||
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
|
||||
}
|
||||
func testRelatedReferenceValidationAndPrivateCompanionBoundary() throws {
|
||||
let id = String(repeating: "a",count:64)
|
||||
let good = LibraryJSON.object(["id": .string("guide"), "title": .string("Example guide"), "document_id": .string(id), "sha256": .string(id), "role": .string("Hints"), "spoiler": .bool(true)])
|
||||
XCTAssertEqual(try SoftwareLibraryRelatedReference.parse(good).documentID,id)
|
||||
var bad = good.object; bad["page"] = .number(0)
|
||||
XCTAssertThrowsError(try SoftwareLibraryRelatedReference.parse(.object(bad)))
|
||||
bad = good.object; bad["sha256"] = .string(String(repeating:"b",count:64))
|
||||
XCTAssertThrowsError(try SoftwareLibraryRelatedReference.parse(.object(bad)))
|
||||
}
|
||||
}
|
||||
@@ -312,7 +312,8 @@ extension StartupTests {
|
||||
custom.media.cartridges!.physicalSlot=2
|
||||
try profileStore.save(custom)
|
||||
for launch in 0..<2 {
|
||||
let model = MachineModel(diskStore:f.disks,displayDefaults:defaults,inputStore:inputStore,startupStore:f.startup)
|
||||
let model = MachineModel(diskStore:f.disks,displayDefaults:defaults,inputStore:inputStore,startupStore:f.startup,
|
||||
inputControllerReadings: { [] })
|
||||
try await waitForStartup(model)
|
||||
if launch == 0 {
|
||||
await model.loadProfile(custom);XCTAssertNil(model.profileError);XCTAssertTrue(model.settings.use6309)
|
||||
@@ -321,7 +322,7 @@ extension StartupTests {
|
||||
XCTAssertNil(model.profileError);XCTAssertNil(model.fileError)
|
||||
XCTAssertEqual(model.settings,MachineSettings());XCTAssertEqual(model.state,.running)
|
||||
XCTAssertEqual(model.videoOutput,.composite);XCTAssertTrue(model.audioEnabled);XCTAssertEqual(model.volume,0.5)
|
||||
XCTAssertEqual(model.input.settings,InputSettings());XCTAssertFalse(model.tapeFast)
|
||||
XCTAssertEqual(model.input.settings,.freshDefaults);XCTAssertFalse(model.tapeFast)
|
||||
XCTAssertEqual(model.cartridgeAssignments,expected.media.cartridges)
|
||||
XCTAssertTrue(model.disks[0].mounted);XCTAssertFalse(model.disks[0].writeProtected);XCTAssertFalse(model.diskTemporary[0])
|
||||
XCTAssertTrue(model.disks.dropFirst().allSatisfy { !$0.mounted });XCTAssertFalse(model.hardDiskConnected)
|
||||
@@ -333,6 +334,37 @@ extension StartupTests {
|
||||
await withCheckedContinuation { done in model.shutdown { done.resume() } }
|
||||
}
|
||||
}
|
||||
@MainActor func testBuiltInProfilePreservesInputButPersonalProfileAndExplicitResetApplyTheirChoices() async throws {
|
||||
let f = try Fixture(); defer { f.remove() }
|
||||
let suite = "VCCInputProfile-" + UUID().uuidString, defaults = UserDefaults(suiteName: suite)!
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let inputStore = InputSettingsStore(url: f.support.appendingPathComponent("Input.json"))
|
||||
var configured = InputSettings()
|
||||
configured.right.source = .controller; configured.right.device = "remembered-disconnected"
|
||||
configured.right.rightStick = true; configured.right.fire1 = 4; configured.right.fire2 = 8
|
||||
configured.right.deadZone = 0.3; configured.right.interface = .tandy
|
||||
configured.left.source = .keyboard
|
||||
try inputStore.save(configured)
|
||||
let controller = VCCMachineController()
|
||||
let model = MachineModel(diskStore: f.disks, controller: controller, displayDefaults: defaults, inputStore: inputStore,
|
||||
startupStore: f.startup, inputControllerReadings: { [] }, restoreMediaOnLaunch: false)
|
||||
let loaded = await model.loadSystemProfile(.diskBasic)
|
||||
XCTAssertTrue(loaded); XCTAssertEqual(model.input.settings, configured)
|
||||
XCTAssertEqual(try inputStore.load(), configured)
|
||||
let snapshot = await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } }
|
||||
XCTAssertEqual(Int(snapshot.joystickInputs[0].mode), configured.right.interface.rawValue,
|
||||
"Preserving settings must also restore their interface to the newly loaded guest")
|
||||
var personal = try f.startup.appDefaults()
|
||||
personal.name = "Explicit personal input"; personal.input.right.source = .mouse
|
||||
personal.input.left.source = .keyboard; personal.sound = false
|
||||
await model.loadProfile(personal)
|
||||
XCTAssertNil(model.profileError); XCTAssertEqual(model.input.settings, personal.input)
|
||||
XCTAssertFalse(try inputStore.loadState().automaticRightController)
|
||||
let reset = await model.restoreAppDefaults()
|
||||
XCTAssertTrue(reset); XCTAssertEqual(model.input.settings, .freshDefaults)
|
||||
XCTAssertTrue(try inputStore.loadState().automaticRightController)
|
||||
await withCheckedContinuation { done in model.shutdown { done.resume() } }
|
||||
}
|
||||
@MainActor func testDefaultRestoreRefusesUnsavedDiskAndRecording() async throws {
|
||||
let f = try Fixture(); defer { f.remove() }
|
||||
let suite = "VCCDefaultGuards-" + UUID().uuidString, defaults = UserDefaults(suiteName:suite)!
|
||||
|
||||
@@ -85,6 +85,29 @@ static NSArray<NSDictionary *> *MCPBuildDiagnosticTools() {
|
||||
@"annotations":@{@"readOnlyHint":@YES,@"openWorldHint":@NO}}];
|
||||
}
|
||||
|
||||
static NSArray<NSDictionary *> *MCPPlaytestVideoTools() {
|
||||
NSDictionary *identifier = @{ @"type":@"string", @"minLength":@1, @"maxLength":@64 };
|
||||
NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, NSArray *, BOOL) =
|
||||
^NSDictionary *(NSString *name, NSString *description, NSDictionary *fields, NSArray *required, BOOL readOnly) {
|
||||
return @{ @"name":name, @"description":description,
|
||||
@"inputSchema":@{ @"type":@"object", @"properties":fields, @"required":required, @"additionalProperties":@NO },
|
||||
@"annotations":@{ @"readOnlyHint":@(readOnly), @"openWorldHint":@NO } };
|
||||
};
|
||||
return @[
|
||||
tool(@"start_playtest_video", @"Start a bounded MP4 recording of an owned disposable playtest's actual CoCo picture and optional generated CoCo audio. Does not advance execution: use ordinary playtest_input afterward. No microphone, Mac windows, personal emulator audio or capture UI cues are recorded. Maximum 3600 emulated fields (60 seconds), 64 MiB per clip, four clips and 256 MiB retained per run. Reuse an identical request_id on retry. Recordings end at their field/size limit with explicit truncation status; stop and retrieve the completed clip before restarting.",
|
||||
@{ @"run_id":identifier, @"request_id":identifier, @"include_audio":@{ @"type":@"boolean", @"default":@YES },
|
||||
@"max_fields":@{ @"type":@"integer", @"minimum":@1, @"maximum":@3600, @"default":@1800 } },
|
||||
@[@"run_id", @"request_id"], NO),
|
||||
tool(@"stop_playtest_video", @"Finish the current owned playtest recording without advancing the guest. Returns completed MP4 identity, byte count, SHA-256, actual field interval and truncation status. Retrying the identical request_id returns the same receipt. Remains available when ordinary mutation requests are exhausted; working files are retained if finalization fails.",
|
||||
@{ @"run_id":identifier, @"request_id":identifier }, @[@"run_id", @"request_id"], NO),
|
||||
tool(@"read_playtest_video", @"Read a completed MP4 belonging to this owned playtest in bounded base64 chunks. Assemble the chunks in offset order and verify the complete byte_count and SHA-256 from the receipt. Accepts only a clip_id returned by this run, never a host file path. Does not advance or change the guest.",
|
||||
@{ @"run_id":identifier, @"clip_id":identifier,
|
||||
@"offset":@{ @"type":@"integer", @"minimum":@0, @"maximum":@67108864, @"default":@0 },
|
||||
@"limit":@{ @"type":@"integer", @"minimum":@1, @"maximum":@65536, @"default":@65536 } },
|
||||
@[@"run_id", @"clip_id"], YES)
|
||||
];
|
||||
}
|
||||
|
||||
static NSArray<NSDictionary *> *MCPPlaytestAudioTools() {
|
||||
return @[@{@"name":@"capture_playtest_audio", @"description":@"Advance an owned disposable guest for 1 to 120 emulated fields and return its direct audio as PCM16 stereo WAV. Leaves the guest paused; verified stops can shorten the interval. Uses no microphone or personal emulator audio. Reuse request_id on retry to return the same clip without execution. Maximum 16 clips and 4 MiB retained WAV per run across boots; a maximum-clip allowance must remain before capture. Receipts include actual field interval, boot/run/artifact identity, sample count and SHA-256.",
|
||||
@"inputSchema":@{@"type":@"object", @"properties":@{
|
||||
|
||||
@@ -114,7 +114,7 @@ NSDictionary *hostCall(NSDictionary *grant, bool loopback, NSString *tool, NSDic
|
||||
Descriptor peer(socket(address->sa_family, SOCK_STREAM, 0));
|
||||
const bool playtestCall = [@[@"start_playtest", @"playtest_input", @"playtest_debug", @"capture_playtest",
|
||||
@"restart_playtest", @"stop_playtest", @"get_debug_snapshot", @"capture_playtest_graphics",
|
||||
@"exchange_playtest_media"] containsObject:tool];
|
||||
@"exchange_playtest_media", @"start_playtest_video", @"stop_playtest_video"] containsObject:tool];
|
||||
const auto deadline = Clock::now() + std::chrono::seconds(playtestCall ? 55 : 5);
|
||||
if (peer.fd < 0 || fcntl(peer.fd, F_SETFL, O_NONBLOCK) < 0) return @{@"error":@"host_unavailable"};
|
||||
if (connect(peer.fd, address, address->sa_len) != 0) {
|
||||
@@ -381,6 +381,23 @@ NSDictionary *handle(id message, NSDictionary *grant, bool loopback, NSArray *to
|
||||
}
|
||||
NSMutableDictionary *data = [reply[@"result"] mutableCopy];
|
||||
NSMutableArray *content = [NSMutableArray array];
|
||||
if ([name isEqual:@"read_playtest_video"]) {
|
||||
NSString *encoded = data[@"video_chunk_base64"], *hash = data[@"sha256"];
|
||||
if (!string(encoded) || encoded.length > 87384 || !string(hash) || hash.length != 64 ||
|
||||
[hash rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet]].location != NSNotFound ||
|
||||
![data[@"mime_type"] isEqual:@"video/mp4"] || ![data[@"clip_id"] isEqual:args[@"clip_id"]] ||
|
||||
!integer(data[@"offset"]) || !integer(data[@"next_offset"]) || !integer(data[@"byte_count"]) ||
|
||||
![data[@"eof"] isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)data[@"eof"]) != CFBooleanGetTypeID())
|
||||
return toolError(rid, @"invalid_playtest_video");
|
||||
NSData *chunk = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
|
||||
const long long offset = [data[@"offset"] longLongValue], next = [data[@"next_offset"] longLongValue], total = [data[@"byte_count"] longLongValue];
|
||||
const long long requestedOffset = args[@"offset"] ? [args[@"offset"] longLongValue] : 0;
|
||||
const NSUInteger limit = args[@"limit"] ? [args[@"limit"] unsignedIntegerValue] : 65536;
|
||||
if (!chunk || chunk.length > limit || chunk.length > 65536 || offset != requestedOffset || offset < 0 ||
|
||||
total < 1 || total > 67108864 || offset > total || next != offset + (long long)chunk.length || next > total ||
|
||||
[data[@"eof"] boolValue] != (next == total) || (!chunk.length && next < total))
|
||||
return toolError(rid, @"invalid_playtest_video");
|
||||
}
|
||||
if ([name isEqual:@"capture_playtest_audio"]) {
|
||||
NSString *encoded = data[@"audio_wav_base64"];
|
||||
if (!string(encoded) || !object(data[@"audio"])) return toolError(rid, @"invalid_playtest_audio");
|
||||
@@ -492,6 +509,10 @@ int main(int argc, char **argv) {
|
||||
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 &&
|
||||
[grant[@"playtest"] isEqual:@YES] && [grant[@"playtestAudio"] isEqual:@YES])
|
||||
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestAudioTools()];
|
||||
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 12 &&
|
||||
[grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
|
||||
[grant[@"playtestVideo"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestVideo"]) == CFBooleanGetTypeID())
|
||||
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestVideoTools()];
|
||||
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 10 && [grant[@"playtest"] isEqual:@YES] &&
|
||||
CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
|
||||
[grant[@"playtestCallContext"] isEqual:@YES] &&
|
||||
|
||||
@@ -93,6 +93,8 @@ def check(helper):
|
||||
result = {"result": active["playtest_graphics"]}
|
||||
if request["tool"] == "capture_playtest_audio" and "playtest_audio" in active:
|
||||
result = {"result": active["playtest_audio"]}
|
||||
if request["tool"] in ("start_playtest_video", "stop_playtest_video", "read_playtest_video") and "playtest_video" in active:
|
||||
result = {"result": active["playtest_video"]}
|
||||
if request["tool"] == "get_build_log" and "build_log" in active:
|
||||
result = {"result": active["build_log"]}
|
||||
if request["tool"] == "get_debug_snapshot" and "debug_snapshot" in active:
|
||||
@@ -788,6 +790,56 @@ def check(helper):
|
||||
assert refused["isError"] and not any(x["type"] == "audio" for x in refused["content"])
|
||||
del active["playtest_audio"]
|
||||
|
||||
video_tools = {"start_playtest_video", "stop_playtest_video", "read_playtest_video"}
|
||||
for kind, toolset, play, video in (("cmoc", 11, True, True), ("assembly", 12, True, True),
|
||||
("cmoc", 12, False, True), ("cmoc", 12, 1, True),
|
||||
("cmoc", 12, True, False), ("cmoc", 12, True, 1),
|
||||
("cmoc", 12, True, "yes"), ("cmoc", 12, True, True)):
|
||||
write_grant(kind=kind, toolset=toolset, playtest=play, playtestVideo=video, token=active["token"])
|
||||
with Client(helper, grant_file) as c:
|
||||
c.handshake("2025-11-25")
|
||||
catalog = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
|
||||
enabled = kind == "cmoc" and toolset >= 12 and play is True and video is True
|
||||
assert video_tools.intersection(catalog) == (video_tools if enabled else set())
|
||||
if not enabled:
|
||||
continue
|
||||
assert catalog["start_playtest_video"]["annotations"]["readOnlyHint"] is False
|
||||
assert catalog["stop_playtest_video"]["annotations"]["readOnlyHint"] is False
|
||||
assert catalog["read_playtest_video"]["annotations"]["readOnlyHint"] is True
|
||||
for tool in video_tools:
|
||||
assert catalog[tool]["inputSchema"]["additionalProperties"] is False
|
||||
active["playtest_video"] = {"run_id":"owned", "video_recording":{"status":"recording"}}
|
||||
for args in ({"run_id":"owned", "request_id":"begin"},
|
||||
{"run_id":"owned", "request_id":"begin", "include_audio":False, "max_fields":3600}):
|
||||
assert c.call("start_playtest_video", **args)["result"]["structuredContent"] == active["playtest_video"]
|
||||
assert c.call("stop_playtest_video", run_id="owned", request_id="end")["result"]["structuredContent"] == active["playtest_video"]
|
||||
count = len(active["requests"])
|
||||
for update in ({"max_fields":0}, {"max_fields":3601}, {"max_fields":True}, {"max_fields":1.5},
|
||||
{"include_audio":1}, {"include_audio":"yes"}, {"path":"/tmp/private"}):
|
||||
args = {"run_id":"owned", "request_id":"bad", **update}
|
||||
assert c.call("start_playtest_video", **args)["result"]["isError"], update
|
||||
assert c.call("stop_playtest_video",run_id="owned",request_id="bad",path="/tmp/private")["result"]["isError"]
|
||||
for update in ({"offset":-1}, {"offset":True}, {"offset":67108865}, {"limit":0},
|
||||
{"limit":65537}, {"limit":True}, {"path":"/tmp/private"}):
|
||||
assert c.call("read_playtest_video",run_id="owned",clip_id="clip",**update)["result"]["isError"], update
|
||||
assert count == len(active["requests"]), "Invalid video requests must never reach the host"
|
||||
payload = b"\x00\x00\x00\x18ftypmp42" + bytes(range(256)) * 255
|
||||
chunk = dict(run_id="owned", clip_id="clip", video_chunk_base64=base64.b64encode(payload).decode(),
|
||||
offset=0,next_offset=len(payload),byte_count=len(payload),eof=True,
|
||||
sha256=hashlib.sha256(payload).hexdigest(),mime_type="video/mp4")
|
||||
active["playtest_video"] = chunk
|
||||
result = c.call("read_playtest_video",run_id="owned",clip_id="clip")["result"]
|
||||
assert result["structuredContent"] == chunk
|
||||
assert json.loads(result["content"][0]["text"]) == chunk
|
||||
for update in ({"video_chunk_base64":"!"}, {"next_offset":len(payload)+1}, {"byte_count":67108865},
|
||||
{"offset":1}, {"eof":False}, {"sha256":"x"*64}, {"clip_id":"foreign"},
|
||||
{"mime_type":"audio/wav"}, {"video_chunk_base64":"", "next_offset":0}):
|
||||
active["playtest_video"] = {**chunk, **update}
|
||||
assert c.call("read_playtest_video",run_id="owned",clip_id="clip")["result"]["isError"], update
|
||||
active["playtest_video"] = {**chunk, "video_chunk_base64":"", "offset":len(payload), "next_offset":len(payload)}
|
||||
assert c.call("read_playtest_video",run_id="owned",clip_id="clip",offset=len(payload))["result"]["structuredContent"]["eof"] is True
|
||||
del active["playtest_video"]
|
||||
|
||||
write_grant(version=2, kind="archive", token=active["token"], canPropose=True, toolset=3)
|
||||
with Client(helper, grant_file) as c:
|
||||
c.handshake("2025-11-25")
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
|
||||
/// Only linked into the disposable helper. These waits never run in the Mac
|
||||
/// application's main actor or machine controller. The codec implementation is
|
||||
/// exactly the same bounded writer used by the native capture controls.
|
||||
@objc(VCCPlaytestVideoWriter)
|
||||
final class VCCPlaytestVideoWriter: NSObject {
|
||||
private let encoder: CoCoVideoEncoder
|
||||
private let directory: URL
|
||||
private let includeAudio: Bool
|
||||
private var sampleOffset: Int64 = 0
|
||||
|
||||
@objc init(directory: URL, includeAudio: Bool) throws {
|
||||
self.directory = directory; self.includeAudio = includeAudio
|
||||
encoder = try CoCoVideoEncoder(workingURL: directory.appendingPathComponent("Working.mov"))
|
||||
super.init()
|
||||
}
|
||||
|
||||
private final class Reply<T>: @unchecked Sendable {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
private let lock = NSLock()
|
||||
private var result: Result<T, Error>?
|
||||
func complete(_ result: Result<T, Error>) { lock.lock(); self.result = result; lock.unlock(); semaphore.signal() }
|
||||
func wait() throws -> T {
|
||||
guard semaphore.wait(timeout: .now() + 20) == .success else { throw CoCoRecordingError.message("The disposable video writer timed out.") }
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let result else { throw CoCoRecordingError.message("The disposable video writer returned no result.") }
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func appendPixels(_ pixels: Data, area: CGRect, samples: Data) throws {
|
||||
guard samples.count % 8 == 0, samples.count <= 16_384 * 8 else { throw CoCoRecordingError.message("Invalid disposable video audio interval.") }
|
||||
let frame = CoCoVideoFrame(pixels: pixels, area: area,
|
||||
audio: includeAudio ? samples : Data(count: samples.count), sampleOffset: sampleOffset)
|
||||
encoder.append([frame]); sampleOffset += Int64(samples.count / 8)
|
||||
let reply = Reply<Void>()
|
||||
encoder.whenDrained { reply.complete($0) }
|
||||
try reply.wait()
|
||||
}
|
||||
|
||||
@objc func finish() throws -> URL {
|
||||
let reply = Reply<URL>()
|
||||
encoder.finish { reply.complete($0) }
|
||||
let working = try reply.wait()
|
||||
let output = directory.appendingPathComponent("Clip.mp4")
|
||||
let exported = Reply<URL>()
|
||||
Task.detached {
|
||||
do { try await CoCoVideoEncoder.exportMP4(from: working, to: output); exported.complete(.success(output)) }
|
||||
catch { exported.complete(.failure(error)) }
|
||||
}
|
||||
let result = try exported.wait()
|
||||
// Conversion verifies playable tracks/duration before removing only our
|
||||
// known working file. Failures retain that file for explicit recovery.
|
||||
try FileManager.default.removeItem(at: working)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,16 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
// The class is implemented in Swift and shares CoCoVideoEncoder with the app.
|
||||
@interface VCCPlaytestVideoWriter : NSObject
|
||||
- (instancetype)initWithDirectory:(NSURL *)directory includeAudio:(BOOL)includeAudio error:(NSError **)error;
|
||||
- (BOOL)appendPixels:(NSData *)pixels area:(CGRect)area samples:(NSData *)samples error:(NSError **)error;
|
||||
- (NSURL *)finishAndReturnError:(NSError **)error;
|
||||
@end
|
||||
using namespace VCC::Mac;
|
||||
namespace {
|
||||
constexpr size_t wireLimit = 1024 * 1024;
|
||||
@@ -21,6 +28,7 @@ constexpr uint64_t fieldBudget = 216000;
|
||||
constexpr size_t maximumDiskBytes = 512 * 1024;
|
||||
constexpr unsigned audioFieldLimit = 120;
|
||||
constexpr size_t audioSampleFrameLimit = 131072;
|
||||
constexpr uint64_t videoByteLimit = 64 * 1024 * 1024;
|
||||
void little16(std::vector<uint8_t>& bytes, uint16_t value) {
|
||||
bytes.push_back(value & 255); bytes.push_back(value >> 8);
|
||||
}
|
||||
@@ -274,6 +282,55 @@ class Playtest {
|
||||
void armStop() { armEvidence(stops, stopModule); }
|
||||
void armInspection() { armEvidence({}, {}); }
|
||||
uint64_t consumed = 0, fieldClock = 0, bootNumber = 0, mediaGeneration = 0;
|
||||
VCCPlaytestVideoWriter *videoWriter = nil;
|
||||
NSMutableDictionary *videoInfo = nil;
|
||||
NSURL *videoDirectory = nil;
|
||||
unsigned videoMaximumFields = 0;
|
||||
uint64_t videoFirstField = 0, videoSamples = 0;
|
||||
void finishVideo(NSString *reason) {
|
||||
if (!videoWriter) return;
|
||||
NSError *error = nil;
|
||||
NSURL *output = nil;
|
||||
if (videoSamples) output = [videoWriter finishAndReturnError:&error];
|
||||
videoWriter = nil;
|
||||
videoInfo[@"field_end"] = @(fieldClock);
|
||||
videoInfo[@"fields_recorded"] = @(fieldClock - videoFirstField);
|
||||
videoInfo[@"sample_frames"] = @(videoSamples);
|
||||
videoInfo[@"truncated"] = @(![reason isEqual:@"stopped"] && ![reason isEqual:@"run_stopped"]);
|
||||
videoInfo[@"reason"] = reason;
|
||||
videoInfo[@"status"] = @"failed"; videoInfo[@"completed"] = @NO;
|
||||
if (!output) { videoInfo[@"error"] = error.localizedDescription ?: @"No emulated audio/video interval was recorded."; return; }
|
||||
NSData *data = [NSData dataWithContentsOfURL:output options:NSDataReadingMappedIfSafe error:&error];
|
||||
if (!data || data.length == 0 || data.length > videoByteLimit) {
|
||||
videoInfo[@"error"] = error.localizedDescription ?: @"playtest_video_byte_limit"; return;
|
||||
}
|
||||
std::vector<uint8_t> bytes(static_cast<const uint8_t *>(data.bytes), static_cast<const uint8_t *>(data.bytes) + data.length);
|
||||
videoInfo[@"status"] = @"complete"; videoInfo[@"completed"] = @YES;
|
||||
videoInfo[@"byte_count"] = @(data.length); videoInfo[@"sha256"] = sha256(bytes);
|
||||
videoInfo[@"mime_type"] = @"video/mp4"; videoInfo[@"filename"] = @"Clip.mp4";
|
||||
}
|
||||
void recordVideo(const std::vector<StereoSample>& samples) {
|
||||
if (!videoWriter || samples.empty()) return;
|
||||
const auto snapshot = machine->snapshot();
|
||||
const auto frame = snapshot.frame;
|
||||
if (!frame || frame->pixels.size() != Frame::width * Frame::height) {
|
||||
finishVideo(@"picture_unavailable"); return;
|
||||
}
|
||||
const auto area = frame->activeArea;
|
||||
NSError *error = nil;
|
||||
const BOOL ok = [videoWriter appendPixels:[NSData dataWithBytes:frame->pixels.data() length:frame->pixels.size() * sizeof(uint32_t)]
|
||||
area:CGRectMake(area.x, area.y, area.width, area.height)
|
||||
samples:[NSData dataWithBytes:samples.data() length:samples.size() * sizeof(StereoSample)] error:&error];
|
||||
if (!ok) {
|
||||
videoWriter = nil; videoInfo[@"status"] = @"failed"; videoInfo[@"completed"] = @NO;
|
||||
videoInfo[@"error"] = error.localizedDescription ?: @"playtest_video_writer_failed"; return;
|
||||
}
|
||||
videoSamples += samples.size();
|
||||
videoInfo[@"field_end"] = @(fieldClock); videoInfo[@"fields_recorded"] = @(fieldClock - videoFirstField);
|
||||
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:[videoDirectory URLByAppendingPathComponent:@"Working.mov"].path error:nil];
|
||||
if ([attributes fileSize] >= videoByteLimit - 1024 * 1024) finishVideo(@"byte_limit");
|
||||
else if (fieldClock - videoFirstField >= videoMaximumFields) finishVideo(@"field_limit");
|
||||
}
|
||||
Processor processor = Processor::MC6809;
|
||||
NSString *originalDiskHash = nil, *currentMediaID = nil;
|
||||
NSString *diskHash() const {
|
||||
@@ -332,8 +389,9 @@ class Playtest {
|
||||
if (consumed + n > fieldBudget) throw std::runtime_error("playtest_field_limit");
|
||||
for (unsigned i = 0; i < n && machine->snapshot().state == RunState::Running; ++i) {
|
||||
const auto before = machine->snapshot().frames;
|
||||
machine->advance(); machine->takeAudio(); ++consumed;
|
||||
machine->advance(); ++consumed;
|
||||
fieldClock += machine->snapshot().frames - before;
|
||||
auto samples = machine->takeAudio(); recordVideo(samples);
|
||||
}
|
||||
}
|
||||
void boot() {
|
||||
@@ -354,7 +412,7 @@ class Playtest {
|
||||
auto s = machine->snapshot();
|
||||
const bool hd6309 = s.configuration.processor == Processor::HD6309;
|
||||
const auto *image = floppy->image(0);
|
||||
return @{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809",
|
||||
NSMutableDictionary *out = [@{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809",
|
||||
@"execution_mode": hd6309 ? (s.cpu.IsNative6309 ? @"native" : @"emulation") : @"not_applicable",
|
||||
@"md_register": hd6309 ? (id)@(s.cpu.MD) : NSNull.null, @"ram_kb": @512,
|
||||
@"fields": @(fieldClock), @"field_clock": @(fieldClock), @"boot": @(bootNumber), @"machine_frame": @(s.frames),
|
||||
@@ -366,7 +424,9 @@ class Playtest {
|
||||
@"disk_present": @(image != nullptr), @"media_id": currentMediaID ?: (id)NSNull.null,
|
||||
@"media_generation": @(mediaGeneration), @"floppy_busy": @(floppy->snapshot().busy),
|
||||
@"disk_dirty": @(image && image->dirty()), @"disk_reads": @(floppy->readEvents(0)),
|
||||
@"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) };
|
||||
@"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) } mutableCopy];
|
||||
if (videoInfo) out[@"video_recording"] = [videoInfo copy];
|
||||
return out;
|
||||
}
|
||||
NSDictionary *capture() const {
|
||||
NSMutableDictionary *out = [status() mutableCopy];
|
||||
@@ -396,6 +456,7 @@ class Playtest {
|
||||
auto next = machine->takeAudio();
|
||||
if (next.size() > audioSampleFrameLimit - samples.size()) throw std::runtime_error("playtest_audio_limit");
|
||||
samples.insert(samples.end(), next.begin(), next.end());
|
||||
recordVideo(next);
|
||||
};
|
||||
// Discard audio from earlier input/steps. A capture owns only this
|
||||
// explicit interval, including any normal leave-breakpoint CPU slice.
|
||||
@@ -452,6 +513,19 @@ public:
|
||||
for (NSDictionary *item in declared) {
|
||||
if (![item isKindOfClass:NSDictionary.class] || ![item[@"id"] isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_modules");
|
||||
DebugBankedModule module; module.identifier = [item[@"id"] UTF8String];
|
||||
id overlayGroup = item[@"overlay_group"], overlayOwner = item[@"overlay_owner"];
|
||||
if (overlayGroup || overlayOwner) {
|
||||
if (![overlayGroup isKindOfClass:NSString.class] || ![overlayOwner isKindOfClass:NSString.class] ||
|
||||
![overlayGroup length] || ![overlayOwner length] ||
|
||||
[overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128 ||
|
||||
[overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128)
|
||||
throw std::invalid_argument("invalid_overlay_identity");
|
||||
const char *groupText = [overlayGroup UTF8String], *ownerText = [overlayOwner UTF8String];
|
||||
if (!groupText || !ownerText || std::strlen(groupText) != [overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] ||
|
||||
std::strlen(ownerText) != [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding])
|
||||
throw std::invalid_argument("invalid_overlay_identity");
|
||||
module.overlayGroup = groupText; module.overlayOwner = ownerText;
|
||||
}
|
||||
NSArray *pages = item[@"pages"], *guards = item[@"guards"];
|
||||
if (![pages isKindOfClass:NSArray.class] || pages.count == 0 || pages.count > 8 ||
|
||||
![guards isKindOfClass:NSArray.class] || guards.count == 0 || guards.count > 8192) throw std::invalid_argument("invalid_modules");
|
||||
@@ -543,6 +617,32 @@ public:
|
||||
return exportMedia();
|
||||
}
|
||||
if ([op isEqual:@"exchange_media"]) return exchangeMedia(r);
|
||||
if ([op isEqual:@"video_start"]) {
|
||||
if (r.count != 5 || ![r[@"clip_id"] isKindOfClass:NSString.class] ||
|
||||
![r[@"directory"] isKindOfClass:NSString.class] || !r[@"include_audio"] ||
|
||||
CFGetTypeID((__bridge CFTypeRef)r[@"include_audio"]) != CFBooleanGetTypeID()) throw std::invalid_argument("invalid_arguments");
|
||||
if (videoWriter) throw std::runtime_error("playtest_video_active");
|
||||
NSUUID *identifier = [[NSUUID alloc] initWithUUIDString:r[@"clip_id"]];
|
||||
NSURL *directory = [NSURL fileURLWithPath:r[@"directory"] isDirectory:YES];
|
||||
if (!identifier || ![directory.lastPathComponent isEqual:identifier.UUIDString] ||
|
||||
![NSFileManager.defaultManager fileExistsAtPath:directory.path]) throw std::invalid_argument("invalid_arguments");
|
||||
videoMaximumFields = number(r[@"max_fields"], 1, 3600);
|
||||
NSError *error = nil;
|
||||
videoWriter = [[VCCPlaytestVideoWriter alloc] initWithDirectory:directory includeAudio:[r[@"include_audio"] boolValue] error:&error];
|
||||
if (!videoWriter) throw std::runtime_error((error.localizedDescription ?: @"playtest_video_start_failed").UTF8String);
|
||||
videoDirectory = directory; videoFirstField = fieldClock; videoSamples = 0;
|
||||
machine->takeAudio();
|
||||
videoInfo = [@{@"clip_id":identifier.UUIDString, @"status":@"recording", @"include_audio":r[@"include_audio"],
|
||||
@"max_fields":@(videoMaximumFields), @"field_start":@(fieldClock), @"field_end":@(fieldClock),
|
||||
@"fields_recorded":@0, @"completed":@NO, @"truncated":@NO, @"boot":@(bootNumber),
|
||||
@"ui_cues_included":@NO, @"microphone_included":@NO, @"host_audio_included":@NO} mutableCopy];
|
||||
return status();
|
||||
}
|
||||
if ([op isEqual:@"video_stop"]) {
|
||||
if (r.count != 1 || !videoInfo) throw std::runtime_error("playtest_video_unavailable");
|
||||
finishVideo(@"stopped");
|
||||
NSMutableDictionary *out = [status() mutableCopy]; out[@"video"] = [videoInfo copy]; return out;
|
||||
}
|
||||
if ([op isEqual:@"input"]) {
|
||||
if (r.count != 2) throw std::invalid_argument("invalid_arguments");
|
||||
unsigned total = 0;
|
||||
@@ -563,6 +663,7 @@ public:
|
||||
applied = machine->resumeWithInput(step.keys, step.joysticks);
|
||||
const auto advanced = machine->snapshot().frames - before.frames;
|
||||
fieldClock += advanced; consumed += advanced;
|
||||
auto samples = machine->takeAudio(); recordVideo(samples);
|
||||
if (advanced > step.fields) throw std::runtime_error("playtest_input_timing");
|
||||
} else {
|
||||
machine->setKeyboard(step.keys);
|
||||
@@ -621,15 +722,16 @@ public:
|
||||
return out;
|
||||
}
|
||||
if ([op isEqual:@"restart"]) {
|
||||
if (videoWriter) throw std::runtime_error("playtest_video_active: stop the recording before restarting");
|
||||
if (floppy->snapshot().busy) throw std::runtime_error("disk_busy");
|
||||
boot(); return status();
|
||||
}
|
||||
if ([op isEqual:@"continue"]) { armInspection(); machine->resume(); return status(); }
|
||||
if ([op isEqual:@"continue"]) { armInspection(); const auto before = machine->snapshot().frames; machine->resume(); fieldClock += machine->snapshot().frames - before; auto samples = machine->takeAudio(); recordVideo(samples); return status(); }
|
||||
if ([op isEqual:@"pause"]) { machine->releaseInputs(); machine->pause(); return status(); }
|
||||
if ([op isEqual:@"step"]) {
|
||||
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
|
||||
const auto before = machine->snapshot().frames;
|
||||
machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; return status();
|
||||
machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; auto samples = machine->takeAudio(); recordVideo(samples); return status();
|
||||
}
|
||||
if ([op isEqual:@"stop_at"]) {
|
||||
if (modules.empty() && flatGuards.empty()) throw std::runtime_error("unverified_stop");
|
||||
@@ -643,7 +745,8 @@ public:
|
||||
}
|
||||
armEvidence({nextPoint}, nextModule);
|
||||
stops = {nextPoint}; stopModule = nextModule;
|
||||
machine->resume(); return status();
|
||||
const auto before = machine->snapshot().frames; machine->resume(); fieldClock += machine->snapshot().frames - before;
|
||||
auto samples = machine->takeAudio(); recordVideo(samples); return status();
|
||||
}
|
||||
if ([op isEqual:@"debug"]) {
|
||||
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
|
||||
@@ -658,6 +761,7 @@ public:
|
||||
out[@"registers"] = registers;
|
||||
out[@"mapping_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerMappingFingerprint];
|
||||
out[@"program_revision"] = @(machine->snapshot().debuggerProgramRevision);
|
||||
out[@"residency_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerResidencyFingerprint];
|
||||
out[@"attached"] = @(machine->snapshot().debuggerDevelopmentAttached);
|
||||
out[@"paused"] = @YES;
|
||||
out[@"logical_memory"] = [[NSData dataWithBytes:d.memory.data() length:d.memory.size()] base64EncodedStringWithOptions:0];
|
||||
@@ -684,7 +788,9 @@ public:
|
||||
}
|
||||
if ([op isEqual:@"stop"]) {
|
||||
machine->releaseInputs(); machine->pause();
|
||||
finishVideo(@"run_stopped");
|
||||
NSMutableDictionary *out = [status() mutableCopy];
|
||||
if (videoInfo) out[@"video"] = [videoInfo copy];
|
||||
if (const auto *image = floppy->image(0)) {
|
||||
const auto& disk = image->bytes();
|
||||
out[@"disk_base64"] = [[NSData dataWithBytes:disk.data() length:disk.size()] base64EncodedStringWithOptions:0];
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import AppKit
|
||||
import CryptoKit
|
||||
import AVFoundation
|
||||
|
||||
// Run using the VCCUITests scheme: its separate app identity and mandatory
|
||||
// authored fixture keep personal ROMs, media, profiles and sessions untouched.
|
||||
@@ -11,6 +13,9 @@ final class InteractionTests: XCTestCase {
|
||||
private var diskEditorFixtureFolder: URL?
|
||||
private var projectSetupFixtureFolder: URL?
|
||||
private var audioGameFixtureFolder: URL?
|
||||
private var captureFixtureFolder: URL?
|
||||
private var coverFixtureFolder: URL?
|
||||
private var continuityFixtureFolder: URL?
|
||||
private var originalClipboard: [NSPasteboardItem]?
|
||||
private var main: XCUIElement { app.windows["VCC UI Tests"] }
|
||||
private var display: XCUIElement { main.descendants(matching: .any)["coco-display"].firstMatch }
|
||||
@@ -87,6 +92,27 @@ final class InteractionTests: XCTestCase {
|
||||
return true
|
||||
}
|
||||
app.launchArguments = ["-ApplePersistenceIgnoreState", "YES", "-NSQuitAlwaysKeepsWindows", "NO"]
|
||||
if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") {
|
||||
try requireFullManualEdition()
|
||||
let token = UUID().uuidString
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityRelaunch-" + token)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
|
||||
try token.write(to: folder.appendingPathComponent("fixture-owner"), atomically: true, encoding: .utf8)
|
||||
continuityFixtureFolder = folder
|
||||
app.launchEnvironment["VCC_CONTINUITY_TEST_ROOT"] = folder.path
|
||||
}
|
||||
if name.contains("testPersonalLibraryCover") {
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCoverUI-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
|
||||
coverFixtureFolder = folder
|
||||
app.launchEnvironment["VCC_COVER_DRAG_TRACE"] = folder.appendingPathComponent("drag-trace.txt").path
|
||||
app.launchEnvironment["VCC_COVER_DRAG_SOURCE"] = folder.appendingPathComponent("Blue Cover.png").path
|
||||
}
|
||||
if name.contains("testCoCoCapture") {
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCaptureUI-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
|
||||
captureFixtureFolder = folder; app.launchEnvironment["VCC_CAPTURE_TEST_DIRECTORY"] = folder.path
|
||||
}
|
||||
if name.contains("CompactOS9") { app.launchArguments.append("--disk-editor-compact-fixture") }
|
||||
if name.contains("testDiskImageEditor") {
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
@@ -120,17 +146,36 @@ final class InteractionTests: XCTestCase {
|
||||
let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
.deletingLastPathComponent().deletingLastPathComponent()
|
||||
let store = repo.appendingPathComponent("media/knowledge-base")
|
||||
let index = store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite")
|
||||
// Match normal packaging: prefer the prepared local index and avoid
|
||||
// touching the optional external research volume during UI setup.
|
||||
let localIndex = repo.appendingPathComponent("media/app-inputs/archive-library/ArchiveLibrary.sqlite")
|
||||
let index = FileManager.default.fileExists(atPath: localIndex.path) ? localIndex :
|
||||
store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite")
|
||||
try XCTSkipUnless(FileManager.default.fileExists(atPath: index.path), "Stage the local Archive Library index.")
|
||||
let cache = FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveReader-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: false)
|
||||
archiveCache = cache
|
||||
func seed(_ relative: String, as filename: String) throws {
|
||||
let original = store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative)
|
||||
// Stage optional retained originals before launching XCTest when
|
||||
// the research store is on a removable volume. File access in
|
||||
// setUp must not wait indefinitely on an unseen system prompt.
|
||||
let staged = repo.appendingPathComponent(".build/archive-ui-fixtures").appendingPathComponent(relative)
|
||||
let original = FileManager.default.fileExists(atPath: staged.path) ? staged :
|
||||
store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative)
|
||||
try XCTSkipUnless(FileManager.default.fileExists(atPath: original.path), "Stage the Archive fixture " + relative)
|
||||
try FileManager.default.copyItem(at: original, to: cache.appendingPathComponent(filename))
|
||||
let data = try Data(contentsOf: original)
|
||||
XCTAssertEqual(SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(),
|
||||
(filename as NSString).deletingPathExtension, "Retained fixture must match the indexed original")
|
||||
try data.write(to: cache.appendingPathComponent(filename), options: .atomic)
|
||||
}
|
||||
if name.contains("testArchiveLibraryBrowsesTextAndImageInline") {
|
||||
if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") {
|
||||
try seed("Magazines/MOTD/MOTD 1986 04.pdf", as: "917d4da1916fd14cd89f20da6fea5474e807a16e723f05055231992e430e6d33.pdf")
|
||||
try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png",
|
||||
as: "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5.png")
|
||||
app.launchArguments += ["-archive-library.collection", "Walkthroughs/Sierra Games"]
|
||||
} else if name.contains("testArchiveLibraryRelatedReferenceFromSoftware") {
|
||||
try seed("Walkthroughs/Raaka-Tu Walkthrough (Tandy).txt", as: "e55b30ce36985c0ff35ade23152828e090014bae1b8ddcadd50b02b90f72c7dc.txt")
|
||||
} else if name.contains("testArchiveLibraryBrowsesTextAndImageInline") {
|
||||
try seed("Walkthroughs/Sierra Games/AGI Quest I Walkthrough (Juha Terho).txt",
|
||||
as: "563a8fe2ba0e251227fb05c1ac6a4bfe965bc3e124bb91547f8bae493adab68a.txt")
|
||||
try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png",
|
||||
@@ -200,6 +245,13 @@ final class InteractionTests: XCTestCase {
|
||||
if let diskEditorFixtureFolder { try? FileManager.default.removeItem(at: diskEditorFixtureFolder) }
|
||||
if let projectSetupFixtureFolder { try? FileManager.default.removeItem(at: projectSetupFixtureFolder) }
|
||||
if let audioGameFixtureFolder { try? FileManager.default.removeItem(at: audioGameFixtureFolder) }
|
||||
if let captureFixtureFolder { try? FileManager.default.removeItem(at: captureFixtureFolder) }
|
||||
if let coverFixtureFolder { try? FileManager.default.removeItem(at: coverFixtureFolder) }
|
||||
if let continuityFixtureFolder {
|
||||
let suite = continuityFixtureFolder.lastPathComponent
|
||||
UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
|
||||
try? FileManager.default.removeItem(at: continuityFixtureFolder)
|
||||
}
|
||||
}
|
||||
if let app, app.state != .notRunning {
|
||||
if (testRun?.failureCount ?? 0) > 0 {
|
||||
@@ -4550,3 +4602,480 @@ extension InteractionTests {
|
||||
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
|
||||
}
|
||||
}
|
||||
|
||||
extension InteractionTests {
|
||||
func testCoCoCaptureHeaderScreenshotTimerAndMovie() async throws {
|
||||
let before = session()
|
||||
let root = try XCTUnwrap(captureFixtureFolder)
|
||||
let documents = root.appendingPathComponent("Documents", isDirectory: true)
|
||||
func files(_ dir: URL, _ ext: String) -> [URL] {
|
||||
((try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []).filter { $0.pathExtension == ext && !$0.lastPathComponent.hasPrefix(".") }
|
||||
}
|
||||
func waitFor(_ predicate: @escaping () -> Bool, seconds: TimeInterval = 12) {
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in predicate() }, object: nil)], timeout: seconds), .completed)
|
||||
}
|
||||
let camera = main.buttons["capture-now"], record = main.buttons["capture-record"]
|
||||
let options = main.menuButtons["capture-options"]
|
||||
func choose(_ label: String) {
|
||||
options.click()
|
||||
let item = app.menuItems[label].firstMatch
|
||||
XCTAssertTrue(item.waitForExistence(timeout: 3)); item.click()
|
||||
}
|
||||
XCTAssertTrue(camera.waitForExistence(timeout: 5)); XCTAssertTrue(record.exists)
|
||||
camera.click(); waitFor { files(root,"png").count == 1 }
|
||||
let png = try XCTUnwrap(files(root,"png").first)
|
||||
let picture = try XCTUnwrap(NSImage(contentsOf: png))
|
||||
XCTAssertLessThanOrEqual(picture.size.width, 640); XCTAssertLessThanOrEqual(picture.size.height, 480)
|
||||
XCTAssertGreaterThan(picture.size.width, 200)
|
||||
choose("10 Seconds")
|
||||
let cancel = main.buttons["capture-countdown-cancel"]
|
||||
XCTAssertFalse(cancel.exists, "Changing the timer must not start a capture")
|
||||
XCTAssertEqual(files(root,"png").count, 1)
|
||||
camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3)); cancel.click()
|
||||
XCTAssertFalse(cancel.exists); XCTAssertEqual(files(root,"png").count, 1)
|
||||
choose("5 Seconds")
|
||||
XCTAssertFalse(cancel.exists, "Only the camera performs a capture")
|
||||
camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3))
|
||||
waitFor({ files(root,"png").count == 2 }, seconds: 10)
|
||||
choose("None")
|
||||
choose("Documents")
|
||||
// The chooser changes the one shared destination only on confirmation.
|
||||
choose("Other Location…")
|
||||
let chooser = app.windows["Save Screenshots and Videos To"]
|
||||
XCTAssertTrue(chooser.waitForExistence(timeout: 4))
|
||||
chooser.buttons["Cancel"].click()
|
||||
camera.click(); waitFor { files(documents,"png").count == 1 }
|
||||
XCTAssertEqual(files(root,"png").count, 2)
|
||||
choose("Include CoCo Audio in Video")
|
||||
record.click()
|
||||
waitFor { record.label == "Stop Recording" }
|
||||
// Take another image while video is active. Its shutter is host-only.
|
||||
camera.click(); waitFor { files(documents,"png").count == 2 }
|
||||
choose("Include CoCo Audio in Video") // Changes the next recording only.
|
||||
let deadline = Date().addingTimeInterval(1.2)
|
||||
waitFor { Date() >= deadline }
|
||||
record.click()
|
||||
waitFor({ files(documents,"mp4").count == 1 }, seconds: 20)
|
||||
let movie = try XCTUnwrap(files(documents,"mp4").first)
|
||||
XCTAssertGreaterThan(try movie.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0, 1000)
|
||||
let asset = AVURLAsset(url: movie)
|
||||
let tracks = try await asset.loadTracks(withMediaType: .audio)
|
||||
let track = try XCTUnwrap(tracks.first)
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
|
||||
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
|
||||
reader.add(output); XCTAssertTrue(reader.startReading())
|
||||
var peak: Float = 0, samples = 0
|
||||
while let sample = output.copyNextSampleBuffer() {
|
||||
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
|
||||
var data = Data(count: CMBlockBufferGetDataLength(buffer))
|
||||
XCTAssertEqual(data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) }, noErr)
|
||||
data.withUnsafeBytes { raw in
|
||||
for value in raw.bindMemory(to: Float.self) { peak = max(peak, abs(value)); samples += 1 }
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(samples, 0)
|
||||
XCTAssertLessThan(peak, 0.00001, "Local start/shutter cues must not leak into the silent video")
|
||||
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
|
||||
XCTAssertGreaterThan(session()[1], before[1])
|
||||
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
|
||||
let shot = XCTAttachment(screenshot: main.screenshot()); shot.name = "Shared capture controls"; shot.lifetime = .keepAlways; add(shot)
|
||||
}
|
||||
}
|
||||
|
||||
extension InteractionTests {
|
||||
func testArchiveLibraryAndManualsResumeAcrossProcessRelaunch() throws {
|
||||
let fixture = try XCTUnwrap(continuityFixtureFolder)
|
||||
let stateFile = fixture.appendingPathComponent("LibraryContinuity.json")
|
||||
func state() -> [String: Any] {
|
||||
guard let data = try? Data(contentsOf: stateFile),
|
||||
let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] }
|
||||
return object
|
||||
}
|
||||
func waitUntil(_ description: String, _ condition: @escaping () -> Bool) {
|
||||
let predicate = NSPredicate { _, _ in condition() }
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 12), .completed, description)
|
||||
}
|
||||
func reading(_ key: String) -> [String: Any] { (state()["reading"] as? [String: [String: Any]])?[key] ?? [:] }
|
||||
func bookmarks() -> [[String: Any]] { state()["bookmarks"] as? [[String: Any]] ?? [] }
|
||||
func capture(_ window: XCUIElement, _ title: String) {
|
||||
let image = XCTAttachment(screenshot: window.screenshot()); image.name = title; image.lifetime = .keepAlways; add(image)
|
||||
}
|
||||
func relaunch() {
|
||||
app.activate()
|
||||
app.typeKey("q", modifierFlags: .command)
|
||||
waitUntil("The first isolated process must quit before launching its successor") { self.app.state == .notRunning }
|
||||
app.launch()
|
||||
XCTAssertTrue(main.waitForExistence(timeout: 15))
|
||||
waitUntil("The successor process must finish its authored machine startup") {
|
||||
self.main.buttons["execution"].label == "Pause" && self.main.links["FD0 Authored FD0.dsk"].exists
|
||||
}
|
||||
}
|
||||
menu("Media", "Software Library…")
|
||||
let software = app.windows["Software Library"]
|
||||
XCTAssertTrue(software.buttons["library-scope-all"].waitForExistence(timeout: 10))
|
||||
software.buttons["library-scope-all"].click()
|
||||
let softwareSearch = software.descendants(matching: .any)["library-search"].firstMatch
|
||||
softwareSearch.click(); app.typeText("Raaka-Tu")
|
||||
let game = software.buttons["library-title-486dda54b9351ac926c382f70f328aa5"]
|
||||
XCTAssertTrue(game.waitForExistence(timeout: 10)); game.click()
|
||||
waitUntil("Software title and search must reach the continuity file") {
|
||||
let browse = (state()["browse"] as? [String: [String: Any]])?["software-main"]
|
||||
return browse?["selectedID"] as? String == "486dda54b9351ac926c382f70f328aa5"
|
||||
}
|
||||
|
||||
menu("Help", "Archive Library…")
|
||||
let archive = app.windows["Archive Library"]
|
||||
let map = archive.descendants(matching: .any)["archive-browse-list"].firstMatch.staticTexts["King's Quest I Map (Sierra)"]
|
||||
XCTAssertTrue(map.waitForExistence(timeout: 10)); map.click()
|
||||
XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10))
|
||||
archive.buttons["Zoom in"].click()
|
||||
let mapID = "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5"
|
||||
waitUntil("Archive image zoom must be checkpointed") { (reading("archive:" + mapID)["zoom"] as? Double ?? 0) > 1 }
|
||||
let mapZoom = try XCTUnwrap(reading("archive:" + mapID)["zoom"] as? Double)
|
||||
capture(archive, "Archive map before process relaunch")
|
||||
|
||||
menu("Help", "Manual Library…")
|
||||
let manual = app.windows["Manual Library"]
|
||||
func follow(_ title: String) {
|
||||
let link = manual.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
|
||||
XCTAssertTrue(link.waitForExistence(timeout: 10), title); link.click()
|
||||
}
|
||||
let firstBook = "meet-your-color-computer", secondBook = "back-at-the-coco"
|
||||
func readAndBookmark(_ book: String) {
|
||||
let chapter = book + (book == firstBook ? "/meet-the-machine.html" : "/familiar-hardware.html")
|
||||
waitUntil("The selected chapter must finish loading") {
|
||||
reading("manual-last")["relativePath"] as? String == chapter && manual.buttons["manual.bookmark-location"].isEnabled
|
||||
}
|
||||
manual.webViews.firstMatch.scroll(byDeltaX: 0, deltaY: -600)
|
||||
waitUntil("Scrolling must record a reading position") {
|
||||
let position = reading("manual-book:" + book)
|
||||
return (position["offset"] as? Double ?? 0) > 0.001 || position["anchor"] as? String != nil
|
||||
}
|
||||
let bookmark = manual.buttons["manual.bookmark-location"]
|
||||
XCTAssertTrue(bookmark.isEnabled); bookmark.click()
|
||||
waitUntil("A bookmark in each book must be saved") { bookmarks().contains { $0["bookID"] as? String == book } }
|
||||
}
|
||||
follow("Open the first book"); follow("Start reading"); readAndBookmark(firstBook)
|
||||
manual.buttons["manual.home"].click()
|
||||
follow("Open Back at the CoCo"); follow("Start reading"); readAndBookmark(secondBook)
|
||||
let firstPosition = reading("manual-book:" + firstBook), secondPosition = reading("manual-book:" + secondBook)
|
||||
let firstMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == firstBook }?["id"] as? String)
|
||||
let secondMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == secondBook }?["id"] as? String)
|
||||
XCTAssertEqual(bookmarks().count, 2)
|
||||
capture(manual, "Second manual before process relaunch")
|
||||
relaunch()
|
||||
|
||||
menu("Media", "Software Library…")
|
||||
XCTAssertTrue(game.waitForExistence(timeout: 10))
|
||||
XCTAssertEqual(softwareSearch.value as? String, "Raaka-Tu")
|
||||
XCTAssertTrue(software.links["library-reference-02587e81cceaec9ac0c11fe9"].waitForExistence(timeout: 10), "The selected software detail must resume")
|
||||
capture(software, "Software selection and search after process relaunch")
|
||||
menu("Help", "Archive Library…")
|
||||
XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10), "The selected browse image must resume")
|
||||
XCTAssertTrue(archive.buttons["Fit Image"].isEnabled, "The image must retain its zoom")
|
||||
XCTAssertEqual(reading("archive:" + mapID)["zoom"] as? Double, mapZoom)
|
||||
let archiveSearch = archive.textFields["archive-search"]
|
||||
archiveSearch.click(); app.typeText("MOTD strip buffer")
|
||||
let result = archive.outlines["archive-results-list"].descendants(matching: .outlineRow).containing(.staticText, identifier: "PDF page 12").firstMatch
|
||||
XCTAssertTrue(result.waitForExistence(timeout: 10)); result.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click()
|
||||
let pdfPage = archive.textFields["PDF page number"]
|
||||
waitUntil("The selected search result must show its cited page") { pdfPage.value as? String == "12" }
|
||||
capture(archive, "Archive search before second process relaunch")
|
||||
menu("Help", "Manual Library…")
|
||||
waitUntil("The last active manual must resume") { reading("manual-last")["documentID"] as? String == secondBook && manual.buttons["manual.bookmark-location"].isEnabled }
|
||||
XCTAssertEqual(reading("manual-last")["relativePath"] as? String, secondPosition["relativePath"] as? String)
|
||||
XCTAssertEqual(reading("manual-last")["anchor"] as? String, secondPosition["anchor"] as? String)
|
||||
manual.buttons["manual.bookmarks"].click()
|
||||
manual.radioButtons["All Books"].click()
|
||||
let firstEntry = manual.buttons["manual.bookmark-open-" + firstMark]
|
||||
let secondEntry = manual.buttons["manual.bookmark-open-" + secondMark]
|
||||
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertTrue(secondEntry.exists)
|
||||
capture(manual, "Two-book bookmarks after process relaunch")
|
||||
// This journey verifies native scope actions and persistence. Focused
|
||||
// keyboard/VoiceOver operation is qualified separately; clicking a Mac
|
||||
// radio button alone does not establish keyboard focus for arrow keys.
|
||||
manual.radioButtons["This Book"].click()
|
||||
waitUntil("This Book must show only the active book's bookmark") { !firstEntry.exists && secondEntry.exists }
|
||||
manual.radioButtons["All Books"].click()
|
||||
waitUntil("All Books must show both saved bookmarks") { firstEntry.exists && secondEntry.exists }
|
||||
firstEntry.click()
|
||||
waitUntil("Explicit bookmark navigation must win over second-book resume") { reading("manual-last")["documentID"] as? String == firstBook }
|
||||
XCTAssertEqual(reading("manual-last")["anchor"] as? String, firstPosition["anchor"] as? String)
|
||||
manual.buttons["manual.bookmarks"].click()
|
||||
manual.radioButtons["This Book"].click()
|
||||
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists)
|
||||
firstEntry.click()
|
||||
relaunch()
|
||||
menu("Help", "Archive Library…")
|
||||
XCTAssertEqual(archiveSearch.value as? String, "MOTD strip buffer")
|
||||
waitUntil("The selected PDF search page must survive the second process relaunch") { pdfPage.value as? String == "12" }
|
||||
capture(archive, "Archive search and cited page after process relaunch")
|
||||
menu("Help", "Manual Library…")
|
||||
waitUntil("The explicit first-book visit must become the new automatic resume") { reading("manual-last")["documentID"] as? String == firstBook && manual.buttons["manual.bookmark-location"].isEnabled }
|
||||
manual.buttons["manual.bookmarks"].click()
|
||||
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists)
|
||||
manual.radioButtons["All Books"].click(); XCTAssertTrue(secondEntry.exists)
|
||||
XCTAssertEqual(bookmarks().count, 2)
|
||||
capture(manual, "First manual and saved bookmark filter after second relaunch")
|
||||
}
|
||||
|
||||
func testManualLibraryBookmarksAndWindowResume() throws {
|
||||
try requireFullManualEdition()
|
||||
menu("Help", "Manual Library…")
|
||||
let reader = app.windows["Manual Library"]
|
||||
XCTAssertTrue(reader.waitForExistence(timeout: 8))
|
||||
for title in ["Open the first book", "Start reading"] {
|
||||
let link = reader.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
|
||||
XCTAssertTrue(link.waitForExistence(timeout: 8)); link.click()
|
||||
}
|
||||
let bookmark = reader.buttons["manual.bookmark-location"]
|
||||
let ready = NSPredicate { _, _ in bookmark.exists && bookmark.isEnabled }
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 8), .completed)
|
||||
bookmark.click(); reader.buttons["manual.bookmarks"].click()
|
||||
let entry = reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).firstMatch
|
||||
XCTAssertTrue(entry.waitForExistence(timeout: 5))
|
||||
reader.radioButtons["All Books"].click(); XCTAssertTrue(entry.exists)
|
||||
reader.radioButtons["This Book"].click(); XCTAssertTrue(entry.exists)
|
||||
let shot = XCTAttachment(screenshot: reader.screenshot()); shot.name = "Manual bookmarks — one list with filters"; shot.lifetime = .keepAlways; add(shot)
|
||||
entry.click()
|
||||
reader.buttons["manual.bookmark-location"].click() // recognizes the existing entry
|
||||
XCTAssertTrue(entry.waitForExistence(timeout: 5))
|
||||
XCTAssertEqual(reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).count, 1)
|
||||
entry.click()
|
||||
reader.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
|
||||
menu("Help", "Manual Library…")
|
||||
XCTAssertTrue(reader.buttons["manual.bookmark-location"].waitForExistence(timeout: 5))
|
||||
reader.buttons["manual.bookmarks"].click(); XCTAssertTrue(entry.waitForExistence(timeout: 5))
|
||||
}
|
||||
|
||||
func testSoftwareLibraryPersonalImportPreservesGuest() throws {
|
||||
let before = session()
|
||||
menu("Media", "Software Library…")
|
||||
let library = app.windows["Software Library"]
|
||||
XCTAssertTrue(library.waitForExistence(timeout: 8))
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let source = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk")
|
||||
let original = try Data(contentsOf: source)
|
||||
library.buttons["library-scope-personal"].click()
|
||||
let addButton = library.buttons["library-personal-add"]
|
||||
let addFirst = library.buttons["library-personal-add-first"]
|
||||
XCTAssertTrue(addButton.waitForExistence(timeout: 5))
|
||||
XCTAssertTrue(addFirst.waitForExistence(timeout: 5))
|
||||
addFirst.click()
|
||||
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
|
||||
app.buttons["Cancel"].click()
|
||||
XCTAssertTrue(addButton.waitForExistence(timeout: 5))
|
||||
addButton.click()
|
||||
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
|
||||
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(source.path); app.typeKey(.return, modifierFlags: [])
|
||||
app.buttons["Review Files"].click()
|
||||
let field = library.textFields["personal-title"]
|
||||
XCTAssertTrue(field.waitForExistence(timeout: 8)); field.click(); app.typeKey("a", modifierFlags: .command); app.typeText("Private Library UI Example")
|
||||
let category = library.popUpButtons["personal-category"]
|
||||
XCTAssertTrue(category.exists); XCTAssertEqual(category.value as? String, "Other")
|
||||
category.click(); app.menuItems["Games"].click()
|
||||
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Add Personal Software — review before import"; shot.lifetime = .keepAlways; add(shot)
|
||||
library.buttons["personal-save"].click()
|
||||
let title = library.staticTexts["Private Library UI Example"].firstMatch
|
||||
XCTAssertTrue(title.waitForExistence(timeout: 10))
|
||||
XCTAssertTrue(library.buttons["library-scope-personal"].exists)
|
||||
XCTAssertTrue(addButton.exists, "Add Software stays available after the first import")
|
||||
XCTAssertFalse(addFirst.exists, "A populated library must not show the first-item invitation")
|
||||
let search = library.descendants(matching: .any)["library-search"].firstMatch
|
||||
search.click(); app.typeText("No such personal title 370")
|
||||
let clear = library.buttons["library-empty-clear-search"]
|
||||
XCTAssertTrue(clear.waitForExistence(timeout: 5))
|
||||
XCTAssertFalse(addButton.exists, "The header search opens global results, outside the private-only browse scope")
|
||||
XCTAssertFalse(addFirst.exists, "A filtered library is not an empty personal collection")
|
||||
clear.click()
|
||||
library.buttons["library-scope-getting-started"].click()
|
||||
search.click(); app.typeText("Private Library UI Example")
|
||||
let personalCard = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-personal:")).firstMatch
|
||||
XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "Global search must find a private game from Getting Started")
|
||||
XCTAssertTrue(personalCard.label.contains("Personal"))
|
||||
library.buttons["Clear search"].click()
|
||||
library.buttons["library-type-Games"].click()
|
||||
XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "The standard Games category includes the private game")
|
||||
let grouped = XCTAttachment(screenshot: library.screenshot()); grouped.name = "Unified Games — Personal Library before Catalog"; grouped.lifetime = .keepAlways; add(grouped)
|
||||
library.radioButtons["Table"].click()
|
||||
let table = library.outlines["Software titles"]
|
||||
XCTAssertTrue(table.waitForExistence(timeout: 5))
|
||||
table.scroll(byDeltaX: 0, deltaY: 1200)
|
||||
let tableShot = XCTAttachment(screenshot: library.screenshot()); tableShot.name = "Unified Games — Table Personal badge"; tableShot.lifetime = .keepAlways; add(tableShot)
|
||||
let firstRow = table.outlineRows.element(boundBy: 0)
|
||||
let badge = firstRow.descendants(matching: .any)["library-personal-badge"].firstMatch
|
||||
XCTAssertTrue(badge.waitForExistence(timeout: 5), "The first table row visibly identifies the personal entry")
|
||||
XCTAssertFalse(addButton.exists, "Other categories keep personal import in Library Actions")
|
||||
XCTAssertEqual(try Data(contentsOf: source), original)
|
||||
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
|
||||
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
|
||||
}
|
||||
|
||||
func testPersonalLibraryCoverChooserCancelDropAndRemovePreserveGuest() throws {
|
||||
try personalCoverJourney(includeDrop: true)
|
||||
}
|
||||
func testPersonalLibraryCoverChooserCancelAndRemovePreserveGuest() throws {
|
||||
try personalCoverJourney(includeDrop: false)
|
||||
}
|
||||
private func personalCoverJourney(includeDrop: Bool) throws {
|
||||
let manualDrag = includeDrop && ProcessInfo.processInfo.environment["VCC_UI_MANUAL_COVER_DRAG"] == "1"
|
||||
var manualFinderWindow: XCUIElement?
|
||||
defer {
|
||||
if let window = manualFinderWindow, window.exists,
|
||||
window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists {
|
||||
window.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
|
||||
}
|
||||
}
|
||||
let before = session()
|
||||
let folder = try XCTUnwrap(coverFixtureFolder)
|
||||
defer { try? FileManager.default.removeItem(at: folder) }
|
||||
func image(_ color: NSColor, name: String) throws -> URL {
|
||||
let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 320, pixelsHigh: 200,
|
||||
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
|
||||
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
|
||||
color.setFill(); NSBezierPath(rect: NSRect(x: 0, y: 0, width: 320, height: 200)).fill()
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
let url = folder.appendingPathComponent(name)
|
||||
try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: url)
|
||||
return url
|
||||
}
|
||||
let red = try image(.red, name: "Red Cover.png"), blue = try image(.blue, name: "Blue Cover.png")
|
||||
let redBytes = try Data(contentsOf: red), blueBytes = try Data(contentsOf: blue)
|
||||
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
|
||||
let disk = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk"), diskBytes = try Data(contentsOf: disk)
|
||||
menu("Media", "Software Library…")
|
||||
let library = app.windows["Software Library"]
|
||||
XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-personal"].click()
|
||||
library.buttons["library-personal-add"].click()
|
||||
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
|
||||
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(disk.path); app.typeKey(.return, modifierFlags: [])
|
||||
app.buttons["Review Files"].click()
|
||||
XCTAssertTrue(library.buttons["personal-save"].waitForExistence(timeout: 8)); library.buttons["personal-save"].click()
|
||||
let cover = library.descendants(matching: .any)["library-personal-cover"].firstMatch
|
||||
XCTAssertTrue(cover.waitForExistence(timeout: 8))
|
||||
func choose(_ url: URL, prompt: String) {
|
||||
XCTAssertTrue(app.buttons[prompt].waitForExistence(timeout: 5))
|
||||
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(url.path); app.typeKey(.return, modifierFlags: [])
|
||||
app.buttons[prompt].click()
|
||||
}
|
||||
func matches(_ element: XCUIElement, red: Bool) -> Bool {
|
||||
guard element.exists, let pixels = NSBitmapImageRep(data: element.screenshot().pngRepresentation),
|
||||
let color = pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2)?.usingColorSpace(.deviceRGB) else { return false }
|
||||
// Native display captures carry the monitor's color transform;
|
||||
// verify the authored dominant channel rather than raw PNG bytes.
|
||||
return red ? color.redComponent > 0.7 && color.redComponent - max(color.greenComponent, color.blueComponent) > 0.4
|
||||
: color.blueComponent > 0.7 && color.blueComponent - max(color.greenComponent, color.redComponent) > 0.4
|
||||
}
|
||||
func waitForColor(_ element: XCUIElement, red: Bool, timeout: TimeInterval = 15) {
|
||||
let expectation = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in matches(element, red: red) }, object: nil)
|
||||
let result = XCTWaiter.wait(for: [expectation], timeout: timeout)
|
||||
if result != .completed {
|
||||
let screenshot = element.screenshot()
|
||||
let attachment = XCTAttachment(screenshot: screenshot); attachment.name = "Cover pixel assertion"; attachment.lifetime = .keepAlways; add(attachment)
|
||||
if let pixels = NSBitmapImageRep(data: screenshot.pngRepresentation) {
|
||||
print("Cover screenshot \(pixels.pixelsWide)x\(pixels.pixelsHigh), center \(String(describing: pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2))), frame \(element.frame)")
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(result, .completed)
|
||||
}
|
||||
library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Choose Cover Image…"].click()
|
||||
choose(red, prompt: "Use Image"); waitForColor(cover, red: true)
|
||||
library.buttons["Edit Details…"].click()
|
||||
let chooseDraft = library.buttons["personal-cover-choose"]
|
||||
XCTAssertTrue(chooseDraft.waitForExistence(timeout: 5))
|
||||
let preview = library.descendants(matching: .any)["personal-cover-preview"].firstMatch
|
||||
let form = library.sheets.firstMatch.scrollViews.firstMatch
|
||||
for _ in 0..<6 where !form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame) {
|
||||
form.scroll(byDeltaX: 0, deltaY: -180)
|
||||
}
|
||||
XCTAssertTrue(form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame), "Inspect the complete preview inside the form viewport")
|
||||
chooseDraft.click(); choose(blue, prompt: "Choose Image")
|
||||
waitForColor(preview, red: false)
|
||||
let editorShot = XCTAttachment(screenshot: library.screenshot()); editorShot.name = "Personal cover — draft image preview"; editorShot.lifetime = .keepAlways; add(editorShot)
|
||||
library.sheets.firstMatch.buttons["Cancel"].click(); waitForColor(cover, red: true)
|
||||
|
||||
if includeDrop {
|
||||
app.activate()
|
||||
// The authored native source starts an actual NSDraggingSession with
|
||||
// a file URL. It never calls the destination handler or changes model
|
||||
// state; the normal decoder/store/render path must produce blue pixels.
|
||||
let source = library.descendants(matching: .any)["personal-cover-drag-source"].firstMatch
|
||||
XCTAssertTrue(source.waitForExistence(timeout: 5))
|
||||
let pasteboardGeneration = NSPasteboard(name: .drag).changeCount
|
||||
if manualDrag {
|
||||
let finder = XCUIApplication(bundleIdentifier: "com.apple.finder")
|
||||
finder.activate(); finder.typeKey("n", modifierFlags: .command)
|
||||
finder.typeKey("g", modifierFlags: [.command, .shift]); finder.typeText(folder.path); finder.typeKey(.return, modifierFlags: [])
|
||||
let window = finder.windows[folder.lastPathComponent]
|
||||
XCTAssertTrue(window.waitForExistence(timeout: 8))
|
||||
manualFinderWindow = window
|
||||
print("VCC_COVER_MANUAL_DRAG_READY: Drag Blue Cover.png from Finder onto the red cover in Software Library")
|
||||
fflush(stdout)
|
||||
let delivered = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
|
||||
let log = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? ""
|
||||
return log.contains("perform file-count=1") && matches(cover, red: false)
|
||||
}, object: nil)
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [delivered], timeout: 180), .completed)
|
||||
} else {
|
||||
source.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).press(forDuration: 0.25,
|
||||
thenDragTo: cover.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)), withVelocity: .slow, thenHoldForDuration: 1)
|
||||
}
|
||||
XCTAssertGreaterThan(NSPasteboard(name: .drag).changeCount, pasteboardGeneration)
|
||||
XCTAssertTrue(NSPasteboard(name: .drag).types?.contains(.fileURL) == true)
|
||||
let trace = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? "No native drag events"
|
||||
print("Native cover drag: " + trace)
|
||||
XCTAssertTrue(trace.contains("perform file-count=1"))
|
||||
if !manualDrag { app.activate(); waitForColor(cover, red: false) }
|
||||
let shot = XCTAttachment(screenshot: cover.screenshot()); shot.name = "Personal cover — native file drop replacement"; shot.lifetime = .keepAlways; add(shot)
|
||||
}
|
||||
if let window = manualFinderWindow, window.exists,
|
||||
window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists {
|
||||
window.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
|
||||
manualFinderWindow = nil
|
||||
app.activate()
|
||||
}
|
||||
library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Remove Cover"].click()
|
||||
let removed = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in cover.label.hasSuffix(" category cover") }, object: nil)
|
||||
XCTAssertEqual(XCTWaiter.wait(for: [removed], timeout: 10), .completed)
|
||||
XCTAssertFalse(matches(cover, red: true)); XCTAssertFalse(matches(cover, red: false))
|
||||
XCTAssertEqual(try Data(contentsOf: red), redBytes); XCTAssertEqual(try Data(contentsOf: blue), blueBytes)
|
||||
XCTAssertEqual(try Data(contentsOf: disk), diskBytes)
|
||||
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
|
||||
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
|
||||
}
|
||||
|
||||
func testArchiveLibraryRelatedReferenceFromSoftware() throws {
|
||||
let before = session()
|
||||
menu("Media", "Software Library…")
|
||||
let library = app.windows["Software Library"]
|
||||
XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-all"].click()
|
||||
let search = library.descendants(matching: .any)["library-search"].firstMatch
|
||||
search.click(); app.typeText("Raaka-Tu")
|
||||
let game = library.buttons["library-title-486dda54b9351ac926c382f70f328aa5"]
|
||||
XCTAssertTrue(game.waitForExistence(timeout: 8)); game.click()
|
||||
let referenceID = "library-reference-02587e81cceaec9ac0c11fe9"
|
||||
let link = library.links[referenceID]
|
||||
XCTAssertTrue(link.waitForExistence(timeout: 8))
|
||||
let detail = library.scrollViews.containing(.link, identifier: referenceID).firstMatch
|
||||
func guideVisible() -> Bool {
|
||||
// macOS can report clipped content beneath the fixed footer as
|
||||
// hittable. Require the complete link inside its actual viewport.
|
||||
let frame = link.frame
|
||||
return !frame.isEmpty && link.isHittable && detail.frame.insetBy(dx: 10, dy: 18).contains(frame)
|
||||
}
|
||||
for _ in 0..<8 where !guideVisible() { detail.scroll(byDeltaX: 0, deltaY: -250) }
|
||||
XCTAssertTrue(guideVisible(), "Scroll the entire guide action clear of the fixed footer before opening it")
|
||||
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Software Library — Raaka-Tu Guides & References"; shot.lifetime = .keepAlways; add(shot)
|
||||
link.click()
|
||||
let archive = app.windows["Archive Library"]
|
||||
let text = archive.textViews["archive-inline-text"]
|
||||
XCTAssertTrue(text.waitForExistence(timeout: 10)); XCTAssertGreaterThan((text.value as? String ?? "").count, 100)
|
||||
XCTAssertEqual(text.label, "Raaka-Tu Walkthrough (Tandy)", "The loaded reader must identify the exact linked document")
|
||||
let readerShot = XCTAttachment(screenshot: archive.screenshot()); readerShot.name = "Archive Library — linked Raaka-Tu walkthrough"; readerShot.lifetime = .keepAlways; add(readerShot)
|
||||
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
|
||||
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,39 @@
|
||||
};
|
||||
"objectVersion" = 56;
|
||||
"objects" = {
|
||||
"2464EE6BFE2AA97DBC5C2913" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/CoCoCaptureFeedback.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"E4061E4E0AB7CA7A47624B27" = { isa = PBXBuildFile; fileRef = "2464EE6BFE2AA97DBC5C2913"; };
|
||||
"337343EA275BED13114792F9" = { isa = PBXBuildFile; fileRef = "2464EE6BFE2AA97DBC5C2913"; };
|
||||
"DC1C21A297BCCD34706DBEE1" = { isa = PBXFileReference; lastKnownFileType = folder; path = "Resources/CaptureSounds"; sourceTree = SOURCE_ROOT; };
|
||||
"B7A7B5BFA3C251D22DC8561A" = { isa = PBXBuildFile; fileRef = "DC1C21A297BCCD34706DBEE1"; };
|
||||
"17CB263DB27EF1128FBF12D4" = { isa = PBXBuildFile; fileRef = "DC1C21A297BCCD34706DBEE1"; };
|
||||
|
||||
"CCF46B90050E0BE77D1F5FAA" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/CoCoVideoBudgetTests.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"9944B924F1F25A1C31E87133" = { isa = PBXBuildFile; fileRef = "CCF46B90050E0BE77D1F5FAA"; };
|
||||
"C3DEFD6B0A505C9AA2ADEB3B" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/CoCoCaptureTests.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"03B7230E381C6D102C3BF95F" = { isa = PBXBuildFile; fileRef = "C3DEFD6B0A505C9AA2ADEB3B"; };
|
||||
"971F1C3D34CF84F153F037EC" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/SoftwareLibraryPersonalTests.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"F97715060F4E2618EB80AFDE" = { isa = PBXBuildFile; fileRef = "971F1C3D34CF84F153F037EC"; };
|
||||
|
||||
"FFA296F39D044DC70C6FCFB7" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/CoCoCapture.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"2921AED78693AE35B29C2B88" = { isa = PBXBuildFile; fileRef = "FFA296F39D044DC70C6FCFB7"; };
|
||||
"F770A2E6626B73FE7071CB9A" = { isa = PBXBuildFile; fileRef = "FFA296F39D044DC70C6FCFB7"; };
|
||||
"386691BEF25A11E0954243CD" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/CoCoVideoEncoder.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"F69F722FBCDDA97A8FB48C96" = { isa = PBXBuildFile; fileRef = "386691BEF25A11E0954243CD"; };
|
||||
"A1DC73569D936F22FB4E554E" = { isa = PBXBuildFile; fileRef = "386691BEF25A11E0954243CD"; };
|
||||
"C9DF7704560822DA03677397" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/LibraryContinuity.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"31E94EDA2FFA2E36C43113B4" = { isa = PBXBuildFile; fileRef = "C9DF7704560822DA03677397"; };
|
||||
"6229E570150FBFD4653A4E38" = { isa = PBXBuildFile; fileRef = "C9DF7704560822DA03677397"; };
|
||||
"F75B630AE8D4162CD9E45A75" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/SoftwareLibraryPersonal.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"77B510203B32A69B19F95BAF" = { isa = PBXBuildFile; fileRef = "F75B630AE8D4162CD9E45A75"; };
|
||||
"B07B7E2C92770E75D506BABD" = { isa = PBXBuildFile; fileRef = "F75B630AE8D4162CD9E45A75"; };
|
||||
"9EA2B6271ECBBEC8E2BE5A67" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/SoftwareLibraryPersonalView.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"AF8FCAD6F87C7AAA1B8398AF" = { isa = PBXBuildFile; fileRef = "9EA2B6271ECBBEC8E2BE5A67"; };
|
||||
"6EB73875746CB21BDF3E7AB3" = { isa = PBXBuildFile; fileRef = "9EA2B6271ECBBEC8E2BE5A67"; };
|
||||
"A1009AA9F3239FF614E22103" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/LibraryContinuityTests.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"A8BC07BAEA1215B7503E9364" = { isa = PBXBuildFile; fileRef = "A1009AA9F3239FF614E22103"; };
|
||||
"1893D6FB6CB3BF8A429B887C" = { isa = PBXGroup; name = "3.7.0 Libraries and Capture"; sourceTree = "<group>"; children = ("2464EE6BFE2AA97DBC5C2913","DC1C21A297BCCD34706DBEE1","CCF46B90050E0BE77D1F5FAA","C3DEFD6B0A505C9AA2ADEB3B","971F1C3D34CF84F153F037EC", "FFA296F39D044DC70C6FCFB7","386691BEF25A11E0954243CD","C9DF7704560822DA03677397","F75B630AE8D4162CD9E45A75","9EA2B6271ECBBEC8E2BE5A67","A1009AA9F3239FF614E22103" ); };
|
||||
|
||||
"8BB8CC2C6D97EC712B6F9399" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.swift"; "path" = "Tests/SoftwareLibraryPublishedGameTests.swift"; "sourceTree" = "<group>"; };
|
||||
"2716C73C955C5C8E0B2B6C1A" = { "isa" = "PBXBuildFile"; "fileRef" = "8BB8CC2C6D97EC712B6F9399"; };
|
||||
"1A6A84C4CFAE563E14CE3FF0" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.swift"; "path" = "App/SoftwareLibrarySourceImporter.swift"; "sourceTree" = "<group>"; };
|
||||
@@ -190,16 +223,20 @@ DE524C5CEEB7201C899C173E = { isa = PBXBuildFile; fileRef = 2DDBE7F7A3DE72AD67CB6
|
||||
"CB17E83394A9C5DF26C5FFF1" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.swift"; "path" = "App/MCPPlaytest.swift"; "sourceTree" = "<group>"; };
|
||||
"05C12D61D4309FF67ECD44D8" = { "isa" = "PBXBuildFile"; "fileRef" = "CB17E83394A9C5DF26C5FFF1"; };
|
||||
"F59D1FEA561570A5236F53C0" = { "isa" = "PBXBuildFile"; "fileRef" = "CB17E83394A9C5DF26C5FFF1"; };
|
||||
|
||||
"B1E09D51DE234384B03D6D01" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tools/Playtest/VideoWriter.swift"; sourceTree = SOURCE_ROOT; };
|
||||
"B1E09D51DE234384B03D6D02" = { isa = PBXBuildFile; fileRef = "B1E09D51DE234384B03D6D01"; };
|
||||
"B1E09D51DE234384B03D6D03" = { isa = PBXBuildFile; fileRef = "386691BEF25A11E0954243CD"; };
|
||||
"D481BB9B31A0A44756A2C642" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.cpp.objcpp"; "path" = "Tools/Playtest/main.mm"; "sourceTree" = "<group>"; };
|
||||
"2CA37FF7143467180924EC4A" = { "isa" = "PBXFileReference"; "explicitFileType" = "compiled.mach-o.executable"; "path" = "vcc-playtest"; "sourceTree" = "BUILT_PRODUCTS_DIR"; };
|
||||
"D0275CCCC6A237EF6D400FB5" = { "isa" = "PBXBuildFile"; "fileRef" = "D481BB9B31A0A44756A2C642"; };
|
||||
"E4D502132B13D1D69821BEC7" = { "isa" = "PBXBuildFile"; "fileRef" = "BB79E6426D224A59088F8FC5"; };
|
||||
"D889C482CF734BE1E411EACC" = { "isa" = "PBXSourcesBuildPhase"; "buildActionMask" = 2147483647; "files" = ( "D0275CCCC6A237EF6D400FB5" ); "runOnlyForDeploymentPostprocessing" = 0; };
|
||||
"D889C482CF734BE1E411EACC" = { "isa" = "PBXSourcesBuildPhase"; "buildActionMask" = 2147483647; "files" = ( "D0275CCCC6A237EF6D400FB5", "B1E09D51DE234384B03D6D02", "B1E09D51DE234384B03D6D03" ); "runOnlyForDeploymentPostprocessing" = 0; };
|
||||
"96EC2DA93CC1D27E9CE71ECB" = { "isa" = "PBXFrameworksBuildPhase"; "buildActionMask" = 2147483647; "files" = ( "E4D502132B13D1D69821BEC7" ); "runOnlyForDeploymentPostprocessing" = 0; };
|
||||
"B26398CF1C4055136A0E5AD8" = { "isa" = "PBXTargetDependency"; "target" = "3289BA136C1065982C4C284C"; };
|
||||
"2F408F2A78A3A02A06B97DE3" = { "isa" = "XCBuildConfiguration"; "name" = "Debug"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; };
|
||||
"62FEB1115C3993DF5AE98912" = { "isa" = "XCBuildConfiguration"; "name" = "Release"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; };
|
||||
"BB186D2F0C21A9CDDC88F589" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; };
|
||||
"2F408F2A78A3A02A06B97DE3" = { "isa" = "XCBuildConfiguration"; "name" = "Debug"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SWIFT_VERSION" = "5.0"; "SWIFT_STRICT_CONCURRENCY" = "minimal"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; };
|
||||
"62FEB1115C3993DF5AE98912" = { "isa" = "XCBuildConfiguration"; "name" = "Release"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SWIFT_VERSION" = "5.0"; "SWIFT_STRICT_CONCURRENCY" = "minimal"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; };
|
||||
"BB186D2F0C21A9CDDC88F589" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SWIFT_VERSION" = "5.0"; "SWIFT_STRICT_CONCURRENCY" = "minimal"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; };
|
||||
"CC5600E33F7749FAC3723D73" = { "isa" = "XCConfigurationList"; "buildConfigurations" = ( "2F408F2A78A3A02A06B97DE3", "62FEB1115C3993DF5AE98912", "BB186D2F0C21A9CDDC88F589" ); "defaultConfigurationIsVisible" = 0; "defaultConfigurationName" = "Release"; };
|
||||
"3F1A4FB64B04593F884782C9" = { "isa" = "PBXNativeTarget"; "name" = "vcc-playtest"; "productName" = "vcc-playtest"; "productReference" = "2CA37FF7143467180924EC4A"; "productType" = "com.apple.product-type.tool"; "buildConfigurationList" = "CC5600E33F7749FAC3723D73"; "buildPhases" = ( "D889C482CF734BE1E411EACC", "96EC2DA93CC1D27E9CE71ECB" ); "buildRules" = (); "dependencies" = ( "B26398CF1C4055136A0E5AD8" ); };
|
||||
"2807D2B83250A4DAA977771A" = { "isa" = "PBXTargetDependency"; "target" = "3F1A4FB64B04593F884782C9"; };
|
||||
@@ -657,7 +694,7 @@ DE524C5CEEB7201C899C173E = { isa = PBXBuildFile; fileRef = 2DDBE7F7A3DE72AD67CB6
|
||||
"CEEB1C09197841D54A6AD5E8" = { "isa" = "PBXBuildFile"; "fileRef" = "2ECB4508563F3873B436B9EE"; };
|
||||
"3AE8BC7E4A8F296EB0B7AEFD" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "folder"; "path" = "Resources/About"; "sourceTree" = "<group>"; };
|
||||
"370CBA86395A91DC191231AB" = { "isa" = "PBXBuildFile"; "fileRef" = "3AE8BC7E4A8F296EB0B7AEFD"; };
|
||||
"53AAABD74B976C180137280A" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "INFOPLIST_KEY_VCCCompanionProtocolVersion" = "1"; "COPY_PHASE_STRIP" = "NO"; "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" ); "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG VCC_UI_TESTING"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.6.2"; "INFOPLIST_FILE" = "App/Info.plist"; "ENABLE_TESTABILITY" = "YES"; "GENERATE_INFOPLIST_FILE" = "YES"; "ENABLE_USER_SCRIPT_SANDBOXING" = "NO"; "SWIFT_OBJC_BRIDGING_HEADER" = "$(SRCROOT)/Bridge/VCCMac-Bridging-Header.h"; "INFOPLIST_KEY_CFBundleDisplayName" = "VCC OSS UI Tests"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "PRODUCT_NAME" = "VCC Plus OSS"; "PRODUCT_MODULE_NAME" = "VCCMac"; "OTHER_LDFLAGS" = "$(inherited) -larchive -framework Network"; "INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment"; "PRODUCT_BUNDLE_IDENTIFIER" = "com.brianholman.vccplus.oss.mac.uitesting"; "CURRENT_PROJECT_VERSION" = "60"; }; };
|
||||
"53AAABD74B976C180137280A" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "INFOPLIST_KEY_VCCCompanionProtocolVersion" = "1"; "COPY_PHASE_STRIP" = "NO"; "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" ); "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG VCC_UI_TESTING"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.7.0"; "INFOPLIST_FILE" = "App/Info.plist"; "ENABLE_TESTABILITY" = "YES"; "GENERATE_INFOPLIST_FILE" = "YES"; "ENABLE_USER_SCRIPT_SANDBOXING" = "NO"; "SWIFT_OBJC_BRIDGING_HEADER" = "$(SRCROOT)/Bridge/VCCMac-Bridging-Header.h"; "INFOPLIST_KEY_CFBundleDisplayName" = "VCC OSS UI Tests"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "PRODUCT_NAME" = "VCC Plus OSS"; "PRODUCT_MODULE_NAME" = "VCCMac"; "OTHER_LDFLAGS" = "$(inherited) -larchive -framework Network"; "INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment"; "PRODUCT_BUNDLE_IDENTIFIER" = "com.brianholman.vccplus.oss.mac.uitesting"; "CURRENT_PROJECT_VERSION" = "63"; }; };
|
||||
"4478F567020A87952E7BF5BE" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG"; "PRODUCT_NAME" = "VCCCore"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "SKIP_INSTALL" = "YES"; "ENABLE_TESTABILITY" = "YES"; "EXECUTABLE_PREFIX" = "lib"; "GCC_PREPROCESSOR_DEFINITIONS" = ( "$(inherited)", "USE_DEBUG_TESTS=false" ); }; };
|
||||
"6E5C730B0C1F6F8D5EB8881A" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "ONLY_ACTIVE_ARCH" = "NO"; "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "CLANG_ENABLE_MODULES" = "YES"; "CODE_SIGN_IDENTITY" = "-"; "MACOSX_DEPLOYMENT_TARGET" = "14.0"; "CLANG_CXX_LANGUAGE_STANDARD" = "c++17"; "ENABLE_TESTABILITY" = "YES"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "ARCHS" = "$(ARCHS_STANDARD)"; "HEADER_SEARCH_PATHS" = ( "$(inherited)", "$(SRCROOT)/../../src/core", "$(SRCROOT)/../../src" ); "SDKROOT" = "macosx"; "SWIFT_VERSION" = "5.0"; "CODE_SIGN_STYLE" = "Manual"; "DEVELOPMENT_TEAM" = ""; "VCC_BUILD_CONTENT_PROFILE" = "source"; "CLANG_ENABLE_OBJC_ARC" = "YES"; "CLANG_CXX_LIBRARY" = "libc++"; }; };
|
||||
"9D61CCD0757A3005AF102148" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "$(PLATFORM_DIR)/Developer/Library/Frameworks" ); "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "ENABLE_TESTABILITY" = "YES"; "GENERATE_INFOPLIST_FILE" = "YES"; "SWIFT_OBJC_BRIDGING_HEADER" = "$(SRCROOT)/Bridge/VCCMac-Bridging-Header.h"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "PRODUCT_NAME" = "VCCCoreTests"; "OTHER_LDFLAGS" = ( "$(inherited)", "-larchive", "-framework", "Network", "-framework", "XCTest" ); "FRAMEWORK_SEARCH_PATHS" = ( "$(inherited)", "$(PLATFORM_DIR)/Developer/Library/Frameworks" ); "PRODUCT_BUNDLE_IDENTIFIER" = "com.brianholman.vccplus.oss.mac.coretests"; "GCC_PREPROCESSOR_DEFINITIONS" = ( "$(inherited)", "DEBUG=1" ); }; };
|
||||
@@ -1591,7 +1628,7 @@ DE524C5CEEB7201C899C173E = { isa = PBXBuildFile; fileRef = 2DDBE7F7A3DE72AD67CB6
|
||||
"FEE92F734ED030D5B7F43539" = {
|
||||
"isa" = "PBXSourcesBuildPhase";
|
||||
"buildActionMask" = 2147483647;
|
||||
"files" = (
|
||||
"files" = ( "AF8FCAD6F87C7AAA1B8398AF", "77B510203B32A69B19F95BAF", "31E94EDA2FFA2E36C43113B4", "F69F722FBCDDA97A8FB48C96", "2921AED78693AE35B29C2B88", "E4061E4E0AB7CA7A47624B27",
|
||||
|
||||
D802CE11D18A211CE0CE5350,
|
||||
4F53DC2D981592B5A8E3FD11,
|
||||
@@ -1629,7 +1666,7 @@ CF5FFC06DB9D6CE02797B0DB,
|
||||
"buildActionMask" = 2147483647;
|
||||
"files" = ( "DA353EB8E8234292B4FCD1A9", "4D9D69AC7FDB3596BA58736A", "1E9C301114564D29D79F701A", "6E555C622A520877AB5EA78E", "6A46CA9A9BCDA42FDEDE0BFF", "370CBA86395A91DC191231AB",
|
||||
"296ADED30AE511DEAD130956",
|
||||
"56FE1E32C4755CD5F5692180", "1069B9674C8A658B4902A323" );
|
||||
"56FE1E32C4755CD5F5692180", "1069B9674C8A658B4902A323", "B7A7B5BFA3C251D22DC8561A" );
|
||||
"runOnlyForDeploymentPostprocessing" = 0;
|
||||
};
|
||||
"730C02D607B0893E83B3D2EA" = {
|
||||
@@ -1661,8 +1698,8 @@ CF5FFC06DB9D6CE02797B0DB,
|
||||
"INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment";
|
||||
"INFOPLIST_KEY_CFBundleDisplayName" = "VCC Plus OSS";
|
||||
"INFOPLIST_FILE" = "App/Info.plist";
|
||||
"VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.6.2";
|
||||
"CURRENT_PROJECT_VERSION" = "60";
|
||||
"VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.7.0";
|
||||
"CURRENT_PROJECT_VERSION" = "63";
|
||||
"LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" );
|
||||
"GCC_OPTIMIZATION_LEVEL" = "0";
|
||||
"SWIFT_OPTIMIZATION_LEVEL" = "-Onone";
|
||||
@@ -1682,8 +1719,8 @@ CF5FFC06DB9D6CE02797B0DB,
|
||||
"INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment";
|
||||
"INFOPLIST_KEY_CFBundleDisplayName" = "VCC Plus OSS";
|
||||
"INFOPLIST_FILE" = "App/Info.plist";
|
||||
"VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.6.2";
|
||||
"CURRENT_PROJECT_VERSION" = "60";
|
||||
"VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.7.0";
|
||||
"CURRENT_PROJECT_VERSION" = "63";
|
||||
"LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" );
|
||||
"GCC_OPTIMIZATION_LEVEL" = "2";
|
||||
"SWIFT_OPTIMIZATION_LEVEL" = "-O";
|
||||
@@ -1931,7 +1968,7 @@ CF5FFC06DB9D6CE02797B0DB,
|
||||
"E08DF13589706C56B1CA802C" = {
|
||||
"isa" = "PBXSourcesBuildPhase";
|
||||
"buildActionMask" = 2147483647;
|
||||
"files" = (
|
||||
"files" = ("9944B924F1F25A1C31E87133", "F97715060F4E2618EB80AFDE", "03B7230E381C6D102C3BF95F", "A8BC07BAEA1215B7503E9364", "6EB73875746CB21BDF3E7AB3", "B07B7E2C92770E75D506BABD", "6229E570150FBFD4653A4E38", "A1DC73569D936F22FB4E554E", "F770A2E6626B73FE7071CB9A", "337343EA275BED13114792F9",
|
||||
|
||||
|
||||
9788522075DEBF3EFB11491B,
|
||||
@@ -1977,7 +2014,7 @@ B7E302195F6A9DD0DEDAAE81, "F69A6B3CA6DADD9644B13172", "E28A5CEB274AF11A9D4D64A7"
|
||||
"00749908191B1902B8091B7B" = {
|
||||
"isa" = "PBXResourcesBuildPhase";
|
||||
"buildActionMask" = 2147483647;
|
||||
"files" = ( "B7A5DC0C696900499A34C88C", "C61C0FB4458A570B13BABD15", "92E50AAAE9437FD82A2AEA5F", "204BF507804696BC356530AC", "321E79BF2EA9B8C75D314039", "E33F4A7F24184C7137E4A4B0" );
|
||||
"files" = ( "B7A5DC0C696900499A34C88C", "C61C0FB4458A570B13BABD15", "92E50AAAE9437FD82A2AEA5F", "204BF507804696BC356530AC", "321E79BF2EA9B8C75D314039", "E33F4A7F24184C7137E4A4B0", "17CB263DB27EF1128FBF12D4" );
|
||||
"runOnlyForDeploymentPostprocessing" = 0;
|
||||
};
|
||||
"C8D1DE9C6F7B72659C81D2D8" = {
|
||||
@@ -2058,8 +2095,8 @@ B7E302195F6A9DD0DEDAAE81, "F69A6B3CA6DADD9644B13172", "E28A5CEB274AF11A9D4D64A7"
|
||||
};
|
||||
"DC76E9F0C0006E8F919E0C51" = {
|
||||
"isa" = "PBXGroup";
|
||||
"children" = (
|
||||
8C395B59B89AD94C577095CC, "01B2CD4F57507B2482FA993D", "BDB9AD06DF2962978FC5E007", "D481BB9B31A0A44756A2C642", "CB17E83394A9C5DF26C5FFF1", "C7751857B7E10600A291771F", "FAD4DB6739AE4807ADA3C27B", "91E042FFB6E1419B8931E646", "067A7A84E2E4F118095A8BB3", "9DCB740145E540C996E6692F", "312B00F5A13D4921AE264A2A", "5B5BB817A4524500B7E3CB1E", "53272DD2F81E40B2AF672610", "0F12DBE149CE0CD675AA66F8", "52B95FA5ED31A04909EFE857", "781F14A708182E90BDE108E3", "00B808A7780A251CC29CB06B", "7E6AA63365575C8888A99124", "C445DF085F7C807B908C19CB", "5421B06971D847A1A805F702", "9254269AE4824C5B8AAA4996", "16504192DF96663A78D5DFA8", "27644F1DECBC432E1B2768B8", "D333DD1A438EB4BC0A55464B", "C321FDC49814C39490B20F79", "0F7A6228BA94CC0C12A84F39", "16D176D2DB64F7417D6ACFC8", "530ADB2D5152809BD56B4BED", "5F75B5064C7FDFAC8800C0D3", "F12C3866E3125783A11526D4", "F797210E51F1F0B1CD8FF395", "49569D327A43047408F2DEAE", "5A3424F913D65182707784B8", "51E4344CADBA88EC0446EEA7", "792A514D818919EDF5F34717", "A1F993CAF2D203E517890FD7", "901D1E1FBB7B60F19AD95144", "07DA06A775F9267984E51EEC", "11A4CB4B8DF107985B0CB524", "7B1F352E41BE60388711F023", "9E3128773E24559995067F7F", "14868044C1345013A7F60685", "11EC6918F3B91AEE9FFB49F7", "9D6A737AD809CB34F0980691", "FFC326493D8F4603BD28BB6B", "C6A3EB89A975DDC859E73A36", "8BB8CC2C6D97EC712B6F9399", "EEEDC5273980EA83CBC757C5", "733493F7C9E00346B4010B62", "33C98A5D72682FD6AC0E5F62", "A748DE9CAD2C1300FF48663D", "F57F14F4BFF647EF7FDB64CC", "5BFFA01A19C5FC41EF60EE4A", "1B9725597009D3DE68DF62E3", "F80D3145FD907815FDAF4BA7", "1A6A84C4CFAE563E14CE3FF0", "58F6CDBEF369605DFC3FCA85", "F415937106477DDE7F72A7B8", "14F91CCC9DF1CB8D35001AEE", "EFF84673C3646AA99164A863", "5B72E96E835077666362CF7A", "A39C36931B6A59B325F0FB90", "B64B0E42CAB9E1342A8BD94F", "F0C6E8F2BD38C724C36913D6", "6CE23109A4C2422F878E5C78", "BCCC0E3132CFE859BA8542F6", "BB100B517FD5ADB833B0B9C0", "9426E9B4DB9CAF1E6EAFA927", "EF7750B1163369DD13DD5CE1", "A7B7BA8AEF5A062CF3C843DF", "F6B4DAA016C1911A09758E63", "5143771599404245B3DEA52E", "760BA2B4DE5F2E924A84BF1D", "C2646126B83489FB52DC1D6E", "14AE753173354D3EB5864563", "F82EC7B41E234EADA1CF84D1", "A3C1EA3C22CE43C8892A802C", "BA967E7658F745E1BC0ED7F2", "4F0596325DE3470A80EFE4EA", "3BDB3184317E405C82B06486", "5866911856DA41268827A601", "D168EF13EB20422AACCD96E2", "15ABD5DCBAFD4B6DAE418797", "BE84A652C2B04396BCBB921A", "455C6D7E1EB546C4B5A75AAF", "D70CBBA8530C6BC9B02AB379", "4B8AEF880E57EE0677BC1153", "F54CF4225FFCED7D7F647951", "67FB937B65ACB9D4278CFA4E", "3598AF219C2977DF6C4A5C2F", "F87E4A23CC0809CEA94F12E6", "E8ACFC9B89CAD012A308C316", "9DB93A677589CE78172A44A7", "4F76A349DB6B5A0F9E6A2C43", "E81B18C39152139A6105B84E", "25A93A2467BFAAED3F191E1B", "5BFC3293E94D0E3351244621", "D8248EBAF73CAB10C7C448FB", "217DC0F34A56DA5C4BB91E77", "A0DF98B8016880CAF0C0CD58", "42D841F636995F06C9332A0C", "31A4FF4E73AF3B5CFC309F60", "749C4BDB6AC37B600911C9C9", "39A991CE28D47963DE7E15F3", "A18B9CFC47DCA8A891571318", "1A65828188431AEC64A2EF1F", "C0CF07236765657B1CF3A441", "6DEBF620342B2A4B3AE5BCB1", "90FBFEB8BEE4D4B5EA4FF8B0", "6679E2C250A647804D193528", "8692D98EA40F7B2EE5EE136F", "3D4B95521A762F5E8B8ABB14", "EBC28D481E37A6D95550ED04", "9749C3A6E351964032384A3D", "79604D0603B58EC1CC2A9DA2", "91B7567AB5800567DAC343CD", "AFE25089ECEE6A77C768C432", "B4051C9774DFB5E15D886F79", "FB41D37D8F4F766B6F337A30", "5D4CCAE92059989714989D6B", "0F7F71696BF73C2A0921178C", "C05CBCBB0DDDF3E9B71ED4AB", "6E861FD0CA44590764FE438B", "C99C3267AC413B97551BD1EF", "472AC2CCB232639BB577696C", "A02293D0378FF4DA75C39EB5", "18267AA57F2798E15C7DEA3C", "4E1B73C4B6AD14CC00967423", "EDC3E15D86A8D4874AD0C180", "2711817C64CE46C182C5A8E9", "E5ADAD330B664E2BBC535C6A", "C6249A99265F026C199FD295", "5E52CBA4F430EC64E65E4239", "1AAB13C7AEC9576FCE909B30", "ACAA7FB0B84ABBE3CC50469D", "FC1ACF21BD5C46FC8CF22B60", "F147DB0A0B7B363C0181BBC4", "CE053132399860C266BA4115", "36D1A8AB53B6003A6A4B68D1", "45A42226A532DA306D381520", "29CCFF9C7E6B33DDB3DDA617", "EF0BA4677314B7DCCE726359", "68ABF5E4DB7DD34B8CC7EBA4", "2C765C18C64E564F954A7173", "9B68DF21D14BBFC0C977A0A8", "4C0DBA3B44DA84392AA3796A", "80C6105AD9495A0EB1F4A58C", "9F3C15DE610B4BFABF101002", "9F3C15DE610B4BFABF101003", "9F3C15DE610B4BFABF101001", "7339FE1A16674B2588333001", "3AE8BC7E4A8F296EB0B7AEFD", "2ECB4508563F3873B436B9EE", "277E06BEAA4F5310C0718CF2", "796FD8945B70098E2E2C7B92",
|
||||
"children" = ( "1893D6FB6CB3BF8A429B887C",
|
||||
8C395B59B89AD94C577095CC, "01B2CD4F57507B2482FA993D", "BDB9AD06DF2962978FC5E007", "D481BB9B31A0A44756A2C642", "B1E09D51DE234384B03D6D01", "CB17E83394A9C5DF26C5FFF1", "C7751857B7E10600A291771F", "FAD4DB6739AE4807ADA3C27B", "91E042FFB6E1419B8931E646", "067A7A84E2E4F118095A8BB3", "9DCB740145E540C996E6692F", "312B00F5A13D4921AE264A2A", "5B5BB817A4524500B7E3CB1E", "53272DD2F81E40B2AF672610", "0F12DBE149CE0CD675AA66F8", "52B95FA5ED31A04909EFE857", "781F14A708182E90BDE108E3", "00B808A7780A251CC29CB06B", "7E6AA63365575C8888A99124", "C445DF085F7C807B908C19CB", "5421B06971D847A1A805F702", "9254269AE4824C5B8AAA4996", "16504192DF96663A78D5DFA8", "27644F1DECBC432E1B2768B8", "D333DD1A438EB4BC0A55464B", "C321FDC49814C39490B20F79", "0F7A6228BA94CC0C12A84F39", "16D176D2DB64F7417D6ACFC8", "530ADB2D5152809BD56B4BED", "5F75B5064C7FDFAC8800C0D3", "F12C3866E3125783A11526D4", "F797210E51F1F0B1CD8FF395", "49569D327A43047408F2DEAE", "5A3424F913D65182707784B8", "51E4344CADBA88EC0446EEA7", "792A514D818919EDF5F34717", "A1F993CAF2D203E517890FD7", "901D1E1FBB7B60F19AD95144", "07DA06A775F9267984E51EEC", "11A4CB4B8DF107985B0CB524", "7B1F352E41BE60388711F023", "9E3128773E24559995067F7F", "14868044C1345013A7F60685", "11EC6918F3B91AEE9FFB49F7", "9D6A737AD809CB34F0980691", "FFC326493D8F4603BD28BB6B", "C6A3EB89A975DDC859E73A36", "8BB8CC2C6D97EC712B6F9399", "EEEDC5273980EA83CBC757C5", "733493F7C9E00346B4010B62", "33C98A5D72682FD6AC0E5F62", "A748DE9CAD2C1300FF48663D", "F57F14F4BFF647EF7FDB64CC", "5BFFA01A19C5FC41EF60EE4A", "1B9725597009D3DE68DF62E3", "F80D3145FD907815FDAF4BA7", "1A6A84C4CFAE563E14CE3FF0", "58F6CDBEF369605DFC3FCA85", "F415937106477DDE7F72A7B8", "14F91CCC9DF1CB8D35001AEE", "EFF84673C3646AA99164A863", "5B72E96E835077666362CF7A", "A39C36931B6A59B325F0FB90", "B64B0E42CAB9E1342A8BD94F", "F0C6E8F2BD38C724C36913D6", "6CE23109A4C2422F878E5C78", "BCCC0E3132CFE859BA8542F6", "BB100B517FD5ADB833B0B9C0", "9426E9B4DB9CAF1E6EAFA927", "EF7750B1163369DD13DD5CE1", "A7B7BA8AEF5A062CF3C843DF", "F6B4DAA016C1911A09758E63", "5143771599404245B3DEA52E", "760BA2B4DE5F2E924A84BF1D", "C2646126B83489FB52DC1D6E", "14AE753173354D3EB5864563", "F82EC7B41E234EADA1CF84D1", "A3C1EA3C22CE43C8892A802C", "BA967E7658F745E1BC0ED7F2", "4F0596325DE3470A80EFE4EA", "3BDB3184317E405C82B06486", "5866911856DA41268827A601", "D168EF13EB20422AACCD96E2", "15ABD5DCBAFD4B6DAE418797", "BE84A652C2B04396BCBB921A", "455C6D7E1EB546C4B5A75AAF", "D70CBBA8530C6BC9B02AB379", "4B8AEF880E57EE0677BC1153", "F54CF4225FFCED7D7F647951", "67FB937B65ACB9D4278CFA4E", "3598AF219C2977DF6C4A5C2F", "F87E4A23CC0809CEA94F12E6", "E8ACFC9B89CAD012A308C316", "9DB93A677589CE78172A44A7", "4F76A349DB6B5A0F9E6A2C43", "E81B18C39152139A6105B84E", "25A93A2467BFAAED3F191E1B", "5BFC3293E94D0E3351244621", "D8248EBAF73CAB10C7C448FB", "217DC0F34A56DA5C4BB91E77", "A0DF98B8016880CAF0C0CD58", "42D841F636995F06C9332A0C", "31A4FF4E73AF3B5CFC309F60", "749C4BDB6AC37B600911C9C9", "39A991CE28D47963DE7E15F3", "A18B9CFC47DCA8A891571318", "1A65828188431AEC64A2EF1F", "C0CF07236765657B1CF3A441", "6DEBF620342B2A4B3AE5BCB1", "90FBFEB8BEE4D4B5EA4FF8B0", "6679E2C250A647804D193528", "8692D98EA40F7B2EE5EE136F", "3D4B95521A762F5E8B8ABB14", "EBC28D481E37A6D95550ED04", "9749C3A6E351964032384A3D", "79604D0603B58EC1CC2A9DA2", "91B7567AB5800567DAC343CD", "AFE25089ECEE6A77C768C432", "B4051C9774DFB5E15D886F79", "FB41D37D8F4F766B6F337A30", "5D4CCAE92059989714989D6B", "0F7F71696BF73C2A0921178C", "C05CBCBB0DDDF3E9B71ED4AB", "6E861FD0CA44590764FE438B", "C99C3267AC413B97551BD1EF", "472AC2CCB232639BB577696C", "A02293D0378FF4DA75C39EB5", "18267AA57F2798E15C7DEA3C", "4E1B73C4B6AD14CC00967423", "EDC3E15D86A8D4874AD0C180", "2711817C64CE46C182C5A8E9", "E5ADAD330B664E2BBC535C6A", "C6249A99265F026C199FD295", "5E52CBA4F430EC64E65E4239", "1AAB13C7AEC9576FCE909B30", "ACAA7FB0B84ABBE3CC50469D", "FC1ACF21BD5C46FC8CF22B60", "F147DB0A0B7B363C0181BBC4", "CE053132399860C266BA4115", "36D1A8AB53B6003A6A4B68D1", "45A42226A532DA306D381520", "29CCFF9C7E6B33DDB3DDA617", "EF0BA4677314B7DCCE726359", "68ABF5E4DB7DD34B8CC7EBA4", "2C765C18C64E564F954A7173", "9B68DF21D14BBFC0C977A0A8", "4C0DBA3B44DA84392AA3796A", "80C6105AD9495A0EB1F4A58C", "9F3C15DE610B4BFABF101002", "9F3C15DE610B4BFABF101003", "9F3C15DE610B4BFABF101001", "7339FE1A16674B2588333001", "3AE8BC7E4A8F296EB0B7AEFD", "2ECB4508563F3873B436B9EE", "277E06BEAA4F5310C0718CF2", "796FD8945B70098E2E2C7B92",
|
||||
"445AFB9A10CBBAE48539A39F",
|
||||
"6BD293692BB0058E467291CC",
|
||||
"C015745C6395762B28454414",
|
||||
|
||||
Reference in new issue
Block a user