fix(ui): 修正风扇转轴与速率图并精简进程表

This commit is contained in:
2026-11-15 19:21:18 +08:00
parent 99e558625b
commit 60c146f8b7
21 changed files with 303 additions and 107 deletions
@@ -2,9 +2,8 @@ import SwiftUI
struct MemoryDetailsView: View {
let memory: MemoryMetrics
private var values: [UInt64] { [memory.app, memory.wired, memory.compressed, memory.available] }
private var values: [UInt64] { [memory.app, memory.wired, memory.compressed] }
private let labels: [LocalizedStringKey] = ["memory.appShort", "memory.wiredShort", "memory.compressedShort"]
private var colors: [Color] { [Color("MemoryApplication"), Color("MemoryWired"), Color("MemoryCompressed"), Color("MemoryAvailable")] }
var body: some View {
VStack(alignment: .leading, spacing: 4) {
@@ -21,12 +20,12 @@ struct MemoryDetailsView: View {
}
.font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.75)
CapacityBar(values: values.map { Double($0) }, colors: colors, total: Double(memory.total), height: 4)
HStack(spacing: 4) {
Text("memory.available").foregroundStyle(.secondary)
MetricText(value: MetricFormat.memory(memory.available))
}.font(.system(size: 9)).lineLimit(1)
}
.help(Text("memory.distributionHelp"))
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("memory.distribution"))
}
@@ -11,7 +11,7 @@ extension MenuPanelView {
PanelTrendChart(
dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"),
secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, visibleSeriesCount: 2
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, visibleSeriesCount: 2, projection: .split(upwardSeries: 1)
).id(selectedInterface)
}
) {
@@ -141,7 +141,7 @@ extension MenuPanelView {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"),
secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, visibleSeriesCount: 2
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, visibleSeriesCount: 2, projection: .split(upwardSeries: 0)
)
}
) {
+36 -10
View File
@@ -17,20 +17,22 @@ import SwiftUI
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = true
let scroll = FittingScrollView()
scroll.hasVerticalScroller = true; scroll.hasHorizontalScroller = false
scroll.horizontalScrollElasticity = .none
scroll.autohidesScrollers = true; scroll.drawsBackground = false
let table = ProcessNSTableView()
table.style = .inset; table.rowHeight = 20
table.style = .plain; table.rowHeight = 20
table.usesAlternatingRowBackgroundColors = true; table.backgroundColor = .clear
table.allowsMultipleSelection = false; table.allowsEmptySelection = true
table.columnAutoresizingStyle = .sequentialColumnAutoresizingStyle
for (key, width) in [("pid", 48.0), ("name", 140), ("cpu", 65), ("memory", 85), ("power", 90), ("threads", 65), ("path", 250)] {
table.columnAutoresizingStyle = .noColumnAutoresizing
table.intercellSpacing.width = 0
for (key, width) in [("pid", 48.0), ("name", 140), ("cpu", 65), ("memory", 85), ("power", 90), ("threads", 65)] {
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(key))
column.width = width
column.minWidth = key == "path" ? 150 : key == "name" ? 90 : width
column.maxWidth = key == "name" ? 180 : key == "path" ? 10_000 : width
column.resizingMask = key == "path" ? [.autoresizingMask, .userResizingMask] : .userResizingMask
column.minWidth = 0
column.maxWidth = 10_000
column.resizingMask = []
column.sortDescriptorPrototype = NSSortDescriptor(key: key, ascending: false)
table.addTableColumn(column)
}
@@ -47,7 +49,32 @@ import SwiftUI
context.coordinator.apply(self, to: table)
}
private final class FittingScrollView: NSScrollView {
private var fitting = false
override func tile() {
super.tile()
guard !fitting, let table = documentView as? ProcessNSTableView else { return }
fitting = true; defer { fitting = false }
table.fitColumns(to: contentView.bounds.width)
}
}
final class ProcessNSTableView: NSTableView {
/// Allocate the complete viewport; AppKit's uniform resizing can leave columns clipped at narrow widths.
func fitColumns(to width: CGFloat) {
guard width.isFinite, width > 0, tableColumns.count == 6 else { return }
let minimum: [CGFloat] = [32,54,40,52,54,32]
let preferred: [CGFloat] = [48,140,65,85,90,65]
let minimumTotal = minimum.reduce(0, +)
let baseScale = min(1, width / minimumTotal)
let extraScale = max(0, width - minimumTotal) / (preferred.reduce(0, +) - minimumTotal)
for index in tableColumns.indices {
let value = minimum[index] * baseScale + (preferred[index] - minimum[index]) * extraScale
if abs(tableColumns[index].width - value) > 0.01 { tableColumns[index].width = value }
}
if abs(frame.width - width) > 0.01 { setFrameSize(CGSize(width: width, height: frame.height)) }
}
var contextMenu: ((Int) -> NSMenu?)?
var cancel: (() -> Void)?
override func keyDown(with event: NSEvent) {
@@ -145,7 +172,6 @@ import SwiftUI
switch key {
case "pid": text = String(process.id.pid)
case "name": text = process.name
case "path": text = process.path ?? "--"
case "cpu": text = process.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--"
case "memory": text = process.footprintBytes.map { String(format: "%.1f MB", Double($0) / 1_048_576) } ?? "--"
case "power": text = process.formattedPower
@@ -228,7 +254,7 @@ import SwiftUI
text.font = ["pid", "cpu", "memory", "threads", "power"].contains(key) ? .monospacedDigitSystemFont(ofSize: 11, weight: .regular) : .systemFont(ofSize: 11)
text.alignment = ["cpu", "memory", "threads", "power"].contains(key) ? .right : .left
text.lineBreakMode = .byTruncatingMiddle
text.textColor = key == "path" ? .secondaryLabelColor : .labelColor
text.textColor = .labelColor
addSubview(text); textField = text
if key == "name" || key == "threads" {
let image = NSImageView(); image.imageScaling = .scaleProportionallyDown
+9 -15
View File
@@ -31,11 +31,6 @@ struct ProcessTableView: View {
Spacer(minLength: 0)
searchField.frame(maxWidth: 180)
}
HStack(spacing: 8) {
Text("panel.processScope").lineLimit(2)
Spacer(minLength: 4)
energyStatus
}.font(.system(size: 9)).foregroundStyle(.secondary)
if snapshot?.failed == true { Text("panel.processFailed") }
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
NativeProcessTable(rows: rows, selection: $state.selected, sorting: $state.sortOrder, locale: locale, onExit: handleExit)
@@ -72,22 +67,21 @@ struct ProcessTableView: View {
private var processTitle: some View {
Label("panel.processes", systemImage: "list.bullet.rectangle")
.font(PanelStyle.title)
.help(Text("\(Text("panel.processScope"))\n\(energyStatus)"))
}
private var searchField: some View {
NativeSearchField(text: $state.search, isFocused: $searchFocused,
placeholder: AppLocalization.string("panel.search", locale: locale))
}
private var energyStatus: some View {
Group {
switch energy?.state {
case .unsupported: Text("energy.unsupported")
case .unavailable: Text("energy.unavailable")
case .available, .partial:
Text("energy.coverage \(energy?.measured ?? 0) \(energy?.candidates ?? 0)")
default: Text("energy.waiting")
}
}.help(Text("energy.scopeHelp")).lineLimit(1)
private var energyStatus: Text {
switch energy?.state {
case .unsupported: Text("energy.unsupported")
case .unavailable: Text("energy.unavailable")
case .available, .partial:
Text("energy.coverage \(energy?.measured ?? 0) \(energy?.candidates ?? 0)")
default: Text("energy.waiting")
}
}
private func rebuild(retainOrder: Bool) {
+22
View File
@@ -1,6 +1,28 @@
{
"sourceLanguage" : "en",
"strings" : {
"memory.distributionHelp" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "App includes anonymous memory used by apps and system processes. Wired includes resident kernel and driver memory. Compressed is physical compressor memory. Reclaimable cache is included in available memory; disk Swap is not added to physical memory usage."
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "应用包含应用和系统进程使用的匿名内存;联动包含内核、驱动等常驻内存;压缩为压缩器的实际物理占用。可回收缓存计入可用空间,磁盘 Swap 不再叠加到物理内存已用量。"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "應用包含應用和系統程序使用的匿名記憶體;連動包含核心、驅動等常駐記憶體;壓縮為壓縮器的實際實體佔用。可回收快取計入可用空間,磁碟 Swap 不再疊加到實體記憶體已用量。"
}
}
}
},
"gpu.idle" : {
"localizations": {
"en": {
+35 -6
View File
@@ -1,6 +1,20 @@
import AppKit
import SwiftUI
/// Rate plots share a zero axis and equal positive amplitudes on either side.
nonisolated enum PanelCurveProjection: Equatable {
case fullHeight
case split(upwardSeries: Int)
func y(value: Double, scale: Double, series: Int, height: Double) -> Double {
let fraction = min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1)))
switch self {
case .fullHeight: return height * (1 - fraction)
case .split(let upward): return height * (0.6 + (series == upward ? -0.3 : 0.3) * fraction)
}
}
}
/// Bounded static lines and per-run area paths. Hover never rebuilds geometry.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
@@ -11,6 +25,7 @@ struct NativePanelCurve: NSViewRepresentable {
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -19,7 +34,7 @@ struct NativePanelCurve: NSViewRepresentable {
func makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked))
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked, projection: projection))
}
struct Input: Equatable {
let frame: PanelCurveFrame
@@ -30,11 +45,13 @@ struct NativePanelCurve: NSViewRepresentable {
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
}
final class PlotView: NSView {
private(set) var input: Input?
private(set) var pathBuildCount = 0
let grid = CAShapeLayer()
let baseline = CAShapeLayer()
let curves = CALayer()
let hoverLine = CAShapeLayer()
private var hoverDots: [CAShapeLayer] = []
@@ -52,7 +69,8 @@ struct NativePanelCurve: NSViewRepresentable {
grid.fillColor = nil; grid.lineWidth = 0.5
grid.isHidden = true
hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2]
for child in [grid, curves, hoverLine] { layer?.addSublayer(child) }
baseline.fillColor = nil; baseline.lineWidth = 0.5; baseline.isHidden = true
for child in [grid, baseline, curves, hoverLine] { layer?.addSublayer(child) }
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
@@ -63,6 +81,7 @@ struct NativePanelCurve: NSViewRepresentable {
let frameChanged = old?.frame != value.frame
input = value
CATransaction.begin(); CATransaction.setDisableActions(true)
if old?.projection != value.projection { updateBaseline() }
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count
@@ -70,7 +89,7 @@ struct NativePanelCurve: NSViewRepresentable {
for index in seriesLayers.indices {
seriesLayers[index].root.isHidden = index >= (value.visibleSeriesCount ?? value.frame.series.count)
}
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked {
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked || old?.projection != value.projection {
rebuildPaths()
}
updateHover()
@@ -89,6 +108,7 @@ struct NativePanelCurve: NSViewRepresentable {
private func updatePalette() {
effectiveAppearance.performAsCurrentDrawingAppearance {
palette = input?.colors.map(NSColor.init) ?? []
baseline.strokeColor = NSColor.labelColor.withAlphaComponent(0.12).cgColor
grid.strokeColor = NSColor.labelColor.withAlphaComponent(0.10).cgColor
hoverLine.strokeColor = NSColor.labelColor.withAlphaComponent(0.45).cgColor
guard !palette.isEmpty else { return }
@@ -102,7 +122,16 @@ struct NativePanelCurve: NSViewRepresentable {
}
}
}
private func updateBaseline() {
baseline.frame = bounds
baseline.isHidden = input?.projection == .fullHeight || input == nil
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: bounds.height * 0.6))
path.addLine(to: CGPoint(x: bounds.width, y: bounds.height * 0.6))
baseline.path = path
}
private func updateGrid() {
updateBaseline()
grid.frame = bounds; hoverLine.frame = bounds
curves.bounds = bounds; curves.position = .zero
let path = CGMutablePath()
@@ -138,7 +167,7 @@ struct NativePanelCurve: NSViewRepresentable {
let line = CGMutablePath(), dots = CGMutablePath(), area = CGMutablePath()
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) }
y: input.projection.y(value: $0.value, scale: scale, series: index, height: bounds.height)) }
guard let start = points.first else { continue }
if points.count == 1 {
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
@@ -151,7 +180,7 @@ struct NativePanelCurve: NSViewRepresentable {
line.addPath(segment)
// Close against the matching lower boundary, never against another run or missing component.
let lowerPoints = run.reversed().map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.lower / scale)))) }
y: input.projection.y(value: $0.lower, scale: scale, series: index, height: bounds.height)) }
let fill = CGMutablePath(); fill.addPath(segment)
if let lowerStart = lowerPoints.first { fill.addLine(to: lowerStart) }
for (a, b) in zip(lowerPoints, lowerPoints.dropFirst()) {
@@ -178,7 +207,7 @@ struct NativePanelCurve: NSViewRepresentable {
let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
let y = input.projection.y(value: value, scale: scale, series: series, height: bounds.height)
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
}
}
+2 -1
View File
@@ -32,6 +32,7 @@ struct PanelTrendChart: View {
var intervals: [TimeInterval] = []
var visibleSeriesCount = 1
var stackOrder: [Int] = []
var projection: PanelCurveProjection = .fullHeight
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@@ -114,7 +115,7 @@ struct PanelTrendChart: View {
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
filledSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, stacked: !stackOrder.isEmpty)
filledSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, stacked: !stackOrder.isEmpty, projection: projection)
.contentShape(Rectangle())
.onContinuousHover { phase in
switch phase {
+41 -8
View File
@@ -58,7 +58,9 @@ struct FanRotor: NSViewRepresentable {
}
static func dismantleNSView(_ view: RotorView, coordinator: ()) { view.stop() }
final class RotorView: NSImageView {
final class RotorView: NSView {
let rotorLayer = CALayer()
private var artworkSize = CGSize.zero
static let animationKey = "fan.rotation"
private var rpm: Double?
private var active = false
@@ -68,9 +70,9 @@ struct FanRotor: NSViewRepresentable {
init() {
super.init(frame: .zero)
wantsLayer = true
image = NSImage(systemSymbolName: "fanblades.fill", accessibilityDescription: nil)
contentTintColor = .secondaryLabelColor
imageScaling = .scaleProportionallyUpOrDown
rotorLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
rotorLayer.contentsGravity = .resizeAspect
layer?.addSublayer(rotorLayer)
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
@@ -81,10 +83,41 @@ struct FanRotor: NSViewRepresentable {
}
func stop() {
active = false; refresh()
layer?.removeAnimation(forKey: Self.animationKey)
rotorLayer.removeAnimation(forKey: Self.animationKey)
}
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); refresh() }
override func layout() {
super.layout()
CATransaction.begin(); CATransaction.setDisableActions(true)
rotorLayer.bounds = CGRect(origin: .zero, size: bounds.size)
rotorLayer.position = CGPoint(x: bounds.midX, y: bounds.midY)
if artworkSize != bounds.size { updateArtwork() }
CATransaction.commit()
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance(); updateArtwork()
}
override func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties(); updateArtwork()
}
private func updateArtwork() {
artworkSize = bounds.size
guard bounds.width > 0, bounds.height > 0 else { return }
effectiveAppearance.performAsCurrentDrawingAppearance {
let symbol = NSImage(systemSymbolName: "fanblades.fill", accessibilityDescription: nil)
let artwork = NSImage(size: bounds.size, flipped: false) { rect in
symbol?.draw(in: rect)
NSColor.secondaryLabelColor.setFill(); rect.fill(using: .sourceIn)
return true
}
CATransaction.begin(); CATransaction.setDisableActions(true)
rotorLayer.contentsScale = window?.backingScaleFactor ?? 2
rotorLayer.contents = artwork.cgImage(forProposedRect: nil, context: nil, hints: nil)
CATransaction.commit()
}
}
private func refresh() {
let readable = active && window != nil ? rpm : nil
let speed = FanRotation.speed(rpm: readable, reducedMotion: reducedMotion)
@@ -92,15 +125,15 @@ struct FanRotor: NSViewRepresentable {
rotation.update(rpm: readable, reducedMotion: reducedMotion, at: CACurrentMediaTime())
let radians = rotation.phase * .pi / 180
CATransaction.begin(); CATransaction.setDisableActions(true)
layer?.removeAnimation(forKey: Self.animationKey)
layer?.transform = CATransform3DMakeRotation(radians, 0, 0, 1)
rotorLayer.removeAnimation(forKey: Self.animationKey)
rotorLayer.transform = CATransform3DMakeRotation(radians, 0, 0, 1)
if speed > 0 {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = radians; animation.toValue = radians + .pi * 2
animation.duration = 360 / speed
animation.repeatCount = .infinity
animation.timingFunction = CAMediaTimingFunction(name: .linear)
layer?.add(animation, forKey: Self.animationKey)
rotorLayer.add(animation, forKey: Self.animationKey)
}
CATransaction.commit()
}