perf(menubar): 降低绘制驻留并复用原生进程表与缩略图

This commit is contained in:
2026-11-04 10:39:15 +08:00
parent 1c26fc18f3
commit 065c53622a
28 changed files with 964 additions and 160 deletions
+130
View File
@@ -0,0 +1,130 @@
import AppKit
import SwiftUI
/// A bounded native plot; SwiftUI still owns axes, legends and hover presentation.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
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))
}
struct Input: Equatable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
}
final class PlotView: NSView {
private(set) var input: Input?
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
super.init(frame: .zero)
wantsLayer = true
layerContentsRedrawPolicy = .onSetNeedsDisplay
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard input != value else { return }
input = value
needsDisplay = true
}
override func setFrameSize(_ newSize: NSSize) {
let changed = frame.size != newSize
super.setFrameSize(newSize)
if changed { needsDisplay = true }
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance()
needsDisplay = true
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current?.cgContext else { return }
context.saveGState()
defer { context.restoreGState() }
context.clip(to: bounds)
context.setLineWidth(0.5)
context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.10).cgColor)
for step in 0...10 {
let x = bounds.width * Double(step) / 10
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height))
}
for step in 0...2 {
let y = bounds.height * Double(step) / 2
context.move(to: CGPoint(x: 0, y: y)); context.addLine(to: CGPoint(x: bounds.width, y: y))
}
context.strokePath()
guard let input, let first = input.frame.dates.first, let last = input.frame.dates.last,
!input.colors.isEmpty, !input.scales.isEmpty else { return }
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
for index in input.frame.series.indices {
let tint = NSColor(input.colors[min(index, input.colors.count - 1)])
let proposedScale = input.scales[min(index, input.scales.count - 1)]
let scale = proposedScale.isFinite && proposedScale > 0 ? proposedScale : 1
let runs = PanelCurveGeometry.runs(dates: input.frame.dates, values: input.frame.series[index],
maximumGap: input.maximumGap, boundaryDates: input.frame.boundaryDates, intervals: input.frame.intervals)
context.setFillColor(tint.cgColor)
context.setStrokeColor(tint.cgColor)
context.setLineWidth(1.5)
context.setLineCap(.round); context.setLineJoin(.round)
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) }
guard let start = points.first, let finish = points.last else { continue }
if points.count == 1 {
context.fillEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4))
continue
}
let line = CGMutablePath(); line.move(to: start)
for (a, b) in zip(points, points.dropFirst()) {
let middle = (a.x + b.x) / 2
line.addCurve(to: b, control1: CGPoint(x: middle, y: a.y), control2: CGPoint(x: middle, y: b.y))
}
let area = line.mutableCopy()!
area.addLine(to: CGPoint(x: finish.x, y: bounds.height))
area.addLine(to: CGPoint(x: start.x, y: bounds.height)); area.closeSubpath()
if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB),
colors: [tint.withAlphaComponent(0.20).cgColor, tint.withAlphaComponent(0.01).cgColor] as CFArray,
locations: [0, 1]) {
context.saveGState(); context.addPath(area); context.clip()
context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: bounds.height), options: [])
context.restoreGState()
}
context.addPath(line); context.strokePath()
}
}
if let index = input.hoveredIndex, input.frame.dates.indices.contains(index), last > first {
let x = bounds.width * domain.position(input.frame.dates[index])
context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.45).cgColor)
context.setLineWidth(1); context.setLineDash(phase: 0, lengths: [3, 2])
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height)); context.strokePath()
context.setLineDash(phase: 0, lengths: [])
for series in input.frame.series.indices {
let values = input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let scale = input.scales[min(series, input.scales.count - 1)]
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
context.setFillColor(NSColor(input.colors[min(series, input.colors.count - 1)]).cgColor)
context.fillEllipse(in: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5))
}
}
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
import Foundation
/// A render frame may keep one outgoing point beyond the bounded 60-sample history.
nonisolated struct PanelCurveFrame {
nonisolated struct PanelCurveFrame: Equatable {
let dates: [Date]
let series: [[Double?]]
let intervals: [TimeInterval]
+2 -78
View File
@@ -123,25 +123,9 @@ struct PanelTrendChart: View {
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight)
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale],
maximumGap: max(5, expectedInterval * 2),
targetBegin: dates.first, targetEnd: dates.last,
previousBegin: nil, previousEnd: nil, progress: 1)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
Path { path in
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: proxy.size.height))
}.stroke(.primary.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [3, 2]))
ForEach(0..<4, id: \.self) { series in
let values = [first, second, third, fourth][series]
if index < values.count, let value = values[index], value.isFinite {
let seriesScale = [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale][series]
Circle().fill([color, secondColor, thirdColor, fourthColor][series]).frame(width: 5, height: 5)
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / seriesScale))))
}
}
}
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index)
}
.contentShape(Rectangle())
.onContinuousHover { phase in
@@ -199,63 +183,3 @@ struct PanelTrendChart: View {
.accessibilityElement(children: .combine)
}
}
private struct PanelCurveCanvas: View, Animatable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
let targetBegin: Date?
let targetEnd: Date?
let previousBegin: Date?
let previousEnd: Date?
var progress: CGFloat
var animatableData: CGFloat {
get { progress }
set { progress = newValue }
}
var body: some View {
Canvas { context, size in
var grid = Path()
for step in 0...10 {
let x = size.width * Double(step) / 10
grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: size.height))
}
for step in 0...2 {
let y = size.height * Double(step) / 2
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
}
context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5)
guard let first = targetBegin, let last = targetEnd else { return }
let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd,
begin: first, end: last, progress: Double(progress))
for seriesIndex in frame.series.indices {
let values = frame.series[seriesIndex]
let tint = colors[min(seriesIndex, colors.count - 1)]
let scale = scales[min(seriesIndex, scales.count - 1)]
for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) {
let points = run.map { item in
CGPoint(x: size.width * domain.position(item.date),
y: size.height * (1 - min(1, max(0, item.value / scale))))
}
guard let start = points.first, let finish = points.last else { continue }
var line = Path(); line.move(to: start)
for pair in zip(points, points.dropFirst()) {
let middle = (pair.0.x + pair.1.x) / 2
// Horizontal tangents keep the rounded curve between adjacent sample values.
line.addCurve(to: pair.1, control1: CGPoint(x: middle, y: pair.0.y), control2: CGPoint(x: middle, y: pair.1.y))
}
if points.count == 1 {
context.fill(Path(ellipseIn: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)), with: .color(tint))
} else {
var area = line
area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath()
context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
}
}
}
}
}
}