feat(menubar): 调整两排卡片布局并加入复合曲线与数值动效
This commit is contained in:
@@ -57,11 +57,12 @@ GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取
|
||||
### 面板、历史与外观
|
||||
|
||||
- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线。
|
||||
- 当前正式入口为统一 `MenuPanelView`:CPU/GPU/内存、网络/存储/电池六张 ResourceCard + 同面板进程表,宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时,两排资源完整布局,参考尺寸两排分别 230/240pt,进程区使用剩余空间(最小 170pt),独立窗口已实测七行。其他尺寸资源独立滚动,进程仍常驻。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,移动/缩放和布局后约束完整 frame 原点;最终 MenuBarExtra 定位仍待复验。
|
||||
- 当前正式入口为统一 `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 根据真实时间定位,显示网格、三段刻度与分段面积填充;缺失值和超过 5 秒的间隙断线,不跨暂停连线或补面积。CPU/GPU/电量固定 0–100%,内存按物理总字节,网络/IO 两线共用量级;扩大立即、缩小连续十次低于一半后调整。没有独立 Timer 或后台动画循环。新图表追加平移动画尚未实施。
|
||||
- 卡片底色和各指标语义色在 Assets 中独立定义深浅模式,操作强调色仍由偏好决定;卡片底色不透明。底部继续保留保持唤醒、暂停/恢复、设置、退出四个操作及胶囊玻璃。数字、曲线和行重排当前直接更新;P5 动效与完整可访问性验收待续。
|
||||
- 进程表支持 CPU/RSS 排序、名称/PID/路径搜索、同卡内选中路径展示/复制与读取覆盖计数。投影按采样/筛选/排序事件计算并缓存,不在 body 或滚动中重复排序;hover、搜索/焦点和选中冻结旧身份顺序,新增项追加到其后。完整路径在表下方同卡展示以保持固定行高;选中进程退出短暂提示后移除,关闭面板拆卸表并清掉路径状态。路径不持久化,不收集参数或环境变量。
|
||||
- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值和超过 5 秒间隙断线。图例显示最新值,悬浮绘图区时显示最近采样时刻的各序列值、游标和交点;未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。
|
||||
- 各卡标题与彩色主值同行,数值组件复用系统 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` 的独立玻璃胶囊在三个选项间移动;遵循减少动态效果,其他表单仍使用系统分组与原生控件。
|
||||
|
||||
@@ -244,3 +244,13 @@ xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build
|
||||
本机地址默认显示代表接口/地址,更多地址与卷信息使用可选原生 popover;关键指标无需悬浮外侧详情。Store 每轮采样显式传入可见性,窗口可见判断不再要求 occlusion 标志;空搜索框自动聚焦不冻结初始 CPU 排序,首个有效 CPU 基线到达后建立排行。
|
||||
|
||||
已使用同源码、同资源的独立签名沙盒 WindowGroup 测试窗口检查深浅色和三段比例,进程初始可见七行;完成独立滚动、搜索、暂停和 Esc 清空搜索检查。该窗口不是正式 MenuBarExtra,不能替代原生弹窗定位、玻璃材质、外部关闭和完整键盘/VoiceOver 验收。详见验证记录。
|
||||
|
||||
### 第二轮布局与交互修订(2026-11-03,代码完成)
|
||||
|
||||
按用户九项要求替代上一轮布局:第一排 CPU / GPU / 电池,电池宽高相等,CPU/GPU 均分余宽;第二排内存 / 存储 / 网络等宽。各卡片标题与主值同行,移除底栏,将版本、电脑型号和四项操作收拢到顶栏。卡片底色半透明,减少透明度时恢复实色。
|
||||
|
||||
涉及 MenuBar 布局、UI 图表/数值组件、Core 历史中的 CPU 用户/系统序列与系统默认网络接口/硬件名称元数据。复合图使用独立语义色、图例、悬浮时间/各序列数值;保持缺失值断线、真实时间轴和有界历史。追加动画仅在采样更新时运行,数字恢复 numericText 翻动,并遵守减少动态效果设置。进程表仍独立滚动,不给所有行施加数值动画;RSS 表头改为内存,说明保留驻留内存口径。
|
||||
|
||||
验证:Debug 构建、CPU 历史/缺失边界、默认接口降级、编译颜色透明度、布局预算与真实 UI 的布局/悬浮/操作;动画主观手感、实际玻璃与多屏仍需分别说明验证边界。风险:紧凑电池卡文字、多地址长文本、三线对比度和连续悬浮期间数据更新;不通过虚构数据或删除关键口径规避。
|
||||
|
||||
本轮九项调整已实现;Debug/Release、数据/曲线几何/布局/编译颜色/多语言检查通过,独立深浅测试窗口与暂停、进程排序/搜索/独立滚动已验证。悬浮事件自动化和动画主观体验、正式菜单弹窗材质仍待验收,未将本轮代码完成等同于整体 P5/P6 完成,证据与边界见验证记录。
|
||||
|
||||
@@ -59,3 +59,16 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条
|
||||
新增 Store 端到端检查通过:打开后在有界等待内出现真实可读进程,关闭立即清空且跨采样周期仍为空。采样每轮显式同步可见性,避免只依赖异步事件留下旧状态。Debug / Release 构建通过。
|
||||
|
||||
限制:独立测试包使用不同签名标识,SMART XPC 因身份约束不可读,截图中 SMART 为 --,不能用它判定正式主包回归;正式主包/XPC 协议未改。本轮截图是单个测试窗口,未采集无关屏幕;没有复验最终 MenuBarExtra 的锚点定位、玻璃材质、外部关闭、多屏、三语全矩阵或长期资源预算。UI 工具两次建立新应用绑定耗时异常长,超出调用设置的 timeout;后续已绑定对象的截图/交互约一秒,不把工具耗时计入应用采样性能。
|
||||
|
||||
### 九项布局与图表修订(2026-11-03)
|
||||
|
||||
- 第一排为 CPU/GPU/电池,1240×820pt 下电池 230×230pt,CPU/GPU 各 487pt;第二排内存/存储/网络各约 401pt。标题与主值同行,版本和本机产品名/芯片移入顶栏,四项操作位于右侧,移除采样标识/更新时间和底栏。较低三列屏幕保持该顺序与比例,资源区单独滚动。
|
||||
- CPU 历史保留总占用、用户、系统三份真实采样,复合曲线使用三色图例;网络上下行、存储读写使用双曲线与图例。采用相邻点内的圆滑曲线、真实时间轴追加过渡、数值 numericText 动效;减少动态效果时关闭过渡。悬浮绘图区选择最近历史样本,显示各线读数、时刻、游标和交点,缺失值仍为 --。
|
||||
- 网络默认地址来自 NWPath 偏好首位接口,实际沙盒窗口确认 en0 的 IPv4 已直接展示(不把地址记录在本文件);断网/元数据不可读显示未知。本机硬件信息已确认显示 MacBook Pro (14-inch, Nov 2024) · Apple M4 Pro,产品名不可读退回硬件代码;不读取序列号。
|
||||
- 卡片资源深浅色 alpha 均为 0.68,减少透明度时回退到系统实色背景;编译 NSColor 检查确认资源透明度和指标色 alpha=1。进程表头与排序改为“内存”,说明保留物理驻留大小(RSS)口径。
|
||||
|
||||
通过:最终 Debug 和 Release xcodebuild build;独立 UnifiedPanelChecks(新增 CPU 用户/系统历史和缺失值,保留进程可见性/基线与有界历史);PanelLayoutChecks(新增两排宽高预算);PanelCurveChecks(真实追加、满历史、暂停断开、缺失/非有限值、时间倒退、短序列);PanelAssetChecks(实际构建资源深浅色透明度);LocalizationChecks 与三语复合图例/内存表头资源检查。工程仍无测试 Target,以上不称为 xcodebuild test。默认执行沙盒阻止 Swift 编译宏,使用工具审批环境后完成编译,没有修改应用沙盒权限。
|
||||
|
||||
真实 UI:沿用同源码独立 WindowGroup 沙盒测试包、隔离标识与偏好,深浅色截图核对完整两排卡片、三线 CPU/双线网络与存储、等宽第二排、正方形电池、顶栏信息与主值对齐;初始可见约八行进程。顶栏暂停按钮切为继续监控,原生 Scroll Down 只改变进程表行与滚动条,上方字段保持;“内存”分段排序、搜索路径中的 kymo、Esc 恢复完整列表均通过。测试前记录用户已有 Xcode 副本,未终止该路径;仅关闭本轮 /private/tmp 下测试进程并清理本轮临时构建、脚本和偏好。
|
||||
|
||||
未验证:坐标点击图表未得到可稳定保留的悬浮状态,当前工具无公开的独立鼠标移动接口,因此不声称真实悬浮事件已验收;动画主观手感、减少动态/透明度的系统开关矩阵、正式 MenuBarExtra 的玻璃穿透/定位/外部关闭、多屏与完整 VoiceOver 尚待补验。独立普通窗口背景不能替代正式菜单材质验证。该测试包因标识/签名与正式 XPC 身份要求不同,SMART 显示未知,不据此判断主产品回归;本轮未进行长时 CPU/内存/能耗验收。
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"red": "0.960",
|
||||
"green": "0.970",
|
||||
"blue": "0.990",
|
||||
"alpha": "1.000"
|
||||
"alpha": "0.680"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -26,7 +26,7 @@
|
||||
"red": "0.100",
|
||||
"green": "0.120",
|
||||
"blue": "0.160",
|
||||
"alpha": "1.000"
|
||||
"alpha": "0.680"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ nonisolated struct TrendSample: Sendable {
|
||||
var upload: Double?
|
||||
var read: Double?
|
||||
var write: Double?
|
||||
var cpuUser: Double?
|
||||
var cpuSystem: Double?
|
||||
}
|
||||
|
||||
/// Bounded sampling history; no timer or UI visibility dependence.
|
||||
@@ -24,7 +26,8 @@ nonisolated struct MetricHistory: Sendable {
|
||||
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))
|
||||
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system))
|
||||
let current = snapshot.network ?? []
|
||||
let keys = Set(current.map(\.identity))
|
||||
interfaces = interfaces.filter { keys.contains($0.key) }
|
||||
|
||||
@@ -23,6 +23,7 @@ nonisolated struct MetricsSnapshot: Sendable {
|
||||
var memory: MemoryMetrics?
|
||||
var network: [NetworkInterfaceMetrics]?
|
||||
var networkPath: NetworkPathStatus?
|
||||
var defaultNetworkInterface: String?
|
||||
var disk: DiskMetrics?
|
||||
var diskHealth: DiskHealthMetrics?
|
||||
var diskIO: DiskIOMetrics?
|
||||
|
||||
@@ -10,6 +10,7 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
|
||||
private let monitor = NWPathMonitor()
|
||||
private let lock = NSLock()
|
||||
private var status: NetworkPathStatus?
|
||||
private var primaryInterface: String?
|
||||
|
||||
init() {
|
||||
monitor.pathUpdateHandler = { [weak self] path in
|
||||
@@ -22,6 +23,7 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
|
||||
}
|
||||
self.lock.lock()
|
||||
self.status = next
|
||||
self.primaryInterface = path.status == .satisfied ? path.availableInterfaces.first?.name : nil
|
||||
self.lock.unlock()
|
||||
}
|
||||
monitor.start(queue: DispatchQueue(label: "cn.airnan.kymo.network-path"))
|
||||
@@ -33,5 +35,11 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
|
||||
return status
|
||||
}
|
||||
|
||||
func defaultInterface() -> String? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return primaryInterface
|
||||
}
|
||||
|
||||
deinit { monitor.cancel() }
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ actor SystemSampler {
|
||||
result.memory = MemoryMonitor.sample()
|
||||
result.network = network.sample()
|
||||
result.networkPath = networkPath.snapshot()
|
||||
result.defaultNetworkInterface = networkPath.defaultInterface()
|
||||
result.disk = DiskMonitor.sample()
|
||||
result.diskIO = diskIO.sample()
|
||||
result.battery = BatteryMonitor.sample()
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
import IOKit
|
||||
import Darwin
|
||||
|
||||
/// Cached local model metadata, without serial numbers or network/device names.
|
||||
nonisolated enum HardwareIdentity {
|
||||
static let displayName: String = {
|
||||
let entry = IORegistryEntryFromPath(kIOMainPortDefault, "IODeviceTree:/product")
|
||||
var product: String?
|
||||
if entry != 0 {
|
||||
defer { IOObjectRelease(entry) }
|
||||
if let data = IORegistryEntryCreateCFProperty(entry, "product-name" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? Data {
|
||||
product = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .controlCharacters)
|
||||
}
|
||||
}
|
||||
let model = string("hw.model")
|
||||
let chip = string("machdep.cpu.brand_string")
|
||||
return [product?.isEmpty == false ? product : model, chip].compactMap { $0 }.joined(separator: " · ")
|
||||
}()
|
||||
|
||||
private static func string(_ key: String) -> String? {
|
||||
var count = 0
|
||||
guard sysctlbyname(key, nil, &count, nil, 0) == 0, count > 0 else { return nil }
|
||||
var bytes = [CChar](repeating: 0, count: count)
|
||||
guard sysctlbyname(key, &bytes, &count, nil, 0) == 0 else { return nil }
|
||||
return String(cString: bytes)
|
||||
}
|
||||
}
|
||||
@@ -26,28 +26,18 @@ struct MenuPanelView: View {
|
||||
var body: some View {
|
||||
VStack(spacing: 8) {
|
||||
header
|
||||
if columns == 3 && panelSize.height >= 810 {
|
||||
VStack(spacing: 8) {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
cpuCard.frame(width: (panelSize.width - 36) * 0.35)
|
||||
gpuCard.frame(width: (panelSize.width - 36) * 0.33)
|
||||
memoryCard.frame(width: (panelSize.width - 36) * 0.32)
|
||||
}.frame(height: panelSize.height - 590)
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
networkCard.frame(width: (panelSize.width - 36) * 0.42)
|
||||
diskCard.frame(width: (panelSize.width - 36) * 0.27)
|
||||
batteryCard.frame(width: (panelSize.width - 36) * 0.31)
|
||||
}.frame(height: 240)
|
||||
}
|
||||
if columns == 3 {
|
||||
if panelSize.height >= 810 { resourceRows }
|
||||
else { ScrollView { resourceRows } }
|
||||
} else {
|
||||
ScrollView {
|
||||
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)
|
||||
memoryCard.frame(minHeight: 240)
|
||||
networkCard.frame(minHeight: 250)
|
||||
diskCard.frame(minHeight: 250)
|
||||
batteryCard.frame(minHeight: 250)
|
||||
networkCard.frame(minHeight: 250)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +45,6 @@ struct MenuPanelView: View {
|
||||
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900, logicalCPUCount: snapshot.cpu?.cores.count ?? 1).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.frame(minHeight: 170)
|
||||
}
|
||||
footer
|
||||
}
|
||||
.padding(10)
|
||||
.frame(width: panelSize.width, height: panelSize.height)
|
||||
@@ -71,33 +60,49 @@ struct MenuPanelView: View {
|
||||
.modifier(AppearanceStyle(preferences: preferences))
|
||||
}
|
||||
|
||||
private var resourceRows: some View {
|
||||
VStack(spacing: 8) {
|
||||
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))
|
||||
}.frame(height: PanelLayout.resourceRowHeight(size: panelSize))
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
memoryCard.frame(width: (panelSize.width - 36) / 3)
|
||||
diskCard.frame(width: (panelSize.width - 36) / 3)
|
||||
networkCard.frame(width: (panelSize.width - 36) / 3)
|
||||
}.frame(height: 240)
|
||||
}
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 10) {
|
||||
Image("BrandMark").renderingMode(.template)
|
||||
Text("Kymo").font(.system(size: 18, weight: .semibold))
|
||||
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")")
|
||||
.font(.system(size: 10)).foregroundStyle(.secondary)
|
||||
if panelSize.width >= 900 {
|
||||
Text(verbatim: "\(ProcessInfo.processInfo.processorCount) CPU · \(MetricFormat.bytes(snapshot.memory?.total))")
|
||||
.font(.system(size: 11)).foregroundStyle(.secondary)
|
||||
Text(verbatim: HardwareIdentity.displayName)
|
||||
.font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
|
||||
}
|
||||
Spacer()
|
||||
VStack(alignment: .trailing, spacing: 2) {
|
||||
Label(metrics.isPaused ? "panel.paused" : "panel.sampling", systemImage: metrics.isPaused ? "pause.circle" : "circle.fill")
|
||||
.foregroundStyle(metrics.isPaused ? Color.secondary : Color("MetricBattery"))
|
||||
Text(snapshot.date, style: .time).foregroundStyle(.secondary)
|
||||
}.font(.system(size: 10))
|
||||
Spacer(minLength: 8)
|
||||
controls
|
||||
}.padding(.horizontal, 4)
|
||||
}
|
||||
|
||||
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color) -> some View {
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color)
|
||||
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color, label: LocalizedStringKey = "panel.total") -> some View {
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label)
|
||||
}
|
||||
private func line(_ key: LocalizedStringKey, _ value: String) -> some View {
|
||||
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); Text(verbatim: value).monospacedDigit() }
|
||||
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) }
|
||||
}
|
||||
|
||||
private var cpuCard: some View {
|
||||
ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) {
|
||||
chart(\.cpu, color: Color("MetricCPU"))
|
||||
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")
|
||||
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) {
|
||||
@@ -115,7 +120,7 @@ struct MenuPanelView: View {
|
||||
|
||||
} else { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
Spacer(minLength: 0)
|
||||
HStack { line("system.load", snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")); Spacer(minLength: 8); Text(verbatim: String(format: "%.1f h", snapshot.uptime / 3600)) }
|
||||
HStack { line("system.load", snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")); Spacer(minLength: 8); AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600)) }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -148,7 +153,7 @@ struct MenuPanelView: View {
|
||||
line("memory.app", MetricFormat.bytes(m.used - min(m.used, m.wired + m.compressed)))
|
||||
HStack { line("memory.wired", MetricFormat.bytes(m.wired)); line("memory.compressed", MetricFormat.bytes(m.compressed)) }
|
||||
HStack { line("memory.available", MetricFormat.bytes(m.total - min(m.total, m.used))); line("memory.swap", MetricFormat.bytes(m.swapUsed)) }
|
||||
HStack { Text("memory.pressure").foregroundStyle(.secondary); Spacer(); pressure(m.pressure); Text(verbatim: MetricFormat.percent(m.usage)).foregroundStyle(Color("MetricMemory")) }
|
||||
HStack { Text("memory.pressure").foregroundStyle(.secondary); Spacer(); pressure(m.pressure); AnimatedMetricText(value: MetricFormat.percent(m.usage)).foregroundStyle(Color("MetricMemory")) }
|
||||
} else { Text("metric.waiting") }
|
||||
}
|
||||
}
|
||||
@@ -169,10 +174,11 @@ struct MenuPanelView: View {
|
||||
}.labelsHidden().controlSize(.mini).frame(maxWidth: 200)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
if let item = network.first, let address = item.addresses.first {
|
||||
Text(verbatim: "\(item.name) · \(address)").font(.system(size: 10)).lineLimit(1).truncationMode(.middle).textSelection(.enabled)
|
||||
}
|
||||
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), fixedScale: nil).id(selectedInterface)
|
||||
if let item = addressInterface {
|
||||
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)
|
||||
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 {
|
||||
@@ -208,6 +214,10 @@ struct MenuPanelView: View {
|
||||
|
||||
}
|
||||
}
|
||||
private var addressInterface: NetworkInterfaceMetrics? {
|
||||
let name = selectedInterface.isEmpty ? snapshot.defaultNetworkInterface : network.first?.name
|
||||
return snapshot.network?.first { $0.name == name && $0.active }
|
||||
}
|
||||
private var networkDates: [Date] { selectedInterface.isEmpty ? samples.map(\.date) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.date) }
|
||||
private var networkDownloads: [Double?] { selectedInterface.isEmpty ? samples.map(\.download) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.download) }
|
||||
private var networkUploads: [Double?] { selectedInterface.isEmpty ? samples.map(\.upload) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.upload) }
|
||||
@@ -215,7 +225,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)
|
||||
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")
|
||||
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" } ?? "--") }
|
||||
@@ -243,7 +253,7 @@ struct MenuPanelView: View {
|
||||
private var batteryCard: some View {
|
||||
ResourceCard(title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), value: MetricFormat.percent(snapshot.battery?.charge)) {
|
||||
if let battery = snapshot.battery {
|
||||
chart(\.battery, color: Color("MetricBattery"))
|
||||
chart(\.battery, color: Color("MetricBattery"), label: "metric.battery")
|
||||
Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging")
|
||||
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
|
||||
line("battery.health", MetricFormat.percent(battery.health))
|
||||
@@ -251,7 +261,7 @@ struct MenuPanelView: View {
|
||||
Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
if battery.externalPower && !battery.charging { Text("battery.timeNotApplicable") }
|
||||
else if let minutes = battery.minutesRemaining { Text(verbatim: "\(minutes) min") }
|
||||
else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") }
|
||||
else { Text("battery.timeUnknown") }
|
||||
}
|
||||
|
||||
@@ -260,10 +270,8 @@ struct MenuPanelView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
private var footer: some View {
|
||||
private var controls: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")").font(.system(size: 10)).foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
HStack(spacing: 2) {
|
||||
Button { keepAwake.toggle() } label: {
|
||||
Image(systemName: keepAwake.isEnabled ? "cup.and.saucer.fill" : "cup.and.saucer")
|
||||
@@ -292,7 +300,7 @@ struct MenuPanelView: View {
|
||||
}
|
||||
.help(Text("action.quit")).accessibilityLabel(Text("action.quit"))
|
||||
}
|
||||
.buttonStyle(FooterButtonStyle())
|
||||
.buttonStyle(PanelControlButtonStyle())
|
||||
.padding(4)
|
||||
.glassEffect(.regular, in: .capsule)
|
||||
}
|
||||
@@ -302,15 +310,15 @@ struct MenuPanelView: View {
|
||||
}
|
||||
|
||||
|
||||
private struct FooterButtonStyle: ButtonStyle {
|
||||
private struct PanelControlButtonStyle: ButtonStyle {
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
FooterButtonBody(isPressed: configuration.isPressed) {
|
||||
PanelControlButtonBody(isPressed: configuration.isPressed) {
|
||||
configuration.label
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct FooterButtonBody<Content: View>: View {
|
||||
private struct PanelControlButtonBody<Content: View>: View {
|
||||
let isPressed: Bool
|
||||
@ViewBuilder var content: () -> Content
|
||||
@State private var isHovered = false
|
||||
|
||||
@@ -2,6 +2,9 @@ import Foundation
|
||||
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 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))))
|
||||
|
||||
@@ -71,7 +71,7 @@ struct ProcessTableView: View {
|
||||
}
|
||||
}
|
||||
.font(.system(size: 12)).padding(10)
|
||||
.background(Color("PanelCard"), in: .rect(cornerRadius: 14))
|
||||
.modifier(PanelCardBackground(radius: 14))
|
||||
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.primary.opacity(0.1)))
|
||||
.onAppear { rebuild(retainOrder: false) }
|
||||
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && (byMemory ? rows.contains { $0.residentBytes != nil } : rows.contains { $0.cpu != nil })) }
|
||||
|
||||
@@ -2174,19 +2174,19 @@
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CPU: one core = 100%, may exceed 100% · Memory: RSS · Restricted fields shown as --"
|
||||
"value" : "CPU: one core = 100%, may exceed 100% · Memory: physical resident size (RSS) · Restricted fields shown as --"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CPU:单核 100%,可超过 100% · 内存:RSS · 受限字段显示 --"
|
||||
"value" : "CPU:单核 100%,可超过 100% · 内存:实际驻留物理内存(RSS)· 受限字段显示 --"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CPU:單核 100%,可超過 100% · 記憶體:RSS · 受限欄位顯示 --"
|
||||
"value" : "CPU:單核 100%,可超過 100% · 記憶體:實際駐留實體記憶體(RSS)· 受限欄位顯示 --"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2243,19 +2243,19 @@
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "RSS"
|
||||
"value" : "Memory"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "RSS"
|
||||
"value" : "内存"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "RSS"
|
||||
"value" : "記憶體"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2398,6 +2398,13 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"panel.total" : {
|
||||
"localizations" : {
|
||||
"en" : { "stringUnit" : { "state" : "translated", "value" : "Total" } },
|
||||
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "总占用" } },
|
||||
"zh-Hant" : { "stringUnit" : { "state" : "translated", "value" : "總佔用" } }
|
||||
}
|
||||
},
|
||||
"panel.totalNetwork" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum PanelCurveGeometry {
|
||||
struct Sample {
|
||||
let date: Date
|
||||
let value: Double
|
||||
}
|
||||
|
||||
static func isAppend(from old: [Date], to new: [Date]) -> Bool {
|
||||
guard old.count > 1, let previous = old.last, let next = new.last,
|
||||
next > previous, next.timeIntervalSince(previous) <= 5 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]] {
|
||||
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() }
|
||||
run.append(Sample(date: dates[index], value: value))
|
||||
}
|
||||
flush()
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,148 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Real timestamps determine x positions; missing data and pauses break the path.
|
||||
/// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append.
|
||||
struct PanelTrendChart: View {
|
||||
let dates: [Date]
|
||||
let first: [Double?]
|
||||
var second: [Double?] = []
|
||||
var third: [Double?] = []
|
||||
let color: Color
|
||||
var secondColor: Color = .orange
|
||||
var thirdColor: Color = .purple
|
||||
var fixedScale: Double? = 1
|
||||
var scaleLabel: String?
|
||||
var firstLabel: LocalizedStringKey = "panel.total"
|
||||
var secondLabel: LocalizedStringKey = "network.upload"
|
||||
var thirdLabel: LocalizedStringKey = "cpu.system"
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
@State private var retainedScale: Double = 1
|
||||
@State private var smallSamples = 0
|
||||
@State private var hoveredDate: Date?
|
||||
@State private var previousBegin: Date?
|
||||
@State private var previousEnd: Date?
|
||||
@State private var progress: CGFloat = 1
|
||||
|
||||
private var maximum: Double { max(1, (first + second).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
|
||||
private var middleLabel: String {
|
||||
if let fixedScale { return fixedScale == 1 ? "50%" : MetricFormat.bytes(UInt64(max(0, fixedScale / 2))) }
|
||||
return MetricFormat.rate(retainedScale / 2)
|
||||
private var maximum: Double { max(1, (first + second + third).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
|
||||
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
|
||||
private var index: Int? {
|
||||
guard !dates.isEmpty else { return nil }
|
||||
guard let hoveredDate else { return dates.count - 1 }
|
||||
return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) }
|
||||
}
|
||||
private func formatted(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite else { return "--" }
|
||||
if fixedScale == 1 { return MetricFormat.percent(value) }
|
||||
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()
|
||||
}.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 2) {
|
||||
VStack(spacing: 3) {
|
||||
HStack(spacing: 10) {
|
||||
legend(firstLabel, values: first, tint: color)
|
||||
if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor) }
|
||||
if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) }
|
||||
Spacer(minLength: 0)
|
||||
}.frame(height: 14)
|
||||
HStack(spacing: 5) {
|
||||
VStack(alignment: .trailing) {
|
||||
Text(verbatim: scaleLabel ?? (fixedScale == nil ? MetricFormat.rate(retainedScale) : "100%"))
|
||||
.lineLimit(1).minimumScaleFactor(0.75)
|
||||
Text(verbatim: scaleLabel ?? formatted(scale))
|
||||
Spacer(minLength: 0)
|
||||
Text(verbatim: middleLabel).lineLimit(1).minimumScaleFactor(0.75)
|
||||
Text(verbatim: formatted(scale / 2))
|
||||
Spacer(minLength: 0)
|
||||
Text(verbatim: "0")
|
||||
}.font(.system(size: 8)).foregroundStyle(.secondary).frame(width: 52, height: 48)
|
||||
}.font(.system(size: 8)).foregroundStyle(.secondary)
|
||||
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: 58)
|
||||
GeometryReader { proxy in
|
||||
ZStack(alignment: .topLeading) {
|
||||
PanelCurveCanvas(dates: dates, series: [first, second, third], colors: [color, secondColor, thirdColor],
|
||||
scale: scale, 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
|
||||
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: proxy.size.height))
|
||||
}.stroke(.primary.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [3, 2]))
|
||||
ForEach(0..<3, id: \.self) { series in
|
||||
let values = [first, second, third][series]
|
||||
if index < values.count, let value = values[index], value.isFinite {
|
||||
Circle().fill([color, secondColor, thirdColor][series]).frame(width: 5, height: 5)
|
||||
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / scale))))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.onContinuousHover { phase in
|
||||
switch phase {
|
||||
case .active(let point):
|
||||
if let begin = dates.first, let end = dates.last {
|
||||
hoveredDate = begin.addingTimeInterval(end.timeIntervalSince(begin) * min(1, max(0, point.x / max(1, proxy.size.width))))
|
||||
}
|
||||
case .ended: hoveredDate = nil
|
||||
}
|
||||
}
|
||||
}.frame(height: 58).clipped()
|
||||
}
|
||||
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)
|
||||
.onAppear { retainedScale = maximum }
|
||||
.onChange(of: dates) { old, new in
|
||||
let target = maximum
|
||||
if target > retainedScale { retainedScale = target; smallSamples = 0 }
|
||||
else if target < retainedScale * 0.5 {
|
||||
smallSamples += 1
|
||||
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
|
||||
} else { smallSamples = 0 }
|
||||
let append = PanelCurveGeometry.isAppend(from: old, to: new)
|
||||
var transaction = Transaction(); transaction.disablesAnimations = true
|
||||
withTransaction(transaction) {
|
||||
previousBegin = append && !reduceMotion ? old.first : nil
|
||||
previousEnd = append && !reduceMotion ? old.last : nil
|
||||
progress = previousBegin == nil ? 1 : 0
|
||||
}
|
||||
}
|
||||
.task(id: dates.last) {
|
||||
guard progress == 0, !reduceMotion else { return }
|
||||
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
|
||||
withAnimation(.easeInOut(duration: 0.35)) { progress = 1 }
|
||||
}
|
||||
.onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil } }
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PanelCurveCanvas: View, Animatable {
|
||||
let dates: [Date]
|
||||
let series: [[Double?]]
|
||||
let colors: [Color]
|
||||
let scale: Double
|
||||
let previousBegin: Date?
|
||||
let previousEnd: Date?
|
||||
var progress: CGFloat
|
||||
var animatableData: CGFloat {
|
||||
get { progress }
|
||||
set { progress = newValue }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Canvas { context, size in
|
||||
var grid = Path()
|
||||
for step in 0...10 {
|
||||
@@ -38,53 +153,33 @@ struct PanelTrendChart: View {
|
||||
let y = size.height * Double(step) / 2
|
||||
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
|
||||
}
|
||||
context.stroke(grid, with: .color(color.opacity(0.14)), lineWidth: 0.5)
|
||||
guard let begin = dates.first, let end = dates.last, end > begin else { return }
|
||||
let scale = fixedScale ?? retainedScale
|
||||
for (values, tint) in [(first, color), (second, secondColor)] {
|
||||
var path = Path()
|
||||
var connected = false
|
||||
var fill = Path()
|
||||
var runStart: CGPoint?
|
||||
var runEnd: CGPoint?
|
||||
func closeRun() {
|
||||
guard let start = runStart, let end = runEnd else { return }
|
||||
fill.addLine(to: CGPoint(x: end.x, y: size.height))
|
||||
fill.addLine(to: CGPoint(x: start.x, y: size.height)); fill.closeSubpath()
|
||||
runStart = nil; runEnd = nil
|
||||
context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5)
|
||||
guard let first = dates.first, let last = dates.last else { return }
|
||||
let begin = (previousBegin ?? first).timeIntervalSinceReferenceDate * (1 - progress) + first.timeIntervalSinceReferenceDate * progress
|
||||
let end = (previousEnd ?? last).timeIntervalSinceReferenceDate * (1 - progress) + last.timeIntervalSinceReferenceDate * progress
|
||||
for (values, tint) in zip(series, colors) {
|
||||
for run in PanelCurveGeometry.runs(dates: dates, values: values) {
|
||||
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))))
|
||||
}
|
||||
guard let start = points.first, let finish = points.last else { continue }
|
||||
var line = Path(); line.move(to: start)
|
||||
for pair in zip(points, points.dropFirst()) {
|
||||
let middle = (pair.0.x + pair.1.x) / 2
|
||||
// Horizontal tangents keep the rounded curve between adjacent sample values.
|
||||
line.addCurve(to: pair.1, control1: CGPoint(x: middle, y: pair.0.y), control2: CGPoint(x: middle, y: pair.1.y))
|
||||
}
|
||||
if points.count == 1 {
|
||||
context.fill(Path(ellipseIn: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)), with: .color(tint))
|
||||
} else {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
for index in dates.indices {
|
||||
guard index < values.count, let value = values[index], value.isFinite else { closeRun(); connected = false; continue }
|
||||
if index > 0 && dates[index].timeIntervalSince(dates[index - 1]) > 5 { closeRun(); connected = false }
|
||||
let point = CGPoint(x: size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin),
|
||||
y: size.height * (1 - min(1, max(0, value / scale))))
|
||||
if connected { path.addLine(to: point); fill.addLine(to: point) }
|
||||
else { path.move(to: point); fill.move(to: point); runStart = point }
|
||||
runEnd = point
|
||||
connected = true
|
||||
}
|
||||
closeRun()
|
||||
context.fill(fill, with: .linearGradient(Gradient(colors: [tint.opacity(0.45), tint.opacity(0.03)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
|
||||
context.stroke(path, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round))
|
||||
}
|
||||
}.frame(height: 48)
|
||||
}
|
||||
HStack {
|
||||
if let date = dates.first { Text(date, style: .time) }
|
||||
Spacer()
|
||||
if let date = dates.last { Text(date, style: .time) }
|
||||
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(maxWidth: .infinity)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.onAppear { retainedScale = maximum }
|
||||
.onChange(of: dates.last) { _, _ in
|
||||
let target = maximum
|
||||
if target > retainedScale { retainedScale = target; smallSamples = 0 }
|
||||
else if target < retainedScale * 0.5 {
|
||||
smallSamples += 1
|
||||
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
|
||||
} else { smallSamples = 0 }
|
||||
}
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The same system numeric roll/blur transition as the original metric rows.
|
||||
struct AnimatedMetricText: View {
|
||||
let value: String
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
|
||||
var body: some View {
|
||||
Text(verbatim: value)
|
||||
.monospacedDigit()
|
||||
.contentTransition(.numericText())
|
||||
.animation(reduceMotion ? nil : .spring(duration: 0.35, bounce: 0), value: value)
|
||||
}
|
||||
}
|
||||
|
||||
struct PanelCardBackground: ViewModifier {
|
||||
let radius: CGFloat
|
||||
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
|
||||
|
||||
func body(content: Content) -> some View {
|
||||
content.background {
|
||||
if reduceTransparency {
|
||||
RoundedRectangle(cornerRadius: radius).fill(Color(nsColor: .windowBackgroundColor))
|
||||
} else {
|
||||
RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,21 +10,25 @@ struct ResourceCard<Content: View>: View {
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Label { Text(title).foregroundStyle(.primary) } icon: {
|
||||
Image(systemName: symbol).foregroundStyle(color)
|
||||
}.font(.system(size: 13, weight: .semibold))
|
||||
HStack(alignment: .firstTextBaseline) {
|
||||
Text(verbatim: value).font(.system(size: 27, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(color).monospacedDigit().lineLimit(1).minimumScaleFactor(0.8)
|
||||
Spacer(minLength: 4)
|
||||
if let secondaryValue { Text(verbatim: secondaryValue).font(.system(size: 15, weight: .semibold)).foregroundStyle(color).lineLimit(1) }
|
||||
}.font(.system(size: 13, weight: .semibold)).fixedSize()
|
||||
Spacer(minLength: 0)
|
||||
VStack(alignment: .trailing, spacing: 0) {
|
||||
AnimatedMetricText(value: value)
|
||||
.font(.system(size: 20, weight: .semibold, design: .rounded))
|
||||
if let secondaryValue {
|
||||
AnimatedMetricText(value: secondaryValue).font(.system(size: 11, weight: .semibold))
|
||||
}
|
||||
}.foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.65)
|
||||
}
|
||||
content()
|
||||
}
|
||||
.font(.system(size: 11))
|
||||
.padding(10)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.background(Color("PanelCard"), in: .rect(cornerRadius: 10))
|
||||
.modifier(PanelCardBackground(radius: 10))
|
||||
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@ import AppKit
|
||||
NSAppearance(named: appearance)!.performAsCurrentDrawingAppearance {
|
||||
for name in ["PanelCard", "MetricCPU", "MetricGPU", "MetricMemory", "MetricNetwork", "MetricDisk", "MetricBattery"] {
|
||||
guard let color = NSColor(named: NSColor.Name(name), bundle: bundle)?.usingColorSpace(.sRGB) else { fatalError("Missing color: \(name)") }
|
||||
precondition(abs(color.alphaComponent - 1) < 0.001, "Transparent \(name)")
|
||||
precondition(abs(color.alphaComponent - (name == "PanelCard" ? 0.68 : 1)) < 0.005, "Unexpected alpha \(name)")
|
||||
if name == "MetricGPU" && appearance == .darkAqua { precondition(color.blueComponent > 0.99) }
|
||||
}
|
||||
}
|
||||
}
|
||||
print("PASS: compiled light/dark semantic colors exist, fully opaque, GPU blue component is normalized")
|
||||
print("PASS: compiled light/dark semantic colors exist, card translucent/semantic colors opaque, GPU blue component is normalized")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import Foundation
|
||||
|
||||
@main struct PanelCurveChecks {
|
||||
static func main() {
|
||||
let dates = (0..<60).map { Date(timeIntervalSinceReferenceDate: Double($0 * 2)) }
|
||||
precondition(PanelCurveGeometry.isAppend(from: Array(dates.prefix(2)), to: Array(dates.prefix(3))))
|
||||
precondition(PanelCurveGeometry.isAppend(from: dates, to: Array(dates.dropFirst()) + [dates.last!.addingTimeInterval(2)]))
|
||||
precondition(!PanelCurveGeometry.isAppend(from: dates, to: Array(dates.dropFirst()) + [dates.last!.addingTimeInterval(8)]))
|
||||
precondition(!PanelCurveGeometry.isAppend(from: dates, to: dates))
|
||||
let runs = PanelCurveGeometry.runs(dates: Array(dates.prefix(6)), values: [0, 0.5, nil, .nan, 0.8, 1])
|
||||
precondition(runs.count == 2 && runs[0].count == 2 && runs[1].count == 2)
|
||||
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)
|
||||
print("PASS: timestamp append/full history, pause/reset, missing/nonfinite data, short series and disconnected curves")
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,12 @@ import CoreGraphics
|
||||
precondition(visible.insetBy(dx: 16, dy: 16).contains(PanelLayout.constrainedFrame(frame, visible: visible)))
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
let input: [ProcessMetrics] = (0..<2000).map { (index: Int) -> ProcessMetrics in
|
||||
let id = ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0)
|
||||
let path: String? = index == 42 ? "/test/needle" : nil
|
||||
|
||||
+12
-1
@@ -134,4 +134,15 @@ swiftc -parse-as-library -module-cache-path /private/tmp/kymo-unified-cache \
|
||||
/private/tmp/kymo-panel-asset-checks /absolute/path/to/kymo.app
|
||||
```
|
||||
|
||||
前者覆盖屏幕预算、边界约束和 2000 行投影,不证明原生定位或滚动手感;后者读取编译资源,防止整数色值被解释为 1/255。
|
||||
前者覆盖屏幕预算、边界约束和 2000 行投影,不证明原生定位或滚动手感;后者读取编译资源,防止整数色值被解释为 1/255,并确认卡片半透明、指标色不透明。
|
||||
|
||||
复合图几何检查(真实时间追加、满历史平移、暂停断线、缺失/非有限值):
|
||||
|
||||
```bash
|
||||
swiftc -module-cache-path /private/tmp/kymo-check-cache \
|
||||
kymo/UI/Charts/PanelCurveGeometry.swift kymoTests/PanelCurveChecks.swift \
|
||||
-o /private/tmp/kymo-panel-curve-checks
|
||||
/private/tmp/kymo-panel-curve-checks
|
||||
```
|
||||
|
||||
该检查不证明悬浮事件投递或动画观感。
|
||||
|
||||
@@ -12,9 +12,14 @@ import Foundation
|
||||
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 1, sent: 1, download: 12, upload: 8),
|
||||
NetworkInterfaceMetrics(name: "utun0", received: 1, sent: 1, download: 99, upload: 99)]
|
||||
precondition(snapshot.downloadRate == 12 && snapshot.uploadRate == 8)
|
||||
snapshot.cpu = CPUMetrics(usage: 0.6, user: 0.4, system: 0.2, cores: [])
|
||||
var history = MetricHistory()
|
||||
for _ in 0..<65 { history.append(snapshot) }
|
||||
precondition(history.samples.count == 60 && history.interfaces["0:en0"]?.count == 60)
|
||||
precondition(history.samples.last?.cpuUser == 0.4 && history.samples.last?.cpuSystem == 0.2)
|
||||
snapshot.cpu = nil
|
||||
history.append(snapshot)
|
||||
precondition(history.samples.last?.cpuUser == nil && history.samples.last?.cpuSystem == nil)
|
||||
snapshot.network = []
|
||||
history.append(snapshot)
|
||||
precondition(history.interfaces.isEmpty && snapshot.downloadRate == nil)
|
||||
|
||||
Reference in New Issue
Block a user