perf(efficiency): 接入真实CPU能量并隔离展示与采样需求
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
import SwiftUI
|
||||
|
||||
/// A separate observation scope: energy completion does not replace the resource snapshot.
|
||||
struct EnergyProcessSection: View {
|
||||
let metrics: MetricsStore
|
||||
private var snapshot: ProcessEnergySnapshot? { metrics.energy }
|
||||
private var rows: [ProcessEnergyUsage] { snapshot?.rows ?? [] }
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
Text("energy.cpuProcesses").font(PanelStyle.section)
|
||||
if snapshot?.state == .partial {
|
||||
Text("energy.partial").font(.system(size: 8)).foregroundStyle(.secondary)
|
||||
.help(Text("energy.coverage \(snapshot?.measured ?? 0) \(snapshot?.candidates ?? 0)"))
|
||||
}
|
||||
Spacer()
|
||||
Text("energy.averagePower").foregroundStyle(.secondary)
|
||||
}.font(PanelStyle.label)
|
||||
if rows.isEmpty {
|
||||
Text(statusKey).foregroundStyle(.secondary).font(PanelStyle.label)
|
||||
} else {
|
||||
ForEach(rows) { usage in
|
||||
EnergyProcessListRow(usage: usage, maximum: rows.first?.watts ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
.help(Text("energy.scopeHelp"))
|
||||
}
|
||||
private var statusKey: LocalizedStringKey {
|
||||
switch snapshot?.state {
|
||||
case .unsupported: "energy.unsupported"
|
||||
case .unavailable: "energy.unavailable"
|
||||
default: "energy.waiting"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct EnergyProcessListRow: View {
|
||||
let usage: ProcessEnergyUsage
|
||||
let maximum: Double
|
||||
private var progress: Double { maximum > 0 ? min(1, max(0, usage.watts / maximum)) : 0 }
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 5) {
|
||||
ProcessIcon(process: usage.process)
|
||||
Text(verbatim: usage.process.name).lineLimit(1).truncationMode(.middle)
|
||||
.frame(width: 66, alignment: .leading)
|
||||
GeometryReader { proxy in
|
||||
Capsule().fill(.primary.opacity(0.07))
|
||||
.overlay(alignment: .leading) {
|
||||
Capsule().fill(Color("MetricCPU"))
|
||||
.frame(width: proxy.size.width * progress, height: 4).clipped()
|
||||
}.clipShape(Capsule())
|
||||
}.frame(height: 4)
|
||||
Text(verbatim: usage.formattedPower)
|
||||
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
|
||||
.monospacedDigit().frame(width: 57, alignment: .trailing)
|
||||
}
|
||||
.font(PanelStyle.label).frame(height: 16)
|
||||
.help(Text("energy.window \(usage.seconds.formatted(.number.precision(.fractionLength(1))))"))
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import SwiftUI
|
||||
import Observation
|
||||
|
||||
@MainActor @Observable final class PanelPresentation {
|
||||
fileprivate(set) var isOpen = false
|
||||
var isPinned = false { didSet { onPinChange?(isPinned) } }
|
||||
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
|
||||
}
|
||||
@@ -11,10 +12,14 @@ import Observation
|
||||
@MainActor final class MenuPanelController: NSObject {
|
||||
let presentation = PanelPresentation()
|
||||
let panel = MonitoringPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
private(set) weak var lastHiddenContent: NSView?
|
||||
#endif
|
||||
private var statusItem: NSStatusItem?
|
||||
private var localMouse: Any?
|
||||
private var globalMouse: Any?
|
||||
private var tokens: [NSObjectProtocol] = []
|
||||
private var visibilityObservation: NSKeyValueObservation?
|
||||
private let content: (PanelPresentation) -> NSView
|
||||
private let visibility: (Bool) -> Void
|
||||
private let menuTitle: (String) -> String
|
||||
@@ -52,6 +57,12 @@ import Observation
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.place() }
|
||||
})
|
||||
visibilityObservation = panel.observe(\.isVisible, options: [.new]) { [weak self] _, _ in
|
||||
Task { @MainActor [weak self] in self?.publishVisibility() }
|
||||
}
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, object: panel, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.publishVisibility() }
|
||||
})
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: NSApp, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated {
|
||||
guard let self, !self.showingStatusMenu, !self.isOverStatusItem(NSEvent.mouseLocation) else { return }
|
||||
@@ -98,6 +109,7 @@ import Observation
|
||||
func show() {
|
||||
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
|
||||
place()
|
||||
presentation.isOpen = true
|
||||
panel.contentView = content(presentation)
|
||||
panel.level = presentation.isPinned ? .floating : .normal
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
@@ -105,12 +117,20 @@ import Observation
|
||||
// Opening the panel must not start editing the first text field.
|
||||
// Explicit clicks and keyboard navigation can still focus its controls.
|
||||
panel.makeFirstResponder(panel)
|
||||
visibility(true)
|
||||
publishVisibility()
|
||||
installMonitors()
|
||||
}
|
||||
|
||||
private func publishVisibility() {
|
||||
visibility(panel.isVisible && panel.occlusionState.contains(.visible))
|
||||
}
|
||||
|
||||
func hide() {
|
||||
presentation.isOpen = false
|
||||
panel.orderOut(nil)
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
if let content = panel.contentView { lastHiddenContent = content }
|
||||
#endif
|
||||
panel.contentView = nil
|
||||
visibility(false)
|
||||
removeMonitors()
|
||||
@@ -127,6 +147,7 @@ import Observation
|
||||
statusItem = nil
|
||||
tokens.forEach(NotificationCenter.default.removeObserver)
|
||||
tokens.removeAll()
|
||||
visibilityObservation = nil
|
||||
}
|
||||
|
||||
private func place() {
|
||||
|
||||
@@ -52,20 +52,7 @@ extension MenuPanelView {
|
||||
}.font(PanelStyle.label)
|
||||
.modifier(CardInset())
|
||||
}
|
||||
.task(id: "\(publicIPRoute):\(metrics.isPaused)") {
|
||||
guard !metrics.isPaused, metrics.isPanelVisible else { return }
|
||||
publicIPAddress = nil
|
||||
guard snapshot.networkPath == .available else { return }
|
||||
await PublicIPAddressService.shared.refreshContinuously(route: publicIPRoute) { address in
|
||||
await MainActor.run {
|
||||
guard !Task.isCancelled else { return }
|
||||
publicIPAddress = address
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var publicIPRoute: String {
|
||||
"\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")"
|
||||
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
|
||||
}
|
||||
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
|
||||
HStack(spacing: 4) {
|
||||
|
||||
@@ -237,22 +237,7 @@ extension MenuPanelView {
|
||||
.frame(height: 32)
|
||||
Spacer(minLength: 0)
|
||||
CardSeparator()
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
Text("battery.highestEnergyProcess").font(PanelStyle.section)
|
||||
Spacer()
|
||||
Text("battery.cpuUsage").foregroundStyle(.secondary)
|
||||
}
|
||||
.font(PanelStyle.label)
|
||||
let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? []
|
||||
if energyProcesses.isEmpty {
|
||||
Text("metric.waiting").foregroundStyle(.secondary)
|
||||
} else {
|
||||
ForEach(energyProcesses) { process in
|
||||
EnergyProcessListRow(process: process)
|
||||
}
|
||||
}
|
||||
}
|
||||
EnergyProcessSection(metrics: metrics)
|
||||
// Reserve the header and all three rows before process sampling completes.
|
||||
.frame(height: 74, alignment: .top)
|
||||
.lineLimit(1)
|
||||
@@ -261,36 +246,3 @@ extension MenuPanelView {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct EnergyProcessListRow: View {
|
||||
let process: ProcessMetrics
|
||||
|
||||
private var progress: Double {
|
||||
guard let value = process.cpu, value.isFinite else { return 0 }
|
||||
return min(max(value, 0), 1)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 5) {
|
||||
ProcessIcon(process: process)
|
||||
Text(verbatim: process.name).lineLimit(1).truncationMode(.middle)
|
||||
.frame(width: 66, alignment: .leading)
|
||||
GeometryReader { proxy in
|
||||
Capsule().fill(.primary.opacity(0.07))
|
||||
.overlay(alignment: .leading) {
|
||||
Capsule().fill(Color("MetricCPU"))
|
||||
.frame(width: proxy.size.width * progress, height: 4)
|
||||
.clipped()
|
||||
}
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
.frame(height: 4)
|
||||
AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--")
|
||||
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
|
||||
.monospacedDigit().frame(width: 39, alignment: .trailing)
|
||||
}
|
||||
.font(PanelStyle.label)
|
||||
.frame(height: 16)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ struct MenuPanelView: View {
|
||||
} else {
|
||||
resourceRows
|
||||
}
|
||||
if metrics.isPanelVisible && PanelResourceAudit.omitted != "processes" {
|
||||
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
|
||||
PanelProcessSection(metrics: metrics, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.frame(minHeight: 170)
|
||||
}
|
||||
}
|
||||
@@ -65,13 +65,11 @@ struct MenuPanelView: View {
|
||||
if panelSize != size { panelSize = size }
|
||||
}.frame(width: 0, height: 0))
|
||||
.onAppear {
|
||||
metrics.setPanelVisible(true)
|
||||
reservedFanCount = snapshot.fans?.count ?? 0
|
||||
}
|
||||
.onChange(of: snapshot.fans?.count) { _, count in
|
||||
reservedFanCount = max(reservedFanCount, count ?? 0)
|
||||
}
|
||||
.onDisappear { metrics.setPanelVisible(false) }
|
||||
.onChange(of: snapshot.network?.map(\.identity)) { _, keys in
|
||||
if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" }
|
||||
}
|
||||
@@ -215,3 +213,10 @@ private struct PanelControlButtonBody<Content: View>: View {
|
||||
.onHover { isHovered = $0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep process publications out of the resource-card observation scope.
|
||||
private struct PanelProcessSection: View {
|
||||
let metrics: MetricsStore
|
||||
let wide: Bool
|
||||
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, wide: wide) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Shared by the dashboard and the text-only audit so network work is comparable.
|
||||
struct PanelPublicIPRefresh: ViewModifier {
|
||||
let metrics: MetricsStore
|
||||
@Binding var address: String?
|
||||
private var route: String {
|
||||
let snapshot = metrics.snapshot
|
||||
return "\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")"
|
||||
}
|
||||
func body(content: Content) -> some View {
|
||||
content.task(id: "\(route):\(metrics.isPaused):\(metrics.isSystemSleeping):\(metrics.isDisplaySleeping):\(metrics.isPanelVisible)") {
|
||||
guard !metrics.isPaused, !metrics.isSystemSleeping, !metrics.isDisplaySleeping, metrics.isPanelVisible else { return }
|
||||
address = nil
|
||||
guard metrics.snapshot.networkPath == .available else { return }
|
||||
await PublicIPAddressService.shared.refreshContinuously(route: route) { value in
|
||||
await MainActor.run {
|
||||
guard !Task.isCancelled else { return }
|
||||
address = value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,26 @@ import AppKit
|
||||
|
||||
/// Explicit local measurement only. Never schedules work during normal launches.
|
||||
@MainActor enum PanelResourceAudit {
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1"
|
||||
static let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : ""
|
||||
|
||||
static func run(controller: MenuPanelController, metrics: MetricsStore) {
|
||||
guard enabled else { return }
|
||||
Task { @MainActor in
|
||||
@MainActor func mark(_ event: String) { SamplingDiagnostics.record(metrics.snapshot, event: "audit." + event) }
|
||||
controller.panel.animationBehavior = .none
|
||||
if ProcessInfo.processInfo.environment["KYMO_XPC_AUDIT"] == "1" {
|
||||
await checkRequestCompletion()
|
||||
SamplingDiagnostics.record(metrics.snapshot, event: "audit.xpcChecksPassed")
|
||||
controller.shutdown()
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
@MainActor func mark(_ event: String) {
|
||||
var report = metrics.snapshot
|
||||
report.processes = metrics.processSnapshot
|
||||
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil)
|
||||
}
|
||||
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
|
||||
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
|
||||
controller.presentation.isPinned = true
|
||||
@@ -36,4 +49,43 @@ import AppKit
|
||||
NSApp.terminate(nil)
|
||||
}
|
||||
}
|
||||
/// Uses real connection lifecycle but injects local callbacks; peer auth is tested separately by RPCs.
|
||||
private static func checkRequestCompletion() async {
|
||||
for _ in 0..<20 {
|
||||
let result: Int? = await ServiceRequest.perform(timeout: 0.2) { _, finish in
|
||||
finish(1); finish(2)
|
||||
}
|
||||
precondition(result == 1, "A reply must finish exactly once")
|
||||
}
|
||||
for _ in 0..<20 {
|
||||
let result: Int? = await ServiceRequest.perform(timeout: 0.2) { _, finish in
|
||||
DispatchQueue.concurrentPerform(iterations: 2) { finish($0) }
|
||||
}
|
||||
precondition(result == 0 || result == 1)
|
||||
}
|
||||
let timeoutStart = ContinuousClock.now
|
||||
let timedOut: Int? = await ServiceRequest.perform(timeout: 0.1) { _, _ in }
|
||||
let timeoutElapsed = timeoutStart.duration(to: .now)
|
||||
precondition(timedOut == nil && timeoutElapsed >= .milliseconds(80) && timeoutElapsed < .seconds(2))
|
||||
let cancellationStart = ContinuousClock.now
|
||||
let (started, signal) = AsyncStream<Void>.makeStream()
|
||||
let cancelled = Task<Int?, Never> {
|
||||
await ServiceRequest.perform(timeout: 10) { _, _ in signal.yield(()); signal.finish() }
|
||||
}
|
||||
for await _ in started { break }
|
||||
cancelled.cancel()
|
||||
let cancelledResult = await cancelled.value
|
||||
precondition(cancelledResult == nil && cancellationStart.duration(to: .now) < .seconds(2))
|
||||
let early = Task<Int?, Never> { await ServiceRequest.perform(timeout: 10) { _, _ in } }
|
||||
early.cancel()
|
||||
let earlyResult = await early.value
|
||||
precondition(earlyResult == nil)
|
||||
}
|
||||
|
||||
#else
|
||||
static let enabled = false
|
||||
static let omitted = ""
|
||||
static func run(controller: MenuPanelController, metrics: MetricsStore) {}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
/// An opt-in comparison frontend. Sampling, history, IPC and public-IP policy remain enabled.
|
||||
struct TextMonitoringAuditView: View {
|
||||
let metrics: MetricsStore
|
||||
let appearance: AppearancePreferences
|
||||
@State private var publicAddress: String?
|
||||
var body: some View {
|
||||
TextReportHost(snapshot: metrics.snapshot, processes: metrics.processSnapshot, energy: metrics.energy,
|
||||
historyPoints: metrics.history.samples.count, publicAddress: publicAddress, appearance: appearance.appearance)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicAddress))
|
||||
}
|
||||
}
|
||||
|
||||
private struct TextReportHost: NSViewRepresentable {
|
||||
let snapshot: MetricsSnapshot
|
||||
let processes: ProcessSnapshot?
|
||||
let energy: ProcessEnergySnapshot?
|
||||
let historyPoints: Int
|
||||
let publicAddress: String?
|
||||
let appearance: AppAppearance
|
||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||
func makeNSView(context: Context) -> ReportScrollView {
|
||||
let scroll = ReportScrollView()
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.hasHorizontalScroller = true
|
||||
scroll.autohidesScrollers = false
|
||||
scroll.scrollerStyle = .legacy
|
||||
let table = NSTableView(frame: NSRect(x: 0, y: 0, width: 3200, height: 800))
|
||||
table.headerView = nil
|
||||
table.style = .plain
|
||||
table.rowHeight = 15
|
||||
table.intercellSpacing = .zero
|
||||
table.selectionHighlightStyle = .none
|
||||
table.backgroundColor = .windowBackgroundColor
|
||||
table.columnAutoresizingStyle = .noColumnAutoresizing
|
||||
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("text"))
|
||||
column.width = 3200
|
||||
table.addTableColumn(column)
|
||||
table.delegate = context.coordinator
|
||||
table.dataSource = context.coordinator
|
||||
scroll.documentView = table
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: ReportScrollView, context: Context) {
|
||||
scroll.choice = appearance
|
||||
guard let table = scroll.documentView as? NSTableView else { return }
|
||||
let c = context.coordinator
|
||||
if c.processDate != processes?.date {
|
||||
c.processDate = processes?.date
|
||||
c.rows = ProcessTableProjection.rows(processes?.rows ?? [], query: "", sorting: [ProcessSort(key: .cpu)], order: [])
|
||||
}
|
||||
let heading = Self.resourceText(snapshot) + "\nHistory points retained: \(historyPoints)\nPublic IP: \(publicAddress ?? "--")\n\n" + Self.energyText(energy)
|
||||
+ "\nProcesses: \(processes?.readable ?? 0)/\(processes?.enumerated ?? 0), failed=\(processes?.failed ?? false)\nPID\tCPU %\tRSS bytes\tThreads\tRestricted\tName\tPath"
|
||||
c.lines = heading.components(separatedBy: "\n")
|
||||
let origin = scroll.contentView.bounds.origin
|
||||
let oldCount = table.numberOfRows
|
||||
let newCount = c.lines.count + c.rows.count
|
||||
if newCount != oldCount {
|
||||
table.beginUpdates()
|
||||
if newCount > oldCount { table.insertRows(at: IndexSet(integersIn: oldCount..<newCount), withAnimation: []) }
|
||||
else { table.removeRows(at: IndexSet(integersIn: newCount..<oldCount), withAnimation: []) }
|
||||
table.endUpdates()
|
||||
}
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
if visible.location != NSNotFound, visible.length > 0 {
|
||||
for row in visible.location..<min(newCount, visible.location + visible.length) {
|
||||
if let cell = table.view(atColumn: 0, row: row, makeIfNecessary: false) as? NSTableCellView {
|
||||
c.update(cell, row: row)
|
||||
}
|
||||
}
|
||||
}
|
||||
scroll.contentView.scroll(to: origin)
|
||||
scroll.reflectScrolledClipView(scroll.contentView)
|
||||
SamplingDiagnostics.recordTextPresentation(processes: c.rows.count, cells: c.createdCells)
|
||||
}
|
||||
/// Fixed-height native text rows format only visible records. All sampled rows remain scrollable.
|
||||
final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
|
||||
var processDate: Date?
|
||||
var rows: [ProcessMetrics] = []
|
||||
var lines: [String] = []
|
||||
var createdCells = 0
|
||||
func numberOfRows(in tableView: NSTableView) -> Int { lines.count + rows.count }
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
guard row >= 0, row < lines.count + rows.count else { return nil }
|
||||
let key = NSUserInterfaceItemIdentifier("text.cell")
|
||||
let cell: NSTableCellView
|
||||
if let reused = tableView.makeView(withIdentifier: key, owner: nil) as? NSTableCellView { cell = reused }
|
||||
else {
|
||||
cell = NSTableCellView()
|
||||
cell.identifier = key
|
||||
let field = NSTextField(labelWithString: "")
|
||||
field.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||
field.lineBreakMode = .byClipping
|
||||
field.translatesAutoresizingMaskIntoConstraints = false
|
||||
cell.addSubview(field)
|
||||
cell.textField = field
|
||||
NSLayoutConstraint.activate([
|
||||
field.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 8),
|
||||
field.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -4),
|
||||
field.topAnchor.constraint(equalTo: cell.topAnchor), field.bottomAnchor.constraint(equalTo: cell.bottomAnchor)
|
||||
])
|
||||
createdCells += 1
|
||||
}
|
||||
update(cell, row: row)
|
||||
return cell
|
||||
}
|
||||
func update(_ cell: NSTableCellView, row: Int) {
|
||||
guard row >= 0, row < lines.count + rows.count else { return }
|
||||
let value = row < lines.count ? lines[row] : TextReportHost.processLine(rows[row - lines.count])
|
||||
if cell.textField?.stringValue != value { cell.textField?.stringValue = value }
|
||||
}
|
||||
}
|
||||
final class ReportScrollView: NSScrollView {
|
||||
var choice = AppAppearance.system { didSet { apply() } }
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); apply() }
|
||||
private func apply() {
|
||||
let target = choice.windowAppearance
|
||||
if window?.appearance?.name != target?.name { window?.appearance = target }
|
||||
}
|
||||
}
|
||||
private static func number(_ value: Double?) -> String { value.map { String(format: "%.3f", $0) } ?? "--" }
|
||||
private static func bytes(_ value: UInt64?) -> String { value.map(String.init) ?? "--" }
|
||||
private static func resourceText(_ s: MetricsSnapshot) -> String {
|
||||
var lines = ["Kymo — plain text comparison (no charts, icons or animation)", "Resource timestamp: \(s.date.timeIntervalSince1970)"]
|
||||
lines += ["CPU total/user/system fraction: \(number(s.cpu?.usage)) / \(number(s.cpu?.user)) / \(number(s.cpu?.system))",
|
||||
"CPU cores: \(s.cpu?.cores.map { number($0) }.joined(separator: " ") ?? "--")",
|
||||
"CPU/GPU temperature °C: \(number(s.cpuTemperature)) / \(number(s.gpuTemperature))",
|
||||
"Fans RPM: \(s.fans?.map { "\($0.id)=\(number($0.rpm))" }.joined(separator: " ") ?? "--")",
|
||||
"GPU usage/renderer/tiler/cores: \(number(s.gpu?.usage)) / \(number(s.gpu?.renderer)) / \(number(s.gpu?.tiler)) / \(s.gpu?.coreCount.map(String.init) ?? "--")",
|
||||
"GPU in-use/allocated bytes: \(bytes(s.gpu?.inUseMemory)) / \(bytes(s.gpu?.allocatedMemory))",
|
||||
"Memory total/used/available/cached/wired/compressed/swap bytes: \(bytes(s.memory?.total)) / \(bytes(s.memory?.used)) / \(bytes(s.memory?.available)) / \(bytes(s.memory?.cached)) / \(bytes(s.memory?.wired)) / \(bytes(s.memory?.compressed)) / \(bytes(s.memory?.swapUsed))",
|
||||
"Memory pressure: \(s.memory?.pressure.map(String.init) ?? "--")",
|
||||
"Disk total/available bytes: \(bytes(s.disk?.total)) / \(bytes(s.disk?.available))",
|
||||
"Disk IO read/write B/s: \(number(s.diskIO?.read)) / \(number(s.diskIO?.written))",
|
||||
"SMART remaining/hour: \(number(s.diskHealth?.remainingLife)) / \(bytes(s.diskHealth?.powerOnHours))",
|
||||
"Battery charge/health/power W/cycles: \(number(s.battery?.charge)) / \(number(s.battery?.health)) / \(number(s.battery?.power)) / \(s.battery?.cycles.map(String.init) ?? "--")",
|
||||
"Battery charging/external/minutes/state: \(String(describing: s.battery?.charging)) / \(String(describing: s.battery?.externalPower)) / \(s.battery?.minutesRemaining.map(String.init) ?? "--") / \(s.batteryState)",
|
||||
"Uptime/load: \(number(s.uptime)) / \(s.load.map { number($0) }.joined(separator: " "))",
|
||||
"Network path/default interface: \(String(describing: s.networkPath)) / \(s.defaultNetworkInterface ?? "--")"]
|
||||
for i in s.network ?? [] { lines.append("\(i.name) active=\(i.active) received/sent=\(i.received)/\(i.sent) B, down/up=\(number(i.download))/\(number(i.upload)) B/s, addresses=\(i.addresses.joined(separator: ","))") }
|
||||
for v in s.volumes ?? [] { lines.append("Volume \(v.name) \(v.path): total/available \(v.capacity.total)/\(v.capacity.available) B") }
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
private static func energyText(_ energy: ProcessEnergySnapshot?) -> String {
|
||||
guard let energy else { return "CPU energy: waiting\n" }
|
||||
return "CPU energy: \(energy.state), measured/readable/enumerated=\(energy.measured)/\(energy.readable)/\(energy.candidates)\n" + energy.rows.map { "\($0.id.pid) \($0.process.name): \($0.formattedPower), interval \(number($0.seconds)) s" }.joined(separator: "\n") + "\n"
|
||||
}
|
||||
private static func processLine(_ process: ProcessMetrics) -> String {
|
||||
"\(process.id.pid)\t\(number(process.cpu.map { $0 * 100 }))\t\(bytes(process.residentBytes))\t\(process.threads.map(String.init) ?? "--")\t\(process.restricted)\t\(process.name)\t\(process.path ?? "--")"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#else
|
||||
/// The diagnostic renderer is excluded from distribution builds.
|
||||
struct TextMonitoringAuditView: View {
|
||||
let metrics: MetricsStore
|
||||
let appearance: AppearancePreferences
|
||||
var body: some View { EmptyView() }
|
||||
}
|
||||
#endif
|
||||
Reference in New Issue
Block a user