fix(power): 完善电池卡片的共同供电判定、功率图标与预估续航

按适配器和电池的实际贡献判定共同供电,以双图标和双色柱展示两路功率。同步三语预估续航文案,在仅外接供电时隐藏估时行。
This commit is contained in:
2026-11-16 15:06:02 +08:00
parent ae448bce5c
commit 451d31682d
16 changed files with 262 additions and 147 deletions
+41 -2
View File
@@ -15,9 +15,44 @@ nonisolated struct BatteryPowerFlow: Sendable {
var load: PowerReading?
var adapterCapacity: Double?
struct JointSupply: Sendable {
let adapter: PowerReading
let discharge: PowerReading
var batteryFraction: Double { discharge.watts / (adapter.watts + discharge.watts) }
}
// Classification floor in watts, separate from the resolution of the displayed readings.
private static let minimumContribution = 0.5
private(set) var registryJointSupply: JointSupply?
var jointSupply: JointSupply? {
guard connected == true, let battery,
battery.watts <= -Self.minimumContribution else { return nil }
if battery.source == .smc { return registryJointSupply }
guard let input, input.watts >= Self.minimumContribution else { return nil }
// IOPS reports a single primary source. Override its battery-only indication
// only if all three direct telemetry channels independently support the split.
if externalSupply == false &&
(input.source != .telemetry || battery.source != .telemetry || load?.source != .telemetry) { return nil }
let discharge: PowerReading
if battery.source == .telemetry || battery.source == .balance {
discharge = PowerReading(watts: -battery.watts, source: battery.source)
} else if let load, load.source == .telemetry, input.source == .telemetry {
discharge = PowerReading(watts: load.watts - input.watts, source: .balance)
} else { return nil }
guard discharge.watts >= Self.minimumContribution else { return nil }
if let load, load.source == .telemetry, input.source == .telemetry {
// Reject conflicting measured channels rather than normalize an unexplained excess.
let residual = abs(input.watts + discharge.watts - load.watts)
guard residual <= max(1, 0.1 * load.watts) else { return nil }
}
return JointSupply(adapter: input, discharge: discharge)
}
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 }
if battery?.source != .smc { registryJointSupply = jointSupply }
battery = PowerReading(watts: watts, source: .smc)
// Estimates made from older registry measurements no longer share a sampling window.
if load?.source == .balance { load = nil }
@@ -37,8 +72,12 @@ nonisolated struct BatteryPowerFlow: Sendable {
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 }
if jointSupply != nil { return .combined }
if connected == false || externalSupply == false { return .battery }
if let input, input.source != .balance {
if input.watts < Self.minimumContribution { return .battery }
if battery.watts > -Self.minimumContribution { return .external }
}
return .discharging
}
}
+29 -13
View File
@@ -4,7 +4,15 @@ import IOKit.ps
nonisolated struct BatteryMetrics: Sendable {
let charge: Double?
var flow = BatteryPowerFlow()
var minutesRemaining: Int?
var minutesToFull: Int?
var minutesToEmpty: Int?
var minutesRemaining: Int? {
switch flow.state {
case .charging: minutesToFull
case .battery, .discharging, .combined: minutesToEmpty
case .external, .unknown: nil
}
}
var cycles: Int?
var health: Double?
}
@@ -19,7 +27,11 @@ nonisolated struct BatteryMonitor {
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))
return isFresh(at: now)
}
func isFresh(at now: Date) -> Bool {
(0...120).contains(now.timeIntervalSince(updated))
}
}
@@ -42,7 +54,7 @@ nonisolated struct BatteryMonitor {
}
static func positiveMinutes(_ value: Int?) -> Int? {
value.flatMap { $0 > 0 ? $0 : nil }
value.flatMap { (1..<65535).contains($0) ? $0 : nil }
}
static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? {
@@ -77,14 +89,15 @@ nonisolated struct BatteryMonitor {
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())
}
return BatteryMetrics(charge: charge, flow: powerFlow(properties, externalSupply: supply, charging: charging),
minutesRemaining: estimate,
let flow = powerFlow(properties, externalSupply: supply, charging: charging)
let systemMinutes = Self.estimatedMinutes(charging: false, externalPower: supply != false,
sourceMinutes: item[kIOPSTimeToEmptyKey] as? Int, systemSeconds: IOPSGetTimeRemainingEstimate())
let now = Date()
let recentPack = Self.packIsRecent(properties, at: now)
let packMinutes = recentPack && packStamp.isFresh(at: now) ? Self.positiveMinutes(properties["AvgTimeToEmpty"] as? Int) : nil
return BatteryMetrics(charge: charge, flow: flow,
minutesToFull: charging == true ? Self.positiveMinutes(item[kIOPSTimeToFullChargeKey] as? Int) : nil,
minutesToEmpty: systemMinutes ?? packMinutes,
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
}
return nil
@@ -106,6 +119,10 @@ nonisolated struct BatteryMonitor {
return input?.source == .telemetry ? input?.watts : nil
}
private static func packIsRecent(_ properties: [String: Any], at now: Date) -> Bool {
scalar(properties["UpdateTime"]).map { (0...120).contains(now.timeIntervalSince1970 - $0) } ?? true
}
private static func scalar(_ raw: Any?) -> Double? {
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
number.doubleValue.isFinite else { return nil }
@@ -141,8 +158,7 @@ nonisolated struct BatteryMonitor {
// 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 recent = Self.packIsRecent(properties, at: now)
let voltage = properties["Voltage"] ?? pack["Voltage"] ?? pack["AppleRawBatteryVoltage"]
let instant = properties["InstantAmperage"] ?? pack["InstantAmperage"]
let average = properties["Amperage"] ?? pack["Amperage"]
+30 -10
View File
@@ -10,6 +10,7 @@ struct BatteryHistoryLayout {
let range: ClosedRange<CGFloat>
let charge: Double?
let joinsPrevious: Bool
let batteryFraction: Double?
let state: BatteryPowerFlow.State
}
struct SleepBand {
@@ -50,7 +51,8 @@ struct BatteryHistoryLayout {
let charge = sample.battery.flatMap { (0...1).contains($0) ? $0 : nil }
if charge != nil || sample.powerFlow != nil {
bars.append(Bar(index: i, x: (left + right) / 2, range: left...right,
charge: charge, joinsPrevious: continuous, state: sample.powerFlow?.state ?? .unknown))
charge: charge, joinsPrevious: continuous, batteryFraction: sample.powerFlow?.jointSupply?.batteryFraction,
state: sample.powerFlow?.state ?? .unknown))
}
guard let previous, elapsed > 0, left > -pitch else { break }
right = left
@@ -134,8 +136,7 @@ private extension BatteryPowerFlow.State {
switch self {
case .battery, .discharging: (NSColor(named: "MetricBattery") ?? .systemGreen, "battery.50percent")
case .charging: (NSColor(named: "BatteryExternal") ?? .systemBlue, "bolt.fill")
case .external: (NSColor(named: "BatteryExternal") ?? .systemBlue, "powerplug.fill")
case .combined: (NSColor(named: "BatteryExternal") ?? .systemBlue, "plus.circle.fill")
case .external, .combined: (NSColor(named: "BatteryExternal") ?? .systemBlue, "powerplug.fill")
case .unknown: (.secondaryLabelColor, "questionmark")
}
}
@@ -212,10 +213,20 @@ final class BatteryHistoryPlot: NSView {
}
let range = bar.range.lowerBound...bars[end].range.upperBound
let style = bar.state.style
drawSymbol(style.symbol, color: style.color, in: range)
if bar.state == .combined {
let left = max(range.lowerBound, 0), right = min(range.upperBound, layoutData.width)
if right - left >= 12 {
let mid = (left + right) / 2
drawSymbol(style.symbol, color: style.color, in: left...mid, minimumWidth: 6)
drawSymbol("battery.50percent", color: NSColor(named: "MetricBattery") ?? .systemGreen,
in: mid...right, minimumWidth: 6)
}
} else {
drawSymbol(style.symbol, color: style.color, in: range)
}
for item in bars[start...end] {
column(at: item.x, width: columnWidth, height: item.charge.map { $0 * baseline },
baseline: baseline, color: style.color)
baseline: baseline, color: style.color, batteryFraction: item.batteryFraction)
}
start = end + 1
}
@@ -238,7 +249,7 @@ final class BatteryHistoryPlot: NSView {
}
}
private func column(at x: CGFloat, width: CGFloat, height: CGFloat?, baseline: CGFloat, color: NSColor) {
private func column(at x: CGFloat, width: CGFloat, height: CGFloat?, baseline: CGFloat, color: NSColor, batteryFraction: Double? = nil) {
let track = CGRect(x: x - width / 2, y: 0, width: width, height: baseline)
let radius = min(width, baseline) / 2
if (height ?? 0) < baseline {
@@ -249,15 +260,24 @@ final class BatteryHistoryPlot: NSView {
let fill = CGRect(x: track.minX, y: baseline - height, width: width, height: height)
let fillRadius = min(radius, height / 2)
color.setFill()
NSBezierPath(roundedRect: fill, xRadius: fillRadius, yRadius: fillRadius).fill()
let path = NSBezierPath(roundedRect: fill, xRadius: fillRadius, yRadius: fillRadius)
path.fill()
if let batteryFraction {
NSGraphicsContext.saveGraphicsState()
path.addClip()
(NSColor(named: "MetricBattery") ?? .systemGreen).setFill()
let greenHeight = height * batteryFraction
NSBezierPath(rect: CGRect(x: fill.minX, y: baseline - greenHeight, width: width, height: greenHeight)).fill()
NSGraphicsContext.restoreGraphicsState()
}
}
private func drawSymbol(_ symbol: String, color: NSColor, in range: ClosedRange<CGFloat>) {
private func drawSymbol(_ symbol: String, color: NSColor, in range: ClosedRange<CGFloat>, minimumWidth: CGFloat = 13) {
let visibleLeft = max(0, range.lowerBound)
let visibleWidth = min(layoutData.width, range.upperBound) - visibleLeft
guard visibleWidth >= 13, let image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)?
guard visibleWidth >= minimumWidth, let image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)?
.withSymbolConfiguration(.init(paletteColors: [color])) else { return }
let scale = min(11 / image.size.width, 9 / image.size.height)
let scale = min(min(11, visibleWidth) / image.size.width, 9 / image.size.height)
let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
let icon = CGRect(x: visibleLeft + (visibleWidth - size.width) / 2,
y: bounds.maxY - 5.5 - size.height / 2, width: size.width, height: size.height)
+47 -21
View File
@@ -27,17 +27,18 @@ struct PowerResourceCard: View {
}
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"
var rows: [(String, String)]
if let joint = flow.jointSupply {
let load = flow.load ?? PowerReading(watts: joint.adapter.watts + joint.discharge.watts, source: .balance)
rows = [("power.adapterContribution", formatted(joint.adapter)),
("power.batteryContribution", formatted(joint.discharge)),
("power.load", formatted(load))]
} else {
let batteryLabel = flow.battery?.source == .average ? "power.averageBattery" : "battery.power"
rows = [(batteryLabel, formatted(flow.battery, signed: true)), ("power.load", formatted(flow.load))]
if flow.connected != false { rows.append(("power.input", formatted(flow.input))) }
}
if flow.connected != false { rows.append(("power.capacity", MetricFormat.watts(flow.adapterCapacity))) }
return rows.map { AppLocalization.string($0.0, locale: locale) + " " + $0.1 }.joined(separator: "\n")
}
@@ -66,9 +67,12 @@ struct PowerResourceCard: View {
}
private var batteryPowerCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
let joint = snapshot.battery?.flow.jointSupply
return ResourceCard(
title: "metric.battery", symbol: joint == nil ? "battery.100percent" : "powerplug.fill",
color: Color(joint == nil ? "MetricBattery" : "BatteryExternal"),
value: MetricFormat.percent(snapshot.battery?.charge),
companionIcon: joint == nil ? nil : ("battery.50percent", Color("MetricBattery")),
status: snapshot.battery.map { label($0.flow.state) },
warningText: snapshot.battery.map { Text(verbatim: details($0.flow)) },
chart: {
@@ -81,8 +85,17 @@ struct PowerResourceCard: View {
}
}
) {
InlineMetric("battery.powerShort", formatted(snapshot.battery?.flow.battery, signed: true))
if let joint {
HStack(spacing: 8) {
powerLabel(joint.adapter, symbol: "powerplug.fill", color: "BatteryExternal", title: "power.adapterContribution")
powerLabel(joint.discharge, symbol: "battery.50percent", color: "MetricBattery", title: "power.batteryContribution")
}
.frame(height: 16)
} else {
powerLabel(snapshot.battery?.flow.battery, signed: true, symbol: "battery.50percent",
color: "MetricBattery", title: "battery.power")
.frame(height: 16)
}
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
@@ -91,20 +104,33 @@ struct PowerResourceCard: View {
}
}
}
private func powerLabel(_ reading: PowerReading?, signed: Bool = false, symbol: String,
color: String, title: LocalizedStringKey) -> some View {
let value = formatted(reading, signed: signed)
return Label {
Text(verbatim: value).monospacedDigit()
} icon: {
Image(systemName: symbol).foregroundStyle(Color(color))
}
.accessibilityLabel(Text(title)).accessibilityValue(Text(verbatim: value))
.help(Text(title))
}
private func batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
InlineMetric("battery.healthShort", MetricFormat.percent(battery.health))
InlineMetric("battery.cyclesShort", battery.cycles.map(String.init) ?? "--")
}
HStack(spacing: 4) {
Text(battery.flow.charging == true ? "battery.timeToFull" : "battery.timeShort").foregroundStyle(.secondary)
if let minutes = battery.minutesRemaining {
Text("duration.minutes \(minutes)").monospacedDigit()
} else if battery.flow.state == .external && battery.flow.charging != true {
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
} else {
Text("battery.timeUnknown")
if battery.flow.state != .external {
HStack(spacing: 4) {
Text(battery.flow.state == .charging ? "battery.timeToFull" : "battery.timeEstimate")
.foregroundStyle(.secondary)
if let minutes = battery.minutesRemaining {
Text("duration.minutes \(minutes)").monospacedDigit()
} else {
Text("battery.timeUnknown")
}
}
}
}
+47 -91
View File
@@ -1,6 +1,50 @@
{
"sourceLanguage" : "en",
"strings" : {
"power.adapterContribution": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Adapter supply"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "适配器供电"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "轉接器供電"
}
}
}
},
"power.batteryContribution": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Battery supply"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "电池供电"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "電池供電"
}
}
}
},
"action.about": {
"extractionState": "manual",
"localizations": {
@@ -648,28 +692,6 @@
}
}
},
"battery.timeShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Time left"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "剩余时间"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "剩餘時間"
}
}
}
},
"battery.timeToFull" : {
"localizations": {
"en": {
@@ -692,28 +714,6 @@
}
}
},
"battery.powerShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Power"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "功率"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "功率"
}
}
}
},
"memory.appShort" : {
"localizations": {
"en": {
@@ -824,28 +824,6 @@
}
}
},
"battery.notApplicableShort" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "N/A"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "不适用"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "不適用"
}
}
}
},
"panel.power" : {
"localizations" : {
"zh-Hans" : {
@@ -1704,41 +1682,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Battery life estimate"
"value" : "Estimated runtime"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "续航预估"
"value" : "预估续航"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "續航預估"
}
}
}
},
"battery.timeNotApplicable" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Not applicable on AC"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "外接电源,不适用"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "外接電源,不適用"
"value" : "預估續航"
}
}
}
+7 -1
View File
@@ -11,6 +11,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
let symbol: String
let color: Color
let value: String
var companionIcon: (symbol: String, color: Color)? = nil
var secondaryValue: String? = nil
var valueColor: Color? = nil
var secondaryValueColor: Color? = nil
@@ -90,7 +91,12 @@ struct ResourceCard<Chart: View, Content: View>: View {
Label {
Text(title).foregroundStyle(statusWarning ? .red : .primary)
} icon: {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
HStack(spacing: 1) {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
if let companionIcon {
Image(systemName: companionIcon.symbol).foregroundStyle(companionIcon.color)
}
}
}
.font(.system(size: 11, weight: .semibold)).fixedSize()
if let titleBadge {