Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / VisualizerPresetStrip.swift

Raw 9.0 KB on 15681b389943bdb82ce0ee35ea3df6538f046361
1import SwiftUI
2import AppKit
3
4/// Lay out names once, then create controls only for the visible portion of the row.
5/// Jumping thousands of presets must not build every intervening SwiftUI button.
6struct VisualizerPresetStrip: NSViewRepresentable, Equatable {
7 @ObservedObject private var library = ProjectMPresets.shared
8 let selected: Int
9 var revealRequest = 0
10 var poolRevision = 0
11 let accent: Color
12 let background: Color
13 let choose: (Int) -> Void
14 nonisolated static func == (lhs: Self, rhs: Self) -> Bool {
15 lhs.selected == rhs.selected && lhs.poolRevision == rhs.poolRevision && lhs.revealRequest == rhs.revealRequest && lhs.accent == rhs.accent && lhs.background == rhs.background
16 }
17 func makeNSView(context: Context) -> PresetStripView { PresetStripView() }
18 func updateNSView(_ view: PresetStripView, context: Context) {
19 view.update(library: library, selected: selected, accent: NSColor(accent), background: NSColor(background), isEnabled: context.environment.isEnabled, revealRequest: revealRequest, choose: choose)
20 }
21}
22
23final class PresetStripView: NSScrollView {
24 private let canvas = NSView()
25 private var starts: [CGFloat] = []
26 private var widths: [CGFloat] = []
27 private var rowWidth: CGFloat = 0
28 private var viewportWidth: CGFloat = -1
29 private var names: [String] = []
30 /// Scene ID for each laid-out position; the row offers only available scenes.
31 private var scenes: [Int] = []
32 private var positions: [Int: Int] = [:]
33 private var library: ProjectMPresets?
34 private var selected = -1
35 private var revealRequest = 0
36 private var accent = NSColor.systemPink
37 private var buttonBackground = NSColor.windowBackgroundColor
38 private var choose: ((Int) -> Void)?
39 private var controlsEnabled = true
40 private var buttons: [Int: PresetStripButton] = [:]
41 private var observer: PresetStripObservation?
42 override init(frame: NSRect) {
43 super.init(frame: frame)
44 drawsBackground = false; hasHorizontalScroller = true; hasVerticalScroller = false
45 autohidesScrollers = false; scrollerStyle = .legacy; scrollerKnobStyle = .light
46 horizontalScrollElasticity = .allowed; verticalScrollElasticity = .none
47 documentView = canvas; contentView.postsBoundsChangedNotifications = true
48 observer = PresetStripObservation(NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: contentView, queue: .main) { [weak self] _ in
49 MainActor.assumeIsolated { self?.showVisibleButtons() }
50 })
51 }
52 required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
53 override func layout() {
54 super.layout()
55 canvas.frame.size.height = max(62, contentView.bounds.height)
56 if viewportWidth != contentView.bounds.width {
57 updateCanvasWidth()
58 }
59 showVisibleButtons()
60 }
61 func update(library: ProjectMPresets, selected: Int, accent: NSColor, background: NSColor, isEnabled: Bool = true, revealRequest: Int = 0, choose: @escaping (Int) -> Void) {
62 self.library = library; self.choose = choose
63 let available = library.eligibleScenes
64 let changedNames = scenes != available || names != available.map { library.sceneNames[$0] }
65 let changedEnabled = controlsEnabled != isEnabled
66 controlsEnabled = isEnabled
67 let changedStyle = self.selected != selected || self.accent != accent || buttonBackground != background
68 if changedNames {
69 scenes = available
70 names = available.map { library.sceneNames[$0] }
71 positions = Dictionary(uniqueKeysWithValues: available.enumerated().map { ($0.element, $0.offset) })
72 var position: CGFloat = 0
73 starts = []; widths = []
74 let font = NSFont.systemFont(ofSize: 12, weight: .medium)
75 for name in names {
76 let width = ceil((name as NSString).size(withAttributes: [.font: font]).width) + 72
77 starts.append(position); widths.append(width); position += width + 6
78 }
79 rowWidth = max(0, position - 6)
80 updateCanvasWidth()
81 // A newly filtered list starts at its own left edge; ordinary selections stay still.
82 contentView.scroll(to: .zero); reflectScrolledClipView(contentView)
83 buttons.values.forEach { $0.removeFromSuperview() }; buttons.removeAll()
84 }
85 self.selected = selected; self.accent = accent; buttonBackground = background
86 if self.revealRequest != revealRequest, let position = positions[selected] {
87 let x = min(starts[position], max(0, canvas.frame.width - contentView.bounds.width))
88 contentView.scroll(to: NSPoint(x: x, y: 0)); reflectScrolledClipView(contentView)
89 }
90 self.revealRequest = revealRequest
91 showVisibleButtons()
92 if changedStyle || changedEnabled { for (index, button) in buttons { style(button, index: index) } }
93 }
94 private func updateCanvasWidth() {
95 viewportWidth = contentView.bounds.width
96 let trailingSpace = max(0, viewportWidth - (widths.last ?? 0))
97 canvas.frame = NSRect(x: 0, y: 0, width: max(viewportWidth, rowWidth + trailingSpace), height: max(62, contentView.bounds.height))
98 }
99 private func style(_ button: PresetStripButton, index: Int) {
100 button.isEnabled = controlsEnabled
101 button.isSelected = scenes[index] == selected; button.accent = accent; button.fill = buttonBackground
102 button.needsDisplay = true
103 }
104 private func showVisibleButtons() {
105 guard let library, !starts.isEmpty else { return }
106 let visible = contentView.bounds.insetBy(dx: -100, dy: 0)
107 // Binary search avoids scanning the full library on every scroll event.
108 var low = 0, high = starts.count
109 while low < high { let middle = (low + high) / 2; if starts[middle] + widths[middle] < visible.minX { low = middle + 1 } else { high = middle } }
110 var wanted = Set<Int>(), index = low
111 while index < starts.count && starts[index] < visible.maxX { wanted.insert(index); index += 1 }
112 for index in Array(buttons.keys) where !wanted.contains(index) { buttons.removeValue(forKey: index)?.removeFromSuperview() }
113 for index in wanted.sorted() {
114 let button: PresetStripButton
115 if let existing = buttons[index] { button = existing } else {
116 let scene = scenes[index]
117 button = PresetStripButton()
118 button.title = names[index]; button.setAccessibilityLabel(names[index])
119 button.image = NSImage(systemSymbolName: library.icon(for: scene), accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: 27, weight: .light))
120 button.toolTip = library.preset(for: scene)?.originalTitle ?? names[index]
121 button.tag = scene; button.target = self; button.action = #selector(pick(_:))
122 buttons[index] = button; canvas.addSubview(button); style(button, index: index)
123 }
124 button.frame = NSRect(x: starts[index], y: (canvas.frame.height - 62) / 2, width: widths[index], height: 62)
125 }
126 }
127 @objc private func pick(_ sender: NSButton) { if controlsEnabled { choose?(sender.tag) } }
128}
129
130private final class PresetStripButton: NSButton {
131 var isSelected = false
132 var accent = NSColor.systemPink
133 var fill = NSColor.windowBackgroundColor
134 override init(frame: NSRect) { super.init(frame: frame); isBordered = false; setButtonType(.momentaryPushIn) }
135 required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
136 override func draw(_ dirtyRect: NSRect) {
137 let rect = bounds.insetBy(dx: 0.5, dy: 0.5), path = NSBezierPath(roundedRect: rect, xRadius: 9, yRadius: 9)
138 (isSelected ? accent.withAlphaComponent(0.13) : fill.withAlphaComponent(0.65)).setFill(); path.fill()
139 (isSelected ? accent.withAlphaComponent(0.8) : NSColor.white.withAlphaComponent(0.08)).setStroke(); path.lineWidth = 1; path.stroke()
140 let color = isSelected ? accent : NSColor(red: 0.79, green: 0.69, blue: 0.89, alpha: 1)
141 if let image {
142 let size = image.size
143 let scale = min(32 / max(1, size.width), 32 / max(1, size.height))
144 let icon = NSRect(x: 10 + (42 - size.width * scale) / 2, y: (bounds.height - size.height * scale) / 2, width: size.width * scale, height: size.height * scale)
145 image.withSymbolConfiguration(.init(paletteColors: [color]))?.draw(in: icon)
146 }
147 let attributes: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 12, weight: .medium), .foregroundColor: NSColor.white]
148 let size = (title as NSString).size(withAttributes: attributes)
149 (title as NSString).draw(at: NSPoint(x: 62, y: (bounds.height - size.height) / 2), withAttributes: attributes)
150 }
151}
152
153private final class PresetStripObservation: @unchecked Sendable {
154 let token: NSObjectProtocol
155 init(_ token: NSObjectProtocol) { self.token = token }
156 deinit { NotificationCenter.default.removeObserver(token) }
157}