From 754e2bcaf3df123e63dd5fc311876fd9e1bf5f59 Mon Sep 17 00:00:00 2001 From: "prompt.ac/@jeffrey" Date: Sun, 17 May 2026 15:12:16 -0400 Subject: [PATCH] menuband: pitch-bend holds while finger rests; sample-voice + tape work - Pitch-bend no longer snaps back on a 150ms idle timeout. The gesture rides .mouseMoved events, which carry no trackpad touch state, so a finger resting still on the trackpad emitted no deltas and the timer fired mid-hold. Spring-back is now driven solely by keyboard note release (onLitChanged -> startBendDecay), which was always the intended design. Removed the dead bendIdleTimer property and its cancelBendDecay cleanup. - MenuBandSampleVoice/Synth/Controller: sample-voice playback so pressing a key plays the piano instead of falling back to a tone. - New cassette/tape feature: MenuBandTape recorder + TapeTransportView popover deck + TapeCoverArt Finder icon + TapeDragSource eject. - KeyboardIconRenderer + AboutWindow + popover supporting tweaks. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../Sources/MenuBand/AboutWindow.swift | 29 + .../Sources/MenuBand/AppDelegate.swift | 223 ++++- .../MenuBand/KeyboardIconRenderer.swift | 846 +++++++++++++++++- .../Sources/MenuBand/MenuBandController.swift | 108 +++ .../Sources/MenuBand/MenuBandPopover.swift | 4 + .../MenuBand/MenuBandSampleVoice.swift | 76 +- .../Sources/MenuBand/MenuBandSynth.swift | 201 +++-- .../Sources/MenuBand/MenuBandTape.swift | 667 ++++++++++++++ .../Sources/MenuBand/TapeCoverArt.swift | 409 +++++++++ .../Sources/MenuBand/TapeDragSource.swift | 26 + .../Sources/MenuBand/TapeTransportView.swift | 492 ++++++++++ 11 files changed, 3009 insertions(+), 72 deletions(-) create mode 100644 slab/menuband/Sources/MenuBand/MenuBandTape.swift create mode 100644 slab/menuband/Sources/MenuBand/TapeCoverArt.swift create mode 100644 slab/menuband/Sources/MenuBand/TapeDragSource.swift create mode 100644 slab/menuband/Sources/MenuBand/TapeTransportView.swift diff --git a/slab/menuband/Sources/MenuBand/AboutWindow.swift b/slab/menuband/Sources/MenuBand/AboutWindow.swift index 77d97d0ae6..291deb82d5 100644 --- a/slab/menuband/Sources/MenuBand/AboutWindow.swift +++ b/slab/menuband/Sources/MenuBand/AboutWindow.swift @@ -331,6 +331,24 @@ final class AboutWindowController: NSWindowController, NSWindowDelegate { let langRow = buildLanguagePicker() stack.addArrangedSubview(langRow) + // Tape-deck feature toggle — defaults off until the deck is + // ready to ship. Lives in the About window (not the popover) + // so it's tucked away as a beta switch, not a normal control. + stack.setCustomSpacing(12, after: langRow) + let tapeCheckbox = NSButton( + checkboxWithTitle: "Cassette deck (beta)", + target: self, + action: #selector(toggleTapeFeature(_:)) + ) + tapeCheckbox.state = UserDefaults.standard + .bool(forKey: KeyboardIconRenderer.tapeFeatureDefaultsKey) + ? .on : .off + tapeCheckbox.font = NSFont.systemFont(ofSize: 11) + tapeCheckbox.toolTip = + "Show the cassette tape deck in the menubar. Work in progress." + tapeCheckbox.translatesAutoresizingMaskIntoConstraints = false + stack.addArrangedSubview(tapeCheckbox) + // Crash-report summary — single orange ⚠️ button reading // "Menu Band crashed N times". Opens the scroll viewer where // the user can review the .ips contents and click Send to @@ -585,6 +603,17 @@ final class AboutWindowController: NSWindowController, NSWindowDelegate { onOpenPlugins?() } + /// Persist the cassette-deck beta flag and tell AppDelegate to + /// re-render the menubar icon. Status-item width changes on the + /// flip, so the notification handler also resizes the slot. + @objc private func toggleTapeFeature(_ sender: NSButton) { + let on = sender.state == .on + UserDefaults.standard.set( + on, forKey: KeyboardIconRenderer.tapeFeatureDefaultsKey) + NotificationCenter.default.post( + name: .menuBandTapeFeatureChanged, object: nil) + } + /// Open a scroll panel containing the .ips text for every pending /// diagnostic report. Built fresh each time so it always reflects /// the current contents of `~/Library/Logs/DiagnosticReports/`. diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index 1b3ad545f5..ec08360277 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -31,6 +31,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// many menubar apps). When that happens we shrink the layout — /// full piano → 1 octave → compact chip — until something fits. private var visibilityTimer: Timer? + /// Live drag-source for the inline tape eject. NSStatusBarButton + /// doesn't conform to NSDraggingSource so we hand a small adapter + /// in; this ivar keeps it alive for the duration of the drag. + private var tapeDragSource: TapeDragSource? /// 24fps redraw timer for the in-chip mini visualizer. Drives the /// per-bar sine wiggle + smooths the activity level so bars move /// continuously instead of snapping on note events. @@ -182,11 +186,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// CGAssociateMouseAndMouseCursorPosition so position doesn't /// drift). private var pitchBendLockScreenPoint: NSPoint = .zero - /// Fires when no cursor-Y delta has come in for the idle - /// window — synthesizes a "finger lifted off the trackpad" - /// edge. mouseMoved has no .ended phase, so we infer it from - /// silence and start the rubber-band. - private var bendIdleTimer: Timer? /// Local + global NSEvent monitors for trackpad scroll events. /// Held so we can teardown if needed (we don't, but per-instance /// retention is cleaner than globals). @@ -222,6 +221,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // Otherwise the icon flashes the default `.full` width until // the next updateIcon() catches up. applyForcedLayoutIfAny() + // Mirror the tape-deck feature flag from UserDefaults into the + // renderer BEFORE the status item is sized — otherwise the bar + // would briefly reserve room for the deck and then snap back. + KeyboardIconRenderer.tapeFeatureEnabled = UserDefaults.standard + .bool(forKey: KeyboardIconRenderer.tapeFeatureDefaultsKey) + NotificationCenter.default.addObserver( + self, + selector: #selector(handleTapeFeatureToggled(_:)), + name: .menuBandTapeFeatureChanged, + object: nil + ) Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in debugLog("heartbeat") } @@ -1478,6 +1488,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // tint the chip + VU bars red while the user is holding the // record key. KeyboardIconRenderer.recordingActive = menuBand.sampleRecordingActive + // Tape state — refreshed every paint so the cassette REC dot, + // mic LED, fill bar and playhead track the controller in real + // time. Position fractions are computed off the tape's own + // duration accessors; phase is wall-clock so the reels keep + // turning smoothly between paint ticks. + let tape = menuBand.tape + let fillFrac = CGFloat(tape.durationSeconds / MenuBandTape.maxDurationSeconds) + let playFrac = CGFloat(tape.positionSeconds / max(0.001, tape.durationSeconds)) + KeyboardIconRenderer.tapeRecording = (tape.state == .recording) + KeyboardIconRenderer.tapePlaying = (tape.state == .playing) + KeyboardIconRenderer.tapeFillFraction = min(1, max(0, fillFrac)) + KeyboardIconRenderer.tapePlayheadFraction = min(1, max(0, playFrac)) + KeyboardIconRenderer.tapeMicHot = + (tape.state == .recording) && + (MenuBandSampleVoice.micAuthorizationStatus() == .authorized) + KeyboardIconRenderer.tapePhase = CACurrentMediaTime() // Note: miniVisualizerLevel + miniVisualizerPhase are driven by // the visualizerAnimTimer (24fps smoothed VU motion), not from // here — overriding them on every note-event redraw would @@ -1710,6 +1736,67 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // never from a stray tap on the LED bars. showPopover() return + case .tape: + handleTapeMouseDown(button: button, + downEvent: downEvent, + imagePoint: imagePoint) + return + case .tapeRew: + menuBand.rewindTape() + updateIcon() + return + case .tapeStop: + menuBand.stopTape() + updateIcon() + return + case .tapePlay: + menuBand.playTape() + updateIcon() + return + case .tapeFfwd: + menuBand.tapeSeekToEnd() + updateIcon() + return + case .tapeRec: + menuBand.toggleTapeRecording() + updateIcon() + return + case .tapeEject: + // Drop the WAV onto the Desktop with the cassette-art icon + // already attached by `tape.eject()`. The cassette body still + // owns the live drag-to-anywhere gesture; this button is the + // "didn't think to drag it" fallback. Stop any in-flight + // recording first so the eject sees a finalized buffer. + let stateBefore = menuBand.tape.state + let hasRec = menuBand.tape.hasRecording + let dur = menuBand.tape.durationSeconds + NSLog("MenuBand: eject button pressed — state=\(stateBefore) hasRecording=\(hasRec) duration=\(dur)s") + if stateBefore == .recording { + menuBand.stopTape() + } + if let src = menuBand.ejectTape() { + NSLog("MenuBand: eject wrote \(src.lastPathComponent)") + let desktop = FileManager.default.urls( + for: .desktopDirectory, in: .userDomainMask).first + if let desktop = desktop { + let dest = uniqueDestinationOnDesktop( + in: desktop, preferredName: src.lastPathComponent) + do { + try FileManager.default.moveItem(at: src, to: dest) + NSWorkspace.shared.activateFileViewerSelecting([dest]) + } catch { + NSLog("MenuBand: tape eject move failed: \(error)") + NSWorkspace.shared.activateFileViewerSelecting([src]) + } + } else { + NSWorkspace.shared.activateFileViewerSelecting([src]) + } + } else { + NSLog("MenuBand: eject button — nothing to eject (no recording)") + NSSound.beep() + } + updateIcon() + return case .note(let n): startDisplayNote = n case .none: @@ -1793,6 +1880,106 @@ final class AppDelegate: NSObject, NSApplicationDelegate { return UInt8(value) } + // MARK: - Tape mouse routing + // + // Mouse-down on the inline cassette enters a small dispatcher that + // distinguishes between a click (toggle REC) and a drag (eject the + // current recording onto the desktop). Same mouse-tracking trick as + // SheetMusicView's PDF pull-out — we run our own modal-ish event + // loop until either `mouseUp` (click) or a meaningful drag delta + // arrives (eject). + + /// Pick a non-colliding filename inside `dir` for the freshly + /// ejected WAV. macOS' move would fail (or silently overwrite) if + /// a tape with the same name is already on the Desktop. + private func uniqueDestinationOnDesktop(in dir: URL, + preferredName: String) -> URL { + var candidate = dir.appendingPathComponent(preferredName) + if !FileManager.default.fileExists(atPath: candidate.path) { + return candidate + } + let base = (preferredName as NSString).deletingPathExtension + let ext = (preferredName as NSString).pathExtension + var n = 2 + while true { + let name = ext.isEmpty + ? "\(base) \(n)" + : "\(base) \(n).\(ext)" + candidate = dir.appendingPathComponent(name) + if !FileManager.default.fileExists(atPath: candidate.path) { + return candidate + } + n += 1 + } + } + + private func handleTapeMouseDown(button: NSStatusBarButton, + downEvent: NSEvent, + imagePoint: (NSPoint) -> NSPoint) { + let startPt = imagePoint(downEvent.locationInWindow) + while let next = NSApp.nextEvent( + matching: [.leftMouseDragged, .leftMouseUp], + until: .distantFuture, + inMode: .eventTracking, + dequeue: true + ) { + if next.type == .leftMouseUp { + // Click without drag → no-op. REC moved out to the + // dedicated red transport button; the cassette body is + // now a pure drag-source. + return + } + // .leftMouseDragged + let p = imagePoint(next.locationInWindow) + if abs(p.x - startPt.x) > 5 || abs(p.y - startPt.y) > 5 { + if startTapeEjectDrag(button: button, event: next) { + return + } + // Drag-out failed (no recording, write error). Wait + // for mouseUp so we don't leave a stuck drag state. + } + } + } + + /// Begin a drag session whose pasteboard item is the freshly + /// rendered WAV. Mirrors `SheetMusicView.beginPDFDrag` — eager + /// render to a temp file BEFORE calling `beginDraggingSession`, + /// then animate the cassette "ejecting" downward so the user + /// sees the source artifact leave the menubar. + @discardableResult + private func startTapeEjectDrag(button: NSStatusBarButton, + event: NSEvent) -> Bool { + guard menuBand.tape.hasRecording else { + NSLog("MenuBand: tape eject ignored — no recording") + return false + } + // Capture the result struct so we can use the actual cover + // art (waveform + date + duration) as the drag image. Falls + // back to a generic cassette glyph if eject fails. + guard let result = menuBand.tape.eject() else { + NSLog("MenuBand: tape eject failed to write stems") + return false + } + let dragItem = NSDraggingItem(pasteboardWriter: result.file as NSURL) + // Drag preview = the exact icon `eject()` just attached to + // the .wav file. Reading it back through `NSWorkspace` + // rather than re-rendering keeps the preview and the on-disk + // icon identical, so the user sees the same cassette artwork + // riding the cursor that they'll see in Finder after drop. + let previewIcon = NSWorkspace.shared.icon(forFile: result.file.path) + let previewSize = NSSize(width: 96, height: 96) + let local = button.convert(event.locationInWindow, from: nil) + let dragFrame = NSRect(x: local.x - previewSize.width / 2, + y: local.y - previewSize.height / 2, + width: previewSize.width, + height: previewSize.height) + dragItem.setDraggingFrame(dragFrame, contents: previewIcon) + let source = TapeDragSource() + tapeDragSource = source + button.beginDraggingSession(with: [dragItem], event: event, source: source) + return true + } + // MARK: - Popover /// Close the popover and tear down the click-away monitor. Called from @@ -1851,6 +2038,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// verify chrome that lives only in the About panel (the /// crash-report send button, the language picker, the plugins /// chip) without driving the menubar. + @objc private func handleTapeFeatureToggled(_ note: Notification) { + let enabled = UserDefaults.standard + .bool(forKey: KeyboardIconRenderer.tapeFeatureDefaultsKey) + KeyboardIconRenderer.tapeFeatureEnabled = enabled + // Status item width changes with the flag — resize the slot + // before redrawing so the icon doesn't get cropped/scaled. + statusItem.length = KeyboardIconRenderer.imageSize.width + updateIcon() + } + @objc private func handleShowAboutNotification(_ note: Notification) { debugLog("handleShowAboutNotification received") DispatchQueue.main.async { [weak self] in @@ -2089,14 +2286,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { showPitchBendOverlay() } updatePitchBendOverlayImage() - // Re-arm the idle-detection timer; if 150 ms goes by - // without another delta we treat the finger as lifted - // and start the spring rubber-band. - bendIdleTimer?.invalidate() - bendIdleTimer = Timer.scheduledTimer(withTimeInterval: 0.15, - repeats: false) { [weak self] _ in - self?.startBendDecay() - } + // No idle timeout: a finger resting still on the trackpad + // emits no .mouseMoved deltas, so any silence-based timer + // would snap the bend back while the user is deliberately + // holding it. The rubber-band is driven solely by keyboard + // note release (see onLitChanged → startBendDecay), so the + // bend holds wherever it's left until the note lifts. debugLog("bend cursor dy=\(dy) lit=\(menuBand.litNotes.count) amt=\(bendAmount)") } @@ -2169,8 +2364,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private func cancelBendDecay() { bendDecayTimer?.invalidate() bendDecayTimer = nil - bendIdleTimer?.invalidate() - bendIdleTimer = nil bendVelocity = 0 } diff --git a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift index dfdac68916..bc7de9ffbc 100644 --- a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift +++ b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift @@ -300,12 +300,123 @@ enum KeyboardIconRenderer { /// note + settingsHitRect stay anchored where they were; this /// pad just gives multi-digit numbers somewhere to grow without /// clipping at the image edge. - static let voiceBadgeRightPad: CGFloat = 12.0 + /// Reserved space to the right of the music-note glyph for the + /// voice-number badge digits. Sized so a 2-digit voice (1-99, + /// covers the entire GM lineup except the top 28) sits cleanly + /// inside the slot. 3-digit voices may extend a hair past the + /// edge but still read clearly. Keeps the icon's right margin + /// close to standard macOS menubar spacing. + static let voiceBadgeRightPad: CGFloat = 5.0 enum HitResult: Equatable { case openSettings case openVisualizer case note(UInt8) + /// Cassette body — pure drag-source now (REC moved to its own + /// transport button). Clicking the cassette is a no-op; pulling + /// it sideways ejects the WAV to the Desktop. + case tape + /// Transport buttons live between the cassette and the piano, + /// in classic Walkman order: REW · STOP · PLAY · FFWD · REC · EJECT. + case tapeRew + case tapeStop + case tapePlay + case tapeFfwd + case tapeRec + case tapeEject + } + + // MARK: - Tape (inline cassette) + // + // A miniature Walkman-style cassette sits to the LEFT of the piano + // keys. Single-click toggles REC; mouse-drag starts a drag session + // that ejects the WAV file onto the desktop. Visual cues: + // + // • Two hexagonal-hub reels rotate during REC (red tint) or PLAY + // (steel tint). + // • A small red "● REC" LED inside the label card glows while + // recording. + // • A mic-permission LED to the right of the cassette glows + // orange while the hot mic is delivering frames (i.e. while + // REC is engaged AND mic access was granted). + // + // All state is pushed in via the static properties below before + // each `image(...)` render — AppDelegate's `updateIcon()` reads + // the controller's tape and refreshes these. + static var tapeRecording: Bool = false + static var tapePlaying: Bool = false + /// 0..1 fraction of the recording capacity used. Drives the + /// "fill" of the right reel and the duration tick mark. + static var tapeFillFraction: CGFloat = 0 + /// 0..1 playhead position. Identical to fill while no recording + /// happened yet; tracks playback otherwise. + static var tapePlayheadFraction: CGFloat = 0 + /// Orange "mic hot" LED. True while the synth is delivering mic + /// frames AND the tape is recording. + static var tapeMicHot: Bool = false + /// Continuous wall-clock seconds; drives reel rotation so the + /// reels keep turning smoothly between hover events. + static var tapePhase: CFTimeInterval = 0 + + // Feature flag — the tape deck is still WIP. AppDelegate mirrors + // `MenuBandTapeDeckEnabled` from UserDefaults into this flag, and + // every tape-related layout/draw/hit-test branch is gated on it. + // Defaults to OFF so a fresh install doesn't ship the unfinished + // surface in the menubar. + static var tapeFeatureEnabled: Bool = false + + /// UserDefaults key for the tape-deck feature flag. + static let tapeFeatureDefaultsKey = "MenuBandTapeDeckEnabled" + + // Compact Cassette physical aspect: 100.4mm × 63.8mm ≈ 1.574:1. + // Cassette fills the full piano height (whiteH = 21pt); width + // tracks the real-world ratio: 21 × 33 ≈ 1.571:1. + static let tapeBodyW: CGFloat = 33.0 + static var tapeBodyH: CGFloat { whiteH } + static let tapeBodyGap: CGFloat = 6.0 + /// Horizontal pad before the tape — keeps the cassette flush with + /// the menubar's leading edge of the status item. + static let tapeLeadPad: CGFloat = 0.5 + + // ── Deck panel (transport buttons only — cassette is mounted to + // the LEFT of the deck on visible drive spokes that stick out of + // the deck's left edge, like a portable cassette mechanism where + // the transport face is one slab and the tape rides on spindles). + static let deckPadInsetX: CGFloat = 2.5 + /// Visible run of the drive spokes between cassette and deck face. + static let deckSpokesWidth: CGFloat = 6.0 + /// Horizontal pad between the deck's trailing edge and the piano. + static let deckTrailGap: CGFloat = 4.0 + + // Transport buttons — tall narrow columns running the full deck + // height. Square corners, separated by hairline gaps so the row + // reads as a stack of piano-key levers, not pill chiclets. + static let transportBtnW: CGFloat = 17.0 + static let transportBtnGap: CGFloat = 1.6 + /// Vertical inset between deck face edge and column top/bottom. + static let transportColumnInset: CGFloat = 1.6 + static let transportButtonCount: Int = 6 + + static var transportStripWidth: CGFloat { + CGFloat(transportButtonCount) * transportBtnW + + CGFloat(transportButtonCount - 1) * transportBtnGap + } + + /// Width of the deck panel itself (transport buttons + padding). + /// Cassette no longer lives inside the deck — it hangs off the + /// deck's left side on visible drive spokes. + static var deckPanelWidth: CGFloat { + deckPadInsetX + transportStripWidth + deckPadInsetX + } + + /// Total footprint added to the status-item width — cassette, + /// drive spokes, deck panel, and trailing pad before the piano. + /// Returns 0 when the tape feature is disabled so the piano + + /// settings chip shift left into the freed space. + static var tapeReservedWidth: CGFloat { + guard tapeFeatureEnabled else { return 0 } + return tapeLeadPad + tapeBodyW + deckSpokesWidth + + deckPanelWidth + deckTrailGap } // Letter labels keyed by MIDI note, per layout. The renderer picks @@ -359,11 +470,52 @@ enum KeyboardIconRenderer { } static var imageSize: NSSize { - let totalW = ceil(pad + pianoWidth + settingsLeadGap + settingsW + pad + voiceBadgeRightPad) + // imageSize is always queried in tape-included context (it's + // the menubar status-item size). Compute as if the static + // flag were set, regardless of the flag's transient state. + let totalW = ceil(tapeReservedWidth + pad + pianoWidth + settingsLeadGap + settingsW + pad + voiceBadgeRightPad) let totalH = ceil(whiteH + pad * 2) return NSSize(width: totalW, height: totalH) } + /// Cassette body rect — hangs off the LEFT side of the deck on + /// visible drive spokes. Same vertical extent as the piano keys + /// so the cassette reads as the same "device height" as the deck. + static var tapeRect: NSRect { + let bodyY = (imageSize.height - tapeBodyH) / 2.0 + return NSRect(x: tapeLeadPad, + y: bodyY, + width: tapeBodyW, + height: tapeBodyH) + } + + /// Outer rect of the deck panel — the white transport face. Sits + /// to the RIGHT of the cassette, separated by `deckSpokesWidth` + /// worth of visible drive-spindle metal. Matches piano height. + static var deckRect: NSRect { + let x = tapeRect.maxX + deckSpokesWidth + return NSRect(x: x, + y: pad, + width: deckPanelWidth, + height: whiteH) + } + + /// X origin of the transport strip inside the deck face. + static var transportStripOriginX: CGFloat { + deckRect.minX + deckPadInsetX + } + + /// Rect for a single transport button by index (0 = REW … 5 = EJECT). + /// Columns span the deck's full height (minus a small inset), so + /// they read as vertical piano-key-style levers rather than caps. + static func transportButtonRect(_ index: Int) -> NSRect { + let x = transportStripOriginX + + CGFloat(index) * (transportBtnW + transportBtnGap) + let y = deckRect.minY + transportColumnInset + let h = deckRect.height - transportColumnInset * 2 + return NSRect(x: x, y: y, width: transportBtnW, height: h) + } + /// Where the VU bars actually DRAW — the original 3 staff-line /// band only, AppKit y [chip.midY - 1.5, chip.midY + 4.25] (height /// 5.75pt). Bars never grow past these bounds; this rect is also @@ -397,12 +549,25 @@ enum KeyboardIconRenderer { } static func pianoImageSize(layout: Layout) -> NSSize { + // pianoImageSize is used by callers that draw the keyboard + // WITHOUT the tape strip (the floating play palette, e.g.). + // Don't reserve tape width here. let totalW = ceil(pad + pianoWidth(layout: layout) + pad) let totalH = ceil(whiteH + pad * 2) return NSSize(width: totalW, height: totalH) } - private static var pianoOriginX: CGFloat { pad } + /// Whether the current render is including the tape strip (true + /// for the full menubar icon; false for the standalone keyboard + /// in the floating palette). Defaults to TRUE because the status + /// item is the dominant caller — hit-testing + size queries fire + /// outside any drawing closure and need the tape reservation in + /// place. Flipped to FALSE only inside the palette's drawing + /// handler (`includeSettings == false`). + private static var tapeReservedInLayout: Bool = true + private static var pianoOriginX: CGFloat { + (tapeReservedInLayout ? tapeReservedWidth : 0) + pad + } /// Settings chip's visual rect IS its hit-test rect — they're identical /// so the user gets visual feedback wherever the click lands. @@ -423,9 +588,21 @@ enum KeyboardIconRenderer { let whites = whiteList() var whiteIndex: [Int: Int] = [:] for (i, m) in whites.enumerated() { whiteIndex[m] = i } + // NSImage's drawing handler fires LAZILY — once AppKit needs + // the bitmap, not at the moment we hand the closure over. So + // any static state we'd want active "during drawing" has to be + // set INSIDE the closure, not around it. `includeSettings` + // captures into the closure; the closure flips + // `tapeReservedInLayout` to match it for the duration of the + // draw, then restores. Default static value (true) covers + // hit-testing + size queries that happen outside any + // drawing context. let size = includeSettings ? imageSize : pianoImageSize(layout: layout) let img = NSImage(size: size, flipped: false) { _ in + let savedTapeReserved = tapeReservedInLayout + tapeReservedInLayout = includeSettings + defer { tapeReservedInLayout = savedTapeReserved } // Piano. NSGraphicsContext.saveGraphicsState() @@ -436,8 +613,13 @@ enum KeyboardIconRenderer { // continuity (no whole-icon shift, no chip jiggle). // Clip first (in unmoved coords), then apply the // translation so keys slide behind the clip edges. + // Piano area starts AFTER the tape strip when the tape is + // drawn into the same image. The closure runs while + // `tapeReservedInLayout == includeSettings`, so + // `pianoOriginX` already reflects whether the tape is in + // the layout — derive the clip start from it directly. let pianoMaskWidth = ceil(pad + pianoWidth(layout: layout) + pad) - let pianoMaskRect = NSRect(x: 0, y: 0, + let pianoMaskRect = NSRect(x: pianoOriginX - pad, y: 0, width: pianoMaskWidth, height: size.height) NSBezierPath(rect: pianoMaskRect).addClip() @@ -719,6 +901,22 @@ enum KeyboardIconRenderer { } NSGraphicsContext.restoreGraphicsState() + if includeSettings && tapeFeatureEnabled { + // Deck face — transport panel on the right. + drawDeckPanel(in: deckRect) + // Drive spokes — two horizontal metal rods extending + // from the deck's left edge into the cassette's reel + // centers. Drawn before the cassette so the cassette + // body covers the inner tips of the spokes. + drawDriveSpokes(deck: deckRect, cassette: tapeRect) + // Cassette mounted on the spokes, off to the left of + // the deck. Full piano height. + drawTapeWidget(in: tapeRect, + hovered: hovered == .tape) + // Transport buttons mounted on the deck face. + drawTapeTransportStrip(hovered: hovered) + } + if includeSettings { // Settings chip — `music.note` glyph on the LEFT (click // = popover) + 3 LED visualizer bars on the RIGHT (click @@ -760,8 +958,11 @@ enum KeyboardIconRenderer { // `settingsIconRect` directly (not via this hit rect) so the // glyph stays put even though the hit zone now covers the pad. private static var settingsHitRect: NSRect { + // Tape sits at the leading edge; the settings chip hit zone + // starts AFTER the tape so the cassette stays clickable + // (REC toggle) and draggable (eject) even in `.compact`. let leftX = displayLayout == .compact - ? 0 + ? tapeReservedWidth : pianoOriginX + pianoWidth(layout: .fixedCanvas) let rightX = imageSize.width return NSRect(x: leftX, y: 0, width: rightX - leftX, height: imageSize.height) @@ -780,13 +981,38 @@ enum KeyboardIconRenderer { // claims its slice of the image. let oldRight = imageSize.width - voiceBadgeRightPad let cx = oldRight - w / 2 - pad - let cy = imageSize.height / 2 + // Nudge the chip slightly UP so the SF Symbol `music.note` + // glyph — which is visually bottom-heavy (the stem extends + // upward from a wide note head) — reads as centered in the + // menubar slot. Without this the icon sits a touch low. + let cy = imageSize.height / 2 + 1.2 return NSRect(x: cx - w / 2, y: cy - h / 2, width: w, height: h) } // MARK: - Hit testing static func hit(at point: NSPoint) -> HitResult? { + if tapeFeatureEnabled { + // Tape sits at the leading edge — checked first so the + // cassette wins over any speculative key hit math that + // might wander left of the piano origin. + if tapeRect.contains(point) { return .tape } + // Transport buttons immediately right of the cassette. + // Order matches Walkman: REW · STOP · PLAY · FFWD · REC · EJECT. + for i in 0.. 0.001 { + let tickW: CGFloat = 1.5 + let tickX = stripeRect.minX + frac * (stripeRect.width - tickW) + let tickRect = NSRect(x: tickX, y: stripeRect.minY - 0.5, + width: tickW, height: 2.0) + NSColor.white.withAlphaComponent(0.85).setFill() + NSBezierPath(rect: tickRect).fill() + } + + // Two hexagonal reels. Hub-spoke geometry reads as "tape" even + // at 16pt — circles alone look like a generic dial. + let reelAreaY = rect.minY + 1.4 + let reelAreaH = labelRect.minY - reelAreaY - 1.0 + let reelR: CGFloat = min(reelAreaH * 0.45, rect.width * 0.18) + let reelGap: CGFloat = rect.width * 0.22 + let reelCY = reelAreaY + reelAreaH / 2 + let leftCX = rect.midX - reelGap + let rightCX = rect.midX + reelGap + + // Reel rotation speed — slow turn at idle (always-on lazy + // shimmer), faster during PLAY, fastest during REC. + let angularSpeed: CGFloat + if tapeRecording { angularSpeed = 4.5 } + else if tapePlaying { angularSpeed = 3.2 } + else { angularSpeed = 0.0 } + let phase = CGFloat(tapePhase) * angularSpeed + drawTapeReel(centerX: leftCX, centerY: reelCY, + radius: reelR, rotation: phase, isDark: isDark) + drawTapeReel(centerX: rightCX, centerY: reelCY, + radius: reelR, rotation: -phase + 0.5, isDark: isDark) + + // REC dot — sits in the label card, between the reels. + // Pulses with a sine envelope while recording so the user's + // peripheral vision registers "still rolling." + if tapeRecording { + let dotR: CGFloat = 1.7 + let pulseT = 0.5 + 0.5 * sin(CGFloat(tapePhase) * 6.0) + let alpha: CGFloat = 0.7 + 0.3 * pulseT + let dotRect = NSRect(x: labelRect.midX - dotR, + y: labelRect.midY - dotR + 0.2, + width: dotR * 2, + height: dotR * 2) + NSColor(srgbRed: 235/255, green: 50/255, blue: 50/255, + alpha: alpha).setFill() + NSBezierPath(ovalIn: dotRect).fill() + } + + // Mic LED — a tiny orange dot in the upper-right corner of + // the label, lit while the hot mic is delivering frames + // (i.e. while REC is engaged AND mic access is granted). + // Walkman TPS-L2 "hotline" button orange. + if tapeMicHot { + let micR: CGFloat = 0.9 + let micRect = NSRect(x: labelRect.maxX - micR * 2 - 1.0, + y: labelRect.maxY - micR * 2 - 0.6, + width: micR * 2, + height: micR * 2) + NSColor(srgbRed: 255/255, green: 150/255, blue: 40/255, + alpha: 0.95).setFill() + NSBezierPath(ovalIn: micRect).fill() + } + + // Hover affordance — light edge so the user can tell the + // cassette is interactive without us drawing a literal + // button border. + if hovered { + NSColor.white.withAlphaComponent(0.35).setStroke() + let hp = NSBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), + xRadius: 2.2, yRadius: 2.2) + hp.lineWidth = 1.2 + hp.stroke() + } + } + + /// One reel: outer rim, hexagonal hub with 6 spokes radiating to + /// the rim. Rotation is in radians. + private static func drawTapeReel(centerX: CGFloat, centerY: CGFloat, + radius: CGFloat, rotation: CGFloat, + isDark: Bool) { + // Reel window — a black disc cut into the cassette body that + // the reel sits in. Reels themselves are slightly lighter so + // they pop forward. + let windowRect = NSRect(x: centerX - radius - 0.4, + y: centerY - radius - 0.4, + width: (radius + 0.4) * 2, + height: (radius + 0.4) * 2) + NSColor.black.withAlphaComponent(isDark ? 0.55 : 0.65).setFill() + NSBezierPath(ovalIn: windowRect).fill() + + // Reel disc — the "tape spool" with a hexagonal hub. Color + // edges toward warm tape brown so it reads as wound tape + // even at 5pt radius. + let reelRect = NSRect(x: centerX - radius, + y: centerY - radius, + width: radius * 2, + height: radius * 2) + let reelColor = NSColor(srgbRed: 70/255, green: 55/255, + blue: 45/255, alpha: 1.0) + reelColor.setFill() + NSBezierPath(ovalIn: reelRect).fill() + + // Hexagonal hub — 6 vertices around centerX/centerY, rotated + // by `rotation`. The hub itself is brighter than the spool + // edge so it reads as the plastic reel core, not part of the + // wound tape. + let hubR = radius * 0.55 + let hubPath = NSBezierPath() + for i in 0..<6 { + let theta = rotation + CGFloat(i) * (.pi / 3) + let x = centerX + cos(theta) * hubR + let y = centerY + sin(theta) * hubR + if i == 0 { hubPath.move(to: NSPoint(x: x, y: y)) } + else { hubPath.line(to: NSPoint(x: x, y: y)) } + } + hubPath.close() + NSColor(srgbRed: 200/255, green: 195/255, blue: 185/255, + alpha: 1.0).setFill() + hubPath.fill() + + // Center dot — captures the "drive spindle hole" that all + // cassettes have. Same color as the body so it visually + // recedes. + let pinR: CGFloat = max(0.45, radius * 0.12) + let pinRect = NSRect(x: centerX - pinR, y: centerY - pinR, + width: pinR * 2, height: pinR * 2) + NSColor.black.withAlphaComponent(0.85).setFill() + NSBezierPath(ovalIn: pinRect).fill() + + // One bright spoke — gives the rotation a clearer visual + // anchor than the symmetric hexagon alone provides at this + // size. Slim trapezoid from hub to rim, painted white at low + // alpha so it reads as a wound-tape highlight catching light. + let spokePath = NSBezierPath() + let spokeWidthTheta: CGFloat = 0.20 + let spokeInner = hubR * 0.95 + let spokeOuter = radius * 0.92 + let cosL = cos(rotation - spokeWidthTheta) + let sinL = sin(rotation - spokeWidthTheta) + let cosR = cos(rotation + spokeWidthTheta) + let sinR = sin(rotation + spokeWidthTheta) + spokePath.move(to: NSPoint(x: centerX + cosL * spokeInner, + y: centerY + sinL * spokeInner)) + spokePath.line(to: NSPoint(x: centerX + cosL * spokeOuter, + y: centerY + sinL * spokeOuter)) + spokePath.line(to: NSPoint(x: centerX + cosR * spokeOuter, + y: centerY + sinR * spokeOuter)) + spokePath.line(to: NSPoint(x: centerX + cosR * spokeInner, + y: centerY + sinR * spokeInner)) + spokePath.close() + NSColor.white.withAlphaComponent(0.45).setFill() + spokePath.fill() + } + private static func drawChipVisualizer(in rect: NSRect, level: CGFloat, hovered: Bool, color: NSColor, baseAlpha: CGFloat) { @@ -1233,6 +1717,356 @@ enum KeyboardIconRenderer { } } + // MARK: - Drive spokes + // + // Two horizontal metal rods extend out of the deck's left face, + // crossing the gap to the cassette and visually engaging with the + // cassette's two reel centers. Reads as the mechanical drive + // spindles of a portable deck. Drawn before the cassette so the + // rod tips disappear behind the cassette body. + private static func drawDriveSpokes(deck: NSRect, cassette: NSRect) { + guard let ctx = NSGraphicsContext.current?.cgContext else { return } + let isDark = NSApp.effectiveAppearance.bestMatch( + from: [.aqua, .darkAqua]) == .darkAqua + ctx.saveGState() + defer { ctx.restoreGState() } + + // Reel-center math mirrors `drawTapeWidget` so the spokes + // line up with the visible hubs no matter how the cassette + // resizes. + let reelGap = cassette.width * 0.22 + let reelCY = cassette.minY + cassette.height * 0.32 - 0.4 + let leftReelCY = reelCY + let rightReelCY = reelCY + let _ = leftReelCY // (reels share Y; vars kept for clarity) + _ = rightReelCY + + // Rod endpoints: start at deck's left face, end ~1pt INSIDE + // the cassette so the rod looks plugged into the hub. + let xStart = deck.minX - 0.2 + let xEnd = cassette.maxX + 1.0 + // Two rods — left rod aligns with cassette's LEFT reel, + // right rod with cassette's RIGHT reel. + let leftReelLine = cassette.midX - reelGap + let rightReelLine = cassette.midX + reelGap + _ = leftReelLine + _ = rightReelLine + + // Rod thickness ~ 1.8pt; centered on the reel Y. + let rodH: CGFloat = 1.8 + let rodRect = { (cy: CGFloat) -> NSRect in + NSRect(x: xEnd, y: cy - rodH / 2, + width: xStart - xEnd, height: rodH) + } + + // The two reels share the same Y, so a single horizontal rod + // would only need one Y. Real deck mechanisms have ONE driven + // capstan + idler. Mimic that: one chunkier upper rod + // (capstan) + one thinner lower rod (idler) to give the + // illusion of mechanical complexity. + let capstanY = reelCY + 1.4 + let idlerY = reelCY - 2.4 + + let metalHi: NSColor + let metalLo: NSColor + if isDark { + metalHi = NSColor(srgbRed: 200/255, green: 205/255, blue: 215/255, alpha: 1) + metalLo = NSColor(srgbRed: 110/255, green: 115/255, blue: 125/255, alpha: 1) + } else { + metalHi = NSColor(srgbRed: 220/255, green: 224/255, blue: 230/255, alpha: 1) + metalLo = NSColor(srgbRed: 130/255, green: 138/255, blue: 152/255, alpha: 1) + } + + for cy in [capstanY, idlerY] { + let r = rodRect(cy) + let path = NSBezierPath(roundedRect: r, + xRadius: rodH / 2, yRadius: rodH / 2) + NSGradient(colors: [metalHi, metalLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: path, angle: -90) + // Thin dark line under the rod for a touch of dimensional + // shadow against the menubar. + NSColor.black.withAlphaComponent(0.30).setStroke() + path.lineWidth = 0.4 + path.stroke() + } + } + + // MARK: - Deck panel (transport face) + // + // Bevelled pewter face that houses both the cassette window and the + // transport row. Drawn first; everything else sits on top. + private static func drawDeckPanel(in rect: NSRect) { + let isDark = NSApp.effectiveAppearance.bestMatch( + from: [.aqua, .darkAqua]) == .darkAqua + guard let ctx = NSGraphicsContext.current?.cgContext else { return } + ctx.saveGState() + defer { ctx.restoreGState() } + + // Outer face — bright porcelain white in light mode (Walkman + // WM-EX series enamel), graphite in dark mode. Very subtle + // vertical gradient so the face still reads as 3D plastic + // rather than a flat paper rectangle. + let faceHi: NSColor + let faceLo: NSColor + if isDark { + faceHi = NSColor(srgbRed: 96/255, green: 100/255, blue: 110/255, alpha: 1) + faceLo = NSColor(srgbRed: 46/255, green: 50/255, blue: 58/255, alpha: 1) + } else { + // Near-pure white with a 4% shading drop to the bottom. + faceHi = NSColor(srgbRed: 254/255, green: 254/255, blue: 254/255, alpha: 1) + faceLo = NSColor(srgbRed: 238/255, green: 240/255, blue: 244/255, alpha: 1) + } + let facePath = NSBezierPath(roundedRect: rect.insetBy(dx: 0.4, dy: 0.4), + xRadius: 2.4, yRadius: 2.4) + NSGradient(colors: [faceHi, faceLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: facePath, angle: -90) + + // Top bevel + bottom shadow — pencil-line accents that sell + // the face as a milled plate, not a sticker. Toned down in + // light mode so they don't fight the white enamel. + ctx.saveGState() + facePath.addClip() + NSColor.white.withAlphaComponent(isDark ? 0.18 : 0.55).setStroke() + let topBevel = NSBezierPath() + topBevel.move(to: NSPoint(x: rect.minX + 1.5, y: rect.maxY - 0.8)) + topBevel.line(to: NSPoint(x: rect.maxX - 1.5, y: rect.maxY - 0.8)) + topBevel.lineWidth = 0.7 + topBevel.stroke() + + NSColor.black.withAlphaComponent(isDark ? 0.45 : 0.10).setStroke() + let bottomShadow = NSBezierPath() + bottomShadow.move(to: NSPoint(x: rect.minX + 1.5, y: rect.minY + 0.9)) + bottomShadow.line(to: NSPoint(x: rect.maxX - 1.5, y: rect.minY + 0.9)) + bottomShadow.lineWidth = 0.7 + bottomShadow.stroke() + ctx.restoreGState() + + // Outer border — soft gray in light mode so the white deck has + // a defined edge against the menubar. + NSColor.black.withAlphaComponent(isDark ? 0.60 : 0.18).setStroke() + facePath.lineWidth = 0.5 + facePath.stroke() + } + + /// "Clear plastic door" over the cassette compartment — a thin + /// glossy overlay with a recessed frame, so the cassette reads as + /// sealed behind a flip-down window. Reference: the smoked-acrylic + /// door on a Walkman WM-D6C / Nakamichi Dragon's cassette well. + private static func drawCassetteDoor(over rect: NSRect) { + guard let ctx = NSGraphicsContext.current?.cgContext else { return } + ctx.saveGState() + defer { ctx.restoreGState() } + + let frame = rect.insetBy(dx: -1.0, dy: -1.0) + let framePath = NSBezierPath(roundedRect: frame, + xRadius: 2.2, yRadius: 2.2) + + // Recessed frame — dark inner ring around the cassette window. + NSColor.black.withAlphaComponent(0.55).setStroke() + framePath.lineWidth = 0.7 + framePath.stroke() + + // Inner clear pane — wider than the cassette body so the door + // visibly frames it. Translucent gradient gives the smoked-acrylic + // sheen without obscuring the reels. + let panePath = NSBezierPath(roundedRect: frame.insetBy(dx: 0.6, dy: 0.6), + xRadius: 1.6, yRadius: 1.6) + ctx.saveGState() + panePath.addClip() + + // Diagonal sheen — bright top-left → dim bottom-right. + let sheenHi = NSColor.white.withAlphaComponent(0.22) + let sheenLo = NSColor.white.withAlphaComponent(0.00) + NSGradient(colors: [sheenHi, sheenLo], + atLocations: [0.0, 0.55], + colorSpace: .sRGB)?.draw(in: panePath, angle: -55) + + // A thin highlight streak across the top quarter — that classic + // "glass catching the light" line. Stays under 0.18 alpha so + // it never obscures the cassette label below. + let streakRect = NSRect(x: frame.minX + 1.0, + y: frame.maxY - frame.height * 0.30, + width: frame.width - 2.0, + height: frame.height * 0.16) + let streakHi = NSColor.white.withAlphaComponent(0.18) + let streakLo = NSColor.white.withAlphaComponent(0.04) + NSGradient(colors: [streakHi, streakLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: NSBezierPath(rect: streakRect), + angle: -90) + ctx.restoreGState() + + // Inner highlight — bright top edge of the pane to sell the + // door as a 3D piece. + NSColor.white.withAlphaComponent(0.28).setStroke() + let topGloss = NSBezierPath() + topGloss.move(to: NSPoint(x: frame.minX + 1.2, y: frame.maxY - 0.9)) + topGloss.line(to: NSPoint(x: frame.maxX - 1.2, y: frame.maxY - 0.9)) + topGloss.lineWidth = 0.5 + topGloss.stroke() + } + + // MARK: - Tape transport strip + // + // Six skeuomorph chiclets — REW · STOP · PLAY · FFWD · REC · EJECT — + // styled after the bottom row of a Walkman / Nakamichi Dragon. Pewter + // bodies with a top highlight bevel and bottom shadow, REC tinted red, + // PLAY tinted green when engaged. Hover brightens the body; an active + // state (REC armed, PLAY rolling) draws a pressed-in inverse gradient. + private static func drawTapeTransportStrip(hovered: HitResult?) { + let isDark = NSApp.effectiveAppearance.bestMatch( + from: [.aqua, .darkAqua]) == .darkAqua + let labels: [HitResult] = [ + .tapeRew, .tapeStop, .tapePlay, .tapeFfwd, .tapeRec, .tapeEject, + ] + for (i, role) in labels.enumerated() { + let r = transportButtonRect(i) + let isHover = hovered == role + let isActive: Bool + switch role { + case .tapeRec: isActive = tapeRecording + case .tapePlay: isActive = tapePlaying + default: isActive = false + } + drawTransportButton(in: r, + role: role, + hovered: isHover, + active: isActive, + isDark: isDark) + } + } + + private static func drawTransportButton(in rect: NSRect, + role: HitResult, + hovered: Bool, + active: Bool, + isDark: Bool) { + // Flat column — no body fill, no gradient. The deck face shows + // straight through; only the glyph differentiates the column. + // A hairline separator on the right edge keeps adjacent columns + // visually distinct without forcing a chiclet silhouette. + + // Hover wash — gentle film so the user can tell which column + // their cursor is over without painting in a hard hover box. + // White film in dark mode, soft gray in light mode (so it + // actually reads against the white deck). + if hovered { + if isDark { + NSColor.white.withAlphaComponent(0.14).setFill() + } else { + NSColor.black.withAlphaComponent(0.08).setFill() + } + NSBezierPath(rect: rect).fill() + } + + // Symbol color follows function — classic cassette-deck legend. + let glyphColor = transportGlyphColor(for: role, active: active, isDark: isDark) + drawTransportGlyph(in: rect, role: role, color: glyphColor) + } + + /// Glyph color per transport role. Classic legend: REW/FFWD amber, + /// STOP white/charcoal, PLAY green, REC red, EJECT orange. + private static func transportGlyphColor(for role: HitResult, + active: Bool, + isDark: Bool) -> NSColor { + switch role { + case .tapeRew, .tapeFfwd: + // Amber — Walkman tape-direction LEDs. + return NSColor(srgbRed: 255/255, green: 190/255, blue: 70/255, alpha: 1) + case .tapeStop: + return isDark + ? NSColor.white.withAlphaComponent(0.92) + : NSColor(white: 0.10, alpha: 1.0) + case .tapePlay: + // Green — bright enough to glow when engaged, slightly + // dimmer at rest so the deck doesn't look "running" all + // the time. + return active + ? NSColor(srgbRed: 90/255, green: 220/255, blue: 90/255, alpha: 1) + : NSColor(srgbRed: 70/255, green: 180/255, blue: 80/255, alpha: 1) + case .tapeRec: + // Saturated red; brightens when armed. + return active + ? NSColor(srgbRed: 255/255, green: 60/255, blue: 60/255, alpha: 1) + : NSColor(srgbRed: 220/255, green: 50/255, blue: 50/255, alpha: 1) + case .tapeEject: + // Warm orange — same family as the cassette's mic-hot LED. + return NSColor(srgbRed: 255/255, green: 145/255, blue: 35/255, alpha: 1) + default: + return isDark ? .white : NSColor(white: 0.10, alpha: 1.0) + } + } + + /// Hand-drawn vector glyphs sized for the wider full-height + /// column buttons (≈ 17×17pt). Color-coded, centered in the rect. + private static func drawTransportGlyph(in rect: NSRect, + role: HitResult, + color: NSColor) { + color.setFill() + color.setStroke() + let cx = rect.midX + let cy = rect.midY + let s: CGFloat = 3.6 // half-glyph short axis + let t: CGFloat = 4.6 // half-glyph long axis + switch role { + case .tapeRew: + // Two left-pointing triangles, side by side. + let g = NSBezierPath() + let dx: CGFloat = 3.6 + for k in 0...1 { + let ox = cx - dx * 0.5 + CGFloat(k) * dx + g.move(to: NSPoint(x: ox + s * 0.6, y: cy + t * 0.85)) + g.line(to: NSPoint(x: ox - s * 0.6, y: cy)) + g.line(to: NSPoint(x: ox + s * 0.6, y: cy - t * 0.85)) + g.close() + } + g.fill() + case .tapeStop: + let side: CGFloat = 6.4 + let r = NSRect(x: cx - side / 2, y: cy - side / 2, + width: side, height: side) + NSBezierPath(rect: r).fill() + case .tapePlay: + let g = NSBezierPath() + g.move(to: NSPoint(x: cx - s, y: cy + t)) + g.line(to: NSPoint(x: cx + s + 0.8, y: cy)) + g.line(to: NSPoint(x: cx - s, y: cy - t)) + g.close() + g.fill() + case .tapeFfwd: + let g = NSBezierPath() + let dx: CGFloat = 3.6 + for k in 0...1 { + let ox = cx - dx * 0.5 + CGFloat(k) * dx + g.move(to: NSPoint(x: ox - s * 0.6, y: cy + t * 0.85)) + g.line(to: NSPoint(x: ox + s * 0.6, y: cy)) + g.line(to: NSPoint(x: ox - s * 0.6, y: cy - t * 0.85)) + g.close() + } + g.fill() + case .tapeRec: + let diam: CGFloat = 7.2 + let r = NSRect(x: cx - diam / 2, y: cy - diam / 2, + width: diam, height: diam) + NSBezierPath(ovalIn: r).fill() + case .tapeEject: + // Up triangle over a thin bar. + let g = NSBezierPath() + g.move(to: NSPoint(x: cx - s, y: cy - t * 0.2)) + g.line(to: NSPoint(x: cx + s, y: cy - t * 0.2)) + g.line(to: NSPoint(x: cx, y: cy + t * 0.95)) + g.close() + g.fill() + let bar = NSRect(x: cx - s, y: cy - t * 0.9, + width: s * 2, height: 1.8) + NSBezierPath(rect: bar).fill() + default: + break + } + } + private static func drawSettingsChip(in _: NSRect, hoverRect _: NSRect, midiOn: Bool, hovered: Bool, flash: CGFloat = 0, diff --git a/slab/menuband/Sources/MenuBand/MenuBandController.swift b/slab/menuband/Sources/MenuBand/MenuBandController.swift index 621559c0ae..e1be73533a 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandController.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandController.swift @@ -5,6 +5,12 @@ import CoreGraphics final class MenuBandController { private let midi = MenuBandMIDI() private let synth = MenuBandSynth() + /// 90-second tape that captures synth output + mic together. Wired + /// up in `bootstrap` after `synth.start()` so the player node has + /// a running engine to attach to. + let tape = MenuBandTape() + private let tapeMicPinReason = "tape-record" + private let tapeWaveformPinReason = "tape" private var keyTap: KeyEventTap? private var heldNotes: [UInt16: UInt8] = [:] /// Synth channel each held keystroke is voicing on. Mirrors @@ -782,6 +788,86 @@ final class MenuBandController { } + // MARK: - Tape transport + // + // Thin facade over `MenuBandTape` that adds two pieces of glue the + // tape itself doesn't know about: + // + // • Hot-mic pinning — REC must keep the input tap delivering + // frames even when the sample-voice backtick gate is closed. + // • Waveform-tap pinning — REC + PLAY must keep the synth's + // mainMixer tap installed so output flows into `ingestSynth`. + // + // Pin reasons are released in `handleTapeChange()` when the tape + // transitions back to `.idle`. + + /// Toggle the tape between IDLE and RECORDING. On first-ever REC + /// press, surface the macOS mic permission prompt; the recording + /// is started for real once the user grants access. + func toggleTapeRecording() { + if tape.state == .recording { + tape.stop() + return + } + let auth = MenuBandSampleVoice.micAuthorizationStatus() + switch auth { + case .authorized: + beginTapeRecording() + case .notDetermined: + MenuBandSampleVoice.requestMicAccess { [weak self] granted in + guard granted else { return } + self?.beginTapeRecording() + } + case .denied, .restricted: + // No mic available — record synth output only. The mic + // indicator on the inline widget will read as "off". + beginTapeRecording() + @unknown default: + beginTapeRecording() + } + } + + private func beginTapeRecording() { + // Pin both the hot mic and the synth waveform tap before we + // flip the tape state, so the first audio block after REC + // already lands in the buffer. + synth.addWaveformTapPin(tapeWaveformPinReason) + synth.pinHotMic(reason: tapeMicPinReason) + tape.record() + } + + func stopTape() { tape.stop() } + func playTape() { + // Need the waveform tap pinned during playback so the live + // visualizer in the popover shows tape output — the player + // node feeds into the same mixer the tap reads from. (Cheap + // to pin redundantly; reasons set is set-typed.) + synth.addWaveformTapPin(tapeWaveformPinReason) + tape.play() + } + func pauseTape() { tape.pause() } + func rewindTape() { tape.rewind() } + func tapeSeekToEnd() { tape.seekToEnd() } + func clearTape() { tape.clear() } + + /// Drag-out path. Returns the on-disk 4-channel `.wav` URL for + /// the current recording (synth L/R on channels 1-2, mic on + /// channels 3-4) with the cassette cover-art icon applied. + /// AppDelegate's status-button drag source rides this URL on the + /// pasteboard so dropping the cassette onto the Desktop yields a + /// single multi-track WAV that DAWs can split into stems. + func ejectTape() -> URL? { tape.eject()?.file } + + /// State-change observer. Drops the pins whenever the tape goes + /// back to idle so the synth engine can suspend on inactivity. + private func handleTapeChange() { + if tape.state == .idle { + synth.unpinHotMic(reason: tapeMicPinReason) + synth.removeWaveformTapPin(tapeWaveformPinReason) + } + onChange?() + } + func bootstrap() { // Built-in synth is always live. TYPE mode and MIDI mode are now // independent toggles: TYPE controls global keyboard capture + key @@ -798,6 +884,28 @@ final class MenuBandController { } synth.start() synth.setMelodicProgram(melodicProgram) + // Tape wiring: attach the player to the synth's pre-limiter + // sum bus, fork the existing audio taps into the tape's + // ingestion methods, and listen for state changes so we can + // unpin the hot mic / waveform tap when REC ends. + synth.attachTape(tape) + synth.onWaveformBuffer = { [weak self] buffer in + self?.tape.ingestSynth(buffer) + } + synth.onMicInputBuffer = { [weak self] buffer in + self?.tape.ingestMic(buffer) + } + // Block-based observer so the controller (a plain Swift class, + // not NSObject) can register without inheriting from + // NSObject. Token-less because the controller lives for the + // app's full duration. + NotificationCenter.default.addObserver( + forName: .menuBandTapeChanged, + object: tape, + queue: .main + ) { [weak self] _ in + self?.handleTapeChange() + } // Restore the user's last master-volume setting before any notes // sound. Default of 1.0 means a fresh install plays at full // volume (matches previous behaviour); explicit lower picks diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index 0ec7f3fe5d..ab57c7b89d 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -194,6 +194,9 @@ final class MenuBandPopoverViewController: NSViewController { /// vertical popover space to a full visualizer block. private var miniWaveformView: WaveformView! private var miniWaveformBezel: HoverTrackingView! + // Tape transport moved to the menubar status item — see + // `KeyboardIconRenderer.drawTapeTransportStrip`. The popover no + // longer hosts a deck panel. deinit { if let monitor = focusShortcutRecorderMonitor { @@ -775,6 +778,7 @@ final class MenuBandPopoverViewController: NSViewController { stack.addArrangedSubview(miniWaveformBezel) miniWaveformBezel.widthAnchor.constraint(equalToConstant: InstrumentListView.preferredWidth).isActive = true miniWaveformBezel.heightAnchor.constraint(equalToConstant: 56).isActive = true + // Pill container is allocated but unused (kept so any // legacy refresh path doesn't crash); not added to the // bezel. diff --git a/slab/menuband/Sources/MenuBand/MenuBandSampleVoice.swift b/slab/menuband/Sources/MenuBand/MenuBandSampleVoice.swift index 759c1367ad..c11f381181 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandSampleVoice.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandSampleVoice.swift @@ -80,6 +80,14 @@ final class MenuBandSampleVoice { /// RMS [0, 1]. Wired up from `MenuBandSynth` so the menubar VU /// bars can pulse with the user's voice while recording. var onLevel: ((Float) -> Void)? + /// Live callback fired once per input-tap block with the raw mic + /// buffer (whatever format the input device delivers). The tape + /// recorder subscribes here so it can capture mic frames without + /// installing a second tap on `inputNode` (AVAudioEngine allows + /// only one tap per bus). Always called when the hot mic is + /// running, regardless of whether `recording` is true — the tape + /// has its own gate. + var onInputBuffer: ((AVAudioPCMBuffer) -> Void)? /// Public read of the recording flag — `MenuBandSynth` proxies /// this out to the controller / AppDelegate so the menubar icon @@ -109,6 +117,11 @@ final class MenuBandSampleVoice { private let recordEngine = AVAudioEngine() private var inputTapInstalled = false private var hotMicStopWork: DispatchWorkItem? + /// External callers (the tape recorder) pin the hot mic on while + /// they're recording so the input tap keeps delivering frames + /// regardless of whether the sample-voice backtick gate is open. + /// `scheduleHotMicStop` is a no-op while any pin is held. + private var hotMicPinReasons: Set = [] // Mic stays hot for 30 s after the last record so the // *second* and subsequent record key presses get zero start // latency. Lifted from 3 s — a typical record/audition/record @@ -369,7 +382,11 @@ final class MenuBandSampleVoice { private func scheduleHotMicStop() { hotMicStopWork?.cancel() let work = DispatchWorkItem { [weak self] in - guard let self = self, !self.recording else { return } + guard let self = self else { return } + // Skip the idle-off if either the sample-voice is still + // recording OR an external consumer (tape) has pinned the + // mic on. Both paths need a continuous input stream. + if self.recording || !self.hotMicPinReasons.isEmpty { return } if self.inputTapInstalled { self.recordEngine.inputNode.removeTap(onBus: 0) self.inputTapInstalled = false @@ -384,6 +401,56 @@ final class MenuBandSampleVoice { execute: work) } + /// Pin the hot mic on for a reason. The tape uses this so its + /// REC path always has frames, independent of the backtick-held + /// sample-voice capture. Idempotent. Pair with `removeHotMicPin`. + /// Returns true if the mic is now running and delivering frames. + @discardableResult + func addHotMicPin(_ reason: String) -> Bool { + let wasEmpty = hotMicPinReasons.isEmpty && !recording + hotMicPinReasons.insert(reason) + hotMicStopWork?.cancel() + hotMicStopWork = nil + // Same mic-permission gating as `startRecording` — without + // this, the input tap's `inputNode.inputFormat(forBus:)` can + // return a zero-channel format on first launch and the + // recording silently fails. We don't trigger the prompt here + // (the tape REC path is the user-facing trigger that should + // surface permission UI); if not yet authorized, just bail. + let auth = AVCaptureDevice.authorizationStatus(for: .audio) + guard auth == .authorized else { + NSLog("MenuBand SampleVoice: hot mic pin '\(reason)' deferred — auth=\(auth.rawValue)") + return false + } + if wasEmpty { + return ensureHotMicRunning() + } + return inputTapInstalled && recordEngine.isRunning + } + + func removeHotMicPin(_ reason: String) { + hotMicPinReasons.remove(reason) + if hotMicPinReasons.isEmpty && !recording { + scheduleHotMicStop() + } + } + + /// Direct read of mic authorization so the tape can mirror the + /// permission-prompt path without each call site re-implementing + /// the TCC check. + static func micAuthorizationStatus() -> AVAuthorizationStatus { + AVCaptureDevice.authorizationStatus(for: .audio) + } + + /// Request mic permission. The TCC prompt only fires the first + /// time; subsequent calls re-deliver the cached status. Used by + /// the tape's REC path on first record press. + static func requestMicAccess(_ completion: @escaping (Bool) -> Void) { + AVCaptureDevice.requestAccess(for: .audio) { granted in + DispatchQueue.main.async { completion(granted) } + } + } + /// Stop capture and promote scratch to the active recording. /// Returns true iff at least 100 ms of usable samples were captured. /// On false, the synth should not switch to the sample backend — @@ -534,6 +601,13 @@ final class MenuBandSampleVoice { /// real ceiling). Also computes per-block RMS and forwards to /// `onLevel` for the menubar VU meter. private func ingestInput(_ buffer: AVAudioPCMBuffer) { + // Fork to the tape (or any other mic consumer) BEFORE the + // sample-voice recording gate — the tape's REC is independent + // of the sample-voice backtick capture, so it needs frames + // any time the hot mic is running. + if let extra = onInputBuffer { + extra(buffer) + } guard recording else { return } // Fast path for the common macOS case: built-in/default mics diff --git a/slab/menuband/Sources/MenuBand/MenuBandSynth.swift b/slab/menuband/Sources/MenuBand/MenuBandSynth.swift index 282540382b..94c52834ef 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandSynth.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandSynth.swift @@ -119,12 +119,51 @@ final class MenuBandSynth { var supportsInstantProgramChange: Bool { midiSynthReady } private var currentMelodicProgram: UInt8 = 0 + /// Attach an external `MenuBandTape` to this synth's audio graph. + /// Connects the tape's `playerNode` to `preLimiterMixer` so tape + /// playback shares the same limiter + master volume + waveform + /// tap as the live synth. Called once from the controller after + /// `start()`. + func attachTape(_ tape: MenuBandTape) { + tape.attach(to: engine, output: preLimiterMixer) + } + + /// Pin the hot mic running for a named reason (the tape uses + /// "tape-record" while REC is engaged). Forwards to the sample + /// voice's pin mechanism. Returns true if the mic stream is now + /// flowing. + @discardableResult + func pinHotMic(reason: String) -> Bool { + sampleVoice.addHotMicPin(reason) + } + func unpinHotMic(reason: String) { + sampleVoice.removeHotMicPin(reason) + } + // Tap-driven ring buffer for the popover's live waveform display. private static let waveformRingSize = 4096 private var waveformRing = [Float](repeating: 0, count: waveformRingSize) private var waveformWriteIdx: Int = 0 private let waveformLock = NSLock() private var waveformTapInstalled = false + /// Additional consumers of the mainMixer tap buffer. AVAudioEngine + /// only allows one tap per bus, so anyone else who wants the + /// realtime synth output (the tape recorder) subscribes here and + /// gets buffers forwarded synchronously from the audio thread. + var onWaveformBuffer: ((AVAudioPCMBuffer) -> Void)? + /// Bridge for the tape recorder: forward to the sample-voice's + /// mic-tap fork. Controller sets this on init so the tape can + /// subscribe without the synth importing `MenuBandTape`. + var onMicInputBuffer: ((AVAudioPCMBuffer) -> Void)? { + get { sampleVoice.onInputBuffer } + set { sampleVoice.onInputBuffer = newValue } + } + /// External callers (the tape recorder) can pin the waveform tap + /// on independently of `setWaveformCaptureEnabled`. The tap stays + /// installed as long as EITHER the visualizer or the tape needs + /// it. Tracked separately so toggling one off doesn't kill the + /// other. + private var waveformTapPinReasons: Set = [] /// Apple's DLS bank — present on every macOS install since 10.x. private static let bankURL = URL( @@ -235,13 +274,34 @@ final class MenuBandSynth { engine.attach(avUnit) connectMIDISynthIfNeeded(avUnit) - // 3. Load just the programs we need. MIDISynth requires - // EnablePreload(true) → PC → EnablePreload(false) to actually - // fault each program's samples in from the DLS bank; without - // that, the bank URL is set but no instruments load and noteOn - // is silent. The earlier full 128-program sweep used the same - // mechanism but at startup cost; we now load programs lazily on - // first use via setMelodicProgram. + // 3. Preload every GM program (and the drum kit) while the engine + // is paused. MIDISynth's EnablePreload→PC→disable dance only + // actually faults samples in when the PC events are processed + // during the preload-enabled window. With the engine running, + // MusicDeviceMIDIEvent gets queued for the next render cycle + // and the preload-disable on the main thread can land before + // that render runs — programs would silently fail to load and + // noteOn would play MIDISynth's default sine fallback instead + // of the chosen instrument. Pausing the engine around the + // preload turns the PC handling synchronous on the main + // thread and matches the original (pre-engine-start) sweep + // that worked. Cost: a ~few-hundred-ms gap in sampler audio + // once per launch; afterwards every program switch is an + // instant PC with no further loading. + let engineWasRunning = engine.isRunning + if engineWasRunning { engine.pause() } + preloadAllMelodicPrograms(au) + preloadDrumKit(au) + if engineWasRunning { + do { try engine.start() } catch { + NSLog("MenuBand: engine restart after MIDISynth preload failed: \(error)") + } + } + + // After preload-disable the AU's *active* program on each channel + // is unset — send a fresh bank-select + PC so the very first + // noteOn lands on the user's chosen voice (and the drum kit on + // channel 9) without an extra audible swap. selectMelodicProgram(au, program: currentMelodicProgram) selectDrumKit(au) @@ -377,61 +437,72 @@ final class MenuBandSynth { (UInt16(channel) << 8) | UInt16(midi) } - /// Set of (bankMSB << 8 | program) keys we've already faulted in. The - /// EnablePreload dance only needs to run once per (bank, program) — once - /// loaded, subsequent program changes to the same slot are instant. - private var loadedPrograms: Set = [] - - /// Select a melodic program on channel 0. First time a (bank, program) - /// is touched we wrap the bank-select + PC in EnablePreload so MIDISynth - /// actually faults the instrument's samples in from the DLS bank. - /// Subsequent calls for an already-loaded program skip the preload - /// toggle and just send the bank-select + PC for instant switching. - /// CC0 = bank MSB (0x79 GM Melodic), CC32 = bank LSB (0). - private func selectMelodicProgram(_ au: AudioUnit, program: UInt8) { - let key: UInt16 = (UInt16(0x79) << 8) | UInt16(program) - let needsLoad = !loadedPrograms.contains(key) - if needsLoad { setMIDISynthPreload(au, enable: true) } - // Broadcast bank+PC to all 8 melodic channels (0-7). The - // controller's round-robin voice allocator (live 0-3, doppler - // 4-7) needs every channel preloaded with the chosen voice so - // a noteOn lands on the user's instrument no matter which - // channel it picked. Channel 9 is reserved for drums; 8 and - // 10-15 are unused. Without this loop only ch0 played the - // selected voice, which collapsed all "rotation" back to a - // single channel and let same-note retriggers cut each other. + /// Fault in every GM melodic program (0-127) on the GM Melodic bank + /// (MSB 0x79). Must be called with the audio engine paused — the + /// preload protocol relies on MusicDeviceMIDIEvent's PC messages + /// being processed synchronously while EnablePreload is true, and + /// a running engine queues them for the render thread instead. + private func preloadAllMelodicPrograms(_ au: AudioUnit) { + setMIDISynthPreload(au, enable: true) + // Bank select once per channel (the MSB+LSB pair sticks until + // overridden), then issue a PC for every program. We preload on + // channels 0-7 to match the controller's voice allocator + // (live 0-3, doppler 4-7); channel 9 is drums, 8 and 10-15 are + // unused so we skip them. for ch: UInt8 in 0..<8 { sendMIDIEvent(au, status: 0xB0 | ch, data1: 0, data2: 0x79) sendMIDIEvent(au, status: 0xB0 | ch, data1: 32, data2: 0x00) - sendMIDIEvent(au, status: 0xC0 | ch, data1: program) } - if needsLoad { - setMIDISynthPreload(au, enable: false) - loadedPrograms.insert(key) - // After preload-disable the AU's *active* program is still - // unset on each channel — re-send PC so noteOn lands on the - // freshly loaded instrument instead of silence. + for program: UInt8 in 0...127 { for ch: UInt8 in 0..<8 { sendMIDIEvent(au, status: 0xC0 | ch, data1: program) } + loadedPrograms.insert((UInt16(0x79) << 8) | UInt16(program)) } + setMIDISynthPreload(au, enable: false) } - /// Select the standard GM drum kit on channel 9 (bank MSB 0x78). - private func selectDrumKit(_ au: AudioUnit) { - let key: UInt16 = (UInt16(0x78) << 8) | 0 - let needsLoad = !loadedPrograms.contains(key) - if needsLoad { setMIDISynthPreload(au, enable: true) } - sendMIDIEvent(au, status: 0xB9, data1: 0, data2: 0x78) // CC0 bank MSB - sendMIDIEvent(au, status: 0xB9, data1: 32, data2: 0x00) // CC32 bank LSB - sendMIDIEvent(au, status: 0xC9, data1: 0) // PC kit 0 - if needsLoad { - setMIDISynthPreload(au, enable: false) - loadedPrograms.insert(key) - sendMIDIEvent(au, status: 0xC9, data1: 0) + /// Fault in the standard GM drum kit on channel 9 (bank MSB 0x78). + /// Same preload-with-engine-paused requirement as the melodic sweep. + private func preloadDrumKit(_ au: AudioUnit) { + setMIDISynthPreload(au, enable: true) + sendMIDIEvent(au, status: 0xB9, data1: 0, data2: 0x78) + sendMIDIEvent(au, status: 0xB9, data1: 32, data2: 0x00) + sendMIDIEvent(au, status: 0xC9, data1: 0) + setMIDISynthPreload(au, enable: false) + loadedPrograms.insert((UInt16(0x78) << 8) | 0) + } + + /// Set of (bankMSB << 8 | program) keys faulted in by the startup + /// preload sweep. Retained so the `selectMelodicProgram` / + /// `selectDrumKit` callers can assert their program landed in the + /// preload set, and so an unexpected slot (e.g. a future + /// non-GM bank) can re-enter a one-shot preload if needed. + private var loadedPrograms: Set = [] + + /// Switch the active melodic program on the broadcast channels. + /// With the startup preload sweep every GM program is already + /// resident in the AU, so this is just a bank-select + PC pair — + /// sub-millisecond, no disk I/O, no DSP rebuild. The 8-channel + /// broadcast matches the controller's round-robin voice allocator + /// (live 0-3, doppler 4-7) so a noteOn lands on the user's + /// instrument no matter which channel it picked. + private func selectMelodicProgram(_ au: AudioUnit, program: UInt8) { + for ch: UInt8 in 0..<8 { + sendMIDIEvent(au, status: 0xB0 | ch, data1: 0, data2: 0x79) + sendMIDIEvent(au, status: 0xB0 | ch, data1: 32, data2: 0x00) + sendMIDIEvent(au, status: 0xC0 | ch, data1: program) } } + /// Switch channel 9 back to the standard GM drum kit. The kit is + /// preloaded once at startup so this is a bank-select + PC pair. + private func selectDrumKit(_ au: AudioUnit) { + sendMIDIEvent(au, status: 0xB9, data1: 0, data2: 0x78) + sendMIDIEvent(au, status: 0xB9, data1: 32, data2: 0x00) + sendMIDIEvent(au, status: 0xC9, data1: 0) + } + private func setMIDISynthPreload(_ au: AudioUnit, enable: Bool) { var flag: UInt32 = enable ? 1 : 0 let status = AudioUnitSetProperty( @@ -652,7 +723,30 @@ final class MenuBandSynth { return } installWaveformTapIfNeeded() - } else { + } else if waveformTapPinReasons.isEmpty { + removeWaveformTapIfNeeded() + scheduleIdleSuspendIfNeeded() + } + } + + /// Pin the mainMixer tap on for a reason (currently: the tape + /// recorder needs the synth output stream while RECORDING or + /// PLAYING). Idempotent. Pair with `removeWaveformTapPin` so the + /// tap goes away once both the visualizer AND every pin reason + /// have released it. + func addWaveformTapPin(_ reason: String) { + guard started else { return } + let wasEmpty = waveformTapPinReasons.isEmpty + waveformTapPinReasons.insert(reason) + if wasEmpty { + _ = resumeAudioEngineIfNeeded() + installWaveformTapIfNeeded() + } + } + + func removeWaveformTapPin(_ reason: String) { + waveformTapPinReasons.remove(reason) + if waveformTapPinReasons.isEmpty && !waveformCaptureEnabled { removeWaveformTapIfNeeded() scheduleIdleSuspendIfNeeded() } @@ -677,6 +771,13 @@ final class MenuBandSynth { } private func ingestWaveformBuffer(_ buffer: AVAudioPCMBuffer) { + // Fork the audio thread buffer to any extra consumers (the + // tape recorder) BEFORE we lock the visualizer ring. Avoids + // delivering to consumers AFTER we've returned from this + // call — that's the whole point of the shared tap. + if let extra = onWaveformBuffer { + extra(buffer) + } guard let data = buffer.floatChannelData?[0] else { return } let frames = Int(buffer.frameLength) waveformLock.lock() diff --git a/slab/menuband/Sources/MenuBand/MenuBandTape.swift b/slab/menuband/Sources/MenuBand/MenuBandTape.swift new file mode 100644 index 0000000000..bd55d06c5d --- /dev/null +++ b/slab/menuband/Sources/MenuBand/MenuBandTape.swift @@ -0,0 +1,667 @@ +import Foundation +import AVFoundation +import AppKit + +extension Notification.Name { + /// Fired (on main) whenever tape state, position, or buffer changes + /// in a way the UI cares about. Listeners refresh the menubar icon + /// and any popover transport widgets. + static let menuBandTapeChanged = Notification.Name("MenuBandTapeChanged") + /// Fired when the user flips the tape-deck feature flag in the + /// About window. AppDelegate re-reads UserDefaults, resizes the + /// status item, and redraws the menubar icon. + static let menuBandTapeFeatureChanged = Notification.Name("MenuBandTapeFeatureChanged") +} + +/// 90-second analog-style tape with **stem separation** baked in. +/// +/// Two float buffers run in parallel — synth (stereo) and mic (mono) — +/// each fed by its own ingest path with an independent write head. +/// Playback sums them on the fly into a temporary buffer scheduled +/// through `AVAudioPlayerNode`; eject writes three AAC `.m4a` files +/// (mix / instruments / vocals) into a folder so the recording can be +/// dropped into a DAW with the vocals already split out from the +/// instruments. +/// +/// synth.mainMixerNode ── (waveform tap fork) ──► ingestSynth ──► synthBuffer +/// sampleVoice.inputNode ── (mic tap fork) ──► ingestMic ──► micBuffer +/// +/// playerNode ──► preLimiterMixer ← scheduled from sum(synth, mic) +final class MenuBandTape { + enum State: Equatable { + case idle + case recording + case paused + case playing + } + + static let sampleRate: Double = 44_100 + static let maxDurationSeconds: Double = 90.0 + static let maxFrames: Int = Int(sampleRate * maxDurationSeconds) + + // MARK: - Storage formats + + /// Stereo float32 — the synth's stems live here. + private let synthFormat: AVAudioFormat + /// Mono float32 — the mic's stem lives here. + private let micFormat: AVAudioFormat + /// Stereo float32 — playback schedules a buffer in this format + /// summed from synthBuffer + micBuffer. + private let mixFormat: AVAudioFormat + + private let synthBuffer: AVAudioPCMBuffer + private let micBuffer: AVAudioPCMBuffer + private let bufferLock = NSLock() + + private var synthWriteFrame: Int = 0 + private var micWriteFrame: Int = 0 + private var playFrame: Int = 0 + + private(set) var state: State = .idle { + didSet { if oldValue != state { postChange() } } + } + + var hasRecording: Bool { + bufferLock.lock(); defer { bufferLock.unlock() } + return max(synthWriteFrame, micWriteFrame) > 0 + } + var durationSeconds: Double { + bufferLock.lock(); defer { bufferLock.unlock() } + return Double(max(synthWriteFrame, micWriteFrame)) / Self.sampleRate + } + var positionSeconds: Double { + if state == .playing, let render = playerRenderFrame() { + return Double(playStartFrame + render) / Self.sampleRate + } + return Double(playFrame) / Self.sampleRate + } + + private var micConverter: AVAudioConverter? + private var micConverterSrcFormat: AVAudioFormat? + private var synthConverter: AVAudioConverter? + private var synthConverterSrcFormat: AVAudioFormat? + + // MARK: - Playback + + let playerNode = AVAudioPlayerNode() + private weak var engine: AVAudioEngine? + private weak var playerOutput: AVAudioNode? + private var playerAttached = false + private var playStartFrame: Int = 0 + private var playSampleTimeZero: AVAudioFramePosition = 0 + private var playerRenderArmed = false + + /// Track which date the current take began on. Used by `eject` to + /// stamp the cover art + name the file. Captured at `record()`. + private var recordStartDate: Date = Date() + + /// Cached eject result for the current take. Set on first eject, + /// reused for subsequent ejects of the same recording, cleared + /// when `record()` is called for a new take. Saves us from + /// re-encoding 90 s of audio every time the user drags the + /// cassette out OR clicks the popover EJECT button after dragging. + private var cachedEject: EjectResult? + + init() { + guard let synth = AVAudioFormat(commonFormat: .pcmFormatFloat32, + sampleRate: Self.sampleRate, + channels: 2, + interleaved: false), + let mic = AVAudioFormat(commonFormat: .pcmFormatFloat32, + sampleRate: Self.sampleRate, + channels: 1, + interleaved: false) + else { + fatalError("MenuBandTape: failed to build storage formats") + } + self.synthFormat = synth + self.micFormat = mic + self.mixFormat = synth // playback is always stereo + guard let sb = AVAudioPCMBuffer(pcmFormat: synth, + frameCapacity: AVAudioFrameCount(Self.maxFrames)), + let mb = AVAudioPCMBuffer(pcmFormat: mic, + frameCapacity: AVAudioFrameCount(Self.maxFrames)) + else { + fatalError("MenuBandTape: failed to allocate 90s stem buffers") + } + sb.frameLength = AVAudioFrameCount(Self.maxFrames) + mb.frameLength = AVAudioFrameCount(Self.maxFrames) + self.synthBuffer = sb + self.micBuffer = mb + } + + // MARK: - Engine attach + + func attach(to engine: AVAudioEngine, output: AVAudioNode) { + guard !playerAttached else { return } + self.engine = engine + self.playerOutput = output + engine.attach(playerNode) + engine.connect(playerNode, to: output, format: mixFormat) + playerAttached = true + } + + // MARK: - Transport + + func record() { + switch state { + case .recording: return + case .playing, .paused: stop() + case .idle: break + } + bufferLock.lock() + if let l = synthBuffer.floatChannelData?[0], + let r = synthBuffer.floatChannelData?[1] { + memset(l, 0, Self.maxFrames * MemoryLayout.size) + memset(r, 0, Self.maxFrames * MemoryLayout.size) + } + if let m = micBuffer.floatChannelData?[0] { + memset(m, 0, Self.maxFrames * MemoryLayout.size) + } + synthWriteFrame = 0 + micWriteFrame = 0 + playFrame = 0 + recordStartDate = Date() + cachedEject = nil + bufferLock.unlock() + state = .recording + } + + func stop() { + switch state { + case .recording: + state = .idle + postChange() + case .playing, .paused: + playerNode.stop() + playerRenderArmed = false + state = .idle + case .idle: + return + } + } + + func play() { + guard state != .playing else { return } + guard hasRecording else { return } + guard let _ = engine else { return } + let total = bufferLock.withLock { max(synthWriteFrame, micWriteFrame) } + if playFrame >= total { playFrame = 0 } + let start = playFrame + let length = total - start + guard length > 0 else { return } + guard let mixSlice = renderMixSlice(startFrame: start, frames: length) else { + return + } + playerNode.stop() + playerRenderArmed = false + playStartFrame = start + playerNode.scheduleBuffer(mixSlice, at: nil, options: []) { [weak self] in + DispatchQueue.main.async { + guard let self = self, self.state == .playing else { return } + let total = self.bufferLock.withLock { + max(self.synthWriteFrame, self.micWriteFrame) + } + self.playFrame = total + self.playerRenderArmed = false + self.state = .idle + } + } + playerNode.play() + state = .playing + } + + func pause() { + guard state == .playing else { return } + let snapshot = positionSeconds + playerNode.stop() + playerRenderArmed = false + playFrame = Int(snapshot * Self.sampleRate) + state = .paused + } + + func rewind() { + let wasPlaying = (state == .playing) + if wasPlaying { playerNode.stop(); playerRenderArmed = false } + playFrame = 0 + if wasPlaying { state = .idle; play() } + else if state == .playing { state = .idle } + else { postChange() } + } + + func seekToEnd() { + let wasPlaying = (state == .playing) + if wasPlaying { playerNode.stop(); playerRenderArmed = false; state = .idle } + playFrame = bufferLock.withLock { max(synthWriteFrame, micWriteFrame) } + postChange() + } + + func clear() { + stop() + bufferLock.lock() + synthWriteFrame = 0 + micWriteFrame = 0 + playFrame = 0 + bufferLock.unlock() + postChange() + } + + // MARK: - Eject (drag-out to Finder) + + /// Result of an eject — a single multi-channel WAV plus the date + /// + duration metadata the cover-art renderer needs. + struct EjectResult { + let file: URL + let date: Date + let duration: TimeInterval + } + + /// Render the recording into a single 4-channel WAV: + /// + /// Channel 1 — synth L + /// Channel 2 — synth R + /// Channel 3 — mic L (vocals duplicated) + /// Channel 4 — mic R (vocals duplicated) + /// + /// DAWs that handle multi-channel imports (Logic, ProTools, + /// Reaper, Ableton, Audition) offer to split the file into + /// separate tracks at import time; players that don't (QuickTime, + /// Finder preview) just play channels 1-2 — i.e. the synth — which + /// is a reasonable default. + /// + /// The mix is reconstructable from the file's channels (sum 1+3 + /// for left, 2+4 for right). We don't pre-bake a mix track here; + /// a single 4-channel WAV is the cleanest "tape" artifact. + @discardableResult + func eject() -> EjectResult? { + guard hasRecording else { return nil } + // Reuse the cached result if the on-disk file is still + // there. Same take → same file → faster drag, no duplicate + // tapes accumulating in /tmp. + if let cached = cachedEject, + FileManager.default.fileExists(atPath: cached.file.path) { + return cached + } + let frames = bufferLock.withLock { max(synthWriteFrame, micWriteFrame) } + guard frames > 0 else { return nil } + let duration = Double(frames) / Self.sampleRate + let date = recordStartDate + + // Pick a friendly filename + dodge collisions in /tmp. + let baseName = Self.makeCuteName(date: date) + let tmpRoot = FileManager.default.temporaryDirectory + var url = tmpRoot.appendingPathComponent("\(baseName).wav") + var suffix = 1 + while FileManager.default.fileExists(atPath: url.path) { + suffix += 1 + url = tmpRoot.appendingPathComponent("\(baseName)-\(suffix).wav") + } + + // 4-channel signed-16 WAV (the lingua franca for DAW import). + // 32-bit float would preserve internal headroom but some + // legacy DAW versions choke on float WAV; 16-bit is the + // safest format that every audio app on macOS can open. + guard let outFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, + sampleRate: Self.sampleRate, + channels: 4, + interleaved: true) + else { return nil } + // Float storage format for the in-memory 4-channel buffer + // we hand to the converter. Non-interleaved so we can fill + // each channel independently. + guard let quadFloat = AVAudioFormat(commonFormat: .pcmFormatFloat32, + sampleRate: Self.sampleRate, + channels: 4, + interleaved: false) + else { return nil } + + let file: AVAudioFile + do { + try? FileManager.default.removeItem(at: url) + file = try AVAudioFile(forWriting: url, + settings: outFormat.settings, + commonFormat: .pcmFormatInt16, + interleaved: true) + } catch { + NSLog("MenuBandTape: eject WAV open failed: \(error)") + return nil + } + + // Stream the recording out in 8192-frame chunks so the work + // buffer stays small. Each chunk: copy synth L/R + mic into + // a 4-channel float buffer, convert to int16, write. + guard let converter = AVAudioConverter(from: quadFloat, to: outFormat) + else { return nil } + let chunkFrames = 8192 + var cursor = 0 + while cursor < frames { + let take = min(chunkFrames, frames - cursor) + guard let src = AVAudioPCMBuffer(pcmFormat: quadFloat, + frameCapacity: AVAudioFrameCount(take)) + else { return nil } + src.frameLength = AVAudioFrameCount(take) + bufferLock.lock() + if let sl = synthBuffer.floatChannelData?[0], + let sr = synthBuffer.floatChannelData?[1], + let mc = micBuffer.floatChannelData?[0], + let d0 = src.floatChannelData?[0], + let d1 = src.floatChannelData?[1], + let d2 = src.floatChannelData?[2], + let d3 = src.floatChannelData?[3] { + memcpy(d0, sl.advanced(by: cursor), take * MemoryLayout.size) + memcpy(d1, sr.advanced(by: cursor), take * MemoryLayout.size) + // Mic is mono — duplicate into ch3 + ch4 so DAWs + // that auto-pair-stereo see a vocal stereo track. + memcpy(d2, mc.advanced(by: cursor), take * MemoryLayout.size) + memcpy(d3, mc.advanced(by: cursor), take * MemoryLayout.size) + } + bufferLock.unlock() + + guard let dst = AVAudioPCMBuffer(pcmFormat: outFormat, + frameCapacity: AVAudioFrameCount(take)) + else { return nil } + var supplied = false + var error: NSError? + let status = converter.convert(to: dst, error: &error) { _, outStatus in + if supplied { + outStatus.pointee = .endOfStream + return nil + } + supplied = true + outStatus.pointee = .haveData + return src + } + if status == .error { + NSLog("MenuBandTape: eject convert failed: \(error?.localizedDescription ?? "?")") + return nil + } + do { + try file.write(from: dst) + } catch { + NSLog("MenuBandTape: eject write failed: \(error)") + return nil + } + cursor += take + } + + // Cover art on the .wav file. Use the mix-derived waveform + // for the icon — visually represents what the user will hear + // by default when scrubbing the file. + let waveform = mixDownsampleRMS(frames: frames, buckets: 512) + let icon = TapeCoverArt.makeIcon(date: date, + duration: duration, + waveform: waveform) + NSWorkspace.shared.setIcon(icon, forFile: url.path, options: []) + + NSLog("MenuBandTape: ejected \(baseName).wav (\(duration) s, 4ch) → \(url.path)") + let result = EjectResult(file: url, date: date, duration: duration) + cachedEject = result + return result + } + + // MARK: - Ingest + + func ingestSynth(_ buffer: AVAudioPCMBuffer) { + guard state == .recording else { return } + let frames = Int(buffer.frameLength) + guard frames > 0 else { return } + let inFmt = buffer.format + if inFmt.commonFormat == .pcmFormatFloat32, + inFmt.channelCount == 2, + !inFmt.isInterleaved, + abs(inFmt.sampleRate - Self.sampleRate) < 0.5, + let inL = buffer.floatChannelData?[0], + let inR = buffer.floatChannelData?[1] { + writeSynthFrames(left: inL, right: inR, frames: frames) + return + } + if synthConverterSrcFormat != inFmt { + synthConverter = AVAudioConverter(from: inFmt, to: synthFormat) + synthConverterSrcFormat = inFmt + } + guard let conv = synthConverter, + let scratch = AVAudioPCMBuffer( + pcmFormat: synthFormat, + frameCapacity: AVAudioFrameCount( + Int(Double(frames) * (Self.sampleRate / inFmt.sampleRate)) + 16)) + else { return } + var supplied = false + var err: NSError? + let status = conv.convert(to: scratch, error: &err) { _, outStatus in + if supplied { outStatus.pointee = .endOfStream; return nil } + supplied = true; outStatus.pointee = .haveData + return buffer + } + guard status != .error, + let l = scratch.floatChannelData?[0], + let r = scratch.floatChannelData?[1] else { return } + writeSynthFrames(left: l, right: r, frames: Int(scratch.frameLength)) + } + + func ingestMic(_ buffer: AVAudioPCMBuffer) { + guard state == .recording else { return } + let frames = Int(buffer.frameLength) + guard frames > 0 else { return } + let inFmt = buffer.format + if inFmt.commonFormat == .pcmFormatFloat32, + abs(inFmt.sampleRate - Self.sampleRate) < 0.5, + !inFmt.isInterleaved, + let channelData = buffer.floatChannelData { + let ch = max(1, Int(inFmt.channelCount)) + if ch == 1 { + writeMicFrames(mono: channelData[0], frames: frames) + } else { + var mono = [Float](repeating: 0, count: frames) + let denom = Float(ch) + for i in 0.., + right: UnsafePointer, + frames: Int) { + bufferLock.lock() + let remaining = Self.maxFrames - synthWriteFrame + let take = min(frames, remaining) + if take > 0, + let dl = synthBuffer.floatChannelData?[0], + let dr = synthBuffer.floatChannelData?[1] { + let off = synthWriteFrame + memcpy(dl.advanced(by: off), left, take * MemoryLayout.size) + memcpy(dr.advanced(by: off), right, take * MemoryLayout.size) + synthWriteFrame += take + } + let bothFull = synthWriteFrame >= Self.maxFrames && micWriteFrame >= Self.maxFrames + bufferLock.unlock() + if bothFull && state == .recording { + DispatchQueue.main.async { [weak self] in + guard self?.state == .recording else { return } + self?.stop() + } + } + } + + private func writeMicFrames(mono: UnsafePointer, frames: Int) { + bufferLock.lock() + let remaining = Self.maxFrames - micWriteFrame + let take = min(frames, remaining) + if take > 0, let dst = micBuffer.floatChannelData?[0] { + memcpy(dst.advanced(by: micWriteFrame), mono, + take * MemoryLayout.size) + micWriteFrame += take + } + let bothFull = synthWriteFrame >= Self.maxFrames && micWriteFrame >= Self.maxFrames + bufferLock.unlock() + if bothFull && state == .recording { + DispatchQueue.main.async { [weak self] in + guard self?.state == .recording else { return } + self?.stop() + } + } + } + + // MARK: - Playback helpers + + private func renderMixSlice(startFrame: Int, frames: Int) -> AVAudioPCMBuffer? { + guard let slice = AVAudioPCMBuffer(pcmFormat: mixFormat, + frameCapacity: AVAudioFrameCount(frames)) + else { return nil } + slice.frameLength = AVAudioFrameCount(frames) + bufferLock.lock() + if let sl = synthBuffer.floatChannelData?[0], + let sr = synthBuffer.floatChannelData?[1], + let mc = micBuffer.floatChannelData?[0], + let ol = slice.floatChannelData?[0], + let or = slice.floatChannelData?[1] { + // Synth contributes its real L/R; mic is summed into both + // channels. Same mix the eject path bakes into mix.m4a so + // the user hears exactly what gets exported. + for i in 0.. Int? { + guard playerNode.isPlaying, + let lastRender = playerNode.lastRenderTime, + lastRender.isSampleTimeValid, + let playerTime = playerNode.playerTime(forNodeTime: lastRender) + else { return nil } + if !playerRenderArmed { + playSampleTimeZero = playerTime.sampleTime + playerRenderArmed = true + return 0 + } + let delta = Int(playerTime.sampleTime - playSampleTimeZero) + return max(0, delta) + } + + private func postChange() { + DispatchQueue.main.async { + NotificationCenter.default.post( + name: .menuBandTapeChanged, + object: self) + } + } + + // MARK: - Mix waveform for cover art + + /// Downsample the recording's mix (synth+mic) to `buckets` RMS + /// values. Drives the waveform plotted across the cassette's + /// label-card cover art. + private func mixDownsampleRMS(frames: Int, buckets: Int) -> [Float] { + guard buckets > 0, frames > 0 else { return [] } + let bucketLen = max(1, frames / buckets) + var out = [Float](repeating: 0, count: buckets) + bufferLock.lock() + defer { bufferLock.unlock() } + guard let sl = synthBuffer.floatChannelData?[0], + let sr = synthBuffer.floatChannelData?[1], + let mc = micBuffer.floatChannelData?[0] + else { return [] } + for b in 0..= end { break } + var sumSq: Float = 0 + for i in start.. String { + let cal = Calendar.current + let comps = cal.dateComponents([.hour, .minute, .second], from: date) + let seed = (comps.hour ?? 0) * 3600 + + (comps.minute ?? 0) * 60 + + (comps.second ?? 0) + let adj = Self.adjectives[seed % Self.adjectives.count] + let noun = Self.nouns[(seed / 7) % Self.nouns.count] + let monthDay = Self.monthDayFormatter.string(from: date).lowercased() + return "\(adj)-\(noun)-\(monthDay)" + } + + private static let monthDayFormatter: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "MMM-d" + return f + }() + + private static let adjectives: [String] = [ + "ruby", "cobalt", "amber", "violet", "emerald", "saffron", + "midnight", "neon", "honey", "velvet", "frost", "ember", + "lilac", "ivory", "indigo", "scarlet", "moss", "pearl", + "copper", "lemon", "rose", "azure", "ochre", "blush", + "cinder", "linen", "smoke", "candy", "jade", "peach", + "mint", "cherry", "plum", "ash", "cream", "rust", + ] + private static let nouns: [String] = [ + "clouds", "rivers", "static", "lanterns", "highways", + "kittens", "tapes", "mornings", "drifts", "echoes", + "porches", "trains", "tides", "courtyards", "sparrows", + "bridges", "marquees", "weather", "balconies", "comets", + "fireflies", "pavilions", "ferries", "windowsills", "memos", + "shadows", "carousels", "blossoms", "skylights", "pages", + "footprints", "telescopes", "bonfires", "hallways", "barges", + "sundials", "swallows", + ] +} + +// MARK: - Lock convenience + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + lock(); defer { unlock() } + return body() + } +} diff --git a/slab/menuband/Sources/MenuBand/TapeCoverArt.swift b/slab/menuband/Sources/MenuBand/TapeCoverArt.swift new file mode 100644 index 0000000000..f1c5c97583 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/TapeCoverArt.swift @@ -0,0 +1,409 @@ +import AppKit + +/// Per-tape Finder cover art. Renders a 512×512 cassette icon with the +/// recording's downsampled waveform plotted across the label card and a +/// date/duration stamp on the J-card spine — so when the user drops a +/// tape onto the Desktop, the file's icon shows what's on it rather +/// than the generic audio file glyph. +/// +/// Attached via `NSWorkspace.shared.setIcon(_:forFile:options:)` after +/// `AVAudioFile.write` completes. The icon is stored on the file's +/// resource fork (extended attribute on APFS); it travels with the +/// file across Finder copies and survives a re-import into a DAW. +enum TapeCoverArt { + static let canvasSize = CGSize(width: 512, height: 512) + + /// Build a custom Finder icon for a freshly-rendered tape. + /// + /// - Parameters: + /// - date: time of recording — colors the body palette (a + /// time-of-day tint that distinguishes morning vs evening + /// tapes at a glance in a folder full of them). + /// - duration: recorded length in seconds. Drawn on the label + /// spine; also caps the waveform render to its actual span. + /// - waveform: downsampled RMS buckets, one per horizontal pixel + /// of the label width. Empty → label stays plain. Values are + /// in 0…1 normalized to the recording's peak. + static func makeIcon(date: Date, + duration: TimeInterval, + waveform: [Float]) -> NSImage { + let img = NSImage(size: canvasSize) + img.lockFocus() + defer { img.unlockFocus() } + draw(date: date, duration: duration, waveform: waveform, + rect: NSRect(origin: .zero, size: canvasSize)) + return img + } + + private static func draw(date: Date, + duration: TimeInterval, + waveform: [Float], + rect: NSRect) { + // Clear background so the icon has transparent corners + // (rounded square + free space around the cassette). + NSColor.clear.setFill() + rect.fill() + + // Body color shifts with time of day — same palette logic the + // recap photo pipeline uses, narrowed to four bands so the + // tape labels read as "morning tape" / "afternoon tape" / + // "evening tape" / "night tape" without us having to think + // about a per-minute gradient. Inspired by the 70s AGFA bold- + // color blank cassettes in the Core77 archive. + let palette = palette(for: date) + + // Cassette body — landscape-oriented inside the 512×512 + // canvas. Generous margin so the corners can host the date + // stamp without crowding the cassette. + let bodyMargin: CGFloat = 56 + let bodyAspect: CGFloat = 11.0 / 7.0 // matches a real cassette + let maxW = rect.width - bodyMargin * 2 + var bodyW = maxW + var bodyH = bodyW / bodyAspect + if bodyH > rect.height - bodyMargin * 2 { + bodyH = rect.height - bodyMargin * 2 + bodyW = bodyH * bodyAspect + } + let bodyRect = NSRect(x: rect.midX - bodyW / 2, + y: rect.midY - bodyH / 2, + width: bodyW, + height: bodyH) + + // Drop shadow — sits the cassette above the canvas. Stops the + // icon from looking like a flat sticker against a Finder + // window background. + let shadow = NSShadow() + shadow.shadowColor = NSColor.black.withAlphaComponent(0.35) + shadow.shadowOffset = NSSize(width: 0, height: -8) + shadow.shadowBlurRadius = 22 + NSGraphicsContext.saveGraphicsState() + shadow.set() + + let bodyPath = NSBezierPath(roundedRect: bodyRect, + xRadius: 14, yRadius: 14) + NSGradient(colors: [palette.bodyHi, palette.bodyLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: bodyPath, angle: -90) + NSGraphicsContext.restoreGraphicsState() + + NSColor.white.withAlphaComponent(0.25).setStroke() + bodyPath.lineWidth = 1.5 + bodyPath.stroke() + + // Label card — across the top half of the cassette body. This + // is where the waveform goes. Real cassette J-cards used a + // cream + thin colored stripe; we match the idiom but trade + // the typography for an audio-visualization payload. + let labelInset: CGFloat = 22 + let labelH = bodyRect.height * 0.40 + let labelRect = NSRect(x: bodyRect.minX + labelInset, + y: bodyRect.maxY - labelH - 16, + width: bodyRect.width - labelInset * 2, + height: labelH) + let labelPath = NSBezierPath(roundedRect: labelRect, + xRadius: 5, yRadius: 5) + NSGradient(colors: [palette.labelHi, palette.labelLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: labelPath, angle: -90) + NSColor(srgbRed: 30/255, green: 30/255, blue: 40/255, + alpha: 0.20).setStroke() + labelPath.lineWidth = 0.8 + labelPath.stroke() + + // TDK-gold stripe — bottom edge of the label card. + let stripeColor = palette.stripe + let stripeRect = NSRect(x: labelRect.minX, + y: labelRect.minY, + width: labelRect.width, + height: 5) + stripeColor.setFill() + NSBezierPath(rect: stripeRect).fill() + + // Waveform — the actual "cover art" of this tape. RMS buckets + // plotted as vertical bars across the label card, centered on + // the label's mid-Y so it reads symmetrically (above and + // below the waveform axis), mimicking a stereo audio editor + // VU meter. + drawWaveform(in: labelRect.insetBy(dx: 12, dy: 18), + buckets: waveform, + color: palette.waveform) + + // Two big hexagonal-hub reels below the label. Same geometry + // as the inline + popover cassettes; scale gives plenty of + // detail room here. + let reelAreaY = bodyRect.minY + 20 + let reelAreaH = labelRect.minY - reelAreaY - 12 + let reelR = min(reelAreaH * 0.46, bodyRect.width * 0.13) + let reelCY = reelAreaY + reelAreaH / 2 + let leftCX = bodyRect.midX - reelR * 2.2 + let rightCX = bodyRect.midX + reelR * 2.2 + drawReel(at: NSPoint(x: leftCX, y: reelCY), + radius: reelR, + rotation: 0, + fillFraction: 0.85, + spoolColor: palette.spool) + drawReel(at: NSPoint(x: rightCX, y: reelCY), + radius: reelR, + rotation: .pi / 6, + fillFraction: 0.15, + spoolColor: palette.spool) + + // Drive holes between the reels — small white circles that + // every cassette has for the deck's pinch wheels. + let driveR: CGFloat = 5 + let driveColor = NSColor.black.withAlphaComponent(0.55) + for i in 0..<3 { + let x = bodyRect.midX + CGFloat(i - 1) * 22 + driveColor.setFill() + NSBezierPath(ovalIn: NSRect(x: x - driveR, + y: reelCY - driveR, + width: driveR * 2, + height: driveR * 2)).fill() + } + + // Date stamp on the label — small monospaced caption inside + // the label card, lower left. + drawDateAndDuration(date: date, + duration: duration, + rect: labelRect.insetBy(dx: 14, dy: 6)) + + // Wordmark — "MENU BAND" along the bottom of the cassette + // body, in tiny letters like a real cassette manufacturer + // signature. + let wordmark = "MENU BAND" + let wordmarkAttrs: [NSAttributedString.Key: Any] = [ + .font: NSFont.systemFont(ofSize: 13, weight: .heavy), + .foregroundColor: NSColor.white.withAlphaComponent(0.7), + .kern: 3.0, + ] + let wmSize = (wordmark as NSString).size(withAttributes: wordmarkAttrs) + let wmRect = NSRect(x: bodyRect.midX - wmSize.width / 2, + y: bodyRect.minY + 8, + width: wmSize.width, + height: wmSize.height) + (wordmark as NSString).draw(in: wmRect, withAttributes: wordmarkAttrs) + } + + // MARK: - Waveform plot + + private static func drawWaveform(in rect: NSRect, + buckets: [Float], + color: NSColor) { + guard !buckets.isEmpty, rect.width > 1 else { return } + + // Resample to the rect's pixel width so we get one bar per + // horizontal pixel, regardless of how many buckets came in. + let columns = Int(rect.width) + let resampled = resample(buckets, to: columns) + + // Auto-gain so quiet recordings still produce visible bars. + var peak: Float = 0.0001 + for v in resampled { peak = max(peak, abs(v)) } + let gain = min(8.0, 0.95 / peak) + + let midY = rect.midY + let halfH = rect.height / 2 + let barW: CGFloat = 1 + color.setFill() + for (i, value) in resampled.enumerated() { + let amp = CGFloat(min(1.0, value * gain)) + let h = amp * halfH + let x = rect.minX + CGFloat(i) * barW + // Symmetric VU rendering — looks like a stereo audio + // editor display, reads as "this is sound." + let bar = NSRect(x: x, y: midY - h, width: barW, height: h * 2) + NSBezierPath(rect: bar).fill() + } + + // Center line — thin axis so the waveform reads as silence + // (no bars) vs sound (bars rising symmetrically). + color.withAlphaComponent(0.35).setStroke() + let axis = NSBezierPath() + axis.move(to: NSPoint(x: rect.minX, y: midY)) + axis.line(to: NSPoint(x: rect.maxX, y: midY)) + axis.lineWidth = 0.5 + axis.stroke() + } + + private static func resample(_ buckets: [Float], to count: Int) -> [Float] { + guard count > 0 else { return [] } + if buckets.count == count { return buckets } + var out = [Float](repeating: 0, count: count) + let ratio = Double(buckets.count) / Double(count) + for i in 0.. Palette { + let cal = Calendar.current + let hour = cal.component(.hour, from: date) + switch hour { + case 6..<12: + return Palette( + bodyHi: NSColor(srgbRed: 255/255, green: 175/255, blue: 145/255, alpha: 1), + bodyLo: NSColor(srgbRed: 210/255, green: 110/255, blue: 90/255, alpha: 1), + labelHi: NSColor(srgbRed: 252/255, green: 240/255, blue: 215/255, alpha: 1), + labelLo: NSColor(srgbRed: 232/255, green: 215/255, blue: 180/255, alpha: 1), + stripe: NSColor(srgbRed: 235/255, green: 100/255, blue: 70/255, alpha: 1), + waveform: NSColor(srgbRed: 160/255, green: 60/255, blue: 40/255, alpha: 0.92), + spool: NSColor(srgbRed: 85/255, green: 50/255, blue: 40/255, alpha: 1)) + case 12..<18: + return Palette( + bodyHi: NSColor(srgbRed: 110/255, green: 135/255, blue: 175/255, alpha: 1), + bodyLo: NSColor(srgbRed: 52/255, green: 68/255, blue: 105/255, alpha: 1), + labelHi: NSColor(srgbRed: 252/255, green: 246/255, blue: 224/255, alpha: 1), + labelLo: NSColor(srgbRed: 230/255, green: 220/255, blue: 192/255, alpha: 1), + stripe: NSColor(srgbRed: 215/255, green: 175/255, blue: 70/255, alpha: 1), + waveform: NSColor(srgbRed: 40/255, green: 55/255, blue: 90/255, alpha: 0.92), + spool: NSColor(srgbRed: 70/255, green: 55/255, blue: 45/255, alpha: 1)) + case 18..<22: + return Palette( + bodyHi: NSColor(srgbRed: 235/255, green: 115/255, blue: 75/255, alpha: 1), + bodyLo: NSColor(srgbRed: 160/255, green: 50/255, blue: 60/255, alpha: 1), + labelHi: NSColor(srgbRed: 250/255, green: 235/255, blue: 200/255, alpha: 1), + labelLo: NSColor(srgbRed: 225/255, green: 200/255, blue: 165/255, alpha: 1), + stripe: NSColor(srgbRed: 240/255, green: 90/255, blue: 60/255, alpha: 1), + waveform: NSColor(srgbRed: 130/255, green: 30/255, blue: 40/255, alpha: 0.92), + spool: NSColor(srgbRed: 90/255, green: 45/255, blue: 35/255, alpha: 1)) + default: // 22..6 + return Palette( + bodyHi: NSColor(srgbRed: 78/255, green: 70/255, blue: 120/255, alpha: 1), + bodyLo: NSColor(srgbRed: 32/255, green: 28/255, blue: 60/255, alpha: 1), + labelHi: NSColor(srgbRed: 230/255, green: 220/255, blue: 235/255, alpha: 1), + labelLo: NSColor(srgbRed: 200/255, green: 190/255, blue: 215/255, alpha: 1), + stripe: NSColor(srgbRed: 175/255, green: 100/255, blue: 220/255, alpha: 1), + waveform: NSColor(srgbRed: 50/255, green: 40/255, blue: 85/255, alpha: 0.92), + spool: NSColor(srgbRed: 60/255, green: 50/255, blue: 75/255, alpha: 1)) + } + } +} diff --git a/slab/menuband/Sources/MenuBand/TapeDragSource.swift b/slab/menuband/Sources/MenuBand/TapeDragSource.swift new file mode 100644 index 0000000000..8311bfc06c --- /dev/null +++ b/slab/menuband/Sources/MenuBand/TapeDragSource.swift @@ -0,0 +1,26 @@ +import AppKit + +/// Minimal `NSDraggingSource` for the inline tape eject. The status +/// item button itself doesn't conform to `NSDraggingSource`, and adding +/// a conformance to `NSStatusBarButton` via extension would touch every +/// other drag path that lives on that button. A tiny adapter object +/// keeps the drag isolated to the tape feature. +/// +/// We allow `.copy` for external contexts (Finder, Mail, browsers) so +/// the user's recording lands on disk as a duplicate of the temp file +/// — the temp .wav stays in `/tmp` and gets reaped by macOS later, the +/// user's copy lives wherever they dropped it. +final class TapeDragSource: NSObject, NSDraggingSource { + func draggingSession(_ session: NSDraggingSession, + sourceOperationMaskFor context: NSDraggingContext) + -> NSDragOperation { + switch context { + case .outsideApplication: + return .copy + case .withinApplication: + return [] + @unknown default: + return .copy + } + } +} diff --git a/slab/menuband/Sources/MenuBand/TapeTransportView.swift b/slab/menuband/Sources/MenuBand/TapeTransportView.swift new file mode 100644 index 0000000000..0a0aac7723 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/TapeTransportView.swift @@ -0,0 +1,492 @@ +import AppKit + +/// Larger cassette deck for the popover. Mirrors the inline status-item +/// cassette but renders at a roomier size, with the full transport row +/// (REW / STOP / PLAY / FFWD / REC / EJECT) below the cassette window +/// and a 1:30 position counter on the left. +/// +/// Reference: Nakamichi Dragon's chunky beveled transport buttons + +/// Walkman TPS-L2 silver/blue body + TDK SA gold label stripe. Buttons +/// use SF Symbols with the standardized IEC 60417 glyphs (`backward.fill`, +/// `stop.fill`, `play.fill`, `forward.fill`, `record.circle.fill`, +/// `eject.fill`) so the row reads as media transport regardless of +/// locale. +final class TapeTransportView: NSView { + weak var menuBand: MenuBandController? { + didSet { + // Bring the visible state in line with whatever the + // controller is doing right now — view may be installed + // mid-recording (rare but possible if the popover opens + // while REC is engaged). + refresh() + } + } + + private let cassetteView = TapeCassetteView() + private let positionLabel = NSTextField(labelWithString: "00:00 / 01:30") + private let stateLabel = NSTextField(labelWithString: "") + + private let rewindButton = NSButton() + private let stopButton = NSButton() + private let playButton = NSButton() + private let ffwdButton = NSButton() + private let recButton = NSButton() + private let ejectButton = NSButton() + + private var observerToken: NSObjectProtocol? + /// 12fps redraw timer that fires while the tape is recording or + /// playing, so the cassette reels turn smoothly and the position + /// counter ticks without us re-publishing notifications at frame + /// rate. Invalidated when the tape returns to idle. + private var refreshTimer: Timer? + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + wantsLayer = true + layer?.backgroundColor = NSColor.clear.cgColor + setUp() + startObserving() + } + required init?(coder: NSCoder) { nil } + + deinit { + if let t = observerToken { NotificationCenter.default.removeObserver(t) } + refreshTimer?.invalidate() + } + + // MARK: - Layout + + private func setUp() { + cassetteView.translatesAutoresizingMaskIntoConstraints = false + addSubview(cassetteView) + + positionLabel.font = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .medium) + positionLabel.textColor = .secondaryLabelColor + positionLabel.translatesAutoresizingMaskIntoConstraints = false + addSubview(positionLabel) + + stateLabel.font = NSFont.systemFont(ofSize: 10, weight: .semibold) + stateLabel.textColor = .tertiaryLabelColor + stateLabel.alignment = .right + stateLabel.translatesAutoresizingMaskIntoConstraints = false + addSubview(stateLabel) + + let symbolConfig = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold) + configureTransport(button: rewindButton, + symbol: "backward.fill", + tooltip: "Rewind to start", + action: #selector(rewindClicked(_:))) + configureTransport(button: stopButton, + symbol: "stop.fill", + tooltip: "Stop", + action: #selector(stopClicked(_:))) + configureTransport(button: playButton, + symbol: "play.fill", + tooltip: "Play", + tint: NSColor(srgbRed: 90/255, green: 180/255, + blue: 90/255, alpha: 1), + action: #selector(playClicked(_:))) + configureTransport(button: ffwdButton, + symbol: "forward.fill", + tooltip: "Jump to end", + action: #selector(ffwdClicked(_:))) + configureTransport(button: recButton, + symbol: "record.circle.fill", + tooltip: "Record", + tint: NSColor(srgbRed: 220/255, green: 60/255, + blue: 60/255, alpha: 1), + action: #selector(recClicked(_:))) + configureTransport(button: ejectButton, + symbol: "eject.fill", + tooltip: "Save tape to Desktop (or drag the cassette)", + action: #selector(ejectClicked(_:))) + + // Apply the buttons + symbol config in one pass. + for button in [rewindButton, stopButton, playButton, + ffwdButton, recButton, ejectButton] { + button.image = button.image? + .withSymbolConfiguration(symbolConfig) + addSubview(button) + } + + let transportStack = NSStackView(views: [ + rewindButton, stopButton, playButton, + ffwdButton, recButton, ejectButton, + ]) + transportStack.spacing = 8 + transportStack.distribution = .fillEqually + transportStack.alignment = .centerY + transportStack.orientation = .horizontal + transportStack.translatesAutoresizingMaskIntoConstraints = false + addSubview(transportStack) + + NSLayoutConstraint.activate([ + cassetteView.topAnchor.constraint(equalTo: topAnchor, constant: 4), + cassetteView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 6), + cassetteView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -6), + cassetteView.heightAnchor.constraint(equalToConstant: 56), + + positionLabel.topAnchor.constraint(equalTo: cassetteView.bottomAnchor, constant: 4), + positionLabel.leadingAnchor.constraint(equalTo: cassetteView.leadingAnchor, constant: 2), + + stateLabel.centerYAnchor.constraint(equalTo: positionLabel.centerYAnchor), + stateLabel.trailingAnchor.constraint(equalTo: cassetteView.trailingAnchor, constant: -2), + + transportStack.topAnchor.constraint(equalTo: positionLabel.bottomAnchor, constant: 6), + transportStack.leadingAnchor.constraint(equalTo: cassetteView.leadingAnchor), + transportStack.trailingAnchor.constraint(equalTo: cassetteView.trailingAnchor), + transportStack.heightAnchor.constraint(equalToConstant: 28), + transportStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4), + ]) + } + + private func configureTransport(button: NSButton, + symbol: String, + tooltip: String, + tint: NSColor = NSColor.labelColor, + action: Selector) { + button.translatesAutoresizingMaskIntoConstraints = false + button.image = NSImage(systemSymbolName: symbol, + accessibilityDescription: tooltip) + button.bezelStyle = .recessed + button.isBordered = true + button.imagePosition = .imageOnly + button.contentTintColor = tint + button.target = self + button.action = action + button.toolTip = tooltip + } + + // MARK: - State sync + + private func startObserving() { + observerToken = NotificationCenter.default.addObserver( + forName: .menuBandTapeChanged, + object: nil, + queue: .main + ) { [weak self] _ in + self?.refresh() + } + refresh() + } + + /// Pull current state from the controller and update everything + /// the UI shows. Drives both the cassette draw and the button + /// enable states; cheap enough to call every animation tick. + func refresh() { + guard let menuBand = menuBand else { return } + let tape = menuBand.tape + cassetteView.recording = (tape.state == .recording) + cassetteView.playing = (tape.state == .playing) + cassetteView.fillFraction = CGFloat( + tape.durationSeconds / MenuBandTape.maxDurationSeconds) + cassetteView.playheadFraction = CGFloat( + tape.positionSeconds / max(0.001, tape.durationSeconds)) + cassetteView.micHot = (tape.state == .recording) && + (MenuBandSampleVoice.micAuthorizationStatus() == .authorized) + cassetteView.needsDisplay = true + + let pos = formatTime(tape.positionSeconds) + let dur = formatTime(tape.durationSeconds) + let cap = formatTime(MenuBandTape.maxDurationSeconds) + positionLabel.stringValue = "\(pos) / \(cap)" + switch tape.state { + case .recording: + stateLabel.stringValue = "● REC" + stateLabel.textColor = NSColor(srgbRed: 220/255, green: 60/255, + blue: 60/255, alpha: 1) + case .playing: + stateLabel.stringValue = "▶ PLAY" + stateLabel.textColor = NSColor(srgbRed: 70/255, green: 150/255, + blue: 70/255, alpha: 1) + case .paused: + stateLabel.stringValue = "‖ PAUSED" + stateLabel.textColor = .secondaryLabelColor + case .idle: + stateLabel.stringValue = tape.hasRecording + ? "tape: \(dur)" + : "empty tape" + stateLabel.textColor = .tertiaryLabelColor + } + + // Button enable rules — REW/STOP/PLAY/FFWD/EJECT need a + // recording; REC is always live (toggles). + let hasRec = tape.hasRecording + let isPlaying = tape.state == .playing + rewindButton.isEnabled = hasRec + stopButton.isEnabled = (tape.state != .idle) || isPlaying + playButton.isEnabled = hasRec && !isPlaying + ffwdButton.isEnabled = hasRec + ejectButton.isEnabled = hasRec + // REC button visual — tinted red, glows brighter while + // armed. Apple's `.recessed` bezel doesn't expose a "filled" + // active style, but we can flip the symbol between + // `record.circle.fill` and `largecircle.fill.circle` to make + // the toggle obvious. + recButton.image = NSImage( + systemSymbolName: tape.state == .recording + ? "largecircle.fill.circle" : "record.circle.fill", + accessibilityDescription: "Record")? + .withSymbolConfiguration(NSImage.SymbolConfiguration( + pointSize: 13, weight: .semibold)) + + // Keep the reels turning while the tape is active. The + // controller broadcasts `menuBandTapeChanged` only on state + // transitions, not at frame rate — that's where this timer + // earns its keep. + let needsTick = (tape.state == .recording || tape.state == .playing) + if needsTick && refreshTimer == nil { + let timer = Timer(timeInterval: 1.0 / 12.0, repeats: true) { + [weak self] _ in self?.refresh() + } + RunLoop.main.add(timer, forMode: .common) + refreshTimer = timer + } else if !needsTick { + refreshTimer?.invalidate() + refreshTimer = nil + } + } + + private func formatTime(_ seconds: Double) -> String { + let total = max(0, min(seconds, MenuBandTape.maxDurationSeconds)) + let m = Int(total) / 60 + let s = Int(total) % 60 + return String(format: "%02d:%02d", m, s) + } + + // MARK: - Actions + + @objc private func rewindClicked(_ sender: Any?) { menuBand?.rewindTape() } + @objc private func stopClicked(_ sender: Any?) { menuBand?.stopTape() } + @objc private func playClicked(_ sender: Any?) { menuBand?.playTape() } + @objc private func ffwdClicked(_ sender: Any?) { menuBand?.tapeSeekToEnd() } + @objc private func recClicked(_ sender: Any?) { menuBand?.toggleTapeRecording() } + @objc private func ejectClicked(_ sender: Any?) { + // Click-to-eject: write WAV then reveal in Finder. The + // drag-out gesture from the inline cassette stays the primary + // export path (no extra Finder window pop); the popover button + // is a fallback for users who don't think to drag the menubar + // cassette. + guard let url = menuBand?.ejectTape() else { return } + NSWorkspace.shared.activateFileViewerSelecting([url]) + } +} + +/// Cassette artwork for the popover. Same skeuomorph language as the +/// inline status-item drawing, but at a larger size so the label-card +/// text + reel motion is properly visible. Subclasses NSView (rather +/// than reusing `KeyboardIconRenderer.drawTapeWidget`) so we get a +/// stable target for the popover's draw cycle without coupling the +/// transport panel to the renderer's static state. +final class TapeCassetteView: NSView { + var recording = false + var playing = false + var fillFraction: CGFloat = 0 + var playheadFraction: CGFloat = 0 + var micHot = false + + private var startTime: CFTimeInterval = CACurrentMediaTime() + + override var wantsUpdateLayer: Bool { false } + override var isFlipped: Bool { false } + + override func draw(_ dirtyRect: NSRect) { + let isDark = NSApp.effectiveAppearance.bestMatch( + from: [.aqua, .darkAqua]) == .darkAqua + let rect = bounds.insetBy(dx: 1, dy: 1) + + // Body — same navy/silver gradient as the inline widget, just + // taller so the reels read clearly. + let bodyHi: NSColor + let bodyLo: NSColor + if isDark { + bodyHi = NSColor(srgbRed: 88/255, green: 98/255, blue: 112/255, alpha: 1) + bodyLo = NSColor(srgbRed: 42/255, green: 50/255, blue: 60/255, alpha: 1) + } else { + bodyHi = NSColor(srgbRed: 98/255, green: 118/255, blue: 152/255, alpha: 1) + bodyLo = NSColor(srgbRed: 52/255, green: 68/255, blue: 98/255, alpha: 1) + } + let bodyPath = NSBezierPath(roundedRect: rect, xRadius: 6, yRadius: 6) + NSGradient(colors: [bodyHi, bodyLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: bodyPath, angle: -90) + NSColor.white.withAlphaComponent(isDark ? 0.18 : 0.30).setStroke() + bodyPath.lineWidth = 0.8 + bodyPath.stroke() + + // Label card — cream stripe across the top. + let labelInset: CGFloat = 6 + let labelH = rect.height * 0.32 + let labelRect = NSRect(x: rect.minX + labelInset, + y: rect.maxY - labelH - 5, + width: rect.width - labelInset * 2, + height: labelH) + let labelHi: NSColor = isDark + ? NSColor(srgbRed: 230/255, green: 220/255, blue: 195/255, alpha: 1) + : NSColor(srgbRed: 250/255, green: 245/255, blue: 225/255, alpha: 1) + let labelLo: NSColor = isDark + ? NSColor(srgbRed: 195/255, green: 180/255, blue: 150/255, alpha: 1) + : NSColor(srgbRed: 230/255, green: 220/255, blue: 195/255, alpha: 1) + let labelPath = NSBezierPath(roundedRect: labelRect, + xRadius: 2, yRadius: 2) + NSGradient(colors: [labelHi, labelLo], + atLocations: [0.0, 1.0], + colorSpace: .sRGB)?.draw(in: labelPath, angle: -90) + + // Label text — wordmark on the cassette. "MENU BAND" in the + // small caps that real cassette labels favored, plus a thin + // gold stripe below. + let title = "MENU BAND • 90" + let attrs: [NSAttributedString.Key: Any] = [ + .font: NSFont.systemFont(ofSize: 9, weight: .heavy), + .foregroundColor: NSColor(srgbRed: 30/255, green: 30/255, + blue: 40/255, alpha: 0.85), + .kern: 1.0, + ] + let titleSize = (title as NSString).size(withAttributes: attrs) + let titleRect = NSRect(x: labelRect.midX - titleSize.width / 2, + y: labelRect.midY - titleSize.height / 2 + 1, + width: titleSize.width, + height: titleSize.height) + (title as NSString).draw(in: titleRect, withAttributes: attrs) + + // Gold stripe — color-codes the deck state (red REC, green + // PLAY, gold idle), same idiom as the inline widget so the + // two surfaces feel like one instrument. + let stripeColor: NSColor + if recording { + stripeColor = NSColor(srgbRed: 220/255, green: 60/255, blue: 60/255, alpha: 1) + } else if playing { + stripeColor = NSColor(srgbRed: 90/255, green: 180/255, blue: 90/255, alpha: 1) + } else { + stripeColor = NSColor(srgbRed: 210/255, green: 175/255, blue: 80/255, alpha: 1) + } + let stripeRect = NSRect(x: labelRect.minX, y: labelRect.minY, + width: labelRect.width, height: 2.5) + stripeColor.setFill() + NSBezierPath(rect: stripeRect).fill() + + // Progress tick across the stripe — REC fills toward the + // right; PLAY moves a discrete marker. + let frac = recording + ? min(1, max(0, fillFraction)) + : min(1, max(0, playheadFraction)) + if frac > 0.001 { + let tickW: CGFloat = 3.0 + let tickX = stripeRect.minX + frac * (stripeRect.width - tickW) + NSColor.white.withAlphaComponent(0.85).setFill() + NSBezierPath(rect: NSRect(x: tickX, y: stripeRect.minY - 1.0, + width: tickW, height: 4.5)).fill() + } + + // Reels. + let reelAreaY = rect.minY + 6 + let reelAreaH = labelRect.minY - reelAreaY - 4 + let reelR = min(reelAreaH * 0.45, 14) + let reelCY = reelAreaY + reelAreaH / 2 + let leftCX = rect.midX - reelR * 1.8 + let rightCX = rect.midX + reelR * 1.8 + + let phaseRaw = CACurrentMediaTime() - startTime + let speed: CGFloat + if recording { speed = 4.5 } + else if playing { speed = 3.2 } + else { speed = 0.0 } + let phase = CGFloat(phaseRaw) * speed + + drawReel(at: NSPoint(x: leftCX, y: reelCY), radius: reelR, + rotation: phase, isDark: isDark) + drawReel(at: NSPoint(x: rightCX, y: reelCY), radius: reelR, + rotation: -phase + 0.5, isDark: isDark) + + // Mic LED on the cassette — orange dot inside the label + // upper-right, lit while mic is hot. + if micHot { + let micR: CGFloat = 2.5 + let micRect = NSRect(x: labelRect.maxX - micR * 2 - 4, + y: labelRect.maxY - micR * 2 - 3, + width: micR * 2, height: micR * 2) + NSColor(srgbRed: 255/255, green: 150/255, blue: 40/255, + alpha: 0.95).setFill() + NSBezierPath(ovalIn: micRect).fill() + // Tiny soft halo so the LED reads as glowing, not as a + // flat dot. + NSColor(srgbRed: 255/255, green: 150/255, blue: 40/255, + alpha: 0.25).setFill() + NSBezierPath(ovalIn: micRect.insetBy(dx: -2, dy: -2)).fill() + } + + // REC LED — bigger pulsing red dot between the reels. + if recording { + let dotR: CGFloat = 4 + let pulse = 0.5 + 0.5 * sin(CGFloat(phaseRaw) * 6.0) + let alpha: CGFloat = 0.7 + 0.3 * pulse + let dotRect = NSRect(x: rect.midX - dotR, + y: reelCY - dotR, + width: dotR * 2, height: dotR * 2) + NSColor(srgbRed: 235/255, green: 50/255, blue: 50/255, + alpha: alpha).setFill() + NSBezierPath(ovalIn: dotRect).fill() + } + } + + private func drawReel(at center: NSPoint, + radius: CGFloat, + rotation: CGFloat, + isDark: Bool) { + let windowRect = NSRect(x: center.x - radius - 1, + y: center.y - radius - 1, + width: (radius + 1) * 2, + height: (radius + 1) * 2) + NSColor.black.withAlphaComponent(isDark ? 0.55 : 0.7).setFill() + NSBezierPath(ovalIn: windowRect).fill() + + let reelRect = NSRect(x: center.x - radius, + y: center.y - radius, + width: radius * 2, height: radius * 2) + NSColor(srgbRed: 70/255, green: 55/255, blue: 45/255, + alpha: 1.0).setFill() + NSBezierPath(ovalIn: reelRect).fill() + + // Hexagonal hub. + let hubR = radius * 0.55 + let hub = NSBezierPath() + for i in 0..<6 { + let theta = rotation + CGFloat(i) * (.pi / 3) + let x = center.x + cos(theta) * hubR + let y = center.y + sin(theta) * hubR + if i == 0 { hub.move(to: NSPoint(x: x, y: y)) } + else { hub.line(to: NSPoint(x: x, y: y)) } + } + hub.close() + NSColor(srgbRed: 200/255, green: 195/255, blue: 185/255, + alpha: 1.0).setFill() + hub.fill() + + // Drive-spindle hole. + let pinR: CGFloat = max(1, radius * 0.12) + let pinRect = NSRect(x: center.x - pinR, y: center.y - pinR, + width: pinR * 2, height: pinR * 2) + NSColor.black.withAlphaComponent(0.85).setFill() + NSBezierPath(ovalIn: pinRect).fill() + + // Light-catch spoke for rotation legibility. + let spoke = NSBezierPath() + let halfTheta: CGFloat = 0.18 + let inner = hubR * 0.95 + let outer = radius * 0.92 + let cL = cos(rotation - halfTheta), sL = sin(rotation - halfTheta) + let cR = cos(rotation + halfTheta), sR = sin(rotation + halfTheta) + spoke.move(to: NSPoint(x: center.x + cL * inner, + y: center.y + sL * inner)) + spoke.line(to: NSPoint(x: center.x + cL * outer, + y: center.y + sL * outer)) + spoke.line(to: NSPoint(x: center.x + cR * outer, + y: center.y + sR * outer)) + spoke.line(to: NSPoint(x: center.x + cR * inner, + y: center.y + sR * inner)) + spoke.close() + NSColor.white.withAlphaComponent(0.45).setFill() + spoke.fill() + } +} -- knotmirror 0.0.1