feat(menubar): 用分色进度柱展示电量、供电与睡眠历史
记录系统睡眠和唤醒区间,保留真实采样空档。电量柱按固定间距从右侧滑入,以蓝色、绿色和橙黄色分别标记外接电源、电池和睡眠,支持悬浮查看历史。
This commit is contained in:
@@ -0,0 +1,266 @@
|
||||
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 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, 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: (NSColor(named: "BatteryExternal") ?? .systemBlue, "powerplug.fill")
|
||||
case .combined: (NSColor(named: "BatteryExternal") ?? .systemBlue, "plus.circle.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
|
||||
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)
|
||||
}
|
||||
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) {
|
||||
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()
|
||||
NSBezierPath(roundedRect: fill, xRadius: fillRadius, yRadius: fillRadius).fill()
|
||||
}
|
||||
|
||||
private func drawSymbol(_ symbol: String, color: NSColor, in range: ClosedRange<CGFloat>) {
|
||||
let visibleLeft = max(0, range.lowerBound)
|
||||
let visibleWidth = min(layoutData.width, range.upperBound) - visibleLeft
|
||||
guard visibleWidth >= 13, 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 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)
|
||||
}
|
||||
}
|
||||
@@ -166,7 +166,7 @@ extension MenuPanelView {
|
||||
}
|
||||
}
|
||||
var batteryCard: some View {
|
||||
PowerResourceCard(snapshot: snapshot, samples: samples, chartInterval: chartInterval,
|
||||
PowerResourceCard(snapshot: snapshot, samples: samples, sleepIntervals: metrics.history.sleepIntervals, chartInterval: chartInterval,
|
||||
chartBoundaries: chartBoundaries, chartIntervals: chartIntervals)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ import AppKit
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
@MainActor func plots(in view: NSView?) -> [NativePanelCurve.PlotView] {
|
||||
@MainActor func plots(in view: NSView?) -> [NSView] {
|
||||
guard let view else { return [] }
|
||||
let own = (view as? NativePanelCurve.PlotView).map { [$0] } ?? []
|
||||
let own = view is NativePanelCurve.PlotView || view is BatteryHistoryViewport ? [view] : []
|
||||
return own + view.subviews.flatMap { plots(in: $0) }
|
||||
}
|
||||
@MainActor func mark(_ event: String) {
|
||||
@@ -27,7 +27,7 @@ import AppKit
|
||||
let views = plots(in: controller.panel.contentView)
|
||||
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil,
|
||||
windowNumber: controller.panel.isVisible ? controller.panel.windowNumber : nil,
|
||||
hoveredPlots: views.filter { $0.input?.hoveredIndex != nil }.count, nativePlots: views.count,
|
||||
hoveredPlots: views.filter { ($0 as? NativePanelCurve.PlotView)?.input?.hoveredIndex != nil || ($0 as? BatteryHistoryViewport)?.plot.hit != nil }.count, nativePlots: views.count,
|
||||
pointerInsidePanel: controller.panel.isVisible && controller.panel.frame.contains(NSEvent.mouseLocation),
|
||||
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] })
|
||||
if event == "open1.10", ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1",
|
||||
|
||||
@@ -3,6 +3,7 @@ import SwiftUI
|
||||
struct PowerResourceCard: View {
|
||||
let snapshot: MetricsSnapshot
|
||||
let samples: [TrendSample]
|
||||
let sleepIntervals: [DateInterval]
|
||||
let chartInterval: TimeInterval
|
||||
let chartBoundaries: Set<Date>
|
||||
let chartIntervals: [TimeInterval]
|
||||
@@ -70,22 +71,14 @@ struct PowerResourceCard: View {
|
||||
value: MetricFormat.percent(snapshot.battery?.charge),
|
||||
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),
|
||||
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
|
||||
)
|
||||
BatteryHistoryChart(samples: samples, sleeps: sleepIntervals) { sample in
|
||||
let flow = sample.powerFlow ?? BatteryPowerFlow()
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(verbatim: MetricFormat.percent(sample.battery) + " · " + label(flow.state)).bold()
|
||||
Text(verbatim: details(flow)).monospacedDigit()
|
||||
}
|
||||
}
|
||||
}
|
||||
) {
|
||||
InlineMetric("battery.powerShort", formatted(snapshot.battery?.flow.battery, signed: true))
|
||||
|
||||
Reference in New Issue
Block a user