feat(menubar): 完善首排监控卡片与温度风扇采样

补充 GPU 渲染分块、内存与利用率统计,增加只读 SMC 温度及风扇信息和旋转动效。完善电池功率与耗电进程列表,统一首排布局并固定异步加载区域高度。同步验证用例、架构说明和 GPU 能力调研工具。
This commit is contained in:
2026-11-03 16:42:09 +08:00
parent 45a6e16bb8
commit cc38066de2
43 changed files with 2658 additions and 536 deletions
+5
View File
@@ -20,5 +20,10 @@ nonisolated enum MetricFormat {
return String(format: "%.1f %@", scaled, units[index])
}
static func watts(_ value: Double?) -> String {
guard let value, value.isFinite, value >= 0 else { return "--" }
return String(format: "%.1f W", value)
}
static func decimal(_ value: Double) -> String { String(format: "%.1f", value) }
}
+11
View File
@@ -0,0 +1,11 @@
import Foundation
nonisolated struct FanMetrics: Sendable, Identifiable {
let id: Int
let rpm: Double?
static func validRPM(_ value: Double?) -> Double? {
guard let value, value.isFinite, value >= 0, value <= 30_000 else { return nil }
return value
}
}
+33 -2
View File
@@ -8,11 +8,14 @@ nonisolated struct TrendSample: Sendable {
var download: Double?
var disk: Double?
var battery: Double?
var batteryPower: Double?
var upload: Double?
var read: Double?
var write: Double?
var cpuUser: Double?
var cpuSystem: Double?
var gpuRenderer: Double?
var gpuTiler: Double?
var breakBefore = false
var expectedInterval: TimeInterval = 2
}
@@ -27,9 +30,10 @@ nonisolated struct MetricHistory: Sendable {
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore, expectedInterval: expectedInterval))
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler, breakBefore: breakBefore, expectedInterval: expectedInterval))
let current = snapshot.network ?? []
let keys = Set(current.map(\.identity))
interfaces = interfaces.filter { keys.contains($0.key) }
@@ -47,3 +51,30 @@ nonisolated struct InterfaceTrendSample: Sendable {
let upload: Double?
var expectedInterval: TimeInterval = 2
}
/// Time-weighted observed utilization; never bridge failures or sleep boundaries.
nonisolated struct GPUUtilizationSummary {
let average: Double?
let peak: Double?
let coverage: TimeInterval
init(samples: [TrendSample], window: TimeInterval = 60) {
guard let end = samples.last?.date else { average = nil; peak = nil; coverage = 0; return }
let start = end.addingTimeInterval(-window)
peak = samples.filter { $0.date >= start }.compactMap(\.gpu).max()
var area = 0.0
var duration = 0.0
for (a, b) in zip(samples, samples.dropFirst()) {
let dt = b.date.timeIntervalSince(a.date)
guard !b.breakBefore, dt > 0, dt <= max(a.expectedInterval, b.expectedInterval) * 2.5,
let av = a.gpu, let bv = b.gpu else { continue }
let overlap = b.date.timeIntervalSince(max(a.date, start))
guard overlap > 0 else { continue }
let left = av + (bv - av) * (1 - overlap / dt)
area += (left + bv) * 0.5 * overlap
duration += overlap
}
coverage = duration
average = duration > 0 ? area / duration : nil
}
}
+3
View File
@@ -20,6 +20,9 @@ nonisolated struct MemoryMetrics: Sendable {
nonisolated struct MetricsSnapshot: Sendable {
var date = Date()
var cpu: CPUMetrics?
var cpuTemperature: Double?
var gpuTemperature: Double?
var fans: [FanMetrics]?
var memory: MemoryMetrics?
var network: [NetworkInterfaceMetrics]?
var networkPath: NetworkPathStatus?
+18
View File
@@ -23,3 +23,21 @@ nonisolated struct ProcessSnapshot: Sendable {
let rows: [ProcessMetrics]
let failed: Bool
}
nonisolated extension ProcessSnapshot {
func highestCPUProcesses(limit: Int) -> [ProcessMetrics] {
guard limit > 0 else { return [] }
var result: [ProcessMetrics] = []
for row in rows {
guard let cpu = row.cpu, cpu.isFinite, cpu >= 0 else { continue }
let index = result.firstIndex { ($0.cpu ?? 0) < cpu } ?? result.endIndex
result.insert(row, at: index)
if result.count > limit { result.removeLast() }
}
return result
}
var highestCPUProcess: ProcessMetrics? {
highestCPUProcesses(limit: 1).first
}
}
+25 -1
View File
@@ -5,12 +5,22 @@ nonisolated struct BatteryMetrics: Sendable {
let charge: Double?
let charging: Bool
let externalPower: Bool
var power: Double? = nil
var minutesRemaining: Int?
var cycles: Int?
var health: Double?
}
nonisolated enum BatteryMonitor {
static func normalizedPower(voltageMillivolts: Double?, amperageMilliamps: Double?) -> Double? {
guard let voltageMillivolts, let amperageMilliamps,
voltageMillivolts.isFinite, amperageMilliamps.isFinite,
voltageMillivolts > 0, voltageMillivolts <= 30_000,
abs(amperageMilliamps) <= 20_000 else { return nil }
let watts = abs(voltageMillivolts * amperageMilliamps) / 1_000_000
return watts.isFinite && watts <= 500 ? watts : nil
}
static func positiveMinutes(_ value: Int?) -> Int? {
value.flatMap { $0 > 0 ? $0 : nil }
}
@@ -55,10 +65,24 @@ nonisolated enum BatteryMonitor {
let charging = item[kIOPSIsChargingKey] as? Bool ?? false
let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue
let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int
let batteryData = properties["BatteryData"] as? [String: Any] ?? [:]
let voltage = firstNumber([properties["Voltage"], batteryData["Voltage"], batteryData["AppleRawBatteryVoltage"]])
let amperage = firstNumber([properties["InstantAmperage"], batteryData["InstantAmperage"], properties["Amperage"], batteryData["Amperage"]])
return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false,
externalPower: external, minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
externalPower: external,
power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage),
minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
}
return nil
}
private static func firstNumber(_ values: [Any?]) -> Double? {
for case let value? in values {
if let number = value as? NSNumber, number.doubleValue.isFinite {
return number.doubleValue
}
}
return nil
}
}
@@ -0,0 +1,123 @@
import Foundation
import IOKit
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan keys; never write keys.
nonisolated final class CPUTemperatureMonitor {
static let highTemperatureThreshold = 90.0
private struct Version { var major: UInt8 = 0; var minor: UInt8 = 0; var build: UInt8 = 0; var reserved: UInt8 = 0; var release: UInt16 = 0 }
private struct Limits { var version: UInt16 = 0; var length: UInt16 = 0; var cpu: UInt32 = 0; var gpu: UInt32 = 0; var memory: UInt32 = 0 }
private struct KeyInfo { var size: UInt32 = 0; var type: UInt32 = 0; var attributes: UInt8 = 0; var padding1: UInt8 = 0; var padding2: UInt8 = 0; var padding3: UInt8 = 0 }
private struct Request {
var key: UInt32 = 0; var version = Version(); var limits = Limits(); var info = KeyInfo()
var result: UInt8 = 0; var status: UInt8 = 0; var command: UInt8 = 0; var index: UInt32 = 0
var bytes: (UInt64, UInt64, UInt64, UInt64) = (0, 0, 0, 0)
}
static var hasExpectedLayout: Bool {
MemoryLayout<Request>.stride == 80 && MemoryLayout<Request>.offset(of: \Request.info) == 28 &&
MemoryLayout<Request>.offset(of: \Request.command) == 42 && MemoryLayout<Request>.offset(of: \Request.index) == 44 &&
MemoryLayout<Request>.offset(of: \Request.bytes) == 48
}
static func isHighTemperature(_ value: Double?) -> Bool {
guard let value else { return false }
return value >= highTemperatureThreshold
}
enum Zone { case cpu, gpu }
private let zone: Zone
init(zone: Zone = .cpu) { self.zone = zone }
private var connection: io_connect_t = 0
private var keys: [(UInt32, UInt32)] = []
private var attempted = false
deinit { if connection != 0 { IOServiceClose(connection) } }
private func call(_ request: inout Request) -> Request? {
var response = Request()
var size = MemoryLayout<Request>.stride
let result = IOConnectCallStructMethod(connection, 2, &request, MemoryLayout<Request>.stride, &response, &size)
guard result == KERN_SUCCESS, size == MemoryLayout<Request>.stride, response.result == 0 else { return nil }
return response
}
private func openConnection() -> Bool {
if connection != 0 { return true }
guard Self.hasExpectedLayout else { return false }
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"))
guard service != 0 else { return false }
defer { IOObjectRelease(service) }
guard IOServiceOpen(service, mach_task_self_, 0, &connection) == KERN_SUCCESS else { connection = 0; return false }
return true
}
private func discover() {
attempted = true
guard openConnection() else { return }
var countRequest = Request(); countRequest.key = 0x234b4559; countRequest.info.size = 4; countRequest.command = 5
guard let countResponse = call(&countRequest) else { return }
let count = withUnsafeBytes(of: countResponse.bytes) { UInt32($0[0]) << 24 | UInt32($0[1]) << 16 | UInt32($0[2]) << 8 | UInt32($0[3]) }
guard count <= 10000 else { return }
for index in 0..<count {
var request = Request(); request.command = 8; request.index = index
guard let response = call(&request) else { continue }
let prefix = response.key >> 16
guard zone == .gpu ? prefix == 0x5467 : (prefix == 0x5470 || prefix == 0x5465) else { continue }
var info = Request(); info.key = response.key; info.command = 9
guard let metadata = call(&info), metadata.info.type == 0x666c7420, metadata.info.size == 4 else { continue }
keys.append((response.key, metadata.info.size))
}
if keys.isEmpty {
IOServiceClose(connection)
connection = 0
attempted = false
}
}
/// Highest valid selected temperature-zone sensor reading in Celsius, not an official package temperature.
func sample() -> Double? {
if !attempted { discover() }
guard connection != 0 else { return nil }
var highest: Double?
for (key, size) in keys {
var request = Request(); request.key = key; request.info.size = size; request.command = 5
guard let response = call(&request) else { continue }
let bits = withUnsafeBytes(of: response.bytes) { UInt32($0[0]) | UInt32($0[1]) << 8 | UInt32($0[2]) << 16 | UInt32($0[3]) << 24 }
let value = Double(Float(bitPattern: bits))
guard value.isFinite, value > 0, value < 150 else { continue }
highest = max(highest ?? value, value)
}
return highest
}
/// Fixed read-only fan keys. nil means unavailable; [] means a fanless device.
func sampleFans() -> [Double?]? {
guard openConnection(), let count = readNumber(0x464e756d),
count.isFinite, count >= 0, count <= 10, count.rounded() == count else { return nil }
return (0..<Int(count)).map { index in
let key = UInt32(0x46304163) + (UInt32(index) << 16) // F0Ac ... F9Ac
guard let rpm = readNumber(key), rpm.isFinite, rpm >= 0, rpm <= 30_000 else { return nil }
return rpm
}
}
private func readNumber(_ key: UInt32) -> Double? {
var request = Request(); request.key = key; request.command = 9
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
request.command = 5; request.info.size = metadata.info.size
guard let response = call(&request) else { return nil }
let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) }
return Self.decodeSensorNumber(type: metadata.info.type, bytes: bytes)
}
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
switch (type, bytes.count) {
case (0x666c7420, 4): // flt, little-endian IEEE754
let bits = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
let value = Double(Float(bitPattern: bits))
return value.isFinite ? value : nil
case (0x66706532, 2): // fpe2, big-endian unsigned 14.2 fixed point
return Double(UInt16(bytes[0]) << 8 | UInt16(bytes[1])) / 4
case (0x75693820, 1): return Double(bytes[0]) // ui8
default: return nil
}
}
}
+17 -1
View File
@@ -4,6 +4,11 @@ import IOKit
nonisolated struct GPUMetrics: Sendable {
let usage: Double?
let coreCount: Int?
var renderer: Double? = nil
var tiler: Double? = nil
// Driver accounting, not dedicated VRAM or a capacity denominator.
var inUseMemory: UInt64? = nil
var allocatedMemory: UInt64? = nil
// Independent per-core counters have not been obtained. Never split total usage.
}
@@ -20,12 +25,23 @@ nonisolated enum GPUMonitor {
let stats = IORegistryEntryCreateCFProperty(service, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [String: Any]
let raw = (stats?["Device Utilization %"] as? NSNumber)?.doubleValue
let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil }))
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil },
renderer: normalized((stats?["Renderer Utilization %"] as? NSNumber)?.doubleValue),
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue),
inUseMemory: memoryBytes(stats?["In use system memory"]),
allocatedMemory: memoryBytes(stats?["Alloc system memory"])))
}
// Do not average incompatible utilization counters on multi-GPU machines.
return devices.count == 1 ? devices[0] : nil
}
static func memoryBytes(_ raw: Any?) -> UInt64? {
guard let number = raw as? NSNumber else { return nil }
let value = number.doubleValue
guard value.isFinite, value >= 0, value < Double(UInt64.max) else { return nil }
return UInt64(value)
}
static func normalized(_ value: Double?) -> Double? {
value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil }
}
+24
View File
@@ -4,6 +4,11 @@ import Darwin
/// One coordinator owns baselines; slow workers have at most one in-flight call each.
actor SystemSampler {
private var cpu = CPUMonitor()
private var temperatureTask: Task<Void, Never>?
private var temperatureCache: Double?
private var gpuTemperatureCache: Double?
private var fanCache: [FanMetrics]?
private var nextTemperature: TimeInterval = 0
private var didProbe = false
private let diskHealth = DiskHealthMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
@@ -56,6 +61,17 @@ actor SystemSampler {
let start = ProcessInfo.processInfo.systemUptime
var result = MetricsSnapshot()
result.cpu = cpu.sample()
if temperatureTask == nil && start >= nextTemperature {
temperatureTask = Task { [self] in
async let cpu = CPUTemperatureServiceClient.read()
async let gpu = CPUTemperatureServiceClient.read(gpu: true)
async let fans = CPUTemperatureServiceClient.readFans()
await finishTemperature(cpu, gpu: gpu, fans: fans)
}
}
result.cpuTemperature = temperatureCache
result.gpuTemperature = gpuTemperatureCache
result.fans = fanCache
result.memory = MemoryMonitor.sample()
result.network = network.sample()
result.networkPath = networkPath.snapshot()
@@ -95,6 +111,14 @@ actor SystemSampler {
return result
}
private func finishTemperature(_ value: Double?, gpu: Double?, fans: [FanMetrics]?) {
fanCache = fans
gpuTemperatureCache = gpu
temperatureCache = value
nextTemperature = ProcessInfo.processInfo.systemUptime + (value == nil && gpu == nil && fans == nil ? 60 : 5)
temperatureTask = nil
}
private func finishVolumes(_ value: [VolumeMetrics]?) {
volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil
}
@@ -0,0 +1,73 @@
import Foundation
nonisolated enum CPUTemperatureServiceClient {
static func read(gpu: Bool = false) async -> Double? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil)
return
}
let receive: (NSNumber?) -> Void = { number in
let value = number?.doubleValue
reply.finish(value.flatMap { $0.isFinite && $0 > 0 && $0 < 150 ? $0 : nil })
}
if gpu { proxy.readGPUTemperature(withReply: receive) }
else { proxy.readCPUTemperature(withReply: receive) }
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
}
}
static func readFans() async -> [FanMetrics]? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil); return
}
proxy.readFanSpeeds { values in
guard let values, values.count <= 10 else { reply.finish(nil); return }
reply.finish(values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) })
}
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
}
}
private final class Reply<Value: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<Value?, Never>?
private let connection: NSXPCConnection
init(connection: NSXPCConnection, continuation: CheckedContinuation<Value?, Never>) {
self.connection = connection
self.continuation = continuation
}
func finish(_ value: Value?) {
lock.lock()
let callback = continuation
continuation = nil
lock.unlock()
guard let callback else { return }
connection.invalidationHandler = nil
connection.interruptionHandler = nil
connection.invalidate()
callback.resume(returning: value)
}
}
}
@@ -2,5 +2,8 @@ import Foundation
/// Fixed read-only operation: no caller-supplied paths or commands.
@objc protocol SMARTServiceProtocol {
nonisolated func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void)
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
nonisolated func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
}
@@ -14,6 +14,7 @@ nonisolated enum SamplingDiagnostics {
]
payload["cpu"] = snapshot.cpu?.usage
payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature
payload["gpuUsage"] = snapshot.gpuUsage
payload["gpuCoreCount"] = snapshot.gpu?.coreCount
payload["processEnumerated"] = snapshot.processes?.enumerated
@@ -32,6 +33,7 @@ nonisolated enum SamplingDiagnostics {
payload["volumeCount"] = snapshot.volumes?.count
payload["batteryCycles"] = snapshot.battery?.cycles
payload["batteryHealth"] = snapshot.battery?.health
payload["batteryPower"] = snapshot.battery?.power
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
let status = withUnsafeMutablePointer(to: &info) { pointer in
+80 -24
View File
@@ -27,42 +27,98 @@ struct CPUCoreGrid: View {
}
}
static func groups(count: Int, kinds: [Int: CPUCoreTopology.Kind]) -> [[Int]] {
let order: [CPUCoreTopology.Kind?] = [.efficiency, .middle, .performance, nil]
return order.map { kind in (0..<max(0, count)).filter { kinds[$0] == kind } }.filter { !$0.isEmpty }
}
static func groupWidths(groups: [[Int]], width: CGFloat) -> [CGFloat] {
let weights = groups.map { CGFloat(($0.count + 1) / 2) }
let total = max(1, weights.reduce(0, +))
let available = max(0, width - CGFloat(max(0, groups.count - 1)) * 13)
return weights.map { available * $0 / total }
}
var body: some View {
CPUCoreGridLayout {
ForEach(Array(values.enumerated()), id: \.offset) { index, value in
let kind = kinds[index]
GeometryReader { proxy in
let numberWidth = min(max(12, CGFloat(String(values.count).count) * 6), max(0, proxy.size.width * 0.45))
let spacing = min(3, proxy.size.width * 0.08)
ZStack(alignment: .leading) {
Text(verbatim: "\(index + 1)").font(.system(size: 9))
.lineLimit(1).minimumScaleFactor(0.3).frame(width: numberWidth)
MetricProgressBar(value: value, color: color(kind))
.frame(width: max(0, proxy.size.width - numberWidth - spacing), height: 7)
.offset(x: numberWidth + spacing)
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value)
}.frame(width: proxy.size.width, height: proxy.size.height, alignment: .leading)
}.clipped()
.help((kind.map { label($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))"))
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
let groups = Self.groups(count: values.count, kinds: kinds)
GeometryReader { geometry in
let widths = Self.groupWidths(groups: groups, width: geometry.size.width)
let diameter = zip(groups, widths).map { indices, width in
let columns = CPUCoreGridLayout.rowCounts(count: indices.count, width: width).max() ?? 1
let spacing = min(CPUCoreGridLayout.columnSpacing, max(0, (width / CGFloat(columns) - 18) / 2))
return max(0, (width - CGFloat(columns - 1) * spacing) / CGFloat(columns) - 4)
}.min() ?? 20
HStack(alignment: .top, spacing: 6) {
ForEach(groups.indices, id: \.self) { group in
if group > 0 {
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1)
}
VStack(alignment: .leading, spacing: 5) {
HStack(spacing: 3) {
Circle().fill(color(kinds[groups[group][0]])).frame(width: 5, height: 5)
if let kind = kinds[groups[group][0]] { label(kind) }
else { Text("cpu.core") }
Text(verbatim: "\(groups[group].count)").foregroundStyle(.secondary)
}
.font(.system(size: 9, weight: .medium))
.lineLimit(1).minimumScaleFactor(0.6)
CPUCoreGridLayout {
ForEach(groups[group], id: \.self) { index in
ring(index: index, maximumDiameter: min(20, diameter))
}
}
}.frame(width: widths[group], alignment: .topLeading)
}
}
}.padding(.vertical, 3)
}
.frame(height: 15 + CGFloat(maxRows(groups: groups)) * 22 + CGFloat(max(0, maxRows(groups: groups) - 1)) * 4)
.padding(.vertical, 4)
}
// Match the content width so row reservation agrees with placement.
var availableWidth: CGFloat = 380
private func maxRows(groups: [[Int]]) -> Int {
let widths = Self.groupWidths(groups: groups, width: availableWidth)
return zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
}
private func ring(index: Int, maximumDiameter: CGFloat) -> some View {
let kind = kinds[index]
let value = values[index].isFinite ? min(1, max(0, values[index])) : 0
return GeometryReader { proxy in
let diameter = min(maximumDiameter, max(0, proxy.size.width - 4))
ZStack {
Circle().inset(by: 1).stroke(color(kind).opacity(0.16), lineWidth: 2)
Circle().inset(by: 1).trim(from: 0, to: value)
.stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round))
.rotationEffect(.degrees(-90))
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value)
Text(verbatim: "\(Int((value * 100).rounded()))")
.font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4)
}
.frame(width: diameter, height: diameter)
.frame(width: proxy.size.width, height: proxy.size.height)
}
.help((kind.map { label($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))"))
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
}
}
struct CPUCoreGridLayout: Layout {
static let columnSpacing: CGFloat = 6
static let rowSpacing: CGFloat = 5
static let rowHeight: CGFloat = 12
static let preferredCellWidth: CGFloat = 38
static let rowSpacing: CGFloat = 4
static let rowHeight: CGFloat = 22
static let minimumTwoRowCellWidth: CGFloat = 16
static func rowCounts(count: Int, width: CGFloat) -> [Int] {
guard count > 0 else { return [] }
guard count > 1 else { return [1] }
let twoColumns = (count + 1) / 2
let widthForTwoRows = CGFloat(twoColumns) * preferredCellWidth + CGFloat(twoColumns - 1) * columnSpacing
let rows = count > 2 && width < widthForTwoRows ? 3 : 2
let availableForCells = width - CGFloat(twoColumns - 1) * columnSpacing
let twoRowCellWidth = availableForCells / CGFloat(twoColumns)
let rows = count > 2 && twoRowCellWidth < minimumTwoRowCellWidth ? 3 : 2
let quotient = count / rows, remainder = count % rows
return (0..<rows).map { quotient + ($0 < remainder ? 1 : 0) }
}
@@ -0,0 +1,41 @@
import SwiftUI
/// Memory bars share a byte scale, not a used/allocated capacity ratio.
struct GPUStatisticsView: View {
let inUse: UInt64?
let allocated: UInt64?
let average: Double?
let peak: Double?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var reference: Double { max(1, Double(max(inUse ?? 0, allocated ?? 0))) }
var body: some View {
HStack(spacing: 10) {
VStack(spacing: 5) {
memoryRow("gpu.driverMemory", bytes: inUse, color: Color("MetricMemory"))
memoryRow("gpu.allocatedMemory", bytes: allocated, color: Color("MetricNetwork"))
}.frame(maxWidth: .infinity).help(Text("gpu.memoryComparisonHelp"))
Divider()
HStack(spacing: 6) {
MetricRingGauge(title: "gpu.recentAverage", value: average, color: Color("MetricCPU"))
MetricRingGauge(title: "gpu.peak", value: peak, color: Color("MetricGPU"))
}.frame(maxWidth: .infinity).help(Text("gpu.summaryHelp"))
}.frame(height: 42)
}
private func memoryRow(_ title: LocalizedStringKey, bytes: UInt64?, color: Color) -> some View {
VStack(spacing: 3) {
HStack(spacing: 4) {
Text(title).foregroundStyle(.secondary)
Spacer(minLength: 0)
AnimatedMetricText(value: MetricFormat.bytes(bytes)).fontWeight(.medium)
}.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.7)
MetricProgressBar(value: bytes.map { Double($0) / reference } ?? 0, color: color)
.frame(height: 3)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: bytes)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: reference)
.accessibilityHidden(true)
}
}
}
+210 -55
View File
@@ -8,6 +8,7 @@ struct MenuPanelView: View {
let settingsPresentation: SettingsPresentation
var presentation = PanelPresentation()
var onOpenSettings: () -> Void = {}
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760))
@State private var selectedInterface = ""
@State private var showAddresses = false
@@ -19,6 +20,14 @@ struct MenuPanelView: View {
private var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 }
private var chartBoundaries: Set<Date> { Set(samples.filter(\.breakBefore).map(\.date)) }
private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 }
private var firstRowHeight: CGFloat {
let cardWidth = (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns)
let groups = CPUCoreGrid.groups(count: snapshot.cpu?.cores.count ?? 0, kinds: CPUCoreTopology.cores)
let widths = CPUCoreGrid.groupWidths(groups: groups, width: max(0, cardWidth - 20))
let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
let extraFanRows = max(0, ((snapshot.fans?.count ?? 0) + 1) / 2 - 1)
return max(260 + (coreRows >= 3 ? 26 : 0), 260 + CGFloat(extraFanRows) * 19)
}
private var network: [NetworkInterfaceMetrics] {
(snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface }
}
@@ -36,9 +45,9 @@ struct MenuPanelView: View {
} else {
ScrollView {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: columns), spacing: 8) {
cpuCard.frame(minHeight: 240)
gpuCard.frame(minHeight: 240)
batteryCard.aspectRatio(4.0 / 3.0, contentMode: .fit)
cpuCard.frame(height: firstRowHeight)
gpuCard.frame(height: firstRowHeight)
batteryCard.frame(height: firstRowHeight)
memoryCard.frame(minHeight: 240)
diskCard.frame(minHeight: 250)
networkCard.frame(minHeight: 250)
@@ -68,10 +77,10 @@ struct MenuPanelView: View {
private var resourceRows: some View {
VStack(spacing: 8) {
HStack(alignment: .top, spacing: 8) {
cpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize))
gpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize))
batteryCard.frame(width: PanelLayout.batteryWidth(size: panelSize))
}.frame(height: PanelLayout.resourceRowHeight(size: panelSize))
cpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight)
gpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight)
batteryCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight)
}.frame(height: firstRowHeight)
HStack(alignment: .top, spacing: 8) {
memoryCard.frame(width: (panelSize.width - 36) / 3)
diskCard.frame(width: (panelSize.width - 36) / 3)
@@ -83,10 +92,18 @@ struct MenuPanelView: View {
private var header: some View {
HStack(spacing: 10) {
Image("BrandMark").renderingMode(.template)
Text("Kymo").font(.system(size: 18, weight: .semibold))
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")")
.font(.system(size: 10)).foregroundStyle(.secondary)
HStack(alignment: .firstTextBaseline, spacing: 2) {
Text("Kymo").font(.system(size: 18, weight: .semibold))
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")")
.font(.system(size: 8, weight: .medium))
.foregroundStyle(.secondary)
.baselineOffset(7)
}
if panelSize.width >= 900 {
Rectangle()
.fill(.secondary.opacity(0.32))
.frame(width: 1, height: 16)
.accessibilityHidden(true)
Text(verbatim: HardwareIdentity.displayName)
.font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
}
@@ -122,58 +139,97 @@ struct MenuPanelView: View {
}
}
private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
}
private var cpuCard: some View {
ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) {
let temperature = snapshot.cpuTemperature
let highTemperature = CPUTemperatureMonitor.isHighTemperature(temperature)
return ResourceCard(
title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"),
value: MetricFormat.percent(snapshot.cpu?.usage),
status: temperature.map { "\(Int($0.rounded()))°C" },
statusWarning: highTemperature,
statusHelp: temperature == nil ? nil : Text("cpu.temperature.help", tableName: "CPUDetails"),
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil
) {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
if let cpu = snapshot.cpu {
HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) }
let kinds = [CPUCoreTopology.Kind.efficiency, .middle, .performance].filter { CPUCoreTopology.cores.values.contains($0) }
if !kinds.isEmpty {
HStack(spacing: 10) {
ForEach(kinds, id: \.rawValue) { kind in
HStack(spacing: 3) { Circle().fill(coreColor(kind)).frame(width: 6, height: 6); coreLabel(kind) }
}
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
}
CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval)
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
Spacer(minLength: 0)
CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval,
availableWidth: max(0, (columns == 3 ? PanelLayout.cardWidth(size: panelSize) : (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns)) - 20))
} else { Text("metric.waiting").foregroundStyle(.secondary) }
Spacer(minLength: 0)
HStack(spacing: 5) {
HStack(spacing: 5) {
Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary)
if let load = snapshot.load.first, load.isFinite, load >= 0, let count = snapshot.cpu?.cores.count, count > 0 {
MetricProgressBar(value: load / Double(count), color: Color("MetricCPU"))
.frame(minWidth: 20, maxWidth: .infinity).frame(height: 7)
.accessibilityHidden(true)
AnimatedMetricText(value: "\(MetricFormat.decimal(load)) / \(count)")
} else {
Spacer(minLength: 20)
Text(verbatim: "--")
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary)
Spacer(minLength: 3)
AnimatedMetricText(value: snapshot.load.first.map { "\(MetricFormat.decimal($0)) / \(snapshot.cpu?.cores.count ?? 0)" } ?? "--")
}
MetricProgressBar(value: (snapshot.load.first ?? 0) / Double(max(1, snapshot.cpu?.cores.count ?? 0)), color: Color("MetricCPU"))
.frame(height: 5).accessibilityHidden(true)
}.frame(maxWidth: .infinity).help(Text("cpu.load.help", tableName: "CPUDetails"))
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 25)
VStack(alignment: .leading, spacing: 3) {
Text("panel.uptime").foregroundStyle(.secondary)
AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
.fontWeight(.medium)
}
.help(Text("cpu.load.help", tableName: "CPUDetails"))
Spacer(minLength: 8)
Text("panel.uptime").foregroundStyle(.secondary)
AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
}
.lineLimit(1).minimumScaleFactor(0.7)
}.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7)
}
}
private var gpuCard: some View {
ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage)) {
chart(\.gpu, color: Color("MetricGPU"))
let summary = GPUUtilizationSummary(samples: samples)
return ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" },
statusHelp: Text("gpu.temperatureHelp"),
detail: snapshot.gpu?.coreCount.map { String(format: String(localized: "gpu.coreCountFormat"), $0) }) {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
if snapshot.gpuUsage == nil { Text("gpu.unavailable").foregroundStyle(.secondary) }
line("panel.gpuCores", snapshot.gpu?.coreCount.map(String.init) ?? "--")
Label("panel.gpuPerCore", systemImage: "info.circle").foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
gpuActivity("gpu.rendererActivity", value: snapshot.gpu?.renderer, color: Color("MetricCPU"))
gpuActivity("gpu.tilerActivity", value: snapshot.gpu?.tiler, color: Color("SeriesSystem"))
Divider().padding(.vertical, 3)
Spacer(minLength: 0)
Text("panel.gpuSource").font(.system(size: 9)).foregroundStyle(.secondary)
GPUStatisticsView(inUse: snapshot.gpu?.inUseMemory, allocated: snapshot.gpu?.allocatedMemory,
average: summary.average, peak: summary.peak)
Spacer(minLength: 0)
if let fans = snapshot.fans, !fans.isEmpty {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) {
ForEach(fans) { fan in
FanSpeedIndicator(title: fans.count == 2 ? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight") : LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm)
}
}
.padding(.horizontal, 7).padding(.vertical, 5)
.background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6))
}
}
}
private func gpuActivity(_ title: LocalizedStringKey, value: Double?, color: Color) -> some View {
HStack(spacing: 8) {
Text(title).frame(width: 65, alignment: .leading)
MetricProgressBar(value: value ?? 0, color: color).frame(height: 5)
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value)
AnimatedMetricText(value: MetricFormat.percent(value)).frame(width: 30, alignment: .trailing)
}.font(.system(size: 10)).help(Text("gpu.pipelineHelp"))
}
private var memoryCard: some View {
ResourceCard(title: "metric.memory", symbol: "memorychip", color: Color("MetricMemory"), value: snapshot.memory.map { String(format: "%.1f / %.1f GB", Double($0.used) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") {
PanelTrendChart(dates: samples.map(\.date),
@@ -294,17 +350,68 @@ struct MenuPanelView: View {
private var batteryCard: some View {
ResourceCard(title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), value: MetricFormat.percent(snapshot.battery?.charge)) {
if let battery = snapshot.battery {
chart(\.battery, color: Color("MetricBattery"), label: "metric.battery")
Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging")
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
line("battery.health", MetricFormat.percent(battery.health))
HStack {
Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary)
Spacer()
if battery.externalPower && !battery.charging { Text("battery.timeNotApplicable") }
else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") }
else { Text("battery.timeUnknown") }
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map(\.battery),
second: samples.map(\.batteryPower),
color: Color("MetricBattery"),
secondColor: Color("SeriesUser"),
fixedScale: 1,
secondSeriesUsesAutonomousScale: true,
secondValueFormat: .watts,
firstLabel: "metric.battery",
secondLabel: batteryPowerLabel(battery),
expectedInterval: chartInterval,
boundaryDates: chartBoundaries,
intervals: chartIntervals
)
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
HStack(alignment: .top, spacing: 10) {
VStack(spacing: 5) {
line("battery.health", MetricFormat.percent(battery.health))
HStack {
Text("battery.powerSource").foregroundStyle(.secondary)
Spacer(minLength: 4)
Text(battery.externalPower ? "battery.acPower" : "battery.batterySource")
}
}
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 32)
VStack(spacing: 5) {
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
HStack {
Text("battery.timeEstimate").foregroundStyle(.secondary)
Spacer(minLength: 4)
if battery.externalPower { Text("battery.timeNotApplicable") }
else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") }
else { Text("battery.timeUnknown") }
}
}
}
.font(.system(size: 10))
.lineLimit(1).minimumScaleFactor(0.72)
.frame(height: 32)
Spacer(minLength: 0)
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3)
VStack(alignment: .leading, spacing: 4) {
HStack {
Text("battery.highestEnergyProcess").fontWeight(.semibold)
Spacer()
Text("battery.cpuUsage").foregroundStyle(.secondary)
}
.font(.system(size: 10))
let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? []
if energyProcesses.isEmpty {
Text("metric.waiting").foregroundStyle(.secondary)
} else {
ForEach(energyProcesses) { process in
EnergyProcessListRow(process: process)
}
}
}
// Reserve the header and all three rows before process sampling completes.
.frame(height: 72, alignment: .top)
.lineLimit(1)
.help(Text("battery.energyProxyHelp"))
} else {
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
@@ -356,13 +463,61 @@ struct MenuPanelView: View {
}
.buttonStyle(PanelControlButtonStyle())
.padding(4)
.background(Color("PanelCard"), in: .capsule)
.glassEffect(.regular, in: .capsule)
}
.controlSize(.small)
.padding(.horizontal, 2).padding(.vertical, 0)
}
}
private struct EnergyProcessListRow: View {
let process: ProcessMetrics
@State private var icon: NSImage?
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) {
Group {
if let icon {
Image(nsImage: icon).resizable().interpolation(.high)
} else {
Image(systemName: "app.dashed").resizable().scaledToFit().padding(2)
}
}
.frame(width: 15, height: 15)
.accessibilityHidden(true)
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)
.animation(.easeInOut(duration: 0.35), value: process.cpu)
AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--")
.foregroundStyle(Color("MetricCPU"))
.monospacedDigit().frame(width: 39, alignment: .trailing)
}
.font(.system(size: 10))
.frame(height: 16)
.task(id: process.id) {
icon = NSRunningApplication(processIdentifier: process.id.pid)?.icon
if icon == nil, let path = process.path {
icon = NSWorkspace.shared.icon(forFile: path)
}
}
}
}
private struct PanelControlButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
+6 -3
View File
@@ -2,9 +2,12 @@ import Foundation
import CoreGraphics
nonisolated enum PanelLayout {
static func resourceRowHeight(size: CGSize) -> CGFloat { min(230, max(220, size.height - 590)) }
static func batteryWidth(size: CGSize) -> CGFloat { resourceRowHeight(size: size) * 4 / 3 }
static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - batteryWidth(size: size)) / 2 }
static func resourceRowHeight(size: CGSize, coreRows: Int) -> CGFloat {
let compact = min(239, max(224, size.height - 581))
let thirdRowExpansion: CGFloat = coreRows >= 3 ? 26 : 0
return min(265, compact + thirdRowExpansion)
}
static func cardWidth(size: CGSize) -> CGFloat { max(0, (size.width - 36) / 3) }
static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize {
CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))),
+46
View File
@@ -115,6 +115,52 @@
}
}
}
},
"cpu.temperature.help": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Highest valid CPU cluster sensor reading; warning at 90°C."
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "CPU 核心区域的最高有效传感器读数;达到 90°C 时提示。"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "CPU 核心區域的最高有效感測器讀數;達到 90°C 時提示。"
}
}
}
},
"cpu.temperature.high": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "High temperature"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "温度过高"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "溫度過高"
}
}
}
}
},
"version": "1.0"
File diff suppressed because it is too large Load Diff
+66 -17
View File
@@ -1,5 +1,12 @@
import SwiftUI
enum TrendValueFormat {
case percent
case rate
case bytes
case watts
}
/// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append.
struct PanelTrendChart: View {
let dates: [Date]
@@ -11,15 +18,20 @@ struct PanelTrendChart: View {
var thirdColor: Color = .purple
var fixedScale: Double? = 1
var scaleLabel: String?
var secondSeriesUsesAutonomousScale = false
var secondValueFormat: TrendValueFormat?
var firstLabel: LocalizedStringKey = "panel.total"
var secondLabel: LocalizedStringKey = "network.upload"
var thirdLabel: LocalizedStringKey = "cpu.system"
var expectedInterval: TimeInterval = 2
var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = []
var plotHeight: CGFloat = 58
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@State private var smallSecondSamples = 0
@State private var hoveredDate: Date?
@State private var hoverPoint: CGPoint?
@State private var previousBegin: Date?
@@ -34,39 +46,50 @@ struct PanelTrendChart: View {
boundaryDates: boundaryDates)
}
private var maximum: Double { max(1, (first + second + third).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
private var secondaryScale: Double { max(0.0001, retainedSecondScale) }
private var hasSecondaryScale: Bool { secondSeriesUsesAutonomousScale && !second.isEmpty }
private var automaticFormat: TrendValueFormat {
if fixedScale == 1 { return .percent }
if fixedScale == nil { return .rate }
return .bytes
}
private var index: Int? {
guard !dates.isEmpty else { return nil }
guard let hoveredDate else { return dates.count - 1 }
return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) }
}
private func formatted(_ value: Double?) -> String {
private func formatted(_ value: Double?, format: TrendValueFormat? = nil) -> String {
guard let value, value.isFinite else { return "--" }
if fixedScale == 1 { return MetricFormat.percent(value) }
if fixedScale == nil { return MetricFormat.rate(value) }
return MetricFormat.bytes(UInt64(max(0, value)))
switch format ?? automaticFormat {
case .percent: return MetricFormat.percent(value)
case .rate: return MetricFormat.rate(value)
case .bytes: return MetricFormat.bytes(UInt64(max(0, value)))
case .watts: return MetricFormat.watts(value)
}
}
private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color) -> some View {
private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil) -> some View {
HStack(spacing: 3) {
RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7)
Text(label)
Text(verbatim: formatted(values.last ?? nil)).monospacedDigit()
Text(verbatim: formatted(values.last ?? nil, format: format)).monospacedDigit()
}.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8)
}
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View {
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, index: Int) -> some View {
HStack(spacing: 6) {
RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8)
Text(label)
Spacer(minLength: 4)
Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit()
Text(verbatim: formatted(index < values.count ? values[index] : nil, format: format)).monospacedDigit()
}
}
private func tooltip(index: Int) -> some View {
VStack(alignment: .leading, spacing: 5) {
Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary)
tooltipRow(firstLabel, values: first, tint: color, index: index)
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) }
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, format: secondValueFormat, index: index) }
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
}
.font(.system(size: 10)).padding(8)
@@ -79,7 +102,7 @@ struct PanelTrendChart: View {
VStack(spacing: 3) {
HStack(spacing: 10) {
legend(firstLabel, values: first, tint: color)
if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor) }
if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor, format: secondValueFormat) }
if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) }
Spacer(minLength: 0)
}.frame(height: 14)
@@ -91,11 +114,12 @@ struct PanelTrendChart: View {
Spacer(minLength: 0)
Text(verbatim: "0")
}.font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: 58)
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight)
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor],
scale: scale, maximumGap: max(5, expectedInterval * 2),
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale],
maximumGap: max(5, expectedInterval * 2),
targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last,
previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
@@ -106,8 +130,9 @@ struct PanelTrendChart: View {
ForEach(0..<3, id: \.self) { series in
let values = [first, second, third][series]
if index < values.count, let value = values[index], value.isFinite {
let seriesScale = [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale][series]
Circle().fill([color, secondColor, thirdColor][series]).frame(width: 5, height: 5)
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / scale))))
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / seriesScale))))
}
}
}
@@ -124,11 +149,21 @@ struct PanelTrendChart: View {
}
}
.clipped()
}.frame(height: 58)
}.frame(height: plotHeight)
.anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in
guard let hoverPoint, let index else { return nil }
return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index)))
}
if hasSecondaryScale {
VStack(alignment: .leading) {
Text(verbatim: formatted(secondaryScale, format: .watts))
Spacer(minLength: 0)
Text(verbatim: formatted(secondaryScale / 2, format: .watts))
Spacer(minLength: 0)
Text(verbatim: "0 W")
}.font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 45, height: plotHeight)
}
}
HStack {
if let date = dates.first { Text(date, style: .time) }
@@ -137,7 +172,12 @@ struct PanelTrendChart: View {
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12)
}
.frame(maxWidth: .infinity)
.onAppear { retainedScale = maximum; lastFrame = inputFrame; displayedFrame = inputFrame }
.onAppear {
retainedScale = maximum
retainedSecondScale = secondMaximum
lastFrame = inputFrame
displayedFrame = inputFrame
}
.onChange(of: dates) { _, _ in
let target = maximum
if target > retainedScale { retainedScale = target; smallSamples = 0 }
@@ -145,6 +185,12 @@ struct PanelTrendChart: View {
smallSamples += 1
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
} else { smallSamples = 0 }
let secondTarget = secondMaximum
if secondTarget > retainedSecondScale { retainedSecondScale = secondTarget; smallSecondSamples = 0 }
else if secondTarget < retainedSecondScale * 0.5 {
smallSecondSamples += 1
if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 }
} else { smallSecondSamples = 0 }
let next = inputFrame
let old = lastFrame
let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2))
@@ -174,7 +220,7 @@ struct PanelTrendChart: View {
private struct PanelCurveCanvas: View, Animatable {
let frame: PanelCurveFrame
let colors: [Color]
let scale: Double
let scales: [Double]
let maximumGap: TimeInterval
let targetBegin: Date?
let targetEnd: Date?
@@ -201,7 +247,10 @@ private struct PanelCurveCanvas: View, Animatable {
guard let first = targetBegin, let last = targetEnd else { return }
let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd,
begin: first, end: last, progress: Double(progress))
for (values, tint) in zip(frame.series, colors) {
for seriesIndex in frame.series.indices {
let values = frame.series[seriesIndex]
let tint = colors[min(seriesIndex, colors.count - 1)]
let scale = scales[min(seriesIndex, scales.count - 1)]
for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) {
let points = run.map { item in
CGPoint(x: size.width * domain.position(item.date),
@@ -0,0 +1,57 @@
import SwiftUI
/// Approximate visual speed tiers; rotation does not attempt to reproduce physical RPM.
nonisolated struct FanRotation {
private(set) var phase: Double = 0
private(set) var speed: Double = 0
private var reference: TimeInterval = 0
static func speed(rpm: Double?, reducedMotion: Bool) -> Double {
guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 }
switch rpm {
case ..<2000: return 90
case ..<4000: return 180
case ..<6000: return 300
default: return 450
}
}
func angle(at time: TimeInterval) -> Double {
(phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360)
}
mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) {
phase = angle(at: time)
reference = time
speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion)
}
}
struct FanSpeedIndicator: View {
let title: LocalizedStringKey
let rpm: Double?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var rotation = FanRotation()
var body: some View {
HStack(spacing: 5) {
TimelineView(.animation(minimumInterval: 1.0 / 30, paused: rotation.speed == 0)) { context in
Image(systemName: "fanblades.fill")
.rotationEffect(.degrees(rotation.angle(at: context.date.timeIntervalSinceReferenceDate)))
.foregroundStyle(.secondary)
}.frame(width: 14, height: 14).accessibilityHidden(true)
Text(title).foregroundStyle(.secondary)
Spacer(minLength: 2)
AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.monospacedDigit().fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7)
.onAppear { update() }
.onChange(of: rpm) { _, _ in update() }
.onChange(of: reduceMotion) { _, _ in update() }
}
private func update() {
rotation.update(rpm: rpm, reducedMotion: reduceMotion, at: Date.timeIntervalSinceReferenceDate)
}
}
+31
View File
@@ -0,0 +1,31 @@
import SwiftUI
/// A bounded percentage gauge; missing data keeps an empty track and an explicit -- label.
struct MetricRingGauge: View {
let title: LocalizedStringKey
let value: Double?
let color: Color
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var fraction: Double { value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0 }
var body: some View {
VStack(spacing: 3) {
ZStack {
Circle().stroke(color.opacity(0.17), lineWidth: 3)
Circle().trim(from: 0, to: fraction)
.stroke(color, style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotationEffect(.degrees(-90))
.animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: fraction)
AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12)
}.padding(2).frame(width: 28, height: 28).accessibilityHidden(true)
Text(title).font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.7)
}
.frame(maxWidth: .infinity)
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(title))
.accessibilityValue(Text(verbatim: MetricFormat.percent(value)))
}
}
+29 -5
View File
@@ -6,16 +6,40 @@ struct ResourceCard<Content: View>: View {
let color: Color
let value: String
var secondaryValue: String? = nil
var status: String? = nil
var statusWarning = false
var statusHelp: Text? = nil
var warningText: Text? = nil
var detail: String? = nil
@ViewBuilder var content: () -> Content
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack(alignment: .firstTextBaseline, spacing: 6) {
Label { Text(title).foregroundStyle(.primary) } icon: {
Image(systemName: symbol).foregroundStyle(color)
VStack(alignment: .leading, spacing: 3) {
HStack(alignment: .center, spacing: 6) {
Label { Text(title).foregroundStyle(statusWarning ? .red : .primary) } icon: {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
}.font(.system(size: 13, weight: .semibold)).fixedSize()
if let status {
Text(verbatim: status)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(statusWarning ? .red : color)
.padding(.horizontal, 6).padding(.vertical, 2)
.background((statusWarning ? Color.red : color).opacity(0.14), in: Capsule())
.help(statusHelp ?? Text(verbatim: status))
if let warningText {
warningText
.font(.system(size: 10)).foregroundStyle(.red).lineLimit(1).minimumScaleFactor(0.7)
}
}
if let detail {
Text(verbatim: detail)
.font(.system(size: 9, weight: .medium)).foregroundStyle(.secondary)
.padding(.horizontal, 5).padding(.vertical, 2)
.background(.primary.opacity(0.06), in: Capsule())
.lineLimit(1).minimumScaleFactor(0.7)
}
Spacer(minLength: 0)
HStack(alignment: .firstTextBaseline, spacing: 6) {
HStack(alignment: .center, spacing: 6) {
AnimatedMetricText(value: value)
.font(.system(size: 13, weight: .semibold))
if let secondaryValue {