fix(charts): 修复浮窗层级并平滑切频与曲线移出

This commit is contained in:
2026-11-03 12:07:01 +08:00
parent 36b8e32af3
commit 7ef92d9c21
17 changed files with 271 additions and 59 deletions
+4 -4
View File
@@ -39,9 +39,9 @@ Kymo 是一款 macOS 菜单栏常驻的资源监控工具,设计目标为「
`App` 持有一个 `MetricsStore`(MainActor、`@Observable`),注入菜单栏场景与面板。
仓库创建唯一 Task,调用 `SystemSampler` actor,在后台串行读取 `CPUMonitor`、
`MemoryMonitor` 与 `getloadavg`,返回 Sendable `MetricsSnapshot`,再回 MainActor 整体发布。
每次采样完成后等待当前间隔,不重叠快速采样。SamplingPreferences 以毫秒整数分别保存面板/后台间隔,100ms 步进、500ms–1800000ms,非法值归一化。前者在面板顶栏调整,后者在设置监控页调整。频率或可见性变化取消旧等待、递增发布代次并立即重排,不重置差分基线;未生效一侧偏好改变不唤醒当前调度。暂停优先于频率和可见性,恢复重新建立基线。
每次采样完成后等待当前间隔,不重叠快速采样。SamplingPreferences 以毫秒整数分别保存面板/后台间隔,100ms 步进、500ms–1800000ms,非法值归一化。前者在面板顶栏调整,后者在设置监控页调整。频率或可见性变化取消旧等待、递增快速快照发布代次并重排,不重置差分基线;改频率按上次发布时间计算新截止时刻,避免立即重复读取;开面板仍立即刷新。未生效一侧偏好改变不唤醒当前调度。暂停优先于频率和可见性,恢复重新建立基线。
SystemSampler 统一协调 SMART、电池健康、卷列表与进程的单次在途任务,快速链路不等待其完成;SMART/电池健康结果带时间戳,成功一小时、失败十分钟后重试,卷列表约三十秒刷新。任务完成清空在途槽;取消/隐藏不释放尚未结束的同步查询槽,不无限补发。
进程通过 sysctl 枚举并逐项读取 proc_taskallinfo/proc_pidpath;PID + 启动秒/微秒为身份,读取前后核对枚举身份,未知字段独立降级。CPU 计时为纳秒差分,单核 100%,RSS 不等同活动监视器内存。只在面板可见且未暂停时采样;关闭清空快照、监控器基线与缓存,迟到结果按代次拒绝,重新打开重建基线;其他用户受限行保留覆盖说明。Store 另以发布/可见性代次防止暂停或快速开关后发布旧结果。进程单次在途完成后通过 Sendable 回调立即发布当前代次结果,不等待可能长达 30min 的下一周期,不追加图表历史或新建轮询;快速快照保留同周期已先到的进程结果,防止覆盖为 nil。若快速关开时旧同步读取仍占在途槽,旧结果结束后接续最新可见代次的待办查询,不等下一长周期,仍仅一次在途。
进程通过 sysctl 枚举并逐项读取 proc_taskallinfo/proc_pidpath;PID + 启动秒/微秒为身份,读取前后核对枚举身份,未知字段独立降级。CPU 计时为纳秒差分,单核 100%,RSS 不等同活动监视器内存。只在面板可见且未暂停时采样;关闭清空快照、监控器基线与缓存,迟到结果按代次拒绝,重新打开重建基线;其他用户受限行保留覆盖说明。Store 另以发布/可见性代次防止暂停或快速开关后发布旧结果。进程单次在途完成后通过 Sendable 回调立即发布当前可见性/暂停代次结果,纯改频率不丢弃有效在途进程结果,不等待可能长达 30min 的下一周期,不追加图表历史或新建轮询;快速快照保留同周期已先到的进程结果,防止覆盖为 nil。若快速关开时旧同步读取仍占在途槽,旧结果结束后接续最新可见代次的待办查询,不等下一长周期,仍仅一次在途。
菜单栏由 Features/MenuBar 的 MenuPanelController 持有 NSStatusItem,仅显示模板 BrandMark。点击图标切换同一 NSPanel,所属屏幕优先按菜单栏按钮选择,水平居中、顶部留边并限制在 visibleFrame 内。NSPanel 允许成为 key 而不成为 main,不因失焦自动隐藏。可见期间注册被动本地/全局鼠标监听,不拦截外部点击;普通状态外部点击/应用失活关闭,固定时使用 floating 层级并忽略外部关闭请求。菜单图标、Esc/Cmd+W 和进入设置可显式隐藏面板,固定状态保留到本次进程结束;shutdown 复位,不持久化。隐藏时拆卸内容并移除鼠标监听。App 只装配生命周期与服务,Features 之间不横向依赖。
@@ -58,10 +58,10 @@ GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取
### 面板、历史与外观
- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线;breakBefore 标记在恢复、可见性/有效频率切换处断开。60 点代表样本数,时间跨度随真实间隔变化。
- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线;breakBefore 标记只在首次/暂停恢复处断开;每个样本及分接口历史保留自己的预期间隔,改频率不插入人为断点。60 点代表样本数,时间跨度随真实间隔变化。
- 当前正式入口为统一 `MenuPanelView`:第一排 CPU/GPU/电池,电池宽高比 4:3、CPU/GPU 均分余宽;第二排内存/存储/网络等宽。宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时两排完整布局,参考尺寸两排分别 230/240pt,进程区使用剩余空间(最小 170pt)。其他尺寸资源独立滚动,进程常驻;三列低高度仍保持上述比例与顺序。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,布局后约束完整 frame 原点并水平居中。NSPanel 固定/关闭策略和 key/main 资格已有独立检查;实际外部点击与多屏专项待补。
- `PanelWindowObserver` 仅观察所属窗口的屏幕/移动/缩放,测量尺寸并约束居中;可见性由 MenuPanelController 开关与内容挂载生命周期通知 Store,不根据失焦推断关闭。
- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值、显式中断标记和超过 max(5s, 当前间隔×2) 的间隙断线。图例始终显示最新值;悬浮时使用独立浮层显示历史时刻与各序列值,保留游标/交点,不覆盖图例数据。浮层不参与鼠标命中,不创建顶层窗口;背景 alpha=0.97 提高文字可读性。CPU 使用青绿/紫红/金色及实线/虚线/点线区分,未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示,无独立 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%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。
- 各卡标题与彩色主值均为 13pt、共享基线同行,数值组件复用系统 numericText 数字翻动/模糊过渡并遵循减少动态效果;进程行不施加该动画。PanelCard 资源深浅色 alpha=0.68,减少透明度时改为系统实色窗口背景。操作强调色仍由偏好决定;刷新控件、图钉、保持唤醒、暂停/恢复、设置、退出胶囊位于顶栏右侧。顶栏左侧为品牌、版本及缓存的本机产品名/芯片,产品名不可读时退回 hw.model,不读取序列号。原采样状态/更新时间与底栏移除。
- NetworkPathObserver 从系统路径的偏好首位接口提供默认接口名称([NWPath 接口按偏好排序](https://developer.apple.com/documentation/network/nwpath)),网络卡默认直接展示该接口的 IPv4,若无则展示 IPv6;未知不随意选择另一个接口。手动切换接口时同步展示该接口地址。getifaddrs 元数据、接口速率和路径状态仍独立采集;不把接口 IP 当作公网出口地址。
- 进程表支持 CPU/内存(RSS)排序、名称/PID/路径搜索、同卡内选中路径展示/复制与读取覆盖计数。投影按采样/筛选/排序事件计算并缓存,不在 body 或滚动中重复排序;hover、搜索/焦点和选中冻结旧身份顺序,新增项追加到其后。完整路径在表下方同卡展示以保持固定行高;选中进程退出短暂提示后移除,关闭面板拆卸表并清掉路径状态。路径不持久化,不收集参数或环境变量。
+1 -1
View File
@@ -50,7 +50,7 @@
- 差分类指标(CPU、网络、磁盘 IO)采样器内部持有上一次快照,自行做差分;
- 菜单栏仅显示品牌图标,指标在面板展示;
- 采样完成后按可见性等待:面板默认 2s,关闭默认 5s;两者独立持久化、100ms 步进、500ms–30min,面板顶栏调前者,设置监控页调后者;顶栏暂停/恢复。
- 改有效频率或开关面板立即取消旧等待并重排,纯改频率不重置差分基线;暂停不会被偏好变更唤醒。进程完成单次读取后立即发布有效代次结果,隐藏不查询进程。60 点历史跨度随间隔变化,显式边界防止跨暂停/频率切换连线。
- 改有效频率或开关面板立即取消旧等待并重排,频率修改以距上次发布的剩余间隔等待、避免重复快采样;纯改频率不重置差分基线;暂停不会被偏好变更唤醒。进程完成单次读取后立即发布有效代次结果,隐藏不查询进程。60 点历史跨度随间隔变化,显式边界保留暂停中断,样本各自携带间隔元数据以平滑连接有效切频历史。
磁盘寿命通过用户授权的嵌入式非沙盒 XPC 服务低频读取 `diskutil info -plist`,主应用保留沙盒。NVMe 寿命消耗字段换算预计剩余寿命,通电小时读取 128 位计数的可表示部分;高位非零不截断展示。SMART 数据是物理设备级,多个 APFS 卷不重复合算,缺失/多物理存储显示 --。服务固定只读查询,无管理员权限或系统开机项,详见 disk-smart-helper-plan.md。
+9 -1
View File
@@ -11,7 +11,7 @@
- Core 新增独立 SamplingPreferences,保存前台/后台毫秒整数与边界归一化;MetricsStore 仍为唯一采样调度器,频率/可见性改变取消旧等待并按发布代次重排,快速采样不重叠,隐藏后不采进程。首次/恢复重建基线,纯频率变化不重置 CPU/网络基线。暂停始终高于频率与可见性。
- Features/Settings 新增监控设置页,调整后台间隔;UI 提供通用区间输入控件,无 Features 横向依赖。
- UI/Charts 的图例始终显示最新值,浮层单独显示时间、各序列读数和色块,游标/交点保留;浮层约束在卡片绘图区附近且不参与鼠标命中,不创建新顶层窗口。复合图引入区分明显的资产色及线型。
- 历史保持 60 点有界,间隔可变后按真实时间轴与当前预期间隔断线,显式中断标记防止跨暂停/切频率补线。电池宽度为第一排高度的 4/3,CPU/GPU 均分余宽;卡片主值与标题均 13pt。
- 历史保持 60 点有界,样本保存各自预期间隔,按真实时间轴判断长空档;首次/暂停恢复明确中断,单纯切频连续。UI 过渡缓冲最多 61 点以保留移出样本。电池宽度为第一排高度的 4/3,CPU/GPU 均分余宽;卡片主值与标题均 13pt。
## 实施顺序
@@ -34,3 +34,11 @@
显式进入设置时隐藏面板,避免 floating 面板遮挡设置;固定状态保留至本次退出。AppKit 生命周期补齐标准菜单与快捷键。独立悬浮背景最终使用 alpha=0.97 的深浅资源以提高文字可读性,不另建窗口。归一化属性使用底层存储避免观察 setter 自写回递归。
补充并发边界:快速关闭/重开遇到旧进程同步读取占槽时,结束后立即接续当前可见代次的待办查询;注入延迟读取验证无需下一次 sample、峰值在途为 1,不额外轮询。
### 连续趋势与材质修订(2026-11-03)
用户实测提出:调整间隔时出现人为断点;满 60 点时左侧先删一段再平移;浮窗需要半透明模糊。Core 只在首次/暂停恢复标记真实中断,改有效频率按上次发布时刻重排等待,避免立即重复读取得到无 tick 差分;每个历史样本保留其预期间隔,图表按相邻两点的间隔判断缺测,不能用当前较短间隔重判过去的慢采样。真实缺失、暂停和异常长空档继续断开。
UI 为过渡保留唯一一个移出样本(最多 61 点),域从旧首尾连续插值到新首尾,不能在动画首帧删除旧左端点;静态历史仍最多 60 点。独立卡片根浮层继续保留,背景改为 withinWindow 原生 popover 模糊材质并遵循减少透明度。验证切频率边界、慢到快历史连续性、缺测/暂停、满容量起止/中间几何和有界缓存,以及深浅重叠浮层渲染;不把几何检查当作完整主观动效验收。
本次连续趋势修订代码与独立检查已完成:慢到快连续性、真实中断、61 点过渡与起中止域、改频率期间的在途进程结果、深浅模糊浮层重叠和满容量追加操作已验证,完整主观动效/正式原生事件边界见验证记录。
+4
View File
@@ -258,3 +258,7 @@ xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build
### 固定、居中与双刷新频率修订(2026-11-03)
用户进一步要求独立悬浮小浮层、区分序列配色、图钉、前台/后台独立频率、电池 4:3、水平居中及标题/主值同字号。已按 [固定面板与刷新实施计划](pinned-panel-refresh-plan.md) 实现,取代前述 MenuBarExtra 容器、1:1 电池与固定 2s 调度。两种间隔默认 2s/5s、100ms 步进、500ms–30min;固定状态仅内存保存。改频率/可见性立即重排,历史带显式中断;进程完成结果无需等待下一长周期。Debug/Release、独立采样/窗口/几何/资源与普通窗口 UI 验证结果见验证记录,不把窗口策略单测或浮层渲染样例当作实际鼠标事件验收。整体长时性能与多屏/完整可访问性仍未完成。
### 连续趋势修订(2026-11-03)
取代上一轮“切频插入历史中断”的策略:只在首次/暂停恢复明确断开,样本保留各自的预期间隔以正确呈现慢到快历史,改频率按下一截止时刻等待,不强制再读一个紧邻快照。满容量追加使用最多 61 点的独立 UI 帧保留移出点,旧/新时间域连续插值,防止先丢左侧再平移。浮层在卡片根层绘制,使用 withinWindow 半透明模糊材质。对应方案与边界验证见 pinned-panel-refresh-plan.md 和 unified-panel-validation.md;不将单次截图等同完整主观动效验收。
+18
View File
@@ -92,3 +92,21 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条
能力边界:直接读取本轮非 main 的 NSPanel 超时(首轮约 295s,后续短超时),普通主窗口能读;暂不能据此归因权限缺失或断言所有 NSPanel 都不可操作。临时尝试常规激活、辅助窗口及主焦点资格,最终采用标准 NSWindow 承载相同 SwiftUI 内容验证控件;这些临时改动未进入正式 Target。浅色浮层截图使用仅临时源码的悬浮状态注入,确认历史时间/读数在独立浮层、图例保持最新值(截图中系统读数与图例不同),不作为真实鼠标悬浮事件投递通过的证据。最终高不透明浮层底色由编译资源检查覆盖。
未验证:正式菜单栏图标开关、真实系统外部点击在固定/未固定两种状态下的投递、实际悬浮与子 popover 焦点组合、多屏/全屏/刘海屏、最终 NSPanel 玻璃手感、减少动态/透明度完整矩阵及长时资源预算。进入设置属于显式操作,会隐藏面板避免固定窗口遮挡,重开保留本次固定状态。独立测试包标识/签名不同导致 SMART 未知,不将其视为主产品读取回归。测试前记录已有用户 Xcode 副本 PID 16854,未终止该路径;只清理本轮 /private/tmp 测试副本、脚本、构建及隔离偏好。
### 图表浮窗层级修复(2026-11-03)
用户截图确认时间轴末端与卡片字段绘制在浮窗上方。原图表内 overlay 的 zIndex 只在局部布局容器生效,不能保证覆盖外部兄弟视图。现由图表通过 Anchor Preference 传递绘图区锚点、悬浮点和浮窗内容,ResourceCard 在所有内容/边框之后的根 overlay 绘制;不另建窗口,不改变悬浮取样和图例语义。浮窗按实际内容测量,并在卡片局部坐标中约束位置,再转换到 Layout 放置坐标;浮层不参与命中。
使用独立标准窗口加载本轮实际 ResourceCard、ChartTooltipLayer 和图表源码,只在临时图表副本注入悬浮状态。固定样例包含真实格式的 11:15 时间轴末端、额外的右对齐 11:15 字段及两行核心字段,刻意让浮窗跨过这些区域;浅色与深色截图均确认外部文字在浮窗之下、浮窗读数完整。该检查证明渲染层级与边缘放置,不扩大为真实鼠标悬浮事件或正式 NSPanel 全路径验收。Debug 构建通过;本轮无新测试 Target,也未添加重复实现的单元测试。用户已有 Xcode 副本 PID 20754 保留,仅清理本轮临时测试包与构建。
### 切频连续性、左端移出与模糊材质(2026-11-03,接续上一修复)
用户提供 GPU 切频断点及左端先消失一段的截图。确认两个独立原因:Store 的所有 reschedule 都插入 breakBefore;绘图直接使用已删除最左点的 60 点新历史,再插值旧/新时间域。
- 改频率不再产生中断标记,按距上次发布的剩余间隔重排,避免紧接上一快照立即再读造成 CPU 无 tick 差分。首次/暂停恢复仍有显式中断,缺失值不补零。每个历史样本和分接口样本保存自身预期间隔,按相邻两点的较大间隔判断长空档,不能用新的快频率重判旧慢历史。进程发布使用可见性/暂停代次,切频不丢弃当前有效的在途结果;频率等待与进程读取互不阻塞。
- PanelCurveFrame 作为 UI 渲染帧,在满容量追加时保留唯一一个移出点,最多 61 点,真实历史仍最多 60。旧首尾时间域连续插值到新首尾域,移出线段被 viewport 连续裁出。动画任务 ID 改为已提交的帧状态,确保开始状态先提交。没有独立 Timer 或后台动画循环。
- 浮层继续由卡片根 overlay 绘制,改为 NSVisualEffectView 的 popover/withinWindow 背景模糊图表和字段,轻叠 PanelTooltip 资源色;减少透明度时实色回退。材质 NSView 显式 hitTest 透传,不拦截图表操作。
通过:最终 Debug/Release 构建;PanelCurveChecks 验证慢到快的已有历史继续连线、暂停/缺失仍断开、61 点移出帧的旧 60 点完整保留,并检查 0/25/50/75/100% 时左边界一直被有效线段跨过、起止域和新点位置正确。SamplingIntervalChecks 验证改频率无 breakBefore、采样间隔元数据、无重复快采样,以及慢进程读取途中改到 30min 后仍即时发布该在途结果;既有延迟单次在途/快速关开、暂停优先、持久化边界检查继续通过。UnifiedPanelChecks 和 SamplingChecks 回归实际采样、可见性及暂停恢复通过。
渲染证据:独立标准窗口中,使用实际 ResourceCard、浮层根 overlay 和 withinWindow 材质,在浅/深两种模式下确认历史浮层跨过 11:15 刻度和右对齐字段,文字与模糊层叠放正常。浮层使用临时源码注入并保持悬浮状态,未改正式手势代码,不当作真实鼠标事件验收。另用实际 PanelTrendChart 源码与 60 点固定历史、Append 按钮执行追加并截图,左边界保持曲线覆盖;完整连续帧的主观手感、正式 NSPanel 原生事件/多屏/系统辅助功能开关矩阵仍需实机验收。临时样例、源码与构建清理,不操作用户已有应用。
+5 -3
View File
@@ -14,6 +14,7 @@ nonisolated struct TrendSample: Sendable {
var cpuUser: Double?
var cpuSystem: Double?
var breakBefore = false
var expectedInterval: TimeInterval = 2
}
/// Bounded sampling history; no timer or UI visibility dependence.
@@ -22,18 +23,18 @@ nonisolated struct MetricHistory: Sendable {
private(set) var samples: [TrendSample] = []
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:]
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false) {
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false, expectedInterval: TimeInterval = 2) {
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore))
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore, expectedInterval: expectedInterval))
let current = snapshot.network ?? []
let keys = Set(current.map(\.identity))
interfaces = interfaces.filter { keys.contains($0.key) }
for item in current {
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload))
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload, expectedInterval: expectedInterval))
if interfaces[item.identity, default: []].count > Self.capacity { interfaces[item.identity]?.removeFirst() }
}
if samples.count > Self.capacity { samples.removeFirst(samples.count - Self.capacity) }
@@ -44,4 +45,5 @@ nonisolated struct InterfaceTrendSample: Sendable {
let date: Date
let download: Double?
let upload: Double?
var expectedInterval: TimeInterval = 2
}
+20 -8
View File
@@ -12,15 +12,17 @@ final class MetricsStore {
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler = SystemSampler()
@ObservationIgnored private let sampler: SystemSampler
@ObservationIgnored private var scheduledInterval = 0
@ObservationIgnored private var needsHistoryBoundary = true
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
init(sampling: SamplingPreferences? = nil) {
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
self.sampler = sampler
self.sampling = sampling ?? SamplingPreferences()
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused, self.effectiveMilliseconds != self.scheduledInterval else { return }
self.reschedule(reset: false)
self.reschedule(reset: false, sampleImmediately: false)
}
start()
}
@@ -31,22 +33,30 @@ final class MetricsStore {
reschedule(reset: true)
}
private func reschedule(reset: Bool) {
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
generation += 1
task?.cancel()
needsHistoryBoundary = true
needsHistoryBoundary = needsHistoryBoundary || reset
scheduledInterval = effectiveMilliseconds
var delay = Duration.zero
if !sampleImmediately, let lastPublishedAt {
delay = max(.zero, .milliseconds(effectiveMilliseconds) - lastPublishedAt.duration(to: .now))
}
let initialDelay = delay
let currentGeneration = generation
task = Task { [weak self, sampler] in
guard !Task.isCancelled else { return }
if initialDelay > .zero {
do { try await Task.sleep(for: initialDelay) } catch { return }
}
if reset { await sampler.reset() }
while !Task.isCancelled {
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.generation == currentGeneration, self.visibilityGeneration == visibleGeneration,
guard let self, self.visibilityGeneration == visibleGeneration,
self.isPanelVisible, !self.isPaused else { return }
self.snapshot.processes = processes
if self.snapshot.processes.map({ $0.date > processes.date }) != true { self.snapshot.processes = processes }
}
})
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
@@ -56,7 +66,8 @@ final class MetricsStore {
next.processes = completed
}
self?.snapshot = next
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true)
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
self?.lastPublishedAt = .now
self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next)
let interval = self?.effectiveMilliseconds ?? 5_000
@@ -70,6 +81,7 @@ final class MetricsStore {
if isPaused { start() }
else {
generation += 1
visibilityGeneration += 1
task?.cancel()
task = nil
Task { await sampler.setProcessVisible(false) }
+7 -5
View File
@@ -15,6 +15,7 @@ struct MenuPanelView: View {
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<Date> { Set(samples.filter(\.breakBefore).map(\.date)) }
private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 }
@@ -95,7 +96,7 @@ struct MenuPanelView: View {
}
private func chart(_ key: KeyPath<TrendSample, Double?>, 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)
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) }
@@ -106,7 +107,7 @@ struct MenuPanelView: View {
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: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries)
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
if let cpu = snapshot.cpu {
HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) }
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 5) {
@@ -143,7 +144,7 @@ struct MenuPanelView: View {
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), expectedInterval: chartInterval, boundaryDates: chartBoundaries)
scaleLabel: MetricFormat.bytes(snapshot.memory?.total), expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
if let m = snapshot.memory {
GeometryReader { geometry in
@@ -182,7 +183,7 @@ struct MenuPanelView: View {
Text(verbatim: "\(item.name) · \(item.addresses.first(where: { !$0.contains(":") }) ?? item.addresses.first ?? "--")")
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.8).textSelection(.enabled)
} else { Text("panel.addressUnknown").foregroundStyle(.secondary) }
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries).id(selectedInterface)
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals).id(selectedInterface)
if !network.isEmpty && total(\.download) == nil { Text("panel.rateBaseline").foregroundStyle(.secondary) }
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 {
@@ -222,6 +223,7 @@ struct MenuPanelView: View {
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) }
@@ -229,7 +231,7 @@ struct MenuPanelView: 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("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries)
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
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" } ?? "--") }
+36
View File
@@ -0,0 +1,36 @@
import SwiftUI
/// Charts export their plot anchor; the owning card draws the tooltip above all content.
struct ChartTooltipPresentation {
let plot: Anchor<CGRect>
let point: CGPoint
let content: AnyView
}
struct ChartTooltipPreference: PreferenceKey {
static var defaultValue: ChartTooltipPresentation? { nil }
static func reduce(value: inout ChartTooltipPresentation?, nextValue: () -> ChartTooltipPresentation?) {
if let next = nextValue() { value = next }
}
}
/// Measures the actual localized tooltip, then keeps it inside the card.
struct ChartTooltipLayer: Layout {
let point: CGPoint
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
proposal.replacingUnspecifiedDimensions()
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
guard let tooltip = subviews.first else { return }
let width = min(180, max(1, bounds.width - 20))
let tooltipProposal = ProposedViewSize(width: width, height: nil)
let size = tooltip.sizeThatFits(tooltipProposal)
let x = min(max(10, point.x + 12), max(10, bounds.width - size.width - 10))
let below = point.y + 10
let preferredY = below + size.height <= bounds.height - 10 ? below : point.y - size.height - 10
let y = min(max(10, preferredY), max(10, bounds.height - size.height - 10))
tooltip.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading, proposal: tooltipProposal)
}
}
+36
View File
@@ -0,0 +1,36 @@
import Foundation
/// A render frame may keep one outgoing point beyond the bounded 60-sample history.
nonisolated struct PanelCurveFrame {
let dates: [Date]
let series: [[Double?]]
let intervals: [TimeInterval]
let boundaryDates: Set<Date>
struct Domain {
let begin: TimeInterval
let end: TimeInterval
func position(_ date: Date) -> Double {
end > begin ? (date.timeIntervalSinceReferenceDate - begin) / (end - begin) : 1
}
}
static func domain(previousBegin: Date?, previousEnd: Date?, begin: Date, end: Date, progress: Double) -> Domain {
let progress = min(1, max(0, progress))
return Domain(begin: (previousBegin ?? begin).timeIntervalSinceReferenceDate * (1 - progress) + begin.timeIntervalSinceReferenceDate * progress,
end: (previousEnd ?? end).timeIntervalSinceReferenceDate * (1 - progress) + end.timeIntervalSinceReferenceDate * progress)
}
static func transition(from old: Self, to new: Self) -> Self {
guard old.dates.count > 1, old.dates.count == new.dates.count,
Array(old.dates.dropFirst()) == Array(new.dates.dropLast()),
let outgoing = old.dates.first else { return new }
let series = new.series.enumerated().map { index, values -> [Double?] in
let previous = index < old.series.count ? old.series[index] : []
return previous.isEmpty && values.isEmpty ? [] : [previous.first ?? nil] + values
}
return Self(dates: [outgoing] + new.dates, series: series,
intervals: [old.intervals.first ?? 2] + new.intervals,
boundaryDates: new.boundaryDates.union(old.boundaryDates.intersection([outgoing])))
}
}
+8 -2
View File
@@ -13,13 +13,19 @@ nonisolated enum PanelCurveGeometry {
return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast())
}
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = []) -> [[Sample]] {
static func allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval {
guard index > 0, index < intervals.count else { return fallback }
let pair = [intervals[index - 1], intervals[index]].filter { $0.isFinite && $0 > 0 }
return pair.isEmpty ? fallback : max(5, (pair.max() ?? 2) * 2)
}
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = []) -> [[Sample]] {
var result: [[Sample]] = []
var run: [Sample] = []
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
for index in dates.indices {
guard index < values.count, let value = values[index], value.isFinite else { flush(); continue }
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > maximumGap || dates[index] <= dates[index - 1]) { flush() }
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > allowedGap(at: index, intervals: intervals, fallback: maximumGap) || dates[index] <= dates[index - 1]) { flush() }
run.append(Sample(date: dates[index], value: value))
}
flush()
+43 -32
View File
@@ -16,6 +16,7 @@ struct PanelTrendChart: View {
var thirdLabel: LocalizedStringKey = "cpu.system"
var expectedInterval: TimeInterval = 2
var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = []
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@@ -24,7 +25,14 @@ struct PanelTrendChart: View {
@State private var previousBegin: Date?
@State private var previousEnd: Date?
@State private var progress: CGFloat = 1
@State private var lastFrame: PanelCurveFrame?
@State private var displayedFrame: PanelCurveFrame?
private var inputFrame: PanelCurveFrame {
PanelCurveFrame(dates: dates, series: [first, second, third],
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
boundaryDates: boundaryDates)
}
private var maximum: Double { max(1, (first + second + third).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
private var index: Int? {
@@ -62,7 +70,7 @@ struct PanelTrendChart: View {
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
}
.font(.system(size: 10)).padding(8)
.background(Color("PanelTooltip"), in: .rect(cornerRadius: 7))
.background { TooltipMaterialBackground() }
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
.shadow(color: .black.opacity(0.2), radius: 5, y: 2)
}
@@ -86,8 +94,10 @@ struct PanelTrendChart: View {
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: 58)
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(dates: dates, series: [first, second, third], colors: [color, secondColor, thirdColor],
scale: scale, maximumGap: max(5, expectedInterval * 2), boundaryDates: boundaryDates, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor],
scale: scale, maximumGap: max(5, expectedInterval * 2),
targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last,
previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
Path { path in
@@ -114,17 +124,11 @@ struct PanelTrendChart: View {
}
}
.clipped()
.overlay(alignment: .topLeading) {
if let hoverPoint, let index {
tooltip(index: index)
.frame(width: min(180, proxy.size.width))
.offset(x: min(max(0, hoverPoint.x + 12), max(0, proxy.size.width - 180)),
y: min(hoverPoint.y + 10, proxy.size.height - 12))
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
}.frame(height: 58).zIndex(10)
}.frame(height: 58)
.anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in
guard let hoverPoint, let index else { return nil }
return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index)))
}
}
HStack {
if let date = dates.first { Text(date, style: .time) }
@@ -133,40 +137,47 @@ struct PanelTrendChart: View {
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12)
}
.frame(maxWidth: .infinity)
.zIndex(hoveredDate == nil ? 0 : 20)
.onAppear { retainedScale = maximum }
.onChange(of: dates) { old, new in
.onAppear { retainedScale = maximum; lastFrame = inputFrame; displayedFrame = inputFrame }
.onChange(of: dates) { _, _ 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 }
let append = PanelCurveGeometry.isAppend(from: old, to: new, maximumGap: max(5, expectedInterval * 2)) && !(new.last.map { boundaryDates.contains($0) } ?? false)
let next = inputFrame
let old = lastFrame
let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2))
let append = old.map { PanelCurveGeometry.isAppend(from: $0.dates, to: next.dates, maximumGap: gap) } == true
&& !(next.dates.last.map { boundaryDates.contains($0) } ?? false)
let animated = append && !reduceMotion
var transaction = Transaction(); transaction.disablesAnimations = true
withTransaction(transaction) {
previousBegin = append && !reduceMotion ? old.first : nil
previousEnd = append && !reduceMotion ? old.last : nil
progress = previousBegin == nil ? 1 : 0
lastFrame = next
displayedFrame = next
if animated, let old { displayedFrame = PanelCurveFrame.transition(from: old, to: next) }
previousBegin = animated ? old?.dates.first : nil
previousEnd = animated ? old?.dates.last : nil
progress = animated ? 0 : 1
}
}
.task(id: dates.last) {
.task(id: lastFrame?.dates.last) {
guard progress == 0, !reduceMotion else { return }
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
withAnimation(.easeInOut(duration: 0.35)) { progress = 1 }
}
.onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil } }
.onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil; lastFrame = inputFrame; displayedFrame = inputFrame } }
.accessibilityElement(children: .combine)
}
}
private struct PanelCurveCanvas: View, Animatable {
let dates: [Date]
let series: [[Double?]]
let frame: PanelCurveFrame
let colors: [Color]
let scale: Double
let maximumGap: TimeInterval
let boundaryDates: Set<Date>
let targetBegin: Date?
let targetEnd: Date?
let previousBegin: Date?
let previousEnd: Date?
var progress: CGFloat
@@ -187,14 +198,14 @@ private struct PanelCurveCanvas: View, Animatable {
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
}
context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5)
guard let first = dates.first, let last = dates.last else { return }
let begin = (previousBegin ?? first).timeIntervalSinceReferenceDate * (1 - progress) + first.timeIntervalSinceReferenceDate * progress
let end = (previousEnd ?? last).timeIntervalSinceReferenceDate * (1 - progress) + last.timeIntervalSinceReferenceDate * progress
for (seriesIndex, entry) in zip(series, colors).enumerated() {
guard let first = targetBegin, let last = targetEnd else { return }
let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd,
begin: first, end: last, progress: Double(progress))
for (seriesIndex, entry) in zip(frame.series, colors).enumerated() {
let (values, tint) = entry
for run in PanelCurveGeometry.runs(dates: dates, values: values, maximumGap: maximumGap, boundaryDates: boundaryDates) {
for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) {
let points = run.map { item in
CGPoint(x: end > begin ? size.width * (item.date.timeIntervalSinceReferenceDate - begin) / (end - begin) : size.width,
CGPoint(x: size.width * domain.position(item.date),
y: size.height * (1 - min(1, max(0, item.value / scale))))
}
guard let start = points.first, let finish = points.last else { continue }
+13
View File
@@ -30,5 +30,18 @@ struct ResourceCard<Content: View>: View {
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.modifier(PanelCardBackground(radius: 10))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
.overlayPreferenceValue(ChartTooltipPreference.self) { tooltip in
GeometryReader { proxy in
if let tooltip {
let plot = proxy[tooltip.plot]
ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y)) {
tooltip.content.fixedSize(horizontal: false, vertical: true)
}
.frame(width: proxy.size.width, height: proxy.size.height)
}
}
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
}
@@ -0,0 +1,31 @@
import SwiftUI
import AppKit
/// Within-window blending blurs the chart and labels below the card's root overlay.
struct TooltipMaterialBackground: View {
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
var body: some View {
Group {
if reduceTransparency { Color(nsColor: .windowBackgroundColor) }
else {
WithinWindowMaterial()
.overlay(Color("PanelTooltip").opacity(0.12))
}
}.clipShape(.rect(cornerRadius: 7))
}
}
private struct WithinWindowMaterial: NSViewRepresentable {
func makeNSView(context: Context) -> NSVisualEffectView {
let view = PassthroughVisualEffectView()
view.material = .popover
view.blendingMode = .withinWindow
view.state = .active
return view
}
func updateNSView(_ view: NSVisualEffectView, context: Context) {}
}
private final class PassthroughVisualEffectView: NSVisualEffectView {
override func hitTest(_ point: NSPoint) -> NSView? { nil }
}
+17 -1
View File
@@ -16,6 +16,22 @@ import Foundation
precondition(PanelCurveGeometry.runs(dates: slow, values: [0.1, 0.2, 0.3], maximumGap: 3600).count == 1)
precondition(PanelCurveGeometry.runs(dates: slow, values: [0.1, 0.2, 0.3], maximumGap: 3600, boundaryDates: [slow[1]]).count == 2)
precondition(PanelCurveGeometry.isAppend(from: Array(slow.prefix(2)), to: slow, maximumGap: 3600))
print("PASS: timestamp append/full history, pause/reset, missing/nonfinite data, short series and disconnected curves")
precondition(PanelCurveGeometry.runs(dates: slow, values: [0.1, 0.2, 0.3], maximumGap: 5, intervals: [1800, 1800, 0.5]).count == 1)
precondition(PanelCurveGeometry.runs(dates: slow, values: [0.1, 0.2, 0.3], maximumGap: 5, boundaryDates: [slow[2]], intervals: [1800, 1800, 0.5]).count == 2)
let old = PanelCurveFrame(dates: dates, series: [Array(repeating: 0.3, count: 60), []], intervals: Array(repeating: 2, count: 60), boundaryDates: [])
let next = PanelCurveFrame(dates: Array(dates.dropFirst()) + [dates.last!.addingTimeInterval(2)], series: [Array(repeating: 0.3, count: 59) + [0.4], []], intervals: Array(repeating: 2, count: 60), boundaryDates: [])
let transition = PanelCurveFrame.transition(from: old, to: next)
precondition(transition.dates.count == 61 && transition.dates.first == old.dates.first)
precondition(transition.series[0].first! == 0.3 && transition.series[0].last! == 0.4 && transition.series[1].isEmpty)
precondition(Array(transition.series[0].prefix(60)) == old.series[0])
for progress in [0.0, 0.25, 0.5, 0.75, 1.0] {
let domain = PanelCurveFrame.domain(previousBegin: old.dates.first, previousEnd: old.dates.last,
begin: next.dates.first!, end: next.dates.last!, progress: progress)
let left = domain.position(transition.dates[0]), right = domain.position(transition.dates[1])
precondition(left <= 0 && right >= 0, "Outgoing segment must cover the left boundary throughout the animation")
if progress == 0 { precondition(abs(left) < 0.000001 && abs(domain.position(old.dates.last!) - 1) < 0.000001) }
if progress == 1 { precondition(abs(right) < 0.000001 && abs(domain.position(next.dates.last!) - 1) < 0.000001) }
}
print("PASS: timestamp append/full history, pause/reset, missing/nonfinite data, short series, cadence continuity, pause boundaries and 61-point left-edge animation geometry")
}
}
+1 -1
View File
@@ -140,7 +140,7 @@ swiftc -parse-as-library -module-cache-path /private/tmp/kymo-unified-cache \
```bash
swiftc -module-cache-path /private/tmp/kymo-check-cache \
kymo/UI/Charts/PanelCurveGeometry.swift kymoTests/PanelCurveChecks.swift \
kymo/UI/Charts/PanelCurveGeometry.swift kymo/UI/Charts/PanelCurveFrame.swift kymoTests/PanelCurveChecks.swift \
-o /private/tmp/kymo-panel-curve-checks
/private/tmp/kymo-panel-curve-checks
```
+18 -1
View File
@@ -33,6 +33,8 @@ import Foundation
precondition(store.snapshot.date == hiddenDate && store.snapshot.processes == nil)
preferences.backgroundMilliseconds = 500
try await until { store.snapshot.date > hiddenDate }
precondition(store.history.samples.last?.breakBefore == false)
precondition(store.history.samples.last?.expectedInterval == 0.5)
let first = store.snapshot.date
try await until { store.snapshot.date > first }
precondition(store.snapshot.date.timeIntervalSince(first) >= 0.45)
@@ -62,6 +64,19 @@ import Foundation
precondition(didDeliver, "Reopened process request must complete without another sample")
precondition(probe.count >= 2 && probe.peak == 1)
await deferred.setProcessVisible(false)
let slowRead = DelayedProcessRead(delay: 0.5)
let changing = SamplingPreferences(defaults: defaults)
changing.panelMilliseconds = 500
changing.backgroundMilliseconds = 1_800_000
let changingStore = MetricsStore(sampling: changing, sampler: SystemSampler(processRead: { slowRead.read(&$0) }))
changingStore.setPanelVisible(true)
try await until { !changingStore.history.samples.isEmpty }
precondition(changingStore.snapshot.processes == nil)
let countBeforeChange = changingStore.history.samples.count
changing.panelMilliseconds = 1_800_000
try await until { changingStore.snapshot.processes != nil }
precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample")
changingStore.togglePause()
print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary")
}
@MainActor private static func until(_ predicate: () -> Bool) async throws {
@@ -78,6 +93,8 @@ private actor ProcessDelivery {
private final class DelayedProcessRead: @unchecked Sendable {
private let lock = NSLock()
private let delay: TimeInterval
init(delay: TimeInterval = 0.2) { self.delay = delay }
private var active = 0
private var reads = 0
private var maximum = 0
@@ -86,7 +103,7 @@ private final class DelayedProcessRead: @unchecked Sendable {
func read(_ monitor: inout ProcessMonitor) -> ProcessSnapshot {
lock.lock(); active += 1; reads += 1; maximum = max(maximum, active); lock.unlock()
defer { lock.lock(); active -= 1; lock.unlock() }
Thread.sleep(forTimeInterval: 0.2)
Thread.sleep(forTimeInterval: delay)
return monitor.sample()
}
}