Files
Kymo/kymo/UI/Charts/NativePanelCurve.swift
T
wangairnan 4b8deb2e48 feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
2026-11-15 23:54:19 +08:00

281 lines
15 KiB
Swift

import AppKit
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)
}
}
}
/// Bounded lines and per-run area paths. Hover never rebuilds geometry.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
var animates = false
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
}
func makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked, projection: projection, animates: animates))
}
struct Input: Equatable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
var animates = false
}
final class PlotView: NSView {
private(set) var input: Input?
private(set) var pathBuildCount = 0
let grid = CAShapeLayer()
let baseline = CAShapeLayer()
let curves = CALayer()
let hoverLine = CAShapeLayer()
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = []
private var drawingFrame: PanelCurveFrame?
private static let slideKey = "trend.slide"
private var plottedBands: [StackedSeries.Band] = []
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
super.init(frame: .zero)
wantsLayer = true
layer?.masksToBounds = true
curves.anchorPoint = .zero
grid.fillColor = nil; grid.lineWidth = 0.5
grid.isHidden = true
hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2]
baseline.fillColor = nil; baseline.lineWidth = 0.5; baseline.isHidden = true
for child in [grid, baseline, curves, hoverLine] { layer?.addSublayer(child) }
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard input != value else { return }
let old = input
let frameChanged = old?.frame != value.frame
let slides = value.animates && value.hoveredIndex == nil && window?.isVisible == true
&& frameChanged && old.map { value.frame.follows($0.frame, maximumGap: value.maximumGap) } == true
input = value
if frameChanged || !value.animates || value.hoveredIndex != nil {
curves.removeAnimation(forKey: Self.slideKey)
}
if frameChanged {
drawingFrame = slides ? old.map { value.frame.includingOutgoing(from: $0.frame) } : nil
}
CATransaction.begin(); CATransaction.setDisableActions(true)
if old?.projection != value.projection { updateBaseline() }
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count
|| old?.filledSeriesCount != value.filledSeriesCount { updatePalette() }
for index in seriesLayers.indices {
seriesLayers[index].root.isHidden = index >= (value.visibleSeriesCount ?? value.frame.series.count)
}
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked || old?.projection != value.projection {
rebuildPaths()
}
updateHover()
if slides, let old { slide(from: old.frame, to: value.frame) }
CATransaction.commit()
}
private func slide(from previous: PanelCurveFrame, to next: PanelCurveFrame) {
guard bounds.width > 0, let a = previous.dates.first, let b = previous.dates.last,
let c = next.dates.first, let d = next.dates.last else { return }
// Map the new geometry onto the old time domain, then reveal the new point.
let span = b.timeIntervalSince(a)
let transform = CGAffineTransform(a: d.timeIntervalSince(c) / span, b: 0, c: 0, d: 1,
tx: c.timeIntervalSince(a) / span * bounds.width, ty: 0)
let animation = CABasicAnimation(keyPath: "transform")
animation.fromValue = NSValue(caTransform3D: CATransform3DMakeAffineTransform(transform))
animation.toValue = NSValue(caTransform3D: CATransform3DIdentity)
animation.duration = 0.35
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
curves.add(animation, forKey: Self.slideKey)
}
private func ensureLayers(_ count: Int) {
while seriesLayers.count < count {
let series = SeriesLayer(); seriesLayers.append(series); curves.addSublayer(series.root)
let dot = CAShapeLayer(); hoverDots.append(dot); layer?.addSublayer(dot)
}
while seriesLayers.count > count {
seriesLayers.removeLast().root.removeFromSuperlayer()
hoverDots.removeLast().removeFromSuperlayer()
}
}
private func updatePalette() {
effectiveAppearance.performAsCurrentDrawingAppearance {
palette = input?.colors.map(NSColor.init) ?? []
baseline.strokeColor = NSColor.labelColor.withAlphaComponent(0.12).cgColor
grid.strokeColor = NSColor.labelColor.withAlphaComponent(0.10).cgColor
hoverLine.strokeColor = NSColor.labelColor.withAlphaComponent(0.45).cgColor
guard !palette.isEmpty else { return }
for index in seriesLayers.indices {
let color = palette[min(index, palette.count - 1)], series = seriesLayers[index]
series.line.strokeColor = color.cgColor; series.points.fillColor = color.cgColor
let dark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
series.area.fillColor = index < (input?.filledSeriesCount ?? 0)
? color.withAlphaComponent(dark ? 0.16 : 0.12).cgColor : nil
hoverDots[index].fillColor = color.cgColor
}
}
}
private func updateBaseline() {
baseline.frame = bounds
baseline.isHidden = input?.projection == .fullHeight || input == nil
let path = CGMutablePath()
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() {
updateBaseline()
grid.frame = bounds; hoverLine.frame = bounds
curves.bounds = bounds; curves.position = .zero
let path = CGMutablePath()
for step in 0...10 {
let x = bounds.width * Double(step) / 10
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height))
}
for step in 0...2 {
let y = bounds.height * Double(step) / 2
path.move(to: CGPoint(x: 0, y: y)); path.addLine(to: CGPoint(x: bounds.width, y: y))
}
grid.path = path
}
private func rebuildPaths() {
pathBuildCount += 1
guard let input, let first = input.frame.dates.first, let last = input.frame.dates.last,
!input.scales.isEmpty else {
for series in seriesLayers { series.clear() }
return
}
let domain = PanelCurveFrame.domain(begin: first, end: last)
let frame = drawingFrame ?? input.frame
plottedBands = input.stacked ? StackedSeries.bands(frame.series, count: frame.dates.count, limit: input.scales.first) : []
for index in frame.series.indices {
let series = seriesLayers[index]
series.resize(bounds)
let value = input.scales[input.stacked ? 0 : min(index, input.scales.count - 1)]
let scale = value.isFinite && value > 0 ? value : 1
let upper = input.stacked ? plottedBands[index].upper : frame.series[index]
let lower = input.stacked ? plottedBands[index].lower : nil
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: upper, maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals, lowerValues: lower)
let line = CGMutablePath(), dots = CGMutablePath(), area = CGMutablePath()
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: input.projection.y(value: $0.value, scale: scale, series: index, height: bounds.height)) }
guard let start = points.first else { continue }
if points.count == 1 {
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
}
let segment = CGMutablePath(); segment.move(to: start)
for (a, b) in zip(points, points.dropFirst()) {
let mid = (a.x + b.x) / 2
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
line.addPath(segment)
// Close against the matching lower boundary, never against another run or missing component.
let lowerPoints = run.reversed().map { CGPoint(x: bounds.width * domain.position($0.date),
y: input.projection.y(value: $0.lower, scale: scale, series: index, height: bounds.height)) }
let fill = CGMutablePath(); fill.addPath(segment)
if let lowerStart = lowerPoints.first { fill.addLine(to: lowerStart) }
for (a, b) in zip(lowerPoints, lowerPoints.dropFirst()) {
let mid = (a.x + b.x) / 2
fill.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
fill.closeSubpath(); area.addPath(fill)
}
series.line.path = line
series.points.path = dots
series.area.path = area
}
}
private func updateHover() {
for dot in hoverDots { dot.path = nil; dot.frame = bounds }
hoverLine.path = nil
guard let input, !input.colors.isEmpty, let index = input.hoveredIndex, input.frame.dates.indices.contains(index),
let first = input.frame.dates.first, let last = input.frame.dates.last, last > first, !input.scales.isEmpty else { return }
let domain = PanelCurveFrame.domain(begin: first, end: last)
let x = bounds.width * domain.position(input.frame.dates[index])
let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path
for series in input.frame.series.indices {
guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
let plottedIndex = index + (input.stacked ? (drawingFrame?.dates.count ?? input.frame.dates.count) - input.frame.dates.count : 0)
guard values.indices.contains(plottedIndex), let value = values[plottedIndex], value.isFinite else { continue }
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
let y = input.projection.y(value: value, scale: scale, series: series, height: bounds.height)
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
}
}
override func setFrameSize(_ size: NSSize) {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
curves.removeAnimation(forKey: Self.slideKey)
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { curves.removeAnimation(forKey: Self.slideKey) }
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance()
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
private final class SeriesLayer {
let root = CALayer(), area = CAShapeLayer(), line = CAShapeLayer(), points = CAShapeLayer()
init() {
line.fillColor = nil; line.lineWidth = 1.4; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(area); root.addSublayer(line); root.addSublayer(points)
}
func resize(_ bounds: CGRect) {
root.frame = bounds
let local = CGRect(origin: .zero, size: bounds.size)
area.frame = local; line.frame = local; points.frame = local
}
func clear() { area.path = nil; line.path = nil; points.path = nil }
}
}
}