Sync source edition with VCC Plus 3.7.0 build 63
This commit is contained in:
1 parent
c652a5276d
commit
b2ecec4d87
86 files changed
+10519
-472
No files matched your search
@@ -0,0 +1,556 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// Finder file drags use the native file-URL pasteboard representation. Image
|
||||
/// decoding remains in the receiving model/editor's bounded background work.
|
||||
struct PersonalCoverFileDropTarget: NSViewRepresentable {
|
||||
let enabled: Bool
|
||||
@Binding var isTargeted: Bool
|
||||
let perform: ([URL]) -> Bool
|
||||
|
||||
func makeNSView(context: Context) -> DropView {
|
||||
let view = DropView()
|
||||
view.registerForDraggedTypes([.fileURL])
|
||||
view.setAccessibilityElement(false)
|
||||
view.setAccessibilityHidden(true)
|
||||
return view
|
||||
}
|
||||
func updateNSView(_ view: DropView, context: Context) {
|
||||
view.enabled = enabled
|
||||
view.targeted = $isTargeted
|
||||
view.perform = perform
|
||||
if !enabled, isTargeted {
|
||||
DispatchQueue.main.async { [weak view] in
|
||||
guard let view, !view.enabled else { return }
|
||||
view.setTargeted(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
static func dismantleNSView(_ view: DropView, coordinator: ()) {
|
||||
view.unregisterDraggedTypes()
|
||||
view.perform = nil
|
||||
let targeted = view.targeted
|
||||
view.targeted = nil
|
||||
if targeted?.wrappedValue == true {
|
||||
DispatchQueue.main.async { targeted?.wrappedValue = false }
|
||||
}
|
||||
}
|
||||
final class DropView: NSView {
|
||||
var enabled = false
|
||||
var targeted: Binding<Bool>?
|
||||
var perform: (([URL]) -> Bool)?
|
||||
override func layout() {
|
||||
super.layout()
|
||||
#if VCC_UI_TESTING
|
||||
trace("layout frame=\(frame) window=\(String(describing: window?.frame))")
|
||||
#endif
|
||||
}
|
||||
private func trace(_ message: String) {
|
||||
#if VCC_UI_TESTING
|
||||
guard let path = ProcessInfo.processInfo.environment["VCC_COVER_DRAG_TRACE"] else { return }
|
||||
let url = URL(fileURLWithPath: path)
|
||||
var data = (try? Data(contentsOf: url)) ?? Data()
|
||||
guard data.count < 8192 else { return }
|
||||
data.append(Data((message + "\n").utf8)); try? data.write(to: url)
|
||||
#endif
|
||||
}
|
||||
|
||||
func setTargeted(_ value: Bool) {
|
||||
if targeted?.wrappedValue != value { targeted?.wrappedValue = value }
|
||||
}
|
||||
private func urls(from sender: NSDraggingInfo) -> [URL]? {
|
||||
guard enabled,
|
||||
let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self],
|
||||
options: [.urlReadingFileURLsOnly: true]) as? [URL],
|
||||
urls.count == 1, let url = urls.first, url.isFileURL,
|
||||
url.host == nil || url.host == "localhost", url.query == nil, url.fragment == nil else { return nil }
|
||||
return urls
|
||||
}
|
||||
private func operation(for sender: NSDraggingInfo) -> NSDragOperation {
|
||||
let accepts = sender.draggingSourceOperationMask.contains(.copy) && urls(from: sender) != nil
|
||||
setTargeted(accepts)
|
||||
return accepts ? .copy : []
|
||||
}
|
||||
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
|
||||
trace("entered enabled=\(enabled) frame=\(frame)")
|
||||
return operation(for: sender)
|
||||
}
|
||||
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { operation(for: sender) }
|
||||
override func draggingExited(_ sender: NSDraggingInfo?) { setTargeted(false) }
|
||||
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
|
||||
operation(for: sender) == .copy
|
||||
}
|
||||
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
|
||||
defer { setTargeted(false) }
|
||||
guard sender.draggingSourceOperationMask.contains(.copy), let urls = urls(from: sender) else { return false }
|
||||
trace("perform file-count=\(urls.count)")
|
||||
return perform?(urls) ?? false
|
||||
}
|
||||
override func concludeDragOperation(_ sender: NSDraggingInfo?) { setTargeted(false) }
|
||||
}
|
||||
}
|
||||
|
||||
#if VCC_UI_TESTING
|
||||
/// Authored UI-test source for a real AppKit file drag. It uses the same
|
||||
/// pasteboard representation as Finder and never calls a drop handler itself.
|
||||
struct PersonalCoverFileDragFixture: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> SourceView {
|
||||
let view = SourceView()
|
||||
view.setAccessibilityElement(true)
|
||||
view.isEnabled = true
|
||||
view.setAccessibilityLabel("Drag test image")
|
||||
view.setAccessibilityIdentifier("personal-cover-drag-source")
|
||||
return view
|
||||
}
|
||||
func updateNSView(_ view: SourceView, context: Context) {
|
||||
view.sourceURL = ProcessInfo.processInfo.environment["VCC_COVER_DRAG_SOURCE"].map { URL(fileURLWithPath: $0) }
|
||||
view.needsDisplay = true
|
||||
}
|
||||
final class SourceView: NSImageView, NSDraggingSource {
|
||||
var sourceURL: URL?
|
||||
override var intrinsicContentSize: NSSize { NSSize(width: 100, height: 45) }
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
super.draw(dirtyRect)
|
||||
let frame = bounds.insetBy(dx: 1, dy: 1)
|
||||
let border = NSBezierPath(roundedRect: frame, xRadius: 5, yRadius: 5)
|
||||
NSColor.controlBackgroundColor.setFill(); border.fill()
|
||||
NSColor.separatorColor.setStroke(); border.stroke()
|
||||
NSImage(systemSymbolName: "doc", accessibilityDescription: nil)?
|
||||
.draw(in: NSRect(x: bounds.midX - 8, y: 23, width: 16, height: 17))
|
||||
let paragraph = NSMutableParagraphStyle(); paragraph.alignment = .center
|
||||
("Drag test image" as NSString).draw(in: NSRect(x: 3, y: 5, width: bounds.width - 6, height: 14),
|
||||
withAttributes: [.font: NSFont.systemFont(ofSize: 10), .foregroundColor: NSColor.labelColor,
|
||||
.paragraphStyle: paragraph])
|
||||
}
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
guard let sourceURL else { return }
|
||||
let item = NSDraggingItem(pasteboardWriter: sourceURL as NSURL)
|
||||
let icon = NSImage(systemSymbolName: "doc", accessibilityDescription: nil)
|
||||
item.setDraggingFrame(NSRect(x: bounds.midX - 16, y: bounds.midY - 16, width: 32, height: 32), contents: icon)
|
||||
let session = beginDraggingSession(with: [item], event: event, source: self)
|
||||
session.animatesToStartingPositionsOnCancelOrFail = true
|
||||
}
|
||||
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
|
||||
.copy
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Guest command text must retain ASCII quotes and literal keystrokes. A native
|
||||
/// plain-text editor also keeps Return inside the draft instead of saving it.
|
||||
private struct PersonalLaunchCommandEditor: NSViewRepresentable {
|
||||
@Binding var text: String
|
||||
let isEnabled: Bool
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(text: $text) }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSTextView.scrollableTextView()
|
||||
let editor = scroll.documentView as! NSTextView
|
||||
scroll.drawsBackground = false
|
||||
editor.drawsBackground = false
|
||||
editor.isRichText = false
|
||||
editor.allowsUndo = true
|
||||
editor.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)
|
||||
editor.textColor = .labelColor
|
||||
editor.isAutomaticQuoteSubstitutionEnabled = false
|
||||
editor.isAutomaticDashSubstitutionEnabled = false
|
||||
editor.isAutomaticTextReplacementEnabled = false
|
||||
editor.isAutomaticSpellingCorrectionEnabled = false
|
||||
editor.isContinuousSpellCheckingEnabled = false
|
||||
editor.isAutomaticLinkDetectionEnabled = false
|
||||
editor.isAutomaticDataDetectionEnabled = false
|
||||
editor.isAutomaticTextCompletionEnabled = false
|
||||
editor.smartInsertDeleteEnabled = false
|
||||
editor.textContainerInset = NSSize(width: 4, height: 6)
|
||||
editor.setAccessibilityLabel("Keyboard loading commands (optional)")
|
||||
editor.setAccessibilityIdentifier("personal-launch-commands")
|
||||
editor.delegate = context.coordinator
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
let editor = scroll.documentView as! NSTextView
|
||||
context.coordinator.text = $text
|
||||
editor.isEditable = isEnabled
|
||||
if editor.string != text { editor.string = text }
|
||||
}
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var text: Binding<String>
|
||||
init(text: Binding<String>) { self.text = text }
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let editor = notification.object as? NSTextView else { return }
|
||||
text.wrappedValue = editor.string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PersonalSoftwareEditor: View {
|
||||
@State var entry: PersonalSoftwareEntry
|
||||
let unsupported: [String]
|
||||
let isImport: Bool
|
||||
let saving: Bool
|
||||
let error: String?
|
||||
let duplicateID: UUID?
|
||||
let save: (PersonalSoftwareEntry, Data?, Bool) -> Void
|
||||
let openExisting: (UUID) -> Void
|
||||
let previewCover: (PersonalSoftwareEntry) async throws -> Data?
|
||||
let cancel: () -> Void
|
||||
private let initialEntry: PersonalSoftwareEntry
|
||||
@State private var included: Set<String>
|
||||
@State private var pendingCoverData: Data?
|
||||
@State private var coverImage: NSImage?
|
||||
@State private var coverBusy = false
|
||||
@State private var coverError: String?
|
||||
@State private var coverGeneration = UUID()
|
||||
@State private var coverTask: Task<Void, Never>?
|
||||
@State private var coverImageTask: Task<Data, Error>?
|
||||
@State private var previewingImportedPath: String?
|
||||
@State private var coverPanel: NSOpenPanel?
|
||||
@State private var coverEditorActive = true
|
||||
@State private var coverDropTargeted = false
|
||||
init(entry: PersonalSoftwareEntry, unsupported: [String] = [], isImport: Bool, saving: Bool,
|
||||
error: String?, duplicateID: UUID?, save: @escaping (PersonalSoftwareEntry, Data?, Bool) -> Void,
|
||||
openExisting: @escaping (UUID) -> Void,
|
||||
previewCover: @escaping (PersonalSoftwareEntry) async throws -> Data?, cancel: @escaping () -> Void) {
|
||||
var normalized = entry
|
||||
normalized.category = PersonalSoftwareEntry.standardCategory(entry.category)
|
||||
_entry = State(initialValue: normalized); _included = State(initialValue: Set(entry.files.map(\.path)))
|
||||
self.unsupported = unsupported; self.isImport = isImport; self.saving = saving; self.error = error
|
||||
self.duplicateID = duplicateID; self.save = save; self.openExisting = openExisting
|
||||
self.previewCover = previewCover; self.cancel = cancel; self.initialEntry = entry
|
||||
}
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Label(isImport ? "Add Personal Software" : "Edit Personal Software", systemImage: "lock.rectangle.stack")
|
||||
.font(.title2.weight(.semibold))
|
||||
Spacer()
|
||||
Text("Private — On This Mac").font(.callout).foregroundStyle(.secondary)
|
||||
}.padding(20)
|
||||
Divider()
|
||||
Form {
|
||||
Section("Files & Details") {
|
||||
TextField("Title", text: $entry.title).accessibilityIdentifier("personal-title")
|
||||
TextField("Author / Publisher (optional)", text: $entry.author)
|
||||
TextField("Software version (optional)", text: $entry.softwareVersion)
|
||||
Picker("Category", selection: $entry.category) {
|
||||
ForEach(PersonalSoftwareEntry.standardCategories, id: \.self) { category in
|
||||
Text(SoftwareLibraryOwnedGame.categoryLabel(category)).tag(category)
|
||||
}
|
||||
}.pickerStyle(.menu).accessibilityIdentifier("personal-category")
|
||||
Text("Find this personal software alongside matching catalog titles when browsing categories. Your files stay private on this Mac.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
TextField("Notes / loading instructions", text: $entry.notes, axis: .vertical).lineLimit(3...8)
|
||||
Text("Your source files stay untouched. Imported originals and writable working files are kept separately in the app's private library. Nothing is uploaded.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
LabeledContent("Selected files", value: "\(included.count) · " + ByteCountFormatter.string(fromByteCount: entry.files.filter { included.contains($0.path) }.reduce(0) { $0 + $1.byteSize }, countStyle: .file))
|
||||
ForEach(Array(entry.files.indices), id: \.self) { index in
|
||||
HStack {
|
||||
if isImport {
|
||||
Toggle(isOn: Binding(get: { included.contains(entry.files[index].path) }, set: { value in
|
||||
setIncluded(entry.files[index].path, value)
|
||||
})) { Text(entry.files[index].path).lineLimit(2).textSelection(.enabled) }
|
||||
} else { Text(entry.files[index].path).lineLimit(2).textSelection(.enabled) }
|
||||
Spacer()
|
||||
if isImport, (entry.files[index].path as NSString).pathExtension.lowercased() == "os9" {
|
||||
Picker("Interpret OS-9 media", selection: Binding(get: { entry.files[index].kind }, set: {
|
||||
entry.files[index].kind = $0; entry.files[index].role = ""
|
||||
})) {
|
||||
Text("Floppy disk").tag("disk")
|
||||
Text("Hard disk").tag("hard-disk")
|
||||
}.labelsHidden().frame(width: 125).help("OS-9 files can represent floppy or hard disks. Choose how this file will be mounted.")
|
||||
} else { Text(entry.files[index].kind.capitalized).font(.caption).foregroundStyle(.secondary) }
|
||||
}
|
||||
}
|
||||
if !unsupported.isEmpty {
|
||||
Label("Supporting files are retained but not run. Nested archives and unrecognized formats are not expanded or treated as media.", systemImage: "info.circle")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
Section("Cover Image") { coverEditor }
|
||||
Section("Launch Setup") {
|
||||
Toggle("Use reviewed launch settings", isOn: $entry.configured).accessibilityIdentifier("personal-configured")
|
||||
Text("Save reviewed machine settings and media assignments to enable Play. Keyboard loading commands are optional: without them, Play opens the CoCo with its media ready for manual loading. Off keeps manual setup. Saving this entry never starts or changes the CoCo.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
Picker("Machine setup", selection: $entry.profile) {
|
||||
Text("Disk BASIC / Cassette").tag("disk-basic")
|
||||
Text("ROM Cartridge").tag("rom-cartridge")
|
||||
Text("Hard-drive BASIC").tag("hard-drive-basic")
|
||||
}
|
||||
Picker("Processor", selection: $entry.processor) { Text("MC6809").tag("6809"); Text("HD6309").tag("6309") }
|
||||
Picker("RAM", selection: $entry.ramKiB) {
|
||||
ForEach([128,512,2048,8192], id: \.self) { value in Text(value < 1024 ? "\(value) KB" : "\(value / 1024) MB").tag(value) }
|
||||
}
|
||||
Picker("Video", selection: $entry.video) { Text("Composite").tag("composite"); Text("RGB").tag("rgb") }
|
||||
ForEach(Array(entry.files.indices).filter { entry.files[$0].isMedia && included.contains(entry.files[$0].path) }, id: \.self) { index in
|
||||
Picker(entry.files[index].path, selection: $entry.files[index].role) {
|
||||
Text("Not assigned").tag("")
|
||||
ForEach(roles(entry.files[index].kind), id: \.self) { role in Text(roleLabel(role)).tag(role) }
|
||||
}.disabled(!entry.configured)
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Keyboard loading commands (optional)")
|
||||
PersonalLaunchCommandEditor(text: $entry.command, isEnabled: entry.configured)
|
||||
.frame(height: 90).padding(6)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 6))
|
||||
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.secondary.opacity(0.3)))
|
||||
}
|
||||
Text("Press Return for a new command line. For a BASIC program, enter LOAD \"PROGRAM\" on one line and RUN on the next. Commands are ordinary CoCo keyboard input; leave this blank if the loading sequence is unknown.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
if entry.configured, !entry.command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
SoftwareLibraryLaunchPlan.decodeCommands(entry.command) == nil {
|
||||
Label("These commands need manual entry and will not be typed automatically. Check the syntax and put LOAD and RUN on separate lines.", systemImage: "info.circle")
|
||||
.font(.caption).foregroundStyle(.orange)
|
||||
.accessibilityIdentifier("personal-launch-commands-manual")
|
||||
}
|
||||
}
|
||||
}.formStyle(.grouped)
|
||||
if let error {
|
||||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal,20).padding(.vertical,8)
|
||||
}
|
||||
Divider()
|
||||
HStack {
|
||||
if saving { ProgressView().controlSize(.small); Text("Saving private copy…").font(.callout) }
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel, action: cancelEditing).keyboardShortcut(.cancelAction).disabled(saving)
|
||||
if let duplicateID {
|
||||
Button("Open Existing") { openExisting(duplicateID) }.disabled(saving)
|
||||
Button("Add Separate Copy") { submit(true) }.disabled(saving || coverBusy)
|
||||
} else {
|
||||
Button(isImport ? "Add to Personal Library" : "Save Details") { submit(false) }
|
||||
.keyboardShortcut(.defaultAction).disabled(saving || coverBusy || entry.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !entry.files.contains(where: { $0.isMedia && included.contains($0.path) }))
|
||||
.accessibilityIdentifier("personal-save")
|
||||
}
|
||||
}.padding(16)
|
||||
}.frame(minWidth: 650, idealWidth: 720, minHeight: 600)
|
||||
.onAppear {
|
||||
coverEditorActive = true
|
||||
loadCoverPreview(entry, commitChoice: false)
|
||||
}
|
||||
.onDisappear { discardPendingCover() }
|
||||
}
|
||||
private var coverEditor: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack(alignment: .top, spacing: 16) {
|
||||
coverPreview
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Picker("Cover", selection: Binding(get: { coverSelection }, set: selectCover)) {
|
||||
Text("Category Icon").tag("category")
|
||||
ForEach(entry.files.filter { $0.kind == "cover" }) { file in
|
||||
Text(file.path).tag("imported:" + file.path)
|
||||
}
|
||||
if hasExistingCustomCover { Text("Saved Custom Image").tag("custom") }
|
||||
if pendingCoverData != nil { Text("Chosen Image").tag("replacement") }
|
||||
}.pickerStyle(.menu).accessibilityIdentifier("personal-cover-selection")
|
||||
Button("Choose Image…", systemImage: "photo.badge.plus", action: chooseCoverImage)
|
||||
.disabled(saving || coverPanel != nil).accessibilityIdentifier("personal-cover-choose")
|
||||
Button("Remove Cover", systemImage: "photo.badge.minus", action: useCategoryIcon)
|
||||
.disabled(saving || (coverSelection == "category" && !coverBusy))
|
||||
.accessibilityIdentifier("personal-cover-remove")
|
||||
Text("Choose an image or drop one image file onto the preview. The image stays private on this Mac and is saved only when you save this entry.")
|
||||
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
if let coverError {
|
||||
Label(coverError, systemImage: "exclamationmark.triangle")
|
||||
.font(.caption).foregroundStyle(.orange).textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
private var coverPreview: some View {
|
||||
ZStack {
|
||||
RoundedRectangle(cornerRadius: 9).fill(.quaternary.opacity(0.35))
|
||||
if let coverImage {
|
||||
Image(nsImage: coverImage).resizable().scaledToFit().padding(5)
|
||||
} else {
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: SoftwareLibraryCategoryStyle.symbol(for: entry.category))
|
||||
.font(.system(size: 42, weight: .light))
|
||||
.foregroundStyle(SoftwareLibraryCategoryStyle.tint(for: entry.category).opacity(0.7))
|
||||
Text(SoftwareLibraryOwnedGame.categoryLabel(entry.category))
|
||||
.font(.caption.weight(.medium)).foregroundStyle(.secondary)
|
||||
}.padding(12)
|
||||
}
|
||||
if coverBusy {
|
||||
ProgressView().controlSize(.small).frame(maxHeight: .infinity, alignment: .bottom).padding(8)
|
||||
}
|
||||
}.frame(width: 150, height: 180)
|
||||
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(coverDropTargeted ? Color.accentColor : .clear, lineWidth: 3))
|
||||
.overlay {
|
||||
PersonalCoverFileDropTarget(enabled: !saving && coverEditorActive, isTargeted: $coverDropTargeted) { urls in
|
||||
guard let url = urls.first else { return false }
|
||||
prepareCoverImage(url)
|
||||
return true
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity).accessibilityHidden(true)
|
||||
}
|
||||
.accessibilityElement(children: .ignore).accessibilityLabel("Cover image preview")
|
||||
.accessibilityValue(coverBusy ? "Loading image" : coverImage == nil ? "Category icon" : "Selected image")
|
||||
.accessibilityIdentifier("personal-cover-preview")
|
||||
.help("Drop one image file here to choose a private cover image")
|
||||
}
|
||||
private var hasExistingCustomCover: Bool {
|
||||
if case .custom? = initialEntry.cover { return true }
|
||||
return false
|
||||
}
|
||||
private var coverSelection: String {
|
||||
if pendingCoverData != nil { return "replacement" }
|
||||
switch entry.cover {
|
||||
case .categoryIcon?: return "category"
|
||||
case .imported(let path)?: return "imported:" + path
|
||||
case .custom?: return "custom"
|
||||
case nil:
|
||||
return entry.files.first(where: { $0.kind == "cover" && included.contains($0.path) })
|
||||
.map { "imported:" + $0.path } ?? "category"
|
||||
}
|
||||
}
|
||||
private func selectCover(_ selection: String) {
|
||||
guard !saving, coverEditorActive, selection != coverSelection else { return }
|
||||
if selection == "category" { useCategoryIcon(); return }
|
||||
var candidate = entry
|
||||
if selection == "custom", hasExistingCustomCover { candidate.cover = initialEntry.cover }
|
||||
else if selection.hasPrefix("imported:") {
|
||||
let path = String(selection.dropFirst("imported:".count))
|
||||
guard entry.files.contains(where: { $0.kind == "cover" && $0.path == path }) else { return }
|
||||
candidate.cover = .imported(path)
|
||||
} else { return }
|
||||
loadCoverPreview(candidate, commitChoice: true)
|
||||
}
|
||||
private func loadCoverPreview(_ candidate: PersonalSoftwareEntry, commitChoice: Bool) {
|
||||
let generation = beginCoverWork()
|
||||
var snapshot = candidate
|
||||
// A selected imported image is retained with the draft even if it had
|
||||
// been unchecked in Files & Details before choosing it here.
|
||||
let selectedPath: String?
|
||||
if case .imported(let path)? = candidate.cover { selectedPath = path } else { selectedPath = nil }
|
||||
previewingImportedPath = selectedPath
|
||||
snapshot.files = snapshot.files.filter { included.contains($0.path) || $0.path == selectedPath }
|
||||
coverTask = Task { @MainActor in
|
||||
do {
|
||||
let data = try await previewCover(snapshot)
|
||||
guard coverEditorActive, entry.id == candidate.id, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
let image = data.flatMap(NSImage.init(data:))
|
||||
guard data == nil || image != nil else { throw CocoaError(.fileReadCorruptFile) }
|
||||
if commitChoice {
|
||||
entry.cover = candidate.cover
|
||||
if let selectedPath { included.insert(selectedPath) }
|
||||
pendingCoverData = nil
|
||||
}
|
||||
coverImage = image
|
||||
finishCoverWork()
|
||||
} catch {
|
||||
guard coverEditorActive, entry.id == candidate.id, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
coverError = "Could not read this cover image. " + error.localizedDescription
|
||||
finishCoverWork()
|
||||
}
|
||||
}
|
||||
}
|
||||
private func chooseCoverImage() {
|
||||
guard !saving, coverEditorActive else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.image]
|
||||
panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.allowsMultipleSelection = false
|
||||
panel.message = "Choose a private cover image for this software."
|
||||
panel.prompt = "Choose Image"
|
||||
coverPanel = panel
|
||||
panel.begin { response in
|
||||
Task { @MainActor in
|
||||
guard coverEditorActive, coverPanel === panel else { return }
|
||||
coverPanel = nil
|
||||
if response == .OK, let url = panel.url { prepareCoverImage(url) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func prepareCoverImage(_ url: URL) {
|
||||
let generation = beginCoverWork()
|
||||
let entryID = entry.id
|
||||
let worker = Task.detached(priority: .userInitiated) {
|
||||
try Task.checkCancellation()
|
||||
let data = try PersonalCoverImage.prepare(url)
|
||||
try Task.checkCancellation()
|
||||
return data
|
||||
}
|
||||
coverImageTask = worker
|
||||
coverTask = Task { @MainActor in
|
||||
do {
|
||||
let data = try await worker.value
|
||||
guard coverEditorActive, entry.id == entryID, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
guard let image = NSImage(data: data) else { throw CocoaError(.fileReadCorruptFile) }
|
||||
pendingCoverData = data
|
||||
coverImage = image
|
||||
finishCoverWork()
|
||||
} catch {
|
||||
guard coverEditorActive, entry.id == entryID, coverGeneration == generation, !Task.isCancelled else { return }
|
||||
coverError = "Could not use this image. " + error.localizedDescription
|
||||
finishCoverWork()
|
||||
}
|
||||
}
|
||||
}
|
||||
private func beginCoverWork() -> UUID {
|
||||
stopCoverWork()
|
||||
coverBusy = true; coverError = nil
|
||||
return coverGeneration
|
||||
}
|
||||
private func finishCoverWork() {
|
||||
coverBusy = false; coverTask = nil; coverImageTask = nil; previewingImportedPath = nil
|
||||
}
|
||||
private func stopCoverWork() {
|
||||
coverGeneration = UUID()
|
||||
coverTask?.cancel(); coverTask = nil
|
||||
coverImageTask?.cancel(); coverImageTask = nil
|
||||
previewingImportedPath = nil
|
||||
coverBusy = false
|
||||
}
|
||||
private func useCategoryIcon() {
|
||||
stopCoverWork()
|
||||
entry.cover = .categoryIcon; pendingCoverData = nil; coverImage = nil; coverError = nil
|
||||
}
|
||||
private func setIncluded(_ path: String, _ value: Bool) {
|
||||
let removingSelectedCover = !value && coverSelection == "imported:" + path
|
||||
if !value, previewingImportedPath == path { stopCoverWork() }
|
||||
if value { included.insert(path) } else { included.remove(path) }
|
||||
if !value, pendingCoverData != nil, case .imported(let previousPath)? = entry.cover, previousPath == path {
|
||||
// The validated replacement is independent of this imported file.
|
||||
entry.cover = .categoryIcon
|
||||
} else if removingSelectedCover { useCategoryIcon() }
|
||||
}
|
||||
private func discardPendingCover() {
|
||||
coverEditorActive = false
|
||||
stopCoverWork()
|
||||
coverPanel?.cancel(nil); coverPanel = nil
|
||||
pendingCoverData = nil; coverDropTargeted = false
|
||||
}
|
||||
private func cancelEditing() {
|
||||
discardPendingCover()
|
||||
cancel()
|
||||
}
|
||||
private func submit(_ allowDuplicate: Bool) {
|
||||
guard !saving, !coverBusy else { return }
|
||||
var edited = entry
|
||||
edited.files = edited.files.filter { included.contains($0.path) }
|
||||
// The store validates the file inventory before installing the PNG.
|
||||
// A replaced imported cover may have been excluded from that inventory.
|
||||
if pendingCoverData != nil { edited.cover = .categoryIcon }
|
||||
edited.command = edited.command.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r")
|
||||
save(edited, pendingCoverData, allowDuplicate)
|
||||
}
|
||||
private func roles(_ kind: String) -> [String] {
|
||||
switch kind {
|
||||
case "disk": return ["disk0","disk1","disk2","disk3"]
|
||||
case "hard-disk": return ["hard0","hard1"]
|
||||
case "cassette": return ["media"]
|
||||
case "cartridge": return ["cartridge"]
|
||||
default: return []
|
||||
}
|
||||
}
|
||||
private func roleLabel(_ role: String) -> String {
|
||||
switch role { case "media": return "Cassette"; case "cartridge": return "ROM Cartridge"
|
||||
default: return role.hasPrefix("hard") ? "HD" + role.suffix(1) : "FD" + role.suffix(1) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user