261 lines
14 KiB
Swift
261 lines
14 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import AppKit
|
|
import SwiftUI
|
|
|
|
// Guest events only. A brief hold makes transfers between UI polls visible;
|
|
// pausing consumes counters and clears the hold immediately.
|
|
struct ActivityTracker {
|
|
enum State: String { case empty, loaded, read, write }
|
|
private var previous: (UInt64, UInt64)?
|
|
private var until: Double = 0
|
|
private var held = State.loaded
|
|
mutating func update(reads: UInt64, writes: UInt64, mounted: Bool, running: Bool, now: Double) -> State {
|
|
defer { previous = (reads, writes) }
|
|
guard mounted, running else { until = 0; held = .loaded; return mounted ? .loaded : .empty }
|
|
if let previous, reads < previous.0 || writes < previous.1 { until = 0; held = .loaded }
|
|
else if let previous, writes > previous.1 { held = .write; until = now + 0.16 }
|
|
else if let previous, reads > previous.0 {
|
|
if held != .write || now >= until { held = .read; until = now + 0.16 }
|
|
}
|
|
return now < until ? held : .loaded
|
|
}
|
|
}
|
|
|
|
struct HardwareState: Equatable {
|
|
var values: [String: String] = ["scene":"on", "mpi":"off", "ram":"512kb", "cpu":"6809", "startup":"4", "floppy":"off", "hard":"off", "floppyCase":"off", "hardCase":"off", "tape":"empty", "tapeActivity":"empty", "printerPower":"off", "printerPaper":"blank", "sdcActivity":"empty"]
|
|
var custom = false
|
|
var activities = Array(repeating: ActivityTracker.State.empty, count: 7)
|
|
static let ramKeys = ["128kb", "512kb", "2mb", "8mb"]
|
|
init() {
|
|
for n in 1...4 { values["slot\(n)"] = "empty" }
|
|
for id in ["fd0","fd1","fd2","fd3","hd0","hd1"] { values[id] = "empty"; values[id + "Activity"] = "empty" }
|
|
}
|
|
init(snapshot: VCCMachineSnapshot, activities: [ActivityTracker.State], sdcActivity: ActivityTracker.State = .empty) {
|
|
self.init(); self.activities = activities
|
|
values["cpu"] = snapshot.use6309 ? "6309" : "6809"
|
|
values["ram"] = Self.ramKeys[min(3, Int(snapshot.ramConfiguration))]
|
|
values["mpi"] = snapshot.multiPakEnabled ? "on" : "off"
|
|
values["startup"] = String(snapshot.physicalSlot)
|
|
values["floppy"] = snapshot.diskConnected ? "on" : "off"
|
|
values["hard"] = snapshot.hardDiskConnected ? "on" : "off"
|
|
values["floppyCase"] = snapshot.diskConnected || snapshot.hardDiskConnected ? "on" : "off"
|
|
values["hardCase"] = values["floppyCase"]
|
|
custom = !snapshot.multiPakEnabled && snapshot.cartridgeKinds.first?.intValue != 0
|
|
|| snapshot.multiPakEnabled && snapshot.cartridgeKinds.dropFirst().contains { $0.intValue == 4 }
|
|
for n in 1...4 {
|
|
let kind = snapshot.cartridgeKinds[n].intValue
|
|
let available = !snapshot.cartridgeNames[n].isEmpty
|
|
values["slot\(n)"] = available && (0...7).contains(kind) ? ["empty","rom","floppy","hard","empty","orchestra","speech","sdc"][kind] : "empty"
|
|
}
|
|
for (i, disk) in (snapshot.disks + snapshot.hardDisks).enumerated() {
|
|
let id = i < 4 ? "fd\(i)" : "hd\(i-4)"
|
|
values[id] = disk.mounted ? "loaded" : "empty"
|
|
values[id + "Activity"] = activities[i].rawValue
|
|
}
|
|
values["sdcActivity"] = sdcActivity.rawValue
|
|
values["printerPower"] = snapshot.printerEnabled ? "on" : "off"
|
|
values["printerPaper"] = snapshot.printerByteCount > 0 ? "printed" : "blank"
|
|
values["tape"] = snapshot.tapeMounted ? "loaded" : "empty"
|
|
values["tapeActivity"] = activities[6].rawValue
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class PresentationSettings: ObservableObject {
|
|
enum Mode: String { case display, system }
|
|
@Published var mode: Mode { didSet { defaults.set(mode.rawValue, forKey: "interface.presentation") } }
|
|
@Published var expanded: Bool { didSet { defaults.set(expanded, forKey: "interface.expanded") } }
|
|
@Published var showConnections: Bool { didSet { defaults.set(showConnections, forKey: "interface.connections") } }
|
|
@Published var showClickableAreas: Bool { didSet { defaults.set(showClickableAreas, forKey: "interface.clickableAreas") } }
|
|
@Published private(set) var controlsFocusRequest: UInt64 = 0
|
|
// UI history is independent of saved machine profiles and Restore Defaults.
|
|
func shouldIntroduce(_ profile: SystemProfile) -> Bool {
|
|
!defaults.bool(forKey: "interface.usageGuide.seen." + profile.rawValue)
|
|
}
|
|
func didShowGuide(_ profile: SystemProfile) {
|
|
defaults.set(true, forKey: "interface.usageGuide.seen." + profile.rawValue)
|
|
}
|
|
let windows: WindowPlacements
|
|
func focusControls() { controlsFocusRequest += 1 }
|
|
private let defaults: UserDefaults
|
|
init(defaults: UserDefaults = .standard) {
|
|
self.defaults = defaults
|
|
windows = WindowPlacements(defaults: defaults)
|
|
expanded = defaults.bool(forKey: "interface.expanded")
|
|
showConnections = defaults.bool(forKey: "interface.connections")
|
|
showClickableAreas = defaults.object(forKey: "interface.clickableAreas") == nil
|
|
? true : defaults.bool(forKey: "interface.clickableAreas")
|
|
mode = Mode(rawValue: defaults.string(forKey: "interface.presentation") ?? "") ?? .system
|
|
}
|
|
}
|
|
|
|
// Pure, absolute geometry: return never inverts an accumulated transform.
|
|
struct SystemGeometry {
|
|
static let canvas = CGRect(x: -120, y: 0, width: 960, height: 457)
|
|
// The approved PNG includes transparent margins and its soft shelf shadow.
|
|
// Keep its 2:1 aspect ratio; the separate target follows the visible object.
|
|
static let libraryArtwork = CGRect(x: 420, y: 0, width: 304, height: 152)
|
|
static let monitor = CGRect(x: 48, y: 4, width: 285, height: 256)
|
|
static let screen = CGRect(x: 90, y: 44.5, width: 202, height: 151.1)
|
|
let scene: CGRect
|
|
let monitor: CGRect
|
|
let screen: CGRect
|
|
init(size: CGSize, system: Bool, expanded: Bool, contentBounds: CGRect = Self.canvas) {
|
|
let scale = min(size.width / 960, size.height / 457)
|
|
// Translate the shared scene, monitor and controls together. Keep the
|
|
// full-scene scale so removing the tower does not enlarge the hardware.
|
|
let offset = system ? (Self.canvas.midX - contentBounds.midX) * scale : 0
|
|
scene = CGRect(x: (size.width - 960 * scale) / 2 + offset, y: (size.height - 457 * scale) / 2, width: 960 * scale, height: 457 * scale)
|
|
if !system {
|
|
monitor = .zero
|
|
// Metal fits the current active raster, including wider CoCo 3 modes.
|
|
screen = CGRect(origin:.zero,size:size)
|
|
} else {
|
|
let m: CGRect
|
|
if expanded {
|
|
let s = min((size.width - 24) / Self.monitor.width, (size.height - 16) / Self.monitor.height)
|
|
m = CGRect(x: (size.width-Self.monitor.width*s)/2, y: (size.height-Self.monitor.height*s)/2, width: Self.monitor.width*s, height: Self.monitor.height*s)
|
|
} else {
|
|
m = CGRect(x: scene.minX+(Self.monitor.minX+120)*scale, y: scene.minY+Self.monitor.minY*scale, width: Self.monitor.width*scale, height: Self.monitor.height*scale)
|
|
}
|
|
monitor = m
|
|
let s = m.width / Self.monitor.width
|
|
screen = CGRect(x: m.minX+(Self.screen.minX-Self.monitor.minX)*s, y: m.minY+(Self.screen.minY-Self.monitor.minY)*s, width: Self.screen.width*s, height: Self.screen.height*s)
|
|
}
|
|
}
|
|
func monitorRect(_ r: CGRect) -> CGRect {
|
|
let s = monitor.width / Self.monitor.width
|
|
return CGRect(x: monitor.minX + (r.minX - Self.monitor.minX) * s,
|
|
y: monitor.minY + (r.minY - Self.monitor.minY) * s, width: r.width * s, height: r.height * s)
|
|
}
|
|
func rect(_ r: CGRect) -> CGRect {
|
|
let s = scene.width/960
|
|
return CGRect(x: scene.minX+(r.minX+120)*s, y: scene.minY+r.minY*s, width: r.width*s, height: r.height*s)
|
|
}
|
|
}
|
|
|
|
struct ArtworkLayer: Decodable {
|
|
let file: String
|
|
let bounds: [Double]
|
|
let when: [String:String]
|
|
let part: String
|
|
var rect: CGRect { CGRect(x: bounds[0], y: bounds[1], width: bounds[2], height: bounds[3]) }
|
|
func visible(_ values: [String:String]) -> Bool { when.allSatisfy { values[$0.key] == $0.value } }
|
|
}
|
|
|
|
private final class ArtworkBundleMarker: NSObject {}
|
|
|
|
@MainActor
|
|
final class HardwareArtwork {
|
|
static let shared = HardwareArtwork()
|
|
let layers: [ArtworkLayer]
|
|
private var images: [String:NSImage] = [:]
|
|
let directory: URL?
|
|
init(bundle: Bundle? = nil) {
|
|
let bundle = bundle ?? Bundle(for: ArtworkBundleMarker.self)
|
|
directory = bundle.url(forResource: "Hardware", withExtension: nil)
|
|
if let directory, let data = try? Data(contentsOf: directory.appendingPathComponent("layers.json")),
|
|
let decoded = try? JSONDecoder().decode([ArtworkLayer].self, from: data) { layers = decoded }
|
|
else { layers = [] }
|
|
}
|
|
func layoutBounds(_ values: [String:String]) -> CGRect {
|
|
guard values["floppyCase"] != "on", values["hardCase"] != "on" else { return SystemGeometry.canvas }
|
|
let visible = layers.filter { $0.visible(values) }.map(\.rect)
|
|
return visible.reduce(SystemTarget.library.rect) { $0.union($1) }
|
|
}
|
|
func cartridgeHitRect(slot: Int, values: [String:String]) -> CGRect? {
|
|
func bounds(_ n: Int) -> CGRect? {
|
|
let matching = layers.filter { $0.when["mpi"] == "on" && $0.when["slot\(n)"] == values["slot\(n)"] && $0.when.keys.allSatisfy { $0 == "mpi" || $0 == "slot\(n)" } }
|
|
return matching.map(\.rect).reduce(nil) { (r: CGRect?, next) in r.map { $0.union(next) } ?? next }
|
|
}
|
|
guard var rect = bounds(slot) else { return nil }
|
|
for n in 1..<slot {
|
|
if let front = bounds(n), front.intersects(rect) {
|
|
rect.size.height = max(0, min(rect.maxY, front.minY) - rect.minY)
|
|
}
|
|
}
|
|
rect.size.height = max(0, min(rect.maxY, SystemTarget.slot(slot).rect.minY) - rect.minY)
|
|
return rect.height >= 8 ? rect.insetBy(dx: 1, dy: 1) : nil
|
|
}
|
|
func image(_ name: String) -> NSImage? {
|
|
if let image = images[name] { return image }
|
|
guard let directory, let image = NSImage(contentsOf: directory.appendingPathComponent(name)) else { return nil }
|
|
images[name] = image; return image
|
|
}
|
|
}
|
|
|
|
struct HardwareBadge: View {
|
|
let name: String
|
|
let label: String
|
|
var body: some View {
|
|
Group {
|
|
if let image = HardwareArtwork.shared.image(name + ".pdf") { Image(nsImage: image).resizable().scaledToFit() }
|
|
else { Text(label) }
|
|
}.accessibilityElement(children: .ignore).accessibilityLabel(label)
|
|
}
|
|
}
|
|
|
|
// Each cropped asset has a persistent native layer. Video polls never redraw
|
|
// artwork; I/O changes only hide/show small pre-rendered layers. Resizing
|
|
// regenerates the visible layers at the window's current backing scale.
|
|
struct HardwareCanvas: NSViewRepresentable {
|
|
let values: [String:String]
|
|
let part: String
|
|
func makeNSView(context: Context) -> LayeredHardwareView { LayeredHardwareView(part: part) }
|
|
func updateNSView(_ view: LayeredHardwareView, context: Context) { view.apply(values) }
|
|
}
|
|
final class LayeredHardwareView: NSView {
|
|
override var isFlipped: Bool { true }
|
|
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
|
private let assets: [ArtworkLayer]
|
|
private var artworkLayers: [CALayer] = []
|
|
private var values: [String:String] = [:]
|
|
private var renderedSizes: [CGSize]
|
|
private let part: String
|
|
private(set) var rasterizations = 0
|
|
init(part: String) {
|
|
self.part = part
|
|
assets = HardwareArtwork.shared.layers.filter { $0.part == part }
|
|
renderedSizes = Array(repeating: .zero, count: assets.count)
|
|
super.init(frame: .zero)
|
|
wantsLayer = true; layer?.isGeometryFlipped = true
|
|
setAccessibilityElement(false)
|
|
for _ in assets {
|
|
let child = CALayer(); child.isHidden = true
|
|
layer?.addSublayer(child); artworkLayers.append(child)
|
|
}
|
|
}
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
func apply(_ next: [String:String]) {
|
|
guard values != next else { return }; values = next; needsLayout = true
|
|
}
|
|
override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties(); renderedSizes = Array(repeating: .zero, count: assets.count); needsLayout = true }
|
|
override func layout() {
|
|
super.layout()
|
|
let canvas = part == "monitor" ? SystemGeometry.monitor : SystemGeometry.canvas
|
|
let scale = min(bounds.width/canvas.width, bounds.height/canvas.height)
|
|
guard scale > 0 else { return }
|
|
let backing = window?.backingScaleFactor ?? 2
|
|
CATransaction.begin(); CATransaction.setDisableActions(true)
|
|
for i in assets.indices {
|
|
let asset = assets[i], child = artworkLayers[i], r = asset.rect
|
|
child.isHidden = !asset.visible(values)
|
|
let disconnected = (asset.when["floppyCase"] != nil && values["floppy"] != "on") ||
|
|
(asset.when["hardCase"] != nil && values["hard"] != "on")
|
|
child.opacity = disconnected ? 0.42 : 1
|
|
child.frame = CGRect(x:(r.minX-canvas.minX)*scale,y:(r.minY-canvas.minY)*scale,width:r.width*scale,height:r.height*scale)
|
|
guard !child.isHidden else { continue }
|
|
let size = CGSize(width: ceil(r.width*scale*backing), height: ceil(r.height*scale*backing))
|
|
if renderedSizes[i] != size, let image = HardwareArtwork.shared.image(asset.file) {
|
|
let rep = NSBitmapImageRep(bitmapDataPlanes:nil,pixelsWide:max(1,Int(size.width)),pixelsHigh:max(1,Int(size.height)),bitsPerSample:8,samplesPerPixel:4,hasAlpha:true,isPlanar:false,colorSpaceName:.deviceRGB,bytesPerRow:0,bitsPerPixel:0)!
|
|
NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep:rep)
|
|
image.draw(in:CGRect(origin:.zero,size:size),from:.zero,operation:.sourceOver,fraction:1,respectFlipped:false,hints:nil)
|
|
NSGraphicsContext.restoreGraphicsState()
|
|
child.contents = rep.cgImage; child.contentsScale = backing
|
|
renderedSizes[i] = size; rasterizations += 1
|
|
}
|
|
}
|
|
CATransaction.commit()
|
|
}
|
|
}
|