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
+1 -1
View File
@@ -12,7 +12,7 @@ Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点
- 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。
- 进程:PID、名称、路径、CPU、RSS 和线程数;支持搜索、列排序及复制。
面板支持固定显示、保持唤醒、暂停 / 恢复采样。默认采用短时视觉过渡,可在设置开启“减弱动画”;后台记录独立控制。面板刷新默认 2 秒;默认隐藏停止采样,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。
面板支持固定显示、保持唤醒、暂停 / 恢复采样。默认保留数字滚动、曲线平滑移动和圆环连续变化,可在设置开启“减弱动画”;后台记录独立控制。面板刷新默认 2 秒;默认隐藏停止采样,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。
部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;耗电进程显示系统归属的 CPU 能量区间平均功率,注明可读覆盖范围,不代表完整应用总耗电。指标口径和限制见[监控指标](docs/monitoring.md)。
+1 -1
View File
@@ -10,7 +10,7 @@
| [测试与验证](testing.md) | 独立检查程序、执行方式和人工验收边界 |
| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 实施中:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 |
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。第三批见[原生绘制与进程表记录](efficiency-third-batch.md);第四批见[动效与效率排查](motion-and-efficiency-plan.md)。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。第三批见[原生绘制与进程表记录](efficiency-third-batch.md);第四批见[动效与效率排查](motion-and-efficiency-plan.md);其淡入实现已由[保留原动效的优化](motion-preservation-plan.md)替代。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
2026-11-03 依据当前源码重新整理;同日补充极致轻量化与进程能耗实施方案。此前清理的旧阶段计划、设计概念图和路线图可通过 Git 查询。主题文档描述当前实现,方案中的目标不代表已实现,也不以代码已实现代替运行验收。
+1 -1
View File
@@ -72,7 +72,7 @@ CPU / GPU / 风扇合并为一次只读 XPC 请求,按到期类别选择读取
进程表使用 MenuBar 的 NativeProcessTable(view-based NSTableView),继续消费 ProcessTableProjection 的搜索 / 排序 / 冻结投影。仅创建可见单元格,行数改变时增删尾行,刷新时原地修改可见文本与图像;选择以完整 ProcessIdentity 同步,用户选择 / 排序延后到委托回调之外写回 SwiftUI。原生 Esc 转发至原有分层退出逻辑,右键菜单保留复制能力。共享 ProcessIconCache 将 NSWorkspace 原图绘制为 30×30 像素、15pt 的单一位图,不保留原图;最多 128 项 / 1 MiB 解码像素,30 秒过期、LRU 淘汰、内存压力清空,不启动轮询。其预算不代表系统图标服务内部缓存已受控。
外观偏好保存独立的 reduceMotion(默认 false),设置提供减弱动画;MenuPanelView 根据手动 / 系统减弱动态效果、实际可见、暂停和睡眠计算并注入 UI 动效策略。默认数字交叉淡入、进度条短过渡、原生曲线连续追加与圆环整值淡入;首次挂载直接显示,真实断点不插值。减弱动画使用静态数字 / 曲线 / 进度条。原生控件在策略禁用或离开窗口时取消过渡;风扇没有持续旋转或 TimelineView。后台记录仍只由 SamplingPreferences 控制,动效偏好不改变采样间隔和历史。此措施不代表面板内存预算已通过;剩余峰值与 CPU 未达标情况见[第三批记录](efficiency-third-batch.md)和[动效与第四批排查](motion-and-efficiency-plan.md)。
外观偏好保存独立的 reduceMotion(默认 false),设置提供减弱动画;MenuPanelView 根据手动 / 系统减弱动态效果、实际可见、暂停和睡眠计算并注入 UI 动效策略。默认数字沿用原系统 numericText 滚动 / 模糊与 0.35 秒无回弹 spring;曲线按原时间域公式预计算 61 个横向变换关键帧,由 Core Animation 做 0.35 秒 easeInOut 移动;网格与悬浮层独立,路径仅在数据 / 几何改变时构建。满 60 点保留一个出界点,渐变覆盖出界区。圆环由 CAShapeLayer.strokeEnd 做 0.35 秒 easeInOut 弧长插值,中断从 presentation 值继续。有限属性动画配一次性清理截止,不使用 opacity 替代,不设逐帧 CPU 定时器。数字相同值由 Equatable 子视图跳过重复求值;首次挂载直接显示,真实断点不插值。减弱动画使用静态数字 / 曲线 / 进度条。原生控件在策略禁用或离开窗口时取消过渡;风扇没有持续旋转或 TimelineView。后台记录仍只由 SamplingPreferences 控制,动效偏好不改变采样间隔和历史。此措施不代表面板内存预算已通过;剩余峰值与 CPU 未达标情况见[第三批记录](efficiency-third-batch.md)和[动效与第四批排查](motion-and-efficiency-plan.md);恢复原动效后的对照见[保留动效的优化记录](motion-preservation-plan.md)。
`PanelResourceAudit` 与纯文字对照渲染器仅在 Debug 或显式 `KYMO_AUDIT` 编译条件下包含实现;普通 Release 不包含诊断驱动与文字列表实现。测试构建还需设置 `KYMO_RESOURCE_AUDIT=1` 才驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启;实际启用动效的曲线数量以 animatedPlots 记录;审计标记附带原生图区数量 / 尺寸、悬浮状态和指针是否在面板内,窗口编号只在可见时读取。
+52
View File
@@ -0,0 +1,52 @@
# 保持原动效的实现优化
2026-11-04,起点 f18f665。用户明确禁止用渐隐渐现替换原视觉效果。视觉基线取 8333349 的实际实现:数字系统 numericText + 0.35 秒无回弹 spring;曲线真实时间域的 0.35 秒 easeInOut 平滑移动;圆环从顶部顺时针、圆头、0.35 秒 easeInOut 连续伸缩。减弱模式保持静态,后台控制独立。
## 范围与设计
- UI / AnimatedMetricText 恢复系统数字滚动,不自行模拟字形或替换方向;用独立 Equatable 内容避免数值未变的父级刷新重复计算,不改变继承字体 / 颜色 / 辅助功能。
- NativeMetricRing 使用独立 CAShapeLayer 的 strokeEnd 插值;中断从 presentation 当前值继续,不以两幅图的透明度替代弧长变化。静态轨道不动。
- NativePanelCurve 保留原曲线几何、渐变、断点和最多一个出界点。曲线层和静态网格 / 悬浮层分离。每次数据只构建一次路径;用原时间域公式计算横向仿射变换关键帧,交给 Core Animation 移动曲线。增长窗口、满历史、非均匀时间戳都按原公式,不用简单位移偷换缩放;真实空档不补动画。
- MetricMotion 管理有限属性动画和单次清理截止;不设置 opacity / CATransition,不建立每控件逐帧 CPU 回调。隐藏、暂停、减弱、卸载立即移除属性动画并显示最终数据。
## 实施与验证顺序
1. 实现上述三类效果;核对 baseline 和调用链,保护现有字符串目录改动。
2. 对中间帧做行为检查:圆环 strokeEnd 位于端点之间;曲线变换中间位置与原时间域公式一致、网格不移动、满历史无丢出界点;停止 / 结束 / 重定向 / 断点不留动画。
3. Debug / Release 构建、完整检查、实际原生窗口及设置切换验证。数字直接沿用原系统 API;视觉手感仍需用户验收,不把截图当作动态验证。
4. 对同一 Release 的默认 / 减弱模式测量并比较已有失败版本;保留完整功能和采样频率。性能超预算继续记录,不擅自降级视觉。
风险:系统数字滚动仍可能有较高成本;本轮优先保证效果正确,再量化收益。图形内存 / 合成成本需要实测,不能仅由主线程无逐帧计时器判省电达标。普通 Release 不含诊断驱动。跨 UI / MenuBar 调用约束与测试说明同步更新。
## 结果与边界
已实现上述三类动效;减弱模式静态,后台偏好与采样频率未改。只改 UI 实现及行为检查,未引入依赖或新增产品功能。数字仍用原系统 API,不自行模拟字形。
### 同功能资源对照
2026-11-04,arm64、签名的 KYMO_AUDIT Release 顺序运行,前台 2 秒、后台关闭,保留全部后端 / 真实 CPU 能量候选 / 当前包资源 / 原生进程表。临时参考源码仅将 PanelTrendChart、MetricRingGauge、CPUCoreGrid、AnimatedMetricText 恢复到 8333349 的原效果,接入相同减弱开关;参考不是较便宜的淡入版。每组冷启动 10 秒后,三轮开窗 30 秒 / 关窗 30 秒,第一轮另暂停 10 秒。CPU / 内存中位数使用每轮开窗第 10–30 秒,CPU 来自 rusage 时间差并换算 Mach 单位,单核 100%。
| 指标 | 原效果参考 | 当前默认 | 当前减弱 |
| --- | --- | --- | --- |
| 主进程 CPU%,三轮 | 33.49 / 33.98 / 35.00 | 29.97 / 30.33 / 30.80 | 4.18 / 6.70 / 2.45 |
| 主进程 footprint 中位数 MiB,三轮 | 344.20 / 284.99 / 287.00 | 205.57 / 212.30 / 214.68 | 61.21 / 63.61 / 71.27 |
| 主进程整组累计 footprint 峰值 MiB | 401.02 | 330.31 | 183.55 |
| 关窗 30 秒 footprint MiB,三轮 | 206.42 / 148.11 / 150.31 | 201.13 / 206.97 / 210.80 | 52.67 / 59.59 / 66.25 |
| 主进程唤醒 / 秒,三轮 | 112.14 / 113.53 / 116.56 | 71.15 / 75.13 / 71.27 | 6.05 / 14.00 / 4.05 |
XPC 区间 CPU 均约 0.18–0.21%,footprint 中位数约 4.6–5.0 MiB。默认主进程区间 CPU 比参考低约 10–12%,累计峰值低约 18%;这些是本轮观察,不能承诺固定收益。关窗后默认内存仍在增长,后两轮比参考更高,**内存、CPU 和长期省电预算仍未通过**。关闭内容的弱引用已释放,不能据此断言所有框架 / 合成缓存已回收,也未证明泄漏已排除。
顺序测量期间无并行构建或 GUI 检查;未锁定外部工作负载,鼠标由用户使用(日志记录悬浮 / 面板内指针状态),因此模式间差值不是严格因果分解。未测实际瓦数、100 次循环或 8 小时。测量后仅补显式动画时钟起点 / linear 总时序、空输入防护与检查,最终源码仍需长期复测;不能把此表称作最终版本稳定预算。
### 未合入的数字试验
- drawingGroup:原系统数字滚动与 spring 不变,真实独立窗口两次更新确认滚动 / 模糊仍在;单轮 CPU 31.28%,内存中位数 208.16 MiB,唤醒 124.21 次 / 秒,没有收益,拒绝合入。
- 弹簧收敛后清理数字 transition 状态:独立窗口中间滚动和下次更新正常;单轮 CPU 32.76%,中位数 207.42 MiB,未显示明确收益,拒绝合入。没有为了回收提前截断弹簧。
目前数字动效是进一步排查的重要线索,尚未完成分配根因归属。下一步须用相同视觉、重复 A/B 与分配记录验证,不能以淡入、静态或降刷新频率替代。
### 最终验收
Debug、普通 Release 和 KYMO_AUDIT Release 构建均通过;统一入口 35 项 Swift 检查、211 条三语言目录与 host entitlement 检查通过,包括真实窗口组件及 sandbox HTTPS。未创建 XCTest target,不将独立检查称为 xcodebuild test。最终普通 Release 深层严格签名校验通过,21 个文件逻辑大小 2,070,576 字节(约 1.97 MiB),主可执行文件 1,283,648 字节;没有新增资源或依赖。
最终审计包整窗 AX 与限定自身窗口截图确认曲线 / 渐变未上下颠倒,圆环从顶部顺时针、样式与数据正常。独立数字对照窗口确认更新中的滚动 / 模糊与后续更新;这仍不能替代完整产品动态手感验收。临时试验及构建文件清理;仅结束本轮测试副本。数字滚动手感、曲线与圆环动态观感由用户重启当前 Xcode 运行后验收;保留用户既有进程,不替用户退出 Xcode 调试副本。
+6
View File
@@ -315,3 +315,9 @@ Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必
自己的面板内容位图可用 `KYMO_AUDIT_CAPTURE=1` 在 open1.10 时经 stdout 返回 audit.capture 的 PNG;仅 Debug / KYMO_AUDIT 编入,实现只绘制自身宿主、限制面积,不读取桌面。该操作会增加内存和 CPU,必须单独运行,不纳入资源基线;原始图含本应用展示的进程 / 网络信息,验收后清理。
本轮已实测原生应用 AX 读取、设置按钮点击、隔离副本的动效 / 后台开关、间隔编辑、Cmd+W / Cmd+, 与 App 局部设置截图;精确范围及未验证项见第四批记录。full 分配历史需按本机 `man malloc` 显式设置 MallocStackLogging=full,并提供应用自身可写的既有目录;不能将 lite 的当前分配当成峰值历史。
## 保留原动效的回归
当前默认数字沿用原 numericText + spring;曲线和圆环分别验证 transform 关键帧与 strokeEnd 中间值,明确禁止用 CATransition 淡入替代。NativeMetricDrawingChecks 检查网格不动、动画期间及悬浮不重建路径、满 60 点的出界渐变、真实断点、禁用与卸载取消。PanelCurveChecks 对增长 / 满历史 / 非均匀时间戳的中间横坐标逐项核对原时间域公式。图层位图检查不能替代滚动模糊和动态观感验收。
相同后端、2 秒刷新、后台关闭的三轮 Release 对照与未达标项见[保留动效的优化记录](motion-preservation-plan.md)。记录主进程与 XPC 的实际 CPU 时间,使用 Mach timebase 换算;CPU 百分比以单核为 100%,不以自有列表的瞬时值替代区间测量。未测实际瓦数或长时能耗。
+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()
}
}
}
+47 -4
View File
@@ -1,5 +1,6 @@
import AppKit
import SwiftUI
import QuartzCore
@main struct NativeMetricDrawingChecks {
@MainActor static func main() {
@@ -49,7 +50,22 @@ import SwiftUI
intervals: [2,2,2,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5, animates: true)
plot.configure(continuous); plot.configure(moving)
precondition(plot.isAnimating)
try? await Task.sleep(for: .milliseconds(400))
let builds = plot.pathBuildCount
precondition(plot.grid.animationKeys() == nil, "The grid must stay stationary")
let movement = plot.curves.animation(forKey: MetricMotion.key) as! CAKeyframeAnimation
precondition(movement.keyPath == "transform" && movement.values?.count == 61)
precondition(plot.curves.animation(forKey: kCATransition) == nil, "A moving curve must not be replaced with a fade")
let middle = (movement.values![30] as! NSValue).caTransform3DValue
let oldDomain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: dates.first!, end: dates.last!, progress: 1)
let newDomain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: extendedDates.first!, end: extendedDates.last!, progress: 1)
let expected = PanelCurveFrame.horizontalTransform(from: oldDomain, to: newDomain, progress: 0.5, width: 280)
precondition(abs(middle.m11 - expected.scale) < 0.0001 && abs(middle.m41 - expected.translation) < 0.0001)
try? await Task.sleep(for: .milliseconds(180))
precondition(plot.pathBuildCount == builds, "Animation frames must not rebuild curve geometry")
var duringHover = moving; duringHover.hoveredIndex = 2
plot.configure(duringHover)
precondition(plot.pathBuildCount == builds && plot.isAnimating, "Hover must not rebuild or restart movement")
try? await Task.sleep(for: .milliseconds(320))
precondition(!plot.isAnimating && plot.drawingFrame == moving.frame)
var appended = moving
appended = NativePanelCurve.Input(frame: PanelCurveFrame(dates: extendedDates + [Date(timeIntervalSinceReferenceDate: 10)],
@@ -65,9 +81,32 @@ import SwiftUI
var attached = beforeGap; attached.animates = true
plot.configure(attached); precondition(plot.isAnimating)
plot.removeFromSuperview(); precondition(!plot.isAnimating)
root.addSubview(plot)
let fullDates = (0..<60).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
let fullFrame = PanelCurveFrame(dates: fullDates, series: [Array(repeating: 0.8, count: 60)], intervals: Array(repeating: 2, count: 60), boundaryDates: [])
let nextFrame = PanelCurveFrame(dates: Array(fullDates.dropFirst()) + [Date(timeIntervalSinceReferenceDate: 120)],
series: [Array(repeating: 0.8, count: 59) + [0.5]], intervals: Array(repeating: 2, count: 60), boundaryDates: [])
plot.configure(.init(frame: fullFrame, colors: [.red], scales: [1], maximumGap: 5, animates: true))
plot.configure(.init(frame: nextFrame, colors: [.red], scales: [1], maximumGap: 5, animates: true))
precondition(plot.isAnimating && plot.drawingFrame?.dates.count == 61)
let initialTransform = ((plot.curves.animation(forKey: MetricMotion.key) as! CAKeyframeAnimation).values!.first as! NSValue).caTransform3DValue
CATransaction.begin(); CATransaction.setDisableActions(true)
plot.curves.transform = initialTransform
CATransaction.commit()
precondition(redPixels(bitmap(plot), from: 0, to: 0.01) > 0, "Outgoing fill must cover the left edge while scrolling")
CATransaction.begin(); CATransaction.setDisableActions(true); plot.curves.transform = CATransform3DIdentity; CATransaction.commit()
plot.configure(.init(frame: nextFrame, colors: [.red], scales: [1], maximumGap: 5))
precondition(!plot.isAnimating && plot.drawingFrame?.dates.count == 60)
plot.removeFromSuperview()
ring.configure(NativeMetricRing.Input(value: 0, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2, animates: true))
precondition(ring.isAnimating)
try? await Task.sleep(for: .milliseconds(400))
let arcAnimation = ring.arc.animation(forKey: MetricMotion.key) as! CABasicAnimation
precondition(arcAnimation.keyPath == "strokeEnd" && (arcAnimation.fromValue as! Double) == 1 && (arcAnimation.toValue as! Double) == 0)
precondition(ring.arc.animation(forKey: kCATransition) == nil)
try? await Task.sleep(for: .milliseconds(150))
let intermediate = ring.displayedValue
precondition(intermediate > 0 && intermediate < 1, "Ring must show intermediate arc lengths")
try? await Task.sleep(for: .milliseconds(350))
precondition(!ring.isAnimating && ring.displayedValue == 0)
ring.configure(NativeMetricRing.Input(value: 0.8, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2, animates: true))
precondition(ring.isAnimating)
@@ -82,8 +121,12 @@ import SwiftUI
NSApp.run()
}
@MainActor private static func bitmap(_ view: NSView) -> NSBitmapImageRep {
let result = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
view.cacheDisplay(in: view.bounds, to: result)
view.layoutSubtreeIfNeeded(); view.displayIfNeeded()
let result = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(view.bounds.width * 2), pixelsHigh: Int(view.bounds.height * 2),
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
let context = NSGraphicsContext(bitmapImageRep: result)!.cgContext
context.scaleBy(x: 2, y: 2)
view.layer!.render(in: context)
return result
}
private static func redPixels(_ image: NSBitmapImageRep, from: Double = 0, to: Double = 1, opaque: Bool = false) -> Int {
+14
View File
@@ -32,6 +32,20 @@ import Foundation
if progress == 0 { precondition(abs(left) < 0.000001 && abs(domain.position(old.dates.last!) - 1) < 0.000001) }
if progress == 1 { precondition(abs(right) < 0.000001 && abs(domain.position(next.dates.last!) - 1) < 0.000001) }
}
// The compositor mapping must equal the original interpolated time-domain formula.
for previous in [PanelCurveFrame.Domain(begin: 0, end: 4), .init(begin: 0, end: 118), .init(begin: 2, end: 119.3)] {
for target in [PanelCurveFrame.Domain(begin: 0, end: 6), .init(begin: 2, end: 120), .init(begin: 4.4, end: 121.8)] {
for p in [0.0, 0.25, 0.5, 0.75, 1] {
let map = PanelCurveFrame.horizontalTransform(from: previous, to: target, progress: p, width: 350)
let interpolated = PanelCurveFrame.Domain(begin: previous.begin * (1-p) + target.begin * p,
end: previous.end * (1-p) + target.end * p)
for t in [0.0, 2, 60, 120] {
let date = Date(timeIntervalSinceReferenceDate: t)
precondition(abs(target.position(date) * 350 * map.scale + map.translation - interpolated.position(date) * 350) < 0.00001)
}
}
}
}
print("PASS: timestamp append/full history, pause/reset, missing/nonfinite data, short series, cadence continuity, pause boundaries and 61-point left-edge animation geometry")
}
}