From 2816b6f9fb22e97820dffcff0713bc2ab9de68a3 Mon Sep 17 00:00:00 2001 From: Esteban Uribe Date: Thu, 30 Apr 2026 12:45:08 -0700 Subject: [PATCH] Refine floating palette shortcuts and layout Add a palette-specific keyboard renderer layout so the floating piano no longer keeps the menu bar's left-side negative space. Wire focused floating-palette keyboard handling so the focus shortcut exits cleanly back to the prior app, add a keyboard layout toggle shortcut, and surface the shortcut hints in the palette UI. --- .../Sources/MenuBand/AppDelegate.swift | 170 ++++- .../MenuBand/FloatingPlayPalette.swift | 720 ++++++++++++++++++ .../MenuBand/KeyboardIconRenderer.swift | 85 ++- .../Sources/MenuBand/MenuBandShortcut.swift | 40 +- .../Sources/MenuBand/NoteExpression.swift | 25 + 5 files changed, 1001 insertions(+), 39 deletions(-) create mode 100644 slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift create mode 100644 slab/menuband/Sources/MenuBand/NoteExpression.swift diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index 4255a09195..d06d04345c 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -9,8 +9,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private var trackingArea: NSTrackingArea? private var typeModeHotkey: GlobalHotkey? private var focusCaptureHotkey: GlobalHotkey? + private var playPaletteHotkey: GlobalHotkey? + private var layoutToggleHotkey: GlobalHotkey? private let popover = NSPopover() private var popoverVC: MenuBandPopoverViewController? + private lazy var floatingPlayPalette = FloatingPlayPaletteController(menuBand: menuBand) + private var appBeforePopover: NSRunningApplication? private var appBeforeFocusCapture: NSRunningApplication? private var focusCaptureArmedByShortcut = false @@ -109,6 +113,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.kickIconAnim(slide: dir, flash: 1.0) } self.updateIcon() + self.floatingPlayPalette.refresh() // Refresh the popover too so live state changes // (octave shift via , / . , MIDI mode flip, etc.) // reflect immediately while the popover is open. @@ -129,8 +134,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.lastLitCount = cur self.updateIcon() self.popoverVC?.refreshHeldNotes() + self.floatingPlayPalette.refresh() } menuBand.bootstrap() + floatingPlayPalette.onDismiss = { [weak self] in + self?.updateIcon() + self?.popoverVC?.syncFromController() + } + floatingPlayPalette.isPianoFocusActive = { [weak self] in + self?.localCapture.isArmed ?? false + } + floatingPlayPalette.onFocusRelease = { [weak self] in + self?.finishFloatingPaletteKeyboardFocus() + } + floatingPlayPalette.onToggleKeymap = { [weak self] in + self?.toggleKeyboardLayoutShortcut() + } statusItem = NSStatusBar.system.statusItem(withLength: KeyboardIconRenderer.imageSize.width) debugLog("statusItem created, button=\(statusItem.button != nil) length=\(statusItem.length)") @@ -161,6 +180,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { registerTypeModeHotkey() _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) + _ = registerPlayPaletteHotkey(MenuBandShortcutPreferences.playPaletteShortcut) + registerLayoutToggleHotkey() // Dev affordance: post the // `computer.aestheticcomputer.menuband.showPopover` @@ -186,6 +207,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.localCapture.disarm(reason: .cancelled) return true } + if isDown && MenuBandShortcut.layoutToggle.matches( + keyCode: UInt32(keyCode), + modifiers: MenuBandShortcut.carbonModifiers(from: flags) + ) { + self.toggleKeyboardLayoutShortcut() + return true + } let consumed = self.menuBand.handleLocalKey( keyCode: keyCode, isDown: isDown, isRepeat: isRepeat, flags: flags ) @@ -218,6 +246,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { vc.onFocusShortcutRecordingChanged = { [weak self] isRecording in self?.setShortcutRecording(isRecording) } + vc.onPlayPaletteToggle = { [weak self] in + self?.togglePlayPaletteFromCommand() + } + vc.onPlayPaletteShortcutChange = { [weak self] shortcut in + self?.applyPlayPaletteShortcut(shortcut) ?? false + } + vc.onPlayPaletteShortcutRecordingChanged = { [weak self] isRecording in + self?.setShortcutRecording(isRecording) + } + vc.isPlayPaletteShown = { [weak self] in + self?.floatingPlayPalette.isShown ?? false + } popoverVC = vc popover.contentViewController = vc // .applicationDefined: never auto-close. We manage closing manually @@ -257,6 +297,36 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } + private func registerLayoutToggleHotkey() { + let hotkey = GlobalHotkey( + signature: OSType(0x4D424C54), // 'MBLT' + id: 1 + ) { [weak self] in + self?.toggleKeyboardLayoutShortcut() + } + if hotkey.register( + keyCode: MenuBandShortcut.layoutToggle.keyCode, + modifiers: MenuBandShortcut.layoutToggle.modifiers + ) { + layoutToggleHotkey = hotkey + } + } + + @discardableResult + private func registerPlayPaletteHotkey(_ shortcut: MenuBandShortcut) -> Bool { + let hotkey = GlobalHotkey( + signature: OSType(0x4D425050), // 'MBPP' + id: 1 + ) { [weak self] in + self?.togglePlayPaletteFromShortcut() + } + guard hotkey.register(keyCode: shortcut.keyCode, modifiers: shortcut.modifiers) else { + return false + } + playPaletteHotkey = hotkey + return true + } + @discardableResult private func registerFocusCaptureHotkey(_ shortcut: MenuBandShortcut) -> Bool { let hotkey = GlobalHotkey( @@ -274,7 +344,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } private func applyFocusShortcut(_ shortcut: MenuBandShortcut) -> Bool { - guard shortcut.isValidForRecording, !shortcut.isReservedForTypeMode else { + guard shortcut.isValidForRecording, + !shortcut.isReservedForTypeMode, + shortcut != MenuBandShortcutPreferences.playPaletteShortcut else { return false } let previous = MenuBandShortcutPreferences.focusShortcut @@ -288,21 +360,76 @@ final class AppDelegate: NSObject, NSApplicationDelegate { return true } + private func applyPlayPaletteShortcut(_ shortcut: MenuBandShortcut) -> Bool { + guard shortcut.isValidForRecording, + !shortcut.isReservedForTypeMode, + shortcut != MenuBandShortcutPreferences.focusShortcut else { + return false + } + let previous = MenuBandShortcutPreferences.playPaletteShortcut + playPaletteHotkey?.unregister() + playPaletteHotkey = nil + guard registerPlayPaletteHotkey(shortcut) else { + _ = registerPlayPaletteHotkey(previous) + return false + } + MenuBandShortcutPreferences.playPaletteShortcut = shortcut + return true + } + private func setShortcutRecording(_ isRecording: Bool) { if isRecording { typeModeHotkey?.unregister() typeModeHotkey = nil focusCaptureHotkey?.unregister() focusCaptureHotkey = nil + playPaletteHotkey?.unregister() + playPaletteHotkey = nil + layoutToggleHotkey?.unregister() + layoutToggleHotkey = nil } else { if typeModeHotkey == nil { registerTypeModeHotkey() } if focusCaptureHotkey == nil { _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) } + if playPaletteHotkey == nil { + _ = registerPlayPaletteHotkey(MenuBandShortcutPreferences.playPaletteShortcut) + } + if layoutToggleHotkey == nil { registerLayoutToggleHotkey() } + } + } + + private func togglePlayPaletteFromShortcut() { + if floatingPlayPalette.isShown { + floatingPlayPalette.toggleFromShortcut() + return + } + beginFloatingPlayPalette() + floatingPlayPalette.toggleFromShortcut() + } + + private func togglePlayPaletteFromCommand() { + let appToRestore = appBeforePopover + beginFloatingPlayPalette() + appBeforePopover = nil + floatingPlayPalette.showFromCommand(restoringTo: appToRestore) + } + + private func beginFloatingPlayPalette() { + closePopover() + if localCapture.isArmed { + localCapture.disarm(reason: .resignedKey) + } + if menuBand.typeMode { + menuBand.disableTypeModeForFocusCapture() } } private func toggleFocusCaptureFromShortcut() { + if floatingPlayPalette.isKeyboardFocused { + finishFloatingPaletteKeyboardFocus() + return + } if localCapture.isArmed, focusCaptureArmedByShortcut { localCapture.disarm(reason: .cancelled) return @@ -324,6 +451,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { focusCaptureArmedByShortcut = true localCapture.arm() updateIcon() + floatingPlayPalette.refresh() } private func finishLocalCapture(reason: LocalKeyCapture.EndReason) { @@ -334,6 +462,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { ghostRefreshTimer?.invalidate() ghostRefreshTimer = nil updateIcon() + floatingPlayPalette.refresh() if shouldRestoreFocus { restorePreviousAppFocus() } @@ -347,6 +476,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { app.activate(options: [.activateIgnoringOtherApps]) } + private func finishFloatingPaletteKeyboardFocus() { + menuBand.releaseAllHeldNotes() + floatingPlayPalette.clearInteraction() + floatingPlayPalette.releaseKeyboardFocus() + updateIcon() + floatingPlayPalette.refresh() + } + + private func toggleKeyboardLayoutShortcut() { + menuBand.keymap = (menuBand.keymap == .ableton) ? .notepat : .ableton + } + // MARK: - Adaptive menubar layout /// `true` when the status item button is laid out on a real screen. @@ -427,6 +568,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } func applicationWillTerminate(_ notification: Notification) { + floatingPlayPalette.dismiss(reason: .programmatic) menuBand.shutdown() } @@ -799,7 +941,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } let initialPt = imagePoint(from: downEvent.locationInWindow) - let (vel0, pan0) = expression(for: startNote, at: initialPt) + let (vel0, pan0) = NoteExpression.values(for: startNote, at: initialPt) menuBand.startTapNote(startNote, velocity: vel0, pan: pan0) // Arm sandbox-friendly local capture on a real piano click. We // skip arming when global TYPE mode is already on — the global @@ -809,6 +951,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // when you're just tapping the piano with the mouse. if !menuBand.typeMode { localCapture.arm() + floatingPlayPalette.refresh() } var current: UInt8? = startNote while let next = NSApp.nextEvent( @@ -826,31 +969,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate { if hovered != current { if let prev = current { menuBand.stopTapNote(prev) } if let nxt = hovered { - let (v, p) = expression(for: nxt, at: pt) + let (v, p) = NoteExpression.values(for: nxt, at: pt) menuBand.startTapNote(nxt, velocity: v, pan: p) } current = hovered } else if let c = current { - let (_, p) = expression(for: c, at: pt) + let (_, p) = NoteExpression.values(for: c, at: pt) menuBand.updateTapPan(c, pan: p) } } } - private func expression(for midiNote: UInt8, at pt: NSPoint) -> (UInt8, UInt8) { - guard let rect = KeyboardIconRenderer.keyRect(for: midiNote) else { - return (100, 64) - } - let xRel = max(0, min(1, (pt.x - rect.minX) / rect.width)) - let yRel = max(0, min(1, (pt.y - rect.minY) / rect.height)) - let pan = UInt8(max(0, min(127, Int(round(xRel * 127))))) - let yDist = abs(yRel - 0.5) * 2.0 - let vMin: Double = 60, vMax: Double = 120 - let vel = vMax - (vMax - vMin) * yDist - let velocity = UInt8(max(1, min(127, Int(round(vel))))) - return (velocity, pan) - } - // MARK: - Popover /// Close the popover and tear down the click-away monitor. Called from @@ -862,6 +991,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } if let m = clickAwayMonitor { NSEvent.removeMonitor(m); clickAwayMonitor = nil } if let m = popoverEscMonitor { NSEvent.removeMonitor(m); popoverEscMonitor = nil } + appBeforePopover = nil } /// Distributed-notification entry point for the dev affordance @@ -900,6 +1030,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // register immediately. NSStatusItem popovers don't pull focus // by default; without this you have to click into the popover // once before its controls react. + let frontmost = NSWorkspace.shared.frontmostApplication + appBeforePopover = frontmost?.bundleIdentifier == Bundle.main.bundleIdentifier + ? nil + : frontmost NSApp.activate(ignoringOtherApps: true) popover.show(relativeTo: anchor, of: button, preferredEdge: .minY) DispatchQueue.main.async { diff --git a/slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift b/slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift new file mode 100644 index 0000000000..99d6a25be4 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift @@ -0,0 +1,720 @@ +import AppKit + +final class FloatingPlayPaletteController: NSObject, NSWindowDelegate { + enum DismissReason { + case closeButton + case shortcut + case programmatic + + var shouldRestoreFocus: Bool { + switch self { + case .closeButton, .shortcut: + return true + case .programmatic: + return false + } + } + } + + private let menuBand: MenuBandController + private let viewController: FloatingPlayPaletteViewController + private var panel: FloatingPlayPalettePanel? + private var keyMonitor: Any? + private var appBeforeOpen: NSRunningApplication? + private var isDismissing = false + + var onDismiss: (() -> Void)? + var onFocusRelease: (() -> Void)? + var onToggleKeymap: (() -> Void)? + var isPianoFocusActive: (() -> Bool)? { + get { viewController.isPianoFocusActive } + set { viewController.isPianoFocusActive = newValue } + } + + var isShown: Bool { + panel?.isVisible == true + } + + init(menuBand: MenuBandController) { + self.menuBand = menuBand + self.viewController = FloatingPlayPaletteViewController(menuBand: menuBand) + super.init() + self.viewController.onClose = { [weak self] in + self?.dismiss(reason: .closeButton) + } + } + + func toggleFromShortcut() { + if isShown { + dismiss(reason: .shortcut) + } else { + show() + } + } + + func showFromCommand(restoringTo previousApp: NSRunningApplication? = nil) { + show(restoringTo: previousApp) + } + + func show(restoringTo previousApp: NSRunningApplication? = nil) { + if panel == nil { buildPanel() } + guard let panel = panel else { return } + + if panel.isVisible { + panel.makeKeyAndOrderFront(nil) + return + } + + appBeforeOpen = previousApp ?? currentFrontmostOtherApp() + viewController.refresh() + panel.setFrame(frameForCurrentMouseScreen(size: viewController.preferredContentSize), display: false) + + NSApp.activate(ignoringOtherApps: true) + panel.makeKeyAndOrderFront(nil) + viewController.setPresented(true) + installMonitors() + } + + func dismiss(reason: DismissReason = .programmatic) { + guard !isDismissing else { return } + guard isShown || keyMonitor != nil else { return } + + isDismissing = true + removeMonitors() + viewController.setPresented(false) + viewController.clearInteraction() + menuBand.releaseAllHeldNotes() + panel?.orderOut(nil) + onDismiss?() + if reason.shouldRestoreFocus { + restorePreviousAppFocus() + } + appBeforeOpen = nil + isDismissing = false + } + + func refresh() { + guard isShown else { return } + viewController.refresh() + resizePanelToCurrentContent() + } + + func clearInteraction() { + viewController.clearInteraction() + } + + var isKeyboardFocused: Bool { + panel?.isKeyWindow == true + } + + func releaseKeyboardFocus() { + guard isShown else { return } + restorePreviousAppFocus() + } + + private func buildPanel() { + let p = FloatingPlayPalettePanel( + contentRect: NSRect(origin: .zero, size: viewController.preferredContentSize), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + p.contentViewController = viewController + p.delegate = self + p.isOpaque = false + p.backgroundColor = .clear + p.hasShadow = true + p.level = .floating + p.animationBehavior = .none + p.collectionBehavior = [.transient] + p.hidesOnDeactivate = false + p.canHide = false + p.isMovableByWindowBackground = false + p.acceptsMouseMovedEvents = true + panel = p + } + + private func installMonitors() { + if keyMonitor == nil { + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp]) { [weak self] event in + guard let self = self, self.panel?.isKeyWindow == true else { return event } + let isDown = event.type == .keyDown + if isDown && event.keyCode == 53 /* kVK_Escape */ { + self.onFocusRelease?() + return nil + } + if isDown && MenuBandShortcutPreferences.focusShortcut.matches(event: event) { + self.onFocusRelease?() + return nil + } + if isDown && MenuBandShortcut.layoutToggle.matches(event: event) { + self.onToggleKeymap?() + return nil + } + let consumed = self.menuBand.handleLocalKey( + keyCode: event.keyCode, + isDown: isDown, + isRepeat: event.isARepeat, + flags: event.modifierFlags + ) + if consumed { + self.refresh() + return nil + } + return event + } + } + } + + private func removeMonitors() { + if let m = keyMonitor { + NSEvent.removeMonitor(m) + keyMonitor = nil + } + } + + private func resizePanelToCurrentContent() { + guard let panel = panel, panel.isVisible else { return } + let size = viewController.preferredContentSize + let old = panel.frame + guard abs(old.width - size.width) > 0.5 || abs(old.height - size.height) > 0.5 else { return } + let center = NSPoint(x: old.midX, y: old.midY) + var frame = NSRect( + x: center.x - size.width / 2, + y: center.y - size.height / 2, + width: size.width, + height: size.height + ) + let visible = (panel.screen ?? NSScreen.main)?.visibleFrame + ?? NSRect(x: 0, y: 0, width: 1024, height: 768) + frame = clamped(frame, to: visible) + panel.setFrame(frame, display: true) + } + + private func frameForCurrentMouseScreen(size: NSSize) -> NSRect { + let mouse = NSEvent.mouseLocation + let screen = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) } + ?? NSScreen.main + ?? NSScreen.screens.first + let visible = screen?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1024, height: 768) + let margin: CGFloat = 16 + let preferred = NSPoint( + x: visible.midX - size.width / 2, + y: visible.midY + visible.height * 0.12 - size.height / 2 + ) + let x = min(max(preferred.x, visible.minX + margin), visible.maxX - size.width - margin) + let y = min(max(preferred.y, visible.minY + margin), visible.maxY - size.height - margin) + return NSRect(origin: NSPoint(x: x, y: y), size: size) + } + + private func clamped(_ frame: NSRect, to visible: NSRect) -> NSRect { + let margin: CGFloat = 16 + let x = min(max(frame.origin.x, visible.minX + margin), visible.maxX - frame.width - margin) + let y = min(max(frame.origin.y, visible.minY + margin), visible.maxY - frame.height - margin) + return NSRect(origin: NSPoint(x: x, y: y), size: frame.size) + } + + private func currentFrontmostOtherApp() -> NSRunningApplication? { + let frontmost = NSWorkspace.shared.frontmostApplication + guard frontmost?.bundleIdentifier != Bundle.main.bundleIdentifier else { return nil } + return frontmost + } + + private func restorePreviousAppFocus() { + guard let app = appBeforeOpen, + !app.isTerminated, + app.bundleIdentifier != Bundle.main.bundleIdentifier else { return } + app.activate(options: [.activateIgnoringOtherApps]) + } + + deinit { + dismiss(reason: .programmatic) + } +} + +private final class FloatingPlayPaletteViewController: NSViewController { + private let paletteView: FloatingPlayPaletteView + var onClose: (() -> Void)? { + get { paletteView.onClose } + set { paletteView.onClose = newValue } + } + var isPianoFocusActive: (() -> Bool)? { + get { paletteView.isPianoFocusActive } + set { paletteView.isPianoFocusActive = newValue } + } + + init(menuBand: MenuBandController) { + self.paletteView = FloatingPlayPaletteView(menuBand: menuBand) + super.init(nibName: nil, bundle: nil) + preferredContentSize = paletteView.fittingSize + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + override func loadView() { + view = paletteView + } + + func refresh() { + paletteView.refresh() + preferredContentSize = paletteView.fittingSize + } + + func clearInteraction() { + paletteView.clearInteraction() + } + + func setPresented(_ isPresented: Bool) { + paletteView.setPresented(isPresented) + } +} + +private final class FloatingPlayPaletteView: NSView { + private weak var menuBand: MenuBandController? + private let waveformView = WaveformView() + private let pianoView: FloatingPianoView + private let dragHandle = FloatingPaletteDragHandleView() + private let closeButton = NSButton() + private let shortcutHintLabel = NSTextField(labelWithString: "") + + var onClose: (() -> Void)? + var isPianoFocusActive: (() -> Bool)? + + private let pianoScale: CGFloat = 2.0 + private let inset: CGFloat = 14 + private let gap: CGFloat = 8 + private let closeSize: CGFloat = 18 + private let hintHeight: CGFloat = 42 + private var waveformHeightConstraint: NSLayoutConstraint? + + init(menuBand: MenuBandController) { + self.menuBand = menuBand + self.pianoView = FloatingPianoView(menuBand: menuBand, pianoScale: pianoScale) + super.init(frame: NSRect(origin: .zero, size: .zero)) + wantsLayer = true + + waveformView.menuBand = menuBand + waveformView.translatesAutoresizingMaskIntoConstraints = false + pianoView.translatesAutoresizingMaskIntoConstraints = false + dragHandle.translatesAutoresizingMaskIntoConstraints = false + closeButton.translatesAutoresizingMaskIntoConstraints = false + shortcutHintLabel.translatesAutoresizingMaskIntoConstraints = false + addSubview(waveformView) + addSubview(pianoView) + shortcutHintLabel.font = NSFont.systemFont(ofSize: 10) + shortcutHintLabel.textColor = .secondaryLabelColor + shortcutHintLabel.alignment = .center + shortcutHintLabel.maximumNumberOfLines = 2 + shortcutHintLabel.lineBreakMode = .byWordWrapping + addSubview(shortcutHintLabel) + addSubview(dragHandle) + updateShortcutHint() + + let closeConfig = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold) + closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close")? + .withSymbolConfiguration(closeConfig) + closeButton.isBordered = false + closeButton.imagePosition = .imageOnly + closeButton.contentTintColor = .secondaryLabelColor + closeButton.toolTip = "Close" + closeButton.target = self + closeButton.action = #selector(closeClicked(_:)) + addSubview(closeButton) + + let keyboardSize = self.keyboardSize() + let waveformHeightConstraint = waveformView.heightAnchor.constraint( + equalToConstant: waveformHeight(for: keyboardSize) + ) + self.waveformHeightConstraint = waveformHeightConstraint + + NSLayoutConstraint.activate([ + widthAnchor.constraint(equalToConstant: keyboardSize.width + inset * 2), + + closeButton.topAnchor.constraint(equalTo: topAnchor, constant: inset), + closeButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset), + closeButton.widthAnchor.constraint(equalToConstant: closeSize), + closeButton.heightAnchor.constraint(equalToConstant: closeSize), + + dragHandle.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset), + dragHandle.trailingAnchor.constraint(equalTo: closeButton.leadingAnchor, constant: -gap), + dragHandle.centerYAnchor.constraint(equalTo: closeButton.centerYAnchor), + dragHandle.heightAnchor.constraint(equalToConstant: closeSize), + + waveformView.topAnchor.constraint(equalTo: closeButton.bottomAnchor, constant: gap), + waveformView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset), + waveformView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset), + waveformHeightConstraint, + + pianoView.topAnchor.constraint(equalTo: waveformView.bottomAnchor, constant: gap), + pianoView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset), + pianoView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset), + + shortcutHintLabel.topAnchor.constraint(equalTo: pianoView.bottomAnchor, constant: gap), + shortcutHintLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset), + shortcutHintLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset), + shortcutHintLabel.heightAnchor.constraint(equalToConstant: hintHeight), + shortcutHintLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -inset) + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + override var acceptsFirstResponder: Bool { true } + + override var fittingSize: NSSize { + pianoView.refreshLayout() + layoutSubtreeIfNeeded() + return super.fittingSize + } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + let background = bounds.insetBy(dx: 0.5, dy: 0.5) + let path = NSBezierPath(roundedRect: background, xRadius: 13, yRadius: 13) + NSColor.windowBackgroundColor.withAlphaComponent(0.96).setFill() + path.fill() + NSColor.separatorColor.withAlphaComponent(0.55).setStroke() + path.lineWidth = 1 + path.stroke() + } + + func refresh() { + updateShortcutHint() + let keyboardSize = keyboardSize() + waveformHeightConstraint?.constant = waveformHeight(for: keyboardSize) + pianoView.refreshLayout() + layoutSubtreeIfNeeded() + updateWaveformLiveState(isPresented: window?.isVisible == true) + needsDisplay = true + pianoView.needsDisplay = true + } + + func clearInteraction() { + pianoView.clearInteraction() + } + + func setPresented(_ isPresented: Bool) { + updateWaveformLiveState(isPresented: isPresented) + } + + private func updateWaveformLiveState(isPresented: Bool) { + waveformView.isLive = isPresented && !(menuBand?.midiMode ?? false) + waveformView.alphaValue = (menuBand?.midiMode ?? false) ? 0.35 : 1.0 + } + + private func keyboardSize() -> NSSize { + withFloatingPaletteKeyboard(menuBand: menuBand) { + let piano = KeyboardIconRenderer.pianoImageSize(layout: .tightActiveRange) + return NSSize(width: piano.width * pianoScale, height: piano.height * pianoScale) + } + } + + private func waveformHeight(for keyboard: NSSize) -> CGFloat { + keyboard.height * 2.0 + } + + private func updateShortcutHint() { + let floatingShortcut = MenuBandShortcutPreferences.playPaletteShortcut.displayString + let focusShortcut = MenuBandShortcutPreferences.focusShortcut.displayString + let layoutShortcut = MenuBandShortcut.layoutToggle.displayString + let focusText = (isPianoFocusActive?() ?? false) + ? "Exit focus: \(focusShortcut)" + : "Focus piano: \(focusShortcut)" + shortcutHintLabel.stringValue = + "Show/hide floating piano: \(floatingShortcut)\n\(focusText) Toggle layout: \(layoutShortcut)" + } + + @objc private func closeClicked(_ sender: NSButton) { + onClose?() + } +} + +private final class FloatingPianoView: NSView { + private static let rendererLayout: KeyboardIconRenderer.Layout = .tightActiveRange + + private weak var menuBand: MenuBandController? + private var trackingArea: NSTrackingArea? + private var hoveredNote: UInt8? + private var currentNote: UInt8? + + private let pianoScale: CGFloat + private var widthConstraint: NSLayoutConstraint! + private var heightConstraint: NSLayoutConstraint! + + init(menuBand: MenuBandController, pianoScale: CGFloat) { + self.menuBand = menuBand + self.pianoScale = pianoScale + super.init(frame: NSRect(origin: .zero, size: .zero)) + wantsLayer = true + + let preferredSize = preferredSize() + widthConstraint = widthAnchor.constraint(equalToConstant: preferredSize.width) + heightConstraint = heightAnchor.constraint(equalToConstant: preferredSize.height) + NSLayoutConstraint.activate([widthConstraint, heightConstraint]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + override var acceptsFirstResponder: Bool { true } + + func refreshLayout() { + let preferredSize = preferredSize() + widthConstraint.constant = preferredSize.width + heightConstraint.constant = preferredSize.height + } + + private func preferredSize() -> NSSize { + withFloatingPaletteKeyboard(menuBand: menuBand) { + let piano = KeyboardIconRenderer.pianoImageSize(layout: Self.rendererLayout) + return NSSize( + width: piano.width * pianoScale, + height: piano.height * pianoScale + ) + } + } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let trackingArea = trackingArea { + removeTrackingArea(trackingArea) + } + let area = NSTrackingArea( + rect: bounds, + options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], + owner: self, + userInfo: nil + ) + addTrackingArea(area) + trackingArea = area + } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + guard let menuBand = menuBand else { return } + + withFloatingPaletteKeyboard(menuBand: menuBand) { + KeyboardIconRenderer.activeKeymap = menuBand.keymap + let image = KeyboardIconRenderer.image( + litNotes: menuBand.litNotes, + enabled: menuBand.midiMode, + typeMode: true, + hovered: hoveredNote.map { .note($0) }, + includeSettings: false, + layout: Self.rendererLayout + ) + image.draw(in: pianoTargetRect()) + } + } + + override func mouseMoved(with event: NSEvent) { + updateHover(with: event) + } + + override func mouseExited(with event: NSEvent) { + if hoveredNote != nil { + hoveredNote = nil + needsDisplay = true + } + } + + override func mouseDown(with event: NSEvent) { + window?.makeKey() + guard let menuBand = menuBand, + let point = rendererPoint(from: event), + let note = withFloatingPaletteKeyboard( + menuBand: menuBand, + { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } + ) + else { return } + let expression = withFloatingPaletteKeyboard(menuBand: menuBand) { + NoteExpression.values(for: note, at: point, layout: Self.rendererLayout) + } + currentNote = note + hoveredNote = note + menuBand.startTapNote(note, velocity: expression.velocity, pan: expression.pan) + needsDisplay = true + } + + override func mouseDragged(with event: NSEvent) { + guard let menuBand = menuBand, + let point = rendererPoint(from: event) else { return } + let hovered = withFloatingPaletteKeyboard( + menuBand: menuBand, + { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } + ) + hoveredNote = hovered + + if hovered != currentNote { + if let previous = currentNote { + menuBand.stopTapNote(previous) + } + if let next = hovered { + let expression = withFloatingPaletteKeyboard(menuBand: menuBand) { + NoteExpression.values(for: next, at: point, layout: Self.rendererLayout) + } + menuBand.startTapNote(next, velocity: expression.velocity, pan: expression.pan) + } + currentNote = hovered + } else if let current = currentNote { + let expression = withFloatingPaletteKeyboard(menuBand: menuBand) { + NoteExpression.values(for: current, at: point, layout: Self.rendererLayout) + } + menuBand.updateTapPan(current, pan: expression.pan) + } + needsDisplay = true + } + + override func mouseUp(with event: NSEvent) { + if let note = currentNote { + menuBand?.stopTapNote(note) + } + currentNote = nil + updateHover(with: event) + } + + func clearInteraction() { + currentNote = nil + hoveredNote = nil + needsDisplay = true + } + + private func updateHover(with event: NSEvent) { + guard let point = rendererPoint(from: event) else { + if hoveredNote != nil { + hoveredNote = nil + needsDisplay = true + } + return + } + let next = withFloatingPaletteKeyboard( + menuBand: menuBand, + { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } + ) + if next != hoveredNote { + hoveredNote = next + needsDisplay = true + } + } + + private func rendererPoint(from event: NSEvent) -> NSPoint? { + let local = convert(event.locationInWindow, from: nil) + let target = pianoTargetRect() + let point = NSPoint( + x: (local.x - target.minX) / pianoScale, + y: (local.y - target.minY) / pianoScale + ) + let piano = withFloatingPaletteKeyboard(menuBand: menuBand) { + KeyboardIconRenderer.pianoImageSize(layout: Self.rendererLayout) + } + guard point.x >= -KeyboardIconRenderer.whiteW, + point.x <= piano.width + KeyboardIconRenderer.whiteW, + point.y >= -piano.height, + point.y <= piano.height * 2 else { return nil } + return point + } + + private func pianoTargetRect() -> NSRect { + let piano = withFloatingPaletteKeyboard(menuBand: menuBand) { + KeyboardIconRenderer.pianoImageSize(layout: Self.rendererLayout) + } + let size = NSSize(width: piano.width * pianoScale, height: piano.height * pianoScale) + return NSRect( + x: bounds.midX - size.width / 2, + y: bounds.midY - size.height / 2, + width: size.width, + height: size.height + ) + } +} + +private final class FloatingPaletteDragHandleView: NSView { + private var dragStartMouse: NSPoint? + private var dragStartWindowOrigin: NSPoint? + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + let pan = NSPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) + addGestureRecognizer(pan) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + let gripWidth: CGFloat = 34 + let gripHeight: CGFloat = 3 + let grip = NSRect( + x: bounds.midX - gripWidth / 2, + y: bounds.midY - gripHeight / 2, + width: gripWidth, + height: gripHeight + ) + NSColor.tertiaryLabelColor.withAlphaComponent(0.55).setFill() + NSBezierPath(roundedRect: grip, xRadius: gripHeight / 2, yRadius: gripHeight / 2).fill() + } + + override func resetCursorRects() { + super.resetCursorRects() + addCursorRect(bounds, cursor: .openHand) + } + + @objc private func handlePan(_ recognizer: NSPanGestureRecognizer) { + switch recognizer.state { + case .began: + dragStartMouse = NSEvent.mouseLocation + dragStartWindowOrigin = window?.frame.origin + NSCursor.closedHand.set() + case .changed: + guard let window = window, + let startMouse = dragStartMouse, + let startOrigin = dragStartWindowOrigin else { return } + let mouse = NSEvent.mouseLocation + let nextOrigin = NSPoint( + x: startOrigin.x + mouse.x - startMouse.x, + y: startOrigin.y + mouse.y - startMouse.y + ) + NSAnimationContext.runAnimationGroup { context in + context.duration = 0 + context.allowsImplicitAnimation = false + window.setFrameOrigin(nextOrigin) + } + case .ended, .cancelled, .failed: + dragStartMouse = nil + dragStartWindowOrigin = nil + NSCursor.openHand.set() + default: + break + } + } +} + +private func withFloatingPaletteKeyboard(menuBand: MenuBandController?, _ body: () -> T) -> T { + let oldLayout = KeyboardIconRenderer.displayLayout + let oldKeymap = KeyboardIconRenderer.activeKeymap + KeyboardIconRenderer.displayLayout = .full + if let menuBand = menuBand { + KeyboardIconRenderer.activeKeymap = menuBand.keymap + } + defer { + KeyboardIconRenderer.displayLayout = oldLayout + KeyboardIconRenderer.activeKeymap = oldKeymap + } + return body() +} + +private final class FloatingPlayPalettePanel: NSPanel { + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { false } +} diff --git a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift index d3923a98f4..0ea1ac8601 100644 --- a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift +++ b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift @@ -10,6 +10,11 @@ import AppKit // buttons are flat (no fill, no border) so they read like native menubar // text. Keys are skeuomorphic: white gradient + dark-accent black gradient. enum KeyboardIconRenderer { + enum Layout { + case fixedCanvas + case tightActiveRange + } + /// Updated by AppDelegate.updateIcon() before each render so the renderer /// can pick the right letter labels and active-range without threading /// the keymap through every static method's signature. @@ -153,6 +158,16 @@ enum KeyboardIconRenderer { return NSSize(width: totalW, height: totalH) } + static var pianoImageSize: NSSize { + pianoImageSize(layout: .fixedCanvas) + } + + static func pianoImageSize(layout: Layout) -> NSSize { + 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 } /// Settings chip's visual rect IS its hit-test rect — they're identical @@ -166,11 +181,13 @@ enum KeyboardIconRenderer { hovered: HitResult? = nil, letterAlpha: ((UInt8) -> CGFloat)? = nil, slideOffsetX: CGFloat = 0, - settingsFlash: CGFloat = 0) -> NSImage { + settingsFlash: CGFloat = 0, + includeSettings: Bool = true, + layout: Layout = .fixedCanvas) -> NSImage { let whites = whiteList() var whiteIndex: [Int: Int] = [:] for (i, m) in whites.enumerated() { whiteIndex[m] = i } - let size = imageSize + let size = includeSettings ? imageSize : pianoImageSize(layout: layout) let img = NSImage(size: size, flipped: false) { _ in @@ -225,10 +242,10 @@ enum KeyboardIconRenderer { // corners. Active range may be right-aligned (Ableton) so the // outer corners sit on the first/last active white in the slot // layout, not the geometric ends of the render area. - let activeWhites = whites.filter { isActive($0) } + let activeWhites = activeWhites(layout: layout) let leftmostMidi = activeWhites.first ?? firstMidi let rightmostMidi = activeWhites.last ?? lastMidi - let slotOffset = activeSlotOffset + let slotOffset = slotOffset(layout: layout) for (idx, m) in whites.enumerated() { if !isActive(m) { continue } // negative space — skip draw let rect = whiteRect(at: idx + slotOffset) @@ -315,14 +332,16 @@ enum KeyboardIconRenderer { } NSGraphicsContext.restoreGraphicsState() - // Single settings chip — glyph + color reflect MIDI/DAW state. - // MIDI on → `waveform` tinted accent (signal flowing to DAW); - // MIDI off → `slider.horizontal.3` in label color (generic). - drawSettingsChip(in: settingsRect, hoverRect: settingsHitRect, - midiOn: enabled, - hovered: hovered == .openSettings, - flash: settingsFlash, - voiceNumber: Int(melodicProgram)) + if includeSettings { + // Single settings chip — glyph + color reflect MIDI/DAW state. + // MIDI on → `waveform` tinted accent (signal flowing to DAW); + // MIDI off → `slider.horizontal.3` in label color (generic). + drawSettingsChip(in: settingsRect, hoverRect: settingsHitRect, + midiOn: enabled, + hovered: hovered == .openSettings, + flash: settingsFlash, + voiceNumber: Int(melodicProgram)) + } return true } img.isTemplate = false @@ -341,7 +360,7 @@ 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 { - let leftX = pianoOriginX + pianoWidth + let leftX = pianoOriginX + pianoWidth(layout: .fixedCanvas) let rightX = imageSize.width return NSRect(x: leftX, y: 0, width: rightX - leftX, height: imageSize.height) } @@ -370,7 +389,7 @@ enum KeyboardIconRenderer { let whites = whiteList() var whiteIndex: [Int: Int] = [:] for (i, m) in whites.enumerated() { whiteIndex[m] = i } - let slotOffset = activeSlotOffset + let slotOffset = slotOffset(layout: .fixedCanvas) // Black-key hit area = the visual blackRect. 1:1 mapping with what // the user sees on screen — clicking on visible black triggers black, // clicking visible white triggers white. Inactive (negative-space) @@ -401,10 +420,10 @@ enum KeyboardIconRenderer { /// Public lookup so callers (drag handler) can compute cursor-relative /// expression — e.g. y→velocity, x→pan within the active key's bounds. - static func keyRect(for midi: UInt8) -> NSRect? { + static func keyRect(for midi: UInt8, layout: Layout = .fixedCanvas) -> NSRect? { let m = Int(midi) let whites = whiteList() - let slotOffset = activeSlotOffset + let slotOffset = slotOffset(layout: layout) if isWhite(m) { guard let idx = whites.firstIndex(of: m) else { return nil } return whiteRect(at: idx + slotOffset) @@ -420,11 +439,11 @@ enum KeyboardIconRenderer { /// can be anywhere); horizontally tolerates a small overshoot past the /// leftmost/rightmost white key so a drag rolling past the edge keeps /// the edge key sounding. - static func noteAt(_ point: NSPoint) -> UInt8? { + static func noteAt(_ point: NSPoint, layout: Layout = .fixedCanvas) -> UInt8? { let whites = whiteList() - let activeWhites = whites.filter { isActive($0) } + let activeWhites = activeWhites(layout: layout) guard !activeWhites.isEmpty else { return nil } - let slotOffset = activeSlotOffset + let slotOffset = slotOffset(layout: layout) // Active keys occupy slots [slotOffset, slotOffset + activeWhites.count - 1]. let leftEdge = pianoOriginX + CGFloat(slotOffset) * whiteW let rightEdge = pianoOriginX + CGFloat(slotOffset + activeWhites.count) * whiteW @@ -457,6 +476,34 @@ enum KeyboardIconRenderer { // MARK: - Layout helpers + private static func activeWhites(layout: Layout) -> [Int] { + let whites = whiteList() + switch layout { + case .fixedCanvas: + return whites.filter { isActive($0) } + case .tightActiveRange: + return whites.filter { isActive($0) } + } + } + + private static func slotOffset(layout: Layout) -> Int { + switch layout { + case .fixedCanvas: + return activeSlotOffset + case .tightActiveRange: + return 0 + } + } + + private static func pianoWidth(layout: Layout) -> CGFloat { + switch layout { + case .fixedCanvas: + return CGFloat(whiteList().count) * whiteW + case .tightActiveRange: + return CGFloat(activeWhites(layout: layout).count) * whiteW + } + } + private static func whiteRect(at index: Int) -> NSRect { let x = pianoOriginX + CGFloat(index) * whiteW return NSRect(x: x, y: pad, width: whiteW, height: whiteH) diff --git a/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift b/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift index a201dfb684..19ff70e2b6 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift @@ -10,11 +10,21 @@ struct MenuBandShortcut: Equatable { modifiers: UInt32(cmdKey | controlKey | optionKey) ) + static let defaultPlayPalette = MenuBandShortcut( + keyCode: UInt32(kVK_Space), + modifiers: UInt32(cmdKey | controlKey | optionKey) + ) + static let typeMode = MenuBandShortcut( keyCode: UInt32(kVK_ANSI_P), modifiers: UInt32(cmdKey | controlKey | optionKey) ) + static let layoutToggle = MenuBandShortcut( + keyCode: UInt32(kVK_ANSI_L), + modifiers: UInt32(cmdKey | controlKey | optionKey) + ) + var isValidForRecording: Bool { (modifiers & UInt32(cmdKey | controlKey | optionKey)) != 0 } @@ -33,8 +43,11 @@ struct MenuBandShortcut: Equatable { } func matches(event: NSEvent) -> Bool { - UInt32(event.keyCode) == keyCode && - Self.carbonModifiers(from: event.modifierFlags) == modifiers + matches(keyCode: UInt32(event.keyCode), modifiers: Self.carbonModifiers(from: event.modifierFlags)) + } + + func matches(keyCode: UInt32, modifiers: UInt32) -> Bool { + self.keyCode == keyCode && self.modifiers == modifiers } static func carbonModifiers(from flags: NSEvent.ModifierFlags) -> UInt32 { @@ -96,6 +109,8 @@ struct MenuBandShortcut: Equatable { enum MenuBandShortcutPreferences { private static let focusKeyCodeKey = "notepat.focusShortcut.keyCode" private static let focusModifiersKey = "notepat.focusShortcut.modifiers" + private static let playPaletteKeyCodeKey = "notepat.playPaletteShortcut.keyCode" + private static let playPaletteModifiersKey = "notepat.playPaletteShortcut.modifiers" static var focusShortcut: MenuBandShortcut { get { @@ -117,4 +132,25 @@ enum MenuBandShortcutPreferences { UserDefaults.standard.set(Int(newValue.modifiers), forKey: focusModifiersKey) } } + + static var playPaletteShortcut: MenuBandShortcut { + get { + let defaults = UserDefaults.standard + guard defaults.object(forKey: playPaletteKeyCodeKey) != nil, + defaults.object(forKey: playPaletteModifiersKey) != nil else { + return .defaultPlayPalette + } + let shortcut = MenuBandShortcut( + keyCode: UInt32(defaults.integer(forKey: playPaletteKeyCodeKey)), + modifiers: UInt32(defaults.integer(forKey: playPaletteModifiersKey)) + ) + return shortcut.isValidForRecording && !shortcut.isReservedForTypeMode + ? shortcut + : .defaultPlayPalette + } + set { + UserDefaults.standard.set(Int(newValue.keyCode), forKey: playPaletteKeyCodeKey) + UserDefaults.standard.set(Int(newValue.modifiers), forKey: playPaletteModifiersKey) + } + } } diff --git a/slab/menuband/Sources/MenuBand/NoteExpression.swift b/slab/menuband/Sources/MenuBand/NoteExpression.swift new file mode 100644 index 0000000000..627922fe4b --- /dev/null +++ b/slab/menuband/Sources/MenuBand/NoteExpression.swift @@ -0,0 +1,25 @@ +import AppKit + +enum NoteExpression { + static func values( + for midiNote: UInt8, + at point: NSPoint, + layout: KeyboardIconRenderer.Layout = .fixedCanvas + ) -> (velocity: UInt8, pan: UInt8) { + guard let rect = KeyboardIconRenderer.keyRect(for: midiNote, layout: layout) else { + return (100, 64) + } + return values(in: rect, at: point) + } + + private static func values(in rect: NSRect, at point: NSPoint) -> (velocity: UInt8, pan: UInt8) { + let xRel = max(0, min(1, (point.x - rect.minX) / rect.width)) + let yRel = max(0, min(1, (point.y - rect.minY) / rect.height)) + let pan = UInt8(max(0, min(127, Int(round(xRel * 127))))) + let yDist = abs(yRel - 0.5) * 2.0 + let vMin: Double = 60, vMax: Double = 120 + let vel = vMax - (vMax - vMin) * yDist + let velocity = UInt8(max(1, min(127, Int(round(vel))))) + return (velocity, pan) + } +} -- knotmirror 0.0.1