// SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import AppKit import UniformTypeIdentifiers struct ProfileControlsView: View { private static let profileType = UTType(exportedAs: "com.brianholman.vccplus.mac.configuration-profile", conformingTo: .json) private static let legacyProfileType = UTType(importedAs: "org.vcc.mac.configuration-profile", conformingTo: .json) @ObservedObject var machine: MachineModel @StateObject private var library: ProfileLibrary init(machine: MachineModel, store: ProfileStore = .standard) { self.machine = machine _library = StateObject(wrappedValue: ProfileLibrary(store: store)) } @State private var selection: String? = SystemProfile.diskBasic.id @State private var working = false private var selected: ConfigurationProfile? { library.profiles.first { $0.id.uuidString == selection } } private var selectedSystem: SystemProfile? { SystemProfile.allCases.first { $0.id == selection } } private var unavailable: Bool { working || machine.busy || machine.state == .closed } var body: some View { VStack(alignment: .leading, spacing: 0) { VStack(alignment: .leading, spacing: 14) { SecondaryHeader(title: "Configuration Profiles", symbol: "square.grid.2x2", subtitle: "Named setups and file locations — not saved machine snapshots.") HStack { Button(action: saveCurrent) { Label("Save Current As…", systemImage: "doc.badge.plus") } Button(action: importProfile) { Label("Import…", systemImage: "folder") } Spacer() Button(action: library.reload) { Label("Refresh", systemImage: "arrow.clockwise") } }.disabled(unavailable) }.padding(20) Divider() HSplitView { List(selection: $selection) { Section("System Profiles") { ForEach(SystemProfile.allCases) { profile in Label(profile.name, systemImage: "lock.fill").tag(profile.id) .accessibilityIdentifier(profile.id) } } Section("My Profiles") { ForEach(library.profiles) { profile in Label(profile.name, systemImage: "doc.text").tag(profile.id.uuidString) } } }.listStyle(.sidebar).frame(minWidth: 175, idealWidth: 220, maxWidth: 280) ScrollView { VStack(alignment: .leading, spacing: 16) { if let kind = selectedSystem { systemDetails(kind) } else if let profile = selected { personalDetails(profile) } else { Label("Select a profile", systemImage: "square.grid.2x2").font(.title2) Text(library.profiles.isEmpty ? "Save your current setup to create the first personal profile." : "Select a profile to review its setup and files.") .foregroundStyle(.secondary) } }.frame(maxWidth: .infinity, alignment: .leading).padding(20) }.frame(minWidth: 380) }.frame(minHeight: 260).disabled(unavailable) Divider() VStack(alignment: .leading, spacing: 10) { if let error = library.error ?? machine.profileError { ScrollView { Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 100) } HStack(spacing: 12) { if working || machine.busy { ProgressView().controlSize(.small) } if let name = machine.profileName { Text("Last loaded: \(name)").font(.caption).foregroundStyle(.secondary) .lineLimit(1).truncationMode(.middle) .help("Later changes do not update the saved profile automatically.") } else { Text(selectedSystem != nil ? "System profiles are read-only." : "Load replaces the current setup and clears RAM.") .font(.caption).foregroundStyle(.secondary) } Spacer() if selected != nil { personalActions.disabled(unavailable) } Button(action: loadSelected) { Label("Load…", systemImage: "arrow.clockwise") } .keyboardShortcut(.defaultAction) .disabled(unavailable || (selected == nil && selectedSystem == nil) || selectedSystem.map { machine.systemProfileUnavailableReason($0) != nil } == true) } }.padding(16) }.frame(minWidth: 740, minHeight: 540) } @ViewBuilder private var personalActions: some View { if let profile = selected { ProfileActionsMenu(profileID: profile.id, update: updateSelected, rename: renameSelected, export: exportSelected, delete: deleteSelected).equatable() } } private func systemDetails(_ kind: SystemProfile) -> some View { VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 6) { Label(kind.name, systemImage: "lock.fill").font(.title2.bold()) Text(kind.summary).foregroundStyle(.secondary) } SecondaryCard { VStack(alignment: .leading, spacing: 10) { Label("Setup", systemImage: "cpu").font(.headline) Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) { summaryRow("Hardware", "Motorola 6809 · 512 KB") summaryRow("Video", "Composite TV") summaryRow("Startup", kind == .cocoSDC ? "Slot 4 · SDC-DOS" : kind == .diskBasic ? "Slot 4 · Disk BASIC" : "Slot 4 · RGBDOS") Divider().gridCellColumns(2).gridCellUnsizedAxes(.horizontal).padding(.vertical, 4) if kind == .cocoSDC { summaryRow("SD card", "Local writable folder · CoCo SDC") summaryRow("SDC0", "HELLO.DSK · mounted at startup") } else { summaryRow("FD0", "Hello World floppy") } if kind == .hardDriveBasic || kind == .nitros9 { summaryRow("HD0", kind == .nitros9 ? "NitrOS-9 system disk" : "Hello World hard disk") } if kind == .nitros9 { summaryRow("HD1", "Shared Hard Drive BASIC disk") } if kind == .diskBasic { summaryRow("Cassette", "Hello World · stopped") } } SecondaryHelp(title: "Setup details") { Text(kind.explanation) } } } VStack(alignment: .leading, spacing: 6) { Label(kind == .nitros9 ? "Load restarts and automatically boots NitrOS-9." : "Load restarts BASIC with an empty program. Examples do not run automatically.", systemImage: "arrow.clockwise") .font(.callout).fixedSize(horizontal: false, vertical: true) Text(kind == .nitros9 ? "Existing data is kept. An empty shared OS-9 area is initialized with a backup." : kind == .diskBasic ? "Your writable media is preserved. This is the same setup as Restore App Defaults." : "Your writable media is preserved.") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } if let reason = machine.systemProfileUnavailableReason(kind) { Label(reason, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) .fixedSize(horizontal: false, vertical: true) } SecondaryCard { VStack(alignment: .leading, spacing: 10) { Label("Make it yours", systemImage: "doc.on.doc").font(.headline) ViewThatFits(in: .horizontal) { HStack(alignment: .top, spacing: 16) { copyChoice(kind, freshMedia: false).frame(width: 180, alignment: .leading) copyChoice(kind, freshMedia: true).frame(width: 230, alignment: .leading) } VStack(alignment: .leading, spacing: 12) { copyChoice(kind, freshMedia: false) copyChoice(kind, freshMedia: true) } } Text("Both create an editable personal profile. Existing files and the current session stay unchanged; load the new profile when ready.") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } } SecondaryHelp(title: kind == .nitros9 ? "Using NitrOS-9" : "Try the examples") { if kind == .nitros9 { Nitros9UsageGuide() } else if kind == .cocoSDC { SDCUsageGuide() } else { Text(kind.instructions).textSelection(.enabled) } } } } private func summaryRow(_ title: String, _ value: String) -> some View { GridRow(alignment: .firstTextBaseline) { Text(title).foregroundStyle(.secondary) Text(value).fixedSize(horizontal: false, vertical: true) } } private func copyChoice(_ kind: SystemProfile, freshMedia: Bool) -> some View { VStack(alignment: .leading, spacing: 4) { Button { copySystem(kind, freshMedia: freshMedia) } label: { Label(freshMedia ? "Create Fresh Starter Media…" : "Save as My Profile…", systemImage: freshMedia ? "doc.badge.plus" : "doc.on.doc") }.fixedSize().accessibilityIdentifier(freshMedia ? "fresh-system-media" : "copy-system-profile") .disabled(machine.systemProfileUnavailableReason(kind) != nil) Text(freshMedia ? "New, clean media copies." : "The same working media files.") .font(.caption).foregroundStyle(.secondary) } } private func personalDetails(_ profile: ConfigurationProfile) -> some View { VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 6) { Label(profile.name, systemImage: "doc.text").font(.title2.bold()) Text(ProfileGuidance(profile).title).foregroundStyle(.secondary) } SecondaryCard { Label("Setup", systemImage: "cpu").font(.headline) Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) { summaryRow("Processor", profile.machine.use6309 ? "Hitachi 6309" : "Motorola 6809") summaryRow("Memory", MachineSettings.memoryLabels[profile.machine.ram]) summaryRow("CPU overclock", "\(profile.machine.overclock)×") summaryRow("Pacing", profile.machine.fastForward ? "Fast-forward · playback silenced" : "Normal") summaryRow("Cartridges", profile.media.cartridges?.multiPak == true ? "Multi-Pak" : "Single cartridge") } Text(ProfileGuidance(profile).coverage).font(.caption).foregroundStyle(.secondary) } if profile.systemROM == nil { Label("No system ROM assigned. Choose one after loading this setup.", systemImage: "exclamationmark.triangle") .foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true) } if profile.bootNitros9 == true { Label("After Run, this profile automatically boots NitrOS-9 with DOS 255. Cold Restart opens the archive menu; select 6 (EXIT TO BASIC) and press Return.", systemImage: "info.circle") .font(.callout).fixedSize(horizontal: false, vertical: true) } SecondaryCard { Label("Files", systemImage: "folder").font(.headline) if profile.references.isEmpty { Text("No files assigned.").foregroundStyle(.secondary) } ForEach(profile.references, id: \.key) { reference in HStack(alignment: .top, spacing: 12) { VStack(alignment: .leading, spacing: 3) { Text(reference.key.label).font(.caption).foregroundStyle(.secondary) Text(reference.url.lastPathComponent).lineLimit(1).truncationMode(.middle) Text(reference.url.path).font(.caption).foregroundStyle(.secondary) .lineLimit(1).truncationMode(.middle).textSelection(.enabled).help(reference.url.path) }.frame(maxWidth: .infinity, alignment: .leading) Button { replace(reference.key, in: profile) } label: { Label("Replace…", systemImage: "folder") } .accessibilityLabel("Replace \(reference.key.label)") } } Text("Replace updates this saved profile's file location. Load the profile to apply it; files are not copied.") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } SecondaryHelp(title: "About this configuration") { Text(ProfileGuidance(profile).explanation).fixedSize(horizontal: false, vertical: true) Text("Later changes do not update the saved profile automatically. Use Actions → Update from Current to replace its saved setup.") } } } private func namePrompt(_ title: String, initial: String) -> String? { let alert = NSAlert(); alert.messageText = title let field = NSTextField(string: initial); field.frame = NSRect(x: 0, y: 0, width: 320, height: 24) field.setAccessibilityIdentifier("profile-name") alert.accessoryView = field; alert.addButton(withTitle: "Save"); alert.addButton(withTitle: "Cancel") alert.window.initialFirstResponder = field guard alert.runModal() == .alertFirstButtonReturn else { return nil } return field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) } private func confirm(_ title: String, detail: String, action: String) -> Bool { let alert = NSAlert(); alert.messageText = title; alert.informativeText = detail alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: action) return alert.runModal() == .alertSecondButtonReturn } private func saveCurrent() { guard let name = namePrompt("Save Current Setup as Profile", initial: "") else { return } capture(name: name, id: nil) } private func capture(name: String, id: UUID?) { working = true Task { @MainActor in defer { working = false } do { let profile = try await machine.captureProfile(name: name, replacing: id) if library.save(profile) { selection = profile.id.uuidString } } catch { library.error = error.localizedDescription } } } private func copySystem(_ kind: SystemProfile, freshMedia: Bool) { guard let name = namePrompt(freshMedia ? "Name Setup with Fresh Starter Media" : "Save System Setup as My Profile", initial: "My " + kind.name), !name.isEmpty else { return } do { try ConfigurationProfile(name: name).validate() } catch { library.error = error.localizedDescription; return } // Check names before allocating a fresh hard disk. Never overwrite a profile. guard !library.profiles.contains(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else { library.error = "A profile with that name already exists. Choose another name."; return } working = true; library.error = nil Task { @MainActor in defer { working = false } do { var profile = try await machine.makeSystemProfile(kind, freshMedia: freshMedia) profile.name = name if library.save(profile) { selection = profile.id.uuidString } } catch { library.error = error.localizedDescription } } } private func loadSelected() { if let kind = selectedSystem { guard confirm("Load “\(kind.name)”?", detail: (kind == .nitros9 ? "This restarts and boots NitrOS-9. Empty OS-9 space on the shared data disk is initialized with a backup. " : "This restarts BASIC with the system setup. ") + " Current RAM and RAM disk contents are cleared. Writable disks are saved first; unsaved temporary disks or recordings block the switch. Existing starter media is reused, never erased. Neither example loads or runs automatically.", action: "Load Profile") else { return } library.error = nil; working = true Task { @MainActor in _ = await machine.loadSystemProfile(kind); working = false } return } guard let profile = selected, confirm("Load “\(profile.name)”?", detail: "This clears the current machine's RAM and RAM disk contents and replaces its setup and media. Writable disk changes will be saved first; unsaved temporary images or recordings block the switch. The new machine starts paused. Profiles are not saved-game snapshots." + (profile.bootNitros9 == true ? " Pressing Run will automatically boot NitrOS-9." : ""), action: "Load Profile") else { return } library.error = nil; working = true Task { @MainActor in await machine.loadProfile(profile); working = false } } private func updateSelected() { guard let profile = selected, confirm("Update “\(profile.name)” from the current setup?", detail: "This replaces the saved configuration and file assignments. It does not copy media contents or alter their files.", action: "Update Profile") else { return } capture(name: profile.name, id: profile.id) } private func renameSelected() { guard var profile = selected, let name = namePrompt("Rename Profile", initial: profile.name) else { return } profile.name = name; library.save(profile) } private func deleteSelected() { guard let profile = selected, confirm("Delete “\(profile.name)” from Profiles?", detail: "Its ROMs and media files are kept. The current machine is unchanged.", action: "Delete Profile") else { return } library.delete(profile.id); if library.error == nil { selection = nil } } private func replace(_ reference: ConfigurationProfile.Reference, in original: ConfigurationProfile) { let panel = NSOpenPanel(); panel.title = "Replace \(reference.label)" if case .sdcFolder = reference { panel.canChooseDirectories = true; panel.canChooseFiles = false } else { panel.canChooseDirectories = false; panel.canChooseFiles = true } panel.allowsMultipleSelection = false panel.begin { result in guard result == .OK, let url = panel.url else { return } var profile = original; profile.replace(reference, with: url); library.save(profile) } } private func importProfile() { let panel = NSOpenPanel(); panel.title = "Import Configuration Profile" panel.allowedContentTypes = [Self.profileType, Self.legacyProfileType, .json] panel.canChooseDirectories = false; panel.allowsMultipleSelection = false panel.begin { result in guard result == .OK, let url = panel.url else { return } do { var profile = try ProfileStore.read(url); profile.id = UUID() guard let name = namePrompt("Name Imported Profile", initial: profile.name) else { return } profile.name = name if library.save(profile) { selection = profile.id.uuidString } } catch { library.error = error.localizedDescription } } } private func exportSelected() { guard let profile = selected else { return } let panel = NSSavePanel(); panel.title = "Export Configuration Profile" panel.allowedContentTypes = [Self.profileType] panel.nameFieldStringValue = profile.name.replacingOccurrences(of: "/", with: "-") + ".vccprofile" panel.message = "The file includes local file paths and controller identifiers, but no ROM or media contents." panel.begin { result in guard result == .OK, let url = panel.url else { return } do { try ProfileStore.write(profile, to: url); library.error = nil } catch { library.error = error.localizedDescription } } } } // Frame/status updates must not replace an open menu. The selected profile is // its identity; commands still read the authoritative library and machine state. private struct ProfileActionsMenu: View, Equatable { let profileID: UUID let update: () -> Void let rename: () -> Void let export: () -> Void let delete: () -> Void static func == (lhs: Self, rhs: Self) -> Bool { lhs.profileID == rhs.profileID } var body: some View { Menu { Button(action: update) { Label("Update from Current…", systemImage: "arrow.triangle.2.circlepath") } Button(action: rename) { Label("Rename…", systemImage: "pencil") } Button(action: export) { Label("Export…", systemImage: "square.and.arrow.up") } Divider() Button(role: .destructive, action: delete) { Label("Delete…", systemImage: "trash") } } label: { Label("Actions", systemImage: "ellipsis.circle") } .fixedSize().accessibilityIdentifier("profile-actions") } }