14 Commits
Author SHA1 Message Date
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
87 changed files with 3004 additions and 683 deletions
+7 -7
View File
@@ -1,18 +1,18 @@
# Kymo
Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点击打开概览 / 进程双页面板,每次打开默认进入概览。
Kymo 是 macOS 菜单栏资源监控工具。菜单栏以竖条显示 CPU、GPU、内存和磁盘占用,以两行文字显示上传和下载速率。点击状态项打开资源卡片与进程同页的监控面板。
## 当前功能
- CPU:总占用、用户态与系统态趋势、逐核数值与短条、温度;设备信息与开机时间位于公共底栏。
- GPU:总占用与 Renderer / Tiler 趋势、核心数、温度和风扇转速。
- CPU:总占用、用户态与系统态趋势、按核型分组的逐核单元与悬浮数值、温度;设备信息与开机时间位于公共底栏。
- GPU:总占用、渲染器与分块器实时百分比和独立趋势,标题后的核心数胶囊、温度和风扇转速。
- 内存:已用与总量、应用 / 联动 / 压缩分类、缓存、可用量、压力与 Swap。
- 存储:主目录所在卷容量、块设备读写速率、各本地卷容量、可读取的 SMART 寿命与通电时间。
- 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计。
- 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计;确认无电池时显示传感器整机即时功率及 W 趋势。
- 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 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 和关于信息。
部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;耗电进程显示系统归属的 CPU 能量区间平均功率,注明可读覆盖范围,不代表完整应用总耗电。指标口径和限制见[监控指标](docs/monitoring.md)。
@@ -26,7 +26,7 @@ open kymo.xcodeproj
xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build
```
在 Xcode 中运行 `kymo`。平时仅显示菜单栏图标,打开设置时临时显示 Dock 图标。左键图标切换面板,右键打开快捷菜单。
在 Xcode 中运行 `kymo`。平时通过菜单栏状态项操作,打开设置时临时显示 Dock 图标。左键状态项切换面板,右键打开快捷菜单。
## 文档与协作
+5
View File
@@ -3,6 +3,7 @@ import Foundation
private actor CPUTemperatureReader {
private let monitor = CPUTemperatureMonitor()
private let gpuMonitor = CPUTemperatureMonitor(zone: .gpu)
func sampleSystemPower() -> Double? { monitor.sampleSystemPower() }
func sampleFans() -> [Double?]? { monitor.sampleFans() }
func sampleGPU() -> Double? { gpuMonitor.sample() }
@@ -14,6 +15,10 @@ private actor CPUTemperatureReader {
final class SMARTService: NSObject, SMARTServiceProtocol {
private let temperatureReader = CPUTemperatureReader()
func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void) {
Task { reply(await temperatureReader.sampleSystemPower().map(NSNumber.init(value:))) }
}
func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) {
Task {
+4 -1
View File
@@ -1,6 +1,6 @@
# 项目文档
本目录只描述当前源码实现、维护方式和验证边界。历史方案与过程报告通过 Git 历史查询。
本目录记录当前源码实现、维护方式、验证边界,以及明确标注为未实施的设计稿。历史方案与过程报告通过 Git 历史查询。
| 文档 | 内容 |
| --- | --- |
@@ -9,5 +9,8 @@
| [开发指南](development.md) | 构建、修改入口、本地化和诊断参数 |
| [测试与验证](testing.md) | 统一检查入口、覆盖范围、实际交互与验收边界 |
| [测试分发](free-test-distribution.md) | 本地 Release 打包、签名与安装支持范围 |
| [UI 设计规范](ui-design-standard.md) | 单页布局、卡片尺寸、字体、颜色、堆叠背景、风扇动效与信息契约 |
| [菜单栏动态指标](menu-bar-metrics-plan.md) | 设计图、勾选与预览同步、采样需求及验收结果 |
| [卡片背景趋势设计稿](designs/card-background-trends-v1/README.md) | 已采纳的浅色 / 深色风格参考,具体实现以设计规范和代码为准 |
修改实现时直接更新相应主题;大型变更的临时方案按 [AGENTS.md](../AGENTS.md) 存放在本目录,完成后将有效结论归入主题文档并清理失效记录。
+23 -17
View File
@@ -5,14 +5,14 @@
| 位置 | 当前职责 |
| --- | --- |
| `kymo/App` | AppKit 入口、生命周期、依赖装配、主菜单和 SwiftUI Settings 场景 |
| `kymo/Features/MenuBar` | 状态项、监控 NSPanel、概览卡片、进程表、业务展示投影与本地验证驱动 |
| `kymo/Features/Settings` | 通用 / 关于设置页、窗口焦点和 Dock 生命周期 |
| `kymo/Features/MenuBar` | 状态项、监控 NSPanel、资源卡片、进程表、业务展示投影与本地验证驱动 |
| `kymo/Features/Settings` | 通用 / 菜单栏 / 关于设置页、窗口焦点和 Dock 生命周期 |
| `kymo/Core/Monitors` | 系统采样、报告解析与 SystemSampler actor |
| `kymo/Core/Services` | MetricsStore、偏好、XPC 客户端、网络地址、保持唤醒与诊断 |
| `kymo/Core/Models` / `Extensions` | 指标、进程身份、有界历史 / 格式化 |
| `kymo/UI` | 无业务副作用的卡片、图表、控件、外观与本地化宿主 |
| `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 仅表示展示请求,不持有窗口。
@@ -20,30 +20,32 @@ App 装配依赖,方向为 Features → UI → Core → 系统 API。Features
入口 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 可见;完全遮挡降级采样而保留内容及交互状态。
MenuBarPreferences 在 UserDefaults 保存勾选集合,首次全选,空集保留。单项和批量选择均一次写入整组,只在空选与有选项之间切换时通知采样需求变化。App 将同一读取闭包注入设置页和状态项。闭包从当前 MetricsSnapshot 生成 MenuBarReading,UI 的 MenuBarMetricStrip 在两处绘制四项竖条占用及独立上下行文本。状态按钮负责点击与辅助功能,绘图子视图透传命中。取消全部后恢复原品牌图标;系统空间不足可能隐藏状态项,此时从 Finder 或 Spotlight 再次打开 Kymo 可进入设置。
设置窗口打开时转为 regular 模式并恢复焦点,SettingsWindowLifecycle 在关闭后恢复 accessory。关闭最后一个窗口不退出应用;退出时清理状态项、窗口、通知和保持唤醒断言。
## 采样、状态与并发
```text
系统 API → SystemSampler actor → MetricsSnapshot → MetricsStore(MainActor)
│ ├─ snapshot → 概览
│ ├─ snapshot → 资源卡片 / 设置预览 / 状态项
├─ 慢任务缓存 ├─ processSnapshot / energy → 进程表
└─ 单在途进程任务 └─ MetricHistory → 趋势图
SMARTService(XPC)→ 只读客户端 → 慢缓存 / 进程任务
实际可见性、页面需求、睡眠与偏好 → MetricsStore 调度
SMARTService(XPC)→ 只读客户端 → 整机功率 / 慢缓存 / 进程任务
实际可见性、详情需求、睡眠与偏好 → 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 派生。
@@ -55,23 +57,27 @@ SystemSampler actor 持有差分基线。CPU / 内存 Mach 查询取得的 host
## 展示与本地状态
ResourceCard 通过 NativeContentHost 使用固定尺寸的独立 NSHostingView,完整传递字体、颜色、语言及外观环境;更新沿用挂载身份,卸载清空子宿主内容。图表锚点和提示层在同一卡片宿主内处理。NativePanelCurve 绘制静态曲线、网格和悬浮标记,只在数据、几何或外观变化时更新。数字和进度条直接展示最终值;不创建应用自定义动画、面积渐变、遮罩、背景模糊或装饰阴影。
ResourceCard 通过 NativeContentHost 使用固定尺寸的独立 NSHostingView,传递字体、颜色、语言及外观环境;更新沿用挂载身份,卸载清空子宿主内容。CPU、GPU、内存、电池采用整卡背景图,卡片顶边对应 100% 或物理内存总量,底边对应零。存储、网络与无电池时的整机功率图使用详情下方的剩余高度。辅助信息主要为 10pt / 16pt 行高,内存和存储详情通过 ViewThatFits 按信息组换行,默认卡片仍为 176pt 高。统一 16pt 圆角、10pt 前景内边距和静态轻阴影,图表锚点和提示在同一宿主内处理;不显示常驻图例、数值坐标轴、网格或起止时间。
概览与设置共享 NeutralTabPicker,使用静态 AppKit 按钮组;保留 tabGroup / tabButton 语义、选中值与键盘导航。绑定仅传递选择,页面和采样生命周期由上层负责。
StackedSeries 仅在渲染时构建累计上下边界:CPU 自下而上为系统 / 用户,内存为应用 / 联动 / 压缩。GPU 同轴绘制总占用、渲染器、分块器三条独立曲线,仅总占用填色。标题后的胶囊显示驱动报告的核心数,正文显示两个阶段读数。任一必要分量缺失或无效时不构造部分总量,原始历史不变。NativePanelCurve 按连续段在匹配的上下边界间闭合面积,保留真实断点;悬浮使用缓存累计边界定位,而提示读取原始分量。有内置电池绘制电量;仅在 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 与数据边界
主应用启用 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 断开尚不保证取消已进入服务的报告任务。
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)。
+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 单独复核。
- 清理本轮隔离应用、容器、截图、脚本、日志、检查崩溃报告及临时构建。真实鼠标悬浮 / 右键菜单手感、多屏及长期能耗仍未完成本轮实测。
@@ -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 |
| 状态项 / 窗口 / 布局 | MenuPanelController.swift、PanelLayout.swift、PanelWindowObserver.swift |
| 概览 | MenuPanelView.swift 及 ResourceCards / Network 扩展 |
| 单页资源布局 | MenuPanelView.swift 及 ResourceCards / Network 扩展 |
| 进程 | ProcessTableView.swift、ProcessTableProjection.swift、NativeProcessTable.swift |
| 采样 | MetricsStore.swift、SystemSampler.swift |
| 设置 | AppearanceSettingsView.swift、SettingsWindowLifecycle.swift |
通常启动仅显示菜单栏图标;打开设置时临时显示 Dock 图标。面板底栏修改可见采样间隔,通用设置控制后台趋势与后台间隔。概览和进程的按页需求由 App 转为 Core 布尔开关。
启动后按选择显示菜单栏指标,取消全部时显示品牌图标;打开设置时临时显示 Dock 图标。面板底栏修改可见采样间隔,菜单栏指标共用面板刷新间隔,通用设置控制无实时展示需求时的后台趋势与后台间隔。App 同时启用 Core 的进程与慢指标需求,由实际可见性、暂停与睡眠控制执行。
颜色与图片放入 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_PAGE=processes | 每轮打开后进入进程页 |
| KYMO_AUDIT_CAPTURE=1 | 第一轮打开 10 秒后输出本应用面板 PNG 的 JSON 事件 |
| KYMO_AUDIT_CAPTURE=1 | 第一轮打开 10 秒后输出本应用面板 PNG 的 JSON 事件;与 INTERACTIVE / SIZE 组合时截取对应视口 |
| KYMO_AUDIT_INTERACTIVE=1 | 打开固定面板供人工 / UI 工具操作,不自动退出 |
| KYMO_AUDIT_SIZE=480x500 | 交互模式限制测试视口,不覆盖自动尺寸;最小 480×360pt |
| KYMO_AUDIT_SIZE=480x500 | 交互模式限制测试视口,不覆盖自动尺寸;最小 360×360pt |
| KYMO_XPC_AUDIT=1 | 运行请求重复 / 并发完成、超时及取消检查后退出 |
截图来自本应用 contentView,不采集桌面。生命周期驱动不证明菜单栏鼠标或 AX 事件已投递。tools/ 中 GPU 能力、负载和驱动调查程序不参与产品构建,也不代表已实现功能;使用前阅读对应入口。
+2 -2
View File
@@ -1,6 +1,6 @@
# Kymo 免费测试包
当前版本为 **1.2(构建 14)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。
当前版本为 **1.3(构建 15)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。
## 构建与校验
@@ -22,7 +22,7 @@ SHA-256 核对内容一致性,不等同于 Apple 身份认证;校验值应
工程最低 macOS 27.0;实际产物架构由打包输出决定。该工具生成未公证的本地 ad-hoc 签名包,没有 Developer ID 分发身份,不上传、不公证、不修改系统安全策略。
解压后安装完整 kymo.app,先退出旧版再启动新版本;不要单独提取可执行文件或混搭内嵌 XPC。应用通常仅显示菜单栏图标,设置窗口打开时才显示 Dock 图标。
解压后安装完整 kymo.app,先退出旧版再启动新版本;不要单独提取可执行文件或混搭内嵌 XPC。应用在菜单栏展示已勾选的指标,空选时显示品牌图标,设置窗口打开时才显示 Dock 图标。
接收方需核对来源、校验值和本机安全策略,再按 [Apple 对未识别开发者应用的说明](https://support.apple.com/en-gb/102445) 决定是否允许运行。企业管理策略可能禁止运行。本地签名校验通过不能证明其他 Mac 的默认 Gatekeeper 放行,也不代表跨机器安装已验收。
+25
View File
@@ -0,0 +1,25 @@
# 菜单栏动态指标实施计划
## 初版
以 [设置页](designs/menu-bar-metrics-v1/settings.png) 和 [菜单栏](designs/menu-bar-metrics-v1/menu-bar.png) 为视觉依据。现有状态项只显示品牌图标,面板隐藏时默认没有采样需求。目标是让勾选项、预览和真实状态项同步,并保留左键面板与右键菜单入口。
1. Core 保存有序指标的选择,从已有历史提取最近六个采样点,显示 CPU / GPU 利用率、内存已用比例、磁盘读写与网络收发总速率。首次使用按设计图全选,显式空选持久化。菜单栏有指标且屏幕亮起时使用面板间隔,只请求基础数据;沿用一次采样循环、暂停与睡眠规则。
2. UI 共享紧凑柱图和两行文字绘制,App 注入同一选择、历史及语言。Settings 增加独立页,MenuBar 在原生状态按钮内绘制,随选择调整宽度。空选恢复品牌按钮。百分比使用固定刻度,速率使用最近窗口峰值,缺测留空。
3. 补齐三语文案与架构说明。构建并检查选项恢复、采样需求切换、速率、缺值和历史断点。本机验证设置、预览、状态项和面板交互。窄屏菜单栏的可用宽度由系统决定,分辨率与刘海影响需在对应环境验收。
## 实施与验证结果
三个阶段已完成。状态项与预览共用同一读取闭包、有限历史和绘图组件。保留原生按钮负责打开面板和右键菜单,动态数值使用固定栏宽。
- Debug 构建通过。MenuBarMetricChecks、SamplingIntervalChecks、DetailDemandChecks、LocalizationChecks、PanelWindowChecks、SettingsWindowChecks 和三语目录检查通过。
- 本机隔离应用中,逐项取消五项并反向逐项勾选,每步比对设置复选框、预览和真实状态项的辅助功能内容。名称、顺序和数值一致,全选状态项实测宽 356pt,空选为 24pt。单独重启核对空选,以及仅选 CPU 和网络,两组配置均恢复。
- 已检查浅色和深色设置窗口局部截图、外接显示器上的五项状态栏,实测状态项 AX 按压、坐标左击、右键菜单进入设置及键盘 Esc 收起面板。空选的品牌图标也能切换面板。
- 本机主显示器在现有菜单排列下会隐藏放不下的整组指标。实测重新打开已运行且无窗口的应用可进入设置,减少选项后状态项可见。不同桌面排列下的可用宽度与长期能耗仍由实际使用环境决定。
## 第三版紧凑布局
按已确认的[状态项](designs/menu-bar-metrics-v3/menu-bar.png)与[设置预览](designs/menu-bar-metrics-v3/settings.png)调整。四项占用各用 3pt 宽、18pt 高的矩形槽,名称与百分比在右侧上下排列。网络仅显示上下两行速率。设置预览靠近时钟右对齐,继续与状态项共用绘图组件。数据直接取当前快照,沿用已有选项键与采样调度。
Debug 构建和 MenuBarMetricChecks、PanelWindowChecks、SettingsWindowChecks、LocalizationChecks 通过。本机简体中文五项全选实测 239pt,比首版 356pt 缩短约 33%。隔离副本逐项取消并重新勾选,每步比对预览和实际状态项内容及宽度;空选为 24pt。重启后仅选磁盘和网络的配置恢复。本机主目录卷按系统容量计算为 38%,与同期菜单栏一致。已检查局部截图、左键开合、右键进入设置及 Esc 收起面板。
+20 -6
View File
@@ -4,6 +4,8 @@
趋势图跳过无值节点,按真实时间连接前后有效点;有效 0 仍绘制,暂停 / 休眠等显式断点及真实采样空档仍断线。连接只影响曲线外观:缺失时刻悬浮读数为 `--`,原历史不补值。
CPU / GPU / 电池的零值与 100% 分别映射到卡片底边和顶边,内存卡片顶边为物理总量。存储、网络以及无电池设备的功率曲线绘在文字下方。CPU 自下而上堆叠系统态 / 用户态,内存堆叠应用 / 联动 / 压缩,GPU 总利用率、Renderer、Tiler 分别绘制,阶段可能重叠,不相加。电池显示电量,功率提示独立标 W;存储 / 网络以自顶向下 60% 高度为零轴,读取 / 上传向上、写入 / 下载向下;两侧同样使用 30% 绘图区高度振幅及共享自动速率尺度,原始值和提示均保持正速率。不显示常驻数值坐标轴、网格或图例。静态淡色面积在匹配的累计上下边界间按真实连续段闭合,不跨暂停或长空档;单点只显示真实点,必要分量缺失不构造部分总量。悬浮不会替换上方实时主数值。
## 数据来源
| 指标 | 实现与来源 | 口径与边界 |
@@ -19,6 +21,7 @@
| 存储 IO | `DiskIOMonitor`,IOBlockStorageDriver 累计字节 | 物理块设备读写速率,非主卷文件 IO;设备集合变化、计数回退、首次读取均重建基线 |
| SMART | `DiskHealthMonitor` → XPC → `diskutil info -plist` | 主目录所在卷关联报告中的寿命和通电时间;剩余寿命 = 100 − PERCENTAGE_USED(下限 0),通电小时要求高位为 0,多物理存储拒绝合并;不代表所有卷或磁盘 |
| 电池 | `BatteryMonitor`,IOPowerSources 与 AppleSmartBattery | 电量、充电 / 外接电源、循环和功率;功率取电压 × 电流的绝对值,非整机功耗;区分无内置电池和读取失败 |
| 无电池整机功率 | 签名 XPC 只读 AppleSMC 固定键 PSTR | 传感器即时整机功率 W,不是插座侧计量;字段口径可对照 [Stats 传感器表](https://github.com/exelban/stats/blob/master/Modules/Sensors/values.swift)。不支持或读取失败显示不可用,不用电池或进程功率替代 |
| 电池健康 | `SystemBatteryHealthMonitor`,`system_profiler SPPowerDataType -json` | 使用系统报告的最大容量百分比,不用当前充电容量推算 |
| 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线;计数缓冲在采样器内复用,容量不足时扩容,仅解析本轮实际返回字节;本地地址保持系统 numeric formatter(含 scope),每轮共用地址缓冲、每接口最终排序一次 |
| 网络路径 | `NetworkPathObserver`,NWPathMonitor | 可用 / 不可用 / 需连接;代码取 `availableInterfaces.first` 作为主接口候选,并非独立解析系统默认路由;路径可用不保证公网可达 |
@@ -27,6 +30,12 @@
内存容量使用 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 占用。
@@ -38,16 +47,19 @@
| 数据 | 默认 / 周期策略 |
| --- | --- |
| 常规资源快照 | 面板可见默认 2000ms;新配置隐藏默认停止采样,显式启用后台趋势后默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms |
| 常规资源快照 | 面板可见或勾选菜单栏指标且亮屏时默认 2000ms;其余情况仅在显式启用后台趋势时采样,默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms |
| 进程 | 请求进程详情且面板实际可见、未暂停 / 睡眠时随采样请求更新;异步独立发布,最多一个在途 |
| 进程 CPU 能量 | 复用同轮进程候选,成功后至少 5 秒再读(默认 2 秒轮次下通常约 6 秒);失败 30–600 秒退避,明确不支持后 600 秒;最多一批在途 |
| CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 |
| 无电池整机功率 | 仅可见且请求详情时按面板采样间隔读取;2 秒超时、失败独立退避 60–600 秒,历史保留缺失 |
| 卷列表 | 读取结束后至少 30 秒 |
| SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 |
| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;概览可见时按缓存到期持续刷新,路由键变化、暂停或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 |
| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;面板可见时按缓存到期持续刷新,路由键变化、暂停或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 |
| 趋势 | 全局与每接口最多各 60 点,仅内存保存 |
传感器、卷与慢报告只在请求概览慢指标的可见采样轮次检查是否到期;后台趋势不启动这些慢读取。快照中的慢指标可能来自之前的缓存。暂停停止发布,不保证取消已进入系统调用的工作。
菜单栏按 CPU、GPU、内存、磁盘、网络顺序展示。前四项的等高竖条以 0–100% 从底部填充,右侧显示名称与百分比。CPU / GPU 为总利用率,内存为已用 / 总量,磁盘为主目录所在卷的(总容量 − 可用空间)/ 总容量。网络上行在首行(↑),下行在次行(↓),分别复用当前快照的活动 en 接口汇总,每个方向以十进制 B/s 自动换算单位。缺测的读数独立显示 --。
传感器、卷与慢报告只在请求慢指标的可见采样轮次检查是否到期;后台趋势不启动这些慢读取。快照中的慢指标可能来自之前的缓存。暂停停止发布,不保证取消已进入系统调用的工作。
常规周期允许系统在配置周期 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 平均功率,列头可切换升降序;缺失值显示 -- 并始终排末。悬浮功率单元格可查看实际统计窗口。
按全部可测候选的有效能量差分排名。权限受限、进程退出和截止会降低覆盖率;进程页显示已形成差分数 / 枚举总数,首帧等待,失败或不支持明确显示状态。零增量只有连续两帧有效时才代表 0 W。身份变化、计数回退、无效时间和超过允许窗口均不形成排名。超大进程集合在总截止下可能只覆盖部分批次,尚未验证极端规模下的公平轮转。
按全部可测候选的有效能量差分排名。权限受限、进程退出和截止会降低覆盖率;进程标题提示显示已形成差分数 / 枚举总数,首帧等待,失败或不支持明确显示状态。零增量只有连续两帧有效时才代表 0 W。身份变化、计数回退、无效时间和超过允许窗口均不形成排名。超大进程集合在总截止下可能只覆盖部分批次,尚未验证极端规模下的公平轮转。
进程 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 查询后持久网络目录未新增或变更文件。
## 页面采样需求
## 单页采样需求
概览只采集系统资源,不进行进程枚举、footprint 或进程 CPU 能量读取。进入进程页才启用这些读取并重新建立进程差分基线;功率至少需要两次有效读取,现有成功间隔下限 5 秒不变。离开即清除已发布进程 / 能量并拒绝旧代次回写。进程页保留基础资源采样以延续趋势,但不发起概览慢传感器 / 报告或公网 IP 请求;已开始的慢读取可自行结束。基础采样间隔、后台趋势开关、暂停与睡眠规则保持独立。
App 同时请求进程与慢指标,面板实际可见且未暂停 / 睡眠时执行。进程、footprint 与 CPU 能量读取保留单在途约束及独立发布;功率至少需要两次有效读取,成功间隔下限 5 秒不变。隐藏时清除进程 / 能量发布并拒绝旧代次回写;后台趋势只延续基础系统采样,不启动上述详情。基础采样间隔、后台开关、暂停与睡眠规则保持独立。
风扇图标沿用视觉速度档位:正值 <2000 / <4000 / <6000 / 其余 RPM 对应 90 / 180 / 300 / 450°/s,不模拟物理 RPM。零、缺失 / 无效、系统减弱动态效果、暂停、不可见、睡眠或卸载时停止;实际转速文本口径不变。
+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 通过;保留用户已安装副本,清理本轮隔离副本、容器、截图与临时构建。
+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` 拖入「应用程序」。如果正在使用旧版,请先退出旧版再替换。
+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 命中卷入口位置时仅返回组;定向合成点击未观察到弹出窗口,屏幕点击因命中位置不能确认由测试窗口独占而跳过。卷详情弹出仍需在新版面板点击「本地卷」确认。
+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。
+16 -10
View File
@@ -25,24 +25,29 @@ python3 tools/check.py --list
| 检查 | 覆盖范围 |
| --- | --- |
| SamplingChecks、SamplingIntervalChecks、DetailDemandChecks | 差分首帧与重置、间隔与旧偏好、暂停 / 恢复、隐藏零采样、分页需求、独立进程发布与需求代次 |
| SamplingChecks、SamplingIntervalChecks、DetailDemandChecks | 差分首帧与重置、间隔与旧偏好、暂停 / 恢复、隐藏零采样、同时详情需求与需求撤回、独立进程发布与需求代次 |
| StackedSeriesChecks | CPU / 内存 / GPU 累计上下边界、分量缺失 / 无效 / 负值 / 溢出拒绝、零值、GPU 总和与共同断点 |
| BackgroundTrendChecks、PanelCurveChecks | 真实时间域、周期切换、短暂隐藏连续性、60 点有界历史、缺失与非有限点、有效 0、显式停采及真实空档 |
| UnifiedPanelChecks、StageCChecks | 本机采样边界、网络汇总与接口历史、电池估时及系统报告解析 |
| MachPortChecks | CPU / 内存各 1,000 轮后 host 发送权引用无增长 |
| MemoryChecks、MemoryHeaderChecks | 分类守恒、二进制容量、压力 / 缓存 / Swap 标题及三语缺失 / 零值 |
| GPUStatisticsChecks、CPUTemperatureChecks、FanChecks、DiskHealthChecks | 当前 GPU 利用率与历史、温度范围与解码、风扇零值 / 无效值、SMART 边界与多物理存储拒绝合并 |
| MemoryChecks、MemoryHeaderChecks | 含压缩 / 缓存 / Swap 的分类守恒、二进制容量、压力 / 缓存 / Swap 标题及三语缺失 / 零值 |
| GPUStatisticsChecks、CPUTemperatureChecks、FanChecks、DiskHealthChecks | 当前 GPU 利用率与历史、温度范围与解码、风扇零值 / 无效值、历史速度边界与切档相位、SMART 边界与多物理存储拒绝合并 |
| SensorScheduleChecks、BoundedProcessChecks | 各能力独立退避;真实受控子进程输出上限、超时、取消、异常退出与回收 |
| ProcessEnergyChecks、ProcessEnergyReaderChecks、ProcessCPULiveChecks | UInt64 能量差分、身份 / UID / 缺失 / 回退 / 时间边界、受控本机能量增长和 Mach 时基 CPU 差分 |
| ProcessSelectionChecks、PanelLayoutChecks、CPUCoreGridChecks | 退出与 PID 复用、搜索 / 排序、640pt / 窄屏预算、核心行数与边界 |
| ProcessSelectionChecks、PanelLayoutChecks、CPUCoreGridChecks | 退出与 PID 复用、搜索 / 排序、648pt 三列资源及第三行进程 / 两列及单列窄屏预算、全行等高与滚动边界、逐核单元数量、分组和换行边界 |
| PublicIPAddressChecks | 隔离 URLProtocol、600 秒成功 / 30 秒失败缓存、单调时间、持续刷新及取消,不发送真实请求 |
| NetworkAddressChecks、ProcessIconCacheChecks | 沙盒下地址格式 / 速率;图标位图、尺寸、共享、过期、LRU 与严格预算 |
| AppearancePreferencesChecks、LocalizationChecks、PresentationChecks | 外观与偏好隔离、语言持久化、编译资源、窗口显式 / 系统外观切换 |
| CodeIdentityChecks、PanelAssetChecks、KeepAwakeChecks | 签名身份拒绝边界、编译颜色及对比度、真实 IOPM 断言开关与释放 |
| NativeMetricDrawingChecks(--gui) | 实际曲线像素、直接稳定更新、缺失点接续与真实断点、悬浮缓存、无动画 / 渐变 / 遮罩、卸载 |
| NativeContentHostChecks(--gui) | 数字更新、父环境继承、挂载身份、有限尺寸和卸载 |
| NativeProcessTableChecks(--gui) | 原生虚拟表格、原地更新、身份选择、排序 / 列序 / 复制 / 三语列头、合成 Esc 投递 |
| NativeMetricDrawingChecks(--gui) | 实际曲线 / 堆叠色带、双向速率面积和零轴、方向 / 悬浮 / 断点及累计边界定位、单点无虚构填充、隐藏序列隔离、缺失点接续与真实断点、悬浮缓存、滚动时间域变换、悬浮停止动画、断点、无渐变 / 遮罩、卸载 |
| FanRotorChecks(--gui) | 独立图层多角度 / 多尺寸旋转中心不漂移,原生旋转动画时长、无效 / 零 / 缺失、非活动 / 减弱动态效果及卸载停转 |
| ResourceCardChecks(--gui) | 生产卡片与曲线真实挂载,190 / 205⅓ / 400pt、浅深色及三语下的整卡背景图区、存储与网络的独立图区及文字换行边界、10pt 三语内存 / 存储详情在固定卡片内的边界、模拟有电池 / 无电池 / 未知和失败的历史序列及单位尺度、卸载;比较 AppKit 实际尺寸,允许分数点窗口尺寸取整 |
| ProcessSectionChecks(--gui) | 生产进程区域固定 176pt,三语 / 浅深色及 340 / 628pt 下移除说明行后表格占满剩余高度且无横向滚动条 |
| NativeContentHostChecks(--gui) | 小数末位增减后直接显示最终读数、更新帧与稳定帧像素一致、父环境继承、挂载身份、有限尺寸和卸载 |
| NativeProcessTableChecks(--gui) | 原生虚拟表格、原地更新、身份选择、六列窄宽度适配、隐藏路径列但真实菜单复制路径、排序 / 列序 / 复制 / 三语列头、合成 Esc 投递 |
| MenuBarMetricChecks | 全选 / 取消全选与单项持久化、隐藏面板后跟随前台间隔调整、息屏与暂停、四项占用、磁盘容量口径、网络双向独立速率、零值与缺测 |
| TabPickerChecks、LanguageScopeChecks、SettingsWindowChecks(--gui) | 原生页签选择与键盘、已挂载语言即时切换、设置焦点 / 最小化恢复 / Dock 生命周期 |
| PanelWindowChecks(--gui) | 真实 NSPanel 居中、尺寸反馈、固定、遮挡可见性、显式关闭重开默认概览和退出复位 |
| PanelWindowChecks(--gui) | 真实 NSPanel 居中、尺寸反馈、固定、遮挡可见性、显式关闭重开和退出复位 |
| ReleaseServiceChecks(--services) | 临时 hardened sandbox 主程序调用本轮实际嵌入服务,核对同 UID footprint / 能量与传感器 |
| SandboxNetworkChecks(--network) | 使用实际主应用 entitlement 访问产品 HTTPS 端点,核对持久网络目录无新增或变更文件 |
@@ -52,10 +57,11 @@ LocalizationCatalogChecks.py 检查全部保留键的三语完整性与格式参
自动检查可验证模型、原生组件和窗口策略,不能代替正式应用事件。代码改动涉及相应路径时,应在本机完成:
- 在「设置 → 菜单栏」逐项勾选与取消,核对预览与真实状态项的顺序、数值及宽度。空选保留品牌入口,重启保留选项。系统菜单栏宽度不足时检查重新打开应用的设置入口。
- 菜单栏左键打开 / 收起、右键菜单、设置入口与退出。
- 概览六张卡片、双列 / 窄屏单列和滚动,进程分页与关闭重开默认概览。
- 六张资源卡片与等高通栏进程同页,三列资源 / 窄屏两列及单列和整体滚动,关闭重开。
- 固定 / 取消固定、外部点击、Esc 分层处理,图表悬浮、复制、缺失值。
- 底栏刷新间隔、后台趋势、暂停 / 恢复;概览停止进程读取,进程页停止概览慢读取,基础趋势延续。
- 底栏刷新间隔、后台趋势、暂停 / 恢复;同时详情需求,隐藏 / 暂停停止进程及慢读取,显式后台仅延续基础趋势。
- 实际签名沙盒应用的 GPU、温度、风扇、SMART、电池、网络、footprint 和 CPU 功率来源 / 单位 / 不可用状态。
- 三语即时切换、浅深色与系统跟随、重启持久化、设置焦点与 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 共用百分比轴但各自绘制,只有总利用率填充面积。电池背景显示电量,功率在悬浮中单独注明 W,不能与电量共用未解释的尺度。存储和网络采用上下双向曲线:自顶向下 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;六张卡片共用样式与几何规范,不增加依赖、背景轮询或历史容量。颜色、外观、数据或尺寸变化才更新相应图层;隐藏卸载仍释放图表和提示。
必须验证构建、布局预算、实际曲线 / 面积像素、显式空档无填充、缺失悬浮、悬浮几何缓存、浅深色、三语、大数值与窄屏;实际应用检查同页资源 / 进程、接口、卷详情、复制、暂停 / 恢复及关闭重开。真实多屏与长期能耗需对应环境,不用单次快照代替。
+4 -4
View File
@@ -303,7 +303,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 14;
CURRENT_PROJECT_VERSION = 15;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
@@ -325,7 +325,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.2;
MARKETING_VERSION = 1.3;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -371,7 +371,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 14;
CURRENT_PROJECT_VERSION = 15;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEPLOYMENT_POSTPROCESSING = YES;
@@ -388,7 +388,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.2;
MARKETING_VERSION = 1.3;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
+21 -5
View File
@@ -17,6 +17,7 @@ import AppKit
private let awake = KeepAwakeService()
private let presentation = SettingsPresentation()
private let appearance = AppearancePreferences()
private let menuBarPreferences = MenuBarPreferences()
private let language = LanguagePreferences()
private var openSettingsAction: (() -> Void)?
private var scenes: AnyObject?
@@ -35,10 +36,21 @@ import AppKit
MainActor.assumeIsolated { self?.metrics.setDisplaySleeping(sleeping) }
})
}
let readings = { [metrics, menuBarPreferences, language] () -> [MenuBarReading] in
let selected = menuBarPreferences.selected
guard !selected.isEmpty else { return [] }
let locale = language.locale
return MenuBarReading.readings(selection: selected, snapshot: metrics.snapshot) {
AppLocalization.string($0.titleKey, locale: locale)
}
}
menuBarPreferences.onDemandChange = { [metrics] in metrics.setMenuBarEnabled($0) }
metrics.setMenuBarEnabled(!menuBarPreferences.selected.isEmpty)
let settings = NSHostingSceneRepresentation {
Settings {
AppLanguageScope(preferences: language, onChange: { self.configureMainMenu() }) { [self] in
AppearanceSettingsView(preferences: appearance, language: language, sampling: metrics.sampling, presentation: presentation)
AppearanceSettingsView(preferences: appearance, language: language, sampling: metrics.sampling,
menuBar: menuBarPreferences, readings: readings, presentation: presentation)
}
}
}
@@ -46,10 +58,8 @@ import AppKit
scenes = settings
openSettingsAction = { settings.environment.openSettings() }
configureMainMenu()
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) },
pageChanged: { [metrics] page in
metrics.setDetailDemand(processes: page == .processes, slowMetrics: page == .overview)
},
metrics.setDetailDemand(processes: true, slowMetrics: true)
menuBar = MenuPanelController(readings: readings, visibility: { [metrics] in metrics.setPanelVisible($0) },
menuTitle: { [language] key in
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
@@ -106,5 +116,11 @@ import AppKit
scenes = nil
}
// Finder or Spotlight remains a settings entry point when macOS hides a wide status item.
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag { settingsCommand() }
return true
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
}
+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: ", ")
}
}
+2
View File
@@ -8,6 +8,7 @@ nonisolated struct TrendSample: Sendable {
var download: Double?
var battery: Double?
var batteryPower: Double?
var systemPower: Double?
var upload: Double?
var read: Double?
var write: Double?
@@ -46,6 +47,7 @@ nonisolated struct MetricHistory: Sendable {
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate,
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
systemPower: snapshot.batteryState == .absent ? snapshot.systemPower : nil,
upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler,
+1
View File
@@ -34,6 +34,7 @@ nonisolated struct MetricsSnapshot: Sendable {
var diskHealth: DiskHealthMetrics?
var diskIO: DiskIOMetrics?
var volumes: [VolumeMetrics]?
var systemPower: Double?
var battery: BatteryMetrics?
var uptime: TimeInterval = 0
var gpu: GPUMetrics?
+10 -1
View File
@@ -1,7 +1,7 @@
import Foundation
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 power keys; never write keys.
nonisolated final class CPUTemperatureMonitor {
static let highTemperatureThreshold = 90.0
@@ -99,6 +99,12 @@ nonisolated final class CPUTemperatureMonitor {
}
}
/// 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
}
private func readNumber(_ key: UInt32) -> Double? {
var request = Request(); request.key = key; request.command = 9
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
@@ -116,6 +122,9 @@ nonisolated final class CPUTemperatureMonitor {
return value.isFinite ? value : nil
case (0x66706532, 2): // fpe2, big-endian unsigned 14.2 fixed point
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
default: return nil
}
+13 -1
View File
@@ -8,6 +8,8 @@ actor SystemSampler {
private var temperatureCache: Double?
private var gpuTemperatureCache: Double?
private var fanCache: [FanMetrics]?
private var powerSchedule = SensorSchedule(successInterval: 0)
private var readingPower = false
private var cpuSchedule = SensorSchedule()
private var gpuSchedule = SensorSchedule()
private var fanSchedule = SensorSchedule()
@@ -67,7 +69,7 @@ actor SystemSampler {
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = 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() }
if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() }
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
@@ -120,6 +122,16 @@ actor SystemSampler {
result.battery?.health = batteryCache
result.volumes = volumes
result.uptime = 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 && !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" {
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
@@ -7,6 +7,14 @@ nonisolated struct SensorReadings: Sendable {
}
nonisolated enum CPUTemperatureServiceClient {
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? {
await ServiceRequest.perform(timeout: 2) { proxy, finish 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) }
}
}
+19 -6
View File
@@ -15,12 +15,14 @@ final class MetricsStore {
private(set) var slowMetricsRequested = true
let sampling: SamplingPreferences
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
private var menuBarEnabled = false
private var liveDemand: Bool { panelDemand || (menuBarEnabled && !isDisplaySleeping) }
private var processDemand: Bool { panelDemand && processUpdatesRequested }
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
var effectiveMilliseconds: Int { liveDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { !isSystemSleeping && (liveDemand || sampling.backgroundEnabled) }
// Permit timer coalescing without changing the requested cadence or delta timestamps.
private var schedulingTolerance: Duration {
.milliseconds(min(effectiveMilliseconds / 10, panelDemand ? 200 : 1_000))
.milliseconds(min(effectiveMilliseconds / 10, liveDemand ? 200 : 1_000))
}
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@@ -36,7 +38,7 @@ final class MetricsStore {
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused,
self.effectiveMilliseconds != self.scheduledInterval || self.hasSamplingDemand != (self.task != nil) else { return }
self.reschedule(reset: false, sampleImmediately: false)
self.reschedule(reset: self.task == nil, sampleImmediately: self.task == nil)
}
start()
}
@@ -134,14 +136,25 @@ final class MetricsStore {
func setDisplaySleeping(_ sleeping: Bool) {
guard sleeping != isDisplaySleeping else { return }
let wasActive = hasSamplingDemand
isDisplaySleeping = sleeping
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
updateDemand(reset: !wasActive || !hasSamplingDemand, sampleImmediately: liveDemand)
}
func setPanelVisible(_ visible: Bool) {
guard isPanelVisible != visible else { return }
let wasActive = hasSamplingDemand
isPanelVisible = visible
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
updateDemand(reset: !wasActive || !hasSamplingDemand, sampleImmediately: panelDemand)
}
func setMenuBarEnabled(_ enabled: Bool) {
guard menuBarEnabled != enabled else { return }
let wasLive = liveDemand
let wasActive = hasSamplingDemand
menuBarEnabled = enabled
guard wasLive != liveDemand, !isPaused, !isSystemSleeping else { return }
reschedule(reset: !wasActive || !hasSamplingDemand, sampleImmediately: enabled)
}
/// The caller supplies data needs, without introducing UI types into Core.
@@ -4,6 +4,7 @@ import Foundation
@objc protocol SMARTServiceProtocol {
nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
@@ -33,6 +33,8 @@ nonisolated enum SamplingDiagnostics {
payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature
payload["gpuUsage"] = snapshot.gpuUsage
payload["gpuRenderer"] = snapshot.gpu?.renderer
payload["gpuTiler"] = snapshot.gpu?.tiler
payload["gpuCoreCount"] = snapshot.gpu?.coreCount
payload["processEnumerated"] = snapshot.processes?.enumerated
payload["processReadable"] = snapshot.processes?.readable
@@ -50,6 +52,7 @@ nonisolated enum SamplingDiagnostics {
payload["volumeCount"] = snapshot.volumes?.count
payload["batteryCycles"] = snapshot.battery?.cycles
payload["batteryHealth"] = snapshot.battery?.health
payload["systemPower"] = snapshot.systemPower
payload["batteryPower"] = snapshot.battery?.power
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)
+48 -40
View File
@@ -1,6 +1,6 @@
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 {
let values: [Double]
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 {
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 .middle: Text("cpu.kind.performance", tableName: "CPUDetails")
case .performance:
@@ -31,79 +41,77 @@ struct CPUCoreGrid: View {
}
static func groupWidths(groups: [[Int]], width: CGFloat) -> [CGFloat] {
let weights = groups.map { CGFloat(($0.count + 1) / 2) }
let total = max(1, weights.reduce(0, +))
let available = max(0, width - CGFloat(max(0, groups.count - 1)) * 13)
return weights.map { available * $0 / total }
guard !groups.isEmpty else { return [] }
let available = width.isFinite ? max(0, width - CGFloat(groups.count - 1) * 8) : 0
let minimum = min(44, available / CGFloat(groups.count))
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 {
let groups = Self.groups(count: values.count, kinds: kinds)
GeometryReader { geometry in
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
if group > 0 {
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1)
}
VStack(alignment: .leading, spacing: 5) {
HStack(spacing: 3) {
Circle().fill(color(kinds[groups[group][0]])).frame(width: 5, height: 5)
if let kind = kinds[groups[group][0]] { label(kind) }
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 2) {
Circle().fill(color(kinds[groups[group][0]])).frame(width: 3, height: 3)
if let kind = kinds[groups[group][0]] { label(kind, compact: true) }
else { Text("cpu.core") }
Text(verbatim: "\(groups[group].count)").foregroundStyle(.secondary)
Text(verbatim: "\(groups[group].count)").foregroundStyle(.primary)
}
.font(.system(size: 9, weight: .medium))
.lineLimit(1).minimumScaleFactor(0.6)
.font(.system(size: 9, weight: .medium)).lineLimit(1).minimumScaleFactor(0.65)
.frame(height: 12)
CPUCoreGridLayout {
ForEach(groups[group], id: \.self) { index in
core(index: index)
}
ForEach(groups[group], id: \.self) { index in core(index: index) }
}
}.frame(width: widths[group], alignment: .topLeading)
}
}
}
.frame(height: 15 + CGFloat(maxRows(groups: groups)) * 22 + CGFloat(max(0, maxRows(groups: groups) - 1)) * 4)
.padding(.vertical, 1)
.frame(height: gridHeight(groups: groups))
}
// Match the content width so row reservation agrees with placement.
var availableWidth: CGFloat = 380
var availableWidth: CGFloat = 185
private func maxRows(groups: [[Int]]) -> Int {
private func gridHeight(groups: [[Int]]) -> CGFloat {
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 {
let kind = kinds[index]
let value = values[index].isFinite ? min(1, max(0, values[index])) : 0
return VStack(spacing: 3) {
Text(verbatim: "\(Int((value * 100).rounded()))")
.font(.system(size: 8, weight: .medium)).monospacedDigit().lineLimit(1)
MetricProgressBar(value: value, color: color(kind)).frame(height: 3)
let measured = values[index].isFinite ? values[index] : nil
return RoundedRectangle(cornerRadius: 2)
.fill(color(kind).opacity(0.22))
.overlay(alignment: .bottom) {
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)
.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)
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
.accessibilityValue("\(index + 1): \(MetricFormat.percent(measured))")
}
}
struct CPUCoreGridLayout: Layout {
static let columnSpacing: CGFloat = 6
static let columnSpacing: CGFloat = 3
static let rowSpacing: CGFloat = 4
static let rowHeight: CGFloat = 22
static let minimumTwoRowCellWidth: CGFloat = 16
static let rowHeight: CGFloat = 11
static let minimumCellWidth: CGFloat = 7
static func rowCounts(count: Int, width: CGFloat) -> [Int] {
guard count > 0 else { return [] }
guard count > 1 else { return [1] }
let usableWidth = width.isFinite ? max(0, width) : 0
let capacity = max(1, Int(min(CGFloat(count), (usableWidth + columnSpacing) / (minimumTwoRowCellWidth + columnSpacing))))
let rows = max(2, (count + capacity - 1) / capacity)
let capacity = max(1, Int(min(CGFloat(count), (usableWidth + columnSpacing) / (minimumCellWidth + columnSpacing))))
let rows = max(1, (count + capacity - 1) / capacity)
let quotient = count / rows, remainder = count % rows
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 ()) {
let rows = Self.rowCounts(count: subviews.count, width: bounds.width)
guard let columns = rows.max(), columns > 0 else { return }
let spacing = min(Self.columnSpacing, max(0, (bounds.width / CGFloat(columns) - 18) / 2))
let cellWidth = max(0, (bounds.width - CGFloat(columns - 1) * spacing) / CGFloat(columns))
let spacing = min(Self.columnSpacing, max(0, (bounds.width / CGFloat(columns) - Self.minimumCellWidth) / 2))
let cellWidth = min(Self.minimumCellWidth, max(0, (bounds.width - CGFloat(columns - 1) * spacing) / CGFloat(columns)))
var index = 0
for (row, count) in rows.enumerated() {
for column in 0..<count {
+29 -10
View File
@@ -2,22 +2,41 @@ import SwiftUI
struct MemoryDetailsView: View {
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, memory.available] }
private let labels: [LocalizedStringKey] = ["memory.app", "memory.wired", "memory.compressed", "memory.available"]
private var values: [UInt64] { [memory.app, memory.wired, memory.compressed] }
private let labels: [LocalizedStringKey] = ["memory.appShort", "memory.wiredShort", "memory.compressedShort"]
var body: some View {
VStack(alignment: .leading, spacing: 3) {
CardSeparator()
CapacityBar(values: values.map { Double($0) }, colors: colors, total: Double(memory.total))
VStack(alignment: .leading, spacing: 4) {
ViewThatFits(in: .horizontal) {
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) {
ForEach(0..<4) { index in
CapacityField(title: labels[index], value: MetricFormat.memory(values[index]), color: colors[index])
}
}
Text("memory.available").foregroundStyle(.secondary)
MetricText(value: MetricFormat.memory(memory.available)).fontWeight(.medium)
}.frame(height: 16)
}
.font(.system(size: 10)).lineLimit(1)
.help(Text("memory.distributionHelp"))
.accessibilityElement(children: .contain)
.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 badgeTitle: String { pressure.key == nil ? "--" : localized("memory.pressurePrefix") + title }
var color: Color { pressure.color }
var help: String {
"\(localized("memory.pressure")): \(title)\n"
+31 -11
View File
@@ -2,14 +2,10 @@ import AppKit
import SwiftUI
import Observation
enum PanelPage: Hashable { case overview, processes }
@MainActor @Observable final class PanelPresentation {
fileprivate(set) var isOpen = false
var isPinned = false { didSet { onPinChange?(isPinned) } }
var page: PanelPage = .overview { didSet { if oldValue != page { onPageChange?(page) } } }
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
@ObservationIgnored var onPageChange: ((PanelPage) -> Void)?
}
/// 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
private(set) weak var lastHiddenContent: NSView?
#endif
private let metricStrip = MenuBarMetricStrip()
private let readings: () -> [MenuBarReading]
private var statusItem: NSStatusItem?
private var localMouse: Any?
private var globalMouse: Any?
@@ -32,11 +30,12 @@ enum PanelPage: Hashable { case overview, processes }
private var isHiding = false
private var preferredContentHeight = PanelLayout.defaultHeight
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
pageChanged: @escaping (PanelPage) -> Void = { _ in },
init<Content: View>(installStatusItem: Bool = true, readings: @escaping () -> [MenuBarReading] = { [] },
visibility: @escaping (Bool) -> Void,
menuTitle: @escaping (String) -> String = { $0 },
openSettings: @escaping () -> Void = {},
@ViewBuilder content: @escaping (PanelPresentation) -> Content) {
self.readings = readings
self.visibility = visibility
self.menuTitle = menuTitle
self.openSettings = openSettings
@@ -57,16 +56,15 @@ enum PanelPage: Hashable { case overview, processes }
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.dismiss = { [weak self] in self?.hide() }
presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal }
presentation.onPageChange = pageChanged
if installStatusItem {
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
item.button?.image = NSImage(named: "BrandMark")
item.button?.image?.isTemplate = true
item.button?.setAccessibilityLabel("Kymo")
item.button?.target = self
item.button?.action = #selector(statusItemClicked)
item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
statusItem = item
metricStrip.setAccessibilityElement(false)
item.button?.addSubview(metricStrip)
refreshStatusItem()
}
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.place() }
@@ -85,6 +83,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 private func statusItemClicked() {
@@ -123,7 +144,6 @@ enum PanelPage: Hashable { case overview, processes }
func show() {
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
place()
presentation.page = .overview
presentation.isOpen = true
panel.contentView = content(presentation)
panel.level = presentation.isPinned ? .floating : .normal
@@ -6,24 +6,37 @@ extension MenuPanelView {
ResourceCard(
title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: "↓ " + MetricFormat.rate(total(\.download)),
secondaryValue: "↑ " + MetricFormat.rate(total(\.upload)), valueColor: Color("MetricMemory"),
secondaryValueColor: Color("SeriesUpload")
) {
secondaryValueColor: Color("SeriesUpload"), headerAccessory: AnyView(networkInterfacePicker),
chart: {
PanelTrendChart(
dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"),
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)
CardSeparator()
HStack(alignment: .top, spacing: 8) {
networkTotal(
"network.received", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received }),
symbol: "arrow.down", color: Color("MetricMemory"))
Divider().frame(height: 32)
networkTotal(
"network.sent", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent }),
symbol: "arrow.up", color: Color("SeriesUpload"))
Divider().frame(height: 32)
VStack(alignment: .leading, spacing: 4) {
}
) {
HStack(spacing: 3) {
Text("network.totalShort").foregroundStyle(.secondary)
Image(systemName: "arrow.down").foregroundStyle(Color("MetricMemory"))
MetricText(value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received })).fontWeight(.medium)
Text("·").foregroundStyle(.secondary)
Image(systemName: "arrow.up").foregroundStyle(Color("SeriesUpload"))
MetricText(value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent })).fontWeight(.medium)
}.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9).frame(height: 16)
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) {
Circle().fill(networkStatusColor).frame(width: 5, height: 5)
Picker("panel.interface", selection: $selectedInterface) {
@@ -31,29 +44,17 @@ extension MenuPanelView {
ForEach(snapshot.network ?? [], id: \.identity) { item in
Text(verbatim: item.name).tag(item.identity)
}
}.labelsHidden().controlSize(.mini).fixedSize()
}.labelsHidden().controlSize(.mini).fixedSize().frame(maxWidth: 70)
}
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())
.help(Text(networkStatusLabel))
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("network.addresses"))
}
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
.accessibilityValue(Text(networkStatusLabel))
}
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
HStack(spacing: 3) {
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 ?? "--"))
.frame(maxWidth: .infinity, alignment: .leading)
if let address {
@@ -61,21 +62,12 @@ extension MenuPanelView {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(address, forType: .string)
} label: {
Image(systemName: "doc.on.doc")
Image(systemName: "doc.on.doc").frame(width: 14, height: 14)
}
.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 {
switch snapshot.networkPath {
case .available: "network.pathAvailable"
@@ -3,17 +3,11 @@ import SwiftUI
extension MenuPanelView {
func line(_ key: LocalizedStringKey, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) {
Text(key).font(PanelStyle.label).foregroundStyle(.secondary)
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text(key).font(.system(size: 10)).foregroundStyle(.secondary)
Spacer(minLength: 6)
MetricText(value: value).font(PanelStyle.value)
}.frame(height: 14)
}
func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
MetricText(value: value).font(.system(size: 10, weight: .medium))
}.frame(height: 16)
}
var cpuCard: some View {
@@ -24,15 +18,21 @@ extension MenuPanelView {
value: MetricFormat.percent(snapshot.cpu?.usage),
status: temperature.map { "\(Int($0.rounded()))°C" },
statusWarning: highTemperature,
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil
) {
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil,
chartPlacement: .background,
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals)
CardSeparator()
boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [2, 1])
}
) {
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 {
CPUCoreGrid(
values: cpu.cores, kinds: CPUCoreTopology.cores,
@@ -47,37 +47,52 @@ extension MenuPanelView {
var gpuCard: some View {
return ResourceCard(
title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
titleBadge: snapshot.gpu?.coreCount.map {
String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0)
},
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(
dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
firstLabel: "gpu.totalUtilization",
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
if !fans.isEmpty {
CardSeparator()
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 4) {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 5, alignment: .leading), count: min(2, fans.count)), spacing: 2) {
ForEach(fans) { fan in
FanSpeedIndicator(
title: fans.count == 2
? (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)
}
}
.modifier(CardInset())
} else if snapshot.fans == nil {
CardSeparator()
Text("metric.waiting").font(PanelStyle.label)
Text("metric.waiting").font(.system(size: 10))
.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 {
let header = MemoryHeaderInfo(memory: snapshot.memory, locale: locale)
return ResourceCard(
@@ -85,25 +100,26 @@ extension MenuPanelView {
value: snapshot.memory.map {
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.title, detailColor: header.color, detailHelp: header.help
) {
detail: header.badgeTitle, detailColor: snapshot.memory?.pressure == 1 ? Color("MetricBattery") : header.color,
detailHelp: header.help + "\n" + MetricFormat.percent(snapshot.memory?.usage),
chartPlacement: .background,
chart: {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
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),
scaleLabel: MetricFormat.memory(snapshot.memory?.total), firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals,
showsLegendValues: cardContentWidth >= 340)
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [1, 2, 3])
}
) {
if let memory = snapshot.memory {
MemoryDetailsView(memory: memory)
} else {
CardSeparator()
Text("metric.waiting").foregroundStyle(.secondary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
@@ -114,18 +130,19 @@ extension MenuPanelView {
String(
format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 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(
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",
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) {
VStack(alignment: .leading, spacing: 8) {
Text("disk.homeVolume")
@@ -139,7 +156,7 @@ extension MenuPanelView {
"\(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)
.environment(\.locale, locale)
@@ -148,67 +165,7 @@ extension MenuPanelView {
}
}
var batteryCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
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)
PowerResourceCard(snapshot: snapshot, samples: samples, chartInterval: chartInterval,
chartBoundaries: chartBoundaries, chartIntervals: chartIntervals)
}
}
}
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)
}
}
+40 -35
View File
@@ -29,7 +29,7 @@ struct MenuPanelView: View {
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 }
}
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) }
private var cardHeights: [PanelCard: CGFloat] {
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 {
VStack(spacing: PanelStyle.gap) {
header
if presentation.page == .overview {
if PanelLayout.needsResourceScroll(size: panelSize, heights: cardHeights) {
ScrollView { resourceColumns }
if PanelLayout.needsDashboardScroll(size: panelSize, heights: cardHeights) {
ScrollView { dashboard }
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
resourceColumns
.frame(maxHeight: .infinity, alignment: .top)
}
} else if presentation.isOpen {
PanelProcessSection(metrics: metrics, state: processState)
.frame(maxWidth: .infinity, maxHeight: .infinity)
dashboard.frame(maxHeight: .infinity, alignment: .top)
}
footer
}
@@ -87,19 +81,32 @@ struct MenuPanelView: View {
}
.background(Color("PanelBackground"), in: .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))
}
private var resourceColumns: some View {
let groups = PanelLayout.cardColumns(columns: columns)
return HStack(alignment: .top, spacing: PanelStyle.gap) {
ForEach(groups.indices, id: \.self) { column in
private var dashboard: some View {
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)
.frame(maxWidth: .infinity)
.frame(height: cardHeights[card])
.frame(height: heights[row])
.onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in
if card == .cpu { measuredCardWidth = width }
}
@@ -121,52 +128,50 @@ struct MenuPanelView: View {
}
}
private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
private var brand: some View {
HStack(spacing: 6) {
Image("BrandMark").renderingMode(.template).resizable().scaledToFit()
.frame(width: 22, height: 22)
HStack(alignment: .top, spacing: 3) {
Text("Kymo").font(.system(size: 17, weight: .semibold))
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 {
VStack(spacing: 4) {
HStack(spacing: 8) {
brand
Spacer(minLength: 8)
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))
.padding(.horizontal, 4)
}
private var footer: some View {
HStack {
Text(verbatim: HardwareIdentity.displayName)
.lineLimit(1).truncationMode(.middle)
.help(Text(verbatim: HardwareIdentity.displayName))
Spacer(minLength: 8)
HStack(spacing: 4) {
Text("panel.uptime")
MetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
}.fixedSize()
Divider().frame(height: 14)
Text(verbatim: HardwareIdentity.displayName)
.lineLimit(1).truncationMode(.middle)
.help(Text(verbatim: HardwareIdentity.displayName))
Spacer(minLength: 8)
HStack(spacing: 4) {
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)
.accessibilityLabel(Text("sampling.panel"))
+36 -10
View File
@@ -17,20 +17,22 @@ import SwiftUI
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true
let scroll = FittingScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = false
scroll.horizontalScrollElasticity = .none
scroll.autohidesScrollers = true; scroll.drawsBackground = false
let table = ProcessNSTableView()
table.style = .inset; table.rowHeight = 20
table.style = .plain; table.rowHeight = 20
table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear
table.allowsMultipleSelection = false; table.allowsEmptySelection = true
table.columnAutoresizingStyle = .sequentialColumnAutoresizingStyle
for (key, width) in [("pid", 48.0), ("name", 140), ("cpu", 65), ("memory", 85), ("power", 90), ("threads", 65), ("path", 250)] {
table.columnAutoresizingStyle = .noColumnAutoresizing
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))
column.width = width
column.minWidth = key == "path" ? 150 : key == "name" ? 90 : width
column.maxWidth = key == "name" ? 180 : key == "path" ? 10_000 : width
column.resizingMask = key == "path" ? [.autoresizingMask, .userResizingMask] : .userResizingMask
column.minWidth = 0
column.maxWidth = 10_000
column.resizingMask = []
column.sortDescriptorPrototype = NSSortDescriptor(key: key, ascending: false)
table.addTableColumn(column)
}
@@ -47,7 +49,32 @@ import SwiftUI
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 {
/// 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 cancel: (() -> Void)?
override func keyDown(with event: NSEvent) {
@@ -145,7 +172,6 @@ import SwiftUI
switch key {
case "pid": text = String(process.id.pid)
case "name": text = process.name
case "path": text = process.path ?? "--"
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 "power": text = process.formattedPower
@@ -228,7 +254,7 @@ import SwiftUI
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.lineBreakMode = .byTruncatingMiddle
text.textColor = key == "path" ? .secondaryLabelColor : .labelColor
text.textColor = .labelColor
addSubview(text); textField = text
if key == "name" || key == "threads" {
let image = NSImageView(); image.imageScaling = .scaleProportionallyDown
+35 -22
View File
@@ -2,58 +2,71 @@ import Foundation
import CoreGraphics
nonisolated enum PanelCard: Int, CaseIterable {
case cpu, battery, gpu, storage, memory, network
case cpu, gpu, memory, battery, storage, network
}
nonisolated enum PanelLayout {
static let footerHeight: CGFloat = 26
static let maximumWidth: CGFloat = ResourceCardMetrics.preferredWidth * 3 + 32
static let maximumHeight: CGFloat = 800
static func headerHeight(width: CGFloat) -> CGFloat { width >= 560 ? 32 : 64 }
static func columns(width: CGFloat) -> Int { width >= 560 ? 2 : 1 }
static func headerHeight(width: CGFloat) -> CGFloat { 32 }
static func columns(width: CGFloat) -> Int { width >= 620 ? 3 : width >= 430 ? 2 : 1 }
static func cardWidth(size: CGSize) -> CGFloat {
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.
static func cardColumns(columns: Int) -> [[PanelCard]] {
columns > 1 ? [[.cpu, .gpu, .memory], [.battery, .storage, .network]] : [PanelCard.allCases]
/// Keep reading order stable across three-, two- and single-column grids.
static func cardRows(columns: Int) -> [[PanelCard]] {
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] {
let base = ResourceCardMetrics.minimumHeight
let fanRows = fanCount.map { (max(0, $0) + 1) / 2 } ?? 1
return [.cpu: 152 + CGFloat(max(1, coreRows)) * 26,
.gpu: fanRows == 0 ? 124 : 144 + CGFloat(fanRows) * 20,
.memory: 180, .battery: 170, .storage: 170, .network: 208]
return [.cpu: base + CGFloat(max(0, coreRows - 1)) * 15,
.gpu: base + CGFloat(max(0, fanRows - 1)) * 18,
.memory: base, .battery: base, .storage: base, .network: base]
}
static func columnHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] {
cardColumns(columns: columns).map { cards in
cards.reduce(0) { $0 + (heights[$1] ?? 0) } + CGFloat(max(0, cards.count - 1)) * 8
static func rowHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] {
Array(repeating: processHeight(heights: heights), count: cardRows(columns: columns).count)
}
static func processHeight(heights: [PanelCard: CGFloat]) -> CGFloat {
heights.values.max() ?? ResourceCardMetrics.minimumHeight
}
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 {
min(maximumHeight, resourceHeight(columns: columns(width: width), heights: heights)
+ 20 + headerHeight(width: width) + footerHeight + 16)
min(maximumHeight, dashboardHeight(columns: columns(width: width), heights: heights)
+ 20 + headerHeight(width: width) + footerHeight + 12)
}
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 {
resourceHeight(columns: columns(width: size.width), heights: heights)
> size.height - 20 - headerHeight(width: size.width) - footerHeight - 16
static func needsDashboardScroll(size: CGSize, heights: [PanelCard: CGFloat]) -> Bool {
dashboardHeight(columns: columns(width: size.width), heights: heights)
> size.height - 20 - headerHeight(width: size.width) - footerHeight - 12
}
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,
visible.height - 32 - max(0, chrome.height))))
}
@@ -40,12 +40,16 @@ import AppKit
controller.show()
if let value = ProcessInfo.processInfo.environment["KYMO_AUDIT_SIZE"] {
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),
height: min(parts[1], controller.panel.frame.height)))
}
}
mark("interactive")
if ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1" {
await wait(10)
mark("open1.10")
}
return
}
let quick = ProcessInfo.processInfo.environment["KYMO_AUDIT_QUICK"] == "1"
@@ -54,7 +58,6 @@ import AppKit
mark("hidden10")
for cycle in 1...3 {
controller.show()
if ProcessInfo.processInfo.environment["KYMO_AUDIT_PAGE"] == "processes" { controller.presentation.page = .processes }
mark("open\(cycle).0")
await wait(1); mark("open\(cycle).1")
await wait(9); mark("open\(cycle).10")
@@ -0,0 +1,87 @@
import SwiftUI
struct PowerResourceCard: View {
let snapshot: MetricsSnapshot
let samples: [TrendSample]
let chartInterval: TimeInterval
let chartBoundaries: Set<Date>
let chartIntervals: [TimeInterval]
@Environment(\.locale) private var locale
private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
}
@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,
firstLabel: "power.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals)
}) {
Text(snapshot.systemPower == nil ? "power.sensorUnavailable" : "panel.noBattery")
.font(.system(size: 10)).foregroundStyle(.secondary)
}
} else {
batteryChargeCard
}
}
private var batteryChargeCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
value: MetricFormat.percent(snapshot.battery?.charge),
status: snapshot.battery.map { AppLocalization.string($0.externalPower ? "battery.acPower" : "battery.batterySource", locale: locale) },
chartPlacement: .background,
chart: {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map(\.battery),
second: samples.map(\.batteryPower),
color: Color("MetricBattery"),
secondColor: Color("SeriesUser"),
fixedScale: 1,
secondSeriesUsesAutonomousScale: true,
secondValueFormat: .watts,
firstLabel: "metric.battery",
secondLabel: snapshot.battery.map(batteryPowerLabel) ?? "battery.power",
expectedInterval: chartInterval,
boundaryDates: chartBoundaries,
intervals: chartIntervals
)
}
) {
InlineMetric("battery.powerShort", MetricFormat.watts(snapshot.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 batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
InlineMetric("battery.healthShort", MetricFormat.percent(battery.health))
InlineMetric("battery.cyclesShort", battery.cycles.map(String.init) ?? "--")
}
HStack(spacing: 4) {
Text("battery.timeShort").foregroundStyle(.secondary)
if battery.externalPower {
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
} else if let minutes = battery.minutesRemaining {
MetricText(value: "\(minutes) min")
} else {
Text("battery.timeUnknown")
}
}
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9)
}
}
+4 -8
View File
@@ -31,19 +31,16 @@ struct ProcessTableView: View {
Spacer(minLength: 0)
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") }
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
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) } }
if exitedSelection != nil, let departed = state.departed {
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)
.modifier(CardSurface())
.onAppear { rebuild(retainOrder: false) }
@@ -70,14 +67,14 @@ struct ProcessTableView: View {
private var processTitle: some View {
Label("panel.processes", systemImage: "list.bullet.rectangle")
.font(PanelStyle.title)
.help(Text("\(Text("panel.processScope"))\n\(energyStatus)"))
}
private var searchField: some View {
NativeSearchField(text: $state.search, isFocused: $searchFocused,
placeholder: AppLocalization.string("panel.search", locale: locale))
}
private var energyStatus: some View {
Group {
private var energyStatus: Text {
switch energy?.state {
case .unsupported: Text("energy.unsupported")
case .unavailable: Text("energy.unavailable")
@@ -85,7 +82,6 @@ struct ProcessTableView: View {
Text("energy.coverage \(energy?.measured ?? 0) \(energy?.candidates ?? 0)")
default: Text("energy.waiting")
}
}.help(Text("energy.scopeHelp")).lineLimit(1)
}
private func rebuild(retainOrder: Bool) {
+21 -25
View File
@@ -3,40 +3,36 @@ import SwiftUI
struct StorageDetailsView: View {
let disk: DiskMetrics?
let health: DiskHealthMetrics?
let showVolumes: () -> Void
let io: DiskIOMetrics?
var body: some View {
VStack(alignment: .leading, spacing: 4) {
CardSeparator()
HStack(spacing: 8) {
VStack(spacing: 4) {
VStack(alignment: .leading, spacing: 3) {
field("memory.available", value: MetricFormat.bytes(disk?.available))
field("disk.powerOnHours", value: health?.powerOnHours.map { "\($0) h" } ?? "--")
ViewThatFits(in: .horizontal) {
HStack(spacing: 6) { read; write }.fixedSize(horizontal: true, vertical: true)
VStack(alignment: .leading, spacing: 3) { read; write }
}
Divider().frame(height: 32)
VStack(spacing: 4) {
field("disk.remainingLife", value: MetricFormat.percent(health?.remainingLife))
Button(action: showVolumes) {
HStack(spacing: 3) {
Text("disk.localVolumes")
Spacer(minLength: 3)
Image(systemName: "chevron.right").font(.system(size: 8))
}.contentShape(.rect)
}
.buttonStyle(.plain).help(Text("disk.viewDetails"))
.frame(height: 14)
}
}.font(PanelStyle.label).lineLimit(1)
ViewThatFits(in: .horizontal) {
HStack(spacing: 4) {
life
Text("·").foregroundStyle(.secondary)
powerOn
}.fixedSize(horizontal: true, vertical: true)
VStack(alignment: .leading, spacing: 3) { life; powerOn }
}
}
.font(.system(size: 10)).lineLimit(1)
}
private var read: some View { field("disk.read", value: MetricFormat.rate(io?.read)) }
private var write: some View { field("disk.write", value: MetricFormat.rate(io?.written)) }
private var life: some View { field("disk.lifeShort", value: MetricFormat.percent(health?.remainingLife)) }
private var powerOn: some View { field("disk.powerOnShort", value: health?.powerOnHours.map { "\($0) h" } ?? "--") }
private func field(_ title: LocalizedStringKey, value: String) -> some View {
HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary).help(Text(title))
Spacer(minLength: 3)
MetricText(value: value).font(PanelStyle.value)
}
.frame(height: 14)
.frame(maxWidth: .infinity)
MetricText(value: value).fontWeight(.medium).foregroundStyle(.primary)
}.frame(height: 14)
}
}
@@ -6,6 +6,8 @@ struct AppearanceSettingsView: View {
@Bindable var preferences: AppearancePreferences
@Bindable var language: LanguagePreferences
@Bindable var sampling: SamplingPreferences
let menuBar: MenuBarPreferences
let readings: () -> [MenuBarReading]
let presentation: SettingsPresentation
@Environment(\.locale) private var locale
@State private var selection = SettingsPage.general
@@ -14,6 +16,7 @@ struct AppearanceSettingsView: View {
Group {
switch selection {
case .general: generalPage
case .menuBar: MenuBarSettingsPage(preferences: menuBar, readings: readings())
case .about: aboutPage
}
}
@@ -21,7 +24,7 @@ struct AppearanceSettingsView: View {
.toolbar {
ToolbarItem(placement: .principal) {
NeutralTabPicker(title: "settings.title", selection: $selection,
options: [(.general, "settings.general"), (.about, "settings.about")])
options: [(.general, "settings.general"), (.menuBar, "settings.menuBar"), (.about, "settings.about")])
}
.sharedBackgroundVisibility(.hidden)
}
@@ -120,5 +123,5 @@ private extension AppAppearance {
}
private enum SettingsPage: Hashable {
case general, about
case general, menuBar, 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"
+521 -6
View File
@@ -1,6 +1,314 @@
{
"sourceLanguage" : "en",
"strings" : {
"power.system": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "System power"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "整机功率"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "整機功率"
}
}
}
},
"power.sensorUnavailable": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Power sensor unavailable"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "功率传感器不可用"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "功率感測器無法使用"
}
}
}
},
"memory.distributionHelp" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "App includes anonymous memory used by apps and system processes. Wired includes resident kernel and driver memory. Compressed is physical compressor memory. Reclaimable cache is included in available memory; disk Swap is not added to physical memory usage."
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "应用包含应用和系统进程使用的匿名内存;联动包含内核、驱动等常驻内存;压缩为压缩器的实际物理占用。可回收缓存计入可用空间,磁盘 Swap 不再叠加到物理内存已用量。"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "應用包含應用和系統程序使用的匿名記憶體;連動包含核心、驅動等常駐記憶體;壓縮為壓縮器的實際實體佔用。可回收快取計入可用空間,磁碟 Swap 不再疊加到實體記憶體已用量。"
}
}
}
},
"disk.lifeShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Life"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "剩余寿命"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "剩餘壽命"
}
}
}
},
"disk.powerOnShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "On-time"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "通电"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "通電"
}
}
}
},
"battery.healthShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Health"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "健康"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "健康"
}
}
}
},
"battery.cyclesShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Cycles"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "循环"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "循環"
}
}
}
},
"battery.timeShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Time"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "续航"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "續航"
}
}
}
},
"battery.powerShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Power"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "功率"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "功率"
}
}
}
},
"memory.appShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "App"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "应用"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "應用"
}
}
}
},
"memory.wiredShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Wired"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "联动"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "連動"
}
}
}
},
"memory.compressedShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Compressed"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "压缩"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "壓縮"
}
}
}
},
"memory.pressurePrefix" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Pressure "
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "压力"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "壓力"
}
}
}
},
"network.totalShort" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Total"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "累计"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "累計"
}
}
}
},
"battery.notApplicableShort" : {
"localizations" : {
"en" : {
@@ -2667,19 +2975,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Uptime"
"value" : "System uptime"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "运行时间"
"value" : "开机时间"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "執行時間"
"value" : "開機時間"
}
}
}
@@ -2981,6 +3289,213 @@
}
}
},
"settings.menuBar" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Menu Bar"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "菜单栏"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "選單列"
}
}
}
},
"menuBar.preview %@" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Menu bar preview: %@"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "菜单栏预览:%@"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "選單列預覽:%@"
}
}
}
},
"menuBar.items" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Displayed items"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "显示项目"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "顯示項目"
}
}
}
},
"menuBar.deselectAll" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Deselect All"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "取消全选"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "取消全選"
}
}
}
},
"menuBar.disk" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Disk"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "磁盘"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "磁碟"
}
}
}
},
"menuBar.utilization" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Utilization"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "使用率"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "使用率"
}
}
}
},
"menuBar.usedFraction" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Percent used"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "已用比例"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "已用比例"
}
}
}
},
"menuBar.diskSpace" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Disk space used"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "空间已用比例"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "空間已用比例"
}
}
}
},
"menuBar.networkRate" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Upload and download rates"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "上传和下载速率"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "上傳和下載速率"
}
}
}
},
"settings.title" : {
"extractionState" : "manual",
"localizations" : {
@@ -3010,19 +3525,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "When off, hiding the panel stops recording and leaves gaps in charts. When on, recording follows the background interval. Pausing or system sleep stops recording."
"value" : "Menu bar items update at the panel interval while the display is awake. Enable background recording to keep trends when neither is displayed. Pausing or system sleep stops recording."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "关闭时,隐藏面板停止记录,图表保留空档。开启后按后台间隔记录;暂停或系统睡眠期间不记录。"
"value" : "亮屏时,菜单栏指标按面板间隔刷新。面板和菜单栏均不展示指标时,可开启后台记录以延续趋势。暂停或系统睡眠时停止记录。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "關閉時,隱藏面板停止記錄,圖表保留空檔。開啟後按背景間隔記錄;暫停或系統睡眠期間不記錄。"
"value" : "螢幕亮起時,選單列指標依面板間隔更新。面板與選單列均未顯示指標時,可開啟背景記錄以延續趨勢。暫停或系統睡眠時停止記錄。"
}
}
}
+2 -1
View File
@@ -17,6 +17,7 @@ struct ChartTooltipPreference: PreferenceKey {
/// Measures the actual localized tooltip, then keeps it inside the card.
struct ChartTooltipLayer: Layout {
let point: CGPoint
var minimumY: CGFloat = 0
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
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 below = point.y + 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)
}
}
+110 -20
View File
@@ -1,13 +1,32 @@
import AppKit
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 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 .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 {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
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? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -16,7 +35,7 @@ struct NativePanelCurve: NSViewRepresentable {
func makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
hoveredIndex: hoveredIndex))
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked, projection: projection, animates: animates))
}
struct Input: Equatable {
let frame: PanelCurveFrame
@@ -24,16 +43,25 @@ struct NativePanelCurve: NSViewRepresentable {
let scales: [Double]
let maximumGap: TimeInterval
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 {
private(set) var input: Input?
private(set) var pathBuildCount = 0
let grid = CAShapeLayer()
let baseline = CAShapeLayer()
let curves = CALayer()
let hoverLine = CAShapeLayer()
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
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 func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -43,8 +71,10 @@ struct NativePanelCurve: NSViewRepresentable {
layer?.masksToBounds = true
curves.anchorPoint = .zero
grid.fillColor = nil; grid.lineWidth = 0.5
grid.isHidden = true
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)
}
required init?(coder: NSCoder) { nil }
@@ -53,17 +83,46 @@ struct NativePanelCurve: NSViewRepresentable {
guard input != value else { return }
let old = input
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
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)
if old?.projection != value.projection { updateBaseline() }
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count { updatePalette() }
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap {
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count
|| 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()
}
updateHover()
if slides, let old { slide(from: old.frame, to: value.frame) }
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) {
while seriesLayers.count < count {
let series = SeriesLayer(); seriesLayers.append(series); curves.addSublayer(series.root)
@@ -77,17 +136,30 @@ struct NativePanelCurve: NSViewRepresentable {
private func updatePalette() {
effectiveAppearance.performAsCurrentDrawingAppearance {
palette = input?.colors.map(NSColor.init) ?? []
baseline.strokeColor = NSColor.labelColor.withAlphaComponent(0.12).cgColor
grid.strokeColor = NSColor.labelColor.withAlphaComponent(0.10).cgColor
hoverLine.strokeColor = NSColor.labelColor.withAlphaComponent(0.45).cgColor
guard !palette.isEmpty else { return }
for index in seriesLayers.indices {
let color = palette[min(index, palette.count - 1)], series = seriesLayers[index]
series.line.strokeColor = color.cgColor; series.points.fillColor = color.cgColor
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
}
}
}
private func updateBaseline() {
baseline.frame = bounds
baseline.isHidden = input?.projection == .fullHeight || input == nil
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: bounds.height * 0.6))
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height * 0.6))
baseline.path = path
}
private func updateGrid() {
updateBaseline()
grid.frame = bounds; hoverLine.frame = bounds
curves.bounds = bounds; curves.position = .zero
let path = CGMutablePath()
@@ -109,18 +181,21 @@ struct NativePanelCurve: NSViewRepresentable {
return
}
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 {
let series = seriesLayers[index]
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 runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index], maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals)
let line = CGMutablePath(), dots = CGMutablePath()
let upper = input.stacked ? plottedBands[index].upper : frame.series[index]
let lower = input.stacked ? plottedBands[index].lower : nil
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 {
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 }
if points.count == 1 {
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
@@ -131,9 +206,20 @@ struct NativePanelCurve: NSViewRepresentable {
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
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.points.path = dots
series.area.path = area
}
}
private func updateHover() {
@@ -145,10 +231,12 @@ struct NativePanelCurve: NSViewRepresentable {
let x = bounds.width * domain.position(input.frame.dates[index])
let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path
for series in input.frame.series.indices {
let values = input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let scale = input.scales[min(series, input.scales.count - 1)]
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
let plottedIndex = index + (input.stacked ? (drawingFrame?.dates.count ?? input.frame.dates.count) - input.frame.dates.count : 0)
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)
}
}
@@ -156,12 +244,14 @@ struct NativePanelCurve: NSViewRepresentable {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
curves.removeAnimation(forKey: Self.slideKey)
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { curves.removeAnimation(forKey: Self.slideKey) }
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
@@ -171,17 +261,17 @@ struct NativePanelCurve: NSViewRepresentable {
updatePalette(); CATransaction.commit()
}
private final class SeriesLayer {
let root = CALayer(), line = CAShapeLayer(), points = CAShapeLayer()
let root = CALayer(), area = CAShapeLayer(), line = CAShapeLayer(), points = CAShapeLayer()
init() {
line.fillColor = nil; line.lineWidth = 1.5; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(line); root.addSublayer(points)
line.fillColor = nil; line.lineWidth = 1.4; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(area); root.addSublayer(line); root.addSublayer(points)
}
func resize(_ bounds: CGRect) {
root.frame = bounds
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
/// 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 {
let dates: [Date]
let series: [[Double?]]
let intervals: [TimeInterval]
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 {
let begin: TimeInterval
let end: TimeInterval
+8 -2
View File
@@ -4,6 +4,7 @@ nonisolated enum PanelCurveGeometry {
struct Sample {
let date: Date
let value: Double
var lower: Double = 0
}
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
}
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 run: [Sample] = []
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() }
// 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 }
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()
return result
+35 -59
View File
@@ -8,7 +8,7 @@ enum TrendValueFormat {
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 {
let dates: [Date]
let first: [Double?]
@@ -20,7 +20,6 @@ struct PanelTrendChart: View {
var thirdColor: Color = .purple
var fourthColor: Color = .yellow
var fixedScale: Double? = 1
var scaleLabel: String?
var secondSeriesUsesAutonomousScale = false
var firstValueFormat: TrendValueFormat?
var secondValueFormat: TrendValueFormat?
@@ -31,8 +30,12 @@ struct PanelTrendChart: View {
var expectedInterval: TimeInterval = 2
var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = []
var plotHeight: CGFloat = PanelStyle.plotHeight
var showsLegendValues = true
var visibleSeriesCount = 1
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 smallSamples = 0
@State private var retainedSecondScale: Double = 1
@@ -47,7 +50,22 @@ struct PanelTrendChart: View {
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
boundaryDates: boundaryDates)
}
private var maximum: Double { max(1, (first + second + third + fourth).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var renderFrame: PanelCurveFrame {
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 ?? []
return max(1, values.compactMap { $0 }.filter(\.isFinite).max() ?? 1)
}
private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
private var secondaryScale: Double { max(0.0001, retainedSecondScale) }
@@ -73,16 +91,6 @@ struct PanelTrendChart: View {
case .watts: return MetricFormat.watts(value)
}
}
private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil) -> 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) {
RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8)
@@ -92,42 +100,26 @@ struct PanelTrendChart: 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)
tooltipRow(firstLabel, values: first, tint: color, index: index)
if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, format: secondValueFormat, index: index) }
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
}
.font(.system(size: 10)).padding(8)
.font(.system(size: 9)).padding(6)
.background { TooltipBackground() }
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
}
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
ZStack(alignment: .topLeading) {
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index)
}
NativePanelCurve(frame: renderFrame, colors: renderColors,
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
filledSeriesCount: stackOrder.isEmpty ? (filledSeriesCount ?? visibleSeriesCount) : stackOrder.count, stacked: !stackOrder.isEmpty, projection: projection,
animates: active && !reduceMotion)
.contentShape(Rectangle())
.onContinuousHover { phase in
switch phase {
@@ -139,30 +131,12 @@ struct PanelTrendChart: View {
case .ended: hoveredDate = nil; hoverPoint = nil
}
}
.clipped()
}.frame(height: plotHeight)
.anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in
guard let hoverPoint, let index else { return nil }
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)
}
}
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)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
retainedScale = maximum
retainedSecondScale = secondMaximum
@@ -181,6 +155,8 @@ struct PanelTrendChart: View {
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
/// 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 {
let title: Text
let rpm: Double?
var isActive = true
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
HStack(spacing: 5) {
Image(systemName: "fanblades.fill")
.foregroundStyle(.secondary)
.frame(width: 14, height: 14).accessibilityHidden(true)
HStack(spacing: 3) {
FanRotor(rpm: rpm, isActive: isActive, reduceMotion: reduceMotion)
.frame(width: 11, height: 11).accessibilityHidden(true)
title.foregroundStyle(.secondary)
Spacer(minLength: 2)
MetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.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
var range: ClosedRange<Int> = 500...1_800_000
var step = 100
var fieldWidth: CGFloat = 64
@State private var text = ""
@FocusState private var focused: Bool
@@ -13,7 +14,7 @@ struct IntervalControl: View {
TextField("sampling.seconds", text: $text)
.labelsHidden()
.textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing)
.frame(width: 64).focused($focused)
.frame(width: fieldWidth).focused($focused)
.onChange(of: text) { _, value in
if let seconds = Double(value.replacingOccurrences(of: ",", with: ".")), seconds.isFinite,
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
}
}
+5 -3
View File
@@ -4,17 +4,19 @@ import SwiftUI
struct MetricProgressBar: View {
let value: Double
let color: Color
var cornerRadius: CGFloat? = nil
private var fraction: Double { value.isFinite ? min(1, max(0, value)) : 0 }
var body: some View {
GeometryReader { proxy in
let shape = RoundedRectangle(cornerRadius: cornerRadius ?? proxy.size.height / 2, style: .continuous)
ZStack(alignment: .leading) {
Capsule().fill(color.opacity(0.15))
Capsule().fill(color).frame(width: proxy.size.width * fraction)
shape.fill(color.opacity(0.15))
shape.fill(color).frame(width: proxy.size.width * fraction)
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(Capsule())
.clipShape(shape)
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}
+22 -2
View File
@@ -1,9 +1,15 @@
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 {
let value: String
var body: some View { Text(verbatim: value).monospacedDigit() }
var body: some View {
Text(verbatim: value).monospacedDigit()
}
}
struct PanelCardBackground: ViewModifier {
@@ -13,3 +19,17 @@ struct PanelCardBackground: ViewModifier {
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
/// 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 {
static let title = Font.system(size: 13, weight: .semibold)
static let label = Font.system(size: 10)
static let value = Font.system(size: 10, weight: .medium)
static let legend = Font.system(size: 9)
static let padding: CGFloat = 10
static let gap: CGFloat = 8
static let gap: CGFloat = 6
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 {
@@ -37,15 +28,8 @@ struct CardField<Content: View>: View {
struct CardSurface: ViewModifier {
func body(content: Content) -> some View {
content.modifier(PanelCardBackground(radius: 10))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
}
}
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))
content.modifier(PanelCardBackground(radius: ResourceCardMetrics.radius))
.overlay(RoundedRectangle(cornerRadius: ResourceCardMetrics.radius).strokeBorder(.primary.opacity(0.06)))
}
}
@@ -54,6 +38,7 @@ struct CapacityBar: View {
let values: [Double]
let colors: [Color]
let total: Double
var height: CGFloat = 8
var body: some View {
GeometryReader { bounds in
@@ -65,7 +50,7 @@ struct CapacityBar: View {
}
.clipShape(Capsule())
}
.frame(height: 8)
.frame(height: height)
.accessibilityHidden(true)
}
}
+123 -51
View File
@@ -1,6 +1,12 @@
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 symbol: String
let color: Color
@@ -8,75 +14,50 @@ struct ResourceCard<Content: View>: View {
var secondaryValue: String? = nil
var valueColor: Color? = nil
var secondaryValueColor: Color? = nil
var titleBadge: String? = nil
var status: String? = nil
var statusWarning = false
var warningText: Text? = nil
var detail: String? = nil
var detailColor: Color? = nil
var detailHelp: String? = nil
var headerAccessory: AnyView? = nil
var chartPlacement: CardChartPlacement = .belowDetails
@ViewBuilder var chart: () -> Chart
@ViewBuilder var content: () -> Content
@Environment(\.colorScheme) private var colorScheme
var body: some View {
NativeContentHost(content: cardBody)
}
var body: some View { NativeContentHost(content: cardBody) }
private var cardBody: some View {
GeometryReader { bounds in
VStack(alignment: .leading, spacing: 4) {
HStack(alignment: .center, spacing: 6) {
Label {
Text(title).foregroundStyle(statusWarning ? .red : .primary)
} icon: {
Image(systemName: symbol).frame(width: 16, height: 16).foregroundStyle(statusWarning ? .red : color)
}.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)
VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
foreground
.padding(.horizontal, ResourceCardMetrics.padding)
.padding(.top, ResourceCardMetrics.padding)
if chartPlacement == .belowDetails {
chart().frame(maxWidth: .infinity, maxHeight: .infinity).clipped()
}
}
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)
.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
GeometryReader { proxy in
if let tooltip {
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)
}
.frame(width: proxy.size.width, height: proxy.size.height)
@@ -86,4 +67,95 @@ struct ResourceCard<Content: View>: View {
.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: {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : 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
}
+13 -8
View File
@@ -9,15 +9,15 @@ import SwiftUI
if let first = rows.first, let last = rows.last {
precondition(last > 0 && first - last <= 1)
let columns = rows.max()!
let cellWidth = (width - Double(columns - 1) * 6) / Double(columns)
precondition(cellWidth >= 16, "Core text must fit a readable cell instead of being forced into three rows")
let cellWidth = (width - Double(columns - 1) * 3) / Double(columns)
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: 280) == [9, 9])
precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [16, 16])
precondition(CPUCoreGridLayout.rowCounts(count: 48, width: 430) == [16, 16, 16])
precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 430) == [18])
precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 280) == [18])
precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [32])
precondition(CPUCoreGridLayout.rowCounts(count: 48, width: 430) == [24, 24])
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 groups = CPUCoreGrid.groups(count: count, kinds: kinds)
@@ -25,7 +25,8 @@ import SwiftUI
for width in [120.0, 280.0, 380.0, 800.0] {
let widths = CPUCoreGrid.groupWidths(groups: groups, width: width)
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) {
let rows = CPUCoreGridLayout.rowCounts(count: group.count, width: groupWidth)
precondition(rows.reduce(0, +) == group.count)
@@ -36,6 +37,10 @@ import SwiftUI
precondition(CPUCoreGridLayout.rowCounts(count: 128, width: width).reduce(0, +) == 128)
}
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")
}
}
+6 -6
View File
@@ -13,17 +13,17 @@ import Foundation
store.setPanelVisible(true)
try await until { store.history.samples.count >= 2 }
precondition(probe.count == 0 && store.processSnapshot == nil && store.energy == nil,
"Overview must not enumerate processes or publish process power")
store.setDetailDemand(processes: true, slowMetrics: false)
"Disabled process demand must not enumerate processes or publish process power")
store.setDetailDemand(processes: true, slowMetrics: true)
try await until { probe.count > 0 }
// Withdraw demand while the synchronous OS read still holds the single slot.
store.setDetailDemand(processes: false, slowMetrics: true)
try await Task.sleep(for: .milliseconds(350))
precondition(store.processSnapshot == nil, "A completion from the previous page must not publish")
precondition(store.processSnapshot == nil, "A completion from the withdrawn demand must not publish")
let stopped = probe.count
try await Task.sleep(for: .milliseconds(650))
precondition(probe.count == stopped && store.snapshot.cpu != nil)
store.setDetailDemand(processes: true, slowMetrics: false)
store.setDetailDemand(processes: true, slowMetrics: true)
try await until { store.processSnapshot != nil }
precondition(probe.peak == 1)
precondition(store.history.samples.dropFirst().allSatisfy { !$0.breakBefore && $0.cpu != nil },
@@ -32,7 +32,7 @@ import Foundation
precondition(store.processSnapshot == nil && store.energy == nil)
store.togglePause()
let pausedCount = store.history.samples.count
store.setDetailDemand(processes: true, slowMetrics: false)
store.setDetailDemand(processes: true, slowMetrics: true)
try await Task.sleep(for: .milliseconds(650))
precondition(store.history.samples.count == pausedCount && store.processSnapshot == nil)
store.togglePause()
@@ -40,7 +40,7 @@ import Foundation
store.setPanelVisible(false)
precondition(store.processSnapshot == nil && store.energy == nil)
store.togglePause()
print("PASS: overview performs no process reads, page withdrawal rejects stale completion, single in-flight read, continuous base history and pause/hidden precedence")
print("PASS: disabled demand performs no process reads, unified demand supports both details, withdrawal rejects stale completion, single in-flight read, continuous base history and pause/hidden precedence")
}
@MainActor private static func until(_ condition: () -> Bool) async throws {
+12 -1
View File
@@ -10,7 +10,18 @@ import Foundation
precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0, bytes: []) == nil)
precondition(FanMetrics.validRPM(0) == 0)
for value in [Double.nan, .infinity, -1, 30_001] { precondition(FanMetrics.validRPM(value) == nil) }
print("PASS: fan decoding, invalid RPM and static indicator data")
for (rpm, speed) in [(1.0,90.0), (1999,90), (2000,180), (3999,180), (4000,300), (5999,300), (6000,450)] {
precondition(FanRotation.speed(rpm: rpm, reducedMotion: false) == speed)
precondition(FanRotation.speed(rpm: rpm, reducedMotion: true) == 0)
}
var rotation = FanRotation()
rotation.update(rpm: 1000, reducedMotion: false, at: 10)
precondition(rotation.angle(at: 11) == 90)
rotation.update(rpm: 3000, reducedMotion: false, at: 11)
precondition(rotation.angle(at: 11) == 90 && rotation.angle(at: 12) == 270)
rotation.update(rpm: 0, reducedMotion: false, at: 12)
precondition(rotation.angle(at: 100) == 270)
print("PASS: fan decoding, invalid RPM, historical speed boundaries and continuous phase")
print("Live fan RPM:", CPUTemperatureMonitor().sampleFans() as Any)
}
}
+51
View File
@@ -0,0 +1,51 @@
import AppKit
import SwiftUI
@main struct FanRotorChecks {
@MainActor static func main() {
_ = NSApplication.shared; NSApp.setActivationPolicy(.accessory)
Task { @MainActor in
let window = NSWindow(contentRect: NSRect(x: 30, y: 30, width: 40, height: 40), styleMask: [.borderless], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
let rotor = FanRotor.RotorView(); rotor.frame = NSRect(x: 4, y: 4, width: 20, height: 20)
window.contentView!.addSubview(rotor); window.orderFrontRegardless()
try? await Task.sleep(for: .milliseconds(100))
for size: CGFloat in [11,20,32] {
rotor.setFrameSize(NSSize(width: size, height: size)); rotor.layoutSubtreeIfNeeded()
precondition(rotor.rotorLayer.anchorPoint == CGPoint(x: 0.5, y: 0.5))
precondition(rotor.rotorLayer.contents != nil)
precondition(CATransform3DIsIdentity(rotor.layer!.transform), "AppKit's host layer must never rotate")
CATransaction.begin(); CATransaction.setDisableActions(true)
for degrees in [0.0,45,90,180,270] {
rotor.rotorLayer.transform = CATransform3DMakeRotation(degrees * .pi / 180, 0, 0, 1)
let center = rotor.rotorLayer.convert(CGPoint(x: size / 2, y: size / 2), to: rotor.layer!)
precondition(abs(center.x - rotor.bounds.midX) < 1e-9 && abs(center.y - rotor.bounds.midY) < 1e-9,
"The icon center must not orbit at any angle or size")
}
rotor.rotorLayer.transform = CATransform3DIdentity
CATransaction.commit()
}
for (rpm, duration) in [(1000.0,4.0),(2000,2),(4000,1.2),(6000,0.8)] {
rotor.configure(rpm: rpm, active: true, reducedMotion: false)
precondition(abs(rotor.rotorLayer.animation(forKey: FanRotor.RotorView.animationKey)!.duration - duration) < 1e-9)
}
for rpm: Double? in [0,nil,.nan,-1] {
rotor.configure(rpm: rpm, active: true, reducedMotion: false)
precondition(rotor.rotorLayer.animationKeys()?.isEmpty != false)
}
rotor.configure(rpm: 3000, active: true, reducedMotion: false)
precondition(rotor.rotorLayer.animationKeys()?.isEmpty == false)
rotor.configure(rpm: 3000, active: false, reducedMotion: false)
precondition(rotor.rotorLayer.animationKeys()?.isEmpty != false)
rotor.configure(rpm: 3000, active: true, reducedMotion: true)
precondition(rotor.rotorLayer.animationKeys()?.isEmpty != false)
rotor.configure(rpm: 3000, active: true, reducedMotion: false)
rotor.removeFromSuperview()
precondition(rotor.rotorLayer.animationKeys()?.isEmpty != false, "Detached fans must stop rotating")
window.orderOut(nil); window.close()
print("PASS: centered child-layer rotation at multiple angles/sizes, native rotor speed tiers, nil/zero/invalid readings, inactive/reduced motion and detach stop")
NSApp.terminate(nil)
}
NSApp.run()
}
}
+9
View File
@@ -4,6 +4,15 @@ import Foundation
precondition(MetricFormat.memory(51_539_607_552) == "48.0 GiB")
precondition(MetricFormat.memory(0) == "0 B")
precondition(MetricFormat.memory(nil) == "--")
for m in [
MemoryMetrics(total: 48 << 30, used: 26 << 30, wired: 3 << 30, compressed: 1 << 30, swapUsed: 8 << 30, pressure: 1, cached: 17 << 30),
MemoryMetrics(total: 32 << 30, used: 20 << 30, wired: 2 << 30, compressed: 13 << 30, swapUsed: 4 << 30, pressure: 2, cached: 8 << 30),
MemoryMetrics(total: 16 << 30, used: 0, wired: 0, compressed: 0, swapUsed: 0, pressure: 1, cached: 12 << 30)
] {
precondition(m.app + m.wired + m.compressed == m.used)
precondition(m.app + m.wired + m.compressed + m.available == m.total)
precondition(m.available == m.total - m.used, "Reclaimable cache and disk swap must not be added again")
}
guard let m = MemoryMonitor.sample() else { fatalError("No sample") }
precondition(m.app + m.wired + m.compressed + m.available == m.total)
var snapshot = MetricsSnapshot()
+2
View File
@@ -13,6 +13,7 @@ import Foundation
compressed: 2 << 30, swapUsed: 0, pressure: pressure, cached: 12 << 30)
let header = MemoryHeaderInfo(memory: memory, locale: locale, bundle: bundle)
precondition(header.title == title)
precondition(header.badgeTitle == localized("memory.pressurePrefix") + title)
precondition(header.help.components(separatedBy: "\n") == [
"\(localized("memory.pressure")): \(title)",
"\(localized("memory.cached")): 12.0 GiB",
@@ -24,6 +25,7 @@ import Foundation
swapUsed: nil, pressure: pressure)
let header = MemoryHeaderInfo(memory: unknown, locale: locale, bundle: bundle)
precondition(header.title == "--")
precondition(header.badgeTitle == "--")
precondition(header.help.components(separatedBy: "\n").allSatisfy { $0.hasSuffix(": --") })
}
let absent = MemoryHeaderInfo(memory: nil, locale: locale, bundle: bundle)
+94
View File
@@ -0,0 +1,94 @@
import Foundation
@main struct MenuBarMetricChecks {
@MainActor static func main() async throws {
let suite = "kymo-menubar-checks-" + UUID().uuidString
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let preferences = MenuBarPreferences(defaults: defaults)
precondition(preferences.selected == Set(MenuBarMetric.allCases))
let sampling = SamplingPreferences(defaults: defaults)
sampling.panelMilliseconds = 500
sampling.backgroundMilliseconds = 30000
let store = MetricsStore(sampling: sampling)
var demandChanges: [Bool] = []
preferences.onDemandChange = { demandChanges.append($0); store.setMenuBarEnabled($0) }
store.setMenuBarEnabled(!preferences.selected.isEmpty)
try await until { store.history.samples.count >= 2 }
precondition(!store.isPanelVisible && store.processSnapshot == nil && store.effectiveMilliseconds == 500)
sampling.panelMilliseconds = 1200
precondition(store.effectiveMilliseconds == 1200)
let beforeChange = store.history.samples.count
try await until { store.history.samples.count >= beforeChange + 2 }
let times = store.history.samples.suffix(2).map(\.date)
precondition(times[1].timeIntervalSince(times[0]) >= 1.1, "Hidden menu bar must adopt the new foreground interval")
sampling.panelMilliseconds = 500
preferences.set(.gpu, enabled: false)
precondition(!preferences.allSelected)
preferences.setAllSelected(true)
precondition(preferences.allSelected && MenuBarPreferences(defaults: defaults).allSelected && demandChanges.isEmpty)
preferences.setAllSelected(false)
preferences.setAllSelected(false)
precondition(MenuBarPreferences(defaults: defaults).selected.isEmpty && demandChanges == [false])
try await expectStopped(store)
preferences.setAllSelected(true)
precondition(preferences.allSelected && demandChanges == [false, true])
preferences.setAllSelected(false)
preferences.set(.disk, enabled: true)
preferences.set(.cpu, enabled: true)
preferences.set(.cpu, enabled: true)
let restored = MenuBarPreferences(defaults: defaults)
precondition(restored.selected == [.cpu, .disk] && demandChanges == [false, true, false, true])
let last = store.snapshot.date
try await until { store.snapshot.date > last }
precondition(store.history.samples.last?.breakBefore == true)
store.setDisplaySleeping(true)
try await expectStopped(store)
store.setDisplaySleeping(false)
let wake = store.snapshot.date
try await until { store.snapshot.date > wake }
store.togglePause()
try await expectStopped(store)
checkReadings()
print("PASS: menu bar persistence, selection demand, hidden-panel sampling, sleep, pause, ordered vertical gauges, disk space, independent transfer rates and missing data")
}
private static func checkReadings() {
let selected = Set(MenuBarMetric.allCases)
var snapshot = MetricsSnapshot()
snapshot.cpu = CPUMetrics(usage: 0.86, user: 0.86, system: 0, cores: [])
snapshot.gpu = GPUMetrics(usage: 0.12, coreCount: nil)
snapshot.memory = MemoryMetrics(total: 100, used: 64, wired: 0, compressed: 0, swapUsed: nil, pressure: nil)
snapshot.disk = DiskMetrics(total: 1_000, available: 270)
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 0, sent: 0,
download: 2_400_000, upload: 128_000)]
func readings() -> [MenuBarReading] {
MenuBarReading.readings(selection: selected, snapshot: snapshot) { $0.rawValue }
}
let result = readings()
precondition(result.map(\.metric) == MenuBarMetric.allCases)
precondition(result.map(\.content) == [.usage(0.86), .usage(0.12), .usage(0.64), .usage(0.73),
.network(upload: "128 KB/s", download: "2.4 MB/s")])
snapshot.disk = nil
snapshot.diskIO = DiskIOMetrics(read: 40_000_000, written: 60_000_000)
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 0, sent: 0, download: 0, upload: nil)]
precondition(readings()[3].content == .usage(nil))
precondition(readings()[4].content == .network(upload: "--", download: "0 B/s"))
snapshot.disk = DiskMetrics(total: 100, available: 0)
precondition(readings()[3].accessibilityText == "disk 100%")
snapshot = MetricsSnapshot()
precondition(readings().accessibilitySummary == "cpu --, gpu --, memory --, disk --, network ↑ --, ↓ --")
}
@MainActor private static func expectStopped(_ store: MetricsStore) async throws {
let date = store.snapshot.date
try await Task.sleep(for: .milliseconds(750))
precondition(store.snapshot.date == date && store.processSnapshot == nil)
}
@MainActor private static func until(_ condition: () -> Bool) async throws {
let deadline = ContinuousClock.now.advanced(by: .seconds(4))
while !condition() && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) }
precondition(condition())
}
}
+15 -15
View File
@@ -11,7 +11,7 @@ import SwiftUI
styleMask: [.borderless], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
window.level = .floating
let host = NSHostingView(rootView: Example(value: "128", probe: probe))
let host = NSHostingView(rootView: Example(value: "12.8 W", probe: probe))
host.sizingOptions = []
window.contentView = host
window.orderFrontRegardless()
@@ -22,18 +22,18 @@ import SwiftUI
precondition(probe.appearances == 1 && probe.locale == "en_US" && probe.font == .system(size: 22, weight: .medium))
precondition(redPixels(before) > 30, "Foreground style must cross the native boundary")
let originalLifetime = ObjectIdentifier(probe.lifetime!)
host.rootView = Example(value: "345", probe: probe)
try? await Task.sleep(for: .milliseconds(140))
let settled = bitmap(host)
try? await Task.sleep(for: .milliseconds(600))
let after = bitmap(host)
precondition(before.bitmapData != nil && after.bitmapData != nil)
precondition(pixels(before) != pixels(after), "Changed values must reach the retained child host")
precondition(pixels(settled) == pixels(after),
"A sample must settle immediately without numeric rolling or a later animation frame")
host.rootView = Example(value: "12.9 W", probe: probe)
try? await Task.sleep(for: .milliseconds(40))
let updated = pixels(bitmap(host))
precondition(updated != pixels(before), "The next render must display the new reading")
try? await Task.sleep(for: .milliseconds(500))
precondition(updated == pixels(bitmap(host)), "Updated digits must be stationary")
host.rootView = Example(value: "12.8 W", probe: probe)
try? await Task.sleep(for: .milliseconds(40))
precondition(pixels(bitmap(host)) == pixels(before), "A decrease must restore the original digits immediately")
precondition(probe.appearances == 1 && probe.lifetime.map(ObjectIdentifier.init) == originalLifetime,
"Sampling must update mounted content, not remount it")
host.rootView = Example(value: "345", probe: probe, locale: "zh_CN")
host.rootView = Example(value: "12.9 W", probe: probe, locale: "zh_CN")
try? await Task.sleep(for: .milliseconds(100))
precondition(probe.locale == "zh_CN")
window.setContentSize(NSSize(width: 360, height: 100))
@@ -44,7 +44,7 @@ import SwiftUI
}
let child = childHost(host)
precondition(child?.bounds.size == host.bounds.size, "The parent must remain the sole frame owner")
host.rootView = Example(value: "345", probe: probe, visible: false)
host.rootView = Example(value: "12.9 W", probe: probe, visible: false)
try? await Task.sleep(for: .milliseconds(150))
precondition(probe.disappearances == 1)
let releaseDeadline = ContinuousClock.now.advanced(by: .seconds(1))
@@ -55,7 +55,7 @@ import SwiftUI
window.orderOut(nil)
window.contentView = nil
window.close()
print("PASS: static card host preserves immediate stable text, inherited font/style/locale, child state, resize and unmount")
print("PASS: card host displays stationary updated digits and preserves inherited font/style/locale, child state, resize and unmount")
fflush(stdout)
NSApp.terminate(nil)
}
@@ -118,12 +118,12 @@ import SwiftUI
}
return data
}
private static func redPixels(_ bitmap: NSBitmapImageRep) -> Int {
private static func redPixels(_ bitmap: NSBitmapImageRep, contrast: CGFloat = 0.2) -> Int {
var count = 0
for x in 0..<bitmap.pixelsWide {
for y in 0..<bitmap.pixelsHigh {
if let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB),
color.redComponent > color.greenComponent + 0.2 && color.redComponent > color.blueComponent + 0.2 {
(color.redComponent - max(color.greenComponent, color.blueComponent)) * color.alphaComponent > contrast {
count += 1
}
}
+94 -1
View File
@@ -23,6 +23,10 @@ import QuartzCore
plot.configure(continuous)
let image = bitmap(plot)
precondition(redPixels(image, from: 0.4, to: 0.6) > 10, "Continuous curve must cross the middle")
let fill = image.colorAt(x: image.pixelsWide / 2, y: image.pixelsHigh / 2)!
precondition(fill.alphaComponent > 0.10 && fill.alphaComponent < 0.18,
"A continuous run must have a translucent area below its real curve")
precondition(plot.grid.isHidden, "Background trends must not draw a chart grid")
plot.needsDisplay = false; plot.configure(continuous)
precondition(!plot.needsDisplay, "Identical inputs must not invalidate the plot")
plot.configure(input([0.8,0.8,nil,0.8]))
@@ -39,6 +43,20 @@ import QuartzCore
precondition(dots.path == nil, "Connecting a missing value must not invent a measured hover dot")
plot.configure(input([nil,nil,nil,nil]))
precondition(redPixels(bitmap(plot)) == 0)
plot.configure(input([nil,0.8,nil,nil]))
let single = bitmap(plot)
precondition(single.colorAt(x: single.pixelsWide / 2, y: single.pixelsHigh / 2)!.alphaComponent == 0,
"A single sample must not create a fabricated area")
var hiddenSeries = NativePanelCurve.Input(frame: .init(dates: dates,
series: [[nil,nil,nil,nil], [0.8,0.8,0.8,0.8]], intervals: [2,2,2,2], boundaryDates: []),
colors: [.red, .red], scales: [1], maximumGap: 5)
hiddenSeries.visibleSeriesCount = 1; hiddenSeries.hoveredIndex = 1
plot.configure(hiddenSeries)
precondition(redPixels(bitmap(plot)) == 0, "A tooltip-only series must not leak lines, fill or hover dots")
var unfilled = continuous; unfilled.filledSeriesCount = 0
plot.configure(unfilled)
let noArea = bitmap(plot)
precondition(noArea.colorAt(x: noArea.pixelsWide / 2, y: noArea.pixelsHigh / 2)!.alphaComponent == 0)
let changedDates = [0.0, 2, 8, 10].map { Date(timeIntervalSinceReferenceDate: $0) }
plot.configure(.init(frame: .init(dates: changedDates, series: [[0.8,0.8,0.8,0.8]],
intervals: [2,30,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5))
@@ -77,14 +95,89 @@ import QuartzCore
series: [Array(repeating: 0.8, count: 59) + [0.5]], intervals: fullFrame.intervals, boundaryDates: [])
plot.configure(.init(frame: appended, colors: [.red], scales: [1], maximumGap: 5))
precondition(plot.input?.frame.dates.count == 60, "Static history must not retain an outgoing animation point")
var moving = NativePanelCurve.Input(frame: appended, colors: [.red], scales: [1], maximumGap: 5, animates: true)
plot.configure(.init(frame: fullFrame, colors: [.red], scales: [1], maximumGap: 5))
plot.configure(moving)
let slide = plot.curves.animation(forKey: "trend.slide") as? CABasicAnimation
let start = (slide?.fromValue as? NSValue)?.caTransform3DValue
precondition(abs((start?.m41 ?? 0) - 280.0/59) < 0.001 && slide?.duration == 0.35)
let movingBuilds = plot.pathBuildCount
moving.hoveredIndex = 3
plot.configure(moving)
precondition(plot.curves.animationKeys()?.isEmpty != false && plot.pathBuildCount == movingBuilds)
plot.configure(.init(frame: .init(dates: Array(appended.dates.dropFirst()) + [Date(timeIntervalSinceReferenceDate: 122)],
series: appended.series, intervals: appended.intervals, boundaryDates: [Date(timeIntervalSinceReferenceDate: 122)]),
colors: [.red], scales: [1], maximumGap: 5, animates: true))
precondition(plot.curves.animationKeys()?.isEmpty != false, "Do not slide through a pause")
// Adding a series with an unchanged palette must color the new layer too.
plot.configure(.init(frame: PanelCurveFrame(dates: dates, series: [[nil,nil,nil,nil], [0.5,0.5,0.5,0.5]],
intervals: [2,2,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5))
precondition(redPixels(bitmap(plot), from: 0.4, to: 0.6) > 10)
// Distinct cumulative bands must meet at 30%, with 70% total at the full plot scale.
var stack = NativePanelCurve.Input(frame: .init(dates: dates,
series: [Array(repeating: 0.3, count: 4), Array(repeating: 0.4, count: 4)],
intervals: [2,2,2,2], boundaryDates: []), colors: [.red,.blue], scales: [1], maximumGap: 5,
filledSeriesCount: 2, stacked: true)
plot.configure(stack)
let upperArea = (plot.curves.sublayers![1].sublayers![0] as! CAShapeLayer).path!.boundingBoxOfPath
precondition(abs(upperArea.minY - 18) < 1e-9 && abs(upperArea.maxY - 42) < 1e-9,
"The upper component must fill only between cumulative boundaries")
let stackedBitmap = bitmap(plot)
var redBand = 0, blueBand = 0
for y in 0..<stackedBitmap.pixelsHigh {
let c = stackedBitmap.colorAt(x: stackedBitmap.pixelsWide / 2, y: y)!.usingColorSpace(.deviceRGB)!
guard c.alphaComponent > 0.1 && c.alphaComponent < 0.18 else { continue }
if c.redComponent > c.blueComponent + 0.2 { redBand += 1 }
if c.blueComponent > c.redComponent + 0.2 { blueBand += 1 }
}
precondition(redBand > 20 && blueBand > 30, "Both components must produce separate translucent area pixels")
let stackedBuilds = plot.pathBuildCount
stack.hoveredIndex = 1; plot.configure(stack)
let cumulativeDot = plot.layer!.sublayers!.last as! CAShapeLayer
precondition(abs(cumulativeDot.path!.boundingBoxOfPath.midY - 18) < 1e-9)
precondition(plot.pathBuildCount == stackedBuilds)
stack = .init(frame: .init(dates: dates,
series: [Array(repeating: 0.3, count: 4), Array(repeating: 0.4, count: 4)],
intervals: [2,2,2,2], boundaryDates: [dates[2]]), colors: [.red,.blue], scales: [1], maximumGap: 5,
filledSeriesCount: 2, stacked: true)
plot.configure(stack)
precondition(redPixels(bitmap(plot), from: 0.4, to: 0.6) == 0,
"Every stack band must respect the same real sampling break")
// Rate panels use a common zero axis, not a percent scale at the card top.
var rates = NativePanelCurve.Input(frame: .init(dates: dates,
series: [Array(repeating: 0.8, count: 4), Array(repeating: 0.4, count: 4)],
intervals: [2,2,2,2], boundaryDates: []), colors: [.red,.blue], scales: [1], maximumGap: 5,
filledSeriesCount: 2, projection: .split(upwardSeries: 0))
plot.configure(rates)
@MainActor func areaBox(_ index: Int) -> CGRect {
(plot.curves.sublayers![index].sublayers![0] as! CAShapeLayer).path!.boundingBoxOfPath
}
precondition(abs(areaBox(0).minY - 21.6) < 1e-9 && abs(areaBox(0).maxY - 36) < 1e-9)
precondition(abs(areaBox(1).minY - 36) < 1e-9 && abs(areaBox(1).maxY - 43.2) < 1e-9)
precondition(!plot.baseline.isHidden && abs(plot.baseline.path!.boundingBoxOfPath.midY - 36) < 1e-9)
precondition(redPixels(bitmap(plot)) > 10)
let rateBuilds = plot.pathBuildCount
rates.hoveredIndex = 1; plot.configure(rates)
precondition(abs((plot.layer!.sublayers!.last as! CAShapeLayer).path!.boundingBoxOfPath.midY - 43.2) < 1e-9)
precondition(plot.pathBuildCount == rateBuilds)
rates.projection = .split(upwardSeries: 1); plot.configure(rates)
precondition(abs(areaBox(0).maxY - 50.4) < 1e-9 && abs(areaBox(1).minY - 28.8) < 1e-9,
"Network download must go down and upload up without negating raw rates")
precondition(plot.pathBuildCount == rateBuilds + 1)
rates = .init(frame: .init(dates: dates,
series: [Array(repeating: 0.8, count: 4), Array(repeating: 0.4, count: 4)],
intervals: [2,2,2,2], boundaryDates: [dates[2]]), colors: [.red,.blue], scales: [1], maximumGap: 5,
filledSeriesCount: 2, projection: .split(upwardSeries: 0))
plot.configure(rates)
precondition(redPixels(bitmap(plot), from: 0.4, to: 0.6) == 0)
for series in 0...1 {
precondition(PanelCurveProjection.split(upwardSeries: 0).y(value: 0, scale: 10, series: series, height: 176) == 105.6)
}
precondition(abs(PanelCurveProjection.split(upwardSeries: 0).y(value: 10, scale: 10, series: 0, height: 176) - 52.8) < 1e-9)
assertStatic(plot.layer!)
plot.removeFromSuperview()
window.orderOut(nil); window.close()
print("PASS: static curve pixels, immediate stable updates, no animation/material/gradient layers, real gaps, hover cache, palette growth, appearance, full history and unmount")
print("PASS: bidirectional rate areas/zero axis/direction/hover/gaps, stacked component pixels and cumulative hover, static background lines/area pixels, no single-point fill, hidden-series isolation, reduced-motion stable updates, rolling transform and hover cancellation, real gaps, hover cache, palette growth, appearance, full history and unmount")
fflush(stdout); NSApp.terminate(nil)
}
NSApp.run()
+24 -10
View File
@@ -62,18 +62,32 @@ private struct Host: View {
let coordinator = table.delegate as! NativeProcessTable.Coordinator
let probe = DelegateProbe(state, coordinator)
table.delegate = probe
precondition(table.numberOfRows == 500 && table.tableColumns.count == 7)
precondition(table.tableColumns.map(\.identifier.rawValue) == ["pid", "name", "cpu", "memory", "power", "threads", "path"],
"The path column must follow all process metrics")
precondition(table.numberOfRows == 500 && table.tableColumns.count == 6)
precondition(table.tableColumns.map(\.identifier.rawValue) == ["pid", "name", "cpu", "memory", "power", "threads"],
"Only the six metric columns must be visible")
precondition(table.frame.width >= table.enclosingScrollView!.contentSize.width - 1, "Native table must fill its viewport")
precondition(coordinator.createdCells > 0 && coordinator.createdCells < 200, "Rows must be virtualized")
let pathCell = table.view(atColumn: table.tableColumns.count - 1, row: 0, makeIfNecessary: true) as! NSTableCellView
precondition(pathCell.textField?.stringValue == "/test/worker-0")
let copyPath = coordinator.menu(row: 0)!.items[2]
let copyMenu = coordinator.menu(row: 0)!, copyPath = copyMenu.items[2]
precondition(copyPath.isEnabled && copyPath.representedObject as? String == "/test/worker-0")
for ascending in [false, true] {
table.sortDescriptors = [NSSortDescriptor(key: "path", ascending: ascending)]
await until { state.sorting == [ProcessSort(key: .path, order: ascending ? .forward : .reverse)] }
let savedPasteboard = NSPasteboard.general.pasteboardItems?.map { item in
item.types.compactMap { type in item.data(forType: type).map { (type, $0) } }
} ?? []
copyMenu.performActionForItem(at: 2)
precondition(NSPasteboard.general.string(forType: .string) == "/test/worker-0",
"Hiding the path column must preserve the real Copy Path action")
NSPasteboard.general.clearContents()
let restored = savedPasteboard.map { values in
let item = NSPasteboardItem(); for (type, data) in values { item.setData(data, forType: type) }; return item
}
NSPasteboard.general.writeObjects(restored)
for width: CGFloat in [900,628,340] {
window.setContentSize(CGSize(width: width, height: 260))
try? await Task.sleep(for: .milliseconds(100)); host.layoutSubtreeIfNeeded()
precondition(abs(host.bounds.width - width) < 1)
let scroll = table.enclosingScrollView!
precondition(!scroll.hasHorizontalScroller)
precondition(table.rect(ofColumn: 5).maxX <= scroll.contentView.bounds.width + 1,
"All six columns must fit the viewport without horizontal scrolling: \(width), \(table.rect(ofColumn: 5)), \(scroll.contentView.bounds)")
}
let memoryColumn = table.tableColumns.firstIndex { $0.identifier.rawValue == "memory" }!
let memoryCell = table.view(atColumn: memoryColumn, row: 0, makeIfNecessary: true) as! NSTableCellView
@@ -124,7 +138,7 @@ private struct Host: View {
window.sendEvent(escape)
await until { state.exits == 1 }
window.orderOut(nil); window.close()
print("PASS: real native table virtualization/reuse, deferred delegate writes, identity selection, sorting, copy menu, missing paths, removal, locale and in-window Esc event routing")
print("PASS: six columns fit narrow/regular viewports, real hidden-path copy, native table virtualization/reuse, deferred delegate writes, identity selection, sorting, copy menu, missing paths, removal, locale and in-window Esc event routing")
fflush(stdout); NSApp.terminate(nil)
}
NSApp.run()
+43 -28
View File
@@ -3,7 +3,7 @@ import CoreGraphics
@main struct PanelLayoutChecks {
static func main() {
precondition(PanelLayout.contentSize(visible: CGRect(x: 0, y: 0, width: 1512, height: 900)).width == 640)
precondition(PanelLayout.contentSize(visible: CGRect(x: 0, y: 0, width: 1512, height: 900)) == CGSize(width: 648, height: 630))
for visible in [CGRect(x: 0, y: 67, width: 1512, height: 882), CGRect(x: -1440, y: -200, width: 1440, height: 800), CGRect(x: 0, y: 24, width: 800, height: 600)] {
let content = PanelLayout.contentSize(visible: visible, chrome: CGSize(width: 4, height: 12))
precondition(content.width + 4 <= visible.width - 32 && content.height + 12 <= visible.height - 32)
@@ -14,42 +14,57 @@ import CoreGraphics
precondition(visible.insetBy(dx: 16, dy: 16).contains(centered))
}
}
let compact = PanelLayout.cardHeights(coreRows: 2, fanCount: 2)
precondition(PanelLayout.cardColumns(columns: 2) == [[.cpu, .gpu, .memory], [.battery, .storage, .network]])
precondition(PanelLayout.cardColumns(columns: 1).first == PanelCard.allCases)
for width: CGFloat in [480, 559, 560, 600, 640, 960] {
let compact = PanelLayout.cardHeights(coreRows: 1, fanCount: 2)
precondition(PanelLayout.cardRows(columns: 3) == [[.cpu, .gpu, .memory], [.battery, .storage, .network]])
precondition(PanelLayout.cardRows(columns: 2) == [[.cpu, .gpu], [.memory, .battery], [.storage, .network]])
precondition(PanelLayout.cardRows(columns: 1) == PanelCard.allCases.map { [$0] })
for width: CGFloat in [360, 429, 430, 559, 560, 619, 620, 648] {
let size = CGSize(width: width, height: 820)
let columns = PanelLayout.columns(width: width)
let cardWidth = PanelLayout.cardWidth(size: size)
precondition(abs(CGFloat(columns) * cardWidth + CGFloat(columns - 1) * 8 - (width - 20)) < 0.001)
let cards = PanelLayout.cardColumns(columns: columns).flatMap { $0 }
precondition(cards.count == 6 && Set(cards) == Set(PanelCard.allCases))
precondition(PanelLayout.needsResourceScroll(size: CGSize(width: width, height: 500), heights: compact))
precondition(!PanelLayout.needsResourceScroll(size: CGSize(width: width, height: 2400), heights: compact))
precondition(abs(CGFloat(columns) * cardWidth + CGFloat(columns - 1) * 6 - (width - 20)) < 0.001)
let rows = PanelLayout.cardRows(columns: columns)
precondition(rows.flatMap { $0 } == PanelCard.allCases)
precondition(rows.allSatisfy { $0.count == columns })
for (row, height) in zip(rows, PanelLayout.rowHeights(columns: columns, heights: compact)) {
precondition(row.allSatisfy { (compact[$0] ?? 0) <= height }, "Every card must fit its aligned row")
}
precondition(PanelLayout.columnHeights(columns: 2, heights: compact) == [564, 564],
"The compact memory card must align ordinary two-column bottoms")
precondition(PanelLayout.preferredHeight(width: 640, heights: compact) == 658)
precondition(!PanelLayout.needsResourceScroll(size: CGSize(width: 640, height: 658), heights: compact))
precondition(PanelLayout.needsResourceScroll(size: CGSize(width: 640, height: 640), heights: compact))
precondition(PanelLayout.needsResourceScroll(size: CGSize(width: 480, height: 800), heights: compact))
precondition(PanelLayout.columns(width: 640) == 2 && PanelLayout.columns(width: 559) == 1)
precondition(PanelLayout.needsDashboardScroll(size: CGSize(width: width, height: 400), heights: compact))
precondition(!PanelLayout.needsDashboardScroll(size: CGSize(width: width, height: 2400), heights: compact))
}
precondition(PanelLayout.rowHeights(columns: 3, heights: compact) == [176, 176])
precondition(PanelLayout.rowHeights(columns: 2, heights: compact) == [176, 176, 176])
precondition(PanelLayout.cardWidth(size: CGSize(width: 648, height: 630)) == ResourceCardMetrics.preferredWidth,
"Three columns must retain readable card widths")
precondition(PanelLayout.preferredHeight(width: 648, heights: compact) == 630)
precondition(PanelLayout.preferredHeight(width: 520, heights: compact) == 800)
precondition(!PanelLayout.needsDashboardScroll(size: CGSize(width: 648, height: 630), heights: compact))
precondition(PanelLayout.needsDashboardScroll(size: CGSize(width: 648, height: 629), heights: compact))
precondition(!PanelLayout.needsDashboardScroll(size: CGSize(width: 520, height: 812), heights: compact))
precondition(PanelLayout.needsDashboardScroll(size: CGSize(width: 520, height: 811), heights: compact))
precondition(PanelLayout.needsDashboardScroll(size: CGSize(width: 360, height: 800), heights: compact))
precondition(PanelLayout.columns(width: 648) == 3 && PanelLayout.columns(width: 620) == 3)
precondition(PanelLayout.columns(width: 619) == 2 && PanelLayout.columns(width: 430) == 2 && PanelLayout.columns(width: 429) == 1)
let tallerCPU = PanelLayout.cardHeights(coreRows: 6, fanCount: 2)
precondition(tallerCPU[.cpu]! > compact[.cpu]! && tallerCPU[.battery] == compact[.battery],
"A taller CPU card must not stretch the opposite battery card")
let moreFans = PanelLayout.cardHeights(coreRows: 2, fanCount: 6)
precondition(PanelLayout.rowHeights(columns: 3, heights: tallerCPU) == [251, 251],
"All resource rows must share the maximum structural card height")
let moreFans = PanelLayout.cardHeights(coreRows: 1, fanCount: 10)
precondition(moreFans[.gpu]! > compact[.gpu]! && moreFans[.storage] == compact[.storage])
let noFans = PanelLayout.cardHeights(coreRows: 2, fanCount: 0)
precondition(noFans[.gpu] == 124 && PanelLayout.columnHeights(columns: 2, heights: noFans) == [524, 564])
precondition(PanelLayout.preferredHeight(width: 640, heights: noFans) == 658,
"The right column owns the height when the GPU has no fan section")
precondition(PanelLayout.cardHeights(coreRows: 2, fanCount: nil) == compact,
precondition(PanelLayout.rowHeights(columns: 3, heights: moreFans) == [248, 248])
let noFans = PanelLayout.cardHeights(coreRows: 1, fanCount: 0)
precondition(noFans[.gpu] == 176 && PanelLayout.rowHeights(columns: 3, heights: noFans) == [176, 176])
precondition(PanelLayout.preferredHeight(width: 648, heights: noFans) == 630,
"A fanless GPU must keep row alignment with CPU and memory")
precondition(PanelLayout.cardHeights(coreRows: 1, fanCount: nil) == compact,
"Discovery placeholders must reserve the ordinary fan row")
let manyCores = PanelLayout.cardHeights(coreRows: 30, fanCount: 10)
precondition(PanelLayout.preferredHeight(width: 640, heights: manyCores) == 800)
precondition(PanelLayout.needsResourceScroll(size: CGSize(width: 640, height: 800), heights: manyCores))
precondition(PanelLayout.preferredHeight(width: 648, heights: manyCores) == 800)
precondition(PanelLayout.needsDashboardScroll(size: CGSize(width: 648, height: 800), heights: manyCores))
let requested = PanelLayout.contentSize(visible: CGRect(x: 0, y: 0, width: 1512, height: 900), preferredHeight: 732)
precondition(requested.height == 732, "A hardware-driven height above the default must be preserved")
precondition(PanelLayout.processHeight(heights: compact) == 176)
precondition(PanelLayout.dashboardHeight(columns: 3, heights: compact) == 540)
precondition(PanelLayout.processHeight(heights: tallerCPU) == 251)
let input: [ProcessMetrics] = (0..<2000).map { (index: Int) -> ProcessMetrics in
let id = ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0)
let path: String? = index == 42 ? "/test/needle" : nil
@@ -77,6 +92,6 @@ import CoreGraphics
}
let pidSorted = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .pid)], order: [])
precondition(pidSorted.first?.id.pid == 2000)
print("PASS: independent columns, hardware-driven heights, scroll and screen limits, column breakpoints, width conservation, resource scrolling, visible-frame bounds/chrome/negative origins, 2000-row CPU/footprint projection, frozen order, path search and empty results")
print("PASS: three-column resource grid plus equal-height process row, aligned hardware-driven row heights, responsive reading order, scroll and screen limits, column breakpoints, width conservation, visible-frame bounds/chrome/negative origins, 2000-row CPU/footprint projection, frozen order, path search and empty results")
}
}
-2
View File
@@ -43,7 +43,6 @@ import SwiftUI
// Geometry reports and centering run on subsequent main-queue turns.
try? await Task.sleep(for: .milliseconds(200))
controller.presentation.isPinned = true
controller.presentation.page = .processes
let cover = NSWindow(contentRect: controller.panel.frame.insetBy(dx: -8, dy: -8),
styleMask: [.borderless], backing: .buffered, defer: false)
cover.isReleasedWhenClosed = false
@@ -75,7 +74,6 @@ import SwiftUI
precondition(!controller.panel.isVisible && !visible)
controller.togglePanel()
precondition(controller.panel.isVisible && visible)
precondition(controller.presentation.page == .overview, "Explicit reopening must select overview")
controller.statusMenu().performActionForItem(at: 1)
precondition(settingsRequests == 1 && !controller.panel.isVisible)
controller.show()
+45
View File
@@ -0,0 +1,45 @@
import AppKit
import SwiftUI
/// Verify the production section fills its assigned row after removing the scope row.
@main struct ProcessSectionChecks {
@MainActor static func main() {
_ = NSApplication.shared; NSApp.setActivationPolicy(.accessory)
Task { @MainActor in
let window = NSWindow(contentRect: NSRect(x: 30, y: 30, width: 628, height: 176),
styleMask: [.borderless], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false; window.level = .floating
let host = NSHostingView(rootView: AnyView(EmptyView())); host.sizingOptions = []
window.contentView = host; window.orderFrontRegardless()
let rows = (0..<100).map { ProcessMetrics(id: .init(pid: Int32($0 + 1), seconds: 1, microseconds: 0),
name: "worker-\($0)", path: "/fixture/worker", cpu: 0.1, footprintBytes: 1 << 20, threads: 2, restricted: false) }
let snapshot = ProcessSnapshot(date: Date(), enumerated: 100, readable: 100, rows: rows, failed: false)
let energy = ProcessEnergySnapshot(date: Date(), candidates: 100, readable: 100, rows: [], state: .available)
for dark in [false,true] {
window.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
for language in ["zh-Hans","zh-Hant","en"] {
for width: CGFloat in [340,628] {
window.setContentSize(NSSize(width: width, height: 176))
host.rootView = AnyView(ProcessTableView(snapshot: snapshot, energy: energy, state: ProcessTableState())
.environment(\.locale, Locale(identifier: language))
.environment(\.colorScheme, dark ? .dark : .light))
try? await Task.sleep(for: .milliseconds(100)); host.layoutSubtreeIfNeeded()
let scrolls = descendants(host).compactMap { $0 as? NSScrollView }.filter { $0.documentView is NSTableView }
precondition(scrolls.count == 1)
precondition(!scrolls[0].hasHorizontalScroller)
let scroll = scrolls[0], rect = scroll.convert(scroll.bounds, to: host)
let topRect = host.isFlipped ? rect : CGRect(x: rect.minX, y: host.bounds.height - rect.maxY, width: rect.width, height: rect.height)
precondition(abs(topRect.maxY - 166) < 1 && topRect.height > 110,
"The native table must fill the equal-height row down to its 10pt inset: \(language), \(width), \(topRect)")
precondition(abs(topRect.minX - 10) < 1 && abs(topRect.maxX - (width - 10)) < 1)
}
}
}
host.rootView = AnyView(EmptyView()); window.orderOut(nil); window.close()
print("PASS: production process section at 176pt, no scope row or horizontal scrollbar, full remaining table height, two widths, three languages and light/dark")
NSApp.terminate(nil)
}
NSApp.run()
}
@MainActor private static func descendants(_ view: NSView) -> [NSView] { [view] + view.subviews.flatMap(descendants) }
}
+2
View File
@@ -24,6 +24,8 @@ import Darwin
print("FAIL: hardened sandbox to packaged XPC sensor RPC"); exit(1)
}
print("PASS: hardened sandbox host authenticates packaged XPC; footprint, CPU energy and sensor RPCs")
let power = await CPUTemperatureServiceClient.readSystemPower()
print("System-total sensor (W):", power.map(String.init(describing:)) ?? "unavailable")
print("Sensor coverage: CPU=\(sensors.cpu != nil), GPU=\(sensors.gpu != nil), fans=\(sensors.fans?.count ?? 0)")
}
}
+126
View File
@@ -0,0 +1,126 @@
import AppKit
import SwiftUI
/// Mount the production card and chart together; verify their real native geometry.
@main struct ResourceCardChecks {
@MainActor static func main() {
_ = NSApplication.shared
NSApp.setActivationPolicy(.accessory)
Task { @MainActor in
let window = NSWindow(contentRect: NSRect(x: 40, y: 40, width: 308 * 2 / 3, height: 176),
styleMask: [.borderless], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false; window.level = .floating
let probe = DetailProbe()
let host = NSHostingView(rootView: AnyView(EmptyView())); host.sizingOptions = []
window.contentView = host; window.orderFrontRegardless()
for dark in [false, true] {
window.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
for language in ["zh-Hans", "zh-Hant", "en"] {
for width: CGFloat in [190, 308 * 2 / 3, 400] {
window.setContentSize(NSSize(width: width, height: 176))
host.rootView = AnyView(fixture(probe: probe, dualMetric: width < 300)
.environment(\.locale, Locale(identifier: language))
.environment(\.colorScheme, dark ? .dark : .light))
try? await Task.sleep(for: .milliseconds(80))
host.layoutSubtreeIfNeeded()
let plots = descendants(host).compactMap { $0 as? NativePanelCurve.PlotView }
precondition(plots.count == 1)
let plot = plots[0]
precondition(abs(host.bounds.width - width) < 1, "AppKit may round fractional content sizes to a point")
let graph = topRect(plot, in: host)
let detail = topRect(probe.view!, in: host)
precondition(abs(graph.width - host.bounds.width) < 0.5 && abs(graph.maxY - host.bounds.height) < 0.5)
precondition(detail.maxY + 3 <= graph.minY && graph.height >= 32,
"The plot must sit entirely below the text at every width and locale")
precondition(plot.grid.isHidden && plot.input?.visibleSeriesCount == 1)
for kind in 0...1 {
host.rootView = AnyView(detailsFixture(kind: kind, probe: probe)
.environment(\.locale, Locale(identifier: language))
.environment(\.colorScheme, dark ? .dark : .light))
try? await Task.sleep(for: .milliseconds(60)); host.layoutSubtreeIfNeeded()
let details = topRect(probe.view!, in: host)
let trend = descendants(host).compactMap { $0 as? NativePanelCurve.PlotView }.first!
let plotRect = topRect(trend, in: host)
if kind == 0 {
precondition(plotRect == host.bounds, "Physical memory capacity must map to the top of the card")
} else {
precondition(plotRect.height >= 24 && plotRect.minY >= details.maxY + 3,
"Storage details must leave a separate usable plot")
}
precondition(details.maxY <= host.bounds.height - 10 + 0.5 && details.width <= host.bounds.width - 20 + 0.5,
"Larger production details must fit the unchanged card: \(kind), \(language), \(width), \(details)")
}
}
}
}
// Mount the production branch with a desktop, a missing sensor and a failed battery read.
for state: BatteryAvailability in [.absent, .failed, .present, .unknown] {
var sample = MetricsSnapshot()
sample.batteryState = state
sample.systemPower = state == .absent ? 32.5 : nil
if state == .present { sample.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true, power: 0) }
var history = MetricHistory()
history.append(sample)
sample.date = sample.date.addingTimeInterval(2); sample.systemPower = nil
history.append(sample)
host.rootView = AnyView(PowerResourceCard(snapshot: sample, samples: history.samples,
chartInterval: 2, chartBoundaries: [], chartIntervals: [2,2]))
try? await Task.sleep(for: .milliseconds(80)); host.layoutSubtreeIfNeeded()
let plot = descendants(host).compactMap { $0 as? NativePanelCurve.PlotView }.first!
let first = plot.input?.frame.series.first
switch state {
case .absent: precondition(first == [32.5, nil] && plot.input?.scales.first == 32.5)
case .present: precondition(first == [0.8, 0.8] && plot.input?.scales.first == 1 && topRect(plot, in: host) == host.bounds)
default: precondition(first == [nil, nil] && plot.input?.scales.first == 1)
}
}
host.rootView = AnyView(EmptyView())
try? await Task.sleep(for: .milliseconds(100))
precondition(descendants(host).allSatisfy { !($0 is NativePanelCurve.PlotView) })
window.orderOut(nil); window.contentView = nil; window.close()
print("PASS: production card geometry at 190/205⅓/400pt, light/dark, three languages, separate plot below text, localized memory/storage details, unmount")
NSApp.terminate(nil)
}
NSApp.run()
}
@MainActor private static func fixture(probe: DetailProbe, dualMetric: Bool) -> some View {
let dates = (0..<60).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
return ResourceCard(title: "metric.network", symbol: "network", color: .blue,
value: dualMetric ? "↓ 999.9 TB/s" : "99%", secondaryValue: dualMetric ? "↑ 999.9 TB/s" : nil,
chart: {
PanelTrendChart(dates: dates, first: Array(repeating: 0.8, count: 60),
second: Array(repeating: 0.6, count: 60), color: .blue)
}) {
DetailMarker(probe: probe).frame(height: 40)
}
}
@MainActor private static func detailsFixture(kind: Int, probe: DetailProbe) -> some View {
let memory = MemoryMetrics(total: 48 << 30, used: 26 << 30, wired: 3 << 30, compressed: 1 << 30,
swapUsed: 0, pressure: 1)
let details = kind == 0 ? AnyView(MemoryDetailsView(memory: memory))
: AnyView(StorageDetailsView(disk: .init(total: 1_000_000_000_000, available: 999_000_000_000),
health: .init(remainingLife: 0.98, powerOnHours: 99999),
io: .init(read: 999_900_000_000, written: 999_900_000_000)))
return ResourceCard(title: kind == 0 ? "metric.memory" : "metric.disk", symbol: "memorychip", color: .blue,
value: "26.0 / 48 GiB", chartPlacement: kind == 0 ? .background : .belowDetails, chart: { PanelTrendChart(dates: [Date()], first: [0.5], color: .blue) }) {
details.background(DetailMarker(probe: probe).allowsHitTesting(false))
}
}
@MainActor private static func descendants(_ view: NSView) -> [NSView] {
[view] + view.subviews.flatMap(descendants)
}
@MainActor private static func topRect(_ view: NSView, in host: NSView) -> CGRect {
let rect = view.convert(view.bounds, to: host)
return host.isFlipped ? rect : CGRect(x: rect.minX, y: host.bounds.height - rect.maxY, width: rect.width, height: rect.height)
}
@MainActor private final class DetailProbe { weak var view: NSView? }
private struct DetailMarker: NSViewRepresentable {
let probe: DetailProbe
func makeNSView(context: Context) -> NSView { let view = NSView(); probe.view = view; return view }
func updateNSView(_ view: NSView, context: Context) {}
}
}
+27
View File
@@ -0,0 +1,27 @@
import Foundation
@main struct StackedSeriesChecks {
static func main() {
let components: [[Double?]] = [[0.2,0,nil,0.4,Double.nan,-0.1], [0.3,0,0.1,0.2,0.1,0.2]]
let bands = StackedSeries.bands(components, count: 6, limit: 1)
precondition(bands[0].lower[0] == 0 && bands[0].upper[0] == 0.2)
precondition(bands[1].lower[0] == 0.2 && bands[1].upper[0] == 0.5)
precondition(bands[1].upper[1] == 0, "Real zero must remain a measured stack")
for index in [2,4,5] {
precondition(bands.allSatisfy { $0.lower[index] == nil && $0.upper[index] == nil },
"Missing or invalid components must not invent partial totals")
}
let memory = StackedSeries.bands([[22,24], [3,4], [1,2]], count: 2, limit: 48)
precondition(memory[2].lower == [25,28] && memory[2].upper == [26,30])
let gpu = StackedSeries.bands([[0,0.7,1], [1,0.3,0]], count: 3, limit: 1)
precondition(gpu.last!.upper == [1,1,1])
precondition(StackedSeries.bands([[0.8],[0.4]], count: 1, limit: 1).allSatisfy { $0.upper == [nil] })
precondition(StackedSeries.bands([[Double.greatestFiniteMagnitude],[Double.greatestFiniteMagnitude]], count: 1).allSatisfy { $0.upper == [nil] })
let dates = (0..<4).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
let pair = StackedSeries.bands([[0.2,nil,nil,0.3],[0.3,nil,nil,0.2]], count: 4)
let runs = PanelCurveGeometry.runs(dates: dates, values: pair[1].upper, boundaryDates: [dates[2]], lowerValues: pair[1].lower)
precondition(runs.count == 2 && runs[0][0].lower == 0.2 && runs[1][0].lower == 0.3)
precondition(runs.flatMap { $0 }.map(\.date) == [dates[0],dates[3]])
print("PASS: cumulative component boundaries, CPU/memory/GPU sums, zero/missing/invalid/overflow, paired lower boundaries and sampling breaks")
}
}
+8
View File
@@ -23,6 +23,14 @@ import Foundation
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 0, amperageMilliamps: 2_500) == nil)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: .nan) == nil)
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 50_000, amperageMilliamps: 2_500) == nil)
var history = MetricHistory()
for state: BatteryAvailability in [.absent, .failed, .unknown, .present] {
var sample = MetricsSnapshot()
sample.batteryState = state; sample.systemPower = 29.5
history.append(sample)
precondition(history.samples.last?.systemPower == (state == .absent ? 29.5 : nil))
precondition(history.samples.last?.batteryPower == nil && history.samples.last?.battery == nil)
}
let report = Data(#"{"SPPowerDataType":[{"sppower_battery_health_info":{"sppower_battery_health_maximum_capacity":"100%"}}]}"#.utf8)
precondition(SystemBatteryHealthMonitor.parse(report) == 1)
precondition(SystemBatteryHealthMonitor.parse(Data(String(decoding: report, as: UTF8.self).replacingOccurrences(of: "100%", with: "83%").utf8)) == 0.83)
+34 -4
View File
@@ -25,7 +25,7 @@ CHECKS.update({
"BoundedProcessChecks": ["kymo/Core/Services/BoundedProcess.swift"],
"SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.swift"],
"CPUCoreGridChecks": ["kymo/Features/MenuBar/CPUCoreGrid.swift", "kymo/Core/Services/CPUCoreTopology.swift",
"kymo/Core/Extensions/MetricFormat.swift", "kymo/UI/Components/MetricProgressBar.swift"],
"kymo/Core/Extensions/MetricFormat.swift"],
"CPUTemperatureChecks": ["kymo/Core/Monitors/CPUTemperatureMonitor.swift"],
"DiskHealthChecks": ["kymo/Core/Models/DiskHealthMetrics.swift", "kymo/Core/Monitors/DiskHealthReport.swift"],
"PublicIPAddressChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
@@ -61,7 +61,37 @@ CHECKS.update({
"kymo/Features/MenuBar/PanelWindowObserver.swift", "kymo/UI/Components/IntervalControl.swift"],
"SandboxNetworkChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
})
GUI = {"NativeMetricDrawingChecks", "NativeContentHostChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks", "TabPickerChecks"}
CHECKS["ResourceCardChecks"] = [
"kymo/UI/Components/ResourceCard.swift", "kymo/UI/Components/ResourceCardMetrics.swift",
"kymo/UI/Components/PanelStyle.swift", "kymo/UI/Components/NativeContentHost.swift",
"kymo/UI/Components/MetricText.swift", "kymo/UI/Components/TooltipBackground.swift",
"kymo/UI/Charts/PanelTrendChart.swift", "kymo/UI/Charts/NativePanelCurve.swift",
"kymo/UI/Charts/PanelCurveFrame.swift", "kymo/UI/Charts/PanelCurveGeometry.swift",
"kymo/UI/Charts/ChartTooltipLayer.swift", "kymo/Core/Extensions/MetricFormat.swift",
]
CHECKS["ResourceCardChecks"] = list(dict.fromkeys(CORE + CHECKS["ResourceCardChecks"] + [
"kymo/Features/MenuBar/PowerResourceCard.swift", "kymo/UI/Components/AppLocalization.swift",
"kymo/Features/MenuBar/MemoryDetailsView.swift", "kymo/Features/MenuBar/StorageDetailsView.swift",
]))
CHECKS["MenuBarMetricChecks"] = CORE
CHECKS["PanelWindowChecks"] += CORE + ["kymo/UI/Components/MenuBarMetricStrip.swift"]
for name in ("PanelLayoutChecks", "PanelWindowChecks"):
CHECKS[name].append("kymo/UI/Components/ResourceCardMetrics.swift")
for name in ("NativeMetricDrawingChecks", "ResourceCardChecks"):
CHECKS[name].append("kymo/UI/Charts/StackedSeries.swift")
CHECKS["StackedSeriesChecks"] = ["kymo/UI/Charts/StackedSeries.swift", "kymo/UI/Charts/PanelCurveGeometry.swift"]
CHECKS["FanRotorChecks"] = ["kymo/UI/Components/FanSpeedIndicator.swift", "kymo/UI/Components/MetricText.swift"]
CHECKS["ProcessSectionChecks"] = CHECKS["NativeProcessTableChecks"] + [
"kymo/Core/Models/ProcessEnergy.swift", "kymo/Features/MenuBar/ProcessTableView.swift",
"kymo/UI/Components/NativeSearchField.swift", "kymo/UI/Components/PanelStyle.swift",
"kymo/UI/Components/ResourceCardMetrics.swift", "kymo/UI/Components/MetricText.swift",
]
GUI = {"ProcessSectionChecks", "FanRotorChecks", "ResourceCardChecks", "NativeMetricDrawingChecks", "NativeContentHostChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks", "TabPickerChecks"}
NETWORK = {"SandboxNetworkChecks"}
SERVICES = {"ReleaseServiceChecks"}
@@ -95,7 +125,7 @@ def test_bundle(work, name, executable, host_entitlements=None, resources=None,
(contents / "Info.plist").write_bytes(plistlib.dumps({
"CFBundleIdentifier": "cn.airnan.kymo.checks." + uuid.uuid4().hex,
"CFBundleExecutable": name, "CFBundlePackageType": "APPL",
"LSUIElement": name in {"PanelWindowChecks", "NativeMetricDrawingChecks", "NativeContentHostChecks", "NativeProcessTableChecks", "NetworkAddressChecks", "SandboxNetworkChecks", "TabPickerChecks"},
"LSUIElement": name in {"ProcessSectionChecks", "FanRotorChecks", "ResourceCardChecks", "PanelWindowChecks", "NativeMetricDrawingChecks", "NativeContentHostChecks", "NativeProcessTableChecks", "NetworkAddressChecks", "SandboxNetworkChecks", "TabPickerChecks"},
}))
if resources:
shutil.copytree(resources, contents / "Resources")
@@ -176,7 +206,7 @@ def main():
run(["swiftc", "-parse-as-library", "-module-cache-path", work / "cache", *CHECKS[name],
f"kymoTests/{name}.swift", "-o", executable])
if name in GUI:
bundle = test_bundle(work, name, executable, resources=app / "Contents/Resources" if name in {"NativeProcessTableChecks", "TabPickerChecks"} else None)
bundle = test_bundle(work, name, executable, resources=app / "Contents/Resources" if name in {"ProcessSectionChecks", "ResourceCardChecks", "NativeProcessTableChecks", "TabPickerChecks"} else None)
# Open the complete app for native activation semantics, while collecting its output.
output = work / (name + ".out")
error = work / (name + ".err")