12 Commits
Author SHA1 Message Date
wangairnan ec37b8e3f9 feat(updates): 使用 Sparkle 从发布 ZIP 下载并重启更新 2026-11-16 16:17:31 +08:00
wangairnan 451d31682d fix(power): 完善电池卡片的共同供电判定、功率图标与预估续航
按适配器和电池的实际贡献判定共同供电,以双图标和双色柱展示两路功率。同步三语预估续航文案,在仅外接供电时隐藏估时行。
2026-11-16 15:06:02 +08:00
wangairnan ae448bce5c fix(menubar): 将面板运行时长更名为开机时长 2026-11-16 13:34:31 +08:00
wangairnan 4a8f580156 chore(release): 升级至 1.4 并准备构建 16 发布说明 2026-11-16 11:31:06 +08:00
wangairnan 0442398407 feat(settings): 新增关于菜单和基于正式发布的更新检测 2026-11-16 11:26:18 +08:00
wangairnan b9abb970d9 feat(menubar): 用分色进度柱展示电量、供电与睡眠历史
记录系统睡眠和唤醒区间,保留真实采样空档。电量柱按固定间距从右侧滑入,以蓝色、绿色和橙黄色分别标记外接电源、电池和睡眠,支持悬浮查看历史。
2026-11-16 11:07:07 +08:00
wangairnan 36518d29db fix(ui): 校正三语指标文案并核对构建包译文 2026-11-16 00:17:42 +08:00
wangairnan 3ee6b45eb4 perf(menubar): 减少进程表刷新排序并清理闲置代码 2026-11-16 00:06:14 +08:00
wangairnan 97c1bc3b7f perf(monitors): 复用网络接口元数据并一致读取路径状态 2026-11-16 00:06:03 +08:00
wangairnan 4b8deb2e48 feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
2026-11-15 23:54:19 +08:00
wangairnan 1595af6d13 chore(release): 升级至 1.3 并准备构建 15 发布说明 2026-11-15 22:58:12 +08:00
wangairnan fe62b7910b feat(menubar): 新增可配置的实时菜单栏指标与设置预览
使用竖条显示 CPU、GPU、内存与磁盘占用,分行展示上传和下载速率。支持全选、取消全选与空选恢复品牌图标,实时指标跟随面板刷新间隔。
2026-11-15 22:52:37 +08:00
91 changed files with 3467 additions and 421 deletions
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SUAllowsAutomaticUpdates</key>
<false/>
<key>SUEnableAutomaticChecks</key>
<true/>
<key>SUEnableInstallerLauncherService</key>
<true/>
<key>SUFeedURL</key>
<string>https://git.airnan.cn/wangairnan/Kymo/releases/download/latest/appcast.xml</string>
<key>SUPublicEDKey</key>
<string>jOL7AATUmzgitnDff81drd31wiPcYWDujII/KU+uhYI=</string>
<key>SURequireSignedFeed</key>
<true/>
<key>SUScheduledCheckInterval</key>
<integer>21600</integer>
<key>SUShowReleaseNotes</key>
<false/>
<key>SUVerifyUpdateBeforeExtraction</key>
<true/>
</dict>
</plist>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spks</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spki</string>
</array>
</dict>
</plist>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spks</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)-spki</string>
</array>
</dict>
</plist>
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>cdhash</key>
<dict>
<key>$in</key>
<array>
<data>
UZ2SEZ68zg8Ox1KdIRiLa0oRoww=
</data>
<data>
YVeicQp6v0Skchu7R9uuirzJd48=
</data>
</array>
</dict>
</dict>
</plist>
+3 -3
View File
@@ -1,6 +1,6 @@
# Kymo
Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点击打开资源卡片与进程同页的监控面板。
Kymo 是 macOS 菜单栏资源监控工具。菜单栏以竖条显示 CPU、GPU、内存和磁盘占用,以两行文字显示上传和下载速率。点击状态项打开资源卡片与进程同页的监控面板。
## 当前功能
@@ -12,7 +12,7 @@ Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点
- 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。
- 进程:PID、名称、CPU、内存 footprint、CPU 平均功率、线程数六列;路径仍支持搜索和右键复制,无横向滚动条;支持列排序及复制,功率缺失始终排末。
面板支持固定显示、保持唤醒、暂停 / 恢复采样。首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,第三行进程表跨满内容区;默认三行均高 176pt,面板 648×630pt,小屏退为两列或单列并滚动。CPU、GPU、内存和电池趋势覆盖整卡,存储和网络趋势位于详情下方;CPU 系统 / 用户、内存应用 / 联动 / 压缩按分量堆叠,悬浮查询原始历史;存储 / 网络以绘图区 60% 高度零轴上下显示读 / 写、上传 / 下载,内存不再重复显示容量条。每个逻辑核对应一格,以填充高度表示占用;风扇图标沿用转速档位旋转,暂停、隐藏或系统减弱动态效果时停转。数值随采样直接更新。曲线随新采样平滑平移,遵循系统减弱动态效果。资源和进程同时按可见性采样,后台趋势独立控制。面板刷新默认 2 秒;默认隐藏停止采样,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。
面板支持固定显示、保持唤醒、暂停 / 恢复采样。首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,第三行进程表跨满内容区;默认三行均高 176pt,面板 648×630pt,小屏退为两列或单列并滚动。CPU、GPU 和内存趋势覆盖整卡,电池、存储和网络趋势位于详情下方。电量柱按供电状态着色,月亮标出系统睡眠时段;CPU 系统 / 用户、内存应用 / 联动 / 压缩按分量堆叠,悬浮查询原始历史;存储 / 网络以绘图区 60% 高度零轴上下显示读 / 写、上传 / 下载,内存不再重复显示容量条。每个逻辑核对应一格,以填充高度表示占用;风扇图标沿用转速档位旋转,暂停、隐藏或系统减弱动态效果时停转。数值随采样直接更新。曲线随新采样平滑平移,遵循系统减弱动态效果。资源和进程同时按可见性采样,后台趋势独立控制。面板及亮屏菜单栏指标默认每 2 秒刷新。设置的「菜单栏」页可预览并勾选 CPU、GPU、内存、磁盘和网络,全部取消则显示品牌图标。没有实时展示需求时,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。自动检查默认开启,每次启动及运行中每 6 小时检测更新。发现新版时,面板 Kymo 字样右上角的版本角标可点击下载,准备就绪后再次点击即可重启更新。「关于 Kymo」同步显示更新状态、手动检查入口和自动检查开关。
部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;耗电进程显示系统归属的 CPU 能量区间平均功率,注明可读覆盖范围,不代表完整应用总耗电。指标口径和限制见[监控指标](docs/monitoring.md)。
@@ -26,7 +26,7 @@ open kymo.xcodeproj
xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build
```
在 Xcode 中运行 `kymo`。平时仅显示菜单栏图标,打开设置时临时显示 Dock 图标。左键图标切换面板,右键打开快捷菜单。
在 Xcode 中运行 `kymo`。平时通过菜单栏状态项操作,打开设置时临时显示 Dock 图标。左键状态项切换面板,右键打开快捷菜单。
## 文档与协作
+5
View File
@@ -3,6 +3,7 @@ import Foundation
private actor CPUTemperatureReader {
private let monitor = CPUTemperatureMonitor()
private let gpuMonitor = CPUTemperatureMonitor(zone: .gpu)
func sampleBatteryPower() -> Double? { monitor.sampleBatteryPower() }
func sampleSystemPower() -> Double? { monitor.sampleSystemPower() }
func sampleFans() -> [Double?]? { monitor.sampleFans() }
func sampleGPU() -> Double? { gpuMonitor.sample() }
@@ -15,6 +16,10 @@ private actor CPUTemperatureReader {
final class SMARTService: NSObject, SMARTServiceProtocol {
private let temperatureReader = CPUTemperatureReader()
func readBatteryPower(withReply reply: @escaping (NSNumber?) -> Void) {
Task { reply(await temperatureReader.sampleBatteryPower().map(NSNumber.init(value:))) }
}
func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void) {
Task { reply(await temperatureReader.sampleSystemPower().map(NSNumber.init(value:))) }
}
+1
View File
@@ -10,6 +10,7 @@
| [测试与验证](testing.md) | 统一检查入口、覆盖范围、实际交互与验收边界 |
| [测试分发](free-test-distribution.md) | 本地 Release 打包、签名与安装支持范围 |
| [UI 设计规范](ui-design-standard.md) | 单页布局、卡片尺寸、字体、颜色、堆叠背景、风扇动效与信息契约 |
| [菜单栏动态指标](menu-bar-metrics-plan.md) | 设计图、勾选与预览同步、采样需求及验收结果 |
| [卡片背景趋势设计稿](designs/card-background-trends-v1/README.md) | 已采纳的浅色 / 深色风格参考,具体实现以设计规范和代码为准 |
修改实现时直接更新相应主题;大型变更的临时方案按 [AGENTS.md](../AGENTS.md) 存放在本目录,完成后将有效结论归入主题文档并清理失效记录。
+18 -12
View File
@@ -6,7 +6,7 @@
| --- | --- |
| `kymo/App` | AppKit 入口、生命周期、依赖装配、主菜单和 SwiftUI Settings 场景 |
| `kymo/Features/MenuBar` | 状态项、监控 NSPanel、资源卡片、进程表、业务展示投影与本地验证驱动 |
| `kymo/Features/Settings` | 通用 / 关于设置页、窗口焦点和 Dock 生命周期 |
| `kymo/Features/Settings` | 通用 / 菜单栏 / 关于设置页、窗口焦点和 Dock 生命周期 |
| `kymo/Core/Monitors` | 系统采样、报告解析与 SystemSampler actor |
| `kymo/Core/Services` | MetricsStore、偏好、XPC 客户端、网络地址、保持唤醒与诊断 |
| `kymo/Core/Models` / `Extensions` | 指标、进程身份、有界历史 / 格式化 |
@@ -14,13 +14,13 @@
| `kymo/Resources` / `Assets.xcassets` | 三语字符串 / 颜色和图片 |
| `SMARTService` | 按需只读 XPC:温度、风扇、整机功率、SMART、同 UID 进程 footprint 与 CPU 能量 |
App 装配依赖,方向为 Features → UI → Core → 系统 API。Features 可使用窗口所需 AppKit / SwiftUI;模块之间通过 App 注入动作与 Core 状态协作,无横向依赖。Core 不引用 Features 或 UI。SettingsPresentation 仅表示展示请求,不持有窗口。
App 装配依赖,方向为 Features → UI → Core → 系统 API。Features 可使用窗口所需 AppKit / SwiftUI;模块之间通过 App 注入动作与 Core 状态协作,无横向依赖。Core 不引用 Features 或 UI。SettingsPresentation 保存当前设置页签和窗口展示请求序号。
## 窗口与界面
入口 kymoApp.main() 启动 NSApplication,由 ApplicationLifecycle 管理;应用以 accessory 模式启动,通过 NSHostingSceneRepresentation 注册 Settings。
MenuPanelController 拥有模板品牌 NSStatusItem 和无边框、可成为 key 的非激活 MonitoringPanel。左键切换面板,右键提供打开 / 隐藏、设置和退出。窗口以状态项所在屏幕可见区域为边界,水平居中,边缘至少留 16pt;最大宽 648pt,常规高 630pt,按卡片内容预算调整,最大高 800pt,并受实际屏幕限制。
MenuPanelController 拥有可变宽度 NSStatusItem 和无边框、可成为 key 的非激活 MonitoringPanel。左键切换面板,右键提供打开 / 隐藏、设置、关于和退出。窗口以状态项所在屏幕可见区域为边界,水平居中,边缘至少留 16pt;最大宽 648pt,常规高 630pt,按卡片内容预算调整,最大高 800pt,并受实际屏幕限制。
单页面板首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,第三行进程表跨满内容区。所有行按最高资源卡片的结构预算等高,默认均为 176pt;资源卡片宽 205⅓pt。32pt 顶栏在品牌标题右上方显示包内短版本号。26pt 底栏从左向右排列开机时间、设备与刷新间隔,面板间隔输入框宽 50pt。宽度小于 620pt 退为两列资源网格,小于 430pt 退为单列;进程始终放在资源之后,高度不足时中间区域整体滚动,表格保留自身滚动。
@@ -28,44 +28,50 @@ MenuPanelController 拥有模板品牌 NSStatusItem 和无边框、可成为 key
固定按钮切换 normal / floating 层级。未固定时外部交互或应用失活收起;固定仍可显式关闭。进程表 Esc 依次清空搜索、清除选择、退出搜索焦点,然后关闭面板。隐藏卸载内容、关闭底层窗口资源并移除外部鼠标监听,控制器保留窗口对象供重开。presentation.isOpen 控制内容装配,采样可见性同时要求窗口 isVisible 与 occlusionState 可见;完全遮挡降级采样而保留内容及交互状态。
MenuBarPreferences 在 UserDefaults 保存勾选集合,首次全选,空集保留。单项和批量选择均一次写入整组,只在空选与有选项之间切换时通知采样需求变化。App 将同一读取闭包注入设置页和状态项。闭包从当前 MetricsSnapshot 生成 MenuBarReading,UI 的 MenuBarMetricStrip 在两处绘制四项竖条占用及独立上下行文本。状态按钮负责点击与辅助功能,绘图子视图透传命中。取消全部后恢复原品牌图标;系统空间不足可能隐藏状态项,此时从 Finder 或 Spotlight 再次打开 Kymo 可进入设置。
设置窗口打开时转为 regular 模式并恢复焦点,SettingsWindowLifecycle 在关闭后恢复 accessory。关闭最后一个窗口不退出应用;退出时清理状态项、窗口、通知和保持唤醒断言。
应用主菜单和状态项的「关于 Kymo」共用同一导航动作,可从已打开或已关闭的设置窗口直达关于页。App 装配 SparkleUpdater 与 ReleaseUpdates。SparkleUpdater 作为 Sparkle 2 的用户界面驱动和委托,启动时沿用已有的 updates.automatic 偏好(默认开启)。开启时在启动后立即检查,后续由 Sparkle 按 SUScheduledCheckInterval(21600 秒)调度。关闭后保留手动检查。Sparkle 检查签名的 appcast,按 CFBundleVersion 识别新版,并处理系统版本、下载与安装兼容性。发现可用更新后结束检测会话,保留可操作角标;点击下载时重新确认目标构建号,版本已变化则展示新目标。面板品牌角标和关于页共享下载、解压准备、重启和错误重试状态。下载并准备好后由用户点击重启,Sparkle 也可在应用自然退出时完成已准备的安装。
更新源固定为最新正式 Release 的 appcast.xml 附件,包地址固定到其版本标签。EdDSA 公钥内置于应用;清单须签名,ZIP 在解压前验证。主程序启用 Sparkle 安装服务和两项限定于本应用标识的 Mach 通信权限,通过现有出站网络权限下载。SMARTService 与更新安装器独立。ad-hoc Release 的 Hardened Runtime 库加载约束仅允许锁定的双架构 Sparkle 库哈希及系统库。升级框架时需要核对官方二进制并同步更新约束。
## 采样、状态与并发
```text
系统 API → SystemSampler actor → MetricsSnapshot → MetricsStore(MainActor)
│ ├─ snapshot → 资源卡片
│ ├─ snapshot → 资源卡片 / 设置预览 / 状态项
├─ 慢任务缓存 ├─ processSnapshot / energy → 进程表
└─ 单在途进程任务 └─ MetricHistory → 趋势图
SMARTService(XPC)→ 只读客户端 → 整机功率 / 慢缓存 / 进程任务
实际可见性、详情需求、睡眠与偏好 → MetricsStore 调度
```
MetricsStore 是 MainActor 可观察状态。App 装配时通过 setDetailDemand(processes: true, slowMetrics: true) 同时请求进程和慢指标,Core 只接收需求布尔值,不依赖界面类型。实际可见性、暂停与睡眠统一决定是否执行;隐藏默认停止采样,显式后台趋势仅延续基础历史,不启动进程、footprint、能量或慢报告。
MetricsStore 是 MainActor 可观察状态。App 装配时通过 setDetailDemand(processes: true, slowMetrics: true) 同时请求进程和慢指标,Core 只接收需求布尔值,不依赖界面类型。实际可见性、暂停与睡眠统一决定是否执行;面板隐藏时,亮屏且菜单栏至少勾选一项会延续基础采样。只有后台趋势开启时,息屏才按后台间隔记录。这两种需求均不启动进程、footprint、能量或慢报告。
新配置隐藏不采样;显式启用后台趋势后使用后台间隔,默认 30 秒。已有数值后台间隔且没有显式开关时保留启用状态,显式关闭优先。面板可见默认 2 秒,范围与各指标周期见[监控指标](monitoring.md)。周期按单调时钟从每轮开始安排,不补跑错过轮次;配置变化参考上次发布时间。允许 10% 周期容差,前台最多 200ms、后台最多 1 秒,速率仍按实际经过时间差分。
面板可见或菜单栏指标启用且亮屏时按面板间隔更新。两者都不需要时,显式后台趋势按后台间隔更新(默认 30 秒),否则停止采样。已有数值后台间隔且没有显式开关时保留启用状态,显式关闭优先。面板可见默认 2 秒,范围与各指标周期见[监控指标](monitoring.md)。周期按单调时钟从每轮开始安排,不补跑错过轮次;配置变化参考上次发布时间。允许 10% 周期容差,前台最多 200ms、后台最多 1 秒,速率仍按实际经过时间差分。
SystemSampler actor 持有差分基线。CPU / 内存 Mach 查询取得的 host 发送权在调用结束释放。卷和进程枚举使用 utility detached Task;温度、磁盘健康、电池健康各最多一个慢任务在途。缓存可晚于快照更新,已开始的系统调用可能在需求结束后完成。快照仅保留当前消费者需要的数据;GPU 总占用直接由 gpu.usage 派生。
SystemSampler actor 持有差分基线。网络采样按接口名关联前后两轮计数,并比较索引、活动状态和已排序地址以决定是否计算速率。路径状态和主接口候选在同一锁内读取,取自同一次路径回调。CPU / 内存 Mach 查询取得的 host 发送权在调用结束释放。卷和进程枚举使用 utility detached Task;温度、磁盘健康、电池健康各最多一个慢任务在途。缓存可晚于快照更新,已开始的系统调用可能在需求结束后完成。快照仅保留当前消费者需要的数据;GPU 总占用直接由 gpu.usage 派生。
进程数据独立发布到 processSnapshot,避免触发资源卡片观察者;能量独立发布,仅保留完整进程身份、功率和统计窗口,测量数量由结果行数派生,排序统一由进程表投影负责。需求代次同时在 Store 与 actor 校验,旧结果不能复活隐藏需求。失效的同步进程读取仍占用单在途槽位,完成后立即补读新代次,无需等待下一轮。
暂停停止周期发布、停用进程更新并保留快照和历史;恢复重置基线并标记历史断点。系统睡眠停止采样;息屏停用前台、进程、能量、公网与慢读取,只保留显式后台趋势。NSWorkspace 事件由 App 转发。
暂停停止周期发布、停用进程更新并保留快照和历史;恢复重置基线并标记历史断点。系统睡眠停止采样;息屏停用前台、进程、能量、公网与慢读取,只保留显式后台趋势。App 转发 NSWorkspace 通知。MetricsStore 配对系统睡眠与唤醒的实际时间,MetricHistory 在最近采样窗口内保留至多 60 段睡眠,息屏或暂停不会产生睡眠记录。
历史全局及每接口各最多 60 点,接口移除时清理其历史。每点 expectedInterval 表示其后的计划等待;连续需求重新调度将最长等待记入最近点。绘图按真实时间跳过 nil / 非有限节点,连接有效点,保留有效 0;显式停采、长空档和倒序仍断线,包括空值点携带的断点。原数据不补值,缺失时刻无悬浮测量标记。
## 展示与本地状态
ResourceCard 通过 NativeContentHost 使用固定尺寸的独立 NSHostingView,传递字体、颜色、语言及外观环境;更新沿用挂载身份,卸载清空子宿主内容。CPU、GPU、内存、电池采用整卡背景图,卡片顶边对应 100% 或物理内存总量,底边对应零。存储、网络与无电池时的整机功率图使用详情下方的剩余高度。辅助信息主要为 10pt / 16pt 行高,内存和存储详情通过 ViewThatFits 按信息组换行,默认卡片仍为 176pt 高。统一 16pt 圆角、10pt 前景内边距和静态轻阴影,图表锚点和提示在同一宿主内处理;不显示常驻图例、数值坐标轴、网格或起止时间。
ResourceCard 通过 NativeContentHost 使用固定尺寸的独立 NSHostingView,传递字体、颜色、语言及外观环境;更新沿用挂载身份,卸载清空子宿主内容。CPU、GPU 和内存采用整卡背景图,卡片顶边对应 100% 或物理内存总量,底边对应零。存储、网络与无电池整机功率图使用详情下方的剩余高度。辅助信息主要为 10pt / 16pt 行高,内存和存储详情通过 ViewThatFits 按信息组换行,默认卡片仍为 176pt 高。统一 16pt 圆角、10pt 前景内边距和静态轻阴影,图表锚点和提示在同一宿主内处理;不显示常驻图例、数值坐标轴、网格或起止时间。
StackedSeries 仅在渲染时构建累计上下边界:CPU 自下而上为系统 / 用户,内存为应用 / 联动 / 压缩。GPU 同轴绘制总占用、渲染器、分块器三条独立曲线,仅总占用填色。标题后的胶囊显示驱动报告的核心数,正文显示两个阶段读数。任一必要分量缺失或无效时不构造部分总量,原始历史不变。NativePanelCurve 按连续段在匹配的上下边界间闭合面积,保留真实断点;悬浮使用缓存累计边界定位,而提示读取原始分量。有内置电池绘制电量;仅在 IOPowerSources 确认无内置电池时,前台详情轮次通过固定只读 XPC 请求 AppleSMC PSTR,快照和历史独立保存整机瓦数。请求最多一个在途、2 秒超时,不可用退避 60–600 秒,不用旧值填充历史。存储 / 网络通过 PanelCurveProjection.split 在自绘图区顶向下 60% 位置绘制零轴,读取 / 上传向上、写入 / 下载向下,两侧各使用绘图区高度 30% 的振幅并共享自动速率尺度,峰值不映射到卡片顶边。原始速率仍为正值,提示、标记与面积采用同一投影,保留缺失与真实断点。内存的已用三层包含匿名应用 / 系统进程、联动和压缩器物理内存;缓存 / Swap 口径见监控文档,不再显示重复容量进度条。
StackedSeries 仅在渲染时构建累计上下边界:CPU 自下而上为系统 / 用户,内存为应用 / 联动 / 压缩。GPU 同轴绘制总占用、渲染器、分块器三条独立曲线,仅总占用填色。标题后的胶囊显示驱动报告的核心数,正文显示两个阶段读数。任一必要分量缺失或无效时不构造部分总量,原始历史不变。NativePanelCurve 按连续段在匹配的上下边界间闭合面积,保留真实断点;悬浮使用缓存累计边界定位,而提示读取原始分量。有内置电池时,SystemSampler 持有 BatteryMonitor 的采样标记,快照和历史保存 BatteryPowerFlow(供电状态、输入、电池及系统瓦数和读数来源)。BatteryHistoryChart 在详情下方以固定柱距从右向左滚动。一次连续采样移动一格,绘图区左侧多绘一格用于自然移出。停采间隔占独立空档,按配对事件的真实起止在空档中标出睡眠。供电分段来自样本的 powerFlow。共同供电时保留同一组遥测中的两路供给值,前台 B0AP 复核放电方向,卡片与历史图共用该组数据计算蓝绿占比。绘制与悬浮共用布局,悬浮、暂停和减弱动态效果时直接显示最终位置。可见详情按面板节奏通过签名 XPC 读取固定 B0AP 电池功率,失败独立退避并回退到电池报告。App 订阅 kIOPSNotifyPowerSource;面板可见且采样启用时立即重采,并在最多一秒的调度间隔后复读一次,再使用设置的周期。仅在 IOPowerSources 确认无内置电池时,前台详情轮次通过固定只读 XPC 请求 AppleSMC PSTR,快照和历史独立保存整机瓦数。请求最多一个在途、2 秒超时,不可用退避 60–600 秒,不用旧值填充历史。存储 / 网络通过 PanelCurveProjection.split 在自绘图区顶向下 60% 位置绘制零轴,读取 / 上传向上、写入 / 下载向下,两侧各使用绘图区高度 30% 的振幅并共享自动速率尺度,峰值不映射到卡片顶边。原始速率仍为正值,提示、标记与面积采用同一投影,保留缺失与真实断点。内存的已用三层包含匿名应用 / 系统进程、联动和压缩器物理内存;缓存 / Swap 口径见监控文档,不再显示重复容量进度条。
MetricText 用等宽数字直接显示当前读数。连续追加时 NativePanelCurve 在已有 curves 图层进行 0.35 秒水平变换,历史满窗时绘制一个出界旧点;不逐帧重建路径。悬浮时对齐最终位置,暂停、减弱动态效果与断点不启动滚动。风扇是唯一持续动效:FanRotor 将 SF Symbol 绘制到独立图像子图层,固定中心锚点和位置,使用原生 Core Animation 旋转子图层,AppKit 宿主图层保持不变,按历史 RPM 档位映射 90 / 180 / 300 / 450°/s,切档保留相位;零 / 无效 / 缺失值、系统减弱动态效果、暂停、隐藏、遮挡、睡眠或卸载时停止。没有新增帧计时器。样式与异常状态见 [UI 设计规范](ui-design-standard.md)。
设置使用 NeutralTabPicker 静态 AppKit 按钮组,保留 tabGroup / tabButton 语义、选中值与键盘导航。
进程列表使用 view-based NSTableView,只创建可见单元格并原地更新。ProcessTableProjection 负责搜索、排序及悬停 / 选择 / 搜索期间的顺序保持。选择由完整 ProcessIdentity 同步,原生委托回调之后才写回 SwiftUI。只显示 PID、名称、CPU、内存、CPU 功率、线程数六列;使用 plain 样式消除额外行内缩进,由原生滚动宿主在 tile 时按可用宽度分配六列,禁用横向滚动及手动扩宽。路径保留在模型中用于搜索与右键复制。原可见口径 / 能量覆盖说明行移至进程标题提示,保留状态且不占行高。ProcessIconCache 保存 30×30 像素缩略图,最多 128 项 / 1 MiB,30 秒过期、LRU 淘汰、内存压力清空,无轮询任务。
进程列表使用 view-based NSTableView,只创建可见单元格并原地更新。ProcessTableProjection 负责搜索、排序及悬停 / 选择 / 搜索期间的顺序保持。保持顺序时按上一轮显示的完整进程身份取回最新行,仅对新出现的匹配行排序后追加。选择由完整 ProcessIdentity 同步,原生委托回调之后才写回 SwiftUI。只显示 PID、名称、CPU、内存、CPU 功率、线程数六列;使用 plain 样式消除额外行内缩进,由原生滚动宿主在 tile 时按可用宽度分配六列,禁用横向滚动及手动扩宽。路径保留在模型中用于搜索与右键复制。原可见口径 / 能量覆盖说明行移至进程标题提示,保留状态且不占行高。ProcessIconCache 保存 30×30 像素缩略图,最多 128 项 / 1 MiB,30 秒过期、LRU 淘汰、内存压力清空,无轮询任务。
外观、语言和采样配置写入 UserDefaults;固定、暂停、保持唤醒与进程交互不持久化。旧减弱动画偏好键忽略但不清除。AppLanguageScope 传递应用语言并刷新宿主,AppLocalization 为原生菜单取文案;编号风扇保留参数化 Text。
外观、语言、菜单栏勾选和采样配置写入 UserDefaults;固定、暂停、保持唤醒与进程交互不持久化。旧减弱动画偏好键忽略但不清除。AppLanguageScope 传递应用语言并刷新宿主,AppLocalization 为原生菜单取文案;编号风扇保留参数化 Text。
## XPC 与数据边界
+25
View File
@@ -0,0 +1,25 @@
# 电池电量与睡眠历史
## 目标和范围
电池卡片原先用一条面积曲线表示电量。合盖通勤和普通停采都会留下空白,读者也看不出何时切换供电来源。本次调整 Core 的睡眠历史、MenuBar 的电池图、三语资源和验证入口。无内置电池时继续使用整机功率图。
## 设计与步骤
1. 复用已有的系统入睡与唤醒通知,在内存历史中保存已完成的睡眠区间。按最近采样窗口淘汰,并限制区间数。息屏、暂停和普通采样间隔各自保持原有含义。
2. 在详情下方绘制固定柱距、右侧入场的窄柱,柱高表示实测电量,颜色和分组图标标识供电状态。睡眠区间用橙黄色柱和月亮标记。悬浮显示对应读数或睡眠起止。
3. 检查事件配对、历史淘汰、睡眠与缺测命中、充电和接电未充的区别、原生绘制和真实面板。同步架构、监控口径和设计文档。
## 边界
历史沿用最近 60 点的内存窗口。系统通知仅对应用运行期间有效。睡眠期间没有电量或功率测量;显示时间以收到的系统通知为准。浅深色图面复用资源色,窄时间段保留颜色和悬浮详情。
## 实现与验证
已接入 MetricsStore、MetricHistory 和三语电池卡片。BatteryHistoryLayout 按采样顺序从右缘排柱,普通连续更新向左平移一格。短历史左侧留空,长间隔压缩为独立空档,睡眠按实际起止在空档内定位。电源状态用蓝色和插头或闪电,共同供电使用插头、电池双图标与蓝绿分段柱,电池用绿色,睡眠用等距橙黄色柱和月亮。每根柱子单独绘制实色电量和半透明剩余轨道,底部图标按状态分组。保留电量缺测时已知的供电状态。睡眠期间单独显示起止时间。
[实际卡片示例](designs/battery-history/power-states.png)使用模拟读数,从左到右依次为接电、电池供电、睡眠、电池供电、充电、接电。
Debug 构建通过。ResourceCardChecks、BackgroundTrendChecks、MenuBarMetricChecks、NativeMetricDrawingChecks、BatteryPowerChecks、SamplingChecks、LocalizationChecks 均通过,185 个目录词条已核对三语构建资源。模拟合盖场景中,实际移动鼠标至睡眠带后显示月亮、状态及起止时间。最终构建实测面板打开后挂载六个图区,电池图区约 190×50pt;关闭后图区卸载,内容宿主释放。测试通过既有睡眠状态入口驱动事件,真实通勤仍需在运行新版后复验。
固定柱距调整后,在可见的 AppKit 窗口中验证了首柱靠右、连续采样左移一格、动画中途的实际位移、满窗淘汰,以及悬浮和采样中断时停止平移。
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+1 -1
View File
@@ -24,7 +24,7 @@ kymo/ 使用文件系统同步组,源码自动纳入应用;新增非源码
| 采样 | MetricsStore.swift、SystemSampler.swift |
| 设置 | AppearanceSettingsView.swift、SettingsWindowLifecycle.swift |
通常启动仅显示菜单栏图标;打开设置时临时显示 Dock 图标。面板底栏修改可见采样间隔,通用设置控制后台趋势与后台间隔。App 同时启用 Core 的进程与慢指标需求,由实际可见性、暂停与睡眠控制执行。
启动后按选择显示菜单栏指标,取消全部时显示品牌图标;打开设置时临时显示 Dock 图标。面板底栏修改可见采样间隔,菜单栏指标共用面板刷新间隔,通用设置控制无实时展示需求时的后台趋势与后台间隔。App 同时启用 Core 的进程与慢指标需求,由实际可见性、暂停与睡眠控制执行。
颜色与图片放入 Assets.xcassets;字符串位于 Resources 的 Localizable、CPUDetails、Process、StatusItem 四个目录,支持简体中文、繁体中文、英文及跟随系统。SwiftUI 文案使用当前 locale,原生文案通过 AppLocalization 读取。新增文案同步三语、格式参数并检查真实布局:
+10 -4
View File
@@ -1,14 +1,20 @@
# Kymo 免费测试包
当前版本为 **1.2(构建 14)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。
当前版本为 **1.5(构建 17)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。
## 构建与校验
```bash
python3 tools/package_release.py
python3 tools/package_release.py --output dist/v1.5
```
工具构建普通 Release,验证主程序与 XPC 的 ad-hoc 签名、Hardened Runtime、权限和包内容,再校验 ZIP 解压后的签名。默认输出到 Git 忽略的 dist/,文件名按实际版本、构建号与架构生成,包含 ZIP 和同名 .sha256;不覆盖已有产物,可用 --output 指定目录。临时构建目录自动清理。
工具构建普通 Release,验证主程序与 XPC 的 ad-hoc 签名、Hardened Runtime、权限和包内容,再校验 ZIP 解压后的签名。默认输出到 Git 忽略的 dist/,文件名按实际版本、构建号与架构生成,包含 ZIP、同名 .sha256 和签名的 appcast.xml;不覆盖已有产物,可用 --output 指定目录。临时构建目录自动清理。
发布机使用钥匙串账户 `cn.airnan.kymo` 中的 Sparkle EdDSA 私钥,公钥在 `Config/Kymo-Info.plist`。首次访问可能出现钥匙串授权。迁移发布机时用 Sparkle 官方 generate_keys 工具安全备份、导入同一密钥。仅制作本地 ZIP 时可加 `--zip-only`。已有含 Sparkle 的发布包可运行 `python3 tools/package_release.py --sign-existing <原始ZIP路径>`,在原包旁生成 appcast.xml。
每次发版递增工程构建号。脚本用最终 ZIP 生成清单,验证签名、构建号、长度和标签下载地址。先在对应标签(如 v1.5)的 Release 草稿中上传 ZIP、SHA-256 和 appcast.xml,再发布。固定入口是同一仓库的 `releases/download/latest/appcast.xml`。完整 ZIP 同时用于首次安装和应用内升级。1.4 及更早版本需要从发布页手动安装一次含 Sparkle 的版本。
保留上游框架签名,使 ad-hoc Release 的库加载约束能够逐架构固定 Sparkle 的 CDHash。打包时检查主程序签名中的约束和框架实际哈希。变更框架版本时,先核对 SwiftPM 锁定版本与官方分发包,再更新 `Config/Sparkle-library-constraint.plist`;重新签名框架会改变哈希。
下载后在校验文件所在目录执行:
@@ -22,7 +28,7 @@ SHA-256 核对内容一致性,不等同于 Apple 身份认证;校验值应
工程最低 macOS 27.0;实际产物架构由打包输出决定。该工具生成未公证的本地 ad-hoc 签名包,没有 Developer ID 分发身份,不上传、不公证、不修改系统安全策略。
解压后安装完整 kymo.app,先退出旧版再启动新版本;不要单独提取可执行文件或混搭内嵌 XPC。应用通常仅显示菜单栏图标,设置窗口打开时才显示 Dock 图标。
解压后安装完整 kymo.app,先退出旧版再启动新版本;不要单独提取可执行文件或混搭内嵌 XPC。应用在菜单栏展示已勾选的指标,空选时显示品牌图标,设置窗口打开时才显示 Dock 图标。
接收方需核对来源、校验值和本机安全策略,再按 [Apple 对未识别开发者应用的说明](https://support.apple.com/en-gb/102445) 决定是否允许运行。企业管理策略可能禁止运行。本地签名校验通过不能证明其他 Mac 的默认 Gatekeeper 放行,也不代表跨机器安装已验收。
+25
View File
@@ -0,0 +1,25 @@
# 菜单栏动态指标实施计划
## 初版
以 [设置页](designs/menu-bar-metrics-v1/settings.png) 和 [菜单栏](designs/menu-bar-metrics-v1/menu-bar.png) 为视觉依据。现有状态项只显示品牌图标,面板隐藏时默认没有采样需求。目标是让勾选项、预览和真实状态项同步,并保留左键面板与右键菜单入口。
1. Core 保存有序指标的选择,从已有历史提取最近六个采样点,显示 CPU / GPU 利用率、内存已用比例、磁盘读写与网络收发总速率。首次使用按设计图全选,显式空选持久化。菜单栏有指标且屏幕亮起时使用面板间隔,只请求基础数据;沿用一次采样循环、暂停与睡眠规则。
2. UI 共享紧凑柱图和两行文字绘制,App 注入同一选择、历史及语言。Settings 增加独立页,MenuBar 在原生状态按钮内绘制,随选择调整宽度。空选恢复品牌按钮。百分比使用固定刻度,速率使用最近窗口峰值,缺测留空。
3. 补齐三语文案与架构说明。构建并检查选项恢复、采样需求切换、速率、缺值和历史断点。本机验证设置、预览、状态项和面板交互。窄屏菜单栏的可用宽度由系统决定,分辨率与刘海影响需在对应环境验收。
## 实施与验证结果
三个阶段已完成。状态项与预览共用同一读取闭包、有限历史和绘图组件。保留原生按钮负责打开面板和右键菜单,动态数值使用固定栏宽。
- Debug 构建通过。MenuBarMetricChecks、SamplingIntervalChecks、DetailDemandChecks、LocalizationChecks、PanelWindowChecks、SettingsWindowChecks 和三语目录检查通过。
- 本机隔离应用中,逐项取消五项并反向逐项勾选,每步比对设置复选框、预览和真实状态项的辅助功能内容。名称、顺序和数值一致,全选状态项实测宽 356pt,空选为 24pt。单独重启核对空选,以及仅选 CPU 和网络,两组配置均恢复。
- 已检查浅色和深色设置窗口局部截图、外接显示器上的五项状态栏,实测状态项 AX 按压、坐标左击、右键菜单进入设置及键盘 Esc 收起面板。空选的品牌图标也能切换面板。
- 本机主显示器在现有菜单排列下会隐藏放不下的整组指标。实测重新打开已运行且无窗口的应用可进入设置,减少选项后状态项可见。不同桌面排列下的可用宽度与长期能耗仍由实际使用环境决定。
## 第三版紧凑布局
按已确认的[状态项](designs/menu-bar-metrics-v3/menu-bar.png)与[设置预览](designs/menu-bar-metrics-v3/settings.png)调整。四项占用各用 3pt 宽、18pt 高的矩形槽,名称与百分比在右侧上下排列。网络仅显示上下两行速率。设置预览靠近时钟右对齐,继续与状态项共用绘图组件。数据直接取当前快照,沿用已有选项键与采样调度。
Debug 构建和 MenuBarMetricChecks、PanelWindowChecks、SettingsWindowChecks、LocalizationChecks 通过。本机简体中文五项全选实测 239pt,比首版 356pt 缩短约 33%。隔离副本逐项取消并重新勾选,每步比对预览和实际状态项内容及宽度;空选为 24pt。重启后仅选磁盘和网络的配置恢复。本机主目录卷按系统容量计算为 38%,与同期菜单栏一致。已检查局部截图、左键开合、右键进入设置及 Esc 收起面板。
+6 -4
View File
@@ -4,7 +4,7 @@
趋势图跳过无值节点,按真实时间连接前后有效点;有效 0 仍绘制,暂停 / 休眠等显式断点及真实采样空档仍断线。连接只影响曲线外观:缺失时刻悬浮读数为 `--`,原历史不补值。
CPU / GPU / 电池的零值与 100% 分别映射到卡片底边和顶边,内存卡片顶边为物理总量。存储、网络以及无电池设备的功率曲线绘在文字下方。CPU 自下而上堆叠系统态 / 用户态,内存堆叠应用 / 联动 / 压缩,GPU 总利用率、Renderer、Tiler 分别绘制,阶段可能重叠,不相加。电池显示电量,功率提示独立标 W;存储 / 网络以自顶向下 60% 高度为零轴,读取 / 上传向上、写入 / 下载向下;两侧同样使用 30% 绘图区高度振幅及共享自动速率尺度,原始值和提示均保持正速率。不显示常驻数值坐标轴、网格或图例。静态淡色面积在匹配的累计上下边界间按真实连续段闭合,不跨暂停或长空档;单点只显示真实点,必要分量缺失不构造部分总量。悬浮不会替换上方实时主数值。
CPU / GPU 的零值与 100% 分别映射到卡片底边和顶边,内存卡片顶边为物理总量。存储、网络及无电池整机功率曲线绘在文字下方。CPU 自下而上堆叠系统态 / 用户态,内存堆叠应用 / 联动 / 压缩,GPU 总利用率、Renderer、Tiler 分别绘制,阶段可能重叠,不相加。电池主读数与详情下方的柱高表示电量百分比,详情显示正充负放的瓦数;每次采样在右侧加入一柱,柱距固定,悬浮显示实际时间。柱色来自该次供电状态。橙黄色睡眠柱取自系统睡眠、唤醒通知,柱高沿用入睡前一笔电量,缺少该读数时用短柱标记,悬浮显示起止时间,普通缺测留白;存储 / 网络以自顶向下 60% 高度为零轴,读取 / 上传向上、写入 / 下载向下;两侧同样使用 30% 绘图区高度振幅及共享自动速率尺度,原始值和提示均保持正速率。不显示常驻数值坐标轴、网格或图例。静态淡色面积在匹配的累计上下边界间按真实连续段闭合,不跨暂停或长空档;单点只显示真实点,必要分量缺失不构造部分总量。悬浮不会替换上方实时主数值。
## 数据来源
@@ -20,7 +20,7 @@ CPU / GPU / 电池的零值与 100% 分别映射到卡片底边和顶边,内
| 存储容量 | `DiskMonitor`,URL volume resource values | 主卡片为主目录所在卷;卷列表仅本地且非隐藏挂载卷。APFS 卷共享容器空间,不应直接累加 |
| 存储 IO | `DiskIOMonitor`,IOBlockStorageDriver 累计字节 | 物理块设备读写速率,非主卷文件 IO;设备集合变化、计数回退、首次读取均重建基线 |
| SMART | `DiskHealthMonitor` → XPC → `diskutil info -plist` | 主目录所在卷关联报告中的寿命和通电时间;剩余寿命 = 100 − PERCENTAGE_USED(下限 0),通电小时要求高位为 0,多物理存储拒绝合并;不代表所有卷或磁盘 |
| 电池 | `BatteryMonitor`,IOPowerSources 与 AppleSmartBattery | 电量、充电 / 外接电源、循环和功率;功率取电压 × 电流的绝对值,非整机功耗;区分无内置电池和读取失败 |
| 电池 | `BatteryMonitor`,IOPowerSources 与 AppleSmartBattery | 电池净功率正充负放,可见时优先经 XPC 读取 B0AP(si32,小端毫瓦),不支持时读取 PowerTelemetryData.BatteryPower,回退到电池端电压 × 带符号电流,同次输入和负载的差值标 ≈。共同供电要求两路各至少 0.5 W,按同组遥测的实际输入和放电计算占比。三项直读时,功率平衡残差容许 1 W 或负载的 10%,取较大者。阈值为应用判断口径。适配器实际输入与报告能力分列;无内置电池、读取失败分别处理 |
| 无电池整机功率 | 签名 XPC 只读 AppleSMC 固定键 PSTR | 传感器即时整机功率 W,不是插座侧计量;字段口径可对照 [Stats 传感器表](https://github.com/exelban/stats/blob/master/Modules/Sensors/values.swift)。不支持或读取失败显示不可用,不用电池或进程功率替代 |
| 电池健康 | `SystemBatteryHealthMonitor`,`system_profiler SPPowerDataType -json` | 使用系统报告的最大容量百分比,不用当前充电容量推算 |
| 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线;计数缓冲在采样器内复用,容量不足时扩容,仅解析本轮实际返回字节;本地地址保持系统 numeric formatter(含 scope),每轮共用地址缓冲、每接口最终排序一次 |
@@ -41,13 +41,13 @@ CPU / GPU / 电池的零值与 100% 分别映射到卡片底边和顶边,内
- GPU Renderer / Tiler 是活动阶段指标,可能重叠,不能相加成为总占用。GPU 核心数不代表逐核计数;目前没有独立逐核 GPU 占用。
- 网络“全部”仅汇总 active 且名称以 `en` 开头的接口,避免物理链路与 `utun` 双计。接口选择仍可查看其他活动接口;这个规则不等于所有设备和隧道的通用流量归因。
- 进程 CPU 以一个逻辑核满载为 100%,多线程可超过 100%,不能直接与整机 CPU 百分比比较。首次进程采样没有差分值;功率列使用独立 CPU 能量计数差分,不能将进程 CPU 百分比当成耗电。
- 电池卡片仅在非外接电源时显示剩余时间;外接电源显示不适用,系统未给出有效估计时显示未知。
- 电池卡片在系统报告充电时显示距充满的估时,放电或共同供电时显示预估续航。仅外接供电时隐藏整行估时,系统未提供有效估时则显示相应提示。
## 采样与缓存周期
| 数据 | 默认 / 周期策略 |
| --- | --- |
| 常规资源快照 | 面板可见默认 2000ms;新配置隐藏默认停止采样,显式启用后台趋势后默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms |
| 常规资源快照 | 面板可见或勾选菜单栏指标且亮屏时默认 2000ms;其余情况仅在显式启用后台趋势时采样,默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms |
| 进程 | 请求进程详情且面板实际可见、未暂停 / 睡眠时随采样请求更新;异步独立发布,最多一个在途 |
| 进程 CPU 能量 | 复用同轮进程候选,成功后至少 5 秒再读(默认 2 秒轮次下通常约 6 秒);失败 30–600 秒退避,明确不支持后 600 秒;最多一批在途 |
| CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 |
@@ -57,6 +57,8 @@ CPU / GPU / 电池的零值与 100% 分别映射到卡片底边和顶边,内
| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;面板可见时按缓存到期持续刷新,路由键变化、暂停或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 |
| 趋势 | 全局与每接口最多各 60 点,仅内存保存 |
菜单栏按 CPU、GPU、内存、磁盘、网络顺序展示。前四项的等高竖条以 0–100% 从底部填充,右侧显示名称与百分比。CPU / GPU 为总利用率,内存为已用 / 总量,磁盘为主目录所在卷的(总容量 − 可用空间)/ 总容量。网络上行在首行(↑),下行在次行(↓),分别复用当前快照的活动 en 接口汇总,每个方向以十进制 B/s 自动换算单位。缺测的读数独立显示 --。
传感器、卷与慢报告只在请求慢指标的可见采样轮次检查是否到期;后台趋势不启动这些慢读取。快照中的慢指标可能来自之前的缓存。暂停停止发布,不保证取消已进入系统调用的工作。
常规周期允许系统在配置周期 10% 的容差内合并唤醒,前台最多 200ms、后台最多 1 秒;不是严格实时截止。差分的时间分母始终取实际经过的单调时间,历史保留真实采样日期,配置周期不被改写。
+64
View File
@@ -0,0 +1,64 @@
# 电源卡片的供电状态与功率计算方案
已实现。有电池的卡片以电量百分比为主,详情常显带符号的功率,标题显示供电状态,悬浮查看适配器、电池及系统负载明细。
## 现状与实机依据
v1.3 的 BatteryMonitor 对电池电压和电流之积取绝对值。电源卡片用当前充电标记与供电来源给整段历史命名,插电补电和插电放电可能得到相同读数。只有确认无内置电池时,SystemSampler 才经 SMARTService 读取整机功率 PSTR。
本机一次只读 IORegistry 采样中,外接已连接,系统报告未充电,电池瞬时电流为 0。AdapterDetails.Watts 为 70 W,PowerTelemetryData 中 SystemPowerIn 和 SystemLoad 均为 17,453 mW,BatteryPower 为 0 mW。这组数据可核对插电待机;充电、放电及台式机需要另外验证。
## 状态与显示
先判断内置电池是否存在,再分别判断外接是否连接、是否实际供电、电池功率方向。使用 IOPowerSources 判定电源类型及供电来源,结合 ExternalConnected 判定物理连接。UPS 不能算作内置电池。连接状态、充电标记或电流缺失时保留未知。状态判向对直接读数使用 0.05 W 阈值,与一位小数一致;差值估算使用 0.5 W 容差。这是显示策略,尚未跨机标定。历史保留原始值。
有内置电池时,功率详情显示**电池净功率 B**。正值表示实际充入电池的功率,负值表示电池实际放出的功率,零表示当前没有净充放电。适配器的标称或协商能力、Mac 从适配器收到的实际输入分别列在提示中。只要电池端读数有效,即使适配器输入或系统负载缺测,功率仍可显示。
| 场景 | 读数示例 | 功率与状态示例 |
| --- | --- | --- |
| 插电充电 | 适配器报告 65 W,电池实际充入 6 W | +6 W · 充电中 |
| 插电待机 | Mac 接收 17.5 W,电池实测为零 | 0 W · 外接供电 |
| 插电且电池补足供电 | Mac 接收 30 W,电池另放出 8 W | −8 W · 共同供电 |
| 单独电池供电 | 拔电后电池放出 18 W | −18 W · 电池供电 |
| 电池数据需估算 | Mac 实际接收 65 W,同期系统负载 59 W,电池端缺测 | ≈+6.0 W · 充电中 |
| 无内置电池 | 整机功率 PSTR 实测 25 W | 25 W · 整机功率 |
有电池时在标题下方显示大号电量百分比。悬浮可见适配器实际输入、电池充放电、系统负载及可用的适配器报告能力。仅确认外接和电池均在供电时标记“共同供电”。无法确定外接贡献时,仍可按有效的电池读数显示“放电中”。无电池时省去电池项。功率无法读取或可靠估算时显示“--”,已知明细仍可查看。舍入到零时显示“0 W”。
历史按样本保存电池净功率、来源与当时的状态,整卡背景曲线绘制电量百分比,悬浮显示当时的电量和功率。相邻有效电量读数跨插拔连续绘制;暂停、休眠和真实采样空档仍按通用趋势规则断开。无电池整机功率趋势沿用非负尺度。
## 取值与差值
| 量 | 优先来源 | 回退与限制 |
| --- | --- | --- |
| 适配器实际输入 A | Mac 端 PowerTelemetryData.SystemPowerIn,mW 转 W | 可验证的输入端实测电压 × 实测电流;再考虑同口径差值。AdapterDetails.Watts 只表示报告能力 |
| 电池净功率 B | 可见面板优先读取 Apple Silicon SMC 的 B0AP(si32,mW),缺测时读取 BatteryPower,保留正充负放 | 电池端电压 mV × 带符号电流 mA / 1,000,000。解析 NSNumber 时检验负数的有符号及无符号补码表示,平均电流须与瞬时值区分 |
| 系统负载 S | 有电池时读取 SystemLoad;无电池沿用已验证的 PSTR 路径 | 有电池且具备相容读数时可估算;PSTR 作为独立传感器值,不直接混入另一组遥测做差 |
功率详情优先采用电池端有效读数。仅在电池端缺测时,利用同一测量边界内的近似平衡式 **B ≈ A − S** 估算并标“≈”。差值落在测量误差带内时不据此判定充放电方向。确认外接已断开后可取 A = 0;仅有适配器报告能力时,A 仍为未知。悬浮明细缺少 S 或 A 时,同样可用另外两个直接读数推算缺项。
差值只使用同一供电状态、采样窗口相容、量纲和符号已验证的两个直读值。记录来源并独立跟踪电池组和遥测字段的更新。寄存器组连续 120 秒没有更新时停止使用旧读数。插拔或唤醒后等待新状态对应的读数;旧状态缓存、估算值、适配器报告能力及进程 CPU 功率均不参与反推。估算值加“≈”。若计算得到明显负的输入或负载、状态冲突、遥测过期或缺两项,仅保留可信字段。三项实测有差异时保留原值,差额不单列为转换损耗。
IOPowerSources 提供电源状态与适配器信息入口;IORegistry 遥测字段需按机型、系统版本及签名沙盒实测。字段语义可对照 [Apple IOKit 电源接口](https://github.com/apple-oss-distributions/IOKitUser/blob/main/ps.subproj/IOPowerSources.h) 与 [macwatt 的遥测样例](https://github.com/ytomasch/macwatt)。
## 实施顺序与验收
1. 在 Core/Monitors 加入同次采样的数据归一化,在 Core/Models 表达电池存在性、外接供电、电池方向及各功率的来源。以“65 W 适配器、实际充入 6 W 显示 +6 W”和“实际输入 30 W、电池放出 8 W 显示 −8 W”为验收样例,另覆盖只有适配器能力时显示缺测。用已脱敏样本验证上述状态、负数编码、字段缺失、真实零、差值误差和插拔后的旧读数。
2. 使 SystemSampler、MetricsSnapshot 和 MetricHistory 传递同一套读数与历史语义。复用现有采样节奏和无电池 XPC 按需策略。更新 Features/MenuBar 卡片、资源本地化及相关图表提示,验证紧凑宽度、负值格式、过零趋势和历史悬浮。同步维护架构、监控、UI 和测试文档。
3. 运行 Debug 构建及受影响的采样、历史、卡片和本地化检查。用签名应用在笔记本上核对插电充电、插电未充、拔电及重新插电;双源供电和无电池设备分别记录模拟结果和真实硬件结果。以同一时间窗口比对读数和近似平衡式。
## 本轮实测
签名 Debug 应用在本机插电待机时打开了六张资源卡片。将指针移到电池曲线上后,面板显示电量 80%、电池净功率 0 W 和“外接供电”。历史提示中同一时刻的系统负载与实际输入均为 13.3 W,适配器报告功率为 70.0 W。
充入 6 W、插电补放、纯电池放电、供电切换与缺测使用独立 Swift 样本检查;无电池分支使用挂载的生产卡片检查。真实拔插、充电、共同供电及无电池机型仍待对应硬件状态验证。
用户拔电实测后恢复了大号电量百分比及背景电量曲线,净功率回到详情行。面板可见时,插拔通知触发一次立即采样和一次短间隔复读。签名应用在这台已拔电的 Mac 上实际显示 77% 和 −13.4 W;连续六个前台样本都从 B0AP 读到放电瓦数。通知调度和缓存滞后以回归用例验证,尚未测量从物理拔插到首次更新的端到端时间。
## 共同供电修订
1. 在 Core 核对同一组遥测的输入与电池放电,按两路实际供给计算占比,隔离前台 B0AP 与控制器不同时间窗。两路分别达到 0.5 W 才认作共同供电。缺少可靠证据时只显示已知状态。
2. MenuBar 在卡片和历史按同一状态显示双图标与两路功率,柱高保持电量含义。接电放电时尝试电池报告的剩余时间。
3. 用本机微量输入和可重复的双源样本验证方向、差值、过期数据、历史、紧凑卡片与三语;打包独立测试 ZIP。兼容只有电量或缺少部分传感器的设备。
在本机打开签名 Debug 面板采得连续五个样本,适配器输入 0.085 W、B0AP 显示电池放电,均判为电池供电。另一次读取获得电池报告的剩余 389 分钟。实际双源负载用模拟数据验证:适配器 12 W、电池输出 8 W 时,190pt 宽卡片展示两路瓦数和双图标,实色柱段的电池占比为 40%。见[模拟样本的实际卡片](designs/battery-history/joint-supply.png)。放电时优先使用有效的系统剩余时间,缺测时回退至新鲜的电池组 AvgTimeToEmpty,过滤 65535 未知值。[Smart Battery 规范](https://sbs-forum.org/specs/sbdata10.pdf)
+14
View File
@@ -0,0 +1,14 @@
# 正式发布检测与关于页(1.4)
此页记录 1.4 的发布页跳转流程。1.5 的应用内更新见 [Sparkle 更新计划](sparkle-update-plan.md)。
Kymo 从自托管仓库手动发布 ZIP 和校验文件。现有设置窗口包含关于页,应用菜单仅提供设置和退出。此次将菜单定向导航、正式发布检测和用户偏好接入同一窗口。
1. App 将菜单的关于动作传给 SettingsPresentation,Settings 读取同一页签状态。普通设置入口继续打开当前页。
2. Core 读取项目的 releases/latest 接口,以已发布稳定标签与本地版本比较。同版本按发行 ZIP 文件名比较构建号。自动检测默认开启,启动后检查并每 24 小时复查,失败后 1 小时重试。手动检查独立于自动开关。
3. 关于页提供三语开关、检查结果及正式发布页入口。面板在发现更新时提供关于页入口。用户在仓库发布页自行下载。
4. 验证正式接口、版本边界、失败处理、重复请求和开关持久化,再构建并验证菜单与关于页。仓库不可达时允许稍后重试。所有读取均使用公开 HTTPS 接口。
## 验证结果
Debug 构建及 ReleaseUpdateChecks、LocalizationChecks、SettingsWindowChecks、PanelWindowChecks 通过。检查覆盖 195 个三语词条。使用隔离的签名沙盒副本从应用菜单进入关于页,对同一正式接口实测:1.3(15)显示已是最新,标记为 1.2 的测试副本显示新版本 v1.3(15)及发布页入口。关闭自动检测后,重启时保持关闭,关于页的手动按钮仍可完成请求。24 小时复查周期未做等时长实测。
+20
View File
@@ -0,0 +1,20 @@
Kymo 1.3 可以直接在 macOS 菜单栏查看资源占用和网速。点击状态项,即可在同一面板查看资源趋势和进程列表。
### 本版更新
- CPU、GPU、内存和磁盘各用一根竖条和百分比显示当前占用。磁盘显示主目录所在卷的已用空间比例。网络以 ↑ 和 ↓ 分两行显示上传和下载速率。
- 在「设置 → 菜单栏」中可逐项勾选、全选或取消全选。预览与实际菜单栏同步,空选时恢复 Kymo 图标,重启后保留选择。亮屏时菜单栏沿用面板刷新间隔,默认每 2 秒更新。
- 监控面板将六张资源卡片与进程表放在同一页。CPU 和内存以堆叠趋势呈现,存储读写和网络收发沿零轴分向绘制。进程路径可通过搜索定位,也可右键复制。
- 对于没有内置电池且可读取功率传感器的 Mac,电源卡片显示整机即时功率和变化趋势。
### 下载与安装
适用于 Apple Silicon(arm64),最低系统版本为 macOS 27.0。本次构建号为 15,使用本地 ad-hoc 签名,未经 Apple 公证。
ZIP 的 SHA-256 为 `7eb8a746fe30998ef9f380fdf14154744adb6bac9790f16d1241cb88e545d4a8`。将 ZIP 和同名校验文件下载到同一目录后,运行以下命令。
```sh
shasum -a 256 -c kymo-1.3-15-arm64-adhoc.zip.sha256
```
看到 `OK` 后解压,将完整的 `kymo.app` 拖入「应用程序」。如果正在使用旧版,请先退出旧版再替换。
+20
View File
@@ -0,0 +1,20 @@
Kymo 1.4 可以在电池卡片里查看拔电、合盖睡眠和重新接电的过程,也可以从「关于 Kymo」检查新版本。
### 本版更新
- 电量历史从右侧逐格加入新读数。蓝柱表示外接电源,绿柱表示电池供电,橙黄色柱和月亮标记系统睡眠。睡眠柱沿用入睡前的电量,悬停可查看睡眠起止时间。普通采样中断会留白。
- 电池详情显示实际充放电功率,正值表示充电,负值表示放电。面板打开时,插拔电源会触发重新采样,更快反映供电状态变化。
- 应用菜单和菜单栏右键菜单新增「关于 Kymo」,可直接打开设置的关于页。默认启动时检查项目的正式发布,之后每 24 小时复查。可以关闭自动检查,也可以随时手动检查并前往发布页下载。
- 减少进程列表刷新时的重复排序,复用网络接口信息。校正简体中文、繁體中文和英文的指标名称与时间单位。
### 下载与安装
适用于 Apple Silicon(arm64),需要 macOS 27.0 或更高版本。版本为 1.4,构建号为 16,采用 ad-hoc 签名,未经 Apple 公证。
ZIP 的 SHA-256 为 `9ade9db1f2905bc9f63066d963edc7520037b8ceb557948fa0065e853db7e7e4`。将 ZIP 和同名的 `.sha256` 校验文件下载到同一目录,运行以下命令。
```sh
shasum -a 256 -c kymo-1.4-16-arm64-adhoc.zip.sha256
```
看到 `OK` 后,退出正在运行的 Kymo,解压并将完整的 `kymo.app` 拖入「应用程序」。
+21
View File
@@ -0,0 +1,21 @@
Kymo 1.5 新增应用内更新,并改进了电池与适配器共同供电时的显示。
### 本版更新
- 开启自动检查后,Kymo 每次启动时检查更新,运行期间每 6 小时再检查一次。发现新版时,点击面板左上角 Kymo 标志旁的版本角标即可下载,准备好后再次点击即可重启更新。「关于 Kymo」页也能查看进度、手动检查和重试。已有的自动检查偏好会保留。
- 电池与适配器共同供电时,电池卡片显示两路功率,历史电量柱用颜色区分各自的供电占比。微量适配器输入不再触发共同供电提示。放电时可查看预估续航,充电时显示预计充满时间,仅由适配器供电时隐藏估时行。
- 面板底部的「运行时长」更名为「开机时长」,明确显示的是 Mac 自上次启动以来的时间。
### 下载与安装
适用于 Apple Silicon(arm64),需要 macOS 27.0 或更高版本。版本为 **1.5(构建 17)**,采用 ad-hoc 签名,未经 Apple 公证。
从 1.4 或更早版本升级,需要手动安装这一次。下载 ZIP,退出 Kymo,解压后将完整的 `kymo.app` 拖入「应用程序」并重新打开。此后的新版可直接在 Kymo 中下载和安装。
如需校验下载,将 ZIP 与同名的 `.sha256` 文件放在同一目录,运行以下命令。
```sh
shasum -a 256 -c kymo-1.5-17-arm64-adhoc.zip.sha256
```
ZIP 的 SHA-256 为 `cfb7be2f7d6e3b32a25723ab824c2af64e33e100cadfcace32ae719df9475b52`。
+20
View File
@@ -0,0 +1,20 @@
# 现有 ZIP 的应用内更新
## 目标与范围
沿用自托管 Release 的完整应用 ZIP 和现有自动检查偏好。启动时及运行中每六小时检查一次,发现新版后用户可从面板品牌角标或设置关于页下载,再点击重启。首次切换需要手动安装含更新器的版本。
## 设计与实施顺序
1. 为主应用接入 Sparkle 2 和沙盒安装服务。发布端为最终 ZIP 增加 EdDSA 签名和 appcast 附件,私钥保存在发布机器的钥匙串。保留 Release / SHA-256 分发。
2. Core 管理检测偏好与更新阶段,Sparkle 负责定时调度,App 装配更新器,MenuBar 和 Settings 映射同一状态与动作。下载、校验、替换整个应用和重新启动由 Sparkle 执行。
3. 更新三语文本、发版工具和架构说明,构建 Debug / Release。用隔离的两个构建、测试更新源和真实 ZIP 验证下载、重启、保留偏好;检查关闭自动检测、无更新、错误与重试。
4. 在本页记录验证边界。重点验证 ad-hoc 和 Hardened Runtime 的兼容性、框架内嵌签名、沙盒通信与安装目录权限。用户现有应用和正式发布源不参与升级测试。
## 实施与验证记录
- 1.5(17)锁定 Sparkle 2.10.1,沿用 1.4 的偏好键。应用启动后立即发起后台检查,后续按 21600 秒的配置调度。自动检查与手动下载独立。
- 原 ad-hoc Release 直接加载动态库时,dyld 以缺少共同 Team ID 拒绝启动。现使用 Apple 的库加载约束,保留上游框架签名,将 arm64 / x86_64 两个 CDHash 写入主程序签名。实测可启动;另一个隔离副本中重签框架后,dyld 以库加载约束不匹配拒绝载入。[Apple 库加载约束](https://developer.apple.com/videos/play/wwdc2023/10266/) · [Sparkle 沙盒接入](https://sparkle-project.org/documentation/sandboxing/)
- 在独立安装目录和随机 bundle ID 下,使用本地更新源、临时 EdDSA 密钥实测。关于页从 901 下载并重启到 902。重启前关闭自动检测,新进程没有请求清单,手动检查返回已是最新。另一组从真实面板 Kymo 右上角按下下载,改动一个字节的同长度 ZIP 在解压前被拒绝,角标进入重试;恢复原 ZIP 后从角标完成 911 → 912,记录到新进程启动及其自动检查。
- Debug / Release 构建、原始及解压后的主程序和内嵌服务签名、库加载约束、正式格式 ZIP 的 SHA-256、200 项三语资源、更新状态、实际面板与打包 SMARTService RPC 已验证。正式附件路由用已发布 v1.4 校验文件实测。6 小时周期核对配置和 Sparkle 调度入口,未等待满周期;跨机 Gatekeeper 和需管理员授权的安装未实测。两个真实升级使用测试源,正式更新源需待发版。钥匙串授权弹窗显示期间,设置窗口用例曾因窗口未获焦点失败。授权完成后针对最终 ZIP 解压产物复测,窗口首次显示、焦点恢复、关闭再打开全部通过。
- 发布钥匙串授权后,已为 1.5(17)的最终 ZIP 生成正式 appcast.xml。使用应用内置公钥独立验证清单和 ZIP 的 Ed25519 签名,并复核 ZIP 的 SHA-256、附件长度和 v1.5 标签下载地址。
+9 -5
View File
@@ -25,10 +25,11 @@ python3 tools/check.py --list
| 检查 | 覆盖范围 |
| --- | --- |
| SamplingChecks、SamplingIntervalChecks、DetailDemandChecks | 差分首帧与重置、间隔与旧偏好、暂停 / 恢复、隐藏零采样、同时详情需求与需求撤回、独立进程发布与需求代次 |
| SamplingChecks、SamplingIntervalChecks、DetailDemandChecks | 差分首帧与重置、间隔与旧偏好、暂停 / 恢复、隐藏零采样、同时详情需求与需求撤回、独立进程发布与需求代次、长前台周期的电源切换即时重采与复读 |
| StackedSeriesChecks | CPU / 内存 / GPU 累计上下边界、分量缺失 / 无效 / 负值 / 溢出拒绝、零值、GPU 总和与共同断点 |
| BackgroundTrendChecks、PanelCurveChecks | 真实时间域、周期切换、短暂隐藏连续性、60 点有界历史、缺失与非有限点、有效 0、显式停采及真实空档 |
| UnifiedPanelChecks、StageCChecks | 本机采样边界、网络汇总与接口历史、电池估时及系统报告解析 |
| BatteryPowerChecks | 65 W 适配器实际充入 6 W、插电补放、仅电池、单边缺测与反推、带符号的寄存器编码、独立电池读数、旧遥测与唤醒失效、拔电时电源状态与缓存读数先后到达 |
| MachPortChecks | CPU / 内存各 1,000 轮后 host 发送权引用无增长 |
| MemoryChecks、MemoryHeaderChecks | 含压缩 / 缓存 / Swap 的分类守恒、二进制容量、压力 / 缓存 / Swap 标题及三语缺失 / 零值 |
| GPUStatisticsChecks、CPUTemperatureChecks、FanChecks、DiskHealthChecks | 当前 GPU 利用率与历史、温度范围与解码、风扇零值 / 无效值、历史速度边界与切档相位、SMART 边界与多物理存储拒绝合并 |
@@ -39,23 +40,26 @@ python3 tools/check.py --list
| NetworkAddressChecks、ProcessIconCacheChecks | 沙盒下地址格式 / 速率;图标位图、尺寸、共享、过期、LRU 与严格预算 |
| AppearancePreferencesChecks、LocalizationChecks、PresentationChecks | 外观与偏好隔离、语言持久化、编译资源、窗口显式 / 系统外观切换 |
| CodeIdentityChecks、PanelAssetChecks、KeepAwakeChecks | 签名身份拒绝边界、编译颜色及对比度、真实 IOPM 断言开关与释放 |
| NativeMetricDrawingChecks(--gui) | 实际曲线 / 堆叠色带、双向速率面积和零轴、方向 / 悬浮 / 断点及累计边界定位、单点无虚构填充、隐藏序列隔离、缺失点接续与真实断点、悬浮缓存、滚动时间域变换、悬浮停止动画、断点、无渐变 / 遮罩、卸载 |
| NativeMetricDrawingChecks(--gui) | 实际曲线 / 堆叠色带、带符号瓦数零线与两端悬浮点、双向速率面积和零轴、方向 / 悬浮 / 断点及累计边界定位、单点无虚构填充、隐藏序列隔离、缺失点接续与真实断点、悬浮缓存、滚动时间域变换、悬浮停止动画、断点、无渐变 / 遮罩、卸载 |
| FanRotorChecks(--gui) | 独立图层多角度 / 多尺寸旋转中心不漂移,原生旋转动画时长、无效 / 零 / 缺失、非活动 / 减弱动态效果及卸载停转 |
| ResourceCardChecks(--gui) | 生产卡片与曲线真实挂载,190 / 205⅓ / 400pt、浅深色及三语下的整卡背景图区、存储与网络的独立图区及文字换行边界、10pt 三语内存 / 存储详情在固定卡片内的边界、模拟有电池 / 无电池 / 未知和失败的历史序列及单位尺度、卸载;比较 AppKit 实际尺寸,允许分数点窗口尺寸取整 |
| ReleaseUpdateChecks | 自动检查偏好迁移、手动检查、双入口共用动作、重复点击、重试与重启回调仅触发一次;真实 ZIP 验证见 [Sparkle 更新计划](sparkle-update-plan.md) |
| ResourceCardChecks(--gui) | 生产卡片与曲线真实挂载,190 / 205⅓ / 400pt、浅深色及三语下的整卡背景图区、存储与网络的独立图区及文字换行边界、10pt 三语内存 / 存储详情在固定卡片内的边界、电量柱的固定间距、右缘追加、已满窗口移出、原生图层平移和供电分组、共同供电柱的蓝绿分色、睡眠区间与普通停采的悬浮命中、缺少电量时保留供电状态,以及无电池时的功率曲线、卸载;比较 AppKit 实际尺寸,允许分数点窗口尺寸取整 |
| ProcessSectionChecks(--gui) | 生产进程区域固定 176pt,三语 / 浅深色及 340 / 628pt 下移除说明行后表格占满剩余高度且无横向滚动条 |
| NativeContentHostChecks(--gui) | 小数末位增减后直接显示最终读数、更新帧与稳定帧像素一致、父环境继承、挂载身份、有限尺寸和卸载 |
| NativeProcessTableChecks(--gui) | 原生虚拟表格、原地更新、身份选择、六列窄宽度适配、隐藏路径列但真实菜单复制路径、排序 / 列序 / 复制 / 三语列头、合成 Esc 投递 |
| MenuBarMetricChecks | 全选 / 取消全选与单项持久化、隐藏面板后跟随前台间隔调整、息屏与暂停、四项占用、磁盘容量口径、网络双向独立速率、零值与缺测 |
| TabPickerChecks、LanguageScopeChecks、SettingsWindowChecks(--gui) | 原生页签选择与键盘、已挂载语言即时切换、设置焦点 / 最小化恢复 / Dock 生命周期 |
| PanelWindowChecks(--gui) | 真实 NSPanel 居中、尺寸反馈、固定、遮挡可见性、显式关闭重开和退出复位 |
| ReleaseServiceChecks(--services) | 临时 hardened sandbox 主程序调用本轮实际嵌入服务,核对同 UID footprint / 能量与传感器 |
| ReleaseServiceChecks(--services) | 临时 hardened sandbox 主程序调用本轮实际嵌入服务,核对同 UID footprint / 能量与传感器,并输出本机 B0AP 带符号瓦数或不可用状态 |
| SandboxNetworkChecks(--network) | 使用实际主应用 entitlement 访问产品 HTTPS 端点,核对持久网络目录无新增或变更文件 |
LocalizationCatalogChecks.py 检查全部保留键的三语完整性与格式参数,不替代翻译语义和实际排版。服务 / 网络不可达也会使对应检查失败。
LocalizationCatalogChecks.py 检查全部词条的三语完整性与格式参数。统一检查入口还逐项比对构建包内四份字符串表与源译文;翻译语义和实际排版需另行核对。服务 / 网络不可达也会使对应检查失败。
## 实际应用验收
自动检查可验证模型、原生组件和窗口策略,不能代替正式应用事件。代码改动涉及相应路径时,应在本机完成:
- 在「设置 → 菜单栏」逐项勾选与取消,核对预览与真实状态项的顺序、数值及宽度。空选保留品牌入口,重启保留选项。系统菜单栏宽度不足时检查重新打开应用的设置入口。
- 菜单栏左键打开 / 收起、右键菜单、设置入口与退出。
- 六张资源卡片与等高通栏进程同页,三列资源 / 窄屏两列及单列和整体滚动,关闭重开。
- 固定 / 取消固定、外部点击、Esc 分层处理,图表悬浮、复制、缺失值。
+4 -4
View File
@@ -19,7 +19,7 @@
| 卡片 | 基础高 176,圆角 16,前景内边距 10 |
| 动态高度 | CPU 核型横向分组,逐核单元一行基础预算,超出每行增加 15;GPU 超过一行风扇后每行增加 18;所有行采用最大结构预算,不裁掉硬件数据 |
| 标题 / 主值区域 | 标题行 16,主值行 34,区域间距 4 |
| 背景趋势 | CPU / GPU / 电池从卡底 0 到卡顶 100%,内存从卡底 0 到卡顶物理总量。存储和网络使用详情下方独立图区,零轴位于该区高度的 60% |
| 背景趋势 | CPU / GPU / 电量从卡底 0 到卡顶 100%,内存从卡底 0 到卡顶物理总量。存储和网络使用详情下方独立图区,零轴位于该区高度的 60% |
| 逐核格子 | 每核一个 7×11 单元,从底部按真实比例填充;核型短标签与数量在上方 |
| 顶栏 / 底栏 | 32 / 26。标题右上显示版本胶囊,开机时间在底栏最左,间隔输入框宽 50 |
@@ -30,13 +30,13 @@
- 主要辅助信息 10pt、行高 16pt,标签 secondary、数值 primary / medium;逐核紧凑短标签 9pt、行高 12pt。悬浮提示沿用 9pt。内存分类 / 存储读写和健康说明在宽度不足时按组换行;少数紧凑单行最低缩至 90%,避免回落到原 8pt。
- 主数值使用 primary,提高浅深色对比度;网络仅方向箭头着色。CPU 青绿(MetricCPU)、GPU 玫红(MetricGPU)、内存蓝(MemoryApplication)、电池绿(MetricBattery)、存储琥珀(MetricDisk)、下载蓝(MetricMemory)、上传琥珀(SeriesUpload)。所有颜色来自 Assets。
- 温度在标题右侧;CPU ≥90°C 使用红色和既有高温说明。内存压力沿用正常 / 警告 / 严重颜色和文字,不能仅靠颜色传达状态。
- CPU、GPU、内存和电池的文字叠在整卡趋势上。存储、网络和无电池整机功率卡优先安排详情高度,曲线接在下方。保留放大后的辅助字号、行距和按组换行,不使用模糊或渐变。
- CPU、GPU 和内存的文字叠在整卡趋势上。电池、存储、网络和无电池整机功率卡优先安排详情高度,图接在下方。保留放大后的辅助字号、行距和按组换行,不使用模糊或渐变。
- 卡片采用 PanelCard、面板采用 PanelBackground 的浅深色资源。边框为 primary 浅色 2.5% / 深色 6%;静态轻阴影半径 4、纵偏移 1,不给文字或曲线单独加阴影。
## 曲线与悬浮
- 不显示常驻图例、数值坐标轴、网格、起止时间与独立图框。背景曲线线宽 1.4,填充为同色静态实色透明度:浅色 12%、深色 16%;不使用渐变层或遮罩层,连续追加时仅移动已有曲线图层。
- CPU 自下而上堆叠系统态 / 用户态;内存堆叠应用 / 联动 / 压缩,顶边为物理总量、空余为可用空间;GPU 总利用率、Renderer、Tiler 共用百分比轴但各自绘制,只有总利用率填充面积。电池背景显示电量,功率在悬浮中单独注明 W,不能与电量共用未解释的尺度。存储和网络采用上下双向曲线:自顶向下 60% 为零轴(细线),向上读取 / 上传、向下写入 / 下载,两侧各有绘图区高度 30% 的振幅,共用自动速率尺度,峰值不触及卡片顶边。
- CPU 自下而上堆叠系统态 / 用户态;内存堆叠应用 / 联动 / 压缩,顶边为物理总量、空余为可用空间;GPU 总利用率、Renderer、Tiler 共用百分比轴但各自绘制,只有总利用率填充面积。每根电池柱都是独立的圆角进度条,实色从底部向上表示电量,余量使用同色半透明轨道,柱间留空。绿柱和电池图标表示电池供电或放电,蓝柱配插头或闪电分别表示外接供电或充电。共同供电时显示蓝色插头与绿色电池,两路瓦数分别列出,实色柱段按适配器和电池的供电占比分色。未知来源为灰色。电量柱保持固定间距,最新值从右缘进入。睡眠区间使用等距橙黄色柱和月亮,柱高沿用入睡前一笔电量,缺少该读数时用短柱标记,普通停采留白。窄段省略图标,悬浮可读出对应状态。存储和网络采用上下双向曲线:自顶向下 60% 为零轴(细线),向上读取 / 上传、向下写入 / 下载,两侧各有绘图区高度 30% 的振幅,共用自动速率尺度,峰值不触及卡片顶边。
- 百分比固定 0–100%;内存固定当前物理总量;速率保留既有自动范围及延迟缩小策略,不为视觉任意改变振幅。
- 时间使用真实采样日期;有效 0 保留,nil / 非有限数值不补值。沿用既有缺失节点接续与显式断点 / 长空档策略。堆叠缺少任一必要分量时不构造部分总量;面积在匹配上下边界之间按每个连续段分别闭合,不能填过暂停空档。
- 单点历史仅显示真实点,不绘制虚构面积。全缺失无曲线和填充。
@@ -50,7 +50,7 @@
| CPU | 总占用、温度 / 高温状态、左对齐用户 / 系统;核型横向分组、每核独立单元,数值通过悬浮和辅助功能提供;禁止把核数画成亮灯计数 |
| GPU | 总占用、温度,GPU 标题后紧跟实际核心数胶囊,带曲线色标的渲染器 / 分块器读数、旋转风扇图标与转速或等待状态 |
| 内存 | 已用 / 总量 GiB、压力标签;应用 / 联动 / 压缩单行及可用量,移除重复容量条;占用率、缓存和 Swap 保留在压力提示中 |
| 电池 | 电量;电源在标题右侧;功率、健康 / 循环、估时依次左对齐;确认无内置电池时切换为整机即时 W 与独立趋势;传感器缺失显示不可用,电池读取失败不触发切换 |
| 电池 | 主读数为电量百分比,详情用绿色电池图标标识带符号的电池瓦数,共同供电时以蓝色插头和绿色电池分别标识两路输出,电源状态在标题右侧;悬浮查看该时刻的适配器输入、报告能力、电池及负载,差值标 ≈;保留健康 / 循环与估时;确认无内置电池时切换为整机即时 W 与独立趋势;传感器缺失显示不可用,电池读取失败不触发切换 |
| 存储 | 已用 / 总量 GB;本地卷入口在标题右侧;可用、读写、寿命 / 通电依次左对齐;保留卷弹出层与口径说明 |
| 网络 | 黑白主数值与着色方向箭头;单行累计收发;标题右侧接口与路径状态;两行公网 / 本地 IP 及全文提示 / 选择 / 复制 |
+33 -4
View File
@@ -19,6 +19,8 @@
CC1000000000000000000003 /* ProcessMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000004 /* ProcessMetrics.swift */; };
CC1000000000000000000005 /* ProcessEnergy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000006 /* ProcessEnergy.swift */; };
CC1000000000000000000007 /* ProcessEnergyReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000008 /* ProcessEnergyReader.swift */; };
1A5000000000000000000001 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 1A5000000000000000000002 /* Sparkle */; };
1A5000000000000000000004 /* Sparkle.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 1A5000000000000000000006 /* Sparkle.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -41,6 +43,13 @@
);
name = "Embed XPC Services";
};
1A5000000000000000000005 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
dstPath = "";
dstSubfolderSpec = 10;
files = (1A5000000000000000000004 /* Sparkle.framework in Embed Frameworks */,);
name = "Embed Frameworks";
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
@@ -58,6 +67,7 @@
CC1000000000000000000006 /* ProcessEnergy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessEnergy.swift; path = kymo/Core/Models/ProcessEnergy.swift; sourceTree = SOURCE_ROOT; };
CC1000000000000000000008 /* ProcessEnergyReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessEnergyReader.swift; path = SMARTService/ProcessEnergyReader.swift; sourceTree = SOURCE_ROOT; };
D9E51E73309338B0000608DE /* kymo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = kymo.app; sourceTree = BUILT_PRODUCTS_DIR; };
1A5000000000000000000006 /* Sparkle.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Sparkle.framework; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
@@ -77,6 +87,7 @@
D9E51E70309338B0000608DE /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
files = (
1A5000000000000000000001 /* Sparkle in Frameworks */,
);
};
/* End PBXFrameworksBuildPhase section */
@@ -144,6 +155,7 @@
D9E51E70309338B0000608DE /* Frameworks */,
D9E51E71309338B0000608DE /* Resources */,
BB0000000000000000000004 /* Embed XPC Services */,
1A5000000000000000000005 /* Embed Frameworks */,
);
buildRules = (
);
@@ -154,6 +166,7 @@
D9E51E75309338B0000608DE /* kymo */,
);
name = kymo;
packageProductDependencies = (1A5000000000000000000002 /* Sparkle */,);
productName = kymo;
productReference = D9E51E73309338B0000608DE /* kymo.app */;
productType = "com.apple.product-type.application";
@@ -182,6 +195,7 @@
"zh-Hant",
Base,
);
packageReferences = (1A5000000000000000000003 /* Sparkle */,);
mainGroup = D9E51E6A309338B0000608DE;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
@@ -235,6 +249,14 @@
};
/* End PBXTargetDependency section */
/* Begin XCRemoteSwiftPackageReference section */
1A5000000000000000000003 /* Sparkle */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/sparkle-project/Sparkle"; requirement = {kind = exactVersion; version = 2.10.1; }; };
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
1A5000000000000000000002 /* Sparkle */ = {isa = XCSwiftPackageProductDependency; package = 1A5000000000000000000003 /* Sparkle */; productName = Sparkle; };
/* End XCSwiftPackageProductDependency section */
/* Begin XCBuildConfiguration section */
BB0000000000000000000028 /* Debug configuration for PBXNativeTarget "SMARTService" */ = {
isa = XCBuildConfiguration;
@@ -303,7 +325,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 14;
CURRENT_PROJECT_VERSION = 17;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
@@ -325,7 +347,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.2;
MARKETING_VERSION = 1.5;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -371,7 +393,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 14;
CURRENT_PROJECT_VERSION = 17;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEPLOYMENT_POSTPROCESSING = YES;
@@ -388,7 +410,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.2;
MARKETING_VERSION = 1.5;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
@@ -407,6 +429,9 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
CODE_SIGN_ENTITLEMENTS = Config/Kymo.entitlements;
INFOPLIST_FILE = Config/Kymo-Info.plist;
PACKAGE_SKIP_AUTO_EMBEDDING_DYNAMIC_BINARY_FRAMEWORKS = YES;
ENABLE_APP_SANDBOX = YES;
ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;
ENABLE_PREVIEWS = YES;
@@ -438,6 +463,10 @@
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
CODE_SIGN_ENTITLEMENTS = Config/Kymo-adhoc.entitlements;
LIBRARY_LOAD_CONSTRAINT = "Config/Sparkle-library-constraint.plist";
INFOPLIST_FILE = Config/Kymo-Info.plist;
PACKAGE_SKIP_AUTO_EMBEDDING_DYNAMIC_BINARY_FRAMEWORKS = YES;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;
@@ -0,0 +1,15 @@
{
"originHash" : "e721da7f9826abdffcb6185e886155efa2514bd6234475f1afa893e29eb258d6",
"pins" : [
{
"identity" : "sparkle",
"kind" : "remoteSourceControl",
"location" : "https://github.com/sparkle-project/Sparkle",
"state" : {
"revision" : "ab7d71291238df6e0492143b120c9b696a35f603",
"version" : "2.10.1"
}
}
],
"version" : 3
}
+44 -8
View File
@@ -1,5 +1,7 @@
import SwiftUI
import AppKit
import IOKit.ps
import notify
/// AppKit owns launch only; MenuBar owns windows, Core owns sampling and preferences.
@main @MainActor struct kymoApp {
@@ -16,14 +18,22 @@ import AppKit
private let metrics = MetricsStore()
private let awake = KeepAwakeService()
private let presentation = SettingsPresentation()
private let updates = ReleaseUpdates()
private lazy var updater = SparkleUpdater(updates: updates)
private let appearance = AppearancePreferences()
private let menuBarPreferences = MenuBarPreferences()
private let language = LanguagePreferences()
private var openSettingsAction: (() -> Void)?
private var scenes: AnyObject?
private var menuBar: MenuPanelController?
private var powerSourceToken: Int32?
private var workspaceTokens: [NSObjectProtocol] = []
func applicationWillFinishLaunching(_ notification: Notification) {
var token: Int32 = 0
if notify_register_dispatch(kIOPSNotifyPowerSource, &token, .main, { [weak self] _ in
MainActor.assumeIsolated { self?.metrics.powerSourceDidChange() }
}) == NOTIFY_STATUS_OK { powerSourceToken = token }
let center = NSWorkspace.shared.notificationCenter
for (name, sleeping) in [(NSWorkspace.willSleepNotification, true), (NSWorkspace.didWakeNotification, false)] {
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
@@ -35,10 +45,21 @@ import AppKit
MainActor.assumeIsolated { self?.metrics.setDisplaySleeping(sleeping) }
})
}
let readings = { [metrics, menuBarPreferences, language] () -> [MenuBarReading] in
let selected = menuBarPreferences.selected
guard !selected.isEmpty else { return [] }
let locale = language.locale
return MenuBarReading.readings(selection: selected, snapshot: metrics.snapshot) {
AppLocalization.string($0.titleKey, locale: locale)
}
}
menuBarPreferences.onDemandChange = { [metrics] in metrics.setMenuBarEnabled($0) }
metrics.setMenuBarEnabled(!menuBarPreferences.selected.isEmpty)
let settings = NSHostingSceneRepresentation {
Settings {
AppLanguageScope(preferences: language, onChange: { self.configureMainMenu() }) { [self] in
AppearanceSettingsView(preferences: appearance, language: language, sampling: metrics.sampling, presentation: presentation)
AppearanceSettingsView(preferences: appearance, language: language, sampling: metrics.sampling,
menuBar: menuBarPreferences, readings: readings, presentation: presentation, updates: updates)
}
}
}
@@ -47,15 +68,14 @@ import AppKit
openSettingsAction = { settings.environment.openSettings() }
configureMainMenu()
metrics.setDetailDemand(processes: true, slowMetrics: true)
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) },
menuBar = MenuPanelController(readings: readings, visibility: { [metrics] in metrics.setPanelVisible($0) },
menuTitle: { [language] key in
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
}, openSettings: { [weak self] in self?.settingsCommand() }, openAbout: { [weak self] in self?.aboutCommand() }) { [self] panel in
AppLanguageScope(preferences: language) {
MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation,
MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, updates: self.updates,
presentation: panel, onOpenSettings: { [weak self] in
self?.menuBar?.hide()
settings.environment.openSettings()
self?.settingsCommand()
}, onPreferredHeight: { [weak self] height in
self?.menuBar?.setPreferredContentHeight(height)
})
@@ -68,6 +88,10 @@ import AppKit
let root = NSMenu()
let application = NSMenu()
let appItem = NSMenuItem(); appItem.submenu = application; root.addItem(appItem)
let about = NSMenuItem(title: AppLocalization.string("action.about", locale: language.locale), action: #selector(aboutCommand), keyEquivalent: "")
about.target = self
application.addItem(about)
application.addItem(.separator())
let settings = NSMenuItem(title: AppLocalization.string("action.settings", locale: language.locale), action: #selector(settingsCommand), keyEquivalent: ",")
settings.target = self
application.addItem(settings)
@@ -87,14 +111,20 @@ import AppKit
NSApp.mainMenu = root
}
@objc private func settingsCommand() {
func applicationDidFinishLaunching(_ notification: Notification) { updater.start() }
@objc private func settingsCommand() { showSettings() }
@objc private func aboutCommand() { showSettings(.about) }
private func showSettings(_ page: SettingsPage? = nil) {
NSApp.setActivationPolicy(.regular)
presentation.request()
presentation.request(page)
menuBar?.hide()
openSettingsAction?()
}
func applicationWillTerminate(_ notification: Notification) {
if let powerSourceToken { notify_cancel(powerSourceToken) }
workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver)
workspaceTokens.removeAll()
menuBar?.shutdown()
@@ -104,5 +134,11 @@ import AppKit
scenes = nil
}
// Finder or Spotlight remains a settings entry point when macOS hides a wide status item.
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag { settingsCommand() }
return true
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
}
@@ -0,0 +1,38 @@
{
"colors": [
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.172549",
"green": "0.427451",
"blue": "0.717647",
"alpha": "1.000"
}
}
},
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.439216",
"green": "0.698039",
"blue": "0.988235",
"alpha": "1.000"
}
},
"appearances": [
{
"appearance": "luminosity",
"value": "dark"
}
]
}
],
"info": {
"author": "xcode",
"version": 1
}
}
+6
View File
@@ -26,6 +26,12 @@ nonisolated enum MetricFormat {
return String(format: "%.1f %@", scaled, units[index])
}
static func signedWatts(_ value: Double?) -> String {
guard let value, value.isFinite else { return "--" }
if abs(value) < 0.05 { return "0 W" }
return (value < 0 ? "−" : "+") + watts(abs(value))
}
static func watts(_ value: Double?) -> String {
guard let value, value.isFinite, value >= 0 else { return "--" }
return String(format: "%.1f W", value)
+90
View File
@@ -0,0 +1,90 @@
import Foundation
nonisolated struct PowerReading: Sendable, Equatable {
enum Source: Sendable { case smc, telemetry, instantaneous, average, balance }
let watts: Double
var source: Source = .telemetry
}
nonisolated struct BatteryPowerFlow: Sendable {
var connected: Bool?
var externalSupply: Bool?
var charging: Bool?
var battery: PowerReading?
var input: PowerReading?
var load: PowerReading?
var adapterCapacity: Double?
struct JointSupply: Sendable {
let adapter: PowerReading
let discharge: PowerReading
var batteryFraction: Double { discharge.watts / (adapter.watts + discharge.watts) }
}
// Classification floor in watts, separate from the resolution of the displayed readings.
private static let minimumContribution = 0.5
private(set) var registryJointSupply: JointSupply?
var jointSupply: JointSupply? {
guard connected == true, let battery,
battery.watts <= -Self.minimumContribution else { return nil }
if battery.source == .smc { return registryJointSupply }
guard let input, input.watts >= Self.minimumContribution else { return nil }
// IOPS reports a single primary source. Override its battery-only indication
// only if all three direct telemetry channels independently support the split.
if externalSupply == false &&
(input.source != .telemetry || battery.source != .telemetry || load?.source != .telemetry) { return nil }
let discharge: PowerReading
if battery.source == .telemetry || battery.source == .balance {
discharge = PowerReading(watts: -battery.watts, source: battery.source)
} else if let load, load.source == .telemetry, input.source == .telemetry {
discharge = PowerReading(watts: load.watts - input.watts, source: .balance)
} else { return nil }
guard discharge.watts >= Self.minimumContribution else { return nil }
if let load, load.source == .telemetry, input.source == .telemetry {
// Reject conflicting measured channels rather than normalize an unexplained excess.
let residual = abs(input.watts + discharge.watts - load.watts)
guard residual <= max(1, 0.1 * load.watts) else { return nil }
}
return JointSupply(adapter: input, discharge: discharge)
}
mutating func applyBatterySensor(_ watts: Double) {
// The gauge may still report the last charging sample just after unplugging.
guard watts <= 0 || (externalSupply != false && connected != false) else { return }
if battery?.source != .smc { registryJointSupply = jointSupply }
battery = PowerReading(watts: watts, source: .smc)
// Estimates made from older registry measurements no longer share a sampling window.
if load?.source == .balance { load = nil }
if input?.source == .balance { input = nil }
if connected == false, load == nil, watts < 0 {
load = PowerReading(watts: -watts, source: .balance)
}
}
enum State: Sendable {
case charging, combined, battery, discharging, external, unknown
}
var state: State {
if let battery {
// Differences of two sensors are less precise than a battery-terminal reading.
let threshold = battery.source == .balance ? 0.5 : 0.05
if battery.watts >= threshold { return .charging }
if battery.watts <= -threshold {
if jointSupply != nil { return .combined }
if connected == false || externalSupply == false { return .battery }
if let input, input.source != .balance {
if input.watts < Self.minimumContribution { return .battery }
if battery.watts > -Self.minimumContribution { return .external }
}
return .discharging
}
}
if battery == nil, charging == true, connected != false, externalSupply != false { return .charging }
if externalSupply == false { return .battery }
if externalSupply == true || (input?.watts ?? 0) > 0 { return .external }
if connected == false { return .battery }
return .unknown
}
}
+49
View File
@@ -0,0 +1,49 @@
import Foundation
nonisolated enum MenuBarMetric: String, CaseIterable {
case cpu, gpu, memory, disk, network
var titleKey: String { self == .disk ? "menuBar.disk" : "metric." + rawValue }
}
nonisolated struct MenuBarReading: Equatable {
enum Content: Equatable {
case usage(Double?)
case network(upload: String, download: String)
}
let metric: MenuBarMetric
let title: String
let content: Content
static func readings(selection: Set<MenuBarMetric>, snapshot: MetricsSnapshot,
title: (MenuBarMetric) -> String) -> [Self] {
MenuBarMetric.allCases.filter(selection.contains).map { metric in
let content: Content = switch metric {
case .cpu: .usage(snapshot.cpu?.usage)
case .gpu: .usage(snapshot.gpuUsage)
case .memory: .usage(snapshot.memory?.usage)
case .disk: .usage(snapshot.disk?.usage)
case .network: .network(upload: compactRate(snapshot.uploadRate), download: compactRate(snapshot.downloadRate))
}
return Self(metric: metric, title: title(metric), content: content)
}
}
private static func compactRate(_ value: Double?) -> String {
MetricFormat.rate(value).replacingOccurrences(of: ".0 ", with: " ")
}
var accessibilityText: String {
switch content {
case let .usage(value): "\(title) \(MetricFormat.percent(value))"
case let .network(upload, download): "\(title) ↑ \(upload), ↓ \(download)"
}
}
}
nonisolated extension Array where Element == MenuBarReading {
var accessibilitySummary: String {
isEmpty ? "Kymo" : map(\.accessibilityText).joined(separator: ", ")
}
}
+18 -4
View File
@@ -7,8 +7,9 @@ nonisolated struct TrendSample: Sendable {
let memory: Double?
var download: Double?
var battery: Double?
var batteryPower: Double?
var powerFlow: BatteryPowerFlow?
var systemPower: Double?
var desktopInput: Double?
var upload: Double?
var read: Double?
var write: Double?
@@ -30,6 +31,14 @@ nonisolated struct MetricHistory: Sendable {
private(set) var samples: [TrendSample] = []
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:]
private(set) var sleepIntervals: [DateInterval] = []
mutating func recordSleep(from start: Date, to end: Date) {
guard let oldest = samples.first?.date, end > start, end > oldest else { return }
sleepIntervals.append(DateInterval(start: start, end: end))
if sleepIntervals.count > Self.capacity { sleepIntervals.removeFirst() }
}
/// A slow cadence can begin and end without producing a point (for example a short hide).
/// Preserve that outgoing wait on the existing point without changing earlier segments.
mutating func recordScheduledInterval(_ interval: TimeInterval) {
@@ -43,12 +52,13 @@ nonisolated struct MetricHistory: Sendable {
}
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false, expectedInterval: TimeInterval = 2) {
if let last = samples.last, snapshot.date < last.date { sleepIntervals.removeAll() }
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate,
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
battery: snapshot.battery?.charge, powerFlow: snapshot.battery?.flow,
systemPower: snapshot.batteryState == .absent ? snapshot.systemPower : nil,
upload: snapshot.uploadRate,
desktopInput: snapshot.desktopInput, upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler,
memoryApp: snapshot.memory.map { Double($0.app) },
@@ -61,7 +71,11 @@ nonisolated struct MetricHistory: Sendable {
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload, expectedInterval: expectedInterval))
if interfaces[item.identity, default: []].count > Self.capacity { interfaces[item.identity]?.removeFirst() }
}
if samples.count > Self.capacity { samples.removeFirst(samples.count - Self.capacity) }
if samples.count > Self.capacity {
samples.removeFirst(samples.count - Self.capacity)
let oldest = samples[0].date
sleepIntervals.removeAll { $0.end <= oldest }
}
}
}
+1
View File
@@ -35,6 +35,7 @@ nonisolated struct MetricsSnapshot: Sendable {
var diskIO: DiskIOMetrics?
var volumes: [VolumeMetrics]?
var systemPower: Double?
var desktopInput: Double?
var battery: BatteryMetrics?
var uptime: TimeInterval = 0
var gpu: GPUMetrics?
-18
View File
@@ -30,24 +30,6 @@ nonisolated struct ProcessSnapshot: Sendable {
let failed: Bool
}
nonisolated extension ProcessSnapshot {
func highestCPUProcesses(limit: Int) -> [ProcessMetrics] {
guard limit > 0 else { return [] }
var result: [ProcessMetrics] = []
for row in rows {
guard let cpu = row.cpu, cpu.isFinite, cpu >= 0 else { continue }
let index = result.firstIndex { ($0.cpu ?? 0) < cpu } ?? result.endIndex
result.insert(row, at: index)
if result.count > limit { result.removeLast() }
}
return result
}
var highestCPUProcess: ProcessMetrics? {
highestCPUProcesses(limit: 1).first
}
}
nonisolated struct ProcessMemoryRequest: Codable, Sendable {
let token: UUID
let identities: [ProcessIdentity]
+164 -33
View File
@@ -3,26 +3,58 @@ import IOKit.ps
nonisolated struct BatteryMetrics: Sendable {
let charge: Double?
let charging: Bool
let externalPower: Bool
var power: Double? = nil
var minutesRemaining: Int?
var flow = BatteryPowerFlow()
var minutesToFull: Int?
var minutesToEmpty: Int?
var minutesRemaining: Int? {
switch flow.state {
case .charging: minutesToFull
case .battery, .discharging, .combined: minutesToEmpty
case .external, .unknown: nil
}
}
var cycles: Int?
var health: Double?
}
nonisolated enum BatteryMonitor {
nonisolated struct BatteryMonitor {
// The controller publishes less frequently than the panel. After a source change or
// wake, wait for each register group to advance before using it again.
private struct Freshness {
var stamp: [NSNumber?]?
var updated = Date.distantPast
mutating func accepts(_ next: [NSNumber?], at now: Date, invalidate: Bool) -> Bool {
if next != stamp { updated = now; stamp = next }
else if invalidate { updated = .distantPast }
return isFresh(at: now)
}
func isFresh(at now: Date) -> Bool {
(0...120).contains(now.timeIntervalSince(updated))
}
}
private var telemetryStamp = Freshness()
private var packStamp = Freshness()
private var previousConnection: Bool?
private var previousSupply: Bool?
private var sampled = false
private var invalidated = false
mutating func invalidate() { invalidated = true }
static func normalizedPower(voltageMillivolts: Double?, amperageMilliamps: Double?) -> Double? {
guard let voltageMillivolts, let amperageMilliamps,
voltageMillivolts.isFinite, amperageMilliamps.isFinite,
voltageMillivolts > 0, voltageMillivolts <= 30_000,
abs(amperageMilliamps) <= 20_000 else { return nil }
let watts = abs(voltageMillivolts * amperageMilliamps) / 1_000_000
return watts.isFinite && watts <= 500 ? watts : nil
let watts = (voltageMillivolts * amperageMilliamps) / 1_000_000
return watts.isFinite && abs(watts) <= 500 ? watts : nil
}
static func positiveMinutes(_ value: Int?) -> Int? {
value.flatMap { $0 > 0 ? $0 : nil }
value.flatMap { (1..<65535).contains($0) ? $0 : nil }
}
static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? {
@@ -44,7 +76,7 @@ nonisolated enum BatteryMonitor {
return .absent
}
static func sample() -> BatteryMetrics? {
mutating func sample() -> BatteryMetrics? {
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
for source in sources {
@@ -53,36 +85,135 @@ nonisolated enum BatteryMonitor {
let current = item[kIOPSCurrentCapacityKey] as? Double
let maximum = item[kIOPSMaxCapacityKey] as? Double
let charge = current.flatMap { c in maximum.flatMap { $0 > 0 ? min(1, max(0, c / $0)) : nil } }
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
var properties: [String: Any] = [:]
if service != 0 {
defer { IOObjectRelease(service) }
var raw: Unmanaged<CFMutableDictionary>?
if IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS {
properties = raw?.takeRetainedValue() as? [String: Any] ?? [:]
}
}
let charging = item[kIOPSIsChargingKey] as? Bool ?? false
let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue
let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int
let batteryData = properties["BatteryData"] as? [String: Any] ?? [:]
let voltage = firstNumber([properties["Voltage"], batteryData["Voltage"], batteryData["AppleRawBatteryVoltage"]])
let amperage = firstNumber([properties["InstantAmperage"], batteryData["InstantAmperage"], properties["Amperage"], batteryData["Amperage"]])
return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false,
externalPower: external,
power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage),
minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
let properties = Self.registryProperties() ?? [:]
let state = item[kIOPSPowerSourceStateKey] as? String
let supply: Bool? = state == kIOPSACPowerValue ? true : state == kIOPSBatteryPowerValue ? false : nil
let charging = item[kIOPSIsChargingKey] as? Bool
let flow = powerFlow(properties, externalSupply: supply, charging: charging)
let systemMinutes = Self.estimatedMinutes(charging: false, externalPower: supply != false,
sourceMinutes: item[kIOPSTimeToEmptyKey] as? Int, systemSeconds: IOPSGetTimeRemainingEstimate())
let now = Date()
let recentPack = Self.packIsRecent(properties, at: now)
let packMinutes = recentPack && packStamp.isFresh(at: now) ? Self.positiveMinutes(properties["AvgTimeToEmpty"] as? Int) : nil
return BatteryMetrics(charge: charge, flow: flow,
minutesToFull: charging == true ? Self.positiveMinutes(item[kIOPSTimeToFullChargeKey] as? Int) : nil,
minutesToEmpty: systemMinutes ?? packMinutes,
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
}
return nil
}
private static func firstNumber(_ values: [Any?]) -> Double? {
for case let value? in values {
if let number = value as? NSNumber, number.doubleValue.isFinite {
return number.doubleValue
private static func registryProperties() -> [String: Any]? {
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
guard service != 0 else { return nil }
defer { IOObjectRelease(service) }
var raw: Unmanaged<CFMutableDictionary>?
guard IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS else { return nil }
return raw?.takeRetainedValue() as? [String: Any]
}
/// A machine without a pack can still publish an independent DC input reading.
mutating func desktopInput() -> Double? {
guard let properties = Self.registryProperties() else { return nil }
let input = powerFlow(properties, externalSupply: true).input
return input?.source == .telemetry ? input?.watts : nil
}
private static func packIsRecent(_ properties: [String: Any], at now: Date) -> Bool {
scalar(properties["UpdateTime"]).map { (0...120).contains(now.timeIntervalSince1970 - $0) } ?? true
}
private static func scalar(_ raw: Any?) -> Double? {
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
number.doubleValue.isFinite else { return nil }
return number.doubleValue
}
/// IORegistry can expose signed telemetry as an unsigned 32- or 64-bit register.
private static func signed(_ raw: Any?, limit: Double) -> Double? {
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }
var value = number.doubleValue
if value > limit, !CFNumberIsFloatType(number) {
let bits = number.uint64Value
if bits <= UInt32.max { value = Double(Int32(bitPattern: UInt32(bits))) }
else { value = Double(Int64(bitPattern: bits)) }
}
return value.isFinite && abs(value) <= limit ? value : nil
}
mutating func powerFlow(_ properties: [String: Any], externalSupply: Bool?, charging: Bool? = nil, now: Date = Date()) -> BatteryPowerFlow {
let connected = properties["ExternalConnected"] as? Bool ?? (externalSupply == true ? true : nil)
let changed = invalidated || (sampled && (previousConnection != connected || previousSupply != externalSupply))
previousConnection = connected
previousSupply = externalSupply
sampled = true
invalidated = false
let telemetry = properties["PowerTelemetryData"] as? [String: Any] ?? [:]
let pack = properties["BatteryData"] as? [String: Any] ?? [:]
let adapter = properties["AdapterDetails"] as? [String: Any]
var flow = BatteryPowerFlow(connected: connected, externalSupply: externalSupply, charging: charging ?? properties["IsCharging"] as? Bool)
if connected != false, let capacity = Self.scalar(adapter?["Watts"]), (0.1...500).contains(capacity) {
flow.adapterCapacity = capacity
}
// IORegistry can observe physical disconnection before IOPowerSources catches up.
if connected == false { flow.externalSupply = false; flow.charging = false }
let recent = Self.packIsRecent(properties, at: now)
let voltage = properties["Voltage"] ?? pack["Voltage"] ?? pack["AppleRawBatteryVoltage"]
let instant = properties["InstantAmperage"] ?? pack["InstantAmperage"]
let average = properties["Amperage"] ?? pack["Amperage"]
let packFresh = packStamp.accepts([properties["UpdateTime"], voltage, instant, average].map { $0 as? NSNumber }, at: now, invalidate: changed)
let counters = ["SystemLoadAccumulatorCount", "SystemPowerInAccumulatorCount", "SystemPowerIn",
"BatteryPower", "SystemLoad", "SystemVoltageIn", "SystemCurrentIn"]
let telemetryFresh = telemetryStamp.accepts(counters.map { telemetry[$0] as? NSNumber }, at: now, invalidate: changed)
let disconnected = connected == false
func compatible(_ watts: Double) -> Bool { watts <= 0 || (!disconnected && externalSupply != false) }
if packFresh && recent {
for (raw, source) in [(instant, PowerReading.Source.instantaneous), (average, .average)] {
if let watts = Self.normalizedPower(voltageMillivolts: Self.scalar(voltage),
amperageMilliamps: Self.signed(raw, limit: 20_000)), compatible(watts) {
flow.battery = PowerReading(watts: watts, source: source)
break
}
}
}
return nil
if disconnected { flow.input = PowerReading(watts: 0) }
guard telemetryFresh, recent else { return flow }
func measured(_ key: String) -> Double? {
guard let value = Self.scalar(telemetry[key]), (0...500_000).contains(value) else { return nil }
return value / 1000
}
var input = measured("SystemPowerIn")
if input == nil, let mv = Self.scalar(telemetry["SystemVoltageIn"]), (1...50_000).contains(mv),
let ma = Self.scalar(telemetry["SystemCurrentIn"]), (0...10_000).contains(ma) {
input = mv * ma / 1_000_000
}
// A positive adapter reading after unplugging belongs to the previous supply.
if disconnected && (input ?? 0) > 0 { return flow }
if !disconnected { flow.input = input.map { PowerReading(watts: $0) } }
flow.load = measured("SystemLoad").map { PowerReading(watts: $0) }
if let mw = Self.signed(telemetry["BatteryPower"], limit: 500_000), compatible(mw / 1000) {
let watts = mw / 1000
// Some controllers retain zero/old-direction battery telemetry while the
// pack already reports discharge. Prefer the instantaneous pack in that case.
if let pack = flow.battery, pack.source == .instantaneous {
if abs(pack.watts) >= 0.05 && watts * pack.watts <= 0 { return flow }
if watts > 0 && pack.watts == 0 && flow.charging == false { return flow }
}
flow.battery = PowerReading(watts: watts)
}
if flow.battery == nil, connected != nil || externalSupply != nil, let input = flow.input, let load = flow.load, compatible(input.watts - load.watts) {
flow.battery = PowerReading(watts: input.watts - load.watts, source: .balance)
} else if let battery = flow.battery, battery.source == .telemetry {
// Reverse estimates use only quantities published in the same telemetry group.
if flow.load == nil, let input = flow.input, (0...500).contains(input.watts - battery.watts) {
flow.load = PowerReading(watts: input.watts - battery.watts, source: .balance)
} else if flow.input == nil, connected == true, let load = flow.load, (0...500).contains(load.watts + battery.watts) {
flow.input = PowerReading(watts: load.watts + battery.watts, source: .balance)
}
}
return flow
}
}
+17 -3
View File
@@ -1,7 +1,7 @@
import Foundation
import IOKit
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system power keys; never write keys.
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system and battery power keys; never write keys.
nonisolated final class CPUTemperatureMonitor {
static let highTemperatureThreshold = 90.0
@@ -105,9 +105,21 @@ nonisolated final class CPUTemperatureMonitor {
return watts
}
private func readNumber(_ key: UInt32) -> Double? {
/// B0AP on Apple Silicon is a signed, little-endian milliwatt reading at the battery.
func sampleBatteryPower() -> Double? {
#if arch(arm64)
guard openConnection(), let milliwatts = readNumber(0x42304150, expectedType: 0x73693332),
abs(milliwatts) <= 500_000 else { return nil }
return milliwatts / 1000
#else
return nil
#endif
}
private func readNumber(_ key: UInt32, expectedType: UInt32? = nil) -> Double? {
var request = Request(); request.key = key; request.command = 9
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
guard let metadata = call(&request), metadata.info.size <= 32,
expectedType == nil || metadata.info.type == expectedType else { return nil }
request.command = 5; request.info.size = metadata.info.size
guard let response = call(&request) else { return nil }
let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) }
@@ -116,6 +128,8 @@ nonisolated final class CPUTemperatureMonitor {
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
switch (type, bytes.count) {
case (0x73693332, 4): // si32, little-endian signed integer
return Double(bytes.withUnsafeBytes { Int32(littleEndian: $0.loadUnaligned(as: Int32.self)) })
case (0x666c7420, 4): // flt, little-endian IEEE754
let bits = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
let value = Double(Float(bitPattern: bits))
+20 -13
View File
@@ -15,9 +15,15 @@ nonisolated struct NetworkInterfaceMetrics: Sendable {
}
nonisolated struct NetworkMonitor {
struct InterfaceMetadata: Equatable {
let index: UInt32
var addresses: [String] = []
let active: Bool
}
private var previous: [String: (UInt64, UInt64)] = [:]
private var timestamp: TimeInterval?
private var identities: [String: String] = [:]
private var previousMetadata: [String: InterfaceMetadata] = [:]
private var counterBuffer: [UInt8] = []
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
@@ -28,31 +34,31 @@ nonisolated struct NetworkMonitor {
mutating func sample() -> [NetworkInterfaceMetrics]? {
guard let counters = counters() else { previous = [:]; timestamp = nil; return nil }
let now = ProcessInfo.processInfo.systemUptime
return update(counters: counters, metadata: Self.interfaces(), at: now)
}
mutating func update(counters: [String: (UInt64, UInt64)], metadata: [String: InterfaceMetadata],
at now: TimeInterval) -> [NetworkInterfaceMetrics] {
let elapsed = timestamp.map { now - $0 } ?? 0
let metadata = Self.interfaces()
let result = counters.keys.sorted().map { name in
let current = counters[name]!
let result = counters.sorted { $0.key < $1.key }.map { name, current in
let item = metadata[name]
let identity = "\(item?.index ?? 0):\(name):\(item?.active ?? false):\(item?.addresses.joined(separator: ",") ?? "")"
let old = identities[name] == identity ? previous[name] : nil
let old = previousMetadata[name] == item ? previous[name] : nil
return NetworkInterfaceMetrics(name: name, received: current.0, sent: current.1,
download: Self.rate(current: current.0, previous: old?.0, elapsed: elapsed),
upload: Self.rate(current: current.1, previous: old?.1, elapsed: elapsed),
index: item?.index ?? 0, addresses: item?.addresses ?? [], active: item?.active ?? false)
}
identities = Dictionary(uniqueKeysWithValues: result.map {
($0.name, "\($0.index):\($0.name):\($0.active):\($0.addresses.joined(separator: ","))")
})
previousMetadata = metadata
previous = counters
timestamp = now
return result
}
private static func interfaces() -> [String: (index: UInt32, addresses: [String], active: Bool)] {
private static func interfaces() -> [String: InterfaceMetadata] {
var head: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&head) == 0 else { return [:] }
defer { freeifaddrs(head) }
var result: [String: (index: UInt32, addresses: [String], active: Bool)] = [:]
var result: [String: InterfaceMetadata] = [:]
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
var cursor = head
while let entry = cursor {
@@ -60,7 +66,7 @@ nonisolated struct NetworkMonitor {
let name = String(cString: entry.pointee.ifa_name)
let flags = entry.pointee.ifa_flags
let active = flags & UInt32(IFF_UP | IFF_RUNNING) == UInt32(IFF_UP | IFF_RUNNING)
var item = result[name] ?? (if_nametoindex(entry.pointee.ifa_name), [], active)
var item = result[name] ?? InterfaceMetadata(index: if_nametoindex(entry.pointee.ifa_name), active: active)
if let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) {
if let host = numericAddress(address, buffer: &hostBuffer) {
item.addresses.append(host)
@@ -68,7 +74,8 @@ nonisolated struct NetworkMonitor {
}
result[name] = item
}
return result.mapValues { (index: $0.index, addresses: $0.addresses.sorted(), active: $0.active) }
for name in result.keys { result[name]?.addresses.sort() }
return result
}
static func numericAddress(_ address: UnsafePointer<sockaddr>, buffer: inout [CChar]) -> String? {
+2 -8
View File
@@ -29,16 +29,10 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
monitor.start(queue: DispatchQueue(label: "cn.airnan.kymo.network-path"))
}
func snapshot() -> NetworkPathStatus? {
func snapshot() -> (status: NetworkPathStatus?, primaryInterface: String?) {
lock.lock()
defer { lock.unlock() }
return status
}
func defaultInterface() -> String? {
lock.lock()
defer { lock.unlock() }
return primaryInterface
return (status, primaryInterface)
}
deinit { monitor.cancel() }
+19 -3
View File
@@ -10,11 +10,14 @@ actor SystemSampler {
private var fanCache: [FanMetrics]?
private var powerSchedule = SensorSchedule(successInterval: 0)
private var readingPower = false
private var batteryPowerSchedule = SensorSchedule(successInterval: 0)
private var readingBatteryPower = false
private var cpuSchedule = SensorSchedule()
private var gpuSchedule = SensorSchedule()
private var fanSchedule = SensorSchedule()
private var didProbe = false
private let diskHealth = DiskHealthMonitor()
private var batteryMonitor = BatteryMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
private var network = NetworkMonitor()
private let networkPath = NetworkPathObserver()
@@ -48,6 +51,8 @@ actor SystemSampler {
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func invalidateBatteryReadings() { batteryMonitor.invalidate() }
func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
var changedRevision = false
if let revision {
@@ -97,11 +102,10 @@ actor SystemSampler {
result.fans = fanCache
result.memory = MemoryMonitor.sample()
result.network = network.sample()
result.networkPath = networkPath.snapshot()
result.defaultNetworkInterface = networkPath.defaultInterface()
(result.networkPath, result.defaultNetworkInterface) = networkPath.snapshot()
result.disk = DiskMonitor.sample()
result.diskIO = diskIO.sample()
result.battery = BatteryMonitor.sample()
result.battery = batteryMonitor.sample()
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample()
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
@@ -122,8 +126,20 @@ actor SystemSampler {
result.battery?.health = batteryCache
result.volumes = volumes
result.uptime = ProcessInfo.processInfo.systemUptime
if includeSlowMetrics && result.battery != nil && !readingBatteryPower && batteryPowerSchedule.isDue(at: start) {
readingBatteryPower = true
let watts = await CPUTemperatureServiceClient.readBatteryPower()
readingBatteryPower = false
if !Task.isCancelled {
if let watts { result.battery?.flow.applyBatterySensor(watts) }
batteryPowerSchedule.complete(available: watts != nil, at: ProcessInfo.processInfo.systemUptime)
}
}
// Only a confirmed batteryless machine requests the fixed system-total key.
// Use this sample's reply directly: a missing reading never repeats the last wattage.
if includeSlowMetrics && result.batteryState == .absent {
result.desktopInput = batteryMonitor.desktopInput()
}
if includeSlowMetrics && result.batteryState == .absent && !readingPower && powerSchedule.isDue(at: start) {
readingPower = true
result.systemPower = await CPUTemperatureServiceClient.readSystemPower()
@@ -7,6 +7,14 @@ nonisolated struct SensorReadings: Sendable {
}
nonisolated enum CPUTemperatureServiceClient {
static func readBatteryPower() async -> Double? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readBatteryPower { value in
finish(value.flatMap { abs($0.doubleValue) <= 500 ? $0.doubleValue : nil })
}
}
}
static func readSystemPower() async -> Double? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSystemPower { value in
@@ -0,0 +1,35 @@
import Foundation
import Observation
@MainActor @Observable final class MenuBarPreferences {
private static let key = "menuBar.metrics"
@ObservationIgnored private let defaults: UserDefaults
@ObservationIgnored var onDemandChange: ((Bool) -> Void)?
private(set) var selected: Set<MenuBarMetric>
var allSelected: Bool { selected.count == MenuBarMetric.allCases.count }
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
selected = defaults.stringArray(forKey: Self.key).map { Set($0.compactMap(MenuBarMetric.init(rawValue:))) }
?? Set(MenuBarMetric.allCases)
}
func set(_ metric: MenuBarMetric, enabled: Bool) {
var next = selected
if enabled { next.insert(metric) } else { next.remove(metric) }
replaceSelection(with: next)
}
func setAllSelected(_ enabled: Bool) {
replaceSelection(with: enabled ? Set(MenuBarMetric.allCases) : [])
}
private func replaceSelection(with next: Set<MenuBarMetric>) {
guard selected != next else { return }
let wasEmpty = selected.isEmpty
selected = next
defaults.set(MenuBarMetric.allCases.filter(selected.contains).map(\.rawValue), forKey: Self.key)
if wasEmpty != selected.isEmpty { onDemandChange?(!selected.isEmpty) }
}
}
+43 -8
View File
@@ -15,18 +15,22 @@ final class MetricsStore {
private(set) var slowMetricsRequested = true
let sampling: SamplingPreferences
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
private var menuBarEnabled = false
private var liveDemand: Bool { panelDemand || (menuBarEnabled && !isDisplaySleeping) }
private var processDemand: Bool { panelDemand && processUpdatesRequested }
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
var effectiveMilliseconds: Int { liveDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (liveDemand || sampling.backgroundEnabled) }
// Permit timer coalescing without changing the requested cadence or delta timestamps.
private var schedulingTolerance: Duration {
.milliseconds(min(effectiveMilliseconds / 10, panelDemand ? 200 : 1_000))
.milliseconds(min(effectiveMilliseconds / 10, liveDemand ? 200 : 1_000))
}
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler: SystemSampler
@ObservationIgnored private var scheduledInterval = 0
@ObservationIgnored private var sleepStartedAt: Date?
@ObservationIgnored private var batteryWasAsleep = false
@ObservationIgnored private var needsHistoryBoundary = true
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
@@ -36,7 +40,7 @@ final class MetricsStore {
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused,
self.effectiveMilliseconds != self.scheduledInterval || self.hasSamplingDemand != (self.task != nil) else { return }
self.reschedule(reset: false, sampleImmediately: false)
self.reschedule(reset: self.task == nil, sampleImmediately: self.task == nil)
}
start()
}
@@ -48,7 +52,12 @@ final class MetricsStore {
reschedule(reset: true)
}
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
func powerSourceDidChange() {
guard panelDemand, !isPaused, !isSystemSleeping else { return }
reschedule(reset: false, confirmPowerChange: true)
}
private func reschedule(reset: Bool, sampleImmediately: Bool = true, confirmPowerChange: Bool = false) {
generation += 1
task?.cancel()
task = nil
@@ -69,7 +78,12 @@ final class MetricsStore {
if initialDelay > .zero {
do { try await Task.sleep(for: initialDelay, tolerance: self?.schedulingTolerance) } catch { return }
}
if self?.batteryWasAsleep == true {
self?.batteryWasAsleep = false
await sampler.invalidateBatteryReadings()
}
if reset { await sampler.reset() }
var needsConfirmation = confirmPowerChange
while !Task.isCancelled {
let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration
@@ -103,7 +117,10 @@ final class MetricsStore {
self?.lastPublishedAt = .now
self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next)
let interval = self?.effectiveMilliseconds ?? 5_000
let cadence = self?.effectiveMilliseconds ?? 5_000
// A source notification may arrive just before the gauge updates.
let interval = needsConfirmation ? min(cadence, 1000) : cadence
needsConfirmation = false
// Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
let deadline = sampledAt.advanced(by: .milliseconds(interval))
do { try await Task.sleep(until: max(deadline, .now), tolerance: self?.schedulingTolerance, clock: .continuous) }
@@ -128,20 +145,38 @@ final class MetricsStore {
func setSystemSleeping(_ sleeping: Bool) {
guard sleeping != isSystemSleeping else { return }
if sleeping {
sleepStartedAt = Date()
batteryWasAsleep = true
} else if let start = sleepStartedAt {
history.recordSleep(from: start, to: Date())
sleepStartedAt = nil
}
isSystemSleeping = sleeping
updateDemand(reset: true)
}
func setDisplaySleeping(_ sleeping: Bool) {
guard sleeping != isDisplaySleeping else { return }
let wasActive = hasSamplingDemand
isDisplaySleeping = sleeping
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
updateDemand(reset: !wasActive || !hasSamplingDemand, sampleImmediately: liveDemand)
}
func setPanelVisible(_ visible: Bool) {
guard isPanelVisible != visible else { return }
let wasActive = hasSamplingDemand
isPanelVisible = visible
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
updateDemand(reset: !wasActive || !hasSamplingDemand, sampleImmediately: panelDemand)
}
func setMenuBarEnabled(_ enabled: Bool) {
guard menuBarEnabled != enabled else { return }
let wasLive = liveDemand
let wasActive = hasSamplingDemand
menuBarEnabled = enabled
guard wasLive != liveDemand, !isPaused, !isSystemSleeping else { return }
reschedule(reset: !wasActive || !hasSamplingDemand, sampleImmediately: enabled)
}
/// The caller supplies data needs, without introducing UI types into Core.
+74
View File
@@ -0,0 +1,74 @@
import Foundation
import Observation
/// Shared by the panel badge and About page. Sparkle owns the actual update session.
@MainActor @Observable final class ReleaseUpdates {
enum Phase { case idle, checking, current, available, downloading, extracting, ready, restarting, failed }
struct Version: Equatable {
let display: String
let build: String
let infoURL: URL?
var label: String { "v\(display) (\(build))" }
}
private(set) var phase = Phase.idle
private(set) var version: Version?
private(set) var errorMessage: String?
private(set) var fraction: Double?
var automatic: Bool {
didSet {
guard oldValue != automatic else { return }
defaults.set(automatic, forKey: Self.preferenceKey)
changeAutomatic?(automatic)
}
}
private static let preferenceKey = "updates.automatic"
private let defaults: UserDefaults
@ObservationIgnored var changeAutomatic: ((Bool) -> Void)?
@ObservationIgnored var beginCheck: (() -> Void)?
@ObservationIgnored var beginDownload: ((Version) -> Void)?
@ObservationIgnored private var restart: (() -> Void)?
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
automatic = defaults.object(forKey: Self.preferenceKey) as? Bool ?? true
}
func check() {
guard [.idle, .available, .current, .failed].contains(phase) else { return }
beginCheck?()
}
func performAction() {
switch phase {
case .available:
if let version, version.infoURL == nil { beginDownload?(version) }
case .ready:
guard let restart else { return }
self.restart = nil
transition(to: .restarting)
restart()
case .failed, .idle, .current: check()
default: break
}
}
func found(_ version: Version) {
self.version = version
transition(to: .available)
}
func ready(restart: @escaping () -> Void) {
transition(to: .ready)
self.restart = restart
}
func transition(to phase: Phase, fraction: Double? = nil, error: String? = nil) {
self.phase = phase
self.fraction = fraction
errorMessage = error
restart = nil
if phase == .current || phase == .idle { version = nil }
}
}
@@ -4,6 +4,7 @@ import Foundation
@objc protocol SMARTServiceProtocol {
nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readBatteryPower(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
+5 -1
View File
@@ -53,7 +53,11 @@ nonisolated enum SamplingDiagnostics {
payload["batteryCycles"] = snapshot.battery?.cycles
payload["batteryHealth"] = snapshot.battery?.health
payload["systemPower"] = snapshot.systemPower
payload["batteryPower"] = snapshot.battery?.power
payload["batteryPower"] = snapshot.battery?.flow.battery?.watts
payload["batteryPowerSource"] = snapshot.battery?.flow.battery.map { String(describing: $0.source) }
payload["adapterInput"] = snapshot.battery?.flow.input?.watts
payload["systemLoad"] = snapshot.battery?.flow.load?.watts
payload["powerState"] = snapshot.battery.map { String(describing: $0.flow.state) }
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
let status = withUnsafeMutablePointer(to: &info) { pointer in
@@ -1,7 +1,15 @@
import Observation
enum SettingsPage: Hashable {
case general, menuBar, about
}
/// A UI-independent intent shared by the menu entry and the settings scene.
@MainActor @Observable final class SettingsPresentation {
var selection: SettingsPage = .general
private(set) var requestID: UInt64 = 0
func request() { requestID &+= 1 }
func request(_ page: SettingsPage? = nil) {
if let page { selection = page }
requestID &+= 1
}
}
+126
View File
@@ -0,0 +1,126 @@
import Foundation
import Sparkle
@MainActor final class SparkleUpdater: NSObject, SPUUserDriver, SPUUpdaterDelegate {
private let updates: ReleaseUpdates
private lazy var updater = SPUUpdater(hostBundle: .main, applicationBundle: .main, userDriver: self, delegate: self)
private var started = false
private var requestedBuild: String?
private var expectedBytes: UInt64 = 0
private var receivedBytes: UInt64 = 0
init(updates: ReleaseUpdates) {
self.updates = updates
super.init()
updates.changeAutomatic = { [weak self] enabled in self?.updater.automaticallyChecksForUpdates = enabled }
updates.beginCheck = { [weak self] in self?.check() }
updates.beginDownload = { [weak self] in self?.check(download: $0) }
}
func start() {
guard prepare() else { return }
if updates.automatic { updater.checkForUpdatesInBackground() }
}
private func prepare() -> Bool {
if started { return true }
do {
if updater.automaticallyChecksForUpdates != updates.automatic {
updater.automaticallyChecksForUpdates = updates.automatic
}
try updater.start()
started = true
return true
} catch {
updates.transition(to: .failed, error: error.localizedDescription)
return false
}
}
private func check(download: ReleaseUpdates.Version? = nil) {
guard prepare(), !updater.sessionInProgress else { return }
requestedBuild = download?.build
updates.transition(to: .checking)
updater.checkForUpdates()
}
func show(_ request: SPUUpdatePermissionRequest, reply: @escaping (SUUpdatePermissionResponse) -> Void) {
reply(SUUpdatePermissionResponse(automaticUpdateChecks: updates.automatic, sendSystemProfile: false))
}
func showUserInitiatedUpdateCheck(cancellation: @escaping () -> Void) {}
func showUpdateFound(with appcastItem: SUAppcastItem, state: SPUUserUpdateState,
reply: @escaping (SPUUserUpdateChoice) -> Void) {
guard state.userInitiated || updates.automatic else { reply(.dismiss); return }
let version = ReleaseUpdates.Version(display: appcastItem.displayVersionString, build: appcastItem.versionString,
infoURL: appcastItem.isInformationOnlyUpdate ? appcastItem.infoURL : nil)
updates.found(version)
if state.stage == .installing {
updates.ready { reply(.install) }
} else if state.userInitiated, requestedBuild == version.build, !appcastItem.isInformationOnlyUpdate {
updates.transition(to: .downloading)
reply(.install)
} else {
// Keep the badge, release the session so Sparkle can check again in six hours.
reply(.dismiss)
}
}
func showUpdateReleaseNotes(with downloadData: SPUDownloadData) {}
func showUpdateReleaseNotesFailedToDownloadWithError(_ error: Error) {}
func showUpdateNotFoundWithError(_ error: Error, acknowledgement: @escaping () -> Void) {
updates.transition(to: .current)
acknowledgement()
}
func showUpdaterError(_ error: Error, acknowledgement: @escaping () -> Void) {
updates.transition(to: .failed, error: error.localizedDescription)
acknowledgement()
}
func showDownloadInitiated(cancellation: @escaping () -> Void) {
expectedBytes = 0
receivedBytes = 0
updates.transition(to: .downloading)
}
func showDownloadDidReceiveExpectedContentLength(_ expectedContentLength: UInt64) {
expectedBytes = expectedContentLength
}
func showDownloadDidReceiveData(ofLength length: UInt64) {
receivedBytes += length
let fraction = expectedBytes > 0 ? min(1, Double(receivedBytes) / Double(expectedBytes)) : nil
updates.transition(to: .downloading, fraction: fraction)
}
func showDownloadDidStartExtractingUpdate() { updates.transition(to: .extracting) }
func showExtractionReceivedProgress(_ progress: Double) { updates.transition(to: .extracting, fraction: progress) }
func showReady(toInstallAndRelaunch reply: @escaping (SPUUserUpdateChoice) -> Void) {
updates.ready { reply(.install) }
}
func showInstallingUpdate(withApplicationTerminated terminated: Bool, retryTerminatingApplication: @escaping () -> Void) {
if !terminated { updates.ready(restart: retryTerminatingApplication) }
}
func showUpdateInstalledAndRelaunched(_ relaunched: Bool, acknowledgement: @escaping () -> Void) {
updates.transition(to: .current)
acknowledgement()
}
func dismissUpdateInstallation() {}
func updater(_ updater: SPUUpdater, didFinishUpdateCycleFor updateCheck: SPUUpdateCheck, error: Error?) {
requestedBuild = nil
guard let error = error as NSError? else { return }
if error.domain == SUSparkleErrorDomain, error.code == SUError.noUpdateError.rawValue {
updates.transition(to: .current)
} else {
updates.transition(to: .failed, error: error.localizedDescription)
}
}
}
@@ -0,0 +1,286 @@
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 batteryFraction: Double?
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, batteryFraction: sample.powerFlow?.jointSupply?.batteryFraction,
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, .combined: (NSColor(named: "BatteryExternal") ?? .systemBlue, "powerplug.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
if bar.state == .combined {
let left = max(range.lowerBound, 0), right = min(range.upperBound, layoutData.width)
if right - left >= 12 {
let mid = (left + right) / 2
drawSymbol(style.symbol, color: style.color, in: left...mid, minimumWidth: 6)
drawSymbol("battery.50percent", color: NSColor(named: "MetricBattery") ?? .systemGreen,
in: mid...right, minimumWidth: 6)
}
} else {
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, batteryFraction: item.batteryFraction)
}
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, batteryFraction: Double? = nil) {
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()
let path = NSBezierPath(roundedRect: fill, xRadius: fillRadius, yRadius: fillRadius)
path.fill()
if let batteryFraction {
NSGraphicsContext.saveGraphicsState()
path.addClip()
(NSColor(named: "MetricBattery") ?? .systemGreen).setFill()
let greenHeight = height * batteryFraction
NSBezierPath(rect: CGRect(x: fill.minX, y: baseline - greenHeight, width: width, height: greenHeight)).fill()
NSGraphicsContext.restoreGraphicsState()
}
}
private func drawSymbol(_ symbol: String, color: NSColor, in range: ClosedRange<CGFloat>, minimumWidth: CGFloat = 13) {
let visibleLeft = max(0, range.lowerBound)
let visibleWidth = min(layoutData.width, range.upperBound) - visibleLeft
guard visibleWidth >= minimumWidth, let image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)?
.withSymbolConfiguration(.init(paletteColors: [color])) else { return }
let scale = min(min(11, visibleWidth) / 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)
}
}
@@ -15,6 +15,8 @@ import Observation
#if DEBUG || KYMO_AUDIT
private(set) weak var lastHiddenContent: NSView?
#endif
private let metricStrip = MenuBarMetricStrip()
private let readings: () -> [MenuBarReading]
private var statusItem: NSStatusItem?
private var localMouse: Any?
private var globalMouse: Any?
@@ -24,17 +26,22 @@ import Observation
private let visibility: (Bool) -> Void
private let menuTitle: (String) -> String
private let openSettings: () -> Void
private let openAbout: () -> Void
private var showingStatusMenu = false
private var isHiding = false
private var preferredContentHeight = PanelLayout.defaultHeight
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
init<Content: View>(installStatusItem: Bool = true, readings: @escaping () -> [MenuBarReading] = { [] },
visibility: @escaping (Bool) -> Void,
menuTitle: @escaping (String) -> String = { $0 },
openSettings: @escaping () -> Void = {},
openAbout: @escaping () -> Void = {},
@ViewBuilder content: @escaping (PanelPresentation) -> Content) {
self.readings = readings
self.visibility = visibility
self.menuTitle = menuTitle
self.openSettings = openSettings
self.openAbout = openAbout
self.content = {
let host = NSHostingView(rootView: content($0))
// The controller owns the fixed panel frame; content must not negotiate window limits.
@@ -54,13 +61,13 @@ import Observation
presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal }
if installStatusItem {
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
item.button?.image = NSImage(named: "BrandMark")
item.button?.image?.isTemplate = true
item.button?.setAccessibilityLabel("Kymo")
item.button?.target = self
item.button?.action = #selector(statusItemClicked)
item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
statusItem = item
metricStrip.setAccessibilityElement(false)
item.button?.addSubview(metricStrip)
refreshStatusItem()
}
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.place() }
@@ -79,6 +86,29 @@ import Observation
})
}
private func refreshStatusItem() {
guard let statusItem, let button = statusItem.button else { return }
let current = withObservationTracking { readings() } onChange: { [weak self] in
Task { @MainActor [weak self] in self?.refreshStatusItem() }
}
metricStrip.readings = current
metricStrip.isHidden = current.isEmpty
if current.isEmpty {
button.image = NSImage(named: "BrandMark")
button.image?.isTemplate = true
statusItem.length = NSStatusItem.squareLength
} else {
button.image = nil
let size = metricStrip.intrinsicContentSize
let length = size.width + 8
if statusItem.length != length { statusItem.length = length }
metricStrip.frame = NSRect(x: 4, y: 0, width: size.width, height: button.bounds.height)
metricStrip.autoresizingMask = [.height]
}
button.setAccessibilityLabel("Kymo")
button.setAccessibilityValue(current.accessibilitySummary)
}
@objc func togglePanel() { panel.isVisible ? hide() : show() }
@objc private func statusItemClicked() {
@@ -100,6 +130,9 @@ import Observation
let settings = NSMenuItem(title: menuTitle("settings"), action: #selector(settingsClicked), keyEquivalent: ",")
settings.target = self
menu.addItem(settings)
let about = NSMenuItem(title: menuTitle("about"), action: #selector(aboutClicked), keyEquivalent: "")
about.target = self
menu.addItem(about)
menu.addItem(.separator())
let quit = NSMenuItem(title: menuTitle("quit"), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
quit.target = NSApp
@@ -107,6 +140,7 @@ import Observation
return menu
}
@objc private func aboutClicked() { hide(); openAbout() }
@objc private func settingsClicked() { hide(); openSettings() }
private func isOverStatusItem(_ screenPoint: NSPoint) -> Bool {
@@ -48,7 +48,8 @@ extension MenuPanelView {
return ResourceCard(
title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
titleBadge: snapshot.gpu?.coreCount.map {
String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0)
$0 == 1 ? AppLocalization.string("gpu.oneCore", locale: locale)
: String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0)
},
status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" },
chartPlacement: .background,
@@ -110,7 +111,7 @@ extension MenuPanelView {
second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed),
color: Color("MemoryApplication"), secondColor: Color("MemoryApplication"),
thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1),
firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
firstValueFormat: .memory, firstLabel: "memory.used",
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [1, 2, 3])
}
@@ -165,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)
}
}
+13 -8
View File
@@ -5,7 +5,7 @@ struct MenuPanelView: View {
let metrics: MetricsStore
let preferences: AppearancePreferences
let keepAwake: KeepAwakeService
let settingsPresentation: SettingsPresentation
let updates: ReleaseUpdates
var presentation = PanelPresentation()
var onOpenSettings: () -> Void = {}
var onPreferredHeight: (CGFloat) -> Void = { _ in }
@@ -136,7 +136,15 @@ struct MenuPanelView: View {
.frame(width: 22, height: 22)
HStack(alignment: .top, spacing: 3) {
Text("Kymo").font(.system(size: 17, weight: .semibold))
if let version = Self.version {
if updates.version != nil {
UpdateAction(phase: updates.phase, version: updates.version, compact: true, action: updates.performAction)
.buttonStyle(.plain)
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(Color.accentColor)
.padding(.horizontal, 5).padding(.vertical, 2)
.background(Color.accentColor.opacity(0.12), in: Capsule())
.offset(y: -2)
} else if let version = Self.version {
Text(verbatim: "v" + version)
.font(.system(size: 9, weight: .semibold)).monospacedDigit()
.padding(.horizontal, 5).padding(.vertical, 1)
@@ -162,7 +170,8 @@ struct MenuPanelView: View {
HStack {
HStack(spacing: 4) {
Text("panel.uptime")
MetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
let hours = (snapshot.uptime / 3600).formatted(.number.precision(.fractionLength(1)).grouping(.never).locale(locale))
Text("duration.hours \(hours)").monospacedDigit()
}.fixedSize()
Divider().frame(height: 14)
Text(verbatim: HardwareIdentity.displayName)
@@ -204,11 +213,7 @@ struct MenuPanelView: View {
}
.help(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
.accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
Button {
NSApp.setActivationPolicy(.regular)
settingsPresentation.request()
onOpenSettings()
} label: {
Button(action: onOpenSettings) {
Image(systemName: "gearshape").frame(width: 20, height: 20)
}
.help(Text("action.settings")).accessibilityLabel(Text("action.settings"))
@@ -133,7 +133,7 @@ import SwiftUI
}
}
let descriptors = (pendingSorting ?? value.sorting).map {
NSSortDescriptor(key: Self.name($0.key), ascending: $0.order == .forward)
NSSortDescriptor(key: $0.key.rawValue, ascending: $0.order == .forward)
}
if table.sortDescriptors != descriptors { table.sortDescriptors = descriptors }
let oldCount = table.numberOfRows, newCount = value.rows.count
@@ -211,7 +211,7 @@ import SwiftUI
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard !applying else { return }
let order = tableView.sortDescriptors.compactMap { descriptor -> ProcessSort? in
guard let key = Self.key(descriptor.key ?? "") else { return nil }
guard let key = ProcessSort.Key(rawValue: descriptor.key ?? "") else { return nil }
return ProcessSort(key: key, order: descriptor.ascending ? .forward : .reverse)
}
sortRevision += 1; let revision = sortRevision
@@ -237,12 +237,6 @@ import SwiftUI
guard let value = item.representedObject as? String else { return }
NSPasteboard.general.clearContents(); NSPasteboard.general.setString(value, forType: .string)
}
private static func name(_ key: ProcessSort.Key) -> String {
switch key { case .pid: "pid"; case .name: "name"; case .path: "path"; case .cpu: "cpu"; case .memory: "memory"; case .threads: "threads"; case .power: "power" }
}
private static func key(_ name: String) -> ProcessSort.Key? {
switch name { case "pid": .pid; case "name": .name; case "path": .path; case "cpu": .cpu; case "memory": .memory; case "threads": .threads; case "power": .power; default: nil }
}
}
final class Cell: NSTableCellView {
@@ -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",
+86 -34
View File
@@ -3,15 +3,43 @@ import SwiftUI
struct PowerResourceCard: View {
let snapshot: MetricsSnapshot
let samples: [TrendSample]
let sleepIntervals: [DateInterval]
let chartInterval: TimeInterval
let chartBoundaries: Set<Date>
let chartIntervals: [TimeInterval]
@Environment(\.locale) private var locale
private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
private func label(_ state: BatteryPowerFlow.State) -> String {
let key: String = switch state {
case .charging: "power.charging"
case .combined: "power.combined"
case .discharging: "power.discharging"
case .external: "battery.acPower"
case .battery: "battery.batterySource"
case .unknown: "power.unknown"
}
return AppLocalization.string(key, locale: locale)
}
private func formatted(_ reading: PowerReading?, signed: Bool = false) -> String {
let value = signed ? MetricFormat.signedWatts(reading?.watts) : MetricFormat.watts(reading?.watts)
return reading?.source == .balance ? "≈" + value : value
}
private func details(_ flow: BatteryPowerFlow) -> String {
var rows: [(String, String)]
if let joint = flow.jointSupply {
let load = flow.load ?? PowerReading(watts: joint.adapter.watts + joint.discharge.watts, source: .balance)
rows = [("power.adapterContribution", formatted(joint.adapter)),
("power.batteryContribution", formatted(joint.discharge)),
("power.load", formatted(load))]
} else {
let batteryLabel = flow.battery?.source == .average ? "power.averageBattery" : "battery.power"
rows = [(batteryLabel, formatted(flow.battery, signed: true)), ("power.load", formatted(flow.load))]
if flow.connected != false { rows.append(("power.input", formatted(flow.input))) }
}
if flow.connected != false { rows.append(("power.capacity", MetricFormat.watts(flow.adapterCapacity))) }
return rows.map { AppLocalization.string($0.0, locale: locale) + " " + $0.1 }.joined(separator: "\n")
}
@ViewBuilder var body: some View {
@@ -20,6 +48,13 @@ struct PowerResourceCard: View {
value: MetricFormat.watts(snapshot.systemPower), chart: {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.systemPower),
color: Color("MetricBattery"), fixedScale: nil, firstValueFormat: .watts,
sampleTooltip: { index in
let sample = samples[index]
return AnyView(VStack(alignment: .leading) {
InlineMetric("power.system", MetricFormat.watts(sample.systemPower))
if let input = sample.desktopInput { InlineMetric("power.input", MetricFormat.watts(input)) }
})
},
firstLabel: "power.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals)
}) {
@@ -27,36 +62,40 @@ struct PowerResourceCard: View {
.font(.system(size: 10)).foregroundStyle(.secondary)
}
} else {
batteryChargeCard
batteryPowerCard
}
}
private var batteryChargeCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
private var batteryPowerCard: some View {
let joint = snapshot.battery?.flow.jointSupply
return ResourceCard(
title: "metric.battery", symbol: joint == nil ? "battery.100percent" : "powerplug.fill",
color: Color(joint == nil ? "MetricBattery" : "BatteryExternal"),
value: MetricFormat.percent(snapshot.battery?.charge),
status: snapshot.battery.map { AppLocalization.string($0.externalPower ? "battery.acPower" : "battery.batterySource", locale: locale) },
chartPlacement: .background,
companionIcon: joint == nil ? nil : ("battery.50percent", Color("MetricBattery")),
status: snapshot.battery.map { label($0.flow.state) },
warningText: snapshot.battery.map { Text(verbatim: details($0.flow)) },
chart: {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map(\.battery),
second: samples.map(\.batteryPower),
color: Color("MetricBattery"),
secondColor: Color("SeriesUser"),
fixedScale: 1,
secondSeriesUsesAutonomousScale: true,
secondValueFormat: .watts,
firstLabel: "metric.battery",
secondLabel: snapshot.battery.map(batteryPowerLabel) ?? "battery.power",
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", MetricFormat.watts(snapshot.battery?.power))
if let joint {
HStack(spacing: 8) {
powerLabel(joint.adapter, symbol: "powerplug.fill", color: "BatteryExternal", title: "power.adapterContribution")
powerLabel(joint.discharge, symbol: "battery.50percent", color: "MetricBattery", title: "power.batteryContribution")
}
.frame(height: 16)
} else {
powerLabel(snapshot.battery?.flow.battery, signed: true, symbol: "battery.50percent",
color: "MetricBattery", title: "battery.power")
.frame(height: 16)
}
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
@@ -65,20 +104,33 @@ struct PowerResourceCard: View {
}
}
}
private func powerLabel(_ reading: PowerReading?, signed: Bool = false, symbol: String,
color: String, title: LocalizedStringKey) -> some View {
let value = formatted(reading, signed: signed)
return Label {
Text(verbatim: value).monospacedDigit()
} icon: {
Image(systemName: symbol).foregroundStyle(Color(color))
}
.accessibilityLabel(Text(title)).accessibilityValue(Text(verbatim: value))
.help(Text(title))
}
private func batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
InlineMetric("battery.healthShort", MetricFormat.percent(battery.health))
InlineMetric("battery.cyclesShort", battery.cycles.map(String.init) ?? "--")
}
HStack(spacing: 4) {
Text("battery.timeShort").foregroundStyle(.secondary)
if battery.externalPower {
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
} else if let minutes = battery.minutesRemaining {
MetricText(value: "\(minutes) min")
} else {
Text("battery.timeUnknown")
if battery.flow.state != .external {
HStack(spacing: 4) {
Text(battery.flow.state == .charging ? "battery.timeToFull" : "battery.timeEstimate")
.foregroundStyle(.secondary)
if let minutes = battery.minutesRemaining {
Text("duration.minutes \(minutes)").monospacedDigit()
} else {
Text("battery.timeUnknown")
}
}
}
}
@@ -10,29 +10,37 @@ nonisolated enum ProcessTableProjection {
}
static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], order: [ProcessIdentity]) -> [ProcessMetrics] {
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
return input.filter {
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false)
}.sorted {
let aRank = ranks[$0.id] ?? Int.max, bRank = ranks[$1.id] ?? Int.max
if aRank != bRank { return aRank < bRank }
let matches = query.isEmpty ? input : input.filter {
$0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query)
|| ($0.path?.localizedCaseInsensitiveContains(query) ?? false)
}
func precedes(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> Bool {
for comparator in sorting {
let result = comparator.compare($0, $1)
let result = comparator.compare(lhs, rhs)
if result != .orderedSame { return result == .orderedAscending }
}
return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name
return lhs.name == rhs.name ? lhs.id.pid < rhs.id.pid : lhs.name < rhs.name
}
guard !order.isEmpty else { return matches.sorted(by: precedes) }
// A snapshot has one row per process identity. Refresh retained rows in their
// displayed order, then apply the active sort only to newly visible processes.
var remaining = Dictionary(uniqueKeysWithValues: matches.lazy.map { ($0.id, $0) })
var result = order.compactMap { remaining.removeValue(forKey: $0) }
result.append(contentsOf: remaining.values.sorted(by: precedes))
return result
}
}
/// Missing metrics stay last in either direction. Every newly selected column starts descending.
nonisolated struct ProcessSort: SortComparator, Equatable {
enum Key { case pid, name, path, cpu, memory, threads, power }
enum Key: String { case pid, name, path, cpu, memory, threads, power }
let key: Key
var order: SortOrder = .reverse
func compare(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> ComparisonResult {
func metric(_ a: Double?, _ b: Double?) -> ComparisonResult {
func metric<T: Comparable>(_ a: T?, _ b: T?) -> ComparisonResult {
switch (a, b) {
case (nil, nil): return .orderedSame
case (nil, _): return .orderedDescending
@@ -41,13 +49,13 @@ nonisolated struct ProcessSort: SortComparator, Equatable {
}
}
switch key {
case .pid: return metric(Double(lhs.id.pid), Double(rhs.id.pid))
case .pid: return metric(lhs.id.pid, rhs.id.pid)
case .name: return directed(lhs.name.localizedStandardCompare(rhs.name))
case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? ""))
case .cpu: return metric(lhs.cpu, rhs.cpu)
case .memory: return metric(lhs.footprintBytes.map { Double($0) }, rhs.footprintBytes.map { Double($0) })
case .memory: return metric(lhs.footprintBytes, rhs.footprintBytes)
case .power: return metric(lhs.cpuPower, rhs.cpuPower)
case .threads: return metric(lhs.threads.map { Double($0) }, rhs.threads.map { Double($0) })
case .threads: return metric(lhs.threads, rhs.threads)
}
}
+10 -7
View File
@@ -7,7 +7,7 @@ struct StorageDetailsView: View {
var body: some View {
VStack(alignment: .leading, spacing: 3) {
field("memory.available", value: MetricFormat.bytes(disk?.available))
field("memory.available", value: Text(verbatim: MetricFormat.bytes(disk?.available)))
ViewThatFits(in: .horizontal) {
HStack(spacing: 6) { read; write }.fixedSize(horizontal: true, vertical: true)
VStack(alignment: .leading, spacing: 3) { read; write }
@@ -24,15 +24,18 @@ struct StorageDetailsView: View {
.font(.system(size: 10)).lineLimit(1)
}
private var read: some View { field("disk.read", value: MetricFormat.rate(io?.read)) }
private var write: some View { field("disk.write", value: MetricFormat.rate(io?.written)) }
private var life: some View { field("disk.lifeShort", value: MetricFormat.percent(health?.remainingLife)) }
private var powerOn: some View { field("disk.powerOnShort", value: health?.powerOnHours.map { "\($0) h" } ?? "--") }
private var read: some View { field("disk.read", value: Text(verbatim: MetricFormat.rate(io?.read))) }
private var write: some View { field("disk.write", value: Text(verbatim: MetricFormat.rate(io?.written))) }
private var life: some View { field("disk.lifeShort", value: Text(verbatim: MetricFormat.percent(health?.remainingLife))) }
private var powerOn: some View {
let hours = health?.powerOnHours.map { Text("duration.hours \(String($0))") }
return field("disk.powerOnShort", value: hours ?? Text(verbatim: "--"))
}
private func field(_ title: LocalizedStringKey, value: String) -> some View {
private func field(_ title: LocalizedStringKey, value: Text) -> some View {
HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary).help(Text(title))
MetricText(value: value).fontWeight(.medium).foregroundStyle(.primary)
value.monospacedDigit().fontWeight(.medium).foregroundStyle(.primary)
}.frame(height: 14)
}
}
@@ -6,22 +6,25 @@ struct AppearanceSettingsView: View {
@Bindable var preferences: AppearancePreferences
@Bindable var language: LanguagePreferences
@Bindable var sampling: SamplingPreferences
let presentation: SettingsPresentation
let menuBar: MenuBarPreferences
let readings: () -> [MenuBarReading]
@Bindable var presentation: SettingsPresentation
@Bindable var updates: ReleaseUpdates
@Environment(\.locale) private var locale
@State private var selection = SettingsPage.general
var body: some View {
Group {
switch selection {
switch presentation.selection {
case .general: generalPage
case .menuBar: MenuBarSettingsPage(preferences: menuBar, readings: readings())
case .about: aboutPage
}
}
.padding(12)
.toolbar {
ToolbarItem(placement: .principal) {
NeutralTabPicker(title: "settings.title", selection: $selection,
options: [(.general, "settings.general"), (.about, "settings.about")])
NeutralTabPicker(title: "settings.title", selection: $presentation.selection,
options: [(.general, "settings.general"), (.menuBar, "settings.menuBar"), (.about, "settings.about")])
}
.sharedBackgroundVisibility(.hidden)
}
@@ -94,6 +97,27 @@ struct AppearanceSettingsView: View {
}
.padding(.vertical, 8)
}
Section {
Toggle("updates.automatic", isOn: $updates.automatic)
.toggleStyle(.checkbox)
Text("updates.schedule").font(.callout).foregroundStyle(.secondary)
HStack {
if let version = updates.version {
Text("updates.new \(version.label)")
} else if updates.phase == .current {
Text("updates.current").foregroundStyle(.secondary)
}
Spacer()
UpdateAction(phase: updates.phase, version: updates.version, action: updates.performAction)
}
if updates.phase == .downloading || updates.phase == .extracting {
ProgressView(value: updates.fraction).progressViewStyle(.linear)
}
if let error = updates.errorMessage {
Text(verbatim: error).font(.callout).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
.formStyle(.grouped)
.padding(.horizontal, 12)
@@ -118,7 +142,3 @@ private extension AppAppearance {
}
}
private enum SettingsPage: Hashable {
case general, about
}
@@ -0,0 +1,71 @@
import SwiftUI
struct MenuBarSettingsPage: View {
let preferences: MenuBarPreferences
let readings: [MenuBarReading]
var body: some View {
VStack(alignment: .leading, spacing: 18) {
HStack(spacing: 8) {
Image(systemName: "apple.logo").accessibilityHidden(true)
Spacer(minLength: 0)
if readings.isEmpty {
Image("BrandMark").renderingMode(.template)
.resizable().scaledToFit().frame(width: 18, height: 18)
} else {
MenuBarStripPreview(readings: readings).fixedSize()
}
Text(verbatim: "09:41").font(.system(size: 11, weight: .medium))
}
.padding(.horizontal, 10)
.frame(height: 36)
.background(Color.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))
.accessibilityElement(children: .ignore)
.accessibilityAddTraits(.isImage)
.accessibilityLabel(Text("menuBar.preview \(readings.accessibilitySummary)"))
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("menuBar.items").font(.headline)
Spacer()
Button {
preferences.setAllSelected(!preferences.allSelected)
} label: {
if preferences.allSelected { Text("menuBar.deselectAll") }
else { Text("action.selectAll") }
}
.controlSize(.small)
}
VStack(spacing: 0) {
ForEach(MenuBarMetric.allCases, id: \.self) { metric in
if metric != .cpu { Divider() }
HStack {
Toggle(isOn: Binding(get: { preferences.selected.contains(metric) },
set: { preferences.set(metric, enabled: $0) })) {
Text(LocalizedStringKey(metric.titleKey))
}
.toggleStyle(.checkbox)
Spacer()
Text(descriptionKey(for: metric)).foregroundStyle(.secondary)
}
.padding(.horizontal, 12)
.frame(height: 42)
}
}
.background(.background, in: RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary))
}
Spacer(minLength: 0)
}
.padding(8)
}
private func descriptionKey(for metric: MenuBarMetric) -> LocalizedStringKey {
switch metric {
case .cpu, .gpu: "menuBar.utilization"
case .memory: "menuBar.usedFraction"
case .disk: "menuBar.diskSpace"
case .network: "menuBar.networkRate"
}
}
}
File diff suppressed because it is too large Load Diff
+23
View File
@@ -1,6 +1,29 @@
{
"sourceLanguage" : "en",
"strings" : {
"status.about": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "About Kymo"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "关于 Kymo"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "關於 Kymo"
}
}
}
},
"status.hide" : {
"extractionState" : "manual",
"localizations" : {
+5 -2
View File
@@ -4,11 +4,13 @@ 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)
}
@@ -154,8 +156,9 @@ struct NativePanelCurve: NSViewRepresentable {
baseline.frame = bounds
baseline.isHidden = input?.projection == .fullHeight || input == nil
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: bounds.height * 0.6))
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height * 0.6))
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() {
+17 -23
View File
@@ -5,6 +5,7 @@ enum TrendValueFormat {
case rate
case bytes
case memory
case signedWatts
case watts
}
@@ -20,9 +21,8 @@ struct PanelTrendChart: View {
var thirdColor: Color = .purple
var fourthColor: Color = .yellow
var fixedScale: Double? = 1
var secondSeriesUsesAutonomousScale = false
var firstValueFormat: TrendValueFormat?
var secondValueFormat: TrendValueFormat?
var sampleTooltip: ((Int) -> AnyView)?
var firstLabel: LocalizedStringKey = "panel.total"
var secondLabel: LocalizedStringKey = "network.upload"
var thirdLabel: LocalizedStringKey = "cpu.system"
@@ -38,8 +38,6 @@ struct PanelTrendChart: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@State private var smallSecondSamples = 0
@State private var hoveredDate: Date?
@State private var hoverPoint: CGPoint?
@@ -64,12 +62,10 @@ struct PanelTrendChart: View {
private var maximum: Double {
let values = stackOrder.isEmpty ? first + second + third + fourth
: StackedSeries.bands(renderFrame.series, count: dates.count).last?.upper ?? []
if projection == .signed { return max(1, values.compactMap { $0 }.filter(\.isFinite).map(abs).max() ?? 1) }
return max(1, values.compactMap { $0 }.filter(\.isFinite).max() ?? 1)
}
private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
private var secondaryScale: Double { max(0.0001, retainedSecondScale) }
private var hasSecondaryScale: Bool { secondSeriesUsesAutonomousScale && !second.isEmpty }
private var automaticFormat: TrendValueFormat {
if let firstValueFormat { return firstValueFormat }
if fixedScale == 1 { return .percent }
@@ -81,31 +77,36 @@ struct PanelTrendChart: View {
guard let hoveredDate else { return dates.count - 1 }
return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) }
}
private func formatted(_ value: Double?, format: TrendValueFormat? = nil) -> String {
private func formatted(_ value: Double?) -> String {
guard let value, value.isFinite else { return "--" }
switch format ?? automaticFormat {
switch automaticFormat {
case .percent: return MetricFormat.percent(value)
case .rate: return MetricFormat.rate(value)
case .bytes: return MetricFormat.bytes(UInt64(max(0, value)))
case .memory: return MetricFormat.memory(UInt64(max(0, value)))
case .signedWatts: return MetricFormat.signedWatts(value)
case .watts: return MetricFormat.watts(value)
}
}
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, index: Int) -> some View {
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View {
HStack(spacing: 6) {
RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8)
Text(label)
Spacer(minLength: 4)
Text(verbatim: formatted(index < values.count ? values[index] : nil, format: format)).monospacedDigit()
Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit()
}
}
private func tooltip(index: Int) -> some View {
VStack(alignment: .leading, spacing: 3) {
Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary)
tooltipRow(firstLabel, values: first, tint: color, index: index)
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, format: secondValueFormat, index: index) }
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
if let sampleTooltip {
sampleTooltip(index)
} else {
tooltipRow(firstLabel, values: first, tint: color, index: index)
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) }
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
}
}
.font(.system(size: 9)).padding(6)
.background { TooltipBackground() }
@@ -115,7 +116,7 @@ struct PanelTrendChart: View {
var body: some View {
GeometryReader { proxy in
NativePanelCurve(frame: renderFrame, colors: renderColors,
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
scales: [scale, scale, scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
filledSeriesCount: stackOrder.isEmpty ? (filledSeriesCount ?? visibleSeriesCount) : stackOrder.count, stacked: !stackOrder.isEmpty, projection: projection,
@@ -139,7 +140,6 @@ struct PanelTrendChart: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
retainedScale = maximum
retainedSecondScale = secondMaximum
}
.onChange(of: dates) { _, _ in
let target = maximum
@@ -148,12 +148,6 @@ struct PanelTrendChart: View {
smallSamples += 1
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
} else { smallSamples = 0 }
let secondTarget = secondMaximum
if secondTarget > retainedSecondScale { retainedSecondScale = secondTarget; smallSecondSamples = 0 }
else if secondTarget < retainedSecondScale * 0.5 {
smallSecondSamples += 1
if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 }
} else { smallSecondSamples = 0 }
}
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(firstLabel))
@@ -0,0 +1,87 @@
import AppKit
import SwiftUI
private extension MenuBarMetric {
var colorName: String {
switch self {
case .cpu: "MetricCPU"
case .gpu: "MetricGPU"
case .memory: "MetricMemory"
case .disk: "MetricDisk"
case .network: "MetricNetwork"
}
}
}
/// The same drawing is hosted by the settings preview and by the native status button.
final class MenuBarMetricStrip: NSView {
private let titleFont = NSFont.systemFont(ofSize: 8.5, weight: .medium)
private let valueFont = NSFont.monospacedDigitSystemFont(ofSize: 10, weight: .semibold)
private let rateFont = NSFont.monospacedDigitSystemFont(ofSize: 9.5, weight: .medium)
private let gaugeWidth: CGFloat = 3
private let textInset: CGFloat = 6
private let spacing: CGFloat = 4
var readings: [MenuBarReading] = [] {
didSet {
guard readings != oldValue else { return }
invalidateIntrinsicContentSize()
needsDisplay = true
}
}
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
private func width(of reading: MenuBarReading) -> CGFloat {
switch reading.content {
case .network:
return ceil(("↓ 999.9 MB/s" as NSString).size(withAttributes: [.font: rateFont]).width)
case .usage:
let valueWidth = ("100%" as NSString).size(withAttributes: [.font: valueFont]).width
let titleWidth = (reading.title as NSString).size(withAttributes: [.font: titleFont]).width
return textInset + ceil(max(titleWidth, valueWidth))
}
}
override var intrinsicContentSize: NSSize {
NSSize(width: readings.reduce(0) { $0 + width(of: $1) } + CGFloat(max(0, readings.count - 1)) * spacing,
height: 22)
}
override func draw(_ dirtyRect: NSRect) {
var x: CGFloat = 0
let top = floor(bounds.midY - 11)
for item in readings {
switch item.content {
case let .usage(fraction):
let track = NSRect(x: x, y: top + 2, width: gaugeWidth, height: 18)
NSColor.labelColor.withAlphaComponent(0.18).setFill()
NSBezierPath(rect: track).fill()
if let fraction, fraction.isFinite, fraction > 0 {
let height = track.height * min(1, fraction)
(NSColor(named: item.metric.colorName) ?? .labelColor).setFill()
NSBezierPath(rect: NSRect(x: x, y: track.maxY - height, width: gaugeWidth, height: height)).fill()
}
drawText(item.title, x: x + textInset, y: top, font: titleFont)
drawText(MetricFormat.percent(fraction), x: x + textInset, y: top + 9, font: valueFont)
case let .network(upload, download):
drawText("↑ \(upload)", x: x, y: top, font: rateFont)
drawText("↓ \(download)", x: x, y: top + 10, font: rateFont)
}
x += width(of: item) + spacing
}
}
private func drawText(_ text: String, x: CGFloat, y: CGFloat, font: NSFont) {
(text as NSString).draw(at: NSPoint(x: x, y: y),
withAttributes: [.font: font, .foregroundColor: NSColor.labelColor])
}
}
struct MenuBarStripPreview: NSViewRepresentable {
let readings: [MenuBarReading]
func makeNSView(context: Context) -> MenuBarMetricStrip { MenuBarMetricStrip() }
func updateNSView(_ view: MenuBarMetricStrip, context: Context) { view.readings = readings }
func sizeThatFits(_ proposal: ProposedViewSize, nsView: MenuBarMetricStrip, context: Context) -> CGSize? {
nsView.intrinsicContentSize
}
}
@@ -1,23 +0,0 @@
import SwiftUI
/// Clips both layers to the track, including fills narrower than the track height.
struct MetricProgressBar: View {
let value: Double
let color: Color
var cornerRadius: CGFloat? = nil
private var fraction: Double { value.isFinite ? min(1, max(0, value)) : 0 }
var body: some View {
GeometryReader { proxy in
let shape = RoundedRectangle(cornerRadius: cornerRadius ?? proxy.size.height / 2, style: .continuous)
ZStack(alignment: .leading) {
shape.fill(color.opacity(0.15))
shape.fill(color).frame(width: proxy.size.width * fraction)
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(shape)
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}
}
+7 -1
View File
@@ -11,6 +11,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
let symbol: String
let color: Color
let value: String
var companionIcon: (symbol: String, color: Color)? = nil
var secondaryValue: String? = nil
var valueColor: Color? = nil
var secondaryValueColor: Color? = nil
@@ -90,7 +91,12 @@ struct ResourceCard<Chart: View, Content: View>: View {
Label {
Text(title).foregroundStyle(statusWarning ? .red : .primary)
} icon: {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
HStack(spacing: 1) {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
if let companionIcon {
Image(systemName: companionIcon.symbol).foregroundStyle(companionIcon.color)
}
}
}
.font(.system(size: 11, weight: .semibold)).fixedSize()
if let titleBadge {
+44
View File
@@ -0,0 +1,44 @@
import SwiftUI
/// The same single action is presented as a compact version badge or a settings button.
struct UpdateAction: View {
let phase: ReleaseUpdates.Phase
let version: ReleaseUpdates.Version?
var compact = false
let action: () -> Void
var body: some View {
if let url = version?.infoURL, phase == .available {
Link(destination: url) { content("updates.releasePage", symbol: "arrow.up.right") }
} else {
Button(action: action) {
switch phase {
case .available: content("updates.download", symbol: "arrow.down.circle.fill")
case .ready: content("updates.restart", symbol: "arrow.clockwise.circle.fill")
case .checking: content("updates.checking", symbol: "magnifyingglass")
case .downloading: content("updates.downloading", symbol: "arrow.down")
case .extracting: content("updates.preparing", symbol: "shippingbox")
case .restarting: content("updates.restarting", symbol: "arrow.clockwise")
case .failed: content("updates.retry", symbol: "arrow.clockwise")
case .idle, .current: content("updates.check", symbol: "arrow.clockwise")
}
}
.disabled([.checking, .downloading, .extracting, .restarting].contains(phase))
}
}
private func content(_ title: LocalizedStringKey, symbol: String) -> some View {
HStack(spacing: 3) {
Image(systemName: symbol)
if compact, let version {
Text(verbatim: "v" + version.display)
} else {
Text(title)
}
}
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(title))
.accessibilityValue(Text(verbatim: version?.label ?? ""))
.help(Text(title))
}
}
+7
View File
@@ -50,6 +50,13 @@ import Foundation
let stopped = store.history.samples
precondition(PanelCurveGeometry.runs(dates: stopped.map(\.date), values: stopped.map(\.memory),
boundaryDates: Set(stopped.filter(\.breakBefore).map(\.date)), intervals: stopped.map(\.expectedInterval)).count == 2)
precondition(store.history.sleepIntervals.isEmpty, "Hiding and disabling recording must not mark sleep")
store.setSystemSleeping(true)
store.setSystemSleeping(true)
try await Task.sleep(for: .milliseconds(50))
store.setSystemSleeping(false)
store.setSystemSleeping(false)
precondition(store.history.sleepIntervals.count == 1 && store.history.sleepIntervals[0].duration > 0)
store.togglePause()
print("PASS: disabling background recording still stops sampling and preserves the real gap")
}
+96
View File
@@ -0,0 +1,96 @@
import Foundation
@main struct BatteryPowerChecks {
static func main() {
func read(_ telemetry: [String: Any], extra: [String: Any] = [:], connected: Bool = true) -> BatteryPowerFlow {
var monitor = BatteryMonitor()
var raw = extra
raw["ExternalConnected"] = connected
raw["PowerTelemetryData"] = telemetry
return monitor.powerFlow(raw, externalSupply: connected)
}
let adapter = ["AdapterDetails": ["Watts": 65]]
let charging = read(["BatteryPower": 6_000], extra: adapter)
precondition(charging.battery == PowerReading(watts: 6) && charging.state == .charging)
precondition(charging.adapterCapacity == 65 && charging.input == nil)
precondition(read([:], extra: adapter).battery == nil)
let combined = read(["BatteryPower": NSNumber(value: UInt64(bitPattern: -8000)), "SystemPowerIn": 30_000])
precondition(combined.battery?.watts == -8 && combined.state == .combined)
precondition(combined.load == PowerReading(watts: 38, source: .balance))
let standby = read(["BatteryPower": -4700, "SystemPowerIn": 100, "SystemLoad": 6300], extra: adapter)
precondition(standby.state == .battery && standby.input?.watts == 0.1 && standby.jointSupply == nil)
let tinyDischarge = read(["BatteryPower": -100, "SystemPowerIn": 6300, "SystemLoad": 6400])
precondition(tinyDischarge.state == .external && tinyDischarge.jointSupply == nil)
let contradictory = read(["BatteryPower": -4700, "SystemPowerIn": 6000, "SystemLoad": 6300])
precondition(contradictory.state == .discharging && contradictory.jointSupply == nil)
var primaryBattery = BatteryMonitor()
let withAssist = primaryBattery.powerFlow(["ExternalConnected": true, "PowerTelemetryData":
["SystemPowerIn": 12_000, "BatteryPower": -8000, "SystemLoad": 20_000]], externalSupply: false)
precondition(withAssist.state == .combined && withAssist.jointSupply?.batteryFraction == 0.4)
let estimatedInput = read(["BatteryPower": -8000, "SystemLoad": 38_000])
precondition(estimatedInput.jointSupply?.adapter == PowerReading(watts: 30, source: .balance))
let estimatedAssist = read(["SystemPowerIn": 30_000, "SystemLoad": 38_000])
precondition(estimatedAssist.jointSupply?.discharge == PowerReading(watts: 8, source: .balance))
let staleCharge = read(["BatteryPower": 6_000], extra: ["Voltage": 12_000, "InstantAmperage": 0, "IsCharging": false])
precondition(staleCharge.battery?.watts == 0 && staleCharge.state == .external)
let unknownWatts = read([:], extra: ["IsCharging": true])
precondition(unknownWatts.battery == nil && unknownWatts.state == .charging)
let idle = read(["SystemPowerIn": 17_453, "BatteryPower": 0])
precondition(idle.battery?.watts == 0 && idle.state == .external)
let estimated = read(["SystemPowerIn": 65_000, "SystemLoad": 59_000])
precondition(estimated.battery == PowerReading(watts: 6, source: .balance))
precondition(read(["SystemPowerIn": 30_000, "SystemLoad": 38_000]).state == .combined)
precondition(read(["SystemPowerIn": 30_000, "SystemLoad": 30_200]).state == .external)
precondition(read(["BatteryPower": 6_000, "SystemLoad": 0]).input == PowerReading(watts: 6, source: .balance))
precondition(read(["SystemVoltageIn": 20_000, "SystemCurrentIn": 300]).input?.watts == 6)
let pack = ["Voltage": NSNumber(value: 12_000), "InstantAmperage": NSNumber(value: UInt32(bitPattern: -1500))]
let discharge = read(["SystemPowerIn": 0, "BatteryPower": 0], extra: pack, connected: false)
precondition(discharge.battery == PowerReading(watts: -18, source: .instantaneous) && discharge.state == .battery)
let unplugged = read(["SystemLoad": 18_000], connected: false)
precondition(unplugged.battery == PowerReading(watts: -18, source: .balance))
precondition(read(["SystemLoad": 18_000, "SystemPowerIn": 17_000], connected: false).battery == nil)
precondition(read(["BatteryPower": Double.nan]).battery == nil)
precondition(read(["BatteryPower": NSNumber(value: true)]).battery == nil)
precondition(read([:], extra: ["Voltage": 12_000, "Amperage": -1000]).battery == PowerReading(watts: -12, source: .average))
precondition(MetricFormat.signedWatts(-0.02) == "0 W" && MetricFormat.signedWatts(6) == "+6.0 W")
precondition(MetricFormat.signedWatts(-18) == "−18.0 W" && MetricFormat.signedWatts(nil) == "--")
var monitor = BatteryMonitor()
let now = Date()
var raw: [String: Any] = ["ExternalConnected": true, "PowerTelemetryData": ["BatteryPower": 6_000]]
precondition(monitor.powerFlow(raw, externalSupply: true, now: now).battery?.watts == 6)
monitor.invalidate()
precondition(monitor.powerFlow(raw, externalSupply: true, now: now).battery == nil)
raw["ExternalConnected"] = false
precondition(monitor.powerFlow(raw, externalSupply: false, now: now).battery == nil)
raw["PowerTelemetryData"] = ["BatteryPower": -18_000]
precondition(monitor.powerFlow(raw, externalSupply: false, now: now).battery?.watts == -18)
precondition(monitor.powerFlow(raw, externalSupply: false, now: now.addingTimeInterval(121)).battery == nil)
// Physical disconnection can precede an IOPS update, while both cached power registers still show AC.
let unplug = monitor.powerFlow(["ExternalConnected": false, "PowerTelemetryData": ["SystemPowerIn": 30_000, "BatteryPower": 6_000]], externalSupply: true)
precondition(unplug.state == .battery && unplug.battery == nil)
var live = unplug
live.applyBatterySensor(6)
precondition(live.battery == nil)
live.applyBatterySensor(-12.6)
precondition(live.battery == PowerReading(watts: -12.6, source: .smc) && live.state == .battery)
let delayedRegistry = BatteryPowerFlow(connected: true, externalSupply: false, charging: true, input: PowerReading(watts: 20))
precondition(delayedRegistry.state == .battery)
var joint = combined
joint.applyBatterySensor(-10)
precondition(joint.battery?.watts == -10 && joint.state == .combined && joint.load == nil)
precondition(joint.jointSupply?.batteryFraction == 8.0 / 38 && joint.jointSupply?.discharge.watts == 8)
joint.applyBatterySensor(2)
precondition(joint.state == .charging && joint.jointSupply == nil)
var missingPair = read(["SystemPowerIn": 6000])
missingPair.applyBatterySensor(-5)
precondition(missingPair.state == .discharging && missingPair.jointSupply == nil)
var clock = BatteryMetrics(charge: 0.8, flow: combined, minutesToFull: 20, minutesToEmpty: 345)
precondition(clock.minutesRemaining == 345)
clock.flow = charging
precondition(clock.minutesRemaining == 20)
clock.flow = idle
precondition(clock.minutesRemaining == nil && BatteryMonitor.positiveMinutes(65535) == nil)
print("PASS: signed battery watts, adapter limits, joint supply, measured and derived values, stale telemetry")
}
}
+2
View File
@@ -6,6 +6,8 @@ import Foundation
precondition(!CPUTemperatureMonitor.isHighTemperature(nil))
precondition(!CPUTemperatureMonitor.isHighTemperature(89.9))
precondition(CPUTemperatureMonitor.isHighTemperature(90))
precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x73693332, bytes: [0x80, 0xc1, 0xff, 0xff]) == -16_000)
precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x73693332, bytes: [0x70, 0x17, 0, 0]) == 6_000)
if let temperature = CPUTemperatureMonitor().sample() {
precondition(temperature > 0 && temperature < 150)
}
+17 -3
View File
@@ -1,8 +1,10 @@
"""Validate catalog coverage and printf argument compatibility against zh-Hans."""
"""Validate catalog coverage and printf argument compatibility in the source catalogs and optionally the compiled app."""
import argparse
import collections
import json
from pathlib import Path
import re
import subprocess
root = Path(__file__).resolve().parents[1] / 'kymo/Resources'
pattern = re.compile(r'%(?:(\d+)\$)?[-+#0 ]*(?:\d+)?(?:\.\d+)?(ll|l|h)?([@diuoxXfFeEgGcCsSp])')
@@ -13,13 +15,25 @@ def arguments(text):
result[(int(match[1] or index), (match[2] or '') + match[3])] += 1
return result
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--app', type=Path, help='Also compare every translation with the built app')
app = parser.parse_args().app
locales = ('zh-Hans', 'en', 'zh-Hant')
count = 0
for path in sorted(root.glob('*.xcstrings')):
compiled = {}
if app:
for locale in locales:
table = app / 'Contents' / 'Resources' / f'{locale}.lproj' / f'{path.stem}.strings'
compiled[locale] = json.loads(subprocess.check_output(['plutil', '-convert', 'json', '-o', '-', table]))
for key, entry in json.loads(path.read_text())['strings'].items():
units = {locale: entry['localizations'][locale]['stringUnit']
for locale in ['zh-Hans', 'en', 'zh-Hant']}
for locale in locales}
expected = arguments(key) or arguments(units['en']['value'])
for locale, unit in units.items():
assert unit['state'] == 'translated' and unit['value'].strip(), (path, key, locale)
assert arguments(unit['value']) == arguments(units['zh-Hans']['value']), (path, key, locale)
assert arguments(unit['value']) == expected, (path, key, locale)
if app:
assert compiled[locale].get(key) == unit['value'], (path, key, locale, 'built translation')
count += 1
print(f'PASS: {count} catalog entries, three-language coverage and format arguments')
+6 -1
View File
@@ -36,7 +36,12 @@ import Foundation
let expected = ["en": "Fan", "zh-Hans": "风扇", "zh-Hant": "風扇"][language]!
precondition(title == "\(expected) \(number)", "Numbered fan must use the selected app locale")
}
let minutes = AppLocalization.string("duration.minutes %lld", locale: locale, bundle: bundle)
let hours = AppLocalization.string("duration.hours %@", locale: locale, bundle: bundle)
let durations = [String(format: minutes, Int64(45)), String(format: hours, "1.5")]
let expectedDurations = ["en": ["45 min", "1.5 h"], "zh-Hans": ["45 分钟", "1.5 小时"],
"zh-Hant": ["45 分鐘", "1.5 小時"]]
precondition(durations == expectedDurations[language])
}
print("PASS: system matching, explicit override, fallback, preference roundtrip, built three-language resources")
}
+94
View File
@@ -0,0 +1,94 @@
import Foundation
@main struct MenuBarMetricChecks {
@MainActor static func main() async throws {
let suite = "kymo-menubar-checks-" + UUID().uuidString
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let preferences = MenuBarPreferences(defaults: defaults)
precondition(preferences.selected == Set(MenuBarMetric.allCases))
let sampling = SamplingPreferences(defaults: defaults)
sampling.panelMilliseconds = 500
sampling.backgroundMilliseconds = 30000
let store = MetricsStore(sampling: sampling)
var demandChanges: [Bool] = []
preferences.onDemandChange = { demandChanges.append($0); store.setMenuBarEnabled($0) }
store.setMenuBarEnabled(!preferences.selected.isEmpty)
try await until { store.history.samples.count >= 2 }
precondition(!store.isPanelVisible && store.processSnapshot == nil && store.effectiveMilliseconds == 500)
sampling.panelMilliseconds = 1200
precondition(store.effectiveMilliseconds == 1200)
let beforeChange = store.history.samples.count
try await until { store.history.samples.count >= beforeChange + 2 }
let times = store.history.samples.suffix(2).map(\.date)
precondition(times[1].timeIntervalSince(times[0]) >= 1.1, "Hidden menu bar must adopt the new foreground interval")
sampling.panelMilliseconds = 500
preferences.set(.gpu, enabled: false)
precondition(!preferences.allSelected)
preferences.setAllSelected(true)
precondition(preferences.allSelected && MenuBarPreferences(defaults: defaults).allSelected && demandChanges.isEmpty)
preferences.setAllSelected(false)
preferences.setAllSelected(false)
precondition(MenuBarPreferences(defaults: defaults).selected.isEmpty && demandChanges == [false])
try await expectStopped(store)
preferences.setAllSelected(true)
precondition(preferences.allSelected && demandChanges == [false, true])
preferences.setAllSelected(false)
preferences.set(.disk, enabled: true)
preferences.set(.cpu, enabled: true)
preferences.set(.cpu, enabled: true)
let restored = MenuBarPreferences(defaults: defaults)
precondition(restored.selected == [.cpu, .disk] && demandChanges == [false, true, false, true])
let last = store.snapshot.date
try await until { store.snapshot.date > last }
precondition(store.history.samples.last?.breakBefore == true)
store.setDisplaySleeping(true)
try await expectStopped(store)
store.setDisplaySleeping(false)
let wake = store.snapshot.date
try await until { store.snapshot.date > wake }
store.togglePause()
try await expectStopped(store)
checkReadings()
print("PASS: menu bar persistence, selection demand, hidden-panel sampling, sleep, pause, ordered vertical gauges, disk space, independent transfer rates and missing data")
}
private static func checkReadings() {
let selected = Set(MenuBarMetric.allCases)
var snapshot = MetricsSnapshot()
snapshot.cpu = CPUMetrics(usage: 0.86, user: 0.86, system: 0, cores: [])
snapshot.gpu = GPUMetrics(usage: 0.12, coreCount: nil)
snapshot.memory = MemoryMetrics(total: 100, used: 64, wired: 0, compressed: 0, swapUsed: nil, pressure: nil)
snapshot.disk = DiskMetrics(total: 1_000, available: 270)
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 0, sent: 0,
download: 2_400_000, upload: 128_000)]
func readings() -> [MenuBarReading] {
MenuBarReading.readings(selection: selected, snapshot: snapshot) { $0.rawValue }
}
let result = readings()
precondition(result.map(\.metric) == MenuBarMetric.allCases)
precondition(result.map(\.content) == [.usage(0.86), .usage(0.12), .usage(0.64), .usage(0.73),
.network(upload: "128 KB/s", download: "2.4 MB/s")])
snapshot.disk = nil
snapshot.diskIO = DiskIOMetrics(read: 40_000_000, written: 60_000_000)
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 0, sent: 0, download: 0, upload: nil)]
precondition(readings()[3].content == .usage(nil))
precondition(readings()[4].content == .network(upload: "--", download: "0 B/s"))
snapshot.disk = DiskMetrics(total: 100, available: 0)
precondition(readings()[3].accessibilityText == "disk 100%")
snapshot = MetricsSnapshot()
precondition(readings().accessibilitySummary == "cpu --, gpu --, memory --, disk --, network ↑ --, ↓ --")
}
@MainActor private static func expectStopped(_ store: MetricsStore) async throws {
let date = store.snapshot.date
try await Task.sleep(for: .milliseconds(750))
precondition(store.snapshot.date == date && store.processSnapshot == nil)
}
@MainActor private static func until(_ condition: () -> Bool) async throws {
let deadline = ContinuousClock.now.advanced(by: .seconds(4))
while !condition() && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) }
precondition(condition())
}
}
+10
View File
@@ -19,6 +19,16 @@ import QuartzCore
func input(_ values: [Double?]) -> NativePanelCurve.Input {
NativePanelCurve.Input(frame: PanelCurveFrame(dates: dates, series: [values], intervals: [2,2,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5)
}
var signed = input([-1, 0, 0.5, 1])
signed.projection = .signed
signed.hoveredIndex = 0
plot.configure(signed)
let dischargeDot = plot.layer!.sublayers!.last as! CAShapeLayer
precondition(dischargeDot.path!.boundingBoxOfPath.midY == 60)
precondition(plot.baseline.path!.boundingBoxOfPath.midY == 30)
signed.hoveredIndex = 3
plot.configure(signed)
precondition(dischargeDot.path!.boundingBoxOfPath.midY == 0)
let continuous = input([0.8,0.8,0.8,0.8])
plot.configure(continuous)
let image = bitmap(plot)
+21
View File
@@ -2,7 +2,28 @@ import Foundation
import Darwin
@main struct NetworkAddressChecks {
static func checkBaselineChanges() {
var monitor = NetworkMonitor()
var time: TimeInterval = 0
func next(_ metadata: NetworkMonitor.InterfaceMetadata) -> NetworkInterfaceMetrics {
time += 1
let bytes = UInt64(time) * 10
return monitor.update(counters: ["en0": (bytes, bytes * 2)], metadata: ["en0": metadata], at: time)[0]
}
for metadata in [NetworkMonitor.InterfaceMetadata(index: 1, addresses: ["192.0.2.1"], active: true),
.init(index: 1, addresses: ["192.0.2.2"], active: true),
.init(index: 2, addresses: ["192.0.2.2"], active: true),
.init(index: 2, addresses: ["192.0.2.2"], active: false)] {
let changed = next(metadata)
precondition(changed.download == nil && changed.upload == nil)
let stable = next(metadata)
precondition(stable.download == 10 && stable.upload == 20)
}
}
static func main() {
checkBaselineChanges()
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
func check(_ address: UnsafePointer<sockaddr>) {
var original = [CChar](repeating: 0, count: Int(NI_MAXHOST))
+6 -2
View File
@@ -8,15 +8,16 @@ import SwiftUI
Task { @MainActor in
var visible = false
var settingsRequests = 0
var aboutRequests = 0
var observedSize = CGSize.zero
let controller = MenuPanelController(installStatusItem: false, visibility: { visible = $0 },
openSettings: { settingsRequests += 1 }) { _ in
openSettings: { settingsRequests += 1 }, openAbout: { aboutRequests += 1 }) { _ in
IntervalControl(milliseconds: .constant(1000))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(PanelWindowObserver { observedSize = $0 }.frame(width: 0, height: 0))
}
precondition(!controller.presentation.isPinned)
precondition(controller.statusMenu().items.map(\.title) == ["open", "settings", "", "quit"])
precondition(controller.statusMenu().items.map(\.title) == ["open", "settings", "about", "", "quit"])
controller.show()
precondition(controller.panel.animationBehavior == .none)
try? await Task.sleep(for: .milliseconds(150))
@@ -77,6 +78,9 @@ import SwiftUI
controller.statusMenu().performActionForItem(at: 1)
precondition(settingsRequests == 1 && !controller.panel.isVisible)
controller.show()
controller.statusMenu().performActionForItem(at: 2)
precondition(aboutRequests == 1 && !controller.panel.isVisible)
controller.show()
let screen = controller.panel.screen!
precondition(abs(controller.panel.frame.midX - screen.visibleFrame.midX) < 1)
controller.dismissForOutsideInteraction()
+19
View File
@@ -34,6 +34,25 @@ import Foundation
let sorted = ProcessTableProjection.rows([row, high, low, zero], query: "", sorting: [ProcessSort(key: .power, order: direction)], order: [])
precondition(sorted.last?.cpuPower == nil && sorted.first?.cpuPower == (direction == .forward ? 0 : 3))
}
// The selected process can exit while its PID is reused. The replacement
// joins the sorted newcomers, while retained rows keep fresh measurements.
let fresh = ProcessMetrics(id: large.id, name: large.name, path: nil, cpu: 1,
footprintBytes: nil, threads: 2, restricted: false)
let newcomer = ProcessMetrics(id: .init(pid: 44, seconds: 10, microseconds: 0),
name: "new", path: nil, cpu: 2, footprintBytes: nil,
threads: 1, restricted: false)
let held = ProcessTableProjection.rows([replacement, newcomer, fresh], query: "",
sorting: [ProcessSort(key: .cpu)], order: [id, large.id])
precondition(held.map(\.id) == [large.id, newcomer.id, reused])
precondition(held.first?.threads == 2 && held.first?.footprintBytes == nil)
let filteredHeld = ProcessTableProjection.rows([row, fresh], query: "large", sorting: [], order: [id, large.id])
precondition(filteredHeld.map(\.id) == [large.id])
let nearlyMax = ProcessMetrics(id: id, name: "a", path: nil, cpu: nil,
footprintBytes: UInt64.max - 1, threads: nil, restricted: false)
let max = ProcessMetrics(id: large.id, name: "z", path: nil, cpu: nil,
footprintBytes: UInt64.max, threads: nil, restricted: false)
precondition(ProcessSort(key: .memory).compare(nearlyMax, max) == .orderedDescending)
print("PASS: filtered/live selection, absent selection/snapshot, failed enumeration, actual exit and PID reuse")
}
}
+3
View File
@@ -24,6 +24,9 @@ import Darwin
print("FAIL: hardened sandbox to packaged XPC sensor RPC"); exit(1)
}
print("PASS: hardened sandbox host authenticates packaged XPC; footprint, CPU energy and sensor RPCs")
let battery = await CPUTemperatureServiceClient.readBatteryPower()
precondition(battery.map { abs($0) <= 500 } ?? true)
print("Live battery gauge (W):", battery.map(String.init(describing:)) ?? "unavailable")
let power = await CPUTemperatureServiceClient.readSystemPower()
print("System-total sensor (W):", power.map(String.init(describing:)) ?? "unavailable")
print("Sensor coverage: CPU=\(sensors.cpu != nil), GPU=\(sensors.gpu != nil), fans=\(sensors.fans?.count ?? 0)")
+55
View File
@@ -0,0 +1,55 @@
import Foundation
@main struct ReleaseUpdateChecks {
@MainActor static func main() {
let app = Bundle(path: CommandLine.arguments[1])!
precondition(app.object(forInfoDictionaryKey: "SUScheduledCheckInterval") as? Int == 6 * 60 * 60)
precondition(app.object(forInfoDictionaryKey: "SUEnableAutomaticChecks") as? Bool == true)
precondition(app.object(forInfoDictionaryKey: "SURequireSignedFeed") as? Bool == true)
precondition(app.object(forInfoDictionaryKey: "SUVerifyUpdateBeforeExtraction") as? Bool == true)
let suite = "KymoReleaseUpdateChecks." + UUID().uuidString
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let updates = ReleaseUpdates(defaults: defaults)
let release = ReleaseUpdates.Version(display: "1.5", build: "17", infoURL: nil)
var checks = 0, downloads = 0, restarts = 0
updates.beginCheck = {
checks += 1
updates.transition(to: .checking)
}
updates.beginDownload = { version in
precondition(version == release)
downloads += 1
updates.transition(to: .downloading)
}
precondition(updates.automatic)
var changes = [Bool]()
updates.changeAutomatic = { changes.append($0) }
updates.automatic = false
precondition(changes == [false] && !ReleaseUpdates(defaults: defaults).automatic)
updates.check()
updates.check()
precondition(checks == 1 && updates.phase == .checking)
updates.found(release)
updates.performAction()
updates.performAction()
precondition(downloads == 1)
updates.transition(to: .failed, error: "offline")
updates.performAction()
precondition(checks == 2 && updates.errorMessage == nil)
updates.found(release)
updates.performAction()
updates.transition(to: .extracting, fraction: 0.5)
updates.check()
precondition(checks == 2 && updates.fraction == 0.5)
updates.ready { restarts += 1 }
precondition(restarts == 0 && updates.phase == .ready)
updates.performAction()
updates.performAction()
precondition(restarts == 1 && downloads == 2 && updates.phase == .restarting)
updates.transition(to: .current)
precondition(updates.version == nil)
print("PASS: preserved preference, manual check, shared download/restart actions, busy state, retry and current version")
}
}
+170 -9
View File
@@ -59,22 +59,42 @@ import SwiftUI
var sample = MetricsSnapshot()
sample.batteryState = state
sample.systemPower = state == .absent ? 32.5 : nil
if state == .present { sample.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true, power: 0) }
if state == .present { sample.battery = BatteryMetrics(charge: 0.77, flow: BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: 0))) }
var history = MetricHistory()
history.append(sample)
sample.date = sample.date.addingTimeInterval(2); sample.systemPower = nil
sample.battery?.flow = BatteryPowerFlow(connected: false, externalSupply: false, battery: PowerReading(watts: -18))
history.append(sample)
host.rootView = AnyView(PowerResourceCard(snapshot: sample, samples: history.samples,
chartInterval: 2, chartBoundaries: [], chartIntervals: [2,2]))
if state == .present {
sample.date = sample.date.addingTimeInterval(2)
sample.battery?.flow = BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: 34.8))
history.append(sample)
sample.date.addTimeInterval(2)
sample.battery?.flow = BatteryPowerFlow(connected: true, externalSupply: true,
battery: PowerReading(watts: -8), input: PowerReading(watts: 12))
history.append(sample)
}
host.rootView = AnyView(PowerResourceCard(snapshot: sample, samples: history.samples, sleepIntervals: history.sleepIntervals,
chartInterval: 2, chartBoundaries: [], chartIntervals: history.samples.map(\.expectedInterval)))
try? await Task.sleep(for: .milliseconds(80)); host.layoutSubtreeIfNeeded()
let plot = descendants(host).compactMap { $0 as? NativePanelCurve.PlotView }.first!
let first = plot.input?.frame.series.first
switch state {
case .absent: precondition(first == [32.5, nil] && plot.input?.scales.first == 32.5)
case .present: precondition(first == [0.8, 0.8] && plot.input?.scales.first == 1 && topRect(plot, in: host) == host.bounds)
default: precondition(first == [nil, nil] && plot.input?.scales.first == 1)
if state == .absent {
let plot = descendants(host).compactMap { $0 as? NativePanelCurve.PlotView }.first!
precondition(plot.input?.frame.series.first == [32.5, nil] && plot.input?.scales.first == 32.5)
} else {
let plot = descendants(host).compactMap { $0 as? BatteryHistoryPlot }.first!
let bars = plot.layoutData.bars
precondition(plot.bounds.height >= 24 && plot.bounds.maxY < host.bounds.height)
if state == .present {
precondition(bars.map(\.charge) == [0.77, 0.77, 0.77, 0.77])
precondition(bars.map(\.state) == [.external, .battery, .charging, .combined])
precondition(bars.last?.batteryFraction == 0.4)
for bar in bars { precondition(plot.layoutData.hit(at: bar.x) == .sample(bar.index)) }
} else { precondition(bars.isEmpty) }
}
}
await checkBatteryScrolling(in: host)
checkBatteryGaps()
checkBatteryTracks()
host.rootView = AnyView(EmptyView())
try? await Task.sleep(for: .milliseconds(100))
precondition(descendants(host).allSatisfy { !($0 is NativePanelCurve.PlotView) })
@@ -85,6 +105,147 @@ import SwiftUI
NSApp.run()
}
@MainActor private static func checkBatteryScrolling(in host: NSView) async {
let viewport = BatteryHistoryViewport()
let window = host.window!
let originalSize = host.bounds.size
window.contentView = viewport
window.setContentSize(CGSize(width: 190, height: 50))
defer {
window.contentView = host
window.setContentSize(originalSize)
}
try? await Task.sleep(for: .milliseconds(60))
var history = MetricHistory()
var snapshot = MetricsSnapshot()
snapshot.battery = BatteryMetrics(charge: 0.8)
var last = BatteryHistoryLayout(samples: [], sleeps: [], width: 190)
for i in 0...MetricHistory.capacity {
snapshot.date.addTimeInterval(i.isMultiple(of: 2) ? 1.7 : 2.3)
history.append(snapshot)
let layout = BatteryHistoryLayout(samples: history.samples, sleeps: [], width: 190)
let newest = layout.bars.last!
precondition(newest.range.upperBound == 190 && newest.range.lowerBound == 190 - layout.pitch)
viewport.update(layout, hit: nil, animates: true)
viewport.layoutSubtreeIfNeeded()
if i == 0 {
precondition(layout.hit(at: 95) == nil && viewport.plot.layer?.animation(forKey: BatteryHistoryViewport.slideKey) == nil)
} else {
let oldX = last.bars.last!.x
precondition(layout.bars.dropLast().last!.x == oldX - layout.pitch)
let slide = viewport.plot.layer?.animation(forKey: BatteryHistoryViewport.slideKey) as? CABasicAnimation
precondition(slide?.fromValue as? CGFloat == layout.pitch && slide?.toValue as? CGFloat == 0)
}
if i == 2 {
let deadline = ContinuousClock.now.advanced(by: .milliseconds(500))
var movedLeft = false
while !movedLeft && ContinuousClock.now < deadline {
try? await Task.sleep(for: .milliseconds(10))
let offset = viewport.plot.layer?.presentation()?.transform.m41 ?? 0
movedLeft = offset > 0 && offset < layout.pitch
}
precondition(movedLeft, "The rendered layer must travel between adjacent column positions")
}
last = layout
}
precondition(last.bars.contains { $0.x < 0 }, "Retain a departing column for the slide")
viewport.update(last, hit: .sample(history.samples.count - 1), animates: false)
precondition(viewport.plot.layer?.animation(forKey: BatteryHistoryViewport.slideKey) == nil)
snapshot.date.addTimeInterval(300)
history.append(snapshot, breakBefore: true)
viewport.update(BatteryHistoryLayout(samples: history.samples, sleeps: [], width: 190), hit: nil, animates: true)
precondition(viewport.plot.layer?.animation(forKey: BatteryHistoryViewport.slideKey) == nil)
}
@MainActor private static func checkBatteryTracks() {
var history = MetricHistory()
var snapshot = MetricsSnapshot()
let flow = BatteryPowerFlow(connected: true, externalSupply: true)
for charge: Double? in [0, 0.5, 1, nil] {
snapshot.date.addTimeInterval(2)
snapshot.battery = BatteryMetrics(charge: charge, flow: flow)
history.append(snapshot)
}
let joint = BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: -10),
input: PowerReading(watts: 10))
for _ in 0..<3 {
snapshot.date.addTimeInterval(2)
snapshot.battery = BatteryMetrics(charge: 1, flow: joint)
history.append(snapshot)
}
let plot = BatteryHistoryPlot(frame: CGRect(x: 0, y: 0, width: 590, height: 51))
let layout = BatteryHistoryLayout(samples: history.samples, sleeps: [], width: plot.bounds.width)
plot.layoutData = layout
let bitmap = plot.bitmapImageRepForCachingDisplay(in: plot.bounds)!
plot.cacheDisplay(in: plot.bounds, to: bitmap)
func alpha(_ x: CGFloat, _ y: CGFloat) -> CGFloat {
bitmap.colorAt(x: Int(x * CGFloat(bitmap.pixelsWide) / plot.bounds.width),
y: Int(y * CGFloat(bitmap.pixelsHigh) / plot.bounds.height))!.alphaComponent
}
let bars = layout.bars
for i in [0, 3] {
precondition((0.1...0.4).contains(alpha(bars[i].x, 16)))
precondition((0.1...0.4).contains(alpha(bars[i].x, 34)))
}
let jointX = Int(bars[5].x * CGFloat(bitmap.pixelsWide) / plot.bounds.width)
let jointPixels = [10, 30].map { y in
bitmap.colorAt(x: jointX, y: y * bitmap.pixelsHigh / Int(plot.bounds.height))!.usingColorSpace(.sRGB)!
}
precondition(jointPixels.contains { $0.blueComponent > $0.greenComponent } &&
jointPixels.contains { $0.greenComponent > $0.blueComponent })
let half = [alpha(bars[1].x, 16), alpha(bars[1].x, 34)].sorted()
precondition((0.1...0.4).contains(half[0]) && half[1] > 0.95)
precondition(alpha(bars[2].x, 16) > 0.95 && alpha(bars[2].x, 34) > 0.95)
precondition(alpha((bars[1].x + bars[2].x) / 2, 24) == 0, "Adjacent tracks need a transparent gap")
}
@MainActor private static func checkBatteryGaps() {
let origin = Date(timeIntervalSinceReferenceDate: 100)
var history = MetricHistory()
var snapshot = MetricsSnapshot()
snapshot.battery = BatteryMetrics(charge: 0.8)
for seconds in [0, 2, 10, 30, 40, 42] {
snapshot.date = origin.addingTimeInterval(Double(seconds))
history.append(snapshot, breakBefore: seconds == 30 || seconds == 40)
}
let sleep = DateInterval(start: origin.addingTimeInterval(12), end: origin.addingTimeInterval(25))
history.recordSleep(from: sleep.start, to: sleep.end)
let layout = BatteryHistoryLayout(samples: history.samples, sleeps: history.sleepIntervals, width: 240)
let band = layout.sleeps[0].range
precondition(layout.hit(at: (band.lowerBound + band.upperBound) / 2) == .sleep(sleep))
let plot = BatteryHistoryPlot(frame: CGRect(x: 0, y: 0, width: layout.width, height: 50))
plot.layoutData = layout
let bitmap = plot.bitmapImageRepForCachingDisplay(in: plot.bounds)!
plot.cacheDisplay(in: plot.bounds, to: bitmap)
let scale = CGFloat(bitmap.pixelsWide) / layout.width
var columns = 0
var insideColumn = false
for x in Int(ceil(band.lowerBound * scale))..<Int(floor(band.upperBound * scale)) {
let color = bitmap.colorAt(x: x, y: bitmap.pixelsHigh / 2)!.usingColorSpace(.sRGB)!
let orange = color.alphaComponent > 0.5 && color.redComponent > color.blueComponent + 0.3
if orange && !insideColumn { columns += 1 }
insideColumn = orange
}
precondition(columns == 3, "Observed sleep must render separate orange columns at the sample pitch")
for i in [2, 4] {
let middle = (layout.bars[i - 1].x + layout.bars[i].x) / 2
precondition(layout.hit(at: middle) == nil, "Unobserved gaps stay empty")
}
// The observed sleep covers only part of the gap between two samples.
precondition(layout.hit(at: (band.upperBound + layout.bars[3].x) / 2) == nil)
for bar in layout.bars { precondition(layout.hit(at: bar.x) == .sample(bar.index)) }
snapshot.date.addTimeInterval(2)
snapshot.battery = BatteryMetrics(charge: nil, flow: BatteryPowerFlow(connected: true, externalSupply: true))
history.append(snapshot)
let missingCharge = BatteryHistoryLayout(samples: history.samples, sleeps: history.sleepIntervals, width: 240)
precondition(missingCharge.bars.last?.state == .external && missingCharge.bars.last?.charge == nil)
for _ in 0..<MetricHistory.capacity {
snapshot.date.addTimeInterval(2)
history.append(snapshot)
}
precondition(history.sleepIntervals.isEmpty)
}
@MainActor private static func fixture(probe: DetailProbe, dualMetric: Bool) -> some View {
let dates = (0..<60).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
return ResourceCard(title: "metric.network", symbol: "network", color: .blue,
+4 -4
View File
@@ -29,15 +29,15 @@ import Foundation
precondition(MetricFormat.watts(12.34) == "12.3 W")
var extended = MetricsSnapshot()
extended.network = [NetworkInterfaceMetrics(name: "en0", received: 100, sent: 50, download: 20, upload: 10)]
extended.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true, power: 0)
extended.battery = BatteryMetrics(charge: 0.8, flow: BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: 0)))
var extendedHistory = MetricHistory()
extendedHistory.append(extended)
precondition(extendedHistory.samples.last?.download == 20)
precondition(extendedHistory.samples.last?.battery == 0.8)
precondition(extendedHistory.samples.last?.batteryPower == 0)
extended.battery?.power = 12.5
precondition(extendedHistory.samples.last?.powerFlow?.battery?.watts == 0)
extended.battery?.flow.battery = PowerReading(watts: -12.5)
extendedHistory.append(extended)
precondition(extendedHistory.samples.last?.batteryPower == 12.5)
precondition(extendedHistory.samples.last?.powerFlow?.battery?.watts == -12.5)
extended.network = [NetworkInterfaceMetrics(name: "en0", received: 100, sent: 50, download: nil, upload: nil)]
extendedHistory.append(extended)
precondition(extendedHistory.samples.last?.download == nil)
+11
View File
@@ -56,6 +56,17 @@ import Observation
precondition(store.effectiveMilliseconds == 1_800_000)
precondition(store.history.samples.last?.breakBefore == true)
store.togglePause()
let pausedCount = store.history.samples.count
store.powerSourceDidChange()
try await Task.sleep(for: .milliseconds(100))
precondition(store.history.samples.count == pausedCount)
store.togglePause()
try await until { store.history.samples.count > pausedCount }
let beforeEvent = store.history.samples.count
store.powerSourceDidChange()
try await until { store.history.samples.count >= beforeEvent + 2 }
precondition(store.effectiveMilliseconds == 1_800_000)
store.togglePause()
let probe = DelayedProcessRead()
let deferred = SystemSampler(processRead: { probe.read(&$0) })
await deferred.setProcessVisible(true)
+3 -3
View File
@@ -13,10 +13,10 @@ import SwiftUI
@MainActor static func runChecks() async {
let request = SettingsPresentation()
request.request(.about)
precondition(request.requestID == 1 && request.selection == .about)
request.request()
precondition(request.requestID == 1)
request.request()
precondition(request.requestID == 2)
precondition(request.requestID == 2 && request.selection == .about)
let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 680, height: 450),
styleMask: [.titled, .closable, .miniaturizable], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
+6 -5
View File
@@ -19,7 +19,7 @@ import Foundation
precondition(BatteryMonitor.estimatedMinutes(charging: true, externalPower: true, sourceMinutes: nil, systemSeconds: 5400) == nil)
precondition(BatteryMonitor.estimatedMinutes(charging: false, externalPower: false, sourceMinutes: nil, systemSeconds: .infinity) == nil)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: 2_500) == 30)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: -2_500) == 30)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: -2_500) == -30)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 0, amperageMilliamps: 2_500) == nil)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: .nan) == nil)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 50_000, amperageMilliamps: 2_500) == nil)
@@ -29,7 +29,7 @@ import Foundation
sample.batteryState = state; sample.systemPower = 29.5
history.append(sample)
precondition(history.samples.last?.systemPower == (state == .absent ? 29.5 : nil))
precondition(history.samples.last?.batteryPower == nil && history.samples.last?.battery == nil)
precondition(history.samples.last?.powerFlow?.battery?.watts == nil && history.samples.last?.battery == nil)
}
let report = Data(#"{"SPPowerDataType":[{"sppower_battery_health_info":{"sppower_battery_health_maximum_capacity":"100%"}}]}"#.utf8)
precondition(SystemBatteryHealthMonitor.parse(report) == 1)
@@ -55,10 +55,11 @@ import Foundation
precondition(disk.total > 0 && (0...1).contains(disk.usage))
print("Volume bytes:", disk.total, "available:", disk.available)
}
if let battery = BatteryMonitor.sample() {
var monitor = BatteryMonitor()
if let battery = monitor.sample() {
precondition(battery.charge.map { (0...1).contains($0) } ?? true)
precondition(battery.power.map { $0.isFinite && (0...500).contains($0) } ?? true)
print("Battery:", battery.charge as Any, "charging:", battery.charging, "cycles:", battery.cycles as Any, "health:", battery.health as Any, "powerW:", battery.power as Any, "minutes:", battery.minutesRemaining as Any)
precondition(battery.flow.battery.map { $0.watts.isFinite && abs($0.watts) <= 500 } ?? true)
print("Battery:", battery.charge as Any, "state:", battery.flow.state, "cycles:", battery.cycles as Any, "health:", battery.health as Any, "powerW:", battery.flow.battery as Any, "minutes:", battery.minutesRemaining as Any)
} else { print("Battery unavailable or absent") }
print("Stage C checks passed")
}
-10
View File
@@ -8,16 +8,6 @@ import Foundation
precondition(ProcessMonitor.cpu(current: 1, previous: 0, elapsed: 0) == nil)
precondition(GPUMonitor.normalized(53) == 0.53)
precondition(GPUMonitor.normalized(101) == nil && GPUMonitor.normalized(.nan) == nil)
let processRows = [
ProcessMetrics(id: ProcessIdentity(pid: 1, seconds: 1, microseconds: 1), name: "unknown", path: nil, cpu: nil, footprintBytes: nil, threads: nil, restricted: true),
ProcessMetrics(id: ProcessIdentity(pid: 2, seconds: 1, microseconds: 2), name: "busy", path: nil, cpu: 2.5, footprintBytes: nil, threads: nil, restricted: false),
ProcessMetrics(id: ProcessIdentity(pid: 3, seconds: 1, microseconds: 3), name: "idle", path: nil, cpu: 0, footprintBytes: nil, threads: nil, restricted: false),
ProcessMetrics(id: ProcessIdentity(pid: 4, seconds: 1, microseconds: 4), name: "invalid", path: nil, cpu: -.infinity, footprintBytes: nil, threads: nil, restricted: false)
]
let processSnapshot = ProcessSnapshot(date: Date(), enumerated: 4, readable: 3, rows: processRows, failed: false)
precondition(processSnapshot.highestCPUProcess?.name == "busy")
precondition(processSnapshot.highestCPUProcesses(limit: 3).map(\.name) == ["busy", "idle"])
precondition(processSnapshot.highestCPUProcesses(limit: 0).isEmpty)
var snapshot = MetricsSnapshot()
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 1, sent: 1, download: 12, upload: 8),
NetworkInterfaceMetrics(name: "utun0", received: 1, sent: 1, download: 99, upload: 99)]
+10 -5
View File
@@ -14,10 +14,10 @@ import uuid
ROOT = Path(__file__).resolve().parents[1]
CORE = sorted(str(p.relative_to(ROOT)) for folder in ("Models", "Monitors", "Services", "Extensions")
for p in (ROOT / "kymo/Core" / folder).glob("*.swift"))
for p in (ROOT / "kymo/Core" / folder).glob("*.swift") if p.name != "SparkleUpdater.swift")
CHECKS = {name: list(CORE) for name in (
"SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks",
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks", "ReleaseServiceChecks", "DetailDemandChecks")}
"GPUStatisticsChecks", "StageCChecks", "BatteryPowerChecks", "MachPortChecks", "ReleaseServiceChecks", "DetailDemandChecks")}
CHECKS.update({
"BackgroundTrendChecks": CORE + ["kymo/UI/Charts/PanelCurveGeometry.swift"],
"ProcessEnergyChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "kymo/Core/Monitors/ProcessEnergyMonitor.swift"],
@@ -28,6 +28,7 @@ CHECKS.update({
"kymo/Core/Extensions/MetricFormat.swift"],
"CPUTemperatureChecks": ["kymo/Core/Monitors/CPUTemperatureMonitor.swift"],
"DiskHealthChecks": ["kymo/Core/Models/DiskHealthMetrics.swift", "kymo/Core/Monitors/DiskHealthReport.swift"],
"ReleaseUpdateChecks": ["kymo/Core/Services/ReleaseUpdates.swift"],
"PublicIPAddressChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
"NativeMetricDrawingChecks": ["kymo/UI/Charts/NativePanelCurve.swift", "kymo/UI/Charts/PanelCurveFrame.swift",
"kymo/UI/Charts/PanelCurveGeometry.swift"],
@@ -70,10 +71,14 @@ CHECKS["ResourceCardChecks"] = [
"kymo/UI/Charts/ChartTooltipLayer.swift", "kymo/Core/Extensions/MetricFormat.swift",
]
CHECKS["ResourceCardChecks"] = list(dict.fromkeys(CORE + CHECKS["ResourceCardChecks"] + [
"kymo/Features/MenuBar/PowerResourceCard.swift", "kymo/UI/Components/AppLocalization.swift",
"kymo/Features/MenuBar/PowerResourceCard.swift", "kymo/Features/MenuBar/BatteryHistoryChart.swift",
"kymo/UI/Components/AppLocalization.swift",
"kymo/Features/MenuBar/MemoryDetailsView.swift", "kymo/Features/MenuBar/StorageDetailsView.swift",
]))
CHECKS["MenuBarMetricChecks"] = CORE
CHECKS["PanelWindowChecks"] += CORE + ["kymo/UI/Components/MenuBarMetricStrip.swift"]
for name in ("PanelLayoutChecks", "PanelWindowChecks"):
CHECKS[name].append("kymo/UI/Components/ResourceCardMetrics.swift")
@@ -196,7 +201,7 @@ def main():
print(line, flush=True)
app = work / "build/Build/Products" / args.configuration / "kymo.app"
host_entitlements = entitlements(app)
run([sys.executable, "kymoTests/LocalizationCatalogChecks.py"])
run([sys.executable, "kymoTests/LocalizationCatalogChecks.py", "--app", app])
for index, name in enumerate(selected, 1):
print(f"[{index}/{len(selected)}] {name}", flush=True)
executable = work / name
@@ -232,7 +237,7 @@ def main():
finally:
clean_test_container(bundle)
else:
extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks", "MemoryHeaderChecks"} else []
extra = [app] if name in {"ReleaseUpdateChecks", "LocalizationChecks", "PanelAssetChecks", "MemoryHeaderChecks"} else []
if name == "CodeIdentityChecks":
extra = [app, app / "Contents/XPCServices/SMARTService.xpc"]
run([executable, *extra], timeout=45)
+96 -7
View File
@@ -4,12 +4,16 @@ import argparse
import hashlib
from pathlib import Path
import plistlib
import re
import shutil
import subprocess
import tempfile
import zipfile
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
KEY_ACCOUNT = "cn.airnan.kymo"
RELEASES = "https://git.airnan.cn/wangairnan/Kymo/releases/download"
def run(command):
@@ -21,6 +25,11 @@ def run(command):
def verify(app):
run(["codesign", "--verify", "--deep", "--strict", app])
info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
identifier = info["CFBundleIdentifier"]
installer = app / "Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices/Installer.xpc"
if not installer.is_dir() or not info.get("SUEnableInstallerLauncherService"):
raise RuntimeError("Missing Sparkle sandbox installer")
for target in [app, app / "Contents/XPCServices/SMARTService.xpc"]:
details = run(["codesign", "-dvvv", target]).stderr.decode()
if "Signature=adhoc" not in details or "runtime)" not in details:
@@ -29,20 +38,97 @@ def verify(app):
entitlements = plistlib.loads(signed.stdout)
expected = {"com.apple.security.app-sandbox": True,
"com.apple.security.network.client": True,
"com.apple.security.files.user-selected.read-only": True} if target == app else {}
"com.apple.security.files.user-selected.read-only": True,
"com.apple.security.cs.disable-library-validation": True,
"com.apple.security.temporary-exception.mach-lookup.global-name":
[identifier + "-spks", identifier + "-spki"]} if target == app else {}
if entitlements != expected:
raise RuntimeError("Unexpected release entitlements: " + str(target))
# With no Team ID, Hardened Runtime uses an explicit allowlist of Sparkle code hashes.
# Validate both the signed host constraints and every shipped architecture after embedding.
pinned = plistlib.loads((ROOT / "Config/Sparkle-library-constraint.plist").read_bytes())
hashes = {value.hex() for value in pinned["cdhash"]["$in"]}
details = run(["codesign", "-dvvvv", app])
constraints = (details.stdout + details.stderr).decode()
if "Has Library Load Constraints" not in constraints or any(h not in constraints for h in hashes):
raise RuntimeError("Host signature is missing the Sparkle library constraint")
framework = app / "Contents/Frameworks/Sparkle.framework"
for arch in run(["lipo", "-archs", framework / "Sparkle"]).stdout.decode().split():
signature = run(["codesign", "-dvvv", "--arch", arch, framework]).stderr.decode()
digest = re.search(r"^CDHash=([0-9a-f]+)$", signature, re.MULTILINE)
if not digest or digest[1] not in hashes:
raise RuntimeError(f"Embedded Sparkle signature for {arch} does not match the library constraint")
for path in app.rglob("*"):
if path.name in {".DS_Store", ".git", "xcuserdata"} or path.suffix in {".swift", ".xcstrings", ".md", ".py", ".dSYM"}:
raise RuntimeError("Development file in application: " + str(path))
def archive_info(package):
with zipfile.ZipFile(package) as archive:
if any(not item.filename.startswith("kymo.app/") or ".." in Path(item.filename).parts
for item in archive.infolist()):
raise RuntimeError("Unexpected archive contents")
return plistlib.loads(archive.read("kymo.app/Contents/Info.plist"))
def generate_feed(package, info, tools):
public_key = run([tools / "generate_keys", "--account", KEY_ACCOUNT, "-p"]).stdout.decode().strip()
if public_key != info["SUPublicEDKey"]:
raise RuntimeError("Release key does not match the public key embedded in Kymo")
prefix = f"{RELEASES}/v{info['CFBundleShortVersionString']}/"
run([tools / "generate_appcast", "--account", KEY_ACCOUNT, "--download-url-prefix", prefix,
"--maximum-deltas", "0", package.parent])
feed = package.parent / "appcast.xml"
item = ET.parse(feed).find("./channel/item")
ns = "{http://www.andymatuschak.org/xml-namespaces/sparkle}"
enclosure = item.find("enclosure") if item is not None else None
if (enclosure is None or enclosure.get("url") != prefix + package.name
or enclosure.get("length") != str(package.stat().st_size)
or item.findtext(ns + "version") != info["CFBundleVersion"]):
raise RuntimeError("Appcast does not describe the final release ZIP")
verify_signature = [tools / "sign_update", "--account", KEY_ACCOUNT, "--verify"]
run([*verify_signature, package, enclosure.attrib[ns + "edSignature"]])
run([*verify_signature, feed])
return feed
def sign_existing(package, work):
package = package.expanduser().resolve(strict=True)
feed = package.parent / "appcast.xml"
if feed.exists():
raise RuntimeError("appcast.xml already exists in this directory")
info = archive_info(package)
trusted = plistlib.loads((ROOT / "Config/Kymo-Info.plist").read_bytes())
if info.get("CFBundleIdentifier") != KEY_ACCOUNT or info.get("SUPublicEDKey") != trusted["SUPublicEDKey"]:
raise RuntimeError("ZIP is not a Kymo build for this Sparkle signing key")
archives = work / "archives"
archives.mkdir()
staged = archives / package.name
shutil.copyfile(package, staged)
run(["ditto", "-x", "-k", staged, work / "unpacked"])
verify(work / "unpacked/kymo.app")
run(["xcodebuild", "-resolvePackageDependencies", "-project", "kymo.xcodeproj", "-scheme", "kymo",
"-derivedDataPath", work / "build"])
signed = generate_feed(staged, info, work / "build/SourcePackages/artifacts/sparkle/Sparkle/bin")
if staged.read_bytes() != package.read_bytes():
raise RuntimeError("ZIP changed while generating its appcast")
with feed.open("xb") as result:
result.write(signed.read_bytes())
print("Signed appcast:", feed)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=ROOT / "dist", help="Output directory (existing ZIPs are preserved)")
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--sign-existing", type=Path, metavar="ZIP", help="Generate appcast.xml beside an existing Kymo release ZIP")
mode.add_argument("--zip-only", action="store_true", help="Build a local test ZIP without a signing key or appcast")
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="kymo-release-") as temp:
work = Path(temp)
if args.sign_existing:
sign_existing(args.sign_existing, work)
return
print("Building ordinary ad-hoc Release…", flush=True)
run(["xcodebuild", "-project", "kymo.xcodeproj", "-scheme", "kymo", "-configuration", "Release",
"-derivedDataPath", work / "build", "SWIFT_EMIT_LOC_STRINGS=NO", "SWIFT_ACTIVE_COMPILATION_CONDITIONS=",
@@ -52,12 +138,11 @@ def main():
info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
architectures = run(["lipo", "-archs", app / "Contents/MacOS/kymo"]).stdout.decode().strip().replace(" ", "-")
name = "kymo-{}-{}-{}-adhoc.zip".format(info["CFBundleShortVersionString"], info["CFBundleVersion"], architectures)
package = work / name
archives = work / "archives"
archives.mkdir()
package = archives / name
run(["ditto", "-c", "-k", "--keepParent", "--norsrc", "--noextattr", app, package])
with zipfile.ZipFile(package) as archive:
if any(not item.filename.startswith("kymo.app/") or ".." in Path(item.filename).parts
or item.filename.startswith("/") for item in archive.infolist()):
raise RuntimeError("Unexpected archive contents")
archive_info(package)
unpacked = work / "unpacked"
run(["ditto", "-x", "-k", package, unpacked])
verify(unpacked / "kymo.app")
@@ -65,11 +150,15 @@ def main():
output.mkdir(parents=True, exist_ok=True)
destination = output / name
checksum = output / (name + ".sha256")
if destination.exists() or checksum.exists():
if destination.exists() or checksum.exists() or (not args.zip_only and (output / "appcast.xml").exists()):
raise RuntimeError("Output already exists; choose another --output directory")
feed = None if args.zip_only else generate_feed(package, info, work / "build/SourcePackages/artifacts/sparkle/Sparkle/bin")
digest = hashlib.sha256(package.read_bytes()).hexdigest()
shutil.copy2(package, destination)
checksum.write_text(digest + " " + name + "\n")
if feed:
shutil.copy2(feed, output / feed.name)
print("Signed appcast:", output / feed.name)
print("PASS: original and extracted app signatures, runtime, entitlements and archive contents")
print("Minimum macOS:", info.get("LSMinimumSystemVersion"), "architectures:", architectures)
print("ZIP:", destination, "bytes:", destination.stat().st_size)