From 1419bbbe0931970bdd896dd3e552dc88d8e9ec20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A0=81=E5=86=9C=E9=98=BF=E6=A5=A0?= Date: Tue, 3 Nov 2026 18:59:45 +0800 Subject: [PATCH] =?UTF-8?q?refactor(ui):=20=E7=BB=9F=E4=B8=80=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=8D=A1=E7=89=87=E8=A7=84=E8=8C=83=E5=B9=B6=E6=94=B6?= =?UTF-8?q?=E6=95=9B=E9=9D=A2=E6=9D=BF=E5=B8=83=E5=B1=80=E4=B8=8E=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/README.md | 4 +- docs/architecture.md | 13 +- docs/ui-consistency-review.md | 16 +- docs/ui-consistency-validation.md | 33 ++ kymo/Features/MenuBar/GPUStatisticsView.swift | 6 +- kymo/Features/MenuBar/MemoryDetailsView.swift | 62 +-- .../MenuBar/MenuPanelView+Network.swift | 124 +++++ .../MenuBar/MenuPanelView+ResourceCards.swift | 316 +++++++++++ kymo/Features/MenuBar/MenuPanelView.swift | 497 +++--------------- kymo/Features/MenuBar/PanelLayout.swift | 27 +- kymo/Features/MenuBar/ProcessTableView.swift | 5 +- .../Features/MenuBar/StorageDetailsView.swift | 65 +-- kymo/UI/Charts/PanelTrendChart.swift | 6 +- kymo/UI/Components/PanelStyle.swift | 107 ++++ kymo/UI/Components/ResourceCard.swift | 83 +-- kymoTests/PanelLayoutChecks.swift | 23 +- 16 files changed, 801 insertions(+), 586 deletions(-) create mode 100644 docs/ui-consistency-validation.md create mode 100644 kymo/Features/MenuBar/MenuPanelView+Network.swift create mode 100644 kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift create mode 100644 kymo/UI/Components/PanelStyle.swift diff --git a/docs/README.md b/docs/README.md index 7f69cde..13db7e8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,7 +11,7 @@ | [testing-capabilities.md](testing-capabilities.md) | 当前智能体测试能力实测、环境限制与验证边界 | | [development.md](development.md) | 开发环境搭建、构建调试、测试 Target 添加与协作规范 | | [unified-panel-plan.md](unified-panel-plan.md) | 新一轮统一面板设计审评、总体方案与 P0–P6 实施计划(实施中) | -| [ui-consistency-review.md](ui-consistency-review.md) | 六卡 UI 一致性专项审评、信息角色规范、行高方案与分阶段验收计划(待实施) | +| [ui-consistency-review.md](ui-consistency-review.md) | 六卡 UI 一致性专项审评、信息角色规范、行高方案与分阶段验收计划(已实施,验收边界见文档) | | [implementation-plan.md](implementation-plan.md) | 既有 A–F 方案与历史实施记录 | | [settings-brand-plan.md](settings-brand-plan.md) | 设置窗口展示、系统式侧边栏与分组表单、品牌图标实施记录 | | [stage-a-validation.md](stage-a-validation.md) | A 阶段采样、资源及 UI 验证记录 | @@ -32,3 +32,5 @@ - [磁盘 SMART 只读辅助服务实施方案](disk-smart-helper-plan.md) - [统一面板实施验证](unified-panel-validation.md) + +- [UI 规范改造验证记录](ui-consistency-validation.md):固定数据几何/渲染、交互结果与未覆盖项。 diff --git a/docs/architecture.md b/docs/architecture.md index 666f4eb..197a5d2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -60,11 +60,11 @@ GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取 ### 面板、历史与外观 - Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含 CPU、GPU、内存、电量、电池功率、网络上下行和设备读写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线;breakBefore 标记只在首次/暂停恢复处断开;每个样本及分接口历史保留自己的预期间隔,改频率不插入人为断点。60 点代表样本数,时间跨度随真实间隔变化。 -- 当前正式入口为统一 `MenuPanelView`:第一排 CPU/GPU/电池等宽,第二排内存/存储/网络等宽。宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时两排完整布局;第一排在 CPU 核心占两行时参考高度约 239pt,不预留第三行空间,只有实际需要第三行核心时再扩展到约 265pt;第二排保持 240pt。进程区使用剩余空间(最小 170pt)。其他尺寸资源独立滚动,进程常驻;三列低高度仍保持上述等宽比例与顺序。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,布局后约束完整 frame 原点并水平居中。NSPanel 固定/关闭策略和 key/main 资格已有独立检查;实际外部点击与多屏专项待补。 +- 当前正式入口为统一 `MenuPanelView`:资源顺序为 CPU/GPU/电池/内存/存储/网络。宽高按所属屏幕 visibleFrame 与窗口 chrome 限制为最多 1240×820pt;≥1160pt 三列、≥900pt 两列、其他单列。`PanelLayout` 是列数、初始卡宽、物理行高及资源滚动预算入口;实际卡宽由 HStack 根据滚动视口均分并反馈核心布局:普通卡基准 280pt,CPU 超过两行核心时每行扩展 26pt,GPU 超过一行风扇时每行扩展 26pt;每一物理行取所属卡片需求最大值。两列下电池与内存按实际配对等高。可见期间保留已读到的风扇容量,暂缺转速以 -- 占位,避免异步缺失导致收缩。资源总高超过面板减去内边距、40pt 顶栏预算、间距及 170pt 进程预算时独立滚动;进程区仍使用原生 Table 的纵横滚动与单元格复用。窗口定位/固定/关闭策略不变;真实外部点击与多屏专项待补。 - `PanelWindowObserver` 仅观察所属窗口的屏幕/移动/缩放,测量尺寸并约束居中;可见性由 MenuPanelController 开关与内容挂载生命周期通知 Store,不根据失焦推断关闭。 - CPU 逻辑核心类型在启动后按需从 IODeviceTree 的 `logical-cpu-id` 与 `cluster-type` 一次读取并缓存,按编号关联 Mach 采样结果;E、M、P 分别对应较低、中间和较高等级。存在 M 时 P 显示为超性能核,否则 P 显示为性能核。未知字段或无法读取时保持中性色,不依据核心顺序或数量推断;此设备树字段并非稳定的公开分类接口。卡片图例与辅助功能说明类型,核心进度条按采样平滑变化并遵循减少动态效果。底部标注开机运行时间;负载展示最近 1 分钟的原始平均值和逻辑核心数,进度条以核心数为满刻度,超出时只裁剪图形、保留原始数值,不把负载解释为 CPU 占用率。 - CPU 核心按真实类型分区,依次显示能效、中间、性能及未知类型;每组保留实际核心数量,不推断缺失拓扑。分区按两行所需列数比例分配可用宽度,组内优先均分两行,单元宽低于 16pt 时使用三行,更多核心缩小圆环;所有分区统一使用最小可用圆环直径。高度与首排扩展按各分区实际最大行数计算,不预留第三行。每核中央显示百分比、不显示编号,辅助功能与悬浮说明保留编号;进度动画遵循减少动态效果。CPU 卡片通过细分隔线区分曲线、核心与底部状态,底部负载使用标签与数值同行、下方圆角条,运行时间独立一列。 -- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,用户与系统实时值只保留在图表图例,不在下方重复展示;网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值、显式中断标记和超过 max(5s, 相邻样本预期间隔较大值×2) 的间隙断线。图例始终显示最新值;悬浮时使用独立浮层显示历史时刻与各序列值,保留游标/交点,不覆盖图例数据。图表通过 Anchor Preference 上报绘图区锚点、悬浮位置与内容,ResourceCard 在卡片最外层 overlay 统一绘制浮层,避免局部 zIndex 无法越过时间刻度/卡片字段;按实际本地化内容尺寸测量并约束在卡片内。浮层不参与鼠标命中,不创建顶层窗口;背景使用 NSVisualEffectView 的 popover/withinWindow 材质模糊下方内容,轻叠资源色,减少透明度时回退实色;原生材质视图也透传鼠标。CPU 使用青绿/紫红/金色区分,所有数据序列统一使用圆滑实线,未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示;UI 渲染帧最多保留 61 点,包含一个移出样本,旧首尾域连续插值到新首尾域,左端线段随动画裁出,不能先删除左端点。动画任务由提交后的帧状态触发,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。 +- `PanelTrendChart` 只接收时间戳、最多四序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,用户与系统实时值只保留在图表图例,不在下方重复展示;网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值、显式中断标记和超过 max(5s, 相邻样本预期间隔较大值×2) 的间隙断线。图例始终显示最新值;悬浮时使用独立浮层显示历史时刻与各序列值,保留游标/交点,不覆盖图例数据。图表通过 Anchor Preference 上报绘图区锚点、悬浮位置与内容,ResourceCard 在卡片最外层 overlay 统一绘制浮层,避免局部 zIndex 无法越过时间刻度/卡片字段;按实际本地化内容尺寸测量并约束在卡片内。浮层不参与鼠标命中,不创建顶层窗口;背景使用 NSVisualEffectView 的 popover/withinWindow 材质模糊下方内容,轻叠资源色,减少透明度时回退实色;原生材质视图也透传鼠标。CPU 使用青绿/紫红/金色区分,所有数据序列统一使用圆滑实线,未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示;UI 渲染帧最多保留 61 点,包含一个移出样本,旧首尾域连续插值到新首尾域,左端线段随动画裁出,不能先删除左端点。动画任务由提交后的帧状态触发,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。 - 电池趋势同时绘制 0–100% 电量与瓦特功率;功率序列使用独立自动量级和右侧刻度,避免百分比与 W 共用纵轴。图例和悬浮值分别按百分比与 W 格式化。电池卡下方保留两行摘要:健康度/循环次数、电源类型/续航预估;随后以紧凑列表显示 CPU 占用最高的 3 个进程,每行包含运行应用或可执行文件图标、名称和 CPU 占用。该列表是可观测代理,数据尚未完成或不可读时显示等待状态,不宣称等同于系统能耗评分。 - 各卡标题与彩色主值均为 13pt、垂直居中对齐同一行,温度胶囊与告警文案也共享该中线;数值组件复用系统 numericText 数字翻动/模糊过渡并遵循减少动态效果,进程行不施加该动画。PanelBackground / PanelCard 深浅色均为不透明实色,主面板与卡片不使用玻璃材质;顶栏操作胶囊使用系统液态玻璃材质,NSPanel 保留透明窗口壳仅用于圆角外部。深色强调色为薄荷青 #35D6BD、莓粉 #F56DA6、嫩绿 #93D45B、晴蓝 #6FA0FF、暖金 #FFC15A、浅紫 #BE8AFF,浅色提供同色相较深版本以保证可读性。网络下载/上传为蓝/金,存储读/写为金/紫,CPU 总体/用户/系统为青/粉/金;图表浮窗及原生控件弹窗继续使用模糊材质,遵循减少透明度设置。操作强调色仍由偏好决定;刷新控件、图钉、保持唤醒、暂停/恢复、设置、退出胶囊位于顶栏右侧。顶栏左侧为品牌与右上角小号版本号,经竖线与缓存的本机产品名/芯片分隔,产品名不可读时退回 hw.model,不读取序列号。原采样状态/更新时间与底栏移除。 - NetworkPathObserver 从系统路径的偏好首位接口提供默认接口名称([NWPath 接口按偏好排序](https://developer.apple.com/documentation/network/nwpath)),网络卡默认直接展示该接口的 IPv4,若无则展示 IPv6;未知不随意选择另一个接口。手动切换接口时同步展示该接口地址。getifaddrs 元数据、接口速率和路径状态仍独立采集;不把接口 IP 当作公网出口地址。 @@ -218,3 +218,12 @@ CPU、GPU、电池在三列及窄屏网格中共享显式行高:基础 260pt 网络卡片标题上下行分别使用下载蓝、上传琥珀色;趋势图图例省略重复实时值。累计接收、发送及系统网络路径状态按三列双行展示,简化为“全部”/接口名的选择器位于网络状态标题右侧;底部 IP 地址独立标题,下排公网与内网两列支持复制,不再显示底部范围说明。总体仍仅汇总活动 en 接口,内网地址来自所选接口(总体使用默认接口)。 `PublicIPAddressService` 为 Core actor,通过 HTTPS api.ipify.org 查询系统出口 IP,5 秒请求超时,成功/失败均按路由标识缓存 10 分钟。面板任务在默认接口、活动接口地址或系统路径状态变化时重取,不加入高频采样链路,无独立后台计时器;关闭面板后取消调用方任务,取消结果不写入 UI。失败或离线显示 --,公网不是所选接口绑定查询,也不代表持续外网连通性测试。此查询向 ipify 暴露请求出口地址,不发送本地接口或进程信息。 + + +## 2026-11-03 UI 规范收敛 + +`UI/Components/PanelStyle.swift` 定义资源面板标题、区标题、标签、数值与图例角色,以及通用分隔线、字段、容量条/分类、区标题和外壳/内嵌背景。组件只接收展示入参,不读取 MetricsStore 或业务能力。容量条按真实比例绘制,不给小分类最小宽度;内存 UInt64 明确使用数值转换为 Double,避免 init(bitPattern:) 重载歧义。 + +`ResourceCard` 由布局器确定尺寸,GeometryReader 将外壳背景与描边绑定最终分配 bounds,内层标题固定 20pt,详情统一在独立内容栈中布局;温度/规格胶囊均为 10pt medium、16pt 高。六卡绘图区统一 58pt;存储物理 I/O 范围保留为趋势图帮助说明。内存/存储共用分布标题、8pt 容量条、10pt 分类字段和 32pt 底部字段。电池缺失与内存缺失保留趋势/首分隔线,详情显示状态。进程区使用相同外壳及标题样式,原生控件行为保留。 + +MenuPanelView 主文件保留生命周期、布局和顶栏控制,资源卡片与网络装配分别收敛到同名扩展文件,仍属 Features/MenuBar;跨文件仅开放装配所需的内部状态/计算属性,没有新增公共 API。删除旧的未使用行高公式和展示辅助函数,测试覆盖视图实际调用的布局策略。此节与前述布局现状替代历史记录中的 239/240/260pt 行高、GPU 42pt 统计区等旧描述;当前 GPU 统计区为 46pt。采样、XPC、Core 数据流及设置架构未改。 diff --git a/docs/ui-consistency-review.md b/docs/ui-consistency-review.md index 21f1dfe..aaaec2e 100644 --- a/docs/ui-consistency-review.md +++ b/docs/ui-consistency-review.md @@ -1,6 +1,6 @@ # 统一面板 UI 规范专项审评与优化方案 -日期:2026-11-03。状态:审评完成,以下规范与实施步骤为建议,尚未实施。 +日期:2026-11-03。状态:审评与主要改造完成;第 1–7 节保留实施前依据,实际结果与验证边界见第 8 节。 ## 1. 目标、范围与证据边界 @@ -181,3 +181,17 @@ 本轮已完成截图审评、源码调用链核对、差异清单、语义规范建议、分区预算和实施/验收计划。未修改运行代码,未构建、未执行 UI 测量或交互验证;电池微差的精确根因待 P0。整体架构与数据流未变,因此本轮不修改 `architecture.md` 的当前实现描述;实施新增样式/布局契约时同步更新。 主观密度、动画观感与真实多屏/刘海屏由用户最终验收;工具可观测的布局和交互由实施阶段尽量完成,受阻项目需逐项记录,不能沿用旧会话的成功或失败结果。 + + +## 8. 实施结果(2026-11-03) + +已落地 P1–P3 的样式、公共分区、六卡装配和自适应收敛。基准行高最终采用 **280pt**:统一 20pt 标题、58pt 绘图、10pt 普通字段及电池 Top 3 完整列表后,260pt 预算不足;不采用缩字或裁切补偿。首排与第二排普通状态同为 280pt,硬件扩展仅影响所属物理行。进程区保持至少 170pt,标准尺寸可见行数随资源预算减少,较低窗口滚动资源区。 + +- `PanelStyle` 和公共字段/分布区/分隔线/外壳/内嵌组件统一信息角色;微型核心/统计环、原生表格与图例轴标仍有明确的专属字号。 +- ResourceCard 外壳直接依赖分配 bounds,标题与内容栈分开,避免内容固有尺寸反向推高背景;状态胶囊不再改变标题槽。 +- 存储趋势从 48pt 改为 58pt,统计范围移到帮助说明;内存/存储的分布和底部字段基线共用组件。 +- MenuPanelView 从 575 行拆分为布局/生命周期/顶栏主文件、资源装配扩展、网络扩展;通用 UI 不识别资源类别,未引入新依赖。 +- 旧行高公式被实际布局策略替代;断点、宽度守恒、物理行最大需求、滚动预算以及原有进程投影检查均覆盖实际代码。 +- 本地化文件原有修改保留,不纳入本次提交;部分过长英文标签采用省略与帮助提示,未通过任意缩小普通字号腾空间。 + +验证证据与未覆盖矩阵见 [UI 规范改造验证记录](ui-consistency-validation.md)。原截图微差未通过原版本完整运行时重建定位到单一根因;本轮修正了标题固有高度、背景 bounds 与行高分配契约,并用本轮视图测量验证结果,不能倒推旧版本的唯一原因。 diff --git a/docs/ui-consistency-validation.md b/docs/ui-consistency-validation.md new file mode 100644 index 0000000..4948894 --- /dev/null +++ b/docs/ui-consistency-validation.md @@ -0,0 +1,33 @@ +# UI 规范改造验证记录 + +日期:2026-11-03。对应 [专项审评及方案](ui-consistency-review.md) 的本轮实现。 + +## 实现与取舍 + +普通资源卡统一基准高度 280pt、20pt 标题槽和 58pt 绘图区;实际物理行按 CPU 核心/风扇行数需求取最大值。260pt 草案在统一字号、电池摘要和完整 Top 3 列表下偏紧,最终增加整体预算,未用裁切或普通字段缩字补偿。第二排行高增加会减少进程初始可见行数;1240×820pt 固定样例初始约四行,较低/较窄面板独立滚动资源区,保留进程区至少 170pt。 + +通用角色与组件收敛到 PanelStyle;内存/存储共用区标题、容量条、分类字段和底部字段;外壳与原生进程容器外观一致。主视图拆为布局/生命周期/顶栏、资源卡片扩展、网络扩展,业务装配仍留在 Features。没有改变采样、指标口径、权限、XPC 或设置架构。 + +滚动布局不再把整个面板宽度强加到子卡片:HStack 按实际视口均分,测得卡宽反馈给核心排布与行高预算,兼容占宽的系统滚动条。风扇暂缺时保留已建立的容量,用 -- 展示未知转速。 + +## 已通过 + +- 最终 Debug 构建:`xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug -derivedDataPath /private/tmp/kymo-ui-build build`,BUILD SUCCEEDED。未发现 Swift 编译警告;有系统 AppIntents 元数据提取跳过提示。 +- 独立 PanelLayoutChecks:640/899/900/1159/1160/1240pt 宽度、列数断点、宽度守恒、物理行需求最大值、6 风扇与三行核心的预算、低高窗口滚动判定;保留可见屏幕/chrome/负坐标及 2000 条进程投影、冻结排序、路径搜索检查。工程仍无测试 Target,未运行或声称通过 `xcodebuild test`。 +- 固定数据渲染使用隔离标识 `cn.airnan.kymo.uifixture` 的签名沙盒普通 NSWindow,加载本轮实际 MenuPanelView、ResourceCard、图表和字段组件。仅临时副本替换 App 入口、禁用实时采样并注入固定快照、测量日志;正式源码未增加测试窗口、固定数据或诊断输出。 +- 渲染组合:1240×820pt 简中深色、英语浅色、900×820pt 繁中双列、640×820pt 简中单列、1240×820pt GPU/温度/电池/内存缺失。五组均核对全部六张卡片的几何 bounds、标题槽与内容内边距;截图核对可见内容。窄屏初始截图只显示滚动区的一部分,不把离屏几何测量等同于所有离屏字形的视觉验收。 +- 标准三列各卡外框高度均为 280pt,同排 y 坐标相同;标题相对卡顶均为 10pt、高 20pt,内容起点为卡顶 34pt。CPU/GPU/电池内容区均能位于底部 10pt 留白以内,电池最后一行未突破外壳。内存/存储同类分布区与底部字段对齐,分布条颜色与比例可见。 +- 几何检查采用最多 0.5pt 的字体/子像素取整容差,外框实际相等;本机截图为 2×。英语内存内容的宽度取整差约 0.17pt,无可见越界;未使用逐卡 offset 补偿。 +- 窄屏滚动条占宽已实测:640pt 面板中卡宽从初始提议 620pt 收敛为视口 603pt,卡片左边保持 10pt,未因滚动条导致两侧被裁。900pt 双列中资源滚动至存储/网络卡,卡片完整、顶栏与进程表位置保持;工具动作两次返回状态变化提示,随后 AX 与单窗口截图确认实际已滚动到底,结论以观察结果为准。 +- 原生 UI 在隔离窗口验证:搜索 WeChat 后 20 条变为 6 条,Esc 清空恢复 20 条,点击内存排序状态切换,卷详情 popover 展开。单窗口截图未包含无关桌面。容量条渲染检查发现并修正 UInt64 的 `map(Double.init)` 重载歧义,正式代码明确使用 `{ Double($0) }` 数值转换。 +- 无电池时保留标题、趋势、分隔线与等高状态区;内存缺失同样保留公共槽。GPU 不可用保留字段和未知值,说明位于统计区帮助中;不以零值充当未知指标。 + +## 验证边界与剩余验收 + +本轮未重启或退出用户已有 Xcode 副本 PID 48034。测试包使用固定数据与不同标识,不以其 SMART、公共 IP 或进程图标状态证明正式数据读取。初始原生 Table 产生过 NSTableView delegate reentrant 系统警告,搜索/排序/滚动可用;本轮未修改其数据投影逻辑,未定位该警告来源。 + +未完整覆盖:正式 NSPanel 的菜单栏开关/外部关闭/固定策略、真实多屏/刘海屏与 1× 屏幕、所有三语×深浅色组合、减少动态效果/透明度、完整 VoiceOver、超长 IPv6/极大数值、0/1 条电池进程与多风扇/高核心数的实际渲染、长时能耗与内存。高核心/多风扇本轮只有布局策略检查,不能称为真实硬件验收;IP 复制与接口切换本轮未做端到端交互回归。 + +用户后续验收可在 Xcode 重新运行正式应用:打开面板检查两排卡片及电池最后一行;切换浅色/英文并悬浮长标签确认帮助;在较小屏幕滚动资源区并检查进程仍可操作。动画手感、视觉密度和真实多屏定位由用户最终确认。原截图微差未完成原版本运行时根因复现,不能断言旧版本只有一个原因。 + +本轮临时测试应用、截图、脚本、编译缓存及构建产物在交付前清理。原有 Localizable.xcstrings 改动保留且不纳入提交。 diff --git a/kymo/Features/MenuBar/GPUStatisticsView.swift b/kymo/Features/MenuBar/GPUStatisticsView.swift index f9072ff..d68111e 100644 --- a/kymo/Features/MenuBar/GPUStatisticsView.swift +++ b/kymo/Features/MenuBar/GPUStatisticsView.swift @@ -21,7 +21,7 @@ struct GPUStatisticsView: View { MetricRingGauge(title: "gpu.recentAverage", value: average, color: Color("MetricCPU")) MetricRingGauge(title: "gpu.peak", value: peak, color: Color("MetricGPU")) }.frame(maxWidth: .infinity).help(Text("gpu.summaryHelp")) - }.frame(height: 42) + }.frame(height: 46) } private func memoryRow(_ title: LocalizedStringKey, bytes: UInt64?, color: Color) -> some View { @@ -29,8 +29,8 @@ struct GPUStatisticsView: View { HStack(spacing: 4) { Text(title).foregroundStyle(.secondary) Spacer(minLength: 0) - AnimatedMetricText(value: MetricFormat.bytes(bytes)).fontWeight(.medium) - }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.7) + AnimatedMetricText(value: MetricFormat.bytes(bytes)).font(PanelStyle.value) + }.font(PanelStyle.label).lineLimit(1) MetricProgressBar(value: bytes.map { Double($0) / reference } ?? 0, color: color) .frame(height: 3) .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: bytes) diff --git a/kymo/Features/MenuBar/MemoryDetailsView.swift b/kymo/Features/MenuBar/MemoryDetailsView.swift index c5c5dc6..70d564e 100644 --- a/kymo/Features/MenuBar/MemoryDetailsView.swift +++ b/kymo/Features/MenuBar/MemoryDetailsView.swift @@ -2,62 +2,34 @@ import SwiftUI struct MemoryDetailsView: View { let memory: MemoryMetrics - @Environment(\.accessibilityReduceMotion) private var reduceMotion private var colors: [Color] { [Color("MemoryApplication"), Color("MemoryWired"), Color("MemoryCompressed"), Color("MemoryAvailable")] } private var values: [UInt64] { [memory.app, memory.wired, memory.compressed, memory.available] } private let labels: [LocalizedStringKey] = ["memory.app", "memory.wired", "memory.compressed", "memory.available"] var body: some View { - VStack(alignment: .leading, spacing: 9) { - Divider() - HStack { - Text("memory.distribution").fontWeight(.semibold) - Spacer() - Text("gpu.totalUtilization").foregroundStyle(.secondary) - AnimatedMetricText(value: MetricFormat.percent(memory.usage)).foregroundStyle(Color("MemoryApplication")) - } - GeometryReader { proxy in - HStack(spacing: 0) { - ForEach(0..<4) { index in - Rectangle().fill(colors[index]) - .frame(width: CGFloat(values[index]) / CGFloat(max(1, memory.total)) * proxy.size.width) - } - } - // Round the combined shape; tiny segments never receive a minimum width. - .clipShape(Capsule()) - .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: values) - }.frame(height: 8).accessibilityHidden(true) + VStack(alignment: .leading, spacing: 4) { + CardSeparator() + CardSectionHeader(title: "memory.distribution", valueLabel: "gpu.totalUtilization", + value: MetricFormat.percent(memory.usage), color: Color("MemoryApplication")) + CapacityBar(values: values.map { Double($0) }, colors: colors, total: Double(memory.total)) HStack(spacing: 4) { ForEach(0..<4) { index in - VStack(alignment: .leading, spacing: 4) { - HStack(spacing: 3) { - Circle().fill(colors[index]).frame(width: 4, height: 4) - Text(labels[index]).foregroundStyle(.secondary) - } - AnimatedMetricText(value: MetricFormat.memory(values[index])) - .fontWeight(.medium).monospacedDigit() - }.frame(maxWidth: .infinity, alignment: .leading) + CapacityField(title: labels[index], value: MetricFormat.memory(values[index]), color: colors[index]) } - }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.7) - Divider() + } + CardSeparator() HStack(alignment: .top, spacing: 8) { - VStack(alignment: .leading, spacing: 4) { - Text("memory.pressure").foregroundStyle(.secondary) - pressure - }.frame(maxWidth: .infinity, alignment: .leading) - Divider().frame(height: 30) - VStack(alignment: .leading, spacing: 4) { - Text("memory.cached").foregroundStyle(.secondary) + CardField(title: "memory.pressure") { pressure } + Divider().frame(height: 32) + CardField(title: "memory.cached") { AnimatedMetricText(value: MetricFormat.memory(memory.cached)) - }.frame(maxWidth: .infinity, alignment: .leading) - .help(Text("memory.cachedHelp")) - Divider().frame(height: 30) - VStack(alignment: .leading, spacing: 4) { - Text("memory.swap").foregroundStyle(.secondary) + }.help(Text("memory.cachedHelp")) + Divider().frame(height: 32) + CardField(title: "memory.swap") { AnimatedMetricText(value: MetricFormat.memory(memory.swapUsed)) - }.frame(maxWidth: .infinity, alignment: .leading) - }.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) - }.padding(.top, 4) + } + }.font(PanelStyle.label).lineLimit(1) + } } @ViewBuilder private var pressure: some View { diff --git a/kymo/Features/MenuBar/MenuPanelView+Network.swift b/kymo/Features/MenuBar/MenuPanelView+Network.swift new file mode 100644 index 0000000..b20108b --- /dev/null +++ b/kymo/Features/MenuBar/MenuPanelView+Network.swift @@ -0,0 +1,124 @@ +import AppKit +import SwiftUI + +extension MenuPanelView { + var networkCard: some View { + ResourceCard( + title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: "↓ " + MetricFormat.rate(total(\.download)), + secondaryValue: "↑ " + MetricFormat.rate(total(\.upload)), valueColor: Color("MetricMemory"), + secondaryValueColor: Color("SeriesUpload") + ) { + PanelTrendChart( + dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"), + secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", + expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, showsLegendValues: false + ).id(selectedInterface) + CardSeparator() + HStack(alignment: .top, spacing: 8) { + networkTotal( + "network.received", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received }), + symbol: "arrow.down", color: Color("MetricMemory")) + Divider().frame(height: 32) + networkTotal( + "network.sent", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent }), + symbol: "arrow.up", color: Color("SeriesUpload")) + Divider().frame(height: 32) + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("network.status").foregroundStyle(.secondary) + Picker("panel.interface", selection: $selectedInterface) { + Text("network.all").tag("") + ForEach(snapshot.network ?? [], id: \.identity) { item in + Text(verbatim: item.name).tag(item.identity) + } + }.labelsHidden().controlSize(.mini).fixedSize() + } + HStack(spacing: 4) { + Circle().fill(networkStatusColor).frame(width: 5, height: 5) + Text(networkStatusLabel) + } + }.frame(maxWidth: .infinity, alignment: .leading) + }.font(PanelStyle.label).lineLimit(1) + CardSeparator() + VStack(alignment: .leading, spacing: 5) { + Text("network.addresses").font(PanelStyle.section) + HStack(spacing: 8) { + networkAddress("network.public", address: publicIPAddress) + Divider().frame(height: 15) + networkAddress( + "network.local", + address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first) + } + }.font(PanelStyle.label) + .modifier(CardInset()) + } + .task(id: publicIPRoute) { + publicIPAddress = nil + guard snapshot.networkPath == .available else { return } + let address = await PublicIPAddressService.shared.address(route: publicIPRoute) + guard !Task.isCancelled else { return } + publicIPAddress = address + } + } + var publicIPRoute: String { + "\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")" + } + func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View { + HStack(spacing: 4) { + Text(title).foregroundStyle(.secondary) + Text(verbatim: address ?? "--").font(PanelStyle.value).monospacedDigit().textSelection(.enabled) + .help(Text(verbatim: address ?? "--")) + Spacer(minLength: 0) + if let address { + Button { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(address, forType: .string) + } label: { + Image(systemName: "doc.on.doc") + } + .buttonStyle(.plain).accessibilityLabel(Text("panel.copy")) + } + }.frame(maxWidth: .infinity, alignment: .leading).lineLimit(1) + } + func networkTotal(_ title: LocalizedStringKey, value: String, symbol: String, color: Color) -> some View { + CardField(title: title) { + HStack(spacing: 3) { + Image(systemName: symbol).foregroundStyle(color) + AnimatedMetricText(value: value) + } + } + } + + var networkStatusLabel: LocalizedStringKey { + switch snapshot.networkPath { + case .available: "network.pathAvailable" + case .unavailable: "network.pathUnavailable" + case .requiresConnection: "network.pathRequiresConnection" + case nil: "metric.waiting" + } + } + var networkStatusColor: Color { + switch snapshot.networkPath { + case .available: .green + case .unavailable: .red + case .requiresConnection: .orange + case nil: .secondary + } + } + var addressInterface: NetworkInterfaceMetrics? { + let name = selectedInterface.isEmpty ? snapshot.defaultNetworkInterface : network.first?.name + return snapshot.network?.first { $0.name == name && $0.active } + } + var networkIntervals: [TimeInterval] { + selectedInterface.isEmpty ? chartIntervals : (metrics.history.interfaces[selectedInterface] ?? []).map(\.expectedInterval) + } + var networkDates: [Date] { + selectedInterface.isEmpty ? samples.map(\.date) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.date) + } + var networkDownloads: [Double?] { + selectedInterface.isEmpty ? samples.map(\.download) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.download) + } + var networkUploads: [Double?] { + selectedInterface.isEmpty ? samples.map(\.upload) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.upload) + } +} diff --git a/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift b/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift new file mode 100644 index 0000000..abcb2d4 --- /dev/null +++ b/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift @@ -0,0 +1,316 @@ +import AppKit +import SwiftUI + +extension MenuPanelView { + func line(_ key: LocalizedStringKey, _ value: String) -> some View { + HStack(alignment: .firstTextBaseline) { + Text(key).font(PanelStyle.label).foregroundStyle(.secondary) + Spacer(minLength: 6) + AnimatedMetricText(value: value).font(PanelStyle.value) + }.frame(height: 14) + } + + func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey { + if battery.charging { return "battery.chargePower" } + if !battery.externalPower { return "battery.dischargePower" } + return "battery.power" + } + + var cpuCard: some View { + let temperature = snapshot.cpuTemperature + let highTemperature = CPUTemperatureMonitor.isHighTemperature(temperature) + return ResourceCard( + title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), + value: MetricFormat.percent(snapshot.cpu?.usage), + status: temperature.map { "\(Int($0.rounded()))°C" }, + statusWarning: highTemperature, + statusHelp: temperature == nil ? nil : Text("cpu.temperature.help", tableName: "CPUDetails"), + warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil + ) { + PanelTrendChart( + dates: samples.map(\.date), first: samples.map(\.cpu), + second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem), + color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"), + firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, + boundaryDates: chartBoundaries, intervals: chartIntervals) + CardSeparator() + if let cpu = snapshot.cpu { + Spacer(minLength: 0) + CPUCoreGrid( + values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval, + availableWidth: cardContentWidth) + + } else { + Text("metric.waiting").foregroundStyle(.secondary) + } + Spacer(minLength: 0) + CardSeparator() + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary) + Spacer(minLength: 3) + AnimatedMetricText( + value: snapshot.load.first.map { "\(MetricFormat.decimal($0)) / \(snapshot.cpu?.cores.count ?? 0)" } ?? "--") + } + MetricProgressBar( + value: (snapshot.load.first ?? 0) / Double(max(1, snapshot.cpu?.cores.count ?? 0)), color: Color("MetricCPU") + ) + .frame(height: 5).accessibilityHidden(true) + }.frame(maxWidth: .infinity).help(Text("cpu.load.help", tableName: "CPUDetails")) + Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 25) + VStack(alignment: .leading, spacing: 3) { + Text("panel.uptime").foregroundStyle(.secondary) + AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600)) + .fontWeight(.medium) + } + }.font(PanelStyle.label).lineLimit(1) + + } + } + var gpuCard: some View { + let summary = GPUUtilizationSummary(samples: samples) + return ResourceCard( + title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage), + status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" }, + statusHelp: Text("gpu.temperatureHelp"), + detail: snapshot.gpu?.coreCount.map { String(format: String(localized: "gpu.coreCountFormat"), $0) } + ) { + PanelTrendChart( + dates: samples.map(\.date), first: samples.map(\.gpu), + second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler), + color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"), + firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler", + expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) + CardSeparator() + gpuActivity("gpu.rendererActivity", value: snapshot.gpu?.renderer, color: Color("MetricCPU")) + gpuActivity("gpu.tilerActivity", value: snapshot.gpu?.tiler, color: Color("SeriesSystem")) + CardSeparator() + Spacer(minLength: 0) + GPUStatisticsView( + inUse: snapshot.gpu?.inUseMemory, allocated: snapshot.gpu?.allocatedMemory, + average: summary.average, peak: summary.peak + ) + .help(snapshot.gpuUsage == nil ? Text("gpu.unavailable") : Text("gpu.summaryHelp")) + Spacer(minLength: 0) + let fans = displayedFans + if !fans.isEmpty { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) { + ForEach(fans) { fan in + FanSpeedIndicator( + title: fans.count == 2 + ? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight") + : LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm) + } + } + .modifier(CardInset()) + } + } + } + + func gpuActivity(_ title: LocalizedStringKey, value: Double?, color: Color) -> some View { + HStack(spacing: 8) { + Text(title).font(PanelStyle.label).frame(width: 100, alignment: .leading).help(Text(title)) + MetricProgressBar(value: value ?? 0, color: color).frame(height: 5) + .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value) + AnimatedMetricText(value: MetricFormat.percent(value)).font(PanelStyle.value).frame(width: 30, alignment: .trailing) + }.font(PanelStyle.label).help(Text("gpu.pipelineHelp")) + } + var memoryCard: some View { + ResourceCard( + title: "metric.memory", symbol: "memorychip", color: Color("MemoryApplication"), + value: snapshot.memory.map { + String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824) + } ?? "--" + ) { + PanelTrendChart( + dates: samples.map(\.date), + first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } }, + second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed), + color: Color("MetricCPU"), secondColor: Color("MemoryApplication"), + thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1), + scaleLabel: MetricFormat.memory(snapshot.memory?.total), firstValueFormat: .memory, firstLabel: "gpu.totalUtilization", + secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed", + expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) + if let memory = snapshot.memory { + MemoryDetailsView(memory: memory) + } else { + CardSeparator() + Text("metric.waiting").foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + var diskCard: some View { + ResourceCard( + title: "metric.disk", symbol: "internaldrive", color: Color("MetricDisk"), + value: snapshot.disk.map { + String( + format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000, + Double($0.total) / 1_000_000_000) + } ?? "--" + ) { + + PanelTrendChart( + dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), + secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", + expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals + ) + .help(Text("disk.physicalIO")) + StorageDetailsView(disk: snapshot.disk, health: snapshot.diskHealth) { + showVolumes.toggle() + } + .popover(isPresented: $showVolumes) { + VStack(alignment: .leading, spacing: 8) { + Text("disk.homeVolume") + Text("panel.smartScope").foregroundStyle(.secondary) + Group { + 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) + } + }.padding(12).frame(width: 330) + } + + } + } + var batteryCard: some View { + ResourceCard( + title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), + value: MetricFormat.percent(snapshot.battery?.charge) + ) { + PanelTrendChart( + dates: samples.map(\.date), + first: samples.map(\.battery), + second: samples.map(\.batteryPower), + color: Color("MetricBattery"), + secondColor: Color("SeriesUser"), + fixedScale: 1, + secondSeriesUsesAutonomousScale: true, + secondValueFormat: .watts, + firstLabel: "metric.battery", + secondLabel: snapshot.battery.map(batteryPowerLabel) ?? "battery.power", + expectedInterval: chartInterval, + boundaryDates: chartBoundaries, + intervals: chartIntervals + ) + CardSeparator() + if let battery = snapshot.battery { + batteryDetails(battery) + } else { + Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + private func batteryDetails(_ battery: BatteryMetrics) -> some View { + VStack(alignment: .leading, spacing: 2) { + HStack(alignment: .top, spacing: 10) { + VStack(spacing: 4) { + line("battery.health", MetricFormat.percent(battery.health)) + HStack { + Text("battery.powerSource").foregroundStyle(.secondary) + Spacer(minLength: 4) + Text(battery.externalPower ? "battery.acPower" : "battery.batterySource").font(PanelStyle.value) + }.frame(height: 14) + } + Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 32) + VStack(spacing: 4) { + line("battery.cycles", battery.cycles.map(String.init) ?? "--") + HStack { + Text("battery.timeEstimate").foregroundStyle(.secondary).help(Text("battery.timeEstimate")) + Spacer(minLength: 4) + if battery.externalPower { + Text("battery.timeNotApplicable").font(PanelStyle.value).help(Text("battery.timeNotApplicable")) + } else if let minutes = battery.minutesRemaining { + AnimatedMetricText(value: "\(minutes) min").font(PanelStyle.value) + } else { + Text("battery.timeUnknown").font(PanelStyle.value) + } + }.frame(height: 14) + } + } + .font(PanelStyle.label) + .lineLimit(1) + .frame(height: 32) + Spacer(minLength: 0) + CardSeparator() + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("battery.highestEnergyProcess").font(PanelStyle.section) + Spacer() + Text("battery.cpuUsage").foregroundStyle(.secondary) + } + .font(PanelStyle.label) + let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? [] + if energyProcesses.isEmpty { + Text("metric.waiting").foregroundStyle(.secondary) + } else { + ForEach(energyProcesses) { process in + EnergyProcessListRow(process: process) + } + } + } + // Reserve the header and all three rows before process sampling completes. + .frame(height: 74, alignment: .top) + .lineLimit(1) + .help(Text("battery.energyProxyHelp")) + + }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + +} + +struct EnergyProcessListRow: View { + let process: ProcessMetrics + @State private var icon: NSImage? + + private var progress: Double { + guard let value = process.cpu, value.isFinite else { return 0 } + return min(max(value, 0), 1) + } + + var body: some View { + HStack(spacing: 5) { + Group { + if let icon { + Image(nsImage: icon).resizable().interpolation(.high) + } else { + Image(systemName: "app.dashed").resizable().scaledToFit().padding(2) + } + } + .frame(width: 15, height: 15) + .accessibilityHidden(true) + Text(verbatim: process.name).lineLimit(1).truncationMode(.middle) + .frame(width: 66, alignment: .leading) + GeometryReader { proxy in + Capsule().fill(.primary.opacity(0.07)) + .overlay(alignment: .leading) { + Capsule().fill(Color("MetricCPU")) + .frame(width: proxy.size.width * progress, height: 4) + .clipped() + } + .clipShape(Capsule()) + } + .frame(height: 4) + .animation(.easeInOut(duration: 0.35), value: process.cpu) + AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--") + .foregroundStyle(Color("MetricCPU")).font(PanelStyle.value) + .monospacedDigit().frame(width: 39, alignment: .trailing) + } + .font(PanelStyle.label) + .frame(height: 16) + .task(id: process.id) { + icon = NSRunningApplication(processIdentifier: process.id.pid)?.icon + if icon == nil, let path = process.path { + icon = NSWorkspace.shared.icon(forFile: path) + } + } + } +} diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index e740aad..210e054 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -8,63 +8,68 @@ struct MenuPanelView: View { let settingsPresentation: SettingsPresentation var presentation = PanelPresentation() var onOpenSettings: () -> Void = {} - @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.accessibilityReduceMotion) var reduceMotion @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 publicIPAddress: String? - @State private var showVolumes = false + @State var selectedInterface = "" + @State var publicIPAddress: String? + @State var showVolumes = false - private var snapshot: MetricsSnapshot { metrics.snapshot } - private var samples: [TrendSample] { metrics.history.samples } - private var chartIntervals: [TimeInterval] { samples.map(\.expectedInterval) } - private var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 } - private var chartBoundaries: Set { Set(samples.filter(\.breakBefore).map(\.date)) } - private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 } - private var firstRowHeight: CGFloat { - let cardWidth = (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns) - let groups = CPUCoreGrid.groups(count: snapshot.cpu?.cores.count ?? 0, kinds: CPUCoreTopology.cores) - let widths = CPUCoreGrid.groupWidths(groups: groups, width: max(0, cardWidth - 20)) - let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0 - let extraFanRows = max(0, ((snapshot.fans?.count ?? 0) + 1) / 2 - 1) - return max(260 + (coreRows >= 3 ? 26 : 0), 260 + CGFloat(extraFanRows) * 19) + var snapshot: MetricsSnapshot { metrics.snapshot } + var samples: [TrendSample] { metrics.history.samples } + var chartIntervals: [TimeInterval] { samples.map(\.expectedInterval) } + var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 } + var chartBoundaries: Set { Set(samples.filter(\.breakBefore).map(\.date)) } + @State private var reservedFanCount = 0 + @State private var measuredCardWidth: CGFloat? + var displayedFans: [FanMetrics] { + let fans = snapshot.fans ?? [] + guard fans.count < reservedFanCount else { return fans } + let missingIDs = (0..) -> Double? { + 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: 8) { + VStack(spacing: PanelStyle.gap) { header - if columns == 3 { - if panelSize.height >= 810 { resourceRows } - else { ScrollView { resourceRows } } + if PanelLayout.needsResourceScroll(size: panelSize, rows: rowHeights) { + ScrollView { resourceRows } + .frame(maxHeight: PanelLayout.resourceHeight(rows: rowHeights)) } else { - ScrollView { - LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: columns), spacing: 8) { - cpuCard.frame(height: firstRowHeight) - gpuCard.frame(height: firstRowHeight) - batteryCard.frame(height: firstRowHeight) - memoryCard.frame(minHeight: 240) - diskCard.frame(minHeight: 250) - networkCard.frame(minHeight: 250) - } - } + resourceRows } if metrics.isPanelVisible { ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900, logicalCPUCount: snapshot.cpu?.cores.count ?? 1).frame(maxWidth: .infinity, maxHeight: .infinity) .frame(minHeight: 170) } } - .padding(10) + .padding(PanelStyle.padding) .frame(width: panelSize.width, height: panelSize.height) .background(PanelWindowObserver { size in if panelSize != size { panelSize = size } }.frame(width: 0, height: 0)) - .onAppear { metrics.setPanelVisible(true) } + .onAppear { + metrics.setPanelVisible(true) + reservedFanCount = snapshot.fans?.count ?? 0 + } + .onChange(of: snapshot.fans?.count) { _, count in + reservedFanCount = max(reservedFanCount, count ?? 0) + } .onDisappear { metrics.setPanelVisible(false) } .onChange(of: snapshot.network?.map(\.identity)) { _, keys in if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" } @@ -75,17 +80,31 @@ struct MenuPanelView: View { } private var resourceRows: some View { - VStack(spacing: 8) { - HStack(alignment: .top, spacing: 8) { - cpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight) - gpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight) - batteryCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight) - }.frame(height: firstRowHeight) - HStack(alignment: .top, spacing: 8) { - memoryCard.frame(width: (panelSize.width - 36) / 3) - diskCard.frame(width: (panelSize.width - 36) / 3) - networkCard.frame(width: (panelSize.width - 36) / 3) - }.frame(height: 240) + VStack(spacing: PanelStyle.gap) { + ForEach(rowHeights.indices, id: \.self) { row in + HStack(spacing: PanelStyle.gap) { + ForEach(0.. some View { + switch index { + case 0: cpuCard + case 1: gpuCard + case 2: batteryCard + case 3: memoryCard + case 4: diskCard + case 5: networkCard + default: EmptyView() } } @@ -112,343 +131,6 @@ struct MenuPanelView: View { }.padding(.horizontal, 4) } - private func chart(_ key: KeyPath, color: Color, label: LocalizedStringKey = "panel.total") -> some View { - PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label, expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) - } - private func line(_ key: LocalizedStringKey, _ value: String) -> some View { - HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) } - } - - private func coreColor(_ kind: CPUCoreTopology.Kind?) -> Color { - switch kind { - case .efficiency: Color("MetricCPU") - case .middle: Color("MetricMemory") - case .performance: Color("MetricGPU") - case nil: .secondary - } - } - - private func coreLabel(_ kind: CPUCoreTopology.Kind) -> Text { - switch kind { - case .efficiency: Text("cpu.kind.efficiency", tableName: "CPUDetails") - case .middle: Text("cpu.kind.performance", tableName: "CPUDetails") - case .performance: - CPUCoreTopology.cores.values.contains(.middle) - ? Text("cpu.kind.super", tableName: "CPUDetails") - : Text("cpu.kind.performance", tableName: "CPUDetails") - } - } - - private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey { - if battery.charging { return "battery.chargePower" } - if !battery.externalPower { return "battery.dischargePower" } - return "battery.power" - } - - private var cpuCard: some View { - let temperature = snapshot.cpuTemperature - let highTemperature = CPUTemperatureMonitor.isHighTemperature(temperature) - return ResourceCard( - title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), - value: MetricFormat.percent(snapshot.cpu?.usage), - status: temperature.map { "\(Int($0.rounded()))°C" }, - statusWarning: highTemperature, - statusHelp: temperature == nil ? nil : Text("cpu.temperature.help", tableName: "CPUDetails"), - warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil - ) { - PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu), - second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem), - color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"), - firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) - if let cpu = snapshot.cpu { - Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) - Spacer(minLength: 0) - CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval, - availableWidth: max(0, (columns == 3 ? PanelLayout.cardWidth(size: panelSize) : (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns)) - 20)) - - } else { Text("metric.waiting").foregroundStyle(.secondary) } - Spacer(minLength: 0) - Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) - HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 4) { - HStack { - Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary) - Spacer(minLength: 3) - AnimatedMetricText(value: snapshot.load.first.map { "\(MetricFormat.decimal($0)) / \(snapshot.cpu?.cores.count ?? 0)" } ?? "--") - } - MetricProgressBar(value: (snapshot.load.first ?? 0) / Double(max(1, snapshot.cpu?.cores.count ?? 0)), color: Color("MetricCPU")) - .frame(height: 5).accessibilityHidden(true) - }.frame(maxWidth: .infinity).help(Text("cpu.load.help", tableName: "CPUDetails")) - Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 25) - VStack(alignment: .leading, spacing: 3) { - Text("panel.uptime").foregroundStyle(.secondary) - AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600)) - .fontWeight(.medium) - } - }.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) - - - } - } - private var gpuCard: some View { - let summary = GPUUtilizationSummary(samples: samples) - return ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage), - status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" }, - statusHelp: Text("gpu.temperatureHelp"), - detail: snapshot.gpu?.coreCount.map { String(format: String(localized: "gpu.coreCountFormat"), $0) }) { - PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.gpu), - second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler), - color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"), - firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler", - expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) - if snapshot.gpuUsage == nil { Text("gpu.unavailable").foregroundStyle(.secondary) } - Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) - gpuActivity("gpu.rendererActivity", value: snapshot.gpu?.renderer, color: Color("MetricCPU")) - gpuActivity("gpu.tilerActivity", value: snapshot.gpu?.tiler, color: Color("SeriesSystem")) - Divider().padding(.vertical, 3) - Spacer(minLength: 0) - GPUStatisticsView(inUse: snapshot.gpu?.inUseMemory, allocated: snapshot.gpu?.allocatedMemory, - average: summary.average, peak: summary.peak) - Spacer(minLength: 0) - if let fans = snapshot.fans, !fans.isEmpty { - LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) { - ForEach(fans) { fan in - FanSpeedIndicator(title: fans.count == 2 ? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight") : LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm) - } - } - .padding(.horizontal, 7).padding(.vertical, 5) - .background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6)) - } - } - } - - private func gpuActivity(_ title: LocalizedStringKey, value: Double?, color: Color) -> some View { - HStack(spacing: 8) { - Text(title).frame(width: 65, alignment: .leading) - MetricProgressBar(value: value ?? 0, color: color).frame(height: 5) - .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value) - AnimatedMetricText(value: MetricFormat.percent(value)).frame(width: 30, alignment: .trailing) - }.font(.system(size: 10)).help(Text("gpu.pipelineHelp")) - } - private var memoryCard: some View { - ResourceCard(title: "metric.memory", symbol: "memorychip", color: Color("MemoryApplication"), - value: snapshot.memory.map { String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824) } ?? "--") { - PanelTrendChart(dates: samples.map(\.date), - first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } }, - second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed), - color: Color("MetricCPU"), secondColor: Color("MemoryApplication"), - thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1), - scaleLabel: MetricFormat.memory(snapshot.memory?.total), firstValueFormat: .memory, firstLabel: "gpu.totalUtilization", - secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed", - expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) - if let memory = snapshot.memory { - MemoryDetailsView(memory: memory) - } 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)), secondaryValue: "↑ " + MetricFormat.rate(total(\.upload)), valueColor: Color("MetricMemory"), secondaryValueColor: Color("SeriesUpload")) { - PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, plotHeight: 58, showsLegendValues: false).id(selectedInterface) - Divider().padding(.vertical, 4) - HStack(alignment: .top, spacing: 8) { - networkTotal("network.received", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received }), symbol: "arrow.down", color: Color("MetricMemory")) - Divider().frame(height: 32) - networkTotal("network.sent", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent }), symbol: "arrow.up", color: Color("SeriesUpload")) - Divider().frame(height: 32) - VStack(alignment: .leading, spacing: 4) { - HStack { - Text("network.status").foregroundStyle(.secondary) - Picker("panel.interface", selection: $selectedInterface) { - Text("network.all").tag("") - ForEach(snapshot.network ?? [], id: \.identity) { item in - Text(verbatim: item.name).tag(item.identity) - } - }.labelsHidden().controlSize(.mini).fixedSize() - } - HStack(spacing: 4) { - Circle().fill(networkStatusColor).frame(width: 5, height: 5) - Text(networkStatusLabel) - } - }.frame(maxWidth: .infinity, alignment: .leading) - }.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.65) - Divider().padding(.vertical, 4) - VStack(alignment: .leading, spacing: 5) { - Text("network.addresses").fontWeight(.medium).foregroundStyle(.secondary) - HStack(spacing: 8) { - networkAddress("network.public", address: publicIPAddress) - Divider().frame(height: 15) - networkAddress("network.local", address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first) - } - }.font(.system(size: 10)) - .padding(.horizontal, 7).padding(.vertical, 5) - .background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6)) - } - .task(id: publicIPRoute) { - publicIPAddress = nil - guard snapshot.networkPath == .available else { return } - let address = await PublicIPAddressService.shared.address(route: publicIPRoute) - guard !Task.isCancelled else { return } - publicIPAddress = address - } - } - private var publicIPRoute: String { - "\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")" - } - private func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View { - HStack(spacing: 4) { - Text(title).foregroundStyle(.secondary) - Text(verbatim: address ?? "--").monospacedDigit().textSelection(.enabled) - Spacer(minLength: 0) - if let address { - Button { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(address, forType: .string) - } label: { Image(systemName: "doc.on.doc") } - .buttonStyle(.plain).accessibilityLabel(Text("panel.copy")) - } - }.frame(maxWidth: .infinity, alignment: .leading).lineLimit(1).minimumScaleFactor(0.6) - } - private func networkTotal(_ title: LocalizedStringKey, value: String, symbol: String, color: Color) -> some View { - VStack(alignment: .leading, spacing: 4) { - Text(title).foregroundStyle(.secondary) - HStack(spacing: 3) { - Image(systemName: symbol).foregroundStyle(color) - AnimatedMetricText(value: value).fontWeight(.medium) - } - }.frame(maxWidth: .infinity, alignment: .leading) - } - private var networkStatusLabel: LocalizedStringKey { - switch snapshot.networkPath { - case .available: "network.pathAvailable" - case .unavailable: "network.pathUnavailable" - case .requiresConnection: "network.pathRequiresConnection" - case nil: "metric.waiting" - } - } - private var networkStatusColor: Color { - switch snapshot.networkPath { - case .available: .green - case .unavailable: .red - case .requiresConnection: .orange - case nil: .secondary - } - } - private var addressInterface: NetworkInterfaceMetrics? { - let name = selectedInterface.isEmpty ? snapshot.defaultNetworkInterface : network.first?.name - return snapshot.network?.first { $0.name == name && $0.active } - } - private var networkIntervals: [TimeInterval] { selectedInterface.isEmpty ? chartIntervals : (metrics.history.interfaces[selectedInterface] ?? []).map(\.expectedInterval) } - 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: snapshot.disk.map { String(format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") { - - - PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, plotHeight: 48) - Text("disk.physicalIO") - .font(.system(size: 9)).foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .trailing) - StorageDetailsView(disk: snapshot.disk, health: snapshot.diskHealth) { - showVolumes.toggle() - } - .popover(isPresented: $showVolumes) { - VStack(alignment: .leading, spacing: 8) { - Text("disk.homeVolume") - Text("panel.smartScope").foregroundStyle(.secondary) - Group { - 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) - } - }.padding(12).frame(width: 330) - } - - } - } - 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 { - PanelTrendChart( - dates: samples.map(\.date), - first: samples.map(\.battery), - second: samples.map(\.batteryPower), - color: Color("MetricBattery"), - secondColor: Color("SeriesUser"), - fixedScale: 1, - secondSeriesUsesAutonomousScale: true, - secondValueFormat: .watts, - firstLabel: "metric.battery", - secondLabel: batteryPowerLabel(battery), - expectedInterval: chartInterval, - boundaryDates: chartBoundaries, - intervals: chartIntervals - ) - Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) - HStack(alignment: .top, spacing: 10) { - VStack(spacing: 5) { - line("battery.health", MetricFormat.percent(battery.health)) - HStack { - Text("battery.powerSource").foregroundStyle(.secondary) - Spacer(minLength: 4) - Text(battery.externalPower ? "battery.acPower" : "battery.batterySource") - } - } - Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 32) - VStack(spacing: 5) { - line("battery.cycles", battery.cycles.map(String.init) ?? "--") - HStack { - Text("battery.timeEstimate").foregroundStyle(.secondary) - Spacer(minLength: 4) - if battery.externalPower { Text("battery.timeNotApplicable") } - else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") } - else { Text("battery.timeUnknown") } - } - } - } - .font(.system(size: 10)) - .lineLimit(1).minimumScaleFactor(0.72) - .frame(height: 32) - Spacer(minLength: 0) - Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) - VStack(alignment: .leading, spacing: 4) { - HStack { - Text("battery.highestEnergyProcess").fontWeight(.semibold) - Spacer() - Text("battery.cpuUsage").foregroundStyle(.secondary) - } - .font(.system(size: 10)) - let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? [] - if energyProcesses.isEmpty { - Text("metric.waiting").foregroundStyle(.secondary) - } else { - ForEach(energyProcesses) { process in - EnergyProcessListRow(process: process) - } - } - } - // Reserve the header and all three rows before process sampling completes. - .frame(height: 72, alignment: .top) - .lineLimit(1) - .help(Text("battery.energyProxyHelp")) - - } else { - Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary) - } - } - } private var controls: some View { HStack(spacing: 8) { HStack(spacing: 2) { @@ -501,55 +183,6 @@ struct MenuPanelView: View { } } -private struct EnergyProcessListRow: View { - let process: ProcessMetrics - @State private var icon: NSImage? - - private var progress: Double { - guard let value = process.cpu, value.isFinite else { return 0 } - return min(max(value, 0), 1) - } - - var body: some View { - HStack(spacing: 5) { - Group { - if let icon { - Image(nsImage: icon).resizable().interpolation(.high) - } else { - Image(systemName: "app.dashed").resizable().scaledToFit().padding(2) - } - } - .frame(width: 15, height: 15) - .accessibilityHidden(true) - Text(verbatim: process.name).lineLimit(1).truncationMode(.middle) - .frame(width: 66, alignment: .leading) - GeometryReader { proxy in - Capsule().fill(.primary.opacity(0.07)) - .overlay(alignment: .leading) { - Capsule().fill(Color("MetricCPU")) - .frame(width: proxy.size.width * progress, height: 4) - .clipped() - } - .clipShape(Capsule()) - } - .frame(height: 4) - .animation(.easeInOut(duration: 0.35), value: process.cpu) - AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--") - .foregroundStyle(Color("MetricCPU")) - .monospacedDigit().frame(width: 39, alignment: .trailing) - } - .font(.system(size: 10)) - .frame(height: 16) - .task(id: process.id) { - icon = NSRunningApplication(processIdentifier: process.id.pid)?.icon - if icon == nil, let path = process.path { - icon = NSWorkspace.shared.icon(forFile: path) - } - } - } -} - - private struct PanelControlButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { PanelControlButtonBody(isPressed: configuration.isPressed) { diff --git a/kymo/Features/MenuBar/PanelLayout.swift b/kymo/Features/MenuBar/PanelLayout.swift index dbe9e64..97196ce 100644 --- a/kymo/Features/MenuBar/PanelLayout.swift +++ b/kymo/Features/MenuBar/PanelLayout.swift @@ -2,12 +2,29 @@ import Foundation import CoreGraphics nonisolated enum PanelLayout { - static func resourceRowHeight(size: CGSize, coreRows: Int) -> CGFloat { - let compact = min(239, max(224, size.height - 581)) - let thirdRowExpansion: CGFloat = coreRows >= 3 ? 26 : 0 - return min(265, compact + thirdRowExpansion) + static let baseCardHeight: CGFloat = 280 + static func columns(width: CGFloat) -> Int { width >= 1160 ? 3 : width >= 900 ? 2 : 1 } + static func cardWidth(size: CGSize) -> CGFloat { + let count = columns(width: size.width) + return max(0, (size.width - 20 - CGFloat(count - 1) * 8) / CGFloat(count)) + } + /// Heights are assigned by physical row, including the battery/memory pair at two columns. + static func rowHeights(columns: Int, coreRows: Int, fanCount: Int) -> [CGFloat] { + let cpu = baseCardHeight + CGFloat(max(0, coreRows - 2)) * 26 + let gpu = baseCardHeight + CGFloat(max(0, (fanCount + 1) / 2 - 1)) * 26 + let heights = [cpu, gpu, baseCardHeight, baseCardHeight, baseCardHeight, baseCardHeight] + let count = max(1, min(3, columns)) + return stride(from: 0, to: heights.count, by: count).map { + heights[$0.. CGFloat { + rows.reduce(0, +) + CGFloat(max(0, rows.count - 1)) * 8 + } + static func needsResourceScroll(size: CGSize, rows: [CGFloat]) -> Bool { + // Outer padding, toolbar budget, two gaps, and the minimum process area. + resourceHeight(rows: rows) > size.height - 20 - 40 - 16 - 170 } - static func cardWidth(size: CGSize) -> CGFloat { max(0, (size.width - 36) / 3) } static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize { CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))), diff --git a/kymo/Features/MenuBar/ProcessTableView.swift b/kymo/Features/MenuBar/ProcessTableView.swift index 990b366..1d82afe 100644 --- a/kymo/Features/MenuBar/ProcessTableView.swift +++ b/kymo/Features/MenuBar/ProcessTableView.swift @@ -69,8 +69,7 @@ struct ProcessTableView: View { } } .font(.system(size: 12)).padding(10) - .modifier(PanelCardBackground(radius: 14)) - .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.primary.opacity(0.1))) + .modifier(CardSurface()) .onAppear { rebuild(retainOrder: false) } .onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && (byMemory ? rows.contains { $0.residentBytes != nil } : rows.contains { $0.cpu != nil })) } .onChange(of: search) { _, _ in rebuild(retainOrder: held) } @@ -92,7 +91,7 @@ struct ProcessTableView: View { } private var processTitle: some View { HStack(spacing: 8) { - Label("panel.processes", systemImage: "list.bullet.rectangle").fontWeight(.semibold) + Label("panel.processes", systemImage: "list.bullet.rectangle").font(PanelStyle.title) Text(verbatim: "\(snapshot?.readable ?? 0) / \(snapshot?.enumerated ?? 0) · \(rows.count)") .foregroundStyle(.secondary).help(Text("panel.coverage")) } diff --git a/kymo/Features/MenuBar/StorageDetailsView.swift b/kymo/Features/MenuBar/StorageDetailsView.swift index cf0add0..2d41719 100644 --- a/kymo/Features/MenuBar/StorageDetailsView.swift +++ b/kymo/Features/MenuBar/StorageDetailsView.swift @@ -4,65 +4,40 @@ struct StorageDetailsView: View { let disk: DiskMetrics? let health: DiskHealthMetrics? let showVolumes: () -> Void - @Environment(\.accessibilityReduceMotion) private var reduceMotion private let color = Color("MetricDisk") var body: some View { VStack(alignment: .leading, spacing: 4) { - Divider() - HStack { - Text("disk.distribution").fontWeight(.semibold).help(Text("disk.capacityScope")) - Spacer() - Text("disk.utilization").foregroundStyle(.secondary) - AnimatedMetricText(value: MetricFormat.percent(disk?.usage)).foregroundStyle(color) + CardSeparator() + CardSectionHeader(title: "disk.distribution", valueLabel: "disk.utilization", + value: MetricFormat.percent(disk?.usage), color: color) + .help(Text("disk.capacityScope")) + CapacityBar(values: [Double(disk.map { $0.total - min($0.total, $0.available) } ?? 0), Double(disk?.available ?? 0)], + colors: [color, Color("MemoryAvailable")], total: Double(disk?.total ?? 1)) + HStack(spacing: 4) { + CapacityField(title: "disk.used", value: MetricFormat.bytes(disk.map { $0.total - min($0.total, $0.available) }), color: color) + CapacityField(title: "memory.available", value: MetricFormat.bytes(disk?.available), color: Color("MemoryAvailable")) } - GeometryReader { proxy in - ZStack(alignment: .leading) { - Rectangle().fill(Color("MemoryAvailable")) - Rectangle().fill(color) - .frame(width: proxy.size.width * CGFloat(disk?.usage ?? 0)) - } - // Clip the whole track, with no minimum fill width for tiny values. - .clipShape(Capsule()) - .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: disk?.usage) - }.frame(height: 7).accessibilityHidden(true) - HStack { - capacity("disk.used", value: disk.map { $0.total - min($0.total, $0.available) }, tint: color) - capacity("memory.available", value: disk?.available, tint: Color("MemoryAvailable")) - } - Divider() + CardSeparator() HStack(alignment: .top, spacing: 8) { - VStack(alignment: .leading, spacing: 4) { - Text("disk.remainingLife").foregroundStyle(.secondary) + CardField(title: "disk.remainingLife") { AnimatedMetricText(value: MetricFormat.percent(health?.remainingLife)) - }.frame(maxWidth: .infinity, alignment: .leading) - Divider().frame(height: 30) - VStack(alignment: .leading, spacing: 4) { - Text("disk.powerOnHours").foregroundStyle(.secondary) + } + Divider().frame(height: 32) + CardField(title: "disk.powerOnHours") { AnimatedMetricText(value: health?.powerOnHours.map { "\($0) h" } ?? "--") - }.frame(maxWidth: .infinity, alignment: .leading) - Divider().frame(height: 30) - VStack(alignment: .leading, spacing: 4) { - Text("disk.localVolumes").foregroundStyle(.secondary) + } + Divider().frame(height: 32) + CardField(title: "disk.localVolumes") { Button(action: showVolumes) { HStack(spacing: 2) { Text("disk.viewDetails") Image(systemName: "chevron.right").font(.system(size: 8)) } }.buttonStyle(.plain) - }.frame(maxWidth: .infinity, alignment: .leading) - }.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) - }.padding(.top, 3) + } + }.font(PanelStyle.label).lineLimit(1) + } } - private func capacity(_ title: LocalizedStringKey, value: UInt64?, tint: Color) -> some View { - VStack(alignment: .leading, spacing: 3) { - HStack(spacing: 4) { - Circle().fill(tint).frame(width: 4, height: 4) - Text(title).foregroundStyle(.secondary) - } - AnimatedMetricText(value: MetricFormat.bytes(value)).fontWeight(.medium) - }.frame(maxWidth: .infinity, alignment: .leading) - .font(.system(size: 10)).lineLimit(1) - } } diff --git a/kymo/UI/Charts/PanelTrendChart.swift b/kymo/UI/Charts/PanelTrendChart.swift index 75bc0a7..317b49e 100644 --- a/kymo/UI/Charts/PanelTrendChart.swift +++ b/kymo/UI/Charts/PanelTrendChart.swift @@ -31,7 +31,7 @@ struct PanelTrendChart: View { var expectedInterval: TimeInterval = 2 var boundaryDates: Set = [] var intervals: [TimeInterval] = [] - var plotHeight: CGFloat = 58 + var plotHeight: CGFloat = PanelStyle.plotHeight var showsLegendValues = true @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var retainedScale: Double = 1 @@ -84,7 +84,7 @@ struct PanelTrendChart: View { if showsLegendValues { Text(verbatim: formatted(values.last ?? nil, format: format)).monospacedDigit() } - }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8) + }.font(PanelStyle.legend).lineLimit(1).minimumScaleFactor(0.8) } private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, index: Int) -> some View { @@ -181,7 +181,7 @@ struct PanelTrendChart: View { if let date = dates.first { Text(date, style: .time) } Spacer(minLength: 0) if let date = dates.last { Text(date, style: .time) } - }.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12) + }.font(PanelStyle.legend).foregroundStyle(.secondary).frame(height: 12) } .frame(maxWidth: .infinity) .onAppear { diff --git a/kymo/UI/Components/PanelStyle.swift b/kymo/UI/Components/PanelStyle.swift new file mode 100644 index 0000000..135df1f --- /dev/null +++ b/kymo/UI/Components/PanelStyle.swift @@ -0,0 +1,107 @@ +import SwiftUI + +/// Shared roles for the compact monitoring panel. Micro charts keep their own 8pt role. +enum PanelStyle { + static let title = Font.system(size: 13, weight: .semibold) + static let section = Font.system(size: 11, weight: .semibold) + static let label = Font.system(size: 10) + static let value = Font.system(size: 10, weight: .medium) + static let legend = Font.system(size: 9) + static let padding: CGFloat = 10 + static let gap: CGFloat = 8 + static let titleHeight: CGFloat = 20 + static let plotHeight: CGFloat = 58 +} + +struct CardSeparator: View { + var body: some View { + Rectangle().fill(.primary.opacity(0.08)).frame(height: 1) + .padding(.vertical, 4) + .accessibilityHidden(true) + } +} + +struct CardField: View { + let title: LocalizedStringKey + @ViewBuilder var content: () -> Content + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text(title).font(PanelStyle.label).foregroundStyle(.secondary).help(Text(title)).frame(height: 14) + content().font(PanelStyle.value).monospacedDigit().frame(height: 14) + } + .frame(maxWidth: .infinity, alignment: .leading) + .lineLimit(1) + } +} + +struct CardSurface: ViewModifier { + func body(content: Content) -> some View { + content.modifier(PanelCardBackground(radius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14))) + } +} + +struct CardInset: ViewModifier { + func body(content: Content) -> some View { + content.padding(.horizontal, 8).padding(.vertical, 5) + .background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6)) + } +} + +/// Segment widths are proportional to the supplied total, without minimum fills. +struct CapacityBar: View { + let values: [Double] + let colors: [Color] + let total: Double + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + var body: some View { + GeometryReader { bounds in + HStack(spacing: 0) { + ForEach(values.indices, id: \.self) { index in + Rectangle().fill(colors.isEmpty ? Color.clear : colors[index % colors.count]) + .frame(width: bounds.size.width * min(1, max(0, values[index] / max(1, total)))) + } + } + .clipShape(Capsule()) + .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: values) + } + .frame(height: 8) + .accessibilityHidden(true) + } +} + +struct CapacityField: View { + let title: LocalizedStringKey + let value: String + let color: Color + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 3) { + Circle().fill(color).frame(width: 4, height: 4) + Text(title).font(PanelStyle.label).foregroundStyle(.secondary).help(Text(title)) + }.frame(height: 14) + AnimatedMetricText(value: value).font(PanelStyle.value).frame(height: 14) + } + .frame(maxWidth: .infinity, alignment: .leading) + .lineLimit(1) + } +} + +struct CardSectionHeader: View { + let title: LocalizedStringKey + let valueLabel: LocalizedStringKey + let value: String + let color: Color + + var body: some View { + HStack { + Text(title).font(PanelStyle.section) + Spacer(minLength: 4) + Text(valueLabel).font(PanelStyle.label).foregroundStyle(.secondary) + AnimatedMetricText(value: value).font(PanelStyle.value).foregroundStyle(color) + }.frame(height: 16) + } +} diff --git a/kymo/UI/Components/ResourceCard.swift b/kymo/UI/Components/ResourceCard.swift index 8aee5e4..9788457 100644 --- a/kymo/UI/Components/ResourceCard.swift +++ b/kymo/UI/Components/ResourceCard.swift @@ -16,48 +16,55 @@ struct ResourceCard: View { @ViewBuilder var content: () -> Content var body: some View { - VStack(alignment: .leading, spacing: 3) { - HStack(alignment: .center, spacing: 6) { - Label { Text(title).foregroundStyle(statusWarning ? .red : .primary) } icon: { - Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color) - }.font(.system(size: 13, weight: .semibold)).fixedSize() - if let status { - Text(verbatim: status) - .font(.system(size: 10, weight: .medium)) - .foregroundStyle(statusWarning ? .red : color) - .padding(.horizontal, 6).padding(.vertical, 2) - .background((statusWarning ? Color.red : color).opacity(0.14), in: Capsule()) - .help(statusHelp ?? Text(verbatim: status)) - if let warningText { - warningText - .font(.system(size: 10)).foregroundStyle(.red).lineLimit(1).minimumScaleFactor(0.7) - } - } - if let detail { - Text(verbatim: detail) - .font(.system(size: 9, weight: .medium)).foregroundStyle(.secondary) - .padding(.horizontal, 5).padding(.vertical, 2) - .background(.primary.opacity(0.06), in: Capsule()) - .lineLimit(1).minimumScaleFactor(0.7) - } - Spacer(minLength: 0) + GeometryReader { bounds in + VStack(alignment: .leading, spacing: 4) { HStack(alignment: .center, spacing: 6) { - AnimatedMetricText(value: value) - .font(.system(size: 13, weight: .semibold)) - .foregroundStyle(valueColor ?? color) - if let secondaryValue { - AnimatedMetricText(value: secondaryValue).font(.system(size: 13, weight: .semibold)) - .foregroundStyle(secondaryValueColor ?? color) + Label { + Text(title).foregroundStyle(statusWarning ? .red : .primary) + } icon: { + Image(systemName: symbol).frame(width: 16, height: 16).foregroundStyle(statusWarning ? .red : color) + }.font(PanelStyle.title).fixedSize() + if let status { + Text(verbatim: status) + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(statusWarning ? .red : color) + .padding(.horizontal, 6).frame(height: 16) + .background((statusWarning ? Color.red : color).opacity(0.14), in: Capsule()) + .help(statusHelp ?? Text(verbatim: status)) + if let warningText { + warningText + .font(.system(size: 10)).foregroundStyle(.red).lineLimit(1) + } } - }.foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.65) + if let detail { + Text(verbatim: detail) + .font(.system(size: 10, weight: .medium)).foregroundStyle(.secondary) + .padding(.horizontal, 6).frame(height: 16) + .background(.primary.opacity(0.06), in: Capsule()) + .lineLimit(1) + } + Spacer(minLength: 0) + HStack(alignment: .center, spacing: 6) { + AnimatedMetricText(value: value) + .font(PanelStyle.title) + .foregroundStyle(valueColor ?? color) + if let secondaryValue { + AnimatedMetricText(value: secondaryValue).font(PanelStyle.title) + .foregroundStyle(secondaryValueColor ?? color) + } + }.foregroundStyle(color).lineLimit(1) + } + .frame(height: PanelStyle.titleHeight) + VStack(alignment: .leading, spacing: 4) { + content() + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } - content() + .font(PanelStyle.label) + .padding(PanelStyle.padding) + .frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading) } - .font(.system(size: 11)) - .padding(10) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - .modifier(PanelCardBackground(radius: 10)) - .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14))) + .modifier(CardSurface()) .overlayPreferenceValue(ChartTooltipPreference.self) { tooltip in GeometryReader { proxy in if let tooltip { diff --git a/kymoTests/PanelLayoutChecks.swift b/kymoTests/PanelLayoutChecks.swift index 6d2460f..f3acb68 100644 --- a/kymoTests/PanelLayoutChecks.swift +++ b/kymoTests/PanelLayoutChecks.swift @@ -13,14 +13,21 @@ import CoreGraphics precondition(visible.insetBy(dx: 16, dy: 16).contains(centered)) } } - for size in [CGSize(width: 1240, height: 820), CGSize(width: 1160, height: 810)] { - let compact = PanelLayout.resourceRowHeight(size: size, coreRows: 2) - let expanded = PanelLayout.resourceRowHeight(size: size, coreRows: 3) - let width = PanelLayout.cardWidth(size: size) - precondition(compact >= 224 && compact <= 239) - precondition(expanded == min(265, compact + 26)) - precondition(abs(3 * width + 16 - (size.width - 20)) < 0.001) + for width: CGFloat in [640, 899, 900, 1159, 1160, 1240] { + let size = CGSize(width: width, height: 820) + let columns = PanelLayout.columns(width: width) + let cardWidth = PanelLayout.cardWidth(size: size) + precondition(abs(CGFloat(columns) * cardWidth + CGFloat(columns - 1) * 8 - (width - 20)) < 0.001) + let rows = PanelLayout.rowHeights(columns: columns, coreRows: 3, fanCount: 6) + let requirements: [CGFloat] = [306, 332, 280, 280, 280, 280] + for index in requirements.indices { + precondition(rows[index / columns] >= requirements[index]) + } + precondition(rows.count == (6 + columns - 1) / columns) + precondition(PanelLayout.needsResourceScroll(size: CGSize(width: width, height: 600), rows: rows)) + precondition(!PanelLayout.needsResourceScroll(size: CGSize(width: width, height: 2400), rows: rows)) } + precondition(PanelLayout.rowHeights(columns: 2, coreRows: 2, fanCount: 0) == [280, 280, 280]) 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 @@ -36,6 +43,6 @@ import CoreGraphics 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") + print("PASS: physical-row heights, column breakpoints, width conservation, resource scrolling, visible-frame bounds/chrome/negative origins, 2000-row CPU/RSS projection, frozen order, path search and empty results") } }