feat(cpu): 根据核心数量自适应排列进度条

This commit is contained in:
2026-11-03 13:37:01 +08:00
parent 81cde73883
commit 45a6e16bb8
5 changed files with 147 additions and 12 deletions
+1
View File
@@ -62,6 +62,7 @@ GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取
- 当前正式入口为统一 `MenuPanelView`:第一排 CPU/GPU/电池,电池宽高比 4:3、CPU/GPU 均分余宽;第二排内存/存储/网络等宽。宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时两排完整布局,参考尺寸两排分别 230/240pt,进程区使用剩余空间(最小 170pt)。其他尺寸资源独立滚动,进程常驻;三列低高度仍保持上述比例与顺序。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,布局后约束完整 frame 原点并水平居中。NSPanel 固定/关闭策略和 key/main 资格已有独立检查;实际外部点击与多屏专项待补。
- `PanelWindowObserver` 仅观察所属窗口的屏幕/移动/缩放,测量尺寸并约束居中;可见性由 MenuPanelController 开关与内容挂载生命周期通知 Store,不根据失焦推断关闭。
- CPU 逻辑核心类型在启动后按需从 IODeviceTree 的 `logical-cpu-id` 与 `cluster-type` 一次读取并缓存,按编号关联 Mach 采样结果;E、M、P 分别对应较低、中间和较高等级。存在 M 时 P 显示为超性能核,否则 P 显示为性能核。未知字段或无法读取时保持中性色,不依据核心顺序或数量推断;此设备树字段并非稳定的公开分类接口。卡片图例与辅助功能说明类型,核心进度条按采样平滑变化并遵循减少动态效果。底部标注开机运行时间;负载展示最近 1 分钟的原始平均值和逻辑核心数,进度条以核心数为满刻度,超出时只裁剪图形、保留原始数值,不把负载解释为 CPU 占用率。
- CPU 核心按可用宽度优先均分两行,空间不足时均分三行,每行数量相差不超过一;更多核心通过收紧间距和缩短条形适配,极窄空间下核心编号也会缩小。核心条仍保持各自的颜色、辅助功能和动画。
- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值、显式中断标记和超过 max(5s, 相邻样本预期间隔较大值×2) 的间隙断线。图例始终显示最新值;悬浮时使用独立浮层显示历史时刻与各序列值,保留游标/交点,不覆盖图例数据。图表通过 Anchor Preference 上报绘图区锚点、悬浮位置与内容,ResourceCard 在卡片最外层 overlay 统一绘制浮层,避免局部 zIndex 无法越过时间刻度/卡片字段;按实际本地化内容尺寸测量并约束在卡片内。浮层不参与鼠标命中,不创建顶层窗口;背景使用 NSVisualEffectView 的 popover/withinWindow 材质模糊下方内容,轻叠资源色,减少透明度时回退实色;原生材质视图也透传鼠标。CPU 使用青绿/紫红/金色区分,所有数据序列统一使用圆滑实线,未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示;UI 渲染帧最多保留 61 点,包含一个移出样本,旧首尾域连续插值到新首尾域,左端线段随动画裁出,不能先删除左端点。动画任务由提交后的帧状态触发,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。
- 各卡标题与彩色主值均为 13pt、共享基线同行,数值组件复用系统 numericText 数字翻动/模糊过渡并遵循减少动态效果;进程行不施加该动画。PanelBackground / PanelCard 深浅色均为不透明实色,主面板与按钮组不使用玻璃材质;NSPanel 保留透明窗口壳仅用于圆角外部。深色强调色为薄荷青 #35D6BD、莓粉 #F56DA6、嫩绿 #93D45B、晴蓝 #6FA0FF、暖金 #FFC15A、浅紫 #BE8AFF,浅色提供同色相较深版本以保证可读性。网络下载/上传为蓝/金,存储读/写为金/紫,CPU 总体/用户/系统为青/粉/金;图表浮窗及原生控件弹窗继续使用模糊材质,遵循减少透明度设置。操作强调色仍由偏好决定;刷新控件、图钉、保持唤醒、暂停/恢复、设置、退出胶囊位于顶栏右侧。顶栏左侧为品牌、版本及缓存的本机产品名/芯片,产品名不可读时退回 hw.model,不读取序列号。原采样状态/更新时间与底栏移除。
- NetworkPathObserver 从系统路径的偏好首位接口提供默认接口名称([NWPath 接口按偏好排序](https://developer.apple.com/documentation/network/nwpath)),网络卡默认直接展示该接口的 IPv4,若无则展示 IPv6;未知不随意选择另一个接口。手动切换接口时同步展示该接口地址。getifaddrs 元数据、接口速率和路径状态仍独立采集;不把接口 IP 当作公网出口地址。
+116
View File
@@ -0,0 +1,116 @@
import SwiftUI
/// Keep cores in two balanced rows when they fit, otherwise use at most three.
struct CPUCoreGrid: View {
let values: [Double]
let kinds: [Int: CPUCoreTopology.Kind]
let interval: TimeInterval
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private func color(_ kind: CPUCoreTopology.Kind?) -> Color {
switch kind {
case .efficiency: Color("MetricCPU")
case .middle: Color("MetricMemory")
case .performance: Color("MetricGPU")
case nil: .secondary
}
}
private func label(_ kind: CPUCoreTopology.Kind) -> Text {
switch kind {
case .efficiency: Text("cpu.kind.efficiency", tableName: "CPUDetails")
case .middle: Text("cpu.kind.performance", tableName: "CPUDetails")
case .performance:
kinds.values.contains(.middle)
? Text("cpu.kind.super", tableName: "CPUDetails")
: Text("cpu.kind.performance", tableName: "CPUDetails")
}
}
var body: some View {
CPUCoreGridLayout {
ForEach(Array(values.enumerated()), id: \.offset) { index, value in
let kind = kinds[index]
GeometryReader { proxy in
let numberWidth = min(max(12, CGFloat(String(values.count).count) * 6), max(0, proxy.size.width * 0.45))
let spacing = min(3, proxy.size.width * 0.08)
ZStack(alignment: .leading) {
Text(verbatim: "\(index + 1)").font(.system(size: 9))
.lineLimit(1).minimumScaleFactor(0.3).frame(width: numberWidth)
MetricProgressBar(value: value, color: color(kind))
.frame(width: max(0, proxy.size.width - numberWidth - spacing), height: 7)
.offset(x: numberWidth + spacing)
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value)
}.frame(width: proxy.size.width, height: proxy.size.height, alignment: .leading)
}.clipped()
.help((kind.map { label($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))"))
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
}
}.padding(.vertical, 3)
}
}
struct CPUCoreGridLayout: Layout {
static let columnSpacing: CGFloat = 6
static let rowSpacing: CGFloat = 5
static let rowHeight: CGFloat = 12
static let preferredCellWidth: CGFloat = 38
static func rowCounts(count: Int, width: CGFloat) -> [Int] {
guard count > 0 else { return [] }
guard count > 1 else { return [1] }
let twoColumns = (count + 1) / 2
let widthForTwoRows = CGFloat(twoColumns) * preferredCellWidth + CGFloat(twoColumns - 1) * columnSpacing
let rows = count > 2 && width < widthForTwoRows ? 3 : 2
let quotient = count / rows, remainder = count % rows
return (0..<rows).map { quotient + ($0 < remainder ? 1 : 0) }
}
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let width = max(0, proposal.width ?? 400)
let rows = Self.rowCounts(count: subviews.count, width: width).count
return CGSize(width: width, height: rows == 0 ? 0 : CGFloat(rows) * Self.rowHeight + CGFloat(rows - 1) * Self.rowSpacing)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let rows = Self.rowCounts(count: subviews.count, width: bounds.width)
guard let columns = rows.max(), columns > 0 else { return }
let spacing = min(Self.columnSpacing, max(0, (bounds.width / CGFloat(columns) - 18) / 2))
let cellWidth = max(0, (bounds.width - CGFloat(columns - 1) * spacing) / CGFloat(columns))
var index = 0
for (row, count) in rows.enumerated() {
for column in 0..<count {
subviews[index].place(at: CGPoint(x: bounds.minX + CGFloat(column) * (cellWidth + spacing),
y: bounds.minY + CGFloat(row) * (Self.rowHeight + Self.rowSpacing)),
anchor: .topLeading, proposal: ProposedViewSize(width: cellWidth, height: Self.rowHeight))
index += 1
}
}
}
}
private struct CPUCoreGridPreviews: View {
let width: CGFloat
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
ForEach([4, 8, 14, 18, 24, 32, 48], id: \.self) { count in
VStack(alignment: .leading, spacing: 4) {
Text("\(count) cores").font(.caption)
CPUCoreGrid(values: (0..<count).map { Double(($0 * 17) % 90 + 5) / 100 },
kinds: Dictionary(uniqueKeysWithValues: (0..<count).map { ($0, $0 < count / 3 ? .efficiency : .performance) }), interval: 2)
}
}
}.padding().frame(width: width)
}.frame(height: 600)
}
}
#Preview("CPU 核心 · 宽卡片") {
CPUCoreGridPreviews(width: 450)
}
#Preview("CPU 核心 · 窄卡片") {
CPUCoreGridPreviews(width: 300)
}
+1 -12
View File
@@ -12,7 +12,6 @@ struct MenuPanelView: View {
@State private var selectedInterface = ""
@State private var showAddresses = false
@State private var showVolumes = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var snapshot: MetricsSnapshot { metrics.snapshot }
private var samples: [TrendSample] { metrics.history.samples }
@@ -139,17 +138,7 @@ struct MenuPanelView: View {
}
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
}
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 5) {
ForEach(Array(cpu.cores.enumerated()), id: \.offset) { index, value in
let kind = CPUCoreTopology.cores[index]
HStack(spacing: 3) {
Text(verbatim: "\(index + 1)").font(.system(size: 9)).frame(width: 12)
MetricProgressBar(value: value, color: coreColor(kind)).frame(height: 7)
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value)
}.help((kind.map { coreLabel($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))"))
.accessibilityLabel(kind.map { coreLabel($0) } ?? Text("cpu.core")).accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
}
}.padding(.vertical, 3)
CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval)
} else { Text("metric.waiting").foregroundStyle(.secondary) }
Spacer(minLength: 0)
+19
View File
@@ -0,0 +1,19 @@
import SwiftUI
@main struct CPUCoreGridChecks {
static func main() {
for count in 0...128 {
for width in [120.0, 280.0, 430.0, 800.0] {
let rows = CPUCoreGridLayout.rowCounts(count: count, width: width)
precondition(rows.reduce(0, +) == count && rows.count <= 3)
if let first = rows.first, let last = rows.last {
precondition(last > 0 && first - last <= 1)
}
}
}
precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 430) == [9, 9])
precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 280) == [6, 6, 6])
precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [11, 11, 10])
print("PASS: balanced core rows at multiple widths and counts")
}
}
+10
View File
@@ -1,5 +1,15 @@
# kymoTests
CPU 核心布局检查(检查不同行宽、0–128 核的行数与均分边界;可视效果另看 `CPUCoreGrid` 的 Xcode 预览):
```bash
swiftc -parse-as-library -module-cache-path /private/tmp/kymo-core-grid-cache \
kymo/Features/MenuBar/CPUCoreGrid.swift kymo/Core/Services/CPUCoreTopology.swift \
kymo/Core/Extensions/MetricFormat.swift kymo/UI/Components/MetricProgressBar.swift \
kymoTests/CPUCoreGridChecks.swift -o /private/tmp/kymo-core-grid-checks
/private/tmp/kymo-core-grid-checks
```
单元测试目录。当前工程尚未创建测试 Target,添加步骤见
[docs/development.md](../docs/development.md)「添加测试 Target」一节。