Files
Kymo/kymo/Features/MenuBar/CPUCoreGrid.swift
T

173 lines
8.2 KiB
Swift

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")
}
}
static func groups(count: Int, kinds: [Int: CPUCoreTopology.Kind]) -> [[Int]] {
let order: [CPUCoreTopology.Kind?] = [.efficiency, .middle, .performance, nil]
return order.map { kind in (0..<max(0, count)).filter { kinds[$0] == kind } }.filter { !$0.isEmpty }
}
static func groupWidths(groups: [[Int]], width: CGFloat) -> [CGFloat] {
let weights = groups.map { CGFloat(($0.count + 1) / 2) }
let total = max(1, weights.reduce(0, +))
let available = max(0, width - CGFloat(max(0, groups.count - 1)) * 13)
return weights.map { available * $0 / total }
}
var body: some View {
let groups = Self.groups(count: values.count, kinds: kinds)
GeometryReader { geometry in
let widths = Self.groupWidths(groups: groups, width: geometry.size.width)
let diameter = zip(groups, widths).map { indices, width in
let columns = CPUCoreGridLayout.rowCounts(count: indices.count, width: width).max() ?? 1
let spacing = min(CPUCoreGridLayout.columnSpacing, max(0, (width / CGFloat(columns) - 18) / 2))
return max(0, (width - CGFloat(columns - 1) * spacing) / CGFloat(columns) - 4)
}.min() ?? 20
HStack(alignment: .top, spacing: 6) {
ForEach(groups.indices, id: \.self) { group in
if group > 0 {
Rectangle().fill(.primary.opacity(0.08)).frame(width: 1)
}
VStack(alignment: .leading, spacing: 5) {
HStack(spacing: 3) {
Circle().fill(color(kinds[groups[group][0]])).frame(width: 5, height: 5)
if let kind = kinds[groups[group][0]] { label(kind) }
else { Text("cpu.core") }
Text(verbatim: "\(groups[group].count)").foregroundStyle(.secondary)
}
.font(.system(size: 9, weight: .medium))
.lineLimit(1).minimumScaleFactor(0.6)
CPUCoreGridLayout {
ForEach(groups[group], id: \.self) { index in
ring(index: index, maximumDiameter: min(20, diameter))
}
}
}.frame(width: widths[group], alignment: .topLeading)
}
}
}
.frame(height: 15 + CGFloat(maxRows(groups: groups)) * 22 + CGFloat(max(0, maxRows(groups: groups) - 1)) * 4)
.padding(.vertical, 4)
}
// Match the content width so row reservation agrees with placement.
var availableWidth: CGFloat = 380
private func maxRows(groups: [[Int]]) -> Int {
let widths = Self.groupWidths(groups: groups, width: availableWidth)
return zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
}
private func ring(index: Int, maximumDiameter: CGFloat) -> some View {
let kind = kinds[index]
let value = values[index].isFinite ? min(1, max(0, values[index])) : 0
return GeometryReader { proxy in
let diameter = min(maximumDiameter, max(0, proxy.size.width - 4))
ZStack {
Circle().inset(by: 1).stroke(color(kind).opacity(0.16), lineWidth: 2)
Circle().inset(by: 1).trim(from: 0, to: value)
.stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round))
.rotationEffect(.degrees(-90))
.animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value)
Text(verbatim: "\(Int((value * 100).rounded()))")
.font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4)
}
.frame(width: diameter, height: diameter)
.frame(width: proxy.size.width, height: proxy.size.height)
}
.help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(value))"))
.accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core"))
.accessibilityValue("\(index + 1): \(MetricFormat.percent(value))")
}
}
struct CPUCoreGridLayout: Layout {
static let columnSpacing: CGFloat = 6
static let rowSpacing: CGFloat = 4
static let rowHeight: CGFloat = 22
static let minimumTwoRowCellWidth: CGFloat = 16
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 availableForCells = width - CGFloat(twoColumns - 1) * columnSpacing
let twoRowCellWidth = availableForCells / CGFloat(twoColumns)
let rows = count > 2 && twoRowCellWidth < minimumTwoRowCellWidth ? 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)
}