From 0c846a21278cd55d416443daf7e790f5604c2cd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A0=81=E5=86=9C=E9=98=BF=E6=A5=A0?= Date: Fri, 30 Oct 2026 00:45:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(menubar):=20=E5=AE=9E=E7=8E=B0=E8=B6=8B?= =?UTF-8?q?=E5=8A=BF=E9=9D=A2=E6=9D=BF=E5=A4=96=E4=BE=A7=E8=AF=A6=E6=83=85?= =?UTF-8?q?=E4=B8=8E=E4=B8=89=E8=AF=AD=E5=A4=96=E8=A7=82=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 接入有界趋势、平滑滚动、菜单式外侧详情、底部操作与三语文案,装配独立外观设置和 Dock 生命周期。 合并跟随系统外观刷新、自选颜色入口与色块绘制修复,保留用户确认的配色联动、重启保存及滚动验收。 多场景视觉与长期资源验证边界仍记录于 docs。 --- docs/README.md | 1 + docs/architecture.md | 20 +- docs/development.md | 2 +- docs/implementation-plan.md | 65 +- docs/roadmap.md | 8 +- docs/stage-b-validation.md | 103 ++ kymo.xcodeproj/project.pbxproj | 4 + kymo/App/kymoApp.swift | 8 +- kymo/Core/Extensions/MetricFormat.swift | 15 + kymo/Core/Models/MetricHistory.swift | 20 + kymo/Core/Models/MetricsSnapshot.swift | 1 + kymo/Core/Monitors/SystemSampler.swift | 1 + .../Core/Services/AppearancePreferences.swift | 36 + kymo/Core/Services/MetricsStore.swift | 2 + kymo/Features/MenuBar/MenuBarLabel.swift | 10 +- kymo/Features/MenuBar/MenuPanelView.swift | 129 ++- .../Settings/AppearanceSettingsView.swift | 55 ++ .../Features/Settings/CustomColorPicker.swift | 43 + kymo/Features/Settings/CustomColorWell.swift | 53 + .../Settings/SettingsWindowLifecycle.swift | 38 + kymo/Resources/Localizable.xcstrings | 903 ++++++++++++++++++ kymo/UI/Charts/MiniTrendChart.swift | 82 ++ kymo/UI/Charts/TrendScroll.swift | 18 + kymo/UI/Components/AppearanceStyle.swift | 104 ++ kymo/UI/Components/DetailPlacement.swift | 18 + kymo/UI/Components/HoverDetailPresenter.swift | 124 +++ kymo/UI/Components/MetricRow.swift | 61 ++ kymoTests/PresentationChecks.swift | 68 ++ kymoTests/README.md | 30 +- kymoTests/SamplingChecks.swift | 33 + kymoTests/TrendScrollChecks.swift | 20 + 31 files changed, 2033 insertions(+), 42 deletions(-) create mode 100644 docs/stage-b-validation.md create mode 100644 kymo/Core/Extensions/MetricFormat.swift create mode 100644 kymo/Core/Models/MetricHistory.swift create mode 100644 kymo/Core/Services/AppearancePreferences.swift create mode 100644 kymo/Features/Settings/AppearanceSettingsView.swift create mode 100644 kymo/Features/Settings/CustomColorPicker.swift create mode 100644 kymo/Features/Settings/CustomColorWell.swift create mode 100644 kymo/Features/Settings/SettingsWindowLifecycle.swift create mode 100644 kymo/Resources/Localizable.xcstrings create mode 100644 kymo/UI/Charts/MiniTrendChart.swift create mode 100644 kymo/UI/Charts/TrendScroll.swift create mode 100644 kymo/UI/Components/AppearanceStyle.swift create mode 100644 kymo/UI/Components/DetailPlacement.swift create mode 100644 kymo/UI/Components/HoverDetailPresenter.swift create mode 100644 kymo/UI/Components/MetricRow.swift create mode 100644 kymoTests/PresentationChecks.swift create mode 100644 kymoTests/TrendScrollChecks.swift diff --git a/docs/README.md b/docs/README.md index 3fcbdcd..69f72de 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ | [development.md](development.md) | 开发环境搭建、构建调试、测试 Target 添加与协作规范 | | [implementation-plan.md](implementation-plan.md) | 已定稿方案、阶段顺序与实施进度 | | [stage-a-validation.md](stage-a-validation.md) | A 阶段采样、资源及 UI 验证记录 | +| [stage-b-validation.md](stage-b-validation.md) | B 阶段面板、外观与三语验证记录 | | [roadmap.md](roadmap.md) | 版本路线图与里程碑 | ## 快速链接 diff --git a/docs/architecture.md b/docs/architecture.md index 8fbc46c..4e5e57e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -34,7 +34,7 @@ Kymo 是一款 macOS 菜单栏常驻的资源监控工具,设计目标为「 依赖方向自上而下、单向依赖:`Features → UI → Core → 系统 API`。 禁止反向引用、禁止 Feature 之间横向依赖。 -## 3. 数据流(A 阶段首批已实现) +## 3. 数据流(A 与 B 阶段当前实现) `App` 持有一个 `MetricsStore`(MainActor、`@Observable`),注入菜单栏 label 与面板。 仓库创建唯一 Task,调用 `SystemSampler` actor,在后台串行读取 `CPUMonitor`、 @@ -51,8 +51,22 @@ CPU 计数按 UInt32 回绕计算,`host_processor_info` 分配的缓冲区每 Swap 和压力通过 sysctl 分别读取,失败仅令对应子项为空;压力不由占用率推算。 GPU 的 IOReport spike 能枚举本机通道,但订阅返回空,当前快照 GPU 为 nil: -菜单栏移除 GPU,临时面板说明不可用。CPU、内存不受影响。 -后续网络、存储、电池采样器、通用 ResourceMonitor 协议、设置及历史趋势尚未实现。 +菜单栏移除 GPU,正式面板保留 GPU 行与不可用详情。CPU、内存不受影响。 +网络、存储、电池采样器及通用 ResourceMonitor 协议尚未实现。 + +### 面板、历史与外观 + +- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本(默认间隔约 2 分钟);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线。 +- `MiniTrendChart` 只接收历史值与颜色,使用 SwiftUI Canvas 绘制圆角平滑曲线,无独立计时器。 +- `MetricRow` 接收标题、数值、历史与详情内容;鼠标进入 150ms 后通过 `HoverDetailPresenter` 在独立非激活 NSPanel 中呈现详情,主面板不改变尺寸。详情窗口作为主窗口的 child,默认右侧、空间不足向左,并约束在 screen.visibleFrame 内。鼠标可从指标行移入详情,离开两者有 120ms 跨窗口缓冲后收起;主面板隐藏/关闭或视图拆卸时清理子窗口与观察器。按钮保留键盘与 VoiceOver 入口,不提供移出后点击固定。 +- 面板宽 320pt,当前包含 CPU / GPU / 内存、负载与开机小时数;CPU 详情含用户/系统与每核热条,内存详情含分类/Swap/压力。网络、存储、电池待 C 阶段。 +- 数值与悬浮过渡仅在可见行启用,遵循减少动态效果;面板关闭不挂载独立动画时钟。趋势追加样本时使用 0.35 秒位置插值,满容量保留一个出场点并裁剪;首次显示、非连续更新和减少动态效果直接显示当前历史。仅每次可见更新安排一次可取消任务,无周期动画时钟。 +- 面板沿用 MenuBarExtra 系统窗口背景,不叠加整块自绘玻璃;操作按钮使用系统 `.glass`。TV1 的真实材质融合验收尚未完成,不能由离屏渲染认定通过。 +- `AppearancePreferences` 仅依赖 Foundation / Observation,持久化外观、系统/六种预设/自选 RGB 强调色。UI 层 `AppearanceStyle` 将偏好映射为明确的深/浅色及窗口级 NSAppearance / Color。跟随系统从全局偏好 AppleInterfaceStyle 独立解析,监听系统主题通知及 NSApp effectiveAppearance 变化后刷新;为 SwiftUI 同时提供非 nil 的 preferredColorScheme 与 colorScheme 环境,避免返回 nil 和失焦后重新继承窗口残留模式。用户持久化值仍为 system,App 全局 appearance 不被修改。该系统偏好键/主题通知属于平台约定,系统动态切换仍需实机验证;外观覆盖作用于面板与设置,不作用于菜单栏标签。 +- App 注入同一个偏好仓库,注册独立 Settings 场景;Settings 特性当前仅实现外观表单,不横向引用 MenuBar 特性。 +- 显式设置 `LSUIElement=true` 保持默认无 Dock;设置视图出现切换 `.regular` 并激活,Settings 自己的窗口观察器在重新成为 key 时保持 `.regular`、关闭时恢复 `.accessory`。该 R14 实现为引入设置场景所需而前置,Dock 随设置开关已通过用户本机反馈验收。 +- 自选强调色使用设置特性持有的 `CustomColorPicker` 控制系统 NSColorPanel;选 custom 延迟到下一次主线程调度后打开。色块使用固定 44×26pt 原生 NSButton,直接在 bounds 内绘制 RGB(不使用可缩放的符号图像),保留 target/action 并允许失焦首次点击,面板显式 makeKeyAndOrderFront / orderFrontRegardless,连续回写 RGB,可重复打开,设置关闭时仅清理自身持有的颜色面板。记录入口请求与可见状态日志以便定位。窗口观察/外观/详情锚点 NSView 的 hitTest 均返回 nil,避免拦截正常控件。 +- 用户文案集中在 `Resources/Localizable.xcstrings`,覆盖 en / zh-Hans / zh-Hant;指标缩写、品牌、版本及单位保留通用写法。 ## 4. 并发模型 diff --git a/docs/development.md b/docs/development.md index 3d34de1..7fffe6b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -25,7 +25,7 @@ open kymo.xcodeproj `kymo/` 目录内的文件自动纳入 Target,**新增/移动文件无需手工修改 project.pbxproj**; - `Info.plist` 由构建系统生成(`GENERATE_INFOPLIST_FILE = YES`),需要新增键值时在 Target → Info 标签页配置; -- 菜单栏应用无 Dock 图标:由 `MenuBarExtra` 场景天然保证,无需手动设置 `LSUIElement`; +- 菜单栏应用默认无 Dock 图标:显式设置 `LSUIElement=true`;打开设置窗口时临时切换为常规应用,关闭后恢复菜单栏模式(当前实现待实机验收); - 构建设置开启了 Swift 6 默认 MainActor 隔离与 Approachable Concurrency,新增并发代码时注意隔离边界。 ## 4. 调试技巧 diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 9fbdc7d..d92f3d1 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -76,7 +76,7 @@ Kymo 定位为轻量、低功耗、无干扰的 macOS 菜单栏资源监控工 结构说明: - **指标区(一级概况)**:每项一行(名称 + 迷你趋势图 + 数值),宽度固定约 320pt,高度随模块开关自适应;默认显示 CPU / GPU / 内存 / 网络 / 存储,电池按机型出现; -- **悬浮详情(二级信息)**:鼠标悬浮某指标行,行下方以灵动展开动画显示详情卡(约 150ms 延迟防误触),移出收起: +- **悬浮详情(二级信息)**:鼠标悬浮某指标行,面板外侧以子菜单式详情窗口显示详情(约 150ms 延迟防误触),右侧空间不足时向左展开;允许鼠标移入详情,离开行与详情后收起(按 B 阶段用户反馈修正): | 板块 | 详情内容 | | --- | --- | | CPU | 每核占用热条、系统/用户占比 | @@ -262,3 +262,66 @@ Debug 构建通过,`git diff --check` 通过;修复后实际双指标显示 用户重新运行并提供截图,完整显示 `CPU 14% · MEM 56%`,双指标标签修复通过本轮视觉验收。 结合此前用户确认的暂停/恢复、Esc/外部关闭,当前本机基础 UI 协作验收已通过。 内存预算口径与长时资源观察尚未完成,A 阶段不标记整阶段完成,B 阶段尚未开始。 + +## 10. B 阶段首批实施(2026-10-29) + +用户在 A 阶段 UI 通过后指示「先继续推进」,据此推进 B;A 的内存预算口径与长期观察继续保留,未宣称整阶段达标。 + +- 已实现:320pt 正式概况面板、CPU/GPU/内存行、60 点有界趋势、150ms 悬浮详情、CPU 每核热条、内存分类、负载/开机小时、底部品牌/暂停/设置/退出。 +- 外观:跟随系统/浅色/深色,系统强调色、六种预设及自选 RGB,UserDefaults 持久化;当前独立 Settings 场景仅承载外观表单。因引入此场景需保持菜单栏形态,R14 Dock 生命周期实现一并前置,完整通用/模块/权限设置仍在 D 阶段。 +- 三语:39 个 String Catalog 文案键覆盖 en / zh-Hans / zh-Hant,引用完整性检查通过。 +- TV1 当前策略:沿用系统窗口玻璃背景,避免叠加整块背景,按钮使用系统玻璃样式;真实材质融合待用户截图,尚未关闭技术验证点。 +- Debug 构建、历史容量/缺失值/格式化/外观持久化/无效设置恢复检查及采样暂停恢复回归通过。离屏检查三语深浅色概况文字未见截断;原生玻璃按钮未被渲染器完整输出,不作为真实窗口验收。 +- B 阶段仍待:真实面板/悬浮/按钮/设置开关/自选色/重启保存与 Dock 生命周期验收,深浅色 × 外观模式及 TV1 观感验证,趋势逐点滚动动效打磨。C 阶段未开始。 +- 详细验证证据与截图步骤见 [stage-b-validation.md](stage-b-validation.md)。 + +### B 阶段用户首轮截图与 Dock 验收 + +概况面板与独立外观设置窗口真实截图已收到,菜单栏/面板 CPU 和内存数值一致,底部三个按钮完整可见。 +用户确认 Dock 图标开关正常,R14 本机开关行为验收通过。 +当前系统背景融合已获得静态截图证据,TV1 的多外观/壁纸与主观效果仍待验收。 +悬浮详情、外观/强调色切换和重启保存等尚无相应用户证据,保留待验收。 + +## 11. B 阶段用户反馈修正方案 + +用户确认悬浮能显示详情、重启能保留配置;要求详情改为菜单式外侧扩展,并报告浅色切回跟随系统不刷新、自选色不自动打开选择器。 + +- 范围:UI/Components 悬浮详情呈现与窗口外观桥接;Features/Settings 系统颜色面板入口及生命周期;相关架构与验收记录。采样器和指标口径不变。 +- 详情:使用非激活子面板承载 SwiftUI 详情,主面板尺寸保持稳定;默认右侧,空间不足时左侧,纵向约束在屏幕可用范围内。行/详情之间短暂跨越保留打开状态,移出两者后收起,主面板隐藏时同步清理。仍保留 150ms 防误触,不支持点击固定。 +- 外观:移除 preferredColorScheme 覆盖,显式设置各窗口 NSWindow.appearance,系统模式设为 nil,保持 App 全局外观由系统管理;详情窗口同步所属主窗口的模式。 +- 自选色:选择 custom 时直接打开 NSColorPanel,提供重复打开按钮,连续更新 RGB;使用系统颜色面板的原生取色入口,设置窗口关闭时清理属于本设置的面板。 +- 顺序:先实现外观与颜色入口,再替换外侧详情;最后构建、核心回归与呈现边界检查,记录自动验证和真实截图验收边界。 +- 风险:MenuBarExtra 父窗口与子窗口的焦点/关闭联动、鼠标跨窗口及屏幕边缘位置需真实 UI 复验;系统外观转换与取色面板弹出不能仅靠构建认定通过。 + +### 第 11 节实施与验证结果 + +- 已改为独立非激活子面板,150ms 展开、120ms 跨窗口收起缓冲,主面板不再因详情展开变高;左/右侧与纵向屏幕边界有定位检查。 +- 外观移除 preferredColorScheme,使用窗口级 NSAppearance;系统模式明确清除 override,并同步详情子窗口。颜色选择改为显式 NSColorPanel,选 custom 即打开,可再次点击色块入口打开,设置关闭时清理。 +- Debug 构建通过;PresentationChecks 覆盖右侧/左侧/负屏幕坐标/小屏/上下边界,以及非显示窗口 light→system、dark→system 的 override 清除与系统继承,通过。既有核心与偏好/暂停恢复回归通过。 +- 用户确认重启后配置保留,持久化实际验收通过;用户反馈的外侧交互、跟随系统刷新和颜色面板弹出修正后仍待重新运行验收。 + +## 12. B 阶段外观与自选色第二轮修正 + +用户确认外侧详情正常,按用户反馈验收通过;外观切回系统仍失败,设置失焦后变回系统模式,自选色块点击仍未弹出颜色面板。前一轮非显示窗口检查不足以覆盖实际 SwiftUI/原生混合路径,失败项重新保留。 + +- 外观由系统全局偏好独立解析,明确向 SwiftUI 的 preferredColorScheme / colorScheme 环境和窗口级外观提供同一深/浅色;不再将 system 直接映射为 nil。监听主题与应用有效外观变化,用户保存的 system 语义不变。 +- 色块改为原生 NSButton,明确 target/action、失焦首次点击;选择 custom 后下一主线程调度打开。系统颜色面板显式置前并记录请求/可见性日志。三个只用于窗口桥接的背景 NSView 不再参与鼠标命中。 +- 呈现检查补充系统源解析与模式组合、原生色块 target/action;App Sandbox 临时只读探针读取系统源为 dark,与 defaults 全局查询 Dark 一致。 +- Debug 构建与呈现检查结果见验证记录;失焦保持、真实设置切回系统、真实色块点击/取色面板弹出仍须用户复验,不能由非显示测试认定已通过。 + +### 自选色块尺寸修正与外观验收 + +用户确认第 12 节外观切换修正正常,实际外观交互按反馈通过。自选色块截图仍出现超界白色矩形,已移除可缩放符号图像,改为固定 44×26pt 原生按钮内直接绘制真实 RGB。 +Debug 构建、实际色块离屏 RGB/边界与点击回归通过;真实设置窗口布局和颜色面板弹出仍待复验。 + +### 12.1 颜色入口验收与趋势滚动补齐 + +用户确认颜色选择器能够弹出。继续 B 阶段,趋势追加点采用 0.35 秒水平插值,首次显示、历史重置与减少动态效果不滚动;不增加后台动画时钟。实际动效、多壁纸与多显示器验收仍保留,C 未开始。 + +### 12.2 趋势滚动用户验收(2026-10-30) + +用户确认趋势「正常平滑左移」,本机实际滚动验收通过。B 的剩余验收集中于自选取色联动与 RGB 重启保存、外观/语言组合、多壁纸玻璃观感和屏幕边缘场景;详细边界见 stage-b-validation.md 第六轮记录。B 不提前标记整阶段完成,C 尚未开始。 + +### 12.3 自选颜色完整交互验收(2026-10-30) + +用户确认自选颜色正常使用、重启保存正确、面板与设置配色一致;此前自选色联动及 RGB 持久化待验收项关闭。B 继续保留外观/语言组合、多壁纸玻璃观感、减少动态效果和屏幕边缘/多显示器场景验收,C 尚未开始。 diff --git a/docs/roadmap.md b/docs/roadmap.md index bbc448c..1d7cc9f 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,11 +14,13 @@ A 阶段首批实现已落地,整阶段验收进行中,详情见实施方案 ## v0.3 液态玻璃面板 +B 阶段代码已实现;本机外侧详情、外观切换、自选颜色联动与重启保存、面板与设置配色一致、趋势平滑滚动及 Dock 开关已获用户确认。全部外观/语言组合、多壁纸、减少动态效果与屏幕边缘/多显示器验收仍保留,详见 [stage-b-validation.md](stage-b-validation.md)。C 阶段尚未开始。 + - [ ] 玻璃材质面板(含与系统菜单融合的验证)与灵动动画 -- [ ] 迷你趋势图(SwiftUI Canvas 自绘) -- [ ] 悬浮板块展示详情 +- [x] 迷你趋势图(SwiftUI Canvas 自绘,本机平滑滚动已验收) +- [x] 悬浮板块展示详情(菜单式外侧展开已验收) - [ ] 底部品牌标识与操作区(暂停 / 设置 / 退出) -- [ ] 外观三选项(跟随系统 / 浅色 / 深色)与强调色(系统 / 预设 / 自选) +- [x] 外观三选项与强调色(本机切换、自选配色联动及重启保存已验收;全组合视觉验收仍保留) - [ ] 三语 String Catalog 接入(zh-Hans / zh-Hant / en) - [ ] 网络与存储监控 - [ ] 电池监控 diff --git a/docs/stage-b-validation.md b/docs/stage-b-validation.md new file mode 100644 index 0000000..a694c0b --- /dev/null +++ b/docs/stage-b-validation.md @@ -0,0 +1,103 @@ +# B 阶段面板与外观验证记录 + +日期:2026-10-29。基于用户「先继续推进」指示开始 B,A 阶段内存预算及长时观察仍保留。 + +## 本轮实现与验证 + +- 面板:CPU / GPU / 内存概况,有界趋势、延迟悬浮详情、负载、开机时长、底部品牌与玻璃操作按钮。 +- 外观:独立外观设置,系统/浅色/深色,系统/六种预设/自选色,重启持久化。完整设置与权限页留待 D。 +- Dock:显式 LSUIElement 默认后台形态,设置打开/重新成为 key 使用 regular,窗口关闭恢复 accessory;代码构建通过,真实行为待验收。 +- Debug 构建 `BUILD SUCCEEDED`;生成的 Info.plist 已确认 LSUIElement=true。无本次 Swift 源码编译警告,构建工具仍提示未使用 AppIntents 而跳过其元数据提取。 +- 核心检查通过:60 点历史上限与顺序、缺失值不补零、百分比边界及 GB 格式、偏好保存/恢复和无效设置降级;CPU 差分与 Store 暂停恢复回归通过。 +- String Catalog 的 39 个键均有 en / zh-Hans / zh-Hant 值;Features/UI 引用键完整。构建产物含三种 .lproj。 +- 使用实际 MenuPanelView 及构建后的本地化资源离屏生成三语 × 深浅色六份概况预览,已逐张检查:概况文字与数值未见截断。只有少量采样点,不能据此验收完整历史滚动。 +- 原生玻璃按钮未被 ImageRenderer 完整输出;离屏预览不验证系统窗口玻璃、按钮可见性、真实悬浮或设置表单交互。图片与脚本为临时检查产物,完成后删除。 +- 原生工具本轮对测试构建的 getApp 仍返回 timeoutReached,未取得可操作对象;未据此认定缺少授权。 + +## 待用户协作验收 + +重新在 Xcode 构建运行后,请只截 Kymo 面板或设置窗口: + +1. 打开面板,等待约 20 秒,提供正常概况截图,确认 CPU/内存曲线开始累积,底部暂停/设置/退出按钮均可见。 +2. 鼠标停在 CPU 行,提供每核详情截图;移到内存行,提供内存详情截图。确认移出后收起,没有卡住或超出屏幕。 +3. 点击底部设置,确认独立窗口能打开;依次选择浅色/深色/跟随系统,并测试预设色、自选色。提供一张设置窗口与一张切换后的面板截图。 +4. 文字反馈设置窗口打开时 Dock 图标出现、关闭时消失、再次打开是否正常;重启后所选外观/颜色是否保留。 +5. 回归暂停/恢复与 Esc/外部关闭。退出按钮会结束本次运行,可最后测试。 + +TV1 待真实面板截图检查材质融合;不同壁纸、所有外观组合、减少动态效果、真实多显示器/刘海屏及长期资源观察尚未验收。 +趋势曲线已做空间平滑,逐点滚动的连续插值动画仍待打磨;本阶段未宣布全部完成,C 阶段未开始。 + +## 用户首轮真实 UI 验收补充 + +用户提供概况面板与独立外观设置窗口截图,并明确反馈「dock 图标开关正常」。 + +- 概况截图:菜单栏 `CPU 14% · MEM 56%` 与面板 CPU 14%、内存 56% 一致;GPU 显示 `--`,负载、开机小时、品牌与版本可见,底部暂停/设置/退出三个按钮均完整显示。 +- 设置截图:独立窗口已打开,简体中文外观三选项与强调色选择器完整可见;当前为跟随系统与系统强调色。 +- Dock 随设置窗口开关的行为按用户反馈验收通过。截图本身不能证明该动态行为,不将其混同为工具自动验证。 +- 本机当前背景下可见系统材质与圆角,无额外整块内层窗口背景;TV1 获得当前场景的静态融合证据,其他壁纸/深浅色与主观玻璃质感仍待验收。 +- 截图中的趋势仅有尾部短线,不足以证明 60 点完整趋势与滚动动效。CPU/内存悬浮详情未出现在这两张截图中,不能认定已通过。 + +剩余协作验收:CPU/内存悬浮详情与移出收起、浅/深外观及预设/自选强调色切换、重启保存、新面板暂停/关闭/退出回归,以及多场景玻璃观感。B 阶段仍未标记全部完成。 + +## 第二轮用户反馈与修正 + +- 用户截图证明 CPU 悬浮详情实际可见、历史已有连续曲线;用户要求改为向外展开的子菜单逻辑,替代此前内联撑高形态。 +- 用户报告系统深色时从浅色切回跟随系统仍为浅色,记录为失败;报告选择自选强调色未弹出取色器,记录为入口行为不符合预期。 +- 用户确认重启后外观配置保留,实际持久化验收通过。 + +修正为非激活外侧子面板、窗口级显式外观重置,以及选择 custom 即打开系统颜色面板。 +Debug 构建、屏幕定位边界检查、真实但不显示的 NSWindow 覆盖清除检查、既有采样与偏好回归通过。 +非显示窗口检查确认 window.appearance 回到 nil、effectiveAppearance 与 NSApp 系统继承一致,App 全局外观未被修改; +这不替代 SwiftUI 设置点击后的真实窗口自动刷新验收。 + +请重新运行后复验: + +1. CPU/内存悬浮时详情应在主面板外侧,主面板高度不变;鼠标可移入详情,离开后收起。提供一张包含主面板和外侧详情的局部截图,检查屏幕边缘与 Esc/外部关闭后无残留。 +2. 系统为深色时选择浅色,再选跟随系统,确认设置及面板均恢复深色;反方向也可测试。 +3. 选择自选强调色应直接弹出系统颜色面板,选择颜色连续生效;可用其原生取色入口,重复点击自选色行能再次打开。设置窗口关闭时颜色面板应关闭,Dock 策略保持正常。 + +上述新交互均保留待用户验收,不以构建和几何检查声称通过。真实多显示器、全部外观组合和长期资源风险仍保留。 + +## 第三轮用户反馈与外观/取色入口再修正 + +用户明确反馈:外侧展开正常;外观仍在失焦时变为系统值,浅色切跟随系统仍不响应;点击自选色块仍无颜色面板。用户截图中自选色行与色块可见,不等于点击链路通过。 +外侧展开按用户反馈通过,前一轮外观与取色修正没有通过真实验收,不将其保留为已解决。 + +本轮改动: + +- 以独立系统源解析实际深/浅色,同时设置 SwiftUI 的明确 preferredColorScheme / colorScheme 环境与原生窗口覆盖,避免 nil 清除和失焦继承的不一致。系统主题变化重新解析,用户选择仍保持 system。 +- 原生色块 target/action,允许失焦首次点击;打开颜色面板明确置前。观察窗口的透明桥接 NSView 不参与鼠标命中。 +- 颜色入口增加 cn.airnan.kymo / color-picker 日志,仅记录用户打开请求及面板是否可见,便于失败时继续区分未命中与窗口显示问题。 + +验证:Debug 构建通过;呈现检查通过系统源与四种模式组合、原生色块 target/action、已有定位与窗口级覆盖回归。 +启用 com.apple.security.app-sandbox=true 的临时只读探针使用同一 SystemAppearanceObserver,输出系统源 dark,与全局 defaults 的 Dark 一致;探针不显示窗口、不修改系统偏好。 +原生色块检查用非显示控件 performClick 验证 action 调用,不能证明真实鼠标命中或 NSColorPanel 取色交互。 +本轮没有将构建、非显示检查或探针当成真实 SwiftUI 窗口失焦/跟随系统/取色面板显示验收。 + +待复验:保持软件浅色后让设置失焦,是否仍为浅色;系统深色下浅色切跟随系统,设置与菜单面板是否立即变深;点击色块是否出现可取色的系统颜色面板。 + +## 第四轮用户反馈与色块尺寸修正 + +用户确认外观切换已正常,按用户实际反馈验收通过。新截图显示自选色块呈白色大矩形并超出按钮区域;颜色面板实际弹出与取色未在本轮反馈中明确确认,仍不标记通过。 + +检查发现色块采用可向上缩放的 SF Symbol 图像与 NSButton cell 默认图像布局。已移除该图像路径,改为原生按钮在自身 bounds 内按实际 sRGB 绘制圆角色块,明确 44×26pt 布局与固有尺寸、图层裁剪,并保留失焦首次点击和 target/action。 +Debug 构建通过;离屏渲染实际按钮得到 44×26 PNG,已查看颜色与边界。呈现检查通过中心像素 RGB 与配置匹配、角落透明、原生点击及既有外观/定位回归。 +离屏绘制不等于真实 Form 布局和颜色面板显示验收;请重新运行核对色块范围、颜色以及点击弹出。 + +## 第五轮用户反馈与趋势滚动 + +用户确认自选颜色选择器可以弹出,真实入口验收通过;尚未明确确认取色后的颜色联动及重启保存自选 RGB。继续补齐 B 阶段趋势滚动:追加样本时用 0.35 秒插值向左移动一个采样间距,满容量保留出场点后裁剪,缺失值仍断开。首次打开及减少动态效果直接显示,面板消失取消待启动任务,不新增采样或周期动画时钟。真实滚动手感仍待用户验收。 + +本轮 Debug 构建通过,趋势边界独立检查通过(追加识别、缺失值、未满/满容量起点、中点、终点及出场点)。未启动应用测试副本,未操作用户已有 Xcode 进程;实际面板动效未验证。 + +## 第六轮趋势滚动实际验收(2026-10-30) + +用户确认「正常平滑左移」,本机运行面板的趋势滚动按用户实际反馈验收通过。结合此前反馈,已确认外侧详情、外观切换、颜色选择器弹出、配置保留和 Dock 开关。此反馈不扩展为减少动态效果、全部历史长度、多显示器或长期性能验收。 + +B 阶段剩余:自选取色后的强调色联动及自选 RGB 重启保留、全部外观/语言组合、多壁纸玻璃观感与屏幕边缘场景。已有核心检查、离屏检查及当前场景用户验收不替代这些场景;B 不标记整阶段完成,C 未开始。本轮仅更新文档,检查差异与链接,不重复构建。 + +## 第七轮自选颜色与持久化实际验收(2026-10-30) + +用户确认自选颜色正常使用、重启后颜色正常保存,面板与设置中配色均正确。自选颜色选择、跨窗口配色联动及 RGB 持久化按用户本机实际反馈验收通过,关闭此前对应待验收项。 + +B 剩余验收限于全部外观/语言组合、多壁纸玻璃观感、减少动态效果及屏幕边缘/多显示器场景;本轮反馈不覆盖这些场景或 A 阶段长期性能预算。C 尚未开始。本轮只更新文档,差异检查通过,无运行代码变化,不重复构建。 diff --git a/kymo.xcodeproj/project.pbxproj b/kymo.xcodeproj/project.pbxproj index c6b33f5..37e5562 100644 --- a/kymo.xcodeproj/project.pbxproj +++ b/kymo.xcodeproj/project.pbxproj @@ -107,6 +107,8 @@ hasScannedForEncodings = 0; knownRegions = ( en, + "zh-Hans", + "zh-Hant", Base, ); mainGroup = D9E51E6A309338B0000608DE; @@ -269,6 +271,7 @@ ENABLE_USER_SELECTED_FILES = readonly; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_LSUIElement = YES; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", @@ -299,6 +302,7 @@ ENABLE_USER_SELECTED_FILES = readonly; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INFOPLIST_KEY_LSUIElement = YES; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", diff --git a/kymo/App/kymoApp.swift b/kymo/App/kymoApp.swift index 3f83b3a..260a286 100644 --- a/kymo/App/kymoApp.swift +++ b/kymo/App/kymoApp.swift @@ -15,12 +15,18 @@ import SwiftUI struct kymoApp: App { @State private var metrics = MetricsStore() + @State private var appearance = AppearancePreferences() + var body: some Scene { MenuBarExtra { - MenuPanelView(metrics: metrics) + MenuPanelView(metrics: metrics, preferences: appearance) } label: { MenuBarLabel(snapshot: metrics.snapshot) } .menuBarExtraStyle(.window) + + Settings { + AppearanceSettingsView(preferences: appearance) + } } } diff --git a/kymo/Core/Extensions/MetricFormat.swift b/kymo/Core/Extensions/MetricFormat.swift new file mode 100644 index 0000000..e793417 --- /dev/null +++ b/kymo/Core/Extensions/MetricFormat.swift @@ -0,0 +1,15 @@ +import Foundation + +nonisolated enum MetricFormat { + static func percent(_ value: Double?) -> String { + guard let value, value.isFinite else { return "--" } + return "\(Int((min(1, max(0, value)) * 100).rounded()))%" + } + + static func bytes(_ value: UInt64?) -> String { + guard let value else { return "--" } + return String(format: "%.1f GB", Double(value) / 1_000_000_000) + } + + static func decimal(_ value: Double) -> String { String(format: "%.1f", value) } +} diff --git a/kymo/Core/Models/MetricHistory.swift b/kymo/Core/Models/MetricHistory.swift new file mode 100644 index 0000000..a2c6ba8 --- /dev/null +++ b/kymo/Core/Models/MetricHistory.swift @@ -0,0 +1,20 @@ +import Foundation + +nonisolated struct TrendSample: Sendable { + let date: Date + let cpu: Double? + let gpu: Double? + let memory: Double? +} + +/// Bounded sampling history; no timer or UI visibility dependence. +nonisolated struct MetricHistory: Sendable { + static let capacity = 60 + private(set) var samples: [TrendSample] = [] + + mutating func append(_ snapshot: MetricsSnapshot) { + samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage, + gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage)) + if samples.count > Self.capacity { samples.removeFirst(samples.count - Self.capacity) } + } +} diff --git a/kymo/Core/Models/MetricsSnapshot.swift b/kymo/Core/Models/MetricsSnapshot.swift index 785468b..c406a61 100644 --- a/kymo/Core/Models/MetricsSnapshot.swift +++ b/kymo/Core/Models/MetricsSnapshot.swift @@ -22,6 +22,7 @@ nonisolated struct MetricsSnapshot: Sendable { var cpu: CPUMetrics? var memory: MemoryMetrics? var load: [Double] = [] + var uptime: TimeInterval = 0 // GPU remains unavailable until a reliable IOReport subscription is validated. var gpuUsage: Double? = nil } diff --git a/kymo/Core/Monitors/SystemSampler.swift b/kymo/Core/Monitors/SystemSampler.swift index 2f60206..6ba3eda 100644 --- a/kymo/Core/Monitors/SystemSampler.swift +++ b/kymo/Core/Monitors/SystemSampler.swift @@ -11,6 +11,7 @@ actor SystemSampler { var result = MetricsSnapshot() result.cpu = cpu.sample() result.memory = MemoryMonitor.sample() + result.uptime = ProcessInfo.processInfo.systemUptime var load = [Double](repeating: 0, count: 3) if getloadavg(&load, 3) == 3 { result.load = load } return result diff --git a/kymo/Core/Services/AppearancePreferences.swift b/kymo/Core/Services/AppearancePreferences.swift new file mode 100644 index 0000000..1680bab --- /dev/null +++ b/kymo/Core/Services/AppearancePreferences.swift @@ -0,0 +1,36 @@ +import Foundation +import Observation + +nonisolated enum AppAppearance: String, CaseIterable, Identifiable { + case system, light, dark + var id: String { rawValue } +} + +nonisolated enum AccentChoice: String, CaseIterable, Identifiable { + case system, blue, purple, teal, green, orange, pink, custom + var id: String { rawValue } +} + +@MainActor @Observable +final class AppearancePreferences { + @ObservationIgnored private let defaults: UserDefaults + var appearance: AppAppearance { didSet { defaults.set(appearance.rawValue, forKey: "appearance") } } + var accent: AccentChoice { didSet { defaults.set(accent.rawValue, forKey: "accent") } } + var red: Double { didSet { defaults.set(red, forKey: "accent.red") } } + var green: Double { didSet { defaults.set(green, forKey: "accent.green") } } + var blue: Double { didSet { defaults.set(blue, forKey: "accent.blue") } } + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + appearance = AppAppearance(rawValue: defaults.string(forKey: "appearance") ?? "") ?? .system + accent = AccentChoice(rawValue: defaults.string(forKey: "accent") ?? "") ?? .system + red = Self.component(defaults.object(forKey: "accent.red"), fallback: 0.2) + green = Self.component(defaults.object(forKey: "accent.green"), fallback: 0.5) + blue = Self.component(defaults.object(forKey: "accent.blue"), fallback: 0.9) + } + + private static func component(_ value: Any?, fallback: Double) -> Double { + guard let value = value as? Double, value.isFinite else { return fallback } + return min(1, max(0, value)) + } +} diff --git a/kymo/Core/Services/MetricsStore.swift b/kymo/Core/Services/MetricsStore.swift index cdd950b..bbcfb4b 100644 --- a/kymo/Core/Services/MetricsStore.swift +++ b/kymo/Core/Services/MetricsStore.swift @@ -4,6 +4,7 @@ import Observation @MainActor @Observable final class MetricsStore { private(set) var snapshot = MetricsSnapshot() + private(set) var history = MetricHistory() private(set) var isPaused = false @ObservationIgnored private var task: Task? @ObservationIgnored private let sampler = SystemSampler() @@ -19,6 +20,7 @@ final class MetricsStore { let next = await sampler.sample() guard !Task.isCancelled else { return } self?.snapshot = next + self?.history.append(next) SamplingDiagnostics.record(next) do { try await Task.sleep(for: .seconds(2)) } catch { return } diff --git a/kymo/Features/MenuBar/MenuBarLabel.swift b/kymo/Features/MenuBar/MenuBarLabel.swift index 143d042..249de1a 100644 --- a/kymo/Features/MenuBar/MenuBarLabel.swift +++ b/kymo/Features/MenuBar/MenuBarLabel.swift @@ -16,15 +16,11 @@ struct MenuBarLabel: View { } private var title: String { - var items = ["CPU \(percent(snapshot.cpu?.usage))"] + var items = ["CPU \(MetricFormat.percent(snapshot.cpu?.usage))"] if let gpu = snapshot.gpuUsage { - items.append("GPU \(percent(gpu))") + items.append("GPU \(MetricFormat.percent(gpu))") } - items.append("MEM \(percent(snapshot.memory?.usage))") + items.append("MEM \(MetricFormat.percent(snapshot.memory?.usage))") return items.joined(separator: " · ") } - - private func percent(_ value: Double?) -> String { - value.map { "\(Int(($0 * 100).rounded()))%" } ?? "--" - } } diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index dcc923e..2a28881 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -1,34 +1,115 @@ -// -// MenuPanelView.swift -// kymo -// -// Created by Airnan on 2026/10/29. -// - import SwiftUI +import AppKit -/// A 阶段临时面板:展示采样时间与暂停入口,正式面板在 B 阶段实现。 struct MenuPanelView: View { let metrics: MetricsStore + let preferences: AppearancePreferences + @Environment(\.openSettings) private var openSettings var body: some View { - VStack(alignment: .leading, spacing: 12) { - Label("Kymo 资源监控", systemImage: "gauge") - .font(.headline) - - Text(metrics.snapshot.date, style: .time) - Button(metrics.isPaused ? "继续监控" : "暂停监控") { - metrics.togglePause() + VStack(spacing: 4) { + VStack(spacing: 2) { + MetricRow(title: "metric.cpu", symbol: "cpu", value: MetricFormat.percent(metrics.snapshot.cpu?.usage), + usage: metrics.snapshot.cpu?.usage, history: metrics.history.samples.map(\.cpu), accent: preferences.tintColor) { + cpuDetail + } + MetricRow(title: "metric.gpu", symbol: "square.grid.2x2", value: MetricFormat.percent(metrics.snapshot.gpuUsage), + usage: metrics.snapshot.gpuUsage, history: metrics.history.samples.map(\.gpu), accent: preferences.tintColor) { + Text("gpu.unavailable").foregroundStyle(.secondary) + } + MetricRow(title: "metric.memory", symbol: "memorychip", value: MetricFormat.percent(metrics.snapshot.memory?.usage), + usage: metrics.snapshot.memory?.usage, history: metrics.history.samples.map(\.memory), accent: preferences.tintColor) { + memoryDetail + } } - Text("GPU 暂不可用") - .font(.subheadline) - .foregroundStyle(.secondary) + Divider().padding(.horizontal, 10) + HStack { + Text("system.load") + Text(verbatim: metrics.snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")) + Spacer(minLength: 4) + Image(systemName: "clock") + Text(verbatim: String(format: "%.0fh", floor(metrics.snapshot.uptime / 3600))) + } + .font(.system(size: 10)).monospacedDigit().foregroundStyle(.secondary) + .padding(.horizontal, 10).padding(.vertical, 8) + footer } - .padding(16) - .frame(width: 280, alignment: .leading) + .padding(10) + .frame(width: 320) + .modifier(AppearanceStyle(preferences: preferences)) + } + + @ViewBuilder private var cpuDetail: some View { + if let cpu = metrics.snapshot.cpu { + VStack(alignment: .leading, spacing: 8) { + detailLine("cpu.user", MetricFormat.percent(cpu.user)) + detailLine("cpu.system", MetricFormat.percent(cpu.system)) + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 4) { + ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, usage in + RoundedRectangle(cornerRadius: 4) + .fill(preferences.tintColor.opacity(0.12 + 0.88 * usage)) + .frame(height: 18) + .overlay(Text(verbatim: "\(index + 1)").font(.system(size: 9)).foregroundStyle(.primary)) + .help(MetricFormat.percent(usage)) + .accessibilityLabel(Text("cpu.core")) + .accessibilityValue(Text(verbatim: "\(index + 1): \(MetricFormat.percent(usage))")) + } + } + } + } else { Text("metric.waiting").foregroundStyle(.secondary) } + } + + @ViewBuilder private var memoryDetail: some View { + if let memory = metrics.snapshot.memory { + VStack(spacing: 6) { + detailLine("memory.used", MetricFormat.bytes(memory.used)) + detailLine("memory.available", MetricFormat.bytes(memory.total - memory.used)) + detailLine("memory.app", MetricFormat.bytes(memory.used - min(memory.used, memory.wired + memory.compressed))) + detailLine("memory.wired", MetricFormat.bytes(memory.wired)) + detailLine("memory.compressed", MetricFormat.bytes(memory.compressed)) + detailLine("memory.swap", MetricFormat.bytes(memory.swapUsed)) + HStack { + Text("memory.pressure").foregroundStyle(.secondary) + Spacer() + switch memory.pressure { + case 1: Text("pressure.normal") + case 2: Text("pressure.warning").foregroundStyle(.orange) + case 4: Text("pressure.critical").foregroundStyle(.red) + default: Text(verbatim: "--") + } + } + } + } else { Text("metric.waiting").foregroundStyle(.secondary) } + } + + private func detailLine(_ key: LocalizedStringKey, _ value: String) -> some View { + HStack { Text(key).foregroundStyle(.secondary); Spacer(); Text(verbatim: value).monospacedDigit() } + } + + private var footer: some View { + HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: "Kymo").font(.system(size: 12, weight: .semibold)) + Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")") + .font(.system(size: 9)).foregroundStyle(.tertiary) + } + Spacer() + Button { metrics.togglePause() } label: { + Image(systemName: metrics.isPaused ? "play.fill" : "pause.fill").frame(width: 20, height: 20) + } + .help(metrics.isPaused ? Text("action.resume") : Text("action.pause")) + .accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause")) + Button { NSApp.activate(); openSettings() } label: { + Image(systemName: "gearshape").frame(width: 20, height: 20) + } + .help(Text("action.settings")).accessibilityLabel(Text("action.settings")) + Button { NSApp.terminate(nil) } label: { + Image(systemName: "power").frame(width: 20, height: 20) + } + .help(Text("action.quit")).accessibilityLabel(Text("action.quit")) + } + .buttonStyle(.glass) + .controlSize(.small) + .padding(.horizontal, 8).padding(.vertical, 6) } } - -#Preview { - MenuPanelView(metrics: MetricsStore()) -} diff --git a/kymo/Features/Settings/AppearanceSettingsView.swift b/kymo/Features/Settings/AppearanceSettingsView.swift new file mode 100644 index 0000000..8638850 --- /dev/null +++ b/kymo/Features/Settings/AppearanceSettingsView.swift @@ -0,0 +1,55 @@ +import SwiftUI +import AppKit + +/// B-stage appearance controls; general/modules/permissions remain D-stage work. +struct AppearanceSettingsView: View { + @Bindable var preferences: AppearancePreferences + @State private var colorPicker = CustomColorPicker() + + var body: some View { + Form { + Section("settings.appearance") { + Picker("appearance.title", selection: $preferences.appearance) { + Text("appearance.system").tag(AppAppearance.system) + Text("appearance.light").tag(AppAppearance.light) + Text("appearance.dark").tag(AppAppearance.dark) + } + .pickerStyle(.segmented) + Picker("accent.title", selection: $preferences.accent) { + Text("accent.system").tag(AccentChoice.system) + Text("accent.blue").tag(AccentChoice.blue) + Text("accent.purple").tag(AccentChoice.purple) + Text("accent.teal").tag(AccentChoice.teal) + Text("accent.green").tag(AccentChoice.green) + Text("accent.orange").tag(AccentChoice.orange) + Text("accent.pink").tag(AccentChoice.pink) + Text("accent.custom").tag(AccentChoice.custom) + } + if preferences.accent == .custom { + HStack { + Text("accent.custom") + Spacer() + CustomColorWell(preferences: preferences, picker: colorPicker) + .frame(width: 44, height: 26) + } + } + } + } + .background(SettingsWindowLifecycle(onClose: { colorPicker.close() })) + .onChange(of: preferences.accent) { _, choice in + if choice == .custom { + Task { @MainActor in + await Task.yield() + guard preferences.accent == .custom else { return } + colorPicker.show(for: preferences) + } + } + else { colorPicker.close() } + } + .onAppear { NSApp.setActivationPolicy(.regular); NSApp.activate() } + .formStyle(.grouped) + .frame(width: 420, height: 240) + .modifier(AppearanceStyle(preferences: preferences)) + } + +} diff --git a/kymo/Features/Settings/CustomColorPicker.swift b/kymo/Features/Settings/CustomColorPicker.swift new file mode 100644 index 0000000..678bae6 --- /dev/null +++ b/kymo/Features/Settings/CustomColorPicker.swift @@ -0,0 +1,43 @@ +import AppKit +import OSLog + +@MainActor final class CustomColorPicker: NSObject { + private let logger = Logger(subsystem: "cn.airnan.kymo", category: "color-picker") + private static weak var owner: CustomColorPicker? + private var preferences: AppearancePreferences? + + func show(for preferences: AppearancePreferences) { + logger.info("Custom color panel requested") + Self.owner = self + self.preferences = preferences + let panel = NSColorPanel.shared + panel.appearance = preferences.appearance.windowAppearance + panel.showsAlpha = false + panel.isContinuous = true + panel.color = NSColor(srgbRed: preferences.red, green: preferences.green, + blue: preferences.blue, alpha: 1) + panel.setTarget(self) + panel.setAction(#selector(colorChanged(_:))) + NSApp.activate() + panel.level = .floating + panel.makeKeyAndOrderFront(nil) + panel.orderFrontRegardless() + logger.info("Custom color panel visible: \(panel.isVisible, privacy: .public)") + } + + @objc private func colorChanged(_ sender: NSColorPanel) { + guard let preferences, let rgb = sender.color.usingColorSpace(.sRGB) else { return } + preferences.red = rgb.redComponent + preferences.green = rgb.greenComponent + preferences.blue = rgb.blueComponent + } + + func close() { + guard Self.owner === self else { return } + NSColorPanel.shared.setTarget(nil) + NSColorPanel.shared.setAction(nil) + NSColorPanel.shared.close() + preferences = nil + Self.owner = nil + } +} diff --git a/kymo/Features/Settings/CustomColorWell.swift b/kymo/Features/Settings/CustomColorWell.swift new file mode 100644 index 0000000..046c187 --- /dev/null +++ b/kymo/Features/Settings/CustomColorWell.swift @@ -0,0 +1,53 @@ +import SwiftUI +import AppKit + +/// A native hit target avoids Form/plain-Button hit-testing ambiguity on the swatch. +struct CustomColorWell: NSViewRepresentable { + let preferences: AppearancePreferences + let picker: CustomColorPicker + + func makeNSView(context: Context) -> SwatchButton { + let button = SwatchButton() + button.setAccessibilityLabel(String(localized: "accent.custom")) + return button + } + + func updateNSView(_ button: SwatchButton, context: Context) { + button.open = { picker.show(for: preferences) } + button.swatchColor = NSColor(srgbRed: preferences.red, green: preferences.green, blue: preferences.blue, alpha: 1) + } + + func sizeThatFits(_ proposal: ProposedViewSize, nsView: SwatchButton, context: Context) -> CGSize? { + CGSize(width: 44, height: 26) + } + + final class SwatchButton: NSButton { + var swatchColor = NSColor.systemBlue { didSet { needsDisplay = true } } + override var intrinsicContentSize: NSSize { NSSize(width: 44, height: 26) } + + override func draw(_ dirtyRect: NSRect) { + // Draw the actual RGB color inside bounds; no scalable SF Symbol/cell image. + let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 4, dy: 4), xRadius: 4, yRadius: 4) + (isHighlighted ? swatchColor.withAlphaComponent(0.7) : swatchColor).setFill() + shape.fill() + NSColor.separatorColor.setStroke() + shape.lineWidth = 1 + shape.stroke() + } + + var open: () -> Void = {} + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + bezelStyle = .rounded + isBordered = false + wantsLayer = true + layer?.masksToBounds = true + title = "" + target = self + action = #selector(openPicker) + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + @objc func openPicker() { open() } + } +} diff --git a/kymo/Features/Settings/SettingsWindowLifecycle.swift b/kymo/Features/Settings/SettingsWindowLifecycle.swift new file mode 100644 index 0000000..2957031 --- /dev/null +++ b/kymo/Features/Settings/SettingsWindowLifecycle.swift @@ -0,0 +1,38 @@ +import SwiftUI +import AppKit + +/// Keep the app discoverable while its settings window is open, including reopen. +struct SettingsWindowLifecycle: NSViewRepresentable { + var onClose: () -> Void = {} + + func makeNSView(context: Context) -> WindowObserverView { WindowObserverView() } + func updateNSView(_ nsView: WindowObserverView, context: Context) { nsView.onClose = onClose } + + final class WindowObserverView: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { nil } + var onClose: () -> Void = {} + private var tokens: [NSObjectProtocol] = [] + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + for token in tokens { NotificationCenter.default.removeObserver(token) } + tokens.removeAll() + guard let window else { return } + tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, + object: window, queue: .main) { _ in + MainActor.assumeIsolated { + if NSApp.activationPolicy() != .regular { NSApp.setActivationPolicy(.regular) } + } + }) + tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, + object: window, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { + self?.onClose() + NSApp.setActivationPolicy(.accessory) + } + }) + } + + deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } } + } +} diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings new file mode 100644 index 0000000..9cf7e35 --- /dev/null +++ b/kymo/Resources/Localizable.xcstrings @@ -0,0 +1,903 @@ +{ + "sourceLanguage": "en", + "strings": { + "metric.cpu": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CPU" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "CPU" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "CPU" + } + } + } + }, + "metric.gpu": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "GPU" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "GPU" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "GPU" + } + } + } + }, + "metric.memory": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Memory" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "内存" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "記憶體" + } + } + } + }, + "metric.waiting": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Waiting for sample…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "等待采样…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "等待取樣…" + } + } + } + }, + "gpu.unavailable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "GPU sampling is unavailable on this device." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "此设备暂不支持 GPU 采样。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "此裝置暫不支援 GPU 取樣。" + } + } + } + }, + "cpu.user": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "User" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "用户" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "使用者" + } + } + } + }, + "cpu.system": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "System" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "系统" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "系統" + } + } + } + }, + "cpu.core": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Core" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "核心" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "核心" + } + } + } + }, + "memory.used": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Used" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已用" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已使用" + } + } + } + }, + "memory.available": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Available" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "可用" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "可用" + } + } + } + }, + "memory.app": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "App memory" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "应用内存" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "App 記憶體" + } + } + } + }, + "memory.wired": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Wired" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "联动内存" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "連動記憶體" + } + } + } + }, + "memory.compressed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Compressed" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已压缩" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已壓縮" + } + } + } + }, + "memory.swap": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Swap used" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "交换使用量" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "交換使用量" + } + } + } + }, + "memory.pressure": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Memory pressure" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "内存压力" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "記憶體壓力" + } + } + } + }, + "pressure.normal": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Normal" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正常" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正常" + } + } + } + }, + "pressure.warning": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Warning" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "偏高" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "偏高" + } + } + } + }, + "pressure.critical": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Critical" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "严重" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "嚴重" + } + } + } + }, + "system.load": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Load" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "负载" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "負載" + } + } + } + }, + "action.pause": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pause monitoring" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "暂停监控" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "暫停監控" + } + } + } + }, + "action.resume": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Resume monitoring" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "继续监控" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "繼續監控" + } + } + } + }, + "action.settings": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Settings" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "设置" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "設定" + } + } + } + }, + "action.quit": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Quit Kymo" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "退出 Kymo" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "結束 Kymo" + } + } + } + }, + "detail.expanded": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Details expanded" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "详情已展开" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "詳細資訊已展開" + } + } + } + }, + "detail.collapsed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Details collapsed" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "详情已收起" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "詳細資訊已收合" + } + } + } + }, + "settings.appearance": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Appearance" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "外观" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "外觀" + } + } + } + }, + "appearance.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Appearance" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "外观模式" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "外觀模式" + } + } + } + }, + "appearance.system": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "System" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "跟随系统" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "跟隨系統" + } + } + } + }, + "appearance.light": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Light" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "浅色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "淺色" + } + } + } + }, + "appearance.dark": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Dark" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "深色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "深色" + } + } + } + }, + "accent.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Accent color" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "强调色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "強調色" + } + } + } + }, + "accent.system": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "System accent" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "系统强调色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "系統強調色" + } + } + } + }, + "accent.blue": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Blue" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "蓝色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "藍色" + } + } + } + }, + "accent.purple": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Purple" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "紫色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "紫色" + } + } + } + }, + "accent.teal": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Teal" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "青色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "青色" + } + } + } + }, + "accent.green": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Green" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "绿色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "綠色" + } + } + } + }, + "accent.orange": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Orange" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "橙色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "橘色" + } + } + } + }, + "accent.pink": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pink" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "粉色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "粉紅色" + } + } + } + }, + "accent.custom": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Custom color" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "自选颜色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "自選顏色" + } + } + } + } + }, + "version": "1.0" +} diff --git a/kymo/UI/Charts/MiniTrendChart.swift b/kymo/UI/Charts/MiniTrendChart.swift new file mode 100644 index 0000000..cf00a1e --- /dev/null +++ b/kymo/UI/Charts/MiniTrendChart.swift @@ -0,0 +1,82 @@ +import SwiftUI + +struct MiniTrendChart: View { + let values: [Double?] + let color: Color + + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var displayed: [Double?] = [] + @State private var progress: CGFloat = 1 + @State private var scrolling = false + + var body: some View { + TrendCanvas(values: displayed, color: color, progress: progress, scrolling: scrolling) + .clipped() + .accessibilityHidden(true) + .onAppear { displayed = values; scrolling = false; progress = 1 } + .onChange(of: values) { old, new in + var transaction = Transaction() + transaction.disablesAnimations = true + withTransaction(transaction) { + scrolling = !reduceMotion && TrendScroll.isAppend(from: old, to: new) + displayed = scrolling ? old + [new.last!] : new + progress = scrolling ? 0 : 1 + } + } + .task(id: values) { + guard scrolling, !reduceMotion else { return } + // Commit the starting frame before requesting interpolation; no repeating timer. + do { try await Task.sleep(for: .milliseconds(16)) } catch { return } + guard !Task.isCancelled else { return } + withAnimation(.easeInOut(duration: 0.35)) { progress = 1 } + } + .onChange(of: reduceMotion) { _, reduced in + if reduced { + var transaction = Transaction() + transaction.disablesAnimations = true + withTransaction(transaction) { displayed = values; scrolling = false; progress = 1 } + } + } + } +} + +private struct TrendCanvas: View, Animatable { + let values: [Double?] + let color: Color + var progress: CGFloat + let scrolling: Bool + var animatableData: CGFloat { + get { progress } + set { progress = newValue } + } + + var body: some View { + Canvas { context, size in + guard values.count > 1 else { return } + var path = Path() + var run: [CGPoint] = [] + func appendRun() { + guard let first = run.first, let last = run.last else { return } + path.move(to: first) + if run.count == 1 { path.addLine(to: CGPoint(x: first.x + 0.1, y: first.y)) } + for index in 1.. Bool { + guard !old.isEmpty, !new.isEmpty else { return false } + if old.count < MetricHistory.capacity { + return new.count == old.count + 1 && Array(new.dropLast()) == old + } + return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast()) + } + + static func position(index: Int, count: Int, progress: CGFloat, scrolling: Bool) -> CGFloat { + let offset = MetricHistory.capacity - count + let shift = scrolling ? 1 - min(1, max(0, progress)) : 0 + return (CGFloat(index + offset) + shift) / CGFloat(MetricHistory.capacity - 1) + } +} diff --git a/kymo/UI/Components/AppearanceStyle.swift b/kymo/UI/Components/AppearanceStyle.swift new file mode 100644 index 0000000..704b913 --- /dev/null +++ b/kymo/UI/Components/AppearanceStyle.swift @@ -0,0 +1,104 @@ +import SwiftUI +import AppKit +import Observation + +extension AppAppearance { + func resolved(systemIsDark: Bool) -> AppAppearance { + self == .system ? (systemIsDark ? .dark : .light) : self + } + + var windowAppearance: NSAppearance? { + switch self { + case .system: nil + case .light: NSAppearance(named: .aqua) + case .dark: NSAppearance(named: .darkAqua) + } + } +} + +extension AppearancePreferences { + var tintColor: Color { + switch accent { + case .system: .accentColor + case .blue: .blue + case .purple: .purple + case .teal: .teal + case .green: .green + case .orange: .orange + case .pink: .pink + case .custom: Color(red: red, green: green, blue: blue) + } + } +} + +struct AppearanceStyle: ViewModifier { + let preferences: AppearancePreferences + @State private var system = SystemAppearanceObserver() + private var resolved: AppAppearance { preferences.appearance.resolved(systemIsDark: system.isDark) } + private var scheme: ColorScheme { resolved == .dark ? .dark : .light } + func body(content: Content) -> some View { + content + .background(WindowAppearanceBridge(choice: resolved)) + .preferredColorScheme(scheme) + .environment(\.colorScheme, scheme) + .tint(preferences.tintColor) + } +} + +/// Explicitly clear the NSWindow override when returning to system appearance. +private struct WindowAppearanceBridge: NSViewRepresentable { + let choice: AppAppearance + func makeNSView(context: Context) -> AppearanceView { AppearanceView() } + func updateNSView(_ view: AppearanceView, context: Context) { view.choice = choice } + + final class AppearanceView: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { nil } + var choice = AppAppearance.system { didSet { apply() } } + override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); apply() } + private func apply() { + WindowAppearance.apply(choice, to: window) + } + } +} + +@MainActor enum WindowAppearance { + static func apply(_ choice: AppAppearance, to window: NSWindow?) { + let appearance = choice.windowAppearance + if window?.appearance?.name != appearance?.name { window?.appearance = appearance } + for child in window?.childWindows ?? [] where child.appearance?.name != appearance?.name { + child.appearance = appearance + } + } +} + +/// System source is independent of the color scheme inherited by this window. +@MainActor @Observable final class SystemAppearanceObserver { + private(set) var isDark = false + @ObservationIgnored private var observation: NSKeyValueObservation? + @ObservationIgnored private var themeToken: NSObjectProtocol? + + init() { + refresh() + observation = NSApp.observe(\.effectiveAppearance, options: [.new]) { [weak self] _, _ in + guard let self else { return } + Task { @MainActor in self.refresh() } + } + themeToken = DistributedNotificationCenter.default().addObserver( + forName: Notification.Name("AppleInterfaceThemeChangedNotification"), object: nil, queue: .main + ) { [weak self] _ in + guard let self else { return } + Task { @MainActor in self.refresh() } + } + } + + private func refresh() { + // Read the global domain, not this app's effective window appearance. + isDark = Self.isDark(globalDomain: UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)) + } + + static func isDark(globalDomain: [String: Any]?) -> Bool { + (globalDomain?["AppleInterfaceStyle"] as? String)?.caseInsensitiveCompare("Dark") == .orderedSame + } + + deinit { if let themeToken { DistributedNotificationCenter.default().removeObserver(themeToken) } } +} diff --git a/kymo/UI/Components/DetailPlacement.swift b/kymo/UI/Components/DetailPlacement.swift new file mode 100644 index 0000000..42e89fe --- /dev/null +++ b/kymo/UI/Components/DetailPlacement.swift @@ -0,0 +1,18 @@ +import Foundation +import CoreGraphics + + +/// Screen coordinates: prefer the parent's right side, otherwise use its left. +nonisolated enum DetailPlacement { + static func frame(anchor: CGRect, parent: CGRect, content: CGSize, visible: CGRect) -> CGRect { + let gap: CGFloat = 4 + let width = min(content.width, visible.width) + let height = min(content.height, visible.height) + let right = parent.maxX + gap + let left = parent.minX - gap - width + let candidate = right + width <= visible.maxX ? right : left + let x = max(visible.minX, min(candidate, visible.maxX - width)) + let y = max(visible.minY, min(anchor.maxY - height, visible.maxY - height)) + return CGRect(x: x, y: y, width: width, height: height) + } +} diff --git a/kymo/UI/Components/HoverDetailPresenter.swift b/kymo/UI/Components/HoverDetailPresenter.swift new file mode 100644 index 0000000..9cd75c2 --- /dev/null +++ b/kymo/UI/Components/HoverDetailPresenter.swift @@ -0,0 +1,124 @@ +import SwiftUI +import AppKit + +/// A non-activating child window: outside the parent layout, below no other app. +struct HoverDetailPresenter: NSViewRepresentable { + let isPresented: Bool + let detail: Detail + let onHover: (Bool) -> Void + let onDismiss: () -> Void + + func makeNSView(context: Context) -> AnchorView { AnchorView() } + func updateNSView(_ view: AnchorView, context: Context) { + view.configure(presented: isPresented, detail: AnyView(detail), onHover: onHover, onDismiss: onDismiss) + } + static func dismantleNSView(_ view: AnchorView, coordinator: ()) { view.detach() } + + final class AnchorView: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { nil } + private var panel: DetailPanel? + private var host: NSHostingView? + private var tokens: [NSObjectProtocol] = [] + private var presented = false + private var detail = AnyView(EmptyView()) + private var onHover: (Bool) -> Void = { _ in } + private var onDismiss: () -> Void = {} + + func configure(presented: Bool, detail: AnyView, + onHover: @escaping (Bool) -> Void, onDismiss: @escaping () -> Void) { + self.presented = presented + self.detail = detail + self.onHover = onHover + self.onDismiss = onDismiss + refresh() + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + detach() + guard let window else { return } + for name in [NSWindow.willCloseNotification, NSWindow.didChangeOcclusionStateNotification] { + tokens.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self, weak window] notification in + MainActor.assumeIsolated { + guard notification.name == NSWindow.willCloseNotification || window?.occlusionState.contains(.visible) != true else { return } + self?.hide() + let dismiss = self?.onDismiss + DispatchQueue.main.async { dismiss?() } + } + }) + } + refresh() + } + + func detach() { + hide() + for token in tokens { NotificationCenter.default.removeObserver(token) } + tokens.removeAll() + } + + private func refresh() { + guard presented, let parent = window, parent.isVisible, let screen = parent.screen else { hide(); return } + let content = AnyView(detail + .font(.caption) + .padding(12) + .frame(width: 280) + .fixedSize(horizontal: false, vertical: true) + .onHover { [weak self] inside in self?.onHover(inside) }) + if panel == nil { + let panel = DetailPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false) + panel.isReleasedWhenClosed = false + panel.isOpaque = false + panel.backgroundColor = .clear + panel.hasShadow = true + panel.hidesOnDeactivate = false + panel.level = parent.level + let material = NSVisualEffectView() + material.material = .menu + material.blendingMode = .behindWindow + material.state = .active + material.wantsLayer = true + material.layer?.cornerRadius = 12 + material.layer?.masksToBounds = true + let host = NSHostingView(rootView: content) + host.translatesAutoresizingMaskIntoConstraints = false + material.addSubview(host) + NSLayoutConstraint.activate([ + host.leadingAnchor.constraint(equalTo: material.leadingAnchor), + host.trailingAnchor.constraint(equalTo: material.trailingAnchor), + host.topAnchor.constraint(equalTo: material.topAnchor), + host.bottomAnchor.constraint(equalTo: material.bottomAnchor) + ]) + panel.contentView = material + self.panel = panel + self.host = host + parent.addChildWindow(panel, ordered: .above) + } + guard let panel, let host else { return } + host.rootView = content + panel.appearance = parent.appearance + let row = parent.convertToScreen(convert(bounds, to: nil)) + let size = host.fittingSize + panel.setFrame(DetailPlacement.frame(anchor: row, parent: parent.frame, + content: CGSize(width: 280, height: max(40, size.height)), + visible: screen.visibleFrame), display: true) + panel.orderFront(nil) + } + + private func hide() { + guard let panel else { return } + panel.parent?.removeChildWindow(panel) + panel.orderOut(nil) + panel.contentView = nil + panel.close() + host = nil + self.panel = nil + } + + deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } } + } + + final class DetailPanel: NSPanel { + override var canBecomeKey: Bool { false } + override var canBecomeMain: Bool { false } + } +} diff --git a/kymo/UI/Components/MetricRow.swift b/kymo/UI/Components/MetricRow.swift new file mode 100644 index 0000000..bc5dfa0 --- /dev/null +++ b/kymo/UI/Components/MetricRow.swift @@ -0,0 +1,61 @@ +import SwiftUI + +struct MetricRow: View { + let title: LocalizedStringKey + let symbol: String + let value: String + let usage: Double? + let history: [Double?] + let accent: Color + @ViewBuilder let detail: () -> Detail + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var visible = false + @State private var rowHovered = false + @State private var detailHovered = false + @State private var expanded = false + private var inside: Bool { rowHovered || detailHovered } + + private var color: Color { + guard let usage else { return .secondary } + return usage > 0.95 ? .red : usage >= 0.8 ? .orange : accent + } + + var body: some View { + Button { expanded.toggle() } label: { + HStack(spacing: 10) { + Image(systemName: symbol) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(color) + .frame(width: 20) + Text(title).font(.system(size: 13, weight: .medium)) + .frame(width: 52, alignment: .leading) + MiniTrendChart(values: history, color: color).frame(height: 24) + Text(verbatim: value) + .font(.system(size: 13, weight: .semibold, design: .rounded)) + .monospacedDigit() + .contentTransition(.numericText()) + .frame(width: 46, alignment: .trailing) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(title)) + .accessibilityValue(Text(verbatim: value)) + .accessibilityHint(expanded ? Text("detail.expanded") : Text("detail.collapsed")) + .padding(10) + .background(expanded ? Color.primary.opacity(0.035) : .clear, in: .rect(cornerRadius: 14)) + .background(HoverDetailPresenter(isPresented: expanded && visible, detail: detail(), + onHover: { detailHovered = $0 }, + onDismiss: { expanded = false; detailHovered = false })) + .onHover { rowHovered = $0 } + .task(id: inside) { + do { try await Task.sleep(for: .milliseconds(inside ? 150 : 120)) } + catch { return } + guard !Task.isCancelled else { return } + expanded = inside + } + .onAppear { visible = true } + .onDisappear { visible = false; rowHovered = false; detailHovered = false; expanded = false } + .animation(!visible || reduceMotion ? nil : .spring(duration: 0.3, bounce: 0), value: value) + } +} diff --git a/kymoTests/PresentationChecks.swift b/kymoTests/PresentationChecks.swift new file mode 100644 index 0000000..1c4e95b --- /dev/null +++ b/kymoTests/PresentationChecks.swift @@ -0,0 +1,68 @@ +import Foundation +import AppKit +import CoreGraphics + +@main struct PresentationChecks { + @MainActor static func main() { + let screen = CGRect(x: 0, y: 0, width: 1440, height: 900) + let parent = CGRect(x: 400, y: 400, width: 320, height: 240) + let anchor = CGRect(x: 410, y: 600, width: 300, height: 40) + let size = CGSize(width: 280, height: 180) + let right = DetailPlacement.frame(anchor: anchor, parent: parent, content: size, visible: screen) + precondition(right.minX == parent.maxX + 4 && right.maxY == anchor.maxY) + let edgeParent = CGRect(x: 1100, y: 400, width: 320, height: 240) + let left = DetailPlacement.frame(anchor: anchor, parent: edgeParent, content: size, visible: screen) + precondition(left.maxX == edgeParent.minX - 4) + for visible in [screen, CGRect(x: -1440, y: -200, width: 1440, height: 900), CGRect(x: 0, y: 0, width: 200, height: 100)] { + let result = DetailPlacement.frame(anchor: anchor, parent: parent, content: size, visible: visible) + precondition(visible.contains(result)) + } + let highAnchor = CGRect(x: 400, y: 1100, width: 300, height: 40) + precondition(DetailPlacement.frame(anchor: highAnchor, parent: parent, content: size, visible: screen).maxY == screen.maxY) + let lowAnchor = CGRect(x: 400, y: -200, width: 300, height: 40) + precondition(DetailPlacement.frame(anchor: lowAnchor, parent: parent, content: size, visible: screen).minY == screen.minY) + precondition(AppAppearance.system.resolved(systemIsDark: true) == .dark) + precondition(AppAppearance.system.resolved(systemIsDark: false) == .light) + precondition(AppAppearance.light.resolved(systemIsDark: true) == .light) + precondition(AppAppearance.dark.resolved(systemIsDark: false) == .dark) + precondition(SystemAppearanceObserver.isDark(globalDomain: ["AppleInterfaceStyle": "Dark"])) + precondition(!SystemAppearanceObserver.isDark(globalDomain: [:])) + _ = NSApplication.shared + let swatch = CustomColorWell.SwatchButton(frame: CGRect(x: 0, y: 0, width: 44, height: 26)) + var clicked = false + swatch.open = { clicked = true } + precondition(swatch.acceptsFirstMouse(for: nil)) + swatch.performClick(nil) + precondition(clicked) + swatch.swatchColor = NSColor(srgbRed: 0.2, green: 0.5, blue: 0.9, alpha: 1) + let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 44, pixelsHigh: 26, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, + isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap) + NSColor.clear.setFill() + swatch.bounds.fill(using: .copy) + swatch.draw(swatch.bounds) + NSGraphicsContext.restoreGraphicsState() + let center = bitmap.colorAt(x: 22, y: 13)!.usingColorSpace(.sRGB)! + precondition(abs(center.redComponent - 0.2) < 0.02) + precondition(abs(center.greenComponent - 0.5) < 0.02) + precondition(abs(center.blueComponent - 0.9) < 0.02) + precondition(bitmap.colorAt(x: 0, y: 0)!.alphaComponent == 0) + let global = NSApp.appearance + let window = NSWindow(contentRect: .zero, styleMask: .borderless, backing: .buffered, defer: true) + window.isReleasedWhenClosed = false + for choice in [AppAppearance.light, .system, .dark, .system] { + WindowAppearance.apply(choice, to: window) + if choice == .system { + precondition(window.appearance == nil) + precondition(window.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua])) + } else { + precondition(window.appearance?.name == choice.windowAppearance?.name) + } + precondition(NSApp.appearance === global) + } + window.close() + print("PASS: outward placement, edge fallback, negative screen origins, vertical limits, explicit/system window appearance reset, independent system resolution, native swatch target/action") + } +} diff --git a/kymoTests/README.md b/kymoTests/README.md index 9b70294..2af242c 100644 --- a/kymoTests/README.md +++ b/kymoTests/README.md @@ -15,9 +15,35 @@ ```bash swiftc -module-cache-path /private/tmp/kymo-check-cache \ - kymo/Core/Models/MetricsSnapshot.swift kymo/Core/Monitors/*.swift \ - kymo/Core/Services/*.swift kymoTests/SamplingChecks.swift -o /private/tmp/kymo-sampling-checks + kymo/Core/Models/*.swift kymo/Core/Monitors/*.swift \ + kymo/Core/Services/*.swift kymo/Core/Extensions/*.swift kymoTests/SamplingChecks.swift -o /private/tmp/kymo-sampling-checks /private/tmp/kymo-sampling-checks ``` 此检查不证明应用沙盒权限、SwiftUI 展示、暂停按钮交互或长期性能达标。 + +B 阶段补充检查覆盖历史容量与缺失值、格式化边界、外观持久化和无效设置恢复。 + +## 呈现边界检查 + +以下检查定位与非显示窗口的外观覆盖清除,不验证鼠标交互或屏幕截图: + +```bash +swiftc -module-cache-path /private/tmp/kymo-check-cache \ + kymo/Core/Services/AppearancePreferences.swift \ + kymo/UI/Components/AppearanceStyle.swift kymo/UI/Components/DetailPlacement.swift \ + kymo/Features/Settings/CustomColorPicker.swift kymo/Features/Settings/CustomColorWell.swift \ + kymoTests/PresentationChecks.swift -o /private/tmp/kymo-presentation-checks +/private/tmp/kymo-presentation-checks +``` + +## 趋势滚动边界检查 + +```bash +swiftc -module-cache-path /private/tmp/kymo-check-cache \ + kymo/Core/Models/*.swift kymo/UI/Charts/TrendScroll.swift \ + kymoTests/TrendScrollChecks.swift -o /private/tmp/kymo-trend-checks +/private/tmp/kymo-trend-checks +``` + +覆盖追加识别、缺失值、未满及满 60 点时的起止位置;不证明实际动画手感。 diff --git a/kymoTests/SamplingChecks.swift b/kymoTests/SamplingChecks.swift index 19264b9..3d9d1c9 100644 --- a/kymoTests/SamplingChecks.swift +++ b/kymoTests/SamplingChecks.swift @@ -15,6 +15,37 @@ import Foundation let wrap = CPUMonitor.calculate(current: [[2, 0, 5, 0]], previous: [[UInt32.max, 0, 0, 0]])! precondition(abs(wrap.usage - 3.0 / 8) < 0.000001) + var history = MetricHistory() + for index in 0..<100 { + var item = MetricsSnapshot() + item.date = Date(timeIntervalSince1970: Double(index)) + history.append(item) + } + precondition(history.samples.count == MetricHistory.capacity) + precondition(history.samples.first?.date == Date(timeIntervalSince1970: 40)) + precondition(history.samples.last?.date == Date(timeIntervalSince1970: 99)) + precondition(history.samples.allSatisfy { $0.cpu == nil }) + precondition(MetricFormat.percent(nil) == "--") + precondition(MetricFormat.percent(.nan) == "--") + precondition(MetricFormat.percent(0.126) == "13%") + precondition(MetricFormat.percent(1.2) == "100%") + precondition(MetricFormat.bytes(nil) == "--") + precondition(MetricFormat.bytes(1_000_000_000) == "1.0 GB") + let suite = "kymo-checks-" + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = AppearancePreferences(defaults: defaults) + precondition(preferences.appearance == .system && preferences.accent == .system) + preferences.appearance = .dark + preferences.accent = .custom + preferences.red = 0.75 + let restored = AppearancePreferences(defaults: defaults) + precondition(restored.appearance == .dark && restored.accent == .custom && restored.red == 0.75) + defaults.set("invalid", forKey: "appearance") + defaults.set(2.0, forKey: "accent.red") + let recovered = AppearancePreferences(defaults: defaults) + precondition(recovered.appearance == .system && recovered.red == 1) + print("PASS: bounded history, missing samples, format boundaries, appearance persistence and invalid defaults") let sampler = SystemSampler() let initial = await sampler.sample() precondition(initial.cpu == nil) @@ -35,8 +66,10 @@ import Foundation store.togglePause() precondition(store.isPaused) let pausedDate = store.snapshot.date + let pausedHistoryCount = store.history.samples.count try await Task.sleep(for: .milliseconds(2200)) precondition(store.snapshot.date == pausedDate) + precondition(store.history.samples.count == pausedHistoryCount) store.togglePause() try await waitUntil { store.snapshot.date > pausedDate } precondition(!store.isPaused && store.snapshot.date > pausedDate) diff --git a/kymoTests/TrendScrollChecks.swift b/kymoTests/TrendScrollChecks.swift new file mode 100644 index 0000000..7942da4 --- /dev/null +++ b/kymoTests/TrendScrollChecks.swift @@ -0,0 +1,20 @@ +import Foundation + +@main struct TrendScrollChecks { + static func main() { + precondition(!TrendScroll.isAppend(from: [], to: [0.2])) + precondition(TrendScroll.isAppend(from: [0.2, nil], to: [0.2, nil, 0.4])) + precondition(!TrendScroll.isAppend(from: [0.2], to: [0.4, 0.5])) + let full: [Double?] = (0..