Files
Kymo/kymo/Features/MenuBar/BatteryHistoryChart.swift
wangairnan 451d31682d fix(power): 完善电池卡片的共同供电判定、功率图标与预估续航
按适配器和电池的实际贡献判定共同供电,以双图标和双色柱展示两路功率。同步三语预估续航文案,在仅外接供电时隐藏估时行。
2026-11-16 15:06:02 +08:00

287 lines
13 KiB
Swift

import AppKit
import SwiftUI
/// The same time ranges drive drawing and hover. A gap only acquires a sleep
/// marker when it overlaps an observed system sleep/wake pair.
struct BatteryHistoryLayout {
struct Bar {
let index: Int
let x: CGFloat
let range: ClosedRange<CGFloat>
let charge: Double?
let joinsPrevious: Bool
let batteryFraction: Double?
let state: BatteryPowerFlow.State
}
struct SleepBand {
let interval: DateInterval
let chargeBeforeSleep: Double?
let range: ClosedRange<CGFloat>
}
enum Hit: Equatable {
case sample(Int)
case sleep(DateInterval)
}
private(set) var bars: [Bar] = []
private(set) var sleeps: [SleepBand] = []
let width: CGFloat
let pitch: CGFloat
let newest: Date?
private(set) var previousContinuousDate: Date?
init(samples: [TrendSample], sleeps: [DateInterval], width: CGFloat) {
self.width = width
// Keep one outgoing sample available beyond the viewport at capacity.
pitch = max(4, width / CGFloat(MetricHistory.capacity - 1))
newest = samples.last?.date
guard width > 0 else { return }
var right = width
for i in samples.indices.reversed() {
let sample = samples[i]
let left = right - pitch
let previous = i > 0 ? samples[i - 1] : nil
let elapsed = previous.map { sample.date.timeIntervalSince($0.date) } ?? 0
let continuous = elapsed > 0 && !sample.breakBefore
&& elapsed <= max(5, 2 * (previous?.expectedInterval ?? 0))
if i == samples.count - 1 && continuous { previousContinuousDate = previous?.date }
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, batteryFraction: sample.powerFlow?.jointSupply?.batteryFraction,
state: sample.powerFlow?.state ?? .unknown))
}
guard let previous, elapsed > 0, left > -pitch else { break }
right = left
if !continuous {
// Reserve a separate gap without spreading the surrounding samples.
let gap = max(20, 5 * pitch)
right -= gap
for interval in sleeps {
let begin = max(previous.date, interval.start)
let end = min(sample.date, interval.end)
guard end > begin else { continue }
let x1 = right + gap * begin.timeIntervalSince(previous.date) / elapsed
let x2 = right + gap * end.timeIntervalSince(previous.date) / elapsed
self.sleeps.append(SleepBand(interval: interval, chargeBeforeSleep: previous.battery, range: x1...x2))
}
}
}
bars.reverse()
}
func hit(at x: CGFloat) -> Hit? {
if let band = sleeps.first(where: { $0.range.lowerBound <= x && x < $0.range.upperBound }) {
return .sleep(band.interval)
}
return bars.last(where: { $0.range.contains(x) }).map { .sample($0.index) }
}
}
struct BatteryHistoryChart<Detail: View>: View {
let samples: [TrendSample]
let sleeps: [DateInterval]
@ViewBuilder let detail: (TrendSample) -> Detail
@Environment(\.panelMotionActive) private var active
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var pointer: CGPoint?
var body: some View {
GeometryReader { proxy in
let layout = BatteryHistoryLayout(samples: samples, sleeps: sleeps, width: proxy.size.width)
BatteryHistoryDrawing(layout: layout, hit: pointer.flatMap { layout.hit(at: $0.x) },
animates: active && !reduceMotion && pointer == nil)
.contentShape(Rectangle())
.onContinuousHover { phase in
switch phase {
case .active(let point): pointer = point
case .ended: pointer = nil
}
}
.anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { anchor in
guard let pointer, let hit = layout.hit(at: pointer.x) else { return nil }
return ChartTooltipPresentation(plot: anchor, point: pointer, content: AnyView(tooltip(hit)))
}
}
.padding(.horizontal, 8)
.padding(.bottom, 4)
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text("metric.battery"))
.accessibilityValue(Text(verbatim: MetricFormat.percent(samples.last?.battery)))
}
private func tooltip(_ hit: BatteryHistoryLayout.Hit) -> some View {
VStack(alignment: .leading, spacing: 2) {
switch hit {
case .sleep(let interval):
Label("power.sleep", systemImage: "moon.fill").bold()
Text(interval.start..<interval.end, format: .interval.hour().minute())
case .sample(let index):
let sample = samples[index]
Text(sample.date, format: .dateTime.hour().minute().second()).foregroundStyle(.secondary)
detail(sample)
}
}
.font(.system(size: 9)).padding(6)
.background { TooltipBackground() }
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
}
}
private extension BatteryPowerFlow.State {
var style: (color: NSColor, symbol: String) {
switch self {
case .battery, .discharging: (NSColor(named: "MetricBattery") ?? .systemGreen, "battery.50percent")
case .charging: (NSColor(named: "BatteryExternal") ?? .systemBlue, "bolt.fill")
case .external, .combined: (NSColor(named: "BatteryExternal") ?? .systemBlue, "powerplug.fill")
case .unknown: (.secondaryLabelColor, "questionmark")
}
}
}
private struct BatteryHistoryDrawing: NSViewRepresentable {
let layout: BatteryHistoryLayout
let hit: BatteryHistoryLayout.Hit?
let animates: Bool
func makeNSView(context: Context) -> BatteryHistoryViewport { BatteryHistoryViewport() }
func updateNSView(_ viewport: BatteryHistoryViewport, context: Context) {
viewport.update(layout, hit: hit, animates: animates)
}
}
final class BatteryHistoryViewport: NSView {
let plot = BatteryHistoryPlot()
static let slideKey = "battery.slide"
init() {
super.init(frame: .zero)
wantsLayer = true
layer?.masksToBounds = true
plot.wantsLayer = true
addSubview(plot)
}
required init?(coder: NSCoder) { nil }
override func layout() {
super.layout()
let pitch = plot.layoutData.pitch
plot.frame = CGRect(x: -pitch, y: 0, width: bounds.width + pitch, height: bounds.height)
plot.setBoundsOrigin(CGPoint(x: -pitch, y: 0))
}
func update(_ value: BatteryHistoryLayout, hit: BatteryHistoryLayout.Hit?, animates: Bool) {
let old = plot.layoutData
let appended = value.newest != old.newest
let resized = value.width != old.width
plot.layoutData = value
plot.hit = hit
plot.needsDisplay = true
if resized { needsLayout = true }
if appended || resized || !animates { plot.layer?.removeAnimation(forKey: Self.slideKey) }
guard appended, !resized, animates, window?.isVisible == true,
let previous = value.previousContinuousDate, previous == old.newest else { return }
let slide = CABasicAnimation(keyPath: "transform.translation.x")
slide.fromValue = value.pitch
slide.toValue = 0
slide.duration = 0.35
slide.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
plot.layer?.add(slide, forKey: Self.slideKey)
}
}
final class BatteryHistoryPlot: NSView {
var layoutData = BatteryHistoryLayout(samples: [], sleeps: [], width: 0)
var hit: BatteryHistoryLayout.Hit?
override var isFlipped: Bool { true }
override func draw(_ dirtyRect: NSRect) {
let baseline = bounds.height - 11
guard baseline > 0 else { return }
let bars = layoutData.bars
let columnWidth = min(5, layoutData.pitch * 0.72)
var start = 0
while start < bars.count {
let bar = bars[start]
var end = start
while end + 1 < bars.count, bars[end + 1].state == bar.state,
bars[end + 1].index == bars[end].index + 1,
bars[end + 1].joinsPrevious {
end += 1
}
let range = bar.range.lowerBound...bars[end].range.upperBound
let style = bar.state.style
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, batteryFraction: item.batteryFraction)
}
start = end + 1
}
for sleep in layoutData.sleeps {
let color = NSColor(named: "MetricDisk") ?? .systemOrange
drawSymbol("moon.fill", color: color, in: sleep.range)
let span = sleep.range.upperBound - sleep.range.lowerBound
let pitch = layoutData.pitch
let count = max(1, Int((span / pitch).rounded()))
let margin = (span - CGFloat(count - 1) * pitch) / 2
let height = sleep.chargeBeforeSleep.flatMap { (0...1).contains($0) ? $0 * baseline : nil } ?? 4
for i in 0..<count {
column(at: sleep.range.lowerBound + margin + CGFloat(i) * pitch,
width: min(columnWidth, 2 * margin), height: height, baseline: baseline, color: color)
}
}
if case .sample(let index) = hit, let bar = bars.first(where: { $0.index == index }), let charge = bar.charge {
NSColor.labelColor.setFill()
NSBezierPath(ovalIn: CGRect(x: bar.x - 2, y: baseline * (1 - charge) - 2, width: 4, height: 4)).fill()
}
}
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 {
color.withAlphaComponent(0.22).setFill()
NSBezierPath(roundedRect: track, xRadius: radius, yRadius: radius).fill()
}
guard let height, height > 0 else { return }
let fill = CGRect(x: track.minX, y: baseline - height, width: width, height: height)
let fillRadius = min(radius, height / 2)
color.setFill()
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>, minimumWidth: CGFloat = 13) {
let visibleLeft = max(0, range.lowerBound)
let visibleWidth = min(layoutData.width, range.upperBound) - visibleLeft
guard visibleWidth >= minimumWidth, let image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)?
.withSymbolConfiguration(.init(paletteColors: [color])) else { return }
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)
image.draw(in: icon, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
}
}