From db64e37ebf89c47a4d947cf463ae2fdc9b96fb35 Mon Sep 17 00:00:00 2001 From: "prompt.ac/@jeffrey" Date: Sat, 11 Jul 2026 11:54:58 -0700 Subject: [PATCH] =?UTF-8?q?menuband:=20full-screen=20LED=20visualizer=20+?= =?UTF-8?q?=20alternating-=E2=8C=98=20enable=20gesture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port of the blueberry crunch: the popover's LED scope taken edge-to-edge as an immersive full-screen mode. - VisualizerOverlay.swift / VisualizerCapture.swift: the wall itself — dark glass, live waveform, no chrome. Play routes through the instrument while it's up; Escape exits; real pointer movement dismisses it screensaver-style (grace period + travel threshold + re-anchor so a resting hand doesn't fire it); scroll stays pitch-bend/octave, not a dismissal. - WaveformStripView: setCellGeometry(step:size:) scales the LEDs up for full-screen; off-grid paints as one batched fill (offRects) instead of a screen-sized bitmap blit 30×/sec; phosphor-decay fade on the sweep. - Triggers: tap the popover waveform strip (repointed from the keymap), RIGHT ⌘ ×3, and a showVisualizer distributed-notification hook. - Gesture: replace the double-right-⌘ focus/enable gesture with an ALTERNATING left/right ⌘ triple (accepts R-L-R and L-R-L within 0.5s). The two gestures are disjoint on the same key pair. (Blueberry's separate "reverse dub" RewindVoice WIP was NOT pulled in.) --- .../Sources/MenuBand/AppDelegate.swift | 240 ++++++++++---- .../Sources/MenuBand/MenuBandPopover.swift | 15 +- .../CollapsedPianoWaveformView.swift | 19 +- .../Sources/MenuBand/VisualizerCapture.swift | 73 +++++ .../Sources/MenuBand/VisualizerOverlay.swift | 307 ++++++++++++++++++ .../Sources/MenuBand/WaveformStripView.swift | 140 +++++--- slab/menuband/Sources/MenuBand/main.swift | 5 + 7 files changed, 685 insertions(+), 114 deletions(-) create mode 100644 slab/menuband/Sources/MenuBand/VisualizerCapture.swift create mode 100644 slab/menuband/Sources/MenuBand/VisualizerOverlay.swift diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index 991761008c..d0c44941d4 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -14,6 +14,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// Live conductible drone/arp/drum loop (see MenuBandEngine + the /// `engine.*` distributed-notification handlers). private lazy var engine = MenuBandEngine(menuBand: menuBand) + /// The popover's LED scope, taken full-screen (see VisualizerOverlay). + private lazy var visualizerOverlay = VisualizerOverlay(menuBand: menuBand) /// Mic tempo follower — steers the engine's BPM to the room (engine.listen). private var micTempo: MenuBandMicTempo? /// Text-to-speech voice for the `say` hook (machines talking to each other). @@ -182,24 +184,44 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// works in TYPE mode and quiet-focus alike. private var globalChordMorphMonitor: Any? private var localChordMorphMonitor: Any? - /// Double-tap right-⌘ → toggle Menu Band focus. A bare modifier - /// can't be a Carbon hotkey, so this rides the same global/local - /// .flagsChanged stream the shift monitor uses. Why double-tap: - /// a single right-⌘ is too easy to hit by accident (and burns the - /// key as a plain modifier system-wide). The double-tap is a - /// deliberate gesture that leaves single ⌘ free for normal Mac - /// chording. - private var rightCmdMonitorGlobal: Any? - private var rightCmdMonitorLocal: Any? - /// Right Command's .flagsChanged virtual keycode (left ⌘ is 55). + /// The two bare-⌘ tap gestures. Both ride the same global/local + /// `.flagsChanged` stream (a bare modifier isn't a valid Carbon hotkey), + /// and neither can eat the other's taps because they key off different + /// patterns of the SAME two ⌘ keys: + /// + /// ALTERNATING ⌘ ×3 (R-L-R or L-R-L) → quiet focus (arm/disarm the + /// menubar piano for typing) + /// RIGHT ⌘ ×3 → the full-screen LED visualizer + /// + /// The alternating focus gesture must switch sides on each tap, so three + /// bare RIGHT taps in a row (the visualizer) never register as focus, and + /// vice-versa. Left ⌘ is keycode 55, right ⌘ is 54; we tell them apart via + /// the flagsChanged event's keyCode. + private static let leftCommandKeyCode: UInt16 = 55 private static let rightCommandKeyCode: UInt16 = 54 - /// Wall time of the last bare right-⌘ DOWN edge. Reset to 0 once - /// a pair is consumed or a chord/other-mod press interrupts the - /// sequence, so the next tap starts a fresh window. - private var lastRightCmdPressAt: CFTimeInterval = 0 - /// Max gap between the two bare right-⌘ presses that count as a - /// double-tap. ~300 ms matches macOS's own "press ⌘ twice" feel. - private static let rightCommandDoubleTapWindow: CFTimeInterval = 0.30 + + /// Alternating left/right ⌘ triple → toggle quiet focus. Tracks the side + /// of the last bare-⌘ down edge and the run length; a repeat of the same + /// side (or a lapsed window) restarts the run. + private var quietFocusMonitorGlobal: Any? + private var quietFocusMonitorLocal: Any? + private var quietFocusLastSide: UInt16 = 0 // 0 = none, else the keyCode + private var quietFocusRunCount = 0 + private var lastQuietFocusTapAt: CFTimeInterval = 0 + /// Max gap between consecutive taps of the alternating triple. + private static let quietFocusTapWindow: CFTimeInterval = 0.50 + + /// Triple-tap RIGHT ⌘ → the full-screen LED visualizer. + private var visualizerMonitorGlobal: Any? + private var visualizerMonitorLocal: Any? + /// Bare right-⌘ DOWN edges counted so far in the current run. Three inside + /// the window raises the full-screen visualizer. + private var visualizerTapCount = 0 + private var lastVisualizerTapAt: CFTimeInterval = 0 + /// Max gap BETWEEN consecutive taps of the triple. A touch roomier: three + /// taps is a longer motion to land, and missing it feels worse than waiting + /// a beat. + private static let visualizerTapWindow: CFTimeInterval = 0.40 private var popoverEscMonitor: Any? /// Sandbox-friendly local key capture. Armed when the user clicks the @@ -797,8 +819,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // Four independent global controls: show the floating piano, // focus its keys, exit that focus, and switch the keyboard layout. - // [v1] The double right-⌘ tap (startRightCommandTapMonitor) is the - // ONLY system-wide key. It already arms AND disarms focus capture, + // [v1] The alternating-⌘ triple (startQuietFocusTapMonitor) is the + // ONLY system-wide focus key. It already arms AND disarms focus capture, // so the focus/exit global hotkeys are redundant; the piano-waveform // hotkey is dead (that overlay is retired); and layout + percussion // toggles still fire from the LOCAL `localCapture.onKey` handler — @@ -874,6 +896,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { object: nil ) + // Sibling remote: raise the full-screen LED visualizer (same path the + // popover's LED scope drives). Toggles, so a second post takes it down + // without needing to reach for the mouse or Escape. + DistributedNotificationCenter.default().addObserver( + self, + selector: #selector(handleShowVisualizerNotification(_:)), + name: NSNotification.Name("computer.aestheticcomputer.menuband.showVisualizer"), + object: nil + ) + // Sibling remote: open the Apple Help book (same path as the About // window's "Manual" link). Also the reliable way to exercise Help // Viewer registration from the shell. @@ -1188,7 +1220,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { startFitNegotiation() startShiftStateMonitors() startChordMorphMonitors() - startRightCommandTapMonitor() + startQuietFocusTapMonitor() + startVisualizerTripleTapMonitor() startVisualizerAnimation() // Retint the running app's icon (About panel + Dock) to the @@ -1216,7 +1249,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { if CommandLine.arguments.contains("--focus-on-launch") { debugLog("--focus-on-launch flag detected; arming focus after run-loop settles") DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in - self?.toggleQuietFocusFromRightCommand() + self?.toggleQuietFocusFromCommandTap() } } } @@ -1259,6 +1292,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } self.pianoWaveformWindowDelegate.showExpandedForPopover() } + // Click the cluster's LED scope → the whole screen becomes that scope. + // The popover goes with it: the visualizer is meant to be the only + // thing on screen, and it plays from the keyboard once it's up. + vc.onOpenVisualizer = { [weak self] in + guard let self = self else { return } + if self.isPopoverPanelShown { + self.closePopover() + } + self.visualizerOverlay.show() + } popoverVC = vc _ = vc.view } @@ -1539,12 +1582,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } - /// Right-⌘ tap toggle: arm/disarm keyboard play WITHOUT bringing + /// Alternating-⌘ tap toggle: arm/disarm keyboard play WITHOUT bringing /// up the expanded piano overlay (that's what ⌃⌥⌘K does). Just /// readies the menubar instrument for typing, with a little chime /// so the silent focus change is felt. - private func toggleQuietFocusFromRightCommand() { - // Right-⌘ double-tap is FOCUS-ONLY now: it arms (or re-arms) quiet + private func toggleQuietFocusFromCommandTap() { + // The alternating ⌘ triple is FOCUS-ONLY now: it arms (or re-arms) quiet // focus and is inert once already focused — unfocusing is Esc's job // (see the localCapture Esc handler). Keeps the gesture a pure // "bring me into play" action that can't accidentally drop focus. @@ -1986,53 +2029,124 @@ final class AppDelegate: NSObject, NSApplicationDelegate { ) { event in handler(event); return event } } - /// Double-tap right-⌘ → toggle focus capture. Two bare right-⌘ - /// presses within `rightCommandDoubleTapWindow` arm / disarm - /// the menubar piano for typing; a single tap does nothing, so - /// right ⌘ stays free as a normal modifier for the rest of the - /// system. Trade-off vs. the old single-press flow: you can't - /// do `right-⌘+f` to arm + play F in one motion — you tap twice - /// first, then play. That's the price of not arming on every - /// stray ⌘. The toggle fires a dry click on the qualifying - /// second press so the user feels the gesture land. + /// Alternating left/right ⌘ triple → toggle focus capture. Three bare ⌘ + /// down edges that switch sides each tap (R-L-R or L-R-L) inside + /// `quietFocusTapWindow` arm / disarm the menubar piano for typing. Bare + /// single ⌘ and same-side repeats do nothing, so ⌘ stays free as a normal + /// modifier for the rest of the system, and three same-side RIGHT taps read + /// as the visualizer gesture (see `startVisualizerTripleTapMonitor`), never + /// as focus. The toggle fires a dry click on the qualifying third press so + /// the user feels the gesture land. + /// + /// (This lived on a plain right-⌘ DOUBLE-tap until the visualizer's + /// right-⌘ triple took that key. Alternating sides keeps the two gestures + /// disjoint on the same pair of keys while staying instant.) /// - /// A bare modifier isn't a valid Carbon hotkey, so we ride the - /// same global/local .flagsChanged stream the shift monitor - /// already has permission for — nothing new. - private func startRightCommandTapMonitor() { + /// A bare modifier isn't a valid Carbon hotkey, so we ride the same + /// global/local .flagsChanged stream the shift monitor already has + /// permission for — nothing new. + private func startQuietFocusTapMonitor() { let handler: (NSEvent) -> Void = { [weak self] event in guard let self = self else { return } - guard event.type == .flagsChanged, - event.keyCode == Self.rightCommandKeyCode else { return } - // .flagsChanged fires on press AND release for the same - // physical key — `.command` is set on the down edge, - // cleared on the up edge. We only count down edges. - let isDown = event.modifierFlags.contains(.command) - guard isDown else { return } - // Bare right-⌘ only. If anything else is held (⇧/⌥/⌃/ - // capsLock, or a chord like ⌘⇧), this isn't a double-tap - // candidate — reset the window so a chord can't form - // half of a future double-tap. + guard event.type == .flagsChanged else { return } + let side = event.keyCode + guard side == Self.leftCommandKeyCode || side == Self.rightCommandKeyCode + else { return } + // .flagsChanged fires on press AND release for the same physical + // key — `.command` is set on the down edge, cleared on the up edge. + // We only count down edges. + guard event.modifierFlags.contains(.command) else { return } + // Bare ⌘ only. If anything else is held (⇧/⌥/⌃/capsLock, or a chord + // like ⌘⇧), this isn't a tap candidate — reset the run so a chord + // can't form part of a future alternating triple. let mask = event.modifierFlags.intersection(.deviceIndependentFlagsMask) guard mask == .command else { - self.lastRightCmdPressAt = 0 + self.quietFocusRunCount = 0 + self.quietFocusLastSide = 0 return } let now = CACurrentMediaTime() - if now - self.lastRightCmdPressAt <= Self.rightCommandDoubleTapWindow { - // Pair completed — consume it so a third press - // starts a fresh window instead of chaining toggles. - self.lastRightCmdPressAt = 0 - FocusCueBeep.shared.click() - self.toggleQuietFocusFromRightCommand() + let inWindow = now - self.lastQuietFocusTapAt <= Self.quietFocusTapWindow + // A run continues only when this tap ALTERNATES sides within the + // window; a same-side repeat (or a lapse) starts a fresh run at + // this side. + if inWindow, self.quietFocusRunCount > 0, side != self.quietFocusLastSide { + self.quietFocusRunCount += 1 } else { - self.lastRightCmdPressAt = now + self.quietFocusRunCount = 1 } - } - rightCmdMonitorGlobal = NSEvent.addGlobalMonitorForEvents( + self.quietFocusLastSide = side + self.lastQuietFocusTapAt = now + guard self.quietFocusRunCount >= 3 else { return } + // Triple completed — consume it so a fourth tap starts a fresh run + // instead of chaining toggles. + self.quietFocusRunCount = 0 + self.quietFocusLastSide = 0 + self.lastQuietFocusTapAt = 0 + FocusCueBeep.shared.click() + self.toggleQuietFocusFromCommandTap() + } + quietFocusMonitorGlobal = NSEvent.addGlobalMonitorForEvents( + matching: [.flagsChanged, .keyDown] + ) { handler($0) } + quietFocusMonitorLocal = NSEvent.addLocalMonitorForEvents( + matching: [.flagsChanged, .keyDown] + ) { handler($0); return $0 } + } + + /// Triple-tap RIGHT-⌘ → the full-screen LED visualizer (and again to put it + /// away). Rides the same global/local `.flagsChanged` stream the shift and + /// quiet-focus monitors already have permission for — nothing new to grant. + /// + /// RIGHT ⌘ because that's the key the hand actually reaches for. Quiet focus + /// alternates sides (see `startQuietFocusTapMonitor`) so three same-side + /// RIGHT taps stay unambiguously the visualizer. + /// + /// The subtle part is not counting chords. `.flagsChanged` fires the + /// instant ⌘ goes down, before you've hit the letter — so rattling off + /// ⌘C ⌘V ⌘X looks exactly like three bare taps unless we notice the key + /// that followed. Any keyDown while ⌘ is held cancels the run. + private func startVisualizerTripleTapMonitor() { + let handler: (NSEvent) -> Void = { [weak self] event in + guard let self = self else { return } + if event.type == .keyDown { + // ⌘ + something = a chord, not a tap. Kill the run — but only + // for a real key. A modifier's own keycode can arrive as a + // keyDown from synthesized input (System Events' `key code 54`), + // and treating that as a chord would cancel the very run it's + // trying to make. + let isModifierKey = event.keyCode == Self.leftCommandKeyCode + || event.keyCode == Self.rightCommandKeyCode + if event.modifierFlags.contains(.command), !isModifierKey { + self.visualizerTapCount = 0 + } + return + } + guard event.type == .flagsChanged, + event.keyCode == Self.rightCommandKeyCode else { return } + // .flagsChanged fires on press AND release; .command is set only + // on the down edge. + guard event.modifierFlags.contains(.command) else { return } + // Bare right-⌘ only — ⌘⇧, ⌘⌥ etc. can't build a tap run. + let mask = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + guard mask == .command else { self.visualizerTapCount = 0; return } + let now = CACurrentMediaTime() + self.visualizerTapCount = + (now - self.lastVisualizerTapAt <= Self.visualizerTapWindow) + ? self.visualizerTapCount + 1 + : 1 + self.lastVisualizerTapAt = now + guard self.visualizerTapCount >= 3 else { return } + self.visualizerTapCount = 0 + self.lastVisualizerTapAt = 0 + FocusCueBeep.shared.click() + if self.isPopoverPanelShown { self.closePopover() } + self.visualizerOverlay.toggle() + } + visualizerMonitorGlobal = NSEvent.addGlobalMonitorForEvents( matching: [.flagsChanged, .keyDown] ) { handler($0) } - rightCmdMonitorLocal = NSEvent.addLocalMonitorForEvents( + visualizerMonitorLocal = NSEvent.addLocalMonitorForEvents( matching: [.flagsChanged, .keyDown] ) { handler($0); return $0 } } @@ -3192,6 +3306,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } + @objc private func handleShowVisualizerNotification(_ note: Notification) { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + if self.isPopoverPanelShown { self.closePopover() } + self.visualizerOverlay.toggle() + } + } + /// Remote autoplay. `userInfo` (all string-valued, since it crosses a /// process boundary via DistributedNotificationCenter): /// - `program`: GM melodic program 0–127 (default 78 = Whistle). diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index b9a6f71a04..863c7acf8f 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -446,12 +446,11 @@ final class MenuBandPopoverViewController: NSViewController { cluster.onChartToggled = { [weak self] in self?.refitAndResizePanel() } - // Tap the waveform strip → open the full-screen keymap, same as - // the "Keymap" footer button. (The embedded cluster's own - // onOpenKeymap was never wired, so the visualizer tap did - // nothing here — restored without any global cmd-cmd shortcut.) - cluster.onOpenKeymap = { [weak self] in - self?.onMiniVisualizerExpand?() + // Tap the waveform strip → the little LED scope is a door: + // clicking it takes the same display full-screen (AppDelegate wires + // onOpenVisualizer to visualizerOverlay.show()). + cluster.onOpenVisualizer = { [weak self] in + self?.onOpenVisualizer?() } instrumentCluster = cluster stack.addArrangedSubview(cluster) @@ -1934,6 +1933,10 @@ final class MenuBandPopoverViewController: NSViewController { /// mode. var onMiniVisualizerExpand: (() -> Void)? + /// Closure called when the user clicks the instrument cluster's live LED + /// scope — AppDelegate hooks this to take that display full-screen. + var onOpenVisualizer: (() -> Void)? + @objc private func miniVisualizerClicked(_ sender: Any?) { onMiniVisualizerExpand?() } diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift index 5a5933ffd7..ff9ec0d6cb 100644 --- a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift @@ -66,6 +66,10 @@ final class CollapsedPianoWaveformView: NSView { var onStepDown: (() -> Void)? /// Fired when the Keymap button is clicked — opens the full-screen view. var onOpenKeymap: (() -> Void)? + /// Fired when the live LED scope is clicked — blows the display up to the + /// full-screen visualizer. When unset, the scope falls back to opening the + /// keymap (its original behavior on the standalone floating panel). + var onOpenVisualizer: (() -> Void)? /// Fired after the chooser grid is shown/hidden via the instrument /// name — the host popover re-fits its panel height in response. var onChartToggled: (() -> Void)? @@ -295,9 +299,18 @@ final class CollapsedPianoWaveformView: NSView { keymapButton.toolTip = "Open the full-screen keymap (piano + QWERTY)" waveformStrip.menuBand = menuBand - // Clicking the live scope opens the full keymap view — same action - // as the "Keymap" button below it. - waveformStrip.onClick = { [weak self] in self?.onOpenKeymap?() } + // Clicking the live scope blows it up to the full-screen LED wall — + // the same display, nothing else on screen. Where no visualizer is + // wired (the standalone floating panel), it falls back to its original + // job of opening the full keymap view, same as the "Keymap" button. + waveformStrip.onClick = { [weak self] in + guard let self else { return } + if let openVisualizer = self.onOpenVisualizer { + openVisualizer() + } else { + self.onOpenKeymap?() + } + } waveformStrip.translatesAutoresizingMaskIntoConstraints = false addSubview(contentContainer) diff --git a/slab/menuband/Sources/MenuBand/VisualizerCapture.swift b/slab/menuband/Sources/MenuBand/VisualizerCapture.swift new file mode 100644 index 0000000000..eb666075c7 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/VisualizerCapture.swift @@ -0,0 +1,73 @@ +import AppKit + +// VisualizerCapture — headless capture of the REAL full-screen LED visualizer +// (the same WaveformStripView the overlay puts on screen, built through +// VisualizerOverlay.makeStrip so the shot can't drift from what ships). +// +// MenuBand --render-visualizer --out wall.png [--scale 2] [--size 1440x900] +// [--program N] [--cursor 0.72] +// +// No audio engine runs headless, so the live sweep never accumulates columns +// and the wall would paint as an empty off-grid. We seed the raster with the +// same synthetic note the popover capture uses: silence, a strike, a decaying +// tail trailing up to the write cursor. +enum VisualizerCLI { + static func runIfRequested(_ args: [String]) -> Bool { + guard args.contains("--render-visualizer") else { return false } + func val(_ f: String) -> String? { + guard let i = args.firstIndex(of: f), i + 1 < args.count else { return nil } + return args[i + 1] + } + let out = val("--out") ?? "/tmp/visualizer.png" + let scale = max(1.0, Double(val("--scale") ?? "2") ?? 2) + + // Default to a laptop-ish screen in points so the LED pitch reads the + // way it will in the wild. + var size = NSSize(width: 1440, height: 900) + if let s = val("--size") { + let parts = s.lowercased().split(separator: "x") + if parts.count == 2, let w = Double(parts[0]), let h = Double(parts[1]) { + size = NSSize(width: w, height: h) + } + } + + let app = NSApplication.shared + app.setActivationPolicy(.prohibited) + + let controller = MenuBandController() + let prog = UInt8(val("--program") ?? "0") ?? 0 + controller.setMelodicProgram(prog) + + let strip = VisualizerOverlay.makeStrip(menuBand: controller, size: size) + strip.tintColor = InstrumentListView.colorForProgram(Int(prog)) + strip.seedSyntheticWaveform() + if let cursor = Double(val("--cursor") ?? "") { + // Re-pose the sweep from real-ish levels when a cursor is asked for. + let levels = (0..<220).map { i -> Float in + let t = Float(i) / 220 + return abs(sinf(t * 34)) * (0.25 + 0.75 * expf(-t * 1.6)) + } + strip.seedWaveform(levels: levels, cursorAt: cursor) + } + strip.layoutSubtreeIfNeeded() + strip.displayIfNeeded() + + let bounds = strip.bounds + let pw = Int((bounds.width * scale).rounded()) + let ph = Int((bounds.height * scale).rounded()) + guard let rep = NSBitmapImageRep( + bitmapDataPlanes: nil, pixelsWide: pw, pixelsHigh: ph, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, + colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { + FileHandle.standardError.write(Data("✗ bitmap alloc failed\n".utf8)); return true + } + rep.size = bounds.size // points; pixels are scale× → Retina capture + strip.cacheDisplay(in: bounds, to: rep) + guard let png = rep.representation(using: .png, properties: [:]) else { + FileHandle.standardError.write(Data("✗ png encode failed\n".utf8)); return true + } + try? png.write(to: URL(fileURLWithPath: out)) + print("visualizer \(pw)x\(ph) (native \(Int(bounds.width))x\(Int(bounds.height))) → \(out)") + return true + } +} diff --git a/slab/menuband/Sources/MenuBand/VisualizerOverlay.swift b/slab/menuband/Sources/MenuBand/VisualizerOverlay.swift new file mode 100644 index 0000000000..5f1dfad078 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/VisualizerOverlay.swift @@ -0,0 +1,307 @@ +import AppKit + +/// Full-screen LED visualizer — the popover's little scope with everything +/// else taken away. One dot-matrix raster, edge to edge, dark glass all the +/// way out to the corners, the live waveform sweeping across it. No chrome, +/// no buttons, nothing to read: the display IS the mode. +/// +/// Two ideas hold it together. +/// +/// **You play into it, you don't drive it.** The keyboard still reaches the +/// instrument while the wall is up — that's the whole point of standing back +/// from the machine. Notes route through `handleLocalKey` exactly as they do +/// with the popover open, and Escape is the only key that means "exit." +/// +/// **The mouse means "I'm done."** Any real pointer movement tears it down, +/// screensaver-style, so there's no affordance to hunt for and nothing to +/// break the picture. *Real* is the load-bearing word: the pointer is parked +/// on the LED strip the user just clicked, and a hand resting on a trackpad +/// twitches. So the trigger arms after a grace period, re-anchors to wherever +/// the pointer actually settled, and then wants a few points of travel before +/// it fires. Scroll is deliberately NOT a dismissal — it's pitch-bend and +/// octave, and it moves no pointer. +final class VisualizerOverlay: NSObject { + private weak var menuBand: MenuBandController? + private var panel: VisualizerOverlayPanel? + private var strip: WaveformStripView? + + private var keyMonitor: Any? + private var mouseMonitors: [Any] = [] + private var tintTimer: Timer? + private var armWorkItem: DispatchWorkItem? + + /// Pointer position the dismissal measures against. Travel is compared to + /// this fixed anchor rather than frame-to-frame, so a slow deliberate + /// drift still accumulates into a dismiss instead of sneaking under a + /// per-event threshold forever. + private var anchor: NSPoint = .zero + private var isArmed = false + private var cursorHidden = false + /// Whoever was frontmost before we activated, so exiting hands focus back + /// rather than dumping the user in a menubar-only app. + private var appBeforeOpen: NSRunningApplication? + + /// Beat of stillness before the pointer can dismiss. Long enough to cover + /// the popover's fade-out and the hand coming off the mouse. + private static let armDelay: TimeInterval = 0.45 + /// Pointer travel from `anchor` that counts as intent to leave. + private static let dismissSlop: CGFloat = 6 + /// LED pitch for the wall — 2× the popover's 5/3.5 pt cells. A laptop + /// display lands around 140 × 90 lamps, which is both a longer buffer (the + /// sweep is one column per frame, so more columns = more seconds of music + /// on screen at once — about 5 s here) and still coarse enough to read as + /// hardware rather than a plotted line. + private static let cellStep: CGFloat = 10 + private static let cellSize: CGFloat = 7 + + var isShown: Bool { panel?.isVisible == true } + + init(menuBand: MenuBandController) { + self.menuBand = menuBand + super.init() + } + + /// The wall itself, minus the window around it. `--render-visualizer` + /// builds its capture through here too, so a headless shot can't drift + /// from what actually ships. + static func makeStrip(menuBand: MenuBandController?, size: NSSize) -> WaveformStripView { + let strip = WaveformStripView(frame: NSRect(origin: .zero, size: size)) + strip.menuBand = menuBand + strip.autoresizingMask = [.width, .height] + // The host bezel is the screen itself — no recessed plate, no rounded + // corners, glass straight out to the edges. + strip.drawsPlate = false + strip.setCellGeometry(step: cellStep, size: cellSize) + return strip + } + + deinit { + // Never strand a hidden cursor if we're torn down mid-show. + if cursorHidden { NSCursor.unhide() } + } + + func toggle() { + if isShown { dismiss() } else { show() } + } + + func show() { + guard !isShown, let menuBand else { return } + let mouse = NSEvent.mouseLocation + let screen = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) } + ?? NSScreen.main + ?? NSScreen.screens.first + guard let screen else { return } + + let strip = Self.makeStrip(menuBand: menuBand, size: screen.frame.size) + strip.isLive = true + // Clicking anywhere on the wall exits, same as moving the mouse. + strip.onClick = { [weak self] in self?.dismiss() } + + let panel = VisualizerOverlayPanel( + contentRect: screen.frame, + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + // Above the menubar and the Dock — a visualizer that stopped at the + // menubar would read as a big window, not as the machine taking over + // the screen. + panel.level = .screenSaver + panel.backgroundColor = .black + panel.isOpaque = true + panel.hasShadow = false + panel.animationBehavior = .none + panel.isMovable = false + panel.acceptsMouseMovedEvents = true + panel.isReleasedWhenClosed = false + panel.hidesOnDeactivate = false + panel.collectionBehavior = [ + .canJoinAllSpaces, + .fullScreenAuxiliary, + .stationary, + .ignoresCycle, + ] + panel.contentView = strip + panel.alphaValue = 0 + + self.panel = panel + self.strip = strip + applyTint() + + appBeforeOpen = frontmostOtherApp() + NSApp.activate(ignoringOtherApps: true) + panel.makeKeyAndOrderFront(nil) + NSAnimationContext.runAnimationGroup { ctx in + ctx.duration = 0.18 + ctx.timingFunction = CAMediaTimingFunction(name: .easeOut) + panel.animator().alphaValue = 1 + } + + if !cursorHidden { + NSCursor.hide() + cursorHidden = true + } + + installMonitors() + // Keep the wall's color on the voice: the tint follows the active + // instrument family (red while sampling, accent in MIDI mode), and the + // user can change voice from the keyboard while the visualizer is up. + let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in + self?.applyTint() + } + timer.tolerance = 0.1 + RunLoop.main.add(timer, forMode: .common) + tintTimer = timer + + arm() + } + + func dismiss() { + guard let panel else { return } + removeMonitors() + armWorkItem?.cancel() + armWorkItem = nil + isArmed = false + tintTimer?.invalidate() + tintTimer = nil + // Stop the capture client before the fade so the synth's tap can wind + // down with the display rather than 140 ms after it. + strip?.isLive = false + menuBand?.releaseAllHeldNotes() + if cursorHidden { + NSCursor.unhide() + cursorHidden = false + } + self.panel = nil + self.strip = nil + NSAnimationContext.runAnimationGroup({ ctx in + ctx.duration = 0.14 + ctx.timingFunction = CAMediaTimingFunction(name: .easeOut) + panel.animator().alphaValue = 0 + }, completionHandler: { + panel.orderOut(nil) + panel.contentView = nil + }) + restorePreviousAppFocus() + } + + // MARK: - Dismissal arming + + /// Wait out the grace period, then re-anchor to wherever the pointer + /// actually is. Re-anchoring matters: between the click and now the + /// popover faded and the user may have lifted or nudged the mouse, and + /// measuring from the stale click point would fire immediately. + private func arm() { + armWorkItem?.cancel() + let work = DispatchWorkItem { [weak self] in + guard let self, self.isShown else { return } + self.anchor = NSEvent.mouseLocation + self.isArmed = true + } + armWorkItem = work + DispatchQueue.main.asyncAfter(deadline: .now() + Self.armDelay, execute: work) + } + + private func pointerMoved() { + guard isArmed, isShown else { return } + let p = NSEvent.mouseLocation + guard hypot(p.x - anchor.x, p.y - anchor.y) > Self.dismissSlop else { return } + dismiss() + } + + // MARK: - Monitors + + private func installMonitors() { + let moves: NSEvent.EventTypeMask = [ + .mouseMoved, .leftMouseDragged, .rightMouseDragged, .otherMouseDragged, + ] + // Local covers the pointer over our own key panel; global covers the + // pointer crossing anything else (another Space, a second display). + if let m = NSEvent.addLocalMonitorForEvents(matching: moves, handler: { [weak self] event in + self?.pointerMoved() + return event + }) { + mouseMonitors.append(m) + } + if let m = NSEvent.addGlobalMonitorForEvents(matching: moves, handler: { [weak self] _ in + self?.pointerMoved() + }) { + mouseMonitors.append(m) + } + + // Deliberately NOT gated on `panel.isKeyWindow`. LocalKeyCapture arms + // an invisible panel that can hold key while the user plays, and + // requiring key here would leave Escape with nowhere to land. While + // the wall is up it owns the interaction, whichever of our windows is + // key. + // + // No double-trigger with LocalKeyCapture's own monitor, either: it is + // registered first, and a local monitor returning nil ends the chain. + // Note keys it consumes never reach us; Escape it declines does. + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp]) { [weak self] event in + guard let self, self.isShown else { return event } + let isDown = event.type == .keyDown + if isDown, event.keyCode == 53 { // Escape + self.dismiss() + return nil + } + // Everything else is music. Same routing the expanded keymap panel + // uses, so the instrument behaves identically with the wall up. + let consumed = self.menuBand?.handleLocalKey( + keyCode: event.keyCode, + isDown: isDown, + isRepeat: event.isARepeat, + flags: event.modifierFlags + ) ?? false + return consumed ? nil : event + } + } + + private func removeMonitors() { + for m in mouseMonitors { NSEvent.removeMonitor(m) } + mouseMonitors.removeAll() + if let keyMonitor { + NSEvent.removeMonitor(keyMonitor) + self.keyMonitor = nil + } + } + + // MARK: - Tint + + /// Mirrors `ExpandedPianoWaveformView.applyWaveformTint` — the wall wears + /// the same color the little scope would. + private func applyTint() { + guard let strip, let menuBand else { return } + if menuBand.sampleRecordingActive { + strip.tintColor = .systemRed + } else if menuBand.midiMode { + strip.tintColor = .controlAccentColor + } else { + let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) + strip.tintColor = InstrumentListView.colorForProgram(safe) + } + } + + // MARK: - Focus + + private func frontmostOtherApp() -> NSRunningApplication? { + let frontmost = NSWorkspace.shared.frontmostApplication + guard frontmost?.bundleIdentifier != Bundle.main.bundleIdentifier else { return nil } + return frontmost + } + + private func restorePreviousAppFocus() { + guard let app = appBeforeOpen, + !app.isTerminated, + app.bundleIdentifier != Bundle.main.bundleIdentifier else { return } + appBeforeOpen = nil + app.activate(options: []) + } +} + +/// Borderless panels refuse key focus by default. The visualizer needs it — +/// it's a playable surface, and Escape has to land somewhere. +final class VisualizerOverlayPanel: NSPanel { + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { true } +} diff --git a/slab/menuband/Sources/MenuBand/WaveformStripView.swift b/slab/menuband/Sources/MenuBand/WaveformStripView.swift index e679076766..f3864018b6 100644 --- a/slab/menuband/Sources/MenuBand/WaveformStripView.swift +++ b/slab/menuband/Sources/MenuBand/WaveformStripView.swift @@ -22,7 +22,7 @@ final class WaveformStripView: NSView { /// family color so the display matches its per-voice framing. Rewind /// still flips to orange regardless of this. var tintColor: NSColor? { - didSet { offPattern = nil; needsDisplay = true } + didSet { needsDisplay = true } } /// When false the display stops capturing and clears to an empty grid — @@ -71,15 +71,36 @@ final class WaveformStripView: NSView { private var written: [Bool] = [] private var cursor = 0 /// Raster geometry — chunky cells, low-res on purpose so it reads as a - /// hardware display, not an anti-aliased plot. - private static let cellStep: CGFloat = 5 // px between cell origins - private static let cellSize: CGFloat = 3.5 // lit cell square - private static let inset: CGFloat = 2 // glass inner margin + /// hardware display, not an anti-aliased plot. Sized for the popover by + /// default; `setCellGeometry` scales it up for the full-screen visualizer, + /// where the same 5 pt cells would read as a fine dot screen from across + /// the room instead of a wall of LEDs. + private var cellStep: CGFloat = 5 // px between cell origins + private var cellSize: CGFloat = 3.5 // lit cell square + private static let inset: CGFloat = 2 // glass inner margin + + /// Resize the LEDs. Forces a full raster rebuild (the column/row counts + /// fall out of the cell pitch), so the sweep restarts from a clean grid. + func setCellGeometry(step: CGFloat, size: CGFloat) { + guard step != cellStep || size != cellSize else { return } + cellStep = step + cellSize = size + cols = 0 // defeat updateGridGeometry's no-op guard + rows = 0 + updateGridGeometry() + needsDisplay = true + } private var cols = 0 private var rows = 0 - /// Cached faint off-grid (every cell at rest-glow alpha) so the per-frame - /// draw only fills LIT cells. Rebuilt when geometry or tint changes. - private var offPattern: NSImage? + /// Every cell of the raster, precomputed once per geometry change. The + /// off-grid paints as ONE batched `CGContext.fill` of this list rather than + /// a per-frame blit of a screen-sized bitmap — at full-screen sizes that + /// bitmap was several megabytes copied 30× a second for a picture that + /// never changes. + private var offRects: [CGRect] = [] + /// Scratch buffer for one column's lit cells, reused every frame so the + /// draw loop allocates nothing. + private var columnRects: [CGRect] = [] private var timer: Timer? /// While reversing: eased column offset of the playhead back from the /// cursor, driven by the audio's actual reverse progress. @@ -108,8 +129,8 @@ final class WaveformStripView: NSView { private func updateGridGeometry() { let w = bounds.width - Self.inset * 2 let h = bounds.height - Self.inset * 2 - let newCols = max(0, Int(w / Self.cellStep)) - var newRows = max(3, Int(h / Self.cellStep)) + let newCols = max(0, Int(w / cellStep)) + var newRows = max(3, Int(h / cellStep)) if newRows % 2 == 0 { newRows -= 1 } guard newCols != cols || newRows != rows else { return } cols = newCols @@ -118,7 +139,15 @@ final class WaveformStripView: NSView { gridMax = .init(repeating: 0, count: cols) written = .init(repeating: false, count: cols) cursor = 0 - offPattern = nil + columnRects.reserveCapacity(rows) + offRects = [] + offRects.reserveCapacity(cols * rows) + for c in 0.. NSImage { - if let cached = offPattern, cached.size == bounds.size { return cached } - let img = NSImage(size: bounds.size) - img.lockFocus() - tint.withAlphaComponent(0.09).setFill() - for c in 0.. CGFloat { - Self.inset + (bounds.width - Self.inset * 2 - CGFloat(cols) * Self.cellStep) / 2 - + CGFloat(c) * Self.cellStep + Self.inset + (bounds.width - Self.inset * 2 - CGFloat(cols) * cellStep) / 2 + + CGFloat(c) * cellStep } private func cellY(_ r: Int) -> CGFloat { - Self.inset + (bounds.height - Self.inset * 2 - CGFloat(rows) * Self.cellStep) / 2 - + CGFloat(r) * Self.cellStep + Self.inset + (bounds.height - Self.inset * 2 - CGFloat(rows) * cellStep) / 2 + + CGFloat(r) * cellStep } override func draw(_ dirtyRect: NSRect) { let bounds = self.bounds guard bounds.width > 6, bounds.height > 6 else { return } if cols == 0 { updateGridGeometry() } - guard cols > 0 else { return } + guard cols > 0, let ctx = NSGraphicsContext.current?.cgContext else { return } let reversing = menuBand?.isRewinding ?? false let accent = NSColor.controlAccentColor let tint = tintColor ?? accent @@ -313,12 +327,15 @@ final class WaveformStripView: NSView { Self.glass.setFill(); plate.fill() accent.withAlphaComponent(0.55).setStroke(); plate.lineWidth = 1.0; plate.stroke() } else { - Self.glass.setFill(); bounds.fill() + ctx.setFillColor(Self.glass.cgColor) + ctx.fill(bounds) } - // Faint off-grid — the raster itself, always visible. - offGridImage(tint: tint).draw(in: bounds, from: .zero, - operation: .sourceOver, fraction: 1.0) + // Faint off-grid — the raster itself, always visible. One batched fill + // of every cell; Quartz walks the rect list far faster than we can + // issue the fills one at a time. + ctx.setFillColor(tint.withAlphaComponent(0.09).cgColor) + ctx.fill(offRects) let halfRows = (rows - 1) / 2 let centerRow = halfRows @@ -344,32 +361,63 @@ final class WaveformStripView: NSView { CGFloat(sqrtf(Swift.min(1, Swift.max(0, v) * 2.2))) } + // Age of a column: 0 is the one just written, cols-1 the oldest — the + // one sitting immediately AHEAD of the write cursor, about to be + // overwritten. + func age(_ c: Int) -> CGFloat { + CGFloat(((cursor - 1 - c) % cols + cols) % cols) + } + // Phosphor decay. Without this the ring buffer never appears to clear: + // a column written a full sweep ago paints exactly as bright as one + // written this frame, so the wall just sits there full, quietly + // rewriting itself in place. Fading by age turns the sweep into a comet + // tail — the trace burns in at the head and dims to almost nothing by + // the time the cursor comes back around to erase it. + let oldest = CGFloat(max(1, cols - 1)) + func glow(_ c: Int) -> CGFloat { + let t = age(c) / oldest // 0 fresh → 1 stale + return 0.06 + 0.88 * pow(1 - t, 1.7) // ease-out; never fully black + } + // Lit cells, column by column — center baseline outward. The column // under the write cursor (live) / playhead (reversing) burns brighter. + // One batched fill per column instead of one per cell: the full-screen + // wall repaints thousands of LEDs at 30 fps, and the per-cell fill is + // what made it work harder than it needed to. for c in 0..= 0, headCol < cols { - (reversing ? NSColor.systemOrange : accent).withAlphaComponent(0.30).setFill() + let marker = (reversing ? NSColor.systemOrange : accent).withAlphaComponent(0.30) + ctx.setFillColor(marker.cgColor) let x = cellX(headCol) + columnRects.removeAll(keepingCapacity: true) for r in 0..