feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import IOKit.ps
|
||||
import notify
|
||||
|
||||
/// AppKit owns launch only; MenuBar owns windows, Core owns sampling and preferences.
|
||||
@main @MainActor struct kymoApp {
|
||||
@@ -22,9 +24,14 @@ import AppKit
|
||||
private var openSettingsAction: (() -> Void)?
|
||||
private var scenes: AnyObject?
|
||||
private var menuBar: MenuPanelController?
|
||||
private var powerSourceToken: Int32?
|
||||
private var workspaceTokens: [NSObjectProtocol] = []
|
||||
|
||||
func applicationWillFinishLaunching(_ notification: Notification) {
|
||||
var token: Int32 = 0
|
||||
if notify_register_dispatch(kIOPSNotifyPowerSource, &token, .main, { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.metrics.powerSourceDidChange() }
|
||||
}) == NOTIFY_STATUS_OK { powerSourceToken = token }
|
||||
let center = NSWorkspace.shared.notificationCenter
|
||||
for (name, sleeping) in [(NSWorkspace.willSleepNotification, true), (NSWorkspace.didWakeNotification, false)] {
|
||||
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
|
||||
@@ -107,6 +114,7 @@ import AppKit
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
if let powerSourceToken { notify_cancel(powerSourceToken) }
|
||||
workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver)
|
||||
workspaceTokens.removeAll()
|
||||
menuBar?.shutdown()
|
||||
|
||||
@@ -26,6 +26,12 @@ nonisolated enum MetricFormat {
|
||||
return String(format: "%.1f %@", scaled, units[index])
|
||||
}
|
||||
|
||||
static func signedWatts(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite else { return "--" }
|
||||
if abs(value) < 0.05 { return "0 W" }
|
||||
return (value < 0 ? "−" : "+") + watts(abs(value))
|
||||
}
|
||||
|
||||
static func watts(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite, value >= 0 else { return "--" }
|
||||
return String(format: "%.1f W", value)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated struct PowerReading: Sendable, Equatable {
|
||||
enum Source: Sendable { case smc, telemetry, instantaneous, average, balance }
|
||||
let watts: Double
|
||||
var source: Source = .telemetry
|
||||
}
|
||||
|
||||
nonisolated struct BatteryPowerFlow: Sendable {
|
||||
var connected: Bool?
|
||||
var externalSupply: Bool?
|
||||
var charging: Bool?
|
||||
var battery: PowerReading?
|
||||
var input: PowerReading?
|
||||
var load: PowerReading?
|
||||
var adapterCapacity: Double?
|
||||
|
||||
mutating func applyBatterySensor(_ watts: Double) {
|
||||
// The gauge may still report the last charging sample just after unplugging.
|
||||
guard watts <= 0 || (externalSupply != false && connected != false) else { return }
|
||||
battery = PowerReading(watts: watts, source: .smc)
|
||||
// Estimates made from older registry measurements no longer share a sampling window.
|
||||
if load?.source == .balance { load = nil }
|
||||
if input?.source == .balance { input = nil }
|
||||
if connected == false, load == nil, watts < 0 {
|
||||
load = PowerReading(watts: -watts, source: .balance)
|
||||
}
|
||||
}
|
||||
|
||||
enum State: Sendable {
|
||||
case charging, combined, battery, discharging, external, unknown
|
||||
}
|
||||
|
||||
var state: State {
|
||||
if let battery {
|
||||
// Differences of two sensors are less precise than a battery-terminal reading.
|
||||
let threshold = battery.source == .balance ? 0.5 : 0.05
|
||||
if battery.watts >= threshold { return .charging }
|
||||
if battery.watts <= -threshold {
|
||||
if connected == true, let input, input.source != .balance, input.watts >= 0.05 { return .combined }
|
||||
if connected == false || externalSupply == false || input?.watts == 0 { return .battery }
|
||||
return .discharging
|
||||
}
|
||||
}
|
||||
if battery == nil, charging == true, connected != false, externalSupply != false { return .charging }
|
||||
if externalSupply == false { return .battery }
|
||||
if externalSupply == true || (input?.watts ?? 0) > 0 { return .external }
|
||||
if connected == false { return .battery }
|
||||
return .unknown
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@ nonisolated struct TrendSample: Sendable {
|
||||
let memory: Double?
|
||||
var download: Double?
|
||||
var battery: Double?
|
||||
var batteryPower: Double?
|
||||
var powerFlow: BatteryPowerFlow?
|
||||
var systemPower: Double?
|
||||
var desktopInput: Double?
|
||||
var upload: Double?
|
||||
var read: Double?
|
||||
var write: Double?
|
||||
@@ -46,9 +47,9 @@ nonisolated struct MetricHistory: Sendable {
|
||||
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
||||
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
||||
download: snapshot.downloadRate,
|
||||
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
|
||||
battery: snapshot.battery?.charge, powerFlow: snapshot.battery?.flow,
|
||||
systemPower: snapshot.batteryState == .absent ? snapshot.systemPower : nil,
|
||||
upload: snapshot.uploadRate,
|
||||
desktopInput: snapshot.desktopInput, upload: snapshot.uploadRate,
|
||||
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler,
|
||||
memoryApp: snapshot.memory.map { Double($0.app) },
|
||||
|
||||
@@ -35,6 +35,7 @@ nonisolated struct MetricsSnapshot: Sendable {
|
||||
var diskIO: DiskIOMetrics?
|
||||
var volumes: [VolumeMetrics]?
|
||||
var systemPower: Double?
|
||||
var desktopInput: Double?
|
||||
var battery: BatteryMetrics?
|
||||
var uptime: TimeInterval = 0
|
||||
var gpu: GPUMetrics?
|
||||
|
||||
@@ -3,22 +3,42 @@ import IOKit.ps
|
||||
|
||||
nonisolated struct BatteryMetrics: Sendable {
|
||||
let charge: Double?
|
||||
let charging: Bool
|
||||
let externalPower: Bool
|
||||
var power: Double? = nil
|
||||
var flow = BatteryPowerFlow()
|
||||
var minutesRemaining: Int?
|
||||
var cycles: Int?
|
||||
var health: Double?
|
||||
}
|
||||
|
||||
nonisolated enum BatteryMonitor {
|
||||
nonisolated struct BatteryMonitor {
|
||||
// The controller publishes less frequently than the panel. After a source change or
|
||||
// wake, wait for each register group to advance before using it again.
|
||||
private struct Freshness {
|
||||
var stamp: [NSNumber?]?
|
||||
var updated = Date.distantPast
|
||||
|
||||
mutating func accepts(_ next: [NSNumber?], at now: Date, invalidate: Bool) -> Bool {
|
||||
if next != stamp { updated = now; stamp = next }
|
||||
else if invalidate { updated = .distantPast }
|
||||
return (0...120).contains(now.timeIntervalSince(updated))
|
||||
}
|
||||
}
|
||||
|
||||
private var telemetryStamp = Freshness()
|
||||
private var packStamp = Freshness()
|
||||
private var previousConnection: Bool?
|
||||
private var previousSupply: Bool?
|
||||
private var sampled = false
|
||||
private var invalidated = false
|
||||
|
||||
mutating func invalidate() { invalidated = true }
|
||||
|
||||
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
|
||||
let watts = (voltageMillivolts * amperageMilliamps) / 1_000_000
|
||||
return watts.isFinite && abs(watts) <= 500 ? watts : nil
|
||||
}
|
||||
|
||||
static func positiveMinutes(_ value: Int?) -> Int? {
|
||||
@@ -44,7 +64,7 @@ nonisolated enum BatteryMonitor {
|
||||
return .absent
|
||||
}
|
||||
|
||||
static func sample() -> BatteryMetrics? {
|
||||
mutating func sample() -> BatteryMetrics? {
|
||||
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
||||
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
|
||||
for source in sources {
|
||||
@@ -53,36 +73,131 @@ nonisolated enum BatteryMonitor {
|
||||
let current = item[kIOPSCurrentCapacityKey] as? Double
|
||||
let maximum = item[kIOPSMaxCapacityKey] as? Double
|
||||
let charge = current.flatMap { c in maximum.flatMap { $0 > 0 ? min(1, max(0, c / $0)) : nil } }
|
||||
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
|
||||
var properties: [String: Any] = [:]
|
||||
if service != 0 {
|
||||
defer { IOObjectRelease(service) }
|
||||
var raw: Unmanaged<CFMutableDictionary>?
|
||||
if IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS {
|
||||
properties = raw?.takeRetainedValue() as? [String: Any] ?? [:]
|
||||
}
|
||||
let properties = Self.registryProperties() ?? [:]
|
||||
let state = item[kIOPSPowerSourceStateKey] as? String
|
||||
let supply: Bool? = state == kIOPSACPowerValue ? true : state == kIOPSBatteryPowerValue ? false : nil
|
||||
let charging = item[kIOPSIsChargingKey] as? Bool
|
||||
let minutes = charging == true ? item[kIOPSTimeToFullChargeKey] as? Int : item[kIOPSTimeToEmptyKey] as? Int
|
||||
var estimate: Int?
|
||||
if let supply, let charging {
|
||||
estimate = Self.estimatedMinutes(charging: charging, externalPower: supply, sourceMinutes: minutes,
|
||||
systemSeconds: IOPSGetTimeRemainingEstimate())
|
||||
}
|
||||
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,
|
||||
power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage),
|
||||
minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
|
||||
return BatteryMetrics(charge: charge, flow: powerFlow(properties, externalSupply: supply, charging: charging),
|
||||
minutesRemaining: estimate,
|
||||
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
|
||||
private static func registryProperties() -> [String: Any]? {
|
||||
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
|
||||
guard service != 0 else { return nil }
|
||||
defer { IOObjectRelease(service) }
|
||||
var raw: Unmanaged<CFMutableDictionary>?
|
||||
guard IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS else { return nil }
|
||||
return raw?.takeRetainedValue() as? [String: Any]
|
||||
}
|
||||
|
||||
/// A machine without a pack can still publish an independent DC input reading.
|
||||
mutating func desktopInput() -> Double? {
|
||||
guard let properties = Self.registryProperties() else { return nil }
|
||||
let input = powerFlow(properties, externalSupply: true).input
|
||||
return input?.source == .telemetry ? input?.watts : nil
|
||||
}
|
||||
|
||||
private static func scalar(_ raw: Any?) -> Double? {
|
||||
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
||||
number.doubleValue.isFinite else { return nil }
|
||||
return number.doubleValue
|
||||
}
|
||||
|
||||
/// IORegistry can expose signed telemetry as an unsigned 32- or 64-bit register.
|
||||
private static func signed(_ raw: Any?, limit: Double) -> Double? {
|
||||
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }
|
||||
var value = number.doubleValue
|
||||
if value > limit, !CFNumberIsFloatType(number) {
|
||||
let bits = number.uint64Value
|
||||
if bits <= UInt32.max { value = Double(Int32(bitPattern: UInt32(bits))) }
|
||||
else { value = Double(Int64(bitPattern: bits)) }
|
||||
}
|
||||
return value.isFinite && abs(value) <= limit ? value : nil
|
||||
}
|
||||
|
||||
mutating func powerFlow(_ properties: [String: Any], externalSupply: Bool?, charging: Bool? = nil, now: Date = Date()) -> BatteryPowerFlow {
|
||||
let connected = properties["ExternalConnected"] as? Bool ?? (externalSupply == true ? true : nil)
|
||||
let changed = invalidated || (sampled && (previousConnection != connected || previousSupply != externalSupply))
|
||||
previousConnection = connected
|
||||
previousSupply = externalSupply
|
||||
sampled = true
|
||||
invalidated = false
|
||||
let telemetry = properties["PowerTelemetryData"] as? [String: Any] ?? [:]
|
||||
let pack = properties["BatteryData"] as? [String: Any] ?? [:]
|
||||
let adapter = properties["AdapterDetails"] as? [String: Any]
|
||||
var flow = BatteryPowerFlow(connected: connected, externalSupply: externalSupply, charging: charging ?? properties["IsCharging"] as? Bool)
|
||||
if connected != false, let capacity = Self.scalar(adapter?["Watts"]), (0.1...500).contains(capacity) {
|
||||
flow.adapterCapacity = capacity
|
||||
}
|
||||
|
||||
// IORegistry can observe physical disconnection before IOPowerSources catches up.
|
||||
if connected == false { flow.externalSupply = false; flow.charging = false }
|
||||
let packDate = Self.scalar(properties["UpdateTime"])
|
||||
let recent = packDate.map { (0...120).contains(now.timeIntervalSince1970 - $0) } ?? true
|
||||
let voltage = properties["Voltage"] ?? pack["Voltage"] ?? pack["AppleRawBatteryVoltage"]
|
||||
let instant = properties["InstantAmperage"] ?? pack["InstantAmperage"]
|
||||
let average = properties["Amperage"] ?? pack["Amperage"]
|
||||
let packFresh = packStamp.accepts([properties["UpdateTime"], voltage, instant, average].map { $0 as? NSNumber }, at: now, invalidate: changed)
|
||||
let counters = ["SystemLoadAccumulatorCount", "SystemPowerInAccumulatorCount", "SystemPowerIn",
|
||||
"BatteryPower", "SystemLoad", "SystemVoltageIn", "SystemCurrentIn"]
|
||||
let telemetryFresh = telemetryStamp.accepts(counters.map { telemetry[$0] as? NSNumber }, at: now, invalidate: changed)
|
||||
let disconnected = connected == false
|
||||
func compatible(_ watts: Double) -> Bool { watts <= 0 || (!disconnected && externalSupply != false) }
|
||||
|
||||
if packFresh && recent {
|
||||
for (raw, source) in [(instant, PowerReading.Source.instantaneous), (average, .average)] {
|
||||
if let watts = Self.normalizedPower(voltageMillivolts: Self.scalar(voltage),
|
||||
amperageMilliamps: Self.signed(raw, limit: 20_000)), compatible(watts) {
|
||||
flow.battery = PowerReading(watts: watts, source: source)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
if disconnected { flow.input = PowerReading(watts: 0) }
|
||||
guard telemetryFresh, recent else { return flow }
|
||||
func measured(_ key: String) -> Double? {
|
||||
guard let value = Self.scalar(telemetry[key]), (0...500_000).contains(value) else { return nil }
|
||||
return value / 1000
|
||||
}
|
||||
var input = measured("SystemPowerIn")
|
||||
if input == nil, let mv = Self.scalar(telemetry["SystemVoltageIn"]), (1...50_000).contains(mv),
|
||||
let ma = Self.scalar(telemetry["SystemCurrentIn"]), (0...10_000).contains(ma) {
|
||||
input = mv * ma / 1_000_000
|
||||
}
|
||||
// A positive adapter reading after unplugging belongs to the previous supply.
|
||||
if disconnected && (input ?? 0) > 0 { return flow }
|
||||
if !disconnected { flow.input = input.map { PowerReading(watts: $0) } }
|
||||
flow.load = measured("SystemLoad").map { PowerReading(watts: $0) }
|
||||
if let mw = Self.signed(telemetry["BatteryPower"], limit: 500_000), compatible(mw / 1000) {
|
||||
let watts = mw / 1000
|
||||
// Some controllers retain zero/old-direction battery telemetry while the
|
||||
// pack already reports discharge. Prefer the instantaneous pack in that case.
|
||||
if let pack = flow.battery, pack.source == .instantaneous {
|
||||
if abs(pack.watts) >= 0.05 && watts * pack.watts <= 0 { return flow }
|
||||
if watts > 0 && pack.watts == 0 && flow.charging == false { return flow }
|
||||
}
|
||||
flow.battery = PowerReading(watts: watts)
|
||||
}
|
||||
if flow.battery == nil, connected != nil || externalSupply != nil, let input = flow.input, let load = flow.load, compatible(input.watts - load.watts) {
|
||||
flow.battery = PowerReading(watts: input.watts - load.watts, source: .balance)
|
||||
} else if let battery = flow.battery, battery.source == .telemetry {
|
||||
// Reverse estimates use only quantities published in the same telemetry group.
|
||||
if flow.load == nil, let input = flow.input, (0...500).contains(input.watts - battery.watts) {
|
||||
flow.load = PowerReading(watts: input.watts - battery.watts, source: .balance)
|
||||
} else if flow.input == nil, connected == true, let load = flow.load, (0...500).contains(load.watts + battery.watts) {
|
||||
flow.input = PowerReading(watts: load.watts + battery.watts, source: .balance)
|
||||
}
|
||||
}
|
||||
return flow
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
import IOKit
|
||||
|
||||
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system power keys; never write keys.
|
||||
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system and battery power keys; never write keys.
|
||||
nonisolated final class CPUTemperatureMonitor {
|
||||
static let highTemperatureThreshold = 90.0
|
||||
|
||||
@@ -105,9 +105,21 @@ nonisolated final class CPUTemperatureMonitor {
|
||||
return watts
|
||||
}
|
||||
|
||||
private func readNumber(_ key: UInt32) -> Double? {
|
||||
/// B0AP on Apple Silicon is a signed, little-endian milliwatt reading at the battery.
|
||||
func sampleBatteryPower() -> Double? {
|
||||
#if arch(arm64)
|
||||
guard openConnection(), let milliwatts = readNumber(0x42304150, expectedType: 0x73693332),
|
||||
abs(milliwatts) <= 500_000 else { return nil }
|
||||
return milliwatts / 1000
|
||||
#else
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
||||
private func readNumber(_ key: UInt32, expectedType: UInt32? = nil) -> Double? {
|
||||
var request = Request(); request.key = key; request.command = 9
|
||||
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
|
||||
guard let metadata = call(&request), metadata.info.size <= 32,
|
||||
expectedType == nil || metadata.info.type == expectedType 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))) }
|
||||
@@ -116,6 +128,8 @@ nonisolated final class CPUTemperatureMonitor {
|
||||
|
||||
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
|
||||
switch (type, bytes.count) {
|
||||
case (0x73693332, 4): // si32, little-endian signed integer
|
||||
return Double(bytes.withUnsafeBytes { Int32(littleEndian: $0.loadUnaligned(as: Int32.self)) })
|
||||
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))
|
||||
|
||||
@@ -10,11 +10,14 @@ actor SystemSampler {
|
||||
private var fanCache: [FanMetrics]?
|
||||
private var powerSchedule = SensorSchedule(successInterval: 0)
|
||||
private var readingPower = false
|
||||
private var batteryPowerSchedule = SensorSchedule(successInterval: 0)
|
||||
private var readingBatteryPower = false
|
||||
private var cpuSchedule = SensorSchedule()
|
||||
private var gpuSchedule = SensorSchedule()
|
||||
private var fanSchedule = SensorSchedule()
|
||||
private var didProbe = false
|
||||
private let diskHealth = DiskHealthMonitor()
|
||||
private var batteryMonitor = BatteryMonitor()
|
||||
private let batteryHealth = SystemBatteryHealthMonitor()
|
||||
private var network = NetworkMonitor()
|
||||
private let networkPath = NetworkPathObserver()
|
||||
@@ -48,6 +51,8 @@ actor SystemSampler {
|
||||
|
||||
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
||||
|
||||
func invalidateBatteryReadings() { batteryMonitor.invalidate() }
|
||||
|
||||
func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
|
||||
var changedRevision = false
|
||||
if let revision {
|
||||
@@ -101,7 +106,7 @@ actor SystemSampler {
|
||||
result.defaultNetworkInterface = networkPath.defaultInterface()
|
||||
result.disk = DiskMonitor.sample()
|
||||
result.diskIO = diskIO.sample()
|
||||
result.battery = BatteryMonitor.sample()
|
||||
result.battery = batteryMonitor.sample()
|
||||
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
|
||||
result.gpu = GPUMonitor.sample()
|
||||
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
|
||||
@@ -122,8 +127,20 @@ actor SystemSampler {
|
||||
result.battery?.health = batteryCache
|
||||
result.volumes = volumes
|
||||
result.uptime = ProcessInfo.processInfo.systemUptime
|
||||
if includeSlowMetrics && result.battery != nil && !readingBatteryPower && batteryPowerSchedule.isDue(at: start) {
|
||||
readingBatteryPower = true
|
||||
let watts = await CPUTemperatureServiceClient.readBatteryPower()
|
||||
readingBatteryPower = false
|
||||
if !Task.isCancelled {
|
||||
if let watts { result.battery?.flow.applyBatterySensor(watts) }
|
||||
batteryPowerSchedule.complete(available: watts != nil, at: ProcessInfo.processInfo.systemUptime)
|
||||
}
|
||||
}
|
||||
// Only a confirmed batteryless machine requests the fixed system-total key.
|
||||
// Use this sample's reply directly: a missing reading never repeats the last wattage.
|
||||
if includeSlowMetrics && result.batteryState == .absent {
|
||||
result.desktopInput = batteryMonitor.desktopInput()
|
||||
}
|
||||
if includeSlowMetrics && result.batteryState == .absent && !readingPower && powerSchedule.isDue(at: start) {
|
||||
readingPower = true
|
||||
result.systemPower = await CPUTemperatureServiceClient.readSystemPower()
|
||||
|
||||
@@ -7,6 +7,14 @@ nonisolated struct SensorReadings: Sendable {
|
||||
}
|
||||
|
||||
nonisolated enum CPUTemperatureServiceClient {
|
||||
static func readBatteryPower() async -> Double? {
|
||||
await ServiceRequest.perform(timeout: 2) { proxy, finish in
|
||||
proxy.readBatteryPower { value in
|
||||
finish(value.flatMap { abs($0.doubleValue) <= 500 ? $0.doubleValue : nil })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func readSystemPower() async -> Double? {
|
||||
await ServiceRequest.perform(timeout: 2) { proxy, finish in
|
||||
proxy.readSystemPower { value in
|
||||
|
||||
@@ -29,6 +29,7 @@ final class MetricsStore {
|
||||
@ObservationIgnored private var task: Task<Void, Never>?
|
||||
@ObservationIgnored private let sampler: SystemSampler
|
||||
@ObservationIgnored private var scheduledInterval = 0
|
||||
@ObservationIgnored private var batteryWasAsleep = false
|
||||
@ObservationIgnored private var needsHistoryBoundary = true
|
||||
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
||||
|
||||
@@ -50,7 +51,12 @@ final class MetricsStore {
|
||||
reschedule(reset: true)
|
||||
}
|
||||
|
||||
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
|
||||
func powerSourceDidChange() {
|
||||
guard panelDemand, !isPaused, !isSystemSleeping else { return }
|
||||
reschedule(reset: false, confirmPowerChange: true)
|
||||
}
|
||||
|
||||
private func reschedule(reset: Bool, sampleImmediately: Bool = true, confirmPowerChange: Bool = false) {
|
||||
generation += 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
@@ -71,7 +77,12 @@ final class MetricsStore {
|
||||
if initialDelay > .zero {
|
||||
do { try await Task.sleep(for: initialDelay, tolerance: self?.schedulingTolerance) } catch { return }
|
||||
}
|
||||
if self?.batteryWasAsleep == true {
|
||||
self?.batteryWasAsleep = false
|
||||
await sampler.invalidateBatteryReadings()
|
||||
}
|
||||
if reset { await sampler.reset() }
|
||||
var needsConfirmation = confirmPowerChange
|
||||
while !Task.isCancelled {
|
||||
let sampledAt = ContinuousClock.now
|
||||
let visibleGeneration = self?.visibilityGeneration
|
||||
@@ -105,7 +116,10 @@ final class MetricsStore {
|
||||
self?.lastPublishedAt = .now
|
||||
self?.needsHistoryBoundary = false
|
||||
SamplingDiagnostics.record(next)
|
||||
let interval = self?.effectiveMilliseconds ?? 5_000
|
||||
let cadence = self?.effectiveMilliseconds ?? 5_000
|
||||
// A source notification may arrive just before the gauge updates.
|
||||
let interval = needsConfirmation ? min(cadence, 1000) : cadence
|
||||
needsConfirmation = false
|
||||
// Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
|
||||
let deadline = sampledAt.advanced(by: .milliseconds(interval))
|
||||
do { try await Task.sleep(until: max(deadline, .now), tolerance: self?.schedulingTolerance, clock: .continuous) }
|
||||
@@ -130,6 +144,7 @@ final class MetricsStore {
|
||||
|
||||
func setSystemSleeping(_ sleeping: Bool) {
|
||||
guard sleeping != isSystemSleeping else { return }
|
||||
if sleeping { batteryWasAsleep = true }
|
||||
isSystemSleeping = sleeping
|
||||
updateDemand(reset: true)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import Foundation
|
||||
@objc protocol SMARTServiceProtocol {
|
||||
nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void)
|
||||
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
|
||||
nonisolated func readBatteryPower(withReply reply: @escaping (NSNumber?) -> Void)
|
||||
nonisolated func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void)
|
||||
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
|
||||
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
|
||||
|
||||
@@ -53,7 +53,11 @@ nonisolated enum SamplingDiagnostics {
|
||||
payload["batteryCycles"] = snapshot.battery?.cycles
|
||||
payload["batteryHealth"] = snapshot.battery?.health
|
||||
payload["systemPower"] = snapshot.systemPower
|
||||
payload["batteryPower"] = snapshot.battery?.power
|
||||
payload["batteryPower"] = snapshot.battery?.flow.battery?.watts
|
||||
payload["batteryPowerSource"] = snapshot.battery?.flow.battery.map { String(describing: $0.source) }
|
||||
payload["adapterInput"] = snapshot.battery?.flow.input?.watts
|
||||
payload["systemLoad"] = snapshot.battery?.flow.load?.watts
|
||||
payload["powerState"] = snapshot.battery.map { String(describing: $0.flow.state) }
|
||||
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
|
||||
|
||||
@@ -8,10 +8,36 @@ struct PowerResourceCard: View {
|
||||
let chartIntervals: [TimeInterval]
|
||||
@Environment(\.locale) private var locale
|
||||
|
||||
private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
|
||||
if battery.charging { return "battery.chargePower" }
|
||||
if !battery.externalPower { return "battery.dischargePower" }
|
||||
return "battery.power"
|
||||
private func label(_ state: BatteryPowerFlow.State) -> String {
|
||||
let key: String = switch state {
|
||||
case .charging: "power.charging"
|
||||
case .combined: "power.combined"
|
||||
case .discharging: "power.discharging"
|
||||
case .external: "battery.acPower"
|
||||
case .battery: "battery.batterySource"
|
||||
case .unknown: "power.unknown"
|
||||
}
|
||||
return AppLocalization.string(key, locale: locale)
|
||||
}
|
||||
|
||||
private func formatted(_ reading: PowerReading?, signed: Bool = false) -> String {
|
||||
let value = signed ? MetricFormat.signedWatts(reading?.watts) : MetricFormat.watts(reading?.watts)
|
||||
return reading?.source == .balance ? "≈" + value : value
|
||||
}
|
||||
|
||||
private func details(_ flow: BatteryPowerFlow) -> String {
|
||||
var rows: [(String, String)] = [
|
||||
("battery.power", formatted(flow.battery, signed: true)),
|
||||
("power.load", formatted(flow.load))
|
||||
]
|
||||
if flow.connected != false {
|
||||
rows.append(("power.input", formatted(flow.input)))
|
||||
rows.append(("power.capacity", MetricFormat.watts(flow.adapterCapacity)))
|
||||
}
|
||||
if flow.battery?.source == .average {
|
||||
rows[0].0 = "power.averageBattery"
|
||||
}
|
||||
return rows.map { AppLocalization.string($0.0, locale: locale) + " " + $0.1 }.joined(separator: "\n")
|
||||
}
|
||||
|
||||
@ViewBuilder var body: some View {
|
||||
@@ -20,6 +46,13 @@ struct PowerResourceCard: View {
|
||||
value: MetricFormat.watts(snapshot.systemPower), chart: {
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.systemPower),
|
||||
color: Color("MetricBattery"), fixedScale: nil, firstValueFormat: .watts,
|
||||
sampleTooltip: { index in
|
||||
let sample = samples[index]
|
||||
return AnyView(VStack(alignment: .leading) {
|
||||
InlineMetric("power.system", MetricFormat.watts(sample.systemPower))
|
||||
if let input = sample.desktopInput { InlineMetric("power.input", MetricFormat.watts(input)) }
|
||||
})
|
||||
},
|
||||
firstLabel: "power.system", expectedInterval: chartInterval,
|
||||
boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
}) {
|
||||
@@ -27,35 +60,35 @@ struct PowerResourceCard: View {
|
||||
.font(.system(size: 10)).foregroundStyle(.secondary)
|
||||
}
|
||||
} else {
|
||||
batteryChargeCard
|
||||
batteryPowerCard
|
||||
}
|
||||
}
|
||||
|
||||
private var batteryChargeCard: some View {
|
||||
private var batteryPowerCard: some View {
|
||||
ResourceCard(
|
||||
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
|
||||
value: MetricFormat.percent(snapshot.battery?.charge),
|
||||
status: snapshot.battery.map { AppLocalization.string($0.externalPower ? "battery.acPower" : "battery.batterySource", locale: locale) },
|
||||
status: snapshot.battery.map { label($0.flow.state) },
|
||||
warningText: snapshot.battery.map { Text(verbatim: details($0.flow)) },
|
||||
chartPlacement: .background,
|
||||
chart: {
|
||||
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: snapshot.battery.map(batteryPowerLabel) ?? "battery.power",
|
||||
expectedInterval: chartInterval,
|
||||
boundaryDates: chartBoundaries,
|
||||
intervals: chartIntervals
|
||||
color: Color("MetricBattery"), fixedScale: 1, firstValueFormat: .percent,
|
||||
sampleTooltip: { index in
|
||||
let flow = samples[index].powerFlow ?? BatteryPowerFlow()
|
||||
return AnyView(VStack(alignment: .leading, spacing: 2) {
|
||||
Text(verbatim: MetricFormat.percent(samples[index].battery) + " · " + label(flow.state)).bold()
|
||||
Text(verbatim: details(flow)).monospacedDigit()
|
||||
})
|
||||
},
|
||||
firstLabel: "metric.battery", expectedInterval: chartInterval,
|
||||
boundaryDates: chartBoundaries, intervals: chartIntervals
|
||||
)
|
||||
}
|
||||
) {
|
||||
InlineMetric("battery.powerShort", MetricFormat.watts(snapshot.battery?.power))
|
||||
InlineMetric("battery.powerShort", formatted(snapshot.battery?.flow.battery, signed: true))
|
||||
.frame(height: 16)
|
||||
if let battery = snapshot.battery {
|
||||
batteryDetails(battery)
|
||||
@@ -73,10 +106,10 @@ struct PowerResourceCard: View {
|
||||
}
|
||||
HStack(spacing: 4) {
|
||||
Text("battery.timeShort").foregroundStyle(.secondary)
|
||||
if battery.externalPower {
|
||||
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
|
||||
} else if let minutes = battery.minutesRemaining {
|
||||
if let minutes = battery.minutesRemaining {
|
||||
MetricText(value: "\(minutes) min")
|
||||
} else if battery.flow.state == .external {
|
||||
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
|
||||
} else {
|
||||
Text("battery.timeUnknown")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,182 @@
|
||||
{
|
||||
"sourceLanguage" : "en",
|
||||
"strings" : {
|
||||
"power.charging": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Charging"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "充电中"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "充電中"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.combined": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Combined power"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "共同供电"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "共同供電"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.discharging": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Discharging"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "放电中"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "放電中"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.unknown": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Unknown source"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "供电未知"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "供電未知"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.input": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Adapter input"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "适配器输入"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "轉接器輸入"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.capacity": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Adapter capacity"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "适配器报告功率"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "轉接器回報功率"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.load": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "System load"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "系统负载"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "系統負載"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.averageBattery": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Battery (average)"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "电池功率(平均)"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "電池功率(平均)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"power.system": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
@@ -166,13 +342,13 @@
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "续航"
|
||||
"value": "估时"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "續航"
|
||||
"value": "估時"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1013,19 +1189,19 @@
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "AC power"
|
||||
"value" : "External power"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "交流电"
|
||||
"value" : "外接供电"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "交流電"
|
||||
"value" : "外接供電"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1035,19 +1211,19 @@
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Battery"
|
||||
"value" : "On battery"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "电池"
|
||||
"value" : "电池供电"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "電池"
|
||||
"value" : "電池供電"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,13 @@ import SwiftUI
|
||||
/// Rate plots share a zero axis and equal positive amplitudes on either side.
|
||||
nonisolated enum PanelCurveProjection: Equatable {
|
||||
case fullHeight
|
||||
case signed
|
||||
case split(upwardSeries: Int)
|
||||
|
||||
func y(value: Double, scale: Double, series: Int, height: Double) -> Double {
|
||||
let fraction = min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1)))
|
||||
switch self {
|
||||
case .signed: return height * (0.5 - 0.5 * min(1, max(-1, value / max(0.0001, scale))))
|
||||
case .fullHeight: return height * (1 - fraction)
|
||||
case .split(let upward): return height * (0.6 + (series == upward ? -0.3 : 0.3) * fraction)
|
||||
}
|
||||
@@ -154,8 +156,9 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
baseline.frame = bounds
|
||||
baseline.isHidden = input?.projection == .fullHeight || input == nil
|
||||
let path = CGMutablePath()
|
||||
path.move(to: CGPoint(x: 0, y: bounds.height * 0.6))
|
||||
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height * 0.6))
|
||||
let zero = input?.projection.y(value: 0, scale: 1, series: 0, height: bounds.height) ?? 0
|
||||
path.move(to: CGPoint(x: 0, y: zero))
|
||||
path.addLine(to: CGPoint(x: bounds.width, y: zero))
|
||||
baseline.path = path
|
||||
}
|
||||
private func updateGrid() {
|
||||
|
||||
@@ -5,6 +5,7 @@ enum TrendValueFormat {
|
||||
case rate
|
||||
case bytes
|
||||
case memory
|
||||
case signedWatts
|
||||
case watts
|
||||
}
|
||||
|
||||
@@ -20,9 +21,8 @@ struct PanelTrendChart: View {
|
||||
var thirdColor: Color = .purple
|
||||
var fourthColor: Color = .yellow
|
||||
var fixedScale: Double? = 1
|
||||
var secondSeriesUsesAutonomousScale = false
|
||||
var firstValueFormat: TrendValueFormat?
|
||||
var secondValueFormat: TrendValueFormat?
|
||||
var sampleTooltip: ((Int) -> AnyView)?
|
||||
var firstLabel: LocalizedStringKey = "panel.total"
|
||||
var secondLabel: LocalizedStringKey = "network.upload"
|
||||
var thirdLabel: LocalizedStringKey = "cpu.system"
|
||||
@@ -38,8 +38,6 @@ struct PanelTrendChart: View {
|
||||
@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?
|
||||
|
||||
@@ -64,12 +62,10 @@ struct PanelTrendChart: View {
|
||||
private var maximum: Double {
|
||||
let values = stackOrder.isEmpty ? first + second + third + fourth
|
||||
: StackedSeries.bands(renderFrame.series, count: dates.count).last?.upper ?? []
|
||||
if projection == .signed { return max(1, values.compactMap { $0 }.filter(\.isFinite).map(abs).max() ?? 1) }
|
||||
return max(1, values.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 let firstValueFormat { return firstValueFormat }
|
||||
if fixedScale == 1 { return .percent }
|
||||
@@ -81,31 +77,36 @@ struct PanelTrendChart: View {
|
||||
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?, format: TrendValueFormat? = nil) -> String {
|
||||
private func formatted(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite else { return "--" }
|
||||
switch format ?? automaticFormat {
|
||||
switch automaticFormat {
|
||||
case .percent: return MetricFormat.percent(value)
|
||||
case .rate: return MetricFormat.rate(value)
|
||||
case .bytes: return MetricFormat.bytes(UInt64(max(0, value)))
|
||||
case .memory: return MetricFormat.memory(UInt64(max(0, value)))
|
||||
case .signedWatts: return MetricFormat.signedWatts(value)
|
||||
case .watts: return MetricFormat.watts(value)
|
||||
}
|
||||
}
|
||||
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, index: Int) -> some View {
|
||||
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, 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, format: format)).monospacedDigit()
|
||||
Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit()
|
||||
}
|
||||
}
|
||||
private func tooltip(index: Int) -> some View {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
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, format: secondValueFormat, index: index) }
|
||||
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
|
||||
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
|
||||
if let sampleTooltip {
|
||||
sampleTooltip(index)
|
||||
} else {
|
||||
tooltipRow(firstLabel, values: first, tint: color, index: index)
|
||||
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) }
|
||||
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
|
||||
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
|
||||
}
|
||||
}
|
||||
.font(.system(size: 9)).padding(6)
|
||||
.background { TooltipBackground() }
|
||||
@@ -115,7 +116,7 @@ struct PanelTrendChart: View {
|
||||
var body: some View {
|
||||
GeometryReader { proxy in
|
||||
NativePanelCurve(frame: renderFrame, colors: renderColors,
|
||||
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
|
||||
scales: [scale, scale, scale, scale],
|
||||
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
|
||||
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
|
||||
filledSeriesCount: stackOrder.isEmpty ? (filledSeriesCount ?? visibleSeriesCount) : stackOrder.count, stacked: !stackOrder.isEmpty, projection: projection,
|
||||
@@ -139,7 +140,6 @@ struct PanelTrendChart: View {
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.onAppear {
|
||||
retainedScale = maximum
|
||||
retainedSecondScale = secondMaximum
|
||||
}
|
||||
.onChange(of: dates) { _, _ in
|
||||
let target = maximum
|
||||
@@ -148,12 +148,6 @@ 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 }
|
||||
}
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel(Text(firstLabel))
|
||||
|
||||
Reference in New Issue
Block a user