diff --git a/Apps/FirmwareUpdater/Sources/BackupView.swift b/Apps/FirmwareUpdater/Sources/BackupView.swift index f0de4a28..28ff669b 100644 --- a/Apps/FirmwareUpdater/Sources/BackupView.swift +++ b/Apps/FirmwareUpdater/Sources/BackupView.swift @@ -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 { @@ -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 diff --git a/Apps/FirmwareUpdater/Sources/FirmwareUpdaterApp.swift b/Apps/FirmwareUpdater/Sources/FirmwareUpdaterApp.swift index 1e7c38e9..4c958ca1 100644 --- a/Apps/FirmwareUpdater/Sources/FirmwareUpdaterApp.swift +++ b/Apps/FirmwareUpdater/Sources/FirmwareUpdaterApp.swift @@ -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() } @@ -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() } } @@ -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) diff --git a/Apps/FirmwareUpdater/Sources/PreviewLaunch.swift b/Apps/FirmwareUpdater/Sources/PreviewLaunch.swift new file mode 100644 index 00000000..61d78b48 --- /dev/null +++ b/Apps/FirmwareUpdater/Sources/PreviewLaunch.swift @@ -0,0 +1,38 @@ +#if DEBUG +import Foundation +import UpdaterScreen + +/// Screenshots of the window (#761), in Debug builds only: `FirmwareUpdater --preview ` 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 diff --git a/Apps/FirmwareUpdater/Sources/WindowFitting.swift b/Apps/FirmwareUpdater/Sources/WindowFitting.swift new file mode 100644 index 00000000..4aaf498d --- /dev/null +++ b/Apps/FirmwareUpdater/Sources/WindowFitting.swift @@ -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) } + } + } +} diff --git a/Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/Preview.swift b/Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/Preview.swift new file mode 100644 index 00000000..8177460b --- /dev/null +++ b/Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/Preview.swift @@ -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 diff --git a/Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/WindowFit.swift b/Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/WindowFit.swift new file mode 100644 index 00000000..5ac2863d --- /dev/null +++ b/Packages/FirmwareUpdaterKit/Sources/UpdaterScreen/WindowFit.swift @@ -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) + } +} diff --git a/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/HandSetSizeTests.swift b/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/HandSetSizeTests.swift new file mode 100644 index 00000000..225dc414 --- /dev/null +++ b/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/HandSetSizeTests.swift @@ -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)) + } +} diff --git a/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/PreviewTests.swift b/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/PreviewTests.swift new file mode 100644 index 00000000..4ef50b80 --- /dev/null +++ b/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/PreviewTests.swift @@ -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 diff --git a/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/WindowFitTests.swift b/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/WindowFitTests.swift new file mode 100644 index 00000000..2b461be6 --- /dev/null +++ b/Packages/FirmwareUpdaterKit/Tests/UpdaterScreenTests/WindowFitTests.swift @@ -0,0 +1,55 @@ +import CoreGraphics +import Testing +import UpdaterScreen + +/// The updater's window fits what it shows (#761): the owner never has to resize it to read a section. +@Suite("Updater: the window fits its content") +struct WindowFitTests { + /// A 13-inch MacBook Air's screen at its default scale, less the menu bar and Dock. + static let laptop = CGSize(width: 1470, height: 860) + + @Test("It opens as tall as the content plus the title bar, and at least the minimum width") + func opensToFit() { + let size = WindowFit.size(content: CGSize(width: 420, height: 640), titleBar: 28, visible: Self.laptop) + #expect(size == CGSize(width: 560, height: 668)) + } + + @Test("Content wider than the minimum keeps its own width") + func wideContent() { + let size = WindowFit.size(content: CGSize(width: 700, height: 300), titleBar: 28, visible: Self.laptop) + #expect(size == CGSize(width: 700, height: 328)) + } + + @Test("Content taller than the screen: the window stops at the screen's visible height, and the content scrolls") + func tallerThanScreen() { + let size = WindowFit.size(content: CGSize(width: 560, height: 1200), titleBar: 28, visible: Self.laptop) + #expect(size == CGSize(width: 560, height: 860)) + } + + @Test("Content wider than the screen: the window stops at the screen's visible width") + func widerThanScreen() { + let size = WindowFit.size(content: CGSize(width: 2000, height: 300), titleBar: 28, visible: Self.laptop) + #expect(size == CGSize(width: 1470, height: 328)) + } + + @Test("A size set by hand is never shrunk when the content is smaller") + func handSetKept() { + let size = WindowFit.size(content: CGSize(width: 420, height: 300), titleBar: 28, visible: Self.laptop, + handSet: CGSize(width: 800, height: 700)) + #expect(size == CGSize(width: 800, height: 700)) + } + + @Test("New text taller than a size set by hand: the window still grows to fit it") + func growsPastHandSet() { + let size = WindowFit.size(content: CGSize(width: 420, height: 800), titleBar: 28, visible: Self.laptop, + handSet: CGSize(width: 800, height: 700)) + #expect(size == CGSize(width: 800, height: 828)) + } + + @Test("A size set by hand on a bigger screen stops at this screen's visible frame") + func handSetClamped() { + let size = WindowFit.size(content: CGSize(width: 420, height: 300), titleBar: 28, visible: Self.laptop, + handSet: CGSize(width: 2400, height: 1300)) + #expect(size == CGSize(width: 1470, height: 860)) + } +}