Files
Kymo/kymo/Features/MenuBar/TextMonitoringAuditView.swift
T

166 lines
10 KiB
Swift

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 %\tFootprint 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.footprintBytes))\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