-
-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathContentView.swift
More file actions
819 lines (759 loc) · 33.8 KB
/
ContentView.swift
File metadata and controls
819 lines (759 loc) · 33.8 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
import SwiftUI
import WhatCableCore
import WhatCableDarwinBackend
import WhatCableAppKit
// MARK: - Font scaling environment
private struct FontScaleKey: EnvironmentKey {
static let defaultValue: Double = 1.0
}
extension EnvironmentValues {
var fontScale: Double {
get { self[FontScaleKey.self] }
set { self[FontScaleKey.self] = newValue }
}
}
/// View modifier that reads the fontScale environment and applies a scaled
/// version of the given text style. Use `.scaledFont(.caption)` instead of
/// `.font(.caption)` on any text that should respond to the slider.
struct ScaledFontModifier: ViewModifier {
@Environment(\.fontScale) private var scale
let style: Font.TextStyle
let design: Font.Design?
let weight: Font.Weight?
let monospacedDigit: Bool
init(_ style: Font.TextStyle, design: Font.Design? = nil, weight: Font.Weight? = nil, monospacedDigit: Bool = false) {
self.style = style
self.design = design
self.weight = weight
self.monospacedDigit = monospacedDigit
}
func body(content: Content) -> some View {
let baseSize = Self.baseSize(for: style)
let size = baseSize * scale
var font: Font = design != nil
? .system(size: size, design: design!)
: .system(size: size)
if let weight { font = font.weight(weight) }
if monospacedDigit { font = font.monospacedDigit() }
return content.font(font)
}
static func baseSize(for style: Font.TextStyle) -> Double {
switch style {
case .largeTitle: return 26
case .title: return 22
case .title2: return 17
case .title3: return 15
case .headline: return 13
case .body: return 13
case .callout: return 12
case .subheadline: return 11
case .footnote: return 10
case .caption: return 10
case .caption2: return 9
@unknown default: return 13
}
}
}
extension View {
func scaledFont(_ style: Font.TextStyle, design: Font.Design? = nil, weight: Font.Weight? = nil, monospacedDigit: Bool = false) -> some View {
modifier(ScaledFontModifier(style, design: design, weight: weight, monospacedDigit: monospacedDigit))
}
}
struct ContentView: View {
@StateObject private var portWatcher = USBCPortWatcher()
@StateObject private var deviceWatcher = USBWatcher()
@StateObject private var powerWatcher = PowerSourceWatcher()
@StateObject private var pdWatcher = PDIdentityWatcher()
@StateObject private var tbWatcher = ThunderboltWatcher()
@StateObject private var usb3Watcher = USB3TransportWatcher()
@StateObject private var trmWatcher = TRMTransportWatcher()
@EnvironmentObject private var refresh: RefreshSignal
@ObservedObject private var settings = AppSettings.shared
@ObservedObject private var updates = UpdateChecker.shared
@State private var portRefreshTask: Task<Void, Never>?
@State private var portPollTask: Task<Void, Never>?
@State private var isDesktopMac = false
private var showAdvanced: Bool {
settings.showTechnicalDetails || refresh.optionHeld
}
var body: some View {
Group {
if refresh.showSettings {
SettingsView(dismiss: { refresh.showSettings = false })
} else {
mainContent
}
}
.environment(\.fontScale, settings.fontSize)
.onAppear {
portWatcher.start()
deviceWatcher.start()
powerWatcher.start()
pdWatcher.start()
tbWatcher.start()
usb3Watcher.start()
trmWatcher.start()
startPortPoll()
isDesktopMac = SmartBatteryReader.read().isDesktopMac
}
.onDisappear {
portRefreshTask?.cancel()
portRefreshTask = nil
portPollTask?.cancel()
portPollTask = nil
portWatcher.stop()
deviceWatcher.stop()
powerWatcher.stop()
pdWatcher.stop()
tbWatcher.stop()
usb3Watcher.stop()
trmWatcher.stop()
}
.onChange(of: refresh.tick) { _, _ in
portWatcher.refresh()
powerWatcher.refresh()
pdWatcher.refresh()
tbWatcher.refresh()
usb3Watcher.refresh()
trmWatcher.refresh()
}
// Port controller services don't fire IOKit match notifications when
// their connection state flips, so we re-poll the port watcher
// whenever any of the three live signals (device add/remove, power
// source add/remove, PD identity add/remove) changes. Debounced so a
// single plug event, which can fire all three within a few ms,
// produces one refresh, with a backoff to catch slow controllers.
.onChange(of: deviceWatcher.devices) { _, _ in scheduleLivePortRefresh() }
.onChange(of: powerWatcher.sources) { _, _ in scheduleLivePortRefresh() }
.onChange(of: pdWatcher.identities) { _, _ in scheduleLivePortRefresh() }
}
private func scheduleLivePortRefresh() {
portRefreshTask?.cancel()
portRefreshTask = Task { @MainActor in
// Some port controllers (notably AppleHPMInterfaceType11 / MagSafe)
// hold ConnectionActive=true for several seconds after unplug, so
// we re-poll over a long backoff instead of guessing one delay.
// refresh() is a no-op when nothing changed, so extra polls are
// cheap and never cause flicker.
for delay in [150, 500, 1500, 3000, 6000] {
try? await Task.sleep(for: .milliseconds(delay))
guard !Task.isCancelled else { return }
portWatcher.refresh()
}
}
}
/// Background safety net: poll the port watcher once a second while the
/// popover is visible. Catches slow-updating controllers that don't fire
/// IOKit interest notifications when their connection state flips, and
/// covers state changes that happen outside the burst window triggered
/// by scheduleLivePortRefresh. The conditional assignment in
/// USBCPortWatcher.refresh() means polls are free when nothing changed.
private func startPortPoll() {
portPollTask?.cancel()
portPollTask = Task { @MainActor in
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(1))
guard !Task.isCancelled else { return }
portWatcher.refresh()
}
}
}
private var mainContent: some View {
VStack(spacing: 0) {
header
if let update = updates.available {
UpdateBanner(update: update)
}
Divider()
if isDesktopMac {
HStack(spacing: 4) {
Image(systemName: "info.circle")
Text(String(localized: "Desktop Mac: charger identity (FedDetails) is not available.", bundle: _appLocalizedBundle))
}
.scaledFont(.caption)
.foregroundStyle(.secondary)
.padding(.horizontal, 12)
.padding(.vertical, 6)
}
let visiblePorts = settings.hideEmptyPorts
? portWatcher.ports.filter { isPortLive($0) }
: portWatcher.ports
if visiblePorts.isEmpty {
if portWatcher.ports.isEmpty {
noPortsState
} else {
nothingConnectedState
}
} else {
let activePortCount = portWatcher.ports.filter { $0.connectionActive == true }.count
let adapter = SystemPower.currentAdapter()
ScrollView {
VStack(spacing: 12) {
ForEach(visiblePorts) { port in
let portSources = powerWatcher.sources(for: port)
let wattageSource = ChargerWattageSource.resolve(
portSources: portSources,
activePortCount: activePortCount,
adapter: adapter
)
PortCard(
port: port,
devices: matchingDevices(for: port),
powerSources: portSources,
identities: pdWatcher.identities(for: port),
thunderboltSwitches: tbWatcher.switches,
usb3Transports: usb3Watcher.transports(for: port),
isLive: isPortLive(port),
showAdvanced: showAdvanced,
cioCapability: trmWatcher.cioCapabilities.first { $0.portKey == port.portKey },
chargerWattageSource: wattageSource
)
}
}
.padding(12)
}
}
Divider()
footer
}
}
private var header: some View {
HStack {
Image(systemName: "cable.connector.horizontal")
.scaledFont(.title2)
VStack(alignment: .leading, spacing: 2) {
Text(AppInfo.name).scaledFont(.headline, weight: .bold)
Text(AppInfo.tagline)
.scaledFont(.caption)
.foregroundStyle(.secondary)
}
Spacer()
ForEach(Array(PluginRegistry.shared.headerButtonBuilders.enumerated()), id: \.offset) { _, builder in
builder()
}
Button {
refresh.bump()
} label: {
Image(systemName: "arrow.clockwise")
}
.buttonStyle(.borderless)
.help(String(localized: "Refresh", bundle: _appLocalizedBundle))
Button {
refresh.showSettings = true
} label: {
Image(systemName: "gearshape")
}
.buttonStyle(.borderless)
.help(String(localized: "Settings", bundle: _appLocalizedBundle))
}
.padding(12)
.background(
Button("") {
refresh.showSettings = true
}
.keyboardShortcut(",", modifiers: .command)
.opacity(0)
.allowsHitTesting(false)
)
}
private var footer: some View {
HStack {
Toggle(String(localized: "Show technical details", bundle: _appLocalizedBundle), isOn: $settings.showTechnicalDetails)
.toggleStyle(.switch)
.controlSize(.mini)
.scaledFont(.caption)
Spacer()
Text(String(localized: "\(deviceWatcher.devices.count) USB devices", bundle: _appLocalizedBundle))
.scaledFont(.caption)
.foregroundStyle(.secondary)
Text(verbatim: "·").scaledFont(.caption).foregroundStyle(.secondary)
Text(verbatim: "v\(AppInfo.version) · \(AppInfo.credit)")
.scaledFont(.caption)
.foregroundStyle(.tertiary)
Text(verbatim: "·").scaledFont(.caption).foregroundStyle(.secondary)
Button(String(localized: "Quit", bundle: _appLocalizedBundle)) { NSApplication.shared.terminate(nil) }
.buttonStyle(.borderless)
.scaledFont(.caption)
.foregroundStyle(.secondary)
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
}
private var noPortsState: some View {
VStack(spacing: 8) {
Image(systemName: "powerplug")
.scaledFont(.largeTitle)
.foregroundStyle(.secondary)
Text(String(localized: "No USB-C ports detected", bundle: _appLocalizedBundle))
.scaledFont(.headline, weight: .bold)
Text(String(localized: "This Mac doesn't seem to expose its port-controller services. Hit refresh, or check System Information > USB.", bundle: _appLocalizedBundle))
.scaledFont(.caption)
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
.padding(.horizontal, 32)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.vertical, 40)
}
private var nothingConnectedState: some View {
VStack(spacing: 8) {
Image(systemName: "cable.connector.slash")
.scaledFont(.largeTitle)
.foregroundStyle(.secondary)
Text(String(localized: "Nothing connected", bundle: _appLocalizedBundle))
.scaledFont(.headline, weight: .bold)
Text(String(localized: "\(portWatcher.ports.count) USB-C ports detected, but nothing is currently plugged in. Turn off \"Hide empty ports\" in Settings to see them.", bundle: _appLocalizedBundle))
.scaledFont(.caption)
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
.padding(.horizontal, 32)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
/// Live-signal check delegating to the pure helper in `WhatCableCore`,
/// so the same rules apply to both the GUI and any test harness.
private func isPortLive(_ port: USBCPort) -> Bool {
WhatCableCore.isPortLive(
port: port,
powerSources: powerWatcher.sources(for: port),
identities: pdWatcher.identities(for: port),
matchingDevices: matchingDevices(for: port)
)
}
/// Match USB devices to their physical port. The IOKit relationship
/// isn't direct: USB devices live under the XHCI controller subtree,
/// physical ports under the SPMI/HPM subtree. Two strategies, in order:
///
/// 1. `controllerPortName`: each XHCI controller exposes a `UsbIOPort`
/// property whose path ends in the physical port's service name
/// (e.g. ".../Port-USB-C@1"). When present, this gives a direct
/// link with no ambiguity.
/// 2. `busIndex`: derived from the `hpm<N>` ancestor on the port side
/// and the XHCI controller's `locationID` upper byte on the device
/// side. Fragile, breaks when devices sit deeper behind a hub
/// than the parent walk reaches, or when hpm numbering diverges
/// from controller numbering.
///
/// If neither is available we return [] rather than dumping every
/// device onto the port. Showing all devices on every active USB port
/// is worse than showing none, and it caused the bug that issue #21
/// reported.
private func matchingDevices(for port: USBCPort) -> [USBDevice] {
port.matchingDevices(from: deviceWatcher.devices)
}
}
struct UpdateBanner: View {
let update: AvailableUpdate
@ObservedObject private var installer = Installer.shared
var body: some View {
HStack(spacing: 8) {
Image(systemName: "arrow.down.circle.fill")
.foregroundStyle(.tint)
VStack(alignment: .leading, spacing: 2) {
Text(String(localized: "WhatCable \(update.version) is available", bundle: _appLocalizedBundle))
.scaledFont(.callout, weight: .bold)
statusLine
.scaledFont(.caption).foregroundStyle(.secondary)
}
Spacer()
actionButtons
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(Color.accentColor.opacity(0.12))
}
@ViewBuilder
private var statusLine: some View {
switch installer.state {
case .idle:
Text(String(localized: "You're on \(AppInfo.version)", bundle: _appLocalizedBundle))
case .downloading:
Text(String(localized: "Downloading…", bundle: _appLocalizedBundle))
case .verifying:
Text(String(localized: "Verifying signature…", bundle: _appLocalizedBundle))
case .installing:
Text(String(localized: "Installing, WhatCable will relaunch", bundle: _appLocalizedBundle))
case .failed(let message):
Text(String(localized: "Install failed: \(message)", bundle: _appLocalizedBundle)).foregroundStyle(.red)
}
}
@ViewBuilder
private var actionButtons: some View {
switch installer.state {
case .idle, .failed:
HStack(spacing: 6) {
Button(String(localized: "View release", bundle: _appLocalizedBundle)) {
NSWorkspace.shared.open(update.url)
}
.buttonStyle(.bordered)
.controlSize(.small)
if update.downloadURL != nil {
Button(String(localized: "Install update", bundle: _appLocalizedBundle)) {
Installer.shared.install(update)
}
.buttonStyle(.borderedProminent)
.controlSize(.small)
}
}
case .downloading, .verifying, .installing:
ProgressView().controlSize(.small)
}
}
}
// MARK: - Port card
struct PortCard: View {
let port: USBCPort
let devices: [USBDevice]
let powerSources: [PowerSource]
let identities: [PDIdentity]
let thunderboltSwitches: [ThunderboltSwitch]
let usb3Transports: [USB3Transport]
/// Authoritative connection state derived from the live IOKit watchers,
/// passed in from the parent so we don't have to consult them from here
/// and so PortSummary doesn't fall back to the unreliable
/// `port.connectionActive` property.
let isLive: Bool
let showAdvanced: Bool
let cioCapability: CIOCableCapability?
let chargerWattageSource: ChargerWattageSource
@State private var reportingCable: PDIdentity?
var summary: PortSummary {
PortSummary(
port: port,
sources: powerSources,
identities: identities,
devices: devices,
thunderboltSwitches: thunderboltSwitches,
usb3Transports: usb3Transports,
cioCapability: cioCapability,
isConnectedOverride: isLive,
chargerWattageSource: chargerWattageSource
)
}
/// Switches in the chain from this port's host root to the deepest
/// connected device. Empty if the port doesn't map to any TB switch.
var thunderboltChain: [ThunderboltSwitch] {
guard let socketID = ThunderboltTopology.socketID(fromServiceName: port.serviceName),
let root = ThunderboltTopology.hostRoot(forSocketID: socketID, in: thunderboltSwitches) else {
return []
}
return ThunderboltTopology.chain(from: root, in: thunderboltSwitches)
}
private var cableEmarker: PDIdentity? {
identities.first { $0.endpoint == .sopPrime || $0.endpoint == .sopDoublePrime }
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top, spacing: 12) {
Image(systemName: summary.icon)
.scaledFont(.title2)
.foregroundStyle(summary.iconColor)
.frame(width: 36)
VStack(alignment: .leading, spacing: 2) {
Text(port.portDescription ?? port.serviceName)
.scaledFont(.caption)
.foregroundStyle(.secondary)
Text(summary.headline)
.scaledFont(.title3, weight: .bold)
Text(summary.subtitle)
.scaledFont(.callout)
.foregroundStyle(.secondary)
}
Spacer()
let ctx = PortCardContext(
portKey: port.portKey,
portNumber: port.portNumber,
serviceName: port.serviceName,
portTypeDescription: port.portTypeDescription,
pinConfiguration: port.pinConfiguration,
plugOrientation: port.plugOrientation
)
ForEach(Array(PluginRegistry.shared.portCardTrailingBuilders.enumerated()), id: \.offset) { _, builder in
if let view = builder(ctx) {
view
}
}
}
if !summary.bullets.isEmpty {
VStack(alignment: .leading, spacing: 4) {
ForEach(summary.bullets, id: \.self) { bullet in
HStack(alignment: .top, spacing: 6) {
Text(verbatim: "•").foregroundStyle(.secondary)
Text(bullet).scaledFont(.callout)
Spacer()
}
}
}
.padding(.leading, 48)
}
if !devices.isEmpty {
VStack(alignment: .leading, spacing: 4) {
Text(String(localized: "Connected devices", bundle: _appLocalizedBundle))
.scaledFont(.caption).foregroundStyle(.secondary)
ForEach(devices) { d in
let name = d.productName ?? String(localized: "Unknown", bundle: _appLocalizedBundle)
Text(verbatim: "• \(name) - \(d.speedLabel)")
.scaledFont(.callout)
}
}
.padding(.leading, 48)
}
if let diag = ChargingDiagnostic(port: port, sources: powerSources, identities: identities, wattageSource: chargerWattageSource) {
DiagnosticBanner(diagnostic: diag)
.padding(.leading, 48)
}
if !powerSources.isEmpty {
PowerSourceList(sources: powerSources)
.padding(.leading, 48)
}
if let cable = cableEmarker {
let trust = CableTrustReport(identity: cable)
if !trust.isEmpty {
TrustFlagsCard(flags: trust.flags)
.padding(.leading, 48)
}
HStack {
Spacer()
Button {
reportingCable = cable
} label: {
Label(String(localized: "Report this cable", bundle: _appLocalizedBundle), systemImage: "exclamationmark.bubble")
.scaledFont(.caption)
}
.buttonStyle(.borderless)
.help(String(localized: "File a GitHub issue with this cable's e-marker fingerprint", bundle: _appLocalizedBundle))
}
.padding(.leading, 48)
}
if showAdvanced {
Divider()
AdvancedPortDetails(
port: port,
cableEmarker: cableEmarker,
thunderboltChain: thunderboltChain
)
}
}
.padding(14)
.background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 10))
.sheet(item: $reportingCable) { cable in
CableReportSheet(cableIdentity: cable, cioCapability: cioCapability) {
reportingCable = nil
}
}
}
}
struct DiagnosticBanner: View {
let diagnostic: ChargingDiagnostic
var body: some View {
HStack(alignment: .top, spacing: 8) {
Image(systemName: diagnostic.icon)
.foregroundStyle(diagnostic.isWarning ? Color.orange : Color.green)
.scaledFont(.callout)
VStack(alignment: .leading, spacing: 2) {
Text(diagnostic.summary).scaledFont(.callout, weight: .bold)
Text(diagnostic.detail).scaledFont(.caption).foregroundStyle(.secondary)
}
Spacer()
}
.padding(10)
.background(
(diagnostic.isWarning ? Color.orange : Color.green)
.opacity(0.1),
in: RoundedRectangle(cornerRadius: 8)
)
}
}
struct PowerSourceList: View {
let sources: [PowerSource]
var body: some View {
VStack(alignment: .leading, spacing: 6) {
ForEach(sources) { src in
if !src.options.isEmpty {
VStack(alignment: .leading, spacing: 2) {
let srcName = src.name
Text(String(localized: "\(srcName) profiles", bundle: _appLocalizedBundle))
.scaledFont(.caption).foregroundStyle(.secondary)
ForEach(src.options.sorted(by: { $0.voltageMV < $1.voltageMV }), id: \.self) { opt in
let isWinning = opt == src.winning
HStack(spacing: 6) {
Image(systemName: isWinning ? "checkmark.circle.fill" : "circle")
.foregroundStyle(isWinning ? Color.green : Color.secondary)
.scaledFont(.caption)
Text(verbatim: "\(opt.voltsLabel) @ \(opt.ampsLabel) - \(opt.wattsLabel)")
.scaledFont(.callout, monospacedDigit: true)
if isWinning {
Text(String(localized: "active", bundle: _appLocalizedBundle)).scaledFont(.caption2).foregroundStyle(.green)
}
Spacer()
}
}
}
}
}
}
}
}
struct AdvancedPortDetails: View {
let port: USBCPort
let cableEmarker: PDIdentity?
let thunderboltChain: [ThunderboltSwitch]
var body: some View {
VStack(alignment: .leading, spacing: 8) {
group(String(localized: "Connection", bundle: _appLocalizedBundle)) {
row(String(localized: "Active", bundle: _appLocalizedBundle), bool(port.connectionActive))
row(String(localized: "Active cable electronics", bundle: _appLocalizedBundle), bool(port.activeCable))
row(String(localized: "Optical", bundle: _appLocalizedBundle), bool(port.opticalCable))
row(String(localized: "USB active", bundle: _appLocalizedBundle), bool(port.usbActive))
row(String(localized: "SuperSpeed", bundle: _appLocalizedBundle), bool(port.superSpeedActive))
row(String(localized: "Plug events", bundle: _appLocalizedBundle), port.plugEventCount.map(String.init) ?? "—")
}
group(String(localized: "Transports", bundle: _appLocalizedBundle)) {
row(String(localized: "Supported", bundle: _appLocalizedBundle), port.transportsSupported.joined(separator: ", "))
row(String(localized: "Provisioned", bundle: _appLocalizedBundle), port.transportsProvisioned.joined(separator: ", "))
row(String(localized: "Active", bundle: _appLocalizedBundle), port.transportsActive.isEmpty ? "—" : port.transportsActive.joined(separator: ", "))
}
if let v2 = cableEmarker?.activeCableVDO2 {
ActiveCableVDO2Section(vdo2: v2)
}
if !thunderboltChain.isEmpty {
ThunderboltFabricSection(chain: thunderboltChain)
}
let rawCount = port.rawProperties.count
DisclosureGroup(String(localized: "All raw IOKit properties (\(rawCount))", bundle: _appLocalizedBundle)) {
VStack(alignment: .leading, spacing: 2) {
ForEach(port.rawProperties.sorted(by: { $0.key < $1.key }), id: \.key) { kv in
HStack(alignment: .top) {
Text(kv.key).scaledFont(.caption, design: .monospaced)
.foregroundStyle(.secondary)
.frame(width: 200, alignment: .leading)
Text(kv.value).scaledFont(.caption, design: .monospaced)
.textSelection(.enabled)
Spacer()
}
}
}
.padding(.top, 4)
}
.scaledFont(.caption)
}
}
private func group<Content: View>(_ title: String, @ViewBuilder content: () -> Content) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(title).scaledFont(.caption, weight: .bold).foregroundStyle(.secondary)
content()
}
}
private func row(_ key: String, _ value: String) -> some View {
HStack {
Text(key).scaledFont(.caption).foregroundStyle(.secondary).frame(width: 160, alignment: .leading)
Text(value).scaledFont(.caption, design: .monospaced)
Spacer()
}
}
private func bool(_ v: Bool?) -> String {
guard let v else { return "—" }
return v ? String(localized: "Yes", bundle: _appLocalizedBundle) : String(localized: "No", bundle: _appLocalizedBundle)
}
}
/// Renders every field in Active Cable VDO 2. Hidden behind the
/// existing "show technical details" toggle. The bullet list above the
/// fold already surfaces the user-facing essentials (medium, active
/// element, optical isolation), so this section is the deep view for
/// people who want to see USB protocol support, lane count, idle power,
/// thermal limits, etc.
struct ActiveCableVDO2Section: View {
let vdo2: PDVDO.ActiveCableVDO2
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Text("Active cable (VDO 2)")
.scaledFont(.caption, weight: .bold)
.foregroundStyle(.secondary)
row("Physical connection", vdo2.physicalConnection.label)
row("Active element", vdo2.activeElement.label)
row("Optically isolated", bool(vdo2.opticallyIsolated))
row("USB lanes", vdo2.twoLanesSupported ? "Two" : "One")
row("USB Gen", vdo2.usbGen2OrHigher ? "Gen 2 or higher" : "Gen 1")
row("USB4 supported", bool(vdo2.usb4Supported))
row("USB 3.2 supported", bool(vdo2.usb32Supported))
row("USB 2.0 supported", bool(vdo2.usb2Supported))
row("USB 2.0 hub hops", String(vdo2.usb2HubHopsConsumed))
row("USB4 asymmetric", bool(vdo2.usb4AsymmetricMode))
row("U3 to U0 transition", vdo2.u3ToU0TransitionThroughU3S ? "Through U3S" : "Direct")
row("Idle power (U3/CLd)", vdo2.u3CLdPower.label)
row("Max operating temp", temp(vdo2.maxOperatingTempC))
row("Shutdown temp", temp(vdo2.shutdownTempC))
}
}
private func row(_ key: String, _ value: String) -> some View {
HStack {
Text(key).scaledFont(.caption).foregroundStyle(.secondary).frame(width: 160, alignment: .leading)
Text(value).scaledFont(.caption, design: .monospaced)
Spacer()
}
}
private func bool(_ v: Bool) -> String { v ? "Yes" : "No" }
/// 0 in this field means "not specified" per the spec text. Show
/// the dash placeholder rather than the misleading literal "0°C".
private func temp(_ v: Int) -> String {
v == 0 ? "—" : "\(v)°C"
}
}
/// Compact tree view of the Thunderbolt fabric for one port. Shows the
/// host root, every downstream switch in the chain, and the active
/// downstream lane port's link state for each hop. Hidden behind the
/// existing "show technical details" toggle.
struct ThunderboltFabricSection: View {
let chain: [ThunderboltSwitch]
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(String(localized: "Thunderbolt fabric", bundle: _appLocalizedBundle))
.scaledFont(.caption, weight: .bold).foregroundStyle(.secondary)
ForEach(Array(chain.enumerated()), id: \.element.id) { index, sw in
hopRow(sw, index: index)
}
}
}
@ViewBuilder
private func hopRow(_ sw: ThunderboltSwitch, index: Int) -> some View {
let indent = String(repeating: " ", count: index)
let arrow = index == 0 ? "" : "↳ "
let name = sw.isHostRoot ? String(localized: "Host (\(sw.className))", bundle: _appLocalizedBundle) : ThunderboltLabels.deviceName(for: sw)
let port = ThunderboltTopology.activeDownstreamLanePort(sw)
let linkLabel = port.flatMap { ThunderboltLabels.linkLabel(for: $0) } ?? String(localized: "no active link", bundle: _appLocalizedBundle)
HStack(alignment: .top) {
Text(verbatim: "\(indent)\(arrow)\(name)")
.scaledFont(.caption, design: .monospaced)
Spacer()
Text(linkLabel)
.scaledFont(.caption, design: .monospaced)
.foregroundStyle(.secondary)
}
}
}
private struct TrustFlagsCard: View {
let flags: [TrustFlag]
var body: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(.orange)
Text(String(localized: "Cable trust signals", bundle: _appLocalizedBundle))
.scaledFont(.caption, weight: .bold)
.foregroundStyle(.secondary)
}
ForEach(flags, id: \.code) { flag in
VStack(alignment: .leading, spacing: 2) {
Text(flag.title).scaledFont(.callout, weight: .bold)
Text(flag.detail)
.scaledFont(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
.padding(8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.orange.opacity(0.12), in: RoundedRectangle(cornerRadius: 8))
}
}