perf(menubar): 降低绘制驻留并复用原生进程表与缩略图
This commit is contained in:
@@ -8,13 +8,13 @@ Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点
|
||||
- GPU:总占用、Renderer / Tiler 活动、核心数、驱动内存统计、近期平均与峰值、温度和风扇转速。
|
||||
- 内存:已用与总量、应用 / 联动 / 压缩分类、缓存、可用量、压力与 Swap。
|
||||
- 存储:主目录所在卷容量、块设备读写速率、各本地卷容量、可读取的 SMART 寿命与通电时间。
|
||||
- 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计,以及按 CPU 占用排序的前三个进程。
|
||||
- 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计,以及按系统 CPU 能量差分排序的前三个进程。
|
||||
- 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。
|
||||
- 进程:PID、名称、路径、CPU、RSS 和线程数;支持搜索、列排序及复制。
|
||||
|
||||
面板支持固定显示、保持唤醒、暂停 / 恢复采样。面板刷新与后台刷新分别配置,默认 2 秒 / 5 秒。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。
|
||||
面板支持固定显示、保持唤醒、暂停 / 恢复采样。面板刷新默认 2 秒;默认隐藏停止采样,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。
|
||||
|
||||
部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;电池卡片的进程排名依据 CPU 占用,不是实测能耗。指标口径和限制见[监控指标](docs/monitoring.md)。
|
||||
部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;耗电进程显示系统归属的 CPU 能量区间平均功率,注明可读覆盖范围,不代表完整应用总耗电。指标口径和限制见[监控指标](docs/monitoring.md)。
|
||||
|
||||
## 构建运行
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
| [测试与验证](testing.md) | 独立检查程序、执行方式和人工验收边界 |
|
||||
| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 实施中:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 |
|
||||
|
||||
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
|
||||
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。第三批见[原生绘制与进程表记录](efficiency-third-batch.md)。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
|
||||
|
||||
2026-11-03 依据当前源码重新整理;同日补充极致轻量化与进程能耗实施方案。此前清理的旧阶段计划、设计概念图和路线图可通过 Git 查询。主题文档描述当前实现,方案中的目标不代表已实现,也不以代码已实现代替运行验收。
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
`MenuPanelController` 拥有模板品牌状态项和无边框、可成为 key 的非激活 `MonitoringPanel`。左键切换面板;右键菜单提供打开 / 隐藏、设置和退出。窗口按状态项所在屏幕可见区域定位,水平居中、顶部预留 16pt;最大内容尺寸 1240 × 820pt,并按屏幕缩小。卡片随宽度采用 1 / 2 / 3 列,资源区空间不足时滚动,进程区保留最小高度。
|
||||
|
||||
固定按钮切换普通 / floating 层级。未固定时外部交互或应用失活可收起,固定时仍可通过状态项或显式关闭收起。进程表的 Esc 依次处理搜索、选中和搜索焦点,随后关闭窗口。隐藏面板时释放内容视图并停止监听外部鼠标事件;仅显式启用后台趋势时保留常规采样。
|
||||
固定按钮切换普通 / floating 层级。未固定时外部交互或应用失活可收起,固定时仍可通过状态项或显式关闭收起。进程表的 Esc 依次处理搜索、选中和搜索焦点,随后关闭窗口。隐藏面板时先卸载内容视图、关闭底层窗口资源(保留控制器拥有的窗口对象供重开),并停止监听外部鼠标事件;仅显式启用后台趋势时保留常规采样。
|
||||
|
||||
设置窗口打开时切换 regular 模式并处理焦点恢复,关闭时由 `SettingsWindowLifecycle` 恢复 accessory 模式。关闭最后一个窗口不会退出应用。应用退出时关闭状态项、释放窗口引用及保持唤醒断言。
|
||||
|
||||
@@ -66,11 +66,15 @@ CPU / GPU / 风扇合并为一次只读 XPC 请求,按到期类别选择读取
|
||||
|
||||
外观、语言和双采样间隔写入 UserDefaults。图钉、暂停、保持唤醒和进程表交互状态不作为持久化偏好。`AppLanguageScope` 将语言环境注入 AppKit 承载的 SwiftUI 内容,并处理即时刷新;原生菜单文案通过 `AppLocalization` 读取;编号风扇等 SwiftUI 文案保留为带参数的 `Text`,由当前应用语言环境解析。
|
||||
|
||||
面板和资源卡片使用颜色资产中的不透明背景,顶部操作组使用玻璃效果;不再以全窗口液态玻璃概念图作为实现依据。品牌图标与颜色以 Assets 为运行时来源。
|
||||
面板和资源卡片使用颜色资产中的不透明背景,顶部操作组使用低透明度静态胶囊背景;不再以全窗口液态玻璃概念图作为实现依据。品牌图标与颜色以 Assets 为运行时来源。
|
||||
|
||||
资源显示默认采用静态数字、曲线和进度条;风扇不创建 TimelineView。移除曲线追加过渡任务,保持原有缺失值、断点和悬浮语义。此措施不代表面板内存预算已通过;剩余峰值见效率实施记录。
|
||||
固定 frame 的面板宿主关闭 NSHostingView 自动尺寸协商。趋势图的坐标、图例、悬浮与业务投影继续由 SwiftUI 管理;曲线 / 网格 / 悬浮标记与百分比圆环分别由 UI 层的 NativePanelCurve、NativeMetricRing 使用 Core Graphics 绘制,输入、尺寸或外观变化时才失效,不引入绘制计时器。保留既有 PanelCurveGeometry 的真实时间、缺失值与断点规则。
|
||||
|
||||
`PanelResourceAudit` 与纯文字对照渲染器仅在 Debug 或显式 `KYMO_AUDIT` 编译条件下包含实现;普通 Release 不包含诊断驱动与文字列表实现。测试构建还需设置 `KYMO_RESOURCE_AUDIT=1` 才驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启。
|
||||
进程表使用 MenuBar 的 NativeProcessTable(view-based NSTableView),继续消费 ProcessTableProjection 的搜索 / 排序 / 冻结投影。仅创建可见单元格,行数改变时增删尾行,刷新时原地修改可见文本与图像;选择以完整 ProcessIdentity 同步,用户选择 / 排序延后到委托回调之外写回 SwiftUI。原生 Esc 转发至原有分层退出逻辑,右键菜单保留复制能力。共享 ProcessIconCache 将 NSWorkspace 原图绘制为 30×30 像素、15pt 的单一位图,不保留原图;最多 128 项 / 1 MiB 解码像素,30 秒过期、LRU 淘汰、内存压力清空,不启动轮询。其预算不代表系统图标服务内部缓存已受控。
|
||||
|
||||
资源显示默认采用静态数字、曲线和进度条;风扇不创建 TimelineView。移除曲线追加过渡任务,保持原有缺失值、断点和悬浮语义。此措施不代表面板内存预算已通过;剩余峰值与 CPU 未达标情况见[第三批记录](efficiency-third-batch.md)。
|
||||
|
||||
`PanelResourceAudit` 与纯文字对照渲染器仅在 Debug 或显式 `KYMO_AUDIT` 编译条件下包含实现;普通 Release 不包含诊断驱动与文字列表实现。测试构建还需设置 `KYMO_RESOURCE_AUDIT=1` 才驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启;审计标记附带原生图区数量 / 尺寸、悬浮状态和指针是否在面板内,窗口编号只在可见时读取。
|
||||
|
||||
外部 `system_profiler` / `diskutil` 报告共用 Core 的 `BoundedProcess`(同时编入 XPC Target)。utility 队列阻塞于输出 / 取消 / 退出事件,累计保留输出不超过 256 KiB,最多多读 1 字节判断溢出;10 秒截止、输出超限或调用 Task 取消时 SIGKILL 本轮直接子进程并等待回收。子进程关闭 stdout 后不退出也受截止约束。取消管道唤醒 poll,无周期检查计时器;不杀进程组或其他进程。此取消能力不代表 XPC 连接断开已传播到服务内部 Task,暂停后已启动慢报告的上层取消仍需完善。
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# 第三批:绘制峰值与刷新成本定位
|
||||
|
||||
日期:2026-11-04。起点 `1c26fc1`。延续极致轻量化方案 P0 / P2;本轮先定位可复现触发,再实施局部修正,不降低候选进程覆盖或采样频率。
|
||||
|
||||
## 范围与步骤
|
||||
|
||||
涉及 MenuBar 的资源卡片 / 进程表、UI 组件、必要时 Core 采样路径,以及构建配置。窗口、指标与交互语义保持可验证;普通发行包不包含本轮临时探针。
|
||||
|
||||
1. 核对现有工作区、调用链与上一批证据;记录既有进程,隔离本轮测试副本。
|
||||
2. 用最小文字窗口、单张资源卡片、实时栈与分配快照区分文字数量、共有绘制路径、采样成本及表格发布。
|
||||
3. 对已确认浪费做局部改动;构建、受影响回归和实际签名窗口验证。
|
||||
4. 同条件复测完整功能与包体积;记录未达标项,清理临时产物,分批提交。
|
||||
|
||||
风险:诊断工具会明显改变内存 / CPU,带分配栈的数字仅作归因;短时组件隔离不能替代长期验收。单张卡片测试保留后端,仅调整呈现;产品不能以删除指标达标。
|
||||
|
||||
## 初步定位
|
||||
|
||||
独立原生 NSPanel,固定 1240×820,每 2 秒更新文字。300 个普通 SwiftUI Text 首次 5 秒累计峰值约 35.58 MiB,300 个原生 NSTextField 约 23.63 MiB;300 个日期 Text(time 样式)约 29.63 MiB。单靠文字数量没有复现完整 UI 峰值。
|
||||
|
||||
优化编译的同步微基准,每类 50 次、进程 30 次,线程 CPU 时钟测量:CPU 0.027、内存 0.009、网络 1.498、磁盘 IO 0.029、容量 0.031、电池 0.233、GPU 0.024、进程 0.808 毫秒 / 次。合计约 2.66 毫秒,不能直接当成正式应用 CPU;它不包含异步 XPC、UI、历史与发布,但提示继续追查展示和调度成本。
|
||||
|
||||
临时源码副本(普通 Release 不改动),首开 10 秒累计主进程峰值:完整 209.13 MiB;隐藏图表绘制 196.63;去玻璃效果 207.06;不透明窗口 208.45;次要文字改主色 209.97;去帮助提示 208.00。均未消除峰值,不作为产品改动合入。
|
||||
|
||||
只显示一张卡片,保留所有后端,CPU / GPU / 电池 / 内存 / 磁盘 / 网络依次仍约 166.14 / 165.70 / 165.00 / 166.08 / 166.58 / 168.75 MiB 峰值。不是单一业务卡片的专属问题。
|
||||
|
||||
完整面板的多次日志出现系统警告:`Application performed a reentrant operation in its NSTableView delegate. This warning will become an assert in the future.` 表格时机问题单独验证,不能用它解释不含表格的单卡片峰值。
|
||||
|
||||
## 局部实施设计
|
||||
|
||||
单张 GPU 卡片分别去掉边框、去掉趋势图区后,前者仍 166.50 MiB,后者仅 30.91 MiB;同时去掉两者 29.74 MiB。图区是可独立复现的触发路径,需继续验证内部 Canvas 替换,不能因完整窗口去图表仍有峰值就排除该路径。普通文字、粗体 / 多字号、圆角背景 / 边框的最小窗口约 36–38 MiB,未复现该增量。
|
||||
|
||||
首先将 PanelTrendChart 的曲线绘制从 SwiftUI Canvas 局部换成 AppKit NSView / Core Graphics,保留原几何算法、轴、图例、悬浮、缺失值、断点与颜色;输入相同则不触发原生重绘。颜色与尺寸变化由原生生命周期失效,不引入计时器。再独立验证进程表,已有“只把 onChange 改 task”的试验仍有重入警告,未采用。
|
||||
|
||||
进程表已局部改用 view-based NSTableView:继续使用现有投影、搜索、排序、身份选择、冻结顺序和退出判断;仅创建可见单元格,数据变化原地更新,行数变化增删尾行。用户选择 / 排序的 SwiftUI Binding 延后到委托回调之外发布,程序同步选择不反向触发委托。保留列宽调整、横纵滚动、三语列头、路径复制、受限图标和键盘 Esc。图标采用共享有界缩略图缓存(最多 128 项、解码像素预算 1 MiB、30 秒过期、内存压力清空),避免每个行实例持有原始高分辨率图像。独立窗口检查覆盖可见单元格数量、身份选择、排序、复制与合成 Esc 投递;完整应用 CPU / 内存另测。
|
||||
|
||||
原生曲线在单张 GPU 卡片(保留完整坐标、图例、日期)实测峰值 31.70 MiB,对照旧 Canvas 165.70 MiB;但完整资源区仍有约 190 MiB 的峰值,说明其他路径可独立触发。继续将 CPU 核与百分比圆环的弧线局部改为原生 Core Graphics,保持已有布局、数值、提示与辅助功能。普通圆角边框 / 字体最小复现未触发大增量,不作全面重写。
|
||||
|
||||
所有默认曲线、圆环与表格改为局部原生绘制后,完整窗口首开仍约 187.55 MiB;仅不创建页头则峰值 64.44 MiB。说明页头还存在独立触发。随后将工具条玻璃背景改为静态胶囊,保留所有按钮与交互,并做完整窗口复测;不能用旧实现“单独去玻璃没改善”的结果排除更新后的独立问题。
|
||||
|
||||
面板由控制器显式设置固定 frame,停止 NSHostingView 不必要的 min / intrinsic / max 尺寸协商(sizingOptions=[]),依据 [Apple 文档](https://developer.apple.com/documentation/swiftui/nshostingview/sizingoptions)。此项不是已证明的峰值根因;只关闭默认尺寸不改变原绘制时仍约 205.17 MiB。
|
||||
|
||||
完整面板工具条换为静态胶囊、保持全部按钮后,首开 10 秒累计峰值为 65.95 MiB(原生图形但保留玻璃为 187.55 MiB)。当前属于多条独立绘制路径叠加,单因子未改善不能等同排除该组件。下列完整三轮结果表明,这个首次峰值不能用作最终达标结论。
|
||||
|
||||
## 配对复测与未解决问题
|
||||
|
||||
同一台 M4 Pro / 48 GiB / macOS 27.2,arm64 签名 Release 诊断包。基线取 `1c26fc1` 的独立 Git 归档,保持前台 2 秒、隐藏后台关闭、全部资源 / 历史 / 进程 / 真实 CPU 能量 / 公网策略;每轮展开 30 秒、关闭 30 秒,首轮另暂停 10 秒,循环三次。主进程与包内 XPC 分开累计 rusage CPU;展开 CPU 取每轮 10–30 秒区间,百分比为一个逻辑核的占用。诊断驱动不等于实际鼠标点击;不是最终关闭诊断后的长期验收。
|
||||
|
||||
首次配对:
|
||||
|
||||
| 指标 | 基线 | 原生图形 / 表格 / 静态工具条 |
|
||||
| --- | --- | --- |
|
||||
| 冷启动 / 隐藏 10 秒,MiB | 14.92 / 16.66 | 14.60 / 16.38 |
|
||||
| 三轮展开 30 秒足迹,MiB | 172.88 / 92.17 / 205.59 | 68.66 / 73.55 / 74.06 |
|
||||
| 各轮累计峰值,MiB | 211.84 / 222.16 / 232.13 | 76.35 / 196.33 / 196.33 |
|
||||
| 三轮关闭 30 秒足迹,MiB | 69.72 / 79.86 / 74.64 | 62.28 / 68.14 / 68.77 |
|
||||
| 三轮主进程 CPU,% | 3.68 / 3.73 / 3.68 | 3.35 / 4.45 / 3.23 |
|
||||
| 三轮 XPC CPU,% | 0.22 / 0.21 / 0.22 | 0.22 / 0.20 / 0.22 |
|
||||
|
||||
原生版本稳定足迹有明显改善,但第二次打开仍出现 196 MiB 累计峰值,CPU 没有稳定下降,唤醒也未改善。测试期间用户移动过鼠标,未记录当时悬浮状态,因此“静止不悬浮”的条件不成立,也不能断言峰值由悬浮造成。不能以第一次 66–76 MiB 的结果宣布内存预算通过。
|
||||
|
||||
后续在审计日志增加实际曲线数量、尺寸、悬浮与指针位置。一次单独签名应用采样中,六块图区仅约 299–349 × 58pt,1 / 10 秒均无曲线悬浮,峰值约 68.44 MiB;未发现超大绘图区。无 MallocStackLogging 环境,sample 主线程大部分等待,活跃部分分散于布局、Core Animation 提交和绘制,尚无单一完整根因。带分配栈的试验显著改变内存,仅用于归因,不计入上表性能样本。
|
||||
|
||||
据实际栈做局部修正:原生表格列头按语言缓存、相同图像不重复赋值、原生组件使用父级有限尺寸提议,减少无效布局协商。隐藏时先卸载宿主,再关闭底层窗口资源,窗口对象保持可重开;相应窗口生命周期检查通过,效果另做三轮测量。
|
||||
|
||||
## 采样成本复核
|
||||
|
||||
临时签名应用探针保留全部常规采样与进程 / 能量读取(简化前端未启动公网刷新循环),线程 CPU 时钟测得网络平均约 6.26 ms / 次,明显高于独立 CLI 的 1.50 ms;进程枚举另一次约 6.47 ms / 次。两类环境的 QoS、核心调度、沙盒与缓存状态不同,不能将差异单独归因于沙盒。主应用完整成本不能由 CLI 微基准推算。
|
||||
|
||||
IPv6 scope 名称复用试验随后约 7.92 ms / 次,没有证明 CPU 收益,已撤回复杂替换;保留每轮共用 numeric 地址缓冲和每接口仅最终排序一次,保持系统 canonical formatter、全部接口和地址覆盖。新增沙盒地址检查覆盖 IPv4 / IPv6 / mapped / 已知未知 scope,与本机 14 个实际地址原格式等价,不记录地址值。不把这项标成已量化的 CPU 改善。
|
||||
|
||||
## 最新验证
|
||||
|
||||
精修后同参数再跑三轮(不并行构建 / GUI 检查):
|
||||
|
||||
| 轮次 | 展开 10–30 秒足迹中位数 MiB | 展开 30 秒 MiB | 关闭 30 秒 MiB | 累计峰值 MiB | 主进程 CPU % | XPC CPU % |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 1 | 67.44 | 65.94 | 56.28 | 71.49 | 2.916 | 0.192 |
|
||||
| 2 | 71.28 | 71.11 | 65.97 | 191.50 | 3.171 | 0.193 |
|
||||
| 3 | 72.86 | 72.95 | 67.74 | 197.70 | 4.353 | 0.215 |
|
||||
|
||||
主进程展开唤醒约 3.53 / 8.55 / 10.25 次每秒,未稳定降低;XPC 足迹中位约 4.55–4.89 MiB,应另计。全部关闭标记的宿主弱引用均已释放。第二轮 open1s 峰值时六张图均无悬浮,指针也在面板外,排除这次峰值由图表悬浮直接触发。第三轮指针曾在面板内,虽记录的图表悬浮仍为 0,不能把整次运行称为完全静止受控。关闭底层窗口这一局部改动的收益尚不能从多项同时修正的结果单独归因。
|
||||
|
||||
相较本轮旧源码基线,展开 10–30 秒中位足迹从约 198 / 209 / 204 MiB 降至 67 / 71 / 73 MiB;峰值仍 198 MiB,关闭仍 56–68 MiB,CPU 仍约 2.9–4.4% + XPC 0.2%。本轮确认稳定足迹改善,**峰值、关闭回落、CPU / 唤醒和功耗预算仍未通过**。
|
||||
|
||||
Debug、普通 Release 与显式 KYMO_AUDIT Release 构建通过;仅有未使用 AppIntents 的元数据提示,无 Swift 编译告警。完整 Debug 实包运行 `tools/check.py --app ... --gui --network`:33 项 Swift 检查、208 项三语目录、沙盒权限与实际公网 HTTPS 200 全部通过;其中原生表格、绘制组件和面板关闭 / 重开均已覆盖。没有 XCTest Target,不声称 xcodebuild test 已执行。
|
||||
|
||||
普通签名 arm64 Release(无 KYMO_AUDIT):文件逻辑大小 2,032,456 B、文件分配块合计 2,088,960 B,同格式 ditto ZIP(keepParent / sequesterRsrc)1,062,783 B;主可执行文件 1,247,376 B,Assets.car 495,784 B,XPC 141,296 B。主程序与 XPC 的严格签名核验通过,无源码 / 文档 / 测试脚本混入。较上一批逻辑大小增加 16,288 B(约 0.8%),本批没有进一步缩包;保留默认运行优化,仍满足既定包体积目标,不把这一点当作继续收敛的终点。
|
||||
|
||||
正式面板以窗口编号调用局部 screencapture 失败(could not create image from window),不能据此断言缺少权限;没有扩大到全屏截图。随后绑定本轮测试副本的原生 UI 工具再次返回 -10005 timeoutReached,未取得 AX / 截图结果,不据此推断授权状态。组件位图验证、合成键盘检查与方法驱动不等于完整产品实际 AX / 鼠标 / 键盘输入及视觉验收。
|
||||
|
||||
剩余:完整峰值触发栈、前台 CPU / 唤醒、关闭后的内存预算、自动填充生命周期、100 次开关 / 8 小时 / 实际整机 W 与跨硬件验收。局部替换不代表以上已解决。
|
||||
|
||||
|
||||
本轮汇总后清理全部临时源码副本、探针、采样日志、截图路径和构建;仅退出本轮精确路径下的测试应用,保留用户应用。下一批优先捕获第二次打开时的瞬时分配来源,并对采样 / 发布 / 绘制分别核对 CPU 与唤醒;不先放宽预算或用删指标收尾。
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
日期:2026-11-03。源码基线:`8333349e93c627b8b1df3802e0d3adac32610472`。
|
||||
|
||||
状态:实施中,已完成首批调度 / XPC / 静态显示 / 包体积改动,详见[首批实施记录](efficiency-first-batch.md)。以下设计仍含未实施部分;真实 CPU 能量列表已实现,预算未全部通过;最新证据见[第二批记录](efficiency-second-batch.md)。
|
||||
状态:实施中,已完成首批调度 / XPC / 静态显示 / 包体积改动,详见[首批实施记录](efficiency-first-batch.md)。以下设计仍含未实施部分;真实 CPU 能量列表已实现,预算未全部通过;能量与文字对照见[第二批记录](efficiency-second-batch.md),最新绘制 / 表格定位见[第三批记录](efficiency-third-batch.md)。
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
@@ -54,8 +54,8 @@ Kymo 的定位是体积极小、占用极小、省电的极客监控工具。当
|
||||
| L08 | 确认 / P1 | 固定面板的可见性以 isVisible 管理,完全遮挡时缺少采样与动效降级状态 | 区分打开、实际可见、完全遮挡、隐藏;遮挡后不持续绘制,恢复补一轮有效样本 |
|
||||
| L09 | 确认 / P2 | ProcessMonitor 每轮为所有进程分配路径缓冲并调用 proc_pidpath;两轮系统枚举保护身份 | 按身份缓存路径、复用有界缓冲;保留最终身份复核,不能直接删除防 PID 复用保护 |
|
||||
| L10 | 确认 / P2 | 风扇非零转速时持续约 30 FPS;数值、曲线、进度条还有采样动画 | 默认静态;绘制与数据刷新分离;不可见 / 暂停 / 低电量时无持续动画 |
|
||||
| L11 | 待剖析 / P0→P2 | ProcessIcon 每个已创建行实例调用 NSWorkspace 图标读取;没有应用级有界缩略图复用 | 隔离禁用对照;只缓存显示尺寸缩略图,按路径 / 文件身份复用并限制字节;验证 Table 实际创建的行数 |
|
||||
| L12 | 待剖析 / P0→P2 | 面板已清 contentView,但还有百 MB 级堆占用;框架、任务、图标、浮层、输入系统各可能持有资源 | 分配调用栈与引用路径定位;逐组件对照,不能默认归咎 SwiftUI 或统一重写 |
|
||||
| L11 | 已局部实施 / P2 | ProcessIcon 每个已创建行实例调用 NSWorkspace 图标读取;没有应用级有界缩略图复用 | 隔离禁用对照;只缓存显示尺寸缩略图,按路径 / 文件身份复用并限制字节;验证 Table 实际创建的行数 |
|
||||
| L12 | 部分定位 / P0→P2 | 面板已清 contentView,但还有百 MB 级堆占用;框架、任务、图标、浮层、输入系统各可能持有资源 | 分配调用栈与引用路径定位;逐组件对照,不能默认归咎 SwiftUI 或统一重写 |
|
||||
| L13 | 待剖析 / P2 | MenuPanelView 读取整体 snapshot;资源 / 进程分别发布,可能让无关卡片再次计算;多处 map/filter 和曲线中间数组 | 记录实际 body / 布局 / 绘制次数;按数据域订阅与生成投影,只有相关版本变化才重建 |
|
||||
| L14 | 确认 / P2 | NSSearchField 同时使用立即 action 和文本变化回调;可能重复提交同一查询;系统自动填充服务触发原因未知 | 统计回调与排序次数、避免相同值重复提交;独立控件实验确认系统服务触发条件 |
|
||||
| L15 | 确认 / P1 | system_profiler / diskutil 用 readDataToEndOfFile,完整读完后才检查 256 KiB;超时发 terminate 后仍等待退出 | 流式硬上限、截止时间、可靠回收本轮子进程;模拟大输出、卡住、退出竞态,不引入常规轮询 |
|
||||
@@ -288,12 +288,12 @@ python3 tools/check.py --configuration Release
|
||||
|
||||
| 阶段 | 当前状态 | 证据 / 未完成 |
|
||||
| --- | --- | --- |
|
||||
| 方案 | 实施中 | 按首批与第二批记录推进,性能预算保持原值 |
|
||||
| 方案 | 实施中 | 按首批至第三批记录推进,性能预算保持原值 |
|
||||
| P0 | 进行中 | 新 Release 复现、字形分配栈、组件隔离与真实面板三轮;仍缺受控 Debug / 完整触发链 |
|
||||
| P1 | 部分完成 | 批量 XPC / 服务共享 / 独立退避 / 取消超时 / 隐藏需求 / 公网暂停;遮挡、睡眠、息屏、需求代次与有界子进程已补;出口键和慢报告上层取消未完成 |
|
||||
| P2 | 部分完成 | 静态数字 / 曲线 / 风扇与路径缓存;内存峰值及回落未达标、按域发布已做,纯文字 / 完整面板三轮对照已记录(约 43 / 221 MiB 峰值);图标专项待做 |
|
||||
| P2 | 部分完成 | 静态展示、按域发布、路径缓存;第三批以原生曲线 / 圆环 / 虚拟表格、受限缩略图缓存与静态工具条修正独立绘制路径;完整三轮证据见第三批,内存峰值 / 回落与 CPU 预算尚未全部通过 |
|
||||
| P3 | 功能已实现,验收未完成 | 真实 CPU 能量、签名 XPC、部分覆盖与边界检查;跨硬件、巨大集合、公平性及额外 CPU 预算待验 |
|
||||
| P4 | 本轮包体积目标达标 | 含真实 CPU 能量的普通签名 arm64 app 2,016,168 B / ZIP 1,049,871 B,排除诊断实现;通用架构 / 公证发行流程待验 |
|
||||
| P4 | 本轮包体积目标达标 | 第三批普通签名 arm64 app 2,032,456 B / ZIP 1,062,783 B,排除诊断实现;较第二批增加 16,288 B,继续收敛,通用架构 / 公证发行流程待验 |
|
||||
| P5 | 未完成 | 短时面板和自动检查不替代 CPU / W / 100 次 / 8 小时与多硬件验收 |
|
||||
|
||||
每阶段更新本表及 L01–L16 的结论,记录提交、实测数值、未达标项和原因;架构 / 指标 / 测试事实分别同步主题文档。最终以完整功能、相同条件、关闭诊断的 Release 验收,不以“改完代码”或“编译通过”结束。方案完成后将稳定规则归入主题文档,过程记录保留到问题可审计为止。
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@
|
||||
| SMART | `DiskHealthMonitor` → XPC → `diskutil info -plist` | 主目录所在卷关联报告中的寿命和通电时间;剩余寿命 = 100 − PERCENTAGE_USED(下限 0),通电小时要求高位为 0,多物理存储拒绝合并;不代表所有卷或磁盘 |
|
||||
| 电池 | `BatteryMonitor`,IOPowerSources 与 AppleSmartBattery | 电量、充电 / 外接电源、循环和功率;功率取电压 × 电流的绝对值,非整机功耗;区分无内置电池和读取失败 |
|
||||
| 电池健康 | `SystemBatteryHealthMonitor`,`system_profiler SPPowerDataType -json` | 使用系统报告的最大容量百分比,不用当前充电容量推算 |
|
||||
| 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线 |
|
||||
| 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线;本地地址保持系统 numeric formatter(含 scope),每轮共用缓冲、每接口最终排序一次 |
|
||||
| 网络路径 | `NetworkPathObserver`,NWPathMonitor | 可用 / 不可用 / 需连接;代码取 `availableInterfaces.first` 作为主接口候选,并非独立解析系统默认路由;路径可用不保证公网可达 |
|
||||
| 公网 IP | `PublicIPAddressService`,`https://api.ipify.org` | 外部 HTTPS 服务看到的出口地址,可受代理 / VPN 影响;不是所选接口的公网地址。请求会向该服务暴露出口 IP |
|
||||
| 进程 | `ProcessMonitor`,sysctl、`proc_pidinfo`、`proc_pidpath` | 进程身份用 PID + 启动时间防复用;CPU 用累计 user + system 纳秒差分,RSS 为驻留量,权限受限字段留空 |
|
||||
|
||||
@@ -50,6 +50,7 @@ xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build
|
||||
swiftc -parse-as-library -module-cache-path /private/tmp/kymo-core-grid-cache \
|
||||
kymo/Features/MenuBar/CPUCoreGrid.swift kymo/Core/Services/CPUCoreTopology.swift \
|
||||
kymo/Core/Extensions/MetricFormat.swift kymo/UI/Components/MetricProgressBar.swift \
|
||||
kymo/UI/Components/NativeMetricRing.swift \
|
||||
kymoTests/CPUCoreGridChecks.swift -o /private/tmp/kymo-core-grid-checks
|
||||
/private/tmp/kymo-core-grid-checks
|
||||
```
|
||||
@@ -287,3 +288,16 @@ Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必
|
||||
纯文字与完整面板对照使用同一 Release 诊断包,构建时设置 `SWIFT_ACTIVE_COMPILATION_CONDITIONS=KYMO_AUDIT`;普通 Release 已排除诊断实现。`KYMO_RESOURCE_AUDIT=1 KYMO_DIAGNOSTICS=1` 启用三轮真实窗口生命周期,`KYMO_AUDIT_OMIT=text` 选择原生虚拟文字列表;保留全部后端、历史、公网策略和候选进程,只取消图表、图标、动画与复杂交互呈现。每次顺序运行,固定鼠标位置、不并行编译或 GUI 检查。日志记录 materialized cells 与关闭内容弱引用;这是诊断前端,并非产品界面已替换。
|
||||
|
||||
同一诊断包增加 `KYMO_XPC_AUDIT=1` 可检查 ServiceRequest 重复 / 并发响应、超时、启动前与在途取消。这使用真实连接生命周期与注入的本地完成回调,不代表服务端中断 / 崩溃传播已经实测;对端认证和实际读取另行验证。
|
||||
|
||||
## 第三批原生绘制与表格回归
|
||||
|
||||
统一入口新增四项,当前共 33 个 Swift 检查入口:
|
||||
|
||||
- `NativeMetricDrawingChecks`(GUI):真实 NSWindow 中捕获组件位图,检查曲线连续 / 缺失断点 / 全缺失、悬浮输入、深色外观、重复输入不重绘,以及圆环零 / 四分之一 / 完整像素。
|
||||
- `NativeProcessTableChecks`(GUI):500 行真实原生表格的可见单元格创建上限、原地刷新、身份选择重排 / 删除、委托外发布、排序、三语列头和复制菜单;将合成 Esc NSEvent 经窗口 sendEvent 投递到 firstResponder,验证退出回调。合成事件不是实际系统键盘或菜单栏事件。
|
||||
- `ProcessIconCacheChecks`:显示位图内容 / 尺寸、同应用共享、到期、LRU / 严格数量与像素字节上限、清空。
|
||||
- `NetworkAddressChecks`:应用沙盒下 IPv4 / IPv6 / mapped / 已知和未知 scope 与系统 numeric formatter 的文本等价性,核对本机实际地址但不输出地址值;空缓冲失败边界。
|
||||
|
||||
原生表格测试临时包复制实际编译的本地化资源后签名;不在运行时伪造资源。全部检查:`python3 tools/check.py --app /absolute/path/to/kymo.app --gui --network`。不要与固定浮动的性能审计窗口并行运行。
|
||||
|
||||
本轮组件隔离、完整三轮、CPU 与未解决项见[第三批记录](efficiency-third-batch.md)。正式面板局部截图与实际鼠标 / 键盘输入需单独确认;组件像素检查不等同完整面板视觉验收。
|
||||
|
||||
@@ -52,6 +52,7 @@ nonisolated struct NetworkMonitor {
|
||||
guard getifaddrs(&head) == 0 else { return [:] }
|
||||
defer { freeifaddrs(head) }
|
||||
var result: [String: (index: UInt32, addresses: [String], active: Bool)] = [:]
|
||||
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
var cursor = head
|
||||
while let entry = cursor {
|
||||
defer { cursor = entry.pointee.ifa_next }
|
||||
@@ -60,15 +61,20 @@ nonisolated struct NetworkMonitor {
|
||||
let active = flags & UInt32(IFF_UP | IFF_RUNNING) == UInt32(IFF_UP | IFF_RUNNING)
|
||||
var item = result[name] ?? (if_nametoindex(entry.pointee.ifa_name), [], active)
|
||||
if let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) {
|
||||
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
if getnameinfo(address, socklen_t(address.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 {
|
||||
item.addresses.append(String(cString: host))
|
||||
if let host = numericAddress(address, buffer: &hostBuffer) {
|
||||
item.addresses.append(host)
|
||||
}
|
||||
}
|
||||
item.addresses.sort()
|
||||
result[name] = item
|
||||
}
|
||||
return result
|
||||
return result.mapValues { (index: $0.index, addresses: $0.addresses.sorted(), active: $0.active) }
|
||||
}
|
||||
|
||||
static func numericAddress(_ address: UnsafePointer<sockaddr>, buffer: inout [CChar]) -> String? {
|
||||
guard !buffer.isEmpty else { return nil }
|
||||
let capacity = socklen_t(buffer.count)
|
||||
guard getnameinfo(address, socklen_t(address.pointee.sa_len), &buffer, capacity, nil, 0, NI_NUMERICHOST) == 0 else { return nil }
|
||||
return String(cString: buffer)
|
||||
}
|
||||
|
||||
/// NET_RT_IFLIST2 exposes 64-bit counters, avoiding getifaddrs' 4 GB wrap.
|
||||
|
||||
@@ -21,7 +21,7 @@ nonisolated enum SamplingDiagnostics {
|
||||
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
|
||||
}
|
||||
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil) {
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil, windowNumber: Int? = nil, hoveredPlots: Int? = nil, nativePlots: Int? = nil, pointerInsidePanel: Bool? = nil, plotBounds: [[Double]]? = nil) {
|
||||
guard enabled else { return }
|
||||
var payload: [String: Any] = [
|
||||
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
|
||||
@@ -31,6 +31,11 @@ nonisolated enum SamplingDiagnostics {
|
||||
"load": snapshot.load
|
||||
]
|
||||
payload["hiddenHostAlive"] = hiddenHostAlive
|
||||
payload["windowNumber"] = windowNumber
|
||||
payload["hoveredPlots"] = hoveredPlots
|
||||
payload["nativePlots"] = nativePlots
|
||||
payload["pointerInsidePanel"] = pointerInsidePanel
|
||||
payload["plotBounds"] = plotBounds
|
||||
payload["cpu"] = snapshot.cpu?.usage
|
||||
payload["cores"] = snapshot.cpu?.cores.count
|
||||
payload["cpuTemperature"] = snapshot.cpuTemperature
|
||||
|
||||
@@ -88,10 +88,7 @@ struct CPUCoreGrid: View {
|
||||
return GeometryReader { proxy in
|
||||
let diameter = min(maximumDiameter, max(0, proxy.size.width - 4))
|
||||
ZStack {
|
||||
Circle().inset(by: 1).stroke(color(kind).opacity(0.16), lineWidth: 2)
|
||||
Circle().inset(by: 1).trim(from: 0, to: value)
|
||||
.stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round))
|
||||
.rotationEffect(.degrees(-90))
|
||||
NativeMetricRing(value: value, color: color(kind), lineWidth: 2, trackOpacity: 0.16, inset: 1)
|
||||
Text(verbatim: "\(Int((value * 100).rounded()))")
|
||||
.font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import Observation
|
||||
private let menuTitle: (String) -> String
|
||||
private let openSettings: () -> Void
|
||||
private var showingStatusMenu = false
|
||||
private var isHiding = false
|
||||
|
||||
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
|
||||
menuTitle: @escaping (String) -> String = { $0 },
|
||||
@@ -33,7 +34,12 @@ import Observation
|
||||
self.visibility = visibility
|
||||
self.menuTitle = menuTitle
|
||||
self.openSettings = openSettings
|
||||
self.content = { NSHostingView(rootView: content($0)) }
|
||||
self.content = {
|
||||
let host = NSHostingView(rootView: content($0))
|
||||
// The controller owns the fixed panel frame; content must not negotiate window limits.
|
||||
host.sizingOptions = []
|
||||
return host
|
||||
}
|
||||
super.init()
|
||||
panel.title = "Kymo"
|
||||
panel.isReleasedWhenClosed = false
|
||||
@@ -126,12 +132,16 @@ import Observation
|
||||
}
|
||||
|
||||
func hide() {
|
||||
guard !isHiding else { return }
|
||||
isHiding = true
|
||||
defer { isHiding = false }
|
||||
presentation.isOpen = false
|
||||
panel.orderOut(nil)
|
||||
#if DEBUG || KYMO_AUDIT
|
||||
if let content = panel.contentView { lastHiddenContent = content }
|
||||
#endif
|
||||
panel.contentView = nil
|
||||
panel.closeAfterDetachingContent()
|
||||
visibility(false)
|
||||
removeMonitors()
|
||||
}
|
||||
@@ -197,6 +207,7 @@ final class MonitoringPanel: NSPanel {
|
||||
var dismiss: (() -> Void)?
|
||||
override var canBecomeKey: Bool { true }
|
||||
override var canBecomeMain: Bool { false }
|
||||
func closeAfterDetachingContent() { super.close() }
|
||||
override func cancelOperation(_ sender: Any?) { dismiss?() }
|
||||
override func close() { dismiss?() }
|
||||
override func performClose(_ sender: Any?) { dismiss?() }
|
||||
|
||||
@@ -183,7 +183,7 @@ struct MenuPanelView: View {
|
||||
}
|
||||
.buttonStyle(PanelControlButtonStyle())
|
||||
.padding(4)
|
||||
.glassEffect(.regular, in: .capsule)
|
||||
.background(.primary.opacity(0.04), in: .capsule)
|
||||
}
|
||||
.controlSize(.small)
|
||||
.padding(.horizontal, 2).padding(.vertical, 0)
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Native reusable cells keep process refreshes out of SwiftUI's per-cell render graphs.
|
||||
@MainActor struct NativeProcessTable: NSViewRepresentable {
|
||||
let rows: [ProcessMetrics]
|
||||
@Binding var selection: ProcessIdentity?
|
||||
@Binding var sorting: [ProcessSort]
|
||||
let locale: Locale
|
||||
var onExit: () -> Void = {}
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSScrollView, context: Context) -> CGSize? {
|
||||
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
||||
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSScrollView()
|
||||
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true
|
||||
scroll.autohidesScrollers = true; scroll.drawsBackground = false
|
||||
let table = ProcessNSTableView()
|
||||
table.style = .inset; 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), ("path", 400), ("cpu", 65), ("memory", 85), ("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.sortDescriptorPrototype = NSSortDescriptor(key: key, ascending: false)
|
||||
table.addTableColumn(column)
|
||||
}
|
||||
table.dataSource = context.coordinator; table.delegate = context.coordinator
|
||||
table.cancel = { [weak coordinator = context.coordinator] in
|
||||
Task { @MainActor in coordinator?.parent.onExit() }
|
||||
}
|
||||
table.contextMenu = { [weak coordinator = context.coordinator] row in coordinator?.menu(row: row) }
|
||||
scroll.documentView = table
|
||||
return scroll
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let table = scroll.documentView as? NSTableView else { return }
|
||||
context.coordinator.apply(self, to: table)
|
||||
}
|
||||
|
||||
final class ProcessNSTableView: NSTableView {
|
||||
var contextMenu: ((Int) -> NSMenu?)?
|
||||
var cancel: (() -> Void)?
|
||||
override func keyDown(with event: NSEvent) {
|
||||
// NSTableView otherwise consumes Esc for its own selection/editing behavior.
|
||||
if event.keyCode == 53 && event.modifierFlags.intersection([.command, .control, .option, .shift]).isEmpty {
|
||||
cancelOperation(nil)
|
||||
} else { super.keyDown(with: event) }
|
||||
}
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
if let cancel { cancel() } else { super.cancelOperation(sender) }
|
||||
}
|
||||
override func menu(for event: NSEvent) -> NSMenu? {
|
||||
let row = row(at: convert(event.locationInWindow, from: nil))
|
||||
if row >= 0 { selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) }
|
||||
return contextMenu?(row)
|
||||
}
|
||||
}
|
||||
@MainActor final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
|
||||
private(set) var parent: NativeProcessTable
|
||||
private var applying = false
|
||||
private var selected: ProcessIdentity?
|
||||
private var lastAppliedSelection: ProcessIdentity?
|
||||
private var selectionRevision = 0
|
||||
private var sortRevision = 0
|
||||
private var pendingSelection = false
|
||||
private var pendingSorting: [ProcessSort]?
|
||||
private var localizedLocale: String?
|
||||
private var restrictedTitle = ""
|
||||
private static let placeholder = NSImage(systemSymbolName: "app.dashed", accessibilityDescription: nil)
|
||||
private(set) var createdCells = 0
|
||||
init(_ parent: NativeProcessTable) { self.parent = parent; self.selected = parent.selection; self.lastAppliedSelection = parent.selection }
|
||||
|
||||
func apply(_ value: NativeProcessTable, to table: NSTableView) {
|
||||
// An explicit SwiftUI action (e.g. Esc) takes precedence over queued native events.
|
||||
if value.selection != lastAppliedSelection {
|
||||
selectionRevision += 1; pendingSelection = false
|
||||
}
|
||||
lastAppliedSelection = value.selection
|
||||
parent = value
|
||||
applying = true
|
||||
defer { applying = false }
|
||||
if !pendingSelection { selected = value.selection }
|
||||
if localizedLocale != value.locale.identifier {
|
||||
localizedLocale = value.locale.identifier
|
||||
restrictedTitle = AppLocalization.string("panel.restricted", locale: value.locale)
|
||||
for column in table.tableColumns {
|
||||
let key = column.identifier.rawValue
|
||||
let title: String
|
||||
switch key {
|
||||
case "pid": title = "PID"
|
||||
case "cpu": title = "CPU %"
|
||||
case "memory": title = AppLocalization.string("panel.rss", locale: value.locale)
|
||||
default: title = AppLocalization.string("panel." + key, locale: value.locale)
|
||||
}
|
||||
if column.title != title { column.title = title }
|
||||
}
|
||||
}
|
||||
let descriptors = (pendingSorting ?? value.sorting).map {
|
||||
NSSortDescriptor(key: Self.name($0.key), ascending: $0.order == .forward)
|
||||
}
|
||||
if table.sortDescriptors != descriptors { table.sortDescriptors = descriptors }
|
||||
let oldCount = table.numberOfRows, newCount = value.rows.count
|
||||
if oldCount != newCount {
|
||||
table.beginUpdates()
|
||||
if newCount > oldCount { table.insertRows(at: IndexSet(integersIn: oldCount..<newCount), withAnimation: []) }
|
||||
else { table.removeRows(at: IndexSet(integersIn: newCount..<oldCount), withAnimation: []) }
|
||||
table.endUpdates()
|
||||
}
|
||||
let selectedIndex = selected.flatMap { id in value.rows.firstIndex { $0.id == id } }
|
||||
let indices = selectedIndex.map { IndexSet(integer: $0) } ?? []
|
||||
if table.selectedRowIndexes != indices { table.selectRowIndexes(indices, byExtendingSelection: false) }
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
if visible.location != NSNotFound && visible.length > 0 {
|
||||
for row in visible.location..<min(newCount, visible.location + visible.length) {
|
||||
for column in table.tableColumns.indices {
|
||||
if let cell = table.view(atColumn: column, row: row, makeIfNecessary: false) as? Cell {
|
||||
update(cell, key: table.tableColumns[column].identifier.rawValue, process: value.rows[row])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func numberOfRows(in tableView: NSTableView) -> Int { parent.rows.count }
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
guard let column = tableColumn, parent.rows.indices.contains(row) else { return nil }
|
||||
let key = column.identifier.rawValue
|
||||
let cell: Cell
|
||||
if let reused = tableView.makeView(withIdentifier: column.identifier, owner: nil) as? Cell { cell = reused }
|
||||
else { cell = Cell(key: key); cell.identifier = column.identifier; createdCells += 1 }
|
||||
update(cell, key: key, process: parent.rows[row])
|
||||
return cell
|
||||
}
|
||||
private func update(_ cell: Cell, key: String, process: ProcessMetrics) {
|
||||
let text: String
|
||||
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.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--"
|
||||
default: text = process.threads.map(String.init) ?? "--"
|
||||
}
|
||||
if cell.textField?.stringValue != text { cell.textField?.stringValue = text }
|
||||
if key == "name" {
|
||||
let image = PanelResourceAudit.omitted == "icons" ? nil : process.path.flatMap { ProcessIconCache.shared.image(for: $0) }
|
||||
let desired = image ?? Self.placeholder
|
||||
if cell.imageView?.image !== desired { cell.imageView?.image = desired }
|
||||
} else if key == "threads" {
|
||||
if cell.imageView?.isHidden != !process.restricted { cell.imageView?.isHidden = !process.restricted }
|
||||
if cell.imageView?.accessibilityLabel() != restrictedTitle { cell.imageView?.setAccessibilityLabel(restrictedTitle) }
|
||||
}
|
||||
}
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
guard !applying, let table = notification.object as? NSTableView else { return }
|
||||
selected = parent.rows.indices.contains(table.selectedRow) ? parent.rows[table.selectedRow].id : nil
|
||||
selectionRevision += 1
|
||||
let revision = selectionRevision, id = selected
|
||||
pendingSelection = true
|
||||
// Never mutate the SwiftUI host while AppKit is inside its delegate callback.
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.selectionRevision == revision else { return }
|
||||
self.pendingSelection = false
|
||||
if self.parent.selection != id { self.parent.selection = id }
|
||||
}
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
|
||||
guard !applying else { return }
|
||||
let order = tableView.sortDescriptors.compactMap { descriptor -> ProcessSort? in
|
||||
guard let key = Self.key(descriptor.key ?? "") else { return nil }
|
||||
return ProcessSort(key: key, order: descriptor.ascending ? .forward : .reverse)
|
||||
}
|
||||
sortRevision += 1; let revision = sortRevision
|
||||
pendingSorting = order
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.sortRevision == revision else { return }
|
||||
self.pendingSorting = nil
|
||||
if self.parent.sorting != order { self.parent.sorting = order }
|
||||
}
|
||||
}
|
||||
func menu(row: Int) -> NSMenu? {
|
||||
guard parent.rows.indices.contains(row) else { return nil }
|
||||
let process = parent.rows[row], menu = NSMenu()
|
||||
menu.autoenablesItems = false
|
||||
for (key, value) in [("copyPID", String(process.id.pid)), ("copyName", process.name), ("copyPath", process.path)] {
|
||||
let item = NSMenuItem(title: AppLocalization.string(key, locale: parent.locale, table: "Process"), action: #selector(copyValue(_:)), keyEquivalent: "")
|
||||
item.target = self; item.representedObject = value; item.isEnabled = value != nil
|
||||
menu.addItem(item)
|
||||
}
|
||||
return menu
|
||||
}
|
||||
@objc private func copyValue(_ item: NSMenuItem) {
|
||||
guard let value = item.representedObject as? String else { return }
|
||||
NSPasteboard.general.clearContents(); NSPasteboard.general.setString(value, forType: .string)
|
||||
}
|
||||
private static func name(_ key: ProcessSort.Key) -> String {
|
||||
switch key { case .pid: "pid"; case .name: "name"; case .path: "path"; case .cpu: "cpu"; case .memory: "memory"; case .threads: "threads" }
|
||||
}
|
||||
private static func key(_ name: String) -> ProcessSort.Key? {
|
||||
switch name { case "pid": .pid; case "name": .name; case "path": .path; case "cpu": .cpu; case "memory": .memory; case "threads": .threads; default: nil }
|
||||
}
|
||||
}
|
||||
|
||||
final class Cell: NSTableCellView {
|
||||
private let key: String
|
||||
init(key: String) {
|
||||
self.key = key
|
||||
super.init(frame: .zero)
|
||||
let text = NSTextField(labelWithString: "")
|
||||
text.font = ["pid", "cpu", "memory", "threads"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11)
|
||||
text.alignment = ["cpu", "memory", "threads"].contains(key) ? .right : .left
|
||||
text.lineBreakMode = .byTruncatingMiddle
|
||||
text.textColor = key == "path" ? .secondaryLabelColor : .labelColor
|
||||
addSubview(text); textField = text
|
||||
if key == "name" || key == "threads" {
|
||||
let image = NSImageView(); image.imageScaling = .scaleProportionallyDown
|
||||
if key == "threads" { image.image = NSImage(systemSymbolName: "lock", accessibilityDescription: nil) }
|
||||
else { image.setAccessibilityElement(false) }
|
||||
addSubview(image); imageView = image
|
||||
}
|
||||
}
|
||||
required init?(coder: NSCoder) { nil }
|
||||
override func layout() {
|
||||
super.layout()
|
||||
let start: CGFloat = key == "name" ? 22 : 3
|
||||
let end: CGFloat = key == "threads" ? 16 : 3
|
||||
textField?.frame = NSRect(x: start, y: max(0, (bounds.height - 16) / 2), width: max(0, bounds.width - start - end), height: 16)
|
||||
imageView?.frame = key == "name" ? NSRect(x: 2, y: (bounds.height - 15) / 2, width: 15, height: 15) : NSRect(x: bounds.width - 12, y: (bounds.height - 11) / 2, width: 11, height: 11)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,20 @@ import AppKit
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
@MainActor func plots(in view: NSView?) -> [NativePanelCurve.PlotView] {
|
||||
guard let view else { return [] }
|
||||
let own = (view as? NativePanelCurve.PlotView).map { [$0] } ?? []
|
||||
return own + view.subviews.flatMap { plots(in: $0) }
|
||||
}
|
||||
@MainActor func mark(_ event: String) {
|
||||
var report = metrics.snapshot
|
||||
report.processes = metrics.processSnapshot
|
||||
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil)
|
||||
let views = plots(in: controller.panel.contentView)
|
||||
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil,
|
||||
windowNumber: controller.panel.isVisible ? controller.panel.windowNumber : nil,
|
||||
hoveredPlots: views.filter { $0.input?.hoveredIndex != nil }.count, nativePlots: views.count,
|
||||
pointerInsidePanel: controller.panel.isVisible && controller.panel.frame.contains(NSEvent.mouseLocation),
|
||||
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] })
|
||||
}
|
||||
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
|
||||
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
|
||||
|
||||
@@ -20,10 +20,7 @@ struct ProcessIcon: View {
|
||||
guard PanelResourceAudit.omitted != "icons" else { return }
|
||||
// Resolve by the sampled executable, avoiding an icon from a reused PID.
|
||||
guard let path = process.path else { icon = nil; return }
|
||||
let url = URL(fileURLWithPath: path)
|
||||
let app = sequence(first: url, next: { $0.path == "/" ? nil : $0.deletingLastPathComponent() })
|
||||
.first { $0.pathExtension == "app" }
|
||||
icon = NSWorkspace.shared.icon(forFile: (app ?? url).path)
|
||||
icon = ProcessIconCache.shared.image(for: path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import AppKit
|
||||
|
||||
/// Cache only display-sized pixels; never retain Workspace's original icon representations.
|
||||
@MainActor final class ProcessIconCache {
|
||||
static let shared = ProcessIconCache(observePressure: true)
|
||||
static let pixelLimit = 1_048_576
|
||||
private struct Entry {
|
||||
let image: NSImage
|
||||
let expires: TimeInterval
|
||||
let cost: Int
|
||||
var access: UInt64
|
||||
}
|
||||
private var entries: [String: Entry] = [:]
|
||||
private var access: UInt64 = 0
|
||||
private let resolve: (String) -> NSImage
|
||||
private let clock: () -> TimeInterval
|
||||
private var pressure: DispatchSourceMemoryPressure?
|
||||
private(set) var pixelBytes = 0
|
||||
var count: Int { entries.count }
|
||||
|
||||
init(observePressure: Bool = false, resolve: @escaping (String) -> NSImage = { NSWorkspace.shared.icon(forFile: $0) },
|
||||
clock: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
|
||||
self.resolve = resolve; self.clock = clock
|
||||
if observePressure {
|
||||
let source = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: .main)
|
||||
source.setEventHandler { [weak self] in Task { @MainActor in self?.removeAll() } }
|
||||
source.resume(); pressure = source
|
||||
}
|
||||
}
|
||||
deinit { pressure?.cancel() }
|
||||
|
||||
func image(for path: String) -> NSImage? {
|
||||
let url = URL(fileURLWithPath: path)
|
||||
let owner = sequence(first: url, next: { $0.path == "/" ? nil : $0.deletingLastPathComponent() })
|
||||
.first { $0.pathExtension == "app" }?.path ?? path
|
||||
let now = clock()
|
||||
access &+= 1
|
||||
if var entry = entries[owner], now < entry.expires {
|
||||
entry.access = access; entries[owner] = entry
|
||||
return entry.image
|
||||
}
|
||||
if let old = entries.removeValue(forKey: owner) { pixelBytes -= old.cost }
|
||||
guard let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 30, pixelsHigh: 30,
|
||||
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
|
||||
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0),
|
||||
let context = NSGraphicsContext(bitmapImageRep: bitmap) else { return nil }
|
||||
let original = resolve(owner)
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current = context
|
||||
context.imageInterpolation = .high
|
||||
original.draw(in: NSRect(x: 0, y: 0, width: 30, height: 30), from: .zero, operation: .copy, fraction: 1)
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
bitmap.size = NSSize(width: 15, height: 15)
|
||||
let image = NSImage(size: bitmap.size); image.addRepresentation(bitmap)
|
||||
let cost = bitmap.bytesPerRow * bitmap.pixelsHigh
|
||||
guard cost <= Self.pixelLimit else { return nil }
|
||||
entries[owner] = Entry(image: image, expires: now + 30, cost: cost, access: access)
|
||||
pixelBytes += cost
|
||||
while entries.count > 128 || pixelBytes > Self.pixelLimit {
|
||||
guard let oldest = entries.min(by: { $0.value.access < $1.value.access })?.key,
|
||||
let removed = entries.removeValue(forKey: oldest) else { break }
|
||||
pixelBytes -= removed.cost
|
||||
}
|
||||
return image
|
||||
}
|
||||
func removeAll() { entries.removeAll(); pixelBytes = 0 }
|
||||
}
|
||||
@@ -28,34 +28,7 @@ struct ProcessTableView: View {
|
||||
}
|
||||
if snapshot?.failed == true { Text("panel.processFailed") }
|
||||
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
// Native Table owns its vertical/horizontal scrolling and recycles visible cells.
|
||||
Table(rows, selection: $selected, sortOrder: $sortOrder) {
|
||||
TableColumn("PID", sortUsing: ProcessSort(key: .pid)) { row in Text(verbatim: "\(row.id.pid)") }.width(48)
|
||||
TableColumn("panel.name", sortUsing: ProcessSort(key: .name)) { row in
|
||||
HStack(spacing: 5) { ProcessIcon(process: row); Text(verbatim: row.name).lineLimit(1) }
|
||||
}.width(min: 90, ideal: 140, max: 180)
|
||||
TableColumn("panel.path", sortUsing: ProcessSort(key: .path)) { row in Text(verbatim: row.path ?? "--").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) }.width(min: 150, ideal: 400)
|
||||
TableColumn("CPU %", sortUsing: ProcessSort(key: .cpu)) { row in
|
||||
Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--")
|
||||
.frame(maxWidth: .infinity, alignment: .trailing)
|
||||
}.width(65)
|
||||
TableColumn("panel.rss", sortUsing: ProcessSort(key: .memory)) { row in Text(verbatim: row.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--") }.width(85)
|
||||
TableColumn("panel.threads", sortUsing: ProcessSort(key: .threads)) { row in
|
||||
HStack { Text(verbatim: row.threads.map(String.init) ?? "--"); if row.restricted { Image(systemName: "lock").accessibilityLabel(Text("panel.restricted")) } }
|
||||
}.width(65)
|
||||
}
|
||||
.contextMenu(forSelectionType: ProcessIdentity.self) { identities in
|
||||
if let id = identities.first, let row = rows.first(where: { $0.id == id }) {
|
||||
Button { copy(String(row.id.pid)) } label: { Text("copyPID", tableName: "Process") }
|
||||
Button { copy(row.name) } label: { Text("copyName", tableName: "Process") }
|
||||
Button { if let path = row.path { copy(path) } } label: { Text("copyPath", tableName: "Process") }
|
||||
.disabled(row.path == nil)
|
||||
}
|
||||
}
|
||||
.font(.system(size: 11)).monospacedDigit()
|
||||
.tableStyle(.inset(alternatesRowBackgrounds: true))
|
||||
.scrollContentBackground(.hidden)
|
||||
.transaction { $0.animation = nil }
|
||||
NativeProcessTable(rows: rows, selection: $selected, sorting: $sortOrder, locale: locale, onExit: handleExit)
|
||||
.overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } }
|
||||
if exitedSelection != nil, let departed {
|
||||
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { selected = nil; self.departed = nil } }
|
||||
@@ -75,13 +48,14 @@ struct ProcessTableView: View {
|
||||
do { try await Task.sleep(for: .seconds(3)) } catch { return }
|
||||
if exitedSelection == id { selected = nil; departed = nil }
|
||||
}
|
||||
.onExitCommand {
|
||||
.onExitCommand(perform: handleExit)
|
||||
}
|
||||
private func handleExit() {
|
||||
if !search.isEmpty { search = "" }
|
||||
else if selected != nil { selected = nil; departed = nil }
|
||||
else if searchFocused { searchFocused = false }
|
||||
else { NSApp.keyWindow?.close() }
|
||||
}
|
||||
}
|
||||
private var processTitle: some View {
|
||||
Label("panel.processes", systemImage: "list.bullet.rectangle")
|
||||
.font(PanelStyle.title)
|
||||
@@ -91,10 +65,6 @@ struct ProcessTableView: View {
|
||||
placeholder: AppLocalization.string("panel.search", locale: locale))
|
||||
}
|
||||
|
||||
private func copy(_ value: String) {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(value, forType: .string)
|
||||
}
|
||||
private func rebuild(retainOrder: Bool) {
|
||||
rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, sorting: sortOrder, order: retainOrder ? rows.map(\.id) : [])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// A bounded native plot; SwiftUI still owns axes, legends and hover presentation.
|
||||
struct NativePanelCurve: NSViewRepresentable {
|
||||
let frame: PanelCurveFrame
|
||||
let colors: [Color]
|
||||
let scales: [Double]
|
||||
let maximumGap: TimeInterval
|
||||
var hoveredIndex: Int? = nil
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
|
||||
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
||||
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
|
||||
}
|
||||
|
||||
func makeNSView(context: Context) -> PlotView { PlotView() }
|
||||
func updateNSView(_ view: PlotView, context: Context) {
|
||||
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap, hoveredIndex: hoveredIndex))
|
||||
}
|
||||
|
||||
struct Input: Equatable {
|
||||
let frame: PanelCurveFrame
|
||||
let colors: [Color]
|
||||
let scales: [Double]
|
||||
let maximumGap: TimeInterval
|
||||
var hoveredIndex: Int? = nil
|
||||
}
|
||||
|
||||
final class PlotView: NSView {
|
||||
private(set) var input: Input?
|
||||
override var isFlipped: Bool { true }
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
wantsLayer = true
|
||||
layerContentsRedrawPolicy = .onSetNeedsDisplay
|
||||
setAccessibilityElement(false)
|
||||
}
|
||||
required init?(coder: NSCoder) { nil }
|
||||
|
||||
func configure(_ value: Input) {
|
||||
guard input != value else { return }
|
||||
input = value
|
||||
needsDisplay = true
|
||||
}
|
||||
override func setFrameSize(_ newSize: NSSize) {
|
||||
let changed = frame.size != newSize
|
||||
super.setFrameSize(newSize)
|
||||
if changed { needsDisplay = true }
|
||||
}
|
||||
override func viewDidChangeEffectiveAppearance() {
|
||||
super.viewDidChangeEffectiveAppearance()
|
||||
needsDisplay = true
|
||||
}
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
guard let context = NSGraphicsContext.current?.cgContext else { return }
|
||||
context.saveGState()
|
||||
defer { context.restoreGState() }
|
||||
context.clip(to: bounds)
|
||||
context.setLineWidth(0.5)
|
||||
context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.10).cgColor)
|
||||
for step in 0...10 {
|
||||
let x = bounds.width * Double(step) / 10
|
||||
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height))
|
||||
}
|
||||
for step in 0...2 {
|
||||
let y = bounds.height * Double(step) / 2
|
||||
context.move(to: CGPoint(x: 0, y: y)); context.addLine(to: CGPoint(x: bounds.width, y: y))
|
||||
}
|
||||
context.strokePath()
|
||||
guard let input, let first = input.frame.dates.first, let last = input.frame.dates.last,
|
||||
!input.colors.isEmpty, !input.scales.isEmpty else { return }
|
||||
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
|
||||
for index in input.frame.series.indices {
|
||||
let tint = NSColor(input.colors[min(index, input.colors.count - 1)])
|
||||
let proposedScale = input.scales[min(index, input.scales.count - 1)]
|
||||
let scale = proposedScale.isFinite && proposedScale > 0 ? proposedScale : 1
|
||||
let runs = PanelCurveGeometry.runs(dates: input.frame.dates, values: input.frame.series[index],
|
||||
maximumGap: input.maximumGap, boundaryDates: input.frame.boundaryDates, intervals: input.frame.intervals)
|
||||
context.setFillColor(tint.cgColor)
|
||||
context.setStrokeColor(tint.cgColor)
|
||||
context.setLineWidth(1.5)
|
||||
context.setLineCap(.round); context.setLineJoin(.round)
|
||||
for run in runs {
|
||||
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
|
||||
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) }
|
||||
guard let start = points.first, let finish = points.last else { continue }
|
||||
if points.count == 1 {
|
||||
context.fillEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4))
|
||||
continue
|
||||
}
|
||||
let line = CGMutablePath(); line.move(to: start)
|
||||
for (a, b) in zip(points, points.dropFirst()) {
|
||||
let middle = (a.x + b.x) / 2
|
||||
line.addCurve(to: b, control1: CGPoint(x: middle, y: a.y), control2: CGPoint(x: middle, y: b.y))
|
||||
}
|
||||
let area = line.mutableCopy()!
|
||||
area.addLine(to: CGPoint(x: finish.x, y: bounds.height))
|
||||
area.addLine(to: CGPoint(x: start.x, y: bounds.height)); area.closeSubpath()
|
||||
if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB),
|
||||
colors: [tint.withAlphaComponent(0.20).cgColor, tint.withAlphaComponent(0.01).cgColor] as CFArray,
|
||||
locations: [0, 1]) {
|
||||
context.saveGState(); context.addPath(area); context.clip()
|
||||
context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: bounds.height), options: [])
|
||||
context.restoreGState()
|
||||
}
|
||||
context.addPath(line); context.strokePath()
|
||||
}
|
||||
}
|
||||
if let index = input.hoveredIndex, input.frame.dates.indices.contains(index), last > first {
|
||||
let x = bounds.width * domain.position(input.frame.dates[index])
|
||||
context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.45).cgColor)
|
||||
context.setLineWidth(1); context.setLineDash(phase: 0, lengths: [3, 2])
|
||||
context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height)); context.strokePath()
|
||||
context.setLineDash(phase: 0, lengths: [])
|
||||
for series in input.frame.series.indices {
|
||||
let values = input.frame.series[series]
|
||||
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
|
||||
let scale = input.scales[min(series, input.scales.count - 1)]
|
||||
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
|
||||
context.setFillColor(NSColor(input.colors[min(series, input.colors.count - 1)]).cgColor)
|
||||
context.fillEllipse(in: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// A render frame may keep one outgoing point beyond the bounded 60-sample history.
|
||||
nonisolated struct PanelCurveFrame {
|
||||
nonisolated struct PanelCurveFrame: Equatable {
|
||||
let dates: [Date]
|
||||
let series: [[Double?]]
|
||||
let intervals: [TimeInterval]
|
||||
|
||||
@@ -123,25 +123,9 @@ struct PanelTrendChart: View {
|
||||
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight)
|
||||
GeometryReader { proxy in
|
||||
ZStack(alignment: .topLeading) {
|
||||
PanelCurveCanvas(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
|
||||
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
|
||||
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale],
|
||||
maximumGap: max(5, expectedInterval * 2),
|
||||
targetBegin: dates.first, targetEnd: dates.last,
|
||||
previousBegin: nil, previousEnd: nil, progress: 1)
|
||||
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
|
||||
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
|
||||
Path { path in
|
||||
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: proxy.size.height))
|
||||
}.stroke(.primary.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [3, 2]))
|
||||
ForEach(0..<4, id: \.self) { series in
|
||||
let values = [first, second, third, fourth][series]
|
||||
if index < values.count, let value = values[index], value.isFinite {
|
||||
let seriesScale = [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale][series]
|
||||
Circle().fill([color, secondColor, thirdColor, fourthColor][series]).frame(width: 5, height: 5)
|
||||
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / seriesScale))))
|
||||
}
|
||||
}
|
||||
}
|
||||
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.onContinuousHover { phase in
|
||||
@@ -199,63 +183,3 @@ struct PanelTrendChart: View {
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PanelCurveCanvas: View, Animatable {
|
||||
let frame: PanelCurveFrame
|
||||
let colors: [Color]
|
||||
let scales: [Double]
|
||||
let maximumGap: TimeInterval
|
||||
let targetBegin: Date?
|
||||
let targetEnd: Date?
|
||||
let previousBegin: Date?
|
||||
let previousEnd: Date?
|
||||
var progress: CGFloat
|
||||
var animatableData: CGFloat {
|
||||
get { progress }
|
||||
set { progress = newValue }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Canvas { context, size in
|
||||
var grid = Path()
|
||||
for step in 0...10 {
|
||||
let x = size.width * Double(step) / 10
|
||||
grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: size.height))
|
||||
}
|
||||
for step in 0...2 {
|
||||
let y = size.height * Double(step) / 2
|
||||
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
|
||||
}
|
||||
context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5)
|
||||
guard let first = targetBegin, let last = targetEnd else { return }
|
||||
let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd,
|
||||
begin: first, end: last, progress: Double(progress))
|
||||
for seriesIndex in frame.series.indices {
|
||||
let values = frame.series[seriesIndex]
|
||||
let tint = colors[min(seriesIndex, colors.count - 1)]
|
||||
let scale = scales[min(seriesIndex, scales.count - 1)]
|
||||
for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) {
|
||||
let points = run.map { item in
|
||||
CGPoint(x: size.width * domain.position(item.date),
|
||||
y: size.height * (1 - min(1, max(0, item.value / scale))))
|
||||
}
|
||||
guard let start = points.first, let finish = points.last else { continue }
|
||||
var line = Path(); line.move(to: start)
|
||||
for pair in zip(points, points.dropFirst()) {
|
||||
let middle = (pair.0.x + pair.1.x) / 2
|
||||
// Horizontal tangents keep the rounded curve between adjacent sample values.
|
||||
line.addCurve(to: pair.1, control1: CGPoint(x: middle, y: pair.0.y), control2: CGPoint(x: middle, y: pair.1.y))
|
||||
}
|
||||
if points.count == 1 {
|
||||
context.fill(Path(ellipseIn: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)), with: .color(tint))
|
||||
} else {
|
||||
var area = line
|
||||
area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath()
|
||||
context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
|
||||
context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,10 @@ struct MetricRingGauge: View {
|
||||
var body: some View {
|
||||
VStack(spacing: 3) {
|
||||
ZStack {
|
||||
Circle().stroke(color.opacity(0.17), lineWidth: 3)
|
||||
Circle().trim(from: 0, to: fraction)
|
||||
.stroke(color, style: StrokeStyle(lineWidth: 3, lineCap: .round))
|
||||
.rotationEffect(.degrees(-90))
|
||||
NativeMetricRing(value: fraction, color: color, lineWidth: 3, trackOpacity: 0.17, inset: 2)
|
||||
AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
|
||||
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12)
|
||||
}.padding(2).frame(width: 28, height: 28).accessibilityHidden(true)
|
||||
}.frame(width: 28, height: 28).accessibilityHidden(true)
|
||||
Text(title).font(.system(size: 8)).foregroundStyle(.secondary)
|
||||
.lineLimit(1).minimumScaleFactor(0.7)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Small Core Graphics arcs avoid creating a SwiftUI path-rendering surface for every gauge.
|
||||
struct NativeMetricRing: NSViewRepresentable {
|
||||
let value: Double
|
||||
let color: Color
|
||||
let lineWidth: CGFloat
|
||||
let trackOpacity: Double
|
||||
let inset: CGFloat
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, context: Context) -> CGSize? {
|
||||
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
||||
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
|
||||
}
|
||||
|
||||
func makeNSView(context: Context) -> RingView { RingView() }
|
||||
func updateNSView(_ view: RingView, context: Context) {
|
||||
view.configure(Input(value: value.isFinite ? min(1, max(0, value)) : 0, color: color,
|
||||
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset))
|
||||
}
|
||||
struct Input: Equatable {
|
||||
let value: Double
|
||||
let color: Color
|
||||
let lineWidth: CGFloat
|
||||
let trackOpacity: Double
|
||||
let inset: CGFloat
|
||||
}
|
||||
final class RingView: NSView {
|
||||
private(set) var input: Input?
|
||||
override var isFlipped: Bool { true }
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
wantsLayer = true; layerContentsRedrawPolicy = .onSetNeedsDisplay
|
||||
setAccessibilityElement(false)
|
||||
}
|
||||
required init?(coder: NSCoder) { nil }
|
||||
func configure(_ value: Input) {
|
||||
guard value != input else { return }
|
||||
input = value; needsDisplay = true
|
||||
}
|
||||
override func setFrameSize(_ newSize: NSSize) {
|
||||
let changed = newSize != frame.size
|
||||
super.setFrameSize(newSize)
|
||||
if changed { needsDisplay = true }
|
||||
}
|
||||
override func viewDidChangeEffectiveAppearance() {
|
||||
super.viewDidChangeEffectiveAppearance(); needsDisplay = true
|
||||
}
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
guard let input, let context = NSGraphicsContext.current?.cgContext else { return }
|
||||
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
|
||||
guard radius > 0 else { return }
|
||||
let center = CGPoint(x: bounds.midX, y: bounds.midY)
|
||||
let tint = NSColor(input.color)
|
||||
context.saveGState(); defer { context.restoreGState() }
|
||||
context.setLineWidth(input.lineWidth); context.setLineCap(.round)
|
||||
context.setStrokeColor(tint.withAlphaComponent(input.trackOpacity).cgColor)
|
||||
context.strokeEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))
|
||||
guard input.value > 0 else { return }
|
||||
context.setStrokeColor(tint.cgColor)
|
||||
context.addArc(center: center, radius: radius, startAngle: -.pi / 2,
|
||||
endAngle: -.pi / 2 + 2 * .pi * input.value, clockwise: false)
|
||||
context.strokePath()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
@main struct NativeMetricDrawingChecks {
|
||||
@MainActor static func main() {
|
||||
_ = NSApplication.shared; NSApp.setActivationPolicy(.accessory)
|
||||
Task { @MainActor in
|
||||
let window = NSWindow(contentRect: NSRect(x: 40, y: 40, width: 300, height: 140), styleMask: [.borderless], backing: .buffered, defer: false)
|
||||
window.isReleasedWhenClosed = false
|
||||
let root = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 140))
|
||||
window.contentView = root
|
||||
let plot = NativePanelCurve.PlotView(); plot.frame = NSRect(x: 0, y: 0, width: 280, height: 60)
|
||||
root.addSubview(plot)
|
||||
let ring = NativeMetricRing.RingView(); ring.frame = NSRect(x: 0, y: 70, width: 28, height: 28)
|
||||
root.addSubview(ring)
|
||||
window.orderFrontRegardless()
|
||||
try? await Task.sleep(for: .milliseconds(100))
|
||||
let dates = (0..<4).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
|
||||
func input(_ values: [Double?]) -> NativePanelCurve.Input {
|
||||
NativePanelCurve.Input(frame: PanelCurveFrame(dates: dates, series: [values], intervals: [2,2,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5)
|
||||
}
|
||||
let continuous = input([0.8,0.8,0.8,0.8])
|
||||
plot.configure(continuous)
|
||||
let image = bitmap(plot)
|
||||
precondition(redPixels(image, from: 0.4, to: 0.6) > 10, "Continuous curve must cross the middle")
|
||||
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]))
|
||||
precondition(redPixels(bitmap(plot), from: 0.4, to: 0.6) == 0, "Missing values must leave a real gap")
|
||||
plot.configure(input([nil,nil,nil,nil]))
|
||||
precondition(redPixels(bitmap(plot)) == 0)
|
||||
var hovered = continuous; hovered.hoveredIndex = 1
|
||||
plot.configure(hovered)
|
||||
precondition(redPixels(bitmap(plot)) > 0)
|
||||
plot.appearance = NSAppearance(named: .darkAqua)
|
||||
precondition(redPixels(bitmap(plot)) > 0)
|
||||
ring.configure(NativeMetricRing.Input(value: 0, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2))
|
||||
precondition(redPixels(bitmap(ring), opaque: true) == 0, "Zero ring must not draw a colored arc")
|
||||
ring.configure(NativeMetricRing.Input(value: 0.25, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2))
|
||||
let quarter = redPixels(bitmap(ring), opaque: true)
|
||||
ring.configure(NativeMetricRing.Input(value: 1, color: .red, lineWidth: 3, trackOpacity: 0.17, inset: 2))
|
||||
let full = redPixels(bitmap(ring), opaque: true)
|
||||
precondition(quarter > 0 && full > quarter * 2, "Ring fraction must change the rendered arc")
|
||||
window.orderOut(nil); window.close()
|
||||
print("PASS: native curve pixels, real gaps, missing series, hover, appearance, duplicate-input invalidation and zero/quarter/full ring pixels")
|
||||
fflush(stdout); NSApp.terminate(nil)
|
||||
}
|
||||
NSApp.run()
|
||||
}
|
||||
@MainActor private static func bitmap(_ view: NSView) -> NSBitmapImageRep {
|
||||
let result = view.bitmapImageRepForCachingDisplay(in: view.bounds)!
|
||||
view.cacheDisplay(in: view.bounds, to: result)
|
||||
return result
|
||||
}
|
||||
private static func redPixels(_ image: NSBitmapImageRep, from: Double = 0, to: Double = 1, opaque: Bool = false) -> Int {
|
||||
var count = 0
|
||||
for x in Int(Double(image.pixelsWide) * from)..<Int(Double(image.pixelsWide) * to) {
|
||||
for y in 0..<image.pixelsHigh {
|
||||
guard let color = image.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB) else { continue }
|
||||
if color.redComponent > color.greenComponent + 0.15 && color.redComponent > color.blueComponent + 0.15 && color.alphaComponent > (opaque ? 0.8 : 0.01) { count += 1 }
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import Observation
|
||||
|
||||
@MainActor @Observable private final class State {
|
||||
var rows: [ProcessMetrics]
|
||||
var selection: ProcessIdentity?
|
||||
var sorting = [ProcessSort(key: .cpu)]
|
||||
var locale = Locale(identifier: "en")
|
||||
var insideDelegate = false
|
||||
var exits = 0
|
||||
init() {
|
||||
rows = (0..<500).map { index in
|
||||
ProcessMetrics(id: ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0),
|
||||
name: "worker-\(index)", path: nil, cpu: Double(index) / 100,
|
||||
residentBytes: 10_000_000, threads: 2, restricted: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
private struct Host: View {
|
||||
let state: State
|
||||
var body: some View {
|
||||
NativeProcessTable(rows: state.rows, selection: Binding(get: { state.selection }, set: {
|
||||
precondition(!state.insideDelegate, "Selection published inside an AppKit delegate callback")
|
||||
state.selection = $0
|
||||
}), sorting: Binding(get: { state.sorting }, set: {
|
||||
precondition(!state.insideDelegate, "Sort published inside an AppKit delegate callback")
|
||||
state.sorting = $0
|
||||
}), locale: state.locale, onExit: { state.exits += 1 }).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
@MainActor private final class DelegateProbe: NSObject, NSTableViewDelegate {
|
||||
let state: State
|
||||
let target: NativeProcessTable.Coordinator
|
||||
init(_ state: State, _ target: NativeProcessTable.Coordinator) { self.state = state; self.target = target }
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
state.insideDelegate = true
|
||||
target.tableViewSelectionDidChange(notification)
|
||||
state.insideDelegate = false
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
|
||||
state.insideDelegate = true
|
||||
target.tableView(tableView, sortDescriptorsDidChange: oldDescriptors)
|
||||
state.insideDelegate = false
|
||||
}
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
target.tableView(tableView, viewFor: tableColumn, row: row)
|
||||
}
|
||||
}
|
||||
@main struct NativeProcessTableChecks {
|
||||
@MainActor static func main() {
|
||||
_ = NSApplication.shared; NSApp.setActivationPolicy(.accessory)
|
||||
Task { @MainActor in
|
||||
let state = State()
|
||||
let window = NSWindow(contentRect: NSRect(x: 30, y: 30, width: 900, height: 260), styleMask: [.titled], backing: .buffered, defer: false)
|
||||
window.isReleasedWhenClosed = false
|
||||
let host = NSHostingView(rootView: Host(state: state))
|
||||
window.contentView = host; window.makeKeyAndOrderFront(nil)
|
||||
try? await Task.sleep(for: .milliseconds(200))
|
||||
let table = find(host)!
|
||||
let coordinator = table.delegate as! NativeProcessTable.Coordinator
|
||||
let probe = DelegateProbe(state, coordinator)
|
||||
table.delegate = probe
|
||||
precondition(table.numberOfRows == 500 && table.tableColumns.count == 6)
|
||||
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 chosen = state.rows[10].id
|
||||
table.selectRowIndexes(IndexSet(integer: 10), byExtendingSelection: false)
|
||||
precondition(state.selection == nil, "Native selection must be deferred")
|
||||
await until { state.selection == chosen }
|
||||
state.rows.reverse()
|
||||
await until { table.selectedRow == 489 }
|
||||
precondition(state.selection == chosen, "Selection must follow identity after reordering")
|
||||
for index in 0..<12 {
|
||||
state.rows[0] = ProcessMetrics(id: state.rows[0].id, name: "updated-\(index)", path: nil, cpu: Double(index), residentBytes: nil, threads: nil, restricted: false)
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
if visible.location != NSNotFound, visible.length > 0,
|
||||
let cell = table.view(atColumn: 1, row: visible.location, makeIfNecessary: false) as? NSTableCellView {
|
||||
precondition(cell.textField?.stringValue == state.rows[visible.location].name)
|
||||
} else { preconditionFailure("No visible native cell") }
|
||||
precondition(coordinator.createdCells < 250, "Refreshes must reuse visible cells")
|
||||
table.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
|
||||
await until { state.sorting == [ProcessSort(key: .name, order: .forward)] }
|
||||
let menu = coordinator.menu(row: 0)!
|
||||
precondition(menu.items.count == 3 && menu.items[0].representedObject as? String == String(state.rows[0].id.pid))
|
||||
precondition(menu.items[1].representedObject as? String == state.rows[0].name && !menu.items[2].isEnabled)
|
||||
state.rows.removeAll { $0.id == chosen }
|
||||
await until { table.numberOfRows == 499 && table.selectedRow == -1 }
|
||||
precondition(state.selection == chosen, "Filtering/removal must not invent a new selected identity")
|
||||
state.selection = nil
|
||||
state.locale = Locale(identifier: "zh-Hans")
|
||||
await until { table.tableColumns[1].title == "名称" }
|
||||
state.rows.removeAll(); await until { table.numberOfRows == 0 }
|
||||
precondition(window.makeFirstResponder(table))
|
||||
let escape = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
|
||||
windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)!
|
||||
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")
|
||||
fflush(stdout); NSApp.terminate(nil)
|
||||
}
|
||||
NSApp.run()
|
||||
}
|
||||
@MainActor private static func until(_ predicate: () -> Bool, line: UInt = #line) async {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||
while !predicate() && ContinuousClock.now < deadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||
precondition(predicate(), "Timed out waiting for native table update at line \(line)")
|
||||
}
|
||||
@MainActor private static func find(_ view: NSView) -> NSTableView? {
|
||||
if let table = view as? NSTableView { return table }
|
||||
for child in view.subviews { if let table = find(child) { return table } }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
@main struct NetworkAddressChecks {
|
||||
static func main() {
|
||||
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
func check(_ address: UnsafePointer<sockaddr>) {
|
||||
var original = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
let rc = getnameinfo(address, socklen_t(address.pointee.sa_len), &original, socklen_t(original.count), nil, 0, NI_NUMERICHOST)
|
||||
let expected = rc == 0 ? String(cString: original) : nil
|
||||
let value = NetworkMonitor.numericAddress(address, buffer: &buffer)
|
||||
precondition(value == expected, "Canonical numeric address / scope changed")
|
||||
}
|
||||
let loop = if_nametoindex("lo0")
|
||||
var v4 = sockaddr_in(); v4.sin_len = UInt8(MemoryLayout.size(ofValue: v4)); v4.sin_family = UInt8(AF_INET)
|
||||
precondition(inet_pton(AF_INET, "192.0.2.1", &v4.sin_addr) == 1)
|
||||
withUnsafePointer(to: &v4) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { check($0) } }
|
||||
for text in ["::1", "2001:db8::1", "::ffff:192.0.2.1", "fe80::1"] {
|
||||
var v6 = sockaddr_in6(); v6.sin6_len = UInt8(MemoryLayout.size(ofValue: v6)); v6.sin6_family = UInt8(AF_INET6)
|
||||
precondition(inet_pton(AF_INET6, text, &v6.sin6_addr) == 1)
|
||||
for scope in [UInt32(0), loop, UInt32.max] {
|
||||
v6.sin6_scope_id = scope
|
||||
withUnsafePointer(to: &v6) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
|
||||
check($0)
|
||||
var empty: [CChar] = []
|
||||
precondition(NetworkMonitor.numericAddress($0, buffer: &empty) == nil)
|
||||
} }
|
||||
}
|
||||
}
|
||||
var head: UnsafeMutablePointer<ifaddrs>?
|
||||
precondition(getifaddrs(&head) == 0)
|
||||
defer { freeifaddrs(head) }
|
||||
var cursor = head, count = 0
|
||||
while let entry = cursor {
|
||||
defer { cursor = entry.pointee.ifa_next }
|
||||
guard let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) else { continue }
|
||||
check(UnsafePointer(address))
|
||||
count += 1
|
||||
}
|
||||
precondition(count > 0)
|
||||
print("PASS: sandbox IPv4/IPv6, known/unknown scopes, mapped addresses, empty buffer and canonical equivalence for", count, "live addresses (values omitted)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import AppKit
|
||||
|
||||
@main struct ProcessIconCacheChecks {
|
||||
@MainActor static func main() {
|
||||
var reads = 0, now: TimeInterval = 1
|
||||
let cache = ProcessIconCache(resolve: { _ in
|
||||
reads += 1
|
||||
return NSImage(size: NSSize(width: 1024, height: 1024), flipped: false) { bounds in
|
||||
NSColor.systemBlue.setFill(); bounds.fill(); return true
|
||||
}
|
||||
}, clock: { now })
|
||||
let first = cache.image(for: "/Applications/Example.app/Contents/MacOS/main")!
|
||||
let second = cache.image(for: "/Applications/Example.app/Contents/Helpers/worker")!
|
||||
precondition(first === second && reads == 1, "Executables in the same app must share a thumbnail")
|
||||
let bitmap = first.representations.first as! NSBitmapImageRep
|
||||
precondition(first.size == NSSize(width: 15, height: 15) && bitmap.pixelsWide == 30 && bitmap.pixelsHigh == 30)
|
||||
precondition(first.representations.count == 1 && cache.pixelBytes <= 4096)
|
||||
precondition(bitmap.colorAt(x: 15, y: 15)!.alphaComponent > 0.9, "Thumbnail must retain rendered pixels")
|
||||
now = 32
|
||||
let renewed = cache.image(for: "/Applications/Example.app/Contents/MacOS/main")!
|
||||
precondition(renewed !== first && reads == 2 && cache.count == 1)
|
||||
for index in 0..<200 { _ = cache.image(for: "/test/\(index)/worker") }
|
||||
precondition(cache.count == 128 && cache.pixelBytes <= ProcessIconCache.pixelLimit)
|
||||
let before = reads
|
||||
_ = cache.image(for: "/test/199/worker")
|
||||
precondition(reads == before, "Recent entry must survive eviction")
|
||||
_ = cache.image(for: "/test/0/worker")
|
||||
precondition(reads == before + 1, "Evicted entry must be resolved again")
|
||||
cache.removeAll()
|
||||
precondition(cache.count == 0 && cache.pixelBytes == 0)
|
||||
print("PASS: app-shared raster thumbnails, pixel content/dimensions, expiry, strict bounds, LRU and explicit clearing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
enum PanelResourceAudit { static let omitted = "" }
|
||||
+16
-6
@@ -24,10 +24,18 @@ CHECKS.update({
|
||||
"SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.swift"],
|
||||
"TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.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", "kymo/UI/Components/MetricProgressBar.swift", "kymo/UI/Components/NativeMetricRing.swift"],
|
||||
"CPUTemperatureChecks": ["kymo/Core/Monitors/CPUTemperatureMonitor.swift"],
|
||||
"DiskHealthChecks": ["kymo/Core/Models/DiskHealthMetrics.swift", "kymo/Core/Monitors/DiskHealthReport.swift"],
|
||||
"PublicIPAddressChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
|
||||
"NativeMetricDrawingChecks": ["kymo/UI/Charts/NativePanelCurve.swift", "kymo/UI/Charts/PanelCurveFrame.swift",
|
||||
"kymo/UI/Charts/PanelCurveGeometry.swift", "kymo/UI/Components/NativeMetricRing.swift"],
|
||||
"NetworkAddressChecks": ["kymo/Core/Monitors/NetworkMonitor.swift"],
|
||||
"ProcessIconCacheChecks": ["kymo/Features/MenuBar/ProcessIconCache.swift"],
|
||||
"NativeProcessTableChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/ProcessTableProjection.swift",
|
||||
"kymo/Features/MenuBar/NativeProcessTable.swift", "kymo/Features/MenuBar/ProcessIconCache.swift",
|
||||
"kymo/Core/Services/LanguagePreferences.swift", "kymo/UI/Components/AppLocalization.swift",
|
||||
"kymoTests/Support/ProcessTableAuditStub.swift"],
|
||||
"ProcessSelectionChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/ProcessTableProjection.swift"],
|
||||
"PanelLayoutChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/PanelLayout.swift",
|
||||
"kymo/Features/MenuBar/ProcessTableProjection.swift"],
|
||||
@@ -47,7 +55,7 @@ CHECKS.update({
|
||||
"kymo/UI/Components/IntervalControl.swift"],
|
||||
"SandboxNetworkChecks": [],
|
||||
})
|
||||
GUI = {"LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"}
|
||||
GUI = {"NativeMetricDrawingChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"}
|
||||
NETWORK = {"SandboxNetworkChecks"}
|
||||
|
||||
|
||||
@@ -72,7 +80,7 @@ def entitlements(app):
|
||||
return value
|
||||
|
||||
|
||||
def test_bundle(work, name, executable, host_entitlements=None):
|
||||
def test_bundle(work, name, executable, host_entitlements=None, resources=None):
|
||||
app = work / (name + ".app")
|
||||
contents = app / "Contents"
|
||||
(contents / "MacOS").mkdir(parents=True)
|
||||
@@ -80,8 +88,10 @@ def test_bundle(work, name, executable, host_entitlements=None):
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps({
|
||||
"CFBundleIdentifier": "cn.airnan.kymo.checks." + uuid.uuid4().hex,
|
||||
"CFBundleExecutable": name, "CFBundlePackageType": "APPL",
|
||||
"LSUIElement": name in {"PanelWindowChecks", "SandboxNetworkChecks"},
|
||||
"LSUIElement": name in {"PanelWindowChecks", "NativeMetricDrawingChecks", "NativeProcessTableChecks", "NetworkAddressChecks", "SandboxNetworkChecks"},
|
||||
}))
|
||||
if resources:
|
||||
shutil.copytree(resources, contents / "Resources")
|
||||
command = ["codesign", "--force", "--sign", "-"]
|
||||
if host_entitlements:
|
||||
path = work / "network.entitlements"
|
||||
@@ -141,7 +151,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)
|
||||
bundle = test_bundle(work, name, executable, resources=app / "Contents/Resources" if name == "NativeProcessTableChecks" else None)
|
||||
# Open the complete app for native activation semantics, while collecting its output.
|
||||
output = work / (name + ".out")
|
||||
error = work / (name + ".err")
|
||||
@@ -162,7 +172,7 @@ def main():
|
||||
print(text.strip(), flush=True)
|
||||
if "PASS:" not in text:
|
||||
raise RuntimeError(f"{name} did not report success\n" + (error.read_text() if error.exists() else ""))
|
||||
elif name in NETWORK:
|
||||
elif name in NETWORK or name == "NetworkAddressChecks":
|
||||
bundle = test_bundle(work, name, executable, host_entitlements)
|
||||
run([bundle / "Contents/MacOS" / name], timeout=15)
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user