diff --git a/docs/architecture.md b/docs/architecture.md index 5021d05..e78c54e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,12 +57,12 @@ GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取 ### 面板、历史与外观 - Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线。 -- `MiniTrendChart` 只接收历史值与颜色,使用 SwiftUI Canvas 绘制圆角平滑曲线,无独立计时器。 -- `MetricRow` 接收标题、数值、历史与详情内容;鼠标进入 150ms 后通过 `HoverDetailPresenter` 在独立非激活 NSPanel 中呈现详情,主面板不改变尺寸。详情窗口作为主窗口的 child,默认右侧、空间不足向左,并约束在 screen.visibleFrame 内。鼠标可从指标行移入详情,离开两者有 120ms 跨窗口缓冲后收起;主面板隐藏/关闭或视图拆卸时清理子窗口与观察器。按钮保留键盘与 VoiceOver 入口,不提供移出后点击固定。 -- 面板宽 320pt,当前包含 CPU / GPU / 内存、负载与开机小时数;CPU 详情含用户/系统与每核热条,内存详情含分类/Swap/压力。网络、存储、电池及各自趋势和详情已接入。 -- 外侧详情内容首次挂载时执行 0.2 秒 spring 缩放(0.97→1)与透明度(0→1)过渡,采样更新不重播;减少动态效果直接显示,收起立即销毁子窗口以避免残留。 -- 数值与悬浮过渡仅在可见行启用,遵循减少动态效果;面板关闭不挂载独立动画时钟。趋势追加样本时使用 0.35 秒位置插值,满容量保留一个出场点并裁剪;首次显示、非连续更新和减少动态效果直接显示当前历史。仅每次可见更新安排一次可取消任务,无周期动画时钟。 -- 面板沿用 MenuBarExtra 系统窗口背景,不叠加整块自绘玻璃;操作按钮使用系统 `.glass`。本机当前场景视觉已有用户确认,多壁纸等专项仍保留。 +- 当前正式入口为统一 `MenuPanelView`:CPU/GPU/内存、网络/存储/电池六张 ResourceCard + 同面板进程表,宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。工具栏固定,资源卡片独立滚动,进程卡固定高 220–300pt;原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,移动/缩放和布局后约束完整 frame 原点;标准布局七行常驻目标仍待真实窗口复验。 +- `PanelWindowObserver` 属于 Features/MenuBar,以 NSViewRepresentable 观察所属窗口屏幕、key/close/occlusion 通知,通知 Store 可见性和尺寸;App 仍只装配原生 MenuBarExtra,Core 不依赖 AppKit。 +- `PanelTrendChart` 只接收时间戳、双序列、颜色/量纲,Canvas 根据真实时间定位;缺失值和超过 5 秒的间隙断线,不跨暂停连线。CPU/GPU/电量固定 0–100%,内存按物理总字节,网络/IO 两线共用量级;扩大立即、缩小连续十次低于一半后调整。没有独立 Timer 或后台动画循环。新图表追加平移动画尚未实施。 +- 卡片底色和各指标语义色在 Assets 中独立定义深浅模式,操作强调色仍由偏好决定;卡片底色不透明。底部继续保留保持唤醒、暂停/恢复、设置、退出四个操作及胶囊玻璃。数字、曲线和行重排当前直接更新;P5 动效与完整可访问性验收待续。 +- 进程表支持 CPU/RSS 排序、名称/PID/路径搜索、同卡内选中路径展示/复制与读取覆盖计数。投影按采样/筛选/排序事件计算并缓存,不在 body 或滚动中重复排序;hover、搜索/焦点和选中冻结旧身份顺序,新增项追加到其后。完整路径在表下方同卡展示以保持固定行高;选中进程退出短暂提示后移除,关闭面板拆卸表并清掉路径状态。路径不持久化,不收集参数或环境变量。 +- 旧 MetricRow / HoverDetailPresenter / DetailPlacement 与旧迷你趋势源码暂保留作迁移参照,正式面板已无调用;待真实 UI 回归后在 P6 清理并同步其历史检查程序,不能把源码存在理解为仍有双套交互。 - `AppearancePreferences` 仅依赖 Foundation / Observation,持久化外观、系统/六种预设/自选 RGB 强调色。UI 层 `AppearanceStyle` 将偏好映射为明确的深/浅色及窗口级 NSAppearance / Color。跟随系统从全局偏好 AppleInterfaceStyle 独立解析,监听系统主题通知及 NSApp effectiveAppearance 变化后刷新;为 SwiftUI 同时提供非 nil 的 preferredColorScheme 与 colorScheme 环境,避免返回 nil 和失焦后重新继承窗口残留模式。用户持久化值仍为 system,App 全局 appearance 不被修改。该系统偏好键/主题通知属于平台约定,系统动态切换仍需实机验证;外观覆盖作用于面板与设置,不作用于菜单栏标签。 - 设置页外观选择使用 `GlassEffectContainer`:外层为系统液态玻璃胶囊,选中态以共享 `glassEffectID` / `matchedGeometry` 的独立玻璃胶囊在三个选项间移动;遵循减少动态效果,其他表单仍使用系统分组与原生控件。 - `LanguagePreferences` 独立持久化 system / zh-Hans / zh-Hant / en,仅依赖 Foundation / Observation。App 将同一 locale 注入面板与设置,切换即时生效;系统模式按 Locale.preferredLanguages 匹配已支持语言,无法匹配回退 en,不修改 AppleLanguages。外侧详情的独立 NSHostingView 显式转发 locale;UI 的 AppLocalization 为原生窗口标题与色块辅助标签查找对应 lproj,避免其沿用进程启动语言。系统菜单与 NSColorPanel 的系统文案由 macOS 管理。语言自称保留原文。 diff --git a/docs/monitoring.md b/docs/monitoring.md index 11dde8e..ae83c8f 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -13,8 +13,8 @@ | 磁盘寿命 | NVMe 预计剩余寿命、通电时间 | P1 | 只读 XPC 已实现,本机沙盒主应用读取通过,其他设备待验证 | | 电池 | 电量、充放电状态、循环次数、系统报告最大容量 | P2 | C 电源/时间/循环/系统报告最大容量已实现,专项验收中 | | 传感器 | CPU/GPU 温度、风扇转速 | P2(v0.4) | 规划中(SMC,失败降级隐藏) | -| GPU | 利用率、显存 | P0(面板指标) | 本机 IOReport 订阅返回空,暂降级不可用 | -| 进程 | CPU / 内存 Top N 进程 | P3 | 规划中 | +| GPU | 利用率、显存 | P0(面板指标) | 本机已接入 IOAccelerator 总体/核心数;每核独立利用率不可用 | +| 进程 | CPU / RSS / 线程 / 路径 | 统一面板 | sysctl/proc 已实现,本用户可读、其他用户部分受限;交互待验收 | **告警功能(非指标,v0.5)**:温度过高、内存压力阈值告警,经 `UNUserNotificationCenter` 推送; 设置页可开关并配置阈值,权限页提供授权入口,触发与恢复均有冷却去重(详见 [implementation-plan.md](implementation-plan.md))。 @@ -55,6 +55,6 @@ 磁盘寿命通过用户授权的嵌入式非沙盒 XPC 服务低频读取 `diskutil info -plist`,主应用保留沙盒。NVMe 寿命消耗字段换算预计剩余寿命,通电小时读取 128 位计数的可表示部分;高位非零不截断展示。SMART 数据是物理设备级,多个 APFS 卷不重复合算,缺失/多物理存储显示 --。服务固定只读查询,无管理员权限或系统开机项,详见 disk-smart-helper-plan.md。 -## 统一面板增量(规划,尚未实现) +## 统一面板增量(首版已接入,专项验收中) -新一轮指标与口径见 [统一面板方案 §4、§6](unified-panel-plan.md)。网络拟增加本机 IPv4/IPv6、总体/接口选择及双向历史;进程拟增加 CPU 差分、RSS、线程和可执行文件路径;GPU 总体与每核能力分别验证,不能由总体推算每核。接口地址、进程及路径的候选系统接口必须在真实签名沙盒应用内验证,当前不宣称可读;现有网络仍仅统计活动 en 接口,GPU 仍不可用、进程尚未实现。 +指标与口径见 [统一面板方案 §4、§6](unified-panel-plan.md)。已实现本机 IPv4/IPv6、总体/接口选择及双向历史;进程 CPU 差分、RSS、线程与可执行文件路径;GPU 单设备总体占用和核心拓扑。每核独立利用率未获得,不由总体推算。sysctl 枚举在真实签名沙盒主应用中成立,本用户主要字段可读、其他用户部分受限;正式界面显示覆盖范围。网络总体只汇总活动 en 接口,其他接口独立展示避免 VPN 双计。能力与验证限制见 [实施验证记录](unified-panel-validation.md)。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 0e42a3f..809a9de 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -2,9 +2,9 @@ 截至 2026-11-02:C 阶段功能已接入、专项验收中,部分 D 阶段设置已提前实现。勾选表示功能代码已实现,不代表所有机型、场景或长期性能验收完成。工程版本字段 1.0 不代表发布里程碑已完成。 -## 下一轮:统一面板重设计(规划) +## 当前:统一面板重设计(实施中) -实施入口见 [统一面板设计审评、总体方案与计划](unified-panel-plan.md)。P0 能力验证 → P1 布局原型 → P2 数据/调度 → P3 资源卡片 → P4 进程交互 → P5 玻璃/动画/可访问性 → P6 回归收尾。当前均未开始;进程从旧 E 阶段前置到本轮,GPU 每核只在真实能力验证通过后实现,失败明确留项。 +实施入口见 [统一面板设计审评、总体方案与计划](unified-panel-plan.md)。P0 能力验证 → P1 布局原型 → P2 数据/调度 → P3 资源卡片 → P4 进程交互 → P5 玻璃/动画/可访问性 → P6 回归收尾。当前 P0 已验证,P2 数据层及 P1/P3/P4 首版代码已接入,真实窗口/交互、P5 动效与 P6 长时回归仍待完成;进程从旧 E 阶段前置到本轮,GPU 每核只在真实能力验证通过后实现,失败明确留项。 本轮方案取代下列旧阶段中的窄面板与外侧详情目标;下列勾选仍仅记录既有代码,不代表新面板已完成。旧阶段中未纳入本轮的设置、传感器、告警与发布事项继续保留。 @@ -12,7 +12,7 @@ - [x] 统一采样调度、MetricsStore、暂停/恢复、CPU 与内存指标 - [x] 菜单栏仅显示品牌图标,点击展开监控面板(当前确定设计) -- [ ] GPU 有效采样(本机 IOReport 订阅失败,当前不可用) +- [x] GPU 总体采样(IOAccelerator 驱动字段,跨机型/可控负载待验证;每核独立利用率未获得) - [ ] 长期内存与能耗预算验收 本机 CPU/内存、暂停恢复与基础 UI 已有验证记录;详见 [stage-a-validation.md](stage-a-validation.md)。原菜单栏动态数值、组合配置与自动宽度收缩需求已取消。 diff --git a/docs/testing-capabilities.md b/docs/testing-capabilities.md index a66d416..f2e2488 100644 --- a/docs/testing-capabilities.md +++ b/docs/testing-capabilities.md @@ -41,3 +41,7 @@ ## 2026-10-30 语言测试独立窗口 本轮原生工具能操作独立测试应用 cn.airnan.kymo.languagecheck,已验证菜单项选择、外观单选、设置/面板 AX 即时语言更新与单窗口截图;语言 Picker 的 AX 点击未稳定展开,按窗口截图定位箭头点击可用。截图仅包含独立测试窗口,三语深浅色布局已查看。退出后再次 getAXState 会触发测试应用重启,后续退出验证应结合进程查询避免把自动重启误判为退出失败;本轮最终通过 PID 7984 清理测试副本。不能据此推定正式 MenuBarExtra 和外侧详情的同路径全通过。 + +## 2026-11-02 统一面板重试 + +本会话 getState 可枚举应用;getApp 按 /private/tmp 路径、工具解析的 /tmp 路径和应用名读取均 timeoutReached。bundle ID 路径提示存在 Xcode 与临时构建两个副本,未误操作 Xcode 副本。用户授权并重启后再次尝试,用户另手动展开面板后按准确测试路径仍超时。原因未确定,不能认定为未授权;本轮没有取得可操作 App 对象,故未进行 AX/坐标点击、原生截图与键盘关闭。旧轮次成功记录不替代本轮新面板验收。 diff --git a/docs/unified-panel-plan.md b/docs/unified-panel-plan.md index d28a737..e4343fc 100644 --- a/docs/unified-panel-plan.md +++ b/docs/unified-panel-plan.md @@ -221,6 +221,18 @@ xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build - [x] 审阅深浅概念图、当前调用链、模型/采样与现有验证边界。 - [x] 形成总体实现方案、设计修订与 P0–P6 实施/验收计划。 - [x] P0 首轮签名沙盒探针:sysctl 进程路线成立,GPU 总体/拓扑和地址可读,每核独立数据未获得。 -- [ ] P1–P6 实施与完整验收。 +- [x] P2 数据/调度首版及独立行为检查;慢任务不阻塞、进程按可见性发起、双向/分接口历史。 +- [x] P1/P3/P4 首版代码接入正式入口:响应式资源卡片、同面板进程表、搜索/排序/路径与地址复制。 +- [ ] P1 实际窗口尺寸/位置、P3/P4 真实交互退出条件(当前原生 UI 工具超时)。 +- [ ] P5 图表追加/数值/控件过渡、完整键盘/VoiceOver/对比度和主观验收。 +- [ ] P6 长时资源、专项回归与旧外侧详情清理。 能力探针和实测边界见 [实施验证记录](unified-panel-validation.md),不以原始字段可读代替正式 UI 与完整能力验收。每阶段追加实际决策、验证命令/结果、剩余限制;架构文档继续描述当前代码事实,新增规划明确标注。对应监控指标状态与路线图随实现同步更新,旧验收证据不得直接当作新面板已通过。 + +### 首版实施调整(2026-11-02) + +为避免在尚无窗口测量证据时压缩字段,首版全部断点均使用整体纵向滚动,工具栏固定、进程表窄屏横向滚动;尚未实现标准布局七行进程常驻和单独垂直滚动。此为可运行迁移版本,不代表 P1 布局定稿。旧外侧详情源码暂不删除,正式面板已不依赖;待 UI 回归完成后清理。 + +### 用户实测后的布局修正(2026-11-02,取代上述首版滚动策略) + +用户截图确认面板左侧越界,进程滚动带动全页且卡顿。资源卡片改为独立滚动,进程卡固定 220–300pt 高;原生 SwiftUI Table 管理进程纵横滚动和单元格复用,排序筛选按事件计算并缓存。选中路径在同卡表下方展示,保持固定行高。窗口初始尺寸来自实际屏幕,计入 chrome,并在屏幕/窗口变化和布局后校正 frame 原点。资产 alpha 整数字符串被编译为 1/255,已统一改用浮点格式并检查编译资源。修正需真实窗口复验,计算检查不能证明滚动手感。 diff --git a/docs/unified-panel-validation.md b/docs/unified-panel-validation.md index 1cb1100..5c12dac 100644 --- a/docs/unified-panel-validation.md +++ b/docs/unified-panel-validation.md @@ -27,3 +27,23 @@ P0 不包含 UI、可控 GPU 负载关联、进程 CPU 差分或最坏延迟测 UnifiedPanelChecks 通过:单核 >100% 差分、首帧/计数回退/零时间、真实进程首帧与后续 CPU、GPU 无穷/NaN/越界、VPN 不计总体、接口历史 60 点上限/消失清理、可见/隐藏/重开基线。此检查是独立程序,不替代真实窗口可见性事件和交互验证。完整 GPU 负载关联、低频查询最坏耗时、长期资源与跨机型仍待验证。 回归发现旧 SamplingChecks 把空接口列表期望为 0;已按新方案改为未知(无符合口径的活动接口不代表测得零速率),其他首帧、真实零和计数差分语义保持。无启动标识的进程每帧使用临时身份且不延续 CPU 差分,防止 PID 复用继承选中项。 + +## P1/P3/P4:统一面板首版(代码接入,验收未完成) + +正式入口已由窄列表替换为六资源卡片与进程表,不再调用外侧详情。屏幕尺寸通过 Feature 内窗口桥接读取;三/两/单列断点 1160/900pt,固定工具栏、内容整体纵向滚动、窄屏进程横向滚动。网络卡提供选择器、双线图、本机地址展开/复制、累计口径;存储保留主卷、设备 IO、SMART 和卷列表且不合算 APFS;电池无内置/读取失败状态分离。三语、深浅色语义资产、真实时间轴均已接入。 + +进程表提供 CPU/RSS 排序、搜索、覆盖范围、交互冻结行序、行内路径及复制、退出提示;未知值显示 --,CPU 口径不裁到 100%。旧外侧详情源文件暂保留,但无正式入口引用。图表/数字/行序当前直接更新,P5 动画尚未交付。 + +Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条件通过。重启授权后 getState 能枚举应用,getApp 对准确路径仍超时,用户展开面板后重试也超时。未执行窗口截图(未采集无关屏幕)、AX 点击、坐标点击、Esc、设置/复制/滚动回归。未以超时推断权限原因,也未绕过原生工具使用事件注入。 + +剩余关键项:窗口实际宽高/定位、三语长路径/IPv6 布局、进程/网卡交互、VoiceOver、深浅色和减少动态/透明专项;标准布局七行进程常驻、P5 动效和 P6 清理/长期性能。真实多屏/刘海屏与主观玻璃体验由用户最终验收,当前不宣布整体验收通过。 + +## 用户截图反馈后的修正 + +用户提供实际截图,确认首版左侧越界、进程滚动带动全页,并报告卡顿。实现中统一外层 ScrollView 和 body 内重复排序已确认;不能把卡顿仅归因于进程数量。当前改为资源滚动区 + 固定高进程卡,原生 SwiftUI Table 管理独立滚动与复用,投影仅在数据/筛选/排序事件发生时计算。路径在同卡表下方展示,不再使用无限高度的可展开 SwiftUI 行;保留全部进程数据。 + +实测屏幕 1512×982pt,visibleFrame=(0,67,1512,882),缩放 2。窗口加入首次尺寸预算和布局/屏幕变化后的原点约束。PanelLayoutChecks 通过:本机、小屏、负坐标屏幕、chrome 预算与越界 frame 约束;2000 行 CPU/RSS 排序、冻结、路径搜索和空结果。计算检查不证明实际定位和滚动手感。 + +实际编译资源中 alpha 字符串 "1" 被解析为 0.00392157,GPU 蓝通道也有同样问题。统一使用浮点小数字符串后,PanelAssetChecks 从实际 .app 验证七个深浅色资源存在、alpha=1、GPU 深色蓝通道正确。这解释截图中的透明卡片。 + +实际签名主应用短时采样(本轮 PID 10589 已退出):4 次快速采样 4.08–13.55ms;首帧 SMART/健康/卷未知,下一帧读到 98%/100%/2 卷,GPU 0–18%、20 核;关闭面板进程快照为空。完整沙盒检查 .app 通过进程/可见性/历史检查,实际三语资源检查通过。用户已有 Xcode 副本 PID 10409 保留。短时数据不证明最坏延迟、长期预算或打开面板的资源占用。 diff --git a/kymo/Assets.xcassets/MetricBattery.colorset/Contents.json b/kymo/Assets.xcassets/MetricBattery.colorset/Contents.json new file mode 100644 index 0000000..f7ece1a --- /dev/null +++ b/kymo/Assets.xcassets/MetricBattery.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.180", + "green": "0.430", + "blue": "0.180", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "0.500", + "green": "0.850", + "blue": "0.430", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/MetricCPU.colorset/Contents.json b/kymo/Assets.xcassets/MetricCPU.colorset/Contents.json new file mode 100644 index 0000000..e5b8992 --- /dev/null +++ b/kymo/Assets.xcassets/MetricCPU.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.000", + "green": "0.370", + "blue": "0.400", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "0.250", + "green": "0.850", + "blue": "0.780", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/MetricDisk.colorset/Contents.json b/kymo/Assets.xcassets/MetricDisk.colorset/Contents.json new file mode 100644 index 0000000..16c989d --- /dev/null +++ b/kymo/Assets.xcassets/MetricDisk.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.600", + "green": "0.300", + "blue": "0.020", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "1.000", + "green": "0.670", + "blue": "0.280", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/MetricGPU.colorset/Contents.json b/kymo/Assets.xcassets/MetricGPU.colorset/Contents.json new file mode 100644 index 0000000..1cb7d10 --- /dev/null +++ b/kymo/Assets.xcassets/MetricGPU.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.480", + "green": "0.220", + "blue": "0.700", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "0.760", + "green": "0.550", + "blue": "1.000", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/MetricMemory.colorset/Contents.json b/kymo/Assets.xcassets/MetricMemory.colorset/Contents.json new file mode 100644 index 0000000..e8a6dad --- /dev/null +++ b/kymo/Assets.xcassets/MetricMemory.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.250", + "green": "0.320", + "blue": "0.750", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "0.550", + "green": "0.640", + "blue": "1.000", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/MetricNetwork.colorset/Contents.json b/kymo/Assets.xcassets/MetricNetwork.colorset/Contents.json new file mode 100644 index 0000000..85ea756 --- /dev/null +++ b/kymo/Assets.xcassets/MetricNetwork.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.000", + "green": "0.380", + "blue": "0.650", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "0.350", + "green": "0.720", + "blue": "1.000", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/PanelCard.colorset/Contents.json b/kymo/Assets.xcassets/PanelCard.colorset/Contents.json new file mode 100644 index 0000000..87f4a9a --- /dev/null +++ b/kymo/Assets.xcassets/PanelCard.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.960", + "green": "0.970", + "blue": "0.990", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "color": { + "color-space": "srgb", + "components": { + "red": "0.100", + "green": "0.120", + "blue": "0.160", + "alpha": "1.000" + } + } + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index eef6186..978bb29 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -7,188 +7,216 @@ struct MenuPanelView: View { let keepAwake: KeepAwakeService let settingsPresentation: SettingsPresentation @Environment(\.openSettings) private var openSettings + @State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760)) + @State private var selectedInterface = "" + @State private var showAddresses = false + @State private var showVolumes = false + + private var snapshot: MetricsSnapshot { metrics.snapshot } + private var samples: [TrendSample] { metrics.history.samples } + private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 } + private var network: [NetworkInterfaceMetrics] { + (snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface } + } + private func total(_ key: KeyPath) -> Double? { + let rates = network.compactMap { $0[keyPath: key] } + return !network.isEmpty && rates.count == network.count ? rates.reduce(0, +) : nil + } var body: some View { - VStack(spacing: 4) { - VStack(spacing: 2) { - MetricRow(title: "metric.cpu", symbol: "cpu", value: MetricFormat.percent(metrics.snapshot.cpu?.usage), - usage: metrics.snapshot.cpu?.usage, history: metrics.history.samples.map(\.cpu), accent: preferences.tintColor) { - cpuDetail - } - MetricRow(title: "metric.gpu", symbol: "square.grid.2x2", value: MetricFormat.percent(metrics.snapshot.gpuUsage), - usage: metrics.snapshot.gpuUsage, history: metrics.history.samples.map(\.gpu), accent: preferences.tintColor) { - Text("gpu.unavailable").foregroundStyle(.secondary) - } - MetricRow(title: "metric.memory", symbol: "memorychip", value: MetricFormat.percent(metrics.snapshot.memory?.usage), - usage: metrics.snapshot.memory?.usage, history: metrics.history.samples.map(\.memory), accent: preferences.tintColor) { - memoryDetail - } + VStack(spacing: 10) { + header + ScrollView { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12, alignment: .top), count: columns), alignment: .leading, spacing: 12) { + cpuCard + gpuCard + memoryCard + networkCard + diskCard + batteryCard + }.padding(.trailing, 2) } - VStack(spacing: 2) { - MetricRow(title: "metric.network", symbol: "network", value: networkValue, - usage: metrics.snapshot.downloadRate.map { _ in 0 }, history: networkHistory, accent: preferences.tintColor) { - ScrollView { - VStack(spacing: 6) { - switch metrics.snapshot.networkPath { - case .available: Text("network.pathAvailable") - case .unavailable: Text("network.pathUnavailable") - case .requiresConnection: Text("network.pathRequiresConnection") - case nil: Text("metric.waiting") - } - if let interfaces = metrics.snapshot.network { - if interfaces.isEmpty { Text("network.noLink") } - ForEach(interfaces, id: \.name) { item in - VStack(spacing: 4) { - Text(verbatim: item.name).fontWeight(.semibold) - detailLine("network.download", rate(item.download)) - detailLine("network.upload", rate(item.upload)) - detailLine("network.received", MetricFormat.bytes(item.received)) - detailLine("network.sent", MetricFormat.bytes(item.sent)) - } - } - } else { Text("metric.waiting") } - } - }.frame(maxHeight: 280) - } - MetricRow(title: "metric.disk", symbol: "internaldrive", value: MetricFormat.percent(metrics.snapshot.disk?.usage), - usage: metrics.snapshot.disk?.usage, history: metrics.history.samples.map(\.disk), accent: preferences.tintColor) { - ScrollView { - VStack(spacing: 6) { - Text("disk.homeVolume").foregroundStyle(.secondary) - detailLine("disk.total", MetricFormat.bytes(metrics.snapshot.disk?.total)) - detailLine("memory.available", MetricFormat.bytes(metrics.snapshot.disk?.available)) - detailLine("disk.remainingLife", MetricFormat.percent(metrics.snapshot.diskHealth?.remainingLife)) - HStack { - Text("disk.powerOnHours").foregroundStyle(.secondary) - Spacer() - if let hours = metrics.snapshot.diskHealth?.powerOnHours { - Text("disk.hours \(hours)").monospacedDigit() - } else { Text(verbatim: "--") } - } - Divider() - Text("disk.physicalIO").foregroundStyle(.secondary) - detailLine("disk.read", rate(metrics.snapshot.diskIO?.read)) - detailLine("disk.write", rate(metrics.snapshot.diskIO?.written)) - Divider() - Text("disk.volumes").foregroundStyle(.secondary) - if let volumes = metrics.snapshot.volumes { - ForEach(volumes, id: \.path) { volume in - VStack(spacing: 4) { - Text(verbatim: volume.name).fontWeight(.semibold) - detailLine("disk.total", MetricFormat.bytes(volume.capacity.total)) - detailLine("memory.available", MetricFormat.bytes(volume.capacity.available)) - } - } - } else { Text("metric.waiting") } - } - }.frame(maxHeight: 280) - } - if let battery = metrics.snapshot.battery { - MetricRow(title: "metric.battery", symbol: battery.charging ? "battery.100percent.bolt" : "battery.100percent", - value: MetricFormat.percent(battery.charge), usage: battery.charge.map { _ in 0 }, history: metrics.history.samples.map(\.battery), accent: preferences.tintColor) { - VStack(spacing: 6) { - Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging") - if battery.externalPower && !battery.charging { - HStack { - Text("battery.timeEstimate").foregroundStyle(.secondary) - Spacer() - Text("battery.timeNotApplicable") - } - } else if let minutes = battery.minutesRemaining { - detailLine(battery.charging ? "battery.timeFull" : "battery.timeEmpty", "\(minutes) min") - } else { - HStack { - Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary) - Spacer() - Text("battery.timeUnknown") - } - } - detailLine("battery.cycles", battery.cycles.map(String.init) ?? "--") - detailLine("battery.health", MetricFormat.percent(battery.health)) - } - } - } + .frame(maxWidth: .infinity, maxHeight: .infinity) + if metrics.isPanelVisible { + ProcessTableView(snapshot: snapshot.processes) + .frame(height: min(300, max(220, panelSize.height * 0.36))) } - Divider().padding(.horizontal, 10) - HStack { - Text("system.load") - Text(verbatim: metrics.snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")) - Spacer(minLength: 4) - Image(systemName: "clock") - Text(verbatim: String(format: "%.0fh", floor(metrics.snapshot.uptime / 3600))) - } - .font(.system(size: 10)).monospacedDigit().foregroundStyle(.secondary) - .padding(.horizontal, 10).padding(.vertical, 8) footer } - .padding(10) - .frame(width: 320) + .padding(12) + .frame(width: panelSize.width, height: panelSize.height) + .background(PanelWindowObserver { size, visible in + if panelSize != size { panelSize = size } + if metrics.isPanelVisible != visible { metrics.setPanelVisible(visible) } + }.frame(width: 0, height: 0)) + .onAppear { metrics.setPanelVisible(true) } + .onDisappear { metrics.setPanelVisible(false) } + .onChange(of: snapshot.network?.map(\.identity)) { _, keys in + if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" } + } .modifier(AppearanceStyle(preferences: preferences)) } - // Shared scale for the whole visible history; never label throughput as utilization. - private var networkHistory: [Double?] { - let values = metrics.history.samples.map(\.download) - let scale = max(1_000, values.compactMap { $0 }.max() ?? 1_000) - return values.map { $0.map { $0 / scale } } + private var header: some View { + HStack(spacing: 10) { + Image("BrandMark").renderingMode(.template) + Text("Kymo").font(.system(size: 18, weight: .semibold)) + if panelSize.width >= 900 { + Text(verbatim: "\(ProcessInfo.processInfo.processorCount) CPU · \(MetricFormat.bytes(snapshot.memory?.total))") + .font(.system(size: 11)).foregroundStyle(.secondary) + } + Spacer() + VStack(alignment: .trailing, spacing: 2) { + Label(metrics.isPaused ? "panel.paused" : "panel.sampling", systemImage: metrics.isPaused ? "pause.circle" : "circle.fill") + .foregroundStyle(metrics.isPaused ? Color.secondary : Color("MetricBattery")) + Text(snapshot.date, style: .time).foregroundStyle(.secondary) + }.font(.system(size: 10)) + }.padding(.horizontal, 4) } - private var networkValue: String { - guard let total = metrics.snapshot.downloadRate else { return "--" } - return total >= 1_000_000 ? String(format: "%.1fM↓", total / 1_000_000) : String(format: "%.0fK↓", total / 1000) + private func chart(_ key: KeyPath, color: Color) -> some View { + PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color) + } + private func line(_ key: LocalizedStringKey, _ value: String) -> some View { + HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); Text(verbatim: value).monospacedDigit() } } - private func rate(_ bytes: Double?) -> String { - MetricFormat.rate(bytes) + private var cpuCard: some View { + ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) { + chart(\.cpu, color: Color("MetricCPU")) + if let cpu = snapshot.cpu { + HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 28), spacing: 4)], spacing: 4) { + ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, value in + Text(verbatim: "\(index + 1)").font(.system(size: 9)).frame(maxWidth: .infinity).frame(height: 18) + .background(Color("MetricCPU").opacity(0.12 + value * 0.65), in: .rect(cornerRadius: 3)) + .help("\(index + 1): \(MetricFormat.percent(value))") + .accessibilityLabel(Text("cpu.core")).accessibilityValue("\(index + 1): \(MetricFormat.percent(value))") + } + } + } else { Text("metric.waiting").foregroundStyle(.secondary) } + line("system.load", snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")) + line("panel.uptime", String(format: "%.1f h", snapshot.uptime / 3600)) + } } - - @ViewBuilder private var cpuDetail: some View { - if let cpu = metrics.snapshot.cpu { - VStack(alignment: .leading, spacing: 8) { - detailLine("cpu.user", MetricFormat.percent(cpu.user)) - detailLine("cpu.system", MetricFormat.percent(cpu.system)) - LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 4) { - ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, usage in - RoundedRectangle(cornerRadius: 4) - .fill(preferences.tintColor.opacity(0.12 + 0.88 * usage)) - .frame(height: 18) - .overlay(Text(verbatim: "\(index + 1)").font(.system(size: 9)).foregroundStyle(.primary)) - .help(MetricFormat.percent(usage)) - .accessibilityLabel(Text("cpu.core")) - .accessibilityValue(Text(verbatim: "\(index + 1): \(MetricFormat.percent(usage))")) + private var gpuCard: some View { + ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage)) { + chart(\.gpu, color: Color("MetricGPU")) + if snapshot.gpuUsage == nil { Text("gpu.unavailable").foregroundStyle(.secondary) } + line("panel.gpuCores", snapshot.gpu?.coreCount.map(String.init) ?? "--") + Label("panel.gpuPerCore", systemImage: "info.circle").foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Text("panel.gpuSource").font(.system(size: 10)).foregroundStyle(.secondary) + } + } + private var memoryCard: some View { + ResourceCard(title: "metric.memory", symbol: "memorychip", color: Color("MetricMemory"), value: MetricFormat.percent(snapshot.memory?.usage)) { + PanelTrendChart(dates: samples.map(\.date), + first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } }, + color: Color("MetricMemory"), fixedScale: Double(snapshot.memory?.total ?? 1), + scaleLabel: MetricFormat.bytes(snapshot.memory?.total)) + if let m = snapshot.memory { + line("memory.used", "\(MetricFormat.bytes(m.used)) / \(MetricFormat.bytes(m.total))") + GeometryReader { geometry in + HStack(spacing: 0) { + ForEach(Array([m.used - min(m.used, m.wired + m.compressed), m.wired, m.compressed, m.total - min(m.total, m.used)].enumerated()), id: \.offset) { i, bytes in + Rectangle().fill(Color("MetricMemory").opacity([1, 0.75, 0.5, 0.15][i])) + .frame(width: Double(bytes) / Double(max(1, m.total)) * geometry.size.width) + } + } + }.frame(height: 6).clipped().accessibilityHidden(true) + line("memory.app", MetricFormat.bytes(m.used - min(m.used, m.wired + m.compressed))) + HStack { line("memory.wired", MetricFormat.bytes(m.wired)); line("memory.compressed", MetricFormat.bytes(m.compressed)) } + HStack { line("memory.available", MetricFormat.bytes(m.total - min(m.total, m.used))); line("memory.swap", MetricFormat.bytes(m.swapUsed)) } + HStack { Text("memory.pressure").foregroundStyle(.secondary); Spacer(); pressure(m.pressure) } + } else { Text("metric.waiting") } + } + } + @ViewBuilder private func pressure(_ value: Int?) -> some View { + switch value { + case 1: Text("pressure.normal") + case 2: Text("pressure.warning").foregroundStyle(.orange) + case 4: Text("pressure.critical").foregroundStyle(.red) + default: Text(verbatim: "--") + } + } + private var networkCard: some View { + ResourceCard(title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: MetricFormat.rate(total(\.download))) { + Picker("panel.interface", selection: $selectedInterface) { + Text("panel.totalNetwork").tag("") + ForEach(snapshot.network ?? [], id: \.identity) { item in Text(verbatim: item.name).tag(item.identity) } + }.labelsHidden().controlSize(.small) + PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), fixedScale: nil).id(selectedInterface) + if !network.isEmpty && total(\.download) == nil { Text("panel.rateBaseline").foregroundStyle(.secondary) } + HStack { line("network.download", MetricFormat.rate(total(\.download))); line("network.upload", MetricFormat.rate(total(\.upload))) } + HStack { line("network.received", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received })); line("network.sent", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent })) } + switch snapshot.networkPath { + case .available: Text("network.pathAvailable").foregroundStyle(.secondary) + case .unavailable: Text("network.pathUnavailable").foregroundStyle(.secondary) + case .requiresConnection: Text("network.pathRequiresConnection").foregroundStyle(.secondary) + case nil: Text("metric.waiting") + } + DisclosureGroup("panel.addresses", isExpanded: $showAddresses) { + ForEach(network, id: \.identity) { item in + VStack(alignment: .leading, spacing: 3) { + Text(verbatim: item.name).fontWeight(.medium) + if item.addresses.isEmpty { Text("panel.addressUnknown") } + ForEach(item.addresses, id: \.self) { address in + HStack(alignment: .top) { + Text(verbatim: address).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + Button { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(address, forType: .string) } label: { Image(systemName: "doc.on.doc") }.accessibilityLabel(Text("panel.copy")) + } + } } } } - } else { Text("metric.waiting").foregroundStyle(.secondary) } + Text(selectedInterface.isEmpty ? "panel.totalScope" : "panel.interfaceScope").font(.system(size: 9)).foregroundStyle(.secondary) + } } - - @ViewBuilder private var memoryDetail: some View { - if let memory = metrics.snapshot.memory { - VStack(spacing: 6) { - detailLine("memory.used", MetricFormat.bytes(memory.used)) - detailLine("memory.available", MetricFormat.bytes(memory.total - memory.used)) - detailLine("memory.app", MetricFormat.bytes(memory.used - min(memory.used, memory.wired + memory.compressed))) - detailLine("memory.wired", MetricFormat.bytes(memory.wired)) - detailLine("memory.compressed", MetricFormat.bytes(memory.compressed)) - detailLine("memory.swap", MetricFormat.bytes(memory.swapUsed)) + private var networkDates: [Date] { selectedInterface.isEmpty ? samples.map(\.date) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.date) } + private var networkDownloads: [Double?] { selectedInterface.isEmpty ? samples.map(\.download) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.download) } + private var networkUploads: [Double?] { selectedInterface.isEmpty ? samples.map(\.upload) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.upload) } + private var diskCard: some View { + ResourceCard(title: "metric.disk", symbol: "internaldrive", color: Color("MetricDisk"), value: MetricFormat.percent(snapshot.disk?.usage)) { + Text("disk.homeVolume").foregroundStyle(.secondary) + line("memory.used", snapshot.disk.map { "\(MetricFormat.bytes($0.total - min($0.total, $0.available))) / \(MetricFormat.bytes($0.total))" } ?? "--") + PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil) + Text("disk.physicalIO").foregroundStyle(.secondary) + HStack { line("disk.read", MetricFormat.rate(snapshot.diskIO?.read)); line("disk.write", MetricFormat.rate(snapshot.diskIO?.written)) } + HStack { line("disk.remainingLife", MetricFormat.percent(snapshot.diskHealth?.remainingLife)); line("disk.powerOnHours", snapshot.diskHealth?.powerOnHours.map { "\($0) h" } ?? "--") } + Text("panel.smartScope").font(.system(size: 9)).foregroundStyle(.secondary) + if let date = snapshot.diskHealthDate { Text(date, style: .time).font(.system(size: 9)).foregroundStyle(.secondary) } + DisclosureGroup("disk.volumes", isExpanded: $showVolumes) { + ForEach(snapshot.volumes ?? [], id: \.path) { volume in + VStack(alignment: .leading) { + Text(verbatim: volume.name).lineLimit(1).truncationMode(.middle) + line("memory.available", "\(MetricFormat.bytes(volume.capacity.available)) / \(MetricFormat.bytes(volume.capacity.total))") + } + } + Text("panel.apfsScope").font(.system(size: 9)).foregroundStyle(.secondary) + } + } + } + private var batteryCard: some View { + ResourceCard(title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), value: MetricFormat.percent(snapshot.battery?.charge)) { + if let battery = snapshot.battery { + chart(\.battery, color: Color("MetricBattery")) + Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging") + line("battery.cycles", battery.cycles.map(String.init) ?? "--") + line("battery.health", MetricFormat.percent(battery.health)) HStack { - Text("memory.pressure").foregroundStyle(.secondary) + Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary) Spacer() - switch memory.pressure { - case 1: Text("pressure.normal") - case 2: Text("pressure.warning").foregroundStyle(.orange) - case 4: Text("pressure.critical").foregroundStyle(.red) - default: Text(verbatim: "--") - } + if battery.externalPower && !battery.charging { Text("battery.timeNotApplicable") } + else if let minutes = battery.minutesRemaining { Text(verbatim: "\(minutes) min") } + else { Text("battery.timeUnknown") } } + if let date = snapshot.batteryHealthDate { Text(date, style: .time).font(.system(size: 9)).foregroundStyle(.secondary) } + } else { + Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary) } - } else { Text("metric.waiting").foregroundStyle(.secondary) } + } } - - private func detailLine(_ key: LocalizedStringKey, _ value: String) -> some View { - HStack { Text(key).foregroundStyle(.secondary); Spacer(); Text(verbatim: value).monospacedDigit() } - } - private var footer: some View { HStack(spacing: 8) { VStack(alignment: .leading, spacing: 2) { diff --git a/kymo/Features/MenuBar/PanelLayout.swift b/kymo/Features/MenuBar/PanelLayout.swift new file mode 100644 index 0000000..ed55765 --- /dev/null +++ b/kymo/Features/MenuBar/PanelLayout.swift @@ -0,0 +1,15 @@ +import Foundation +import CoreGraphics + +nonisolated enum PanelLayout { + static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize { + CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))), + height: max(1, min(820, visible.height - 32 - max(0, chrome.height)))) + } + static func constrainedFrame(_ frame: CGRect, visible: CGRect) -> CGRect { + let safe = visible.insetBy(dx: 16, dy: 16) + let width = min(frame.width, safe.width), height = min(frame.height, safe.height) + return CGRect(x: min(max(frame.minX, safe.minX), safe.maxX - width), + y: min(max(frame.minY, safe.minY), safe.maxY - height), width: width, height: height) + } +} diff --git a/kymo/Features/MenuBar/PanelWindowObserver.swift b/kymo/Features/MenuBar/PanelWindowObserver.swift new file mode 100644 index 0000000..48b3180 --- /dev/null +++ b/kymo/Features/MenuBar/PanelWindowObserver.swift @@ -0,0 +1,55 @@ +import SwiftUI +import AppKit + +/// Window geometry/lifecycle stays in the feature layer; Core receives only visibility. +struct PanelWindowObserver: NSViewRepresentable { + var update: (CGSize, Bool) -> Void + func makeNSView(context: Context) -> ObserverView { ObserverView(update: update) } + func updateNSView(_ view: ObserverView, context: Context) { view.update = update } + + final class ObserverView: NSView { + var update: (CGSize, Bool) -> Void + private var observers: [NSObjectProtocol] = [] + init(update: @escaping (CGSize, Bool) -> Void) { self.update = update; super.init(frame: .zero) } + required init?(coder: NSCoder) { fatalError() } + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + observers.forEach(NotificationCenter.default.removeObserver) + observers = [] + guard let window else { return } + for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification, NSWindow.didBecomeKeyNotification, + NSWindow.didResignKeyNotification, NSWindow.willCloseNotification, + NSWindow.didChangeOcclusionStateNotification] { + observers.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.report() } + }) + } + observers.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.report() } + }) + report() + } + private func report() { + guard let window else { return } + let frame = (window.screen ?? NSScreen.main)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1000, height: 760) + let chrome = CGSize(width: max(0, window.frame.width - window.contentLayoutRect.width), + height: max(0, window.frame.height - window.contentLayoutRect.height)) + let size = PanelLayout.contentSize(visible: frame, chrome: chrome) + let visible = window.isVisible && window.occlusionState.contains(.visible) + DispatchQueue.main.async { [weak self, weak window] in + guard let self, let window else { return } + self.update(size, visible) + // SwiftUI can resize a MenuBarExtra after the system chose its anchor origin. + // Clamp after layout as well as on moves; keep the native status-item scene. + DispatchQueue.main.async { [weak window] in + guard let window, window.isVisible else { return } + let adjusted = PanelLayout.constrainedFrame(window.frame, visible: frame) + if abs(adjusted.minX - window.frame.minX) > 0.5 || abs(adjusted.minY - window.frame.minY) > 0.5 { + window.setFrameOrigin(adjusted.origin) + } + } + } + } + deinit { observers.forEach(NotificationCenter.default.removeObserver) } + } +} diff --git a/kymo/Features/MenuBar/ProcessTableProjection.swift b/kymo/Features/MenuBar/ProcessTableProjection.swift new file mode 100644 index 0000000..d564a2e --- /dev/null +++ b/kymo/Features/MenuBar/ProcessTableProjection.swift @@ -0,0 +1,18 @@ +import Foundation + +/// Compute once per data/filter/sort event, never from row rendering or scroll position. +nonisolated enum ProcessTableProjection { + static func rows(_ input: [ProcessMetrics], query: String, byMemory: Bool, order: [ProcessIdentity]) -> [ProcessMetrics] { + let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) }) + return input.filter { + query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || String($0.id.pid).contains(query) || ($0.path?.localizedCaseInsensitiveContains(query) ?? false) + }.sorted { + let aRank = ranks[$0.id] ?? Int.max, bRank = ranks[$1.id] ?? Int.max + if aRank != bRank { return aRank < bRank } + let a = byMemory ? $0.residentBytes.map(Double.init) ?? -1 : $0.cpu ?? -1 + let b = byMemory ? $1.residentBytes.map(Double.init) ?? -1 : $1.cpu ?? -1 + if a != b { return a > b } + return $0.name == $1.name ? $0.id.pid < $1.id.pid : $0.name < $1.name + } + } +} diff --git a/kymo/Features/MenuBar/ProcessTableView.swift b/kymo/Features/MenuBar/ProcessTableView.swift new file mode 100644 index 0000000..34a0a04 --- /dev/null +++ b/kymo/Features/MenuBar/ProcessTableView.swift @@ -0,0 +1,91 @@ +import SwiftUI +import AppKit + +struct ProcessTableView: View { + let snapshot: ProcessSnapshot? + @State private var search = "" + @State private var byMemory = false + @State private var hovering = false + @State private var selected: ProcessIdentity? + @State private var rows: [ProcessMetrics] = [] + @State private var departed: ProcessMetrics? + @FocusState private var searchFocused: Bool + + private var held: Bool { hovering || selected != nil || searchFocused || !search.isEmpty } + private var selectedRow: ProcessMetrics? { rows.first { $0.id == selected } } + private var exitedSelection: ProcessIdentity? { + guard let selected, snapshot != nil, !rows.contains(where: { $0.id == selected }) else { return nil } + return selected + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack { + Label("panel.processes", systemImage: "list.bullet.rectangle").fontWeight(.semibold) + Text(verbatim: "\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)") + .foregroundStyle(.secondary).help(Text("panel.coverage")) + Spacer(minLength: 0) + if held { Button("panel.liveSort") { selected = nil; rebuild(retainOrder: false) } } + Picker("panel.sort", selection: $byMemory) { + Text("CPU %").tag(false) + Text("panel.rss").tag(true) + }.labelsHidden().frame(width: 100) + } + HStack { + Text("panel.processScope").font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(2) + Spacer(minLength: 4) + TextField("panel.search", text: $search).textFieldStyle(.roundedBorder) + .frame(width: 210).focused($searchFocused) + } + 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) { + TableColumn("PID") { row in Text(verbatim: "\(row.id.pid)") }.width(48) + TableColumn("panel.name") { row in Text(verbatim: row.name).lineLimit(1) }.width(min: 90, ideal: 140, max: 180) + TableColumn("panel.path") { row in Text(verbatim: row.path ?? "--").lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) }.width(min: 150, ideal: 400) + TableColumn("CPU %") { row in Text(verbatim: row.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--") }.width(62) + TableColumn("panel.rss") { row in Text(verbatim: row.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--") }.width(85) + TableColumn("panel.threads") { row in + HStack { Text(verbatim: row.threads.map(String.init) ?? "--"); if row.restricted { Image(systemName: "lock").accessibilityLabel(Text("panel.restricted")) } } + }.width(65) + } + .font(.system(size: 11)).monospacedDigit() + .tableStyle(.inset(alternatesRowBackgrounds: true)) + .transaction { $0.animation = nil } + .overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } } + if let row = selectedRow { + HStack(alignment: .top) { + Text(verbatim: row.path ?? "--").textSelection(.enabled).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading) + if let path = row.path { Button("panel.copy") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(path, forType: .string) } } + }.font(.system(size: 11)) + } else if exitedSelection != nil, let departed { + HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { selected = nil; self.departed = nil } } + } + } + .font(.system(size: 12)).padding(10) + .background(Color("PanelCard"), in: .rect(cornerRadius: 14)) + .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.primary.opacity(0.1))) + .onAppear { rebuild(retainOrder: false) } + .onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held) } + .onChange(of: search) { _, _ in rebuild(retainOrder: held) } + .onChange(of: byMemory) { _, _ in rebuild(retainOrder: false) } + .onChange(of: selected) { _, _ in if let row = selectedRow { departed = row } } + .onHover { hovering = $0; if !$0 && !held { rebuild(retainOrder: false) } } + .onChange(of: searchFocused) { _, value in if !value && !held { rebuild(retainOrder: false) } } + .task(id: exitedSelection) { + guard let id = exitedSelection else { return } + do { try await Task.sleep(for: .seconds(3)) } catch { return } + if selected == id { selected = nil; departed = nil } + } + .onExitCommand { + if !search.isEmpty { search = "" } + else if selected != nil { selected = nil; departed = nil } + else if searchFocused { searchFocused = false } + else { NSApp.keyWindow?.close() } + } + } + private func rebuild(retainOrder: Bool) { + rows = ProcessTableProjection.rows(snapshot?.rows ?? [], query: search, byMemory: byMemory, order: retainOrder ? rows.map(\.id) : []) + } +} diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings index 117162c..832d797 100644 --- a/kymo/Resources/Localizable.xcstrings +++ b/kymo/Resources/Localizable.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage" : "en", "strings" : { + "%lld: %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$lld: %2$@" + } + } + } + }, "about.description" : { "localizations" : { "en" : { @@ -679,6 +689,7 @@ } }, "battery.timeEstimate" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -765,6 +776,9 @@ } } } + }, + "CPU %" : { + }, "cpu.core" : { "extractionState" : "manual", @@ -904,6 +918,7 @@ } }, "disk.hours %llu" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -1014,6 +1029,7 @@ } }, "disk.total" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -1515,6 +1531,7 @@ } }, "network.noLink" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -1667,6 +1684,791 @@ } } } + }, + "panel.addresses" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Local IP addresses" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "本机 IP 地址" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "本機 IP 位址" + } + } + } + }, + "panel.addressUnknown" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Address unavailable" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "地址不可用" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "位址無法取得" + } + } + } + }, + "panel.apfsScope" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "APFS volumes may share capacity; do not add totals." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "APFS 卷可能共享容量,不合算总量。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "APFS 卷可能共用容量,不加總。" + } + } + } + }, + "panel.batteryFailed" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Battery status unavailable" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电池状态读取失败" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電池狀態讀取失敗" + } + } + } + }, + "panel.copy" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Copy" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "复制" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "複製" + } + } + } + }, + "panel.coverage" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Readable / enumerated · matching rows" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "可读取 / 枚举总数 · 筛选结果" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "可讀取 / 列舉總數 · 篩選結果" + } + } + } + }, + "panel.dismiss" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dismiss" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "关闭" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "關閉" + } + } + } + }, + "panel.exited" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Process exited" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "进程已退出" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "程序已結束" + } + } + } + }, + "panel.gpuCores" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU cores" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 核心数" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 核心數" + } + } + } + }, + "panel.gpuPerCore" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Independent per-core utilization is unavailable" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未获得独立的 GPU 每核占用数据" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "未取得獨立的 GPU 每核使用率資料" + } + } + } + }, + "panel.gpuSource" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Device utilization reported by the GPU driver" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 驱动报告的设备总体占用" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 驅動程式回報的裝置整體使用率" + } + } + } + }, + "panel.interface" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Network interface" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "网络接口" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "網路介面" + } + } + } + }, + "panel.interfaceScope" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Selected interface only; system cumulative counters." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "仅显示所选接口;累计值为系统接口计数。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "僅顯示所選介面;累計值為系統介面計數。" + } + } + } + }, + "panel.liveSort" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Resume live sorting" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "恢复实时排序" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "恢復即時排序" + } + } + } + }, + "panel.name" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Name" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "名称" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "名稱" + } + } + } + }, + "panel.noBattery" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "No internal battery" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无内置电池" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無內建電池" + } + } + } + }, + "panel.noResults" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "No matching processes" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "没有匹配的进程" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "沒有符合的程序" + } + } + } + }, + "panel.path" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Executable path" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "可执行文件路径" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "執行檔路徑" + } + } + } + }, + "panel.paused" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paused · last update" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已暂停 · 最后更新" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已暫停 · 最後更新" + } + } + } + }, + "panel.processes" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Processes" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "进程" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "程序" + } + } + } + }, + "panel.processFailed" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Process enumeration failed" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "进程枚举失败" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "程序列舉失敗" + } + } + } + }, + "panel.processScope" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "CPU: one core = 100%, may exceed 100% · Memory: RSS · Restricted fields shown as --" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "CPU:单核 100%,可超过 100% · 内存:RSS · 受限字段显示 --" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "CPU:單核 100%,可超過 100% · 記憶體:RSS · 受限欄位顯示 --" + } + } + } + }, + "panel.rateBaseline" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Waiting for complete rate baselines" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在建立速率基线,当前汇总不完整" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在建立速率基準,目前彙總不完整" + } + } + } + }, + "panel.restricted" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Restricted" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "读取受限" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "讀取受限" + } + } + } + }, + "panel.rss" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "RSS" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "RSS" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "RSS" + } + } + } + }, + "panel.sampling" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sampling · last update" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "采样中 · 最后更新" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "取樣中 · 最後更新" + } + } + } + }, + "panel.search" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Search name, PID, path" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索名称、PID、路径" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜尋名稱、PID、路徑" + } + } + } + }, + "panel.smartScope" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "SMART: physical storage backing the home volume" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "SMART:主卷对应物理存储" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "SMART:主卷對應實體儲存裝置" + } + } + } + }, + "panel.sort" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sort processes" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "进程排序" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "程序排序" + } + } + } + }, + "panel.stale" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Data is stale" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "数据已过期" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "資料已過期" + } + } + } + }, + "panel.threads" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Threads" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "线程" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "執行緒" + } + } + } + }, + "panel.totalNetwork" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Total (active en interfaces)" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "总体(活动 en 接口)" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "整體(作用中 en 介面)" + } + } + } + }, + "panel.totalScope" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Active en interfaces only; excludes VPN tunnels. Counters since interface start." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "仅汇总活动 en 接口,不含 VPN 隧道;累计值为系统接口计数。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "僅彙總作用中 en 介面,不含 VPN 通道;累計值為系統介面計數。" + } + } + } + }, + "panel.uptime" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Uptime" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "运行时间" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "運行時間" + } + } + } + }, + "PID" : { + }, "pressure.critical" : { "extractionState" : "manual", diff --git a/kymo/UI/Charts/PanelTrendChart.swift b/kymo/UI/Charts/PanelTrendChart.swift new file mode 100644 index 0000000..8815f16 --- /dev/null +++ b/kymo/UI/Charts/PanelTrendChart.swift @@ -0,0 +1,56 @@ +import SwiftUI + +/// Real timestamps determine x positions; missing data and pauses break the path. +struct PanelTrendChart: View { + let dates: [Date] + let first: [Double?] + var second: [Double?] = [] + let color: Color + var secondColor: Color = .orange + var fixedScale: Double? = 1 + var scaleLabel: String? + @State private var retainedScale: Double = 1 + @State private var smallSamples = 0 + + private var maximum: Double { max(1, (first + second).compactMap { $0 }.filter(\.isFinite).max() ?? 1) } + var body: some View { + VStack(spacing: 2) { + HStack { + Text(verbatim: scaleLabel ?? (fixedScale == nil ? MetricFormat.rate(retainedScale) : "100%")) + Spacer() + }.font(.system(size: 9)).foregroundStyle(.secondary) + Canvas { context, size in + guard let begin = dates.first, let end = dates.last, end > begin else { return } + let scale = fixedScale ?? retainedScale + for (values, tint) in [(first, color), (second, secondColor)] { + var path = Path() + var connected = false + for index in dates.indices { + guard index < values.count, let value = values[index], value.isFinite else { connected = false; continue } + if index > 0 && dates[index].timeIntervalSince(dates[index - 1]) > 5 { connected = false } + let point = CGPoint(x: size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin), + y: size.height * (1 - min(1, max(0, value / scale)))) + if connected { path.addLine(to: point) } else { path.move(to: point) } + connected = true + } + context.stroke(path, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round)) + } + }.frame(height: 44) + HStack { + if let date = dates.first { Text(date, style: .time) } + Spacer() + if let date = dates.last { Text(date, style: .time) } + }.font(.system(size: 9)).foregroundStyle(.secondary) + } + .onAppear { retainedScale = maximum } + .onChange(of: dates.last) { _, _ in + let target = maximum + if target > retainedScale { retainedScale = target; smallSamples = 0 } + else if target < retainedScale * 0.5 { + smallSamples += 1 + if smallSamples >= 10 { retainedScale = target; smallSamples = 0 } + } else { smallSamples = 0 } + } + .accessibilityHidden(true) + } +} diff --git a/kymo/UI/Components/ResourceCard.swift b/kymo/UI/Components/ResourceCard.swift new file mode 100644 index 0000000..a47b72e --- /dev/null +++ b/kymo/UI/Components/ResourceCard.swift @@ -0,0 +1,26 @@ +import SwiftUI + +struct ResourceCard: View { + let title: LocalizedStringKey + let symbol: String + let color: Color + let value: String + @ViewBuilder var content: () -> Content + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack { + Label(title, systemImage: symbol).font(.system(size: 13, weight: .semibold)).foregroundStyle(color) + Spacer(minLength: 6) + Text(verbatim: value).font(.system(size: 20, weight: .semibold, design: .rounded)).monospacedDigit() + } + content() + Spacer(minLength: 0) + } + .font(.system(size: 11)) + .padding(12) + .frame(maxWidth: .infinity, minHeight: 250, alignment: .topLeading) + .background(Color("PanelCard"), in: .rect(cornerRadius: 14)) + .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.primary.opacity(0.1))) + } +} diff --git a/kymoTests/PanelAssetChecks.swift b/kymoTests/PanelAssetChecks.swift new file mode 100644 index 0000000..6d98457 --- /dev/null +++ b/kymoTests/PanelAssetChecks.swift @@ -0,0 +1,17 @@ +import AppKit + +@main struct PanelAssetChecks { + static func main() { + let bundle = Bundle(path: CommandLine.arguments[1])! + for appearance in [NSAppearance.Name.aqua, .darkAqua] { + NSAppearance(named: appearance)!.performAsCurrentDrawingAppearance { + for name in ["PanelCard", "MetricCPU", "MetricGPU", "MetricMemory", "MetricNetwork", "MetricDisk", "MetricBattery"] { + guard let color = NSColor(named: NSColor.Name(name), bundle: bundle)?.usingColorSpace(.sRGB) else { fatalError("Missing color: \(name)") } + precondition(abs(color.alphaComponent - 1) < 0.001, "Transparent \(name)") + if name == "MetricGPU" && appearance == .darkAqua { precondition(color.blueComponent > 0.99) } + } + } + } + print("PASS: compiled light/dark semantic colors exist, fully opaque, GPU blue component is normalized") + } +} diff --git a/kymoTests/PanelLayoutChecks.swift b/kymoTests/PanelLayoutChecks.swift new file mode 100644 index 0000000..8f3ed32 --- /dev/null +++ b/kymoTests/PanelLayoutChecks.swift @@ -0,0 +1,30 @@ +import Foundation +import CoreGraphics + +@main struct PanelLayoutChecks { + static func main() { + 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) + for frame in [CGRect(x: -500, y: 500, width: 1240, height: 820), CGRect(x: 1400, y: -800, width: 2000, height: 1200)] { + precondition(visible.insetBy(dx: 16, dy: 16).contains(PanelLayout.constrainedFrame(frame, visible: visible))) + } + } + 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 + return ProcessMetrics(id: id, name: "worker-\(index)", + path: path, cpu: Double(index), residentBytes: UInt64(2000 - index), threads: 1, restricted: false) + } + let cpu = ProcessTableProjection.rows(input, query: "", byMemory: false, order: []) + precondition(cpu.first?.id.pid == 2000 && cpu.count == 2000) + let memory = ProcessTableProjection.rows(input, query: "", byMemory: true, order: []) + precondition(memory.first?.id.pid == 1) + let held = ProcessTableProjection.rows(input, query: "", byMemory: true, order: cpu.map(\.id)) + precondition(held.map(\.id) == cpu.map(\.id)) + let matched = ProcessTableProjection.rows(input, query: "needle", byMemory: false, order: []) + precondition(matched.count == 1 && matched[0].id.pid == 43) + precondition(ProcessTableProjection.rows(input, query: "does-not-exist", byMemory: false, order: []).isEmpty) + print("PASS: visible-frame bounds/chrome/negative origins, 2000-row CPU/RSS projection, frozen order, path search and empty results") + } +} diff --git a/kymoTests/README.md b/kymoTests/README.md index 0008e7b..c8a274e 100644 --- a/kymoTests/README.md +++ b/kymoTests/README.md @@ -108,3 +108,30 @@ swiftc -module-cache-path /private/tmp/kymo-settings-cache \ ``` 将临时可执行文件放入带 Info.plist 并已完成代码签名的临时 `.app/Contents/MacOS`,再用 `open -n -W` 启动。检查首次展示、焦点恢复、隐藏重开、最小化恢复、普通窗口层级及关闭生命周期;不替代实际多窗口场景与视觉验收。 + +## 统一面板数据检查 + +```bash +swiftc -module-cache-path /private/tmp/kymo-unified-cache \ + kymo/Core/Models/*.swift kymo/Core/Monitors/*.swift \ + kymo/Core/Services/*.swift kymo/Core/Extensions/*.swift \ + kymoTests/UnifiedPanelChecks.swift -o /private/tmp/kymo-unified-checks +/private/tmp/kymo-unified-checks +``` + +覆盖进程 CPU 首帧/差分与可见性基线、GPU 数值范围、VPN 防双计和接口历史容量。签名沙盒包、三语资源与真实 UI 的验证边界见 [统一面板验证](../docs/unified-panel-validation.md)。无 Xcode 测试 Target,不能将上述程序称为 xcodebuild test。 + +布局和列表投影边界、实际编译颜色检查: + +```bash +swiftc -module-cache-path /private/tmp/kymo-unified-cache \ + kymo/Core/Models/ProcessMetrics.swift kymo/Features/MenuBar/PanelLayout.swift \ + kymo/Features/MenuBar/ProcessTableProjection.swift kymoTests/PanelLayoutChecks.swift \ + -o /private/tmp/kymo-panel-layout-checks +/private/tmp/kymo-panel-layout-checks +swiftc -parse-as-library -module-cache-path /private/tmp/kymo-unified-cache \ + kymoTests/PanelAssetChecks.swift -o /private/tmp/kymo-panel-asset-checks +/private/tmp/kymo-panel-asset-checks /absolute/path/to/kymo.app +``` + +前者覆盖屏幕预算、边界约束和 2000 行投影,不证明原生定位或滚动手感;后者读取编译资源,防止整数色值被解释为 1/255。