perf(ui): 恢复数字滚动并优化曲线与圆环连续动效

This commit is contained in:
2026-11-04 14:04:05 +08:00
parent f18f6652ff
commit 44f0415ab7
12 changed files with 394 additions and 144 deletions
+163 -86
View File
@@ -1,7 +1,7 @@
import AppKit
import SwiftUI
/// A bounded native plot; SwiftUI still owns axes, legends and hover presentation.
/// Immutable paths plus compositor time-domain transforms preserve the original scrolling curve.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
@@ -11,16 +11,14 @@ struct NativePanelCurve: NSViewRepresentable {
@Environment(\.metricAnimationsEnabled) private var animates
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, animates: animates))
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
hoveredIndex: hoveredIndex, animates: animates))
}
struct Input: Equatable {
let frame: PanelCurveFrame
let colors: [Color]
@@ -29,10 +27,16 @@ struct NativePanelCurve: NSViewRepresentable {
var hoveredIndex: Int? = nil
var animates = false
}
final class PlotView: NSView {
private(set) var input: Input?
private(set) var drawingFrame: PanelCurveFrame?
private(set) var pathBuildCount = 0
let grid = CAShapeLayer()
let curves = CALayer()
let hoverLine = CAShapeLayer()
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = []
private let motion = MetricMotion()
var isAnimating: Bool { motion.isRunning }
override var isFlipped: Bool { true }
@@ -41,116 +45,189 @@ struct NativePanelCurve: NSViewRepresentable {
init() {
super.init(frame: .zero)
wantsLayer = true
layerContentsRedrawPolicy = .onSetNeedsDisplay
layer?.masksToBounds = true
curves.anchorPoint = .zero
grid.fillColor = nil; grid.lineWidth = 0.5
hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2]
for child in [grid, curves, hoverLine] { layer?.addSublayer(child) }
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard input != value else { return }
let previous = input
let changedFrame = previous?.frame != value.frame
let old = input
let frameChanged = old?.frame != value.frame
input = value
// Keep hover updates from restarting an existing transition.
drawingFrame = value.frame
if !value.animates { motion.stop() }
else if changedFrame {
let animate = value.animates && !value.colors.isEmpty && !value.scales.isEmpty && window != nil && frameChanged && old.map {
guard let end = value.frame.dates.last, !value.frame.boundaryDates.contains(end) else { return false }
return PanelCurveGeometry.isAppend(from: $0.frame.dates, to: value.frame.dates, maximumGap: value.maximumGap)
} == true
CATransaction.begin(); CATransaction.setDisableActions(true)
if frameChanged {
motion.stop()
if window != nil, let previous, let end = value.frame.dates.last,
!value.frame.boundaryDates.contains(end),
PanelCurveGeometry.isAppend(from: previous.frame.dates, to: value.frame.dates,
maximumGap: value.maximumGap) {
motion.start(on: layer)
drawingFrame = animate ? PanelCurveFrame.transition(from: old!.frame, to: value.frame) : value.frame
} else if !value.animates {
motion.stop(); drawingFrame = value.frame
}
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors { updatePalette() }
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || !value.animates && old?.animates == true {
rebuildPaths()
}
updateHover()
CATransaction.commit()
if animate, let old { startMovement(from: old.frame, to: value.frame) }
}
private func startMovement(from old: PanelCurveFrame, to next: PanelCurveFrame) {
guard let a = old.dates.first, let b = old.dates.last,
let c = next.dates.first, let d = next.dates.last else { return }
let previous = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: a, end: b, progress: 1)
let target = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: c, end: d, progress: 1)
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.calculationMode = .linear
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.keyTimes = (0...60).map { NSNumber(value: Double($0) / 60) }
animation.values = (0...60).map { step in
let p = MetricMotion.easeInOut(Double(step) / 60)
let map = PanelCurveFrame.horizontalTransform(from: previous, to: target, progress: p, width: bounds.width)
let transform = CGAffineTransform(a: map.scale, b: 0, c: 0, d: 1, tx: map.translation, ty: 0)
return NSValue(caTransform3D: CATransform3DMakeAffineTransform(transform))
}
motion.start(on: curves, animation: animation)
}
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) ?? []
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
series.gradient.colors = [color.withAlphaComponent(0.20).cgColor, color.withAlphaComponent(0.01).cgColor]
hoverDots[index].fillColor = color.cgColor
}
}
needsDisplay = true
}
private func settle() {
motion.stop(); drawingFrame = input?.frame
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { settle() }
}
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)
private func updateGrid() {
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
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height))
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
context.move(to: CGPoint(x: 0, y: y)); context.addLine(to: CGPoint(x: bounds.width, y: y))
path.move(to: CGPoint(x: 0, y: y)); path.addLine(to: CGPoint(x: bounds.width, y: y))
}
context.strokePath()
grid.path = path
}
private func rebuildPaths() {
pathBuildCount += 1
guard let input, let frame = drawingFrame, let first = input.frame.dates.first, let last = input.frame.dates.last,
!input.colors.isEmpty, !input.scales.isEmpty else { return }
!input.scales.isEmpty else {
for series in seriesLayers { series.clear() }
return
}
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
for index in 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: frame.dates, values: frame.series[index],
maximumGap: input.maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals)
context.setFillColor(tint.cgColor)
context.setStrokeColor(tint.cgColor)
context.setLineWidth(1.5)
context.setLineCap(.round); context.setLineJoin(.round)
let series = seriesLayers[index]
let left = min(0, bounds.width * domain.position(frame.dates.first ?? first))
series.resize(CGRect(x: left, y: 0, width: bounds.width - left, height: bounds.height))
let value = input.scales[min(index, input.scales.count - 1)]
let scale = value.isFinite && value > 0 ? value : 1
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index], maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals)
let line = CGMutablePath(), areas = CGMutablePath(), dots = CGMutablePath()
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 }
guard let start = points.first, let end = 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
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
}
let line = CGMutablePath(); line.move(to: start)
let segment = CGMutablePath(); segment.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 mid = (a.x + b.x) / 2
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, 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()
line.addPath(segment)
segment.addLine(to: CGPoint(x: end.x, y: bounds.height))
segment.addLine(to: CGPoint(x: start.x, y: bounds.height)); segment.closeSubpath()
areas.addPath(segment)
}
var local = CGAffineTransform(translationX: -left, y: 0)
series.line.path = line.copy(using: &local)
series.mask.path = areas.copy(using: &local)
series.points.path = dots.copy(using: &local)
series.gradient.isHidden = areas.isEmpty
}
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))
}
}
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(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
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 {
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))))
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 {
motion.stop(); drawingFrame = input?.frame
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { motion.stop(); drawingFrame = input?.frame }
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(), line = CAShapeLayer(), mask = CAShapeLayer(), points = CAShapeLayer()
let gradient = CAGradientLayer()
init() {
line.fillColor = nil; line.lineWidth = 1.5; line.lineCap = .round; line.lineJoin = .round
mask.fillColor = NSColor.white.cgColor
gradient.startPoint = CGPoint(x: 0.5, y: 0); gradient.endPoint = CGPoint(x: 0.5, y: 1)
gradient.locations = [0, 1]; gradient.mask = mask
root.addSublayer(gradient); root.addSublayer(line); root.addSublayer(points)
}
func resize(_ bounds: CGRect) {
root.frame = bounds
let local = CGRect(origin: .zero, size: bounds.size)
gradient.frame = local; mask.frame = local; line.frame = local; points.frame = local
}
func clear() { line.path = nil; mask.path = nil; points.path = nil }
}
}
}
+16
View File
@@ -21,6 +21,22 @@ nonisolated struct PanelCurveFrame: Equatable {
end: (previousEnd ?? end).timeIntervalSinceReferenceDate * (1 - progress) + end.timeIntervalSinceReferenceDate * progress)
}
struct HorizontalTransform {
let scale: Double
let translation: Double
}
/// Render paths once in the final domain, then map them into the original
/// interpolated time domain. This preserves expansion as well as translation.
static func horizontalTransform(from old: Domain, to target: Domain, progress: Double, width: Double) -> HorizontalTransform {
let p = min(1, max(0, progress))
let begin = old.begin * (1 - p) + target.begin * p
let end = old.end * (1 - p) + target.end * p
let span = end - begin, finalSpan = target.end - target.begin
guard span.isFinite, span > 0, finalSpan.isFinite, finalSpan > 0, width.isFinite else { return HorizontalTransform(scale: 1, translation: 0) }
return HorizontalTransform(scale: finalSpan / span, translation: (target.begin - begin) / span * width)
}
static func transition(from old: Self, to new: Self) -> Self {
guard old.dates.count > 1, old.dates.count == new.dates.count,
Array(old.dates.dropFirst()) == Array(new.dates.dropLast()),
+12 -3
View File
@@ -7,15 +7,24 @@ struct AnimatedMetricText: View {
var body: some View {
if animates {
Text(verbatim: value).monospacedDigit()
.contentTransition(.opacity)
.animation(.easeInOut(duration: MetricMotion.duration), value: value)
RollingMetricText(value: value).equatable()
} else {
Text(verbatim: value).monospacedDigit()
}
}
}
/// Same numeric roll/blur and spring as the original implementation. Unchanged values
/// do not rebuild this subtree when the surrounding resource snapshot changes.
private struct RollingMetricText: View, Equatable {
let value: String
var body: some View {
Text(verbatim: value).monospacedDigit()
.contentTransition(.numericText())
.animation(.spring(duration: 0.35, bounce: 0), value: value)
}
}
struct PanelCardBackground: ViewModifier {
let radius: CGFloat
+22 -14
View File
@@ -5,40 +5,48 @@ private struct MetricAnimationsKey: EnvironmentKey {
static let defaultValue = false
}
extension EnvironmentValues {
/// The owner supplies actual visibility and user/system motion policy.
var metricAnimationsEnabled: Bool {
get { self[MetricAnimationsKey.self] }
set { self[MetricAnimationsKey.self] = newValue }
}
}
/// A finite compositor transition; native controls never create per-frame CPU timers.
/// Finite property animations; no opacity substitution or per-frame CPU timer.
@MainActor final class MetricMotion {
static let duration: TimeInterval = 0.25
static let duration: TimeInterval = 0.35
static let key = "kymo.metric.movement"
private weak var layer: CALayer?
private var deadline: DispatchSourceTimer?
// Core Animation stores every CATransition under this reserved key.
private static let key = kCATransition
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
func start(on layer: CALayer?) {
func start(on layer: CALayer?, animation: CAAnimation) {
stop()
guard let layer else { return }
self.layer = layer
let transition = CATransition()
transition.type = .fade
transition.duration = Self.duration
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
transition.isRemovedOnCompletion = true
layer.add(transition, forKey: Self.key)
// AppKit backing layers can retain a finished transition; enforce a finite lifetime.
// One coalescible cleanup deadline, never a per-frame CPU callback.
animation.duration = Self.duration
animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil)
animation.isRemovedOnCompletion = true
layer.add(animation, forKey: Self.key)
// Backing layers may retain completed animations. Bound their lifetime explicitly.
let deadline = DispatchSource.makeTimerSource(queue: .main)
deadline.schedule(deadline: .now() + Self.duration, leeway: .milliseconds(10))
deadline.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.stop() } }
self.deadline = deadline
deadline.resume()
}
/// Cubic timing curve used by the original SwiftUI easeInOut animation.
static func easeInOut(_ time: Double) -> Double {
let time = min(1, max(0, time))
var low = 0.0, high = 1.0
for _ in 0..<24 {
let u = (low + high) / 2, v = 1 - u
let x = 3 * v * v * u * 0.42 + 3 * v * u * u * 0.58 + u * u * u
if x < time { low = u } else { high = u }
}
let u = (low + high) / 2
return 3 * (1 - u) * u * u + u * u * u
}
func stop() {
deadline?.cancel(); deadline = nil
layer?.removeAnimation(forKey: Self.key); layer = nil
+59 -34
View File
@@ -1,7 +1,7 @@
import AppKit
import SwiftUI
/// Small Core Graphics arcs avoid creating a SwiftUI path-rendering surface for every gauge.
/// Arc geometry is submitted once; the compositor interpolates strokeEnd continuously.
struct NativeMetricRing: NSViewRepresentable {
let value: Double
let color: Color
@@ -11,11 +11,9 @@ struct NativeMetricRing: NSViewRepresentable {
@Environment(\.metricAnimationsEnabled) private var animates
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, 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) -> RingView { RingView() }
func updateNSView(_ view: RingView, context: Context) {
view.configure(Input(value: value.isFinite ? min(1, max(0, value)) : 0, color: color,
@@ -31,57 +29,84 @@ struct NativeMetricRing: NSViewRepresentable {
}
final class RingView: NSView {
private(set) var input: Input?
private(set) var displayedValue = 0.0
let track = CAShapeLayer()
let arc = CAShapeLayer()
private let motion = MetricMotion()
var isAnimating: Bool { motion.isRunning }
var displayedValue: Double {
if isAnimating, let presentation = arc.presentation() { return Double(presentation.strokeEnd) }
return Double(arc.strokeEnd)
}
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
super.init(frame: .zero)
wantsLayer = true; layerContentsRedrawPolicy = .onSetNeedsDisplay
wantsLayer = true
for shape in [track, arc] {
shape.fillColor = nil; shape.lineCap = .round
layer?.addSublayer(shape)
}
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard value != input else { return }
let previous = input
let old = input
let start = displayedValue
input = value
displayedValue = value.value
CATransaction.begin(); CATransaction.setDisableActions(true)
if old?.color != value.color || old?.trackOpacity != value.trackOpacity { updateColors() }
if old?.inset != value.inset || old?.lineWidth != value.lineWidth { updateGeometry() }
arc.strokeEnd = value.value
CATransaction.commit()
if !value.animates { motion.stop() }
else if previous?.value != value.value {
else if old?.value != value.value {
motion.stop()
if previous != nil, window != nil { motion.start(on: layer) }
if old != nil, window != nil, start != value.value {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = start; animation.toValue = value.value
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
motion.start(on: arc, animation: animation)
}
}
}
private func updateColors() {
guard let input else { return }
effectiveAppearance.performAsCurrentDrawingAppearance {
let color = NSColor(input.color)
track.strokeColor = color.withAlphaComponent(input.trackOpacity).cgColor
arc.strokeColor = color.cgColor
}
}
private func updateGeometry() {
guard let input else { return }
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
let path = CGMutablePath()
path.addArc(center: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius,
startAngle: -.pi / 2, endAngle: 3 * .pi / 2, clockwise: false)
for shape in [track, arc] {
shape.frame = bounds; shape.path = path; shape.lineWidth = input.lineWidth
}
}
override func setFrameSize(_ size: NSSize) {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
motion.stop()
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGeometry(); CATransaction.commit()
}
needsDisplay = true
}
private func settle() { motion.stop(); displayedValue = input?.value ?? 0; needsDisplay = true }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { settle() }
}
override func setFrameSize(_ newSize: NSSize) {
let changed = newSize != frame.size
super.setFrameSize(newSize)
if changed { needsDisplay = true }
if window == nil { motion.stop() }
CATransaction.begin(); CATransaction.setDisableActions(true)
updateColors(); CATransaction.commit()
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance(); needsDisplay = true
}
override func draw(_ dirtyRect: NSRect) {
guard let input, let context = NSGraphicsContext.current?.cgContext else { return }
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
guard radius > 0 else { return }
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let tint = NSColor(input.color)
context.saveGState(); defer { context.restoreGState() }
context.setLineWidth(input.lineWidth); context.setLineCap(.round)
context.setStrokeColor(tint.withAlphaComponent(input.trackOpacity).cgColor)
context.strokeEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))
guard displayedValue > 0 else { return }
context.setStrokeColor(tint.cgColor)
context.addArc(center: center, radius: radius, startAngle: -.pi / 2,
endAngle: -.pi / 2 + 2 * .pi * displayedValue, clockwise: false)
context.strokePath()
super.viewDidChangeEffectiveAppearance()
CATransaction.begin(); CATransaction.setDisableActions(true)
updateColors(); CATransaction.commit()
}
}
}