From 36b8e32af3da5cc6382503965cfa2b829e6d87be 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 11:30:37 +0800 Subject: [PATCH] =?UTF-8?q?feat(menubar):=20=E6=94=AF=E6=8C=81=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E5=B1=85=E4=B8=AD=E9=9D=A2=E6=9D=BF=E4=B8=8E=E7=8B=AC?= =?UTF-8?q?=E7=AB=8B=E5=88=B7=E6=96=B0=E9=A2=91=E7=8E=87=E5=8F=8A=E5=9B=BE?= =?UTF-8?q?=E8=A1=A8=E6=B5=AE=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture.md | 24 +- docs/monitoring.md | 3 +- docs/pinned-panel-refresh-plan.md | 36 ++ docs/roadmap.md | 4 +- docs/testing-capabilities.md | 4 + docs/unified-panel-plan.md | 4 + docs/unified-panel-validation.md | 20 + kymo/App/kymoApp.swift | 114 ++-- .../PanelTooltip.colorset/Contents.json | 38 ++ .../SeriesSystem.colorset/Contents.json | 38 ++ .../SeriesUpload.colorset/Contents.json | 38 ++ .../SeriesUser.colorset/Contents.json | 38 ++ kymo/Core/Models/MetricHistory.swift | 5 +- kymo/Core/Monitors/SystemSampler.swift | 42 +- kymo/Core/Services/MetricsStore.swift | 43 +- kymo/Core/Services/SamplingPreferences.swift | 50 ++ .../MenuBar/MenuPanelController.swift | 131 +++++ kymo/Features/MenuBar/MenuPanelView.swift | 41 +- kymo/Features/MenuBar/PanelLayout.swift | 9 +- .../MenuBar/PanelWindowObserver.swift | 20 +- .../Settings/AppearanceSettingsView.swift | 17 +- kymo/Resources/Localizable.xcstrings | 504 +++++++++++++++++- kymo/UI/Charts/PanelCurveGeometry.swift | 8 +- kymo/UI/Charts/PanelTrendChart.swift | 62 ++- kymo/UI/Components/IntervalControl.swift | 43 ++ kymo/UI/Components/ResourceCard.swift | 6 +- kymoTests/PanelAssetChecks.swift | 14 +- kymoTests/PanelCurveChecks.swift | 4 + kymoTests/PanelLayoutChecks.swift | 6 +- kymoTests/PanelWindowChecks.swift | 44 ++ kymoTests/README.md | 15 + kymoTests/SamplingChecks.swift | 4 +- kymoTests/SamplingIntervalChecks.swift | 92 ++++ 33 files changed, 1403 insertions(+), 118 deletions(-) create mode 100644 docs/pinned-panel-refresh-plan.md create mode 100644 kymo/Assets.xcassets/PanelTooltip.colorset/Contents.json create mode 100644 kymo/Assets.xcassets/SeriesSystem.colorset/Contents.json create mode 100644 kymo/Assets.xcassets/SeriesUpload.colorset/Contents.json create mode 100644 kymo/Assets.xcassets/SeriesUser.colorset/Contents.json create mode 100644 kymo/Core/Services/SamplingPreferences.swift create mode 100644 kymo/Features/MenuBar/MenuPanelController.swift create mode 100644 kymo/UI/Components/IntervalControl.swift create mode 100644 kymoTests/PanelWindowChecks.swift create mode 100644 kymoTests/SamplingIntervalChecks.swift diff --git a/docs/architecture.md b/docs/architecture.md index dade06e..e6b328a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,10 +4,10 @@ Kymo 是一款 macOS 菜单栏常驻的资源监控工具,设计目标为「轻量、低功耗、无干扰」: -- **常驻形态**:使用 SwiftUI 原生 `MenuBarExtra`(window 样式),平时无 Dock 图标、无常驻窗口;设置窗口打开期间临时显示 Dock 图标并提供常规窗口焦点; +- **常驻形态**:使用 `NSStatusItem + NSPanel`,内容使用 SwiftUI,平时无 Dock 图标;设置窗口打开期间临时显示 Dock 图标并提供常规窗口焦点;面板可在本次进程内固定置顶; - **数据驱动**:采样器定时采集系统指标 → 汇成统一快照 → 驱动面板 UI;菜单栏固定显示品牌图标; - **可扩展**:新增监控项只需新增一个采样器并注册,不改动既有 UI 结构; -- **低功耗**:单一调度器统一驱动采样,当前固定约 2s,频率配置尚未实现;面板不可见时不挂载趋势动画。 +- **低功耗**:单一调度器统一驱动采样,面板可见与关闭使用独立持久化间隔(默认 2s / 5s);面板不可见时不挂载趋势动画。 ## 2. 总体分层 @@ -39,11 +39,13 @@ Kymo 是一款 macOS 菜单栏常驻的资源监控工具,设计目标为「 `App` 持有一个 `MetricsStore`(MainActor、`@Observable`),注入菜单栏场景与面板。 仓库创建唯一 Task,调用 `SystemSampler` actor,在后台串行读取 `CPUMonitor`、 `MemoryMonitor` 与 `getloadavg`,返回 Sendable `MetricsSnapshot`,再回 MainActor 整体发布。 -默认每次采样完成后等待 2s,不会重叠快速采样;当前刷新间隔尚未接入设置。 +每次采样完成后等待当前间隔,不重叠快速采样。SamplingPreferences 以毫秒整数分别保存面板/后台间隔,100ms 步进、500ms–1800000ms,非法值归一化。前者在面板顶栏调整,后者在设置监控页调整。频率或可见性变化取消旧等待、递增发布代次并立即重排,不重置差分基线;未生效一侧偏好改变不唤醒当前调度。暂停优先于频率和可见性,恢复重新建立基线。 SystemSampler 统一协调 SMART、电池健康、卷列表与进程的单次在途任务,快速链路不等待其完成;SMART/电池健康结果带时间戳,成功一小时、失败十分钟后重试,卷列表约三十秒刷新。任务完成清空在途槽;取消/隐藏不释放尚未结束的同步查询槽,不无限补发。 -进程通过 sysctl 枚举并逐项读取 proc_taskallinfo/proc_pidpath;PID + 启动秒/微秒为身份,读取前后核对枚举身份,未知字段独立降级。CPU 计时为纳秒差分,单核 100%,RSS 不等同活动监视器内存。只在面板可见且未暂停时采样;关闭清空快照、监控器基线与缓存,迟到结果按代次拒绝,重新打开重建基线;其他用户受限行保留覆盖说明。Store 另以发布/可见性代次防止暂停或快速开关后发布旧结果。 +进程通过 sysctl 枚举并逐项读取 proc_taskallinfo/proc_pidpath;PID + 启动秒/微秒为身份,读取前后核对枚举身份,未知字段独立降级。CPU 计时为纳秒差分,单核 100%,RSS 不等同活动监视器内存。只在面板可见且未暂停时采样;关闭清空快照、监控器基线与缓存,迟到结果按代次拒绝,重新打开重建基线;其他用户受限行保留覆盖说明。Store 另以发布/可见性代次防止暂停或快速开关后发布旧结果。进程单次在途完成后通过 Sendable 回调立即发布当前代次结果,不等待可能长达 30min 的下一周期,不追加图表历史或新建轮询;快速快照保留同周期已先到的进程结果,防止覆盖为 nil。若快速关开时旧同步读取仍占在途槽,旧结果结束后接续最新可见代次的待办查询,不等下一长周期,仍仅一次在途。 -菜单栏使用 `MenuBarExtra("Kymo", image: "BrandMark")`,仅显示模板品牌图标,点击展开监控面板。2026-11-02 用户确认取消动态数值、指标组合配置及宽度收缩需求,标题固定为品牌名,不读取采样快照。此前 macOS 27 自定义 label 不可见的调查保留在阶段记录中,不再作为待恢复动态文本的问题。 +菜单栏由 Features/MenuBar 的 MenuPanelController 持有 NSStatusItem,仅显示模板 BrandMark。点击图标切换同一 NSPanel,所属屏幕优先按菜单栏按钮选择,水平居中、顶部留边并限制在 visibleFrame 内。NSPanel 允许成为 key 而不成为 main,不因失焦自动隐藏。可见期间注册被动本地/全局鼠标监听,不拦截外部点击;普通状态外部点击/应用失活关闭,固定时使用 floating 层级并忽略外部关闭请求。菜单图标、Esc/Cmd+W 和进入设置可显式隐藏面板,固定状态保留到本次进程结束;shutdown 复位,不持久化。隐藏时拆卸内容并移除鼠标监听。App 只装配生命周期与服务,Features 之间不横向依赖。 + +Settings 保留 SwiftUI Settings 场景,App 在 applicationWillFinishLaunching 注册 NSHostingSceneRepresentation,通过公开的 environment.openSettings 打开([Apple 场景桥接说明](https://developer.apple.com/videos/play/wwdc2026/272/))。AppKit 生命周期补齐本地化的设置/退出、文件关闭和标准编辑菜单。设置窗口继续管理常规激活与 Dock 生命周期;显式进入设置时隐藏面板,避免固定窗口遮挡设置,重新打开仍保持本次固定状态。2026-11-02 确定的固定品牌标签及无动态菜单栏指标决策继续有效。 CPU 以每核 Mach tick 差分计算,总占用按 tick 加权;首帧、恢复监控首帧及读取失败显示 `--`。 CPU 计数按 UInt32 回绕计算,`host_processor_info` 分配的缓冲区每次释放。 @@ -56,18 +58,18 @@ GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取 ### 面板、历史与外观 -- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线。 -- 当前正式入口为统一 `MenuPanelView`:第一排 CPU/GPU/电池,电池 1:1 正方形、CPU/GPU 均分余宽;第二排内存/存储/网络等宽。宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时两排完整布局,参考尺寸两排分别 230/240pt,进程区使用剩余空间(最小 170pt)。其他尺寸资源独立滚动,进程常驻;三列低高度仍保持上述比例与顺序。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,移动/缩放和布局后约束完整 frame 原点;最终 MenuBarExtra 定位仍待复验。 -- `PanelWindowObserver` 属于 Features/MenuBar,以 NSViewRepresentable 观察所属窗口屏幕、key/close/occlusion 通知,通知 Store 可见性和尺寸;App 仍只装配原生 MenuBarExtra,Core 不依赖 AppKit。 -- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值和超过 5 秒间隙断线。图例显示最新值,悬浮绘图区时显示最近采样时刻的各序列值、游标和交点;未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。 -- 各卡标题与彩色主值同行,数值组件复用系统 numericText 数字翻动/模糊过渡并遵循减少动态效果;进程行不施加该动画。PanelCard 资源深浅色 alpha=0.68,减少透明度时改为系统实色窗口背景。操作强调色仍由偏好决定;保持唤醒、暂停/恢复、设置、退出胶囊位于顶栏右侧。顶栏左侧为品牌、版本及缓存的本机产品名/芯片,产品名不可读时退回 hw.model,不读取序列号。原采样状态/更新时间与底栏移除。 +- 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%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。 +- 各卡标题与彩色主值均为 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、搜索/焦点和选中冻结旧身份顺序,新增项追加到其后。完整路径在表下方同卡展示以保持固定行高;选中进程退出短暂提示后移除,关闭面板拆卸表并清掉路径状态。路径不持久化,不收集参数或环境变量。 - 旧 MetricRow / HoverDetailPresenter / DetailPlacement 与旧迷你趋势源码暂保留作迁移参照,正式面板已无调用;待真实 UI 回归后在 P6 清理并同步其历史检查程序,不能把源码存在理解为仍有双套交互。 - `AppearancePreferences` 仅依赖 Foundation / Observation,持久化外观、系统/六种预设/自选 RGB 强调色。UI 层 `AppearanceStyle` 将偏好映射为明确的深/浅色及窗口级 NSAppearance / Color。跟随系统从全局偏好 AppleInterfaceStyle 独立解析,监听系统主题通知及 NSApp effectiveAppearance 变化后刷新;为 SwiftUI 同时提供非 nil 的 preferredColorScheme 与 colorScheme 环境,避免返回 nil 和失焦后重新继承窗口残留模式。用户持久化值仍为 system,App 全局 appearance 不被修改。该系统偏好键/主题通知属于平台约定,系统动态切换仍需实机验证;外观覆盖作用于面板与设置,不作用于菜单栏标签。 - 设置页外观选择使用 `GlassEffectContainer`:外层为系统液态玻璃胶囊,选中态以共享 `glassEffectID` / `matchedGeometry` 的独立玻璃胶囊在三个选项间移动;遵循减少动态效果,其他表单仍使用系统分组与原生控件。 - `LanguagePreferences` 独立持久化 system / zh-Hans / zh-Hant / en,仅依赖 Foundation / Observation。App 将同一 locale 注入面板与设置,切换即时生效;系统模式按 Locale.preferredLanguages 匹配已支持语言,无法匹配回退 en,不修改 AppleLanguages。外侧详情的独立 NSHostingView 显式转发 locale;UI 的 AppLocalization 为原生窗口标题与色块辅助标签查找对应 lproj,避免其沿用进程启动语言。系统菜单与 NSColorPanel 的系统文案由 macOS 管理。语言自称保留原文。 -- App 注入同一个偏好仓库,注册独立 Settings 场景;设置采用 `NavigationSplitView` 侧边栏与系统式分组 `Form`,分为外观、语言、关于。窗口、侧边栏和控件遵循 macOS 设置页的原生材质与层级,不在内容区叠加整块自绘液态玻璃卡片;关于页展示品牌图标和 Bundle 实际版本,不写死版本号。 +- App 注入同一个偏好仓库,注册独立 Settings 场景;设置采用 `NavigationSplitView` 侧边栏与系统式分组 `Form`,分为外观、语言、监控、关于。窗口、侧边栏和控件遵循 macOS 设置页的原生材质与层级,不在内容区叠加整块自绘液态玻璃卡片;关于页展示品牌图标和 Bundle 实际版本,不写死版本号。 - App 持有一个与 UI 无关的 `SettingsPresentation` 请求状态,并向 MenuBar 与 Settings 注入同一实例。菜单入口先切换 `.regular`,递增请求并调用 `openSettings`;设置窗口观察器在请求变化时取消旧任务、等待 SwiftUI 排序后激活应用、将窗口置前并清除最小化。只使用普通窗口层级,不永久置顶;活动应用通知补充处理激活竞态,隐藏后重开与最小化恢复走同一路径。窗口关闭时恢复 `.accessory`,保留 `LSUIElement=true` 的默认无 Dock 行为。 - 品牌图标由用户提供的 dashboard-3-fill.svg 仪表盘路径派生:菜单栏 `BrandMark` 使用 18/36/54 px 透明模板 PNG,随明暗菜单栏系统着色;AppIcon 全尺寸与关于页 `BrandLogo` 使用覆盖整张画布的不透明白色背景及原深灰图形。Dock/Finder 使用 AppIcon 资源,不增加自绘 Dock 生命周期;系统负责最终圆角蒙版,避免透明边角触发额外的灰色底板。 - 自选强调色使用设置特性持有的 `CustomColorPicker` 控制系统 NSColorPanel;选 custom 延迟到下一次主线程调度后打开。色块使用固定 44×26pt 原生 NSButton,直接在 bounds 内绘制 RGB(不使用可缩放的符号图像),保留 target/action 并允许失焦首次点击,面板显式 makeKeyAndOrderFront / orderFrontRegardless,连续回写 RGB,可重复打开,设置关闭时仅清理自身持有的颜色面板。记录入口请求与可见状态日志以便定位。窗口观察/外观/详情锚点 NSView 的 hitTest 均返回 nil,避免拦截正常控件。 diff --git a/docs/monitoring.md b/docs/monitoring.md index ae83c8f..77143c1 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -49,7 +49,8 @@ - 全部采样由统一的采样调度器驱动,禁止各模块自建 Timer; - 差分类指标(CPU、网络、磁盘 IO)采样器内部持有上一次快照,自行做差分; - 菜单栏仅显示品牌图标,指标在面板展示; -- 当前采样完成后等待 2s,面板底部暂停/恢复;1–10s 配置待实现。 +- 采样完成后按可见性等待:面板默认 2s,关闭默认 5s;两者独立持久化、100ms 步进、500ms–30min,面板顶栏调前者,设置监控页调后者;顶栏暂停/恢复。 +- 改有效频率或开关面板立即取消旧等待并重排,纯改频率不重置差分基线;暂停不会被偏好变更唤醒。进程完成单次读取后立即发布有效代次结果,隐藏不查询进程。60 点历史跨度随间隔变化,显式边界防止跨暂停/频率切换连线。 磁盘寿命通过用户授权的嵌入式非沙盒 XPC 服务低频读取 `diskutil info -plist`,主应用保留沙盒。NVMe 寿命消耗字段换算预计剩余寿命,通电小时读取 128 位计数的可表示部分;高位非零不截断展示。SMART 数据是物理设备级,多个 APFS 卷不重复合算,缺失/多物理存储显示 --。服务固定只读查询,无管理员权限或系统开机项,详见 disk-smart-helper-plan.md。 diff --git a/docs/pinned-panel-refresh-plan.md b/docs/pinned-panel-refresh-plan.md new file mode 100644 index 0000000..5cc71e4 --- /dev/null +++ b/docs/pinned-panel-refresh-plan.md @@ -0,0 +1,36 @@ +# 固定面板与可见性刷新频率实施计划 + +## 背景与范围 + +2026-11-03 用户要求:悬浮读数独立浮层、不覆盖图例,改善序列配色;顶栏加入图钉及前台刷新频率;后台频率默认 5s 并在设置调整;两种频率分开及时持久化,100ms 步进、500ms–30min;电池宽高比 4:3;面板按所属屏幕水平居中;主值与标题同字号。 + +## 设计与影响模块 + +- App 只装配生命周期、共享服务及 SwiftUI Settings 场景。MenuBarExtra 无可靠公开的固定/外部关闭控制,改为 MenuBar 特性的 NSStatusItem + NSPanel;只使用公开 AppKit API。设置继续使用 SwiftUI Settings,通过 NSHostingSceneRepresentation 的公开环境 action 打开,避免私有 selector 或隐形启动窗口。 +- Features/MenuBar 管理面板生命周期、屏幕定位、外部鼠标事件及仅内存存储的固定状态;固定时使用 floating 层级,外部点击不关闭;未固定时外部点击关闭,状态图标和 Esc 可显式关闭,进程退出不恢复固定状态。事件监听只在面板可见期间注册,不吞掉外部点击。 +- Core 新增独立 SamplingPreferences,保存前台/后台毫秒整数与边界归一化;MetricsStore 仍为唯一采样调度器,频率/可见性改变取消旧等待并按发布代次重排,快速采样不重叠,隐藏后不采进程。首次/恢复重建基线,纯频率变化不重置 CPU/网络基线。暂停始终高于频率与可见性。 +- Features/Settings 新增监控设置页,调整后台间隔;UI 提供通用区间输入控件,无 Features 横向依赖。 +- UI/Charts 的图例始终显示最新值,浮层单独显示时间、各序列读数和色块,游标/交点保留;浮层约束在卡片绘图区附近且不参与鼠标命中,不创建新顶层窗口。复合图引入区分明显的资产色及线型。 +- 历史保持 60 点有界,间隔可变后按真实时间轴与当前预期间隔断线,显式中断标记防止跨暂停/切频率补线。电池宽度为第一排高度的 4/3,CPU/GPU 均分余宽;卡片主值与标题均 13pt。 + +## 实施顺序 + +1. 偏好、唯一调度器及边界/开关/暂停检查。 +2. NSPanel 容器迁移、居中、图钉与设置场景桥接,验证正常/固定两种关闭语义。 +3. 控件、浮层/配色、4:3 及同字号,构建并检查真实 UI。 +4. 同步架构/监控/验证文档,清理临时测试包,提交任务文件,不推送。 + +## 验证与风险 + +必需 Debug 构建;独立检查偏好持久化、非法值/100ms 量化、双频切换立即生效、暂停不被唤醒、隐藏不发进程、慢任务单次在途;窗口检查负坐标屏幕/居中、固定层级/关闭策略、设置首次打开/再次置前和退出清理。实际菜单栏图标/面板、设置、频率控件与独立滚动由智能体尽量实测。浮层/曲线配色做深浅色检查,实际多屏/全屏、玻璃与动画手感明确区分自动证据与用户验收。 + +风险:替换容器后的焦点、设置 Dock 策略、原生 popover 子窗口被外部点击误判、0.5s 采样成本,以及 30min 等待时前台唤醒延迟。保持被动鼠标监听、不申请新增授权、不改应用沙盒;慢任务继续有界,不引入持续动画或重复 Timer。 + +## 进度 + +- [x] 核对当前调用链、工作区(保留本地化两处既有 stale 标记)、公开场景桥接接口。 +- [x] 完成代码、Debug/Release、独立调度/窗口/几何/资源检查与普通窗口控件/设置验证;实际 NSPanel 外部事件和真实悬浮仍受当前工具路径限制,详见 unified-panel-validation.md。 + +显式进入设置时隐藏面板,避免 floating 面板遮挡设置;固定状态保留至本次退出。AppKit 生命周期补齐标准菜单与快捷键。独立悬浮背景最终使用 alpha=0.97 的深浅资源以提高文字可读性,不另建窗口。归一化属性使用底层存储避免观察 setter 自写回递归。 + +补充并发边界:快速关闭/重开遇到旧进程同步读取占槽时,结束后立即接续当前可见代次的待办查询;注入延迟读取验证无需下一次 sample、峰值在途为 1,不额外轮询。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 809a9de..75651f4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -42,7 +42,9 @@ - [x] 独立设置窗口、侧边栏、外观/语言/关于、窗口置前及 Dock 生命周期 - [x] 品牌菜单栏图标、应用图标和关于页图标 -- [ ] 面板模块显示开关、采样间隔配置 +- [x] 前台/后台独立采样间隔、持久化和立即重排(默认 2s/5s,500ms–30min) +- [x] 面板图钉、NSPanel 窗口策略及屏幕居中实现(实际外部点击/多屏专项待补) +- [ ] 面板模块显示开关 - [ ] 权限与状态页(自启、通知、传感器能力、隐私说明) - [ ] 温度与风扇(SMC,失败降级) - [ ] 开机自启(可延后至发布准备) diff --git a/docs/testing-capabilities.md b/docs/testing-capabilities.md index 56ecf89..06e9353 100644 --- a/docs/testing-capabilities.md +++ b/docs/testing-capabilities.md @@ -47,3 +47,7 @@ 本会话 getState 可枚举应用;getApp 按 /private/tmp 路径、工具解析的 /tmp 路径和应用名读取均 timeoutReached。bundle ID 路径提示存在 Xcode 与临时构建两个副本,未误操作 Xcode 副本。用户授权并重启后再次尝试,用户另手动展开面板后按准确测试路径仍超时。原因未确定,不能认定为未授权;本轮没有取得可操作 App 对象,故未进行 AX/坐标点击、原生截图与键盘关闭。旧轮次成功记录不替代本轮新面板验收。 后续概念图对齐迭代中,用户 Xcode 副本 AX 读取恢复;独立同源码窗口的 AX、单窗口截图、按钮点击、搜索、Esc 清空及原生 Scroll Down 动作通过。滚动条 setValue 返回元素失效,最终正式菜单弹窗的定位/关闭仍未复验。建立新应用绑定有两次异常长耗时,timeout 参数未截断;不能据此归因为缺少权限,也不能将独立 WindowGroup 检查扩大为所有 MenuBarExtra 路径通过。 + +## 2026-11-03 NSPanel 与刷新控件 + +本轮直接读取非 main 的 NSPanel 未成功,首次 getApp 超时约 295s(timeout 参数未能截断),常规激活后仍有短超时;普通辅助主窗口可读。最终用普通 NSWindow 承载实际 SwiftUI 内容,完成图钉状态、前台/后台间隔输入与步进、Settings 场景和 Cmd+A / Cmd+, / Cmd+W / Cmd+Q 检查;真实 NSPanel 的可见性、居中、浮动层级与关闭策略另由独立程序检查。两者不能合并成真实外部点击/所有窗口焦点路径已通过。浅色图表浮层使用测试源码注入悬浮状态验证渲染,不证明鼠标事件投递。正式代码未加入辅助窗口、常规激活或主焦点资格测试改动。详见 unified-panel-validation.md。 diff --git a/docs/unified-panel-plan.md b/docs/unified-panel-plan.md index dbf13c4..4a3393b 100644 --- a/docs/unified-panel-plan.md +++ b/docs/unified-panel-plan.md @@ -254,3 +254,7 @@ xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build 验证:Debug 构建、CPU 历史/缺失边界、默认接口降级、编译颜色透明度、布局预算与真实 UI 的布局/悬浮/操作;动画主观手感、实际玻璃与多屏仍需分别说明验证边界。风险:紧凑电池卡文字、多地址长文本、三线对比度和连续悬浮期间数据更新;不通过虚构数据或删除关键口径规避。 本轮九项调整已实现;Debug/Release、数据/曲线几何/布局/编译颜色/多语言检查通过,独立深浅测试窗口与暂停、进程排序/搜索/独立滚动已验证。悬浮事件自动化和动画主观体验、正式菜单弹窗材质仍待验收,未将本轮代码完成等同于整体 P5/P6 完成,证据与边界见验证记录。 + +### 固定、居中与双刷新频率修订(2026-11-03) + +用户进一步要求独立悬浮小浮层、区分序列配色、图钉、前台/后台独立频率、电池 4:3、水平居中及标题/主值同字号。已按 [固定面板与刷新实施计划](pinned-panel-refresh-plan.md) 实现,取代前述 MenuBarExtra 容器、1:1 电池与固定 2s 调度。两种间隔默认 2s/5s、100ms 步进、500ms–30min;固定状态仅内存保存。改频率/可见性立即重排,历史带显式中断;进程完成结果无需等待下一长周期。Debug/Release、独立采样/窗口/几何/资源与普通窗口 UI 验证结果见验证记录,不把窗口策略单测或浮层渲染样例当作实际鼠标事件验收。整体长时性能与多屏/完整可访问性仍未完成。 diff --git a/docs/unified-panel-validation.md b/docs/unified-panel-validation.md index b5bd51e..42c1873 100644 --- a/docs/unified-panel-validation.md +++ b/docs/unified-panel-validation.md @@ -72,3 +72,23 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条 真实 UI:沿用同源码独立 WindowGroup 沙盒测试包、隔离标识与偏好,深浅色截图核对完整两排卡片、三线 CPU/双线网络与存储、等宽第二排、正方形电池、顶栏信息与主值对齐;初始可见约八行进程。顶栏暂停按钮切为继续监控,原生 Scroll Down 只改变进程表行与滚动条,上方字段保持;“内存”分段排序、搜索路径中的 kymo、Esc 恢复完整列表均通过。测试前记录用户已有 Xcode 副本,未终止该路径;仅关闭本轮 /private/tmp 下测试进程并清理本轮临时构建、脚本和偏好。 未验证:坐标点击图表未得到可稳定保留的悬浮状态,当前工具无公开的独立鼠标移动接口,因此不声称真实悬浮事件已验收;动画主观手感、减少动态/透明度的系统开关矩阵、正式 MenuBarExtra 的玻璃穿透/定位/外部关闭、多屏与完整 VoiceOver 尚待补验。独立普通窗口背景不能替代正式菜单材质验证。该测试包因标识/签名与正式 XPC 身份要求不同,SMART 显示未知,不据此判断主产品回归;本轮未进行长时 CPU/内存/能耗验收。 + +### 固定面板、双刷新间隔与浮层(2026-11-03) + +实现方案见 [固定面板与刷新计划](pinned-panel-refresh-plan.md)。正式容器已由 MenuBarExtra 改为公开 NSStatusItem + 非激活 NSPanel;Settings 使用 NSHostingSceneRepresentation 的公开环境 action,保留原界面与标准应用/文件/编辑快捷键。第一排电池为 4:3,CPU/GPU 均分余宽;卡片标题与主值同为 13pt,网络上/下行主值也同行;布局测量和屏幕变化后保持所属屏幕水平居中。 + +刷新以整数毫秒分别持久化:面板默认 2000、后台默认 5000;步进 100、范围 500–1800000。顶栏调整前者,设置监控页调整后者;有效频率或可见性改变立即取消旧等待并重排,另一侧偏好改变不唤醒当前调度,暂停优先。进程单次在途完成后立即发布有效代次结果,避免长间隔下首次列表空等;快速快照保留已先到的同周期进程结果,隐藏/暂停拒绝迟到结果。显式历史中断标记防止跨暂停/切频率补线,正常慢间隔仍可连接。 + +图例始终保留最新值,历史读数用独立浮层;CPU 采用青绿/紫红/金色及实线/虚线/点线,网络和存储双线也有独立色/线型。浅色渲染检查发现材质浮层会透出底下文字,最终改为深浅资源 alpha=0.97 的浮层底色;卡片仍为 alpha=0.68。间隔单位指定固定宽度,避免顶栏压缩。 + +通过的客观验证: + +- 最终 Debug、Release 均 BUILD SUCCEEDED;无新增 Swift 编译警告(仅系统 AppIntents 元数据提取提示)。仍无测试 Target,未将独立程序称为 xcodebuild test。 +- SamplingIntervalChecks:默认值、100ms 量化、Int.min/Int.max、非法持久化值、双频独立恢复、30min 等待唤醒、另一侧修改不唤醒、暂停优先、隐藏进程清理、长间隔首批进程立即发布与历史中断;延迟读取夹具复现关闭/立即重开,在没有额外 sample 调用的情况下接续新代次,读取峰值为 1。初版观察属性自身归一化导致递归,已改为底层存储加计算属性,重跑通过。 +- UnifiedPanelChecks、SamplingChecks:既有差分/有界历史/真实采样/暂停恢复与进程可见性回归通过。PanelCurveChecks 新增 30min 正常间隔连线及显式中断;PanelLayoutChecks 新增 4:3 和负屏幕原点居中;PanelAssetChecks 读取实际深浅资源,验证卡片/浮层透明度、序列色 alpha 与三色粗略 RGB 距离(不据此宣称完成色盲/对比度验收)。三语资源检查通过。 +- 独立 `.app` 的真实 NSPanel 检查:isVisible、canBecomeKey=true / canBecomeMain=false、所属屏幕水平居中、未固定外部关闭策略、固定 floating/hidesOnDeactivate=false、固定时拒绝外部关闭请求、close/performClose 显式关闭、重开保留本次固定、取消固定及 shutdown 复位。检查调用外部关闭策略方法,未注入系统鼠标事件。 +- 原生工具读取普通验证窗口成功:同源码内容的深色截图确认 4:3、等宽第二排、同字号主值和三色/线型;顶栏 2.0→2.1s、图钉未固定→已固定;真实 Settings 场景打开、后台 5.0→4.9s;重启副本后前台 2.1、后台 4.9 分别保留,图钉恢复未固定。输入 0.5s、Cmd+A、Cmd+,、Cmd+W 通过;Cmd+Q 后用 CLI 确认测试主进程退出,未调用会自动重启副本的 AX 查询。 + +能力边界:直接读取本轮非 main 的 NSPanel 超时(首轮约 295s,后续短超时),普通主窗口能读;暂不能据此归因权限缺失或断言所有 NSPanel 都不可操作。临时尝试常规激活、辅助窗口及主焦点资格,最终采用标准 NSWindow 承载相同 SwiftUI 内容验证控件;这些临时改动未进入正式 Target。浅色浮层截图使用仅临时源码的悬浮状态注入,确认历史时间/读数在独立浮层、图例保持最新值(截图中系统读数与图例不同),不作为真实鼠标悬浮事件投递通过的证据。最终高不透明浮层底色由编译资源检查覆盖。 + +未验证:正式菜单栏图标开关、真实系统外部点击在固定/未固定两种状态下的投递、实际悬浮与子 popover 焦点组合、多屏/全屏/刘海屏、最终 NSPanel 玻璃手感、减少动态/透明度完整矩阵及长时资源预算。进入设置属于显式操作,会隐藏面板避免固定窗口遮挡,重开保留本次固定状态。独立测试包标识/签名不同导致 SMART 未知,不将其视为主产品读取回归。测试前记录已有用户 Xcode 副本 PID 16854,未终止该路径;只清理本轮 /private/tmp 测试副本、脚本、构建及隔离偏好。 diff --git a/kymo/App/kymoApp.swift b/kymo/App/kymoApp.swift index 4d65717..455a207 100644 --- a/kymo/App/kymoApp.swift +++ b/kymo/App/kymoApp.swift @@ -1,36 +1,86 @@ -// -// kymoApp.swift -// kymo -// -// Created by Airnan on 2026/10/29. -// - import SwiftUI +import AppKit -/// 应用入口。 -/// -/// Kymo 是一款菜单栏常驻应用:平时不显示 Dock 图标与主窗口, -/// 通过 `MenuBarExtra` 场景在系统菜单栏展示状态并承载监控面板。 -/// 打开设置期间临时使用常规应用激活策略,以便设置窗口正常获得焦点。 -@main -struct kymoApp: App { - @State private var metrics = MetricsStore() - @State private var keepAwake = KeepAwakeService() - @State private var settingsPresentation = SettingsPresentation() - - @State private var appearance = AppearancePreferences() - @State private var language = LanguagePreferences() - - var body: some Scene { - MenuBarExtra("Kymo", image: "BrandMark") { - MenuPanelView(metrics: metrics, preferences: appearance, keepAwake: keepAwake, settingsPresentation: settingsPresentation) - .environment(\.locale, language.locale) - } - .menuBarExtraStyle(.window) - - Settings { - AppearanceSettingsView(preferences: appearance, language: language, presentation: settingsPresentation) - .environment(\.locale, language.locale) - } +/// AppKit owns launch only; MenuBar owns windows, Core owns sampling and preferences. +@main @MainActor struct kymoApp { + static func main() { + let application = NSApplication.shared + let lifecycle = ApplicationLifecycle() + application.delegate = lifecycle + application.setActivationPolicy(.accessory) + withExtendedLifetime(lifecycle) { application.run() } } } + +@MainActor private final class ApplicationLifecycle: NSObject, NSApplicationDelegate { + private let metrics = MetricsStore() + private let awake = KeepAwakeService() + private let presentation = SettingsPresentation() + private let appearance = AppearancePreferences() + private let language = LanguagePreferences() + private var openSettingsAction: (() -> Void)? + private var scenes: AnyObject? + private var menuBar: MenuPanelController? + + func applicationWillFinishLaunching(_ notification: Notification) { + let settings = NSHostingSceneRepresentation { + Settings { + AppearanceSettingsView(preferences: appearance, language: language, sampling: metrics.sampling, presentation: presentation) + .environment(\.locale, language.locale) + .onChange(of: language.language) { _, _ in self.configureMainMenu() } + } + } + NSApp.addSceneRepresentation(settings) + scenes = settings + openSettingsAction = { settings.environment.openSettings() } + configureMainMenu() + menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) }) { [self] panel in + MenuPanelView(metrics: metrics, preferences: appearance, keepAwake: awake, settingsPresentation: presentation, + presentation: panel, onOpenSettings: { [weak self] in + self?.menuBar?.hide() + settings.environment.openSettings() + }) + .environment(\.locale, language.locale) + } + } + + private func configureMainMenu() { + let root = NSMenu() + let application = NSMenu() + let appItem = NSMenuItem(); appItem.submenu = application; root.addItem(appItem) + let settings = NSMenuItem(title: AppLocalization.string("action.settings", locale: language.locale), action: #selector(settingsCommand), keyEquivalent: ",") + settings.target = self + application.addItem(settings) + application.addItem(.separator()) + let quit = NSMenuItem(title: AppLocalization.string("action.quit", locale: language.locale), action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") + quit.target = NSApp; application.addItem(quit) + let file = NSMenu() + let fileItem = NSMenuItem(title: AppLocalization.string("action.file", locale: language.locale), action: nil, keyEquivalent: "") + fileItem.submenu = file; root.addItem(fileItem) + file.addItem(NSMenuItem(title: AppLocalization.string("action.closeWindow", locale: language.locale), action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")) + let edit = NSMenu() + let editItem = NSMenuItem(title: AppLocalization.string("action.edit", locale: language.locale), action: nil, keyEquivalent: "") + editItem.submenu = edit; root.addItem(editItem) + for (key, action, shortcut) in [("undo", "undo:", "z"), ("redo", "redo:", "Z"), ("cut", "cut:", "x"), ("copy", "copy:", "c"), ("paste", "paste:", "v"), ("selectAll", "selectAll:", "a")] { + edit.addItem(NSMenuItem(title: AppLocalization.string("action." + key, locale: language.locale), action: Selector(action), keyEquivalent: shortcut)) + } + NSApp.mainMenu = root + } + + @objc private func settingsCommand() { + NSApp.setActivationPolicy(.regular) + presentation.request() + menuBar?.hide() + openSettingsAction?() + } + + func applicationWillTerminate(_ notification: Notification) { + menuBar?.shutdown() + awake.disable() + menuBar = nil + openSettingsAction = nil + scenes = nil + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false } +} diff --git a/kymo/Assets.xcassets/PanelTooltip.colorset/Contents.json b/kymo/Assets.xcassets/PanelTooltip.colorset/Contents.json new file mode 100644 index 0000000..8f730b5 --- /dev/null +++ b/kymo/Assets.xcassets/PanelTooltip.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.990", + "green": "0.990", + "blue": "0.995", + "alpha": "0.970" + } + } + }, + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.130", + "green": "0.150", + "blue": "0.180", + "alpha": "0.970" + } + }, + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/SeriesSystem.colorset/Contents.json b/kymo/Assets.xcassets/SeriesSystem.colorset/Contents.json new file mode 100644 index 0000000..82ec43d --- /dev/null +++ b/kymo/Assets.xcassets/SeriesSystem.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.620", + "green": "0.340", + "blue": "0.000", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "1.000", + "green": "0.760", + "blue": "0.240", + "alpha": "1.000" + } + }, + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/SeriesUpload.colorset/Contents.json b/kymo/Assets.xcassets/SeriesUpload.colorset/Contents.json new file mode 100644 index 0000000..5c2a35f --- /dev/null +++ b/kymo/Assets.xcassets/SeriesUpload.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.700", + "green": "0.260", + "blue": "0.000", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "1.000", + "green": "0.620", + "blue": "0.200", + "alpha": "1.000" + } + }, + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Assets.xcassets/SeriesUser.colorset/Contents.json b/kymo/Assets.xcassets/SeriesUser.colorset/Contents.json new file mode 100644 index 0000000..de6e9c9 --- /dev/null +++ b/kymo/Assets.xcassets/SeriesUser.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors": [ + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "0.700", + "green": "0.040", + "blue": "0.460", + "alpha": "1.000" + } + } + }, + { + "idiom": "universal", + "color": { + "color-space": "srgb", + "components": { + "red": "1.000", + "green": "0.400", + "blue": "0.750", + "alpha": "1.000" + } + }, + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/kymo/Core/Models/MetricHistory.swift b/kymo/Core/Models/MetricHistory.swift index dbe1e6c..87ada36 100644 --- a/kymo/Core/Models/MetricHistory.swift +++ b/kymo/Core/Models/MetricHistory.swift @@ -13,6 +13,7 @@ nonisolated struct TrendSample: Sendable { var write: Double? var cpuUser: Double? var cpuSystem: Double? + var breakBefore = false } /// Bounded sampling history; no timer or UI visibility dependence. @@ -21,13 +22,13 @@ nonisolated struct MetricHistory: Sendable { private(set) var samples: [TrendSample] = [] private(set) var interfaces: [String: [InterfaceTrendSample]] = [:] - mutating func append(_ snapshot: MetricsSnapshot) { + mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false) { 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)) + cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore)) let current = snapshot.network ?? [] let keys = Set(current.map(\.identity)) interfaces = interfaces.filter { keys.contains($0.key) } diff --git a/kymo/Core/Monitors/SystemSampler.swift b/kymo/Core/Monitors/SystemSampler.swift index 6fe9021..b01d796 100644 --- a/kymo/Core/Monitors/SystemSampler.swift +++ b/kymo/Core/Monitors/SystemSampler.swift @@ -21,12 +21,18 @@ actor SystemSampler { private var batteryDate: Date? private var nextDisk: TimeInterval = 0 private var nextBattery: TimeInterval = 0 + private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot private var processMonitor = ProcessMonitor() private var processTask: Task? private var processCache: ProcessSnapshot? + private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)? private var processVisible = false private var processGeneration = 0 + init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) { + self.processRead = processRead + } + func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() } func setProcessVisible(_ visible: Bool) { @@ -34,12 +40,15 @@ actor SystemSampler { processVisible = visible processGeneration += 1 processCache = nil + if !visible { processUpdate = nil } processMonitor = ProcessMonitor() // A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied. } - func sample(includeProcesses: Bool? = nil) -> MetricsSnapshot { + func sample(includeProcesses: Bool? = nil, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot { + guard !Task.isCancelled else { return MetricsSnapshot() } if let includeProcesses { setProcessVisible(includeProcesses) } + self.processUpdate = processUpdate if !didProbe { didProbe = true if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() } @@ -69,15 +78,7 @@ actor SystemSampler { if result.battery != nil && batteryTask == nil && start >= nextBattery { batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) } } - if processVisible && processTask == nil { - let generation = processGeneration - let monitor = processMonitor - processTask = Task.detached(priority: .utility) { [self] in - var worker = monitor - let value = worker.sample() - await finishProcesses(value, monitor: worker, generation: generation) - } - } + startProcessesIfNeeded() result.processes = processVisible ? processCache : nil result.diskHealth = diskCache result.diskHealthDate = diskDate @@ -105,9 +106,28 @@ actor SystemSampler { batteryCache = value; batteryDate = value == nil ? nil : Date() nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil } + private func startProcessesIfNeeded() { + guard processVisible, processTask == nil else { return } + let generation = processGeneration + let monitor = processMonitor + let read = processRead + processTask = Task.detached(priority: .utility) { [self] in + var worker = monitor + let value = read(&worker) + await finishProcesses(value, monitor: worker, generation: generation) + } + } + private func finishProcesses(_ value: ProcessSnapshot, monitor: ProcessMonitor, generation: Int) { processTask = nil - guard processVisible, generation == processGeneration else { return } + guard processVisible else { return } + guard generation == processGeneration else { + // Reopening requested a new generation while the old synchronous read held its slot. + // Fulfil that deferred request now, without waiting for another polling interval. + startProcessesIfNeeded() + return + } processMonitor = monitor; processCache = value + processUpdate?(value) } } diff --git a/kymo/Core/Services/MetricsStore.swift b/kymo/Core/Services/MetricsStore.swift index 0a28cd6..1f25b91 100644 --- a/kymo/Core/Services/MetricsStore.swift +++ b/kymo/Core/Services/MetricsStore.swift @@ -7,30 +7,60 @@ final class MetricsStore { private(set) var history = MetricHistory() private(set) var isPaused = false private(set) var isPanelVisible = false + let sampling: SamplingPreferences + var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds } @ObservationIgnored private var generation = 0 @ObservationIgnored private var visibilityGeneration = 0 @ObservationIgnored private var task: Task? @ObservationIgnored private let sampler = SystemSampler() + @ObservationIgnored private var scheduledInterval = 0 + @ObservationIgnored private var needsHistoryBoundary = true - init() { start() } + init(sampling: SamplingPreferences? = nil) { + 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) + } + start() + } func start() { guard task == nil else { return } isPaused = false + reschedule(reset: true) + } + + private func reschedule(reset: Bool) { generation += 1 + task?.cancel() + needsHistoryBoundary = true + scheduledInterval = effectiveMilliseconds let currentGeneration = generation task = Task { [weak self, sampler] in - await sampler.reset() - await sampler.setProcessVisible(self?.isPanelVisible == true) + guard !Task.isCancelled else { return } + if reset { await sampler.reset() } while !Task.isCancelled { let visibleGeneration = self?.visibilityGeneration - var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true) + 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, + self.isPanelVisible, !self.isPaused else { return } + self.snapshot.processes = processes + } + }) guard !Task.isCancelled, self?.generation == currentGeneration else { return } if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil } + else if let completed = self?.snapshot.processes, completed.date >= next.date { + // A fast detached process result may reach MainActor before this quick snapshot. + next.processes = completed + } self?.snapshot = next - self?.history.append(next) + self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true) + self?.needsHistoryBoundary = false SamplingDiagnostics.record(next) - do { try await Task.sleep(for: .seconds(2)) } + let interval = self?.effectiveMilliseconds ?? 5_000 + do { try await Task.sleep(for: .milliseconds(interval)) } catch { return } } } @@ -55,6 +85,7 @@ final class MetricsStore { if !visible { snapshot.processes = nil } let active = visible && !isPaused Task { await sampler.setProcessVisible(active) } + if !isPaused { reschedule(reset: false) } } deinit { task?.cancel() } diff --git a/kymo/Core/Services/SamplingPreferences.swift b/kymo/Core/Services/SamplingPreferences.swift new file mode 100644 index 0000000..d249d7b --- /dev/null +++ b/kymo/Core/Services/SamplingPreferences.swift @@ -0,0 +1,50 @@ +import Foundation +import Observation +import CoreFoundation + +/// Integer milliseconds avoid drift over repeated 100 ms steps. +@MainActor @Observable final class SamplingPreferences { + static let range = 500...1_800_000 + static let step = 100 + @ObservationIgnored private let defaults: UserDefaults + @ObservationIgnored var onChange: (() -> Void)? + private var panelValue: Int + private var backgroundValue: Int + var panelMilliseconds: Int { + get { panelValue } + set { + let value = Self.normalized(newValue) + guard value != panelValue else { return } + panelValue = value + defaults.set(value, forKey: "sampling.panelMilliseconds") + onChange?() + } + } + var backgroundMilliseconds: Int { + get { backgroundValue } + set { + let value = Self.normalized(newValue) + guard value != backgroundValue else { return } + backgroundValue = value + defaults.set(value, forKey: "sampling.backgroundMilliseconds") + onChange?() + } + } + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + panelValue = Self.read(defaults, key: "sampling.panelMilliseconds", fallback: 2_000) + backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 5_000) + } + + static func normalized(_ value: Int) -> Int { + let clamped = min(range.upperBound, max(range.lowerBound, value)) + return ((clamped + step / 2) / step) * step + } + + private static func read(_ defaults: UserDefaults, key: String, fallback: Int) -> Int { + guard let number = defaults.object(forKey: key) as? NSNumber, + CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite else { return fallback } + return normalized(Int(min(Double(range.upperBound), max(Double(range.lowerBound), number.doubleValue)))) + } +} diff --git a/kymo/Features/MenuBar/MenuPanelController.swift b/kymo/Features/MenuBar/MenuPanelController.swift new file mode 100644 index 0000000..e71cefc --- /dev/null +++ b/kymo/Features/MenuBar/MenuPanelController.swift @@ -0,0 +1,131 @@ +import AppKit +import SwiftUI +import Observation + +@MainActor @Observable final class PanelPresentation { + var isPinned = false { didSet { onPinChange?(isPinned) } } + @ObservationIgnored var onPinChange: ((Bool) -> Void)? +} + +/// Owns only status-item/window behavior. Sampling and settings are injected by App. +@MainActor final class MenuPanelController: NSObject { + let presentation = PanelPresentation() + let panel = MonitoringPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false) + private var statusItem: NSStatusItem? + private var localMouse: Any? + private var globalMouse: Any? + private var tokens: [NSObjectProtocol] = [] + private let content: (PanelPresentation) -> NSView + private let visibility: (Bool) -> Void + + init(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void, + @ViewBuilder content: @escaping (PanelPresentation) -> Content) { + self.visibility = visibility + self.content = { NSHostingView(rootView: content($0)) } + super.init() + panel.title = "Kymo" + panel.isReleasedWhenClosed = false + panel.isOpaque = false + panel.backgroundColor = .clear + panel.hasShadow = true + panel.hidesOnDeactivate = false + panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] + panel.dismiss = { [weak self] in self?.hide() } + presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal } + if installStatusItem { + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) + item.button?.image = NSImage(named: "BrandMark") + item.button?.image?.isTemplate = true + item.button?.toolTip = "Kymo" + item.button?.setAccessibilityLabel("Kymo") + item.button?.target = self + item.button?.action = #selector(togglePanel) + statusItem = item + } + tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.place() } + }) + tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: NSApp, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.dismissForOutsideInteraction() } + }) + } + + @objc func togglePanel() { panel.isVisible ? hide() : show() } + + func show() { + guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return } + place() + panel.contentView = content(presentation) + panel.level = presentation.isPinned ? .floating : .normal + panel.makeKeyAndOrderFront(nil) + panel.orderFrontRegardless() + visibility(true) + installMonitors() + } + + func hide() { + panel.orderOut(nil) + panel.contentView = nil + visibility(false) + removeMonitors() + } + + func dismissForOutsideInteraction() { + if panel.isVisible && !presentation.isPinned { hide() } + } + + func shutdown() { + hide() + presentation.isPinned = false + if let statusItem { NSStatusBar.system.removeStatusItem(statusItem) } + statusItem = nil + tokens.forEach(NotificationCenter.default.removeObserver) + tokens.removeAll() + } + + private func place() { + guard let screen = statusItem?.button?.window?.screen ?? panel.screen ?? NSScreen.main else { return } + let size = PanelLayout.contentSize(visible: screen.visibleFrame) + let initial = CGRect(x: screen.visibleFrame.midX - size.width / 2, y: screen.visibleFrame.maxY - size.height - 16, + width: size.width, height: size.height) + panel.setFrame(PanelLayout.centeredFrame(initial, visible: screen.visibleFrame), display: panel.isVisible) + } + + private func installMonitors() { + removeMonitors() + let mask: NSEvent.EventTypeMask = [.leftMouseDown, .rightMouseDown, .otherMouseDown] + localMouse = NSEvent.addLocalMonitorForEvents(matching: mask) { [weak self] event in + MainActor.assumeIsolated { + guard let self else { return } + if event.window === self.statusItem?.button?.window { return } + var window = event.window + while let current = window { + if current === self.panel { return } + window = current.parent + } + // Native menus/popovers own higher-level windows. Let them handle their dismissal. + if let window = event.window, window.level > self.panel.level { return } + self.dismissForOutsideInteraction() + } + return event + } + globalMouse = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] _ in + Task { @MainActor in self?.dismissForOutsideInteraction() } + } + } + + private func removeMonitors() { + if let localMouse { NSEvent.removeMonitor(localMouse) } + if let globalMouse { NSEvent.removeMonitor(globalMouse) } + localMouse = nil; globalMouse = nil + } +} + +final class MonitoringPanel: NSPanel { + var dismiss: (() -> Void)? + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { false } + override func cancelOperation(_ sender: Any?) { dismiss?() } + override func close() { dismiss?() } + override func performClose(_ sender: Any?) { dismiss?() } +} diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index 251b49e..85ffd14 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -6,7 +6,8 @@ struct MenuPanelView: View { let preferences: AppearancePreferences let keepAwake: KeepAwakeService let settingsPresentation: SettingsPresentation - @Environment(\.openSettings) private var openSettings + var presentation = PanelPresentation() + var onOpenSettings: () -> Void = {} @State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760)) @State private var selectedInterface = "" @State private var showAddresses = false @@ -14,6 +15,8 @@ struct MenuPanelView: View { private var snapshot: MetricsSnapshot { metrics.snapshot } private var samples: [TrendSample] { metrics.history.samples } + 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 network: [NetworkInterfaceMetrics] { (snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface } @@ -34,7 +37,7 @@ struct MenuPanelView: View { LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: columns), spacing: 8) { cpuCard.frame(minHeight: 240) gpuCard.frame(minHeight: 240) - batteryCard.aspectRatio(1, contentMode: .fit) + batteryCard.aspectRatio(4.0 / 3.0, contentMode: .fit) memoryCard.frame(minHeight: 240) diskCard.frame(minHeight: 250) networkCard.frame(minHeight: 250) @@ -48,15 +51,16 @@ struct MenuPanelView: View { } .padding(10) .frame(width: panelSize.width, height: panelSize.height) - .background(PanelWindowObserver { size, visible in + .background(PanelWindowObserver { size in if panelSize != size { panelSize = size } - if metrics.isPanelVisible != visible { metrics.setPanelVisible(visible) } }.frame(width: 0, height: 0)) .onAppear { metrics.setPanelVisible(true) } .onDisappear { metrics.setPanelVisible(false) } .onChange(of: snapshot.network?.map(\.identity)) { _, keys in if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" } } + .background(.ultraThinMaterial, in: .rect(cornerRadius: 18)) + .clipShape(.rect(cornerRadius: 18)) .modifier(AppearanceStyle(preferences: preferences)) } @@ -65,7 +69,7 @@ struct MenuPanelView: View { HStack(alignment: .top, spacing: 8) { cpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize)) gpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize)) - batteryCard.frame(width: PanelLayout.resourceRowHeight(size: panelSize)) + batteryCard.frame(width: PanelLayout.batteryWidth(size: panelSize)) }.frame(height: PanelLayout.resourceRowHeight(size: panelSize)) HStack(alignment: .top, spacing: 8) { memoryCard.frame(width: (panelSize.width - 36) / 3) @@ -91,7 +95,7 @@ struct MenuPanelView: View { } 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) + PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label, expectedInterval: chartInterval, boundaryDates: chartBoundaries) } private func line(_ key: LocalizedStringKey, _ value: String) -> some View { HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) } @@ -101,8 +105,8 @@ struct MenuPanelView: View { ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) { PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu), second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem), - color: Color("MetricCPU"), secondColor: Color("MetricNetwork"), thirdColor: Color("MetricDisk"), - firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system") + color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"), + firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries) 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) { @@ -139,7 +143,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)) + scaleLabel: MetricFormat.bytes(snapshot.memory?.total), expectedInterval: chartInterval, boundaryDates: chartBoundaries) if let m = snapshot.memory { GeometryReader { geometry in @@ -178,7 +182,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"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload").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).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 { @@ -225,7 +229,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") + 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) 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" } ?? "--") } @@ -273,6 +277,19 @@ struct MenuPanelView: View { private var controls: some View { HStack(spacing: 8) { HStack(spacing: 2) { + HStack(spacing: 4) { + Image(systemName: "timer").help(Text("sampling.panel")) + IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 })) + }.padding(.horizontal, 6).accessibilityLabel(Text("sampling.panel")) + Divider().frame(height: 18).padding(.horizontal, 3) + Button { presentation.isPinned.toggle() } label: { + Image(systemName: presentation.isPinned ? "pin.fill" : "pin") + .frame(width: 20, height: 20) + .foregroundStyle(presentation.isPinned ? preferences.tintColor : Color.primary) + } + .help(Text(presentation.isPinned ? "panel.unpin" : "panel.pin")) + .accessibilityLabel(Text(presentation.isPinned ? "panel.unpin" : "panel.pin")) + .accessibilityValue(Text(presentation.isPinned ? "panel.pinned" : "panel.unpinned")) Button { keepAwake.toggle() } label: { Image(systemName: keepAwake.isEnabled ? "cup.and.saucer.fill" : "cup.and.saucer") .frame(width: 20, height: 20) @@ -289,7 +306,7 @@ struct MenuPanelView: View { Button { NSApp.setActivationPolicy(.regular) settingsPresentation.request() - openSettings() + onOpenSettings() } label: { Image(systemName: "gearshape").frame(width: 20, height: 20) } diff --git a/kymo/Features/MenuBar/PanelLayout.swift b/kymo/Features/MenuBar/PanelLayout.swift index 9128db8..b52f00e 100644 --- a/kymo/Features/MenuBar/PanelLayout.swift +++ b/kymo/Features/MenuBar/PanelLayout.swift @@ -3,12 +3,19 @@ import CoreGraphics nonisolated enum PanelLayout { static func resourceRowHeight(size: CGSize) -> CGFloat { min(230, max(220, size.height - 590)) } - static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - resourceRowHeight(size: size)) / 2 } + static func batteryWidth(size: CGSize) -> CGFloat { resourceRowHeight(size: size) * 4 / 3 } + static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - batteryWidth(size: size)) / 2 } static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize { CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))), height: max(1, min(820, visible.height - 32 - max(0, chrome.height)))) } + static func centeredFrame(_ frame: CGRect, visible: CGRect) -> CGRect { + var result = constrainedFrame(frame, visible: visible) + result.origin.x = visible.midX - result.width / 2 + return result + } + static func constrainedFrame(_ frame: CGRect, visible: CGRect) -> CGRect { let safe = visible.insetBy(dx: 16, dy: 16) let width = min(frame.width, safe.width), height = min(frame.height, safe.height) diff --git a/kymo/Features/MenuBar/PanelWindowObserver.swift b/kymo/Features/MenuBar/PanelWindowObserver.swift index a2af4e2..5017f73 100644 --- a/kymo/Features/MenuBar/PanelWindowObserver.swift +++ b/kymo/Features/MenuBar/PanelWindowObserver.swift @@ -1,25 +1,23 @@ import SwiftUI import AppKit -/// Window geometry/lifecycle stays in the feature layer; Core receives only visibility. +/// Observes geometry only; MenuPanelController owns visibility and dismissal. struct PanelWindowObserver: NSViewRepresentable { - var update: (CGSize, Bool) -> Void + var update: (CGSize) -> Void func makeNSView(context: Context) -> ObserverView { ObserverView(update: update) } func updateNSView(_ view: ObserverView, context: Context) { view.update = update } final class ObserverView: NSView { - var update: (CGSize, Bool) -> Void + var update: (CGSize) -> Void private var observers: [NSObjectProtocol] = [] - init(update: @escaping (CGSize, Bool) -> Void) { self.update = update; super.init(frame: .zero) } + init(update: @escaping (CGSize) -> Void) { self.update = update; super.init(frame: .zero) } required init?(coder: NSCoder) { fatalError() } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() observers.forEach(NotificationCenter.default.removeObserver) observers = [] guard let window else { return } - for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification, NSWindow.didBecomeKeyNotification, - NSWindow.didResignKeyNotification, NSWindow.willCloseNotification, - NSWindow.didChangeOcclusionStateNotification] { + for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification] { observers.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.report() } }) @@ -35,15 +33,13 @@ struct PanelWindowObserver: NSViewRepresentable { let chrome = CGSize(width: max(0, window.frame.width - window.contentLayoutRect.width), height: max(0, window.frame.height - window.contentLayoutRect.height)) let size = PanelLayout.contentSize(visible: frame, chrome: chrome) - let visible = window.isVisible DispatchQueue.main.async { [weak self, weak window] in guard let self, let window else { return } - self.update(size, visible) - // SwiftUI can resize a MenuBarExtra after the system chose its anchor origin. - // Clamp after layout as well as on moves; keep the native status-item scene. + self.update(size) + // Keep the complete panel inside its screen and horizontally centered after layout. DispatchQueue.main.async { [weak window] in guard let window, window.isVisible else { return } - let adjusted = PanelLayout.constrainedFrame(window.frame, visible: frame) + let adjusted = PanelLayout.centeredFrame(window.frame, visible: frame) if abs(adjusted.minX - window.frame.minX) > 0.5 || abs(adjusted.minY - window.frame.minY) > 0.5 { window.setFrameOrigin(adjusted.origin) } diff --git a/kymo/Features/Settings/AppearanceSettingsView.swift b/kymo/Features/Settings/AppearanceSettingsView.swift index 0818667..d63d75b 100644 --- a/kymo/Features/Settings/AppearanceSettingsView.swift +++ b/kymo/Features/Settings/AppearanceSettingsView.swift @@ -5,6 +5,7 @@ import AppKit struct AppearanceSettingsView: View { @Bindable var preferences: AppearancePreferences @Bindable var language: LanguagePreferences + @Bindable var sampling: SamplingPreferences let presentation: SettingsPresentation @Environment(\.locale) private var locale @State private var colorPicker = CustomColorPicker() @@ -24,6 +25,7 @@ struct AppearanceSettingsView: View { switch selectedPage { case .appearance: appearancePage case .language: languagePage + case .monitoring: monitoringPage case .about: aboutPage } } @@ -82,6 +84,17 @@ struct AppearanceSettingsView: View { .padding(.top, 6) } + private var monitoringPage: some View { + Form { + Section { + LabeledContent("sampling.background") { + IntervalControl(milliseconds: $sampling.backgroundMilliseconds) + } + Text("sampling.backgroundHelp").font(.callout).foregroundStyle(.secondary) + } + }.formStyle(.grouped).padding(.horizontal, 12).padding(.top, 6) + } + private var languagePage: some View { Form { Section { @@ -207,12 +220,13 @@ private extension AppAppearance { } private enum SettingsPage: String, CaseIterable, Identifiable { - case appearance, language, about + case appearance, language, monitoring, about var id: String { rawValue } var title: LocalizedStringKey { switch self { case .appearance: "settings.appearance" case .language: "settings.language" + case .monitoring: "settings.monitoring" case .about: "settings.about" } } @@ -220,6 +234,7 @@ private enum SettingsPage: String, CaseIterable, Identifiable { switch self { case .appearance: "paintpalette" case .language: "globe" + case .monitoring: "timer" case .about: "info.circle" } } diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings index 78b2f9c..b77f33d 100644 --- a/kymo/Resources/Localizable.xcstrings +++ b/kymo/Resources/Localizable.xcstrings @@ -262,6 +262,213 @@ } } }, + "action.file" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "File" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "文件" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "檔案" + } + } + } + }, + "action.closeWindow" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Close Window" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "关闭窗口" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "關閉視窗" + } + } + } + }, + "action.edit" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "编辑" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "編輯" + } + } + } + }, + "action.undo" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Undo" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "撤销" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "復原" + } + } + } + }, + "action.redo" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Redo" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "重做" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "重做" + } + } + } + }, + "action.cut" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Cut" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "剪切" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "剪下" + } + } + } + }, + "action.copy" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "复制" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "複製" + } + } + } + }, + "action.paste" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Paste" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "粘贴" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "貼上" + } + } + } + }, + "action.selectAll" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Select All" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "全选" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "全選" + } + } + } + }, "action.pause" : { "extractionState" : "manual", "localizations" : { @@ -2400,9 +2607,24 @@ }, "panel.total" : { "localizations" : { - "en" : { "stringUnit" : { "state" : "translated", "value" : "Total" } }, - "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "总占用" } }, - "zh-Hant" : { "stringUnit" : { "state" : "translated", "value" : "總佔用" } } + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Total" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "总占用" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "總佔用" + } + } } }, "panel.totalNetwork" : { @@ -2546,6 +2768,282 @@ } } }, + "sampling.panel" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Panel refresh interval" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "面板刷新间隔" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "面板重新整理間隔" + } + } + } + }, + "sampling.background" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Background refresh interval" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "后台刷新间隔" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "背景重新整理間隔" + } + } + } + }, + "sampling.backgroundHelp" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Applies while the panel is closed. Default: 5 seconds. Panel interval is adjusted in its toolbar." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "仅在面板关闭时生效,默认 5 秒。面板打开时的间隔在顶部工具栏单独调整。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "僅在面板關閉時生效,預設 5 秒。面板開啟時的間隔在頂部工具列獨立調整。" + } + } + } + }, + "sampling.seconds" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Seconds" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "秒数" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "秒數" + } + } + } + }, + "sampling.unit" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "s" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "秒" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "秒" + } + } + } + }, + "sampling.interval" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Refresh interval" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "刷新间隔" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "重新整理間隔" + } + } + } + }, + "sampling.bounds" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "0.5–1800 seconds, in 0.1-second steps" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "0.5–1800 秒,步进 0.1 秒" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "0.5–1800 秒,每次 0.1 秒" + } + } + } + }, + "settings.monitoring" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Monitoring" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "监控" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "監控" + } + } + } + }, + "panel.pin" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pin panel on top" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "固定面板并置顶" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "固定面板並置頂" + } + } + } + }, + "panel.unpin" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unpin panel" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "取消固定面板" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "取消固定面板" + } + } + } + }, + "panel.pinned" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pinned" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已固定" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已固定" + } + } + } + }, + "panel.unpinned" : { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not pinned" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未固定" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "未固定" + } + } + } + }, "settings.about" : { "localizations" : { "en" : { diff --git a/kymo/UI/Charts/PanelCurveGeometry.swift b/kymo/UI/Charts/PanelCurveGeometry.swift index 5184893..ef57571 100644 --- a/kymo/UI/Charts/PanelCurveGeometry.swift +++ b/kymo/UI/Charts/PanelCurveGeometry.swift @@ -6,20 +6,20 @@ nonisolated enum PanelCurveGeometry { let value: Double } - static func isAppend(from old: [Date], to new: [Date]) -> Bool { + static func isAppend(from old: [Date], to new: [Date], maximumGap: TimeInterval = 5) -> Bool { guard old.count > 1, let previous = old.last, let next = new.last, - next > previous, next.timeIntervalSince(previous) <= 5 else { return false } + next > previous, next.timeIntervalSince(previous) <= maximumGap else { return false } if new.count == old.count + 1 { return Array(new.dropLast()) == old } return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast()) } - static func runs(dates: [Date], values: [Double?]) -> [[Sample]] { + static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set = []) -> [[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 && (dates[index].timeIntervalSince(dates[index - 1]) > 5 || dates[index] <= dates[index - 1]) { flush() } + if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > maximumGap || dates[index] <= dates[index - 1]) { flush() } run.append(Sample(date: dates[index], value: value)) } flush() diff --git a/kymo/UI/Charts/PanelTrendChart.swift b/kymo/UI/Charts/PanelTrendChart.swift index 1aac778..52ef8f4 100644 --- a/kymo/UI/Charts/PanelTrendChart.swift +++ b/kymo/UI/Charts/PanelTrendChart.swift @@ -14,10 +14,13 @@ struct PanelTrendChart: View { var firstLabel: LocalizedStringKey = "panel.total" var secondLabel: LocalizedStringKey = "network.upload" var thirdLabel: LocalizedStringKey = "cpu.system" + var expectedInterval: TimeInterval = 2 + var boundaryDates: Set = [] @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var retainedScale: Double = 1 @State private var smallSamples = 0 @State private var hoveredDate: Date? + @State private var hoverPoint: CGPoint? @State private var previousBegin: Date? @State private var previousEnd: Date? @State private var progress: CGFloat = 1 @@ -35,18 +38,35 @@ struct PanelTrendChart: View { if fixedScale == nil { return MetricFormat.rate(value) } return MetricFormat.bytes(UInt64(max(0, value))) } - private func value(_ values: [Double?]) -> String { - guard let index, index < values.count else { return "--" } - return formatted(values[index]) - } private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color) -> some View { HStack(spacing: 3) { RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7) Text(label) - Text(verbatim: value(values)).monospacedDigit() + Text(verbatim: formatted(values.last ?? nil)).monospacedDigit() }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8) } + private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View { + HStack(spacing: 6) { + RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8) + Text(label) + Spacer(minLength: 4) + Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit() + } + } + private func tooltip(index: Int) -> some View { + VStack(alignment: .leading, spacing: 5) { + Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary) + tooltipRow(firstLabel, values: first, tint: color, index: index) + if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) } + if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) } + } + .font(.system(size: 10)).padding(8) + .background(Color("PanelTooltip"), in: .rect(cornerRadius: 7)) + .overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2))) + .shadow(color: .black.opacity(0.2), radius: 5, y: 2) + } + var body: some View { VStack(spacing: 3) { HStack(spacing: 10) { @@ -67,7 +87,7 @@ struct PanelTrendChart: View { GeometryReader { proxy in ZStack(alignment: .topLeading) { PanelCurveCanvas(dates: dates, series: [first, second, third], colors: [color, secondColor, thirdColor], - scale: scale, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress) + scale: scale, maximumGap: max(5, expectedInterval * 2), boundaryDates: boundaryDates, 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 @@ -87,22 +107,33 @@ struct PanelTrendChart: View { switch phase { case .active(let point): if let begin = dates.first, let end = dates.last { + hoverPoint = point hoveredDate = begin.addingTimeInterval(end.timeIntervalSince(begin) * min(1, max(0, point.x / max(1, proxy.size.width)))) } - case .ended: hoveredDate = nil + case .ended: hoveredDate = nil; hoverPoint = nil } } - }.frame(height: 58).clipped() + .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) } HStack { if let date = dates.first { Text(date, style: .time) } Spacer(minLength: 0) - if hoveredDate != nil, let index { Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.primary) } - Spacer(minLength: 0) if let date = dates.last { Text(date, style: .time) } }.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 let target = maximum @@ -111,7 +142,7 @@ struct PanelTrendChart: View { smallSamples += 1 if smallSamples >= 10 { retainedScale = target; smallSamples = 0 } } else { smallSamples = 0 } - let append = PanelCurveGeometry.isAppend(from: old, to: new) + let append = PanelCurveGeometry.isAppend(from: old, to: new, maximumGap: max(5, expectedInterval * 2)) && !(new.last.map { boundaryDates.contains($0) } ?? false) var transaction = Transaction(); transaction.disablesAnimations = true withTransaction(transaction) { previousBegin = append && !reduceMotion ? old.first : nil @@ -134,6 +165,8 @@ private struct PanelCurveCanvas: View, Animatable { let series: [[Double?]] let colors: [Color] let scale: Double + let maximumGap: TimeInterval + let boundaryDates: Set let previousBegin: Date? let previousEnd: Date? var progress: CGFloat @@ -157,8 +190,9 @@ private struct PanelCurveCanvas: View, Animatable { 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 (values, tint) in zip(series, colors) { - for run in PanelCurveGeometry.runs(dates: dates, values: values) { + for (seriesIndex, entry) in zip(series, colors).enumerated() { + let (values, tint) = entry + for run in PanelCurveGeometry.runs(dates: dates, values: values, maximumGap: maximumGap, boundaryDates: boundaryDates) { let points = run.map { item in CGPoint(x: end > begin ? size.width * (item.date.timeIntervalSinceReferenceDate - begin) / (end - begin) : size.width, y: size.height * (1 - min(1, max(0, item.value / scale)))) @@ -176,7 +210,7 @@ private struct PanelCurveCanvas: View, Animatable { var area = line area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath() context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height))) - context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round)) + context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round, dash: seriesIndex == 1 ? [4, 2] : seriesIndex == 2 ? [1, 2] : [])) } } } diff --git a/kymo/UI/Components/IntervalControl.swift b/kymo/UI/Components/IntervalControl.swift new file mode 100644 index 0000000..e1f1a03 --- /dev/null +++ b/kymo/UI/Components/IntervalControl.swift @@ -0,0 +1,43 @@ +import SwiftUI + +/// Generic millisecond interval editor; callers own persistence and scheduling. +struct IntervalControl: View { + @Binding var milliseconds: Int + var range: ClosedRange = 500...1_800_000 + var step = 100 + @State private var text = "" + @FocusState private var focused: Bool + + var body: some View { + HStack(spacing: 3) { + TextField("sampling.seconds", text: $text) + .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing) + .frame(width: 64).focused($focused) + .onChange(of: text) { _, value in + if let seconds = Double(value.replacingOccurrences(of: ",", with: ".")), seconds.isFinite, + seconds >= Double(range.lowerBound) / 1000, seconds <= Double(range.upperBound) / 1000 { + milliseconds = quantized(seconds) + } + } + .onSubmit { commit() } + Text("sampling.unit").foregroundStyle(.secondary).fixedSize() + Stepper("sampling.interval", value: $milliseconds, in: range, step: step).labelsHidden().fixedSize() + } + .font(.system(size: 11)).monospacedDigit().controlSize(.small) + .fixedSize(horizontal: true, vertical: false) + .onAppear { synchronize() } + .onChange(of: milliseconds) { _, _ in if !focused { synchronize() } } + .onChange(of: focused) { _, value in if !value { commit() } } + .help(Text("sampling.bounds")) + } + + private func quantized(_ seconds: Double) -> Int { + let clamped = min(Double(range.upperBound), max(Double(range.lowerBound), seconds * 1000)) + return min(range.upperBound, max(range.lowerBound, Int((clamped / Double(step)).rounded()) * step)) + } + private func synchronize() { text = String(format: "%.1f", Double(milliseconds) / 1000) } + private func commit() { + if let seconds = Double(text.replacingOccurrences(of: ",", with: ".")), seconds.isFinite { milliseconds = quantized(seconds) } + synchronize() + } +} diff --git a/kymo/UI/Components/ResourceCard.swift b/kymo/UI/Components/ResourceCard.swift index 94e1e05..9501a56 100644 --- a/kymo/UI/Components/ResourceCard.swift +++ b/kymo/UI/Components/ResourceCard.swift @@ -15,11 +15,11 @@ struct ResourceCard: View { Image(systemName: symbol).foregroundStyle(color) }.font(.system(size: 13, weight: .semibold)).fixedSize() Spacer(minLength: 0) - VStack(alignment: .trailing, spacing: 0) { + HStack(alignment: .firstTextBaseline, spacing: 6) { AnimatedMetricText(value: value) - .font(.system(size: 20, weight: .semibold, design: .rounded)) + .font(.system(size: 13, weight: .semibold)) if let secondaryValue { - AnimatedMetricText(value: secondaryValue).font(.system(size: 11, weight: .semibold)) + AnimatedMetricText(value: secondaryValue).font(.system(size: 13, weight: .semibold)) } }.foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.65) } diff --git a/kymoTests/PanelAssetChecks.swift b/kymoTests/PanelAssetChecks.swift index 27cbfb6..64d32cc 100644 --- a/kymoTests/PanelAssetChecks.swift +++ b/kymoTests/PanelAssetChecks.swift @@ -5,11 +5,21 @@ import AppKit let bundle = Bundle(path: CommandLine.arguments[1])! for appearance in [NSAppearance.Name.aqua, .darkAqua] { NSAppearance(named: appearance)!.performAsCurrentDrawingAppearance { - for name in ["PanelCard", "MetricCPU", "MetricGPU", "MetricMemory", "MetricNetwork", "MetricDisk", "MetricBattery"] { + for name in ["PanelCard", "PanelTooltip", "MetricCPU", "MetricGPU", "MetricMemory", "MetricNetwork", "MetricDisk", "MetricBattery", "SeriesUser", "SeriesSystem", "SeriesUpload"] { guard let color = NSColor(named: NSColor.Name(name), bundle: bundle)?.usingColorSpace(.sRGB) else { fatalError("Missing color: \(name)") } - precondition(abs(color.alphaComponent - (name == "PanelCard" ? 0.68 : 1)) < 0.005, "Unexpected alpha \(name)") + precondition(abs(color.alphaComponent - (name == "PanelCard" ? 0.68 : name == "PanelTooltip" ? 0.97 : 1)) < 0.005, "Unexpected alpha \(name)") if name == "MetricGPU" && appearance == .darkAqua { precondition(color.blueComponent > 0.99) } } + let names = ["MetricCPU", "SeriesUser", "SeriesSystem"] + let colors = names.map { NSColor(named: NSColor.Name($0), bundle: bundle)!.usingColorSpace(.sRGB)! } + for i in 0.. 0.25, "CPU series hues too close") + } + } } } print("PASS: compiled light/dark semantic colors exist, card translucent/semantic colors opaque, GPU blue component is normalized") diff --git a/kymoTests/PanelCurveChecks.swift b/kymoTests/PanelCurveChecks.swift index d2e036a..735a0cc 100644 --- a/kymoTests/PanelCurveChecks.swift +++ b/kymoTests/PanelCurveChecks.swift @@ -12,6 +12,10 @@ import Foundation precondition(PanelCurveGeometry.runs(dates: [dates[0], dates[4]], values: [0.3, 0.5]).count == 2) precondition(PanelCurveGeometry.runs(dates: [dates[1], dates[0]], values: [0.3, 0.5]).count == 2) precondition(PanelCurveGeometry.runs(dates: dates, values: []).isEmpty) + let slow = [Date(timeIntervalSinceReferenceDate: 0), Date(timeIntervalSinceReferenceDate: 1800), Date(timeIntervalSinceReferenceDate: 3600)] + 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") } } diff --git a/kymoTests/PanelLayoutChecks.swift b/kymoTests/PanelLayoutChecks.swift index 4f9bec6..a4013c6 100644 --- a/kymoTests/PanelLayoutChecks.swift +++ b/kymoTests/PanelLayoutChecks.swift @@ -8,13 +8,17 @@ import CoreGraphics precondition(content.width + 4 <= visible.width - 32 && content.height + 12 <= visible.height - 32) for frame in [CGRect(x: -500, y: 500, width: 1240, height: 820), CGRect(x: 1400, y: -800, width: 2000, height: 1200)] { precondition(visible.insetBy(dx: 16, dy: 16).contains(PanelLayout.constrainedFrame(frame, visible: visible))) + let centered = PanelLayout.centeredFrame(frame, visible: visible) + precondition(abs(centered.midX - visible.midX) < 0.001) + precondition(visible.insetBy(dx: 16, dy: 16).contains(centered)) } } for size in [CGSize(width: 1240, height: 820), CGSize(width: 1160, height: 810)] { let square = PanelLayout.resourceRowHeight(size: size) let wide = PanelLayout.firstRowWideCardWidth(size: size) precondition(square >= 220 && square <= 230) - precondition(abs(2 * wide + square + 16 - (size.width - 20)) < 0.001) + precondition(abs(PanelLayout.batteryWidth(size: size) / square - 4.0 / 3.0) < 0.001) + precondition(abs(2 * wide + PanelLayout.batteryWidth(size: size) + 16 - (size.width - 20)) < 0.001) } let input: [ProcessMetrics] = (0..<2000).map { (index: Int) -> ProcessMetrics in let id = ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0) diff --git a/kymoTests/PanelWindowChecks.swift b/kymoTests/PanelWindowChecks.swift new file mode 100644 index 0000000..d3308c4 --- /dev/null +++ b/kymoTests/PanelWindowChecks.swift @@ -0,0 +1,44 @@ +import AppKit +import SwiftUI + +@main struct PanelWindowChecks { + @MainActor static func main() { + _ = NSApplication.shared + NSApp.setActivationPolicy(.accessory) + Task { @MainActor in + var visible = false + let controller = MenuPanelController(installStatusItem: false, visibility: { visible = $0 }) { _ in Color.clear } + precondition(!controller.presentation.isPinned) + controller.show() + try? await Task.sleep(for: .milliseconds(150)) + precondition(controller.panel.isVisible && visible) + precondition(controller.panel.canBecomeKey && !controller.panel.canBecomeMain) + let screen = controller.panel.screen! + precondition(abs(controller.panel.frame.midX - screen.visibleFrame.midX) < 1) + controller.dismissForOutsideInteraction() + precondition(!controller.panel.isVisible && !visible) + controller.presentation.isPinned = true + controller.show() + precondition(controller.panel.level == .floating && !controller.panel.hidesOnDeactivate) + controller.dismissForOutsideInteraction() + precondition(controller.panel.isVisible && visible) + controller.panel.close() + precondition(!controller.panel.isVisible && !visible) + controller.show() + precondition(controller.presentation.isPinned) + controller.panel.performClose(nil) + precondition(!controller.panel.isVisible && !visible) + controller.show() + controller.presentation.isPinned = false + precondition(controller.panel.level == .normal) + controller.dismissForOutsideInteraction() + precondition(!controller.panel.isVisible) + controller.presentation.isPinned = true + controller.shutdown() + precondition(!controller.presentation.isPinned && !visible) + print("PASS: real NSPanel visibility/centering/key eligibility, outside-dismiss policy, floating pin, explicit close/reopen, unpin and shutdown reset") + NSApp.terminate(nil) + } + NSApp.run() + } +} diff --git a/kymoTests/README.md b/kymoTests/README.md index b049ae2..166cd43 100644 --- a/kymoTests/README.md +++ b/kymoTests/README.md @@ -146,3 +146,18 @@ swiftc -module-cache-path /private/tmp/kymo-check-cache \ ``` 该检查不证明悬浮事件投递或动画观感。 + +## 独立刷新频率与固定窗口检查 + +```bash +swiftc -module-cache-path /private/tmp/kymo-check-cache \ + kymo/Core/Models/*.swift kymo/Core/Monitors/*.swift \ + kymo/Core/Services/*.swift kymo/Core/Extensions/*.swift \ + kymoTests/SamplingIntervalChecks.swift -o /private/tmp/kymo-interval-checks +/private/tmp/kymo-interval-checks +swiftc -parse-as-library -module-cache-path /private/tmp/kymo-check-cache \ + kymo/Features/MenuBar/MenuPanelController.swift kymo/Features/MenuBar/PanelLayout.swift \ + kymoTests/PanelWindowChecks.swift -o /private/tmp/kymo-window-checks +``` + +窗口程序应放进独立 `.app/Contents/MacOS`、配置隔离 Info.plist 并签名后运行。前者覆盖双频持久化/边界、30min 等待唤醒、暂停优先级、隐藏进程清理及长间隔初始列表发布;后者创建真实 NSPanel,检查居中/层级/外部关闭策略/显式关闭/退出复位,不安装状态栏图标。外部关闭策略方法检查不等于实际系统鼠标事件已投递。GUI 工具能力与证据见 [统一面板验证](../docs/unified-panel-validation.md)。 diff --git a/kymoTests/SamplingChecks.swift b/kymoTests/SamplingChecks.swift index cd2bf90..b7a0233 100644 --- a/kymoTests/SamplingChecks.swift +++ b/kymoTests/SamplingChecks.swift @@ -85,7 +85,9 @@ import Foundation await sampler.reset() let reset = await sampler.sample() precondition(reset.cpu == nil) - let store = MetricsStore() + let sampling = SamplingPreferences(defaults: defaults) + sampling.backgroundMilliseconds = 500 + let store = MetricsStore(sampling: sampling) try await waitUntil { store.snapshot.cpu != nil } precondition(store.snapshot.cpu != nil) store.togglePause() diff --git a/kymoTests/SamplingIntervalChecks.swift b/kymoTests/SamplingIntervalChecks.swift new file mode 100644 index 0000000..c7783f0 --- /dev/null +++ b/kymoTests/SamplingIntervalChecks.swift @@ -0,0 +1,92 @@ +import Foundation + +@main struct SamplingIntervalChecks { + @MainActor static func main() async throws { + let suite = "kymo-interval-checks-" + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = SamplingPreferences(defaults: defaults) + precondition(preferences.panelMilliseconds == 2000 && preferences.backgroundMilliseconds == 5000) + for (input, expected) in [(Int.min, 500), (549, 500), (550, 600), (1501, 1500), (Int.max, 1_800_000)] { + preferences.panelMilliseconds = input + precondition(preferences.panelMilliseconds == expected) + } + preferences.backgroundMilliseconds = 1799900 + let restored = SamplingPreferences(defaults: defaults) + precondition(restored.panelMilliseconds == 1_800_000 && restored.backgroundMilliseconds == 1799900) + defaults.set(Double.nan, forKey: "sampling.panelMilliseconds") + defaults.set(true, forKey: "sampling.backgroundMilliseconds") + let invalid = SamplingPreferences(defaults: defaults) + precondition(invalid.panelMilliseconds == 2000 && invalid.backgroundMilliseconds == 5000) + preferences.panelMilliseconds = 500 + preferences.backgroundMilliseconds = 1_800_000 + let store = MetricsStore(sampling: preferences) + store.setPanelVisible(true) + try await until { store.snapshot.processes != nil } + precondition(store.effectiveMilliseconds == 500) + store.setPanelVisible(false) + precondition(store.snapshot.processes == nil && store.effectiveMilliseconds == 1_800_000) + try await Task.sleep(for: .milliseconds(200)) + let hiddenDate = store.snapshot.date + preferences.panelMilliseconds = 700 + try await Task.sleep(for: .milliseconds(650)) + precondition(store.snapshot.date == hiddenDate && store.snapshot.processes == nil) + preferences.backgroundMilliseconds = 500 + try await until { store.snapshot.date > hiddenDate } + let first = store.snapshot.date + try await until { store.snapshot.date > first } + precondition(store.snapshot.date.timeIntervalSince(first) >= 0.45) + store.togglePause() + let paused = store.snapshot.date + preferences.panelMilliseconds = 1_800_000 + store.setPanelVisible(true) + preferences.backgroundMilliseconds = 800 + try await Task.sleep(for: .milliseconds(650)) + precondition(store.isPaused && store.snapshot.date == paused) + store.togglePause() + try await until { store.snapshot.date > paused && store.snapshot.processes != nil } + precondition(store.effectiveMilliseconds == 1_800_000) + precondition(store.history.samples.last?.breakBefore == true) + store.togglePause() + let probe = DelayedProcessRead() + let deferred = SystemSampler(processRead: { probe.read(&$0) }) + await deferred.setProcessVisible(true) + _ = await deferred.sample() + await deferred.setProcessVisible(false) + await deferred.setProcessVisible(true) + let delivered = ProcessDelivery() + _ = await deferred.sample(processUpdate: { _ in Task { await delivered.received() } }) + let deadline = ContinuousClock.now.advanced(by: .seconds(4)) + while !(await delivered.value) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } + let didDeliver = await delivered.value + precondition(didDeliver, "Reopened process request must complete without another sample") + precondition(probe.count >= 2 && probe.peak == 1) + await deferred.setProcessVisible(false) + 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 { + let deadline = ContinuousClock.now.advanced(by: .seconds(4)) + while !predicate() && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } + precondition(predicate(), "Timed out waiting for schedule update") + } +} + +private actor ProcessDelivery { + private(set) var value = false + func received() { value = true } +} + +private final class DelayedProcessRead: @unchecked Sendable { + private let lock = NSLock() + private var active = 0 + private var reads = 0 + private var maximum = 0 + var count: Int { lock.lock(); defer { lock.unlock() }; return reads } + var peak: Int { lock.lock(); defer { lock.unlock() }; return maximum } + 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) + return monitor.sample() + } +}