Skip to content
Merged
14 changes: 13 additions & 1 deletion Apps/FirmwareUpdater/Sources/BackupView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,21 @@ final class BackupModel {
private(set) var stepResult: String?
/// The update this session's backup allows (#693); nil until a backup is saved.
private(set) var update: UpdateModel?
/// A screenshot preview's model (#761): its buttons do nothing, so no MIDI message is sent and no chip is read.
private var inert = false

init() {}

#if DEBUG
init(preview result: String?) {
self.result = result
inert = true
}
#endif

/// The display chip's step into update mode: only on the owner's typed UPDATE, once.
func enterUpdateMode() async {
guard !inert else { return }
let outcome = await UpdateModeStep(midi: CoreMIDISend(), apps: WorkspaceApps()).enter(typed: typed)
typed = ""
switch outcome {
Expand All @@ -25,7 +37,7 @@ final class BackupModel {
}

func backUp() async {
guard !running else { return }
guard !running, !inert else { return }
if let stop = await Preflight(apps: WorkspaceApps()).stop() {
result = stop
return
Expand Down
50 changes: 46 additions & 4 deletions Apps/FirmwareUpdater/Sources/FirmwareUpdaterApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@ import UpdaterScreen

@main
struct FirmwareUpdaterApp: App {
@State private var model = Live.updater()
@State private var model = Self.makeModel()

var body: some Scene {
Window("Firmware Updater", id: "updater") {
UpdaterView(model: model)
.frame(minWidth: 480, minHeight: 360)
.task {
#if DEBUG
if let shot = PreviewLaunch.shot {
await PreviewLaunch.run(shot, on: model)
return
}
#endif
await model.refresh()
FileLog.shared.log(model.screen.firstLookLine)
if SmokeLaunch.isOn { SmokeLaunch.finish() }
Expand All @@ -22,7 +27,15 @@ struct FirmwareUpdaterApp: App {
// Beside the devices, not after them: watch() runs until the app quits.
.task { await model.loadFirmware() }
}
.windowResizability(.contentSize)
}

/// The real ports, or in a Debug build started with --preview, a fixed state on fake ones (#761) and no real port
/// made at all.
@MainActor static func makeModel() -> Updater {
#if DEBUG
if let shot = PreviewLaunch.shot { return Updater.preview(shot.state) }
#endif
return Live.updater()
}
}

Expand Down Expand Up @@ -57,9 +70,38 @@ enum Live {

struct UpdaterView: View {
let model: Updater
@State private var backup = BackupModel()
@State private var backup = Self.makeBackup()
@State private var fitting = WindowFitting()

static func makeBackup() -> BackupModel {
#if DEBUG
if let shot = PreviewLaunch.shot { return BackupModel(preview: shot.backupResult) }
#endif
return BackupModel()
}

/// The sections in a scroll view the window fits (#761): taller than the screen, they scroll, and new text at the
/// bottom is kept in view.
var body: some View {
ScrollViewReader { scroll in
ScrollView(.vertical) {
VStack(spacing: 0) {
sections
Color.clear.frame(height: 0).id(Self.end)
}
.onGeometryChange(for: CGSize.self) { $0.size } action: { size in
fitting.contentChanged(size)
scroll.scrollTo(Self.end, anchor: .bottom)
}
}
}
.frame(minWidth: WindowFit.minWidth, minHeight: 200)
.background(WindowReader { fitting.attach($0) })
}

private static let end = "end"

private var sections: some View {
VStack(alignment: .leading, spacing: 16) {
SectionView(title: "Deck panel", section: model.screen.panel, accept: nil)
FirmwareRow(line: model.firmware)
Expand Down
38 changes: 38 additions & 0 deletions Apps/FirmwareUpdater/Sources/PreviewLaunch.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#if DEBUG
import Foundation
import UpdaterScreen

/// Screenshots of the window (#761), in Debug builds only: `FirmwareUpdater --preview <shot>` opens it in a fixed state
/// on fake ports (Updater.preview). No IOKit, CoreMIDI or serial object is made, no DeckBridge signal is sent, and its
/// buttons reach only the fakes. Shots: nothing, found, backup, updating.
enum PreviewLaunch {
enum Shot: String {
case nothing, found, backup, updating

var state: PreviewState {
switch self {
case .nothing: .nothing
case .found, .backup: .found
case .updating: .updating
}
}

/// The backup line shown in the LC6000 section, after a backup.
var backupResult: String? {
self == .backup ? "Backup saved: read twice and the same, 2 files.\nTop panel chip: firmware 1.0.0." : nil
}
}

static var shot: Shot? {
let arguments = CommandLine.arguments
guard let flag = arguments.firstIndex(of: "--preview"), flag + 1 < arguments.count else { return nil }
return Shot(rawValue: arguments[flag + 1])
}

/// The first look on the fakes, then for `updating`, the update over the (fake) cable.
@MainActor static func run(_ shot: Shot, on model: Updater) async {
await model.refresh()
if shot == .updating { await model.updatePanel() }
}
}
#endif
69 changes: 69 additions & 0 deletions Apps/FirmwareUpdater/Sources/WindowFitting.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import AppKit
import SwiftUI
import UpdaterScreen

/// Sizes the updater's window to its content (#761) by WindowFit's rule: it grows when new text appears, up to the
/// screen's visible frame, and a size the owner sets by hand is remembered and never shrunk.
@MainActor
final class WindowFitting {
private weak var window: NSWindow?
private var content: CGSize?
private let store = HandSetSize()
private var observer: NSObjectProtocol?

func attach(_ window: NSWindow) {
guard self.window !== window else { return }
self.window = window
observer = NotificationCenter.default.addObserver(forName: NSWindow.didEndLiveResizeNotification,
object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.handResized() }
}
fit()
}

/// The content's own size changed: new text appeared or went away.
func contentChanged(_ size: CGSize) {
content = size
fit()
}

private func handResized() {
guard let window else { return }
store.remember(window.frame.size)
}

private func fit() {
guard let window, let content, let screen = window.screen ?? NSScreen.main else { return }
let visible = screen.visibleFrame
let titleBar = window.frame.height - window.contentLayoutRect.height
let size = WindowFit.size(content: CGSize(width: WindowFit.minWidth, height: content.height), titleBar: titleBar,
visible: visible.size, handSet: store.size)
guard size != window.frame.size else { return }
// Keep the top edge where it is, and the whole window on the screen.
var frame = NSRect(x: window.frame.minX, y: window.frame.maxY - size.height, width: size.width, height: size.height)
frame.origin.y = min(max(frame.minY, visible.minY), visible.maxY - frame.height)
frame.origin.x = min(max(frame.minX, visible.minX), visible.maxX - frame.width)
window.setFrame(frame, display: true, animate: false)
}
}

/// Hands the hosting NSWindow to `found` once the view is in one.
struct WindowReader: NSViewRepresentable {
let found: (NSWindow) -> Void

func makeNSView(context: Context) -> NSView { Reader(found: found) }
func updateNSView(_ view: NSView, context: Context) {}

private final class Reader: NSView {
let found: (NSWindow) -> Void
init(found: @escaping (NSWindow) -> Void) {
self.found = found
super.init(frame: .zero)
}
required init?(coder: NSCoder) { nil }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let window { found(window) }
}
}
}
66 changes: 66 additions & 0 deletions Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/Preview.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#if DEBUG
import DeviceFinder
import FirmwareModel
import PanelFlasher

/// The screenshot preview (#761), Debug builds only: the window in a fixed state, on fake ports. Every port here is a
/// plain value in this file: this package has no IOKit, CoreMIDI or serial code, and the preview has no DeckBridge
/// handoff, so nothing is opened, sent or signaled.
public enum PreviewState: String, CaseIterable, Sendable {
/// Nothing plugged in.
case nothing
/// The panel on its cable with its build read, an update offered, and an LC6000 on MIDI.
case found
/// As `found`, with an update over the cable stopped on its writing step.
case updating
}

extension Updater {
/// A model for `state` on fake ports, with a fixed firmware line and no handoff.
public static func preview(_ state: PreviewState) -> Updater {
let plugged = state != .nothing
let finder = DeviceFinder(usb: PreviewUSB(plugged: plugged), midi: PreviewMIDI(plugged: plugged),
serial: PreviewSerial(), log: PreviewLog())
let model = Updater(finder: finder, changes: AsyncStream { $0.finish() },
firmware: { FirmwareLine(source: "Firmware 1.4.0, from this project's newest release", reason: nil) },
flasher: PreviewFlasher())
if plugged { model.acceptLC6000Warning() }
return model
}
}

private struct PreviewUSB: USBDevices {
let plugged: Bool
func devices() async -> [USBDevice] {
plugged ? [USBDevice(vendor: 0x1A86, product: 0x7522, name: "USB Serial", serialPort: PreviewSerial.port)] : []
}
}

private struct PreviewMIDI: MIDIPorts {
let plugged: Bool
func names() async -> [String] { plugged ? ["LC6000 PRIME Controller"] : [] }
}

private struct PreviewSerial: PanelSerial {
/// A made-up name: never opened, only matched against the fake USB device's.
static let port = "/dev/cu.preview"
func listen(on port: String, baud: Int, for seconds: Double, asking question: String?) async -> Listened {
.lines(["deck panel: boot, build 0123abc, version 1.3.0"])
}
}

private struct PreviewLog: LogSink {
func log(_ line: String) {}
}

/// Offers 1.4.0 to any build; an update stops on 42 % written and stays there.
private struct PreviewFlasher: PanelFlashing {
func offer(for build: PanelBuild) -> PanelUpdateOffer? { PanelUpdateOffer(version: "1.4.0", note: nil) }
func repairVersion() -> String? { "1.4.0" }
func flash(report: @escaping @Sendable (PanelUpdate.Step) -> Void) async {
report(.connecting)
report(.writing(0.42))
try? await Task.sleep(for: .seconds(86_400))
}
}
#endif
35 changes: 35 additions & 0 deletions Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/WindowFit.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import CoreGraphics
import Foundation

/// The updater window's size (#761): as big as what it shows, so the owner never resizes it to read a section.
public enum WindowFit {
/// Narrower than this, the longer lines wrap into a tall column.
public static let minWidth: CGFloat = 560

/// The window's size for `content` (the sections' own size) under a title bar `titleBar` tall, on a screen whose
/// visible frame is `visible`. Never smaller than `handSet`, a size the owner set by hand; never bigger than the
/// visible frame: past it, the content scrolls.
public static func size(content: CGSize, titleBar: CGFloat, visible: CGSize, handSet: CGSize? = nil) -> CGSize {
let floor = handSet ?? .zero
return CGSize(width: min(max(content.width, minWidth, floor.width), visible.width),
height: min(max(content.height + titleBar, floor.height), visible.height))
}
}

/// The window size the owner last set by hand (#761), kept in the app's defaults so it lasts across launches.
public struct HandSetSize {
private let defaults: UserDefaults
private static let key = "WindowFit.handSetSize"

public init(defaults: UserDefaults = .standard) { self.defaults = defaults }

/// The size last set by hand; nil when the owner never resized the window.
public var size: CGSize? {
guard let pair = defaults.array(forKey: Self.key) as? [Double], pair.count == 2 else { return nil }
return CGSize(width: pair[0], height: pair[1])
}

public func remember(_ size: CGSize) {
defaults.set([Double(size.width), Double(size.height)], forKey: Self.key)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import CoreGraphics
import Foundation
import Testing
import UpdaterScreen

/// The size the owner set by hand is kept across launches (#761).
@Suite("Updater: the window's hand-set size is remembered")
struct HandSetSizeTests {
static func freshDefaults() -> UserDefaults {
let name = "HandSetSizeTests.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: name)!
defaults.removePersistentDomain(forName: name)
return defaults
}

@Test("Nothing set by hand yet: no size")
func noneYet() {
#expect(HandSetSize(defaults: Self.freshDefaults()).size == nil)
}

@Test("A size set by hand is read back at the next launch")
func readBack() {
let defaults = Self.freshDefaults()
HandSetSize(defaults: defaults).remember(CGSize(width: 820, height: 640))
#expect(HandSetSize(defaults: defaults).size == CGSize(width: 820, height: 640))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#if DEBUG
import Testing
import UpdaterScreen

/// The screenshot preview (#761, Debug builds only): fixed states on fake ports, so the window can be shot with any
/// device on the Mac and none of them touched.
@MainActor @Suite("Updater: the screenshot preview's fixed states")
struct PreviewTests {
@Test("Nothing plugged in: both sections say not found")
func nothing() async {
let model = Updater.preview(.nothing)
await model.refresh()
#expect(model.screen.firstLookLine == "first look: deck panel not found, LC6000 not found")
}

@Test("Panel and LC6000 found: the panel's build is read, an update is offered, the LC6000 warning is accepted")
func found() async {
let model = Updater.preview(.found)
await model.refresh()
#expect(model.screen.firstLookLine == "first look: deck panel found (build read), LC6000 found")
#expect(model.screen.panelUpdate != nil)
#expect(model.screen.lc6000.warning == nil)
}

@Test("During a panel update: it stays on its writing step, with Cancel off")
func updating() async {
let model = Updater.preview(.updating)
await model.refresh()
let update = Task { await model.updatePanel() }
while model.canCancel || !model.updating { await Task.yield() }
#expect(model.updating)
#expect(!model.canCancel)
#expect(model.screen.update == "Writing the new firmware: 42%")
update.cancel()
}
}
#endif
Loading
Loading