From ea3337fc9d810692296e87df4e391208a17a8bc4 Mon Sep 17 00:00:00 2001 From: "prompt.ac/@jeffrey" Date: Fri, 5 Jun 2026 09:32:34 -0700 Subject: [PATCH] =?UTF-8?q?menuband:=20v1=20cutoff=20=E2=80=94=20single-co?= =?UTF-8?q?lumn=20glass=20popover,=20working=20trackpad=20bend,=20double-?= =?UTF-8?q?=E2=8C=98=20as=20sole=20global=20key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v1 boundary for the Mac App Store subset. Folds the floating piano panel into a single liquid-glass popover and trims everything behind the cutoff. UI / layout: - Fold the instrument cluster (qwerty + arrows + chooser) into the popover as one column; retire the floating two-column panel. - Popover backdrop is now NSGlassEffectView on macOS 26 (legacy vibrancy fallback) with a continuous arrow+body mask; embedded cluster skips its own glass so surfaces don't double. - Recessed "ground" plate behind the qwerty map AND the arrow cluster. - Remove the volume slider, the top-right octave readout, and the REC dot. - About: drop the percussion-split, cassette-deck, and pedals controls. Pitch-bend: - Fix trackpad pitch-bend: drop the unreliable NSTouch `trackpadTouchActive` gate (it never fired through the popover's key window, so the gesture never engaged) and gate on `keyboardNotesHeld || shift`. Original mouse-hide bug stays fixed — mouse taps use the tap channels, not keyboardNotesHeld, so a plain pointer move can't bend or hide the cursor. Global keys: - The double right-⌘ tap is now the ONLY system-wide key. The ⌥ percussion taps are local-only, and the focus/exit/layout/piano-waveform/percussion RegisterEventHotKey bindings are unregistered. Layout + percussion still toggle from the local key handler while Menu Band is focused. Other: - Linger fade no longer resurrects a faded note on melodic-channel reuse. Co-Authored-By: Claude Opus 4.8 --- .../Sources/MenuBand/AboutWindow.swift | 65 +-- .../Sources/MenuBand/AppDelegate.swift | 496 +++++------------- .../MenuBand/KeyboardIconRenderer.swift | 12 +- .../Sources/MenuBand/KidLispScreen.swift | 52 +- .../Sources/MenuBand/LocalKeyCapture.swift | 9 +- .../Sources/MenuBand/MenuBandController.swift | 95 ++-- .../Sources/MenuBand/MenuBandPopover.swift | 473 +++-------------- .../MenuBand/MenuBandPopoverPanel.swift | 75 ++- .../CollapsedPianoWaveformView.swift | 51 +- .../PianoWaveformWindowDelegate.swift | 14 + 10 files changed, 383 insertions(+), 959 deletions(-) diff --git a/slab/menuband/Sources/MenuBand/AboutWindow.swift b/slab/menuband/Sources/MenuBand/AboutWindow.swift index 29efa0fa0e..fef9737e22 100644 --- a/slab/menuband/Sources/MenuBand/AboutWindow.swift +++ b/slab/menuband/Sources/MenuBand/AboutWindow.swift @@ -300,27 +300,9 @@ final class AboutWindowController: NSWindowController, NSWindowDelegate { startClubButton.widthAnchor.constraint(equalToConstant: 264).isActive = true stack.addArrangedSubview(startClubButton) - // Plugins chip — opens the AU instrument picker. Beta surface - // for testing third-party AUs (angelsaw etc.) routed through - // Menu Band's audio engine. Hidden when no host is wired up. - // Tinted with `controlAccentColor` so the chip tracks whatever - // accent the user has set in System Settings (refreshed live - // by `refreshAccentChrome`). - if onOpenPlugins != nil { - stack.setCustomSpacing(10, after: nelaButton) - let pluginsBtn = MenuBandPopoverViewController.makeLinkButton( - attr: pluginsLabel(for: NSColor.controlAccentColor), - target: self, - action: #selector(openPlugins), - background: NSColor.controlAccentColor.withAlphaComponent(0.14), - border: NSColor.controlAccentColor.withAlphaComponent(0.55) - ) - pluginsBtn.toolTip = "Beta — engage a Liam Hall pedal" - stack.addArrangedSubview(pluginsBtn) - // makeLinkButton always returns a HoverLinkButton — cast so - // we can refresh idle/hover NSColor refs on accent changes. - pluginsButton = pluginsBtn as? HoverLinkButton - } + // [v1 cutoff] Pedals (AU plugin picker) chip removed — Liam Hall + // pedals / third-party AU hosting are post-v1. The `onOpenPlugins` + // hook + AU picker code stay dormant for the post-release revival. // Language picker — same flag-chip pattern the popover used // to host. Lives in About now so the popover stays a tight @@ -331,43 +313,10 @@ 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) - - // Right-hand percussion split — the upper-octave keys play the - // AC-native drum kit while the lower keys stay melodic. Off by - // default; also toggleable live with ⌘⌃⌥D. - let percCheckbox = NSButton( - checkboxWithTitle: "Percussion split (⌘⌃⌥D)", - target: self, - action: #selector(togglePercussionSplit(_:)) - ) - percCheckbox.state = (UserDefaults.standard - .bool(forKey: KeyboardIconRenderer.percussionLeftDefaultsKey) - || UserDefaults.standard - .bool(forKey: KeyboardIconRenderer.percussionRightDefaultsKey)) - ? .on : .off - percCheckbox.font = NSFont.systemFont(ofSize: 11) - percCheckbox.toolTip = - "Both halves of the board play the drum kit (kick/snare/hats/…). " - + "Tap left-⌥ / right-⌥ to latch just one half." - percCheckbox.translatesAutoresizingMaskIntoConstraints = false - stack.addArrangedSubview(percCheckbox) + // [v1 cutoff] "Cassette deck (beta)" + "Percussion split" beta + // checkboxes removed — both features are post-v1. Their flags + // default off and their live shortcuts stay in place, so the + // toggles can return to About after release. // Crash-report summary — single orange ⚠️ button reading // "Menu Band crashed N times". Opens the scroll viewer where diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index f79942b66d..b46c8136d9 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -46,29 +46,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private var percussionToggleHotkey: GlobalHotkey? private var popoverPanel: MenuBandPopoverPanel? private var popoverVC: MenuBandPopoverViewController? - private var kidlispTVPanel: KidLispTVPanel? - /// Cached "$ pieces" feed for the TV chooser menu. Populated on - /// first popover open; refreshed lazily when stale. - private var kidlispChooserPieces: [KidLispChooserItem] = [] - private var kidlispChooserFetchInflight: Bool = false - private var kidlispChooserFetchedAt: Date? - private static let kidlispChooserCacheTTL: TimeInterval = 300 - private static let kidlispChooserURL = - "https://aesthetic.computer/api/store-kidlisp?recent=15&sortBy=hits" - private static let kidlispTVSourceDefaultsKey = "notepat.kidlispTV.source" - /// Snapshot buffer reused per-frame by the TV's amp provider so - /// every tick is a free read instead of a fresh allocation. - /// 256 mirrors WaveformView's snapshotSize. - private var kidlispAmpSamples = [Float](repeating: 0, count: 256) - /// Wall-clock of the most recent outbound noteOn (any source). - /// Drives a decaying-envelope fallback for the KidLisp `amp` value - /// when the local synth is silent — e.g. MIDI-output mode, where - /// the user hears notes through a DAW but the tap reads zeros. - private var kidlispLastNoteOnAt: CFTimeInterval = 0 - /// Envelope time constant for the noteOn-driven amp fallback. - /// ~250 ms feels right at 60 fps: one tap reads strong, sustained - /// playing reads as a fluttering attack envelope. - private static let kidlispNoteOnTau: Double = 0.25 + /// Indirect-touch sensor embedded in the popover so trackpad + /// pitch-bend still engages while the popover is the key window + /// (the off-screen capture sensor only sees fingers when IT is key, + /// which it isn't once the popover takes focus). First-responder of + /// the popover panel; mouse passes straight through (hitTest → nil). + private var popoverTouchSensor: TouchSensorView? + // [v1 cutoff] KidLisp TV panel + its `$` piece chooser cache + amp + // provider state removed. The shared KidLispState + the About-opened + // aesthetic.computer web window survive on their own. private var isPopoverPanelShown: Bool { popoverPanel?.isVisible == true } private lazy var pianoWaveformWindowDelegate = PianoWaveformWindowDelegate(menuBand: menuBand) @@ -520,15 +506,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.updatePianoWaveformWindow() } } - menuBand.onMIDIEvent = { [weak self] in + menuBand.onMIDIEvent = { // Spike the square indicator to full on every // outbound noteOn; the visualizer animation tick // decays it back toward zero. KeyboardIconRenderer.midiActivityFlash = 1 - // Stamp the noteOn time so the KidLisp TV's `amp` value - // still moves in MIDI-output mode, where the local synth - // is silent and the audio tap reads zeros. - self?.kidlispLastNoteOnAt = CACurrentMediaTime() + // [v1 cutoff] KidLisp TV amp-envelope stamp removed with the TV. } menuBand.bootstrap() // Subscribe to mic RMS during sample-voice recording. The @@ -642,11 +625,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // Four independent global controls: show the floating piano, // focus its keys, exit that focus, and switch the keyboard layout. - _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) - _ = registerPianoWaveformHotkey(MenuBandShortcutPreferences.playPaletteShortcut) - _ = registerExitFocusHotkey(MenuBandShortcutPreferences.exitFocusShortcut) - registerLayoutToggleHotkey() - registerPercussionToggleHotkey() + // [v1] The double right-⌘ tap (startRightCommandTapMonitor) is the + // ONLY system-wide key. It already arms AND disarms focus capture, + // so the focus/exit global hotkeys are redundant; the piano-waveform + // hotkey is dead (that overlay is retired); and layout + percussion + // toggles still fire from the LOCAL `localCapture.onKey` handler and + // the local ⌥ taps while Menu Band is focused. All other global + // RegisterEventHotKey bindings stay unregistered: + // _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) + // _ = registerPianoWaveformHotkey(MenuBandShortcutPreferences.playPaletteShortcut) + // _ = registerExitFocusHotkey(MenuBandShortcutPreferences.exitFocusShortcut) + // registerLayoutToggleHotkey() + // registerPercussionToggleHotkey() // Start the Stickies bridge — listens for keystrokes when // the macOS Stickies app is frontmost and the focused @@ -804,17 +794,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.togglePercussionSplitFromShortcut() return true } - // Spacebar toggles the metronome whenever the popover is - // open. Consumed in both directions so the keystroke - // never falls through to the focused app or to the note - // path (where space would otherwise behave like an - // unmapped key consume). - if keyCode == 49 /* kVK_Space */, self.isPopoverPanelShown { - if isDown && !isRepeat { - self.popoverVC?.toggleMetronome() - } - return true - } + // [v1 cutoff] Spacebar no longer toggles a metronome (removed); + // it falls through to the normal note/key path. // Arrow keys always step the GM program — the chooser // grid lives in the floating panel that pairs with the // popover, so when either is open the user expects ←/→/ @@ -828,6 +809,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // been retired (use the on-screen ArrowKeysIndicator // chevrons in the floating panel for mouse-driven // stepping). + // Keep the popover's touch sensor as first responder while + // the user plays — a stray mouse click on a popover control + // could otherwise move first-responder and stop indirect + // touches from routing to the sensor mid-phrase, silently + // breaking trackpad pitch-bend. Cheap to re-assert; only + // acts when it isn't already first responder. + if isDown, let sensor = self.popoverTouchSensor, + sensor.window?.firstResponder !== sensor { + sensor.window?.makeFirstResponder(sensor) + } let consumed = self.menuBand.handleLocalKey( keyCode: keyCode, isDown: isDown, isRepeat: isRepeat, flags: flags ) @@ -852,20 +843,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self?.finishLocalCapture(reason: reason) } localCapture.onTrackpadTouchActiveChanged = { [weak self] active in - guard let self = self else { return } - self.trackpadTouchActive = active - guard !active else { return } - // Last finger lifted off the trackpad. If no notes are - // held either, this IS the end of the gesture — close - // out the cursor lock and let the fx ramp naturally. - // If notes ARE still held, the user is mid-phrase and - // just resting their finger; leave bend/space/echo at - // whatever values they set so pitch + ambience don't - // drift on their own. The next finger touch (or note - // release) is the right time to change them. - if !self.menuBand.keyboardNotesHeld { - self.endPitchBendSession() - } + self?.setTrackpadTouchActive(active) } // Pre-instance the popover VC + force its view to load now so the @@ -1346,33 +1324,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } - /// Drag-and-drop entry point for Menu Band PDFs onto the - /// menubar piano icon. Opens the popover so the user sees the - /// score render as it auto-plays, then hands the URL to the - /// sheet view — same `loadAndPlay` code path as dropping the - /// PDF onto the score area inside an already-open popover. + /// [v1 cutoff] Menu Band PDF-score import rode on the Verovio + /// SheetMusicView, which was removed for v1. Dropping a `.pdf` + /// now just logs and is ignored; MIDI-file drops still play. + /// Score import returns post-v1 with the reintegrated staff. private func handlePDFFileDrop(url: URL) { - // Open the popover first so the SheetMusicView is laid out - // and its WKWebView is in a window — `loadAndPlay` evaluates - // JS through that webView, which silently no-ops if it has - // no host. `showPopover` is idempotent when the popover is - // already up. - showPopover() - // Defer to the next runloop pass so the popover's view - // hierarchy + initial layout finish before we shove a new - // score through the JS bridge. Without this hop the first - // drag-onto-menubar after launch lands while the sheet - // hasn't loaded yet, and the eval fires into a not-ready - // toolkit. - DispatchQueue.main.async { [weak self] in - guard let sheet = self?.popoverVC?.sheetView else { - NSLog("MenuBand: PDF drop \(url.lastPathComponent) — no sheet view available") - return - } - if !sheet.loadAndPlay(pdfURL: url) { - NSLog("MenuBand: PDF drop \(url.lastPathComponent) wasn't a Menu Band score — ignoring") - } - } + NSLog("MenuBand: PDF drop \(url.lastPathComponent) ignored — score import is not in v1") } // MARK: - Adaptive menubar layout @@ -1731,9 +1688,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { guard mask == .option else { return } self.toggleRightPercussionFromShortcut() } - rightOptionMonitorGlobal = NSEvent.addGlobalMonitorForEvents( - matching: [.flagsChanged] - ) { handler($0) } + // [v1] Local-only — bare right-⌥ flips drums ONLY while Menu Band + // is the active app (popover open / capture armed). No global + // monitor: the double right-⌘ tap is the sole system-wide key, so + // an Option press in another app never reaches percussion. rightOptionMonitorLocal = NSEvent.addLocalMonitorForEvents( matching: [.flagsChanged] ) { handler($0); return $0 } @@ -1754,9 +1712,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { guard mask == .option else { return } self.toggleLeftPercussionFromShortcut() } - leftOptionMonitorGlobal = NSEvent.addGlobalMonitorForEvents( - matching: [.flagsChanged] - ) { handler($0) } + // [v1] Local-only — mirror of the right-⌥ tap. Flips drums only + // while Menu Band is active; never system-wide. leftOptionMonitorLocal = NSEvent.addLocalMonitorForEvents( matching: [.flagsChanged] ) { handler($0); return $0 } @@ -2771,25 +2728,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // false synchronously — prevents toggle paths from racing // with the in-flight fade. popoverPanel = nil - // KidLisp TV panel is a child of the popover panel, so it - // would auto-order-out with the parent — but we want it to - // fade in lockstep, so explicit teardown is cleaner. - if let tv = kidlispTVPanel { - kidlispTVPanel = nil - // Release the synth-capture refcount that the TV took out - // in showPopover. Other surfaces (WaveformView etc.) keep - // their own counts, so the capture loop only actually - // stops when everyone's released. - menuBand.setWaveformCaptureEnabled(false) - NSAnimationContext.runAnimationGroup({ ctx in - ctx.duration = 0.14 - ctx.timingFunction = CAMediaTimingFunction(name: .easeOut) - tv.animator().alphaValue = 0 - }, completionHandler: { - tv.orderOut(nil) - tv.alphaValue = 1 - }) - } + // The popover's touch sensor goes away with it. Clear the + // resting-finger flag so a held bend doesn't strand once the + // sensor that was reporting it is gone (the capture-panel sensor + // takes over again if the user keeps playing with notes held). + popoverTouchSensor?.removeFromSuperview() + popoverTouchSensor = nil + if !menuBand.keyboardNotesHeld { setTrackpadTouchActive(false) } + // [v1 cutoff] KidLisp TV panel removed — no child panel to tear down. if let panel = panelToFade { NSAnimationContext.runAnimationGroup({ ctx in ctx.duration = 0.14 @@ -2955,13 +2901,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate { popoverPanel = panel debugLog("popover panel ordered front; visible=\(panel.isVisible) frame=\(panel.frame)") - // KidLisp TV — skeuomorphic LCD-television panel that sits - // directly under the LEFT floating panel (PianoWaveformWindow), - // not under the popover. Child-windowed off the popover so it - // dismisses with the popover; the anchor frame still comes - // from the left panel so the TV reads as part of the player - // palette stack. KidLispTVView starts its own 30fps timer in - // viewDidMoveToWindow once the panel is on screen. // Now that the popover's live frame is available // (popoverFrameProvider can read popoverPanel.frame), // re-anchor the floating piano panel so it lands at @@ -2974,53 +2913,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // fixing the cause here. pianoWaveformWindowDelegate.refresh() - // KidLisp TV now hangs flush off the bottom of the popover - // (the settings panel), not under the left player column — - // same width as the popover so it reads as the popover's - // own screen, edge to edge. - do { - let tvPanel = KidLispTVPanel(width: panel.frame.width) - // Attach BEFORE anchoring. addChildWindow nudges a child - // window so it sits "below" its parent if their frames - // don't intersect; set the final frame last so it's - // authoritative. - panel.addChildWindow(tvPanel, ordered: .below) - tvPanel.anchor(belowRightAlignedTo: panel.frame) - kidlispTVPanel = tvPanel - // Restore the shared current piece so the TV (and the - // floating web window) stay in sync across open/close. - tvPanel.tv.show(code: KidLispState.shared.code, - source: KidLispState.shared.source) - // Click on the screen → "$ pieces" chooser menu. Bound - // here (not in the panel init) because the chooser - // needs AppDelegate state (cache + persistence). - tvPanel.tv.onScreenClick = { [weak self] view, event in - self?.showKidLispChooser(from: view, event: event) - } - // Feed synth output amplitude into the evaluator each - // tick so pieces that read `amp`/`mic`/`amplitude` - // visualize the live MenuBand performance. Refcounted - // capture is released when closePopover tears the TV - // down so we don't keep the tap thread alive forever. - menuBand.setWaveformCaptureEnabled(true) - tvPanel.tv.ampProvider = { [weak self] in - self?.currentSynthAmp() ?? 0 - } - // Skip the KidLisp tick while the user is actively - // playing — held notes mean the synth + MIDI path - // need the main thread, and the bend gesture's pin - // timer fires at 60Hz. The TV catches up between - // performances and never blocks audio scheduling. - tvPanel.tv.busyProvider = { [weak self] in - guard let self = self else { return false } - return self.menuBand.litNotes.count > 0 - || self.pitchBendCursorLocked - || self.fxRampTimer != nil - } - // Warm the cache so the first click pops a populated - // menu instead of "Loading…". - fetchKidLispChooserPieces(force: false) { } - } + // [v1 cutoff] KidLisp TV panel removed — the popover no longer + // spawns a child LCD screen / `$` piece chooser. The shared + // KidLispState + floating aesthetic.computer web window (opened + // from About) survive independently. // Arm local key capture so arrow keys + spacebar reach // our handler while the popover is up. The InstrumentList @@ -3031,6 +2927,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate { DispatchQueue.main.async { [weak panel] in panel?.makeKey() } + + // Embed a trackpad-touch sensor in the popover (the now-key + // window) so resting fingers are detected here and the + // trackpad pitch-bend gesture engages while the popover is + // open. Made first responder so indirect touches route to it; + // it never steals the mouse (hitTest → nil), so the keys, + // buttons, and chooser grid underneath stay fully clickable. + let sensor = TouchSensorView(frame: panel.chrome.bounds) + sensor.autoresizingMask = [.width, .height] + sensor.onActiveChanged = { [weak self] active in + self?.setTrackpadTouchActive(active) + } + panel.chrome.addSubview(sensor) + panel.makeFirstResponder(sensor) + popoverTouchSensor = sensor // Click-away monitor: clicks on OTHER apps close the popover. // In-app clicks (status item button, the popover itself) don't // fire global monitors and therefore don't dismiss — that's how @@ -3113,6 +3024,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Pitch-bend gesture + /// Central sink for "is a finger resting on the trackpad right now." + /// Fed by BOTH the off-screen key-capture sensor panel (active when + /// no other window is key — e.g. playing with the popover closed) + /// AND the in-popover sensor (active while the popover is the key + /// window). Either source flipping the flag lets the trackpad + /// pitch-bend gesture engage; whichever currently owns the key + /// window's responder chain is the one delivering indirect touches. + func setTrackpadTouchActive(_ active: Bool) { + trackpadTouchActive = active + guard !active else { return } + // Last finger lifted off the trackpad. If no notes are held + // either, this IS the end of the gesture — close out the cursor + // lock and let the fx ramp naturally. If notes ARE still held, + // the user is mid-phrase and just resting their finger; leave + // bend/space/echo where they set them so pitch + ambience don't + // drift on their own. The next finger touch (or note release) + // is the right time to change them. + if !menuBand.keyboardNotesHeld { + endPitchBendSession() + } + } + private func handlePitchBendCursorMove(event: NSEvent) { // Single-finger trackpad gesture: normally active while the // user is holding a KEYBOARD note. Mouse-tapped piano notes @@ -3130,13 +3063,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // begun) so a passing MOUSE move can't reactivate the bend // — only an actual finger on the trackpad. let shift = event.modifierFlags.contains(.shift) - // Latched pitch mode: once engaged, EVERY trackpad move bends — - // no held note, finger, or shift required. The mode only ends on - // Esc or focus loss (endPitchBendSession). Until it's latched, - // fall back to the legacy gate (held note or shift) so a passing - // mouse move can't bend out of nowhere. - guard pitchBendModeLatched - || menuBand.keyboardNotesHeld || shift else { return } + // Engage ONLY while the user is actively holding a KEYBOARD note + // (or Shift, for warping still-ringing tails). This is the gesture: + // hold a letter key → the cursor locks (see onLitChanged) → move + // the pointer to bend → release the key → bend ends + cursor + // unlocks. Gating on `keyboardNotesHeld` (NOT on a latched flag + // that lingers after release) is what keeps the ORIGINAL bug fixed: + // clicking the menubar piano keys with the MOUSE plays via the tap + // channels — never `keyboardNotesHeld` — so a plain mouse move can + // never hide the cursor or bend. (An earlier attempt gated on an + // NSTouch `trackpadTouchActive` sensor, but indirect-touch delivery + // proved unreliable through the popover's key window, so the bend + // never engaged at all — confirmed in the field with touch=false on + // every move while keyHeld=true.) + guard menuBand.keyboardNotesHeld || shift else { return } let dy = Float(event.deltaY) let dx = Float(event.deltaX) guard dy != 0 || dx != 0 else { return } @@ -3189,16 +3129,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { debugLog("bend cursor dy=\(dy) lit=\(menuBand.litNotes.count) amt=\(bendAmount)") } - /// Forward the current effective pitch shift (octave + bend) - /// into the popover's staff view so the staff visibly slides - /// up/down on every shift. ±1 of bendAmount = ±12 semitones - /// (one octave); the staff eases its displayed shift toward - /// this target so changes glide instead of snapping. - private func pushStaffPitchShift() { - let bendSemitones = CGFloat(bendAmount) * MenuBandController.bendSemitonesPerUnit - let octaveSemitones = CGFloat(menuBand.octaveShift) * 12 - popoverVC?.staffView?.targetPitchShiftSemitones = bendSemitones + octaveSemitones - } + /// [v1 cutoff] Previously forwarded the effective pitch shift + /// (octave + bend) into the popover's staff so it slid up/down. + /// The staff was removed for v1; kept as a no-op so the bend / + /// octave call sites stay intact for the post-v1 single-column + /// pitch indicator. + private func pushStaffPitchShift() {} /// 60Hz timer used to overwrite the floating panel's /// `cursorUpdate`-driven cursor sets while pitch-bend is locked. @@ -3553,199 +3489,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { pianoWaveformWindowDelegate.isDocked && (isPopoverPanelShown || pianoWaveformWindowDelegate.isShown) } - // MARK: - KidLisp TV chooser - - /// Audio amplitude for the KidLisp TV, scaled to the 0–10 range - /// kidlisp.mjs uses for `amp`. Combines two sources so the viz - /// reacts in every mode: - /// 1. **Audio peak** of the synth tap (works whenever the local - /// synth is making sound). Compressed ×5 because typical - /// synth peaks live in the 0.05–0.2 band; raw RMS×10 was - /// barely visible. - /// 2. **NoteOn envelope** that decays from the most recent - /// outbound noteOn. Drives the viz in MIDI-output mode where - /// the local synth is muted and the tap reads silence. - /// Returns the louder of the two so the user's performance is - /// always visible, regardless of routing. - private func currentSynthAmp() -> Double { - menuBand.synthSnapshotWaveform(into: &kidlispAmpSamples) - var peak: Float = 0 - for s in kidlispAmpSamples { - let a = abs(s) - if a > peak { peak = a } - } - let audioAmp = Double(min(1.0, peak * 5.0)) * 10.0 - let now = CACurrentMediaTime() - let dt = now - kidlispLastNoteOnAt - let envelope = (kidlispLastNoteOnAt > 0 && dt >= 0) - ? exp(-dt / Self.kidlispNoteOnTau) - : 0 - let noteAmp = envelope * 10.0 - return max(audioAmp, noteAmp) - } - - private struct KidLispChooserItem { - let code: String - let source: String - let preview: String - let handle: String? - } - - /// Pop the "$ pieces" chooser menu at the click point. Empty cache - /// renders a "Loading…" placeholder and kicks off a fetch so the - /// next click is populated. Stale cache renders immediately and - /// refreshes in the background. - private func showKidLispChooser(from view: NSView, event: NSEvent) { - let menu = buildKidLispChooserMenu() - let local = view.convert(event.locationInWindow, from: nil) - menu.popUp(positioning: nil, at: local, in: view) - let stale = kidlispChooserFetchedAt.map { - Date().timeIntervalSince($0) > Self.kidlispChooserCacheTTL - } ?? true - if stale || kidlispChooserPieces.isEmpty { - fetchKidLispChooserPieces(force: false) { } - } - } - - private func buildKidLispChooserMenu() -> NSMenu { - let menu = NSMenu(title: "KidLisp") - menu.autoenablesItems = false - if kidlispChooserPieces.isEmpty { - let item = NSMenuItem(title: "Loading…", action: nil, keyEquivalent: "") - item.isEnabled = false - menu.addItem(item) - } else { - for piece in kidlispChooserPieces { - let item = NSMenuItem( - title: "", - action: #selector(loadKidLispPiece(_:)), - keyEquivalent: "" - ) - item.target = self - item.representedObject = piece - let attr = NSMutableAttributedString() - attr.append(NSAttributedString( - string: "$\(piece.code)", - attributes: [ - .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .semibold) - ] - )) - let cleaned = piece.preview - .replacingOccurrences(of: "\n", with: " · ") - .replacingOccurrences(of: "\r", with: "") - attr.append(NSAttributedString( - string: " \(cleaned)", - attributes: [ - .font: NSFont.monospacedSystemFont(ofSize: 12, weight: .regular), - .foregroundColor: NSColor.secondaryLabelColor - ] - )) - item.attributedTitle = attr - menu.addItem(item) - } - } - menu.addItem(.separator()) - let reset = NSMenuItem( - title: "Reset to default", - action: #selector(resetKidLispPiece(_:)), - keyEquivalent: "" - ) - reset.target = self - menu.addItem(reset) - let reload = NSMenuItem( - title: "Reload pieces…", - action: #selector(reloadKidLispChooser(_:)), - keyEquivalent: "" - ) - reload.target = self - menu.addItem(reload) - return menu - } - - @objc private func loadKidLispPiece(_ sender: NSMenuItem) { - guard let piece = sender.representedObject as? KidLispChooserItem else { return } - KidLispState.shared.select(code: piece.code, source: piece.source) - applyKidLisp() - } - - @objc private func resetKidLispPiece(_ sender: Any?) { - KidLispState.shared.reset() - applyKidLisp() - } - - /// Push the shared current piece to every live surface: the popover - /// TV always, and the floating web window only when a real `$code` - /// is selected (so the default/raw piece doesn't hijack the window - /// away from the AC homepage). - private func applyKidLisp() { - let state = KidLispState.shared - kidlispTVPanel?.tv.show(code: state.code, source: state.source) - if state.hasCode, let code = state.code { - AestheticWebWindowController.current()?.load(piece: "$\(code)") - } - } - - @objc private func reloadKidLispChooser(_ sender: Any?) { - // Force-refresh; next menu open will show the new list. - fetchKidLispChooserPieces(force: true) { } - } - - private func fetchKidLispChooserPieces( - force: Bool, - completion: @escaping () -> Void - ) { - if kidlispChooserFetchInflight { - completion() - return - } - if !force, - let at = kidlispChooserFetchedAt, - Date().timeIntervalSince(at) < Self.kidlispChooserCacheTTL, - !kidlispChooserPieces.isEmpty { - completion() - return - } - guard let url = URL(string: Self.kidlispChooserURL) else { - completion() - return - } - kidlispChooserFetchInflight = true - let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in - DispatchQueue.main.async { - guard let self = self else { completion(); return } - self.kidlispChooserFetchInflight = false - if let error = error { - NSLog("KidLisp chooser fetch failed: \(error)") - completion() - return - } - guard let data = data else { completion(); return } - struct Item: Decodable { - let code: String - let source: String - let preview: String? - let handle: String? - } - struct Response: Decodable { - let recent: [Item] - } - do { - let resp = try JSONDecoder().decode(Response.self, from: data) - self.kidlispChooserPieces = resp.recent.map { - KidLispChooserItem( - code: $0.code, - source: $0.source, - preview: $0.preview ?? "", - handle: $0.handle - ) - } - self.kidlispChooserFetchedAt = Date() - } catch { - NSLog("KidLisp chooser decode failed: \(error)") - } - completion() - } - } - task.resume() - } + // [v1 cutoff] KidLisp TV chooser (currentSynthAmp / KidLispChooserItem / + // showKidLispChooser / buildKidLispChooserMenu / loadKidLispPiece / + // resetKidLispPiece / applyKidLisp / reloadKidLispChooser / + // fetchKidLispChooserPieces) removed with the TV panel. The shared + // KidLispState + the About-opened aesthetic.computer web window remain. } diff --git a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift index c84146e47c..4ffa020a6e 100644 --- a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift +++ b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift @@ -526,8 +526,13 @@ enum KeyboardIconRenderer { static var recElapsed: Double = 0 // seconds, drives timer + morph /// Slot width reserved at the left — full pill width while recording (so /// the keys don't jiggle as the bubble morphs open within the slot). + /// [v1] Returns 0 when the tape feature is disabled (the default), so + /// the menubar REC button to the left of the keys is cut and the piano + /// slides flush to the leading edge. The zero-width `recHitRect` also + /// self-disables the click target. static var recReservedWidth: CGFloat { - recDotLeadPad + (recActive ? recPillWidth : recDotDiameter) + recDotTrailGap + guard tapeFeatureEnabled else { return 0 } + return recDotLeadPad + (recActive ? recPillWidth : recDotDiameter) + recDotTrailGap } // ── Deck panel (transport buttons only — cassette is mounted to @@ -831,8 +836,9 @@ enum KeyboardIconRenderer { // 🔴 REC dot — fixed slot at the far left, before the piano. // Solid red when idle; a blinking dot + elapsed timer while - // recording a tape. Only in the menubar layout (not the palette). - if tapeReservedInLayout { + // recording a tape. Only in the menubar layout (not the palette), + // and [v1] only when the tape feature is enabled (cut by default). + if tapeReservedInLayout && tapeFeatureEnabled { drawRecIndicator(canvasHeight: size.height) } diff --git a/slab/menuband/Sources/MenuBand/KidLispScreen.swift b/slab/menuband/Sources/MenuBand/KidLispScreen.swift index f1be579601..6244eebc4c 100644 --- a/slab/menuband/Sources/MenuBand/KidLispScreen.swift +++ b/slab/menuband/Sources/MenuBand/KidLispScreen.swift @@ -1,34 +1,13 @@ -// Shared plumbing for "what KidLisp piece is the TV showing" so the -// popover's KidLisp TV and the floating AestheticWebWindow can render -// the SAME piece. Two renderers conform to `KidLispScreen`: -// -// • KidLispTVView — native Swift evaluator (phase-1 corpus) -// • KidLispTVWebView — live aesthetic.computer in a WKWebView +// Shared plumbing for the currently-selected KidLisp piece. The popover's +// KidLisp TV used to render it too, but that was removed in the v1 cutoff; +// `KidLispState` survives because the floating AestheticWebWindow (opened +// from About) still mirrors a selected `$code` piece. // // `KidLispState.shared` is the single source of truth for the current -// selection (a `$code` when one is known, plus the raw source for the -// native fallback). The chooser writes to it; both surfaces read it. +// selection (a `$code` when one is known, plus the raw source). import AppKit -/// A view that can display a KidLisp piece. Adopted by both the native -/// framebuffer view and the webview so `KidLispTVPanel` can hold either -/// behind one type and `AppDelegate`'s wiring stays renderer-agnostic. -protocol KidLispScreen: AnyObject { - /// Show a piece. `code` is the bare cache code (no `$`) when known — - /// the webview prefers it for a short `/$code` URL; the native - /// renderer ignores it and evaluates `source` directly. - func show(code: String?, source: String) - - /// Click inside the screen well → owner pops the "$ pieces" chooser. - var onScreenClick: ((NSView, NSEvent) -> Void)? { get set } - /// 0–10 audio amplitude feed (native `amp`). Unused by the webview. - var ampProvider: (() -> Double)? { get set } - /// True while the app is latency-critical; native renderer skips - /// ticks. Unused by the webview. - var busyProvider: (() -> Bool)? { get set } -} - /// URL construction for AC KidLisp pieces. Centralized so the popover /// (clean embed) and the window (full chrome) build the same paths. enum KidLispURL { @@ -74,13 +53,23 @@ final class KidLispState { /// raw sources migrate forward (they load with `code == nil`). private static let sourceKey = "notepat.kidlispTV.source" + /// Fallback raw source when no `$code` is selected. (Formerly + /// `Self.defaultSource`, inlined here when the TV panel + /// was removed in the v1 cutoff.) + static let defaultSource: String = """ + wipe black + ink rainbow + line 0 (- h/2 (* amp 5)) w (- h/2 (* amp 5)) + line 0 (+ h/2 (* amp 5)) w (+ h/2 (* amp 5)) + """ + private(set) var code: String? private(set) var source: String private init() { let d = UserDefaults.standard self.code = d.string(forKey: Self.codeKey) - self.source = d.string(forKey: Self.sourceKey) ?? KidLispTVPanel.defaultSource + self.source = d.string(forKey: Self.sourceKey) ?? Self.defaultSource } /// True when a real cached piece is selected (vs. the default / @@ -104,16 +93,9 @@ final class KidLispState { func reset() { self.code = nil - self.source = KidLispTVPanel.defaultSource + self.source = Self.defaultSource let d = UserDefaults.standard d.removeObject(forKey: Self.codeKey) d.removeObject(forKey: Self.sourceKey) } } - -// MARK: - Native renderer conformance - -extension KidLispTVView: KidLispScreen { - /// The native evaluator only knows source text; ignore the code. - func show(code: String?, source: String) { setSource(source) } -} diff --git a/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift b/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift index 6a2aa14075..7aaa878a0d 100644 --- a/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift +++ b/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift @@ -154,7 +154,7 @@ final class LocalKeyCapture { /// and is in the key window's responder chain; `wantsRestingTouches` /// keeps a motionless finger counted instead of dropping it the moment /// it stops moving (the exact case that was snapping the bend back). -private final class TouchSensorView: NSView { +final class TouchSensorView: NSView { var onActiveChanged: ((Bool) -> Void)? private var lastActive = false @@ -172,6 +172,13 @@ private final class TouchSensorView: NSView { override var acceptsFirstResponder: Bool { true } + // Pure touch listener — never intercept the mouse. Returning nil + // from hitTest keeps clicks/drag flowing through to whatever + // control sits underneath (the popover's keys, buttons, grid), + // while indirect (trackpad) touches still arrive via the key + // window's responder chain because the view is first responder. + override func hitTest(_ point: NSPoint) -> NSView? { nil } + override func touchesBegan(with event: NSEvent) { recompute(event) } override func touchesMoved(with event: NSEvent) { recompute(event) } override func touchesEnded(with event: NSEvent) { recompute(event) } diff --git a/slab/menuband/Sources/MenuBand/MenuBandController.swift b/slab/menuband/Sources/MenuBand/MenuBandController.swift index 2c398a5ee2..4c5aabebf8 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandController.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandController.swift @@ -1659,59 +1659,11 @@ final class MenuBandController { // normal `litNotes` user-input set. Sound emits the same way // a tap would; only the visual state is parallel. - /// Sound + light a note as part of an auto-playback session. - /// `displayNote` is the menubar-clamped key the renderer should - /// draw red — defaults to the played pitch when the caller - /// doesn't have an explicit display. - func startPlaybackNote(_ midiNote: UInt8, velocity: UInt8 = 100, - displayNote: UInt8? = nil) { - let synthCh = nextMelodicChannel() - playbackChannel[midiNote] = synthCh - let mc: UInt8 = 0 - if !midiMode { - synth.noteOn(midiNote, velocity: velocity, channel: synthCh) - } - midiNoteOn(midiNote, velocity: velocity, channel: mc) - let visualNote = displayNote ?? midiNote - let setLit = { [weak self] in - guard let self = self else { return } - if self.playbackLitNotes.insert(visualNote).inserted { - self.onLitChanged?() - } - } - if Thread.isMainThread { setLit() } else { DispatchQueue.main.async(execute: setLit) } - } - - /// Release a note previously started with `startPlaybackNote`. - func stopPlaybackNote(_ midiNote: UInt8, displayNote: UInt8? = nil) { - let synthCh = playbackChannel.removeValue(forKey: midiNote) ?? channel(for: midiNote) - if !midiMode { synth.noteOff(midiNote, channel: synthCh) } - midi.noteOff(midiNote, channel: 0) - let visualNote = displayNote ?? midiNote - DispatchQueue.main.async { [weak self] in - guard let self = self else { return } - if self.playbackLitNotes.remove(visualNote) != nil { - self.onLitChanged?() - } - } - } - - /// Panic — called when superseding a playback session so the - /// previous take doesn't strand notes. - func releaseAllPlaybackNotes() { - for (note, ch) in playbackChannel { - if !midiMode { synth.noteOff(note, channel: ch) } - midi.noteOff(note, channel: 0) - } - playbackChannel.removeAll() - DispatchQueue.main.async { [weak self] in - guard let self = self else { return } - if !self.playbackLitNotes.isEmpty { - self.playbackLitNotes.removeAll() - self.onLitChanged?() - } - } - } + // [v1 cutoff] startPlaybackNote / stopPlaybackNote / + // releaseAllPlaybackNotes removed — only the deleted SheetMusicView + // (PDF/MIDI score auto-playback) drove them. `playbackLitNotes` stays + // declared because the menubar renderer + AppDelegate still read it + // (it simply stays empty until score playback returns post-v1). // MARK: - Linger / bell-ring tail @@ -1776,6 +1728,17 @@ final class MenuBandController { /// after the press" complaint. private var lingerFadeWork: [UInt8: [DispatchWorkItem]] = [:] + /// The still-ringing sustained-linger note on each synth channel, + /// tracked for the lifetime of its fade. A sustained linger keeps + /// its original noteOn alive while Expression ramps 127→0, so the + /// note is physically still sounding (just inaudible) until the + /// tail's cleanup noteOff. If a NEW note reuses this channel before + /// then, `cancelLingerFade` resets the channel volume back to 127 — + /// which, without first stopping the old note, snaps the faded-out + /// note back to full volume (the "it plays again after one press" + /// bug). We noteOff the tracked note before the volume reset. + private var lingeringNoteByChannel: [UInt8: UInt8] = [:] + /// Cancel an in-flight Expression fade on `synthChannel` (if /// any) and immediately restore Expression to 127 so the next /// note on the channel plays at full volume. Call before every @@ -1784,6 +1747,15 @@ final class MenuBandController { if let items = lingerFadeWork.removeValue(forKey: synthChannel) { for w in items { w.cancel() } } + // Kill the still-ringing lingering note on this channel BEFORE + // restoring the volume — otherwise resetting Expression/Volume + // to 127 resurrects the faded-out note at full gain. + if let stale = lingeringNoteByChannel.removeValue(forKey: synthChannel) { + if !midiMode { synth.noteOff(stale, channel: synthChannel) } + // Lingering notes are always melodic → outbound MIDI channel 0 + // (matches midiNoteOn / releaseLingering's midiChannel: 0). + midi.noteOff(stale, channel: 0) + } if !midiMode { synth.sendExpression(value: 127, channel: synthChannel) synth.resetSampleChannelVolumes(channel: synthChannel) @@ -1809,6 +1781,10 @@ final class MenuBandController { private func scheduleSustainedLingerFade(midiNote: UInt8, synthChannel: UInt8, midiChannel: UInt8) { + // Mark this note as ringing-but-fading on its channel so a new + // note that reuses the channel kills it (see cancelLingerFade) + // instead of snapping it back to full volume. + lingeringNoteByChannel[synthChannel] = midiNote // 100 hops over 10 s = every 100 ms. Linear ramp: // Ableton's stock devices (and most third-party plugins) // map CC7/CC11 to a near-linear audible volume curve, so @@ -1860,10 +1836,15 @@ final class MenuBandController { guard let self = self else { return } if !self.midiMode { self.synth.noteOff(midiNote, channel: synthChannel) } self.midi.noteOff(midiNote, channel: midiChannel) - // Don't clear lingerFadeWork[synthChannel] here — leave - // it so a future noteOn knows the channel is in a faded - // state and runs cancelLingerFade to restore CC=127. - // (Cancelled items are harmless if cancel()-ed again.) + // Fade finished and the note is now off — it can no longer be + // resurrected, so stop tracking it (only clear if this same + // note is still the one registered; a newer note may have + // taken the slot). Don't clear lingerFadeWork[synthChannel] + // here — leave it so a future noteOn knows the channel is in a + // faded state and runs cancelLingerFade to restore CC=127. + if self.lingeringNoteByChannel[synthChannel] == midiNote { + self.lingeringNoteByChannel.removeValue(forKey: synthChannel) + } } items.append(tail) // 200 ms breathing room past the last ramp tick. AVAudio's diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index 624db8aa89..ded13a91f9 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -149,17 +149,9 @@ final class MenuBandPopoverViewController: NSViewController { /// popover gets the same searchable chord readout. private var chordCandidatesStack: NSStackView! private var chordCandidatesRow: NSView! - /// All-Swift scrolling staff (Phase 1, below the Verovio sheet) + its - /// backing take. Declarations added to unblock the in-progress - /// tape-staff wiring already referencing them below. - private var tapeStaff: TapeStaffScroller! - private let tapeScore = TapeScore() - /// Internal but exposed so AppDelegate can push the pitch-shift - /// value (octave + bend) directly when those change — the staff - /// translates vertically by that amount so the user feels the - /// shift visually too. - private(set) var staffView: StaffView! - private(set) var sheetView: SheetMusicView! + // [v1 cutoff] tapeStaff / tapeScore / staffView / sheetView removed + // with the staff + Verovio sheet. They return post-v1, reintegrated + // into the single column. private var lastSeenHeldMidis: Set = [] private var lastCompleteChordNames: Set = [] private let chordCandidatesRowHorizontalInset: CGFloat = 6 @@ -190,7 +182,13 @@ final class MenuBandPopoverViewController: NSViewController { /// when the metronome starts. private var tapeBezelHeightConstraint: NSLayoutConstraint? private static let tapeBezelHeight: CGFloat = 88 + 12 - private var metronome: MetronomeWidget! + // [v1 cutoff] metronome removed. + + /// [v1] The instrument cluster (GM bee-vision grid + program readout + + /// QWERTY map + arrow stepper + Notepat/Ableton mode picker), lifted + /// out of the now-retired floating piano window and hosted directly in + /// this popover so the whole instrument lives in a single column. + private var instrumentCluster: CollapsedPianoWaveformView? /// Transport controls that appear next to the metronome when a /// Menu Band PDF score has been loaded into the staff. Play /// restarts from the head; Stop cancels in-flight playback. @@ -242,13 +240,11 @@ final class MenuBandPopoverViewController: NSViewController { stack.translatesAutoresizingMaskIntoConstraints = false root.addSubview(stack) - // Pin the stack to exactly the instrument-grid width plus the - // 8 px insets on each side. Without this, NSSegmentedControl's - // intrinsic-content-size for "Notepat.com" pushes the stack wider - // than 224, which then drags the popover out with it. - stack.widthAnchor.constraint( - equalToConstant: InstrumentListView.preferredWidth + 16 - ).isActive = true + // [v1] No fixed stack width — the hosted instrument cluster + // (CollapsedPianoWaveformView, added below) carries a definite + // internal width, so the stack hugs to that width plus the 8px + // edge insets. titleRow / quitRow derive their width from the + // stack, so they follow the cluster automatically. // Top control row: octave hugs the left, MIDI hugs the right. Brand // title moved into the About section below — fewer wasted rows up top. @@ -347,115 +343,21 @@ final class MenuBandPopoverViewController: NSViewController { _ = octaveCaption titleRow.addArrangedSubview(octaveStepper) // hidden, value model only - // Volume / max-volume mixer slider. Lives at the leading edge of - // the title row so it pins top-left, mirroring the octave readout - // pinned top-right. The icon doubles as a mute toggle (click to - // snap to 0; click again to restore the prior value). - buildVolumeWidget(into: titleRow) + // [v1 cutoff] Volume / max-volume mixer slider removed — system + // volume drives the master mix for v1. The slider + mute icon + // (buildVolumeWidget / volumeSliderChanged / volumeIconClicked) + // stay below as orphaned, guard-protected dead code so the + // post-v1 single-column mixer can re-wire them without a rebuild. + // The title row now flows straight to the octave readout (right). // Spacer lives in the middle so the octave widget pins LEFT and // the MIDI pair pins RIGHT. titleRow.addArrangedSubview(titleSpacer) - // Metronome — sits between the octave widget and the MIDI - // switch. Custom-drawn analog body with a real swinging - // needle (animates while playing) and a tiny `<` BPM `>` - // stepper underneath, mirroring the octave widget's chevron - // look. Click the body to toggle play; chevrons step BPM. - metronome = MetronomeWidget() - metronome.translatesAutoresizingMaskIntoConstraints = false - // Use the dynamic label color so the body / needle / arrows - // invert with the system theme — was hardcoded to white, - // which left the icon invisible against the popover's - // light-mode background. - metronome.tint = .labelColor - metronome.toolTip = "Metronome — space to start / stop" - metronome.onTick = { [weak self] in - // Yellow-flash the menubar music-note icon on every - // metronome beat. AppDelegate's animation tick decays - // it back to zero between beats. - KeyboardIconRenderer.metronomeFlash = 1 - // The all-Swift tape staff is time-based, so it needs no - // per-beat tick. Keep the metronome BPM in sync for any - // beat-grid drawing the staff may do. - if let bpm = self?.metronome?.bpm { - self?.tapeStaff?.bpm = Double(bpm) - } - // Drop a beat marker on the (now-hidden) StaffView - // too — its chord-display path still depends on it - // and removing it would break the existing chord - // popover wiring before we've ported it to the sheet. - guard let self = self, - let staffView = self.staffView, - let metronome = self.metronome else { return } - let anchor = metronome.needleAnchorPoint - let inStaff = staffView.convert(anchor, from: metronome) - staffView.dropBeatMarker(atX: inStaff.x) - } - metronome.onRunningChanged = { [weak self] in - // Repaint the menubar icon as soon as the running state - // flips so the wave indicator appears (or vanishes) - // even while the popover stays open. - (NSApp.delegate as? AppDelegate)?.updateIcon() - // The notation staff only exists while the metronome runs - // (the beat grid needs a tempo). Slide it in on start, - // collapse it on stop. - self?.setNotationVisible(self?.metronome?.isPlaying == true, - animated: true) - } - titleRow.addArrangedSubview(metronome) - titleRow.setCustomSpacing(6, after: metronome) - // The popover's arrow tip points at the horizontal midpoint - // of the title row (see AppDelegate.showPopover — - // arrowScreenX = gearScreen.x and leftScreenX = gearScreen.x - // - contentSize.width / 2). Pin the metronome's centerX to - // the row's centerX so it sits directly under the arrow - // regardless of how wide the trailing octave / MIDI / - // transport cluster grows. NSStackView's natural fill - // distribution honors this explicit constraint and divides - // the slack across the flex spacers on either side. - metronome.centerXAnchor.constraint( - equalTo: titleRow.centerXAnchor - ).isActive = true - // Playback transport — green ▶ + red ◼ that surface only - // after a Menu Band PDF has been dropped onto the staff. - // Symbol images get a circle.fill backdrop in the family - // tint so the buttons read like classic tape transport - // controls. - let transportConfig = NSImage.SymbolConfiguration(pointSize: 12, weight: .bold) - playButton = NSButton() - playButton.translatesAutoresizingMaskIntoConstraints = false - playButton.image = NSImage(systemSymbolName: "play.fill", - accessibilityDescription: "Play score")? - .withSymbolConfiguration(transportConfig) - playButton.bezelStyle = .recessed - playButton.isBordered = false - playButton.imagePosition = .imageOnly - playButton.contentTintColor = NSColor.systemGreen - playButton.toolTip = "Play score" - playButton.target = self - playButton.action = #selector(playScoreClicked(_:)) - playButton.isHidden = true - playButton.widthAnchor.constraint(equalToConstant: 18).isActive = true - playButton.heightAnchor.constraint(equalToConstant: 18).isActive = true - stopButton = NSButton() - stopButton.translatesAutoresizingMaskIntoConstraints = false - stopButton.image = NSImage(systemSymbolName: "stop.fill", - accessibilityDescription: "Stop score")? - .withSymbolConfiguration(transportConfig) - stopButton.bezelStyle = .recessed - stopButton.isBordered = false - stopButton.imagePosition = .imageOnly - stopButton.contentTintColor = NSColor.systemRed - stopButton.toolTip = "Stop score" - stopButton.target = self - stopButton.action = #selector(stopScoreClicked(_:)) - stopButton.isHidden = true - stopButton.widthAnchor.constraint(equalToConstant: 18).isActive = true - stopButton.heightAnchor.constraint(equalToConstant: 18).isActive = true - titleRow.addArrangedSubview(playButton) - titleRow.addArrangedSubview(stopButton) - titleRow.setCustomSpacing(8, after: stopButton) + // [v1 cutoff] Metronome + score transport (play/stop) removed — + // post-v1 they return reintegrated into the single column. The + // title row now flows straight from the octave widget (left) to + // the MIDI badge + octave readout (right). // Inline "MIDI" badge — only visible when MIDI mode is on. // Restores the legacy at-a-glance routing readout from the // popover title row that the chooser-cell-based "0 MIDI OUT" @@ -474,13 +376,11 @@ final class MenuBandPopoverViewController: NSViewController { let trailingSpacer = NSView() trailingSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) titleRow.addArrangedSubview(trailingSpacer) - // Active octave readout — final element in the row, pinned - // to the popover's top-right corner. Sharp drop shadow is - // applied below in `applyOctaveLabelShadow()` and refreshed - // on every appearance change so the contrast direction - // flips with light/dark mode. - titleRow.addArrangedSubview(octaveLabel) - applyOctaveLabelShadow() + // [v1 cutoff] Top-right octave readout removed — the QWERTY map's + // octave-shifted caps + the , / . (z / x) keys already convey the + // active octave. The `octaveLabel` ivar stays alive (it's still + // updated by setOctave/applyOctaveLabelShadow) but is no longer + // added to the title row, so the popover's top edge stays clean. // MIDI toggle is now slot 0 in the chooser ("0 MIDI OUT"). The // ivars below stay so existing references (status sync, the @@ -499,6 +399,31 @@ final class MenuBandPopoverViewController: NSViewController { stack.addArrangedSubview(makeSeparator()) + // [v1] Instrument cluster — folded in from the retired floating + // window. Self-sizing (fixed internal width + a complete vertical + // constraint chain), so it drops straight into the column. Arrow + // steppers drive GM program selection, matching the wiring the + // floating panel used. + if let mb = menuBand { + let cluster = CollapsedPianoWaveformView(menuBand: mb, embedded: true) + cluster.translatesAutoresizingMaskIntoConstraints = false + cluster.onStepBackward = { [weak self] in + self?.menuBand?.stepMelodicProgram(delta: -1) + } + cluster.onStepForward = { [weak self] in + self?.menuBand?.stepMelodicProgram(delta: 1) + } + cluster.onStepUp = { [weak self] in + self?.menuBand?.stepMelodicProgram(delta: -InstrumentListView.cols) + } + cluster.onStepDown = { [weak self] in + self?.menuBand?.stepMelodicProgram(delta: InstrumentListView.cols) + } + instrumentCluster = cluster + stack.addArrangedSubview(cluster) + stack.setCustomSpacing(8, after: cluster) + } + // Input mode picker. Three states: // Pointer — mouse only, two octaves (Notepat range) // Notepat.com — global keystroke capture, two octaves @@ -696,17 +621,11 @@ final class MenuBandPopoverViewController: NSViewController { // border, uniform inner margin around the bars. Without the // bezel the bars sit flush against the popover walls and feel // unfinished. - // The popover's visualizer was retired — the InstrumentListView - // (above) is the only visualizer left. The container below is - // a transparent layout wrapper for the held-notes pills + chord - // cards (no chrome, no background, no border) so the rows just - // sit on the popover surface. - waveformBezel = NSView() - waveformBezel.translatesAutoresizingMaskIntoConstraints = false - // Held-notes goes ABOVE the visualizer so the actively- - // sounding pitches read like a label on the meter housing. - // Build the floating-boxes container HERE so the ivar is - // populated before we add it to the stack. + // [v1 cutoff] The staff bezel (waveformBezel → chordCandidates → + // tapeStaff/StaffView) and the lazy Verovio SheetMusicView are + // gone. The held-note/chord readout below is the only surviving + // surface from this region; its container is built off-tree the + // same way it was before (refreshHeldNotes populates it). heldNotesStack = NSStackView() heldNotesStack.orientation = .horizontal heldNotesStack.alignment = .centerY @@ -719,129 +638,8 @@ final class MenuBandPopoverViewController: NSViewController { heldNotesStack.centerXAnchor.constraint(equalTo: heldNotesContainer.centerXAnchor), heldNotesStack.centerYAnchor.constraint(equalTo: heldNotesContainer.centerYAnchor), ]) - - // Visualizer bezel doubles as the chord-finder canvas: held- - // note pills overlay the top of the meter, chord-candidate - // cards overlay the bottom, both translucent enough that the - // live waveform peeks through underneath. Bezel grows tall - // enough to host both — same integrated layout the floating - // play palette uses, so the two surfaces feel identical. - stack.addArrangedSubview(waveformBezel) - // Bezel extends to match the popover stack's full width (= preferredWidth + 16) - // so the staff lines + scrolling notes paint EDGE TO EDGE of - // the popover, ignoring the chooser-row's interior margins. - waveformBezel.widthAnchor.constraint(equalToConstant: InstrumentListView.preferredWidth + 16).isActive = true - // Bezel grows to fit the tape staff inside. The old Verovio - // sheet was an 8.5×11 portrait (~330pt tall) and the bezel was - // sized to match; the all-Swift tape staff is a short wide - // strip, so the bezel is now just the staff height plus the - // row chrome (chordCandidatesRow pads 4pt top/bottom, stack - // pads 2pt) — no more dead portrait whitespace. - let bezelH = waveformBezel.heightAnchor.constraint( - equalToConstant: Self.tapeBezelHeight) - bezelH.isActive = true - tapeBezelHeightConstraint = bezelH - - // Mini visualizer strip removed — the audio-reactive readout - // now lives in the floating KidLisp TV panel below the - // popover, so the in-popover bars were redundant. The - // `miniWaveformView` / `miniWaveformBezel` ivars stay declared - // (left nil) since the retint + appearance paths already guard - // on `if let`. - - // Pill container is allocated but unused (kept so any - // legacy refresh path doesn't crash); not added to the - // bezel. _ = heldNotesContainer - // Chord candidates — every recognized chord shape that - // contains the user's held pitch classes, plus partial - // candidates whose missing notes are reachable on the - // active keymap. Displayed as a wrapping flow row so - // *all* available chords stay visible (not just three). - chordCandidatesStack = NSStackView() - chordCandidatesStack.orientation = .vertical - chordCandidatesStack.alignment = .centerX - chordCandidatesStack.spacing = 4 - chordCandidatesStack.translatesAutoresizingMaskIntoConstraints = false - chordCandidatesRow = NSView() - chordCandidatesRow.translatesAutoresizingMaskIntoConstraints = false - chordCandidatesRow.wantsLayer = true - chordCandidatesRow.layer?.masksToBounds = false - chordCandidatesRow.addSubview(chordCandidatesStack) - NSLayoutConstraint.activate([ - chordCandidatesStack.centerXAnchor.constraint(equalTo: chordCandidatesRow.centerXAnchor), - chordCandidatesStack.topAnchor.constraint(equalTo: chordCandidatesRow.topAnchor, constant: 2), - chordCandidatesStack.leadingAnchor.constraint(greaterThanOrEqualTo: chordCandidatesRow.leadingAnchor, constant: chordCandidatesRowHorizontalInset), - chordCandidatesStack.trailingAnchor.constraint(lessThanOrEqualTo: chordCandidatesRow.trailingAnchor, constant: -chordCandidatesRowHorizontalInset), - chordCandidatesStack.bottomAnchor.constraint(lessThanOrEqualTo: chordCandidatesRow.bottomAnchor, constant: -2), - ]) - waveformBezel.addSubview(chordCandidatesRow) - NSLayoutConstraint.activate([ - chordCandidatesRow.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor), - chordCandidatesRow.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor), - // Anchor to the bezel itself — heldNotesContainer used - // to be a sibling but was retired with the big-pill - // row, so referencing its bottomAnchor here crashed - // the popover load (no common ancestor). - chordCandidatesRow.topAnchor.constraint(equalTo: waveformBezel.topAnchor, constant: 4), - chordCandidatesRow.bottomAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: -4), - ]) - // Single traditional staff view in the lower half of the - // bezel. Held notes draw as solid heads; *all* chord - // candidates' missing notes are ghosted on top of the - // SAME staff, each chord's notes connected with a colored - // path keyed to the chord family — major routes are green, - // minor blue, dom7 orange, etc. Routes overlap on the - // staff; the user reads the suggestions visually rather - // than as a list. - // staffView stays alive as a sink for the chord-candidate - // write path (so we don't have to rip out that code yet), - // but the bezel now shows a sheet-music card instead — the - // user wanted a stack of stave rows that plops noteheads - // as keys are pressed, not a rolling timeline. Once the - // chord-candidate display is ported to the sheet view, - // staffView can be removed entirely. - staffView = StaffView() - staffView.translatesAutoresizingMaskIntoConstraints = false - // SheetMusicView is no longer shown — it's kept only as the - // lazy Verovio engine for on-demand PDF export + PDF drag-in - // playback. The visible live staff is the all-Swift tapeStaff - // below. Not added to the view hierarchy; its webviews stay - // unbuilt until a PDF is requested. - sheetView = SheetMusicView() - sheetView.menuBand = menuBand - sheetView.translatesAutoresizingMaskIntoConstraints = false - // Drive the transport-button visibility whenever the sheet - // toggles playback state (PDF load, manual stop, natural - // end-of-score). The visibility update is cheap so we don't - // bother coalescing. - sheetView.onPlaybackStateChanged = { [weak self] in - self?.updatePlaybackTransportVisibility() - } - // Sheet is the dominant popover element — fills the bezel - // edge-to-edge horizontally and runs at letter portrait - // aspect (8.5×11). The popover lengthens to host it. No - // inset around the page; the cream paper sits flush with - // the bezel's bounds. - let sheetWidth = InstrumentListView.preferredWidth + 16 - - // The all-Swift scrolling staff — now the sole visible score - // surface. Short wide strip (saves the vertical space the old - // 8.5×11 Verovio portrait ate) with bigger, more legible - // notes. Auto-scrolls to follow the playhead; two-finger - // trackpad scrubs back through the take. - tapeStaff = TapeStaffScroller() - tapeStaff.translatesAutoresizingMaskIntoConstraints = false - tapeStaff.score = tapeScore - tapeStaff.live = true - tapeStaff.bpm = Double(KeyboardIconRenderer.metronomeBPM) - chordCandidatesStack.addArrangedSubview(tapeStaff) - NSLayoutConstraint.activate([ - tapeStaff.widthAnchor.constraint(equalToConstant: sheetWidth), - tapeStaff.heightAnchor.constraint(equalToConstant: 88), - ]) - // (MIDI switch lives in the title row above — see octave + MIDI block.) // MIDI self-test status — populated by the controller after each @@ -1025,8 +823,6 @@ final class MenuBandPopoverViewController: NSViewController { _ = shortcuts _ = playPaletteRow - stack.setCustomSpacing(14, after: waveformBezel) - // Description + brand chip moved out of the popover proper — // they now live in the standard macOS About panel reachable via // the small "About" link at bottom-left. Frees the popover to @@ -1197,28 +993,13 @@ final class MenuBandPopoverViewController: NSViewController { // round-trips back to playback at the staff octave instead // of the original octave — sounded wrong by 12 semitones // every time the user had a non-zero octave shift. - let shiftSemitones = m.octaveShift * 12 - let currentHeld = Set(m.heldNoteEntries().map { entry -> UInt8 in - let played = Int(entry.midi) + shiftSemitones - return UInt8(max(0, min(127, played))) - }) - let newOnsets = currentHeld.subtracting(lastSeenHeldMidis) - let newReleases = lastSeenHeldMidis.subtracting(currentHeld) - // Notes flow only into the all-Swift take now — the Verovio - // pane is no longer driven per-keystroke. It's engraved on - // demand from `tapeScore` when the user exports a PDF. - // Only inscribe while the metronome runs: the notation staff is - // a metronome-gated surface, so there's always a beat grid to - // place notes on. Releases still flow through so a note held - // across a metronome stop closes cleanly. - let t = CACurrentMediaTime() - if metronome?.isPlaying == true { - for midi in newOnsets.sorted() { tapeScore.noteOn(midi, at: t) } - } - for midi in newReleases { tapeScore.noteOff(midi, at: t) } - lastSeenHeldMidis = currentHeld - + // [v1 cutoff] Per-keystroke score inscription (tapeScore) + + // metronome gating removed with the staff. Held notes now drive + // only the live note/chord readout below. qwertyMap?.litKeyCodes = m.heldKeyCodes() + // [v1] Keep the hosted instrument cluster's grid / readout / + // QWERTY lit-state in sync as the user plays. + instrumentCluster?.refresh() for v in heldNotesStack.arrangedSubviews { heldNotesStack.removeArrangedSubview(v) v.removeFromSuperview() @@ -1255,58 +1036,9 @@ final class MenuBandPopoverViewController: NSViewController { } } - // Staff sheet: held notes as solid heads + two ghost - // suggestions for the circle-of-fifths neighbors of the - // currently-played lowest note. Forward = +7 semitones (one - // step CW round the circle, e.g. C → G), backward = -7 - // (one step CCW, e.g. C → F). Two faded letters at the - // preview column, no chord-shape ghosting. - guard let staff = staffView else { lastCompleteChordNames = []; return } - var entries: [StaffView.Note] = [] - for entry in m.heldNoteEntries() { - entries.append(.init( - midi: entry.midi, - pitchClass: entry.pitchClass, - keyLabel: entry.keyLabel, - ghost: false, - color: nil - )) - } - if let root = entries.min(by: { $0.midi < $1.midi }) { - let labels = KeyboardIconRenderer.labelByMidi - let pitchNames = MenuBandController.pitchClassNames - // Wrap the suggestion into the playable two-octave - // keymap range so each circle-of-fifths neighbor lands - // on a real key the user can press. Outside the labeled - // set we fold by octaves until we find one — if nothing - // fits (range too narrow), we skip the ghost rather - // than show an unreachable suggestion. - let labeledMidis = labels.keys.sorted() - guard let lo = labeledMidis.first, - let hi = labeledMidis.last else { - staff.notes = entries - lastCompleteChordNames = Set(m.chordCandidates(maxResults: 6) - .filter(\.isComplete).map(\.name)) - return - } - for delta in [7, -7] { - var target = Int(root.midi) + delta - while target < lo { target += 12 } - while target > hi { target -= 12 } - guard target >= lo, target <= hi else { continue } - let mid = UInt8(target) - let pc = target % 12 - entries.append(.init( - midi: mid, - pitchClass: pitchNames[pc], - keyLabel: labels[target], - ghost: true, - color: nil - )) - } - } - staff.notes = entries - lastCompleteChordNames = Set(m.chordCandidates(maxResults: 6).filter(\.isComplete).map(\.name)) + // [v1 cutoff] Staff note-write + circle-of-fifths ghost + // suggestions removed with StaffView. The held-note readout + // above is the surviving surface. } /// Per-chord-family color, for ghost notes on the staff. @@ -1390,10 +1122,6 @@ final class MenuBandPopoverViewController: NSViewController { guard isViewLoaded, let n = menuBand else { return } midiSwitch.state = n.midiMode ? .on : .off midiInlineLabel?.isHidden = !n.midiMode - // Force the staff to repaint — keymap toggles change which - // slots show as letters/lines on the chart even when the - // held-note set is unchanged. - staffView?.needsDisplay = true refreshHeldNotes() octaveStepper.integerValue = n.octaveShift updateOctaveLabel(n.octaveShift) @@ -1723,6 +1451,7 @@ final class MenuBandPopoverViewController: NSViewController { updateInstrumentReadout() applyAppearanceToVisualizer() qwertyMap?.voiceColor = currentVoiceColor() + instrumentCluster?.refresh() } private func currentVoiceColor() -> NSColor { @@ -2107,67 +1836,13 @@ final class MenuBandPopoverViewController: NSViewController { // MARK: - Actions - /// Programmatic toggle of the metronome's play/pause — wired from - /// the spacebar shortcut in AppDelegate's local key handler so - /// users can start/stop the swing without aiming the mouse. - func toggleMetronome() { - metronome?.isPlaying.toggle() - } - /// Wired by AppDelegate to resize the HOST PANEL when the popover's - /// natural height changes (notation staff sliding in/out), so the - /// whole popover grows/shrinks rather than clipping an inner row. + /// natural height changes, so the whole popover grows/shrinks rather + /// than clipping an inner row. (Kept for the upcoming single-column + /// resize wiring; the metronome-driven notation staff that used it + /// was removed in the v1 cutoff.) var onRequestResize: ((NSSize) -> Void)? - /// Show or hide the notation staff. The staff lives inside - /// `waveformBezel`; collapsing its height to 0 + hiding it makes the - /// popover shrink to a compact height when the metronome is off, and - /// the whole panel grows the staff back in when it starts. - private func setNotationVisible(_ visible: Bool, animated: Bool) { - guard let bezel = waveformBezel, - let h = tapeBezelHeightConstraint else { return } - // Pause/resume the staff's live follow timer with visibility. - tapeStaff?.live = visible - // Resize the inner row immediately, then publish the new fitting - // size so the panel animates its whole frame to match (the panel - // frame animation is what the user sees move — no inner-only - // animation that would clip against a fixed window). - h.constant = visible ? Self.tapeBezelHeight : 0 - bezel.alphaValue = visible ? 1 : 0 - bezel.isHidden = !visible - view.layoutSubtreeIfNeeded() - let fitting = view.fittingSize - preferredContentSize = fitting - onRequestResize?(fitting) - _ = animated - } - - @objc private func playScoreClicked(_ sender: NSButton) { - sheetView?.restartPlayback() - } - - @objc private func stopScoreClicked(_ sender: NSButton) { - sheetView?.stopPlayback() - } - - /// Match the title-row transport buttons to the sheet view's - /// current playback state: hide both when no PDF is loaded; - /// show play when paused/idle with a loaded PDF; show stop - /// when playback is active. - private func updatePlaybackTransportVisibility() { - guard let sheet = sheetView, - let play = playButton, - let stop = stopButton else { return } - if !sheet.hasPlaybackEvents { - play.isHidden = true - stop.isHidden = true - return - } - let active = sheet.isPlaybackActive - play.isHidden = active - stop.isHidden = !active - } - @objc private func midiSwitchToggled(_ sender: NSSwitch) { // Just toggle — don't run the heavy syncFromController. The switch // already shows the user's intent; the loopback test (skipped on diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopoverPanel.swift b/slab/menuband/Sources/MenuBand/MenuBandPopoverPanel.swift index bfe037dc68..7bb45f1186 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopoverPanel.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopoverPanel.swift @@ -101,7 +101,14 @@ final class MenuBandPopoverPanel: NSPanel { } final class MenuBandPopoverChrome: NSView { - private let visualEffect = NSVisualEffectView() + /// The single backdrop surface for the whole popover (body + arrow). + /// On macOS 26 this is a real liquid-glass `NSGlassEffectView`; on + /// older systems it falls back to the `.popover` `NSVisualEffectView`. + /// Either way a `CAShapeLayer` mask carves the popover silhouette so + /// the surface flows continuously from the arrow tip into the body. + private let backdrop: NSView + /// Non-nil only on the legacy (pre-26) path, for appearance re-tints. + private let legacyVisualEffect: NSVisualEffectView? private let content: NSView private let maskLayer = CAShapeLayer() private var arrowOffsetFromLeft: CGFloat = MenuBandPopoverPanel.cornerRadius @@ -109,29 +116,38 @@ final class MenuBandPopoverChrome: NSView { init(content: NSView) { self.content = content + // Prefer the dedicated liquid-glass view when the platform (and + // the user's style override) allow it; otherwise the classic + // vibrancy material. + if PianoWaveformWindowStyle.shouldUseLiquidGlass, #available(macOS 26.0, *) { + let glass = NSGlassEffectView() + glass.style = .clear + self.backdrop = glass + self.legacyVisualEffect = nil + } else { + let ve = NSVisualEffectView() + ve.material = .popover + ve.blendingMode = .behindWindow + ve.state = .active + self.backdrop = ve + self.legacyVisualEffect = ve + } super.init(frame: .zero) wantsLayer = true layer?.masksToBounds = false - // The whole panel area (body + arrow) is one continuous - // visual-effect view. A CAShapeLayer mask carves out the - // popover silhouette, so the liquid-glass material flows from - // the arrow tip down into the body without a seam. - visualEffect.material = .popover - visualEffect.blendingMode = .behindWindow - visualEffect.state = .active - visualEffect.wantsLayer = true - visualEffect.translatesAutoresizingMaskIntoConstraints = false - addSubview(visualEffect) + backdrop.wantsLayer = true + backdrop.translatesAutoresizingMaskIntoConstraints = false + addSubview(backdrop) content.translatesAutoresizingMaskIntoConstraints = false addSubview(content) NSLayoutConstraint.activate([ - visualEffect.leadingAnchor.constraint(equalTo: leadingAnchor), - visualEffect.trailingAnchor.constraint(equalTo: trailingAnchor), - visualEffect.topAnchor.constraint(equalTo: topAnchor), - visualEffect.bottomAnchor.constraint(equalTo: bottomAnchor), + backdrop.leadingAnchor.constraint(equalTo: leadingAnchor), + backdrop.trailingAnchor.constraint(equalTo: trailingAnchor), + backdrop.topAnchor.constraint(equalTo: topAnchor), + backdrop.bottomAnchor.constraint(equalTo: bottomAnchor), // Content sits in the body region (below the arrow strip). content.leadingAnchor.constraint(equalTo: leadingAnchor), content.trailingAnchor.constraint(equalTo: trailingAnchor), @@ -141,23 +157,24 @@ final class MenuBandPopoverChrome: NSView { content.bottomAnchor.constraint(equalTo: bottomAnchor), ]) - visualEffect.layer?.mask = maskLayer + backdrop.layer?.mask = maskLayer } - /// Force the underlying NSVisualEffectView to re-tint against - /// the current effective appearance. AppDelegate calls this - /// from `systemAppearanceChanged()` because NSVisualEffectView - /// can latch on to the appearance present at construction time - /// — without this nudge, the popover's "popover" material - /// keeps showing the old light tint after a system flip. + /// Force the legacy NSVisualEffectView to re-tint against the + /// current effective appearance. AppDelegate calls this from + /// `systemAppearanceChanged()` because NSVisualEffectView can latch + /// on to the appearance present at construction time — without this + /// nudge, the popover's "popover" material keeps showing the old + /// tint after a system flip. The liquid-glass view re-tints itself, + /// so this is a no-op on the macOS 26 path. func refreshAppearance() { - visualEffect.appearance = nil - // Toggling the state forces AppKit to rebuild the - // material's CALayer backing, picking up the new - // effectiveAppearance as a side-effect. - visualEffect.state = .inactive - visualEffect.state = .active - visualEffect.needsDisplay = true + guard let ve = legacyVisualEffect else { needsDisplay = true; return } + ve.appearance = nil + // Toggling the state forces AppKit to rebuild the material's + // CALayer backing, picking up the new effectiveAppearance. + ve.state = .inactive + ve.state = .active + ve.needsDisplay = true needsDisplay = true } diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift index 7792d6a707..a7915cb80b 100644 --- a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift @@ -29,6 +29,10 @@ final class CollapsedPianoWaveformView: NSView { /// the user can see which physical keys play which notes while /// the chooser is open. Lit cells reflect held keys. private let qwertyMap = QwertyLayoutView() + /// Solid recessed "ground" behind the QWERTY map so the keymap + /// reads as a seated plate rather than floating glyphs on the + /// glass. Mirrors the instrument grid's housing fill + hairline. + private let qwertyBackground = NSView() /// Four-arrow cluster below the chooser — preview while held, /// commit on release. Mirrors the popover's old arrows hint /// position (under the keyboard) one level down. @@ -59,6 +63,8 @@ final class CollapsedPianoWaveformView: NSView { private static let edgePadding: CGFloat = 6 private static let gridPadding: CGFloat = 7 private static let rowGap: CGFloat = 4 + /// Padding between the QWERTY map and its recessed ground plate. + private static let qwertyGroundInset: CGFloat = 5 private static let modeRowTopGap: CGFloat = 14 /// Reserved at the top — hosts the chord-candidate row above /// the chooser. 30pt fits the FloatingChordCandidateCard's @@ -68,8 +74,16 @@ final class CollapsedPianoWaveformView: NSView { /// under the bottom-leading fullscreen toggle button. private static let bottomInset: CGFloat = 12 - init(menuBand: MenuBandController) { + /// When true the cluster paints NO panel surface of its own (no + /// liquid-glass backdrop, no opaque fallback fill) — it's being + /// hosted inside another glass surface (the v1 popover) and a second + /// backdrop would read as two stacked sheets. Only the grid's own + /// recessed housing remains. + private let embedded: Bool + + init(menuBand: MenuBandController, embedded: Bool = false) { self.menuBand = menuBand + self.embedded = embedded super.init(frame: .zero) wantsLayer = true layer?.cornerRadius = 10 @@ -84,6 +98,14 @@ final class CollapsedPianoWaveformView: NSView { instrumentGridContainer.layer?.cornerCurve = .continuous } + qwertyBackground.translatesAutoresizingMaskIntoConstraints = false + qwertyBackground.wantsLayer = true + qwertyBackground.layer?.cornerRadius = 8 + qwertyBackground.layer?.masksToBounds = true + if #available(macOS 10.15, *) { + qwertyBackground.layer?.cornerCurve = .continuous + } + instrumentList.menuBand = menuBand instrumentList.translatesAutoresizingMaskIntoConstraints = false instrumentList.onCommit = { [weak self] prog in @@ -207,11 +229,14 @@ final class CollapsedPianoWaveformView: NSView { addSubview(contentContainer) contentContainer.addSubview(instrumentGridContainer) instrumentGridContainer.addSubview(instrumentList) + contentContainer.addSubview(qwertyBackground) // behind the keymap contentContainer.addSubview(qwertyMap) contentContainer.addSubview(arrowsCluster) contentContainer.addSubview(instrumentReadoutLabel) contentContainer.addSubview(modeStack) - installLiquidGlassBackgrounds() + // [v1] Skip our own glass backdrop when embedded in the popover's + // glass surface — otherwise the two stack into a doubled sheet. + if !embedded { installLiquidGlassBackgrounds() } // Panel widens to fit either the chooser or the keyboard // row (qwerty + gap + arrows cluster), whichever is larger. @@ -241,6 +266,14 @@ final class CollapsedPianoWaveformView: NSView { constant: (totalWidth - QwertyLayoutView.intrinsicSize.width - Self.rowGap - arrowsClusterWidth) / 2 ), + // Recessed ground sits behind the keymap AND the arrow-key + // cluster to its right, inset a few points on each side so a + // hairline border frames the whole keyboard row as one plate. + qwertyBackground.leadingAnchor.constraint(equalTo: qwertyMap.leadingAnchor, constant: -Self.qwertyGroundInset), + qwertyBackground.trailingAnchor.constraint(equalTo: arrowsCluster.trailingAnchor, constant: Self.qwertyGroundInset), + qwertyBackground.topAnchor.constraint(equalTo: qwertyMap.topAnchor, constant: -Self.qwertyGroundInset), + qwertyBackground.bottomAnchor.constraint(equalTo: qwertyMap.bottomAnchor, constant: Self.qwertyGroundInset), + arrowsCluster.leadingAnchor.constraint(equalTo: qwertyMap.trailingAnchor, constant: Self.rowGap), arrowsCluster.bottomAnchor.constraint(equalTo: qwertyMap.bottomAnchor), arrowsCluster.heightAnchor.constraint(equalToConstant: Self.arrowsRowHeight), @@ -370,6 +403,11 @@ final class CollapsedPianoWaveformView: NSView { instrumentGridContainer.layer?.borderColor = NSColor.white.withAlphaComponent(isDark ? 0.16 : 0.22).cgColor instrumentGridContainer.layer?.borderWidth = 1.0 + qwertyBackground.layer?.backgroundColor = + NSColor.black.withAlphaComponent(isDark ? 0.26 : 0.10).cgColor + qwertyBackground.layer?.borderColor = + NSColor.white.withAlphaComponent(isDark ? 0.16 : 0.22).cgColor + qwertyBackground.layer?.borderWidth = 1.0 layer?.backgroundColor = NSColor.clear.cgColor } else { instrumentGridContainer.layer?.backgroundColor = @@ -377,10 +415,19 @@ final class CollapsedPianoWaveformView: NSView { instrumentGridContainer.layer?.borderColor = NSColor.separatorColor.withAlphaComponent(0.45).cgColor instrumentGridContainer.layer?.borderWidth = 1.0 + qwertyBackground.layer?.backgroundColor = + NSColor.windowBackgroundColor.withAlphaComponent(isDark ? 0.26 : 0.50).cgColor + qwertyBackground.layer?.borderColor = + NSColor.separatorColor.withAlphaComponent(0.45).cgColor + qwertyBackground.layer?.borderWidth = 1.0 layer?.backgroundColor = (isDark ? NSColor(white: 0.06, alpha: 0.96) : NSColor(white: 0.88, alpha: 0.96)).cgColor } + // [v1] Embedded in the popover's glass — never paint our own panel + // fill; let the single host surface show through. (The grid's + // recessed housing above stays for legibility.) + if embedded { layer?.backgroundColor = NSColor.clear.cgColor } } /// Mirror of `ExpandedPianoWaveformView.updateInstrumentReadout` diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift index d1c3f28252..811c6ed19a 100644 --- a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift @@ -42,6 +42,13 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { private var hideWorkItem: DispatchWorkItem? private var isEnabled: Bool + /// [v1] The floating piano window is retired — its content folded + /// into the popover (single column). Every present-the-panel entry + /// point bails on this flag so the window never appears, while the + /// delegate object + its callbacks stay intact so AppDelegate's + /// many call sites keep compiling. Flip to false to revive it. + static let retiredForV1 = true + private static let expandedOriginXKey = "notepat.unifiedPalette.expandedOriginX" private static let expandedOriginYKey = "notepat.unifiedPalette.expandedOriginY" private static let collapsedOriginXKey = "notepat.unifiedPalette.collapsedOriginX" @@ -148,6 +155,7 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { } func toggleFromShortcut() { + if Self.retiredForV1 { return } if isEnabled { disable(reason: .shortcut) return @@ -156,10 +164,12 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { } func showFromCommand(restoringTo previousApp: NSRunningApplication? = nil) { + if Self.retiredForV1 { return } enableAndShowPreferred(restoringTo: previousApp) } func show(restoringTo previousApp: NSRunningApplication? = nil) { + if Self.retiredForV1 { return } enableAndShowPreferred(restoringTo: previousApp) } @@ -168,6 +178,7 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { /// the expanded panel is what the user sees, not the collapsed /// strip (which has no chooser). func showExpandedForPopover(restoringTo previousApp: NSRunningApplication? = nil) { + if Self.retiredForV1 { return } setEnabled(true) cancelPendingHide() hoverPresented = false // popover is driving now, not hover @@ -182,6 +193,7 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { /// The user's saved preferred state is left untouched so a /// standalone open later still honors it. func showCollapsedForPopover() { + if Self.retiredForV1 { return } setEnabled(true) cancelPendingHide() hoverPresented = false // popover is driving now, not hover @@ -245,6 +257,7 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { } func showIfNeeded() { + if Self.retiredForV1 { return } guard presentationState == .collapsed, !isCollapsedPresentationSuppressed, isEnabled, preferredPresentationState == .collapsed else { return } cancelPendingHide() if panel == nil { @@ -275,6 +288,7 @@ final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { /// preferred state, and it bows out while the popover or the /// expanded view is driving the panel so it can't fight them. func showFromHover() { + if Self.retiredForV1 { return } guard !isCollapsedPresentationSuppressed, popoverFrameProvider?() == nil else { return } if presentationState == .expanded, panel?.isVisible == true { return } // Already up because of hover → just keep it up. -- knotmirror 0.0.1