diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index aa42d10246..491bb4def2 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -13,9 +13,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private var layoutToggleHotkey: GlobalHotkey? private let popover = NSPopover() private var popoverVC: MenuBandPopoverViewController? - private lazy var pianoWaveformPalette = PianoWaveformPalette(menuBand: menuBand) - private var pianoWaveformOverlay: PianoWaveformPalette { pianoWaveformPalette } - private var pianoWaveformStrip: PianoWaveformPalette { pianoWaveformPalette } + private lazy var pianoWaveformWindowDelegate = PianoWaveformWindowDelegate(menuBand: menuBand) private var appBeforePopover: NSRunningApplication? private var appBeforeFocusCapture: NSRunningApplication? private var focusCaptureArmedByShortcut = false @@ -150,7 +148,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.kickIconAnim(slide: dir, flash: 1.0) } self.updateIcon() - self.pianoWaveformOverlay.refresh() + self.updatePianoWaveformWindow() // Refresh the popover too so live state changes // (octave shift via , / . , MIDI mode flip, etc.) // reflect immediately while the popover is open. @@ -171,32 +169,29 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.lastLitCount = cur self.updateIcon() self.popoverVC?.refreshHeldNotes() - self.pianoWaveformOverlay.refresh() - self.pianoWaveformStrip.refresh() - self.updateWaveformStrip() + self.updatePianoWaveformWindow() } menuBand.onInstrumentVisualChange = { [weak self] in DispatchQueue.main.async { guard let self = self else { return } self.updateIcon() - self.pianoWaveformOverlay.refresh() - self.pianoWaveformStrip.refreshAppearance() + self.updatePianoWaveformWindow() } } menuBand.bootstrap() lastKnownOctaveShift = menuBand.octaveShift - pianoWaveformOverlay.onDismiss = { [weak self] in + pianoWaveformWindowDelegate.onDismiss = { [weak self] in self?.updateIcon() self?.popoverVC?.syncFromController() - self?.updateWaveformStripSuppression() + self?.updatePianoWaveformWindowSuppression() } - pianoWaveformOverlay.isPianoFocusActive = { [weak self] in + pianoWaveformWindowDelegate.isPianoFocusActive = { [weak self] in self?.localCapture.isArmed ?? false } - pianoWaveformOverlay.onFocusRelease = { [weak self] in + pianoWaveformWindowDelegate.onFocusRelease = { [weak self] in self?.finishPianoWaveformKeyboardFocus() } - pianoWaveformOverlay.onToggleKeymap = { [weak self] in + pianoWaveformWindowDelegate.onToggleKeymap = { [weak self] in self?.toggleKeyboardLayoutShortcut() } @@ -229,20 +224,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // Pre-build the waveform strip panel so the first note press // doesn't stall on panel + Metal pipeline construction. - pianoWaveformStrip.reposition(statusItemButton: statusItem.button) - pianoWaveformStrip.onStepBackward = { [weak self] in + pianoWaveformWindowDelegate.reposition(statusItemButton: statusItem.button) + pianoWaveformWindowDelegate.onStepBackward = { [weak self] in self?.menuBand.stepMelodicProgram(delta: -1) } - pianoWaveformStrip.onStepForward = { [weak self] in + pianoWaveformWindowDelegate.onStepForward = { [weak self] in self?.menuBand.stepMelodicProgram(delta: +1) } - pianoWaveformStrip.onStepUp = { [weak self] in + pianoWaveformWindowDelegate.onStepUp = { [weak self] in self?.menuBand.stepMelodicProgram(delta: -InstrumentListView.cols) } - pianoWaveformStrip.onStepDown = { [weak self] in + pianoWaveformWindowDelegate.onStepDown = { [weak self] in self?.menuBand.stepMelodicProgram(delta: +InstrumentListView.cols) } - pianoWaveformStrip.warmUp() + pianoWaveformWindowDelegate.warmUp() registerTypeModeHotkey() _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) @@ -280,29 +275,29 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.toggleKeyboardLayoutShortcut() return true } - if self.popover.isShown == false && self.pianoWaveformOverlay.isShown == false { + if self.popover.isShown == false && self.pianoWaveformWindowDelegate.isShown == false { switch keyCode { case 123: // kVK_LeftArrow if isDown { - self.pianoWaveformStrip.registerArrowInput() + self.pianoWaveformWindowDelegate.registerArrowInput() if !isRepeat { self.menuBand.stepMelodicProgram(delta: -1) } } return true case 124: // kVK_RightArrow if isDown { - self.pianoWaveformStrip.registerArrowInput() + self.pianoWaveformWindowDelegate.registerArrowInput() if !isRepeat { self.menuBand.stepMelodicProgram(delta: +1) } } return true case 125: // kVK_DownArrow if isDown { - self.pianoWaveformStrip.registerArrowInput() + self.pianoWaveformWindowDelegate.registerArrowInput() if !isRepeat { self.menuBand.stepMelodicProgram(delta: +InstrumentListView.cols) } } return true case 126: // kVK_UpArrow if isDown { - self.pianoWaveformStrip.registerArrowInput() + self.pianoWaveformWindowDelegate.registerArrowInput() if !isRepeat { self.menuBand.stepMelodicProgram(delta: -InstrumentListView.cols) } } return true @@ -315,7 +310,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { ) if consumed && isDown { if !self.menuBand.litNotes.isEmpty { - self.pianoWaveformStrip.showIfNeeded() + self.pianoWaveformWindowDelegate.showIfNeeded() } // Use the most-recent lit display note as the wave pivot // so the ripple emanates from whichever key the user just @@ -396,7 +391,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self?.setShortcutRecording(isRecording) } vc.isPlayPaletteShown = { [weak self] in - self?.pianoWaveformOverlay.isShown ?? false + self?.pianoWaveformWindowDelegate.isShown ?? false } popoverVC = vc popover.contentViewController = vc @@ -536,22 +531,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } private func togglePianoWaveformFromShortcut() { - if pianoWaveformOverlay.isShown { - pianoWaveformOverlay.toggleFromShortcut() - updateWaveformStripSuppression() + if pianoWaveformWindowDelegate.isShown { + pianoWaveformWindowDelegate.toggleFromShortcut() + updatePianoWaveformWindowSuppression() return } beginPianoWaveformPresentation() - pianoWaveformOverlay.toggleFromShortcut() - updateWaveformStripSuppression() + pianoWaveformWindowDelegate.toggleFromShortcut() + updatePianoWaveformWindowSuppression() } private func togglePianoWaveformFromCommand() { let appToRestore = appBeforePopover beginPianoWaveformPresentation() appBeforePopover = nil - pianoWaveformOverlay.showFromCommand(restoringTo: appToRestore) - updateWaveformStripSuppression() + pianoWaveformWindowDelegate.showFromCommand(restoringTo: appToRestore) + updatePianoWaveformWindowSuppression() } private func beginPianoWaveformPresentation() { @@ -562,11 +557,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate { if menuBand.typeMode { menuBand.disableTypeModeForFocusCapture() } - updateWaveformStripSuppression() + updatePianoWaveformWindowSuppression() } private func toggleFocusCaptureFromShortcut() { - if pianoWaveformOverlay.isKeyboardFocused { + if pianoWaveformWindowDelegate.isKeyboardFocused { finishPianoWaveformKeyboardFocus() return } @@ -591,7 +586,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { focusCaptureArmedByShortcut = true localCapture.arm() updateIcon() - pianoWaveformOverlay.refresh() + updatePianoWaveformWindow() } private func finishLocalCapture(reason: LocalKeyCapture.EndReason) { @@ -602,7 +597,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { ghostRefreshTimer?.invalidate() ghostRefreshTimer = nil updateIcon() - pianoWaveformOverlay.refresh() + updatePianoWaveformWindow() if shouldRestoreFocus { restorePreviousAppFocus() } @@ -618,10 +613,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private func finishPianoWaveformKeyboardFocus() { menuBand.releaseAllHeldNotes() - pianoWaveformOverlay.clearInteraction() - pianoWaveformOverlay.releaseKeyboardFocus() + pianoWaveformWindowDelegate.clearInteraction() + pianoWaveformWindowDelegate.releaseKeyboardFocus() updateIcon() - pianoWaveformOverlay.refresh() + updatePianoWaveformWindow() } private func toggleKeyboardLayoutShortcut() { @@ -824,7 +819,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } func applicationWillTerminate(_ notification: Notification) { - pianoWaveformOverlay.dismiss(reason: .programmatic) + pianoWaveformWindowDelegate.dismiss(reason: .programmatic) menuBand.shutdown() } @@ -1199,7 +1194,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // palette window). Same target the popover's WaveformView // routes to, so the user gets one entry point regardless of // where they tap. - pianoWaveformOverlay.show() + pianoWaveformWindowDelegate.show() return case .note(let n): startDisplayNote = n @@ -1220,7 +1215,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { displayNote: startDisplayNote, linger: initialShift ) - pianoWaveformStrip.showIfNeeded() + pianoWaveformWindowDelegate.showIfNeeded() // Arm sandbox-friendly local capture on a real piano click. We // skip arming when global TYPE mode is already on — the global // tap is already handling keys, doubling up would re-trigger @@ -1229,7 +1224,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // when you're just tapping the piano with the mouse. if !menuBand.typeMode { localCapture.arm() - pianoWaveformOverlay.refresh() + updatePianoWaveformWindow() } var currentDisplay: UInt8? = startDisplayNote var currentPlayed: UInt8? = startNote @@ -1262,7 +1257,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { displayNote: nxtDisplay, linger: shiftNow ) - pianoWaveformStrip.showIfNeeded() + pianoWaveformWindowDelegate.showIfNeeded() currentPlayed = nxtPlayed } else { currentPlayed = nil @@ -1293,7 +1288,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 - updateWaveformStripSuppression() + updatePianoWaveformWindowSuppression() } /// Distributed-notification entry point for the dev affordance @@ -1338,7 +1333,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { : frontmost NSApp.activate(ignoringOtherApps: true) popover.show(relativeTo: anchor, of: button, preferredEdge: .minY) - updateWaveformStripSuppression() + updatePianoWaveformWindowSuppression() DispatchQueue.main.async { self.popover.contentViewController?.view.window?.makeKey() } @@ -1371,17 +1366,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Menubar waveform strip - private func updateWaveformStrip() { - guard pianoWaveformStrip.isCollapsedState else { return } + private func updatePianoWaveformWindow() { + pianoWaveformWindowDelegate.refresh() + guard pianoWaveformWindowDelegate.isCollapsedState else { return } if !menuBand.litNotes.isEmpty { - pianoWaveformStrip.showIfNeeded() + pianoWaveformWindowDelegate.showIfNeeded() } else { - pianoWaveformStrip.scheduleHide() + pianoWaveformWindowDelegate.scheduleHide() } } - private func updateWaveformStripSuppression() { - pianoWaveformStrip.isCollapsedPresentationSuppressed = - pianoWaveformStrip.isDocked && (popover.isShown || pianoWaveformOverlay.isShown) + private func updatePianoWaveformWindowSuppression() { + pianoWaveformWindowDelegate.isCollapsedPresentationSuppressed = + pianoWaveformWindowDelegate.isDocked && (popover.isShown || pianoWaveformWindowDelegate.isShown) } } diff --git a/slab/menuband/Sources/MenuBand/ChordCandidateCard.swift b/slab/menuband/Sources/MenuBand/ChordCandidateCard.swift index 8cf314a86c..51a45c0adc 100644 --- a/slab/menuband/Sources/MenuBand/ChordCandidateCard.swift +++ b/slab/menuband/Sources/MenuBand/ChordCandidateCard.swift @@ -35,6 +35,9 @@ enum FloatingChordCandidateCard { ) nameLabel.drawsBackground = false nameLabel.translatesAutoresizingMaskIntoConstraints = false + nameLabel.lineBreakMode = .byTruncatingTail + nameLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + nameLabel.setContentHuggingPriority(.defaultLow, for: .horizontal) if candidate.isComplete { // Active chord: solid root-color fill + colored glow. @@ -64,6 +67,8 @@ enum FloatingChordCandidateCard { row.alignment = .centerY row.spacing = 4 row.translatesAutoresizingMaskIntoConstraints = false + row.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + row.setContentHuggingPriority(.defaultLow, for: .horizontal) row.addArrangedSubview(nameLabel) if !candidate.isComplete { for pc in candidate.missingPitchClasses { @@ -71,6 +76,8 @@ enum FloatingChordCandidateCard { } } card.addSubview(row) + card.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + card.setContentHuggingPriority(.defaultLow, for: .horizontal) NSLayoutConstraint.activate([ row.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 7), row.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -7), diff --git a/slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift b/slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift deleted file mode 100644 index e398925600..0000000000 --- a/slab/menuband/Sources/MenuBand/FloatingPlayPalette.swift +++ /dev/null @@ -1,1281 +0,0 @@ -import AppKit - -private enum PianoWaveformVisualStyleOverride: String { - case automatic - case liquid - case legacy - - init(rawValue: String?) { - switch rawValue?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { - case Self.liquid.rawValue: - self = .liquid - case Self.legacy.rawValue: - self = .legacy - default: - self = .automatic - } - } -} - -@available(macOS 26.0, *) -private final class PianoWaveformOverlayGlassEffectView: NSGlassEffectView { - override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } -} - -final class PianoWaveformViewController: NSViewController { - enum PresentationMode { - case expanded - case collapsed - } - - private static let panelCornerRadius: CGFloat = 18 - - private let containerView = NSView() - private let expandedView: ExpandedPianoWaveformView - private let collapsedView: CollapsedPianoWaveformView - private let closeButton = NSButton() - private let dockButton = NSButton() - private let expandCollapseButton = NSButton() - private var activeContentView: NSView? - private var presentationMode: PresentationMode = .expanded - private var isPresented = false - private var trackingArea: NSTrackingArea? - private var isMouseInsideView = false - private weak var closeButtonGlassView: NSView? - private weak var dockButtonGlassView: NSView? - private weak var expandCollapseButtonGlassView: NSView? - private let closeButtonSize: CGFloat = 30 - private let closeButtonCornerInset: CGFloat = 3 - private let gap: CGFloat = 8 - - var onCloseRequested: (() -> Void)? - - var onDockRequested: (() -> Void)? - - var onTogglePresentationMode: (() -> Void)? - - var onStepBackward: (() -> Void)? { - get { collapsedView.onStepBackward } - set { collapsedView.onStepBackward = newValue } - } - - var onStepForward: (() -> Void)? { - get { collapsedView.onStepForward } - set { collapsedView.onStepForward = newValue } - } - - var onStepUp: (() -> Void)? { - get { collapsedView.onStepUp } - set { collapsedView.onStepUp = newValue } - } - - var onStepDown: (() -> Void)? { - get { collapsedView.onStepDown } - set { collapsedView.onStepDown = newValue } - } - - var isPianoFocusActive: (() -> Bool)? { - get { expandedView.isPianoFocusActive } - set { expandedView.isPianoFocusActive = newValue } - } - - init(menuBand: MenuBandController) { - self.expandedView = ExpandedPianoWaveformView(menuBand: menuBand) - self.collapsedView = CollapsedPianoWaveformView(menuBand: menuBand) - super.init(nibName: nil, bundle: nil) - preferredContentSize = preferredSize(for: presentationMode) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - nil - } - - override func loadView() { - view = containerView - containerView.wantsLayer = true - configureOverlayButton( - closeButton, - symbolName: "xmark", - toolTip: "Close", - action: #selector(closeClicked(_:)) - ) - configureOverlayButton( - dockButton, - symbolName: "menubar.dock.rectangle", - toolTip: "Dock Below Menubar Piano", - action: #selector(dockClicked(_:)) - ) - configureOverlayButton( - expandCollapseButton, - symbolName: "square.resize.down", - toolTip: "Collapse", - action: #selector(expandCollapseClicked(_:)) - ) - containerView.addSubview(closeButton) - containerView.addSubview(dockButton) - containerView.addSubview(expandCollapseButton) - installOverlayGlassBackgrounds() - NSLayoutConstraint.activate([ - closeButton.topAnchor.constraint( - equalTo: containerView.topAnchor, - constant: PianoWaveformViewController.panelCornerRadius - closeButtonSize / 2 + closeButtonCornerInset - ), - closeButton.leadingAnchor.constraint( - equalTo: containerView.leadingAnchor, - constant: PianoWaveformViewController.panelCornerRadius - closeButtonSize / 2 + closeButtonCornerInset - ), - closeButton.widthAnchor.constraint(equalToConstant: closeButtonSize), - closeButton.heightAnchor.constraint(equalToConstant: closeButtonSize), - - expandCollapseButton.topAnchor.constraint(equalTo: closeButton.topAnchor), - expandCollapseButton.trailingAnchor.constraint( - equalTo: containerView.trailingAnchor, - constant: -(PianoWaveformViewController.panelCornerRadius - closeButtonSize / 2 + closeButtonCornerInset) - ), - expandCollapseButton.widthAnchor.constraint(equalToConstant: closeButtonSize), - expandCollapseButton.heightAnchor.constraint(equalToConstant: closeButtonSize), - - dockButton.topAnchor.constraint(equalTo: closeButton.topAnchor), - dockButton.trailingAnchor.constraint(equalTo: expandCollapseButton.leadingAnchor, constant: -gap), - dockButton.widthAnchor.constraint(equalToConstant: closeButtonSize), - dockButton.heightAnchor.constraint(equalToConstant: closeButtonSize), - ]) - installTrackingArea() - installDisplayedView() - isMouseInsideView = isMouseInsideContainer() - setOverlayControlsVisible(isMouseInsideView, animated: false) - } - - func refresh() { - expandedView.refresh() - collapsedView.refresh() - preferredContentSize = preferredSize(for: presentationMode) - } - - func clearInteraction() { - expandedView.clearInteraction() - } - - func setPresented(_ isPresented: Bool) { - self.isPresented = isPresented - updatePresentationState() - } - - func setPresentationMode(_ presentationMode: PresentationMode) { - guard self.presentationMode != presentationMode else { - preferredContentSize = preferredSize(for: presentationMode) - updatePresentationState() - return - } - self.presentationMode = presentationMode - if isViewLoaded { - installDisplayedView() - } - preferredContentSize = preferredSize(for: presentationMode) - updatePresentationState() - } - - private func installDisplayedView() { - let nextView: NSView - switch presentationMode { - case .expanded: - nextView = expandedView - case .collapsed: - nextView = collapsedView - } - - guard activeContentView !== nextView else { return } - activeContentView?.removeFromSuperview() - nextView.translatesAutoresizingMaskIntoConstraints = false - containerView.addSubview(nextView, positioned: .below, relativeTo: nil) - NSLayoutConstraint.activate([ - nextView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), - nextView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), - nextView.topAnchor.constraint(equalTo: containerView.topAnchor), - nextView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor), - ]) - activeContentView = nextView - } - - private func preferredSize(for presentationMode: PresentationMode) -> NSSize { - switch presentationMode { - case .expanded: - return expandedView.fittingSize - case .collapsed: - return collapsedView.fittingSize - } - } - - private func updatePresentationState() { - expandedView.setPresented(isPresented && presentationMode == .expanded) - collapsedView.setLive(isPresented && presentationMode == .collapsed) - let controlsHidden = false - [closeButton, dockButton, expandCollapseButton, closeButtonGlassView, dockButtonGlassView, expandCollapseButtonGlassView] - .compactMap { $0 } - .forEach { $0.isHidden = controlsHidden } - updateExpandCollapseButtonAppearance() - isMouseInsideView = isMouseInsideContainer() - setOverlayControlsVisible(isMouseInsideView, animated: false) - applyOverlayButtonAppearance() - } - - private func configureOverlayButton( - _ button: NSButton, - symbolName: String, - toolTip: String, - action: Selector - ) { - let config = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold) - button.translatesAutoresizingMaskIntoConstraints = false - button.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: toolTip)? - .withSymbolConfiguration(config) - button.isBordered = false - button.imagePosition = .imageOnly - button.contentTintColor = .white.withAlphaComponent(0.92) - button.toolTip = toolTip - button.target = self - button.action = action - button.alphaValue = 0 - button.wantsLayer = true - button.layer?.cornerRadius = closeButtonSize / 2 - button.layer?.borderWidth = 1 - if #available(macOS 10.15, *) { - button.layer?.cornerCurve = .continuous - } - } - - private func installOverlayGlassBackgrounds() { - guard ExpandedPianoWaveformView.shouldUseLiquidGlass, #available(macOS 26.0, *) else { return } - self.closeButtonGlassView = installGlassBackground(for: closeButton) - self.dockButtonGlassView = installGlassBackground(for: dockButton) - self.expandCollapseButtonGlassView = installGlassBackground(for: expandCollapseButton) - } - - @available(macOS 26.0, *) - private func installGlassBackground(for target: NSView) -> NSView { - let glassView = PianoWaveformOverlayGlassEffectView() - glassView.translatesAutoresizingMaskIntoConstraints = false - glassView.cornerRadius = closeButtonSize / 2 - containerView.addSubview(glassView, positioned: .below, relativeTo: target) - NSLayoutConstraint.activate([ - glassView.leadingAnchor.constraint(equalTo: target.leadingAnchor), - glassView.trailingAnchor.constraint(equalTo: target.trailingAnchor), - glassView.topAnchor.constraint(equalTo: target.topAnchor), - glassView.bottomAnchor.constraint(equalTo: target.bottomAnchor), - ]) - return glassView - } - - private func setOverlayControlsVisible(_ isVisible: Bool, animated: Bool = true) { - let alpha: CGFloat = isVisible ? 1.0 : 0.0 - let views = [closeButton, dockButton, expandCollapseButton, closeButtonGlassView, dockButtonGlassView, expandCollapseButtonGlassView] - .compactMap { $0 } - if animated { - NSAnimationContext.runAnimationGroup { context in - context.duration = 0.12 - closeButton.animator().alphaValue = alpha - dockButton.animator().alphaValue = alpha - expandCollapseButton.animator().alphaValue = alpha - closeButtonGlassView?.animator().alphaValue = alpha - dockButtonGlassView?.animator().alphaValue = alpha - expandCollapseButtonGlassView?.animator().alphaValue = alpha - } - } else { - views.forEach { $0.alphaValue = alpha } - } - } - - private func installTrackingArea() { - if let trackingArea { - containerView.removeTrackingArea(trackingArea) - } - let trackingArea = NSTrackingArea( - rect: .zero, - options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], - owner: self, - userInfo: nil - ) - containerView.addTrackingArea(trackingArea) - self.trackingArea = trackingArea - } - - override func mouseEntered(with event: NSEvent) { - isMouseInsideView = true - setOverlayControlsVisible(true) - } - - override func mouseExited(with event: NSEvent) { - isMouseInsideView = false - setOverlayControlsVisible(false) - } - - private func isMouseInsideContainer() -> Bool { - guard let window = containerView.window else { return false } - let location = containerView.convert(window.mouseLocationOutsideOfEventStream, from: nil) - return containerView.bounds.contains(location) - } - - private func applyOverlayButtonAppearance() { - let effectiveView: NSView - switch presentationMode { - case .expanded: - effectiveView = expandedView - case .collapsed: - effectiveView = collapsedView - } - let isDark = effectiveView.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua - let tintColor = expandedView.paletteTintColor - if ExpandedPianoWaveformView.shouldUseLiquidGlass, #available(macOS 26.0, *) { - for view in [closeButtonGlassView, dockButtonGlassView, expandCollapseButtonGlassView] { - (view as? NSGlassEffectView)?.style = .clear - (view as? NSGlassEffectView)?.tintColor = tintColor.withAlphaComponent(0.34) - } - for button in [closeButton, dockButton, expandCollapseButton] { - button.layer?.backgroundColor = NSColor.clear.cgColor - button.layer?.borderColor = NSColor.clear.cgColor - } - } else { - let border = NSColor.white.withAlphaComponent(0.28).cgColor - let background = NSColor.windowBackgroundColor.withAlphaComponent(isDark ? 0.18 : 0.22).cgColor - for button in [closeButton, dockButton, expandCollapseButton] { - button.layer?.backgroundColor = background - button.layer?.borderColor = border - } - } - } - - private func updateExpandCollapseButtonAppearance() { - let symbolName = presentationMode == .expanded ? "square.resize.down" : "square.resize.up" - let toolTip = presentationMode == .expanded ? "Collapse" : "Expand floating piano" - let config = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold) - expandCollapseButton.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: toolTip)? - .withSymbolConfiguration(config) - expandCollapseButton.toolTip = toolTip - } - - @objc private func closeClicked(_ sender: NSButton) { - onCloseRequested?() - } - - @objc private func dockClicked(_ sender: NSButton) { - onDockRequested?() - } - - @objc private func expandCollapseClicked(_ sender: NSButton) { - onTogglePresentationMode?() - } -} - -private final class ExpandedPianoWaveformView: NSView { - private static let defaultsDomain = "computer.aestheticcomputer.menuband" - private static let styleOverrideDefaultsKey = "MenuBandFloatingPlayPaletteStyle" - private static let styleOverrideEnvironmentKey = "MENUBAND_FLOATING_PLAY_PALETTE_STYLE" - - private static var visualStyleOverride: PianoWaveformVisualStyleOverride { - let environmentValue = ProcessInfo.processInfo.environment[styleOverrideEnvironmentKey] - if environmentValue != nil { - return PianoWaveformVisualStyleOverride(rawValue: environmentValue) - } - let defaultsValue = UserDefaults(suiteName: defaultsDomain)?.string(forKey: styleOverrideDefaultsKey) - ?? UserDefaults.standard.string(forKey: styleOverrideDefaultsKey) - return PianoWaveformVisualStyleOverride(rawValue: defaultsValue) - } - - static var shouldUseLiquidGlass: Bool { - switch visualStyleOverride { - case .liquid: - if #available(macOS 26.0, *) { return true } - return false - case .legacy: - return false - case .automatic: - if #available(macOS 26.0, *) { return true } - return false - } - } - - private weak var menuBand: MenuBandController? - private let contentStack = NSStackView() - private let waveformSection = NSView() - private let waveformView = WaveformView() - private let waveformBezel = NSView() - private let waveformClipView = NSView() - private let heldNotesStack = NSStackView() - private let heldNotesRow = NSView() - private let chordCandidatesStack = NSStackView() - private let chordCandidatesRow = NSView() - private var lastCompleteChordNames: Set = [] - private let instrumentReadout = NSTextField(labelWithString: "") - private let instrumentTitleRow: NSStackView - private let pianoView: PianoKeyboardView - private let shortcutHintRow = NSStackView() - private let focusHintLabel = NSTextField(labelWithString: "") - private let layoutHintLabel = NSTextField(labelWithString: "") - private weak var paletteGlassView: NSView? - private weak var waveformGlassView: NSView? - private weak var waveformSectionGlassView: NSView? - private weak var pianoGlassView: NSView? - private weak var keymapGlassView: NSView? - private weak var hintGlassView: NSView? - /// Large QWERTY keymap shown beneath the piano so the user can - /// see at a glance which physical keys play which notes. Driven - /// at 2× scale so it's legible at the floating palette's size. - private let qwertyView = QwertyLayoutView() - - var isPianoFocusActive: (() -> Bool)? - var onHoverChanged: ((Bool) -> Void)? - - private let pianoScale: CGFloat = 1.6 - private let inset: CGFloat = 14 - private let gap: CGFloat = 8 - private let hintHeight: CGFloat = 20 - private let heldNotesRowHeight: CGFloat = 26 - private let chordCandidatesRowHeight: CGFloat = 30 - private var waveformHeightConstraint: NSLayoutConstraint? - private var trackingArea: NSTrackingArea? - private static let panelCornerRadius: CGFloat = 18 - private static let sectionCornerRadius: CGFloat = 14 - private static let waveformClipCornerRadius: CGFloat = 12 - private static let expandedPanelWidth: CGFloat = 440 - - init(menuBand: MenuBandController) { - self.menuBand = menuBand - let titleLeftSpacer = NSView() - let titleRightSpacer = NSView() - titleLeftSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) - titleRightSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) - self.instrumentTitleRow = NSStackView(views: [titleLeftSpacer, instrumentReadout, titleRightSpacer]) - self.pianoView = PianoKeyboardView(menuBand: menuBand, pianoScale: pianoScale) - super.init(frame: NSRect(origin: .zero, size: .zero)) - wantsLayer = true - - waveformView.menuBand = menuBand - waveformView.translatesAutoresizingMaskIntoConstraints = false - waveformView.setSurfaceStyle(.glassEmbedded) - contentStack.orientation = .vertical - contentStack.alignment = .centerX - contentStack.distribution = .fill - contentStack.spacing = gap - contentStack.translatesAutoresizingMaskIntoConstraints = false - waveformSection.wantsLayer = true - waveformSection.layer?.cornerRadius = Self.sectionCornerRadius - waveformSection.layer?.borderWidth = 0.8 - if #available(macOS 10.15, *) { - waveformSection.layer?.cornerCurve = .continuous - } - waveformSection.translatesAutoresizingMaskIntoConstraints = false - waveformBezel.wantsLayer = true - waveformBezel.layer?.cornerRadius = Self.waveformClipCornerRadius + 2 - waveformBezel.layer?.borderWidth = 0 - if #available(macOS 10.15, *) { - waveformBezel.layer?.cornerCurve = .continuous - } - waveformBezel.translatesAutoresizingMaskIntoConstraints = false - waveformClipView.wantsLayer = true - waveformClipView.translatesAutoresizingMaskIntoConstraints = false - waveformClipView.layer?.cornerRadius = Self.waveformClipCornerRadius - waveformClipView.layer?.masksToBounds = true - if #available(macOS 10.15, *) { - waveformClipView.layer?.cornerCurve = .continuous - } - heldNotesStack.orientation = .horizontal - heldNotesStack.alignment = .centerY - heldNotesStack.spacing = 6 - heldNotesStack.translatesAutoresizingMaskIntoConstraints = false - heldNotesRow.translatesAutoresizingMaskIntoConstraints = false - heldNotesRow.addSubview(heldNotesStack) - chordCandidatesStack.orientation = .horizontal - chordCandidatesStack.alignment = .centerY - chordCandidatesStack.spacing = 6 - chordCandidatesStack.translatesAutoresizingMaskIntoConstraints = false - chordCandidatesRow.translatesAutoresizingMaskIntoConstraints = false - chordCandidatesRow.addSubview(chordCandidatesStack) - instrumentReadout.lineBreakMode = .byTruncatingTail - instrumentReadout.alignment = .center - instrumentReadout.setContentHuggingPriority(.defaultHigh, for: .horizontal) - instrumentReadout.setContentCompressionResistancePriority(.required, for: .horizontal) - instrumentTitleRow.orientation = .horizontal - instrumentTitleRow.alignment = .centerY - instrumentTitleRow.distribution = .fill - instrumentTitleRow.spacing = 0 - instrumentTitleRow.translatesAutoresizingMaskIntoConstraints = false - pianoView.translatesAutoresizingMaskIntoConstraints = false - shortcutHintRow.orientation = .horizontal - shortcutHintRow.alignment = .centerY - shortcutHintRow.distribution = .fill - shortcutHintRow.spacing = gap - shortcutHintRow.translatesAutoresizingMaskIntoConstraints = false - focusHintLabel.translatesAutoresizingMaskIntoConstraints = false - layoutHintLabel.translatesAutoresizingMaskIntoConstraints = false - qwertyView.scale = 1.4 - qwertyView.keymap = menuBand.keymap - qwertyView.translatesAutoresizingMaskIntoConstraints = false - // Mouse-tap on a keycap → route through the controller's - // local-key handler so the floating palette's QWERTY map - // plays the same notes the physical keyboard would. - qwertyView.onKey = { [weak self] keyCode, isDown in - guard let self = self, let menuBand = self.menuBand else { return } - menuBand.handleLocalKey(keyCode: keyCode, isDown: isDown, - isRepeat: false, flags: []) - self.refresh() - } - // Held-note pills and chord-suggestion cards overlay the metal - // visualizer directly so the waveform doubles as the canvas - // for the chord readout. Stack vertically: pills on top, cards - // beneath, both centered. Waveform draws underneath, peeking - // through the translucent card backgrounds. - waveformBezel.addSubview(waveformClipView) - waveformClipView.addSubview(waveformView) - waveformBezel.layer?.masksToBounds = false - heldNotesRow.wantsLayer = true - heldNotesRow.layer?.masksToBounds = false - chordCandidatesRow.wantsLayer = true - chordCandidatesRow.layer?.masksToBounds = false - waveformBezel.addSubview(heldNotesRow) - waveformBezel.addSubview(chordCandidatesRow) - waveformSection.addSubview(waveformBezel) - waveformSection.addSubview(instrumentTitleRow) - addSubview(contentStack) - contentStack.addArrangedSubview(waveformSection) - contentStack.addArrangedSubview(pianoView) - shortcutHintRow.addArrangedSubview(layoutHintLabel) - shortcutHintRow.addArrangedSubview(NSView()) - shortcutHintRow.addArrangedSubview(focusHintLabel) - contentStack.addArrangedSubview(shortcutHintRow) - contentStack.addArrangedSubview(qwertyView) - for label in [focusHintLabel, layoutHintLabel] { - label.font = NSFont.systemFont(ofSize: 10, weight: .bold) - label.textColor = .secondaryLabelColor - label.maximumNumberOfLines = 1 - label.lineBreakMode = .byTruncatingTail - } - layoutHintLabel.alignment = .left - focusHintLabel.alignment = .right - updateShortcutHint() - installLiquidGlassBackgrounds() - - let keyboardSize = self.keyboardSize() - let waveformHeightConstraint = waveformView.heightAnchor.constraint( - equalToConstant: waveformHeight(for: keyboardSize) - ) - self.waveformHeightConstraint = waveformHeightConstraint - let bezelInset: CGFloat = 5 - let titleSpacers = instrumentTitleRow.arrangedSubviews - - NSLayoutConstraint.activate([ - widthAnchor.constraint( - equalToConstant: max(keyboardSize.width + inset * 2, Self.expandedPanelWidth) - ), - - contentStack.topAnchor.constraint(equalTo: topAnchor, constant: inset), - contentStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset), - contentStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset), - contentStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -inset), - - waveformSection.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor), - waveformSection.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor), - - heldNotesStack.centerXAnchor.constraint(equalTo: heldNotesRow.centerXAnchor), - heldNotesStack.centerYAnchor.constraint(equalTo: heldNotesRow.centerYAnchor), - heldNotesStack.leadingAnchor.constraint(greaterThanOrEqualTo: heldNotesRow.leadingAnchor, constant: 6), - heldNotesStack.trailingAnchor.constraint(lessThanOrEqualTo: heldNotesRow.trailingAnchor, constant: -6), - heldNotesRow.heightAnchor.constraint(equalToConstant: heldNotesRowHeight), - - chordCandidatesStack.centerXAnchor.constraint(equalTo: chordCandidatesRow.centerXAnchor), - chordCandidatesStack.centerYAnchor.constraint(equalTo: chordCandidatesRow.centerYAnchor), - chordCandidatesStack.leadingAnchor.constraint(greaterThanOrEqualTo: chordCandidatesRow.leadingAnchor, constant: 6), - chordCandidatesStack.trailingAnchor.constraint(lessThanOrEqualTo: chordCandidatesRow.trailingAnchor, constant: -6), - chordCandidatesRow.heightAnchor.constraint(equalToConstant: chordCandidatesRowHeight), - - waveformBezel.topAnchor.constraint(equalTo: waveformSection.topAnchor, constant: bezelInset), - waveformBezel.leadingAnchor.constraint(equalTo: waveformSection.leadingAnchor, constant: bezelInset), - waveformBezel.trailingAnchor.constraint(equalTo: waveformSection.trailingAnchor, constant: -bezelInset), - waveformClipView.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor, constant: bezelInset), - waveformClipView.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor, constant: -bezelInset), - waveformClipView.topAnchor.constraint(equalTo: waveformBezel.topAnchor, constant: bezelInset), - waveformClipView.bottomAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: -bezelInset), - waveformView.leadingAnchor.constraint(equalTo: waveformClipView.leadingAnchor), - waveformView.trailingAnchor.constraint(equalTo: waveformClipView.trailingAnchor), - waveformView.topAnchor.constraint(equalTo: waveformClipView.topAnchor), - waveformView.bottomAnchor.constraint(equalTo: waveformClipView.bottomAnchor), - waveformHeightConstraint, - - heldNotesRow.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor), - heldNotesRow.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor), - heldNotesRow.topAnchor.constraint(equalTo: waveformBezel.topAnchor, constant: 8), - - chordCandidatesRow.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor), - chordCandidatesRow.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor), - chordCandidatesRow.bottomAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: -8), - - instrumentTitleRow.topAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: 6), - instrumentTitleRow.leadingAnchor.constraint(equalTo: waveformSection.leadingAnchor, constant: 6), - instrumentTitleRow.trailingAnchor.constraint(equalTo: waveformSection.trailingAnchor, constant: -6), - instrumentTitleRow.bottomAnchor.constraint(equalTo: waveformSection.bottomAnchor, constant: -6), - - shortcutHintRow.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor), - shortcutHintRow.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor), - shortcutHintRow.heightAnchor.constraint(equalToConstant: hintHeight), - - qwertyView.centerXAnchor.constraint(equalTo: centerXAnchor), - qwertyView.widthAnchor.constraint( - equalToConstant: QwertyLayoutView.intrinsicSize.width * 1.4 - ), - qwertyView.heightAnchor.constraint( - equalToConstant: QwertyLayoutView.intrinsicSize.height * 1.4 - ), - ]) - if titleSpacers.count == 3 { - titleSpacers[0].widthAnchor.constraint(equalTo: titleSpacers[2].widthAnchor).isActive = true - } - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - nil - } - - private func installLiquidGlassBackgrounds() { - guard Self.shouldUseLiquidGlass, #available(macOS 26.0, *) else { return } - - let paletteGlassView = PianoWaveformOverlayGlassEffectView() - paletteGlassView.translatesAutoresizingMaskIntoConstraints = false - paletteGlassView.cornerRadius = Self.panelCornerRadius - addSubview(paletteGlassView, positioned: .below, relativeTo: waveformSection) - NSLayoutConstraint.activate([ - paletteGlassView.leadingAnchor.constraint(equalTo: leadingAnchor), - paletteGlassView.trailingAnchor.constraint(equalTo: trailingAnchor), - paletteGlassView.topAnchor.constraint(equalTo: topAnchor), - paletteGlassView.bottomAnchor.constraint(equalTo: bottomAnchor), - ]) - self.paletteGlassView = paletteGlassView - - self.waveformSectionGlassView = installGlassBackground( - matchedTo: waveformSection, - below: waveformSection, - cornerRadius: Self.sectionCornerRadius - ) - self.pianoGlassView = installGlassBackground( - matchedTo: pianoView, - below: pianoView, - cornerRadius: Self.sectionCornerRadius - ) - self.keymapGlassView = installGlassBackground( - matchedTo: qwertyView, - below: qwertyView, - cornerRadius: Self.sectionCornerRadius - ) - self.hintGlassView = installGlassBackground( - matchedTo: shortcutHintRow, - below: shortcutHintRow, - cornerRadius: Self.sectionCornerRadius - ) - } - - @available(macOS 26.0, *) - private func installGlassBackground(matchedTo target: NSView, - below anchor: NSView, - cornerRadius: CGFloat) -> NSView { - let glassView = PianoWaveformOverlayGlassEffectView() - glassView.translatesAutoresizingMaskIntoConstraints = false - glassView.cornerRadius = cornerRadius - addSubview(glassView, positioned: .below, relativeTo: anchor) - NSLayoutConstraint.activate([ - glassView.leadingAnchor.constraint(equalTo: target.leadingAnchor), - glassView.trailingAnchor.constraint(equalTo: target.trailingAnchor), - glassView.topAnchor.constraint(equalTo: target.topAnchor), - glassView.bottomAnchor.constraint(equalTo: target.bottomAnchor), - ]) - return glassView - } - - override var acceptsFirstResponder: Bool { true } - - override func updateTrackingAreas() { - super.updateTrackingAreas() - if let trackingArea { - removeTrackingArea(trackingArea) - } - let trackingArea = NSTrackingArea( - rect: bounds, - options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], - owner: self, - userInfo: nil - ) - addTrackingArea(trackingArea) - self.trackingArea = trackingArea - } - - override func mouseEntered(with event: NSEvent) { - super.mouseEntered(with: event) - onHoverChanged?(true) - } - - override func mouseExited(with event: NSEvent) { - super.mouseExited(with: event) - onHoverChanged?(false) - } - - override func viewDidChangeEffectiveAppearance() { - super.viewDidChangeEffectiveAppearance() - applyAppearanceToVisualizer() - } - - override var fittingSize: NSSize { - pianoView.refreshLayout() - layoutSubtreeIfNeeded() - return super.fittingSize - } - - override func draw(_ dirtyRect: NSRect) { - super.draw(dirtyRect) - if Self.shouldUseLiquidGlass, #available(macOS 26.0, *) { - return - } - 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() - applyAppearanceToVisualizer() - refreshHeldNotes() - updateInstrumentReadout() - applyWaveformTint() - updateWaveformLiveState(isPresented: window?.isVisible == true) - needsDisplay = true - pianoView.needsDisplay = true - } - - func clearInteraction() { - pianoView.clearInteraction() - lastCompleteChordNames = [] - } - - func setPresented(_ isPresented: Bool) { - applyAppearanceToVisualizer() - applyWaveformTint() - 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 applyAppearanceToVisualizer() { - let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua - waveformView.setLightMode(!isDark) - if isDark { - waveformSection.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.06).cgColor - waveformBezel.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.04).cgColor - } else { - waveformSection.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.22).cgColor - waveformBezel.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.18).cgColor - } - } - - private func applyWaveformTint() { - guard let menuBand else { return } - if menuBand.midiMode { - waveformView.setDotMatrix(MenuBandPopoverViewController.midiDotPattern) - waveformView.setBaseColor(.controlAccentColor) - waveformSection.layer?.borderColor = NSColor.controlAccentColor - .withAlphaComponent(0.24).cgColor - } else { - waveformView.setDotMatrix(nil) - let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) - let familyColor = InstrumentListView.colorForProgram(safe) - waveformView.setBaseColor(familyColor) - waveformSection.layer?.borderColor = familyColor - .withAlphaComponent(0.22).cgColor - } - if #available(macOS 26.0, *) { - let paletteTint = paletteTintColor - for view in [paletteGlassView, waveformSectionGlassView, pianoGlassView, keymapGlassView, hintGlassView] { - (view as? NSGlassEffectView)?.tintColor = paletteTint - } - } - } - - var paletteTintColor: NSColor { - guard let menuBand else { return NSColor.controlAccentColor.withAlphaComponent(0.20) } - if menuBand.midiMode { - return NSColor.controlAccentColor.withAlphaComponent(0.20) - } - let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) - return InstrumentListView.colorForProgram(safe).withAlphaComponent(0.16) - } - - private func keyboardSize() -> NSSize { - withPianoWaveformKeyboard(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 * 1.25 - } - - private func refreshHeldNotes() { - guard let menuBand else { return } - for view in heldNotesStack.arrangedSubviews { - heldNotesStack.removeArrangedSubview(view) - view.removeFromSuperview() - } - for view in chordCandidatesStack.arrangedSubviews { - chordCandidatesStack.removeArrangedSubview(view) - view.removeFromSuperview() - } - // Live state for the QWERTY keymap below the piano: light up - // the physical keys the user is currently holding, and route - // the qwertyView's onKey (mouse taps on caps) through the - // same handleLocalKey path the keyboard uses so the overlay - // is fully interactive. - qwertyView.litKeyCodes = menuBand.heldKeyCodes() - qwertyView.keymap = menuBand.keymap - let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) - let familyColor = menuBand.midiMode - ? NSColor.controlAccentColor - : InstrumentListView.colorForProgram(safe) - qwertyView.voiceColor = familyColor - - // Held-notes row: each currently sounding note as its own large - // pill so the chord shape reads at-a-glance. Always per-note — - // chord recognition lives in the candidates row below. - let names = menuBand.heldNoteNames() - for name in names { - heldNotesStack.addArrangedSubview(makeHeldNoteBox(name: name, color: familyColor)) - } - - // Chord candidates: every chord shape that contains the held - // pitch classes and whose missing notes are reachable on the - // active keymap. Cards re-render every refresh; transitions - // from incomplete → complete trigger a brief shake on the new - // complete card so the user feels the chord "lock in". - let candidates = menuBand.chordCandidates(maxResults: 8) - let newComplete = Set(candidates.filter(\.isComplete).map(\.name)) - let justCompleted = newComplete.subtracting(lastCompleteChordNames) - for candidate in candidates { - let card = makeChordCandidateCard(candidate: candidate, color: familyColor) - chordCandidatesStack.addArrangedSubview(card) - if candidate.isComplete && justCompleted.contains(candidate.name) { - applyShake(to: card) - } - } - lastCompleteChordNames = newComplete - } - - private func makeHeldNoteBox(name: String, color: NSColor) -> NSView { - let box = NSView() - box.wantsLayer = true - box.layer?.cornerRadius = 4 - box.layer?.backgroundColor = color.withAlphaComponent(0.92).cgColor - box.layer?.borderWidth = 1 - box.layer?.borderColor = color.shadow(withLevel: 0.35)?.cgColor ?? color.cgColor - box.translatesAutoresizingMaskIntoConstraints = false - let label = NSTextField(labelWithString: name) - label.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .heavy) - label.textColor = .black - label.drawsBackground = false - label.translatesAutoresizingMaskIntoConstraints = false - box.addSubview(label) - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: box.leadingAnchor, constant: 5), - label.trailingAnchor.constraint(equalTo: box.trailingAnchor, constant: -5), - label.topAnchor.constraint(equalTo: box.topAnchor, constant: 2), - label.bottomAnchor.constraint(equalTo: box.bottomAnchor, constant: -2), - box.heightAnchor.constraint(equalToConstant: 20), - ]) - return box - } - - private func makeChordCandidateCard(candidate: MenuBandController.ChordCandidate, - color: NSColor) -> NSView { - FloatingChordCandidateCard.build(candidate: candidate, - isDark: effectiveAppearance - .bestMatch(from: [.aqua, .darkAqua]) == .darkAqua) - } - - private func applyShake(to view: NSView) { - guard let layer = view.layer else { return } - let shake = CAKeyframeAnimation(keyPath: "transform.translation.x") - shake.values = [0, -7, 7, -5, 5, -3, 3, 0] - shake.keyTimes = [0, 0.12, 0.27, 0.42, 0.57, 0.72, 0.87, 1.0] - shake.duration = 0.46 - shake.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) - layer.add(shake, forKey: "shake") - } - - private func updateInstrumentReadout() { - guard let menuBand else { return } - let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) - let title = GeneralMIDI.programNames[safe] - let familyColor = InstrumentListView.colorForProgram(safe) - let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua - let textColor: NSColor = isDark ? .white : .black - let shadow = NSShadow() - shadow.shadowColor = (familyColor.highlight(withLevel: isDark ? 0.3 : 0.7) ?? familyColor) - shadow.shadowOffset = NSSize(width: 1, height: -1) - shadow.shadowBlurRadius = 0 - let titleFont: NSFont = { - if let desc = AppDelegate.ywftBoldDescriptor, - let font = NSFont(descriptor: desc, size: 18), - font.familyName == "YWFT Processing" { - return font - } - NSLog("MenuBand: YWFT bold descriptor unavailable; floating title falling back to system font") - return NSFont.systemFont(ofSize: 18, weight: .black) - }() - instrumentReadout.attributedStringValue = NSAttributedString( - string: title, - attributes: [ - .font: titleFont, - .foregroundColor: textColor, - .shadow: shadow, - ] - ) - } - - private func updateShortcutHint() { - let focusShortcut = MenuBandShortcutPreferences.focusShortcut.displayString - let layoutShortcut = MenuBandShortcut.layoutToggle.displayString - layoutHintLabel.stringValue = "Toggle Layout: \(layoutShortcut)" - focusHintLabel.stringValue = (isPianoFocusActive?() ?? false) - ? "Exit Focus: \(focusShortcut)" - : "Focus Piano: \(focusShortcut)" - } - -} - -private final class PianoKeyboardView: NSView { - private static let rendererLayout: KeyboardIconRenderer.Layout = .tightActiveRange - - private weak var menuBand: MenuBandController? - private var trackingArea: NSTrackingArea? - private var hoveredNote: UInt8? - private var currentDisplayNote: UInt8? - private var currentPlayedNote: 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 } - override var mouseDownCanMoveWindow: Bool { false } - - func refreshLayout() { - let preferredSize = preferredSize() - widthConstraint.constant = preferredSize.width - heightConstraint.constant = preferredSize.height - } - - private func preferredSize() -> NSSize { - withPianoWaveformKeyboard(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 } - - withPianoWaveformKeyboard(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 displayNote = withPianoWaveformKeyboard( - menuBand: menuBand, - { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } - ), - let playedNote = playedNote(for: displayNote, menuBand: menuBand) - else { return } - let expression = withPianoWaveformKeyboard(menuBand: menuBand) { - NoteExpression.values(for: displayNote, at: point, layout: Self.rendererLayout) - } - currentDisplayNote = displayNote - currentPlayedNote = playedNote - hoveredNote = displayNote - menuBand.startTapNote( - playedNote, - velocity: expression.velocity, - pan: expression.pan, - displayNote: displayNote - ) - needsDisplay = true - } - - override func mouseDragged(with event: NSEvent) { - guard let menuBand = menuBand, - let point = rendererPoint(from: event) else { return } - let hovered = withPianoWaveformKeyboard( - menuBand: menuBand, - { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } - ) - hoveredNote = hovered - - if hovered != currentDisplayNote { - if let previous = currentPlayedNote { - menuBand.stopTapNote(previous) - } - if let nextDisplay = hovered, - let nextPlayed = playedNote(for: nextDisplay, menuBand: menuBand) { - let expression = withPianoWaveformKeyboard(menuBand: menuBand) { - NoteExpression.values(for: nextDisplay, at: point, layout: Self.rendererLayout) - } - menuBand.startTapNote( - nextPlayed, - velocity: expression.velocity, - pan: expression.pan, - displayNote: nextDisplay - ) - currentPlayedNote = nextPlayed - } else { - currentPlayedNote = nil - } - currentDisplayNote = hovered - } else if let current = currentDisplayNote, - currentPlayedNote != nil { - let expression = withPianoWaveformKeyboard(menuBand: menuBand) { - NoteExpression.values(for: current, at: point, layout: Self.rendererLayout) - } - if let playedNote = currentPlayedNote { - menuBand.updateTapPan(playedNote, pan: expression.pan) - } - } - needsDisplay = true - } - - override func mouseUp(with event: NSEvent) { - if let note = currentPlayedNote { - menuBand?.stopTapNote(note) - } - currentDisplayNote = nil - currentPlayedNote = nil - updateHover(with: event) - } - - func clearInteraction() { - currentDisplayNote = nil - currentPlayedNote = 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 = withPianoWaveformKeyboard( - 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 = withPianoWaveformKeyboard(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 = withPianoWaveformKeyboard(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 func playedNote(for displayNote: UInt8, menuBand: MenuBandController) -> UInt8? { - let value = Int(displayNote) + menuBand.octaveShift * 12 - guard value >= 0, value <= 127 else { return nil } - return UInt8(value) - } -} - -private final class PianoWaveformDragHandleView: 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 - } - } -} - -/// Tall traditional-piano aspect for the floating overlay. Multiplies -/// white-key height (and black-key height proportionally) so the keys -/// read like a real keyboard instead of menubar squares. -private let pianoWaveformKeyHeightScale: CGFloat = 2.4 - -private func withPianoWaveformKeyboard(menuBand: MenuBandController?, _ body: () -> T) -> T { - let oldLayout = KeyboardIconRenderer.displayLayout - let oldKeymap = KeyboardIconRenderer.activeKeymap - let oldScale = KeyboardIconRenderer.keyHeightScale - KeyboardIconRenderer.displayLayout = .full - KeyboardIconRenderer.keyHeightScale = pianoWaveformKeyHeightScale - if let menuBand = menuBand { - KeyboardIconRenderer.activeKeymap = menuBand.keymap - } - defer { - KeyboardIconRenderer.displayLayout = oldLayout - KeyboardIconRenderer.activeKeymap = oldKeymap - KeyboardIconRenderer.keyHeightScale = oldScale - } - return body() -} - -private final class PianoWaveformPanel: 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 13a82bc304..c946439f05 100644 --- a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift +++ b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift @@ -10,6 +10,8 @@ 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 { + private static let pianoWaveformKeyHeightScale: CGFloat = 2.4 + enum Layout { case fixedCanvas case tightActiveRange @@ -158,6 +160,23 @@ enum KeyboardIconRenderer { /// live audio metering rather than three identical pulses. static var miniVisualizerPhase: CFTimeInterval = 0 + static func withPianoWaveformKeyboard(keymap: Keymap?, _ body: () -> T) -> T { + let oldLayout = displayLayout + let oldKeymap = activeKeymap + let oldScale = keyHeightScale + displayLayout = .full + keyHeightScale = pianoWaveformKeyHeightScale + if let keymap { + activeKeymap = keymap + } + defer { + displayLayout = oldLayout + activeKeymap = oldKeymap + keyHeightScale = oldScale + } + return body() + } + // Settings — simple monochrome music note that reads like a native // status-bar icon. Click → popup menu with TYPE / MIDI / Instrument / // About. diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index 6cc0e4422e..521a8c3611 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -152,6 +152,7 @@ final class MenuBandPopoverViewController: NSViewController { private var chordCandidatesStack: NSStackView! private var chordCandidatesRow: NSView! private var lastCompleteChordNames: Set = [] + private let chordCandidatesRowHorizontalInset: CGFloat = 6 private var instrumentSeparator: NSView! private var octaveStepper: NSStepper! private var octaveLabel: NSTextField! @@ -620,8 +621,8 @@ final class MenuBandPopoverViewController: NSViewController { NSLayoutConstraint.activate([ chordCandidatesStack.centerXAnchor.constraint(equalTo: chordCandidatesRow.centerXAnchor), chordCandidatesStack.centerYAnchor.constraint(equalTo: chordCandidatesRow.centerYAnchor), - chordCandidatesStack.leadingAnchor.constraint(greaterThanOrEqualTo: chordCandidatesRow.leadingAnchor, constant: 6), - chordCandidatesStack.trailingAnchor.constraint(lessThanOrEqualTo: chordCandidatesRow.trailingAnchor, constant: -6), + chordCandidatesStack.leadingAnchor.constraint(greaterThanOrEqualTo: chordCandidatesRow.leadingAnchor, constant: chordCandidatesRowHorizontalInset), + chordCandidatesStack.trailingAnchor.constraint(lessThanOrEqualTo: chordCandidatesRow.trailingAnchor, constant: -chordCandidatesRowHorizontalInset), ]) waveformBezel.addSubview(chordCandidatesRow) NSLayoutConstraint.activate([ @@ -1175,9 +1176,18 @@ final class MenuBandPopoverViewController: NSViewController { .bestMatch(from: [.aqua, .darkAqua]) == .darkAqua let newComplete = Set(candidates.filter(\.isComplete).map(\.name)) let justCompleted = newComplete.subtracting(lastCompleteChordNames) + let availableChordWidth = max(chordCandidatesRow.bounds.width - chordCandidatesRowHorizontalInset * 2, 0) + var consumedChordWidth: CGFloat = 0 for candidate in candidates { let card = FloatingChordCandidateCard.build(candidate: candidate, isDark: isDark) + card.layoutSubtreeIfNeeded() + let cardWidth = card.fittingSize.width + let nextWidth = consumedChordWidth == 0 + ? cardWidth + : consumedChordWidth + chordRow.spacing + cardWidth + guard consumedChordWidth == 0 || nextWidth <= availableChordWidth else { break } chordRow.addArrangedSubview(card) + consumedChordWidth = nextWidth if candidate.isComplete && justCompleted.contains(candidate.name) { let shake = CAKeyframeAnimation(keyPath: "transform.translation.x") shake.values = [0, -7, 7, -5, 5, -3, 3, 0] diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift new file mode 100644 index 0000000000..e4981c1988 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/CollapsedPianoWaveformView.swift @@ -0,0 +1,358 @@ +// +// CollapsedPianoWaveformView.swift +// MenuBand +// +// Created by Esteban Uribe on 5/3/26. +// + + +import AppKit + +final class CollapsedPianoWaveformView: NSView { + private static var shouldUseLiquidGlass: Bool { + PianoWaveformWindowStyle.shouldUseLiquidGlass + } + + private weak var menuBand: MenuBandController? + private let contentContainer = NSView() + private let waveformContainer = NSView() + private let waveformClipView = NSView() + private let waveformView = WaveformView() + private let heldNotesContainer = NSView() + private let heldNotesStack = NSStackView() + private let instrumentRow = NSView() + private let instrumentArrows = ArrowKeysIndicator() + private let instrumentLabel = NSTextField(labelWithString: "") + private var trackingArea: NSTrackingArea? + private weak var paletteGlassView: NSView? + private weak var waveformGlassView: NSView? + private weak var instrumentRowGlassView: NSView? + + var onHoverChanged: ((Bool) -> Void)? + var onStepBackward: (() -> Void)? + var onStepForward: (() -> Void)? + var onStepUp: (() -> Void)? + var onStepDown: (() -> Void)? + + private static let waveformHeight: CGFloat = 64 + private static let heldNotesRowHeight: CGFloat = 16 + private static let instrumentRowHeight: CGFloat = 22 + + init(menuBand: MenuBandController) { + self.menuBand = menuBand + super.init(frame: .zero) + wantsLayer = true + layer?.cornerRadius = 10 + layer?.masksToBounds = true + + contentContainer.translatesAutoresizingMaskIntoConstraints = false + waveformView.menuBand = menuBand + waveformView.translatesAutoresizingMaskIntoConstraints = false + waveformView.setSurfaceStyle(.standard) + + waveformContainer.wantsLayer = true + waveformContainer.translatesAutoresizingMaskIntoConstraints = false + waveformContainer.layer?.cornerRadius = 8 + waveformContainer.layer?.masksToBounds = false + + waveformClipView.wantsLayer = true + waveformClipView.translatesAutoresizingMaskIntoConstraints = false + waveformClipView.layer?.cornerRadius = 8 + waveformClipView.layer?.masksToBounds = true + + heldNotesContainer.translatesAutoresizingMaskIntoConstraints = false + heldNotesStack.orientation = .horizontal + heldNotesStack.alignment = .centerY + heldNotesStack.spacing = 4 + heldNotesStack.translatesAutoresizingMaskIntoConstraints = false + + instrumentRow.translatesAutoresizingMaskIntoConstraints = false + instrumentRow.wantsLayer = true + instrumentRow.layer?.cornerRadius = 7 + if #available(macOS 10.15, *) { + instrumentRow.layer?.cornerCurve = .continuous + } + instrumentArrows.translatesAutoresizingMaskIntoConstraints = false + instrumentArrows.setContentHuggingPriority(.required, for: .horizontal) + instrumentArrows.setContentCompressionResistancePriority(.required, for: .horizontal) + instrumentArrows.displayMode = .horizontalPair + instrumentArrows.style = .prominent + instrumentArrows.toolTip = "Change instrument" + instrumentArrows.onClick = { [weak self] direction, isDown in + guard let self, isDown else { return } + switch direction { + case 0: + self.onStepBackward?() + case 1: + self.onStepForward?() + case 2: + self.onStepDown?() + case 3: + self.onStepUp?() + default: + break + } + } + + instrumentLabel.translatesAutoresizingMaskIntoConstraints = false + instrumentLabel.lineBreakMode = .byTruncatingTail + instrumentLabel.drawsBackground = false + instrumentLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + addSubview(contentContainer) + contentContainer.addSubview(waveformContainer) + contentContainer.addSubview(heldNotesContainer) + contentContainer.addSubview(instrumentRow) + waveformContainer.addSubview(waveformClipView) + waveformClipView.addSubview(waveformView) + heldNotesContainer.addSubview(heldNotesStack) + instrumentRow.addSubview(instrumentArrows) + instrumentRow.addSubview(instrumentLabel) + installLiquidGlassBackgrounds() + + NSLayoutConstraint.activate([ + widthAnchor.constraint(equalToConstant: KeyboardIconRenderer.imageSize.width), + contentContainer.leadingAnchor.constraint(equalTo: leadingAnchor), + contentContainer.trailingAnchor.constraint(equalTo: trailingAnchor), + contentContainer.topAnchor.constraint(equalTo: topAnchor), + contentContainer.bottomAnchor.constraint(equalTo: bottomAnchor), + + waveformContainer.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor), + waveformContainer.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor), + waveformContainer.topAnchor.constraint(equalTo: contentContainer.topAnchor), + waveformContainer.heightAnchor.constraint(equalToConstant: Self.waveformHeight), + + waveformClipView.leadingAnchor.constraint(equalTo: waveformContainer.leadingAnchor, constant: 5), + waveformClipView.trailingAnchor.constraint(equalTo: waveformContainer.trailingAnchor, constant: -5), + waveformClipView.topAnchor.constraint(equalTo: waveformContainer.topAnchor, constant: 5), + waveformClipView.bottomAnchor.constraint(equalTo: waveformContainer.bottomAnchor, constant: -5), + + waveformView.leadingAnchor.constraint(equalTo: waveformClipView.leadingAnchor), + waveformView.trailingAnchor.constraint(equalTo: waveformClipView.trailingAnchor), + waveformView.topAnchor.constraint(equalTo: waveformClipView.topAnchor), + waveformView.bottomAnchor.constraint(equalTo: waveformClipView.bottomAnchor), + + heldNotesContainer.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor), + heldNotesContainer.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor), + heldNotesContainer.topAnchor.constraint(equalTo: waveformContainer.bottomAnchor, constant: 2), + heldNotesContainer.heightAnchor.constraint(equalToConstant: Self.heldNotesRowHeight), + + heldNotesStack.centerXAnchor.constraint(equalTo: heldNotesContainer.centerXAnchor), + heldNotesStack.centerYAnchor.constraint(equalTo: heldNotesContainer.centerYAnchor), + + instrumentRow.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor), + instrumentRow.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor), + instrumentRow.topAnchor.constraint(equalTo: heldNotesContainer.bottomAnchor, constant: 2), + instrumentRow.heightAnchor.constraint(equalToConstant: Self.instrumentRowHeight), + instrumentRow.bottomAnchor.constraint(equalTo: contentContainer.bottomAnchor, constant: -2), + + instrumentArrows.leadingAnchor.constraint(equalTo: instrumentRow.leadingAnchor, constant: 6), + instrumentArrows.centerYAnchor.constraint(equalTo: instrumentRow.centerYAnchor), + + instrumentLabel.leadingAnchor.constraint(equalTo: instrumentArrows.trailingAnchor, constant: 6), + instrumentLabel.centerYAnchor.constraint(equalTo: instrumentRow.centerYAnchor), + instrumentLabel.trailingAnchor.constraint(equalTo: instrumentRow.trailingAnchor, constant: -8), + ]) + + refresh() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let trackingArea { + removeTrackingArea(trackingArea) + } + let trackingArea = NSTrackingArea( + rect: bounds, + options: [.activeAlways, .inVisibleRect, .mouseEnteredAndExited], + owner: self, + userInfo: nil + ) + addTrackingArea(trackingArea) + self.trackingArea = trackingArea + } + + override func mouseEntered(with event: NSEvent) { + onHoverChanged?(true) + super.mouseEntered(with: event) + } + + override func mouseExited(with event: NSEvent) { + onHoverChanged?(false) + super.mouseExited(with: event) + } + + func refresh() { + guard let menuBand else { return } + let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + waveformView.setLightMode(!isDark) + + let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) + let familyColor = menuBand.midiMode + ? NSColor.controlAccentColor + : InstrumentListView.colorForProgram(safe) + + let waveformBackground = isDark + ? NSColor(white: 0.06, alpha: 1.0) + : NSColor(white: 0.82, alpha: 1.0) + let glassWaveformBackground = isDark + ? NSColor.white.withAlphaComponent(0.04) + : NSColor.white.withAlphaComponent(0.18) + let instrumentRowBackground = isDark + ? NSColor.white.withAlphaComponent(0.08) + : NSColor.white.withAlphaComponent(0.3) + waveformContainer.layer?.backgroundColor = NSColor.clear.cgColor + waveformClipView.layer?.backgroundColor = Self.shouldUseLiquidGlass + ? glassWaveformBackground.cgColor + : waveformBackground.cgColor + waveformContainer.layer?.borderWidth = 1 + waveformContainer.layer?.borderColor = familyColor.withAlphaComponent( + Self.shouldUseLiquidGlass ? 0.22 : 0.55 + ).cgColor + instrumentRow.layer?.backgroundColor = Self.shouldUseLiquidGlass + ? NSColor.clear.cgColor + : instrumentRowBackground.cgColor + instrumentRow.layer?.borderWidth = 1 + instrumentRow.layer?.borderColor = familyColor.withAlphaComponent( + Self.shouldUseLiquidGlass ? 0.22 : 0.35 + ).cgColor + instrumentLabel.textColor = isDark ? .white : .black + instrumentArrows.accentColor = familyColor + instrumentArrows.isDarkAppearance = isDark + + if menuBand.midiMode { + waveformView.setDotMatrix(MenuBandPopoverViewController.midiDotPattern) + waveformView.setBaseColor(.controlAccentColor) + } else { + waveformView.setDotMatrix(nil) + waveformView.setBaseColor(familyColor) + } + + let shadow = NSShadow() + shadow.shadowColor = familyColor.withAlphaComponent(isDark ? 0.9 : 0.55) + shadow.shadowOffset = NSSize(width: 0, height: -1) + shadow.shadowBlurRadius = 3 + let titleFont: NSFont = { + if let descriptor = AppDelegate.ywftBoldDescriptor, + let font = NSFont(descriptor: descriptor, size: 14), + font.familyName == "YWFT Processing" { + return font + } + return NSFont.systemFont(ofSize: 14, weight: .black) + }() + instrumentLabel.attributedStringValue = NSAttributedString( + string: GeneralMIDI.programNames[safe], + attributes: [ + .font: titleFont, + .foregroundColor: isDark ? NSColor.white : NSColor.black, + .shadow: shadow, + ] + ) + + for view in heldNotesStack.arrangedSubviews { + heldNotesStack.removeArrangedSubview(view) + view.removeFromSuperview() + } + for name in menuBand.heldNoteNames() { + heldNotesStack.addArrangedSubview(makeHeldNoteBox(name: name, color: familyColor)) + } + + if Self.shouldUseLiquidGlass, #available(macOS 26.0, *) { + let paletteTint = familyColor.withAlphaComponent(menuBand.midiMode ? 0.20 : 0.16) + (paletteGlassView as? NSGlassEffectView)?.style = .clear + (paletteGlassView as? NSGlassEffectView)?.tintColor = paletteTint + (waveformGlassView as? NSGlassEffectView)?.style = .clear + (waveformGlassView as? NSGlassEffectView)?.tintColor = paletteTint.withAlphaComponent(0.55) + (instrumentRowGlassView as? NSGlassEffectView)?.style = .clear + (instrumentRowGlassView as? NSGlassEffectView)?.tintColor = paletteTint.withAlphaComponent(0.42) + layer?.backgroundColor = NSColor.clear.cgColor + } else { + layer?.backgroundColor = (isDark + ? NSColor(white: 0.06, alpha: 0.96) + : NSColor(white: 0.88, alpha: 0.96)).cgColor + } + } + + func setLive(_ isLive: Bool) { + waveformView.isLive = isLive + } + + private func makeHeldNoteBox(name: String, color: NSColor) -> NSView { + let box = NSView() + box.translatesAutoresizingMaskIntoConstraints = false + box.wantsLayer = true + box.layer?.cornerRadius = 4 + box.layer?.backgroundColor = color.withAlphaComponent(0.85).cgColor + + let label = NSTextField(labelWithString: name) + label.translatesAutoresizingMaskIntoConstraints = false + label.font = NSFont.monospacedSystemFont(ofSize: 9, weight: .heavy) + label.textColor = .black + box.addSubview(label) + + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: box.leadingAnchor, constant: 5), + label.trailingAnchor.constraint(equalTo: box.trailingAnchor, constant: -5), + label.topAnchor.constraint(equalTo: box.topAnchor, constant: 1), + label.bottomAnchor.constraint(equalTo: box.bottomAnchor, constant: -1), + ]) + return box + } + + private func installLiquidGlassBackgrounds() { + guard Self.shouldUseLiquidGlass, #available(macOS 26.0, *) else { return } + + let paletteGlassView = CollapsedPianoWaveformGlassEffectView() + paletteGlassView.translatesAutoresizingMaskIntoConstraints = false + paletteGlassView.cornerRadius = 10 + addSubview(paletteGlassView, positioned: .below, relativeTo: contentContainer) + NSLayoutConstraint.activate([ + paletteGlassView.leadingAnchor.constraint(equalTo: leadingAnchor), + paletteGlassView.trailingAnchor.constraint(equalTo: trailingAnchor), + paletteGlassView.topAnchor.constraint(equalTo: topAnchor), + paletteGlassView.bottomAnchor.constraint(equalTo: bottomAnchor), + ]) + self.paletteGlassView = paletteGlassView + + self.waveformGlassView = installGlassBackground( + matchedTo: waveformContainer, + below: waveformContainer, + cornerRadius: 8 + ) + self.instrumentRowGlassView = installGlassBackground( + matchedTo: instrumentRow, + below: instrumentRow, + cornerRadius: 7 + ) + } + + @available(macOS 26.0, *) + private func installGlassBackground(matchedTo target: NSView, + below anchor: NSView, + cornerRadius: CGFloat) -> NSView { + let glassView = CollapsedPianoWaveformGlassEffectView() + glassView.translatesAutoresizingMaskIntoConstraints = false + glassView.cornerRadius = cornerRadius + addSubview(glassView, positioned: .below, relativeTo: anchor) + NSLayoutConstraint.activate([ + glassView.leadingAnchor.constraint(equalTo: target.leadingAnchor), + glassView.trailingAnchor.constraint(equalTo: target.trailingAnchor), + glassView.topAnchor.constraint(equalTo: target.topAnchor), + glassView.bottomAnchor.constraint(equalTo: target.bottomAnchor), + ]) + return glassView + } + +} + +@available(macOS 26.0, *) +private final class CollapsedPianoWaveformGlassEffectView: NSGlassEffectView { + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } +} diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/ExpandedPianoWaveformView.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/ExpandedPianoWaveformView.swift new file mode 100644 index 0000000000..e992a4c8aa --- /dev/null +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/ExpandedPianoWaveformView.swift @@ -0,0 +1,611 @@ +// +// ExpandedPianoWaveformView.swift +// MenuBand +// +// Created by Esteban Uribe on 5/3/26. +// + + +import AppKit + +final class ExpandedPianoWaveformView: NSView { + static var shouldUseLiquidGlass: Bool { + PianoWaveformWindowStyle.shouldUseLiquidGlass + } + + private weak var menuBand: MenuBandController? + private let contentStack = NSStackView() + private let waveformSection = NSView() + private let waveformView = WaveformView() + private let waveformBezel = NSView() + private let waveformClipView = NSView() + private let heldNotesStack = NSStackView() + private let heldNotesRow = NSView() + private let chordCandidatesStack = NSStackView() + private let chordCandidatesRow = NSView() + private var lastCompleteChordNames: Set = [] + private let instrumentReadout = NSTextField(labelWithString: "") + private let instrumentTitleRow: NSStackView + private let pianoView: PianoKeyboardView + private let shortcutHintRow = NSStackView() + private let focusHintLabel = NSTextField(labelWithString: "") + private let layoutHintLabel = NSTextField(labelWithString: "") + private weak var paletteGlassView: NSView? + private weak var waveformGlassView: NSView? + private weak var waveformSectionGlassView: NSView? + private weak var pianoGlassView: NSView? + private weak var keymapGlassView: NSView? + private weak var hintGlassView: NSView? + /// Large QWERTY keymap shown beneath the piano so the user can + /// see at a glance which physical keys play which notes. Driven + /// at 2× scale so it's legible at the floating palette's size. + private let qwertyView = QwertyLayoutView() + + var isPianoFocusActive: (() -> Bool)? + var onHoverChanged: ((Bool) -> Void)? + + private let pianoScale: CGFloat = 1.6 + private let inset: CGFloat = 14 + private let gap: CGFloat = 8 + private let hintHeight: CGFloat = 20 + private let heldNotesRowHeight: CGFloat = 26 + private let chordCandidatesRowHeight: CGFloat = 30 + private let chordCandidatesRowHorizontalInset: CGFloat = 6 + private var waveformHeightConstraint: NSLayoutConstraint? + private var isPresented = false + private var trackingArea: NSTrackingArea? + private static let panelCornerRadius: CGFloat = 18 + private static let sectionCornerRadius: CGFloat = 14 + private static let waveformClipCornerRadius: CGFloat = 12 + private static let expandedPanelWidth: CGFloat = 440 + + init(menuBand: MenuBandController) { + self.menuBand = menuBand + let titleLeftSpacer = NSView() + let titleRightSpacer = NSView() + titleLeftSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) + titleRightSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) + self.instrumentTitleRow = NSStackView(views: [titleLeftSpacer, instrumentReadout, titleRightSpacer]) + self.pianoView = PianoKeyboardView(menuBand: menuBand, pianoScale: pianoScale) + super.init(frame: NSRect(origin: .zero, size: .zero)) + wantsLayer = true + + waveformView.menuBand = menuBand + waveformView.translatesAutoresizingMaskIntoConstraints = false + waveformView.setSurfaceStyle(.glassEmbedded) + contentStack.orientation = .vertical + contentStack.alignment = .centerX + contentStack.distribution = .fill + contentStack.spacing = gap + contentStack.translatesAutoresizingMaskIntoConstraints = false + waveformSection.wantsLayer = true + waveformSection.layer?.cornerRadius = Self.sectionCornerRadius + waveformSection.layer?.borderWidth = 0.8 + if #available(macOS 10.15, *) { + waveformSection.layer?.cornerCurve = .continuous + } + waveformSection.translatesAutoresizingMaskIntoConstraints = false + waveformBezel.wantsLayer = true + waveformBezel.layer?.cornerRadius = Self.waveformClipCornerRadius + 2 + waveformBezel.layer?.borderWidth = 0 + if #available(macOS 10.15, *) { + waveformBezel.layer?.cornerCurve = .continuous + } + waveformBezel.translatesAutoresizingMaskIntoConstraints = false + waveformClipView.wantsLayer = true + waveformClipView.translatesAutoresizingMaskIntoConstraints = false + waveformClipView.layer?.cornerRadius = Self.waveformClipCornerRadius + waveformClipView.layer?.masksToBounds = true + if #available(macOS 10.15, *) { + waveformClipView.layer?.cornerCurve = .continuous + } + heldNotesStack.orientation = .horizontal + heldNotesStack.alignment = .centerY + heldNotesStack.spacing = 6 + heldNotesStack.translatesAutoresizingMaskIntoConstraints = false + heldNotesRow.translatesAutoresizingMaskIntoConstraints = false + heldNotesRow.addSubview(heldNotesStack) + chordCandidatesStack.orientation = .horizontal + chordCandidatesStack.alignment = .centerY + chordCandidatesStack.spacing = 6 + chordCandidatesStack.translatesAutoresizingMaskIntoConstraints = false + chordCandidatesRow.translatesAutoresizingMaskIntoConstraints = false + chordCandidatesRow.addSubview(chordCandidatesStack) + instrumentReadout.lineBreakMode = .byTruncatingTail + instrumentReadout.alignment = .center + instrumentReadout.setContentHuggingPriority(.defaultHigh, for: .horizontal) + instrumentReadout.setContentCompressionResistancePriority(.required, for: .horizontal) + instrumentTitleRow.orientation = .horizontal + instrumentTitleRow.alignment = .centerY + instrumentTitleRow.distribution = .fill + instrumentTitleRow.spacing = 0 + instrumentTitleRow.translatesAutoresizingMaskIntoConstraints = false + pianoView.translatesAutoresizingMaskIntoConstraints = false + shortcutHintRow.orientation = .horizontal + shortcutHintRow.alignment = .centerY + shortcutHintRow.distribution = .fill + shortcutHintRow.spacing = gap + shortcutHintRow.translatesAutoresizingMaskIntoConstraints = false + focusHintLabel.translatesAutoresizingMaskIntoConstraints = false + layoutHintLabel.translatesAutoresizingMaskIntoConstraints = false + qwertyView.scale = 1.4 + qwertyView.keymap = menuBand.keymap + qwertyView.translatesAutoresizingMaskIntoConstraints = false + // Mouse-tap on a keycap → route through the controller's + // local-key handler so the floating palette's QWERTY map + // plays the same notes the physical keyboard would. + qwertyView.onKey = { [weak self] keyCode, isDown in + guard let self = self, let menuBand = self.menuBand else { return } + menuBand.handleLocalKey(keyCode: keyCode, isDown: isDown, + isRepeat: false, flags: []) + self.refresh() + } + // Held-note pills and chord-suggestion cards overlay the metal + // visualizer directly so the waveform doubles as the canvas + // for the chord readout. Stack vertically: pills on top, cards + // beneath, both centered. Waveform draws underneath, peeking + // through the translucent card backgrounds. + waveformBezel.addSubview(waveformClipView) + waveformClipView.addSubview(waveformView) + waveformBezel.layer?.masksToBounds = false + heldNotesRow.wantsLayer = true + heldNotesRow.layer?.masksToBounds = false + chordCandidatesRow.wantsLayer = true + chordCandidatesRow.layer?.masksToBounds = false + waveformBezel.addSubview(heldNotesRow) + waveformBezel.addSubview(chordCandidatesRow) + waveformSection.addSubview(waveformBezel) + waveformSection.addSubview(instrumentTitleRow) + addSubview(contentStack) + contentStack.addArrangedSubview(waveformSection) + contentStack.addArrangedSubview(pianoView) + shortcutHintRow.addArrangedSubview(layoutHintLabel) + shortcutHintRow.addArrangedSubview(NSView()) + shortcutHintRow.addArrangedSubview(focusHintLabel) + contentStack.addArrangedSubview(shortcutHintRow) + contentStack.addArrangedSubview(qwertyView) + for label in [focusHintLabel, layoutHintLabel] { + label.font = NSFont.systemFont(ofSize: 10, weight: .bold) + label.textColor = .secondaryLabelColor + label.maximumNumberOfLines = 1 + label.lineBreakMode = .byTruncatingTail + } + layoutHintLabel.alignment = .left + focusHintLabel.alignment = .right + updateShortcutHint() + installLiquidGlassBackgrounds() + + let keyboardSize = self.keyboardSize() + let waveformHeightConstraint = waveformView.heightAnchor.constraint( + equalToConstant: waveformHeight(for: keyboardSize) + ) + self.waveformHeightConstraint = waveformHeightConstraint + let bezelInset: CGFloat = 5 + let titleSpacers = instrumentTitleRow.arrangedSubviews + + NSLayoutConstraint.activate([ + widthAnchor.constraint( + equalToConstant: max(keyboardSize.width + inset * 2, Self.expandedPanelWidth) + ), + + contentStack.topAnchor.constraint(equalTo: topAnchor, constant: inset), + contentStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset), + contentStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset), + contentStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -inset), + + waveformSection.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor), + waveformSection.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor), + + heldNotesStack.centerXAnchor.constraint(equalTo: heldNotesRow.centerXAnchor), + heldNotesStack.centerYAnchor.constraint(equalTo: heldNotesRow.centerYAnchor), + heldNotesStack.leadingAnchor.constraint(greaterThanOrEqualTo: heldNotesRow.leadingAnchor, constant: 6), + heldNotesStack.trailingAnchor.constraint(lessThanOrEqualTo: heldNotesRow.trailingAnchor, constant: -6), + heldNotesRow.heightAnchor.constraint(equalToConstant: heldNotesRowHeight), + + chordCandidatesStack.centerXAnchor.constraint(equalTo: chordCandidatesRow.centerXAnchor), + chordCandidatesStack.centerYAnchor.constraint(equalTo: chordCandidatesRow.centerYAnchor), + chordCandidatesStack.leadingAnchor.constraint(greaterThanOrEqualTo: chordCandidatesRow.leadingAnchor, constant: chordCandidatesRowHorizontalInset), + chordCandidatesStack.trailingAnchor.constraint(lessThanOrEqualTo: chordCandidatesRow.trailingAnchor, constant: -chordCandidatesRowHorizontalInset), + chordCandidatesRow.heightAnchor.constraint(equalToConstant: chordCandidatesRowHeight), + + waveformBezel.topAnchor.constraint(equalTo: waveformSection.topAnchor, constant: bezelInset), + waveformBezel.leadingAnchor.constraint(equalTo: waveformSection.leadingAnchor, constant: bezelInset), + waveformBezel.trailingAnchor.constraint(equalTo: waveformSection.trailingAnchor, constant: -bezelInset), + waveformClipView.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor, constant: bezelInset), + waveformClipView.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor, constant: -bezelInset), + waveformClipView.topAnchor.constraint(equalTo: waveformBezel.topAnchor, constant: bezelInset), + waveformClipView.bottomAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: -bezelInset), + waveformView.leadingAnchor.constraint(equalTo: waveformClipView.leadingAnchor), + waveformView.trailingAnchor.constraint(equalTo: waveformClipView.trailingAnchor), + waveformView.topAnchor.constraint(equalTo: waveformClipView.topAnchor), + waveformView.bottomAnchor.constraint(equalTo: waveformClipView.bottomAnchor), + waveformHeightConstraint, + + heldNotesRow.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor), + heldNotesRow.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor), + heldNotesRow.topAnchor.constraint(equalTo: waveformBezel.topAnchor, constant: 8), + + chordCandidatesRow.leadingAnchor.constraint(equalTo: waveformBezel.leadingAnchor), + chordCandidatesRow.trailingAnchor.constraint(equalTo: waveformBezel.trailingAnchor), + chordCandidatesRow.bottomAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: -8), + + instrumentTitleRow.topAnchor.constraint(equalTo: waveformBezel.bottomAnchor, constant: 6), + instrumentTitleRow.leadingAnchor.constraint(equalTo: waveformSection.leadingAnchor, constant: 6), + instrumentTitleRow.trailingAnchor.constraint(equalTo: waveformSection.trailingAnchor, constant: -6), + instrumentTitleRow.bottomAnchor.constraint(equalTo: waveformSection.bottomAnchor, constant: -6), + + shortcutHintRow.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor), + shortcutHintRow.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor), + shortcutHintRow.heightAnchor.constraint(equalToConstant: hintHeight), + + qwertyView.centerXAnchor.constraint(equalTo: centerXAnchor), + qwertyView.widthAnchor.constraint( + equalToConstant: QwertyLayoutView.intrinsicSize.width * 1.4 + ), + qwertyView.heightAnchor.constraint( + equalToConstant: QwertyLayoutView.intrinsicSize.height * 1.4 + ), + ]) + if titleSpacers.count == 3 { + titleSpacers[0].widthAnchor.constraint(equalTo: titleSpacers[2].widthAnchor).isActive = true + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + private func installLiquidGlassBackgrounds() { + guard Self.shouldUseLiquidGlass, #available(macOS 26.0, *) else { return } + + let paletteGlassView = ExpandedPianoWaveformGlassEffectView() + paletteGlassView.translatesAutoresizingMaskIntoConstraints = false + paletteGlassView.cornerRadius = Self.panelCornerRadius + addSubview(paletteGlassView, positioned: .below, relativeTo: waveformSection) + NSLayoutConstraint.activate([ + paletteGlassView.leadingAnchor.constraint(equalTo: leadingAnchor), + paletteGlassView.trailingAnchor.constraint(equalTo: trailingAnchor), + paletteGlassView.topAnchor.constraint(equalTo: topAnchor), + paletteGlassView.bottomAnchor.constraint(equalTo: bottomAnchor), + ]) + self.paletteGlassView = paletteGlassView + + self.waveformSectionGlassView = installGlassBackground( + matchedTo: waveformSection, + below: waveformSection, + cornerRadius: Self.sectionCornerRadius + ) + self.pianoGlassView = installGlassBackground( + matchedTo: pianoView, + below: pianoView, + cornerRadius: Self.sectionCornerRadius + ) + self.keymapGlassView = installGlassBackground( + matchedTo: qwertyView, + below: qwertyView, + cornerRadius: Self.sectionCornerRadius + ) + self.hintGlassView = installGlassBackground( + matchedTo: shortcutHintRow, + below: shortcutHintRow, + cornerRadius: Self.sectionCornerRadius + ) + } + + @available(macOS 26.0, *) + private func installGlassBackground(matchedTo target: NSView, + below anchor: NSView, + cornerRadius: CGFloat) -> NSView { + let glassView = ExpandedPianoWaveformGlassEffectView() + glassView.translatesAutoresizingMaskIntoConstraints = false + glassView.cornerRadius = cornerRadius + addSubview(glassView, positioned: .below, relativeTo: anchor) + NSLayoutConstraint.activate([ + glassView.leadingAnchor.constraint(equalTo: target.leadingAnchor), + glassView.trailingAnchor.constraint(equalTo: target.trailingAnchor), + glassView.topAnchor.constraint(equalTo: target.topAnchor), + glassView.bottomAnchor.constraint(equalTo: target.bottomAnchor), + ]) + return glassView + } + + override var acceptsFirstResponder: Bool { true } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let trackingArea { + removeTrackingArea(trackingArea) + } + let trackingArea = NSTrackingArea( + rect: bounds, + options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], + owner: self, + userInfo: nil + ) + addTrackingArea(trackingArea) + self.trackingArea = trackingArea + } + + override func mouseEntered(with event: NSEvent) { + super.mouseEntered(with: event) + onHoverChanged?(true) + } + + override func mouseExited(with event: NSEvent) { + super.mouseExited(with: event) + onHoverChanged?(false) + } + + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + applyAppearanceToVisualizer() + } + + override var fittingSize: NSSize { + pianoView.refreshLayout() + layoutSubtreeIfNeeded() + return super.fittingSize + } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + if Self.shouldUseLiquidGlass, #available(macOS 26.0, *) { + return + } + 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() + applyAppearanceToVisualizer() + refreshHeldNotes() + updateInstrumentReadout() + applyWaveformTint() + updateWaveformLiveState(isPresented: isPresented) + needsDisplay = true + pianoView.needsDisplay = true + } + + func clearInteraction() { + pianoView.clearInteraction() + lastCompleteChordNames = [] + } + + func setPresented(_ isPresented: Bool) { + self.isPresented = isPresented + if !isPresented { + clearHeldNotes() + } + applyAppearanceToVisualizer() + applyWaveformTint() + 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 applyAppearanceToVisualizer() { + let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + waveformView.setLightMode(!isDark) + if isDark { + waveformSection.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.06).cgColor + waveformBezel.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.04).cgColor + } else { + waveformSection.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.22).cgColor + waveformBezel.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.18).cgColor + } + } + + private func applyWaveformTint() { + guard let menuBand else { return } + if menuBand.midiMode { + waveformView.setDotMatrix(MenuBandPopoverViewController.midiDotPattern) + waveformView.setBaseColor(.controlAccentColor) + waveformSection.layer?.borderColor = NSColor.controlAccentColor + .withAlphaComponent(0.24).cgColor + } else { + waveformView.setDotMatrix(nil) + let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) + let familyColor = InstrumentListView.colorForProgram(safe) + waveformView.setBaseColor(familyColor) + waveformSection.layer?.borderColor = familyColor + .withAlphaComponent(0.22).cgColor + } + if #available(macOS 26.0, *) { + let paletteTint = paletteTintColor + for view in [paletteGlassView, waveformSectionGlassView, pianoGlassView, keymapGlassView, hintGlassView] { + (view as? NSGlassEffectView)?.tintColor = paletteTint + } + } + } + + var paletteTintColor: NSColor { + guard let menuBand else { return NSColor.controlAccentColor.withAlphaComponent(0.20) } + if menuBand.midiMode { + return NSColor.controlAccentColor.withAlphaComponent(0.20) + } + let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) + return InstrumentListView.colorForProgram(safe).withAlphaComponent(0.16) + } + + private func keyboardSize() -> NSSize { + KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand?.keymap) { + 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 * 1.25 + } + + private func refreshHeldNotes() { + guard isPresented else { + clearHeldNotes() + return + } + guard let menuBand else { return } + clearHeldNotes() + // Live state for the QWERTY keymap below the piano: light up + // the physical keys the user is currently holding, and route + // the qwertyView's onKey (mouse taps on caps) through the + // same handleLocalKey path the keyboard uses so the overlay + // is fully interactive. + qwertyView.litKeyCodes = menuBand.heldKeyCodes() + qwertyView.keymap = menuBand.keymap + let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) + let familyColor = menuBand.midiMode + ? NSColor.controlAccentColor + : InstrumentListView.colorForProgram(safe) + qwertyView.voiceColor = familyColor + + // Held-notes row: each currently sounding note as its own large + // pill so the chord shape reads at-a-glance. Always per-note — + // chord recognition lives in the candidates row below. + let names = menuBand.heldNoteNames() + for name in names { + heldNotesStack.addArrangedSubview(makeHeldNoteBox(name: name, color: familyColor)) + } + + // Chord candidates: every chord shape that contains the held + // pitch classes and whose missing notes are reachable on the + // active keymap. Cards re-render every refresh; transitions + // from incomplete → complete trigger a brief shake on the new + // complete card so the user feels the chord "lock in". + let candidates = menuBand.chordCandidates(maxResults: 8) + let newComplete = Set(candidates.filter(\.isComplete).map(\.name)) + let justCompleted = newComplete.subtracting(lastCompleteChordNames) + let availableChordWidth = max( + chordCandidatesRow.bounds.width - chordCandidatesRowHorizontalInset * 2, + Self.expandedPanelWidth - inset * 2 - 20 - chordCandidatesRowHorizontalInset * 2 + ) + var consumedChordWidth: CGFloat = 0 + for candidate in candidates { + let card = makeChordCandidateCard(candidate: candidate, color: familyColor) + card.layoutSubtreeIfNeeded() + let cardWidth = card.fittingSize.width + let nextWidth = consumedChordWidth == 0 + ? cardWidth + : consumedChordWidth + chordCandidatesStack.spacing + cardWidth + guard consumedChordWidth == 0 || nextWidth <= availableChordWidth else { break } + chordCandidatesStack.addArrangedSubview(card) + consumedChordWidth = nextWidth + if candidate.isComplete && justCompleted.contains(candidate.name) { + applyShake(to: card) + } + } + lastCompleteChordNames = newComplete + } + + private func clearHeldNotes() { + for view in heldNotesStack.arrangedSubviews { + heldNotesStack.removeArrangedSubview(view) + view.removeFromSuperview() + } + for view in chordCandidatesStack.arrangedSubviews { + chordCandidatesStack.removeArrangedSubview(view) + view.removeFromSuperview() + } + qwertyView.litKeyCodes = [] + lastCompleteChordNames = [] + } + + private func makeHeldNoteBox(name: String, color: NSColor) -> NSView { + let box = NSView() + box.wantsLayer = true + box.layer?.cornerRadius = 4 + box.layer?.backgroundColor = color.withAlphaComponent(0.92).cgColor + box.layer?.borderWidth = 1 + box.layer?.borderColor = color.shadow(withLevel: 0.35)?.cgColor ?? color.cgColor + box.translatesAutoresizingMaskIntoConstraints = false + let label = NSTextField(labelWithString: name) + label.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .heavy) + label.textColor = .black + label.drawsBackground = false + label.translatesAutoresizingMaskIntoConstraints = false + box.addSubview(label) + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: box.leadingAnchor, constant: 5), + label.trailingAnchor.constraint(equalTo: box.trailingAnchor, constant: -5), + label.topAnchor.constraint(equalTo: box.topAnchor, constant: 2), + label.bottomAnchor.constraint(equalTo: box.bottomAnchor, constant: -2), + box.heightAnchor.constraint(equalToConstant: 20), + ]) + return box + } + + private func makeChordCandidateCard(candidate: MenuBandController.ChordCandidate, + color: NSColor) -> NSView { + FloatingChordCandidateCard.build(candidate: candidate, + isDark: effectiveAppearance + .bestMatch(from: [.aqua, .darkAqua]) == .darkAqua) + } + + private func applyShake(to view: NSView) { + guard let layer = view.layer else { return } + let shake = CAKeyframeAnimation(keyPath: "transform.translation.x") + shake.values = [0, -7, 7, -5, 5, -3, 3, 0] + shake.keyTimes = [0, 0.12, 0.27, 0.42, 0.57, 0.72, 0.87, 1.0] + shake.duration = 0.46 + shake.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + layer.add(shake, forKey: "shake") + } + + private func updateInstrumentReadout() { + guard let menuBand else { return } + let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) + let title = GeneralMIDI.programNames[safe] + let familyColor = InstrumentListView.colorForProgram(safe) + let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + let textColor: NSColor = isDark ? .white : .black + let shadow = NSShadow() + shadow.shadowColor = (familyColor.highlight(withLevel: isDark ? 0.3 : 0.7) ?? familyColor) + shadow.shadowOffset = NSSize(width: 1, height: -1) + shadow.shadowBlurRadius = 0 + let titleFont: NSFont = { + if let desc = AppDelegate.ywftBoldDescriptor, + let font = NSFont(descriptor: desc, size: 18), + font.familyName == "YWFT Processing" { + return font + } + NSLog("MenuBand: YWFT bold descriptor unavailable; floating title falling back to system font") + return NSFont.systemFont(ofSize: 18, weight: .black) + }() + instrumentReadout.attributedStringValue = NSAttributedString( + string: title, + attributes: [ + .font: titleFont, + .foregroundColor: textColor, + .shadow: shadow, + ] + ) + } + + private func updateShortcutHint() { + let focusShortcut = MenuBandShortcutPreferences.focusShortcut.displayString + let layoutShortcut = MenuBandShortcut.layoutToggle.displayString + layoutHintLabel.stringValue = "Toggle Layout: \(layoutShortcut)" + focusHintLabel.stringValue = (isPianoFocusActive?() ?? false) + ? "Exit Focus: \(focusShortcut)" + : "Focus Piano: \(focusShortcut)" + } + +} + +@available(macOS 26.0, *) +final class ExpandedPianoWaveformGlassEffectView: NSGlassEffectView { + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } +} diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoKeyboardView.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoKeyboardView.swift new file mode 100644 index 0000000000..838becf8a2 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoKeyboardView.swift @@ -0,0 +1,239 @@ +// +// PianoKeyboardView.swift +// MenuBand +// +// Created by Esteban Uribe on 5/3/26. +// + + +import AppKit + +final class PianoKeyboardView: NSView { + private static let rendererLayout: KeyboardIconRenderer.Layout = .tightActiveRange + + private weak var menuBand: MenuBandController? + private var trackingArea: NSTrackingArea? + private var hoveredNote: UInt8? + private var currentDisplayNote: UInt8? + private var currentPlayedNote: 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 } + override var mouseDownCanMoveWindow: Bool { false } + + func refreshLayout() { + let preferredSize = preferredSize() + widthConstraint.constant = preferredSize.width + heightConstraint.constant = preferredSize.height + } + + private func preferredSize() -> NSSize { + KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand?.keymap) { + 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 } + + KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand.keymap) { + 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 displayNote = KeyboardIconRenderer.withPianoWaveformKeyboard( + keymap: menuBand.keymap, + { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } + ), + let playedNote = playedNote(for: displayNote, menuBand: menuBand) + else { return } + let expression = KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand.keymap) { + NoteExpression.values(for: displayNote, at: point, layout: Self.rendererLayout) + } + currentDisplayNote = displayNote + currentPlayedNote = playedNote + hoveredNote = displayNote + menuBand.startTapNote( + playedNote, + velocity: expression.velocity, + pan: expression.pan, + displayNote: displayNote + ) + needsDisplay = true + } + + override func mouseDragged(with event: NSEvent) { + guard let menuBand = menuBand, + let point = rendererPoint(from: event) else { return } + let hovered = KeyboardIconRenderer.withPianoWaveformKeyboard( + keymap: menuBand.keymap, + { KeyboardIconRenderer.noteAt(point, layout: Self.rendererLayout) } + ) + hoveredNote = hovered + + if hovered != currentDisplayNote { + if let previous = currentPlayedNote { + menuBand.stopTapNote(previous) + } + if let nextDisplay = hovered, + let nextPlayed = playedNote(for: nextDisplay, menuBand: menuBand) { + let expression = KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand.keymap) { + NoteExpression.values(for: nextDisplay, at: point, layout: Self.rendererLayout) + } + menuBand.startTapNote( + nextPlayed, + velocity: expression.velocity, + pan: expression.pan, + displayNote: nextDisplay + ) + currentPlayedNote = nextPlayed + } else { + currentPlayedNote = nil + } + currentDisplayNote = hovered + } else if let current = currentDisplayNote, + currentPlayedNote != nil { + let expression = KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand.keymap) { + NoteExpression.values(for: current, at: point, layout: Self.rendererLayout) + } + if let playedNote = currentPlayedNote { + menuBand.updateTapPan(playedNote, pan: expression.pan) + } + } + needsDisplay = true + } + + override func mouseUp(with event: NSEvent) { + if let note = currentPlayedNote { + menuBand?.stopTapNote(note) + } + currentDisplayNote = nil + currentPlayedNote = nil + updateHover(with: event) + } + + func clearInteraction() { + currentDisplayNote = nil + currentPlayedNote = 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 = KeyboardIconRenderer.withPianoWaveformKeyboard( + keymap: menuBand?.keymap, + { 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 = KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand?.keymap) { + 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 = KeyboardIconRenderer.withPianoWaveformKeyboard(keymap: menuBand?.keymap) { + 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 func playedNote(for displayNote: UInt8, menuBand: MenuBandController) -> UInt8? { + let value = Int(displayNote) + menuBand.octaveShift * 12 + guard value >= 0, value <= 127 else { return nil } + return UInt8(value) + } +} diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformViewController.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformViewController.swift new file mode 100644 index 0000000000..69360aa5ae --- /dev/null +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformViewController.swift @@ -0,0 +1,346 @@ +import AppKit + +final class PianoWaveformViewController: NSViewController { + enum PresentationMode { + case expanded + case collapsed + } + + private static let panelCornerRadius: CGFloat = 18 + + private let containerView = NSView() + private let expandedView: ExpandedPianoWaveformView + private let collapsedView: CollapsedPianoWaveformView + private let closeButton = NSButton() + private let dockButton = NSButton() + private let expandCollapseButton = NSButton() + private var activeContentView: NSView? + private var presentationMode: PresentationMode = .expanded + private var isPresented = false + private var trackingArea: NSTrackingArea? + private var isMouseInsideView = false + private weak var closeButtonGlassView: NSView? + private weak var dockButtonGlassView: NSView? + private weak var expandCollapseButtonGlassView: NSView? + private let closeButtonSize: CGFloat = 30 + private let closeButtonCornerInset: CGFloat = 3 + private let gap: CGFloat = 8 + + var onCloseRequested: (() -> Void)? + + var onDockRequested: (() -> Void)? + + var onTogglePresentationMode: (() -> Void)? + + var onStepBackward: (() -> Void)? { + get { collapsedView.onStepBackward } + set { collapsedView.onStepBackward = newValue } + } + + var onStepForward: (() -> Void)? { + get { collapsedView.onStepForward } + set { collapsedView.onStepForward = newValue } + } + + var onStepUp: (() -> Void)? { + get { collapsedView.onStepUp } + set { collapsedView.onStepUp = newValue } + } + + var onStepDown: (() -> Void)? { + get { collapsedView.onStepDown } + set { collapsedView.onStepDown = newValue } + } + + var isPianoFocusActive: (() -> Bool)? { + get { expandedView.isPianoFocusActive } + set { expandedView.isPianoFocusActive = newValue } + } + + init(menuBand: MenuBandController) { + self.expandedView = ExpandedPianoWaveformView(menuBand: menuBand) + self.collapsedView = CollapsedPianoWaveformView(menuBand: menuBand) + super.init(nibName: nil, bundle: nil) + preferredContentSize = preferredSize(for: presentationMode) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + nil + } + + override func loadView() { + view = containerView + containerView.wantsLayer = true + configureOverlayButton( + closeButton, + symbolName: "xmark", + toolTip: "Close", + action: #selector(closeClicked(_:)) + ) + configureOverlayButton( + dockButton, + symbolName: "menubar.dock.rectangle", + toolTip: "Dock Below Menubar Piano", + action: #selector(dockClicked(_:)) + ) + configureOverlayButton( + expandCollapseButton, + symbolName: "square.resize.down", + toolTip: "Collapse", + action: #selector(expandCollapseClicked(_:)) + ) + containerView.addSubview(closeButton) + containerView.addSubview(dockButton) + containerView.addSubview(expandCollapseButton) + installOverlayGlassBackgrounds() + NSLayoutConstraint.activate([ + closeButton.topAnchor.constraint( + equalTo: containerView.topAnchor, + constant: PianoWaveformViewController.panelCornerRadius - closeButtonSize / 2 + closeButtonCornerInset + ), + closeButton.leadingAnchor.constraint( + equalTo: containerView.leadingAnchor, + constant: PianoWaveformViewController.panelCornerRadius - closeButtonSize / 2 + closeButtonCornerInset + ), + closeButton.widthAnchor.constraint(equalToConstant: closeButtonSize), + closeButton.heightAnchor.constraint(equalToConstant: closeButtonSize), + + expandCollapseButton.topAnchor.constraint(equalTo: closeButton.topAnchor), + expandCollapseButton.trailingAnchor.constraint( + equalTo: containerView.trailingAnchor, + constant: -(PianoWaveformViewController.panelCornerRadius - closeButtonSize / 2 + closeButtonCornerInset) + ), + expandCollapseButton.widthAnchor.constraint(equalToConstant: closeButtonSize), + expandCollapseButton.heightAnchor.constraint(equalToConstant: closeButtonSize), + + dockButton.topAnchor.constraint(equalTo: closeButton.topAnchor), + dockButton.trailingAnchor.constraint(equalTo: expandCollapseButton.leadingAnchor, constant: -gap), + dockButton.widthAnchor.constraint(equalToConstant: closeButtonSize), + dockButton.heightAnchor.constraint(equalToConstant: closeButtonSize), + ]) + installTrackingArea() + installDisplayedView() + isMouseInsideView = isMouseInsideContainer() + setOverlayControlsVisible(isMouseInsideView, animated: false) + } + + func refresh() { + expandedView.refresh() + collapsedView.refresh() + preferredContentSize = preferredSize(for: presentationMode) + } + + func clearInteraction() { + expandedView.clearInteraction() + } + + func setPresented(_ isPresented: Bool) { + self.isPresented = isPresented + updatePresentationState() + } + + func setPresentationMode(_ presentationMode: PresentationMode) { + guard self.presentationMode != presentationMode else { + preferredContentSize = preferredSize(for: presentationMode) + updatePresentationState() + return + } + self.presentationMode = presentationMode + if isViewLoaded { + installDisplayedView() + } + preferredContentSize = preferredSize(for: presentationMode) + updatePresentationState() + } + + private func installDisplayedView() { + let nextView: NSView + switch presentationMode { + case .expanded: + nextView = expandedView + case .collapsed: + nextView = collapsedView + } + + guard activeContentView !== nextView else { return } + activeContentView?.removeFromSuperview() + nextView.translatesAutoresizingMaskIntoConstraints = false + containerView.addSubview(nextView, positioned: .below, relativeTo: nil) + NSLayoutConstraint.activate([ + nextView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + nextView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + nextView.topAnchor.constraint(equalTo: containerView.topAnchor), + nextView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor), + ]) + activeContentView = nextView + } + + private func preferredSize(for presentationMode: PresentationMode) -> NSSize { + switch presentationMode { + case .expanded: + return expandedView.fittingSize + case .collapsed: + return collapsedView.fittingSize + } + } + + private func updatePresentationState() { + expandedView.setPresented(isPresented && presentationMode == .expanded) + collapsedView.setLive(isPresented && presentationMode == .collapsed) + let controlsHidden = false + [closeButton, dockButton, expandCollapseButton, closeButtonGlassView, dockButtonGlassView, expandCollapseButtonGlassView] + .compactMap { $0 } + .forEach { $0.isHidden = controlsHidden } + updateExpandCollapseButtonAppearance() + isMouseInsideView = isMouseInsideContainer() + setOverlayControlsVisible(isMouseInsideView, animated: false) + applyOverlayButtonAppearance() + } + + private func configureOverlayButton( + _ button: NSButton, + symbolName: String, + toolTip: String, + action: Selector + ) { + let config = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold) + button.translatesAutoresizingMaskIntoConstraints = false + button.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: toolTip)? + .withSymbolConfiguration(config) + button.isBordered = false + button.imagePosition = .imageOnly + button.contentTintColor = .white.withAlphaComponent(0.92) + button.toolTip = toolTip + button.target = self + button.action = action + button.alphaValue = 0 + button.wantsLayer = true + button.layer?.cornerRadius = closeButtonSize / 2 + button.layer?.borderWidth = 1 + if #available(macOS 10.15, *) { + button.layer?.cornerCurve = .continuous + } + } + + private func installOverlayGlassBackgrounds() { + guard ExpandedPianoWaveformView.shouldUseLiquidGlass, #available(macOS 26.0, *) else { return } + self.closeButtonGlassView = installGlassBackground(for: closeButton) + self.dockButtonGlassView = installGlassBackground(for: dockButton) + self.expandCollapseButtonGlassView = installGlassBackground(for: expandCollapseButton) + } + + @available(macOS 26.0, *) + private func installGlassBackground(for target: NSView) -> NSView { + let glassView = ExpandedPianoWaveformGlassEffectView() + glassView.translatesAutoresizingMaskIntoConstraints = false + glassView.cornerRadius = closeButtonSize / 2 + containerView.addSubview(glassView, positioned: .below, relativeTo: target) + NSLayoutConstraint.activate([ + glassView.leadingAnchor.constraint(equalTo: target.leadingAnchor), + glassView.trailingAnchor.constraint(equalTo: target.trailingAnchor), + glassView.topAnchor.constraint(equalTo: target.topAnchor), + glassView.bottomAnchor.constraint(equalTo: target.bottomAnchor), + ]) + return glassView + } + + private func setOverlayControlsVisible(_ isVisible: Bool, animated: Bool = true) { + let alpha: CGFloat = isVisible ? 1.0 : 0.0 + let views = [closeButton, dockButton, expandCollapseButton, closeButtonGlassView, dockButtonGlassView, expandCollapseButtonGlassView] + .compactMap { $0 } + if animated { + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.12 + closeButton.animator().alphaValue = alpha + dockButton.animator().alphaValue = alpha + expandCollapseButton.animator().alphaValue = alpha + closeButtonGlassView?.animator().alphaValue = alpha + dockButtonGlassView?.animator().alphaValue = alpha + expandCollapseButtonGlassView?.animator().alphaValue = alpha + } + } else { + views.forEach { $0.alphaValue = alpha } + } + } + + private func installTrackingArea() { + if let trackingArea { + containerView.removeTrackingArea(trackingArea) + } + let trackingArea = NSTrackingArea( + rect: .zero, + options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], + owner: self, + userInfo: nil + ) + containerView.addTrackingArea(trackingArea) + self.trackingArea = trackingArea + } + + override func mouseEntered(with event: NSEvent) { + isMouseInsideView = true + setOverlayControlsVisible(true) + } + + override func mouseExited(with event: NSEvent) { + isMouseInsideView = false + setOverlayControlsVisible(false) + } + + private func isMouseInsideContainer() -> Bool { + guard let window = containerView.window else { return false } + let location = containerView.convert(window.mouseLocationOutsideOfEventStream, from: nil) + return containerView.bounds.contains(location) + } + + private func applyOverlayButtonAppearance() { + let effectiveView: NSView + switch presentationMode { + case .expanded: + effectiveView = expandedView + case .collapsed: + effectiveView = collapsedView + } + let isDark = effectiveView.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + let tintColor = expandedView.paletteTintColor + if ExpandedPianoWaveformView.shouldUseLiquidGlass, #available(macOS 26.0, *) { + for view in [closeButtonGlassView, dockButtonGlassView, expandCollapseButtonGlassView] { + (view as? NSGlassEffectView)?.style = .clear + (view as? NSGlassEffectView)?.tintColor = tintColor.withAlphaComponent(0.34) + } + for button in [closeButton, dockButton, expandCollapseButton] { + button.layer?.backgroundColor = NSColor.clear.cgColor + button.layer?.borderColor = NSColor.clear.cgColor + } + } else { + let border = NSColor.white.withAlphaComponent(0.28).cgColor + let background = NSColor.windowBackgroundColor.withAlphaComponent(isDark ? 0.18 : 0.22).cgColor + for button in [closeButton, dockButton, expandCollapseButton] { + button.layer?.backgroundColor = background + button.layer?.borderColor = border + } + } + } + + private func updateExpandCollapseButtonAppearance() { + let symbolName = presentationMode == .expanded ? "square.resize.down" : "square.resize.up" + let toolTip = presentationMode == .expanded ? "Collapse" : "Expand floating piano" + let config = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold) + expandCollapseButton.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: toolTip)? + .withSymbolConfiguration(config) + expandCollapseButton.toolTip = toolTip + } + + @objc private func closeClicked(_ sender: NSButton) { + onCloseRequested?() + } + + @objc private func dockClicked(_ sender: NSButton) { + onDockRequested?() + } + + @objc private func expandCollapseClicked(_ sender: NSButton) { + onTogglePresentationMode?() + } +} diff --git a/slab/menuband/Sources/MenuBand/UnifiedPianoWaveformPalette.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift similarity index 57% rename from slab/menuband/Sources/MenuBand/UnifiedPianoWaveformPalette.swift rename to slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift index 0bc39709fc..c045467c05 100644 --- a/slab/menuband/Sources/MenuBand/UnifiedPianoWaveformPalette.swift +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowDelegate.swift @@ -1,6 +1,6 @@ import AppKit -final class PianoWaveformPalette: NSObject, NSWindowDelegate { +final class PianoWaveformWindowDelegate: NSObject, NSWindowDelegate { enum State { case collapsed case expanded @@ -137,19 +137,11 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { } func showFromCommand(restoringTo previousApp: NSRunningApplication? = nil) { - setEnabled(true) - preferredPresentationState = .expanded - persistPreferredState() - transitionToExpanded() - showExpanded(restoringTo: previousApp) + enableAndShowPreferred(restoringTo: previousApp) } func show(restoringTo previousApp: NSRunningApplication? = nil) { - setEnabled(true) - preferredPresentationState = .expanded - persistPreferredState() - transitionToExpanded() - showExpanded(restoringTo: previousApp) + enableAndShowPreferred(restoringTo: previousApp) } func dismiss(reason: DismissReason = .programmatic) { @@ -312,6 +304,7 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { private func showCollapsedIfNeeded() { guard let panel else { return } + cancelPendingHide() pianoWaveformViewController.setPresentationMode(.collapsed) panel.ignoresMouseEvents = false setPanelFrame(collapsedFrame(size: pianoWaveformViewController.preferredContentSize)) @@ -323,6 +316,7 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { private func focusCollapsedPaletteIfNeeded() { guard presentationState == .collapsed, let panel else { return } + cancelPendingHide() NSApp.activate(ignoringOtherApps: true) panel.makeKeyAndOrderFront(nil) pianoWaveformViewController.setPresented(true) @@ -349,6 +343,12 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { private func dismissCollapsedPanel() { cancelPendingHide() + guard menuBand.litNotes.isEmpty else { + if preferredPresentationState == .collapsed, isEnabled, !isCollapsedPresentationSuppressed { + showCollapsedIfNeeded() + } + return + } pianoWaveformViewController.setPresented(false) panel?.ignoresMouseEvents = false panel?.orderOut(nil) @@ -395,6 +395,7 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { } return } + cancelPendingHide() removeMonitors() pianoWaveformViewController.setPresented(false) pianoWaveformViewController.clearInteraction() @@ -544,6 +545,7 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { private func enableAndShowPreferred(restoringTo previousApp: NSRunningApplication?) { setEnabled(true) + cancelPendingHide() switch preferredPresentationState { case .expanded: transitionToExpanded() @@ -551,7 +553,9 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { case .collapsed: presentationState = .collapsed showIfNeeded() - focusCollapsedPaletteIfNeeded() + if !menuBand.litNotes.isEmpty { + focusCollapsedPaletteIfNeeded() + } } } @@ -621,357 +625,3 @@ final class PianoWaveformPalette: NSObject, NSWindowDelegate { } } -private final class PianoWaveformPanel: NSPanel { - override var canBecomeKey: Bool { true } - override var canBecomeMain: Bool { false } -} - -@available(macOS 26.0, *) -private final class PianoWaveformStripGlassEffectView: NSGlassEffectView { - override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } -} - -final class CollapsedPianoWaveformView: NSView { - private static var shouldUseLiquidGlass: Bool { - if #available(macOS 26.0, *) { return true } - return false - } - - private weak var menuBand: MenuBandController? - private let contentContainer = NSView() - private let waveformContainer = NSView() - private let waveformClipView = NSView() - private let waveformView = WaveformView() - private let heldNotesContainer = NSView() - private let heldNotesStack = NSStackView() - private let instrumentRow = NSView() - private let instrumentArrows = ArrowKeysIndicator() - private let instrumentLabel = NSTextField(labelWithString: "") - private var trackingArea: NSTrackingArea? - private weak var paletteGlassView: NSView? - private weak var waveformGlassView: NSView? - private weak var instrumentRowGlassView: NSView? - - var onHoverChanged: ((Bool) -> Void)? - var onStepBackward: (() -> Void)? - var onStepForward: (() -> Void)? - var onStepUp: (() -> Void)? - var onStepDown: (() -> Void)? - - private static let waveformHeight: CGFloat = 64 - private static let heldNotesRowHeight: CGFloat = 16 - private static let instrumentRowHeight: CGFloat = 22 - - init(menuBand: MenuBandController) { - self.menuBand = menuBand - super.init(frame: .zero) - wantsLayer = true - layer?.cornerRadius = 10 - layer?.masksToBounds = true - - contentContainer.translatesAutoresizingMaskIntoConstraints = false - waveformView.menuBand = menuBand - waveformView.translatesAutoresizingMaskIntoConstraints = false - waveformView.setSurfaceStyle(.standard) - - waveformContainer.wantsLayer = true - waveformContainer.translatesAutoresizingMaskIntoConstraints = false - waveformContainer.layer?.cornerRadius = 8 - waveformContainer.layer?.masksToBounds = false - - waveformClipView.wantsLayer = true - waveformClipView.translatesAutoresizingMaskIntoConstraints = false - waveformClipView.layer?.cornerRadius = 8 - waveformClipView.layer?.masksToBounds = true - - heldNotesContainer.translatesAutoresizingMaskIntoConstraints = false - heldNotesStack.orientation = .horizontal - heldNotesStack.alignment = .centerY - heldNotesStack.spacing = 4 - heldNotesStack.translatesAutoresizingMaskIntoConstraints = false - - instrumentRow.translatesAutoresizingMaskIntoConstraints = false - instrumentRow.wantsLayer = true - instrumentRow.layer?.cornerRadius = 7 - if #available(macOS 10.15, *) { - instrumentRow.layer?.cornerCurve = .continuous - } - instrumentArrows.translatesAutoresizingMaskIntoConstraints = false - instrumentArrows.setContentHuggingPriority(.required, for: .horizontal) - instrumentArrows.setContentCompressionResistancePriority(.required, for: .horizontal) - instrumentArrows.displayMode = .horizontalPair - instrumentArrows.style = .prominent - instrumentArrows.toolTip = "Change instrument" - instrumentArrows.onClick = { [weak self] direction, isDown in - guard let self, isDown else { return } - switch direction { - case 0: - self.onStepBackward?() - case 1: - self.onStepForward?() - case 2: - self.onStepDown?() - case 3: - self.onStepUp?() - default: - break - } - } - - instrumentLabel.translatesAutoresizingMaskIntoConstraints = false - instrumentLabel.lineBreakMode = .byTruncatingTail - instrumentLabel.drawsBackground = false - instrumentLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - addSubview(contentContainer) - contentContainer.addSubview(waveformContainer) - contentContainer.addSubview(heldNotesContainer) - contentContainer.addSubview(instrumentRow) - waveformContainer.addSubview(waveformClipView) - waveformClipView.addSubview(waveformView) - heldNotesContainer.addSubview(heldNotesStack) - instrumentRow.addSubview(instrumentArrows) - instrumentRow.addSubview(instrumentLabel) - installLiquidGlassBackgrounds() - - NSLayoutConstraint.activate([ - widthAnchor.constraint(equalToConstant: KeyboardIconRenderer.imageSize.width), - contentContainer.leadingAnchor.constraint(equalTo: leadingAnchor), - contentContainer.trailingAnchor.constraint(equalTo: trailingAnchor), - contentContainer.topAnchor.constraint(equalTo: topAnchor), - contentContainer.bottomAnchor.constraint(equalTo: bottomAnchor), - - waveformContainer.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor), - waveformContainer.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor), - waveformContainer.topAnchor.constraint(equalTo: contentContainer.topAnchor), - waveformContainer.heightAnchor.constraint(equalToConstant: Self.waveformHeight), - - waveformClipView.leadingAnchor.constraint(equalTo: waveformContainer.leadingAnchor, constant: 5), - waveformClipView.trailingAnchor.constraint(equalTo: waveformContainer.trailingAnchor, constant: -5), - waveformClipView.topAnchor.constraint(equalTo: waveformContainer.topAnchor, constant: 5), - waveformClipView.bottomAnchor.constraint(equalTo: waveformContainer.bottomAnchor, constant: -5), - - waveformView.leadingAnchor.constraint(equalTo: waveformClipView.leadingAnchor), - waveformView.trailingAnchor.constraint(equalTo: waveformClipView.trailingAnchor), - waveformView.topAnchor.constraint(equalTo: waveformClipView.topAnchor), - waveformView.bottomAnchor.constraint(equalTo: waveformClipView.bottomAnchor), - - heldNotesContainer.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor), - heldNotesContainer.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor), - heldNotesContainer.topAnchor.constraint(equalTo: waveformContainer.bottomAnchor, constant: 2), - heldNotesContainer.heightAnchor.constraint(equalToConstant: Self.heldNotesRowHeight), - - heldNotesStack.centerXAnchor.constraint(equalTo: heldNotesContainer.centerXAnchor), - heldNotesStack.centerYAnchor.constraint(equalTo: heldNotesContainer.centerYAnchor), - - instrumentRow.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor), - instrumentRow.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor), - instrumentRow.topAnchor.constraint(equalTo: heldNotesContainer.bottomAnchor, constant: 2), - instrumentRow.heightAnchor.constraint(equalToConstant: Self.instrumentRowHeight), - instrumentRow.bottomAnchor.constraint(equalTo: contentContainer.bottomAnchor, constant: -2), - - instrumentArrows.leadingAnchor.constraint(equalTo: instrumentRow.leadingAnchor, constant: 6), - instrumentArrows.centerYAnchor.constraint(equalTo: instrumentRow.centerYAnchor), - - instrumentLabel.leadingAnchor.constraint(equalTo: instrumentArrows.trailingAnchor, constant: 6), - instrumentLabel.centerYAnchor.constraint(equalTo: instrumentRow.centerYAnchor), - instrumentLabel.trailingAnchor.constraint(equalTo: instrumentRow.trailingAnchor, constant: -8), - ]) - - refresh() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - nil - } - - override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } - - override func updateTrackingAreas() { - super.updateTrackingAreas() - if let trackingArea { - removeTrackingArea(trackingArea) - } - let trackingArea = NSTrackingArea( - rect: bounds, - options: [.activeAlways, .inVisibleRect, .mouseEnteredAndExited], - owner: self, - userInfo: nil - ) - addTrackingArea(trackingArea) - self.trackingArea = trackingArea - } - - override func mouseEntered(with event: NSEvent) { - onHoverChanged?(true) - super.mouseEntered(with: event) - } - - override func mouseExited(with event: NSEvent) { - onHoverChanged?(false) - super.mouseExited(with: event) - } - - func refresh() { - guard let menuBand else { return } - let isDark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua - waveformView.setLightMode(!isDark) - - let safe = max(0, min(127, Int(menuBand.effectiveMelodicProgram))) - let familyColor = menuBand.midiMode - ? NSColor.controlAccentColor - : InstrumentListView.colorForProgram(safe) - - let waveformBackground = isDark - ? NSColor(white: 0.06, alpha: 1.0) - : NSColor(white: 0.82, alpha: 1.0) - let glassWaveformBackground = isDark - ? NSColor.white.withAlphaComponent(0.04) - : NSColor.white.withAlphaComponent(0.18) - let instrumentRowBackground = isDark - ? NSColor.white.withAlphaComponent(0.08) - : NSColor.white.withAlphaComponent(0.3) - waveformContainer.layer?.backgroundColor = NSColor.clear.cgColor - waveformClipView.layer?.backgroundColor = Self.shouldUseLiquidGlass - ? glassWaveformBackground.cgColor - : waveformBackground.cgColor - waveformContainer.layer?.borderWidth = 1 - waveformContainer.layer?.borderColor = familyColor.withAlphaComponent( - Self.shouldUseLiquidGlass ? 0.22 : 0.55 - ).cgColor - instrumentRow.layer?.backgroundColor = Self.shouldUseLiquidGlass - ? NSColor.clear.cgColor - : instrumentRowBackground.cgColor - instrumentRow.layer?.borderWidth = 1 - instrumentRow.layer?.borderColor = familyColor.withAlphaComponent( - Self.shouldUseLiquidGlass ? 0.22 : 0.35 - ).cgColor - instrumentLabel.textColor = isDark ? .white : .black - instrumentArrows.accentColor = familyColor - instrumentArrows.isDarkAppearance = isDark - - if menuBand.midiMode { - waveformView.setDotMatrix(MenuBandPopoverViewController.midiDotPattern) - waveformView.setBaseColor(.controlAccentColor) - } else { - waveformView.setDotMatrix(nil) - waveformView.setBaseColor(familyColor) - } - - let shadow = NSShadow() - shadow.shadowColor = familyColor.withAlphaComponent(isDark ? 0.9 : 0.55) - shadow.shadowOffset = NSSize(width: 0, height: -1) - shadow.shadowBlurRadius = 3 - let titleFont: NSFont = { - if let descriptor = AppDelegate.ywftBoldDescriptor, - let font = NSFont(descriptor: descriptor, size: 14), - font.familyName == "YWFT Processing" { - return font - } - return NSFont.systemFont(ofSize: 14, weight: .black) - }() - instrumentLabel.attributedStringValue = NSAttributedString( - string: GeneralMIDI.programNames[safe], - attributes: [ - .font: titleFont, - .foregroundColor: isDark ? NSColor.white : NSColor.black, - .shadow: shadow, - ] - ) - - for view in heldNotesStack.arrangedSubviews { - heldNotesStack.removeArrangedSubview(view) - view.removeFromSuperview() - } - for name in menuBand.heldNoteNames() { - heldNotesStack.addArrangedSubview(makeHeldNoteBox(name: name, color: familyColor)) - } - - if Self.shouldUseLiquidGlass, #available(macOS 26.0, *) { - let paletteTint = familyColor.withAlphaComponent(menuBand.midiMode ? 0.20 : 0.16) - (paletteGlassView as? NSGlassEffectView)?.style = .clear - (paletteGlassView as? NSGlassEffectView)?.tintColor = paletteTint - (waveformGlassView as? NSGlassEffectView)?.style = .clear - (waveformGlassView as? NSGlassEffectView)?.tintColor = paletteTint.withAlphaComponent(0.55) - (instrumentRowGlassView as? NSGlassEffectView)?.style = .clear - (instrumentRowGlassView as? NSGlassEffectView)?.tintColor = paletteTint.withAlphaComponent(0.42) - layer?.backgroundColor = NSColor.clear.cgColor - } else { - layer?.backgroundColor = (isDark - ? NSColor(white: 0.06, alpha: 0.96) - : NSColor(white: 0.88, alpha: 0.96)).cgColor - } - } - - func setLive(_ isLive: Bool) { - waveformView.isLive = isLive - } - - private func makeHeldNoteBox(name: String, color: NSColor) -> NSView { - let box = NSView() - box.translatesAutoresizingMaskIntoConstraints = false - box.wantsLayer = true - box.layer?.cornerRadius = 4 - box.layer?.backgroundColor = color.withAlphaComponent(0.85).cgColor - - let label = NSTextField(labelWithString: name) - label.translatesAutoresizingMaskIntoConstraints = false - label.font = NSFont.monospacedSystemFont(ofSize: 9, weight: .heavy) - label.textColor = .black - box.addSubview(label) - - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: box.leadingAnchor, constant: 5), - label.trailingAnchor.constraint(equalTo: box.trailingAnchor, constant: -5), - label.topAnchor.constraint(equalTo: box.topAnchor, constant: 1), - label.bottomAnchor.constraint(equalTo: box.bottomAnchor, constant: -1), - ]) - return box - } - - private func installLiquidGlassBackgrounds() { - guard Self.shouldUseLiquidGlass, #available(macOS 26.0, *) else { return } - - let paletteGlassView = PianoWaveformStripGlassEffectView() - paletteGlassView.translatesAutoresizingMaskIntoConstraints = false - paletteGlassView.cornerRadius = 10 - addSubview(paletteGlassView, positioned: .below, relativeTo: contentContainer) - NSLayoutConstraint.activate([ - paletteGlassView.leadingAnchor.constraint(equalTo: leadingAnchor), - paletteGlassView.trailingAnchor.constraint(equalTo: trailingAnchor), - paletteGlassView.topAnchor.constraint(equalTo: topAnchor), - paletteGlassView.bottomAnchor.constraint(equalTo: bottomAnchor), - ]) - self.paletteGlassView = paletteGlassView - - self.waveformGlassView = installGlassBackground( - matchedTo: waveformContainer, - below: waveformContainer, - cornerRadius: 8 - ) - self.instrumentRowGlassView = installGlassBackground( - matchedTo: instrumentRow, - below: instrumentRow, - cornerRadius: 7 - ) - } - - @available(macOS 26.0, *) - private func installGlassBackground(matchedTo target: NSView, - below anchor: NSView, - cornerRadius: CGFloat) -> NSView { - let glassView = PianoWaveformStripGlassEffectView() - glassView.translatesAutoresizingMaskIntoConstraints = false - glassView.cornerRadius = cornerRadius - addSubview(glassView, positioned: .below, relativeTo: anchor) - NSLayoutConstraint.activate([ - glassView.leadingAnchor.constraint(equalTo: target.leadingAnchor), - glassView.trailingAnchor.constraint(equalTo: target.trailingAnchor), - glassView.topAnchor.constraint(equalTo: target.topAnchor), - glassView.bottomAnchor.constraint(equalTo: target.bottomAnchor), - ]) - return glassView - } - -} diff --git a/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowSupport.swift b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowSupport.swift new file mode 100644 index 0000000000..e249e9a8d6 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/PianoWaveformWindow/PianoWaveformWindowSupport.swift @@ -0,0 +1,52 @@ +import AppKit + +enum PianoWaveformVisualStyleOverride: String { + case automatic + case liquid + case legacy + + init(rawValue: String?) { + switch rawValue?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case Self.liquid.rawValue: + self = .liquid + case Self.legacy.rawValue: + self = .legacy + default: + self = .automatic + } + } +} + +enum PianoWaveformWindowStyle { + private static let defaultsDomain = "computer.aestheticcomputer.menuband" + private static let styleOverrideDefaultsKey = "MenuBandFloatingPlayPaletteStyle" + private static let styleOverrideEnvironmentKey = "MENUBAND_FLOATING_PLAY_PALETTE_STYLE" + + static var visualStyleOverride: PianoWaveformVisualStyleOverride { + let environmentValue = ProcessInfo.processInfo.environment[styleOverrideEnvironmentKey] + if environmentValue != nil { + return PianoWaveformVisualStyleOverride(rawValue: environmentValue) + } + let defaultsValue = UserDefaults(suiteName: defaultsDomain)?.string(forKey: styleOverrideDefaultsKey) + ?? UserDefaults.standard.string(forKey: styleOverrideDefaultsKey) + return PianoWaveformVisualStyleOverride(rawValue: defaultsValue) + } + + static var shouldUseLiquidGlass: Bool { + switch visualStyleOverride { + case .liquid: + if #available(macOS 26.0, *) { return true } + return false + case .legacy: + return false + case .automatic: + if #available(macOS 26.0, *) { return true } + return false + } + } +} + +final class PianoWaveformPanel: NSPanel { + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { false } +}