Files
VCCPlusOSS/platforms/macos/App/SoftwareLibraryModel.swift
T

706 lines
39 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import Combine
import AppKit
#if !VCC_COMPANION_CLIENT
/// Native review stays attached to its window and cannot strand shutdown on a
/// canceled download/launch task waiting for a modal response.
@MainActor
final class LibraryReviewSheet {
private let alert: NSAlert
private let parent: NSWindow
private var canceled = false
init(alert: NSAlert, parent: NSWindow) { self.alert = alert; self.parent = parent }
func present() async -> NSApplication.ModalResponse {
await withTaskCancellationHandler {
await withCheckedContinuation { done in
guard !Task.isCancelled, !canceled, parent.attachedSheet == nil else {
done.resume(returning: .cancel); return
}
alert.beginSheetModal(for: parent) { done.resume(returning: $0) }
}
} onCancel: {
Task { @MainActor in
self.canceled = true
if self.alert.window.sheetParent === self.parent {
self.parent.endSheet(self.alert.window, returnCode: .cancel)
}
}
}
}
}
#endif
struct LibraryCategory: Identifiable, Sendable {
let id: String
let name: String
let children: [LibraryCategory]?
static func tree(_ paths: [String], prefix: String = "") -> [Self] {
let names = Set(paths.compactMap { path -> String? in
guard path.hasPrefix(prefix) else { return nil }
return path.dropFirst(prefix.count).split(separator: "/").first.map(String.init)
})
return names.sorted().map { name in
let path = prefix + name
let descendants = tree(paths.filter { $0.hasPrefix(path + "/") }, prefix: path + "/")
return Self(id: path, name: name, children: descendants.isEmpty ? nil : descendants)
}
}
}
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" }
var scope: Scope = .started
var text = ""
var category = ""
var softwareType = ""
var media = ""
var system = ""
var evidence = ""
var sort: Sort = .title
var environment = ""
var processor = ""
var hardware = ""
var hardwareUse = ""
var displayFeature = ""
static let environmentLabels = ["basic": "BASIC", "disk-basic": "Disk BASIC", "os9": "OS-9 / NitrOS-9", "unknown": "Environment unspecified"]
static let processorLabels = ["6309": "Requires Hitachi 6309", "either": "Supports 6809 and 6309", "unknown": "Processor requirement unspecified"]
static let hardwareLabels = ["speech-sound": "Speech/Sound", "orchestra90": "Orchestra-90", "joystick": "Joystick"]
static let hardwareUseLabels = ["required": "Required", "optional": "Optional", "unspecified": "Requirement unspecified"]
static let displayLabels = ["semigraphics": "Semigraphics", "SG-8": "Semigraphics-8", "SG-12": "Semigraphics-12", "SG-24": "Semigraphics-24"]
var additionalFilterLabels: [String] {
[Self.environmentLabels[environment], Self.processorLabels[processor],
Self.hardwareLabels[hardware].map { label in
hardwareUse.isEmpty ? label : label + " — " + (Self.hardwareUseLabels[hardwareUse] ?? hardwareUse)
}, Self.displayLabels[displayFeature]].compactMap { $0 }
}
func matchesHardware(_ release: SoftwareLibraryRelease) -> Bool {
hardware.isEmpty || (release.hardwareSupport[hardware] != nil &&
(hardwareUse.isEmpty || release.hardwareSupport[hardware] == hardwareUse))
}
func matchesDisplay(_ release: SoftwareLibraryRelease) -> Bool {
displayFeature.isEmpty || (displayFeature == "semigraphics" ? !release.semigraphicsModes.isEmpty : release.semigraphicsModes.contains(displayFeature))
}
// Getting Started is an explicit catalog choice, independent of runtime
// checks, provenance and former hard-coded starter selections.
static func isGettingStarted(_ release: SoftwareLibraryRelease) -> Bool {
release.gettingStarted
}
static func types(of release: SoftwareLibraryRelease, related: [SoftwareLibraryRelease] = []) -> [String] {
release.browseCategories.isEmpty ? [type(of: release, related: related)] : release.browseCategories
}
static func matchesCategory(_ category: String, release: SoftwareLibraryRelease) -> Bool {
if release.ownedGame != nil { return category.isEmpty || release.browseCategories.contains(category) }
return category.isEmpty || release.category == category || release.category.hasPrefix(category + "/") ||
release.browseCategories.contains(category)
}
func matches(_ release: SoftwareLibraryRelease, titleName: String, related: [SoftwareLibraryRelease] = []) -> Bool {
guard softwareType.isEmpty || Self.types(of: release, related: related).contains(softwareType),
Self.matchesCategory(category, release: release),
media.isEmpty || release.mediaType == media, system.isEmpty || release.system == system else { return false }
guard environment.isEmpty || release.environment == environment,
processor.isEmpty || release.processorRequirement == processor,
matchesHardware(release), matchesDisplay(release) else { return false }
switch evidence {
case "checked": guard release.setup.status == "spot-checked" else { return false }
case "manual": guard release.setup.status == "manual-setup" else { return false }
case "notes": guard !release.setup.compatibilityNotes.isEmpty || !release.setup.configurationRequirements.isEmpty else { return false }
default: break
}
let haystack = titleName + " " + release.searchText
return text.split(whereSeparator: \.isWhitespace).allSatisfy { haystack.localizedStandardContains(String($0)) }
}
static func type(of release: SoftwareLibraryRelease, related: [SoftwareLibraryRelease] = []) -> String {
if let primary = release.primaryBrowseCategory { return primary }
func categoryType(_ release: SoftwareLibraryRelease) -> String? {
let components = release.category.split(separator: "/").map(String.init)
let names: Set<String> = ["Applications", "Games", "Music", "Educational", "Demos", "Utilities", "Programming", "Magazines", "Books", "Pictures", "Hardware", "Operating Systems"]
// The first software category is authoritative; a game's demo is still a game.
if let name = components.first(where: names.contains) { return name }
if components.contains(where: { $0.hasPrefix("NitrOS-9") || $0.hasPrefix("OS-9 L2") }) { return "Operating Systems" }
if components.contains("Blank disks") || components.contains("Empty Hard Disk") { return "Blank Media" }
return nil
}
if let own = categoryType(release) { return own }
let types = Set(related.compactMap(categoryType))
return types.count == 1 ? types.first! : "Other"
}
func apply(to titles: [SoftwareLibraryTitle], favorites: Set<String>, installed: Set<String>) -> [LibraryBrowseRow] {
var rows = titles.compactMap { title -> LibraryBrowseRow? in
if scope == .favorites && !favorites.contains(title.id) { return nil }
let matches = title.releases.filter {
(scope != .started || Self.isGettingStarted($0)) &&
(scope != .showcase || $0.assets.contains(where: { SoftwareLibraryArtworkCache.canDisplay($0) })) &&
(scope != .installed || installed.contains($0.id)) && self.matches($0, titleName: title.name, related: title.releases)
}
guard !matches.isEmpty else { return nil }
return LibraryBrowseRow(title: title, matchingReleases: matches)
}
rows.sort { a, b in
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 {
case .modified:
let av = a.matchingReleases.compactMap(\.modifiedAt).max() ?? ""
let bv = b.matchingReleases.compactMap(\.modifiedAt).max() ?? ""
if av != bv { return av > bv }
case .size:
let av = a.matchingReleases.map(\.byteSize).max() ?? 0
let bv = b.matchingReleases.map(\.byteSize).max() ?? 0
if av != bv { return av > bv }
case .title: break
}
let order = a.title.name.localizedStandardCompare(b.title.name)
return order == .orderedSame ? a.id < b.id : order == .orderedAscending
}
return rows
}
}
struct LibraryBrowseRow: Identifiable, Sendable {
let title: SoftwareLibraryTitle
let matchingReleases: [SoftwareLibraryRelease]
var id: String { title.id }
var name: String { title.name }
var categoryFeatured: Bool { matchingReleases.contains(where: \.categoryFeatured) }
var formats: String { Set(matchingReleases.map(\.mediaLabel)).sorted().joined(separator: ", ") }
var modified: String { matchingReleases.compactMap(\.modifiedAt).max() ?? "Unknown" }
var size: String { ByteCountFormatter.string(fromByteCount: matchingReleases.map(\.byteSize).max() ?? 0, countStyle: .file) }
}
#if !VCC_COMPANION_CLIENT
struct LibraryLaunchPreview: Identifiable {
let id = UUID()
let prepared: PreparedLibraryLaunch
var plan: SoftwareLibraryLaunchPlan { prepared.plan }
}
#endif
struct LibraryMediaChoice: Identifiable {
let id = UUID()
let release: SoftwareLibraryRelease
let receipt: SoftwareLibraryInstallationReceipt
let candidates: [CompanionLibraryDisk]
}
@MainActor
final class SoftwareLibraryModel: ObservableObject {
let state: SoftwareLibraryState
let manual = SoftwareLibraryManualModel()
let artworkDirectory: URL
@Published private(set) var catalog: SoftwareLibraryCatalog?
@Published private(set) var rows: [LibraryBrowseRow] = []
@Published private(set) var softwareTypes: [String] = []
@Published private(set) var categories: [LibraryCategory] = []
@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"
let companionAccess: (any CompanionLibraryAccess)?
private let insertCompanionDisk: ((URL) async throws -> Void)?
#if !VCC_COMPANION_CLIENT
let installer: SoftwareLibraryInstaller
let machine: MachineModel?
private let sourceImporter: SoftwareLibrarySourceImporter
private let sourceWorkspaceIdentity: (() -> UUID)?
private let openSourceProject: ((URL, UUID, String?) async throws -> Bool)?
@Published var launchPreview: LibraryLaunchPreview?
#endif
@Published var mediaChoice: LibraryMediaChoice?
@Published private(set) var launchBusy = false
@Published private(set) var launchError: String?
@Published private(set) var launchMessage: String?
#if !VCC_COMPANION_CLIENT
@Published private(set) var previousSetup: ConfigurationProfile?
#endif
@Published private(set) var machineFocusRequest = 0
@Published private(set) var sourceFocusRequest = 0
@Published private(set) var importingSourceID: String?
@Published private(set) var sourceImportMessage: String?
@Published private(set) var sourceImportError: String?
@Published private(set) var sourceImportFraction: Double?
@Published private(set) var importedSourceDirectory: URL?
@Published private(set) var sourceDetailsReleaseID: String?
private var sourceImportGeneration = UUID()
private var sourceImportTask: Task<Void, Never>?
private var launchTask: Task<Void, Never>?
@Published private(set) var installingReleaseID: String?
@Published private(set) var installProgress: SoftwareLibraryInstallProgress?
@Published private(set) var installationErrors: [String: String] = [:]
@Published private(set) var installationNotice: String?
@Published private(set) var recoveringInstallations = true
private var installationGeneration = UUID()
private var installationTask: Task<Void, Never>?
private var task: Task<Void, Never>?
private var generation = 0
private var subscriptions: Set<AnyCancellable> = []
#if !VCC_COMPANION_CLIENT
init(state: SoftwareLibraryState, artworkDirectory: URL? = nil, machine: MachineModel? = nil,
sourceWorkspaceIdentity: (() -> UUID)? = nil,
openSourceProject: ((URL, UUID, String?) async throws -> Bool)? = nil) {
companionAccess = nil; insertCompanionDisk = nil
self.state = state
self.machine = machine
self.sourceWorkspaceIdentity = sourceWorkspaceIdentity; self.openSourceProject = openSourceProject
#if VCC_UI_TESTING
sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages"),
configuration: SoftwareLibraryInstallFixture.exclusiveEnabled ? SoftwareLibraryInstallFixture.sourceConfiguration : nil)
#else
sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages"))
#endif
#if VCC_UI_TESTING
installer = SoftwareLibraryInstallFixture.enabled ? SoftwareLibraryInstallFixture.installer(root: state.directory) : SoftwareLibraryInstaller(root: state.directory)
#else
installer = SoftwareLibraryInstaller(root: state.directory)
#endif
#if VCC_UI_TESTING
self.artworkDirectory = SoftwareLibraryInstallFixture.exclusiveEnabled ? state.directory.appendingPathComponent("FixtureArtwork")
: artworkDirectory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("com.brianholman.vccplus.oss.mac/SoftwareLibrary/Artwork")
if SoftwareLibraryInstallFixture.exclusiveEnabled {
do { try SoftwareLibraryInstallFixture.seedExclusiveAssets(manualDirectory: state.directory.appendingPathComponent("Manuals"), artworkDirectory: self.artworkDirectory) }
catch { self.error = error.localizedDescription }
}
#else
self.artworkDirectory = artworkDirectory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("com.brianholman.vccplus.oss.mac/SoftwareLibrary/Artwork")
#endif
state.objectWillChange.sink { [weak self] in
Task { @MainActor [weak self] in self?.objectWillChange.send(); self?.filter() }
}.store(in: &subscriptions)
}
#endif
init(companion: any CompanionLibraryAccess, onInsertDisk: @escaping (URL) async throws -> Void) {
companionAccess = companion; insertCompanionDisk = onInsertDisk
state = SoftwareLibraryState(companion: companion)
artworkDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCompanionPresentation")
#if !VCC_COMPANION_CLIENT
machine = nil; installer = SoftwareLibraryInstaller(root: state.directory)
sourceWorkspaceIdentity = nil; openSourceProject = nil
sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages"))
#endif
// A disk companion starts with all eligible software, including titles
// without cover art. Later snapshots preserve explicit scope choices.
query = LibraryBrowseQuery(scope: .all)
state.objectWillChange.sink { [weak self] in
Task { @MainActor [weak self] in self?.objectWillChange.send(); self?.filter() }
}.store(in: &subscriptions)
}
var isDiskCompanion: Bool { companionAccess != nil }
var canOpenSource: Bool {
#if !VCC_COMPANION_CLIENT
return !isDiskCompanion && sourceWorkspaceIdentity != nil && openSourceProject != nil
#else
return false
#endif
}
func chooseSourceDestination(_ release: SoftwareLibraryRelease) {
#if !VCC_COMPANION_CLIENT
guard canOpenSource, release.ownedGame != nil, importingSourceID == nil else { return }
let panel = NSSavePanel()
panel.title = "Save Source Project"; panel.prompt = "Download Source"
panel.message = "Choose a new personal project folder. Opening source does not build, run or change the CoCo."
panel.canCreateDirectories = true
panel.nameFieldStringValue = (selectedRow?.name ?? "CoCo") + " Source"
panel.begin { [weak self] response in
guard response == .OK, let directory = panel.url else { return }
self?.importSource(release, to: directory)
}
#endif
}
func importSource(_ release: SoftwareLibraryRelease, to directory: URL) {
#if !VCC_COMPANION_CLIENT
guard importingSourceID == nil, let source = release.ownedGame?.source,
let expected = sourceWorkspaceIdentity?(), let openSourceProject else { return }
importingSourceID = release.id; sourceImportMessage = "Downloading source…"
sourceDetailsReleaseID = release.id
let attempt = UUID(); sourceImportGeneration = attempt
sourceImportError = nil; sourceImportFraction = nil; importedSourceDirectory = nil
sourceImportTask = Task {
defer { importingSourceID = nil; sourceImportTask = nil; sourceImportFraction = nil }
do {
let result = try await sourceImporter.importProject(source, to: directory) { progress in
Task { @MainActor in
guard self.importingSourceID == release.id, self.sourceImportGeneration == attempt else { return }
self.sourceImportFraction = progress.fraction
switch progress.stage {
case .downloading: self.sourceImportMessage = "Downloading source…"
case .verifying: self.sourceImportMessage = "Verifying source…"
case .extracting: self.sourceImportMessage = "Preparing source files…"
case .checking: self.sourceImportMessage = "Checking the C project…"
case .complete: break
}
}
}
importedSourceDirectory = result.importedDirectory
try Task.checkCancellation()
let opened = try await openSourceProject(result.projectDirectory, expected, source.buildConfiguration)
sourceImportMessage = opened ? "Your source copy is open in C Development. Build when you are ready."
: "Your source copy is saved. The current C project is still open."
if opened { sourceFocusRequest += 1 }
} catch is CancellationError {
sourceImportMessage = importedSourceDirectory == nil ? "Source download canceled." : "Your source copy is saved."
} catch { sourceImportError = error.localizedDescription; sourceImportMessage = nil }
}
#endif
}
func cancelSourceImport() { sourceImportTask?.cancel() }
var canLaunch: Bool {
if insertCompanionDisk != nil { return true }
#if !VCC_COMPANION_CLIENT
return machine != nil
#else
return false
#endif
}
var hasPreviousSetup: Bool {
#if !VCC_COMPANION_CLIENT
return previousSetup != nil
#else
return false
#endif
}
var hasPendingLaunch: Bool {
#if !VCC_COMPANION_CLIENT
return launchPreview != nil || mediaChoice != nil
#else
return mediaChoice != nil
#endif
}
func launchLabel(_ release: SoftwareLibraryRelease, installed: Bool) -> String {
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)
? (installed ? "Play…" : "Download & Play…") : (installed ? "Set Up…" : "Download & Set Up…")
#else
return "Insert Disk…"
#endif
}
func launchSymbol(_ release: SoftwareLibraryRelease) -> String {
if isDiskCompanion { return "externaldrive" }
#if !VCC_COMPANION_CLIENT
return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release) ? "play.fill" : "desktopcomputer"
#else
return "externaldrive"
#endif
}
func focusDisplay() {
#if !VCC_COMPANION_CLIENT
machine?.focusDisplay()
#endif
}
func load(from url: URL? = SoftwareLibraryCatalog.bundledURL()) async {
guard catalog == nil, !loading else { return }
loading = true; error = nil
if let companionAccess {
defer { loading = false; recoveringInstallations = false }
do {
let response = try await companionAccess.libraryRequest(.init(operation: .snapshot))
try acceptCompanion(response)
guard catalog != nil else { throw CompanionLibraryFailure(message: "VCC Plus did not return its disk catalog.") }
} catch { self.error = error.localizedDescription }
return
}
#if !VCC_COMPANION_CLIENT
await refreshInstallations()
#if VCC_UI_TESTING
if SoftwareLibraryInstallFixture.enabled {
catalog = SoftwareLibraryInstallFixture.catalog
categories = LibraryCategory.tree(catalog!.categories)
updateSoftwareTypes(catalog!)
query.scope = .all
filter(); loading = false; return
}
#endif
do {
guard let url else { throw SoftwareLibraryCatalog.Failure.missing }
let snapshot = try await SoftwareLibraryCatalog.load(from: 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 {
if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) }
if let snapshot = response.snapshot {
// The service filters too; defend the UI and edition picker independently.
let filtered = snapshot.catalog.companionDisksOnly
catalog = filtered; categories = LibraryCategory.tree(filtered.categories)
updateSoftwareTypes(filtered); state.applyRemoteSnapshot(snapshot); filter()
}
}
var selectedRow: LibraryBrowseRow? { rows.first { $0.id == selection } }
var selectedRelease: SoftwareLibraryRelease? {
guard let row = selectedRow else { return nil }
if let preferred = state.preferredReleaseID(for: row.id), let release = row.matchingReleases.first(where: { $0.id == preferred }) { return release }
return row.matchingReleases.first
}
func chooseRelease(_ id: String) {
guard let title = selectedRow?.title, let chosen = title.releases.first(where: { $0.id == id }) else { return }
// Keep the user's context when another edition still matches it. Clear
// only constraints that would hide their explicit edition choice.
var next = query
if !next.softwareType.isEmpty && !LibraryBrowseQuery.types(of: chosen, related: title.releases).contains(next.softwareType) { next.softwareType = "" }
if !next.category.isEmpty && !LibraryBrowseQuery.matchesCategory(next.category, release: chosen) { next.category = "" }
if !next.media.isEmpty && chosen.mediaType != next.media { next.media = "" }
if !next.system.isEmpty && chosen.system != next.system { next.system = "" }
if !next.environment.isEmpty && chosen.environment != next.environment { next.environment = "" }
if !next.processor.isEmpty && chosen.processorRequirement != next.processor { next.processor = "" }
if !next.matchesHardware(chosen) { next.hardware = ""; next.hardwareUse = "" }
if !next.matchesDisplay(chosen) { next.displayFeature = "" }
if !LibraryBrowseQuery(scope: .all, evidence: next.evidence).matches(chosen, titleName: title.name) { next.evidence = "" }
if !LibraryBrowseQuery(scope: .all, text: next.text).matches(chosen, titleName: title.name) { next.text = "" }
if next.scope == .started && !LibraryBrowseQuery.isGettingStarted(chosen) { next.scope = .all }
if next.scope == .showcase && !chosen.assets.contains(where: { SoftwareLibraryArtworkCache.canDisplay($0) }) { next.scope = .all }
if next.scope == .installed && state.installedReleases[id] == nil { next.scope = .all }
state.selectRelease(id, for: title.id)
query = next
}
func browse(_ scope: LibraryBrowseQuery.Scope, category: String = "") {
var next = query
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()
}
func browseType(_ type: String) {
var next = query
next.scope = .all; next.category = ""; next.softwareType = type
query = next
}
func clearFilters() {
var next = query
next.softwareType = ""; next.media = ""; next.system = ""; next.evidence = ""
next.environment = ""; next.processor = ""; next.hardware = ""; next.hardwareUse = ""; next.displayFeature = ""
query = next
}
func install(_ release: SoftwareLibraryRelease, playAfter: Bool = false) {
guard installingReleaseID == nil, !recoveringInstallations, !launchBusy, !hasPendingLaunch else { return }
if companionAccess != nil { installCompanion(release, insertAfter: playAfter); return }
#if !VCC_COMPANION_CLIENT
installationErrors[release.id] = nil; installationNotice = nil
installingReleaseID = release.id; installProgress = nil
let attempt = UUID(); installationGeneration = attempt
installationTask = Task {
do {
let receipt = try await installer.install(release) { progress in
Task { @MainActor in
guard self.installingReleaseID == release.id, self.installationGeneration == attempt else { return }
self.installProgress = progress
}
}
await refreshInstallations()
if playAfter, !Task.isCancelled { await prepareLaunch(release, receipt: receipt) }
} catch {
if Task.isCancelled || error is CancellationError { installationNotice = "Download canceled. You can try again whenever you’re ready." }
else { installationErrors[release.id] = error.localizedDescription }
}
installingReleaseID = nil; installProgress = nil; installationTask = nil
}
#endif
}
func cancelInstallation() {
installationTask?.cancel()
if let companionAccess, let id = installingReleaseID {
Task { _ = try? await companionAccess.libraryRequest(.init(operation: .cancelInstallation, releaseID: id)) }
}
}
func shutdown() async {
sourceImportTask?.cancel()
await sourceImportTask?.value
launchTask?.cancel()
await launchTask?.value
cancelInstallation()
await installationTask?.value
await state.flush()
}
func removeInstallation(_ id: String) async {
guard installingReleaseID == nil, !launchBusy, !hasPendingLaunch else { return }
if let companionAccess {
do { try acceptCompanion(try await companionAccess.libraryRequest(.init(operation: .removeInstallation, releaseID: id))) }
catch { installationErrors[id] = error.localizedDescription }
return
}
#if !VCC_COMPANION_CLIENT
do {
if let retained = try await installer.forgetInstallation(releaseID: id) {
installationNotice = "Removed from the Library. Your files are still in \(retained.path)."
}
await refreshInstallations()
} catch { installationErrors[id] = error.localizedDescription }
#endif
}
func play(_ release: SoftwareLibraryRelease) {
guard canLaunch else { return }
launchError = nil; launchMessage = nil
install(release, playAfter: true)
}
#if !VCC_COMPANION_CLIENT
private func prepareLaunch(_ release: SoftwareLibraryRelease, receipt: SoftwareLibraryInstallationReceipt, selectedMember: String? = nil) async {
guard let machine else { return }
launchBusy = true
defer { launchBusy = false }
do {
let plan = try await Task.detached(priority: .userInitiated) {
try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt, selectedMember: selectedMember)
}.value
try Task.checkCancellation()
let prepared = try await machine.prepareLibraryLaunch(plan)
try Task.checkCancellation()
if plan.usesCuratedStartup {
let snapshot = await machine.mcpReadinessSnapshot()
try Task.checkCancellation()
if Self.needsCuratedRestartReview(snapshot, hasRAMDisk: machine.cartridgeAssignments.slots.contains(where: { $0.kind == .ramDisk })) {
let alert = NSAlert()
alert.messageText = "Restart the current CoCo to play “\(plan.title)”?"
alert.informativeText = "The current program and RAM disk contents will be cleared. Save any program you want to keep first. Writable disk changes are saved; unsaved temporary media or recordings block the restart."
alert.addButton(withTitle: "Restart & Play"); alert.addButton(withTitle: "Cancel")
guard let parent = NSApp.keyWindow else { throw ProfileFailure.message("Open the Software Library to review the current program before restarting.") }
let response = await LibraryReviewSheet(alert: alert, parent: parent).present()
guard response == .alertFirstButtonReturn else { return }
}
try Task.checkCancellation()
let result = try await machine.launchLibrary(prepared)
previousSetup = prepared.previousSetup
launchMessage = result.message ?? "Started " + plan.title + "."
machineFocusRequest += 1
} else { launchPreview = LibraryLaunchPreview(prepared: prepared) }
} catch SoftwareLibraryLaunchPlan.Failure.needsSelection(let candidates) {
guard !Task.isCancelled else { return }
mediaChoice = LibraryMediaChoice(release: release, receipt: receipt, candidates: candidates.map { CompanionLibraryDisk(path: $0.path, mediaType: $0.mediaType) })
} catch {
if !Task.isCancelled { launchError = error.localizedDescription }
}
}
static func needsCuratedRestartReview(_ snapshot: VCCMachineSnapshot, hasRAMDisk: Bool = false) -> Bool {
if hasRAMDisk { return true }
if snapshot.state == .empty { return false }
return snapshot.assistantEmptyBASIC?.boolValue != true || snapshot.assistantDirectPrompt?.boolValue != true
|| snapshot.debuggerDevelopmentAttached || snapshot.basicDebugAttached || snapshot.debuggerAssemblyAttached
|| snapshot.pasteRemaining > 0
}
func confirmLaunch() {
guard let preview = launchPreview, let machine, !launchBusy else { return }
launchPreview = nil; launchBusy = true; launchError = nil; launchMessage = nil
launchTask = Task {
defer { launchBusy = false; launchTask = nil }
do {
let result = try await machine.launchLibrary(preview.prepared)
previousSetup = preview.prepared.previousSetup
launchMessage = result.message ?? (preview.plan.automaticallyStarts ? "Started " + preview.plan.title + "." : "The media is mounted. Follow the loading instructions to start the software.")
machineFocusRequest += 1
} catch { launchError = error.localizedDescription }
}
}
func returnToPreviousSetup() {
guard let profile = previousSetup, let machine, !launchBusy, installingReleaseID == nil, launchPreview == nil, mediaChoice == nil else { return }
launchBusy = true; launchError = nil; launchMessage = nil
launchTask = Task {
defer { launchBusy = false; launchTask = nil }
do {
try await machine.returnLibrarySetup(profile)
previousSetup = nil; launchMessage = "Previous setup restored. Its prior running program and memory are not restored."
machineFocusRequest += 1
} catch { launchError = error.localizedDescription }
}
}
private func refreshInstallations() async {
recoveringInstallations = true
defer { recoveringInstallations = false }
do {
let receipts = try await installer.recoverInstallations()
let warnings = await installer.recoveryWarnings
if !warnings.isEmpty { installationNotice = warnings.joined(separator: "\n") }
state.replaceInstallations(receipts.map { .init(releaseID: $0.releaseID, packageSHA256: $0.packageSHA256, installedAt: $0.installedAt, workingDirectory: $0.workingDirectory) })
} catch { installationNotice = "Installed software could not be checked: " + error.localizedDescription }
}
#endif
func chooseLaunchMember(_ member: String, choice: LibraryMediaChoice) {
guard !launchBusy else { return }
mediaChoice = nil
if companionAccess != nil {
launchTask = Task { await prepareCompanionDisk(choice.release, selectedMember: member) }
return
}
#if !VCC_COMPANION_CLIENT
launchTask = Task {
await prepareLaunch(choice.release, receipt: choice.receipt, selectedMember: member)
launchTask = nil
}
#endif
}
func stopAutomaticLoading() { launchTask?.cancel(); cancelInstallation() }
#if VCC_COMPANION_CLIENT
func returnToPreviousSetup() { }
#endif
private func installCompanion(_ release: SoftwareLibraryRelease, insertAfter: Bool) {
guard let companionAccess, release.mediaType == "disk" else { return }
installationErrors[release.id] = nil; installationNotice = nil
installingReleaseID = release.id; installProgress = nil
let attempt = UUID(); installationGeneration = attempt
installationTask = Task {
defer { if installationGeneration == attempt { installingReleaseID = nil; installProgress = nil; installationTask = nil } }
do {
var response = try await companionAccess.libraryRequest(.init(operation: .install, releaseID: release.id))
while true {
try Task.checkCancellation()
guard installationGeneration == attempt else { return }
try acceptCompanion(response); installProgress = response.progress
if !response.isInstalling { break }
try await Task.sleep(nanoseconds: 350_000_000)
response = try await companionAccess.libraryRequest(.init(operation: .installStatus, releaseID: release.id))
}
guard state.installedReleases[release.id] != nil else {
throw CompanionLibraryFailure(message: "The installation did not complete. Your existing files have been preserved.")
}
if insertAfter { await prepareCompanionDisk(release) }
} catch {
if Task.isCancelled || error is CancellationError { installationNotice = "Download canceled. You can try again whenever you’re ready." }
else { installationErrors[release.id] = error.localizedDescription }
}
}
}
private func prepareCompanionDisk(_ release: SoftwareLibraryRelease, selectedMember: String? = nil) async {
guard let companionAccess, let insertCompanionDisk, release.mediaType == "disk" else { return }
launchBusy = true; launchError = nil; launchMessage = nil
defer { launchBusy = false }
do {
let response = try await companionAccess.libraryRequest(.init(operation: .diskMembers, releaseID: release.id))
try acceptCompanion(response)
let candidates = response.disks ?? []
let chosen: String
if let selectedMember, candidates.contains(where: { $0.path == selectedMember }) { chosen = selectedMember }
else if candidates.count == 1 { chosen = candidates[0].path }
else if candidates.count > 1 {
guard let receipt = response.receipt else { throw CompanionLibraryFailure(message: "VCC Plus did not return the installation record.") }
mediaChoice = LibraryMediaChoice(release: release, receipt: receipt, candidates: candidates)
return
} else { throw CompanionLibraryFailure(message: "This installation has no supported floppy disk image.") }
let exported = try await companionAccess.libraryRequest(.init(operation: .exportDisk, releaseID: release.id, memberPath: chosen))
try acceptCompanion(exported); try Task.checkCancellation()
guard let url = exported.exportedDiskURL, url.isFileURL else { throw CompanionLibraryFailure(message: "VCC Plus did not return a disk copy.") }
try await insertCompanionDisk(url)
launchMessage = "The disk is inserted. Follow the loading instructions on your CoCo."
} catch { if !Task.isCancelled { launchError = error.localizedDescription } }
}
private func filter() {
guard let catalog else { return }
task?.cancel(); generation += 1; let version = generation
let query = query, favorites = state.favoriteTitleIDs, installed = Set(state.installedReleases.keys)
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 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 }
}
}
}