// SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import AppKit struct SoftwareLibraryView: View { @Environment(\.openWindow) private var openWindow @ObservedObject var model: SoftwareLibraryModel @State private var showManual = false @State private var showFilters = false @State private var showAdvancedFilters = false @State private var confirmingReturn = false @State private var removingRelease: SoftwareLibraryRelease? var body: some View { VStack(spacing: 0) { header Divider() HSplitView { sidebar.frame(minWidth: 170, idealWidth: 185, maxWidth: 235, maxHeight: .infinity, alignment: .top) browser.frame(minWidth: 330, maxWidth: .infinity, maxHeight: .infinity, alignment: .top) detail.frame(minWidth: 320, idealWidth: 365, maxWidth: 460, maxHeight: .infinity, alignment: .top) }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) if let notice = model.installationNotice { Text(notice).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 16).padding(.vertical, 6) } if let id = model.installingReleaseID, id != model.selectedRelease?.id { HStack { ProgressView().controlSize(.small) Text("Installing " + (model.catalog?.releases.first { $0.id == id }?.metadata["title"].string ?? "software") + "…") Spacer() Button("Cancel", role: .cancel) { model.cancelInstallation() } }.padding(12) } if let message = model.launchError ?? model.launchMessage { HStack(alignment: .top) { Image(systemName: model.launchError == nil ? "info.circle" : "exclamationmark.triangle") Text(message).textSelection(.enabled).accessibilityIdentifier(model.launchError == nil ? "library-launch-message" : "library-launch-error") }.font(.callout).foregroundStyle(model.launchError == nil ? Color.secondary : Color.orange) .frame(maxWidth: .infinity, alignment: .leading).padding(12) } if model.launchBusy { HStack { ProgressView().controlSize(.small) Text(model.isDiskCompanion ? "Preparing a disk for DriveWire…" : "Preparing and starting the CoCo…") Spacer() Button("Stop Automatic Loading") { model.stopAutomaticLoading() }.accessibilityIdentifier("library-stop-loading") }.padding(12) } Divider() HStack { Text("Color Computer Archive software and VCC Plus-exclusive titles").font(.caption).foregroundStyle(.secondary) Spacer() if model.filtering { ProgressView().controlSize(.mini) } Text(model.catalog.map { "\($0.titles.count.formatted()) titles · \($0.releaseCount.formatted()) editions" } ?? "") .font(.caption).foregroundStyle(.secondary) }.padding(.horizontal, 16).padding(.vertical, 9) } .frame(minWidth: 900, maxWidth: .infinity, minHeight: 570, maxHeight: .infinity, alignment: .top) .task { await model.load() } .onChange(of: model.machineFocusRequest) { _, _ in if !model.isDiskCompanion { openWindow(id: "machine") } DispatchQueue.main.async { model.focusDisplay() } } .onChange(of: model.sourceFocusRequest) { _, _ in if !model.isDiskCompanion { openWindow(id: "c-development") } } .modifier(SoftwareLibraryLaunchPresentation(model: model)) .environment(\.companionLibraryAccess, model.companionAccess) .sheet(isPresented: $showManual) { VStack(spacing: 0) { SoftwareLibraryManualView(model: model.manual) Divider() HStack { Spacer(); Button("Done") { showManual = false }.keyboardShortcut(.defaultAction) }.padding(12) }.frame(minWidth: 700, minHeight: 560) } .sheet(item: $model.mediaChoice) { choice in SoftwareLibraryMediaChoiceView(choice: choice, choose: { model.chooseLaunchMember($0, choice: choice) }, cancel: { model.mediaChoice = nil }) } .alert("Return to Previous Setup?", isPresented: $confirmingReturn) { Button("Cancel", role: .cancel) { } Button("Restore Setup") { model.returnToPreviousSetup() }.accessibilityIdentifier("library-confirm-return") } 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() } } .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 } } message: { _ in Text("Your original download and working files will stay on this Mac, including any saved games or changes. Installing again creates a new working copy.") } } private var header: some View { HStack(spacing: 16) { Label("Software Library", systemImage: "books.vertical.fill").font(.title2.weight(.semibold)) Spacer(minLength: 10) if model.hasPreviousSetup { Button { confirmingReturn = true } label: { Image(systemName: "arrow.uturn.backward") } .help("Return to Previous Setup…").accessibilityLabel("Return to Previous Setup…") .accessibilityIdentifier("library-return-setup") .disabled(model.launchBusy || model.installingReleaseID != nil) } HStack(spacing: 7) { Image(systemName: "magnifyingglass").foregroundStyle(.secondary) TextField("Search titles, authors, or keywords", text: $model.query.text) .textFieldStyle(.plain).accessibilityLabel("Search software").accessibilityIdentifier("library-search") if !model.query.text.isEmpty { Button { model.query.text = "" } 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)) .frame(minWidth: 230, idealWidth: 340, maxWidth: 420) }.padding(16) } private var sidebar: some View { VStack(alignment: .leading, spacing: 0) { VStack(alignment: .leading, spacing: 4) { Text("Discover").font(.caption.weight(.semibold)).foregroundStyle(.secondary) scope("Cover Collection", icon: "rectangle.grid.2x2", scope: .showcase, id: "showcase") scope("Getting Started", icon: "sparkles", scope: .started, id: "getting-started") scope("All Software", icon: "books.vertical", scope: .all, id: "all") 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") }.padding(14) Divider() List { Section("Software Type") { ForEach(model.softwareTypes, id: \.self) { type in Button { model.browseType(type) } label: { Label(type == "Educational" ? "Education" : type, systemImage: SoftwareLibraryCategoryStyle.symbol(for: type)) .foregroundStyle(model.query.softwareType == type ? Color.accentColor : Color.primary) .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) }.buttonStyle(.plain).accessibilityIdentifier("library-type-" + type) } } Section("Archive Folders") { OutlineGroup(model.categories, children: \.children) { category in Button { model.browse(.all, category: category.id) } label: { Text(category.name).font(.callout).lineLimit(2) .foregroundStyle(model.query.category == category.id ? Color.accentColor : Color.primary) .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) }.buttonStyle(.plain).help(category.id).accessibilityIdentifier("library-category-" + category.id) } } }.listStyle(.sidebar).scrollContentBackground(.hidden) }.background(Color(nsColor: .windowBackgroundColor)) } private func scope(_ title: String, icon: String, scope: LibraryBrowseQuery.Scope, id: String) -> some View { Button { model.browse(scope) } label: { Label(title, systemImage: icon).fontWeight(model.query.scope == scope && model.query.category.isEmpty && model.query.softwareType.isEmpty ? .semibold : .regular) .foregroundStyle(model.query.scope == scope && model.query.category.isEmpty && model.query.softwareType.isEmpty ? Color.accentColor : Color.primary) .frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 4).contentShape(Rectangle()) }.buttonStyle(.plain).accessibilityIdentifier("library-scope-" + id) } private var heading: String { 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 { case .showcase: return "Cover Collection" case .started: return "Getting Started" case .all: return "All Software" case .favorites: return "Favorites" case .installed: return "Installed" } } private var browser: some View { VStack(alignment: .leading, spacing: 12) { HStack { VStack(alignment: .leading, spacing: 3) { Text(heading).font(.title3.weight(.semibold)).accessibilityIdentifier("library-heading") Text("\(model.rows.count.formatted()) \(model.rows.count == 1 ? "title" : "titles")").foregroundStyle(.secondary).font(.caption) .accessibilityIdentifier("library-result-count") } Spacer() Picker("Presentation", selection: Binding(get: { model.layout }, set: { value in guard model.layout != value else { return } Task { @MainActor in model.layout = value } })) { Image(systemName: "square.grid.2x2").tag("Shelf").help("Show software on the shelf").accessibilityLabel("Shelf") Image(systemName: "list.bullet").tag("Table").help("Show software in a table").accessibilityLabel("Table") }.pickerStyle(.segmented).labelsHidden().frame(width: 80).accessibilityIdentifier("library-layout") Button { showFilters.toggle() } label: { Image(systemName: "line.3.horizontal.decrease.circle") } .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 == .showcase { Text("Software with cover art, labels and screenshots.") .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16) } else if model.query.scope == .started { 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.") .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16) } if !activeFilters.isEmpty { HStack(alignment: .top, spacing: 8) { Text(activeFilters.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary) .frame(maxWidth: .infinity, alignment: .leading).accessibilityIdentifier("library-active-filters") Button("Clear filters") { model.clearFilters() }.controlSize(.small) }.padding(.horizontal, 16) } if model.loading { Spacer(); ProgressView("Opening the library…").frame(maxWidth: .infinity); Spacer() } else if let error = model.error { ContentUnavailableView { Label("Library unavailable", systemImage: "books.vertical") } description: { Text(error) } actions: { Button("Try Again") { Task { await model.load() } } } } else if model.rows.isEmpty { emptyState.frame(maxWidth: .infinity, maxHeight: .infinity) } else if model.layout == "Table" { Table(model.rows, selection: Binding(get: { model.selection }, set: { value in // AppKit can report selection while SwiftUI installs/removes the table. // Publish on the next main-actor turn, and ignore teardown callbacks. guard model.selection != value else { return } Task { @MainActor in guard model.layout == "Table", value == nil || model.rows.contains(where: { $0.id == value }) else { return } model.selection = value } })) { TableColumn("Title", value: \.name).width(min: 140, ideal: 240) TableColumn("Format", value: \.formats).width(min: 65, ideal: 95) TableColumn("Size", value: \.size).width(55) }.accessibilityLabel("Software titles") } else { ScrollView { LazyVGrid(columns: [GridItem(.adaptive(minimum: 155, maximum: 215), spacing: 18)], alignment: .leading, spacing: 22) { ForEach(model.rows) { row in shelfCard(row) } }.padding(16) }.background(Color.primary.opacity(0.018)) } } } private var activeFilters: [String] { var labels: [String] = [] if !model.query.softwareType.isEmpty { labels.append(SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType)) } if !model.query.media.isEmpty { labels.append(["cartridge": "Cartridge", "cassette": "Cassette", "disk": "Disk", "sdc": "SDC SD card", "hard-disk": "Hard disk"][model.query.media] ?? model.query.media) } if !model.query.system.isEmpty { labels.append(systemName(model.query.system)) } if !model.query.evidence.isEmpty { labels.append(["checked": "VCC Plus spot-checked", "manual": "Manual setup", "notes": "Has compatibility notes"][model.query.evidence] ?? model.query.evidence) } return labels + model.query.additionalFilterLabels } private var searchIsActive: Bool { !model.query.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } private var narrowed: Bool { searchIsActive || !activeFilters.isEmpty || !model.query.category.isEmpty } 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") } 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") } 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") } Button("Browse All Titles") { model.query = LibraryBrowseQuery(scope: .all) } } } private var filters: some View { Form { Picker("Software Type", selection: $model.query.softwareType) { Text("All types").tag("") ForEach(model.softwareTypes, id: \.self) { Text(SoftwareLibraryOwnedGame.categoryLabel($0)).tag($0) } }.accessibilityIdentifier("library-filter-type") if model.isDiskCompanion { LabeledContent("Format") { Label("Disk images only", systemImage: "externaldrive") } } else { Picker("Format", selection: $model.query.media) { Text("All formats").tag("") Text("Cartridge").tag("cartridge"); Text("Cassette").tag("cassette"); Text("Disk").tag("disk") Text("SDC SD card").tag("sdc"); Text("Hard disk").tag("hard-disk") }.accessibilityIdentifier("library-filter-media") } Picker("System", selection: $model.query.system) { Text("All systems").tag("") ForEach(Array(Set(model.catalog?.releases.map(\.system) ?? [])).sorted(), id: \.self) { Text(systemName($0)).tag($0) } }.accessibilityIdentifier("library-filter-system") Picker("Environment", selection: $model.query.environment) { Text("All environments").tag("") ForEach(["basic", "disk-basic", "os9", "unknown"], id: \.self) { Text(LibraryBrowseQuery.environmentLabels[$0]!).tag($0) } }.accessibilityIdentifier("library-filter-environment") Picker("Setup", selection: $model.query.evidence) { Text("All titles").tag(""); Text("VCC Plus spot-checked").tag("checked") Text("Manual setup").tag("manual"); Text("Has compatibility notes").tag("notes") }.accessibilityIdentifier("library-filter-evidence") Picker("Sort by", selection: $model.query.sort) { ForEach(LibraryBrowseQuery.Sort.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.accessibilityIdentifier("library-filter-sort") DisclosureGroup("Advanced Filters", isExpanded: $showAdvancedFilters) { Picker("Processor", selection: $model.query.processor) { Text("Any processor").tag("") ForEach(["6309", "either", "unknown"], id: \.self) { Text(LibraryBrowseQuery.processorLabels[$0]!).tag($0) } }.accessibilityIdentifier("library-filter-processor") Picker("Hardware", selection: Binding(get: { model.query.hardware }, set: { value in var next = model.query; next.hardware = value; next.hardwareUse = ""; model.query = next })) { Text("Any hardware").tag("") ForEach(["speech-sound", "orchestra90", "joystick"], id: \.self) { Text(LibraryBrowseQuery.hardwareLabels[$0]!).tag($0) } }.accessibilityIdentifier("library-filter-hardware") if !model.query.hardware.isEmpty { Picker("Use", selection: $model.query.hardwareUse) { Text("Any reported use").tag("") ForEach(["required", "optional", "unspecified"], id: \.self) { Text(LibraryBrowseQuery.hardwareUseLabels[$0]!).tag($0) } }.accessibilityIdentifier("library-filter-hardware-use") } Picker("Display", selection: $model.query.displayFeature) { Text("Any display features").tag("") ForEach(["semigraphics", "SG-8", "SG-12", "SG-24"], id: \.self) { Text(LibraryBrowseQuery.displayLabels[$0]!).tag($0) } }.accessibilityIdentifier("library-filter-display") Text("Based on catalog information. Missing details do not mean unsupported; reported hardware use may be optional.") .font(.caption).foregroundStyle(.secondary) } }.formStyle(.grouped).fixedSize(horizontal: false, vertical: true) } private func shelfCard(_ row: LibraryBrowseRow) -> some View { let release = row.matchingReleases.first! let asset = release.assets.first { SoftwareLibraryArtworkCache.canDisplay($0) } return Button { model.selection = row.id } label: { VStack(alignment: .leading, spacing: 8) { SoftwareLibraryArtworkView(asset: asset, cacheDirectory: model.artworkDirectory, softwareType: LibraryBrowseQuery.type(of: release, related: row.title.releases)) .frame(height: 180) .overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(model.selection == row.id ? Color.accentColor : .clear, lineWidth: 3)) .shadow(color: .black.opacity(0.1), radius: 3, y: 3) HStack(alignment: .top, spacing: 4) { 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) }.padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).accessibilityIdentifier("library-title-" + row.id) .accessibilityLabel(row.name + ", " + row.formats).help(row.name) } @ViewBuilder private var detail: some View { if let row = model.selectedRow, let release = model.selectedRelease { ScrollView { VStack(alignment: .leading, spacing: 18) { HStack(alignment: .top) { Text(row.name).font(.title2.weight(.semibold)).textSelection(.enabled) .accessibilityIdentifier("library-detail-title") Spacer(minLength: 4) Button { model.state.toggleFavorite(row.id) } label: { Image(systemName: model.state.isFavorite(row.id) ? "heart.fill" : "heart") .foregroundStyle(model.state.isFavorite(row.id) ? Color.pink : Color.secondary) }.buttonStyle(.borderless).controlSize(.large) .help(model.state.isFavorite(row.id) ? "Remove \(row.name) from favorites" : "Add \(row.name) to favorites").accessibilityLabel(model.state.isFavorite(row.id) ? "Remove Favorite" : "Add Favorite") .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) if let owned = release.ownedGame { Label("VCC Plus-exclusive", systemImage: "sparkles").font(.headline) .accessibilityIdentifier("library-exclusive") Text("By " + owned.author).font(.callout) Text("Part of the VCC Plus collection. Compatible real CoCo hardware can run this program too.") .font(.caption).foregroundStyle(.secondary) } if let manual = release.primaryManualAsset { Button { model.manual.open(manual, directory: model.state.directory.appendingPathComponent("Manuals"), companion: model.companionAccess) if model.isDiskCompanion { showManual = true } else { openWindow(id: "software-manual") } } label: { Label(manual.manualURL?.pathExtension.lowercased() == "txt" ? "Read Instructions" : "Read Manual", systemImage: "book") } .accessibilityIdentifier("library-read-manual") } if row.title.releases.count > 1 { Picker("Format / Edition", selection: Binding(get: { release.id }, set: model.chooseRelease)) { ForEach(row.title.releases) { edition in Text(edition.editionLabel).tag(edition.id) .accessibilityIdentifier("library-release-" + edition.id) } }.accessibilityIdentifier("library-release-picker") } else { Label(release.mediaLabel, systemImage: mediaIcon(release.mediaType)).foregroundStyle(.secondary) } if !release.videoBadges.isEmpty { ViewThatFits(in: .horizontal) { HStack { videoBadges(release) } VStack(alignment: .leading) { videoBadges(release) } } } installationCard(release) setupCard(release) if let owned = release.ownedGame { Link(destination: owned.onlineManualURL) { Label("Online Manual", systemImage: "book.pages") } .accessibilityIdentifier("library-online-manual") if model.canOpenSource { sourceCard(release, owned: owned) } Link(destination: owned.projectURL) { Label("Visit Project", systemImage: "arrow.up.right.square") } } if !release.setup.compatibilityNotes.isEmpty || !release.setup.configurationRequirements.isEmpty { VStack(alignment: .leading, spacing: 8) { Label("Compatibility", systemImage: "info.circle").font(.headline) Text((release.setup.compatibilityNotes + release.setup.configurationRequirements).joined(separator: "\n\n")) .font(.callout).textSelection(.enabled).accessibilityIdentifier("library-compatibility-notes") } } assetLinks(release) DisclosureGroup("Edition & source details") { metadata(release, title: row.title).padding(.top, 10) } .font(.callout) if release.ownedGame == nil { Link(destination: release.sourceURL.deletingLastPathComponent().appendingPathComponent("", isDirectory: true)) { Label("View on Color Computer Archive", systemImage: "arrow.up.right.square") } } 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.") .font(.caption).foregroundStyle(.secondary) }.padding(18).frame(maxWidth: .infinity, alignment: .leading) }.id(release.id) } else { ContentUnavailableView("Choose a title", systemImage: "book.closed", description: Text("Explore its editions, loading instructions, and manuals.")) } } private func sourceCard(_ release: SoftwareLibraryRelease, owned: SoftwareLibraryOwnedGame) -> some View { SecondaryCard { Label("Learn from the source", systemImage: "curlybraces").font(.headline) Text("Download an editable copy to a new folder and open it in C Development. Opening does not build, run or change the CoCo.") .font(.callout).fixedSize(horizontal: false, vertical: true) Button("Open Source…", systemImage: "arrow.down.document") { model.chooseSourceDestination(release) } .disabled(model.importingSourceID != nil).accessibilityIdentifier("library-open-source") if model.importingSourceID == release.id { if let fraction = model.sourceImportFraction { ProgressView(value: fraction) } else { ProgressView().controlSize(.small) } Button("Cancel Source Download", role: .cancel) { model.cancelSourceImport() } } if model.sourceDetailsReleaseID == release.id { if let message = model.sourceImportMessage { Text(message).font(.callout).textSelection(.enabled) } if let error = model.sourceImportError { Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).font(.callout).textSelection(.enabled) } if let directory = model.importedSourceDirectory { Button("Show Source Folder", systemImage: "folder") { NSWorkspace.shared.activateFileViewerSelecting([directory]) } } } Link("Source Repository", destination: owned.sourceRepositoryURL).font(.callout) ForEach(Array(owned.source.companionPackages.enumerated()), id: \.offset) { _, package in Link("Download Corresponding Library Sources", destination: package.url).font(.callout) } } } @ViewBuilder private func installationCard(_ release: SoftwareLibraryRelease) -> some View { SecondaryCard { if model.installingReleaseID == release.id { Label(progressTitle, systemImage: "arrow.down.circle").font(.headline) .accessibilityIdentifier("library-install-status") if let fraction = model.installProgress?.fraction { ProgressView(value: fraction) } else { ProgressView().controlSize(.small) } if let progress = model.installProgress, progress.stage == .downloading { Text("\(ByteCountFormatter.string(fromByteCount: progress.receivedBytes, countStyle: .file)) of \(ByteCountFormatter.string(fromByteCount: progress.totalBytes, countStyle: .file))") .font(.caption).foregroundStyle(.secondary) } Button("Cancel", role: .cancel) { model.cancelInstallation() }.accessibilityIdentifier("library-cancel-install") } else if let installed = model.state.installedReleases[release.id] { Label("Installed", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(.green) .accessibilityIdentifier("library-install-status") if model.canLaunch { playButton(release, installed: true) } 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") } 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") } .buttonStyle(.bordered) .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil || model.recoveringInstallations || release.downloadURLs.isEmpty) .accessibilityIdentifier(model.installationErrors[release.id] == nil ? "library-install" : "library-retry-install") Text(ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file) + " download · Does not start the software") .font(.caption).foregroundStyle(.secondary) Text("Keeps the original files and creates your own writable copy. Expanded files may need considerably more space than the download.") .font(.caption).foregroundStyle(.secondary) } if let error = model.installationErrors[release.id] { Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) .accessibilityIdentifier("library-install-error").textSelection(.enabled) } } } private func playButton(_ release: SoftwareLibraryRelease, installed: Bool) -> some View { Button { model.play(release) } label: { Label(model.launchLabel(release, installed: installed), systemImage: model.launchSymbol(release)) }.buttonStyle(.borderedProminent) .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil || model.recoveringInstallations) .accessibilityIdentifier("library-play") } private var progressTitle: String { switch model.installProgress?.stage { case .downloading: return "Downloading…" case .verifying: return "Checking download…" case .extracting: return "Unpacking…" case .preparing: return "Preparing your copy…" case .complete: return "Finishing installation…" case nil: return "Preparing download…" } } @ViewBuilder private func videoBadges(_ release: SoftwareLibraryRelease) -> some View { ForEach(release.videoBadges, id: \.self) { badge in Text(badge).font(.caption.weight(.medium)).padding(.horizontal, 8).padding(.vertical, 4) .background(.quaternary, in: Capsule()) .help(badge.hasPrefix("6847T1") ? "Archive reports support for the 6847T1 video chip. See this edition’s compatibility notes for VCC Plus checks." : "Uses a legacy CoCo semigraphics display mode.") .accessibilityIdentifier("library-video-badge-" + badge) } } private func setupCard(_ release: SoftwareLibraryRelease) -> some View { SecondaryCard { Label("Using this software", systemImage: "play.rectangle").font(.headline) if let profile = release.setup.profile { Text(profileName(profile)).font(.subheadline.weight(.medium)) Text([release.setup.processor.map { $0 + " CPU" }, release.setup.ramKiB.map { $0 >= 1024 ? "\($0 / 1024) MB RAM" : "\($0) KB RAM" }].compactMap { $0 }.joined(separator: " · ")) .font(.caption).foregroundStyle(.secondary) } Text(loadingInstructions(release)) .font(.callout).textSelection(.enabled).accessibilityIdentifier("library-loading-instructions") if let command = release.setup.command, !command.isEmpty { Text(command.replacingOccurrences(of: "\r", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines)) .font(.system(.callout, design: .monospaced)).textSelection(.enabled) .accessibilityIdentifier("library-loading-command") .frame(maxWidth: .infinity, alignment: .leading).padding(10) .background(.background, in: RoundedRectangle(cornerRadius: 6)) } if !release.setup.reasons.isEmpty { Text(release.setup.reasons.joined(separator: "\n")).font(.callout).foregroundStyle(.secondary) } let controls = release.setup.controls.object if !controls.isEmpty { 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) .accessibilityIdentifier("library-controls-" + key) } } } } } @ViewBuilder private func assetLinks(_ release: SoftwareLibraryRelease) -> some View { let manuals = release.assets.filter(\.isManual) if !manuals.isEmpty { VStack(alignment: .leading, spacing: 8) { Text("Manuals").font(.headline) ForEach(manuals) { manual in if manual.manualURL != nil { Button { model.manual.open(manual, directory: model.state.directory.appendingPathComponent("Manuals"), companion: model.companionAccess) if model.isDiskCompanion { showManual = true } else { openWindow(id: "software-manual") } } label: { Label(manual.name, systemImage: "book") } .buttonStyle(.link).font(.callout).help("Read the manual in VCC Plus") .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") } } } } } private func metadata(_ release: SoftwareLibraryRelease, title: SoftwareLibraryTitle) -> some View { VStack(alignment: .leading, spacing: 9) { Text(release.name).textSelection(.enabled) LabeledContent("Software type", value: LibraryBrowseQuery.type(of: release, related: title.releases)) LabeledContent("System", value: systemName(release.system)) if let os = release.setup.configuration["os_hint"].string, os != "unknown" { LabeledContent("Operating system", value: os) } if let environment = LibraryBrowseQuery.environmentLabels[release.environment], release.environment != "unknown" { LabeledContent("Loading environment", value: environment) } if let processor = LibraryBrowseQuery.processorLabels[release.processorRequirement], release.processorRequirement != "unknown" { Text(processor) } ForEach(release.hardwareSupport.keys.sorted(), id: \.self) { device in if let label = LibraryBrowseQuery.hardwareLabels[device] { LabeledContent(label, value: LibraryBrowseQuery.hardwareUseLabels[release.hardwareSupport[device] ?? ""] ?? "Requirement unspecified") } } 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)) 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" { 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") 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.videoModes.isEmpty { Text("Video: " + release.videoModes.joined(separator: ", ")) } if let note = release.setup.curationNote { Text(note) } if !release.assets.isEmpty { Divider() Text("Artwork & manual sources").fontWeight(.medium) ForEach(release.assets) { asset in VStack(alignment: .leading, spacing: 3) { 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) } } } } DisclosureGroup("File identity") { Text(release.packageSHA256).font(.system(.caption, design: .monospaced)).textSelection(.enabled) } } } private func loadingInstructions(_ release: SoftwareLibraryRelease) -> String { let instructions = release.setup.instructions guard !instructions.isEmpty else { return "Loading instructions are not yet available for this edition." } // The command has its own readable code block below, so don't repeat it // as an internal recipe annotation in the surrounding guidance. if let range = instructions.range(of: "Guest command:"), release.setup.command != nil { return String(instructions[.. 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 } } 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 } } private func mediaIcon(_ value: String) -> String { switch value { case "cartridge": return "memorychip"; case "cassette": return "recordingtape"; case "sdc": return "sdcard"; default: return "externaldrive" } } } private struct SoftwareLibraryLaunchPresentation: ViewModifier { @ObservedObject var model: SoftwareLibraryModel func body(content: Content) -> some View { #if VCC_COMPANION_CLIENT content #else content.sheet(item: $model.launchPreview) { preview in SoftwareLibraryLaunchPreviewView(preview: preview, confirm: model.confirmLaunch, cancel: { model.launchPreview = nil }) } #endif } }