// 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? @State private var personalCoverDropTargeted = false 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, creator submissions and your private software").font(.caption).foregroundStyle(.secondary) Spacer() if model.filtering { ProgressView().controlSize(.mini) } Text(model.catalog.map { "Catalog: \($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)) .modifier(SoftwareLibraryPersonalPresentation(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 { 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 } } 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) } libraryActions HStack(spacing: 7) { Image(systemName: "magnifyingglass").foregroundStyle(.secondary) 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.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)) .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") scope("Personal Library", icon: "lock.rectangle.stack", scope: .personal, id: "personal") }.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.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 { case .showcase: return "Cover Collection" case .started: return "Getting Started" 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 { 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 == .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) } 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 let orderingCaption { Text(orderingCaption) .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 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, !hasPersonalResults { 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") { 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 { 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)) } 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 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(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 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 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) } } } } 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) } } 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.isPersonal ? ", Personal Library" : "") + ", " + 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) } 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") 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) relatedReferences(release) DisclosureGroup("Edition & source details") { metadata(release, title: row.title).padding(.top, 10) } .font(.callout) 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.") .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 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) 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 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") 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") 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") } .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.isPersonal ? "your setup" : release.isArchive ? "the Archive" : "the author")).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.isArchive ? "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(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.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.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.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 { Divider() Text("Artwork & manual sources").fontWeight(.medium) ForEach(release.assets) { asset in VStack(alignment: .leading, spacing: 3) { 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) } } } } 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 } } @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 } } 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 } } /// 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) } } } }