24 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
wangairnan 6300db3d15 feat(panel): 调整资源卡片读数布局并保留趋势平移
逐核显示 CPU 占用,在 GPU 标题展示核数并补充分项读数。无电池设备显示整机功率。

存储与网络将曲线排在详情下方,CPU、GPU、内存和电池保留整卡趋势。数值直接刷新,曲线随采样平滑平移。顶栏展示版本号,底栏调整开机时间和刷新间隔。
2026-11-15 22:03:46 +08:00
wangairnan c886c4227d feat(monitors): 为无内置电池的 Mac 采样整机即时功率
加入整机功率采样、XPC 读取和历史记录,并覆盖无电池设备的采样分支。
2026-11-15 22:03:46 +08:00
wangairnan e2f88023d6 fix(ui): 撤销文字底板并保留大字号排版 2026-11-15 19:57:59 +08:00
wangairnan 9088f8a251 fix(ui): 提升卡片文字对比度与辅助信息可读性 2026-11-15 19:51:47 +08:00
wangairnan 60c146f8b7 fix(ui): 修正风扇转轴与速率图并精简进程表 2026-11-15 19:21:18 +08:00
wangairnan 99e558625b feat(ui): 实现全卡堆叠趋势与单页资源进程布局 2026-11-15 17:59:52 +08:00
wangairnan 469766892d docs(ui): 制定堆叠背景与单页监控实施方案 2026-11-15 17:35:29 +08:00
wangairnan d87aa3ccc5 fix(ui): 缩小卡片并还原设计稿紧凑排布 2026-11-15 17:14:42 +08:00
wangairnan 3c1a2baace feat(ui): 统一实现卡片背景趋势与大数值布局 2026-11-15 15:40:29 +08:00
wangairnan 397156249b docs(ui): 制定背景趋势卡片规范与实施计划 2026-11-15 15:13:46 +08:00
wangairnan 3bf251a71c docs(ui): 添加卡片背景趋势浅深色设计稿 2026-11-15 15:08:50 +08:00
wangairnan 47e3fe6ca8 feat(menubar): 将资源概览调整为三列两行布局 2026-11-15 14:39:55 +08:00
127 changed files with 5662 additions and 954 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>
+7 -7
View File
@@ -1,18 +1,18 @@
# Kymo # Kymo
Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点击打开概览 / 进程双页面板,每次打开默认进入概览。 Kymo 是 macOS 菜单栏资源监控工具。菜单栏以竖条显示 CPU、GPU、内存和磁盘占用,以两行文字显示上传和下载速率。点击状态项打开资源卡片与进程同页的监控面板。
## 当前功能 ## 当前功能
- CPU:总占用、用户态与系统态趋势、逐核数值与短条、温度;设备信息与开机时间位于公共底栏。 - CPU:总占用、用户态与系统态趋势、按核型分组的逐核单元与悬浮数值、温度;设备信息与开机时间位于公共底栏。
- GPU:总占用与 Renderer / Tiler 趋势、核心数、温度和风扇转速。 - GPU:总占用、渲染器与分块器实时百分比和独立趋势,标题后的核心数胶囊、温度和风扇转速。
- 内存:已用与总量、应用 / 联动 / 压缩分类、缓存、可用量、压力与 Swap。 - 内存:已用与总量、应用 / 联动 / 压缩分类、缓存、可用量、压力与 Swap。
- 存储:主目录所在卷容量、块设备读写速率、各本地卷容量、可读取的 SMART 寿命与通电时间。 - 存储:主目录所在卷容量、块设备读写速率、各本地卷容量、可读取的 SMART 寿命与通电时间。
- 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计。 - 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计;确认无电池时显示传感器整机即时功率及 W 趋势。
- 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。 - 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。
- 进程:PID、名称、CPU、内存 footprint、CPU 平均功率、线程数和路径;支持搜索、列排序及复制,功率缺失始终排末。 - 进程:PID、名称、CPU、内存 footprint、CPU 平均功率、线程数六列;路径仍支持搜索和右键复制,无横向滚动条;支持列排序及复制,功率缺失始终排末。
面板支持固定显示、保持唤醒、暂停 / 恢复采样。概览采用按内容定高的独立双列,常规 640×658pt,小屏可滚动,极窄屏退为单列;进程页独占内容区。概览停止进程 / footprint / 功率读取,进程页卸载资源图表并停用概览慢读取与公网任务,基础趋势跨页连续。保留彩色卡片,数字、曲线和进度条随采样直接更新,不播放应用自定义动画或背景模糊特效;后台记录独立控制。面板刷新默认 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)。 部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;耗电进程显示系统归属的 CPU 能量区间平均功率,注明可读覆盖范围,不代表完整应用总耗电。指标口径和限制见[监控指标](docs/monitoring.md)。
@@ -26,7 +26,7 @@ open kymo.xcodeproj
xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build
``` ```
在 Xcode 中运行 `kymo`。平时仅显示菜单栏图标,打开设置时临时显示 Dock 图标。左键图标切换面板,右键打开快捷菜单。 在 Xcode 中运行 `kymo`。平时通过菜单栏状态项操作,打开设置时临时显示 Dock 图标。左键状态项切换面板,右键打开快捷菜单。
## 文档与协作 ## 文档与协作
+10
View File
@@ -3,6 +3,8 @@ import Foundation
private actor CPUTemperatureReader { private actor CPUTemperatureReader {
private let monitor = CPUTemperatureMonitor() private let monitor = CPUTemperatureMonitor()
private let gpuMonitor = CPUTemperatureMonitor(zone: .gpu) private let gpuMonitor = CPUTemperatureMonitor(zone: .gpu)
func sampleBatteryPower() -> Double? { monitor.sampleBatteryPower() }
func sampleSystemPower() -> Double? { monitor.sampleSystemPower() }
func sampleFans() -> [Double?]? { monitor.sampleFans() } func sampleFans() -> [Double?]? { monitor.sampleFans() }
func sampleGPU() -> Double? { gpuMonitor.sample() } func sampleGPU() -> Double? { gpuMonitor.sample() }
@@ -14,6 +16,14 @@ private actor CPUTemperatureReader {
final class SMARTService: NSObject, SMARTServiceProtocol { final class SMARTService: NSObject, SMARTServiceProtocol {
private let temperatureReader = CPUTemperatureReader() 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:))) }
}
func readSensors(cpu: Bool, gpu: Bool, fans: Bool, func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) { withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) {
Task { Task {
+4 -1
View File
@@ -1,6 +1,6 @@
# 项目文档 # 项目文档
本目录只描述当前源码实现、维护方式和验证边界。历史方案与过程报告通过 Git 历史查询。 本目录记录当前源码实现、维护方式、验证边界,以及明确标注为未实施的设计稿。历史方案与过程报告通过 Git 历史查询。
| 文档 | 内容 | | 文档 | 内容 |
| --- | --- | | --- | --- |
@@ -9,5 +9,8 @@
| [开发指南](development.md) | 构建、修改入口、本地化和诊断参数 | | [开发指南](development.md) | 构建、修改入口、本地化和诊断参数 |
| [测试与验证](testing.md) | 统一检查入口、覆盖范围、实际交互与验收边界 | | [测试与验证](testing.md) | 统一检查入口、覆盖范围、实际交互与验收边界 |
| [测试分发](free-test-distribution.md) | 本地 Release 打包、签名与安装支持范围 | | [测试分发](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) 存放在本目录,完成后将有效结论归入主题文档并清理失效记录。 修改实现时直接更新相应主题;大型变更的临时方案按 [AGENTS.md](../AGENTS.md) 存放在本目录,完成后将有效结论归入主题文档并清理失效记录。
+30 -20
View File
@@ -5,73 +5,83 @@
| 位置 | 当前职责 | | 位置 | 当前职责 |
| --- | --- | | --- | --- |
| `kymo/App` | AppKit 入口、生命周期、依赖装配、主菜单和 SwiftUI Settings 场景 | | `kymo/App` | AppKit 入口、生命周期、依赖装配、主菜单和 SwiftUI Settings 场景 |
| `kymo/Features/MenuBar` | 状态项、监控 NSPanel、概览卡片、进程表、业务展示投影与本地验证驱动 | | `kymo/Features/MenuBar` | 状态项、监控 NSPanel、资源卡片、进程表、业务展示投影与本地验证驱动 |
| `kymo/Features/Settings` | 通用 / 关于设置页、窗口焦点和 Dock 生命周期 | | `kymo/Features/Settings` | 通用 / 菜单栏 / 关于设置页、窗口焦点和 Dock 生命周期 |
| `kymo/Core/Monitors` | 系统采样、报告解析与 SystemSampler actor | | `kymo/Core/Monitors` | 系统采样、报告解析与 SystemSampler actor |
| `kymo/Core/Services` | MetricsStore、偏好、XPC 客户端、网络地址、保持唤醒与诊断 | | `kymo/Core/Services` | MetricsStore、偏好、XPC 客户端、网络地址、保持唤醒与诊断 |
| `kymo/Core/Models` / `Extensions` | 指标、进程身份、有界历史 / 格式化 | | `kymo/Core/Models` / `Extensions` | 指标、进程身份、有界历史 / 格式化 |
| `kymo/UI` | 无业务副作用的卡片、图表、控件、外观与本地化宿主 | | `kymo/UI` | 无业务副作用的卡片、图表、控件、外观与本地化宿主 |
| `kymo/Resources` / `Assets.xcassets` | 三语字符串 / 颜色和图片 | | `kymo/Resources` / `Assets.xcassets` | 三语字符串 / 颜色和图片 |
| `SMARTService` | 按需只读 XPC:温度、风扇、SMART、同 UID 进程 footprint 与 CPU 能量 | | `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。 入口 kymoApp.main() 启动 NSApplication,由 ApplicationLifecycle 管理;应用以 accessory 模式启动,通过 NSHostingSceneRepresentation 注册 Settings。
MenuPanelController 拥有模板品牌 NSStatusItem 和无边框、可成为 key 的非激活 MonitoringPanel。左键切换面板,右键提供打开 / 隐藏、设置和退出。窗口以状态项所在屏幕可见区域为边界,水平居中,边缘至少留 16pt;最大宽 640pt,常规高 658pt,按卡片内容预算调整,最大高 800pt,并受实际屏幕限制。 MenuPanelController 拥有可变宽度 NSStatusItem 和无边框、可成为 key 的非激活 MonitoringPanel。左键切换面板,右键提供打开 / 隐藏、设置、关于和退出。窗口以状态项所在屏幕可见区域为边界,水平居中,边缘至少留 16pt;最大宽 648pt,常规高 630pt,按卡片内容预算调整,最大高 800pt,并受实际屏幕限制。
每次显式打开进入概览。概览独立双列:左 CPU / GPU / 内存,右电池 / 存储 / 网络。两行 CPU 核心与一行风扇时两列均高 564pt。宽度小于 560pt 退为单列并将页签另放一行;高度不足时滚动。进程页独占中间内容区,两页共用窗口尺寸。底栏显示设备信息、开机时间和刷新间隔。 单页面板首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,第三行进程表跨满内容区。所有行按最高资源卡片的结构预算等高,默认均为 176pt;资源卡片宽 205⅓pt。32pt 顶栏在品牌标题右上方显示包内短版本号。26pt 底栏从左向右排列开机时间、设备与刷新间隔,面板间隔输入框宽 50pt。宽度小于 620pt 退为两列资源网格,小于 430pt 退为单列;进程始终放在资源之后,高度不足时中间区域整体滚动,表格保留自身滚动。
核心数由静态拓扑、硬件核数及快照共同确定;核心单元格按宽度增加行数,避免文字挤压。风扇在本次打开保留已发现槽位。实际卡片宽度和窗口 contentLayoutRect 驱动布局;仅结构预算变化才请求调整窗口高度。 核心数由静态拓扑、硬件核数及快照共同确定;核型分组横向排列,每个逻辑核对应一个 7×11pt 单元,从底部按真实比例填充,保留悬浮 / 辅助功能数值。核心较多时换行,每增加一行结构预算增加 15pt;风扇超过一行后每行增加 18pt,本次打开保留已发现槽位。实际卡片宽度和窗口 contentLayoutRect 驱动布局,仅结构预算变化才请求调整窗口高度。
固定按钮切换 normal / floating 层级。未固定时外部交互或应用失活收起;固定仍可显式关闭。进程表 Esc 依次清空搜索、清除选择、退出搜索焦点,然后关闭面板。隐藏卸载内容、关闭底层窗口资源并移除外部鼠标监听,控制器保留窗口对象供重开。presentation.isOpen 控制内容装配,采样可见性同时要求窗口 isVisible 与 occlusionState 可见;完全遮挡降级采样而保留内容及交互状态。 固定按钮切换 normal / floating 层级。未固定时外部交互或应用失活收起;固定仍可显式关闭。进程表 Esc 依次清空搜索、清除选择、退出搜索焦点,然后关闭面板。隐藏卸载内容、关闭底层窗口资源并移除外部鼠标监听,控制器保留窗口对象供重开。presentation.isOpen 控制内容装配,采样可见性同时要求窗口 isVisible 与 occlusionState 可见;完全遮挡降级采样而保留内容及交互状态。
MenuBarPreferences 在 UserDefaults 保存勾选集合,首次全选,空集保留。单项和批量选择均一次写入整组,只在空选与有选项之间切换时通知采样需求变化。App 将同一读取闭包注入设置页和状态项。闭包从当前 MetricsSnapshot 生成 MenuBarReading,UI 的 MenuBarMetricStrip 在两处绘制四项竖条占用及独立上下行文本。状态按钮负责点击与辅助功能,绘图子视图透传命中。取消全部后恢复原品牌图标;系统空间不足可能隐藏状态项,此时从 Finder 或 Spotlight 再次打开 Kymo 可进入设置。
设置窗口打开时转为 regular 模式并恢复焦点,SettingsWindowLifecycle 在关闭后恢复 accessory。关闭最后一个窗口不退出应用;退出时清理状态项、窗口、通知和保持唤醒断言。 设置窗口打开时转为 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 ```text
系统 API → SystemSampler actor → MetricsSnapshot → MetricsStore(MainActor) 系统 API → SystemSampler actor → MetricsSnapshot → MetricsStore(MainActor)
│ ├─ snapshot → 概览 │ ├─ snapshot → 资源卡片 / 设置预览 / 状态项
├─ 慢任务缓存 ├─ processSnapshot / energy → 进程表 ├─ 慢任务缓存 ├─ processSnapshot / energy → 进程表
└─ 单在途进程任务 └─ MetricHistory → 趋势图 └─ 单在途进程任务 └─ MetricHistory → 趋势图
SMARTService(XPC)→ 只读客户端 → 慢缓存 / 进程任务 SMARTService(XPC)→ 只读客户端 → 整机功率 / 慢缓存 / 进程任务
实际可见性、页面需求、睡眠与偏好 → MetricsStore 调度 实际可见性、详情需求、睡眠与偏好 → MetricsStore 调度
``` ```
MetricsStore 是 MainActor 可观察状态。App 将 PanelPage 转换为 setDetailDemand(processes:slowMetrics:);Core 不依赖页面类型。概览不枚举进程或读取进程 footprint / 能量;进程页不新发起概览传感器、卷、慢报告和公网请求。两页继续基础系统采样与历史,不因切页重置 CPU / 网络 / 磁盘 IO 基线或制造断点。 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 校验,旧结果不能复活隐藏需求。失效的同步进程读取仍占用单在途槽位,完成后立即补读新代次,无需等待下一轮。 进程数据独立发布到 processSnapshot,避免触发资源卡片观察者;能量独立发布,仅保留完整进程身份、功率和统计窗口,测量数量由结果行数派生,排序统一由进程表投影负责。需求代次同时在 Store 与 actor 校验,旧结果不能复活隐藏需求。失效的同步进程读取仍占用单在途槽位,完成后立即补读新代次,无需等待下一轮。
暂停停止周期发布、停用进程更新并保留快照和历史;恢复重置基线并标记历史断点。系统睡眠停止采样;息屏停用前台、进程、能量、公网与慢读取,只保留显式后台趋势。NSWorkspace 事件由 App 转发。 暂停停止周期发布、停用进程更新并保留快照和历史;恢复重置基线并标记历史断点。系统睡眠停止采样;息屏停用前台、进程、能量、公网与慢读取,只保留显式后台趋势。App 转发 NSWorkspace 通知。MetricsStore 配对系统睡眠与唤醒的实际时间,MetricHistory 在最近采样窗口内保留至多 60 段睡眠,息屏或暂停不会产生睡眠记录。
历史全局及每接口各最多 60 点,接口移除时清理其历史。每点 expectedInterval 表示其后的计划等待;连续需求重新调度将最长等待记入最近点。绘图按真实时间跳过 nil / 非有限节点,连接有效点,保留有效 0;显式停采、长空档和倒序仍断线,包括空值点携带的断点。原数据不补值,缺失时刻无悬浮测量标记。 历史全局及每接口各最多 60 点,接口移除时清理其历史。每点 expectedInterval 表示其后的计划等待;连续需求重新调度将最长等待记入最近点。绘图按真实时间跳过 nil / 非有限节点,连接有效点,保留有效 0;显式停采、长空档和倒序仍断线,包括空值点携带的断点。原数据不补值,缺失时刻无悬浮测量标记。
## 展示与本地状态 ## 展示与本地状态
ResourceCard 通过 NativeContentHost 使用固定尺寸的独立 NSHostingView,完整传递字体、颜色、语言及外观环境;更新沿用挂载身份,卸载清空子宿主内容。图表锚点和提示层在同一卡片宿主内处理。NativePanelCurve 绘制静态曲线、网格和悬浮标记,只在数据、几何或外观变化时更新。数字和进度条直接展示最终值;不创建应用自定义动画、面积渐变、遮罩、背景模糊或装饰阴影。 ResourceCard 通过 NativeContentHost 使用固定尺寸的独立 NSHostingView,传递字体、颜色、语言及外观环境;更新沿用挂载身份,卸载清空子宿主内容。CPU、GPU 和内存采用整卡背景图,卡片顶边对应 100% 或物理内存总量,底边对应零。存储、网络与无电池整机功率图使用详情下方的剩余高度。辅助信息主要为 10pt / 16pt 行高,内存和存储详情通过 ViewThatFits 按信息组换行,默认卡片仍为 176pt 高。统一 16pt 圆角、10pt 前景内边距和静态轻阴影,图表锚点和提示在同一宿主内处理;不显示常驻图例、数值坐标轴、网格或起止时间。
概览与设置共享 NeutralTabPicker,使用静态 AppKit 按钮组;保留 tabGroup / tabButton 语义、选中值与键盘导航。绑定仅传递选择,页面和采样生命周期由上层负责。 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 口径见监控文档,不再显示重复容量进度条。
进程列表使用 view-based NSTableView,只创建可见单元格并原地更新。ProcessTableProjection 负责搜索、排序及悬停 / 选择 / 搜索期间的顺序保持。选择由完整 ProcessIdentity 同步,原生委托回调之后才写回 SwiftUI。列依次为 PID、名称、CPU、内存、CPU 功率、线程数、路径;路径末列可横向滚动,支持排序及复制。ProcessIconCache 保存 30×30 像素缩略图,最多 128 项 / 1 MiB,30 秒过期、LRU 淘汰、内存压力清空,无轮询任务。 MetricText 用等宽数字直接显示当前读数。连续追加时 NativePanelCurve 在已有 curves 图层进行 0.35 秒水平变换,历史满窗时绘制一个出界旧点;不逐帧重建路径。悬浮时对齐最终位置,暂停、减弱动态效果与断点不启动滚动。风扇是唯一持续动效:FanRotor 将 SF Symbol 绘制到独立图像子图层,固定中心锚点和位置,使用原生 Core Animation 旋转子图层,AppKit 宿主图层保持不变,按历史 RPM 档位映射 90 / 180 / 300 / 450°/s,切档保留相位;零 / 无效 / 缺失值、系统减弱动态效果、暂停、隐藏、遮挡、睡眠或卸载时停止。没有新增帧计时器。样式与异常状态见 [UI 设计规范](ui-design-standard.md)。
外观、语言和采样配置写入 UserDefaults;固定、暂停、保持唤醒与进程交互不持久化。旧减弱动画偏好键忽略但不清除。AppLanguageScope 传递应用语言并刷新宿主,AppLocalization 为原生菜单取文案;编号风扇保留参数化 Text。 设置使用 NeutralTabPicker 静态 AppKit 按钮组,保留 tabGroup / tabButton 语义、选中值与键盘导航。
进程列表使用 view-based NSTableView,只创建可见单元格并原地更新。ProcessTableProjection 负责搜索、排序及悬停 / 选择 / 搜索期间的顺序保持。保持顺序时按上一轮显示的完整进程身份取回最新行,仅对新出现的匹配行排序后追加。选择由完整 ProcessIdentity 同步,原生委托回调之后才写回 SwiftUI。只显示 PID、名称、CPU、内存、CPU 功率、线程数六列;使用 plain 样式消除额外行内缩进,由原生滚动宿主在 tile 时按可用宽度分配六列,禁用横向滚动及手动扩宽。路径保留在模型中用于搜索与右键复制。原可见口径 / 能量覆盖说明行移至进程标题提示,保留状态且不占行高。ProcessIconCache 保存 30×30 像素缩略图,最多 128 项 / 1 MiB,30 秒过期、LRU 淘汰、内存压力清空,无轮询任务。
外观、语言、菜单栏勾选和采样配置写入 UserDefaults;固定、暂停、保持唤醒与进程交互不持久化。旧减弱动画偏好键忽略但不清除。AppLanguageScope 传递应用语言并刷新宿主,AppLocalization 为原生菜单取文案;编号风扇保留参数化 Text。
## XPC 与数据边界 ## XPC 与数据边界
主应用启用 App Sandbox 和出站网络权限;SMARTService 不启用沙盒,启用 Hardened Runtime,是同用户按需启动的只读服务,不是 root 守护进程,不写 SMC。客户端以包内服务实际 designated requirement 限制连接;服务按同 UID 和所属主应用的实际签名要求认证调用方。 主应用启用 App Sandbox 和出站网络权限;SMARTService 不启用沙盒,启用 Hardened Runtime,是同用户按需启动的只读服务,不是 root 守护进程,不写 SMC。客户端以包内服务实际 designated requirement 限制连接;服务按同 UID 和所属主应用的实际签名要求认证调用方。
ServiceRequest 统一一次性完成响应、错误、中断、超时和取消,并释放计时器与连接。温度 / 风扇超时 2 秒,SMART 超时 15 秒。传感器发现由服务 actor 缓存,各能力独立退避。进程 footprint 和能量经原有签名认证服务批量读取,最多 256 项 / 请求 64 KiB / 响应 256 KiB;客户端总截止 3 秒、单请求 1.5 秒,服务每批 1 秒。服务限制同 UID、PID 与启动时间,能量额外校验请求 UUID、启动标记和计数。进程单在途任务先合并 footprint 再发布、调度能量;缺失内存不回退 RSS。具体口径见[监控指标](monitoring.md)。 ServiceRequest 统一一次性完成响应、错误、中断、超时和取消,并释放计时器与连接。温度 / 风扇 / 整机功率超时 2 秒,SMART 超时 15 秒。传感器发现由服务 actor 缓存,各能力独立退避。进程 footprint 和能量经原有签名认证服务批量读取,最多 256 项 / 请求 64 KiB / 响应 256 KiB;客户端总截止 3 秒、单请求 1.5 秒,服务每批 1 秒。服务限制同 UID、PID 与启动时间,能量额外校验请求 UUID、启动标记和计数。进程单在途任务先合并 footprint 再发布、调度能量;缺失内存不回退 RSS。具体口径见[监控指标](monitoring.md)。
system_profiler / diskutil 共用 BoundedProcess,流式保留最多 256 KiB,额外至多读 1 字节检测溢出;10 秒截止、超限或调用 Task 取消时终止并回收本轮直接子进程。取消管道唤醒 poll,无周期检查计时器,不杀其他进程。XPC 断开尚不保证取消已进入服务的报告任务。 system_profiler / diskutil 共用 BoundedProcess,流式保留最多 256 KiB,额外至多读 1 字节检测溢出;10 秒截止、超限或调用 Task 取消时终止并回收本轮直接子进程。取消管道唤醒 poll,无周期检查计时器,不杀其他进程。XPC 断开尚不保证取消已进入服务的报告任务。
PanelPublicIPRefresh 由概览挂载并控制请求及等待生命周期。路由键包含主接口候选、路径状态和全部活动地址,地址变化可能触发额外刷新。PublicIPAddressService 使用专用 ephemeral URLSession,禁用 URLCache、Cookie 和凭据存储;600 秒成功 / 30 秒失败缓存仅在内存。取消结果不缓存或发布。该约束不覆盖 macOS 容器元数据、日志、崩溃报告或旧版遗留数据。 PanelPublicIPRefresh 由网络卡片挂载并控制请求及等待生命周期。路由键包含主接口候选、路径状态和全部活动地址,地址变化可能触发额外刷新。PublicIPAddressService 使用专用 ephemeral URLSession,禁用 URLCache、Cookie 和凭据存储;600 秒成功 / 30 秒失败缓存仅在内存。取消结果不缓存或发布。该约束不覆盖 macOS 容器元数据、日志、崩溃报告或旧版遗留数据。
保持唤醒使用两个进程级 IOPM 断言阻止用户空闲息屏与系统空闲睡眠;失败、关闭或退出释放。Release 与服务配置 Hardened Runtime;本地 ad-hoc 签名不等同于 Developer ID 和 Apple 公证,详见[测试分发](free-test-distribution.md)。 保持唤醒使用两个进程级 IOPM 断言阻止用户空闲息屏与系统空闲睡眠;失败、关闭或退出释放。Release 与服务配置 Hardened Runtime;本地 ad-hoc 签名不等同于 Developer ID 和 Apple 公证,详见[测试分发](free-test-distribution.md)。
+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 窗口中验证了首柱靠右、连续采样左移一格、动画中途的实际位移、满窗淘汰,以及悬浮和采样中断时停止平移。
+82
View File
@@ -0,0 +1,82 @@
# 背景趋势卡片实施计划
## 背景与目标
用户已确认背景趋势设计图,并要求先制定标准再统一实现。目标是让六张资源卡片遵循统一的“大数值 + 前景详情 + 底部背景趋势”结构,保留数据口径与已有功能。标准见 [UI 设计规范](ui-design-standard.md)。
## 变更前现状与影响范围
变更前 ResourceCard 将主值放在标题行,PanelTrendChart 自带图例 / 轴 / 网格 / 时间,卡片常规高约 204–208pt。涉及 UI/Components(卡片、样式)、UI/Charts(曲线、填充、提示)、Features/MenuBar(六卡内容、几何预算)、kymoTests 与 tools/check.py(检查入口)及 docs。Core 采样、XPC、App 生命周期、Settings 与进程业务不变;资源色继续使用 Assets。
## 设计方案
ResourceCard 统一容纳独立前景和底部 chart,主值与单位分层。NativePanelCurve 用既有有界连续段构建线和实色面积,允许选择可见序列;PanelTrendChart 保留全部历史与自动尺度供悬浮。面积不跨真实断点、不为单点补图,悬浮不触发路径重建。布局基础卡高 264、图区 72,CPU 核心与风扇行扩展预算。
## 分阶段步骤
1. 制定规范与计划,先提交文档。
2. 实现统一卡片、背景曲线与面积;迁移六张卡片及动态尺寸。
3. 更新行为检查并构建;检查浅深色、三语、硬件行数与窄屏。
4. 在隔离应用副本中核对展示与交互;同步架构、指标、测试文档,清理测试产物,提交实现,并输出独立目录的本地测试分发包。
用户未设置阶段暂停点,各阶段按顺序连续执行。
## 测试与验证计划
- xcodebuild Debug build;无 XCTest Target,使用 tools/check.py 的独立检查。
- PanelLayoutChecks / CPUCoreGridChecks:264 基础高、两行等高、动态硬件行、三 / 二 / 单列、屏幕与滚动边界。
- NativeMetricDrawingChecks / PanelCurveChecks:静态填充像素、空档、零、单点、可见序列、缺失提示标记、悬浮缓存与外观。
- 原生宿主 / 页签 / 窗口 / 本地化 / 资源颜色等受影响回归;按需补充真实卡片挂载检查,不仅核对实现字符串。
- 测试前记录既有应用进程,保留用户现有副本;仅截取面板内容;测试结束清理本轮应用、容器、截图与构建产物。
## 风险与兼容性
信息密度增加可能影响窄屏、三语和 IPv6;用独立前景预算、主值缩放、完整悬浮与复制解决。曲线填充可能越过真实断点;必须逐段闭合并做像素验证。静态阴影和填充增加绘制工作,不增加采样或动画任务;长期能耗不由局部截图证明。生成图格子不作为 CPU 拓扑,品牌使用真实素材。部署目标与已有硬件指标兼容性保持不变。
## 进度与验证记录
- [x] 规范与实施计划制定。
- [x] 统一组件与六卡迁移。
- [x] 构建与自动检查。
- [x] 本机可执行的实际应用核对与文档同步,人工验收边界见下。
### 本轮证据(2026-11-15)
- 规范 / 计划先提交为 3971562,随后实施。未新增依赖,Core、XPC 与采样口径未改动。
- Debug 与 Release xcodebuild 均通过;仅有工具链“无 AppIntents 依赖,跳过元数据提取”提示,无 Swift 编译警告。
- tools/check.py 通过 14 项独立 Swift 检查:PanelLayoutChecks、CPUCoreGridChecks、PanelCurveChecks、NativeMetricDrawingChecks、ResourceCardChecks、NativeContentHostChecks、PanelWindowChecks、MemoryHeaderChecks、PanelAssetChecks、LocalizationChecks、LanguageScopeChecks、TabPickerChecks、NativeProcessTableChecks、DetailDemandChecks;145 个资源键三语 / 参数检查与主应用 entitlement 检查通过。
- 主值单位排版、单位对比度与提示定位细化后,重新运行 ResourceCardChecks、NativeMetricDrawingChecks,通过。生产卡片在 266 / 308 / 460pt、浅深色、三语与长双速率 / 百分比下挂载检查通过;原生图区均为贴底 72pt,前景与图区隔离。
- 使用随机 bundle ID 的独立 Debug 副本,主应用 / XPC 保持签名认证。面板自身截图核对:简体浅 / 深色 960×630,英文两列 800×500,繁体深色单列 480×500;未采集桌面。
- 原生 AX 操作确认:暂停 / 恢复(恢复首帧出现差分缺失符合既有规则)、网络从全部切到 en0、本地卷弹出层打开 / Cancel 关闭、繁体单列滚动条从 0 变化、进程页与概览切换及卡片恢复。
- 曾遇到 Mac 锁屏;用户解锁后继续验证。锁屏前的英文两列已完成展示检查,锁屏期间没有继续投递原生交互。
### 未验证与人工验收
- UI 工具对图表 AX 元素的点击未取得有效悬浮证据(采集时 hoveredPlots 为 0),不能将它当成真实指针悬浮已通过。自动检查覆盖了悬浮标记、缺失点与几何缓存;请在任一卡片底部趋势移动鼠标,核对时间 / 各序列值提示、定位点、离开后消失、主数值保持实时且提示不盖住复制控件。
- 长 IPv6 使用既有全文提示 / 选择 / 复制路径,但本轮未遇到真实长 IPv6 环境;真实多显示器、主观外观与长期 CPU / 内存 / 能耗仍需对应环境验收。短时资源或截图不作长期性能结论。
- 分发包按实现提交输出至 dist 的独立子目录,保留已有产物,不自动改版本号。没有安装替换用户当前运行的 /Applications/kymo.app。
### 分发与清理
- 本地 Release 包:`dist/background-trends-v1/kymo-1.2-14-arm64-adhoc.zip`,arm64,最低 macOS 27.0;主应用与 XPC 原始签名 / 解压签名、Hardened Runtime、权限和归档内容检查通过,SHA-256 复核通过。
- SHA-256:`05af0be97d93a96d2e47583f595fbdd26a3dd117023177b6fe1ff0d60bfc6aa1`。本地 ad-hoc 签名,未公证;不代表其他 Mac 默认 Gatekeeper 放行。
- 随机测试副本、其容器、局部截图、临时脚本与 DerivedData 已清理。仅终止本轮测试路径下的进程,未操作用户安装副本;分发产物位于 Git 忽略目录。
## v1.1:按用户反馈收紧尺寸与图稿一致性
用户指出首版未严格还原图稿且尺寸过大,要求宽、高调整为当前 2/3。本轮以此修正规范:常规卡片 308×264 → 205⅓×176pt,面板最大宽 648pt、常规高 448pt,间距 6pt,底图 48pt;三列阈值 620pt、两列阈值 430pt。保持原生布局,不对整个界面做缩放变换。
还原图稿中的紧凑左对齐信息行:CPU 按核型逐行显示真实逐核细条(数值移至悬浮 / 辅助功能);GPU 核数与阶段值放在主数值下方;内存分类改为单行 + 容量条 + 可用量;电源状态和卷入口移到标题右侧;网络累计改为单行,实时数值用 primary、方向箭头保留语义色。采样、图表数据、复制和卷详情行为不变。
实施顺序:几何与组件 → 六卡内容 → 三语 / 窄屏 / 像素及构建检查 → 实际面板与图稿对照 → 更新分发包。验证仍采用前述独立检查,调整它们的几何断言并检查缩小后没有溢出;保留用户已有应用进程。
- [x] v1.1 实施与验证。
### v1.1 验证与交付
- Debug 构建通过;打包脚本的普通 Release 构建、原包 / 解压包签名、权限、Hardened Runtime 和内容检查通过。
- 9 项受影响检查通过:PanelLayoutChecks、CPUCoreGridChecks、ResourceCardChecks、NativeMetricDrawingChecks、PanelWindowChecks、MemoryHeaderChecks、LocalizationChecks、FanChecks、NativeProcessTableChecks。末轮逐核格子、容量条和标签细化后,重跑 CPUCoreGridChecks / ResourceCardChecks / MemoryHeaderChecks / LocalizationChecks,通过;159 个三语资源键与格式参数检查通过。
- 新增实际内存容量条像素检查;明确使用数值转换 UInt64 → Double,避免被解释为浮点位模式。分数点窗口尺寸以 AppKit 实际取整后的 content bounds 校验,背景图区保持贴边 48pt。
- 面板自身截图对照图稿:简体浅色与英文深色 648×448pt,未见明显裁切;容量条、逐核格子、内存分类行、标题右侧电源 / 卷入口和单行网络累计均已核对。
- 实际 AX 操作确认标题栏本地卷入口打开 / Cancel 关闭、520×360pt 窄屏滚动(滚动值由 0 变化)、进程页与概览切换恢复。原有真实指针悬浮、多屏与长期能耗边界仍适用。
- 新包:`dist/background-trends-compact-v1/kymo-1.2-14-arm64-adhoc.zip`;旧包保留。本地 ad-hoc 签名、未公证,最低 macOS 27.0。SHA-256:`d6207b4a02c9576667efb5d41841ecf38de7af926e28451915896156cbb1da64`,校验通过。
+35
View File
@@ -0,0 +1,35 @@
# 单页监控细节修正方案
## 目标与范围
根据本轮两张截图修正风扇转轴、速率背景尺度、内存重复进度条与进程表。工作区及暂存区开始时干净。涉及 UI/Components、UI/Charts、Features/MenuBar、相关检查与 docs;Core 指标及系统 API 不改变,不新增依赖。
## 方案
1. 风扇不再旋转 AppKit 管理的宿主 backing layer。独立图像子图层以 (0.5, 0.5) 为锚点,位置固定为图标区域中心;布局改变只更新尺寸 / 位置,沿用既有速度档位、相位和停转条件。
2. 存储 / 网络采用双向速率曲线:自卡片顶向下 60% 处为零轴,上方读取 / 上传,下方写入 / 下载;两侧各使用卡片高度 30% 的振幅,共享同一自动速率尺度,峰值不触及卡片顶边。保留原始正速率和提示读数、采样断点及缓存几何,不将速率解释为百分比。CPU / GPU / 内存 / 电池继续原尺度。
3. 内存检查实际采样调用链:internal − purgeable 为匿名应用 / 系统进程部分,wired 含内核和驱动等常驻内存,compressed 为压缩器实际物理占用;三者为已用内存。缓存属于可回收 / 可用部分,Swap 为磁盘占用,均不能再次叠入已用。保留三层趋势和分类 / 可用数值,移除额外容量进度条,通过提示及文档说明口径。
4. 进程表只显示 PID、名称、CPU、内存、CPU 功率、线程六列,列宽随视口适配,关闭横向滚动;路径仍在数据模型中,支持搜索和右键复制。移除截图中的整行说明 / 能量覆盖文案,把口径与状态保留在进程标题提示中。
## 实施与验证
- [x] 实现图层中心、双向投影、内存和表格调整。
- [x] 补充旋转中心在多角度 / 多尺寸下不漂移、双向面积 / 悬浮 / 断点、内存分类守恒、六列表格视口适配与真实复制动作检查。
- [x] Debug 构建,运行受影响独立检查;隔离副本实测真实面板、三语 / 浅深色及相关控件,只采集本应用区域。
- [x] 同步架构 / 设计规范 / 监控口径和测试说明;生成新 dist 包并核验,清理本轮临时产物,提交代码,不推送。
## 风险与边界
内存分组是系统统计口径,匿名系统进程不另立一项重复统计;不能保证与另一时间点活动监视器逐字节相同。窄屏六列会截断长名称和标题,完整名称 / 路径可复制。风扇中心使用实际原生图层及多个角度验证,单张静态截图不证明动画全过程;长期能耗与多屏仍需对应环境。
## 验证结果(2026-11-15)
- Debug 构建通过,隔离副本使用 ENABLE_DEBUG_DYLIB=NO;未改变沙盒或权限。仅有未使用 AppIntents 的元数据提示。
- 8 项受影响检查通过:FanRotorChecks、NativeMetricDrawingChecks、NativeProcessTableChecks、ProcessSectionChecks、MemoryChecks、ResourceCardChecks、StackedSeriesChecks、PanelLayoutChecks;161 个目录键的三语和格式参数检查通过。
- 风扇:独立子图层在 11 / 20 / 32pt、0 / 45 / 90 / 180 / 270° 下中心不偏移,宿主变换保持恒等,档位时长、无效 / 零 / 缺失值、非活动 / 减弱动态效果和卸载停转通过。
- 速率:实际图层面积位于各自零轴一侧;存储 / 网络上下方向、共同尺度、真实断点、悬浮位置 / 缓存及静态图层检查通过。检查发现新增零轴更新曾在禁用隐式动画事务之外,已修正并通过无动画检查。
- 内存:实际采样分类守恒;压缩较多 / 缓存 / Swap 夹具不重复叠加;已用与可用合计物理总量。采样公式不变,核对依据与限制记录于 monitoring.md。
- 表格:默认 uniform / inset 布局在窄屏有列被挤出,改为 plain 样式并在滚动宿主 tile 时分配视口宽度;900 / 628 / 340pt 实际窗口中六列末端位于视口内,没有横向滚动条。隐藏路径列后真实 NSMenu 复制动作仍取得完整路径,检查后恢复原剪贴板。三语 / 浅深色的生产区域保持 176pt 高且移除说明行后表格占满剩余空间。
- 隔离实际应用深色简体面板截图与 AX 状态核对:六卡与进程同页;风扇图标位置、双向趋势、无重复内存容量条、六列无路径 / 横向滚动及说明行移到标题帮助均符合设计。只截取本应用内容,保留原安装副本。AX 右键动作只观察到行选择,未把它记为系统鼠标弹出菜单通过;复制能力由上述原生菜单动作检查验证。
- 新 dist/dashboard-polish-v1 的普通 Release 构建、原始 / 解压包签名、Hardened Runtime、沙盒 / 网络权限及压缩包内容通过;版本 1.2 (14),arm64,macOS 27.0 起,ad-hoc 未公证。SHA-256 单独复核。
- 清理本轮隔离应用、容器、截图、脚本、日志、检查崩溃报告及临时构建。真实鼠标悬浮 / 右键菜单手感、多屏及长期能耗仍未完成本轮实测。
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

@@ -0,0 +1,58 @@
# 卡片背景趋势设计稿 v1
日期:2026-11-15。基于当前三列两行概览与用户提供的下载卡片参考图。
**状态:用户已确认并采纳。图片是风格参考,不是应用截图。** 可执行标准见 [UI 设计规范](../../ui-design-standard.md),实施与验证见 [实施计划](../../card-background-trends-plan.md),当前实现以 [架构](../../architecture.md) 和代码为准。
## 设计图
- [浅色概览](overview-light.png)
- [深色概览](overview-dark.png)
- [网络卡片:默认与悬浮读数](network-hover.png)
![浅色概览](overview-light.png)
![深色概览](overview-dark.png)
![网络卡片交互](network-hover.png)
## 视觉与布局
- 保持三列两行:首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,同一行卡片等高。
- 卡片顶部为资源名称、图标和温度 / 状态;主数值置于左上区域并放大,单位与总量降低字号。
- 辅助指标位于中部前景,曲线位于卡片底部约三分之一区域,横向贴边并按卡片圆角裁切。面积填充使用低透明度,避免影响文字对比度。
- 趋势成为卡片背景,移除独立图框、常驻坐标轴、网格和时间标签;历史精确读数通过悬浮提示呈现。
- CPU 青绿、GPU 玫红、内存蓝、电池绿、存储琥珀;网络下载蓝、上传琥珀。浅深色使用相同布局与语义色。
- 顶栏保留品牌、概览 / 进程页签和操作组;底栏保留设备、开机时间和刷新间隔。
## 信息与交互
| 卡片 | 前景信息 | 背景趋势 |
| --- | --- | --- |
| CPU | 总占用、温度、用户 / 系统、逐核区域 | 总占用主曲线;用户 / 系统历史应在后续细化中保留查询 |
| GPU | 总占用、温度、核心数、Renderer / Tiler、风扇 | 总占用主曲线;阶段历史应在后续细化中保留查询 |
| 内存 | 已用 / 总量、压力、分类、可用量与分布条 | 已用量主曲线;缓存、Swap 与分类历史需保留访问路径 |
| 电池 | 电量、功率、电源、健康、循环、估时 | 电量主曲线;功率与电量单位不同,不能共用未经解释的数值尺度 |
| 存储 | 已用 / 总量、可用、读写、寿命、通电、本地卷 | 读 / 写双曲线 |
| 网络 | 收发速率、累计收发、接口、地址和复制 | 下载 / 上传双曲线 |
悬浮于底部趋势区域时显示采样时间、各序列历史值、垂直定位线和有效点标记。上方实时主数值保持当前值,不随悬浮替换。缺失点不伪造值,暂停和真实空档保留断线。
## 效果图与实现规格的边界
- 图片由内置 image_gen 生成,用于评审风格与层级,不是像素级组件规格;图中的数据为示例,IP 使用文档示例地址。
- CPU 核心区的格子是生成图中的粗略示意,数量及填色不作为实现依据。落地时应保留真实逐核数值 / 短条及拓扑分组,不把“能效核 4 / 性能核 10”做成亮灯数量。
- 背景曲线需表达真实数值、时间和缺失状态,不能为了装饰随意改变振幅、补点或添加动态波纹。
- 已采纳静态实色透明填充与轻阴影;不使用面积渐变或动画。具体参数与性能约束以 UI 设计规范为准。
- 生成图中的品牌图标、硬件图标、箭头与刷新控件是视觉示意;实际采用仓库品牌素材、现有系统图标和可编辑刷新控件。
- 效果图中的卡片尺寸仅表达比例;精确字号、圆角、主值适配、三语、窄屏、悬浮、多序列尺度及缺失状态已归入 UI 设计规范,验证结果见实施计划。
## 生成方式与提示词
使用内置 image_gen,以用户参考图作为样式参考;浅色图生成后,作为深色版与交互详情的布局参考。未使用 API / CLI,也未修改参考图片。
最终设计提示词组(可用于后续细化):
1. **浅色概览**:为 macOS 菜单栏资源监控工具 Kymo 生成正视高保真界面。保持三列两行六张等高卡片,上排 CPU、GPU、内存,下排电池、存储、网络。采用参考图的圆角白色卡片、大号深色数值、较小单位、底部贴边彩色折线与低透明度面积填充;无独立图框、坐标轴或网格。前景保留各卡片辅助指标、顶栏页签和固定 / 唤醒 / 暂停 / 设置 / 退出,底栏保留设备、运行时间与刷新。CPU 16%、GPU 40%、内存 26.6 / 48 GiB、电池 80%、存储 373 / 995 GB、网络下载 890 B/s 与上传 128 B/s。准确简体中文,克制的原生 macOS 风格,不加外部宣传标题或设备模型。
2. **深色概览**:以浅色概览为布局参考,只改为深蓝灰面板、稍亮的卡片、浅色主文字与灰色辅助文字;保持六张卡片内容和位置。曲线语义色保持不变,填充透明度约 10–16%,不使用霓虹光晕。CPU 逐核应按四个能效核和十个性能核独立表现。无新增功能和额外标题。
3. **网络交互**:以浅色网络卡片为参考,左右并排展示默认状态和悬浮历史状态。两张卡片的实时值与前景信息一致。右侧仅在底部曲线添加垂直定位线、下载 / 上传点和小型提示框,显示 14:32:18、下载 28 KB/s、上传 2.4 KB/s;实时主值仍为下载 890 B/s、上传 128 B/s。提示框避开地址与主值,曲线贴底裁切,无坐标网格。
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

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

+4 -5
View File
@@ -19,12 +19,12 @@ kymo/ 使用文件系统同步组,源码自动纳入应用;新增非源码
| --- | --- | | --- | --- |
| 入口与装配 | kymo/App/kymoApp.swift | | 入口与装配 | kymo/App/kymoApp.swift |
| 状态项 / 窗口 / 布局 | MenuPanelController.swift、PanelLayout.swift、PanelWindowObserver.swift | | 状态项 / 窗口 / 布局 | MenuPanelController.swift、PanelLayout.swift、PanelWindowObserver.swift |
| 概览 | MenuPanelView.swift 及 ResourceCards / Network 扩展 | | 单页资源布局 | MenuPanelView.swift 及 ResourceCards / Network 扩展 |
| 进程 | ProcessTableView.swift、ProcessTableProjection.swift、NativeProcessTable.swift | | 进程 | ProcessTableView.swift、ProcessTableProjection.swift、NativeProcessTable.swift |
| 采样 | MetricsStore.swift、SystemSampler.swift | | 采样 | MetricsStore.swift、SystemSampler.swift |
| 设置 | AppearanceSettingsView.swift、SettingsWindowLifecycle.swift | | 设置 | AppearanceSettingsView.swift、SettingsWindowLifecycle.swift |
通常启动仅显示菜单栏图标;打开设置时临时显示 Dock 图标。面板底栏修改可见采样间隔,通用设置控制后台趋势与后台间隔。概览和进程的按页需求由 App 转为 Core 布尔开关。 启动后按选择显示菜单栏指标,取消全部时显示品牌图标;打开设置时临时显示 Dock 图标。面板底栏修改可见采样间隔,菜单栏指标共用面板刷新间隔,通用设置控制无实时展示需求时的后台趋势与后台间隔。App 同时启用 Core 的进程与慢指标需求,由实际可见性、暂停与睡眠控制执行。
颜色与图片放入 Assets.xcassets;字符串位于 Resources 的 Localizable、CPUDetails、Process、StatusItem 四个目录,支持简体中文、繁体中文、英文及跟随系统。SwiftUI 文案使用当前 locale,原生文案通过 AppLocalization 读取。新增文案同步三语、格式参数并检查真实布局: 颜色与图片放入 Assets.xcassets;字符串位于 Resources 的 Localizable、CPUDetails、Process、StatusItem 四个目录,支持简体中文、繁体中文、英文及跟随系统。SwiftUI 文案使用当前 locale,原生文案通过 AppLocalization 读取。新增文案同步三语、格式参数并检查真实布局:
@@ -47,10 +47,9 @@ Debug 或显式 KYMO_AUDIT 构建可设置 KYMO_RESOURCE_AUDIT=1 驱动三轮真
| 参数 | 行为 | | 参数 | 行为 |
| --- | --- | | --- | --- |
| KYMO_AUDIT_QUICK=1 | 缩短隐藏等待并跳过暂停阶段 | | KYMO_AUDIT_QUICK=1 | 缩短隐藏等待并跳过暂停阶段 |
| KYMO_AUDIT_PAGE=processes | 每轮打开后进入进程页 | | KYMO_AUDIT_CAPTURE=1 | 第一轮打开 10 秒后输出本应用面板 PNG 的 JSON 事件;与 INTERACTIVE / SIZE 组合时截取对应视口 |
| KYMO_AUDIT_CAPTURE=1 | 第一轮打开 10 秒后输出本应用面板 PNG 的 JSON 事件 |
| KYMO_AUDIT_INTERACTIVE=1 | 打开固定面板供人工 / UI 工具操作,不自动退出 | | KYMO_AUDIT_INTERACTIVE=1 | 打开固定面板供人工 / UI 工具操作,不自动退出 |
| KYMO_AUDIT_SIZE=480x500 | 交互模式限制测试视口,不覆盖自动尺寸;最小 480×360pt | | KYMO_AUDIT_SIZE=480x500 | 交互模式限制测试视口,不覆盖自动尺寸;最小 360×360pt |
| KYMO_XPC_AUDIT=1 | 运行请求重复 / 并发完成、超时及取消检查后退出 | | KYMO_XPC_AUDIT=1 | 运行请求重复 / 并发完成、超时及取消检查后退出 |
截图来自本应用 contentView,不采集桌面。生命周期驱动不证明菜单栏鼠标或 AX 事件已投递。tools/ 中 GPU 能力、负载和驱动调查程序不参与产品构建,也不代表已实现功能;使用前阅读对应入口。 截图来自本应用 contentView,不采集桌面。生命周期驱动不证明菜单栏鼠标或 AX 事件已投递。tools/ 中 GPU 能力、负载和驱动调查程序不参与产品构建,也不代表已实现功能;使用前阅读对应入口。
+10 -4
View File
@@ -1,14 +1,20 @@
# Kymo 免费测试包 # Kymo 免费测试包
当前版本为 **1.2(构建 14)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。 当前版本为 **1.5(构建 17)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。
## 构建与校验 ## 构建与校验
```bash ```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 分发身份,不上传、不公证、不修改系统安全策略。 工程最低 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 放行,也不代表跨机器安装已验收。 接收方需核对来源、校验值和本机安全策略,再按 [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 收起面板。
+22 -8
View File
@@ -4,6 +4,8 @@
趋势图跳过无值节点,按真实时间连接前后有效点;有效 0 仍绘制,暂停 / 休眠等显式断点及真实采样空档仍断线。连接只影响曲线外观:缺失时刻悬浮读数为 `--`,原历史不补值。 趋势图跳过无值节点,按真实时间连接前后有效点;有效 0 仍绘制,暂停 / 休眠等显式断点及真实采样空档仍断线。连接只影响曲线外观:缺失时刻悬浮读数为 `--`,原历史不补值。
CPU / GPU 的零值与 100% 分别映射到卡片底边和顶边,内存卡片顶边为物理总量。存储、网络及无电池整机功率曲线绘在文字下方。CPU 自下而上堆叠系统态 / 用户态,内存堆叠应用 / 联动 / 压缩,GPU 总利用率、Renderer、Tiler 分别绘制,阶段可能重叠,不相加。电池主读数与详情下方的柱高表示电量百分比,详情显示正充负放的瓦数;每次采样在右侧加入一柱,柱距固定,悬浮显示实际时间。柱色来自该次供电状态。橙黄色睡眠柱取自系统睡眠、唤醒通知,柱高沿用入睡前一笔电量,缺少该读数时用短柱标记,悬浮显示起止时间,普通缺测留白;存储 / 网络以自顶向下 60% 高度为零轴,读取 / 上传向上、写入 / 下载向下;两侧同样使用 30% 绘图区高度振幅及共享自动速率尺度,原始值和提示均保持正速率。不显示常驻数值坐标轴、网格或图例。静态淡色面积在匹配的累计上下边界间按真实连续段闭合,不跨暂停或长空档;单点只显示真实点,必要分量缺失不构造部分总量。悬浮不会替换上方实时主数值。
## 数据来源 ## 数据来源
| 指标 | 实现与来源 | 口径与边界 | | 指标 | 实现与来源 | 口径与边界 |
@@ -18,7 +20,8 @@
| 存储容量 | `DiskMonitor`,URL volume resource values | 主卡片为主目录所在卷;卷列表仅本地且非隐藏挂载卷。APFS 卷共享容器空间,不应直接累加 | | 存储容量 | `DiskMonitor`,URL volume resource values | 主卡片为主目录所在卷;卷列表仅本地且非隐藏挂载卷。APFS 卷共享容器空间,不应直接累加 |
| 存储 IO | `DiskIOMonitor`,IOBlockStorageDriver 累计字节 | 物理块设备读写速率,非主卷文件 IO;设备集合变化、计数回退、首次读取均重建基线 | | 存储 IO | `DiskIOMonitor`,IOBlockStorageDriver 累计字节 | 物理块设备读写速率,非主卷文件 IO;设备集合变化、计数回退、首次读取均重建基线 |
| SMART | `DiskHealthMonitor` → XPC → `diskutil info -plist` | 主目录所在卷关联报告中的寿命和通电时间;剩余寿命 = 100 − PERCENTAGE_USED(下限 0),通电小时要求高位为 0,多物理存储拒绝合并;不代表所有卷或磁盘 | | 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` | 使用系统报告的最大容量百分比,不用当前充电容量推算 | | 电池健康 | `SystemBatteryHealthMonitor`,`system_profiler SPPowerDataType -json` | 使用系统报告的最大容量百分比,不用当前充电容量推算 |
| 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线;计数缓冲在采样器内复用,容量不足时扩容,仅解析本轮实际返回字节;本地地址保持系统 numeric formatter(含 scope),每轮共用地址缓冲、每接口最终排序一次 | | 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线;计数缓冲在采样器内复用,容量不足时扩容,仅解析本轮实际返回字节;本地地址保持系统 numeric formatter(含 scope),每轮共用地址缓冲、每接口最终排序一次 |
| 网络路径 | `NetworkPathObserver`,NWPathMonitor | 可用 / 不可用 / 需连接;代码取 `availableInterfaces.first` 作为主接口候选,并非独立解析系统默认路由;路径可用不保证公网可达 | | 网络路径 | `NetworkPathObserver`,NWPathMonitor | 可用 / 不可用 / 需连接;代码取 `availableInterfaces.first` 作为主接口候选,并非独立解析系统默认路由;路径可用不保证公网可达 |
@@ -27,27 +30,36 @@
内存容量使用 GiB / MiB 等二进制单位,存储容量与常规字节 / 速率采用十进制格式;进程 footprint 表列按活动监视器习惯,以 1,048,576 字节折算并标为 MB。 内存容量使用 GiB / MiB 等二进制单位,存储容量与常规字节 / 速率采用十进制格式;进程 footprint 表列按活动监视器习惯,以 1,048,576 字节折算并标为 MB。
## 内存堆叠核对
当前实现保持应用 + 联动 + 压缩 = 已用,已用 + 可用 = 物理总量。应用分类来自 internal − purgeable,包含应用与系统进程的匿名内存,并非仅用户打开的 GUI 应用;联动包含内核 / 驱动等常驻内存;压缩使用 compressor_page_count 的实际物理页,而非压缩前大小。[Apple XNU 字段定义](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/mach/vm_statistics.h)及[统计实现](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/host.c)可对照采样字段。
可回收文件缓存包含在可用部分,Swap 是磁盘交换空间,不另加到物理内存已用堆叠。Apple 活动监视器同样区分 App / Wired / Compressed、Cached Files 与 Swap Used,见[官方口径说明](https://support.apple.com/en-uz/guide/activity-monitor/actmntr1004/10.14/mac/15.0)。背景三层已承担分布表达,因此移除额外容量进度条;前景仍保留分类、可用量、压力及其提示。不同时间点和系统版本不保证与活动监视器逐字节相同。
## 需要明确区分的指标 ## 需要明确区分的指标
- GPU Renderer / Tiler 是活动阶段指标,可能重叠,不能相加成为总占用。GPU 核心数不代表逐核计数;目前没有独立逐核 GPU 占用。 - GPU Renderer / Tiler 是活动阶段指标,可能重叠,不能相加成为总占用。GPU 核心数不代表逐核计数;目前没有独立逐核 GPU 占用。
- 网络“全部”仅汇总 active 且名称以 `en` 开头的接口,避免物理链路与 `utun` 双计。接口选择仍可查看其他活动接口;这个规则不等于所有设备和隧道的通用流量归因。 - 网络“全部”仅汇总 active 且名称以 `en` 开头的接口,避免物理链路与 `utun` 双计。接口选择仍可查看其他活动接口;这个规则不等于所有设备和隧道的通用流量归因。
- 进程 CPU 以一个逻辑核满载为 100%,多线程可超过 100%,不能直接与整机 CPU 百分比比较。首次进程采样没有差分值;功率列使用独立 CPU 能量计数差分,不能将进程 CPU 百分比当成耗电。 - 进程 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 能量 | 复用同轮进程候选,成功后至少 5 秒再读(默认 2 秒轮次下通常约 6 秒);失败 30–600 秒退避,明确不支持后 600 秒;最多一批在途 |
| CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 | | CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 |
| 无电池整机功率 | 仅可见且请求详情时按面板采样间隔读取;2 秒超时、失败独立退避 60–600 秒,历史保留缺失 |
| 卷列表 | 读取结束后至少 30 秒 | | 卷列表 | 读取结束后至少 30 秒 |
| SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 | | SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 |
| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;概览可见时按缓存到期持续刷新,路由键变化、暂停或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 | | 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;面板可见时按缓存到期持续刷新,路由键变化、暂停或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 |
| 趋势 | 全局与每接口最多各 60 点,仅内存保存 | | 趋势 | 全局与每接口最多各 60 点,仅内存保存 |
传感器、卷与慢报告只在请求概览慢指标的可见采样轮次检查是否到期;后台趋势不启动这些慢读取。快照中的慢指标可能来自之前的缓存。暂停停止发布,不保证取消已进入系统调用的工作。 菜单栏按 CPU、GPU、内存、磁盘、网络顺序展示。前四项的等高竖条以 0–100% 从底部填充,右侧显示名称与百分比。CPU / GPU 为总利用率,内存为已用 / 总量,磁盘为主目录所在卷的(总容量 − 可用空间)/ 总容量。网络上行在首行(↑),下行在次行(↓),分别复用当前快照的活动 en 接口汇总,每个方向以十进制 B/s 自动换算单位。缺测的读数独立显示 --。
传感器、卷与慢报告只在请求慢指标的可见采样轮次检查是否到期;后台趋势不启动这些慢读取。快照中的慢指标可能来自之前的缓存。暂停停止发布,不保证取消已进入系统调用的工作。
常规周期允许系统在配置周期 10% 的容差内合并唤醒,前台最多 200ms、后台最多 1 秒;不是严格实时截止。差分的时间分母始终取实际经过的单调时间,历史保留真实采样日期,配置周期不被改写。 常规周期允许系统在配置周期 10% 的容差内合并唤醒,前台最多 200ms、后台最多 1 秒;不是严格实时截止。差分的时间分母始终取实际经过的单调时间,历史保留真实采样日期,配置周期不被改写。
@@ -63,7 +75,7 @@ AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失
该口径是系统归属的 CPU 能量,参考 [Apple XNU task.c](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/task.c) 和 [recount.c](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/recount.c);开源主线不保证与目标系统二进制完全一致。它不含完整 GPU / 屏幕 / 网络 / 整机功耗,不聚合应用子进程,不等于活动监视器 Energy Impact。进程表以 W/mW 显示 CPU 平均功率,列头可切换升降序;缺失值显示 -- 并始终排末。悬浮功率单元格可查看实际统计窗口。 该口径是系统归属的 CPU 能量,参考 [Apple XNU task.c](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/task.c) 和 [recount.c](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/recount.c);开源主线不保证与目标系统二进制完全一致。它不含完整 GPU / 屏幕 / 网络 / 整机功耗,不聚合应用子进程,不等于活动监视器 Energy Impact。进程表以 W/mW 显示 CPU 平均功率,列头可切换升降序;缺失值显示 -- 并始终排末。悬浮功率单元格可查看实际统计窗口。
按全部可测候选的有效能量差分排名。权限受限、进程退出和截止会降低覆盖率;进程页显示已形成差分数 / 枚举总数,首帧等待,失败或不支持明确显示状态。零增量只有连续两帧有效时才代表 0 W。身份变化、计数回退、无效时间和超过允许窗口均不形成排名。超大进程集合在总截止下可能只覆盖部分批次,尚未验证极端规模下的公平轮转。 按全部可测候选的有效能量差分排名。权限受限、进程退出和截止会降低覆盖率;进程标题提示显示已形成差分数 / 枚举总数,首帧等待,失败或不支持明确显示状态。零增量只有连续两帧有效时才代表 0 W。身份变化、计数回退、无效时间和超过允许窗口均不形成排名。超大进程集合在总截止下可能只覆盖部分批次,尚未验证极端规模下的公平轮转。
进程 CPU 的 `pti_total_user` / `pti_total_system` 是 task absolute CPU 时间:累计值先做整数差分,经本机 `mach_timebase_info` 转为纳秒,再除以单调时钟间隔;单逻辑核满载为 100%,多线程可超过 100%。不按整机核心数再平均。真实 CPU 能量采用独立 nJ 计数差分。 进程 CPU 的 `pti_total_user` / `pti_total_system` 是 task absolute CPU 时间:累计值先做整数差分,经本机 `mach_timebase_info` 转为纳秒,再除以单调时钟间隔;单逻辑核满载为 100%,多线程可超过 100%。不按整机核心数再平均。真实 CPU 能量采用独立 nJ 计数差分。
@@ -75,6 +87,8 @@ AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失
公网 IP 网络会话使用 ephemeral 配置并关闭 URLCache、Cookie 与凭据存储;已有 600 秒 / 30 秒缓存是进程内数据,不写磁盘。签名沙盒网络检查直接调用生产服务,核对重复 / 新路由 HTTPS 查询后持久网络目录未新增或变更文件。 公网 IP 网络会话使用 ephemeral 配置并关闭 URLCache、Cookie 与凭据存储;已有 600 秒 / 30 秒缓存是进程内数据,不写磁盘。签名沙盒网络检查直接调用生产服务,核对重复 / 新路由 HTTPS 查询后持久网络目录未新增或变更文件。
## 页面采样需求 ## 单页采样需求
概览只采集系统资源,不进行进程枚举、footprint 或进程 CPU 能量读取。进入进程页才启用这些读取并重新建立进程差分基线;功率至少需要两次有效读取,现有成功间隔下限 5 秒不变。离开即清除已发布进程 / 能量并拒绝旧代次回写。进程页保留基础资源采样以延续趋势,但不发起概览慢传感器 / 报告或公网 IP 请求;已开始的慢读取可自行结束。基础采样间隔、后台趋势开关、暂停与睡眠规则保持独立。 App 同时请求进程与慢指标,面板实际可见且未暂停 / 睡眠时执行。进程、footprint 与 CPU 能量读取保留单在途约束及独立发布;功率至少需要两次有效读取,成功间隔下限 5 秒不变。隐藏时清除进程 / 能量发布并拒绝旧代次回写;后台趋势只延续基础系统采样,不启动上述详情。基础采样间隔、后台开关、暂停与睡眠规则保持独立。
风扇图标沿用视觉速度档位:正值 <2000 / <4000 / <6000 / 其余 RPM 对应 90 / 180 / 300 / 450°/s,不模拟物理 RPM。零、缺失 / 无效、系统减弱动态效果、暂停、不可见、睡眠或卸载时停止;实际转速文本口径不变。
+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)
+41
View File
@@ -0,0 +1,41 @@
# 卡片文字可读性调整
> 后续用户反馈:文字底板削弱图表可读性,已按要求撤销底板,仅保留字号 / 行距 / 换行调整。下文前一轮实施与验证为历史记录,当前以设计规范和代码为准。
## 目标与范围
本轮仅实施用户选择的前两项:文字区底板、辅助字号 / 行距与标签数值层级。涉及 UI/Components 的卡片 / 风扇、Features/MenuBar 六卡详情、现有组件检查和 docs。沿用现有卡片尺寸、三行布局、图表尺度 / 配色 / 透明度、采样与进程表,不新增依赖。
## 实施方案
- 前景标题、主值和详情组成紧凑内容块,使用 PanelCard 同色 88% 不透明底板、8pt 圆角,向文字外延 4pt;底板不包含卡片底部 Spacer、不拦截交互。图表仍覆盖整卡并使用原坐标,底板之外的图层保持原样;无模糊、渐变或额外动画。
- 常规辅助信息提升至 10pt,数值 primary / medium、标签 secondary,行高 16pt;标题行升至 16pt,主值 28 / 网络 16pt 保持。核心紧凑短标签升为 9pt、12pt 高;主值单位 / 状态 / 压力标签按空间提升至 10pt。长分类、速率和硬件说明优先按信息组换行,保留完整提示,不靠缩至原 8pt 排版。
- 默认资源卡片仍为 205⅓×176pt;CPU 逐核、风扇与现有多行结构预算延用,详情在剩余高度内排列。保留所有指标、接口 / 卷入口及复制。
## 步骤与验证
- [x] 实现底板与六卡字体、行高和必要换行。
- [x] Debug 构建;复用现有卡片 / 核心 / 风扇 / 布局检查。检查底板只覆盖前景、整卡图区不变、三语与窄宽度详情不出界。
- [x] 隔离真实面板检查浅深色、入口和暂停 / 恢复,只截取本应用内容,保留用户安装副本。
- [x] 同步设计 / 架构 / 测试文档,生成新 dist,清理本轮临时副本和构建并提交,不推送。
## 风险与边界
文字底板会压淡文字下方的曲线,完整背景坐标与原始数据不变。长英文或极大数值可能增加详情行,使用现有 176pt 高度内的留白并实际检查。主观观感、多屏和长期能耗不以短时验证替代。
## 本轮结果(2026-11-15)
- Debug 构建通过(隔离副本关闭调试 dylib 拆分,未改变沙盒 / 权限);仅有无 AppIntents 依赖的元数据提示。
- ResourceCardChecks、CPUCoreGridChecks、FanRotorChecks、PanelLayoutChecks 通过;161 键的三语 / 格式参数检查通过。新增前景 / 留白像素对比确认只有文字区压淡图表,六卡仍为整卡绘图区;生产内存 / 存储详情在 190 / 205⅓ / 400pt、浅深色和三语下保持在 176pt 卡片边界内。
- 隔离实际应用核对深色简体及浅色英文:六个原生绘图区均约 205⅓×176pt;前景有局部同色底板,放大的辅助数值可见,英文内存分类自动分为两行。已实测暂停 / 恢复、卷详情打开 / 关闭及接口菜单打开 / 取消;底板未拦截这些控件。截图仅来自本应用内容。
- Release 生成 dist/readability-v1;原始 / 解压包签名、Hardened Runtime、权限及压缩包内容通过,SHA-256 单独复核。版本仍为 1.2 (14),arm64 / macOS 27.0 起,ad-hoc 未公证。
- 本轮只实施前两项;图表全局配色 / 明度、投影、采样和进程表保持现有实现。真实鼠标悬浮、主观观感、多屏与长期能耗未由本轮检查替代。
- 清理本轮临时构建、脚本、截图、日志、隔离副本与容器;保留用户原安装进程。
## 后续修正:撤销文字底板
- 用户要求回退底板、保留字体大小。删除前景块的 88% 底板及其透明度参数;保留辅助字号 / 行高、数值层级和换行,卡片尺寸、图表坐标与原绘制样式保持。
- 更新生产卡片像素检查:同一曲线填充在空白详情区与底部留白的色差应一致,防止再次局部压淡。继续核对三语、大字号详情与固定尺寸边界。
- Debug / Release 构建通过;ResourceCardChecks 在浅深色、三语及 190 / 205⅓ / 400pt 下通过,包括文字区与底部填充色差一致、大字号详情不出界;目录与签名权限检查通过。
- 本轮隔离真实深色面板已截图核对:六卡没有文字底板,曲线保持原色,放大的字号与行距仍在,原生绘图区均约 205⅓×176pt。本轮未重新投递鼠标交互。
- 生成 dist/font-only-v1,签名 / 权限 / ZIP 内容与 SHA-256 通过;保留用户已安装副本,清理本轮隔离副本、容器、截图与临时构建。
+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`。
+12
View File
@@ -0,0 +1,12 @@
# 资源卡片读数与趋势调整
目标是让文字与走势可以同时阅读、直观看出真实核心数量,并在没有内置电池时显示传感器的整机即时功率。旧面板以整卡高度绘图,每核四段,GPU 阶段只在提示中;旧版数值滚动曾在性能优化时移除。
1. Core / SMARTService:仅确认无内置电池且面板需要详情时请求固定只读 AppleSMC PSTR。成功按采样间隔更新,失败独立退避;未知/失败不当作无电池,功率缺失不填零。功率历史独立于电量与电池功率。不声称是插座测量。
2. MenuBar / UI / Resources:前景按实际内容高度排版,余下区域给曲线;保留双向速率、现有控件、历史断点与提示。一核一格以连续填充显示负载,GPU 渲染器 / 分块器常显,不相加。无电池切换功率卡与 W 趋势,三语一致。
3. UI:复用初版系统 numericText 动效;连续追加时对已有曲线图层短暂做水平变换,不设逐帧计时器。悬浮、断点和减弱动态效果时保持静态。
4. 验证构建、逐核/高核数换行、曲线滚动与悬浮、缺失值、XPC 实际读取、不同宽度三语布局以及真实面板。保留已运行的应用。当前机器为 MacBook Pro,不能代替 Mac mini 整机验收;跨机型传感器支持、长期功耗与动效手感须分别评估。
实施完成。Debug 构建及 10 项相关 Swift 检查通过。签名沙盒经本轮 XPC 在 M4 Pro 读到 PSTR 30.04 W;桌面功率、无传感器、未知/读取失败和有电池状态使用生产卡片输入分别验证,尚无 Mac mini 实机结果。三语、浅深色及 190 / 205⅓ / 400pt 布局下文字与图区不重叠。真实面板三次打开均挂载六图区、关闭卸载;默认布局中存储 / 网络图高分别为 56 / 48pt。数字滚动以原生宿主中间帧核对;曲线验证满窗滚动、悬浮取消与断点。主观手感和长期能耗未验收。
交互边界:定向 Esc 关闭测试面板已观察到。AX 命中卷入口位置时仅返回组;定向合成点击未观察到弹出窗口,屏幕点击因命中位置不能确认由测试窗口独占而跳过。卷详情弹出仍需在新版面板点击「本地卷」确认。
+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 标签下载地址。
+60
View File
@@ -0,0 +1,60 @@
# 堆叠背景与单页监控实施方案
## 背景与目标
按用户本轮要求:CPU / GPU / 内存改为堆叠图;逐核改为方块组成的竖向柱状进度;恢复风扇图标与历史速度档位;移除概览 / 进程分页,将进程表放在第三行,跨满整行并与资源卡片等高。
用户补充:**卡片整个高度就是图表 0–100% 的绘图区**。底边为 0,顶边为 100%,所有文字和控件位于背景图前景;不再划分底部独立图框。存储 / 网络仍是速率,卡片顶边代表当前速率尺度上限。
## 现状、模块与影响
当前卡片常规 205⅓×176pt,面板 648×448pt,48pt 图区仅位于底部;进程采样按页面需求启停。涉及 App 装配、Features/MenuBar 窗口 / 布局 / 六卡 / 进程、UI/Charts 和 UI/Components、Core 的需求调用方式、检查程序 / 工具及 docs。系统 API、XPC 协议、指标来源不变;Core 继续只接收数据需求布尔值,不引入 UI 类型。
## 设计与口径
- CPU:系统态为底层、用户态在上,二者相加为总占用;提示保留总量与原始分量,不能将累计边界误报为某一分量。
- 内存:应用、联动、压缩自下而上相加为已用量;整卡顶边对应物理内存总量,未填满部分为可用空间。
- GPU:用户已确认采用占用 + 空闲的百分比堆叠,保留 Renderer / Tiler 提示。两阶段可能重叠,不能伪装为可加和分量。
- 图层在同一时间轴上构建累计上下边界,面积闭合在上下边界之间;任一必要分量缺失时该时刻不构造部分总量。保留有效零、原有真实断点与空档规则;悬浮缺失点不补值。
- 每个 CPU 核心为独立竖柱,由四个 6×6 方块及 2pt 间距组成,下方先填充,最后一格按真实比例部分填充。核型分组横向排列;空间不足时换行并增加结构预算,不把核心数量当作利用率。
- 风扇恢复历史 cc38066 中映射:0 / 缺失 / 非有限 / 减弱动态效果停止;正值 <2000 RPM 为 90°/s,<4000 为 180°/s,<6000 为 300°/s,其余为 450°/s。这是视觉档位,不模拟物理转速。仅图标使用原生循环旋转,数值与图表继续直接更新;隐藏、遮挡、暂停、睡眠或卸载时停转。
- 常规前两行为原六卡,第三行进程表跨满内容区;所有行使用资源结构预算中的最大高度,默认 176pt。顶部移除页签;常规面板 648×630pt,小屏统一滚动,进程表自身仍可滚动和排序 / 搜索 / 复制。
- App 同时请求 processes / slowMetrics;可见性、暂停与睡眠仍由 MetricsStore 统一控制。进程独立发布,避免每次进程更新触发六卡重绘。
## 实施阶段
1. 编写本方案,确认 GPU 口径和历史风扇映射。
2. 实现累计边界、原生堆叠面积 / 悬浮与全卡图区。
3. 实现方块竖柱、风扇原生旋转及生命周期控制。
4. 移除页面状态与装配回调,合并布局 / 采样需求,更新检查与文档。
5. 构建和自动检查、实际单页面板验证、打包到独立 dist 目录、清理测试产物并提交。
## 验证计划
- 数学检查:分量相加、上下边界、GPU 占用 + 空闲、缺失 / 负值 / 非有限 / 溢出、真实零及原时间戳。
- 原生图层像素:堆叠面积不重叠或填过断点,标记落在累计边界,提示保留原始分量,悬浮不重建路径;全卡图区与前景几何。
- 逐核布局 / 填充边界;风扇速度档位、切档连续性、零 / 缺失 / 减弱动态效果、暂停 / 隐藏 / 卸载停止动画。
- 单页同时展示资源和进程,第三行等高、屏幕限制 / 小屏滚动;同时需求、隐藏 / 暂停 / 睡眠和旧结果代次拒绝。
- Debug / Release 构建及相关独立检查;真实面板截图限本应用,操作表格与控件;保留用户已运行副本,清理本轮应用和临时数据。
## 风险与兼容性
全卡背景可能穿过文字,采用低透明度面积及前景文字,实测浅深色与三语。GPU 的 100% 为占用与空闲总和,不等于阶段之和。合并后可见时增加进程读取,沿用有界单在途、缓存和截止,不增加后台默认采样。风扇是用户要求恢复的唯一持续动效,其他动效约束保持;短时检查不证明长期能耗或真实多屏表现。
## 进度
- [x] GPU 口径由用户确认;历史风扇档位已从源码历史核实。
- [x] 堆叠 / 全卡图区。
- [x] 方块竖柱 / 风扇。
- [x] 单页装配 / 需求 / 文档。
- [x] 构建、检查、实际验证与打包。
## 本轮验证结果(2026-11-15)
- Debug 构建通过;仅有未使用 AppIntents 的元数据提取提示。隔离 Debug 副本最初因调试 dylib 的 ad-hoc 库验证失败而退出;改用 ENABLE_DEBUG_DYLIB=NO 构建后正常运行,应用沙盒与权限配置保持不变。
- 15 项独立检查通过:StackedSeries、CPUCoreGrid、Fan、PanelLayout、DetailDemand、ResourceCard、NativeMetricDrawing、FanRotor、PanelWindow、NativeProcessTable、BackgroundTrend、PanelCurve、Memory、GPUStatistics、ProcessSection;目录 160 键的三语与参数检查通过。
- 实际隔离应用:浅色简体中文 / 深色英文均同时显示六卡与进程;六个原生绘图区实际均为整卡 176pt 高,宽度约 205⅓pt。搜索 kymo、内存排序、暂停 / 恢复均通过 AX 状态核对。发现英文两行范围说明压缩表格,已修正扩展约束;新增生产 ProcessSection 检查覆盖 176pt、三语 / 浅深色、340 / 628pt 宽下表格占满剩余高度,修正后真实截图等高。
- 繁体 360×500pt 窄屏可整体滚至底部进程表,外层滚动值到 1;表格独立滚动值变化且保留外层位置。锁屏曾暂停后续操作,用户解锁后完成上述验证。
- Release 打包到 dist/stacked-dashboard-v1;原始与解压包签名、Hardened Runtime、沙盒 / 网络权限、压缩包内容及 SHA-256 校验通过。版本 1.2 (14),arm64,macOS 27.0 起;本地 ad-hoc,未公证。
- 验证边界:原生组件检查已核对累计悬浮标记、缓存与缺失值;实际 AX 点击背景不能证明真实鼠标悬浮已投递。真实鼠标提示、主观动效手感、多屏 / 刘海屏与长期能耗仍由相应场景验收。未宣称完成全量回归或长期性能验证。
- 清理本轮隔离副本、截图、脚本、日志、容器及临时构建,保留用户预先运行的 /Applications/kymo.app。
+20 -12
View File
@@ -25,37 +25,45 @@ python3 tools/check.py --list
| 检查 | 覆盖范围 | | 检查 | 覆盖范围 |
| --- | --- | | --- | --- |
| SamplingChecks、SamplingIntervalChecks、DetailDemandChecks | 差分首帧与重置、间隔与旧偏好、暂停 / 恢复、隐藏零采样、分页需求、独立进程发布与需求代次 | | SamplingChecks、SamplingIntervalChecks、DetailDemandChecks | 差分首帧与重置、间隔与旧偏好、暂停 / 恢复、隐藏零采样、同时详情需求与需求撤回、独立进程发布与需求代次、长前台周期的电源切换即时重采与复读 |
| StackedSeriesChecks | CPU / 内存 / GPU 累计上下边界、分量缺失 / 无效 / 负值 / 溢出拒绝、零值、GPU 总和与共同断点 |
| BackgroundTrendChecks、PanelCurveChecks | 真实时间域、周期切换、短暂隐藏连续性、60 点有界历史、缺失与非有限点、有效 0、显式停采及真实空档 | | BackgroundTrendChecks、PanelCurveChecks | 真实时间域、周期切换、短暂隐藏连续性、60 点有界历史、缺失与非有限点、有效 0、显式停采及真实空档 |
| UnifiedPanelChecks、StageCChecks | 本机采样边界、网络汇总与接口历史、电池估时及系统报告解析 | | UnifiedPanelChecks、StageCChecks | 本机采样边界、网络汇总与接口历史、电池估时及系统报告解析 |
| BatteryPowerChecks | 65 W 适配器实际充入 6 W、插电补放、仅电池、单边缺测与反推、带符号的寄存器编码、独立电池读数、旧遥测与唤醒失效、拔电时电源状态与缓存读数先后到达 |
| MachPortChecks | CPU / 内存各 1,000 轮后 host 发送权引用无增长 | | MachPortChecks | CPU / 内存各 1,000 轮后 host 发送权引用无增长 |
| MemoryChecks、MemoryHeaderChecks | 分类守恒、二进制容量、压力 / 缓存 / Swap 标题及三语缺失 / 零值 | | MemoryChecks、MemoryHeaderChecks | 含压缩 / 缓存 / Swap 的分类守恒、二进制容量、压力 / 缓存 / Swap 标题及三语缺失 / 零值 |
| GPUStatisticsChecks、CPUTemperatureChecks、FanChecks、DiskHealthChecks | 当前 GPU 利用率与历史、温度范围与解码、风扇零值 / 无效值、SMART 边界与多物理存储拒绝合并 | | GPUStatisticsChecks、CPUTemperatureChecks、FanChecks、DiskHealthChecks | 当前 GPU 利用率与历史、温度范围与解码、风扇零值 / 无效值、历史速度边界与切档相位、SMART 边界与多物理存储拒绝合并 |
| SensorScheduleChecks、BoundedProcessChecks | 各能力独立退避;真实受控子进程输出上限、超时、取消、异常退出与回收 | | SensorScheduleChecks、BoundedProcessChecks | 各能力独立退避;真实受控子进程输出上限、超时、取消、异常退出与回收 |
| ProcessEnergyChecks、ProcessEnergyReaderChecks、ProcessCPULiveChecks | UInt64 能量差分、身份 / UID / 缺失 / 回退 / 时间边界、受控本机能量增长和 Mach 时基 CPU 差分 | | ProcessEnergyChecks、ProcessEnergyReaderChecks、ProcessCPULiveChecks | UInt64 能量差分、身份 / UID / 缺失 / 回退 / 时间边界、受控本机能量增长和 Mach 时基 CPU 差分 |
| ProcessSelectionChecks、PanelLayoutChecks、CPUCoreGridChecks | 退出与 PID 复用、搜索 / 排序、640pt / 窄屏预算、核心行数与边界 | | ProcessSelectionChecks、PanelLayoutChecks、CPUCoreGridChecks | 退出与 PID 复用、搜索 / 排序、648pt 三列资源及第三行进程 / 两列及单列窄屏预算、全行等高与滚动边界、逐核单元数量、分组和换行边界 |
| PublicIPAddressChecks | 隔离 URLProtocol、600 秒成功 / 30 秒失败缓存、单调时间、持续刷新及取消,不发送真实请求 | | PublicIPAddressChecks | 隔离 URLProtocol、600 秒成功 / 30 秒失败缓存、单调时间、持续刷新及取消,不发送真实请求 |
| NetworkAddressChecks、ProcessIconCacheChecks | 沙盒下地址格式 / 速率;图标位图、尺寸、共享、过期、LRU 与严格预算 | | NetworkAddressChecks、ProcessIconCacheChecks | 沙盒下地址格式 / 速率;图标位图、尺寸、共享、过期、LRU 与严格预算 |
| AppearancePreferencesChecks、LocalizationChecks、PresentationChecks | 外观与偏好隔离、语言持久化、编译资源、窗口显式 / 系统外观切换 | | AppearancePreferencesChecks、LocalizationChecks、PresentationChecks | 外观与偏好隔离、语言持久化、编译资源、窗口显式 / 系统外观切换 |
| CodeIdentityChecks、PanelAssetChecks、KeepAwakeChecks | 签名身份拒绝边界、编译颜色及对比度、真实 IOPM 断言开关与释放 | | CodeIdentityChecks、PanelAssetChecks、KeepAwakeChecks | 签名身份拒绝边界、编译颜色及对比度、真实 IOPM 断言开关与释放 |
| NativeMetricDrawingChecks(--gui) | 实际曲线像素、直接稳定更新、缺失点接续与真实断点、悬浮缓存、无动画 / 渐变 / 遮罩、卸载 | | NativeMetricDrawingChecks(--gui) | 实际曲线 / 堆叠色带、带符号瓦数零线与两端悬浮点、双向速率面积和零轴、方向 / 悬浮 / 断点及累计边界定位、单点无虚构填充、隐藏序列隔离、缺失点接续与真实断点、悬浮缓存、滚动时间域变换、悬浮停止动画、断点、无渐变 / 遮罩、卸载 |
| NativeContentHostChecks(--gui) | 数字更新、父环境继承、挂载身份、有限尺寸和卸载 | | FanRotorChecks(--gui) | 独立图层多角度 / 多尺寸旋转中心不漂移,原生旋转动画时长、无效 / 零 / 缺失、非活动 / 减弱动态效果及卸载停转 |
| NativeProcessTableChecks(--gui) | 原生虚拟表格、原地更新、身份选择、排序 / 列序 / 复制 / 三语列头、合成 Esc 投递 | | 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 生命周期 | | TabPickerChecks、LanguageScopeChecks、SettingsWindowChecks(--gui) | 原生页签选择与键盘、已挂载语言即时切换、设置焦点 / 最小化恢复 / Dock 生命周期 |
| PanelWindowChecks(--gui) | 真实 NSPanel 居中、尺寸反馈、固定、遮挡可见性、显式关闭重开默认概览和退出复位 | | PanelWindowChecks(--gui) | 真实 NSPanel 居中、尺寸反馈、固定、遮挡可见性、显式关闭重开和退出复位 |
| ReleaseServiceChecks(--services) | 临时 hardened sandbox 主程序调用本轮实际嵌入服务,核对同 UID footprint / 能量与传感器 | | ReleaseServiceChecks(--services) | 临时 hardened sandbox 主程序调用本轮实际嵌入服务,核对同 UID footprint / 能量与传感器,并输出本机 B0AP 带符号瓦数或不可用状态 |
| SandboxNetworkChecks(--network) | 使用实际主应用 entitlement 访问产品 HTTPS 端点,核对持久网络目录无新增或变更文件 | | SandboxNetworkChecks(--network) | 使用实际主应用 entitlement 访问产品 HTTPS 端点,核对持久网络目录无新增或变更文件 |
LocalizationCatalogChecks.py 检查全部保留键的三语完整性与格式参数,不替代翻译语义和实际排版。服务 / 网络不可达也会使对应检查失败。 LocalizationCatalogChecks.py 检查全部词条的三语完整性与格式参数。统一检查入口还逐项比对构建包内四份字符串表与源译文;翻译语义和实际排版需另行核对。服务 / 网络不可达也会使对应检查失败。
## 实际应用验收 ## 实际应用验收
自动检查可验证模型、原生组件和窗口策略,不能代替正式应用事件。代码改动涉及相应路径时,应在本机完成: 自动检查可验证模型、原生组件和窗口策略,不能代替正式应用事件。代码改动涉及相应路径时,应在本机完成:
- 在「设置 → 菜单栏」逐项勾选与取消,核对预览与真实状态项的顺序、数值及宽度。空选保留品牌入口,重启保留选项。系统菜单栏宽度不足时检查重新打开应用的设置入口。
- 菜单栏左键打开 / 收起、右键菜单、设置入口与退出。 - 菜单栏左键打开 / 收起、右键菜单、设置入口与退出。
- 概览六张卡片、双列 / 窄屏单列和滚动,进程分页与关闭重开默认概览。 - 六张资源卡片与等高通栏进程同页,三列资源 / 窄屏两列及单列和整体滚动,关闭重开。
- 固定 / 取消固定、外部点击、Esc 分层处理,图表悬浮、复制、缺失值。 - 固定 / 取消固定、外部点击、Esc 分层处理,图表悬浮、复制、缺失值。
- 底栏刷新间隔、后台趋势、暂停 / 恢复;概览停止进程读取,进程页停止概览慢读取,基础趋势延续。 - 底栏刷新间隔、后台趋势、暂停 / 恢复;同时详情需求,隐藏 / 暂停停止进程及慢读取,显式后台仅延续基础趋势。
- 实际签名沙盒应用的 GPU、温度、风扇、SMART、电池、网络、footprint 和 CPU 功率来源 / 单位 / 不可用状态。 - 实际签名沙盒应用的 GPU、温度、风扇、SMART、电池、网络、footprint 和 CPU 功率来源 / 单位 / 不可用状态。
- 三语即时切换、浅深色与系统跟随、重启持久化、设置焦点与 Dock 显隐。 - 三语即时切换、浅深色与系统跟随、重启持久化、设置焦点与 Dock 显隐。
+69
View File
@@ -0,0 +1,69 @@
# Kymo 界面设计规范 v1.6
2026-11-15 根据用户确认的[背景趋势设计稿](designs/card-background-trends-v1/README.md)制定,并按后续反馈将首版卡片宽、高缩至 2/3,恢复图稿中的紧凑左对齐排布;容量与占用趋势铺满卡片,速率趋势位于文字下方,保留分量曲线和第三行进程区。本文为实现与验收标准,效果图中的示例数据、品牌重绘与核心格子不作为数据或素材依据。
## 适用范围与原则
单页面板包括三列两行资源卡片及第三行通栏进程表,顶部移除概览 / 进程页签,保留工具栏与公共底栏。Settings 与进程表保留原有交互;共用外观、语言与控件语义。依赖方向继续为 Features → UI → Core。
按确认图稿保持数值层级、左对齐信息行与曲线背景,并在用户指定尺寸内实现。所有缺失值显示 -- 或既有明确状态,不推导不存在的指标、不以装饰波形代替历史。数值随采样直接刷新。曲线随采样水平移动;遵循系统减弱动态效果,不使用背景模糊。
## 布局与尺寸(pt)
| 项目 | 标准 |
| --- | --- |
| 面板 | 最大宽 648,最大高 800;屏幕边缘至少 16;常规高 630 |
| 网格 | ≥620 宽为三列;430–619 为两列;<430 为单列;不足高时仅中间区域滚动 |
| 顺序 | CPU / GPU / 内存 / 电池 / 存储 / 网络,按行阅读;进程位于资源之后,所有资源行与进程行等高 |
| 面板内边距 / 卡片间距 | 10 / 6;常规卡片宽 205⅓ |
| 卡片 | 基础高 176,圆角 16,前景内边距 10 |
| 动态高度 | CPU 核型横向分组,逐核单元一行基础预算,超出每行增加 15;GPU 超过一行风扇后每行增加 18;所有行采用最大结构预算,不裁掉硬件数据 |
| 标题 / 主值区域 | 标题行 16,主值行 34,区域间距 4 |
| 背景趋势 | CPU / GPU / 电量从卡底 0 到卡顶 100%,内存从卡底 0 到卡顶物理总量。存储和网络使用详情下方独立图区,零轴位于该区高度的 60% |
| 逐核格子 | 每核一个 7×11 单元,从底部按真实比例填充;核型短标签与数量在上方 |
| 顶栏 / 底栏 | 32 / 26。标题右上显示版本胶囊,开机时间在底栏最左,间隔输入框宽 50 |
## 字体、颜色与层级
- 使用系统字体、现有品牌图像和 SF Symbols;数值使用等宽数字。
- 卡片标题 11 semibold,主数值 28 semibold,单位 12 medium;双指标网络主数值 16、单位 10,避免挤压。必要时主值最多缩至 75%,全文保留为辅助说明。
- 主要辅助信息 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 和内存的文字叠在整卡趋势上。电池、存储、网络和无电池整机功率卡优先安排详情高度,图接在下方。保留放大后的辅助字号、行距和按组换行,不使用模糊或渐变。
- 卡片采用 PanelCard、面板采用 PanelBackground 的浅深色资源。边框为 primary 浅色 2.5% / 深色 6%;静态轻阴影半径 4、纵偏移 1,不给文字或曲线单独加阴影。
## 曲线与悬浮
- 不显示常驻图例、数值坐标轴、网格、起止时间与独立图框。背景曲线线宽 1.4,填充为同色静态实色透明度:浅色 12%、深色 16%;不使用渐变层或遮罩层,连续追加时仅移动已有曲线图层。
- CPU 自下而上堆叠系统态 / 用户态;内存堆叠应用 / 联动 / 压缩,顶边为物理总量、空余为可用空间;GPU 总利用率、Renderer、Tiler 共用百分比轴但各自绘制,只有总利用率填充面积。每根电池柱都是独立的圆角进度条,实色从底部向上表示电量,余量使用同色半透明轨道,柱间留空。绿柱和电池图标表示电池供电或放电,蓝柱配插头或闪电分别表示外接供电或充电。共同供电时显示蓝色插头与绿色电池,两路瓦数分别列出,实色柱段按适配器和电池的供电占比分色。未知来源为灰色。电量柱保持固定间距,最新值从右缘进入。睡眠区间使用等距橙黄色柱和月亮,柱高沿用入睡前一笔电量,缺少该读数时用短柱标记,普通停采留白。窄段省略图标,悬浮可读出对应状态。存储和网络采用上下双向曲线:自顶向下 60% 为零轴(细线),向上读取 / 上传、向下写入 / 下载,两侧各有绘图区高度 30% 的振幅,共用自动速率尺度,峰值不触及卡片顶边。
- 百分比固定 0–100%;内存固定当前物理总量;速率保留既有自动范围及延迟缩小策略,不为视觉任意改变振幅。
- 时间使用真实采样日期;有效 0 保留,nil / 非有限数值不补值。沿用既有缺失节点接续与显式断点 / 长空档策略。堆叠缺少任一必要分量时不构造部分总量;面积在匹配上下边界之间按每个连续段分别闭合,不能填过暂停空档。
- 单点历史仅显示真实点,不绘制虚构面积。全缺失无曲线和填充。
- 悬浮响应对应卡片的绘图区:按最近采样时间显示时间、各序列名称与数值;仅为有效可见序列绘制定位点,堆叠标记位于累计边界,缺失显示 --。主数值保持最新值。
- 定位线和提示仅随指针更新,不重建曲线 / 面积几何。提示保持在卡片内,不遮挡标题、主值及主要按钮,不拦截鼠标事件;离开绘图区清除。
## 各卡片信息契约
| 卡片 | 必须保留的前景与入口 |
| --- | --- |
| CPU | 总占用、温度 / 高温状态、左对齐用户 / 系统;核型横向分组、每核独立单元,数值通过悬浮和辅助功能提供;禁止把核数画成亮灯计数 |
| GPU | 总占用、温度,GPU 标题后紧跟实际核心数胶囊,带曲线色标的渲染器 / 分块器读数、旋转风扇图标与转速或等待状态 |
| 内存 | 已用 / 总量 GiB、压力标签;应用 / 联动 / 压缩单行及可用量,移除重复容量条;占用率、缓存和 Swap 保留在压力提示中 |
| 电池 | 主读数为电量百分比,详情用绿色电池图标标识带符号的电池瓦数,共同供电时以蓝色插头和绿色电池分别标识两路输出,电源状态在标题右侧;悬浮查看该时刻的适配器输入、报告能力、电池及负载,差值标 ≈;保留健康 / 循环与估时;确认无内置电池时切换为整机即时 W 与独立趋势;传感器缺失显示不可用,电池读取失败不触发切换 |
| 存储 | 已用 / 总量 GB;本地卷入口在标题右侧;可用、读写、寿命 / 通电依次左对齐;保留卷弹出层与口径说明 |
| 网络 | 黑白主数值与着色方向箭头;单行累计收发;标题右侧接口与路径状态;两行公网 / 本地 IP 及全文提示 / 选择 / 复制 |
进程表显示 PID / 名称 / CPU / 内存 / CPU 功率 / 线程六列,随视口适配且没有横向滚动条。路径不作为可见列,保留路径搜索与右键复制。移除整行口径 / 能量覆盖文案,标题提示保留说明与状态。
三语必须复用或补齐资源键;单位延续现有口径。长 IPv6、设备名和大数值可截断,但通过悬浮或复制取得完整内容。固定、暂停、保持唤醒与设置流程维持原语义。
## 风扇动效
风扇宿主图层不旋转,SF Symbol 独立子图层以图标区域中心为固定转轴;仅图标使用原生循环旋转:正值 <2000 RPM 为 90°/s,<4000 为 180°/s,<6000 为 300°/s,更高为 450°/s;这是沿用的视觉映射,不是物理 RPM。切档保持角度连续。零 / 缺失 / 无效值、暂停、隐藏 / 遮挡、睡眠、卸载及系统减弱动态效果时停转;曲线随新采样短暂平移,数字和进度条直接更新。
## 性能与验收
沿用独立 NativeContentHost 与 NativePanelCurve;六张卡片共用样式与几何规范,不增加依赖、背景轮询或历史容量。颜色、外观、数据或尺寸变化才更新相应图层;隐藏卸载仍释放图表和提示。
必须验证构建、布局预算、实际曲线 / 面积像素、显式空档无填充、缺失悬浮、悬浮几何缓存、浅深色、三语、大数值与窄屏;实际应用检查同页资源 / 进程、接口、卷详情、复制、暂停 / 恢复及关闭重开。真实多屏与长期能耗需对应环境,不用单次快照代替。
+33 -4
View File
@@ -19,6 +19,8 @@
CC1000000000000000000003 /* ProcessMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000004 /* ProcessMetrics.swift */; }; CC1000000000000000000003 /* ProcessMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000004 /* ProcessMetrics.swift */; };
CC1000000000000000000005 /* ProcessEnergy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000006 /* ProcessEnergy.swift */; }; CC1000000000000000000005 /* ProcessEnergy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000006 /* ProcessEnergy.swift */; };
CC1000000000000000000007 /* ProcessEnergyReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000008 /* ProcessEnergyReader.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 */ /* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */ /* Begin PBXContainerItemProxy section */
@@ -41,6 +43,13 @@
); );
name = "Embed XPC Services"; 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 */ /* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference 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; }; 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; }; 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; }; 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 */ /* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */ /* Begin PBXFileSystemSynchronizedRootGroup section */
@@ -77,6 +87,7 @@
D9E51E70309338B0000608DE /* Frameworks */ = { D9E51E70309338B0000608DE /* Frameworks */ = {
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
files = ( files = (
1A5000000000000000000001 /* Sparkle in Frameworks */,
); );
}; };
/* End PBXFrameworksBuildPhase section */ /* End PBXFrameworksBuildPhase section */
@@ -144,6 +155,7 @@
D9E51E70309338B0000608DE /* Frameworks */, D9E51E70309338B0000608DE /* Frameworks */,
D9E51E71309338B0000608DE /* Resources */, D9E51E71309338B0000608DE /* Resources */,
BB0000000000000000000004 /* Embed XPC Services */, BB0000000000000000000004 /* Embed XPC Services */,
1A5000000000000000000005 /* Embed Frameworks */,
); );
buildRules = ( buildRules = (
); );
@@ -154,6 +166,7 @@
D9E51E75309338B0000608DE /* kymo */, D9E51E75309338B0000608DE /* kymo */,
); );
name = kymo; name = kymo;
packageProductDependencies = (1A5000000000000000000002 /* Sparkle */,);
productName = kymo; productName = kymo;
productReference = D9E51E73309338B0000608DE /* kymo.app */; productReference = D9E51E73309338B0000608DE /* kymo.app */;
productType = "com.apple.product-type.application"; productType = "com.apple.product-type.application";
@@ -182,6 +195,7 @@
"zh-Hant", "zh-Hant",
Base, Base,
); );
packageReferences = (1A5000000000000000000003 /* Sparkle */,);
mainGroup = D9E51E6A309338B0000608DE; mainGroup = D9E51E6A309338B0000608DE;
minimizedProjectReferenceProxies = 1; minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77; preferredProjectObjectVersion = 77;
@@ -235,6 +249,14 @@
}; };
/* End PBXTargetDependency section */ /* 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 */ /* Begin XCBuildConfiguration section */
BB0000000000000000000028 /* Debug configuration for PBXNativeTarget "SMARTService" */ = { BB0000000000000000000028 /* Debug configuration for PBXNativeTarget "SMARTService" */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
@@ -303,7 +325,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 14; CURRENT_PROJECT_VERSION = 17;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_STRICT_OBJC_MSGSEND = YES;
@@ -325,7 +347,7 @@
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0; MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.2; MARKETING_VERSION = 1.5;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
@@ -371,7 +393,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 14; CURRENT_PROJECT_VERSION = 17;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEPLOYMENT_POSTPROCESSING = YES; DEPLOYMENT_POSTPROCESSING = YES;
@@ -388,7 +410,7 @@
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0; MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.2; MARKETING_VERSION = 1.5;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
SDKROOT = macosx; SDKROOT = macosx;
@@ -407,6 +429,9 @@
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = 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_APP_SANDBOX = YES;
ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES; ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
@@ -438,6 +463,10 @@
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = 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_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
ENABLE_OUTGOING_NETWORK_CONNECTIONS = 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
}
+45 -11
View File
@@ -1,5 +1,7 @@
import SwiftUI import SwiftUI
import AppKit import AppKit
import IOKit.ps
import notify
/// AppKit owns launch only; MenuBar owns windows, Core owns sampling and preferences. /// AppKit owns launch only; MenuBar owns windows, Core owns sampling and preferences.
@main @MainActor struct kymoApp { @main @MainActor struct kymoApp {
@@ -16,14 +18,22 @@ import AppKit
private let metrics = MetricsStore() private let metrics = MetricsStore()
private let awake = KeepAwakeService() private let awake = KeepAwakeService()
private let presentation = SettingsPresentation() private let presentation = SettingsPresentation()
private let updates = ReleaseUpdates()
private lazy var updater = SparkleUpdater(updates: updates)
private let appearance = AppearancePreferences() private let appearance = AppearancePreferences()
private let menuBarPreferences = MenuBarPreferences()
private let language = LanguagePreferences() private let language = LanguagePreferences()
private var openSettingsAction: (() -> Void)? private var openSettingsAction: (() -> Void)?
private var scenes: AnyObject? private var scenes: AnyObject?
private var menuBar: MenuPanelController? private var menuBar: MenuPanelController?
private var powerSourceToken: Int32?
private var workspaceTokens: [NSObjectProtocol] = [] private var workspaceTokens: [NSObjectProtocol] = []
func applicationWillFinishLaunching(_ notification: Notification) { 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 let center = NSWorkspace.shared.notificationCenter
for (name, sleeping) in [(NSWorkspace.willSleepNotification, true), (NSWorkspace.didWakeNotification, false)] { for (name, sleeping) in [(NSWorkspace.willSleepNotification, true), (NSWorkspace.didWakeNotification, false)] {
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in 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) } 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 { let settings = NSHostingSceneRepresentation {
Settings { Settings {
AppLanguageScope(preferences: language, onChange: { self.configureMainMenu() }) { [self] in 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)
} }
} }
} }
@@ -46,18 +67,15 @@ import AppKit
scenes = settings scenes = settings
openSettingsAction = { settings.environment.openSettings() } openSettingsAction = { settings.environment.openSettings() }
configureMainMenu() configureMainMenu()
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) }, metrics.setDetailDemand(processes: true, slowMetrics: true)
pageChanged: { [metrics] page in menuBar = MenuPanelController(readings: readings, visibility: { [metrics] in metrics.setPanelVisible($0) },
metrics.setDetailDemand(processes: page == .processes, slowMetrics: page == .overview)
},
menuTitle: { [language] key in menuTitle: { [language] key in
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem") 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) { 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 presentation: panel, onOpenSettings: { [weak self] in
self?.menuBar?.hide() self?.settingsCommand()
settings.environment.openSettings()
}, onPreferredHeight: { [weak self] height in }, onPreferredHeight: { [weak self] height in
self?.menuBar?.setPreferredContentHeight(height) self?.menuBar?.setPreferredContentHeight(height)
}) })
@@ -70,6 +88,10 @@ import AppKit
let root = NSMenu() let root = NSMenu()
let application = NSMenu() let application = NSMenu()
let appItem = NSMenuItem(); appItem.submenu = application; root.addItem(appItem) 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: ",") let settings = NSMenuItem(title: AppLocalization.string("action.settings", locale: language.locale), action: #selector(settingsCommand), keyEquivalent: ",")
settings.target = self settings.target = self
application.addItem(settings) application.addItem(settings)
@@ -89,14 +111,20 @@ import AppKit
NSApp.mainMenu = root 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) NSApp.setActivationPolicy(.regular)
presentation.request() presentation.request(page)
menuBar?.hide() menuBar?.hide()
openSettingsAction?() openSettingsAction?()
} }
func applicationWillTerminate(_ notification: Notification) { func applicationWillTerminate(_ notification: Notification) {
if let powerSourceToken { notify_cancel(powerSourceToken) }
workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver) workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver)
workspaceTokens.removeAll() workspaceTokens.removeAll()
menuBar?.shutdown() menuBar?.shutdown()
@@ -106,5 +134,11 @@ import AppKit
scenes = nil 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 } 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]) 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 { static func watts(_ value: Double?) -> String {
guard let value, value.isFinite, value >= 0 else { return "--" } guard let value, value.isFinite, value >= 0 else { return "--" }
return String(format: "%.1f W", value) 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: ", ")
}
}
+20 -4
View File
@@ -7,7 +7,9 @@ nonisolated struct TrendSample: Sendable {
let memory: Double? let memory: Double?
var download: Double? var download: Double?
var battery: Double? var battery: Double?
var batteryPower: Double? var powerFlow: BatteryPowerFlow?
var systemPower: Double?
var desktopInput: Double?
var upload: Double? var upload: Double?
var read: Double? var read: Double?
var write: Double? var write: Double?
@@ -29,6 +31,14 @@ nonisolated struct MetricHistory: Sendable {
private(set) var samples: [TrendSample] = [] private(set) var samples: [TrendSample] = []
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:] 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). /// 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. /// Preserve that outgoing wait on the existing point without changing earlier segments.
mutating func recordScheduledInterval(_ interval: TimeInterval) { mutating func recordScheduledInterval(_ interval: TimeInterval) {
@@ -42,11 +52,13 @@ nonisolated struct MetricHistory: Sendable {
} }
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false, expectedInterval: TimeInterval = 2) { 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, samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage, gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, download: snapshot.downloadRate,
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power, battery: snapshot.battery?.charge, powerFlow: snapshot.battery?.flow,
upload: snapshot.uploadRate, systemPower: snapshot.batteryState == .absent ? snapshot.systemPower : nil,
desktopInput: snapshot.desktopInput, upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written, read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler, cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler,
memoryApp: snapshot.memory.map { Double($0.app) }, memoryApp: snapshot.memory.map { Double($0.app) },
@@ -59,7 +71,11 @@ nonisolated struct MetricHistory: Sendable {
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload, expectedInterval: expectedInterval)) 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 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 }
}
} }
} }
+2
View File
@@ -34,6 +34,8 @@ nonisolated struct MetricsSnapshot: Sendable {
var diskHealth: DiskHealthMetrics? var diskHealth: DiskHealthMetrics?
var diskIO: DiskIOMetrics? var diskIO: DiskIOMetrics?
var volumes: [VolumeMetrics]? var volumes: [VolumeMetrics]?
var systemPower: Double?
var desktopInput: Double?
var battery: BatteryMetrics? var battery: BatteryMetrics?
var uptime: TimeInterval = 0 var uptime: TimeInterval = 0
var gpu: GPUMetrics? var gpu: GPUMetrics?
-18
View File
@@ -30,24 +30,6 @@ nonisolated struct ProcessSnapshot: Sendable {
let failed: Bool 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 { nonisolated struct ProcessMemoryRequest: Codable, Sendable {
let token: UUID let token: UUID
let identities: [ProcessIdentity] let identities: [ProcessIdentity]
+163 -32
View File
@@ -3,26 +3,58 @@ import IOKit.ps
nonisolated struct BatteryMetrics: Sendable { nonisolated struct BatteryMetrics: Sendable {
let charge: Double? let charge: Double?
let charging: Bool var flow = BatteryPowerFlow()
let externalPower: Bool var minutesToFull: Int?
var power: Double? = nil var minutesToEmpty: Int?
var minutesRemaining: Int? var minutesRemaining: Int? {
switch flow.state {
case .charging: minutesToFull
case .battery, .discharging, .combined: minutesToEmpty
case .external, .unknown: nil
}
}
var cycles: Int? var cycles: Int?
var health: Double? 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? { static func normalizedPower(voltageMillivolts: Double?, amperageMilliamps: Double?) -> Double? {
guard let voltageMillivolts, let amperageMilliamps, guard let voltageMillivolts, let amperageMilliamps,
voltageMillivolts.isFinite, amperageMilliamps.isFinite, voltageMillivolts.isFinite, amperageMilliamps.isFinite,
voltageMillivolts > 0, voltageMillivolts <= 30_000, voltageMillivolts > 0, voltageMillivolts <= 30_000,
abs(amperageMilliamps) <= 20_000 else { return nil } abs(amperageMilliamps) <= 20_000 else { return nil }
let watts = abs(voltageMillivolts * amperageMilliamps) / 1_000_000 let watts = (voltageMillivolts * amperageMilliamps) / 1_000_000
return watts.isFinite && watts <= 500 ? watts : nil return watts.isFinite && abs(watts) <= 500 ? watts : nil
} }
static func positiveMinutes(_ value: Int?) -> Int? { 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? { static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? {
@@ -44,7 +76,7 @@ nonisolated enum BatteryMonitor {
return .absent return .absent
} }
static func sample() -> BatteryMetrics? { mutating func sample() -> BatteryMetrics? {
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil } let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
for source in sources { for source in sources {
@@ -53,36 +85,135 @@ nonisolated enum BatteryMonitor {
let current = item[kIOPSCurrentCapacityKey] as? Double let current = item[kIOPSCurrentCapacityKey] as? Double
let maximum = item[kIOPSMaxCapacityKey] 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 charge = current.flatMap { c in maximum.flatMap { $0 > 0 ? min(1, max(0, c / $0)) : nil } }
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery")) let properties = Self.registryProperties() ?? [:]
var properties: [String: Any] = [:] let state = item[kIOPSPowerSourceStateKey] as? String
if service != 0 { let supply: Bool? = state == kIOPSACPowerValue ? true : state == kIOPSBatteryPowerValue ? false : nil
defer { IOObjectRelease(service) } let charging = item[kIOPSIsChargingKey] as? Bool
var raw: Unmanaged<CFMutableDictionary>? let flow = powerFlow(properties, externalSupply: supply, charging: charging)
if IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS { let systemMinutes = Self.estimatedMinutes(charging: false, externalPower: supply != false,
properties = raw?.takeRetainedValue() as? [String: Any] ?? [:] sourceMinutes: item[kIOPSTimeToEmptyKey] as? Int, systemSeconds: IOPSGetTimeRemainingEstimate())
} let now = Date()
} let recentPack = Self.packIsRecent(properties, at: now)
let charging = item[kIOPSIsChargingKey] as? Bool ?? false let packMinutes = recentPack && packStamp.isFresh(at: now) ? Self.positiveMinutes(properties["AvgTimeToEmpty"] as? Int) : nil
let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue return BatteryMetrics(charge: charge, flow: flow,
let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int minutesToFull: charging == true ? Self.positiveMinutes(item[kIOPSTimeToFullChargeKey] as? Int) : nil,
let batteryData = properties["BatteryData"] as? [String: Any] ?? [:] minutesToEmpty: systemMinutes ?? packMinutes,
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()),
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil }) cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
} }
return nil return nil
} }
private static func firstNumber(_ values: [Any?]) -> Double? { private static func registryProperties() -> [String: Any]? {
for case let value? in values { let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
if let number = value as? NSNumber, number.doubleValue.isFinite { 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 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 nil 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
}
}
}
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
} }
} }
+26 -3
View File
@@ -1,7 +1,7 @@
import Foundation import Foundation
import IOKit import IOKit
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan 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 { nonisolated final class CPUTemperatureMonitor {
static let highTemperatureThreshold = 90.0 static let highTemperatureThreshold = 90.0
@@ -99,9 +99,27 @@ nonisolated final class CPUTemperatureMonitor {
} }
} }
private func readNumber(_ key: UInt32) -> Double? { /// PSTR is the SMC system-total sensor, not battery flow or wall-outlet power.
func sampleSystemPower() -> Double? {
guard openConnection(), let watts = readNumber(0x50535452), watts > 0 else { return nil }
return watts
}
/// 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 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 request.command = 5; request.info.size = metadata.info.size
guard let response = call(&request) else { return nil } guard let response = call(&request) else { return nil }
let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) } let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) }
@@ -110,12 +128,17 @@ nonisolated final class CPUTemperatureMonitor {
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? { static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
switch (type, bytes.count) { 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 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 bits = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
let value = Double(Float(bitPattern: bits)) let value = Double(Float(bitPattern: bits))
return value.isFinite ? value : nil return value.isFinite ? value : nil
case (0x66706532, 2): // fpe2, big-endian unsigned 14.2 fixed point case (0x66706532, 2): // fpe2, big-endian unsigned 14.2 fixed point
return Double(UInt16(bytes[0]) << 8 | UInt16(bytes[1])) / 4 return Double(UInt16(bytes[0]) << 8 | UInt16(bytes[1])) / 4
case (0x73703738, 2): // sp78, signed 8.8 (SMC sign-magnitude)
let magnitude = Double(UInt16(bytes[0] & 0x7f) << 8 | UInt16(bytes[1])) / 256
return bytes[0] & 0x80 == 0 ? magnitude : -magnitude
case (0x75693820, 1): return Double(bytes[0]) // ui8 case (0x75693820, 1): return Double(bytes[0]) // ui8
default: return nil default: return nil
} }
+20 -13
View File
@@ -15,9 +15,15 @@ nonisolated struct NetworkInterfaceMetrics: Sendable {
} }
nonisolated struct NetworkMonitor { nonisolated struct NetworkMonitor {
struct InterfaceMetadata: Equatable {
let index: UInt32
var addresses: [String] = []
let active: Bool
}
private var previous: [String: (UInt64, UInt64)] = [:] private var previous: [String: (UInt64, UInt64)] = [:]
private var timestamp: TimeInterval? private var timestamp: TimeInterval?
private var identities: [String: String] = [:] private var previousMetadata: [String: InterfaceMetadata] = [:]
private var counterBuffer: [UInt8] = [] private var counterBuffer: [UInt8] = []
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? { static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
@@ -28,31 +34,31 @@ nonisolated struct NetworkMonitor {
mutating func sample() -> [NetworkInterfaceMetrics]? { mutating func sample() -> [NetworkInterfaceMetrics]? {
guard let counters = counters() else { previous = [:]; timestamp = nil; return nil } guard let counters = counters() else { previous = [:]; timestamp = nil; return nil }
let now = ProcessInfo.processInfo.systemUptime 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 elapsed = timestamp.map { now - $0 } ?? 0
let metadata = Self.interfaces() let result = counters.sorted { $0.key < $1.key }.map { name, current in
let result = counters.keys.sorted().map { name in
let current = counters[name]!
let item = metadata[name] let item = metadata[name]
let identity = "\(item?.index ?? 0):\(name):\(item?.active ?? false):\(item?.addresses.joined(separator: ",") ?? "")" let old = previousMetadata[name] == item ? previous[name] : nil
let old = identities[name] == identity ? previous[name] : nil
return NetworkInterfaceMetrics(name: name, received: current.0, sent: current.1, return NetworkInterfaceMetrics(name: name, received: current.0, sent: current.1,
download: Self.rate(current: current.0, previous: old?.0, elapsed: elapsed), download: Self.rate(current: current.0, previous: old?.0, elapsed: elapsed),
upload: Self.rate(current: current.1, previous: old?.1, elapsed: elapsed), upload: Self.rate(current: current.1, previous: old?.1, elapsed: elapsed),
index: item?.index ?? 0, addresses: item?.addresses ?? [], active: item?.active ?? false) index: item?.index ?? 0, addresses: item?.addresses ?? [], active: item?.active ?? false)
} }
identities = Dictionary(uniqueKeysWithValues: result.map { previousMetadata = metadata
($0.name, "\($0.index):\($0.name):\($0.active):\($0.addresses.joined(separator: ","))")
})
previous = counters previous = counters
timestamp = now timestamp = now
return result return result
} }
private static func interfaces() -> [String: (index: UInt32, addresses: [String], active: Bool)] { private static func interfaces() -> [String: InterfaceMetadata] {
var head: UnsafeMutablePointer<ifaddrs>? var head: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&head) == 0 else { return [:] } guard getifaddrs(&head) == 0 else { return [:] }
defer { freeifaddrs(head) } 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 hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
var cursor = head var cursor = head
while let entry = cursor { while let entry = cursor {
@@ -60,7 +66,7 @@ nonisolated struct NetworkMonitor {
let name = String(cString: entry.pointee.ifa_name) let name = String(cString: entry.pointee.ifa_name)
let flags = entry.pointee.ifa_flags let flags = entry.pointee.ifa_flags
let active = flags & UInt32(IFF_UP | IFF_RUNNING) == UInt32(IFF_UP | IFF_RUNNING) 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 address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) {
if let host = numericAddress(address, buffer: &hostBuffer) { if let host = numericAddress(address, buffer: &hostBuffer) {
item.addresses.append(host) item.addresses.append(host)
@@ -68,7 +74,8 @@ nonisolated struct NetworkMonitor {
} }
result[name] = item 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? { 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")) monitor.start(queue: DispatchQueue(label: "cn.airnan.kymo.network-path"))
} }
func snapshot() -> NetworkPathStatus? { func snapshot() -> (status: NetworkPathStatus?, primaryInterface: String?) {
lock.lock() lock.lock()
defer { lock.unlock() } defer { lock.unlock() }
return status return (status, primaryInterface)
}
func defaultInterface() -> String? {
lock.lock()
defer { lock.unlock() }
return primaryInterface
} }
deinit { monitor.cancel() } deinit { monitor.cancel() }
+32 -4
View File
@@ -8,11 +8,16 @@ actor SystemSampler {
private var temperatureCache: Double? private var temperatureCache: Double?
private var gpuTemperatureCache: Double? private var gpuTemperatureCache: Double?
private var fanCache: [FanMetrics]? 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 cpuSchedule = SensorSchedule()
private var gpuSchedule = SensorSchedule() private var gpuSchedule = SensorSchedule()
private var fanSchedule = SensorSchedule() private var fanSchedule = SensorSchedule()
private var didProbe = false private var didProbe = false
private let diskHealth = DiskHealthMonitor() private let diskHealth = DiskHealthMonitor()
private var batteryMonitor = BatteryMonitor()
private let batteryHealth = SystemBatteryHealthMonitor() private let batteryHealth = SystemBatteryHealthMonitor()
private var network = NetworkMonitor() private var network = NetworkMonitor()
private let networkPath = NetworkPathObserver() private let networkPath = NetworkPathObserver()
@@ -46,6 +51,8 @@ actor SystemSampler {
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() } func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func invalidateBatteryReadings() { batteryMonitor.invalidate() }
func setProcessVisible(_ visible: Bool, revision: Int? = nil) { func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
var changedRevision = false var changedRevision = false
if let revision { if let revision {
@@ -67,7 +74,7 @@ actor SystemSampler {
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = nil, func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = nil,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot { energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) async -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() } guard !Task.isCancelled else { return MetricsSnapshot() }
if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() } if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() }
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision) setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
@@ -95,11 +102,10 @@ actor SystemSampler {
result.fans = fanCache result.fans = fanCache
result.memory = MemoryMonitor.sample() result.memory = MemoryMonitor.sample()
result.network = network.sample() result.network = network.sample()
result.networkPath = networkPath.snapshot() (result.networkPath, result.defaultNetworkInterface) = networkPath.snapshot()
result.defaultNetworkInterface = networkPath.defaultInterface()
result.disk = DiskMonitor.sample() result.disk = DiskMonitor.sample()
result.diskIO = diskIO.sample() result.diskIO = diskIO.sample()
result.battery = BatteryMonitor.sample() result.battery = batteryMonitor.sample()
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample() result.gpu = GPUMonitor.sample()
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 { if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
@@ -120,6 +126,28 @@ actor SystemSampler {
result.battery?.health = batteryCache result.battery?.health = batteryCache
result.volumes = volumes result.volumes = volumes
result.uptime = ProcessInfo.processInfo.systemUptime 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()
readingPower = false
if !Task.isCancelled {
powerSchedule.complete(available: result.systemPower != nil, at: ProcessInfo.processInfo.systemUptime)
}
}
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n" let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8)) try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
@@ -7,6 +7,22 @@ nonisolated struct SensorReadings: Sendable {
} }
nonisolated enum CPUTemperatureServiceClient { 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
finish(value.flatMap { $0.doubleValue.isFinite && $0.doubleValue > 0 ? $0.doubleValue : nil })
}
}
}
static func readSensors(cpu: Bool, gpu: Bool, fans: Bool) async -> SensorReadings? { static func readSensors(cpu: Bool, gpu: Bool, fans: Bool) async -> SensorReadings? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSensors(cpu: cpu, gpu: gpu, fans: fans) { cpu, gpu, fans in proxy.readSensors(cpu: cpu, gpu: gpu, fans: fans) { cpu, gpu, fans 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 private(set) var slowMetricsRequested = true
let sampling: SamplingPreferences let sampling: SamplingPreferences
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping } private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
private var menuBarEnabled = false
private var liveDemand: Bool { panelDemand || (menuBarEnabled && !isDisplaySleeping) }
private var processDemand: Bool { panelDemand && processUpdatesRequested } private var processDemand: Bool { panelDemand && processUpdatesRequested }
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds } var effectiveMilliseconds: Int { liveDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) } private var hasSamplingDemand: Bool { !isSystemSleeping && (liveDemand || sampling.backgroundEnabled) }
// Permit timer coalescing without changing the requested cadence or delta timestamps. // Permit timer coalescing without changing the requested cadence or delta timestamps.
private var schedulingTolerance: Duration { 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 generation = 0
@ObservationIgnored private var visibilityGeneration = 0 @ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>? @ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler: SystemSampler @ObservationIgnored private let sampler: SystemSampler
@ObservationIgnored private var scheduledInterval = 0 @ObservationIgnored private var scheduledInterval = 0
@ObservationIgnored private var sleepStartedAt: Date?
@ObservationIgnored private var batteryWasAsleep = false
@ObservationIgnored private var needsHistoryBoundary = true @ObservationIgnored private var needsHistoryBoundary = true
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant? @ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
@@ -36,7 +40,7 @@ final class MetricsStore {
self.sampling.onChange = { [weak self] in self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused, guard let self, !self.isPaused,
self.effectiveMilliseconds != self.scheduledInterval || self.hasSamplingDemand != (self.task != nil) else { return } 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() start()
} }
@@ -48,7 +52,12 @@ final class MetricsStore {
reschedule(reset: true) 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 generation += 1
task?.cancel() task?.cancel()
task = nil task = nil
@@ -69,7 +78,12 @@ final class MetricsStore {
if initialDelay > .zero { if initialDelay > .zero {
do { try await Task.sleep(for: initialDelay, tolerance: self?.schedulingTolerance) } catch { return } 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() } if reset { await sampler.reset() }
var needsConfirmation = confirmPowerChange
while !Task.isCancelled { while !Task.isCancelled {
let sampledAt = ContinuousClock.now let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration let visibleGeneration = self?.visibilityGeneration
@@ -103,7 +117,10 @@ final class MetricsStore {
self?.lastPublishedAt = .now self?.lastPublishedAt = .now
self?.needsHistoryBoundary = false self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next) 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. // Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
let deadline = sampledAt.advanced(by: .milliseconds(interval)) let deadline = sampledAt.advanced(by: .milliseconds(interval))
do { try await Task.sleep(until: max(deadline, .now), tolerance: self?.schedulingTolerance, clock: .continuous) } 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) { func setSystemSleeping(_ sleeping: Bool) {
guard sleeping != isSystemSleeping else { return } 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 isSystemSleeping = sleeping
updateDemand(reset: true) updateDemand(reset: true)
} }
func setDisplaySleeping(_ sleeping: Bool) { func setDisplaySleeping(_ sleeping: Bool) {
guard sleeping != isDisplaySleeping else { return } guard sleeping != isDisplaySleeping else { return }
let wasActive = hasSamplingDemand
isDisplaySleeping = sleeping isDisplaySleeping = sleeping
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand) updateDemand(reset: !wasActive || !hasSamplingDemand, sampleImmediately: liveDemand)
} }
func setPanelVisible(_ visible: Bool) { func setPanelVisible(_ visible: Bool) {
guard isPanelVisible != visible else { return } guard isPanelVisible != visible else { return }
let wasActive = hasSamplingDemand
isPanelVisible = visible 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. /// 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,8 @@ import Foundation
@objc protocol SMARTServiceProtocol { @objc protocol SMARTServiceProtocol {
nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void) nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readProcessEnergy(_ 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, nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void) nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
+8 -1
View File
@@ -33,6 +33,8 @@ nonisolated enum SamplingDiagnostics {
payload["cores"] = snapshot.cpu?.cores.count payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature payload["cpuTemperature"] = snapshot.cpuTemperature
payload["gpuUsage"] = snapshot.gpuUsage payload["gpuUsage"] = snapshot.gpuUsage
payload["gpuRenderer"] = snapshot.gpu?.renderer
payload["gpuTiler"] = snapshot.gpu?.tiler
payload["gpuCoreCount"] = snapshot.gpu?.coreCount payload["gpuCoreCount"] = snapshot.gpu?.coreCount
payload["processEnumerated"] = snapshot.processes?.enumerated payload["processEnumerated"] = snapshot.processes?.enumerated
payload["processReadable"] = snapshot.processes?.readable payload["processReadable"] = snapshot.processes?.readable
@@ -50,7 +52,12 @@ nonisolated enum SamplingDiagnostics {
payload["volumeCount"] = snapshot.volumes?.count payload["volumeCount"] = snapshot.volumes?.count
payload["batteryCycles"] = snapshot.battery?.cycles payload["batteryCycles"] = snapshot.battery?.cycles
payload["batteryHealth"] = snapshot.battery?.health payload["batteryHealth"] = snapshot.battery?.health
payload["batteryPower"] = snapshot.battery?.power payload["systemPower"] = snapshot.systemPower
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 info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size) 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 let status = withUnsafeMutablePointer(to: &info) { pointer in
@@ -1,7 +1,15 @@
import Observation import Observation
enum SettingsPage: Hashable {
case general, menuBar, about
}
/// A UI-independent intent shared by the menu entry and the settings scene. /// A UI-independent intent shared by the menu entry and the settings scene.
@MainActor @Observable final class SettingsPresentation { @MainActor @Observable final class SettingsPresentation {
var selection: SettingsPage = .general
private(set) var requestID: UInt64 = 0 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)
}
}
+48 -40
View File
@@ -1,6 +1,6 @@
import SwiftUI import SwiftUI
/// Keep two balanced rows when possible; add rows to preserve readable core values. /// Core-kind columns contain one continuously filled cell per real core.
struct CPUCoreGrid: View { struct CPUCoreGrid: View {
let values: [Double] let values: [Double]
let kinds: [Int: CPUCoreTopology.Kind] let kinds: [Int: CPUCoreTopology.Kind]
@@ -14,8 +14,18 @@ struct CPUCoreGrid: View {
} }
} }
private func label(_ kind: CPUCoreTopology.Kind) -> Text { private func label(_ kind: CPUCoreTopology.Kind, compact: Bool = false) -> Text {
if compact {
switch kind { switch kind {
case .efficiency: return Text("cpu.kind.efficiencyShort", tableName: "CPUDetails")
case .middle: return Text("cpu.kind.performanceShort", tableName: "CPUDetails")
case .performance:
return kinds.values.contains(.middle)
? Text("cpu.kind.superShort", tableName: "CPUDetails")
: Text("cpu.kind.performanceShort", tableName: "CPUDetails")
}
}
return switch kind {
case .efficiency: Text("cpu.kind.efficiency", tableName: "CPUDetails") case .efficiency: Text("cpu.kind.efficiency", tableName: "CPUDetails")
case .middle: Text("cpu.kind.performance", tableName: "CPUDetails") case .middle: Text("cpu.kind.performance", tableName: "CPUDetails")
case .performance: case .performance:
@@ -31,79 +41,77 @@ struct CPUCoreGrid: View {
} }
static func groupWidths(groups: [[Int]], width: CGFloat) -> [CGFloat] { static func groupWidths(groups: [[Int]], width: CGFloat) -> [CGFloat] {
let weights = groups.map { CGFloat(($0.count + 1) / 2) } guard !groups.isEmpty else { return [] }
let total = max(1, weights.reduce(0, +)) let available = width.isFinite ? max(0, width - CGFloat(groups.count - 1) * 8) : 0
let available = max(0, width - CGFloat(max(0, groups.count - 1)) * 13) let minimum = min(44, available / CGFloat(groups.count))
return weights.map { available * $0 / total } let remaining = max(0, available - minimum * CGFloat(groups.count))
let total = max(1, groups.reduce(0) { $0 + $1.count })
return groups.map { minimum + remaining * CGFloat($0.count) / CGFloat(total) }
} }
var body: some View { var body: some View {
let groups = Self.groups(count: values.count, kinds: kinds) let groups = Self.groups(count: values.count, kinds: kinds)
GeometryReader { geometry in GeometryReader { geometry in
let widths = Self.groupWidths(groups: groups, width: geometry.size.width) let widths = Self.groupWidths(groups: groups, width: geometry.size.width)
HStack(alignment: .top, spacing: 6) { HStack(alignment: .top, spacing: 8) {
ForEach(groups.indices, id: \.self) { group in ForEach(groups.indices, id: \.self) { group in
if group > 0 { VStack(alignment: .leading, spacing: 4) {
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1) HStack(spacing: 2) {
} Circle().fill(color(kinds[groups[group][0]])).frame(width: 3, height: 3)
VStack(alignment: .leading, spacing: 5) { if let kind = kinds[groups[group][0]] { label(kind, compact: true) }
HStack(spacing: 3) {
Circle().fill(color(kinds[groups[group][0]])).frame(width: 5, height: 5)
if let kind = kinds[groups[group][0]] { label(kind) }
else { Text("cpu.core") } else { Text("cpu.core") }
Text(verbatim: "\(groups[group].count)").foregroundStyle(.secondary) Text(verbatim: "\(groups[group].count)").foregroundStyle(.primary)
} }
.font(.system(size: 9, weight: .medium)) .font(.system(size: 9, weight: .medium)).lineLimit(1).minimumScaleFactor(0.65)
.lineLimit(1).minimumScaleFactor(0.6) .frame(height: 12)
CPUCoreGridLayout { CPUCoreGridLayout {
ForEach(groups[group], id: \.self) { index in ForEach(groups[group], id: \.self) { index in core(index: index) }
core(index: index)
}
} }
}.frame(width: widths[group], alignment: .topLeading) }.frame(width: widths[group], alignment: .topLeading)
} }
} }
} }
.frame(height: 15 + CGFloat(maxRows(groups: groups)) * 22 + CGFloat(max(0, maxRows(groups: groups) - 1)) * 4) .frame(height: gridHeight(groups: groups))
.padding(.vertical, 1)
} }
// Match the content width so row reservation agrees with placement. var availableWidth: CGFloat = 185
var availableWidth: CGFloat = 380
private func maxRows(groups: [[Int]]) -> Int { private func gridHeight(groups: [[Int]]) -> CGFloat {
let widths = Self.groupWidths(groups: groups, width: availableWidth) let widths = Self.groupWidths(groups: groups, width: availableWidth)
return zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0 let rows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
return 16 + CGFloat(rows) * CPUCoreGridLayout.rowHeight + CGFloat(max(0, rows - 1)) * CPUCoreGridLayout.rowSpacing
} }
private func core(index: Int) -> some View { private func core(index: Int) -> some View {
let kind = kinds[index] let kind = kinds[index]
let value = values[index].isFinite ? min(1, max(0, values[index])) : 0 let measured = values[index].isFinite ? values[index] : nil
return VStack(spacing: 3) { return RoundedRectangle(cornerRadius: 2)
Text(verbatim: "\(Int((value * 100).rounded()))") .fill(color(kind).opacity(0.22))
.font(.system(size: 8, weight: .medium)).monospacedDigit().lineLimit(1) .overlay(alignment: .bottom) {
MetricProgressBar(value: value, color: color(kind)).frame(height: 3) Rectangle().fill(color(kind)).frame(height: CPUCoreGridLayout.rowHeight * (measured.map { min(1, max(0, $0)) } ?? 0))
} }
.clipShape(.rect(cornerRadius: 2))
.frame(height: CPUCoreGridLayout.rowHeight)
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
.help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(value))")) .help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(measured))"))
.accessibilityElement(children: .ignore) .accessibilityElement(children: .ignore)
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core")) .accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))") .accessibilityValue("\(index + 1): \(MetricFormat.percent(measured))")
} }
} }
struct CPUCoreGridLayout: Layout { struct CPUCoreGridLayout: Layout {
static let columnSpacing: CGFloat = 6 static let columnSpacing: CGFloat = 3
static let rowSpacing: CGFloat = 4 static let rowSpacing: CGFloat = 4
static let rowHeight: CGFloat = 22 static let rowHeight: CGFloat = 11
static let minimumTwoRowCellWidth: CGFloat = 16 static let minimumCellWidth: CGFloat = 7
static func rowCounts(count: Int, width: CGFloat) -> [Int] { static func rowCounts(count: Int, width: CGFloat) -> [Int] {
guard count > 0 else { return [] } guard count > 0 else { return [] }
guard count > 1 else { return [1] } guard count > 1 else { return [1] }
let usableWidth = width.isFinite ? max(0, width) : 0 let usableWidth = width.isFinite ? max(0, width) : 0
let capacity = max(1, Int(min(CGFloat(count), (usableWidth + columnSpacing) / (minimumTwoRowCellWidth + columnSpacing)))) let capacity = max(1, Int(min(CGFloat(count), (usableWidth + columnSpacing) / (minimumCellWidth + columnSpacing))))
let rows = max(2, (count + capacity - 1) / capacity) let rows = max(1, (count + capacity - 1) / capacity)
let quotient = count / rows, remainder = count % rows let quotient = count / rows, remainder = count % rows
return (0..<rows).map { quotient + ($0 < remainder ? 1 : 0) } return (0..<rows).map { quotient + ($0 < remainder ? 1 : 0) }
} }
@@ -117,8 +125,8 @@ struct CPUCoreGridLayout: Layout {
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let rows = Self.rowCounts(count: subviews.count, width: bounds.width) let rows = Self.rowCounts(count: subviews.count, width: bounds.width)
guard let columns = rows.max(), columns > 0 else { return } guard let columns = rows.max(), columns > 0 else { return }
let spacing = min(Self.columnSpacing, max(0, (bounds.width / CGFloat(columns) - 18) / 2)) let spacing = min(Self.columnSpacing, max(0, (bounds.width / CGFloat(columns) - Self.minimumCellWidth) / 2))
let cellWidth = max(0, (bounds.width - CGFloat(columns - 1) * spacing) / CGFloat(columns)) let cellWidth = min(Self.minimumCellWidth, max(0, (bounds.width - CGFloat(columns - 1) * spacing) / CGFloat(columns)))
var index = 0 var index = 0
for (row, count) in rows.enumerated() { for (row, count) in rows.enumerated() {
for column in 0..<count { for column in 0..<count {
+29 -10
View File
@@ -2,22 +2,41 @@ import SwiftUI
struct MemoryDetailsView: View { struct MemoryDetailsView: View {
let memory: MemoryMetrics let memory: MemoryMetrics
private var colors: [Color] { [Color("MemoryApplication"), Color("MemoryWired"), Color("MemoryCompressed"), Color("MemoryAvailable")] } private var values: [UInt64] { [memory.app, memory.wired, memory.compressed] }
private var values: [UInt64] { [memory.app, memory.wired, memory.compressed, memory.available] } private let labels: [LocalizedStringKey] = ["memory.appShort", "memory.wiredShort", "memory.compressedShort"]
private let labels: [LocalizedStringKey] = ["memory.app", "memory.wired", "memory.compressed", "memory.available"]
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 3) { VStack(alignment: .leading, spacing: 4) {
CardSeparator() ViewThatFits(in: .horizontal) {
CapacityBar(values: values.map { Double($0) }, colors: colors, total: Double(memory.total)) classification(0..<3, unit: true).fixedSize(horizontal: true, vertical: true)
VStack(alignment: .leading, spacing: 4) {
classification(0..<2, unit: false)
classification(2..<3, unit: true)
}
}
HStack(spacing: 4) { HStack(spacing: 4) {
ForEach(0..<4) { index in Text("memory.available").foregroundStyle(.secondary)
CapacityField(title: labels[index], value: MetricFormat.memory(values[index]), color: colors[index]) MetricText(value: MetricFormat.memory(memory.available)).fontWeight(.medium)
} }.frame(height: 16)
}
} }
.font(.system(size: 10)).lineLimit(1)
.help(Text("memory.distributionHelp"))
.accessibilityElement(children: .contain) .accessibilityElement(children: .contain)
.accessibilityLabel(Text("memory.distribution")) .accessibilityLabel(Text("memory.distribution"))
} }
private func classification(_ indices: Range<Int>, unit: Bool) -> some View {
HStack(spacing: 4) {
ForEach(Array(indices), id: \.self) { index in
if index > indices.lowerBound { Text("·").foregroundStyle(.secondary) }
HStack(spacing: 3) {
Text(labels[index]).foregroundStyle(.secondary)
MetricText(value: String(format: "%.1f", Double(values[index]) / 1_073_741_824))
.fontWeight(.medium).foregroundStyle(.primary)
}
.help(Text(MetricFormat.memory(values[index])))
}
if unit { Text(verbatim: "GiB").foregroundStyle(.secondary) }
}.frame(height: 16)
}
} }
@@ -16,6 +16,7 @@ struct MemoryHeaderInfo {
} }
var title: String { pressure.key.map(localized) ?? "--" } var title: String { pressure.key.map(localized) ?? "--" }
var badgeTitle: String { pressure.key == nil ? "--" : localized("memory.pressurePrefix") + title }
var color: Color { pressure.color } var color: Color { pressure.color }
var help: String { var help: String {
"\(localized("memory.pressure")): \(title)\n" "\(localized("memory.pressure")): \(title)\n"
+38 -11
View File
@@ -2,14 +2,10 @@ import AppKit
import SwiftUI import SwiftUI
import Observation import Observation
enum PanelPage: Hashable { case overview, processes }
@MainActor @Observable final class PanelPresentation { @MainActor @Observable final class PanelPresentation {
fileprivate(set) var isOpen = false fileprivate(set) var isOpen = false
var isPinned = false { didSet { onPinChange?(isPinned) } } var isPinned = false { didSet { onPinChange?(isPinned) } }
var page: PanelPage = .overview { didSet { if oldValue != page { onPageChange?(page) } } }
@ObservationIgnored var onPinChange: ((Bool) -> Void)? @ObservationIgnored var onPinChange: ((Bool) -> Void)?
@ObservationIgnored var onPageChange: ((PanelPage) -> Void)?
} }
/// Owns only status-item/window behavior. Sampling and settings are injected by App. /// Owns only status-item/window behavior. Sampling and settings are injected by App.
@@ -19,6 +15,8 @@ enum PanelPage: Hashable { case overview, processes }
#if DEBUG || KYMO_AUDIT #if DEBUG || KYMO_AUDIT
private(set) weak var lastHiddenContent: NSView? private(set) weak var lastHiddenContent: NSView?
#endif #endif
private let metricStrip = MenuBarMetricStrip()
private let readings: () -> [MenuBarReading]
private var statusItem: NSStatusItem? private var statusItem: NSStatusItem?
private var localMouse: Any? private var localMouse: Any?
private var globalMouse: Any? private var globalMouse: Any?
@@ -28,18 +26,22 @@ enum PanelPage: Hashable { case overview, processes }
private let visibility: (Bool) -> Void private let visibility: (Bool) -> Void
private let menuTitle: (String) -> String private let menuTitle: (String) -> String
private let openSettings: () -> Void private let openSettings: () -> Void
private let openAbout: () -> Void
private var showingStatusMenu = false private var showingStatusMenu = false
private var isHiding = false private var isHiding = false
private var preferredContentHeight = PanelLayout.defaultHeight private var preferredContentHeight = PanelLayout.defaultHeight
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void, init<Content: View>(installStatusItem: Bool = true, readings: @escaping () -> [MenuBarReading] = { [] },
pageChanged: @escaping (PanelPage) -> Void = { _ in }, visibility: @escaping (Bool) -> Void,
menuTitle: @escaping (String) -> String = { $0 }, menuTitle: @escaping (String) -> String = { $0 },
openSettings: @escaping () -> Void = {}, openSettings: @escaping () -> Void = {},
openAbout: @escaping () -> Void = {},
@ViewBuilder content: @escaping (PanelPresentation) -> Content) { @ViewBuilder content: @escaping (PanelPresentation) -> Content) {
self.readings = readings
self.visibility = visibility self.visibility = visibility
self.menuTitle = menuTitle self.menuTitle = menuTitle
self.openSettings = openSettings self.openSettings = openSettings
self.openAbout = openAbout
self.content = { self.content = {
let host = NSHostingView(rootView: content($0)) let host = NSHostingView(rootView: content($0))
// The controller owns the fixed panel frame; content must not negotiate window limits. // The controller owns the fixed panel frame; content must not negotiate window limits.
@@ -57,16 +59,15 @@ enum PanelPage: Hashable { case overview, processes }
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.dismiss = { [weak self] in self?.hide() } panel.dismiss = { [weak self] in self?.hide() }
presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal } presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal }
presentation.onPageChange = pageChanged
if installStatusItem { if installStatusItem {
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) 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?.target = self
item.button?.action = #selector(statusItemClicked) item.button?.action = #selector(statusItemClicked)
item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp]) item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
statusItem = item 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 tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.place() } MainActor.assumeIsolated { self?.place() }
@@ -85,6 +86,29 @@ enum PanelPage: Hashable { case overview, processes }
}) })
} }
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 func togglePanel() { panel.isVisible ? hide() : show() }
@objc private func statusItemClicked() { @objc private func statusItemClicked() {
@@ -106,6 +130,9 @@ enum PanelPage: Hashable { case overview, processes }
let settings = NSMenuItem(title: menuTitle("settings"), action: #selector(settingsClicked), keyEquivalent: ",") let settings = NSMenuItem(title: menuTitle("settings"), action: #selector(settingsClicked), keyEquivalent: ",")
settings.target = self settings.target = self
menu.addItem(settings) menu.addItem(settings)
let about = NSMenuItem(title: menuTitle("about"), action: #selector(aboutClicked), keyEquivalent: "")
about.target = self
menu.addItem(about)
menu.addItem(.separator()) menu.addItem(.separator())
let quit = NSMenuItem(title: menuTitle("quit"), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") let quit = NSMenuItem(title: menuTitle("quit"), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
quit.target = NSApp quit.target = NSApp
@@ -113,6 +140,7 @@ enum PanelPage: Hashable { case overview, processes }
return menu return menu
} }
@objc private func aboutClicked() { hide(); openAbout() }
@objc private func settingsClicked() { hide(); openSettings() } @objc private func settingsClicked() { hide(); openSettings() }
private func isOverStatusItem(_ screenPoint: NSPoint) -> Bool { private func isOverStatusItem(_ screenPoint: NSPoint) -> Bool {
@@ -123,7 +151,6 @@ enum PanelPage: Hashable { case overview, processes }
func show() { func show() {
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return } guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
place() place()
presentation.page = .overview
presentation.isOpen = true presentation.isOpen = true
panel.contentView = content(presentation) panel.contentView = content(presentation)
panel.level = presentation.isPinned ? .floating : .normal panel.level = presentation.isPinned ? .floating : .normal
@@ -6,24 +6,37 @@ extension MenuPanelView {
ResourceCard( ResourceCard(
title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: "↓ " + MetricFormat.rate(total(\.download)), title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: "↓ " + MetricFormat.rate(total(\.download)),
secondaryValue: "↑ " + MetricFormat.rate(total(\.upload)), valueColor: Color("MetricMemory"), secondaryValue: "↑ " + MetricFormat.rate(total(\.upload)), valueColor: Color("MetricMemory"),
secondaryValueColor: Color("SeriesUpload") secondaryValueColor: Color("SeriesUpload"), headerAccessory: AnyView(networkInterfacePicker),
) { chart: {
PanelTrendChart( PanelTrendChart(
dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"), dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"),
secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, showsLegendValues: false expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, visibleSeriesCount: 2, projection: .split(upwardSeries: 1)
).id(selectedInterface) ).id(selectedInterface)
CardSeparator() }
HStack(alignment: .top, spacing: 8) { ) {
networkTotal( HStack(spacing: 3) {
"network.received", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received }), Text("network.totalShort").foregroundStyle(.secondary)
symbol: "arrow.down", color: Color("MetricMemory")) Image(systemName: "arrow.down").foregroundStyle(Color("MetricMemory"))
Divider().frame(height: 32) MetricText(value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received })).fontWeight(.medium)
networkTotal( Text("·").foregroundStyle(.secondary)
"network.sent", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent }), Image(systemName: "arrow.up").foregroundStyle(Color("SeriesUpload"))
symbol: "arrow.up", color: Color("SeriesUpload")) MetricText(value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent })).fontWeight(.medium)
Divider().frame(height: 32) }.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9).frame(height: 16)
VStack(alignment: .leading, spacing: 4) { VStack(spacing: 4) {
networkAddress("network.public", address: publicIPAddress)
networkAddress(
"network.local",
address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first)
}
.font(.system(size: 10))
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("network.addresses"))
}
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
}
private var networkInterfacePicker: some View {
HStack(spacing: 4) { HStack(spacing: 4) {
Circle().fill(networkStatusColor).frame(width: 5, height: 5) Circle().fill(networkStatusColor).frame(width: 5, height: 5)
Picker("panel.interface", selection: $selectedInterface) { Picker("panel.interface", selection: $selectedInterface) {
@@ -31,29 +44,17 @@ extension MenuPanelView {
ForEach(snapshot.network ?? [], id: \.identity) { item in ForEach(snapshot.network ?? [], id: \.identity) { item in
Text(verbatim: item.name).tag(item.identity) Text(verbatim: item.name).tag(item.identity)
} }
}.labelsHidden().controlSize(.mini).fixedSize() }.labelsHidden().controlSize(.mini).fixedSize().frame(maxWidth: 70)
} }
Text(networkStatusLabel).help(Text(networkStatusLabel)) .help(Text(networkStatusLabel))
}.frame(maxWidth: .infinity, alignment: .leading)
}.font(PanelStyle.label).lineLimit(1)
CardSeparator()
HStack(spacing: 8) {
networkAddress("network.public", address: publicIPAddress)
Divider().frame(height: 15)
networkAddress(
"network.local",
address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first)
}.font(PanelStyle.label)
.modifier(CardInset())
.accessibilityElement(children: .contain) .accessibilityElement(children: .contain)
.accessibilityLabel(Text("network.addresses")) .accessibilityValue(Text(networkStatusLabel))
}
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
} }
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View { func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
HStack(spacing: 3) { HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary) Text(title).foregroundStyle(.secondary)
Text(verbatim: address ?? "--").font(PanelStyle.value).monospacedDigit().textSelection(.enabled) Text(verbatim: address ?? "--").font(.system(size: 10, weight: .medium)).monospacedDigit().textSelection(.enabled)
.help(Text(verbatim: address ?? "--")) .help(Text(verbatim: address ?? "--"))
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
if let address { if let address {
@@ -61,21 +62,12 @@ extension MenuPanelView {
NSPasteboard.general.clearContents() NSPasteboard.general.clearContents()
NSPasteboard.general.setString(address, forType: .string) NSPasteboard.general.setString(address, forType: .string)
} label: { } label: {
Image(systemName: "doc.on.doc") Image(systemName: "doc.on.doc").frame(width: 14, height: 14)
} }
.buttonStyle(.plain).accessibilityLabel(Text("panel.copy")) .buttonStyle(.plain).accessibilityLabel(Text("panel.copy"))
} }
}.frame(maxWidth: .infinity, alignment: .leading).lineLimit(1) }.frame(maxWidth: .infinity, alignment: .leading).frame(height: 16).lineLimit(1)
} }
func networkTotal(_ title: LocalizedStringKey, value: String, symbol: String, color: Color) -> some View {
CardField(title: title) {
HStack(spacing: 3) {
Image(systemName: symbol).foregroundStyle(color)
MetricText(value: value)
}
}
}
var networkStatusLabel: LocalizedStringKey { var networkStatusLabel: LocalizedStringKey {
switch snapshot.networkPath { switch snapshot.networkPath {
case .available: "network.pathAvailable" case .available: "network.pathAvailable"
@@ -3,17 +3,11 @@ import SwiftUI
extension MenuPanelView { extension MenuPanelView {
func line(_ key: LocalizedStringKey, _ value: String) -> some View { func line(_ key: LocalizedStringKey, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) { HStack(alignment: .firstTextBaseline, spacing: 4) {
Text(key).font(PanelStyle.label).foregroundStyle(.secondary) Text(key).font(.system(size: 10)).foregroundStyle(.secondary)
Spacer(minLength: 6) Spacer(minLength: 6)
MetricText(value: value).font(PanelStyle.value) MetricText(value: value).font(.system(size: 10, weight: .medium))
}.frame(height: 14) }.frame(height: 16)
}
func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
} }
var cpuCard: some View { var cpuCard: some View {
@@ -24,15 +18,21 @@ extension MenuPanelView {
value: MetricFormat.percent(snapshot.cpu?.usage), value: MetricFormat.percent(snapshot.cpu?.usage),
status: temperature.map { "\(Int($0.rounded()))°C" }, status: temperature.map { "\(Int($0.rounded()))°C" },
statusWarning: highTemperature, statusWarning: highTemperature,
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil,
) { chartPlacement: .background,
chart: {
PanelTrendChart( PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.cpu), dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem), second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"), color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals) boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [2, 1])
CardSeparator() }
) {
HStack(spacing: 5) {
InlineMetric("cpu.user", MetricFormat.percent(snapshot.cpu?.user))
InlineMetric("cpu.system", MetricFormat.percent(snapshot.cpu?.system))
}.frame(height: 16)
if let cpu = snapshot.cpu { if let cpu = snapshot.cpu {
CPUCoreGrid( CPUCoreGrid(
values: cpu.cores, kinds: CPUCoreTopology.cores, values: cpu.cores, kinds: CPUCoreTopology.cores,
@@ -47,37 +47,53 @@ extension MenuPanelView {
var gpuCard: some View { var gpuCard: some View {
return ResourceCard( return ResourceCard(
title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage), title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
titleBadge: snapshot.gpu?.coreCount.map {
$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" }, status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" },
detail: snapshot.gpu?.coreCount.map { String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0) } chartPlacement: .background,
) { chart: {
PanelTrendChart( PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.gpu), dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler), second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"), color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler", firstLabel: "gpu.totalUtilization",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals,
visibleSeriesCount: 3, filledSeriesCount: 1)
}
) {
HStack(spacing: 8) {
gpuStage("gpu.renderer", snapshot.gpu?.renderer, Color("MetricCPU"))
gpuStage("gpu.tiler", snapshot.gpu?.tiler, Color("SeriesSystem"))
}.frame(height: 16)
let fans = displayedFans let fans = displayedFans
if !fans.isEmpty { if !fans.isEmpty {
CardSeparator() LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 5, alignment: .leading), count: min(2, fans.count)), spacing: 2) {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 4) {
ForEach(fans) { fan in ForEach(fans) { fan in
FanSpeedIndicator( FanSpeedIndicator(
title: fans.count == 2 title: fans.count == 2
? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight")) ? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight"))
: Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm) : Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm,
isActive: metrics.isPanelVisible && !metrics.isPaused && !metrics.isSystemSleeping && !metrics.isDisplaySleeping)
.frame(height: 16) .frame(height: 16)
} }
} }
.modifier(CardInset())
} else if snapshot.fans == nil { } else if snapshot.fans == nil {
CardSeparator() Text("metric.waiting").font(.system(size: 10))
Text("metric.waiting").font(PanelStyle.label)
.frame(maxWidth: .infinity, alignment: .leading).frame(height: 16) .frame(maxWidth: .infinity, alignment: .leading).frame(height: 16)
.modifier(CardInset())
} }
} }
} }
private func gpuStage(_ title: LocalizedStringKey, _ usage: Double?, _ tint: Color) -> some View {
HStack(spacing: 3) {
Circle().fill(tint).frame(width: 4, height: 4)
InlineMetric(title, MetricFormat.percent(usage))
}
}
var memoryCard: some View { var memoryCard: some View {
let header = MemoryHeaderInfo(memory: snapshot.memory, locale: locale) let header = MemoryHeaderInfo(memory: snapshot.memory, locale: locale)
return ResourceCard( return ResourceCard(
@@ -85,25 +101,26 @@ extension MenuPanelView {
value: snapshot.memory.map { value: snapshot.memory.map {
String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824) String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824)
} ?? "--", } ?? "--",
status: snapshot.memory.map { MetricFormat.percent($0.usage) }, detail: header.badgeTitle, detailColor: snapshot.memory?.pressure == 1 ? Color("MetricBattery") : header.color,
detail: header.title, detailColor: header.color, detailHelp: header.help detailHelp: header.help + "\n" + MetricFormat.percent(snapshot.memory?.usage),
) { chartPlacement: .background,
chart: {
PanelTrendChart( PanelTrendChart(
dates: samples.map(\.date), dates: samples.map(\.date),
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } }, first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed), second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed),
color: Color("MetricCPU"), secondColor: Color("MemoryApplication"), color: Color("MemoryApplication"), secondColor: Color("MemoryApplication"),
thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1), thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1),
scaleLabel: MetricFormat.memory(snapshot.memory?.total), firstValueFormat: .memory, firstLabel: "gpu.totalUtilization", firstValueFormat: .memory, firstLabel: "memory.used",
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed", secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [1, 2, 3])
showsLegendValues: cardContentWidth >= 340) }
) {
if let memory = snapshot.memory { if let memory = snapshot.memory {
MemoryDetailsView(memory: memory) MemoryDetailsView(memory: memory)
} else { } else {
CardSeparator()
Text("metric.waiting").foregroundStyle(.secondary) Text("metric.waiting").foregroundStyle(.secondary)
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, alignment: .leading)
} }
} }
} }
@@ -114,18 +131,19 @@ extension MenuPanelView {
String( String(
format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000, format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000,
Double($0.total) / 1_000_000_000) Double($0.total) / 1_000_000_000)
} ?? "--" } ?? "--",
) { headerAccessory: AnyView(Button { showVolumes.toggle() } label: {
HStack(spacing: 2) { Text("disk.localVolumes"); Image(systemName: "chevron.right").font(.system(size: 7)) }
}.font(.system(size: 10)).buttonStyle(.plain).help(Text("disk.viewDetails"))),
chart: {
PanelTrendChart( PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"),
secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, visibleSeriesCount: 2, projection: .split(upwardSeries: 0)
) )
StorageDetailsView(disk: snapshot.disk, health: snapshot.diskHealth) {
showVolumes.toggle()
} }
) {
StorageDetailsView(disk: snapshot.disk, health: snapshot.diskHealth, io: snapshot.diskIO)
.popover(isPresented: $showVolumes) { .popover(isPresented: $showVolumes) {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
Text("disk.homeVolume") Text("disk.homeVolume")
@@ -139,7 +157,7 @@ extension MenuPanelView {
"\(MetricFormat.bytes(volume.capacity.available)) / \(MetricFormat.bytes(volume.capacity.total))") "\(MetricFormat.bytes(volume.capacity.available)) / \(MetricFormat.bytes(volume.capacity.total))")
} }
} }
Text("panel.apfsScope").font(.system(size: 9)).foregroundStyle(.secondary) Text("panel.apfsScope").font(.system(size: 10)).foregroundStyle(.secondary)
} }
}.padding(12).frame(width: 330) }.padding(12).frame(width: 330)
.environment(\.locale, locale) .environment(\.locale, locale)
@@ -148,67 +166,7 @@ extension MenuPanelView {
} }
} }
var batteryCard: some View { var batteryCard: some View {
ResourceCard( PowerResourceCard(snapshot: snapshot, samples: samples, sleepIntervals: metrics.history.sleepIntervals, chartInterval: chartInterval,
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), chartBoundaries: chartBoundaries, chartIntervals: chartIntervals)
value: MetricFormat.percent(snapshot.battery?.charge)
) {
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
)
CardSeparator()
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
.font(PanelStyle.label).frame(maxWidth: .infinity).frame(height: 32)
} }
} }
}
private func batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 2) {
HStack(alignment: .top, spacing: 10) {
VStack(spacing: 4) {
line("battery.health", MetricFormat.percent(battery.health))
HStack {
Text("battery.powerSource").foregroundStyle(.secondary)
Spacer(minLength: 4)
Text(battery.externalPower ? "battery.acPower" : "battery.batterySource").font(PanelStyle.value)
}.frame(height: 14)
}
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 32)
VStack(spacing: 4) {
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
HStack {
Text("battery.timeEstimate").foregroundStyle(.secondary)
Spacer(minLength: 4)
if battery.externalPower {
Text("battery.notApplicableShort").font(PanelStyle.value)
.help(Text("battery.timeNotApplicable"))
} else if let minutes = battery.minutesRemaining {
MetricText(value: "\(minutes) min").font(PanelStyle.value)
} else {
Text("battery.timeUnknown").font(PanelStyle.value)
}
}.frame(height: 14)
}
}
.font(PanelStyle.label)
.lineLimit(1)
.frame(height: 32)
}.frame(maxWidth: .infinity, alignment: .topLeading)
}
}
+52 -42
View File
@@ -5,7 +5,7 @@ struct MenuPanelView: View {
let metrics: MetricsStore let metrics: MetricsStore
let preferences: AppearancePreferences let preferences: AppearancePreferences
let keepAwake: KeepAwakeService let keepAwake: KeepAwakeService
let settingsPresentation: SettingsPresentation let updates: ReleaseUpdates
var presentation = PanelPresentation() var presentation = PanelPresentation()
var onOpenSettings: () -> Void = {} var onOpenSettings: () -> Void = {}
var onPreferredHeight: (CGFloat) -> Void = { _ in } var onPreferredHeight: (CGFloat) -> Void = { _ in }
@@ -29,7 +29,7 @@ struct MenuPanelView: View {
let missingIDs = (0..<reservedFanCount).filter { id in !fans.contains { $0.id == id } } let missingIDs = (0..<reservedFanCount).filter { id in !fans.contains { $0.id == id } }
return (fans + missingIDs.prefix(reservedFanCount - fans.count).map { FanMetrics(id: $0, rpm: nil) }).sorted { $0.id < $1.id } return (fans + missingIDs.prefix(reservedFanCount - fans.count).map { FanMetrics(id: $0, rpm: nil) }).sorted { $0.id < $1.id }
} }
var cardContentWidth: CGFloat { max(0, (measuredCardWidth ?? PanelLayout.cardWidth(size: panelSize)) - 20) } var cardContentWidth: CGFloat { max(0, (measuredCardWidth ?? PanelLayout.cardWidth(size: panelSize)) - ResourceCardMetrics.padding * 2) }
var columns: Int { PanelLayout.columns(width: panelSize.width) } var columns: Int { PanelLayout.columns(width: panelSize.width) }
private var cardHeights: [PanelCard: CGFloat] { private var cardHeights: [PanelCard: CGFloat] {
let coreCount = max(CPUCoreTopology.cores.count, ProcessInfo.processInfo.processorCount, snapshot.cpu?.cores.count ?? 0) let coreCount = max(CPUCoreTopology.cores.count, ProcessInfo.processInfo.processorCount, snapshot.cpu?.cores.count ?? 0)
@@ -51,17 +51,11 @@ struct MenuPanelView: View {
var body: some View { var body: some View {
VStack(spacing: PanelStyle.gap) { VStack(spacing: PanelStyle.gap) {
header header
if presentation.page == .overview { if PanelLayout.needsDashboardScroll(size: panelSize, heights: cardHeights) {
if PanelLayout.needsResourceScroll(size: panelSize, heights: cardHeights) { ScrollView { dashboard }
ScrollView { resourceColumns }
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
} else { } else {
resourceColumns dashboard.frame(maxHeight: .infinity, alignment: .top)
.frame(maxHeight: .infinity, alignment: .top)
}
} else if presentation.isOpen {
PanelProcessSection(metrics: metrics, state: processState)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} }
footer footer
} }
@@ -87,19 +81,32 @@ struct MenuPanelView: View {
} }
.background(Color("PanelBackground"), in: .rect(cornerRadius: 18)) .background(Color("PanelBackground"), in: .rect(cornerRadius: 18))
.clipShape(.rect(cornerRadius: 18)) .clipShape(.rect(cornerRadius: 18))
.transaction { $0.animation = nil; $0.disablesAnimations = true } .transaction { $0.animation = nil }
.environment(\.panelMotionActive, metrics.isPanelVisible && !metrics.isPaused && !metrics.isSystemSleeping && !metrics.isDisplaySleeping)
.modifier(AppearanceStyle(preferences: preferences)) .modifier(AppearanceStyle(preferences: preferences))
} }
private var resourceColumns: some View { private var dashboard: some View {
let groups = PanelLayout.cardColumns(columns: columns)
return HStack(alignment: .top, spacing: PanelStyle.gap) {
ForEach(groups.indices, id: \.self) { column in
VStack(spacing: PanelStyle.gap) { VStack(spacing: PanelStyle.gap) {
ForEach(groups[column], id: \.self) { card in resourceGrid
if presentation.isOpen {
PanelProcessSection(metrics: metrics, state: processState)
.frame(maxWidth: .infinity)
.frame(height: PanelLayout.processHeight(heights: cardHeights))
}
}
}
private var resourceGrid: some View {
let rows = PanelLayout.cardRows(columns: columns)
let heights = PanelLayout.rowHeights(columns: columns, heights: cardHeights)
return VStack(spacing: PanelStyle.gap) {
ForEach(rows.indices, id: \.self) { row in
HStack(alignment: .top, spacing: PanelStyle.gap) {
ForEach(rows[row], id: \.self) { card in
resourceCard(card) resourceCard(card)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.frame(height: cardHeights[card]) .frame(height: heights[row])
.onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in
if card == .cpu { measuredCardWidth = width } if card == .cpu { measuredCardWidth = width }
} }
@@ -121,52 +128,59 @@ struct MenuPanelView: View {
} }
} }
private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
private var brand: some View { private var brand: some View {
HStack(spacing: 6) { HStack(spacing: 6) {
Image("BrandMark").renderingMode(.template).resizable().scaledToFit() Image("BrandMark").renderingMode(.template).resizable().scaledToFit()
.frame(width: 22, height: 22) .frame(width: 22, height: 22)
HStack(alignment: .top, spacing: 3) {
Text("Kymo").font(.system(size: 17, weight: .semibold)) Text("Kymo").font(.system(size: 17, weight: .semibold))
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)
.background(.primary.opacity(0.09), in: Capsule())
.offset(y: -2)
.accessibilityLabel(Text("about.version \(version)"))
} }
}.fixedSize()
} }
private var pagePicker: some View {
NeutralTabPicker(title: "panel.page", selection: Binding(get: { presentation.page }, set: { presentation.page = $0 }),
options: [(.overview, "panel.overview"), (.processes, "panel.processes")])
.frame(width: 164)
.accessibilityIdentifier("panel.tabs")
} }
private var header: some View { private var header: some View {
VStack(spacing: 4) {
HStack(spacing: 8) { HStack(spacing: 8) {
brand brand
Spacer(minLength: 8) Spacer(minLength: 8)
controls controls
} }
.frame(height: 32)
.overlay {
if panelSize.width >= 560 { pagePicker }
}
if panelSize.width < 560 { pagePicker.frame(maxWidth: .infinity).frame(height: 28) }
}
.frame(height: PanelLayout.headerHeight(width: panelSize.width)) .frame(height: PanelLayout.headerHeight(width: panelSize.width))
.padding(.horizontal, 4) .padding(.horizontal, 4)
} }
private var footer: some View { private var footer: some View {
HStack { HStack {
HStack(spacing: 4) {
Text("panel.uptime")
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) Text(verbatim: HardwareIdentity.displayName)
.lineLimit(1).truncationMode(.middle) .lineLimit(1).truncationMode(.middle)
.help(Text(verbatim: HardwareIdentity.displayName)) .help(Text(verbatim: HardwareIdentity.displayName))
Spacer(minLength: 8) Spacer(minLength: 8)
HStack(spacing: 4) {
Text("panel.uptime")
MetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
}.fixedSize()
Divider().frame(height: 14)
HStack(spacing: 4) { HStack(spacing: 4) {
Image(systemName: "timer").help(Text("sampling.panel")) Image(systemName: "timer").help(Text("sampling.panel"))
IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 })) IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 }), fieldWidth: 50)
} }
.foregroundStyle(.primary) .foregroundStyle(.primary)
.accessibilityLabel(Text("sampling.panel")) .accessibilityLabel(Text("sampling.panel"))
@@ -199,11 +213,7 @@ struct MenuPanelView: View {
} }
.help(metrics.isPaused ? Text("action.resume") : Text("action.pause")) .help(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
.accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause")) .accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause"))
Button { Button(action: onOpenSettings) {
NSApp.setActivationPolicy(.regular)
settingsPresentation.request()
onOpenSettings()
} label: {
Image(systemName: "gearshape").frame(width: 20, height: 20) Image(systemName: "gearshape").frame(width: 20, height: 20)
} }
.help(Text("action.settings")).accessibilityLabel(Text("action.settings")) .help(Text("action.settings")).accessibilityLabel(Text("action.settings"))
+38 -18
View File
@@ -17,20 +17,22 @@ import SwiftUI
func makeCoordinator() -> Coordinator { Coordinator(self) } func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView { func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView() let scroll = FittingScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = false
scroll.horizontalScrollElasticity = .none
scroll.autohidesScrollers = true; scroll.drawsBackground = false scroll.autohidesScrollers = true; scroll.drawsBackground = false
let table = ProcessNSTableView() let table = ProcessNSTableView()
table.style = .inset; table.rowHeight = 20 table.style = .plain; table.rowHeight = 20
table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear
table.allowsMultipleSelection = false; table.allowsEmptySelection = true table.allowsMultipleSelection = false; table.allowsEmptySelection = true
table.columnAutoresizingStyle = .sequentialColumnAutoresizingStyle table.columnAutoresizingStyle = .noColumnAutoresizing
for (key, width) in [("pid", 48.0), ("name", 140), ("cpu", 65), ("memory", 85), ("power", 90), ("threads", 65), ("path", 250)] { table.intercellSpacing.width = 0
for (key, width) in [("pid", 48.0), ("name", 140), ("cpu", 65), ("memory", 85), ("power", 90), ("threads", 65)] {
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(key)) let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(key))
column.width = width column.width = width
column.minWidth = key == "path" ? 150 : key == "name" ? 90 : width column.minWidth = 0
column.maxWidth = key == "name" ? 180 : key == "path" ? 10_000 : width column.maxWidth = 10_000
column.resizingMask = key == "path" ? [.autoresizingMask, .userResizingMask] : .userResizingMask column.resizingMask = []
column.sortDescriptorPrototype = NSSortDescriptor(key: key, ascending: false) column.sortDescriptorPrototype = NSSortDescriptor(key: key, ascending: false)
table.addTableColumn(column) table.addTableColumn(column)
} }
@@ -47,7 +49,32 @@ import SwiftUI
context.coordinator.apply(self, to: table) context.coordinator.apply(self, to: table)
} }
private final class FittingScrollView: NSScrollView {
private var fitting = false
override func tile() {
super.tile()
guard !fitting, let table = documentView as? ProcessNSTableView else { return }
fitting = true; defer { fitting = false }
table.fitColumns(to: contentView.bounds.width)
}
}
final class ProcessNSTableView: NSTableView { final class ProcessNSTableView: NSTableView {
/// Allocate the complete viewport; AppKit's uniform resizing can leave columns clipped at narrow widths.
func fitColumns(to width: CGFloat) {
guard width.isFinite, width > 0, tableColumns.count == 6 else { return }
let minimum: [CGFloat] = [32,54,40,52,54,32]
let preferred: [CGFloat] = [48,140,65,85,90,65]
let minimumTotal = minimum.reduce(0, +)
let baseScale = min(1, width / minimumTotal)
let extraScale = max(0, width - minimumTotal) / (preferred.reduce(0, +) - minimumTotal)
for index in tableColumns.indices {
let value = minimum[index] * baseScale + (preferred[index] - minimum[index]) * extraScale
if abs(tableColumns[index].width - value) > 0.01 { tableColumns[index].width = value }
}
if abs(frame.width - width) > 0.01 { setFrameSize(CGSize(width: width, height: frame.height)) }
}
var contextMenu: ((Int) -> NSMenu?)? var contextMenu: ((Int) -> NSMenu?)?
var cancel: (() -> Void)? var cancel: (() -> Void)?
override func keyDown(with event: NSEvent) { override func keyDown(with event: NSEvent) {
@@ -106,7 +133,7 @@ import SwiftUI
} }
} }
let descriptors = (pendingSorting ?? value.sorting).map { 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 } if table.sortDescriptors != descriptors { table.sortDescriptors = descriptors }
let oldCount = table.numberOfRows, newCount = value.rows.count let oldCount = table.numberOfRows, newCount = value.rows.count
@@ -145,7 +172,6 @@ import SwiftUI
switch key { switch key {
case "pid": text = String(process.id.pid) case "pid": text = String(process.id.pid)
case "name": text = process.name case "name": text = process.name
case "path": text = process.path ?? "--"
case "cpu": text = process.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--" case "cpu": text = process.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--"
case "memory": text = process.footprintBytes.map { String(format: "%.1f MB", Double($0) / 1_048_576) } ?? "--" case "memory": text = process.footprintBytes.map { String(format: "%.1f MB", Double($0) / 1_048_576) } ?? "--"
case "power": text = process.formattedPower case "power": text = process.formattedPower
@@ -185,7 +211,7 @@ import SwiftUI
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard !applying else { return } guard !applying else { return }
let order = tableView.sortDescriptors.compactMap { descriptor -> ProcessSort? in 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) return ProcessSort(key: key, order: descriptor.ascending ? .forward : .reverse)
} }
sortRevision += 1; let revision = sortRevision sortRevision += 1; let revision = sortRevision
@@ -211,12 +237,6 @@ import SwiftUI
guard let value = item.representedObject as? String else { return } guard let value = item.representedObject as? String else { return }
NSPasteboard.general.clearContents(); NSPasteboard.general.setString(value, forType: .string) 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 { final class Cell: NSTableCellView {
@@ -228,7 +248,7 @@ import SwiftUI
text.font = ["pid", "cpu", "memory", "threads", "power"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11) text.font = ["pid", "cpu", "memory", "threads", "power"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11)
text.alignment = ["cpu", "memory", "threads", "power"].contains(key) ? .right : .left text.alignment = ["cpu", "memory", "threads", "power"].contains(key) ? .right : .left
text.lineBreakMode = .byTruncatingMiddle text.lineBreakMode = .byTruncatingMiddle
text.textColor = key == "path" ? .secondaryLabelColor : .labelColor text.textColor = .labelColor
addSubview(text); textField = text addSubview(text); textField = text
if key == "name" || key == "threads" { if key == "name" || key == "threads" {
let image = NSImageView(); image.imageScaling = .scaleProportionallyDown let image = NSImageView(); image.imageScaling = .scaleProportionallyDown
+35 -22
View File
@@ -2,58 +2,71 @@ import Foundation
import CoreGraphics import CoreGraphics
nonisolated enum PanelCard: Int, CaseIterable { nonisolated enum PanelCard: Int, CaseIterable {
case cpu, battery, gpu, storage, memory, network case cpu, gpu, memory, battery, storage, network
} }
nonisolated enum PanelLayout { nonisolated enum PanelLayout {
static let footerHeight: CGFloat = 26 static let footerHeight: CGFloat = 26
static let maximumWidth: CGFloat = ResourceCardMetrics.preferredWidth * 3 + 32
static let maximumHeight: CGFloat = 800 static let maximumHeight: CGFloat = 800
static func headerHeight(width: CGFloat) -> CGFloat { width >= 560 ? 32 : 64 } static func headerHeight(width: CGFloat) -> CGFloat { 32 }
static func columns(width: CGFloat) -> Int { width >= 560 ? 2 : 1 } static func columns(width: CGFloat) -> Int { width >= 620 ? 3 : width >= 430 ? 2 : 1 }
static func cardWidth(size: CGSize) -> CGFloat { static func cardWidth(size: CGSize) -> CGFloat {
let count = columns(width: size.width) let count = columns(width: size.width)
return max(0, (size.width - 20 - CGFloat(count - 1) * 8) / CGFloat(count)) return max(0, (size.width - 20 - CGFloat(count - 1) * 6) / CGFloat(count))
} }
/// Preserve location and order; never rebalance columns when values change. /// Keep reading order stable across three-, two- and single-column grids.
static func cardColumns(columns: Int) -> [[PanelCard]] { static func cardRows(columns: Int) -> [[PanelCard]] {
columns > 1 ? [[.cpu, .gpu, .memory], [.battery, .storage, .network]] : [PanelCard.allCases] let cards = PanelCard.allCases
let count = max(1, columns)
return stride(from: 0, to: cards.count, by: count).map { start in
Array(cards[start..<min(start + count, cards.count)])
}
} }
/// Fixed content rows with a 48pt plot. Nil fans reserve a discovery row. /// Structural foreground height determines the room available for the trend below the text.
static func cardHeights(coreRows: Int, fanCount: Int?) -> [PanelCard: CGFloat] { static func cardHeights(coreRows: Int, fanCount: Int?) -> [PanelCard: CGFloat] {
let base = ResourceCardMetrics.minimumHeight
let fanRows = fanCount.map { (max(0, $0) + 1) / 2 } ?? 1 let fanRows = fanCount.map { (max(0, $0) + 1) / 2 } ?? 1
return [.cpu: 152 + CGFloat(max(1, coreRows)) * 26, return [.cpu: base + CGFloat(max(0, coreRows - 1)) * 15,
.gpu: fanRows == 0 ? 124 : 144 + CGFloat(fanRows) * 20, .gpu: base + CGFloat(max(0, fanRows - 1)) * 18,
.memory: 180, .battery: 170, .storage: 170, .network: 208] .memory: base, .battery: base, .storage: base, .network: base]
} }
static func columnHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] { static func rowHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] {
cardColumns(columns: columns).map { cards in Array(repeating: processHeight(heights: heights), count: cardRows(columns: columns).count)
cards.reduce(0) { $0 + (heights[$1] ?? 0) } + CGFloat(max(0, cards.count - 1)) * 8
} }
static func processHeight(heights: [PanelCard: CGFloat]) -> CGFloat {
heights.values.max() ?? ResourceCardMetrics.minimumHeight
} }
static func resourceHeight(columns: Int, heights: [PanelCard: CGFloat]) -> CGFloat { static func resourceHeight(columns: Int, heights: [PanelCard: CGFloat]) -> CGFloat {
columnHeights(columns: columns, heights: heights).max() ?? 0 let rows = rowHeights(columns: columns, heights: heights)
return rows.reduce(0, +) + CGFloat(max(0, rows.count - 1)) * 6
}
static func dashboardHeight(columns: Int, heights: [PanelCard: CGFloat]) -> CGFloat {
resourceHeight(columns: columns, heights: heights) + 6 + processHeight(heights: heights)
} }
static func preferredHeight(width: CGFloat, heights: [PanelCard: CGFloat]) -> CGFloat { static func preferredHeight(width: CGFloat, heights: [PanelCard: CGFloat]) -> CGFloat {
min(maximumHeight, resourceHeight(columns: columns(width: width), heights: heights) min(maximumHeight, dashboardHeight(columns: columns(width: width), heights: heights)
+ 20 + headerHeight(width: width) + footerHeight + 16) + 20 + headerHeight(width: width) + footerHeight + 12)
} }
static var defaultHeight: CGFloat { static var defaultHeight: CGFloat {
preferredHeight(width: 640, heights: cardHeights(coreRows: 2, fanCount: nil)) preferredHeight(width: maximumWidth, heights: cardHeights(coreRows: 1, fanCount: nil))
} }
static func needsResourceScroll(size: CGSize, heights: [PanelCard: CGFloat]) -> Bool { static func needsDashboardScroll(size: CGSize, heights: [PanelCard: CGFloat]) -> Bool {
resourceHeight(columns: columns(width: size.width), heights: heights) dashboardHeight(columns: columns(width: size.width), heights: heights)
> size.height - 20 - headerHeight(width: size.width) - footerHeight - 16 > size.height - 20 - headerHeight(width: size.width) - footerHeight - 12
} }
static func contentSize(visible: CGRect, chrome: CGSize = .zero, preferredHeight: CGFloat? = nil) -> CGSize { static func contentSize(visible: CGRect, chrome: CGSize = .zero, preferredHeight: CGFloat? = nil) -> CGSize {
CGSize(width: max(1, min(640, visible.width - 32 - max(0, chrome.width))), CGSize(width: max(1, min(maximumWidth, visible.width - 32 - max(0, chrome.width))),
height: max(1, min(maximumHeight, preferredHeight ?? defaultHeight, height: max(1, min(maximumHeight, preferredHeight ?? defaultHeight,
visible.height - 32 - max(0, chrome.height)))) visible.height - 32 - max(0, chrome.height))))
} }
@@ -16,9 +16,9 @@ import AppKit
NSApp.terminate(nil) NSApp.terminate(nil)
return return
} }
@MainActor func plots(in view: NSView?) -> [NativePanelCurve.PlotView] { @MainActor func plots(in view: NSView?) -> [NSView] {
guard let view else { return [] } 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) } return own + view.subviews.flatMap { plots(in: $0) }
} }
@MainActor func mark(_ event: String) { @MainActor func mark(_ event: String) {
@@ -27,7 +27,7 @@ import AppKit
let views = plots(in: controller.panel.contentView) let views = plots(in: controller.panel.contentView)
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil, SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil,
windowNumber: controller.panel.isVisible ? controller.panel.windowNumber : 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), pointerInsidePanel: controller.panel.isVisible && controller.panel.frame.contains(NSEvent.mouseLocation),
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] }) plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] })
if event == "open1.10", ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1", if event == "open1.10", ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1",
@@ -40,12 +40,16 @@ import AppKit
controller.show() controller.show()
if let value = ProcessInfo.processInfo.environment["KYMO_AUDIT_SIZE"] { if let value = ProcessInfo.processInfo.environment["KYMO_AUDIT_SIZE"] {
let parts = value.split(separator: "x").compactMap { Double($0) } let parts = value.split(separator: "x").compactMap { Double($0) }
if parts.count == 2, parts.allSatisfy({ $0.isFinite }), parts[0] >= 480, parts[1] >= 360 { if parts.count == 2, parts.allSatisfy({ $0.isFinite }), parts[0] >= 360, parts[1] >= 360 {
controller.panel.setContentSize(CGSize(width: min(parts[0], controller.panel.frame.width), controller.panel.setContentSize(CGSize(width: min(parts[0], controller.panel.frame.width),
height: min(parts[1], controller.panel.frame.height))) height: min(parts[1], controller.panel.frame.height)))
} }
} }
mark("interactive") mark("interactive")
if ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1" {
await wait(10)
mark("open1.10")
}
return return
} }
let quick = ProcessInfo.processInfo.environment["KYMO_AUDIT_QUICK"] == "1" let quick = ProcessInfo.processInfo.environment["KYMO_AUDIT_QUICK"] == "1"
@@ -54,7 +58,6 @@ import AppKit
mark("hidden10") mark("hidden10")
for cycle in 1...3 { for cycle in 1...3 {
controller.show() controller.show()
if ProcessInfo.processInfo.environment["KYMO_AUDIT_PAGE"] == "processes" { controller.presentation.page = .processes }
mark("open\(cycle).0") mark("open\(cycle).0")
await wait(1); mark("open\(cycle).1") await wait(1); mark("open\(cycle).1")
await wait(9); mark("open\(cycle).10") await wait(9); mark("open\(cycle).10")
@@ -0,0 +1,139 @@
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 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 {
if snapshot.batteryState == .absent {
ResourceCard(title: "power.system", symbol: "bolt.fill", color: Color("MetricBattery"),
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)
}) {
Text(snapshot.systemPower == nil ? "power.sensorUnavailable" : "panel.noBattery")
.font(.system(size: 10)).foregroundStyle(.secondary)
}
} else {
batteryPowerCard
}
}
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),
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: {
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()
}
}
}
) {
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 {
Text(snapshot.batteryState == .unknown ? "metric.waiting" : "panel.batteryFailed").foregroundStyle(.secondary)
.font(.system(size: 10)).frame(maxWidth: .infinity).frame(height: 32)
}
}
}
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) ?? "--")
}
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")
}
}
}
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9)
}
}
@@ -10,29 +10,37 @@ nonisolated enum ProcessTableProjection {
} }
static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], order: [ProcessIdentity]) -> [ProcessMetrics] { static func rows(_ input: [ProcessMetrics], query: String, sorting: [ProcessSort], order: [ProcessIdentity]) -> [ProcessMetrics] {
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) }) let matches = query.isEmpty ? input : input.filter {
return input.filter { $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query)
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false) || ($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 } func precedes(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> Bool {
for comparator in sorting { for comparator in sorting {
let result = comparator.compare($0, $1) let result = comparator.compare(lhs, rhs)
if result != .orderedSame { return result == .orderedAscending } 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. /// Missing metrics stay last in either direction. Every newly selected column starts descending.
nonisolated struct ProcessSort: SortComparator, Equatable { 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 let key: Key
var order: SortOrder = .reverse var order: SortOrder = .reverse
func compare(_ lhs: ProcessMetrics, _ rhs: ProcessMetrics) -> ComparisonResult { 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) { switch (a, b) {
case (nil, nil): return .orderedSame case (nil, nil): return .orderedSame
case (nil, _): return .orderedDescending case (nil, _): return .orderedDescending
@@ -41,13 +49,13 @@ nonisolated struct ProcessSort: SortComparator, Equatable {
} }
} }
switch key { 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 .name: return directed(lhs.name.localizedStandardCompare(rhs.name))
case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? "")) case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? ""))
case .cpu: return metric(lhs.cpu, rhs.cpu) 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 .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)
} }
} }
+4 -8
View File
@@ -31,19 +31,16 @@ struct ProcessTableView: View {
Spacer(minLength: 0) Spacer(minLength: 0)
searchField.frame(maxWidth: 180) searchField.frame(maxWidth: 180)
} }
HStack(spacing: 8) {
Text("panel.processScope").lineLimit(2)
Spacer(minLength: 4)
energyStatus
}.font(.system(size: 9)).foregroundStyle(.secondary)
if snapshot?.failed == true { Text("panel.processFailed") } if snapshot?.failed == true { Text("panel.processFailed") }
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) } else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
NativeProcessTable(rows: rows, selection: $state.selected, sorting: $state.sortOrder, locale: locale, onExit: handleExit) NativeProcessTable(rows: rows, selection: $state.selected, sorting: $state.sortOrder, locale: locale, onExit: handleExit)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } } .overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } }
if exitedSelection != nil, let departed = state.departed { if exitedSelection != nil, let departed = state.departed {
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { state.selected = nil; state.departed = nil } } HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { state.selected = nil; state.departed = nil } }
} }
} }
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.font(.system(size: 12)).padding(10) .font(.system(size: 12)).padding(10)
.modifier(CardSurface()) .modifier(CardSurface())
.onAppear { rebuild(retainOrder: false) } .onAppear { rebuild(retainOrder: false) }
@@ -70,14 +67,14 @@ struct ProcessTableView: View {
private var processTitle: some View { private var processTitle: some View {
Label("panel.processes", systemImage: "list.bullet.rectangle") Label("panel.processes", systemImage: "list.bullet.rectangle")
.font(PanelStyle.title) .font(PanelStyle.title)
.help(Text("\(Text("panel.processScope"))\n\(energyStatus)"))
} }
private var searchField: some View { private var searchField: some View {
NativeSearchField(text: $state.search, isFocused: $searchFocused, NativeSearchField(text: $state.search, isFocused: $searchFocused,
placeholder: AppLocalization.string("panel.search", locale: locale)) placeholder: AppLocalization.string("panel.search", locale: locale))
} }
private var energyStatus: some View { private var energyStatus: Text {
Group {
switch energy?.state { switch energy?.state {
case .unsupported: Text("energy.unsupported") case .unsupported: Text("energy.unsupported")
case .unavailable: Text("energy.unavailable") case .unavailable: Text("energy.unavailable")
@@ -85,7 +82,6 @@ struct ProcessTableView: View {
Text("energy.coverage \(energy?.measured ?? 0) \(energy?.candidates ?? 0)") Text("energy.coverage \(energy?.measured ?? 0) \(energy?.candidates ?? 0)")
default: Text("energy.waiting") default: Text("energy.waiting")
} }
}.help(Text("energy.scopeHelp")).lineLimit(1)
} }
private func rebuild(retainOrder: Bool) { private func rebuild(retainOrder: Bool) {
+25 -26
View File
@@ -3,40 +3,39 @@ import SwiftUI
struct StorageDetailsView: View { struct StorageDetailsView: View {
let disk: DiskMetrics? let disk: DiskMetrics?
let health: DiskHealthMetrics? let health: DiskHealthMetrics?
let showVolumes: () -> Void let io: DiskIOMetrics?
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 3) {
CardSeparator() field("memory.available", value: Text(verbatim: MetricFormat.bytes(disk?.available)))
HStack(spacing: 8) { ViewThatFits(in: .horizontal) {
VStack(spacing: 4) { HStack(spacing: 6) { read; write }.fixedSize(horizontal: true, vertical: true)
field("memory.available", value: MetricFormat.bytes(disk?.available)) VStack(alignment: .leading, spacing: 3) { read; write }
field("disk.powerOnHours", value: health?.powerOnHours.map { "\($0) h" } ?? "--")
} }
Divider().frame(height: 32) ViewThatFits(in: .horizontal) {
VStack(spacing: 4) { HStack(spacing: 4) {
field("disk.remainingLife", value: MetricFormat.percent(health?.remainingLife)) life
Button(action: showVolumes) { Text("·").foregroundStyle(.secondary)
HStack(spacing: 3) { powerOn
Text("disk.localVolumes") }.fixedSize(horizontal: true, vertical: true)
Spacer(minLength: 3) VStack(alignment: .leading, spacing: 3) { life; powerOn }
Image(systemName: "chevron.right").font(.system(size: 8))
}.contentShape(.rect)
} }
.buttonStyle(.plain).help(Text("disk.viewDetails"))
.frame(height: 14)
}
}.font(PanelStyle.label).lineLimit(1)
} }
.font(.system(size: 10)).lineLimit(1)
} }
private func field(_ title: LocalizedStringKey, value: String) -> some View { 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: Text) -> some View {
HStack(spacing: 3) { HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary).help(Text(title)) Text(title).foregroundStyle(.secondary).help(Text(title))
Spacer(minLength: 3) value.monospacedDigit().fontWeight(.medium).foregroundStyle(.primary)
MetricText(value: value).font(PanelStyle.value) }.frame(height: 14)
}
.frame(height: 14)
.frame(maxWidth: .infinity)
} }
} }
@@ -6,22 +6,25 @@ struct AppearanceSettingsView: View {
@Bindable var preferences: AppearancePreferences @Bindable var preferences: AppearancePreferences
@Bindable var language: LanguagePreferences @Bindable var language: LanguagePreferences
@Bindable var sampling: SamplingPreferences @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 @Environment(\.locale) private var locale
@State private var selection = SettingsPage.general
var body: some View { var body: some View {
Group { Group {
switch selection { switch presentation.selection {
case .general: generalPage case .general: generalPage
case .menuBar: MenuBarSettingsPage(preferences: menuBar, readings: readings())
case .about: aboutPage case .about: aboutPage
} }
} }
.padding(12) .padding(12)
.toolbar { .toolbar {
ToolbarItem(placement: .principal) { ToolbarItem(placement: .principal) {
NeutralTabPicker(title: "settings.title", selection: $selection, NeutralTabPicker(title: "settings.title", selection: $presentation.selection,
options: [(.general, "settings.general"), (.about, "settings.about")]) options: [(.general, "settings.general"), (.menuBar, "settings.menuBar"), (.about, "settings.about")])
} }
.sharedBackgroundVisibility(.hidden) .sharedBackgroundVisibility(.hidden)
} }
@@ -94,6 +97,27 @@ struct AppearanceSettingsView: View {
} }
.padding(.vertical, 8) .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) .formStyle(.grouped)
.padding(.horizontal, 12) .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"
}
}
}
+69
View File
@@ -92,6 +92,75 @@
} }
} }
} }
},
"cpu.kind.efficiencyShort": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "E-cores"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "能效核"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "能效核"
}
}
}
},
"cpu.kind.performanceShort": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "P-cores"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "性能核"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "效能核"
}
}
}
},
"cpu.kind.superShort": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "S-cores"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "超大核"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "超大核"
}
}
}
} }
}, },
"version": "1.0" "version": "1.0"
File diff suppressed because it is too large Load Diff
+23
View File
@@ -1,6 +1,29 @@
{ {
"sourceLanguage" : "en", "sourceLanguage" : "en",
"strings" : { "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" : { "status.hide" : {
"extractionState" : "manual", "extractionState" : "manual",
"localizations" : { "localizations" : {
+2 -1
View File
@@ -17,6 +17,7 @@ struct ChartTooltipPreference: PreferenceKey {
/// Measures the actual localized tooltip, then keeps it inside the card. /// Measures the actual localized tooltip, then keeps it inside the card.
struct ChartTooltipLayer: Layout { struct ChartTooltipLayer: Layout {
let point: CGPoint let point: CGPoint
var minimumY: CGFloat = 0
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
proposal.replacingUnspecifiedDimensions() proposal.replacingUnspecifiedDimensions()
@@ -30,7 +31,7 @@ struct ChartTooltipLayer: Layout {
let x = min(max(10, point.x + 12), max(10, bounds.width - size.width - 10)) let x = min(max(10, point.x + 12), max(10, bounds.width - size.width - 10))
let below = point.y + 10 let below = point.y + 10
let preferredY = below + size.height <= bounds.height - 10 ? below : point.y - size.height - 10 let preferredY = below + size.height <= bounds.height - 10 ? below : point.y - size.height - 10
let y = min(max(10, preferredY), max(10, bounds.height - size.height - 10)) let y = min(max(max(10, minimumY), preferredY), max(10, bounds.height - size.height - 10))
tooltip.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading, proposal: tooltipProposal) tooltip.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading, proposal: tooltipProposal)
} }
} }
+113 -20
View File
@@ -1,13 +1,34 @@
import AppKit import AppKit
import SwiftUI import SwiftUI
/// Bounded static Core Graphics paths. No animation, gradient fill or per-frame work. /// Rate plots share a zero axis and equal positive amplitudes on either side.
nonisolated enum PanelCurveProjection: Equatable {
case fullHeight
case signed
case split(upwardSeries: Int)
func y(value: Double, scale: Double, series: Int, height: Double) -> Double {
let fraction = min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1)))
switch self {
case .signed: return height * (0.5 - 0.5 * min(1, max(-1, value / max(0.0001, scale))))
case .fullHeight: return height * (1 - fraction)
case .split(let upward): return height * (0.6 + (series == upward ? -0.3 : 0.3) * fraction)
}
}
}
/// Bounded lines and per-run area paths. Hover never rebuilds geometry.
struct NativePanelCurve: NSViewRepresentable { struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame let frame: PanelCurveFrame
let colors: [Color] let colors: [Color]
let scales: [Double] let scales: [Double]
let maximumGap: TimeInterval let maximumGap: TimeInterval
var hoveredIndex: Int? = nil var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
var animates = false
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? { func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10, CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -16,7 +37,7 @@ struct NativePanelCurve: NSViewRepresentable {
func makeNSView(context: Context) -> PlotView { PlotView() } func makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) { func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap, view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
hoveredIndex: hoveredIndex)) hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked, projection: projection, animates: animates))
} }
struct Input: Equatable { struct Input: Equatable {
let frame: PanelCurveFrame let frame: PanelCurveFrame
@@ -24,16 +45,25 @@ struct NativePanelCurve: NSViewRepresentable {
let scales: [Double] let scales: [Double]
let maximumGap: TimeInterval let maximumGap: TimeInterval
var hoveredIndex: Int? = nil var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
var animates = false
} }
final class PlotView: NSView { final class PlotView: NSView {
private(set) var input: Input? private(set) var input: Input?
private(set) var pathBuildCount = 0 private(set) var pathBuildCount = 0
let grid = CAShapeLayer() let grid = CAShapeLayer()
let baseline = CAShapeLayer()
let curves = CALayer() let curves = CALayer()
let hoverLine = CAShapeLayer() let hoverLine = CAShapeLayer()
private var hoverDots: [CAShapeLayer] = [] private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = [] private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = [] private var palette: [NSColor] = []
private var drawingFrame: PanelCurveFrame?
private static let slideKey = "trend.slide"
private var plottedBands: [StackedSeries.Band] = []
override var isFlipped: Bool { true } override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil } override func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -43,8 +73,10 @@ struct NativePanelCurve: NSViewRepresentable {
layer?.masksToBounds = true layer?.masksToBounds = true
curves.anchorPoint = .zero curves.anchorPoint = .zero
grid.fillColor = nil; grid.lineWidth = 0.5 grid.fillColor = nil; grid.lineWidth = 0.5
grid.isHidden = true
hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2] hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2]
for child in [grid, curves, hoverLine] { layer?.addSublayer(child) } baseline.fillColor = nil; baseline.lineWidth = 0.5; baseline.isHidden = true
for child in [grid, baseline, curves, hoverLine] { layer?.addSublayer(child) }
setAccessibilityElement(false) setAccessibilityElement(false)
} }
required init?(coder: NSCoder) { nil } required init?(coder: NSCoder) { nil }
@@ -53,17 +85,46 @@ struct NativePanelCurve: NSViewRepresentable {
guard input != value else { return } guard input != value else { return }
let old = input let old = input
let frameChanged = old?.frame != value.frame let frameChanged = old?.frame != value.frame
let slides = value.animates && value.hoveredIndex == nil && window?.isVisible == true
&& frameChanged && old.map { value.frame.follows($0.frame, maximumGap: value.maximumGap) } == true
input = value input = value
if frameChanged || !value.animates || value.hoveredIndex != nil {
curves.removeAnimation(forKey: Self.slideKey)
}
if frameChanged {
drawingFrame = slides ? old.map { value.frame.includingOutgoing(from: $0.frame) } : nil
}
CATransaction.begin(); CATransaction.setDisableActions(true) CATransaction.begin(); CATransaction.setDisableActions(true)
if old?.projection != value.projection { updateBaseline() }
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count) ensureLayers(value.frame.series.count)
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count { updatePalette() } if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap { || old?.filledSeriesCount != value.filledSeriesCount { updatePalette() }
for index in seriesLayers.indices {
seriesLayers[index].root.isHidden = index >= (value.visibleSeriesCount ?? value.frame.series.count)
}
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked || old?.projection != value.projection {
rebuildPaths() rebuildPaths()
} }
updateHover() updateHover()
if slides, let old { slide(from: old.frame, to: value.frame) }
CATransaction.commit() CATransaction.commit()
} }
private func slide(from previous: PanelCurveFrame, to next: PanelCurveFrame) {
guard bounds.width > 0, let a = previous.dates.first, let b = previous.dates.last,
let c = next.dates.first, let d = next.dates.last else { return }
// Map the new geometry onto the old time domain, then reveal the new point.
let span = b.timeIntervalSince(a)
let transform = CGAffineTransform(a: d.timeIntervalSince(c) / span, b: 0, c: 0, d: 1,
tx: c.timeIntervalSince(a) / span * bounds.width, ty: 0)
let animation = CABasicAnimation(keyPath: "transform")
animation.fromValue = NSValue(caTransform3D: CATransform3DMakeAffineTransform(transform))
animation.toValue = NSValue(caTransform3D: CATransform3DIdentity)
animation.duration = 0.35
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
curves.add(animation, forKey: Self.slideKey)
}
private func ensureLayers(_ count: Int) { private func ensureLayers(_ count: Int) {
while seriesLayers.count < count { while seriesLayers.count < count {
let series = SeriesLayer(); seriesLayers.append(series); curves.addSublayer(series.root) let series = SeriesLayer(); seriesLayers.append(series); curves.addSublayer(series.root)
@@ -77,17 +138,31 @@ struct NativePanelCurve: NSViewRepresentable {
private func updatePalette() { private func updatePalette() {
effectiveAppearance.performAsCurrentDrawingAppearance { effectiveAppearance.performAsCurrentDrawingAppearance {
palette = input?.colors.map(NSColor.init) ?? [] palette = input?.colors.map(NSColor.init) ?? []
baseline.strokeColor = NSColor.labelColor.withAlphaComponent(0.12).cgColor
grid.strokeColor = NSColor.labelColor.withAlphaComponent(0.10).cgColor grid.strokeColor = NSColor.labelColor.withAlphaComponent(0.10).cgColor
hoverLine.strokeColor = NSColor.labelColor.withAlphaComponent(0.45).cgColor hoverLine.strokeColor = NSColor.labelColor.withAlphaComponent(0.45).cgColor
guard !palette.isEmpty else { return } guard !palette.isEmpty else { return }
for index in seriesLayers.indices { for index in seriesLayers.indices {
let color = palette[min(index, palette.count - 1)], series = seriesLayers[index] let color = palette[min(index, palette.count - 1)], series = seriesLayers[index]
series.line.strokeColor = color.cgColor; series.points.fillColor = color.cgColor series.line.strokeColor = color.cgColor; series.points.fillColor = color.cgColor
let dark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
series.area.fillColor = index < (input?.filledSeriesCount ?? 0)
? color.withAlphaComponent(dark ? 0.16 : 0.12).cgColor : nil
hoverDots[index].fillColor = color.cgColor hoverDots[index].fillColor = color.cgColor
} }
} }
} }
private func updateBaseline() {
baseline.frame = bounds
baseline.isHidden = input?.projection == .fullHeight || input == nil
let path = CGMutablePath()
let zero = input?.projection.y(value: 0, scale: 1, series: 0, height: bounds.height) ?? 0
path.move(to: CGPoint(x: 0, y: zero))
path.addLine(to: CGPoint(x: bounds.width, y: zero))
baseline.path = path
}
private func updateGrid() { private func updateGrid() {
updateBaseline()
grid.frame = bounds; hoverLine.frame = bounds grid.frame = bounds; hoverLine.frame = bounds
curves.bounds = bounds; curves.position = .zero curves.bounds = bounds; curves.position = .zero
let path = CGMutablePath() let path = CGMutablePath()
@@ -109,18 +184,21 @@ struct NativePanelCurve: NSViewRepresentable {
return return
} }
let domain = PanelCurveFrame.domain(begin: first, end: last) let domain = PanelCurveFrame.domain(begin: first, end: last)
let frame = input.frame let frame = drawingFrame ?? input.frame
plottedBands = input.stacked ? StackedSeries.bands(frame.series, count: frame.dates.count, limit: input.scales.first) : []
for index in frame.series.indices { for index in frame.series.indices {
let series = seriesLayers[index] let series = seriesLayers[index]
series.resize(bounds) series.resize(bounds)
let value = input.scales[min(index, input.scales.count - 1)] let value = input.scales[input.stacked ? 0 : min(index, input.scales.count - 1)]
let scale = value.isFinite && value > 0 ? value : 1 let scale = value.isFinite && value > 0 ? value : 1
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index], maximumGap: input.maximumGap, let upper = input.stacked ? plottedBands[index].upper : frame.series[index]
boundaryDates: frame.boundaryDates, intervals: frame.intervals) let lower = input.stacked ? plottedBands[index].lower : nil
let line = CGMutablePath(), dots = CGMutablePath() let runs = PanelCurveGeometry.runs(dates: frame.dates, values: upper, maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals, lowerValues: lower)
let line = CGMutablePath(), dots = CGMutablePath(), area = CGMutablePath()
for run in runs { for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date), let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) } y: input.projection.y(value: $0.value, scale: scale, series: index, height: bounds.height)) }
guard let start = points.first else { continue } guard let start = points.first else { continue }
if points.count == 1 { if points.count == 1 {
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
@@ -131,9 +209,20 @@ struct NativePanelCurve: NSViewRepresentable {
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y)) segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
} }
line.addPath(segment) line.addPath(segment)
// Close against the matching lower boundary, never against another run or missing component.
let lowerPoints = run.reversed().map { CGPoint(x: bounds.width * domain.position($0.date),
y: input.projection.y(value: $0.lower, scale: scale, series: index, height: bounds.height)) }
let fill = CGMutablePath(); fill.addPath(segment)
if let lowerStart = lowerPoints.first { fill.addLine(to: lowerStart) }
for (a, b) in zip(lowerPoints, lowerPoints.dropFirst()) {
let mid = (a.x + b.x) / 2
fill.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
fill.closeSubpath(); area.addPath(fill)
} }
series.line.path = line series.line.path = line
series.points.path = dots series.points.path = dots
series.area.path = area
} }
} }
private func updateHover() { private func updateHover() {
@@ -145,10 +234,12 @@ struct NativePanelCurve: NSViewRepresentable {
let x = bounds.width * domain.position(input.frame.dates[index]) let x = bounds.width * domain.position(input.frame.dates[index])
let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path
for series in input.frame.series.indices { for series in input.frame.series.indices {
let values = input.frame.series[series] guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue } let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
let scale = input.scales[min(series, input.scales.count - 1)] let plottedIndex = index + (input.stacked ? (drawingFrame?.dates.count ?? input.frame.dates.count) - input.frame.dates.count : 0)
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1)))) guard values.indices.contains(plottedIndex), let value = values[plottedIndex], value.isFinite else { continue }
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
let y = input.projection.y(value: value, scale: scale, series: series, height: bounds.height)
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil) hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
} }
} }
@@ -156,12 +247,14 @@ struct NativePanelCurve: NSViewRepresentable {
let changed = frame.size != size let changed = frame.size != size
super.setFrameSize(size) super.setFrameSize(size)
if changed { if changed {
curves.removeAnimation(forKey: Self.slideKey)
CATransaction.begin(); CATransaction.setDisableActions(true) CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit() updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
} }
} }
override func viewDidMoveToWindow() { override func viewDidMoveToWindow() {
super.viewDidMoveToWindow() super.viewDidMoveToWindow()
if window == nil { curves.removeAnimation(forKey: Self.slideKey) }
CATransaction.begin(); CATransaction.setDisableActions(true) CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit() updatePalette(); CATransaction.commit()
} }
@@ -171,17 +264,17 @@ struct NativePanelCurve: NSViewRepresentable {
updatePalette(); CATransaction.commit() updatePalette(); CATransaction.commit()
} }
private final class SeriesLayer { private final class SeriesLayer {
let root = CALayer(), line = CAShapeLayer(), points = CAShapeLayer() let root = CALayer(), area = CAShapeLayer(), line = CAShapeLayer(), points = CAShapeLayer()
init() { init() {
line.fillColor = nil; line.lineWidth = 1.5; line.lineCap = .round; line.lineJoin = .round line.fillColor = nil; line.lineWidth = 1.4; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(line); root.addSublayer(points) root.addSublayer(area); root.addSublayer(line); root.addSublayer(points)
} }
func resize(_ bounds: CGRect) { func resize(_ bounds: CGRect) {
root.frame = bounds root.frame = bounds
let local = CGRect(origin: .zero, size: bounds.size) let local = CGRect(origin: .zero, size: bounds.size)
line.frame = local; points.frame = local area.frame = local; line.frame = local; points.frame = local
} }
func clear() { line.path = nil; points.path = nil } func clear() { area.path = nil; line.path = nil; points.path = nil }
} }
} }
} }
+18 -1
View File
@@ -1,12 +1,29 @@
import Foundation import Foundation
/// A static render frame follows the bounded sampling history without outgoing points. /// History remains bounded; a rolling plot can draw one outgoing vertex beyond its left edge.
nonisolated struct PanelCurveFrame: Equatable { nonisolated struct PanelCurveFrame: Equatable {
let dates: [Date] let dates: [Date]
let series: [[Double?]] let series: [[Double?]]
let intervals: [TimeInterval] let intervals: [TimeInterval]
let boundaryDates: Set<Date> let boundaryDates: Set<Date>
/// Only adjacent samples from the same timeline can slide into view.
func follows(_ old: Self, maximumGap: TimeInterval) -> Bool {
guard old.dates.count >= 2, let before = old.dates.last, let end = dates.last,
let begin = old.dates.first, begin < before, end > before, !boundaryDates.contains(end),
end.timeIntervalSince(before) <= PanelCurveGeometry.allowedGap(at: dates.count - 1, intervals: intervals, fallback: maximumGap)
else { return false }
return dates.dropLast().elementsEqual(old.dates)
|| (dates.count == old.dates.count && dates.dropLast().elementsEqual(old.dates.dropFirst()))
}
func includingOutgoing(from old: Self) -> Self {
guard dates.first != old.dates.first, let outgoing = old.dates.first else { return self }
return Self(dates: [outgoing] + dates, series: series.enumerated().map { index, values in
[old.series.indices.contains(index) ? old.series[index].first ?? nil : nil] + values
}, intervals: [old.intervals.first ?? 2] + intervals, boundaryDates: boundaryDates)
}
struct Domain { struct Domain {
let begin: TimeInterval let begin: TimeInterval
let end: TimeInterval let end: TimeInterval
+8 -2
View File
@@ -4,6 +4,7 @@ nonisolated enum PanelCurveGeometry {
struct Sample { struct Sample {
let date: Date let date: Date
let value: Double let value: Double
var lower: Double = 0
} }
static func allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval { static func allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval {
@@ -12,7 +13,7 @@ nonisolated enum PanelCurveGeometry {
return interval.isFinite && interval > 0 ? max(5, interval * 2) : fallback return interval.isFinite && interval > 0 ? max(5, interval * 2) : fallback
} }
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = []) -> [[Sample]] { static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = [], lowerValues: [Double?]? = nil) -> [[Sample]] {
var result: [[Sample]] = [] var result: [[Sample]] = []
var run: [Sample] = [] var run: [Sample] = []
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } } func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
@@ -20,7 +21,12 @@ nonisolated enum PanelCurveGeometry {
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > allowedGap(at: index, intervals: intervals, fallback: maximumGap) || dates[index] <= dates[index - 1]) { flush() } if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > allowedGap(at: index, intervals: intervals, fallback: maximumGap) || dates[index] <= dates[index - 1]) { flush() }
// Missing values do not create vertices, but their timestamps can still carry a real break. // Missing values do not create vertices, but their timestamps can still carry a real break.
guard index < values.count, let value = values[index], value.isFinite else { continue } guard index < values.count, let value = values[index], value.isFinite else { continue }
run.append(Sample(date: dates[index], value: value)) var lower = 0.0
if let lowerValues {
guard lowerValues.indices.contains(index), let base = lowerValues[index], base.isFinite else { continue }
lower = base
}
run.append(Sample(date: dates[index], value: value, lower: lower))
} }
flush() flush()
return result return result
+48 -78
View File
@@ -5,10 +5,11 @@ enum TrendValueFormat {
case rate case rate
case bytes case bytes
case memory case memory
case signedWatts
case watts case watts
} }
/// Static curves skip missing vertices, retaining timestamps and explicit sampling breaks. /// Curves skip missing vertices, retaining timestamps and explicit sampling breaks.
struct PanelTrendChart: View { struct PanelTrendChart: View {
let dates: [Date] let dates: [Date]
let first: [Double?] let first: [Double?]
@@ -20,10 +21,8 @@ struct PanelTrendChart: View {
var thirdColor: Color = .purple var thirdColor: Color = .purple
var fourthColor: Color = .yellow var fourthColor: Color = .yellow
var fixedScale: Double? = 1 var fixedScale: Double? = 1
var scaleLabel: String?
var secondSeriesUsesAutonomousScale = false
var firstValueFormat: TrendValueFormat? var firstValueFormat: TrendValueFormat?
var secondValueFormat: TrendValueFormat? var sampleTooltip: ((Int) -> AnyView)?
var firstLabel: LocalizedStringKey = "panel.total" var firstLabel: LocalizedStringKey = "panel.total"
var secondLabel: LocalizedStringKey = "network.upload" var secondLabel: LocalizedStringKey = "network.upload"
var thirdLabel: LocalizedStringKey = "cpu.system" var thirdLabel: LocalizedStringKey = "cpu.system"
@@ -31,12 +30,14 @@ struct PanelTrendChart: View {
var expectedInterval: TimeInterval = 2 var expectedInterval: TimeInterval = 2
var boundaryDates: Set<Date> = [] var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = [] var intervals: [TimeInterval] = []
var plotHeight: CGFloat = PanelStyle.plotHeight var visibleSeriesCount = 1
var showsLegendValues = true var filledSeriesCount: Int? = nil
var stackOrder: [Int] = []
var projection: PanelCurveProjection = .fullHeight
@Environment(\.panelMotionActive) private var active
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1 @State private var retainedScale: Double = 1
@State private var smallSamples = 0 @State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@State private var smallSecondSamples = 0
@State private var hoveredDate: Date? @State private var hoveredDate: Date?
@State private var hoverPoint: CGPoint? @State private var hoverPoint: CGPoint?
@@ -47,11 +48,24 @@ struct PanelTrendChart: View {
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count), intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
boundaryDates: boundaryDates) boundaryDates: boundaryDates)
} }
private var maximum: Double { max(1, (first + second + third + fourth).compactMap { $0 }.filter(\.isFinite).max() ?? 1) } private var renderFrame: PanelCurveFrame {
private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) } let raw = inputFrame
guard !stackOrder.isEmpty else { return raw }
return PanelCurveFrame(dates: raw.dates, series: stackOrder.map { index in
raw.series.indices.contains(index) ? raw.series[index] : Array(repeating: nil, count: raw.dates.count)
}, intervals: raw.intervals, boundaryDates: raw.boundaryDates)
}
private var renderColors: [Color] {
let colors = [color, secondColor, thirdColor, fourthColor]
return stackOrder.isEmpty ? colors : stackOrder.map { colors[min(max(0, $0), colors.count - 1)] }
}
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 scale: Double { max(0.0001, fixedScale ?? retainedScale) } 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 { private var automaticFormat: TrendValueFormat {
if let firstValueFormat { return firstValueFormat } if let firstValueFormat { return firstValueFormat }
if fixedScale == 1 { return .percent } if fixedScale == 1 { return .percent }
@@ -63,71 +77,50 @@ struct PanelTrendChart: View {
guard let hoveredDate else { return dates.count - 1 } guard let hoveredDate else { return dates.count - 1 }
return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) } 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 "--" } guard let value, value.isFinite else { return "--" }
switch format ?? automaticFormat { switch automaticFormat {
case .percent: return MetricFormat.percent(value) case .percent: return MetricFormat.percent(value)
case .rate: return MetricFormat.rate(value) case .rate: return MetricFormat.rate(value)
case .bytes: return MetricFormat.bytes(UInt64(max(0, value))) case .bytes: return MetricFormat.bytes(UInt64(max(0, value)))
case .memory: return MetricFormat.memory(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) case .watts: return MetricFormat.watts(value)
} }
} }
private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil) -> some View { private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View {
HStack(spacing: 3) {
RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7)
Text(label)
if showsLegendValues {
Text(verbatim: formatted(values.last ?? nil, format: format)).monospacedDigit()
}
}.font(PanelStyle.legend).lineLimit(1).minimumScaleFactor(0.8)
}
private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, index: Int) -> some View {
HStack(spacing: 6) { HStack(spacing: 6) {
RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8) RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8)
Text(label) Text(label)
Spacer(minLength: 4) 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 { private func tooltip(index: Int) -> some View {
VStack(alignment: .leading, spacing: 5) { VStack(alignment: .leading, spacing: 3) {
Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary) Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary)
if let sampleTooltip {
sampleTooltip(index)
} else {
tooltipRow(firstLabel, values: first, tint: color, index: index) tooltipRow(firstLabel, values: first, tint: color, index: index)
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, format: secondValueFormat, 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 !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) } if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
} }
.font(.system(size: 10)).padding(8) }
.font(.system(size: 9)).padding(6)
.background { TooltipBackground() } .background { TooltipBackground() }
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2))) .overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
} }
var body: some View { var body: some View {
VStack(spacing: 3) {
HStack(spacing: 10) {
legend(firstLabel, values: first, tint: color)
if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor, format: secondValueFormat) }
if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) }
if !fourth.isEmpty { legend(fourthLabel, values: fourth, tint: fourthColor) }
Spacer(minLength: 0)
}.frame(height: 14)
HStack(spacing: 5) {
VStack(alignment: .trailing) {
Text(verbatim: scaleLabel ?? formatted(scale))
Spacer(minLength: 0)
Text(verbatim: formatted(scale / 2))
Spacer(minLength: 0)
Text(verbatim: "0")
}.font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight)
GeometryReader { proxy in GeometryReader { proxy in
ZStack(alignment: .topLeading) { NativePanelCurve(frame: renderFrame, colors: renderColors,
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor], scales: [scale, scale, scale, scale],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale], maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
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,
animates: active && !reduceMotion)
.contentShape(Rectangle()) .contentShape(Rectangle())
.onContinuousHover { phase in .onContinuousHover { phase in
switch phase { switch phase {
@@ -139,33 +132,14 @@ struct PanelTrendChart: View {
case .ended: hoveredDate = nil; hoverPoint = nil case .ended: hoveredDate = nil; hoverPoint = nil
} }
} }
.clipped()
}.frame(height: plotHeight)
.anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in .anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in
guard let hoverPoint, let index else { return nil } guard let hoverPoint, let index else { return nil }
return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index))) return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index)))
} }
if hasSecondaryScale {
VStack(alignment: .leading) {
Text(verbatim: formatted(secondaryScale, format: .watts))
Spacer(minLength: 0)
Text(verbatim: formatted(secondaryScale / 2, format: .watts))
Spacer(minLength: 0)
Text(verbatim: "0 W")
}.font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 45, height: plotHeight)
} }
} .frame(maxWidth: .infinity, maxHeight: .infinity)
HStack {
if let date = dates.first { Text(date, style: .time) }
Spacer(minLength: 0)
if let date = dates.last { Text(date, style: .time) }
}.font(PanelStyle.legend).foregroundStyle(.secondary).frame(height: 12)
}
.frame(maxWidth: .infinity)
.onAppear { .onAppear {
retainedScale = maximum retainedScale = maximum
retainedSecondScale = secondMaximum
} }
.onChange(of: dates) { _, _ in .onChange(of: dates) { _, _ in
let target = maximum let target = maximum
@@ -174,13 +148,9 @@ struct PanelTrendChart: View {
smallSamples += 1 smallSamples += 1
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 } if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
} else { 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: .combine) .accessibilityElement(children: .ignore)
.accessibilityLabel(Text(firstLabel))
.accessibilityValue(Text(verbatim: formatted(first.last ?? nil)))
} }
} }
+32
View File
@@ -0,0 +1,32 @@
import Foundation
/// Additive components retain their raw values; only render boundaries are cumulative.
nonisolated enum StackedSeries {
struct Band {
var lower: [Double?]
var upper: [Double?]
}
static func bands(_ components: [[Double?]], count: Int, limit: Double? = nil) -> [Band] {
var result = components.map { _ in Band(lower: Array(repeating: nil, count: count), upper: Array(repeating: nil, count: count)) }
guard !components.isEmpty else { return result }
for point in 0..<count {
var values: [Double] = []
for component in components {
guard component.indices.contains(point), let value = component[point], value.isFinite, value >= 0 else { break }
values.append(value)
}
guard values.count == components.count else { continue }
let total = values.reduce(0, +)
guard total.isFinite else { continue }
if let limit, limit.isFinite, limit > 0, total > limit + max(1, limit) * 1e-12 { continue }
var lower = 0.0
for (series, value) in values.enumerated() {
result[series].lower[point] = lower
lower += value
result[series].upper[point] = lower
}
}
return result
}
}
+128 -6
View File
@@ -1,19 +1,141 @@
import AppKit
import SwiftUI import SwiftUI
/// Historical visual speed tiers; they deliberately do not reproduce physical RPM.
nonisolated struct FanRotation {
private(set) var phase: Double = 0
private(set) var speed: Double = 0
private var reference: TimeInterval = 0
static func speed(rpm: Double?, reducedMotion: Bool) -> Double {
guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 }
switch rpm {
case ..<2000: return 90
case ..<4000: return 180
case ..<6000: return 300
default: return 450
}
}
func angle(at time: TimeInterval) -> Double {
(phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360)
}
mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) {
phase = angle(at: time)
reference = time
speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion)
}
}
struct FanSpeedIndicator: View { struct FanSpeedIndicator: View {
let title: Text let title: Text
let rpm: Double? let rpm: Double?
var isActive = true
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View { var body: some View {
HStack(spacing: 5) { HStack(spacing: 3) {
Image(systemName: "fanblades.fill") FanRotor(rpm: rpm, isActive: isActive, reduceMotion: reduceMotion)
.foregroundStyle(.secondary) .frame(width: 11, height: 11).accessibilityHidden(true)
.frame(width: 14, height: 14).accessibilityHidden(true)
title.foregroundStyle(.secondary) title.foregroundStyle(.secondary)
Spacer(minLength: 2)
MetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM") MetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.monospacedDigit().fontWeight(.medium) .monospacedDigit().fontWeight(.medium)
} }
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) .font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9)
}
}
/// Only this native icon animates; sampling updates do not create display timers.
struct FanRotor: NSViewRepresentable {
let rpm: Double?
let isActive: Bool
let reduceMotion: Bool
func makeNSView(context: Context) -> RotorView { RotorView() }
func updateNSView(_ view: RotorView, context: Context) {
view.configure(rpm: rpm, active: isActive, reducedMotion: reduceMotion)
}
static func dismantleNSView(_ view: RotorView, coordinator: ()) { view.stop() }
final class RotorView: NSView {
let rotorLayer = CALayer()
private var artworkSize = CGSize.zero
static let animationKey = "fan.rotation"
private var rpm: Double?
private var active = false
private var reducedMotion = false
private(set) var rotation = FanRotation()
init() {
super.init(frame: .zero)
wantsLayer = true
rotorLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
rotorLayer.contentsGravity = .resizeAspect
layer?.addSublayer(rotorLayer)
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(rpm: Double?, active: Bool, reducedMotion: Bool) {
self.rpm = rpm; self.active = active; self.reducedMotion = reducedMotion
refresh()
}
func stop() {
active = false; refresh()
rotorLayer.removeAnimation(forKey: Self.animationKey)
}
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); refresh() }
override func layout() {
super.layout()
CATransaction.begin(); CATransaction.setDisableActions(true)
rotorLayer.bounds = CGRect(origin: .zero, size: bounds.size)
rotorLayer.position = CGPoint(x: bounds.midX, y: bounds.midY)
if artworkSize != bounds.size { updateArtwork() }
CATransaction.commit()
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance(); updateArtwork()
}
override func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties(); updateArtwork()
}
private func updateArtwork() {
artworkSize = bounds.size
guard bounds.width > 0, bounds.height > 0 else { return }
effectiveAppearance.performAsCurrentDrawingAppearance {
let symbol = NSImage(systemSymbolName: "fanblades.fill", accessibilityDescription: nil)
let artwork = NSImage(size: bounds.size, flipped: false) { rect in
symbol?.draw(in: rect)
NSColor.secondaryLabelColor.setFill(); rect.fill(using: .sourceIn)
return true
}
CATransaction.begin(); CATransaction.setDisableActions(true)
rotorLayer.contentsScale = window?.backingScaleFactor ?? 2
rotorLayer.contents = artwork.cgImage(forProposedRect: nil, context: nil, hints: nil)
CATransaction.commit()
}
}
private func refresh() {
let readable = active && window != nil ? rpm : nil
let speed = FanRotation.speed(rpm: readable, reducedMotion: reducedMotion)
guard speed != rotation.speed else { return }
rotation.update(rpm: readable, reducedMotion: reducedMotion, at: CACurrentMediaTime())
let radians = rotation.phase * .pi / 180
CATransaction.begin(); CATransaction.setDisableActions(true)
rotorLayer.removeAnimation(forKey: Self.animationKey)
rotorLayer.transform = CATransform3DMakeRotation(radians, 0, 0, 1)
if speed > 0 {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = radians; animation.toValue = radians + .pi * 2
animation.duration = 360 / speed
animation.repeatCount = .infinity
animation.timingFunction = CAMediaTimingFunction(name: .linear)
rotorLayer.add(animation, forKey: Self.animationKey)
}
CATransaction.commit()
}
} }
} }
+2 -1
View File
@@ -5,6 +5,7 @@ struct IntervalControl: View {
@Binding var milliseconds: Int @Binding var milliseconds: Int
var range: ClosedRange<Int> = 500...1_800_000 var range: ClosedRange<Int> = 500...1_800_000
var step = 100 var step = 100
var fieldWidth: CGFloat = 64
@State private var text = "" @State private var text = ""
@FocusState private var focused: Bool @FocusState private var focused: Bool
@@ -13,7 +14,7 @@ struct IntervalControl: View {
TextField("sampling.seconds", text: $text) TextField("sampling.seconds", text: $text)
.labelsHidden() .labelsHidden()
.textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing) .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing)
.frame(width: 64).focused($focused) .frame(width: fieldWidth).focused($focused)
.onChange(of: text) { _, value in .onChange(of: text) { _, value in
if let seconds = Double(value.replacingOccurrences(of: ",", with: ".")), seconds.isFinite, if let seconds = Double(value.replacingOccurrences(of: ",", with: ".")), seconds.isFinite,
seconds >= Double(range.lowerBound) / 1000, seconds <= Double(range.upperBound) / 1000 { seconds >= Double(range.lowerBound) / 1000, seconds <= Double(range.upperBound) / 1000 {
@@ -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,21 +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
private var fraction: Double { value.isFinite ? min(1, max(0, value)) : 0 }
var body: some View {
GeometryReader { proxy in
ZStack(alignment: .leading) {
Capsule().fill(color.opacity(0.15))
Capsule().fill(color).frame(width: proxy.size.width * fraction)
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(Capsule())
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}
}
+22 -2
View File
@@ -1,9 +1,15 @@
import SwiftUI import SwiftUI
/// Metrics change only when a new sample is published; no numeric transition or spring. extension EnvironmentValues {
@Entry var panelMotionActive: Bool = true
}
struct MetricText: View { struct MetricText: View {
let value: String let value: String
var body: some View { Text(verbatim: value).monospacedDigit() }
var body: some View {
Text(verbatim: value).monospacedDigit()
}
} }
struct PanelCardBackground: ViewModifier { struct PanelCardBackground: ViewModifier {
@@ -13,3 +19,17 @@ struct PanelCardBackground: ViewModifier {
content.background(RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard"))) content.background(RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard")))
} }
} }
struct InlineMetric: View {
let title: LocalizedStringKey
let value: String
init(_ title: LocalizedStringKey, _ value: String) { self.title = title; self.value = value }
var body: some View {
HStack(spacing: 4) {
Text(title).foregroundStyle(.secondary)
MetricText(value: value).fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1)
}
}
+6 -21
View File
@@ -1,23 +1,14 @@
import SwiftUI import SwiftUI
/// Shared roles for the compact monitoring panel. Micro charts keep their own 8pt role. /// Shared roles for auxiliary labels and native panel controls.
enum PanelStyle { enum PanelStyle {
static let title = Font.system(size: 13, weight: .semibold) static let title = Font.system(size: 13, weight: .semibold)
static let label = Font.system(size: 10) static let label = Font.system(size: 10)
static let value = Font.system(size: 10, weight: .medium) static let value = Font.system(size: 10, weight: .medium)
static let legend = Font.system(size: 9) static let legend = Font.system(size: 9)
static let padding: CGFloat = 10 static let padding: CGFloat = 10
static let gap: CGFloat = 8 static let gap: CGFloat = 6
static let titleHeight: CGFloat = 20 static let titleHeight: CGFloat = 20
static let plotHeight: CGFloat = 48
}
struct CardSeparator: View {
var body: some View {
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1)
.padding(.vertical, 2)
.accessibilityHidden(true)
}
} }
struct CardField<Content: View>: View { struct CardField<Content: View>: View {
@@ -37,15 +28,8 @@ struct CardField<Content: View>: View {
struct CardSurface: ViewModifier { struct CardSurface: ViewModifier {
func body(content: Content) -> some View { func body(content: Content) -> some View {
content.modifier(PanelCardBackground(radius: 10)) content.modifier(PanelCardBackground(radius: ResourceCardMetrics.radius))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14))) .overlay(RoundedRectangle(cornerRadius: ResourceCardMetrics.radius).strokeBorder(.primary.opacity(0.06)))
}
}
struct CardInset: ViewModifier {
func body(content: Content) -> some View {
content.padding(.horizontal, 8).padding(.vertical, 5)
.background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6))
} }
} }
@@ -54,6 +38,7 @@ struct CapacityBar: View {
let values: [Double] let values: [Double]
let colors: [Color] let colors: [Color]
let total: Double let total: Double
var height: CGFloat = 8
var body: some View { var body: some View {
GeometryReader { bounds in GeometryReader { bounds in
@@ -65,7 +50,7 @@ struct CapacityBar: View {
} }
.clipShape(Capsule()) .clipShape(Capsule())
} }
.frame(height: 8) .frame(height: height)
.accessibilityHidden(true) .accessibilityHidden(true)
} }
} }
+129 -51
View File
@@ -1,82 +1,64 @@
import SwiftUI import SwiftUI
struct ResourceCard<Content: View>: View { enum CardChartPlacement {
case background
case belowDetails
}
/// One native host owns the text, chart and hover presentation.
struct ResourceCard<Chart: View, Content: View>: View {
let title: LocalizedStringKey let title: LocalizedStringKey
let symbol: String let symbol: String
let color: Color let color: Color
let value: String let value: String
var companionIcon: (symbol: String, color: Color)? = nil
var secondaryValue: String? = nil var secondaryValue: String? = nil
var valueColor: Color? = nil var valueColor: Color? = nil
var secondaryValueColor: Color? = nil var secondaryValueColor: Color? = nil
var titleBadge: String? = nil
var status: String? = nil var status: String? = nil
var statusWarning = false var statusWarning = false
var warningText: Text? = nil var warningText: Text? = nil
var detail: String? = nil var detail: String? = nil
var detailColor: Color? = nil var detailColor: Color? = nil
var detailHelp: String? = nil var detailHelp: String? = nil
var headerAccessory: AnyView? = nil
var chartPlacement: CardChartPlacement = .belowDetails
@ViewBuilder var chart: () -> Chart
@ViewBuilder var content: () -> Content @ViewBuilder var content: () -> Content
@Environment(\.colorScheme) private var colorScheme
var body: some View { var body: some View { NativeContentHost(content: cardBody) }
NativeContentHost(content: cardBody)
}
private var cardBody: some View { private var cardBody: some View {
GeometryReader { bounds in GeometryReader { bounds in
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
HStack(alignment: .center, spacing: 6) { foreground
Label { .padding(.horizontal, ResourceCardMetrics.padding)
Text(title).foregroundStyle(statusWarning ? .red : .primary) .padding(.top, ResourceCardMetrics.padding)
} icon: { if chartPlacement == .belowDetails {
Image(systemName: symbol).frame(width: 16, height: 16).foregroundStyle(statusWarning ? .red : color) chart().frame(maxWidth: .infinity, maxHeight: .infinity).clipped()
}.font(PanelStyle.title).fixedSize()
if let status {
Text(verbatim: status)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(statusWarning ? .red : color)
.padding(.horizontal, 6).frame(height: 16)
.background((statusWarning ? Color.red : color).opacity(0.14), in: Capsule())
if let warningText {
warningText
.font(.system(size: 10)).foregroundStyle(.red).lineLimit(1)
} }
} }
if let detail {
Text(verbatim: detail)
.font(.system(size: 10, weight: .medium)).foregroundStyle(detailColor ?? .secondary)
.padding(.horizontal, 6).frame(height: 16)
.background((detailColor ?? .primary).opacity(detailColor == nil ? 0.06 : 0.14), in: Capsule())
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.help(Text(verbatim: detailHelp ?? detail))
.accessibilityLabel(Text(verbatim: detailHelp ?? detail))
}
Spacer(minLength: 0)
HStack(alignment: .center, spacing: 6) {
MetricText(value: value)
.font(PanelStyle.title)
.foregroundStyle(valueColor ?? color)
if let secondaryValue {
MetricText(value: secondaryValue).font(PanelStyle.title)
.foregroundStyle(secondaryValueColor ?? color)
}
}.foregroundStyle(color).lineLimit(1)
}
.frame(height: PanelStyle.titleHeight)
VStack(alignment: .leading, spacing: 4) {
content()
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
.font(PanelStyle.label)
.padding(PanelStyle.padding)
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading) .frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
.background {
if chartPlacement == .background { chart() }
}
.background(Color("PanelCard"))
.clipShape(.rect(cornerRadius: ResourceCardMetrics.radius))
.overlay(RoundedRectangle(cornerRadius: ResourceCardMetrics.radius).strokeBorder(.primary.opacity(colorScheme == .dark ? 0.06 : 0.025)))
.background {
RoundedRectangle(cornerRadius: ResourceCardMetrics.radius)
.fill(Color("PanelCard"))
.shadow(color: .black.opacity(colorScheme == .dark ? 0.12 : 0.05), radius: 4, x: 0, y: 1)
}
} }
.modifier(CardSurface())
.overlayPreferenceValue(ChartTooltipPreference.self) { tooltip in .overlayPreferenceValue(ChartTooltipPreference.self) { tooltip in
GeometryReader { proxy in GeometryReader { proxy in
if let tooltip { if let tooltip {
let plot = proxy[tooltip.plot] let plot = proxy[tooltip.plot]
ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y)) { ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y),
minimumY: ResourceCardMetrics.tooltipMinimumY) {
tooltip.content.fixedSize(horizontal: false, vertical: true) tooltip.content.fixedSize(horizontal: false, vertical: true)
} }
.frame(width: proxy.size.width, height: proxy.size.height) .frame(width: proxy.size.width, height: proxy.size.height)
@@ -86,4 +68,100 @@ struct ResourceCard<Content: View>: View {
.accessibilityHidden(true) .accessibilityHidden(true)
} }
} }
private var foreground: some View {
VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
header
HStack(alignment: .firstTextBaseline, spacing: 6) {
MetricHeadline(value: value, compact: secondaryValue != nil, color: valueColor ?? .primary)
if let secondaryValue {
MetricHeadline(value: secondaryValue, compact: true, color: secondaryValueColor ?? .primary)
}
}
.frame(height: ResourceCardMetrics.headlineHeight, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
content()
}
.font(.system(size: ResourceCardMetrics.auxiliarySize))
.fixedSize(horizontal: false, vertical: true)
}
private var header: some View {
HStack(spacing: 6) {
Label {
Text(title).foregroundStyle(statusWarning ? .red : .primary)
} icon: {
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 {
Text(verbatim: titleBadge)
.font(.system(size: 9, weight: .semibold)).monospacedDigit()
.foregroundStyle(.secondary)
.padding(.horizontal, 5).frame(height: 14)
.background(.primary.opacity(0.08), in: Capsule())
.fixedSize()
}
Spacer(minLength: 4)
if let status {
MetricText(value: status)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(statusWarning ? .red : .secondary)
.help(warningText ?? Text(verbatim: status))
.accessibilityLabel(warningText.map { Text("\(status) \($0)") } ?? Text(verbatim: status))
}
if let detail {
Text(verbatim: detail)
.font(.system(size: 10, weight: .medium)).foregroundStyle(detailColor ?? .secondary)
.padding(.horizontal, 5).frame(height: 14)
.background((detailColor ?? .primary).opacity(0.10), in: Capsule())
.lineLimit(1)
.help(Text(verbatim: detailHelp ?? detail))
.accessibilityLabel(Text(verbatim: detailHelp ?? detail))
}
headerAccessory
}
.lineLimit(1)
.frame(height: ResourceCardMetrics.titleHeight)
}
}
/// A preformatted value keeps its unit smaller without changing metric semantics.
private struct MetricHeadline: View {
let value: String
let compact: Bool
let color: Color
private var direction: Character? { value.first.flatMap { $0 == "↓" || $0 == "↑" ? $0 : nil } }
private var parts: [Substring] {
let number = direction == nil ? value : String(value.dropFirst()).trimmingCharacters(in: .whitespaces)
if number.hasSuffix("%") { return [number.dropLast(), "%"] }
return number.split(separator: " ", maxSplits: 1)
}
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 2) {
if let direction {
Image(systemName: direction == "↓" ? "arrow.down" : "arrow.up")
.font(.system(size: 12, weight: .medium)).foregroundStyle(color)
}
MetricText(value: parts.first.map(String.init) ?? value)
.font(.system(size: compact ? 16 : 28, weight: .semibold))
if parts.count > 1 {
MetricText(value: String(parts[1]))
.font(.system(size: compact ? 10 : 12, weight: .medium))
.foregroundStyle(Color.primary.opacity(0.8))
}
}
.monospacedDigit().foregroundStyle(.primary)
.lineLimit(1).minimumScaleFactor(0.75)
.frame(maxWidth: .infinity, alignment: .leading)
.help(Text(verbatim: value))
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(verbatim: value))
}
} }
@@ -0,0 +1,15 @@
import CoreGraphics
/// Compact native geometry: card width and height are 2/3 of the first implementation.
nonisolated enum ResourceCardMetrics {
static let preferredWidth: CGFloat = 308 * 2 / 3
static let minimumHeight: CGFloat = 176
static let padding: CGFloat = 10
static let radius: CGFloat = 16
static let titleHeight: CGFloat = 16
static let headlineHeight: CGFloat = 34
static let auxiliarySize: CGFloat = 10
static let auxiliaryHeight: CGFloat = 16
static let gap: CGFloat = 4
static let tooltipMinimumY: CGFloat = 68
}
+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 let stopped = store.history.samples
precondition(PanelCurveGeometry.runs(dates: stopped.map(\.date), values: stopped.map(\.memory), precondition(PanelCurveGeometry.runs(dates: stopped.map(\.date), values: stopped.map(\.memory),
boundaryDates: Set(stopped.filter(\.breakBefore).map(\.date)), intervals: stopped.map(\.expectedInterval)).count == 2) 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() store.togglePause()
print("PASS: disabling background recording still stops sampling and preserves the real gap") 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")
}
}
+13 -8
View File
@@ -9,15 +9,15 @@ import SwiftUI
if let first = rows.first, let last = rows.last { if let first = rows.first, let last = rows.last {
precondition(last > 0 && first - last <= 1) precondition(last > 0 && first - last <= 1)
let columns = rows.max()! let columns = rows.max()!
let cellWidth = (width - Double(columns - 1) * 6) / Double(columns) let cellWidth = (width - Double(columns - 1) * 3) / Double(columns)
precondition(cellWidth >= 16, "Core text must fit a readable cell instead of being forced into three rows") precondition(cellWidth >= 7, "Each real core needs its own visible meter cell")
} }
} }
} }
precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 430) == [9, 9]) precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 430) == [18])
precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 280) == [9, 9]) precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 280) == [18])
precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [16, 16]) precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [32])
precondition(CPUCoreGridLayout.rowCounts(count: 48, width: 430) == [16, 16, 16]) precondition(CPUCoreGridLayout.rowCounts(count: 48, width: 430) == [24, 24])
for count in [0, 1, 4, 8, 14, 18, 24, 32, 48, 128] { for count in [0, 1, 4, 8, 14, 18, 24, 32, 48, 128] {
let kinds = Dictionary(uniqueKeysWithValues: (0..<count).map { ($0, $0 < count / 3 ? CPUCoreTopology.Kind.efficiency : .performance) }) let kinds = Dictionary(uniqueKeysWithValues: (0..<count).map { ($0, $0 < count / 3 ? CPUCoreTopology.Kind.efficiency : .performance) })
let groups = CPUCoreGrid.groups(count: count, kinds: kinds) let groups = CPUCoreGrid.groups(count: count, kinds: kinds)
@@ -25,7 +25,8 @@ import SwiftUI
for width in [120.0, 280.0, 380.0, 800.0] { for width in [120.0, 280.0, 380.0, 800.0] {
let widths = CPUCoreGrid.groupWidths(groups: groups, width: width) let widths = CPUCoreGrid.groupWidths(groups: groups, width: width)
precondition(widths.allSatisfy { $0 >= 0 && $0.isFinite }) precondition(widths.allSatisfy { $0 >= 0 && $0.isFinite })
precondition(widths.reduce(0, +) <= width + 0.001) precondition(widths.allSatisfy { $0 <= width })
if !groups.isEmpty { precondition(abs(widths.reduce(0, +) + Double(groups.count - 1) * 8 - width) < 1e-9) }
for (group, groupWidth) in zip(groups, widths) { for (group, groupWidth) in zip(groups, widths) {
let rows = CPUCoreGridLayout.rowCounts(count: group.count, width: groupWidth) let rows = CPUCoreGridLayout.rowCounts(count: group.count, width: groupWidth)
precondition(rows.reduce(0, +) == group.count) precondition(rows.reduce(0, +) == group.count)
@@ -36,6 +37,10 @@ import SwiftUI
precondition(CPUCoreGridLayout.rowCounts(count: 128, width: width).reduce(0, +) == 128) precondition(CPUCoreGridLayout.rowCounts(count: 128, width: width).reduce(0, +) == 128)
} }
precondition(CPUCoreGrid.groups(count: 3, kinds: [0: .efficiency]).count == 2) precondition(CPUCoreGrid.groups(count: 3, kinds: [0: .efficiency]).count == 2)
print("PASS: balanced core rows at multiple widths and counts") let m4 = CPUCoreGrid.groups(count: 14, kinds: Dictionary(uniqueKeysWithValues:
(0..<14).map { ($0, $0 < 4 ? CPUCoreTopology.Kind.efficiency : .performance) }))
let widths = CPUCoreGrid.groupWidths(groups: m4, width: 185)
precondition(zip(m4, widths).map { CPUCoreGridLayout.rowCounts(count: $0.count, width: $1) } == [[4], [10]])
print("PASS: compact per-core meters with intact identities and bounded wrapping at multiple widths/counts")
} }
} }
+2
View File
@@ -6,6 +6,8 @@ import Foundation
precondition(!CPUTemperatureMonitor.isHighTemperature(nil)) precondition(!CPUTemperatureMonitor.isHighTemperature(nil))
precondition(!CPUTemperatureMonitor.isHighTemperature(89.9)) precondition(!CPUTemperatureMonitor.isHighTemperature(89.9))
precondition(CPUTemperatureMonitor.isHighTemperature(90)) 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() { if let temperature = CPUTemperatureMonitor().sample() {
precondition(temperature > 0 && temperature < 150) precondition(temperature > 0 && temperature < 150)
} }

Some files were not shown because too many files have changed in this diff Show More