Repository navigation
Expand file tree
/
Copy pathUI.swift
More file actions
2491 lines (2316 loc) · 116 KB
/
Copy pathUI.swift
File metadata and controls
2491 lines (2316 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Cocoa
import SwiftUI
// MARK: - Theme
final class Theme: ObservableObject {
static let shared = Theme()
enum Accent: String, CaseIterable, Identifiable {
case amber, blue, sage, rose, violet, mono
var id: String { rawValue }
var title: String { rawValue.capitalized }
var color: Color {
switch self {
case .amber: Color(red: 0.86, green: 0.66, blue: 0.36)
case .blue: Color(red: 0.36, green: 0.62, blue: 0.92)
case .sage: Color(red: 0.52, green: 0.72, blue: 0.52)
case .rose: Color(red: 0.90, green: 0.50, blue: 0.56)
case .violet: Color(red: 0.66, green: 0.56, blue: 0.92)
case .mono: Color.primary.opacity(0.85)
}
}
}
/// `auto` picks per page: list pages are compact, the rack is spacious, at one width
/// so switching tabs never jumps horizontally.
enum Density: String, CaseIterable, Identifiable {
case auto, compact, comfortable, spacious
var id: String { rawValue }
var title: String { rawValue.capitalized }
func metrics(for tab: Tab) -> Metrics {
guard self == .auto else { return metrics }
var m = (tab == .rack ? Density.spacious : .compact).metrics
m.width = 540
return m
}
var metrics: Metrics {
switch self {
case .auto, .compact:
Metrics(width: 420, maxHeight: 520, gutter: 12, rowV: 3, rowGap: 0, badge: 22, nameSize: 12, monoSize: 10,
sectionTop: 8, paramH: 20, gap: 6, bandV: 4, faderH: 84, chainW: 150, chainRowH: 30, subtitle: false)
case .comfortable:
Metrics(width: 480, maxHeight: 600, gutter: 14, rowV: 6, rowGap: 2, badge: 26, nameSize: 13, monoSize: 10.5,
sectionTop: 12, paramH: 24, gap: 10, bandV: 7, faderH: 100, chainW: 170, chainRowH: 34, subtitle: true)
case .spacious:
Metrics(width: 560, maxHeight: 680, gutter: 16, rowV: 9, rowGap: 4, badge: 30, nameSize: 13.5, monoSize: 11,
sectionTop: 14, paramH: 28, gap: 12, bandV: 10, faderH: 120, chainW: 188, chainRowH: 38, subtitle: true)
}
}
}
/// Everything that makes a page dense or airy. Height follows content up to `maxHeight`.
/// Delivered to views through the environment, so a page keeps its own metrics and
/// its own view identity no matter which page is in front.
struct Metrics: Equatable {
var width: CGFloat
let maxHeight, gutter, rowV, rowGap, badge, nameSize, monoSize, sectionTop, paramH, gap, bandV, faderH, chainW, chainRowH: CGFloat
let subtitle: Bool
var name: Font { .system(size: nameSize, weight: .regular) }
var nameStrong: Font { .system(size: nameSize, weight: .semibold) }
var mono: Font { .system(size: monoSize, weight: .medium, design: .monospaced) }
var monoSmall: Font { .system(size: monoSize - 1.5, weight: .medium, design: .monospaced) }
var section: Font { .system(size: monoSize - 0.5, weight: .bold) }
}
@Published var density: Density { didSet { UserDefaults.standard.set(density.rawValue, forKey: "density") } }
@Published var accent: Accent { didSet { UserDefaults.standard.set(accent.rawValue, forKey: "accent"); T.apply(accent) } }
/// Off: the popover closes when you click anywhere else. On: it stays until the menu bar
/// icon is clicked again, for tweaking while another app has focus.
@Published var keepOpen: Bool { didSet { UserDefaults.standard.set(keepOpen, forKey: "keepOpen") } }
/// How much slower a slider moves while shift is held: pointer travel × this.
@Published var scrubFine: Double { didSet { UserDefaults.standard.set(scrubFine, forKey: "scrubFine") } }
static let scrubSteps: [(Double, String)] = [(0.5, "½"), (0.25, "¼"), (0.1, "⅒"), (0.05, "1⁄20"), (0.02, "1⁄50")]
private init() {
accent = Accent(rawValue: UserDefaults.standard.string(forKey: "accent") ?? "") ?? .amber
density = Density(rawValue: UserDefaults.standard.string(forKey: "density") ?? "") ?? .auto
keepOpen = UserDefaults.standard.bool(forKey: "keepOpen")
let fine = UserDefaults.standard.double(forKey: "scrubFine")
scrubFine = fine > 0 ? fine : 0.1
T.apply(accent)
}
}
// MARK: - Tokens
enum T {
static var accent = Color(red: 0.86, green: 0.66, blue: 0.36)
/// Foreground on an accent fill. Mono is the label colour itself, so it takes the
/// window background; every other accent is light enough for near-black.
static var onAccent = Color.black.opacity(0.82)
static let ok = Color(red: 0.48, green: 0.68, blue: 0.48)
static let warn = Color(red: 0.85, green: 0.42, blue: 0.36)
static let hover = Color.primary.opacity(0.07)
static let press = Color.primary.opacity(0.12)
static let track = Color.primary.opacity(0.13)
static let card = Color.primary.opacity(0.045)
static let hairline = Color.primary.opacity(0.09)
static let chromePadding: CGFloat = 16
/// Horizontal inset of list rows; their content starts `rowInset + 10` from the edge,
/// which is where section labels start too.
static let rowInset: CGFloat = 8
static func apply(_ a: Theme.Accent) {
accent = a.color
onAccent = a == .mono ? Color(nsColor: .windowBackgroundColor) : Color.black.opacity(0.82)
}
// Response is the spring's period: at 0.35–0.45 s a move is visibly travelled (about
// 12–16 frames to settle) yet lands before the hand leaves the mouse.
static let quick = Animation.spring(response: 0.32, dampingFraction: 0.84)
/// Selection and toggles: a hint of overshoot.
static let snap = Animation.spring(response: 0.38, dampingFraction: 0.74)
/// Page swap.
static let page = Animation.spring(response: 0.42, dampingFraction: 0.88)
/// Things appearing: rise a few points while fading in.
static let rise = AnyTransition.asymmetric(
insertion: .opacity.combined(with: .offset(y: 6)).combined(with: .scale(scale: 0.98, anchor: .top)),
removal: .opacity)
static let hoverAnim = Animation.easeOut(duration: 0.14)
}
private struct MetricsKey: EnvironmentKey { static let defaultValue = Theme.Density.compact.metrics }
extension EnvironmentValues {
var metrics: Theme.Metrics {
get { self[MetricsKey.self] }
set { self[MetricsKey.self] = newValue }
}
}
/// Width the module editor actually has: the page minus the chain column when it is open.
private struct EditorWidthKey: EnvironmentKey { static let defaultValue: CGFloat = 480 }
extension EnvironmentValues {
var editorWidth: CGFloat {
get { self[EditorWidthKey.self] }
set { self[EditorWidthKey.self] = newValue }
}
}
struct Press: ButtonStyle {
var scale: CGFloat = 0.96
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? scale : 1)
.opacity(configuration.isPressed ? 0.8 : 1)
.animation(configuration.isPressed ? .spring(response: 0.12, dampingFraction: 0.9) : T.snap, value: configuration.isPressed)
}
}
struct HoverRow: ViewModifier {
var radius: CGFloat = 8
@State private var hover = false
func body(content: Content) -> some View {
content
.background(RoundedRectangle(cornerRadius: radius).fill(hover ? T.hover : .clear))
.onHover { hover = $0 }
.animation(T.hoverAnim, value: hover)
}
}
extension View { func hoverRow(_ radius: CGFloat = 8) -> some View { modifier(HoverRow(radius: radius)) } }
/// Sizes its one child to its ideal width, capped at what the parent offers. A borderless
/// Menu fills whatever it is proposed and, pinned with fixedSize, pushes the row wider
/// than the window when its label is long; under Hug it hugs the label and truncates.
struct Hug: Layout {
var maxWidth: CGFloat = .infinity
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
guard let child = subviews.first else { return .zero }
let ideal = child.sizeThatFits(.unspecified)
return CGSize(width: min(ideal.width, proposal.width ?? ideal.width, maxWidth), height: ideal.height)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
subviews.first?.place(at: bounds.origin, anchor: .topLeading, proposal: ProposedViewSize(bounds.size))
}
}
struct SectionLabel: View {
@Environment(\.metrics) private var m
let text: String
var body: some View {
Text(text.uppercased()).font(m.section).tracking(1.1).foregroundStyle(.tertiary)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
/// The mark and name; off the system chain a small badge says which chain the rack page
/// is editing (a route, the microphone) before you get there.
struct Wordmark: View {
let scope: AudioState.RackScope
var body: some View {
HStack(spacing: 7) {
Logo.Mark().frame(width: 16, height: 16).foregroundStyle(T.accent)
Text("patchbay").font(.system(size: 14, weight: .semibold, design: .rounded)).tracking(-0.2)
if scope != .system {
Image(systemName: scope.symbol).font(.system(size: 9, weight: .bold)).foregroundStyle(T.accent)
.frame(width: 18, height: 16)
.background(Capsule().fill(T.accent.opacity(0.14)))
.transition(.opacity)
}
}
.animation(T.quick, value: scope)
}
}
// MARK: - Root
enum Tab: String, CaseIterable, Identifiable {
case output, input, routes, rack, fix
var id: String { rawValue }
var title: String { rawValue.capitalized }
var symbol: String {
switch self {
case .output: "speaker.wave.2"
case .input: "mic"
case .routes: "arrow.triangle.branch"
case .rack: "slider.horizontal.3"
case .fix: "bandage"
}
}
}
struct Root: View {
@ObservedObject var audio: AudioState
@ObservedObject var theme: Theme
var body: some View {
let tab = audio.tab
let front = theme.density.metrics(for: tab)
VStack(spacing: 0) {
HStack(spacing: 14) {
Wordmark(scope: audio.rackScope)
Spacer()
TabBar(tab: $audio.tab)
Spacer()
HStack(spacing: 8) {
Circle().fill(statusColor).frame(width: 6, height: 6)
Toggle("", isOn: Binding(get: { audio.scopeOn }, set: { audio.setScopeOn($0) }))
.labelsHidden().toggleStyle(.switch).controlSize(.small).tint(T.accent)
.disabled(audio.active != nil)
.help(audio.headerScope == .system ? "System chain" : "This route")
}
}
.padding(.horizontal, T.chromePadding).padding(.vertical, 12)
.fixedSize(horizontal: false, vertical: true)
// T.accent is a static token, not an environment value: rebuilding is what makes
// a new accent reach views whose inputs did not otherwise change. The footer is
// left alone so the settings popout picking the accent stays open.
.id(theme.accent)
Rectangle().fill(T.hairline).frame(height: 0.5)
// Preserve page state, but resolve layout immediately. Only the page's
// opacity animates; child controls must not inherit a tab-switch spring.
ZStack(alignment: .top) {
ForEach(Tab.allCases) { t in
let active = t == tab
let metrics = theme.density.metrics(for: t)
page(t, active: active)
.environment(\.metrics, metrics)
.animation(T.page) { content in
content.opacity(active ? 1 : 0)
}
.frame(height: active ? nil : 0, alignment: .top)
.clipped()
.allowsHitTesting(active)
.accessibilityHidden(!active)
}
}
.id(theme.accent)
Rectangle().fill(T.hairline).frame(height: 0.5)
Footer(audio: audio, theme: theme)
}
.frame(width: front.width)
.frame(maxHeight: front.maxHeight, alignment: .top)
.environment(\.metrics, front)
.onChange(of: audio.rackStatus) { _, s in if case .failed(let message) = s { audio.notice = message } }
.background(RackShortcutHost(audio: audio))
}
@ViewBuilder
private func page(_ t: Tab, active: Bool) -> some View {
switch t {
case .output: OutputTab(audio: audio)
case .input: InputTab(audio: audio)
case .routes: RoutesTab(audio: audio)
case .rack: RackTab(audio: audio, active: active)
case .fix: FixTab(audio: audio)
}
}
private var statusColor: Color {
guard audio.scopeOn else { return Color.secondary.opacity(0.35) }
switch audio.scopeStatus {
case .running: return audio.headerBypass ? T.accent : T.ok
case .proving, .waiting: return T.accent
case .failed: return T.warn
case .stopped: return Color.secondary.opacity(0.35)
}
}
}
/// Handles rack undo at the event boundary so a focused AppKit text editor keeps Cmd-Z.
/// View-level SwiftUI keyboard shortcuts are resolved before the native text responder.
private struct RackShortcutHost: NSViewRepresentable {
let audio: AudioState
func makeNSView(context: Context) -> RackShortcutView {
let view = RackShortcutView()
view.audio = audio
return view
}
func updateNSView(_ nsView: RackShortcutView, context: Context) {
nsView.audio = audio
}
static func dismantleNSView(_ nsView: RackShortcutView, coordinator: ()) {
nsView.stopMonitoring()
}
}
private final class RackShortcutView: NSView {
weak var audio: AudioState?
private var monitor: Any?
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil {
stopMonitoring()
} else {
startMonitoring()
}
}
deinit {
stopMonitoring()
}
fileprivate func stopMonitoring() {
if let monitor {
NSEvent.removeMonitor(monitor)
self.monitor = nil
}
}
private func startMonitoring() {
guard monitor == nil else { return }
monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
guard let self else { return event }
return self.handle(event)
}
}
private func handle(_ event: NSEvent) -> NSEvent? {
guard let audio,
audio.tab == .rack,
let window,
event.window === window,
NSApp.keyWindow === window,
event.keyCode == 6
else { return event }
let modifiers = event.modifierFlags.intersection([.command, .shift, .option, .control])
if Self.isTextResponder(window.firstResponder) {
// This menu-bar app has no Edit menu to dispatch the standard commands.
// Keep text edits on the field editor's native history, never the rack's.
guard let manager = window.firstResponder?.undoManager else { return event }
if modifiers == .command, manager.canUndo {
manager.undo()
return nil
}
if modifiers == [.command, .shift], manager.canRedo {
manager.redo()
return nil
}
return event
}
switch modifiers {
case .command:
guard audio.canUndoRack else { return event }
audio.undoRack()
return nil
case [.command, .shift]:
guard audio.canRedoRack else { return event }
audio.redoRack()
return nil
default:
return event
}
}
private static func isTextResponder(_ responder: NSResponder?) -> Bool {
var current = responder
while let responder = current {
if responder is NSTextView || responder is NSTextField || responder is NSSearchField { return true }
current = responder.nextResponder
}
return false
}
}
struct TabBar: View {
@Binding var tab: Tab
/// Only the selection pill moves. Icons and hit targets stay outside its animation.
var body: some View {
let index = CGFloat(Tab.allCases.firstIndex(of: tab) ?? 0)
HStack(spacing: 2) {
ForEach(Tab.allCases) { t in
Button { tab = t } label: {
Image(systemName: t.symbol)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(tab == t ? .primary : .secondary)
.frame(width: 30, height: 22)
.contentShape(Capsule())
}
.buttonStyle(.plain) // Press() animates on isPressed, which coincides with the tab change
.help(t.title)
}
}
.background(alignment: .leading) {
Capsule().fill(T.press).frame(width: 30, height: 22)
.animation(T.snap) { content in
content.offset(x: index * 32)
}
}
.padding(2)
.background(Capsule().fill(T.card))
.overlay(Capsule().strokeBorder(T.hairline, lineWidth: 0.5))
}
}
struct Footer: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
@ObservedObject var theme: Theme
@State private var showSettings = false
@ObservedObject private var updater = Updater.shared
var body: some View {
HStack(spacing: 10) {
// Notices take the status slot for a few seconds instead of floating over the
// page, where they covered whatever control sat underneath.
if let notice = audio.notice {
HStack(spacing: 6) {
Image(systemName: "info.circle.fill").font(.system(size: 10)).foregroundStyle(T.accent)
Text(notice).font(.system(size: 11)).foregroundStyle(.primary).lineLimit(1).truncationMode(.middle)
}
.help(notice)
.transition(.asymmetric(insertion: .opacity.combined(with: .offset(y: 8)), removal: .opacity))
} else {
Text(audio.scopeOn ? audio.scopeStatus.label : (audio.headerScope == .system ? "rack off" : "route off"))
.font(m.mono).foregroundStyle(.tertiary).lineLimit(1).truncationMode(.middle)
.help(audio.rackOn ? audio.diagnostics.tapBinding : "")
.transition(.opacity)
}
Spacer(minLength: 8)
Button { showSettings.toggle() } label: {
Image(systemName: "gearshape").font(.system(size: 11)).foregroundStyle(.secondary).frame(width: 24, height: 22)
.overlay(alignment: .topTrailing) {
if updater.available != nil { Circle().fill(T.accent).frame(width: 5, height: 5).offset(x: -3, y: 3) }
}
}
.buttonStyle(Press())
.help(updater.available.map { "Settings · patchbay \($0) is available" } ?? "Settings")
.popover(isPresented: $showSettings, arrowEdge: .bottom) {
SettingsPopout(audio: audio, theme: theme)
}
Button("Quit") { NSApp.terminate(nil) }.font(.system(size: 11)).foregroundStyle(.tertiary).buttonStyle(.plain)
}
.frame(height: 22)
.padding(.horizontal, T.chromePadding).padding(.vertical, 8)
.animation(T.quick, value: audio.notice)
}
}
struct SettingsPopout: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
@ObservedObject var theme: Theme
@ObservedObject private var updater = Updater.shared
var body: some View {
VStack(alignment: .leading, spacing: 14) {
Text("Settings").font(.system(size: 13, weight: .semibold))
SettingGroup("Layout") {
Picker("", selection: $theme.density) { ForEach(Theme.Density.allCases) { Text($0.title).tag($0) } }
.labelsHidden().pickerStyle(.segmented).controlSize(.small)
if theme.density == .auto {
Text("Compact on the device pages, spacious on the rack. The window follows its content.")
.font(.system(size: 10.5)).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)
}
}
SettingGroup("Window") {
Toggle(isOn: $theme.keepOpen) { Text("Stay open").font(.system(size: 11)) }
.toggleStyle(.switch).controlSize(.mini).tint(T.accent)
.help("Off: a click anywhere else closes the window. On: it stays until the menu bar icon is clicked again.")
}
SettingGroup("Shift step") {
Picker("", selection: $theme.scrubFine) {
ForEach(Theme.scrubSteps, id: \.0) { step in Text(step.1).tag(step.0) }
}
.labelsHidden().pickerStyle(.segmented).controlSize(.small)
.help("Slider speed while shift is held, as a fraction of pointer travel")
}
SettingGroup("Accent") {
HStack(spacing: 8) {
ForEach(Theme.Accent.allCases) { a in
Button { theme.accent = a } label: {
ZStack {
Circle().fill(a.color).frame(width: 18, height: 18)
if theme.accent == a { Circle().strokeBorder(Color.primary.opacity(0.9), lineWidth: 1.5).frame(width: 24, height: 24) }
}
.frame(width: 24, height: 24)
}
.buttonStyle(Press()).help(a.title)
}
}
}
SettingGroup("Audio capture") {
Picker("", selection: Binding(get: { audio.tapMode }, set: { audio.tapMode = $0 })) {
Text("Stereo mixdown").tag(SystemAudioEngine.TapMode.mixdown)
Text("Device stream").tag(SystemAudioEngine.TapMode.deviceStream)
}
.labelsHidden().pickerStyle(.segmented).controlSize(.small)
Text(audio.tapMode == .mixdown
? "Core Audio mixes every app to stereo, then patchbay resamples to the device rate. Works everywhere."
: "Tap bound to the device's own hardware stream: exact format, no resample. Cleaner on paper; some devices go silent.")
.font(.system(size: 10.5)).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)
}
SettingGroup("Virtual microphone") {
HStack(alignment: .firstTextBaseline) {
Text(audio.virtualMicInstalled
? "patchbay Mic is installed in /Library/Audio/Plug-Ins/HAL."
: "Mic effects need a loopback driver (BlackHole, 90 KB). Admin password; Core Audio restarts for ~3 s.")
.font(.system(size: 10.5)).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)
Spacer()
if audio.micBusy {
ProgressView().controlSize(.small).scaleEffect(0.6).frame(width: 12, height: 12)
} else if audio.virtualMicInstalled {
Button("Remove") { audio.uninstallVirtualMic() }.font(.system(size: 11)).controlSize(.small)
} else {
Button("Install") { audio.installVirtualMic() }.font(.system(size: 11)).controlSize(.small)
}
}
}
SettingGroup("Updates") {
if let version = updater.available {
HStack(alignment: .firstTextBaseline) {
Text("patchbay \(version) is available.").font(.system(size: 11))
Spacer()
Button("Update…") { updater.check() }.font(.system(size: 11)).controlSize(.small)
}
}
HStack(alignment: .center) {
Toggle(isOn: Binding(get: { updater.automaticChecks }, set: { updater.automaticChecks = $0 })) {
Text("Check daily").font(.system(size: 11))
}
.toggleStyle(.switch).controlSize(.mini).tint(T.accent)
.help("Fetches the appcast from the latest GitHub release once a day. Nothing is installed without asking.")
Spacer()
Button("Check now") { updater.check() }.font(.system(size: 11)).controlSize(.small).disabled(!updater.canCheck)
}
}
HStack {
Text("patchbay \(Updater.version) · GPLv3").font(m.monoSmall).foregroundStyle(.tertiary)
Spacer()
Link("GitHub", destination: URL(string: "https://github.com/azain47/patchbay")!).font(.system(size: 11))
}
}
.padding(16)
.frame(width: 300)
}
}
struct SettingGroup<Content: View>: View {
@Environment(\.metrics) private var m
let title: String
let content: Content
init(_ title: String, @ViewBuilder content: () -> Content) { self.title = title; self.content = content() }
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(title.uppercased()).font(m.section).tracking(1).foregroundStyle(.tertiary)
content
}
}
}
// MARK: - Fix tab
struct FixTab: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
var body: some View {
VStack(spacing: 0) {
SectionLabel(text: "Audio recovery").padding(.horizontal, T.rowInset + 10).padding(.top, m.sectionTop).padding(.bottom, m.sectionTop / 2)
VStack(spacing: m.rowGap) {
FixRow(icon: "wrench.and.screwdriver.fill", title: "Fix audio", detail: "Reselect a real output and relaunch eqMac if it was routing", kind: .fix, audio: audio) { audio.fixAudio() }
FixRow(icon: "arrow.clockwise", title: "Restart eqMac", detail: "Kill and relaunch eqMac, restoring the hardware output first", kind: .restart, audio: audio) { audio.restartEqMac() }
FixRow(icon: "bolt.fill", title: "Reset Core Audio", detail: "Restart coreaudiod (asks for your password). Audio drops for ~3 s", kind: .reset, audio: audio) { audio.resetCA() }
}
.padding(.horizontal, T.rowInset)
HStack(spacing: 8) {
Circle().fill(audio.eqMacOn ? T.ok : Color.secondary.opacity(0.3)).frame(width: 6, height: 6)
Text(audio.eqMacOn ? "eqMac is running" : "eqMac is not running").font(m.mono).foregroundStyle(.tertiary).lineLimit(1).fixedSize()
Spacer(minLength: 12)
if let out = audio.currentOutput {
Text("default → \(out.name)").font(m.mono).foregroundStyle(out.isEqMac && !audio.eqMacOn ? T.warn : Color.secondary.opacity(0.5))
.lineLimit(1).truncationMode(.middle).help(out.name)
}
}
.padding(.horizontal, T.rowInset + 10).padding(.top, m.sectionTop)
Color.clear.frame(height: m.sectionTop)
}
.frame(maxWidth: .infinity, alignment: .top)
}
}
struct FixRow: View {
@Environment(\.metrics) private var m
let icon: String
let title: String
let detail: String
let kind: Action
@ObservedObject var audio: AudioState
let action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 12) {
ZStack {
Circle().fill(Color.primary.opacity(0.08))
Image(systemName: icon).font(.system(size: 12, weight: .medium)).foregroundStyle(T.accent)
}
.frame(width: m.badge, height: m.badge)
VStack(alignment: .leading, spacing: 2) {
Text(title).font(m.nameStrong)
if m.subtitle { Text(detail).font(.system(size: m.monoSize)).foregroundStyle(.tertiary) }
}
Spacer()
if audio.active == kind {
ProgressView().controlSize(.small).scaleEffect(0.7).frame(width: 16, height: 16)
} else {
Image(systemName: "chevron.right").font(.system(size: 10, weight: .semibold)).foregroundStyle(.quaternary)
}
}
.padding(.horizontal, 10).padding(.vertical, m.rowV + 1)
.contentShape(Rectangle())
}
.buttonStyle(Press())
.help(detail)
.disabled(audio.active != nil)
.opacity(audio.active != nil && audio.active != kind ? 0.5 : 1)
.hoverRow()
}
}
// MARK: - Output / Input tabs
struct OutputTab: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
var body: some View {
VStack(spacing: 0) {
SectionLabel(text: "Output devices").padding(.horizontal, T.rowInset + 10).padding(.top, m.sectionTop).padding(.bottom, m.sectionTop / 2)
VStack(spacing: m.rowGap) {
ForEach(audio.outputs) { d in
DeviceRow(device: d, isRackTarget: audio.rackOn && audio.rackTarget?.id == d.id, action: { audio.select(d) }) {
if !d.isEqMac { DevicePresetTag(audio: audio, device: d) }
}
}
}
.padding(.horizontal, T.rowInset)
if let vol = audio.outputVolume, audio.currentOutput?.isEqMac == false {
LevelRow(icon: "speaker.wave.2", value: Double(vol), muted: false, toggleMute: nil) { audio.setOutputVolume(Float($0)) }
.padding(.top, m.sectionTop - 2)
}
Color.clear.frame(height: m.sectionTop)
}
.frame(maxWidth: .infinity, alignment: .top)
}
}
struct InputTab: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
var body: some View {
VStack(spacing: 0) {
SectionLabel(text: "Input devices").padding(.horizontal, T.rowInset + 10).padding(.top, m.sectionTop).padding(.bottom, m.sectionTop / 2)
VStack(spacing: m.rowGap) {
ForEach(audio.inputs) { d in
DeviceRow(device: d, isRackTarget: audio.micProcessing && audio.micSource?.id == d.id, isDefault: audio.micSource?.id == d.id) { audio.select(d) }
}
}
.padding(.horizontal, T.rowInset)
LevelRow(icon: "mic", value: Double(audio.inputVolume), muted: audio.micMuted, toggleMute: { audio.setMicMuted(!audio.micMuted) }) { audio.setInputVolume(Float($0)) }
.padding(.top, m.sectionTop - 2)
if audio.virtualMicInstalled {
SectionLabel(text: "Microphone chain").padding(.horizontal, T.rowInset + 10).padding(.top, m.sectionTop + 4).padding(.bottom, m.sectionTop / 2)
MicSection(audio: audio).padding(.horizontal, T.rowInset)
}
Color.clear.frame(height: m.sectionTop)
}
.frame(maxWidth: .infinity, alignment: .top)
}
}
/// Processed microphone row, shown once the patchbay Mic driver is installed (Settings →
/// Virtual microphone): on/off, live status, and a way into the chain editor.
struct MicSection: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
var body: some View {
Group {
HStack(spacing: 10) {
Button { audio.setMicProcessing(!audio.micProcessing) } label: {
Circle().fill(dot).frame(width: 7, height: 7).frame(width: 14, height: 14).contentShape(Rectangle())
}
.buttonStyle(.plain).disabled(audio.micBusy)
ZStack {
Circle().fill(audio.micProcessing ? T.accent.opacity(0.9) : Color.primary.opacity(0.08))
Image(systemName: "waveform.and.mic").font(.system(size: 11, weight: .medium))
.foregroundStyle(audio.micProcessing ? T.onAccent : Color.primary.opacity(0.7))
}
.frame(width: m.badge, height: m.badge)
VStack(alignment: .leading, spacing: 2) {
Text("patchbay Mic").font(m.nameStrong)
Text(statusText).font(m.monoSmall).foregroundStyle(.tertiary).lineLimit(1)
}
Spacer()
Toggle("", isOn: Binding(get: { audio.micProcessing }, set: { audio.setMicProcessing($0) }))
.labelsHidden().toggleStyle(.switch).controlSize(.small).tint(T.accent)
.disabled(audio.micBusy || !audio.virtualMicPresent)
IconButton("slider.horizontal.3", active: audio.rackScope == .input) {
audio.setRackScope(.input)
audio.tab = .rack
}
.help("Edit the microphone chain")
}
.padding(.horizontal, 10).padding(.vertical, m.rowV + 1)
.hoverRow()
if m.subtitle {
Text("While on, apps see “patchbay Mic” as the default microphone and receive the processed signal. Turning it off hands the default back to \(audio.micSource?.name ?? "the real microphone").")
.font(.system(size: m.monoSize)).foregroundStyle(.tertiary).fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, m.gutter - 4).padding(.top, 6)
}
}
}
private var statusText: String {
if audio.micBusy { return "restarting Core Audio…" }
if !audio.virtualMicPresent { return "driver installed, device not up yet" }
return audio.micProcessing ? audio.micStatus.label : "off"
}
private var dot: Color {
guard audio.micProcessing else { return Color.primary.opacity(0.18) }
switch audio.micStatus {
case .running: return T.ok
case .proving, .waiting: return T.accent
case .failed: return T.warn
case .stopped: return Color.primary.opacity(0.18)
}
}
}
// MARK: - Routes tab
struct RoutesTab: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
private var unrouted: [AudioApp] { audio.audioApps.filter { app in !audio.routes.contains { $0.bundleID == app.bundleID } } }
var body: some View {
VStack(spacing: 0) {
HStack {
SectionLabel(text: "App routes")
Menu {
if unrouted.isEmpty {
Text("No other apps are connected to Core Audio")
}
ForEach(unrouted) { app in
Button {
audio.addRoute(app: app, outputUID: audio.rackTarget?.uid ?? audio.outputs.first?.uid ?? "")
} label: {
Label { Text(app.name) } icon: {
if let icon = AudioApp.icon(for: app.bundleID) { Image(nsImage: icon) }
}
}
}
} label: {
Image(systemName: "plus").font(.system(size: 11, weight: .semibold)).foregroundStyle(.secondary).frame(width: 22, height: 20)
}
.menuStyle(.borderlessButton).menuIndicator(.hidden).frame(width: 26)
.help("Route an app to a device")
}
.padding(.leading, T.rowInset + 10).padding(.trailing, T.rowInset + 2).padding(.top, m.sectionTop).padding(.bottom, m.sectionTop / 2)
if audio.routes.isEmpty {
VStack(spacing: 6) {
Image(systemName: "arrow.triangle.branch").font(.system(size: 20)).foregroundStyle(.tertiary)
Text("Send one app to a different output.").font(.system(size: 12, weight: .medium)).foregroundStyle(.secondary)
Text("Everything you do not route keeps using the system chain.").font(.system(size: 11)).foregroundStyle(.tertiary)
}
.frame(maxWidth: .infinity).padding(.vertical, m.sectionTop * 2)
} else {
VStack(spacing: m.rowGap) {
ForEach(audio.routes) { route in RouteRow(route: route, audio: audio) }
}
.padding(.horizontal, T.rowInset)
.animation(T.quick, value: audio.routes.map(\.id))
}
Color.clear.frame(height: m.sectionTop)
}
.frame(maxWidth: .infinity, alignment: .top)
.onAppear { audio.refreshProcesses() }
}
}
struct RouteRow: View {
@Environment(\.metrics) private var m
let route: Route
@ObservedObject var audio: AudioState
@State private var hover = false
private var status: SystemAudioEngine.Status { audio.routeStatus[route.id] ?? .stopped }
private var device: Device? { audio.outputs.first { $0.uid == route.outputUID } }
private var editing: Bool { audio.rackScope == .route(route.id) }
var body: some View {
HStack(spacing: 10) {
Button { audio.setRoute(route.id, enabled: !route.enabled) } label: {
Circle().fill(dot).frame(width: 7, height: 7).frame(width: 14, height: 14).contentShape(Rectangle())
}
.buttonStyle(.plain).help(route.enabled ? status.label : "off")
if let icon = AudioApp.icon(for: route.bundleID) {
Image(nsImage: icon).resizable().frame(width: m.badge - 2, height: m.badge - 2)
} else {
Image(systemName: "app").frame(width: m.badge - 2, height: m.badge - 2).foregroundStyle(.secondary)
}
VStack(alignment: .leading, spacing: 2) {
Text(route.name).font(m.nameStrong).lineLimit(1).foregroundStyle(route.enabled ? .primary : .secondary)
if m.subtitle { Text(route.enabled ? status.label : "off").font(m.monoSmall).foregroundStyle(.tertiary) }
}
// Both texts outrank the spacer, so they split the row between them and
// truncate only once it is genuinely full.
.layoutPriority(1)
Spacer(minLength: 6)
Image(systemName: "arrow.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(.quaternary)
Hug {
Menu {
ForEach(audio.outputs.filter { !$0.isEqMac }) { d in
Button { audio.setRoute(route.id, outputUID: d.uid) } label: {
HStack { Text(d.name); if d.uid == route.outputUID { Image(systemName: "checkmark") } }
}
}
} label: {
HStack(spacing: 5) {
Image(systemName: device?.icon ?? "questionmark").font(.system(size: 10))
Text(device?.name ?? "Not connected").font(m.name).lineLimit(1)
}
.foregroundStyle(device == nil ? T.warn : .primary)
}
.menuStyle(.borderlessButton).menuIndicator(.visible)
}
.padding(.leading, 8).padding(.trailing, 2).padding(.vertical, 3)
.background(Capsule().fill(T.card))
.overlay(Capsule().strokeBorder(T.hairline, lineWidth: 0.5))
.layoutPriority(1)
IconButton("slider.horizontal.3", active: editing) {
audio.setRackScope(.route(route.id))
audio.tab = .rack
}
.help("Edit this route's chain")
IconButton("xmark") { audio.removeRoute(route.id) }.help("Remove route").opacity(hover ? 1 : 0.3)
}
.padding(.horizontal, 10).padding(.vertical, m.rowV + 1)
.background(RoundedRectangle(cornerRadius: 8).fill(hover ? T.hover : .clear))
.onHover { hover = $0 }
.animation(T.hoverAnim, value: hover)
}
private var dot: Color {
guard route.enabled else { return Color.primary.opacity(0.18) }
switch status {
case .running: return T.ok
case .proving, .waiting: return T.accent
case .failed: return T.warn
case .stopped: return Color.primary.opacity(0.18)
}
}
}
struct DeviceRow<Accessory: View>: View {
@Environment(\.metrics) private var m
let device: Device
let isRackTarget: Bool
/// Which row is checked. Defaults to macOS's default device; the input list passes
/// the chain's source instead, since the default becomes the virtual mic while on.
var isDefault: Bool? = nil
let action: () -> Void
/// Trailing control with its own clicks (the output list's preset tag).
@ViewBuilder var accessory: Accessory
var body: some View {
let selected = isDefault ?? device.isDefault
HStack(spacing: 12) {
ZStack {
Circle().fill(selected ? T.accent.opacity(0.9) : Color.primary.opacity(0.08))
Image(systemName: device.icon).font(.system(size: 12, weight: .medium))
.foregroundStyle(selected ? T.onAccent : Color.primary.opacity(0.7))
}
.frame(width: m.badge, height: m.badge)
VStack(alignment: .leading, spacing: 2) {
Text(device.name).font(selected ? m.nameStrong : m.name).lineLimit(1).truncationMode(.middle)
if m.subtitle {
Text("\(device.formattedRate) \(device.transportLabel)").font(m.monoSmall).foregroundStyle(.tertiary).lineLimit(1)
}
}
.help(device.name)
Spacer(minLength: 8)
accessory
if !m.subtitle { Text(device.formattedRate).font(m.monoSmall).foregroundStyle(.tertiary).fixedSize() }
Image(systemName: "waveform").font(.system(size: 11)).foregroundStyle(T.accent)
.opacity(isRackTarget ? 1 : 0).help("The rack processes this output")
Image(systemName: "checkmark").font(.system(size: 10, weight: .semibold)).foregroundStyle(.secondary)
.opacity(selected ? 1 : 0)
}
.padding(.horizontal, 10).padding(.vertical, m.rowV)
.contentShape(Rectangle())
.onTapGesture(perform: action)
.hoverRow(m.subtitle ? 8 : 6)
.animation(T.snap, value: selected)
.animation(T.quick, value: isRackTarget)
}
}
extension DeviceRow where Accessory == EmptyView {
init(device: Device, isRackTarget: Bool, isDefault: Bool? = nil, action: @escaping () -> Void) {
self.init(device: device, isRackTarget: isRackTarget, isDefault: isDefault, action: action) { EmptyView() }
}
}
/// The preset an output loads when it becomes active. Faint bookmark while unbound, the
/// preset's name once bound; either way a menu to pick one.
struct DevicePresetTag: View {
@Environment(\.metrics) private var m
@ObservedObject var audio: AudioState
let device: Device
@State private var hover = false
var body: some View {
let bound = audio.boundPreset(for: device.uid)
Hug(maxWidth: 140) {
Menu {
Section("Load on \(device.name)") {
Button { audio.bindPreset(nil, to: device) } label: {
HStack { Text("No preset"); if bound == nil { Image(systemName: "checkmark") } }
}
ForEach(audio.presets) { p in
Button { audio.bindPreset(p.id, to: device) } label: {
HStack { Text(p.name); if bound?.id == p.id { Image(systemName: "checkmark") } }
}
}
}
if audio.presets.isEmpty { Text("Save a preset from the rack first") }
} label: {
HStack(spacing: 4) {
Image(systemName: bound == nil ? "bookmark" : "bookmark.fill").font(.system(size: 9))
if let bound { Text(bound.name).font(.system(size: 10.5, weight: .medium)).lineLimit(1).truncationMode(.middle) }
}
.foregroundStyle(bound == nil ? AnyShapeStyle(.tertiary) : AnyShapeStyle(T.accent))
}
.menuStyle(.borderlessButton).menuIndicator(.hidden)
.tint(bound == nil ? Color.secondary : T.accent)
}
.padding(.horizontal, bound == nil ? 5 : 8).padding(.vertical, 3)
.background(Capsule().fill(bound == nil ? (hover ? T.hover : .clear) : T.accent.opacity(0.13)))
.opacity(bound == nil && !hover ? 0.6 : 1)
.onHover { hover = $0 }
.help(bound.map { "Loads “\($0.name)” when \(device.name) becomes the output" } ?? "Pick a preset to load when \(device.name) becomes the output")
}
}
struct LevelRow: View {